opencode-swarm 7.147.1 → 7.148.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.opencode/skills/swarm-pr-review/SKILL.md +26 -11
- package/.opencode/skills/swarm-pr-review/references/findings-persistence-contract.md +39 -13
- package/dist/cli/{config-doctor-8nskdpgd.js → config-doctor-z2wam5wn.js} +2 -2
- package/dist/cli/{core-9rt6kbk1.js → core-k7m76ce0.js} +1 -1
- package/dist/cli/{curation-policy-9d7jx7cg.js → curation-policy-kd8j8cne.js} +4 -4
- package/dist/cli/{curator-xvymjgan.js → curator-jwpm52kg.js} +23 -23
- package/dist/cli/{curator-llm-factory-8xdxbmnz.js → curator-llm-factory-4qt8b15s.js} +23 -23
- package/dist/cli/{evidence-summary-service-k7a2s8f8.js → evidence-summary-service-90z295j3.js} +9 -9
- package/dist/cli/{gate-evidence-bbpvx28c.js → gate-evidence-3q6q71fw.js} +4 -4
- package/dist/cli/{guardrail-explain-qz2hfyb2.js → guardrail-explain-44xt373y.js} +24 -24
- package/dist/cli/{guardrail-log-6098jxes.js → guardrail-log-kbp5jztb.js} +3 -3
- package/dist/cli/{guardrail-reset-2bcccwmx.js → guardrail-reset-vpazhh8k.js} +23 -23
- package/dist/cli/{hive-promoter-9xzf0r98.js → hive-promoter-tdrkz9nh.js} +23 -23
- package/dist/cli/{index-1k41c7kt.js → index-016708th.js} +2 -2
- package/dist/cli/{index-5qfp2kt4.js → index-07zgs6y0.js} +6 -6
- package/dist/cli/{index-axcvb5kf.js → index-2y14mjfn.js} +2 -2
- package/dist/cli/{index-6cxb7ng4.js → index-52gnz782.js} +3 -3
- package/dist/cli/{index-qy5yz7fn.js → index-702zx3rk.js} +1 -1
- package/dist/cli/{index-9b50bt13.js → index-7ac5z627.js} +1 -1
- package/dist/cli/{index-bp5n93w5.js → index-7hctrdk8.js} +1 -1
- package/dist/cli/{index-by1f9ghd.js → index-9pmmexsd.js} +1 -1
- package/dist/cli/{index-8861hfbt.js → index-crpb0qke.js} +231 -92
- package/dist/cli/{index-b99vp668.js → index-dfvh1r8g.js} +25 -25
- package/dist/cli/{index-n5wzwz8x.js → index-dmbaaz6d.js} +4 -4
- package/dist/cli/{index-7tvbvecm.js → index-ffevkn7k.js} +1 -1
- package/dist/cli/{index-59q7jma6.js → index-gwrv6c56.js} +5 -5
- package/dist/cli/{index-2qapn7fk.js → index-h879g4r4.js} +1 -1
- package/dist/cli/{index-q85xv7t6.js → index-jpa03jcc.js} +1 -1
- package/dist/cli/{index-t4xa2yss.js → index-k6h5yc1j.js} +5 -5
- package/dist/cli/{index-8k9hw17k.js → index-n0fpefqx.js} +2 -2
- package/dist/cli/{index-kbp4xssa.js → index-n96wwf56.js} +4 -4
- package/dist/cli/{index-b834mas0.js → index-p62we2ar.js} +1 -1
- package/dist/cli/{index-zwc96x0a.js → index-qcm97jfh.js} +1 -1
- package/dist/cli/{index-aahyrzmm.js → index-qwj7qjjp.js} +2 -2
- package/dist/cli/{index-vpzvmp21.js → index-rcjq8dm4.js} +2 -2
- package/dist/cli/{index-gkhx2vkh.js → index-sycndcwd.js} +1 -1
- package/dist/cli/{index-b7qzwv3t.js → index-x4rxh8j9.js} +3 -3
- package/dist/cli/{index-1xvxd02x.js → index-y586zet4.js} +1 -1
- package/dist/cli/{index-014mntpw.js → index-ykjjqg79.js} +4 -4
- package/dist/cli/{index-avcqq7xc.js → index-zwpttdgn.js} +1 -1
- package/dist/cli/index.js +23 -23
- package/dist/cli/{knowledge-escalator-300p0bvr.js → knowledge-escalator-0qnm48g8.js} +9 -9
- package/dist/cli/{knowledge-events-5ncg5xv1.js → knowledge-events-3zv81nzp.js} +7 -7
- package/dist/cli/{knowledge-link-stzsjagk.js → knowledge-link-w91bcyx2.js} +3 -3
- package/dist/cli/{knowledge-store-mn75hsww.js → knowledge-store-njtx6wj1.js} +4 -4
- package/dist/cli/{knowledge-validator-763r7qpn.js → knowledge-validator-7eqj5afv.js} +6 -6
- package/dist/cli/{runner-26bc3x73.js → runner-gfzkp9nv.js} +4 -4
- package/dist/cli/{scan-cursor-b7kyjefy.js → scan-cursor-a6dhyf55.js} +5 -5
- package/dist/cli/{schema-zjhwka27.js → schema-p0vn1zgh.js} +1 -1
- package/dist/cli/{scope-persistence-aa7gkgz0.js → scope-persistence-zs97zkt7.js} +5 -5
- package/dist/cli/{skill-generator-nsa7ay0c.js → skill-generator-5qg15q1j.js} +11 -11
- package/dist/cli/{worktree-isolation-3pw7nwnh.js → worktree-isolation-ndb5fwys.js} +23 -23
- package/dist/hooks/pr-workflow-gate.d.ts +64 -3
- package/dist/index.js +54 -11
- package/dist/lang/symbol-visibility.d.ts +10 -7
- package/dist/tools/dispatch-lanes.d.ts +8 -1
- package/dist/tools/repo-graph/types.d.ts +6 -4
- 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.147.1",description:"Architect-centric agentic swarm plugin for OpenCode - hub-and-spoke orchestration with SME consultation, code generation, and QA review",main:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",default:"./dist/index.js"},"./package.json":"./package.json"},bin:{"opencode-swarm":"./dist/cli/index.js"},type:"module",engines:{bun:">=1.3.13"},license:"MIT",repository:{type:"git",url:"https://github.com/ZaxbyHub/opencode-swarm.git"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},keywords:["opencode","opencode-plugin","ai","agents","orchestration","swarm","multi-agent","llm"],files:["dist","dist/lang/grammars","binaries","evaluation-fixtures",".opencode/skills/brainstorm",".opencode/skills/specify",".opencode/skills/clarify-spec",".opencode/skills/resume",".opencode/skills/clarify",".opencode/skills/discover",".opencode/skills/consult",".opencode/skills/pre-phase-briefing",".opencode/skills/council",".opencode/skills/deep-dive",".opencode/skills/deep-research",".opencode/skills/codebase-review-swarm",".opencode/skills/swarm-implement",".opencode/skills/design-docs",".opencode/skills/swarm-pr-review",".opencode/skills/swarm",".opencode/skills/swarm-pr-feedback",".opencode/skills/swarm-pr-subscribe",".opencode/skills/swarm-ci-monitor",".opencode/skills/issue-ingest",".opencode/skills/plan",".opencode/skills/critic-gate",".opencode/skills/execute",".opencode/skills/phase-wrap",".opencode/skills/loop",".opencode/skills/writing-tests",".opencode/skills/running-tests",".opencode/skills/engineering-conventions",".opencode/skills/commit-pr",".opencode/skills/ci-failure-batching",".opencode/skills/gate-attribution",".opencode/skills/merge-queue-readiness",".opencode/skills/skill-edit-validation",".opencode/skills/worktree-retry-cleanup",".opencode/skills/test-file-split",".opencode/skills/fork-pr-operations",".opencode/skills/parallel-work-check",".opencode/skills/ci-fix-monitor",".opencode/skills/issue-tracer",".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:retention":"bun run scripts/check-retention-registry.ts","check:test-file-cap":"bun run scripts/check-test-file-cap.ts","check:pending-fragment":"bun run scripts/check-pending-fragment.ts","check:gate-portability":"bun run scripts/check-gate-portability.ts","check:bare-spawn":"bun run scripts/check-bare-executable-spawn.ts","check:memory-recall":"bun run scripts/memory-recall-regression.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"},peerDependencies:{"@xenova/transformers":"^2.17.2"},peerDependenciesMeta:{"@xenova/transformers":{optional:!0}}}});var QA_AGENTS,PIPELINE_AGENTS,ORCHESTRATOR_NAME="architect",ALL_SUBAGENT_NAMES,ALL_AGENT_NAMES;var init_agent_names=__esm(()=>{QA_AGENTS=["reviewer","critic","critic_oversight","critic_finding_validator"],PIPELINE_AGENTS=["explorer","coder","test_engineer"],ALL_SUBAGENT_NAMES=["sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","curator_postmortem","curator_consolidation","council_generalist","council_skeptic","council_domain_expert","skill_improver","spec_writer",...QA_AGENTS,...PIPELINE_AGENTS],ALL_AGENT_NAMES=["architect",...ALL_SUBAGENT_NAMES]});function getPrWorkflowToolCapability(toolName,mode){let metadata=TOOL_METADATA[toolName];if(!metadata?.prWorkflow?.modes.includes(mode))return null;return metadata.prWorkflow.capability}var TOOL_METADATA,TOOL_NAMES,TOOL_NAME_SET,TOOL_DESCRIPTIONS,AGENT_TOOL_MAP;var init_tool_metadata=__esm(()=>{init_agent_names();TOOL_METADATA={diff:{description:"structured git diff with contract change detection",agents:["architect","reviewer","critic_finding_validator","critic_oversight","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},diff_summary:{description:"filter classified AST changes by category, risk level, or file for reviewer drill-down",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},syntax_check:{description:"check syntax of source files using tree-sitter parsers across multiple languages, returning per-file errors",agents:["architect","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},placeholder_scan:{description:"todo and FIXME comment detection",agents:["architect","reviewer","critic_finding_validator"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},imports:{description:"find all consumers that import from a given file — use before refactoring shared modules to avoid breaking unseen dependents",agents:["architect","sme","researcher","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},lint:{description:"run project linter in check or fix mode; supports biome, eslint, ruff, clippy, and more, returns structured results",agents:["architect","reviewer","critic_finding_validator","coder"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},secretscan:{description:"scan for secrets (API keys, tokens, passwords) via regex and entropy; returns redacted previews, excludes common dirs",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},sast_scan:{description:"static analysis security scan",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},build_check:{description:"discover and run build, typecheck, and test commands for various project ecosystems in the working directory",agents:["architect","coder","test_engineer"]},pre_check_batch:{description:"parallel verification: lint:check + secretscan + sast_scan + quality_budget",agents:["architect","reviewer","critic_finding_validator"]},quality_budget:{description:"code quality budget check",agents:["architect"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},symbols:{description:"extract exported symbols (functions, classes, interfaces, types) from source files; supports TypeScript, JavaScript, 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:"preflight every applicable phase gate, report all blockers, and atomically commit a current passing snapshot",agents:["architect"]},run_phase_review:{description:"run the bounded phase-final review engine and persist complete content-addressed review evidence",agents:["architect"]},repair_gate_evidence:{description:"quarantine corrupt exact-task gate evidence and install a fresh blocked generation that requires every gate to rerun",agents:["architect"]},repair_knowledge_receipt_ledger:{description:"validate or repair authoritative knowledge receipts, preserve corrupt authority in bounded quarantine, and require scoped re-evaluation",agents:["architect"]},record_directive_override:{description:"record an audited architect override for identified critical-directive violations without bypassing unreadable authority",agents:["architect"]},save_plan:{description:"save a structured implementation plan",agents:["architect"]},update_task_status:{description:"mark tasks complete, track phase progress",agents:["architect"]},lint_spec:{description:"validate .swarm/spec.md format and required fields",agents:["architect","spec_writer"]},write_retro:{description:"document phase retrospectives via phase_complete workflow, capture lessons learned",agents:["architect"]},write_drift_evidence:{description:"write drift verification evidence for a completed phase",agents:["architect"]},write_hallucination_evidence:{description:"write hallucination verification evidence for a completed phase",agents:["architect"]},write_mutation_evidence:{description:"write mutation gate evidence for a completed phase; normalizes PASS/WARN/FAIL/SKIP verdicts and writes .swarm/evidence/{phase}/mutation-gate.json",agents:["architect"]},declare_scope:{description:"declare file scope for next coder delegation",agents:["architect"]},knowledge_query:{description:"query swarm or hive knowledge with optional filters",agents:["architect","skill_improver","spec_writer"]},doc_scan:{description:"scan project documentation files and build an index manifest",agents:["architect","docs_design","skill_improver","spec_writer","explorer"]},doc_extract:{description:"extract actionable constraints from project documentation",agents:["architect","docs_design","skill_improver","spec_writer"]},curator_analyze:{description:"run curator phase analysis and optionally apply knowledge recommendations",agents:["architect"]},consensus_mine:{description:"mine cross-run consensus from existing .swarm evidence into an immutable proposals-only report; also deletes its own reports past consensus.report_retention, appends to the shared recommendation dedup ledger (in the shared cohort root, outside this project, when a knowledge link is active), and mirrors proposals into pending swarm-memory proposals when memory is enabled",agents:["architect","curator_phase","curator_postmortem"]},knowledge_add:{description:"store a new lesson in the knowledge base",agents:["architect","coder"]},knowledge_recall:{description:"search the knowledge base for relevant past decisions",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"]},knowledge_remove:{description:"delete an outdated swarm knowledge entry by ID (swarm tier only)",agents:["architect"]},co_change_analyzer:{description:"detect hidden couplings by analyzing git history",agents:["architect"]},context_status:{description:"report current context-window headroom for the active session — returns tokens-used, usageSource (provider|estimated), model-limit, 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_memory_outcome:{description:"record useful, dead-end, or corrected outcomes and, when enabled, synchronously refresh deterministic memory lessons",agents:[]},swarm_command:{description:"run supported /swarm commands through the canonical command registry",agents:["architect","sme","researcher","docs","docs_design","designer","reviewer","critic_finding_validator","critic","explorer","coder","test_engineer"]},dispatch_lanes:{description:"dispatch read-only exploration/review lanes concurrently and BLOCK until all finish; prefer dispatch_lanes_async for non-blocking dispatch, use this only when promptAsync is unavailable",agents:["architect"]},dispatch_lanes_async:{description:"launch read-only advisory lanes non-blockingly and return a batch id plus lane session handles immediately 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.148.0",description:"Architect-centric agentic swarm plugin for OpenCode - hub-and-spoke orchestration with SME consultation, code generation, and QA review",main:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",default:"./dist/index.js"},"./package.json":"./package.json"},bin:{"opencode-swarm":"./dist/cli/index.js"},type:"module",engines:{bun:">=1.3.13"},license:"MIT",repository:{type:"git",url:"https://github.com/ZaxbyHub/opencode-swarm.git"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},keywords:["opencode","opencode-plugin","ai","agents","orchestration","swarm","multi-agent","llm"],files:["dist","dist/lang/grammars","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:retention":"bun run scripts/check-retention-registry.ts","check:test-file-cap":"bun run scripts/check-test-file-cap.ts","check:pending-fragment":"bun run scripts/check-pending-fragment.ts","check:gate-portability":"bun run scripts/check-gate-portability.ts","check:bare-spawn":"bun run scripts/check-bare-executable-spawn.ts","check:memory-recall":"bun run scripts/memory-recall-regression.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"},peerDependencies:{"@xenova/transformers":"^2.17.2"},peerDependenciesMeta:{"@xenova/transformers":{optional:!0}}}});var QA_AGENTS,PIPELINE_AGENTS,ORCHESTRATOR_NAME="architect",ALL_SUBAGENT_NAMES,ALL_AGENT_NAMES;var init_agent_names=__esm(()=>{QA_AGENTS=["reviewer","critic","critic_oversight","critic_finding_validator"],PIPELINE_AGENTS=["explorer","coder","test_engineer"],ALL_SUBAGENT_NAMES=["sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","curator_postmortem","curator_consolidation","council_generalist","council_skeptic","council_domain_expert","skill_improver","spec_writer",...QA_AGENTS,...PIPELINE_AGENTS],ALL_AGENT_NAMES=["architect",...ALL_SUBAGENT_NAMES]});function getPrWorkflowToolCapability(toolName,mode){let metadata=TOOL_METADATA[toolName];if(!metadata?.prWorkflow?.modes.includes(mode))return null;return metadata.prWorkflow.capability}var TOOL_METADATA,TOOL_NAMES,TOOL_NAME_SET,TOOL_DESCRIPTIONS,AGENT_TOOL_MAP;var init_tool_metadata=__esm(()=>{init_agent_names();TOOL_METADATA={diff:{description:"structured git diff with contract change detection",agents:["architect","reviewer","critic_finding_validator","critic_oversight","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},diff_summary:{description:"filter classified AST changes by category, risk level, or file for reviewer drill-down",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},syntax_check:{description:"check syntax of source files using tree-sitter parsers across multiple languages, returning per-file errors",agents:["architect","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},placeholder_scan:{description:"todo and FIXME comment detection",agents:["architect","reviewer","critic_finding_validator"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},imports:{description:"find all consumers that import from a given file — use before refactoring shared modules to avoid breaking unseen dependents",agents:["architect","sme","researcher","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},lint:{description:"run project linter in check or fix mode; supports biome, eslint, ruff, clippy, and more, returns structured results",agents:["architect","reviewer","critic_finding_validator","coder"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},secretscan:{description:"scan for secrets (API keys, tokens, passwords) via regex and entropy; returns redacted previews, excludes common dirs",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},sast_scan:{description:"static analysis security scan",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},build_check:{description:"discover and run build, typecheck, and test commands for various project ecosystems in the working directory",agents:["architect","coder","test_engineer"]},pre_check_batch:{description:"parallel verification: lint:check + secretscan + sast_scan + quality_budget",agents:["architect","reviewer","critic_finding_validator"]},quality_budget:{description:"code quality budget check",agents:["architect"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},symbols:{description:"extract exported symbols (functions, classes, interfaces, types) from source files; supports TypeScript, JavaScript, 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:"preflight every applicable phase gate, report all blockers, and atomically commit a current passing snapshot",agents:["architect"]},run_phase_review:{description:"run the bounded phase-final review engine and persist complete content-addressed review evidence",agents:["architect"]},repair_gate_evidence:{description:"quarantine corrupt exact-task gate evidence and install a fresh blocked generation that requires every gate to rerun",agents:["architect"]},repair_knowledge_receipt_ledger:{description:"validate or repair authoritative knowledge receipts, preserve corrupt authority in bounded quarantine, and require scoped re-evaluation",agents:["architect"]},record_directive_override:{description:"record an audited architect override for identified critical-directive violations without bypassing unreadable authority",agents:["architect"]},save_plan:{description:"save a structured implementation plan",agents:["architect"]},update_task_status:{description:"mark tasks complete, track phase progress",agents:["architect"]},lint_spec:{description:"validate .swarm/spec.md format and required fields",agents:["architect","spec_writer"]},write_retro:{description:"document phase retrospectives via phase_complete workflow, capture lessons learned",agents:["architect"]},write_drift_evidence:{description:"write drift verification evidence for a completed phase",agents:["architect"]},write_hallucination_evidence:{description:"write hallucination verification evidence for a completed phase",agents:["architect"]},write_mutation_evidence:{description:"write mutation gate evidence for a completed phase; normalizes PASS/WARN/FAIL/SKIP verdicts and writes .swarm/evidence/{phase}/mutation-gate.json",agents:["architect"]},declare_scope:{description:"declare file scope for next coder delegation",agents:["architect"]},knowledge_query:{description:"query swarm or hive knowledge with optional filters",agents:["architect","skill_improver","spec_writer"]},doc_scan:{description:"scan project documentation files and build an index manifest",agents:["architect","docs_design","skill_improver","spec_writer","explorer"]},doc_extract:{description:"extract actionable constraints from project documentation",agents:["architect","docs_design","skill_improver","spec_writer"]},curator_analyze:{description:"run curator phase analysis and optionally apply knowledge recommendations",agents:["architect"]},consensus_mine:{description:"mine cross-run consensus from existing .swarm evidence into an immutable proposals-only report; also deletes its own reports past consensus.report_retention, appends to the shared recommendation dedup ledger (in the shared cohort root, outside this project, when a knowledge link is active), and mirrors proposals into pending swarm-memory proposals when memory is enabled",agents:["architect","curator_phase","curator_postmortem"]},knowledge_add:{description:"store a new lesson in the knowledge base",agents:["architect","coder"]},knowledge_recall:{description:"search the knowledge base for relevant past decisions",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"]},knowledge_remove:{description:"delete an outdated swarm knowledge entry by ID (swarm tier only)",agents:["architect"]},co_change_analyzer:{description:"detect hidden couplings by analyzing git history",agents:["architect"]},context_status:{description:"report current context-window headroom for the active session — returns tokens-used, usageSource (provider|estimated), model-limit, 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_memory_outcome:{description:"record useful, dead-end, or corrected outcomes and, when enabled, synchronously refresh deterministic memory lessons",agents:[]},swarm_command:{description:"run supported /swarm commands through the canonical command registry",agents:["architect","sme","researcher","docs","docs_design","designer","reviewer","critic_finding_validator","critic","explorer","coder","test_engineer"]},dispatch_lanes:{description:"dispatch read-only exploration/review lanes concurrently and BLOCK until all finish; prefer dispatch_lanes_async for non-blocking dispatch, use this only when promptAsync is unavailable",agents:["architect"]},dispatch_lanes_async:{description:"launch read-only advisory lanes non-blockingly and return a batch id plus lane session handles immediately 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
|
|
|
@@ -267,7 +267,7 @@ ${trimmed}`}else malformedRows++;continue}let rowFields=fields.slice(0,CANDIDATE
|
|
|
267
267
|
ON qi.profile_id = p.id
|
|
268
268
|
WHERE p.plan_id = ?
|
|
269
269
|
AND qi.profile_id IS NULL
|
|
270
|
-
LIMIT 1`).get(readablePlanId)??null}function buildExactStoragePlanId(identityHash){return`qa2-${identityHash}`}function hasAnyGatePatch(gates){return Object.values(gates).some((value)=>value!==void 0)}function verifyBoundIdentityBinding(binding,identity){if(binding.identity_hash!==identity.identityHash||binding.raw_swarm!==identity.swarm||binding.raw_title!==identity.title||binding.readable_plan_id!==identity.planId)throw Error(`QA gate profile identity binding is corrupt for swarm_id='${identity.swarm}' and plan_title='${identity.title}'`)}function lookupProfileForIdentityTx(db,identity){let binding=readIdentityBindingByHash(db,identity.identityHash);if(binding){verifyBoundIdentityBinding(binding,identity);let row=readProfileRowById(db,binding.profile_id);if(!row)throw Error(`QA gate profile identity binding points to missing profile_id=${binding.profile_id}`);return{kind:"bound",identity,profile:rowToProfileWithBinding(row,binding)}}let legacyRow=readUnboundLegacyProfileRowByReadablePlanId(db,identity.planId);if(legacyRow)return{kind:"unbound_legacy",identity,profile:rowToProfile(legacyRow)};return{kind:"missing",identity}}function createExactIdentityBindingTx(db,profileId,identity){db.run("INSERT INTO qa_gate_profile_identity (identity_hash, profile_id, raw_swarm, raw_title, readable_plan_id) VALUES (?, ?, ?, ?, ?)",[identity.identityHash,profileId,identity.swarm,identity.title,identity.planId])}function createExactProfileTx(db,identity,projectType,initialGates){let gatesJson=JSON.stringify({...DEFAULT_QA_GATES,...initialGates});db.run("INSERT INTO qa_gate_profile (plan_id, project_type, gates) VALUES (?, ?, ?)",[buildExactStoragePlanId(identity.identityHash),projectType??null,gatesJson]);let row=readProfileRowByPlanId(db,buildExactStoragePlanId(identity.identityHash));if(!row)throw Error(`Failed to create QA gate profile row for exact identity plan_id=${identity.planId}`);createExactIdentityBindingTx(db,row.id,identity);let binding=readIdentityBindingByHash(db,identity.identityHash);if(!binding)throw Error(`Failed to create QA gate profile identity binding for plan_id=${identity.planId}`);return rowToProfileWithBinding(row,binding)}function shouldAdoptLegacyProfile(identity,options){if(options.allowLegacyAdoption!==!0)return!1;return options.legacyAdoptionIdentity?.swarm===identity.swarm&&options.legacyAdoptionIdentity?.title===identity.title}function getProfile(directory,planId){if(!projectDbExists(directory))return null;let db=getProjectDb(directory),row=readProfileRowByPlanId(db,planId);return row?rowToProfile(row):null}function getProfileForIdentity(directory,identity){let lookup=getProfileLookupForIdentity(directory,identity);if(lookup.kind==="bound")return lookup.profile;if(lookup.kind==="unbound_legacy")throw new QaGateProfileIdentityUnboundError(lookup.identity);return null}function getProfileLookupForIdentity(directory,identity){let exact=buildProfileIdentity(identity);if(!projectDbExists(directory))return{kind:"missing",identity:exact};let db=getProjectDb(directory);return lookupProfileForIdentityTx(db,exact)}function hasAnyProfileWithEnabledGate(directory,gate){if(!projectDbExists(directory))return!1;let rows=getProjectDb(directory).query("SELECT gates FROM qa_gate_profile").all();for(let row of rows)try{if(JSON.parse(row.gates)?.[gate]===!0)return!0}catch{}return!1}function getOrCreateProfile(directory,planId,projectType,initialGates={}){let existing=_internals14.getProfile(directory,planId);if(existing)return existing;let db=getProjectDb(directory),seededGates={...DEFAULT_QA_GATES};for(let key of Object.keys(DEFAULT_QA_GATES))if(typeof initialGates[key]==="boolean")seededGates[key]=initialGates[key];let gatesJson=JSON.stringify(seededGates),insert=db.transaction(()=>{db.run("INSERT INTO qa_gate_profile (plan_id, project_type, gates) VALUES (?, ?, ?)",[planId,projectType??null,gatesJson])});try{insert()}catch(err){if(!(err instanceof Error?err.message:String(err)).toLowerCase().includes("unique"))throw err}let after=_internals14.getProfile(directory,planId);if(!after)throw Error(`Failed to create or load QA gate profile for plan_id=${planId}`);return after}function getOrCreateProfileForIdentity(directory,identity,projectType,initialGates={}){let db=getProjectDb(directory),exact=buildProfileIdentity(identity);return withImmediateTransaction(db,()=>{let lookup=lookupProfileForIdentityTx(db,exact);if(lookup.kind==="bound")return lookup.profile;if(lookup.kind==="unbound_legacy")return createExactProfileTx(db,exact,projectType,initialGates);return createExactProfileTx(db,exact,projectType,initialGates)})}function setGates(directory,planId,gates){let db=getProjectDb(directory),savepointName=`qa_gate_profile_set_${qaGateProfileSavepointCounter++}`,startedTransaction=!db.inTransaction;db.run(startedTransaction?"BEGIN IMMEDIATE":`SAVEPOINT ${savepointName}`);try{let currentRow=db.query("SELECT * FROM qa_gate_profile WHERE plan_id = ?").get(planId);if(!currentRow)throw Error(`No QA gate profile found for plan_id=${planId} — call getOrCreateProfile first`);let current=rowToProfile(currentRow);if(current.locked_at!==null)throw Error("Cannot modify gates: QA gate profile is locked after critic approval");_internals14.afterSetGatesRead(current);let merged={...current.gates};for(let key of Object.keys(gates)){let incoming=gates[key];if(incoming===void 0)continue;if(incoming===!1&¤t.gates[key]===!0)throw Error(`Cannot disable gate '${key}': sessions can only ratchet tighter`);if(incoming===!0)merged[key]=!0}db.run("UPDATE qa_gate_profile SET gates = ? WHERE plan_id = ?",[JSON.stringify(merged),planId]);let updatedRow=db.query("SELECT * FROM qa_gate_profile WHERE plan_id = ?").get(planId);if(!updatedRow)throw Error(`Failed to re-read QA gate profile after update for plan_id=${planId}`);return db.run(startedTransaction?"COMMIT":`RELEASE ${savepointName}`),rowToProfile(updatedRow)}catch(err){try{if(db.run(startedTransaction?"ROLLBACK":`ROLLBACK TO ${savepointName}`),!startedTransaction)db.run(`RELEASE ${savepointName}`)}catch{}throw err}}function setGatesForIdentity(directory,identity,gates,options={}){let db=getProjectDb(directory),exact=buildProfileIdentity(identity),savepointName=`qa_gate_profile_set_identity_${qaGateProfileSavepointCounter++}`,startedTransaction=!db.inTransaction,finishTransaction=()=>{db.run(startedTransaction?"COMMIT":`RELEASE ${savepointName}`)},rollbackTransaction=()=>{if(db.run(startedTransaction?"ROLLBACK":`ROLLBACK TO ${savepointName}`),!startedTransaction)db.run(`RELEASE ${savepointName}`)};db.run(startedTransaction?"BEGIN IMMEDIATE":`SAVEPOINT ${savepointName}`);try{let lookup=lookupProfileForIdentityTx(db,exact);if(lookup.kind==="missing"){let created=createExactProfileTx(db,exact,options.projectType,gates);return finishTransaction(),created}if(lookup.kind==="unbound_legacy")if(shouldAdoptLegacyProfile(exact,options)){if(createExactIdentityBindingTx(db,lookup.profile.id,exact),lookup=lookupProfileForIdentityTx(db,exact),lookup.kind!=="bound")throw Error(`Failed to adopt legacy QA gate profile for exact identity plan_id=${exact.planId}`)}else if(options.allowLegacyCollisionCreate===!0){let created=createExactProfileTx(db,exact,options.projectType,gates);return finishTransaction(),created}else throw new QaGateProfileIdentityUnboundError(lookup.identity);let current=lookup.profile,currentRow=readProfileRowById(db,current.id);if(!currentRow)throw Error(`Failed to read QA gate profile row for profile_id=${current.id}`);if(_internals14.afterSetGatesForIdentityRead?.({directory,identity:exact,profileId:current.id,storagePlanId:currentRow.plan_id}),current.locked_at!==null){if(!hasAnyGatePatch(gates))return finishTransaction(),current;throw Error("Cannot modify gates: QA gate profile is locked after critic approval")}let merged={...current.gates};for(let key of Object.keys(gates)){let incoming=gates[key];if(incoming===void 0)continue;if(incoming===!1&¤t.gates[key]===!0)throw Error(`Cannot disable gate '${key}': sessions can only ratchet tighter`);if(incoming===!0)merged[key]=!0}db.run("UPDATE qa_gate_profile SET gates = ? WHERE id = ?",[JSON.stringify(merged),current.id]);let updatedRow=readProfileRowById(db,current.id),binding=readIdentityBindingByHash(db,exact.identityHash);if(!updatedRow||!binding)throw Error(`Failed to re-read QA gate profile after exact-identity update for plan_id=${exact.planId}`);return finishTransaction(),rowToProfileWithBinding(updatedRow,binding)}catch(err){try{rollbackTransaction()}catch{}throw err}}function lockProfileForIdentity(directory,identity,snapshotSeq){let db=getProjectDb(directory),exact=buildProfileIdentity(identity);return withImmediateTransaction(db,()=>{let lookup=lookupProfileForIdentityTx(db,exact);if(lookup.kind==="missing")throw Error(`No QA gate profile found for exact identity plan_id=${exact.planId} — cannot lock`);if(lookup.kind==="unbound_legacy")throw new QaGateProfileIdentityUnboundError(lookup.identity);if(lookup.profile.locked_at!==null)return lookup.profile;db.run("UPDATE qa_gate_profile SET locked_at = datetime('now'), locked_by_snapshot_seq = ? WHERE id = ?",[snapshotSeq,lookup.profile.id]);let updatedRow=readProfileRowById(db,lookup.profile.id),binding=readIdentityBindingByHash(db,exact.identityHash);if(!updatedRow||!binding)throw Error(`Failed to re-read locked QA gate profile for exact identity plan_id=${exact.planId}`);return rowToProfileWithBinding(updatedRow,binding)})}function computeProfileHash(profile){let payload=JSON.stringify({plan_id:profile.plan_id,identity_hash:profile.identity_hash,gates:profile.gates});return createHash11("sha256").update(payload).digest("hex")}function getEffectiveGates(profile,sessionOverrides){let merged={...profile.gates};for(let key of Object.keys(sessionOverrides))if(sessionOverrides[key]===!0)merged[key]=!0;return merged}var _internals14,DEFAULT_QA_GATES,QaGateProfileIdentityUnboundError,qaGateProfileSavepointCounter=0;var init_qa_gate_profile=__esm(()=>{init_utils3();init_project_db();_internals14={getProfile,getProfileLookupForIdentity,getProfileForIdentity,getOrCreateProfile,getOrCreateProfileForIdentity,setGates,setGatesForIdentity,lockProfileForIdentity,getEffectiveGates,computeProfileHash,hasAnyProfileWithEnabledGate,afterSetGatesRead:()=>{}},DEFAULT_QA_GATES={reviewer:!0,test_engineer:!0,council_mode:!1,sme_enabled:!0,critic_pre_plan:!0,hallucination_guard:!1,sast_enabled:!0,mutation_test:!1,phase_council:!1,drift_check:!0,final_council:!1};QaGateProfileIdentityUnboundError=class QaGateProfileIdentityUnboundError extends Error{identity;constructor(identity){super(`QA gate profile exists for readable plan_id='${identity.planId}' but is not exact-bound to swarm_id='${identity.swarm}' and plan_title='${identity.title}'. ${formatLegacyQaBindingRecovery(identity,"retry the blocked read-only or enforcement operation")}`);this.name="QaGateProfileIdentityUnboundError",this.identity=identity}}});function detectHostOS(){switch(process.platform){case"win32":return"windows";case"darwin":return"macos";case"linux":return"linux";default:return"unknown"}}function detectShellFamily(){if(process.env.PSModulePath)return"powershell";if((process.env.ComSpec??"").toLowerCase().includes("cmd.exe"))return"cmd";let shell=process.env.SHELL??"";if(shell.includes("bash"))return"bash";if(shell.includes("zsh"))return"zsh";if(shell.includes("/sh"))return"sh";return"unknown"}function detectExecutionMode(hostOS){if(process.env.WSL_DISTRO_NAME)return"wsl";if(hostOS==="linux"){if(["DOCKER_CONTAINER","KUBERNETES_SERVICE_HOST","CONTAINER"].some((k)=>process.env[k]))return"docker"}return"native"}function deriveOperatingMode(hostOS,_executionMode){if(hostOS==="linux")return"linux";if(hostOS==="macos")return"macos-native";if(hostOS==="windows")return"windows-native";return"unknown"}function buildCommandPolicy(profile){if(profile.isWindowsNative)return{preferredShell:"powershell",avoidPosixExamples:!0,preferNodeApis:!0,preferToolingOverShell:!0,pathExampleStyle:"windows",examples:{listDir:"Get-ChildItem -Force",removeFile:"Remove-Item file.tmp",setEnv:'$env:DEBUG = "1"',printEnv:"$env:PATH",searchText:'Get-ChildItem -Recurse src | Select-String "foo"'}};return{preferredShell:profile.shellFamily==="unknown"?"bash":profile.shellFamily,avoidPosixExamples:!1,preferNodeApis:!0,preferToolingOverShell:!0,pathExampleStyle:"posix",examples:{listDir:"ls -la",removeFile:"rm file.tmp",setEnv:"export DEBUG=1",printEnv:"echo $PATH",searchText:'grep -R "foo" src/'}}}function detectEnvironmentProfile(){let hostOS=detectHostOS(),shellFamily=detectShellFamily(),executionMode=detectExecutionMode(hostOS),operatingMode=deriveOperatingMode(hostOS,executionMode),isWindowsNative=hostOS==="windows"&&executionMode==="native",isWindowsDocker=!1;return{hostOS,shellFamily,executionMode,operatingMode,isWindowsNative,isWindowsDocker:!1,isWSL:executionMode==="wsl",pathStyle:hostOS==="windows"?"windows":"posix",shellCommandPreference:isWindowsNative?"powershell-native":"posix-native",evidence:{processPlatform:process.platform,comspec:process.env.ComSpec,psModulePath:process.env.PSModulePath,termProgram:process.env.TERM_PROGRAM,shell:process.env.SHELL,wslDistroName:process.env.WSL_DISTRO_NAME,containerMarkers:["DOCKER_CONTAINER","KUBERNETES_SERVICE_HOST","CONTAINER"].filter((k)=>!!process.env[k])}}}function deriveCommandPolicy(profile){return buildCommandPolicy(profile)}import{createHash as createHash12}from"node:crypto";function hashString(value){return createHash12("sha256").update(value).digest("hex")}function circuitKey(sessionID,invocationID,actionDigest,circuitKind){return`${sessionID}\x00${invocationID}\x00${actionDigest}\x00${circuitKind}`}function familyKey(sessionID,invocationID,actionDigest){return`${sessionID}\x00${invocationID}\x00${actionDigest}`}function familyPrefix(sessionID,invocationID){return`${sessionID}\x00${invocationID}\x00`}function sessionPrefix(sessionID){return`${sessionID}\x00`}function removeEntry(key){actionCircuits.delete(key)}function pruneGenerationTokenIfUnused(family){let prefix=`${family}\x00`,hasEntries=[...actionCircuits.keys()].some((key)=>key.startsWith(prefix)),isArmed=armedActions.has(family);if(!hasEntries&&!isArmed)actionGenerationTokens.delete(family)}function sweepExpired(now){for(let[key,entry]of actionCircuits)if(entry.expiresAt<=now)removeEntry(key),pruneGenerationTokenIfUnused(familyKey(entry.sessionID,entry.invocationID,entry.actionDigest));for(let[family,armedToken]of armedActions)if(actionGenerationTokens.get(family)!==armedToken)armedActions.delete(family)}function ensureGenerationToken(sessionID,invocationID,actionDigest){let family=familyKey(sessionID,invocationID,actionDigest),current=actionGenerationTokens.get(family);if(current!==void 0)return current;return actionGenerationTokens.set(family,1),1}function bumpGenerationToken(sessionID,invocationID,actionDigest){let family=familyKey(sessionID,invocationID,actionDigest),next=ensureGenerationToken(sessionID,invocationID,actionDigest)+1;return actionGenerationTokens.set(family,next),armedActions.delete(family),next}function touchEntry(key,entry,now){let touched={...entry,expiresAt:now+ACTION_CIRCUIT_TTL_MS};return actionCircuits.delete(key),actionCircuits.set(key,touched),touched}function enforceCapacity(){while(actionCircuits.size>MAX_TRACKED_ACTION_CIRCUITS){let oldest=actionCircuits.keys().next().value;if(oldest===void 0)break;let entry=actionCircuits.get(oldest);if(removeEntry(oldest),entry)pruneGenerationTokenIfUnused(familyKey(entry.sessionID,entry.invocationID,entry.actionDigest))}}function recordResetAudit(record2){if(resetAudit.push(record2),resetAudit.length>MAX_RESET_AUDIT_ROWS)resetAudit.shift()}function armActionCircuitAttempt(sessionID,invocationID,actionDigest){let token=ensureGenerationToken(sessionID,invocationID,actionDigest);return armedActions.set(familyKey(sessionID,invocationID,actionDigest),token),token}function noteActionCircuitFailure(input){let now=input.now??Date.now();sweepExpired(now);let family=familyKey(input.sessionID,input.invocationID,input.actionDigest),expectedToken=input.generationToken??armedActions.get(family)??null,currentToken=ensureGenerationToken(input.sessionID,input.invocationID,input.actionDigest);if(expectedToken===null||expectedToken!==currentToken)return{entry:null,enteredHardStop:!1,ignoredLateEvent:!0};let key=circuitKey(input.sessionID,input.invocationID,input.actionDigest,input.circuitKind),existing=actionCircuits.get(key),count=(existing?.count??0)+1,hardStop=count>=input.hardStopThreshold,entry={sessionID:input.sessionID,invocationID:input.invocationID,actionDigest:input.actionDigest,circuitKind:input.circuitKind,count,hardStop,generationToken:currentToken,lastSignalDigest:input.signal?hashString(input.signal):null,firstSeenAt:existing?.firstSeenAt??now,updatedAt:now,expiresAt:now+ACTION_CIRCUIT_TTL_MS};return actionCircuits.delete(key),actionCircuits.set(key,entry),enforceCapacity(),{entry,enteredHardStop:hardStop&&!existing?.hardStop,ignoredLateEvent:!1}}function clearActionCircuitEntries(sessionID,invocationID,actionDigest){let prefix=`${familyKey(sessionID,invocationID,actionDigest)}\x00`;for(let key of[...actionCircuits.keys()])if(key.startsWith(prefix))removeEntry(key)}function clearActionCircuit(sessionID,invocationID,actionDigest,options){if(clearActionCircuitEntries(sessionID,invocationID,actionDigest),bumpGenerationToken(sessionID,invocationID,actionDigest),options?.reason)recordResetAudit({sessionID,invocationID,actionDigest,reason:options.reason,actor:options.actor??null,at:options.now??Date.now()})}function resetActionCircuitExternally(input){clearActionCircuit(input.sessionID,input.invocationID,input.actionDigest,{reason:"external",actor:input.actor??null,now:input.now})}function clearInvocationActionCircuits(sessionID,invocationID,now){let prefix=familyPrefix(sessionID,invocationID);for(let key of[...actionCircuits.keys()])if(key.startsWith(prefix))removeEntry(key);for(let family of[...actionGenerationTokens.keys()])if(family.startsWith(prefix))actionGenerationTokens.delete(family),armedActions.delete(family),recordResetAudit({sessionID,invocationID,actionDigest:family.slice(prefix.length),reason:"invocation",actor:null,at:now??Date.now()})}function clearSessionActionCircuits(sessionID,now){let prefix=sessionPrefix(sessionID);for(let key of[...actionCircuits.keys()])if(key.startsWith(prefix))removeEntry(key);for(let family of[...actionGenerationTokens.keys()])if(family.startsWith(prefix)){let familyTail=family.slice(prefix.length),separatorIndex=familyTail.indexOf("\x00"),invocationID=separatorIndex>0?Number(familyTail.slice(0,separatorIndex)):0,actionDigest=separatorIndex>0?familyTail.slice(separatorIndex+1):familyTail;actionGenerationTokens.delete(family),armedActions.delete(family),recordResetAudit({sessionID,invocationID,actionDigest,reason:"session",actor:null,at:now??Date.now()})}}function getBlockingActionCircuit(sessionID,invocationID,actionDigest){let now=Date.now();sweepExpired(now);let prefix=`${familyKey(sessionID,invocationID,actionDigest)}\x00`;for(let[key,entry]of actionCircuits)if(key.startsWith(prefix)&&entry.hardStop)return touchEntry(key,entry,now);return null}function listBlockingActionCircuitsForInvocation(sessionID,invocationID){let now=Date.now();sweepExpired(now);let prefix=familyPrefix(sessionID,invocationID),result=[];for(let[key,entry]of[...actionCircuits])if(key.startsWith(prefix)&&entry.hardStop)result.push(touchEntry(key,entry,now));return result}function peekActionCircuitCount(sessionID,invocationID,actionDigest,circuitKind){return actionCircuits.get(circuitKey(sessionID,invocationID,actionDigest,circuitKind))?.count??0}function expireActionCircuit(sessionID,invocationID,actionDigest,circuitKind){let entry=actionCircuits.get(circuitKey(sessionID,invocationID,actionDigest,circuitKind));if(entry)entry.expiresAt=Date.now()-1}function clearAllActionCircuits(){actionCircuits.clear(),actionGenerationTokens.clear(),armedActions.clear(),resetAudit.length=0}var MAX_TRACKED_ACTION_CIRCUITS=500,ACTION_CIRCUIT_TTL_MS=1800000,MAX_RESET_AUDIT_ROWS=128,actionCircuits,actionGenerationTokens,armedActions,resetAudit,_test_exports;var init_action_circuit=__esm(()=>{actionCircuits=new Map,actionGenerationTokens=new Map,armedActions=new Map,resetAudit=[];_test_exports={ACTION_CIRCUIT_TTL_MS,MAX_TRACKED_ACTION_CIRCUITS,size:()=>actionCircuits.size,getGenerationToken:(sessionID,invocationID,actionDigest)=>ensureGenerationToken(sessionID,invocationID,actionDigest),getResetAudit:()=>resetAudit.map((entry)=>({...entry}))}});import{randomBytes as randomBytes2}from"node:crypto";import*as fs12 from"node:fs";import*as path17 from"node:path";function matchTempGrammar(basename3){return SWARM_TEMP_GRAMMARS.find((g)=>g.match.test(basename3))}function parseTargetBasename(basename3){for(let g of SWARM_TEMP_GRAMMARS){if(!g.parsesTarget)continue;let m=g.match.exec(basename3);if(m?.[1])return m[1]}return null}function assertWellFormedTargetPath(targetPath){if(!path17.isAbsolute(targetPath))throw Error(`atomic-write target must be absolute: ${targetPath}`);if(/[\0-\x1f\x7f]/.test(targetPath))throw Error("atomic-write target contains control characters");if(/[*?]/.test(targetPath)||/(^|[/\\])\{[^}]*\}([/\\]|$)/.test(targetPath))throw Error(`atomic-write target contains glob metacharacters: ${targetPath}`);if(/(^|[/\\])~([/\\]|$)/.test(targetPath))throw Error("atomic-write target contains unresolved home-dir marker (~)");if(/\$\{?[A-Za-z_][A-Za-z0-9_]*\}?/.test(targetPath)||/%[^/\\%]+%/.test(targetPath))throw Error("atomic-write target contains unresolved environment-variable form")}function lstatNotSymlink(p,what){if(fs12.lstatSync(p).isSymbolicLink())throw Error(`${what} is a symlink/reparse point: ${p}`)}function assertSwarmContainedTarget(targetPath){assertWellFormedTargetPath(targetPath);let resolved=path17.normalize(path17.resolve(targetPath)),segments=resolved.split(path17.sep),swarmIdx=-1;for(let i=segments.length-2;i>=1;i--)if(segments[i]===".swarm"){swarmIdx=i;break}if(swarmIdx===-1)throw Error(`atomic-write target is not under a project .swarm root: ${targetPath}`);let swarmRoot=segments.slice(0,swarmIdx+1).join(path17.sep);try{let st=fs12.lstatSync(swarmRoot);if(!st.isDirectory()||st.isSymbolicLink())throw Error(`.swarm root is not a real directory (symlink/reparse or non-dir): ${swarmRoot}`)}catch(err){if(err?.code!=="ENOENT")throw err}let rel=path17.relative(swarmRoot,resolved);if(!rel||rel.startsWith("..")||path17.isAbsolute(rel))throw Error(`atomic-write target escapes .swarm root: ${targetPath}`);let probe=swarmRoot;for(let seg of rel.split(path17.sep)){if(probe=path17.join(probe,seg),!fs12.existsSync(probe))break;lstatNotSymlink(probe,"path segment under .swarm")}return{projectRoot:path17.dirname(swarmRoot),swarmRoot}}function toBuffer(content){if(typeof content==="string")return Buffer.from(content,"utf-8");return content}function syncSleep(ms){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,ms)}catch{let start=Date.now();while(Date.now()-start<ms);}}function renameWithRetry(tempPath,targetPath){let lastError;for(let attempt=0;attempt<=RENAME_RETRY_DELAYS_MS.length;attempt++)try{_internals15.renameSync(tempPath,targetPath);return}catch(err){lastError=err;let code=err?.code;if(!code||!RETRYABLE_RENAME_CODES.has(code))throw err;if(attempt<RENAME_RETRY_DELAYS_MS.length)syncSleep(RENAME_RETRY_DELAYS_MS[attempt])}throw lastError}function writeAtomicSync(targetPath,content,options){if(options?.contained!==!1)assertSwarmContainedTarget(targetPath);else assertWellFormedTargetPath(targetPath);let resolvedTarget=path17.resolve(targetPath),buffer=toBuffer(content),maxBytes=options?.maxBytes??MAX_ATOMIC_WRITE_BYTES;if(buffer.byteLength>maxBytes)throw Error(`atomic write exceeds ${maxBytes} byte bound: ${buffer.byteLength}`);let tempPath=`${resolvedTarget}.${_internals15.randomSuffix()}.tmp`;fs12.mkdirSync(path17.dirname(tempPath),{recursive:!0});try{let fd=fs12.openSync(tempPath,"wx");try{let written=0;while(written<buffer.byteLength)written+=_internals15.writeSync(fd,buffer,written,buffer.byteLength-written);if(options?.skipFsync!==!0)try{_internals15.fsyncSync(fd)}catch{}}finally{fs12.closeSync(fd)}renameWithRetry(tempPath,resolvedTarget)}finally{try{_internals15.unlinkSync(tempPath)}catch{}}try{let dirFd=fs12.openSync(path17.dirname(resolvedTarget),"r");try{fs12.fsyncSync(dirFd)}finally{fs12.closeSync(dirFd)}}catch{}invalidateCachedArtifact(resolvedTarget)}async function atomicWriteSwarmFile(targetPath,content,options){await new Promise((resolve12)=>setImmediate(resolve12)),writeAtomicSync(targetPath,content,options)}function atomicWriteSwarmFileSync(targetPath,content,options){writeAtomicSync(targetPath,content,options)}async function atomicWriteFileAnyRoot(targetPath,content,options){await new Promise((resolve12)=>setImmediate(resolve12)),writeAtomicSync(targetPath,content,{...options,contained:!1})}var UUID_RE="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",SWARM_TEMP_GRAMMARS,WRITER_CLASSIFICATION,MAX_ATOMIC_WRITE_BYTES=268435456,RENAME_RETRY_DELAYS_MS,RETRYABLE_RENAME_CODES,_internals15;var init_atomic_write=__esm(()=>{init_swarm_artifact_cache();SWARM_TEMP_GRAMMARS=[{id:"canonical-v1",era:"canonical",match:/^(.+)\.[0-9a-f]{32}\.tmp$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/utils/atomic-write.ts:atomicWriteSwarmFile","src/utils/atomic-write.ts:atomicWriteFileAnyRoot"]},{id:"target-suffix-tmp-uuid",era:"current",match:new RegExp(`^(.+)\\.tmp\\.${UUID_RE}$`),token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/commands/handoff.ts:48 (pre-#2035)","src/commands/handoff.ts:79 (pre-#2035)","src/memory/local-jsonl-provider.ts:1171","src/config/bundled-skills.ts:241"]},{id:"target-suffix-tmp-pid-uuid",era:"current",match:new RegExp(`^(.+)\\.tmp\\.\\d+\\.${UUID_RE}$`),token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/hooks/pr-workflow-gate.ts:13358"],note:"pre/post-rename file-identity verification (assertOpened/ClosedSwarmFileIdentity, pr-workflow-gate.ts:13300-13356) is writer-specific and load-bearing"},{id:"target-suffix-tmp-num-num-json",era:"current",match:/^(.+)\.tmp\.\d+\.\d+\.json$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/hooks/issue-trace-state.ts:315"],note:"the .json terminator keeps this shape distinct from the bare two-token family — declared before it so first-match wins"},{id:"target-suffix-tmp-num-alnum",era:"current",match:/^(.+)\.tmp\.\d+\.[0-9a-z]+$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/evidence/task-file.ts:67 (pre-#2035)","src/scope/scope-persistence.ts:2304 (pre-#2035)","src/scope/scope-persistence.ts:2318 (pre-#2035)","src/plan/manager.ts:628","src/plan/manager.ts:1793","src/plan/manager.ts:1839","src/review/evidence.ts:160","src/turbo/lean/evidence.ts:182","src/summaries/manager.ts:122","src/evidence/manager.ts:288","src/evidence/manager.ts:456","src/tools/sast-baseline.ts:106","src/tools/repo-graph/storage.ts:397","src/memory/reflection-service.ts:547 (pre-#2035)","src/hooks/review-receipt.ts:608","src/hooks/review-receipt.ts:674","src/hooks/review-receipt.ts:812","src/knowledge/identity.ts:209","src/evidence/phase-participation.ts:303 (pre-#2035)","src/turbo/lean/integration.ts:426","src/turbo/lean/reviewer.ts:403","src/plan/ledger.ts:713","src/services/synonym-map.ts:389","src/services/skill-optimizer/store.ts:340","src/services/skill-optimizer/store.ts:503","src/turbo/epic/state.ts:177","src/turbo/epic/calibration.ts:197","src/commands/archive-sqlite.ts:318","src/memory/jsonl-migration.ts:157"],note:"fsync-discipline / lock-scoped fd writers whose temp naming is pinned by their own durability test suites (plan-durability invariant 5, #2034 crash matrix); grammars registered here so their residue stays discoverable"},{id:"target-suffix-tmp-token",era:"current",match:/^(.+)\.tmp\.[0-9a-z-]{6,}$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/turbo/lean/state.ts:246","src/turbo/lean/recovery.ts:175","src/hooks/delegation-gate/worktree-merge-status.ts:110"]},{id:"target-suffix-tmp-dash",era:"current",match:/^(.+)\.tmp-\d+-[0-9a-z-]+$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/services/skill-evaluator.ts:492 (pre-#2035)","src/services/skill-improver.ts:154 (pre-#2035)","src/services/skill-consolidation.ts:72 (pre-#2035)","src/services/skill-generator.ts:601 (pre-#2035)","src/tools/spec-write.ts:98","src/sdd/effective-spec.ts:1149","src/background/lane-output-store.ts:353","src/background/pending-delegations.ts:922","src/background/delegation-health.ts:300","src/hooks/delegation-gate/worktree-provisioning-owner.ts:100","src/tools/submit-phase-council-verdicts.ts:458","src/summaries/store.ts:46 (pre-#2035)"],note:"background lane/delegation stores keep bounded-retry rename semantics wired into their callers (#2034/#2276 delivery contracts); migration candidates for a follow-up but grammars registered"},{id:"target-suffix-tmp-dash-num",era:"current",match:/^(.+)\.tmp-\d+$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/services/skill-improver-quota.ts:114"]},{id:"target-dot-pid-uuid-tmp",era:"current",match:new RegExp(`^(.+)\\.\\d+\\.${UUID_RE}\\.tmp$`),token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/hooks/knowledge-receipt-ledger-storage.ts:591"],note:"pre/post-rename file-identity verification (existingFileIdentity checks, knowledge-receipt-ledger-storage.ts:544-591) is writer-specific and load-bearing"},{id:"dot-numeric-instance-tmp",era:"current",match:/^\..+(?:\.\d+){2,4}\.[0-9a-z]+\.tmp$/,token:"instance",quarantineEligible:!0,parsesTarget:!1,producers:["src/utils/bun-compat.ts:138","src/tools/repo-graph/freshness.ts:171"],note:"bunWrite Node-fallback internal temp and the repo-graph fingerprint temp (2-4 numeric token groups); leading-dot temps are standalone, target not parsed"},{id:"dot-uuid-instance-tmp",era:"current",match:new RegExp(`^\\..+\\.${UUID_RE}\\.tmp$`),token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/tools/write-pr-review-artifact.ts:135","src/tools/write-pr-review-trigger-eval.ts:574"],note:"bundled-skills writes outside .swarm (project skill roots) and keeps its own contained-directory logic (invariant 4 bundled-skill ownership)"},{id:"tmp-prefix-named",era:"legacy",match:/^\.tmp-.+-\d+-\d+$/,token:"instance",quarantineEligible:!0,parsesTarget:!1,producers:["src/commands/issue.ts:167 (pre-#2035)"],note:"prefix form embeds the filename; target not reliably parseable (dashes), so eligibility relies on the age/tracked/symlink/lock gates"},{id:"target-rebuild-close",era:"current",match:/^(.+)\.(?:rebuild|close)\.\d+\.[0-9a-z]+$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/plan/manager.ts:1979","src/plan/manager.ts:2168"],note:"plan-durability (invariant 5) fd-write paths; grammars registered, writers unchanged in this PR"},{id:"target-migration-pid",era:"current",match:/^(.+)\.migration-\d+$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/scope/scope-persistence.ts:633 (pre-#2035)"]},{id:"dot-tmp-prefix-legacy",era:"legacy",match:/^\.tmp\..+$/,token:"constant",quarantineEligible:!0,parsesTarget:!1,producers:["pre-7.x writers (historical); matched by the pre-#2035 close sweep"],note:"legacy prefix grammar: issue #2035 req 7 preserves its handling — stale instances are quarantined (formerly unlinked) under the same eligibility gates"},{id:"dot-constant-tmp",era:"current",match:/^\..+\.tmp$/,token:"constant",quarantineEligible:!1,parsesTarget:!1,producers:["src/tools/write-drift-evidence.ts:275","src/tools/write-mutation-evidence.ts:169","src/tools/write-hallucination-evidence.ts:121","src/tools/record-implementation-review.ts:87","src/tools/record-recurrence-sweep.ts:125","src/tools/record-issue-reproduction.ts:85","src/tools/record-issue-publication.ts:74","src/tools/write-final-council-evidence.ts:403"],note:"constant-name temps: no per-invocation token — reported when stale, never auto-quarantined (may be an in-flight writer of any process)"},{id:"target-constant-tmp",era:"current",match:/^(.+)\.tmp$/,token:"constant",quarantineEligible:!1,parsesTarget:!1,producers:["src/tools/checkpoint.ts:194","src/full-auto/state.ts:460","src/context-map/persistence.ts:119","src/context-map/capsule-persistence.ts:107","src/test-impact/history-store.ts:225","src/test-impact/history-store.ts:353","src/hooks/promotion-evidence-store.ts:102","src/hooks/skill-usage-log.ts:554","src/hooks/skill-usage-log.ts:608","src/parallel/file-locks.ts:113","src/plan/ledger.ts:1302","src/plan/ledger.ts:1303"],note:"constant-name temps: reported when stale, never auto-quarantined. file-locks meta sidecars live under the scanner-skipped .swarm/locks/ subtree; the ledger reconcile temp embeds instance tokens but its .tmp-suffix shape maps here (conservatively report-only)"}];WRITER_CLASSIFICATION=Object.freeze({"src/commands/close.ts":"migrated","src/commands/handoff.ts":"migrated","src/commands/simulate.ts":"migrated","src/commands/coupling.ts":"migrated","src/commands/issue.ts":"migrated","src/evidence/task-file.ts":"migrated","src/evidence/phase-participation.ts":"migrated","src/memory/reflection-service.ts":"migrated","src/scope/scope-persistence.ts":"migrated","src/services/skill-consolidation.ts":"migrated","src/services/skill-evaluator.ts":"migrated","src/services/skill-generator.ts":"migrated","src/services/skill-improver.ts":"migrated","src/summaries/store.ts":"migrated","src/background/delegation-health.ts":"registered-bespoke","src/background/lane-output-store.ts":"registered-bespoke","src/background/pending-delegations.ts":"registered-bespoke","src/commands/archive-sqlite.ts":"registered-bespoke","src/context-map/capsule-persistence.ts":"registered-bespoke","src/context-map/persistence.ts":"registered-bespoke","src/context-map/telemetry.ts":"registered-bespoke","src/evidence/documents-retention.ts":"registered-bespoke","src/evidence/manager.ts":"registered-bespoke","src/full-auto/state.ts":"registered-bespoke","src/hooks/delegation-gate/worktree-merge-status.ts":"registered-bespoke","src/hooks/delegation-gate/worktree-provisioning-owner.ts":"registered-bespoke","src/hooks/issue-trace-state.ts":"registered-bespoke","src/hooks/knowledge-receipt-ledger-storage.ts":"registered-bespoke","src/hooks/pr-workflow-gate.ts":"registered-bespoke","src/hooks/promotion-evidence-store.ts":"registered-bespoke","src/hooks/review-receipt.ts":"registered-bespoke","src/hooks/skill-usage-log.ts":"registered-bespoke","src/knowledge/identity.ts":"registered-bespoke","src/memory/jsonl-migration.ts":"external","src/memory/local-jsonl-provider.ts":"registered-bespoke","src/plan/ledger.ts":"registered-bespoke","src/plan/manager.ts":"registered-bespoke","src/review/evidence.ts":"registered-bespoke","src/sdd/effective-spec.ts":"registered-bespoke","src/services/skill-improver-quota.ts":"registered-bespoke","src/services/skill-optimizer/activation.ts":"external","src/services/skill-optimizer/store.ts":"registered-bespoke","src/services/skill-reviser.ts":"external","src/services/synonym-map.ts":"registered-bespoke","src/session/snapshot-writer.ts":"registered-bespoke","src/summaries/manager.ts":"registered-bespoke","src/test-impact/history-store.ts":"registered-bespoke","src/turbo/epic/calibration.ts":"registered-bespoke","src/turbo/epic/state.ts":"registered-bespoke","src/turbo/lean/evidence.ts":"registered-bespoke","src/turbo/lean/integration.ts":"registered-bespoke","src/turbo/lean/recovery.ts":"registered-bespoke","src/turbo/lean/reviewer.ts":"registered-bespoke","src/turbo/lean/state.ts":"registered-bespoke","src/tools/apply-patch.ts":"external","src/tools/checkpoint.ts":"registered-bespoke","src/tools/record-implementation-review.ts":"registered-bespoke","src/tools/record-issue-publication.ts":"registered-bespoke","src/tools/record-issue-reproduction.ts":"registered-bespoke","src/tools/record-recurrence-sweep.ts":"registered-bespoke","src/tools/repo-graph/freshness.ts":"registered-bespoke","src/tools/repo-graph/storage.ts":"registered-bespoke","src/tools/sast-baseline.ts":"registered-bespoke","src/tools/spec-write.ts":"registered-bespoke","src/tools/submit-phase-council-verdicts.ts":"registered-bespoke","src/tools/write-drift-evidence.ts":"registered-bespoke","src/tools/write-final-council-evidence.ts":"registered-bespoke","src/tools/write-hallucination-evidence.ts":"registered-bespoke","src/tools/write-mutation-evidence.ts":"registered-bespoke","src/tools/write-pr-review-artifact.ts":"registered-bespoke","src/tools/write-pr-review-trigger-eval.ts":"registered-bespoke","src/config/bundled-skills.ts":"external","src/services/config-doctor.ts":"external","src/parallel/file-locks.ts":"registered-bespoke","src/utils/bun-compat.ts":"registered-bespoke","src/background/plan-sync-worker.ts":"reader-only","src/config/lane-permissions.ts":"reader-only","src/environment/profile.ts":"reader-only","src/worktree/core.ts":"reader-only"});RENAME_RETRY_DELAYS_MS=[10,25,50,100,200],RETRYABLE_RENAME_CODES=new Set(["EPERM","EBUSY","EACCES","EEXIST"]),_internals15={randomSuffix:()=>randomBytes2(16).toString("hex"),writeSync:(fd,buffer,offset,length)=>fs12.writeSync(fd,buffer,offset,length),renameSync:(from,to)=>fs12.renameSync(from,to),unlinkSync:(p)=>fs12.unlinkSync(p),fsyncSync:(fd)=>fs12.fsyncSync(fd)}});import*as path18 from"node:path";function taskEvidenceRelPath(taskId){return path18.join("evidence",`${taskId}.json`)}function taskEvidencePath(directory,taskId){return path18.join(directory,".swarm",taskEvidenceRelPath(taskId))}async function atomicWriteFile(targetPath,content){await atomicWriteFileAnyRoot(targetPath,content)}function withTaskEvidenceLock(directory,taskId,agent,fn2){return withEvidenceLock(directory,taskEvidenceRelPath(taskId),agent,taskId,fn2)}var init_task_file=__esm(()=>{init_atomic_write();init_lock()});import{createHash as createHash13}from"node:crypto";import*as fs13 from"node:fs";import*as path19 from"node:path";function samePath(left,right){let normalize3=(value)=>process.platform==="win32"?path19.resolve(value).toLowerCase():path19.resolve(value);return normalize3(left)===normalize3(right)}function assertSafeRequirementsParent(directory,create){assertProjectRoot(directory,void 0,"task gate requirements");let rootStat=fs13.lstatSync(directory);if(rootStat.isSymbolicLink()||!rootStat.isDirectory())throw Error("TASK_GATE_REQUIREMENTS_UNREADABLE: project root is not a regular directory");let canonicalRoot=fs13.realpathSync(directory),segments=[".swarm","evidence","task-gate-requirements"],current=canonicalRoot;for(let segment of segments){current=path19.join(current,segment);let info;try{info=fs13.lstatSync(current)}catch(error49){if(error49.code==="ENOENT"){if(!create)return current;try{fs13.mkdirSync(current)}catch(mkdirError){if(mkdirError.code!=="EEXIST")throw mkdirError}info=fs13.lstatSync(current)}else throw error49}if(info.isSymbolicLink()||!info.isDirectory())throw Error("TASK_GATE_REQUIREMENTS_UNREADABLE: receipt parent is redirected or not a directory");let canonicalCurrent=fs13.realpathSync(current);if(!samePath(canonicalCurrent,current))throw Error("TASK_GATE_REQUIREMENTS_UNREADABLE: receipt parent escaped the project root")}return current}function safeTaskGateRequirementsReceiptPath(directory,taskId,createParent){let parent=assertSafeRequirementsParent(directory,createParent);return path19.join(parent,`${taskId}.jsonl`)}function sha256(value){return createHash13("sha256").update(value).digest("hex")}function canonicalReceiptPayload(receipt){return JSON.stringify({...receipt,requiredGates:[...receipt.requiredGates]})}function computeChainHash(receipt){return sha256(canonicalReceiptPayload(receipt))}function readBoundedTextFile(filePath){let pathStat;try{pathStat=fs13.lstatSync(filePath)}catch(error49){if(error49.code==="ENOENT")return null;throw error49}if(pathStat.isSymbolicLink()||!pathStat.isFile())throw Error("TASK_GATE_REQUIREMENTS_UNREADABLE: receipt path is not a regular file");if(pathStat.size>MAX_TASK_GATE_REQUIREMENTS_BYTES)throw Error(`TASK_GATE_REQUIREMENTS_OVERSIZED: ${pathStat.size} bytes exceeds ${MAX_TASK_GATE_REQUIREMENTS_BYTES}`);let descriptor=fs13.openSync(filePath,fs13.constants.O_RDONLY|(fs13.constants.O_NOFOLLOW??0));try{let openedStat=fs13.fstatSync(descriptor);if(!openedStat.isFile()||openedStat.dev!==pathStat.dev||openedStat.ino!==pathStat.ino)throw Error("TASK_GATE_REQUIREMENTS_UNREADABLE: receipt changed while being opened");if(openedStat.size>MAX_TASK_GATE_REQUIREMENTS_BYTES)throw Error(`TASK_GATE_REQUIREMENTS_OVERSIZED: ${openedStat.size} bytes exceeds ${MAX_TASK_GATE_REQUIREMENTS_BYTES}`);return fs13.readFileSync(descriptor,"utf-8")}finally{fs13.closeSync(descriptor)}}async function readTaskGateRequirementsReceipts(directory,taskId){let filePath=safeTaskGateRequirementsReceiptPath(directory,taskId,!1),text=readBoundedTextFile(filePath);if(text===null)return[];let receipts=[];for(let line of text.split(`
|
|
270
|
+
LIMIT 1`).get(readablePlanId)??null}function buildExactStoragePlanId(identityHash){return`qa2-${identityHash}`}function hasAnyGatePatch(gates){return Object.values(gates).some((value)=>value!==void 0)}function verifyBoundIdentityBinding(binding,identity){if(binding.identity_hash!==identity.identityHash||binding.raw_swarm!==identity.swarm||binding.raw_title!==identity.title||binding.readable_plan_id!==identity.planId)throw Error(`QA gate profile identity binding is corrupt for swarm_id='${identity.swarm}' and plan_title='${identity.title}'`)}function lookupProfileForIdentityTx(db,identity){let binding=readIdentityBindingByHash(db,identity.identityHash);if(binding){verifyBoundIdentityBinding(binding,identity);let row=readProfileRowById(db,binding.profile_id);if(!row)throw Error(`QA gate profile identity binding points to missing profile_id=${binding.profile_id}`);return{kind:"bound",identity,profile:rowToProfileWithBinding(row,binding)}}let legacyRow=readUnboundLegacyProfileRowByReadablePlanId(db,identity.planId);if(legacyRow)return{kind:"unbound_legacy",identity,profile:rowToProfile(legacyRow)};return{kind:"missing",identity}}function createExactIdentityBindingTx(db,profileId,identity){db.run("INSERT INTO qa_gate_profile_identity (identity_hash, profile_id, raw_swarm, raw_title, readable_plan_id) VALUES (?, ?, ?, ?, ?)",[identity.identityHash,profileId,identity.swarm,identity.title,identity.planId])}function createExactProfileTx(db,identity,projectType,initialGates){let gatesJson=JSON.stringify({...DEFAULT_QA_GATES,...initialGates});db.run("INSERT INTO qa_gate_profile (plan_id, project_type, gates) VALUES (?, ?, ?)",[buildExactStoragePlanId(identity.identityHash),projectType??null,gatesJson]);let row=readProfileRowByPlanId(db,buildExactStoragePlanId(identity.identityHash));if(!row)throw Error(`Failed to create QA gate profile row for exact identity plan_id=${identity.planId}`);createExactIdentityBindingTx(db,row.id,identity);let binding=readIdentityBindingByHash(db,identity.identityHash);if(!binding)throw Error(`Failed to create QA gate profile identity binding for plan_id=${identity.planId}`);return rowToProfileWithBinding(row,binding)}function shouldAdoptLegacyProfile(identity,options){if(options.allowLegacyAdoption!==!0)return!1;return options.legacyAdoptionIdentity?.swarm===identity.swarm&&options.legacyAdoptionIdentity?.title===identity.title}function getProfile(directory,planId){if(!projectDbExists(directory))return null;let db=getProjectDb(directory),row=readProfileRowByPlanId(db,planId);return row?rowToProfile(row):null}function getProfileForIdentity(directory,identity){let lookup=getProfileLookupForIdentity(directory,identity);if(lookup.kind==="bound")return lookup.profile;if(lookup.kind==="unbound_legacy")throw new QaGateProfileIdentityUnboundError(lookup.identity);return null}function getProfileLookupForIdentity(directory,identity){let exact=buildProfileIdentity(identity);if(!projectDbExists(directory))return{kind:"missing",identity:exact};let db=getProjectDb(directory);return lookupProfileForIdentityTx(db,exact)}function hasAnyProfileWithEnabledGate(directory,gate){if(!projectDbExists(directory))return!1;let rows=getProjectDb(directory).query("SELECT gates FROM qa_gate_profile").all();for(let row of rows)try{if(JSON.parse(row.gates)?.[gate]===!0)return!0}catch{}return!1}function getOrCreateProfile(directory,planId,projectType,initialGates={}){let existing=_internals14.getProfile(directory,planId);if(existing)return existing;let db=getProjectDb(directory),seededGates={...DEFAULT_QA_GATES};for(let key of Object.keys(DEFAULT_QA_GATES))if(typeof initialGates[key]==="boolean")seededGates[key]=initialGates[key];let gatesJson=JSON.stringify(seededGates),insert=db.transaction(()=>{db.run("INSERT INTO qa_gate_profile (plan_id, project_type, gates) VALUES (?, ?, ?)",[planId,projectType??null,gatesJson])});try{insert()}catch(err){if(!(err instanceof Error?err.message:String(err)).toLowerCase().includes("unique"))throw err}let after=_internals14.getProfile(directory,planId);if(!after)throw Error(`Failed to create or load QA gate profile for plan_id=${planId}`);return after}function getOrCreateProfileForIdentity(directory,identity,projectType,initialGates={}){let db=getProjectDb(directory),exact=buildProfileIdentity(identity);return withImmediateTransaction(db,()=>{let lookup=lookupProfileForIdentityTx(db,exact);if(lookup.kind==="bound")return lookup.profile;if(lookup.kind==="unbound_legacy")return createExactProfileTx(db,exact,projectType,initialGates);return createExactProfileTx(db,exact,projectType,initialGates)})}function setGates(directory,planId,gates){let db=getProjectDb(directory),savepointName=`qa_gate_profile_set_${qaGateProfileSavepointCounter++}`,startedTransaction=!db.inTransaction;db.run(startedTransaction?"BEGIN IMMEDIATE":`SAVEPOINT ${savepointName}`);try{let currentRow=db.query("SELECT * FROM qa_gate_profile WHERE plan_id = ?").get(planId);if(!currentRow)throw Error(`No QA gate profile found for plan_id=${planId} — call getOrCreateProfile first`);let current=rowToProfile(currentRow);if(current.locked_at!==null)throw Error("Cannot modify gates: QA gate profile is locked after critic approval");_internals14.afterSetGatesRead(current);let merged={...current.gates};for(let key of Object.keys(gates)){let incoming=gates[key];if(incoming===void 0)continue;if(incoming===!1&¤t.gates[key]===!0)throw Error(`Cannot disable gate '${key}': sessions can only ratchet tighter`);if(incoming===!0)merged[key]=!0}db.run("UPDATE qa_gate_profile SET gates = ? WHERE plan_id = ?",[JSON.stringify(merged),planId]);let updatedRow=db.query("SELECT * FROM qa_gate_profile WHERE plan_id = ?").get(planId);if(!updatedRow)throw Error(`Failed to re-read QA gate profile after update for plan_id=${planId}`);return db.run(startedTransaction?"COMMIT":`RELEASE ${savepointName}`),rowToProfile(updatedRow)}catch(err){try{if(db.run(startedTransaction?"ROLLBACK":`ROLLBACK TO ${savepointName}`),!startedTransaction)db.run(`RELEASE ${savepointName}`)}catch{}throw err}}function setGatesForIdentity(directory,identity,gates,options={}){let db=getProjectDb(directory),exact=buildProfileIdentity(identity),savepointName=`qa_gate_profile_set_identity_${qaGateProfileSavepointCounter++}`,startedTransaction=!db.inTransaction,finishTransaction=()=>{db.run(startedTransaction?"COMMIT":`RELEASE ${savepointName}`)},rollbackTransaction=()=>{if(db.run(startedTransaction?"ROLLBACK":`ROLLBACK TO ${savepointName}`),!startedTransaction)db.run(`RELEASE ${savepointName}`)};db.run(startedTransaction?"BEGIN IMMEDIATE":`SAVEPOINT ${savepointName}`);try{let lookup=lookupProfileForIdentityTx(db,exact);if(lookup.kind==="missing"){let created=createExactProfileTx(db,exact,options.projectType,gates);return finishTransaction(),created}if(lookup.kind==="unbound_legacy")if(shouldAdoptLegacyProfile(exact,options)){if(createExactIdentityBindingTx(db,lookup.profile.id,exact),lookup=lookupProfileForIdentityTx(db,exact),lookup.kind!=="bound")throw Error(`Failed to adopt legacy QA gate profile for exact identity plan_id=${exact.planId}`)}else if(options.allowLegacyCollisionCreate===!0){let created=createExactProfileTx(db,exact,options.projectType,gates);return finishTransaction(),created}else throw new QaGateProfileIdentityUnboundError(lookup.identity);let current=lookup.profile,currentRow=readProfileRowById(db,current.id);if(!currentRow)throw Error(`Failed to read QA gate profile row for profile_id=${current.id}`);if(_internals14.afterSetGatesForIdentityRead?.({directory,identity:exact,profileId:current.id,storagePlanId:currentRow.plan_id}),current.locked_at!==null){if(!hasAnyGatePatch(gates))return finishTransaction(),current;throw Error("Cannot modify gates: QA gate profile is locked after critic approval")}let merged={...current.gates};for(let key of Object.keys(gates)){let incoming=gates[key];if(incoming===void 0)continue;if(incoming===!1&¤t.gates[key]===!0)throw Error(`Cannot disable gate '${key}': sessions can only ratchet tighter`);if(incoming===!0)merged[key]=!0}db.run("UPDATE qa_gate_profile SET gates = ? WHERE id = ?",[JSON.stringify(merged),current.id]);let updatedRow=readProfileRowById(db,current.id),binding=readIdentityBindingByHash(db,exact.identityHash);if(!updatedRow||!binding)throw Error(`Failed to re-read QA gate profile after exact-identity update for plan_id=${exact.planId}`);return finishTransaction(),rowToProfileWithBinding(updatedRow,binding)}catch(err){try{rollbackTransaction()}catch{}throw err}}function lockProfileForIdentity(directory,identity,snapshotSeq){let db=getProjectDb(directory),exact=buildProfileIdentity(identity);return withImmediateTransaction(db,()=>{let lookup=lookupProfileForIdentityTx(db,exact);if(lookup.kind==="missing")throw Error(`No QA gate profile found for exact identity plan_id=${exact.planId} — cannot lock`);if(lookup.kind==="unbound_legacy")throw new QaGateProfileIdentityUnboundError(lookup.identity);if(lookup.profile.locked_at!==null)return lookup.profile;db.run("UPDATE qa_gate_profile SET locked_at = datetime('now'), locked_by_snapshot_seq = ? WHERE id = ?",[snapshotSeq,lookup.profile.id]);let updatedRow=readProfileRowById(db,lookup.profile.id),binding=readIdentityBindingByHash(db,exact.identityHash);if(!updatedRow||!binding)throw Error(`Failed to re-read locked QA gate profile for exact identity plan_id=${exact.planId}`);return rowToProfileWithBinding(updatedRow,binding)})}function computeProfileHash(profile){let payload=JSON.stringify({plan_id:profile.plan_id,identity_hash:profile.identity_hash,gates:profile.gates});return createHash11("sha256").update(payload).digest("hex")}function getEffectiveGates(profile,sessionOverrides){let merged={...profile.gates};for(let key of Object.keys(sessionOverrides))if(sessionOverrides[key]===!0)merged[key]=!0;return merged}var _internals14,DEFAULT_QA_GATES,QaGateProfileIdentityUnboundError,qaGateProfileSavepointCounter=0;var init_qa_gate_profile=__esm(()=>{init_utils3();init_project_db();_internals14={getProfile,getProfileLookupForIdentity,getProfileForIdentity,getOrCreateProfile,getOrCreateProfileForIdentity,setGates,setGatesForIdentity,lockProfileForIdentity,getEffectiveGates,computeProfileHash,hasAnyProfileWithEnabledGate,afterSetGatesRead:()=>{}},DEFAULT_QA_GATES={reviewer:!0,test_engineer:!0,council_mode:!1,sme_enabled:!0,critic_pre_plan:!0,hallucination_guard:!1,sast_enabled:!0,mutation_test:!1,phase_council:!1,drift_check:!0,final_council:!1};QaGateProfileIdentityUnboundError=class QaGateProfileIdentityUnboundError extends Error{identity;constructor(identity){super(`QA gate profile exists for readable plan_id='${identity.planId}' but is not exact-bound to swarm_id='${identity.swarm}' and plan_title='${identity.title}'. ${formatLegacyQaBindingRecovery(identity,"retry the blocked read-only or enforcement operation")}`);this.name="QaGateProfileIdentityUnboundError",this.identity=identity}}});function detectHostOS(){switch(process.platform){case"win32":return"windows";case"darwin":return"macos";case"linux":return"linux";default:return"unknown"}}function detectShellFamily(){if(process.env.PSModulePath)return"powershell";if((process.env.ComSpec??"").toLowerCase().includes("cmd.exe"))return"cmd";let shell=process.env.SHELL??"";if(shell.includes("bash"))return"bash";if(shell.includes("zsh"))return"zsh";if(shell.includes("/sh"))return"sh";return"unknown"}function detectExecutionMode(hostOS){if(process.env.WSL_DISTRO_NAME)return"wsl";if(hostOS==="linux"){if(["DOCKER_CONTAINER","KUBERNETES_SERVICE_HOST","CONTAINER"].some((k)=>process.env[k]))return"docker"}return"native"}function deriveOperatingMode(hostOS,_executionMode){if(hostOS==="linux")return"linux";if(hostOS==="macos")return"macos-native";if(hostOS==="windows")return"windows-native";return"unknown"}function buildCommandPolicy(profile){if(profile.isWindowsNative)return{preferredShell:"powershell",avoidPosixExamples:!0,preferNodeApis:!0,preferToolingOverShell:!0,pathExampleStyle:"windows",examples:{listDir:"Get-ChildItem -Force",removeFile:"Remove-Item file.tmp",setEnv:'$env:DEBUG = "1"',printEnv:"$env:PATH",searchText:'Get-ChildItem -Recurse src | Select-String "foo"'}};return{preferredShell:profile.shellFamily==="unknown"?"bash":profile.shellFamily,avoidPosixExamples:!1,preferNodeApis:!0,preferToolingOverShell:!0,pathExampleStyle:"posix",examples:{listDir:"ls -la",removeFile:"rm file.tmp",setEnv:"export DEBUG=1",printEnv:"echo $PATH",searchText:'grep -R "foo" src/'}}}function detectEnvironmentProfile(){let hostOS=detectHostOS(),shellFamily=detectShellFamily(),executionMode=detectExecutionMode(hostOS),operatingMode=deriveOperatingMode(hostOS,executionMode),isWindowsNative=hostOS==="windows"&&executionMode==="native",isWindowsDocker=!1;return{hostOS,shellFamily,executionMode,operatingMode,isWindowsNative,isWindowsDocker:!1,isWSL:executionMode==="wsl",pathStyle:hostOS==="windows"?"windows":"posix",shellCommandPreference:isWindowsNative?"powershell-native":"posix-native",evidence:{processPlatform:process.platform,comspec:process.env.ComSpec,psModulePath:process.env.PSModulePath,termProgram:process.env.TERM_PROGRAM,shell:process.env.SHELL,wslDistroName:process.env.WSL_DISTRO_NAME,containerMarkers:["DOCKER_CONTAINER","KUBERNETES_SERVICE_HOST","CONTAINER"].filter((k)=>!!process.env[k])}}}function deriveCommandPolicy(profile){return buildCommandPolicy(profile)}import{createHash as createHash12}from"node:crypto";function hashString(value){return createHash12("sha256").update(value).digest("hex")}function circuitKey(sessionID,invocationID,actionDigest,circuitKind){return`${sessionID}\x00${invocationID}\x00${actionDigest}\x00${circuitKind}`}function familyKey(sessionID,invocationID,actionDigest){return`${sessionID}\x00${invocationID}\x00${actionDigest}`}function familyPrefix(sessionID,invocationID){return`${sessionID}\x00${invocationID}\x00`}function sessionPrefix(sessionID){return`${sessionID}\x00`}function removeEntry(key){actionCircuits.delete(key)}function pruneGenerationTokenIfUnused(family){let prefix=`${family}\x00`,hasEntries=[...actionCircuits.keys()].some((key)=>key.startsWith(prefix)),isArmed=armedActions.has(family);if(!hasEntries&&!isArmed)actionGenerationTokens.delete(family)}function sweepExpired(now){for(let[key,entry]of actionCircuits)if(entry.expiresAt<=now)removeEntry(key),pruneGenerationTokenIfUnused(familyKey(entry.sessionID,entry.invocationID,entry.actionDigest));for(let[family,armedToken]of armedActions)if(actionGenerationTokens.get(family)!==armedToken)armedActions.delete(family)}function ensureGenerationToken(sessionID,invocationID,actionDigest){let family=familyKey(sessionID,invocationID,actionDigest),current=actionGenerationTokens.get(family);if(current!==void 0)return current;return actionGenerationTokens.set(family,1),1}function bumpGenerationToken(sessionID,invocationID,actionDigest){let family=familyKey(sessionID,invocationID,actionDigest),next=ensureGenerationToken(sessionID,invocationID,actionDigest)+1;return actionGenerationTokens.set(family,next),armedActions.delete(family),next}function touchEntry(key,entry,now){let touched={...entry,expiresAt:now+ACTION_CIRCUIT_TTL_MS};return actionCircuits.delete(key),actionCircuits.set(key,touched),touched}function enforceCapacity(){while(actionCircuits.size>MAX_TRACKED_ACTION_CIRCUITS){let oldest=actionCircuits.keys().next().value;if(oldest===void 0)break;let entry=actionCircuits.get(oldest);if(removeEntry(oldest),entry)pruneGenerationTokenIfUnused(familyKey(entry.sessionID,entry.invocationID,entry.actionDigest))}}function recordResetAudit(record2){if(resetAudit.push(record2),resetAudit.length>MAX_RESET_AUDIT_ROWS)resetAudit.shift()}function armActionCircuitAttempt(sessionID,invocationID,actionDigest){let token=ensureGenerationToken(sessionID,invocationID,actionDigest);return armedActions.set(familyKey(sessionID,invocationID,actionDigest),token),token}function noteActionCircuitFailure(input){let now=input.now??Date.now();sweepExpired(now);let family=familyKey(input.sessionID,input.invocationID,input.actionDigest),expectedToken=input.generationToken??armedActions.get(family)??null,currentToken=ensureGenerationToken(input.sessionID,input.invocationID,input.actionDigest);if(expectedToken===null||expectedToken!==currentToken)return{entry:null,enteredHardStop:!1,ignoredLateEvent:!0};let key=circuitKey(input.sessionID,input.invocationID,input.actionDigest,input.circuitKind),existing=actionCircuits.get(key),count=(existing?.count??0)+1,hardStop=count>=input.hardStopThreshold,entry={sessionID:input.sessionID,invocationID:input.invocationID,actionDigest:input.actionDigest,circuitKind:input.circuitKind,count,hardStop,generationToken:currentToken,lastSignalDigest:input.signal?hashString(input.signal):null,firstSeenAt:existing?.firstSeenAt??now,updatedAt:now,expiresAt:now+ACTION_CIRCUIT_TTL_MS};return actionCircuits.delete(key),actionCircuits.set(key,entry),enforceCapacity(),{entry,enteredHardStop:hardStop&&!existing?.hardStop,ignoredLateEvent:!1}}function clearActionCircuitEntries(sessionID,invocationID,actionDigest){let prefix=`${familyKey(sessionID,invocationID,actionDigest)}\x00`;for(let key of[...actionCircuits.keys()])if(key.startsWith(prefix))removeEntry(key)}function clearActionCircuit(sessionID,invocationID,actionDigest,options){if(clearActionCircuitEntries(sessionID,invocationID,actionDigest),bumpGenerationToken(sessionID,invocationID,actionDigest),options?.reason)recordResetAudit({sessionID,invocationID,actionDigest,reason:options.reason,actor:options.actor??null,at:options.now??Date.now()})}function resetActionCircuitExternally(input){clearActionCircuit(input.sessionID,input.invocationID,input.actionDigest,{reason:"external",actor:input.actor??null,now:input.now})}function clearInvocationActionCircuits(sessionID,invocationID,now){let prefix=familyPrefix(sessionID,invocationID);for(let key of[...actionCircuits.keys()])if(key.startsWith(prefix))removeEntry(key);for(let family of[...actionGenerationTokens.keys()])if(family.startsWith(prefix))actionGenerationTokens.delete(family),armedActions.delete(family),recordResetAudit({sessionID,invocationID,actionDigest:family.slice(prefix.length),reason:"invocation",actor:null,at:now??Date.now()})}function clearSessionActionCircuits(sessionID,now){let prefix=sessionPrefix(sessionID);for(let key of[...actionCircuits.keys()])if(key.startsWith(prefix))removeEntry(key);for(let family of[...actionGenerationTokens.keys()])if(family.startsWith(prefix)){let familyTail=family.slice(prefix.length),separatorIndex=familyTail.indexOf("\x00"),invocationID=separatorIndex>0?Number(familyTail.slice(0,separatorIndex)):0,actionDigest=separatorIndex>0?familyTail.slice(separatorIndex+1):familyTail;actionGenerationTokens.delete(family),armedActions.delete(family),recordResetAudit({sessionID,invocationID,actionDigest,reason:"session",actor:null,at:now??Date.now()})}}function getBlockingActionCircuit(sessionID,invocationID,actionDigest){let now=Date.now();sweepExpired(now);let prefix=`${familyKey(sessionID,invocationID,actionDigest)}\x00`;for(let[key,entry]of actionCircuits)if(key.startsWith(prefix)&&entry.hardStop)return touchEntry(key,entry,now);return null}function listBlockingActionCircuitsForInvocation(sessionID,invocationID){let now=Date.now();sweepExpired(now);let prefix=familyPrefix(sessionID,invocationID),result=[];for(let[key,entry]of[...actionCircuits])if(key.startsWith(prefix)&&entry.hardStop)result.push(touchEntry(key,entry,now));return result}function peekActionCircuitCount(sessionID,invocationID,actionDigest,circuitKind){return actionCircuits.get(circuitKey(sessionID,invocationID,actionDigest,circuitKind))?.count??0}function expireActionCircuit(sessionID,invocationID,actionDigest,circuitKind){let entry=actionCircuits.get(circuitKey(sessionID,invocationID,actionDigest,circuitKind));if(entry)entry.expiresAt=Date.now()-1}function clearAllActionCircuits(){actionCircuits.clear(),actionGenerationTokens.clear(),armedActions.clear(),resetAudit.length=0}var MAX_TRACKED_ACTION_CIRCUITS=500,ACTION_CIRCUIT_TTL_MS=1800000,MAX_RESET_AUDIT_ROWS=128,actionCircuits,actionGenerationTokens,armedActions,resetAudit,_test_exports;var init_action_circuit=__esm(()=>{actionCircuits=new Map,actionGenerationTokens=new Map,armedActions=new Map,resetAudit=[];_test_exports={ACTION_CIRCUIT_TTL_MS,MAX_TRACKED_ACTION_CIRCUITS,size:()=>actionCircuits.size,getGenerationToken:(sessionID,invocationID,actionDigest)=>ensureGenerationToken(sessionID,invocationID,actionDigest),getResetAudit:()=>resetAudit.map((entry)=>({...entry}))}});import{randomBytes as randomBytes2}from"node:crypto";import*as fs12 from"node:fs";import*as path17 from"node:path";function matchTempGrammar(basename3){return SWARM_TEMP_GRAMMARS.find((g)=>g.match.test(basename3))}function parseTargetBasename(basename3){for(let g of SWARM_TEMP_GRAMMARS){if(!g.parsesTarget)continue;let m=g.match.exec(basename3);if(m?.[1])return m[1]}return null}function assertWellFormedTargetPath(targetPath){if(!path17.isAbsolute(targetPath))throw Error(`atomic-write target must be absolute: ${targetPath}`);if(/[\0-\x1f\x7f]/.test(targetPath))throw Error("atomic-write target contains control characters");if(/[*?]/.test(targetPath)||/(^|[/\\])\{[^}]*\}([/\\]|$)/.test(targetPath))throw Error(`atomic-write target contains glob metacharacters: ${targetPath}`);if(/(^|[/\\])~([/\\]|$)/.test(targetPath))throw Error("atomic-write target contains unresolved home-dir marker (~)");if(/\$\{?[A-Za-z_][A-Za-z0-9_]*\}?/.test(targetPath)||/%[^/\\%]+%/.test(targetPath))throw Error("atomic-write target contains unresolved environment-variable form")}function lstatNotSymlink(p,what){if(fs12.lstatSync(p).isSymbolicLink())throw Error(`${what} is a symlink/reparse point: ${p}`)}function assertSwarmContainedTarget(targetPath){assertWellFormedTargetPath(targetPath);let resolved=path17.normalize(path17.resolve(targetPath)),segments=resolved.split(path17.sep),swarmIdx=-1;for(let i=segments.length-2;i>=1;i--)if(segments[i]===".swarm"){swarmIdx=i;break}if(swarmIdx===-1)throw Error(`atomic-write target is not under a project .swarm root: ${targetPath}`);let swarmRoot=segments.slice(0,swarmIdx+1).join(path17.sep);try{let st=fs12.lstatSync(swarmRoot);if(!st.isDirectory()||st.isSymbolicLink())throw Error(`.swarm root is not a real directory (symlink/reparse or non-dir): ${swarmRoot}`)}catch(err){if(err?.code!=="ENOENT")throw err}let rel=path17.relative(swarmRoot,resolved);if(!rel||rel.startsWith("..")||path17.isAbsolute(rel))throw Error(`atomic-write target escapes .swarm root: ${targetPath}`);let probe=swarmRoot;for(let seg of rel.split(path17.sep)){if(probe=path17.join(probe,seg),!fs12.existsSync(probe))break;lstatNotSymlink(probe,"path segment under .swarm")}return{projectRoot:path17.dirname(swarmRoot),swarmRoot}}function toBuffer(content){if(typeof content==="string")return Buffer.from(content,"utf-8");return content}function syncSleep(ms){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,ms)}catch{let start=Date.now();while(Date.now()-start<ms);}}function renameWithRetry(tempPath,targetPath){let lastError;for(let attempt=0;attempt<=RENAME_RETRY_DELAYS_MS.length;attempt++)try{_internals15.renameSync(tempPath,targetPath);return}catch(err){lastError=err;let code=err?.code;if(!code||!RETRYABLE_RENAME_CODES.has(code))throw err;if(attempt<RENAME_RETRY_DELAYS_MS.length)syncSleep(RENAME_RETRY_DELAYS_MS[attempt])}throw lastError}function writeAtomicSync(targetPath,content,options){if(options?.contained!==!1)assertSwarmContainedTarget(targetPath);else assertWellFormedTargetPath(targetPath);let resolvedTarget=path17.resolve(targetPath),buffer=toBuffer(content),maxBytes=options?.maxBytes??MAX_ATOMIC_WRITE_BYTES;if(buffer.byteLength>maxBytes)throw Error(`atomic write exceeds ${maxBytes} byte bound: ${buffer.byteLength}`);let tempPath=`${resolvedTarget}.${_internals15.randomSuffix()}.tmp`;fs12.mkdirSync(path17.dirname(tempPath),{recursive:!0});try{let fd=fs12.openSync(tempPath,"wx");try{let written=0;while(written<buffer.byteLength)written+=_internals15.writeSync(fd,buffer,written,buffer.byteLength-written);if(options?.skipFsync!==!0)try{_internals15.fsyncSync(fd)}catch{}}finally{fs12.closeSync(fd)}renameWithRetry(tempPath,resolvedTarget)}finally{try{_internals15.unlinkSync(tempPath)}catch{}}try{let dirFd=fs12.openSync(path17.dirname(resolvedTarget),"r");try{fs12.fsyncSync(dirFd)}finally{fs12.closeSync(dirFd)}}catch{}invalidateCachedArtifact(resolvedTarget)}async function atomicWriteSwarmFile(targetPath,content,options){await new Promise((resolve12)=>setImmediate(resolve12)),writeAtomicSync(targetPath,content,options)}function atomicWriteSwarmFileSync(targetPath,content,options){writeAtomicSync(targetPath,content,options)}async function atomicWriteFileAnyRoot(targetPath,content,options){await new Promise((resolve12)=>setImmediate(resolve12)),writeAtomicSync(targetPath,content,{...options,contained:!1})}var UUID_RE="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",SWARM_TEMP_GRAMMARS,WRITER_CLASSIFICATION,MAX_ATOMIC_WRITE_BYTES=268435456,RENAME_RETRY_DELAYS_MS,RETRYABLE_RENAME_CODES,_internals15;var init_atomic_write=__esm(()=>{init_swarm_artifact_cache();SWARM_TEMP_GRAMMARS=[{id:"canonical-v1",era:"canonical",match:/^(.+)\.[0-9a-f]{32}\.tmp$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/utils/atomic-write.ts:atomicWriteSwarmFile","src/utils/atomic-write.ts:atomicWriteFileAnyRoot"]},{id:"target-suffix-tmp-uuid",era:"current",match:new RegExp(`^(.+)\\.tmp\\.${UUID_RE}$`),token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/commands/handoff.ts:48 (pre-#2035)","src/commands/handoff.ts:79 (pre-#2035)","src/memory/local-jsonl-provider.ts:1171","src/config/bundled-skills.ts:241"]},{id:"target-suffix-tmp-pid-uuid",era:"current",match:new RegExp(`^(.+)\\.tmp\\.\\d+\\.${UUID_RE}$`),token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/hooks/pr-workflow-gate.ts:13602"],note:"pre/post-rename file-identity verification (assertOpened/ClosedSwarmFileIdentity, pr-workflow-gate.ts:13544-13601) is writer-specific and load-bearing"},{id:"target-suffix-tmp-num-num-json",era:"current",match:/^(.+)\.tmp\.\d+\.\d+\.json$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/hooks/issue-trace-state.ts:315"],note:"the .json terminator keeps this shape distinct from the bare two-token family — declared before it so first-match wins"},{id:"target-suffix-tmp-num-alnum",era:"current",match:/^(.+)\.tmp\.\d+\.[0-9a-z]+$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/evidence/task-file.ts:67 (pre-#2035)","src/scope/scope-persistence.ts:2304 (pre-#2035)","src/scope/scope-persistence.ts:2318 (pre-#2035)","src/plan/manager.ts:628","src/plan/manager.ts:1793","src/plan/manager.ts:1839","src/review/evidence.ts:160","src/turbo/lean/evidence.ts:182","src/summaries/manager.ts:122","src/evidence/manager.ts:288","src/evidence/manager.ts:456","src/tools/sast-baseline.ts:106","src/tools/repo-graph/storage.ts:397","src/memory/reflection-service.ts:547 (pre-#2035)","src/hooks/review-receipt.ts:608","src/hooks/review-receipt.ts:674","src/hooks/review-receipt.ts:812","src/knowledge/identity.ts:209","src/evidence/phase-participation.ts:303 (pre-#2035)","src/turbo/lean/integration.ts:426","src/turbo/lean/reviewer.ts:403","src/plan/ledger.ts:713","src/services/synonym-map.ts:389","src/services/skill-optimizer/store.ts:340","src/services/skill-optimizer/store.ts:503","src/turbo/epic/state.ts:177","src/turbo/epic/calibration.ts:197","src/commands/archive-sqlite.ts:318","src/memory/jsonl-migration.ts:157"],note:"fsync-discipline / lock-scoped fd writers whose temp naming is pinned by their own durability test suites (plan-durability invariant 5, #2034 crash matrix); grammars registered here so their residue stays discoverable"},{id:"target-suffix-tmp-token",era:"current",match:/^(.+)\.tmp\.[0-9a-z-]{6,}$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/turbo/lean/state.ts:246","src/turbo/lean/recovery.ts:175","src/hooks/delegation-gate/worktree-merge-status.ts:110"]},{id:"target-suffix-tmp-dash",era:"current",match:/^(.+)\.tmp-\d+-[0-9a-z-]+$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/services/skill-evaluator.ts:492 (pre-#2035)","src/services/skill-improver.ts:154 (pre-#2035)","src/services/skill-consolidation.ts:72 (pre-#2035)","src/services/skill-generator.ts:601 (pre-#2035)","src/tools/spec-write.ts:98","src/sdd/effective-spec.ts:1149","src/background/lane-output-store.ts:353","src/background/pending-delegations.ts:922","src/background/delegation-health.ts:300","src/hooks/delegation-gate/worktree-provisioning-owner.ts:100","src/tools/submit-phase-council-verdicts.ts:458","src/summaries/store.ts:46 (pre-#2035)"],note:"background lane/delegation stores keep bounded-retry rename semantics wired into their callers (#2034/#2276 delivery contracts); migration candidates for a follow-up but grammars registered"},{id:"target-suffix-tmp-dash-num",era:"current",match:/^(.+)\.tmp-\d+$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/services/skill-improver-quota.ts:114"]},{id:"target-dot-pid-uuid-tmp",era:"current",match:new RegExp(`^(.+)\\.\\d+\\.${UUID_RE}\\.tmp$`),token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/hooks/knowledge-receipt-ledger-storage.ts:591"],note:"pre/post-rename file-identity verification (existingFileIdentity checks, knowledge-receipt-ledger-storage.ts:544-591) is writer-specific and load-bearing"},{id:"dot-numeric-instance-tmp",era:"current",match:/^\..+(?:\.\d+){2,4}\.[0-9a-z]+\.tmp$/,token:"instance",quarantineEligible:!0,parsesTarget:!1,producers:["src/utils/bun-compat.ts:138","src/tools/repo-graph/freshness.ts:171"],note:"bunWrite Node-fallback internal temp and the repo-graph fingerprint temp (2-4 numeric token groups); leading-dot temps are standalone, target not parsed"},{id:"dot-uuid-instance-tmp",era:"current",match:new RegExp(`^\\..+\\.${UUID_RE}\\.tmp$`),token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/tools/write-pr-review-artifact.ts:135","src/tools/write-pr-review-trigger-eval.ts:574"],note:"bundled-skills writes outside .swarm (project skill roots) and keeps its own contained-directory logic (invariant 4 bundled-skill ownership)"},{id:"tmp-prefix-named",era:"legacy",match:/^\.tmp-.+-\d+-\d+$/,token:"instance",quarantineEligible:!0,parsesTarget:!1,producers:["src/commands/issue.ts:167 (pre-#2035)"],note:"prefix form embeds the filename; target not reliably parseable (dashes), so eligibility relies on the age/tracked/symlink/lock gates"},{id:"target-rebuild-close",era:"current",match:/^(.+)\.(?:rebuild|close)\.\d+\.[0-9a-z]+$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/plan/manager.ts:1979","src/plan/manager.ts:2168"],note:"plan-durability (invariant 5) fd-write paths; grammars registered, writers unchanged in this PR"},{id:"target-migration-pid",era:"current",match:/^(.+)\.migration-\d+$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/scope/scope-persistence.ts:633 (pre-#2035)"]},{id:"dot-tmp-prefix-legacy",era:"legacy",match:/^\.tmp\..+$/,token:"constant",quarantineEligible:!0,parsesTarget:!1,producers:["pre-7.x writers (historical); matched by the pre-#2035 close sweep"],note:"legacy prefix grammar: issue #2035 req 7 preserves its handling — stale instances are quarantined (formerly unlinked) under the same eligibility gates"},{id:"dot-constant-tmp",era:"current",match:/^\..+\.tmp$/,token:"constant",quarantineEligible:!1,parsesTarget:!1,producers:["src/tools/write-drift-evidence.ts:275","src/tools/write-mutation-evidence.ts:169","src/tools/write-hallucination-evidence.ts:121","src/tools/record-implementation-review.ts:87","src/tools/record-recurrence-sweep.ts:125","src/tools/record-issue-reproduction.ts:85","src/tools/record-issue-publication.ts:74","src/tools/write-final-council-evidence.ts:403"],note:"constant-name temps: no per-invocation token — reported when stale, never auto-quarantined (may be an in-flight writer of any process)"},{id:"target-constant-tmp",era:"current",match:/^(.+)\.tmp$/,token:"constant",quarantineEligible:!1,parsesTarget:!1,producers:["src/tools/checkpoint.ts:194","src/full-auto/state.ts:460","src/context-map/persistence.ts:119","src/context-map/capsule-persistence.ts:107","src/test-impact/history-store.ts:225","src/test-impact/history-store.ts:353","src/hooks/promotion-evidence-store.ts:102","src/hooks/skill-usage-log.ts:554","src/hooks/skill-usage-log.ts:608","src/parallel/file-locks.ts:113","src/plan/ledger.ts:1302","src/plan/ledger.ts:1303"],note:"constant-name temps: reported when stale, never auto-quarantined. file-locks meta sidecars live under the scanner-skipped .swarm/locks/ subtree; the ledger reconcile temp embeds instance tokens but its .tmp-suffix shape maps here (conservatively report-only)"}];WRITER_CLASSIFICATION=Object.freeze({"src/commands/close.ts":"migrated","src/commands/handoff.ts":"migrated","src/commands/simulate.ts":"migrated","src/commands/coupling.ts":"migrated","src/commands/issue.ts":"migrated","src/evidence/task-file.ts":"migrated","src/evidence/phase-participation.ts":"migrated","src/memory/reflection-service.ts":"migrated","src/scope/scope-persistence.ts":"migrated","src/services/skill-consolidation.ts":"migrated","src/services/skill-evaluator.ts":"migrated","src/services/skill-generator.ts":"migrated","src/services/skill-improver.ts":"migrated","src/summaries/store.ts":"migrated","src/background/delegation-health.ts":"registered-bespoke","src/background/lane-output-store.ts":"registered-bespoke","src/background/pending-delegations.ts":"registered-bespoke","src/commands/archive-sqlite.ts":"registered-bespoke","src/context-map/capsule-persistence.ts":"registered-bespoke","src/context-map/persistence.ts":"registered-bespoke","src/context-map/telemetry.ts":"registered-bespoke","src/evidence/documents-retention.ts":"registered-bespoke","src/evidence/manager.ts":"registered-bespoke","src/full-auto/state.ts":"registered-bespoke","src/hooks/delegation-gate/worktree-merge-status.ts":"registered-bespoke","src/hooks/delegation-gate/worktree-provisioning-owner.ts":"registered-bespoke","src/hooks/issue-trace-state.ts":"registered-bespoke","src/hooks/knowledge-receipt-ledger-storage.ts":"registered-bespoke","src/hooks/pr-workflow-gate.ts":"registered-bespoke","src/hooks/promotion-evidence-store.ts":"registered-bespoke","src/hooks/review-receipt.ts":"registered-bespoke","src/hooks/skill-usage-log.ts":"registered-bespoke","src/knowledge/identity.ts":"registered-bespoke","src/memory/jsonl-migration.ts":"external","src/memory/local-jsonl-provider.ts":"registered-bespoke","src/plan/ledger.ts":"registered-bespoke","src/plan/manager.ts":"registered-bespoke","src/review/evidence.ts":"registered-bespoke","src/sdd/effective-spec.ts":"registered-bespoke","src/services/skill-improver-quota.ts":"registered-bespoke","src/services/skill-optimizer/activation.ts":"external","src/services/skill-optimizer/store.ts":"registered-bespoke","src/services/skill-reviser.ts":"external","src/services/synonym-map.ts":"registered-bespoke","src/session/snapshot-writer.ts":"registered-bespoke","src/summaries/manager.ts":"registered-bespoke","src/test-impact/history-store.ts":"registered-bespoke","src/turbo/epic/calibration.ts":"registered-bespoke","src/turbo/epic/state.ts":"registered-bespoke","src/turbo/lean/evidence.ts":"registered-bespoke","src/turbo/lean/integration.ts":"registered-bespoke","src/turbo/lean/recovery.ts":"registered-bespoke","src/turbo/lean/reviewer.ts":"registered-bespoke","src/turbo/lean/state.ts":"registered-bespoke","src/tools/apply-patch.ts":"external","src/tools/checkpoint.ts":"registered-bespoke","src/tools/record-implementation-review.ts":"registered-bespoke","src/tools/record-issue-publication.ts":"registered-bespoke","src/tools/record-issue-reproduction.ts":"registered-bespoke","src/tools/record-recurrence-sweep.ts":"registered-bespoke","src/tools/repo-graph/freshness.ts":"registered-bespoke","src/tools/repo-graph/storage.ts":"registered-bespoke","src/tools/sast-baseline.ts":"registered-bespoke","src/tools/spec-write.ts":"registered-bespoke","src/tools/submit-phase-council-verdicts.ts":"registered-bespoke","src/tools/write-drift-evidence.ts":"registered-bespoke","src/tools/write-final-council-evidence.ts":"registered-bespoke","src/tools/write-hallucination-evidence.ts":"registered-bespoke","src/tools/write-mutation-evidence.ts":"registered-bespoke","src/tools/write-pr-review-artifact.ts":"registered-bespoke","src/tools/write-pr-review-trigger-eval.ts":"registered-bespoke","src/config/bundled-skills.ts":"external","src/services/config-doctor.ts":"external","src/parallel/file-locks.ts":"registered-bespoke","src/utils/bun-compat.ts":"registered-bespoke","src/background/plan-sync-worker.ts":"reader-only","src/config/lane-permissions.ts":"reader-only","src/environment/profile.ts":"reader-only","src/worktree/core.ts":"reader-only"});RENAME_RETRY_DELAYS_MS=[10,25,50,100,200],RETRYABLE_RENAME_CODES=new Set(["EPERM","EBUSY","EACCES","EEXIST"]),_internals15={randomSuffix:()=>randomBytes2(16).toString("hex"),writeSync:(fd,buffer,offset,length)=>fs12.writeSync(fd,buffer,offset,length),renameSync:(from,to)=>fs12.renameSync(from,to),unlinkSync:(p)=>fs12.unlinkSync(p),fsyncSync:(fd)=>fs12.fsyncSync(fd)}});import*as path18 from"node:path";function taskEvidenceRelPath(taskId){return path18.join("evidence",`${taskId}.json`)}function taskEvidencePath(directory,taskId){return path18.join(directory,".swarm",taskEvidenceRelPath(taskId))}async function atomicWriteFile(targetPath,content){await atomicWriteFileAnyRoot(targetPath,content)}function withTaskEvidenceLock(directory,taskId,agent,fn2){return withEvidenceLock(directory,taskEvidenceRelPath(taskId),agent,taskId,fn2)}var init_task_file=__esm(()=>{init_atomic_write();init_lock()});import{createHash as createHash13}from"node:crypto";import*as fs13 from"node:fs";import*as path19 from"node:path";function samePath(left,right){let normalize3=(value)=>process.platform==="win32"?path19.resolve(value).toLowerCase():path19.resolve(value);return normalize3(left)===normalize3(right)}function assertSafeRequirementsParent(directory,create){assertProjectRoot(directory,void 0,"task gate requirements");let rootStat=fs13.lstatSync(directory);if(rootStat.isSymbolicLink()||!rootStat.isDirectory())throw Error("TASK_GATE_REQUIREMENTS_UNREADABLE: project root is not a regular directory");let canonicalRoot=fs13.realpathSync(directory),segments=[".swarm","evidence","task-gate-requirements"],current=canonicalRoot;for(let segment of segments){current=path19.join(current,segment);let info;try{info=fs13.lstatSync(current)}catch(error49){if(error49.code==="ENOENT"){if(!create)return current;try{fs13.mkdirSync(current)}catch(mkdirError){if(mkdirError.code!=="EEXIST")throw mkdirError}info=fs13.lstatSync(current)}else throw error49}if(info.isSymbolicLink()||!info.isDirectory())throw Error("TASK_GATE_REQUIREMENTS_UNREADABLE: receipt parent is redirected or not a directory");let canonicalCurrent=fs13.realpathSync(current);if(!samePath(canonicalCurrent,current))throw Error("TASK_GATE_REQUIREMENTS_UNREADABLE: receipt parent escaped the project root")}return current}function safeTaskGateRequirementsReceiptPath(directory,taskId,createParent){let parent=assertSafeRequirementsParent(directory,createParent);return path19.join(parent,`${taskId}.jsonl`)}function sha256(value){return createHash13("sha256").update(value).digest("hex")}function canonicalReceiptPayload(receipt){return JSON.stringify({...receipt,requiredGates:[...receipt.requiredGates]})}function computeChainHash(receipt){return sha256(canonicalReceiptPayload(receipt))}function readBoundedTextFile(filePath){let pathStat;try{pathStat=fs13.lstatSync(filePath)}catch(error49){if(error49.code==="ENOENT")return null;throw error49}if(pathStat.isSymbolicLink()||!pathStat.isFile())throw Error("TASK_GATE_REQUIREMENTS_UNREADABLE: receipt path is not a regular file");if(pathStat.size>MAX_TASK_GATE_REQUIREMENTS_BYTES)throw Error(`TASK_GATE_REQUIREMENTS_OVERSIZED: ${pathStat.size} bytes exceeds ${MAX_TASK_GATE_REQUIREMENTS_BYTES}`);let descriptor=fs13.openSync(filePath,fs13.constants.O_RDONLY|(fs13.constants.O_NOFOLLOW??0));try{let openedStat=fs13.fstatSync(descriptor);if(!openedStat.isFile()||openedStat.dev!==pathStat.dev||openedStat.ino!==pathStat.ino)throw Error("TASK_GATE_REQUIREMENTS_UNREADABLE: receipt changed while being opened");if(openedStat.size>MAX_TASK_GATE_REQUIREMENTS_BYTES)throw Error(`TASK_GATE_REQUIREMENTS_OVERSIZED: ${openedStat.size} bytes exceeds ${MAX_TASK_GATE_REQUIREMENTS_BYTES}`);return fs13.readFileSync(descriptor,"utf-8")}finally{fs13.closeSync(descriptor)}}async function readTaskGateRequirementsReceipts(directory,taskId){let filePath=safeTaskGateRequirementsReceiptPath(directory,taskId,!1),text=readBoundedTextFile(filePath);if(text===null)return[];let receipts=[];for(let line of text.split(`
|
|
271
271
|
`)){if(!line.trim())continue;let parsed=TaskGateRequirementsReceiptSchema.parse(JSON.parse(line));if(parsed.taskId!==taskId)throw Error(`TASK_GATE_REQUIREMENTS_IDENTITY_MISMATCH: expected ${taskId}, found ${parsed.taskId}`);let{chainHash,...withoutChainHash}=parsed;if(computeChainHash(withoutChainHash)!==chainHash)throw Error(`TASK_GATE_REQUIREMENTS_CHAIN_MISMATCH: receipt for ${taskId} failed hash validation`);let previousChainHash=receipts.at(-1)?.chainHash??null;if(parsed.previousChainHash!==previousChainHash)throw Error(`TASK_GATE_REQUIREMENTS_CHAIN_MISMATCH: receipt for ${taskId} failed linkage validation`);receipts.push(parsed)}return receipts}function deriveReceiptRole(event){switch(event.type){case"accepted_mutation":case"dispatch_attempted":case"dispatch_no_mutation":if(typeof event.agentType==="string"&&event.agentType.trim().length>0)return{normalizedRole:event.agentType.trim(),testEngineerExempt:event.agentType==="coder"?event.context?.testEngineerExempt===!0:null};return null;case"stage_b_completed":case"gate_recorded":return{normalizedRole:event.gate,testEngineerExempt:null};default:return null}}function shouldAppendReceipt(current,next,role){if(next.required_gates.length===0)return!1;let currentGeneration=current?.workflow?.generation??-1,nextGeneration=next.workflow?.generation??-1;if(current===null)return!0;if(JSON.stringify(current.required_gates)!==JSON.stringify(next.required_gates))return!0;if((current.test_engineer_exempt??null)!==role.testEngineerExempt)return!0;return currentGeneration!==nextGeneration}async function appendTaskGateRequirementsReceiptIfNeeded(directory,taskId,current,next,event){let role=deriveReceiptRole(event);if(!role||!shouldAppendReceipt(current,next,role))return;let filePath=safeTaskGateRequirementsReceiptPath(directory,taskId,!0),receipts=await readTaskGateRequirementsReceipts(directory,taskId),latest=receipts.at(-1),baseReceipt={schemaVersion:1,taskId,generation:next.workflow?.generation??0,normalizedRole:role.normalizedRole,testEngineerExempt:role.testEngineerExempt,requiredGates:[...next.required_gates],sourceEvent:event.type,sourceTransitionId:event.transitionId??null,recordedAt:new Date().toISOString(),previousChainHash:latest?.chainHash??null},receipt={...baseReceipt,chainHash:computeChainHash(baseReceipt)};if(latest&&latest.generation===receipt.generation&&latest.normalizedRole===receipt.normalizedRole&&latest.testEngineerExempt===receipt.testEngineerExempt&&JSON.stringify(latest.requiredGates)===JSON.stringify(receipt.requiredGates)&&latest.sourceTransitionId===receipt.sourceTransitionId)return;let lines=[...receipts,receipt].map((entry)=>JSON.stringify(entry));assertSafeRequirementsParent(directory,!1),await atomicWriteFile(filePath,`${lines.join(`
|
|
272
272
|
`)}
|
|
273
273
|
`),assertSafeRequirementsParent(directory,!1)}var MAX_TASK_GATE_REQUIREMENTS_BYTES=262144,TaskGateRequirementsReceiptSchema;var init_task_gate_requirements=__esm(()=>{init_zod();init_utils2();init_project_boundary();init_task_file();TaskGateRequirementsReceiptSchema=exports_external.object({schemaVersion:exports_external.literal(1),taskId:exports_external.string().min(1).max(120),generation:exports_external.number().int().min(0),normalizedRole:exports_external.string().min(1).max(120),testEngineerExempt:exports_external.boolean().nullable(),requiredGates:exports_external.array(exports_external.string()).min(1).max(16),sourceEvent:exports_external.string().min(1).max(120),sourceTransitionId:exports_external.string().min(1).max(200).nullable(),recordedAt:exports_external.string().min(1).max(128),previousChainHash:exports_external.string().regex(/^[a-f0-9]{64}$/).nullable(),chainHash:exports_external.string().regex(/^[a-f0-9]{64}$/)}).strict()});function checkUnsafeChars(taskId){if(!taskId||taskId.length===0)return"Invalid task ID: empty string";if(/\0/.test(taskId))return"Invalid task ID: contains null bytes";for(let i=0;i<taskId.length;i++)if(taskId.charCodeAt(i)<32)return"Invalid task ID: contains control characters";if(taskId.includes("..")||taskId.includes("/")||taskId.includes("\\"))return"Invalid task ID: path traversal detected";return}function isStrictTaskId(taskId){if(!taskId)return!1;if(checkUnsafeChars(taskId))return!1;return STRICT_TASK_ID_PATTERN.test(taskId)}function assertStrictTaskId(taskId){if(!isStrictTaskId(taskId))throw Error(`Invalid taskId: "${taskId}". Must match N.M or N.M.P (e.g. "1.1", "1.2.3").`)}function sanitizeTaskId(taskId){let unsafeMsg=checkUnsafeChars(taskId);if(unsafeMsg)throw Error(unsafeMsg);if(STRICT_TASK_ID_PATTERN.test(taskId)||RETRO_TASK_ID_REGEX.test(taskId)||INTERNAL_TOOL_ID_REGEX.test(taskId)||GENERAL_TASK_ID_REGEX.test(taskId))return taskId;throw Error(`Invalid task ID: must be alphanumeric (ASCII) with optional hyphens, underscores, or dots, got "${taskId}"`)}function validateTaskIdFormat(taskId){if(!STRICT_TASK_ID_PATTERN.test(taskId))return`Invalid taskId "${taskId}". Must match pattern N.M or N.M.P (e.g., "1.1", "1.2.3")`;return}var STRICT_TASK_ID_PATTERN,RETRO_TASK_ID_REGEX,INTERNAL_TOOL_ID_REGEX,GENERAL_TASK_ID_REGEX;var init_task_id=__esm(()=>{STRICT_TASK_ID_PATTERN=/^\d+\.\d+(\.\d+)*$/,RETRO_TASK_ID_REGEX=/^retro-\d+$/,INTERNAL_TOOL_ID_REGEX=/^(?:sast_scan|quality_budget|syntax_check|placeholder_scan|sbom_generate|build|secretscan)$/,GENERAL_TASK_ID_REGEX=/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/});import*as path20 from"node:path";function isControlCharacter(character){let codePoint=character.codePointAt(0)??0;return codePoint<=31||codePoint>=127&&codePoint<=159}function isBidiControlCharacter(character){return BIDI_CONTROL_CHARACTERS.test(character)}function getPathFlavor(pathLib=path20){return pathLib.sep==="\\"?"win32":"posix"}function pathImplementation(flavor){return flavor==="win32"?path20.win32:path20.posix}function normalizePathIdentity(value,flavor=getPathFlavor()){let normalized=pathImplementation(flavor).normalize(flavor==="win32"?value.replace(/\//g,"\\"):value);return flavor==="win32"?normalized.toLowerCase():normalized}function pathIdentitiesEqual(a,b,flavor=getPathFlavor()){return normalizePathIdentity(a,flavor)===normalizePathIdentity(b,flavor)}function isPathIdentityWithin(target,container,flavor=getPathFlavor()){let pathImpl=pathImplementation(flavor),targetIdentity=normalizePathIdentity(target,flavor),containerIdentity=normalizePathIdentity(container,flavor);if(targetIdentity===containerIdentity)return!0;let relative5=pathImpl.relative(containerIdentity,targetIdentity);return relative5.length>0&&relative5!==".."&&!relative5.startsWith(`..${pathImpl.sep}`)&&!pathImpl.isAbsolute(relative5)}function isPathWithinDeclaredScope(filePath,scopeEntries,cwd=process.cwd(),flavor=getPathFlavor()){let pathImpl=pathImplementation(flavor),resolvedFile=pathImpl.resolve(cwd,filePath);return scopeEntries.some((scope)=>isPathIdentityWithin(resolvedFile,pathImpl.resolve(cwd,scope),flavor))}function isOnDifferentPathRoot(target,cwd,flavor=getPathFlavor()){let pathImpl=pathImplementation(flavor),targetRoot=pathImpl.parse(pathImpl.normalize(target)).root,cwdRoot=pathImpl.parse(pathImpl.normalize(cwd)).root;return!pathIdentitiesEqual(targetRoot,cwdRoot,flavor)}function unsafePathTextReason(value){if([...value].some(isControlCharacter))return"control characters are not allowed in paths";if([...value].some(isBidiControlCharacter))return"bidirectional control characters are not allowed in paths";return null}function sanitizeDiagnosticText(value,maxLength=256){let rendered=String(value).split("").map((character)=>isControlCharacter(character)||isBidiControlCharacter(character)?"?":character).join("").replace(/\s+/gu," ").trim();if(rendered.length<=maxLength)return rendered;return`${rendered.slice(0,Math.max(0,maxLength-1))}…`}var BIDI_CONTROL_CHARACTERS;var init_path_identity=__esm(()=>{BIDI_CONTROL_CHARACTERS=/[\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/u});import*as fs14 from"node:fs";import*as path21 from"node:path";function recoveryDir(directory){return path21.join(directory,".swarm",RECOVERY_DIR_NAME)}function recordPath(directory,sessionId,laneId){let safeSession=sessionId.replace(/[^a-zA-Z0-9._-]/g,"_"),safeLane=laneId.replace(/[^a-zA-Z0-9._-]/g,"_");return path21.join(recoveryDir(directory),`${safeSession}-${safeLane}.json`)}function isRecoveryRecord(value){if(typeof value!=="object"||value===null||Array.isArray(value))return!1;let record2=value,validStatus=record2.status==="failed"||record2.status==="partial"||record2.status==="conflict";return typeof record2.laneId==="string"&&typeof record2.sessionId==="string"&&typeof record2.worktreePath==="string"&&validStatus&&typeof record2.reason==="string"&&typeof record2.recordedAt==="number"&&Number.isFinite(record2.recordedAt)&&typeof record2.replayHint==="string"&&(record2.branchName===void 0||typeof record2.branchName==="string")&&(record2.conflictFiles===void 0||Array.isArray(record2.conflictFiles)&&record2.conflictFiles.every((file2)=>typeof file2==="string"))}function readRecoveryRecords(directory){let dir=recoveryDir(directory),entries;try{entries=fs14.readdirSync(dir,{withFileTypes:!0})}catch{return{records:[],errored:fs14.existsSync(dir)}}let records=[],errored=!1;for(let entry of entries){if(!entry.isFile()||!entry.name.endsWith(".json"))continue;let full=path21.join(dir,entry.name);try{let parsed=JSON.parse(fs14.readFileSync(full,"utf-8"));if(isRecoveryRecord(parsed))records.push(parsed);else errored=!0}catch{errored=!0}}return{records,errored}}function writeRecoveryRecord(directory,record2){try{let dir=recoveryDir(directory);fs14.mkdirSync(dir,{recursive:!0});let filePath=recordPath(directory,record2.sessionId,record2.laneId),payload={...record2,recordedAt:record2.recordedAt??Date.now()},tmpPath=`${filePath}.tmp.${Date.now()}`;fs14.writeFileSync(tmpPath,JSON.stringify(payload,null,2),"utf-8"),fs14.renameSync(tmpPath,filePath)}catch{}}function listRecoveryRecords(directory){return readRecoveryRecords(directory).records}function hasRecoveryRecordForBranch(directory,branchName){return listRecoveryRecords(directory).some((r)=>r.branchName===branchName)}function clearRecoveryRecord(directory,laneId,sessionId){try{let filePath=recordPath(directory,sessionId,laneId);if(fs14.existsSync(filePath))fs14.unlinkSync(filePath)}catch{}}function recoveryReadErrored(directory){return readRecoveryRecords(directory).errored}var RECOVERY_DIR_NAME="recovery";var init_recovery=()=>{};function isGitBinaryMissing(err,cwd){return classifySpawnFailure(err,cwd)==="binary-missing"}function isSpawnCwdMissing(err,cwd){return classifySpawnFailure(err,cwd)==="cwd-missing"}function isSpawnCwdUnreadable(err,cwd){return classifySpawnFailure(err,cwd)==="cwd-unreadable"}var GitUnavailableError,GitBinaryMissingError,GitSpawnCwdError;var init_git_binary_missing_error=__esm(()=>{init_bun_compat();init_bun_compat();GitUnavailableError=class GitUnavailableError extends Error{};GitBinaryMissingError=class GitBinaryMissingError extends GitUnavailableError{name="GitBinaryMissingError";constructor(message="git binary is not available",options){super(message,options)}};GitSpawnCwdError=class GitSpawnCwdError extends GitUnavailableError{name="GitSpawnCwdError";cwd;fault;constructor(cwd,fault,options){super(fault==="missing"?`git could not start: working directory no longer exists: ${cwd}`:`git could not start: working directory could not be inspected (permission denied): ${cwd}`,options);this.cwd=cwd,this.fault=fault}}});function isSwarmSessionId(sessionId){return typeof sessionId==="string"&&SESSION_ID_PATTERN.test(sessionId)}function isPlainSegment(segment){return typeof segment==="string"&&segment.length>0&&segment!=="."&&segment!==".."}function buildSwarmBranchName(sessionId,id,purpose,legacyLane){let[standardPrefix,legacyLanePrefix]=SWARM_WORKTREE_BRANCH_PREFIXES;return legacyLane?`${legacyLanePrefix}${sessionId}/${id}`:`${standardPrefix}${purpose}/${sessionId}/${id}`}function matchSwarmLanePath(lanePath){if(typeof lanePath!=="string"||lanePath==="")return;let segments=lanePath.split(/[\\/]+/).filter((s)=>s.length>0);if(segments.length<3)return;let[base,sessionId,id]=segments.slice(-3);if(!(process.platform==="win32"?base.toLowerCase()===SWARM_WORKTREE_DIR_NAME.toLowerCase():base===SWARM_WORKTREE_DIR_NAME))return;if(!SESSION_ID_PATTERN.test(sessionId??""))return;if(!isPlainSegment(id))return;return{sessionId,id}}function matchSwarmLaneBranch(branch){if(typeof branch!=="string"||branch==="")return;let segments=branch.split("/");if(segments[0]==="swarm-lane"){if(segments.length!==3)return;let[,sessionId,id]=segments;if(!SESSION_ID_PATTERN.test(sessionId??""))return;if(!isPlainSegment(id))return;return{purpose:"lane",sessionId,id,style:"legacy-lane"}}if(segments[0]==="swarm"){if(segments.length!==4)return;let[,purpose,sessionId,id]=segments;if(!isPlainSegment(purpose))return;if(!SESSION_ID_PATTERN.test(sessionId??""))return;if(!isPlainSegment(id))return;return{purpose,sessionId,id,style:"purpose"}}return}var SWARM_WORKTREE_BRANCH_PREFIXES,SESSION_ID_PATTERN;var init_swarm_branch=__esm(()=>{init_constants();SWARM_WORKTREE_BRANCH_PREFIXES=["swarm/","swarm-lane/"],SESSION_ID_PATTERN=/^ses_[A-Za-z0-9]+$/});import*as crypto3 from"node:crypto";import*as fs15 from"node:fs";import*as path22 from"node:path";function resolvePlanEpochIdentity(events,authoritativePlan){let planId=derivePlanId(authoritativePlan),planIdentityHash=derivePlanIdentityHash(authoritativePlan),payloadHash=computePlanHash(authoritativePlan),candidates=extractPlanEpochCandidates(events,planId);if(new Set(candidates.map((candidate)=>`${candidate.planEpoch}:${candidate.rootEventHash}`)).size>1)throw Error(`Conflicting plan epoch metadata detected for ${planId}; refusing to continue.`);if(candidates.length===0)return null;let existing=candidates[0];return{planId,planIdentityHash,planEpoch:existing.planEpoch,rootEventHash:existing.rootEventHash,payloadHash,source:existing.source}}function getLedgerPath(directory){return path22.join(directory,".swarm",LEDGER_FILENAME)}function getPlanJsonPath(directory){return path22.join(directory,".swarm",PLAN_JSON_FILENAME)}function asRecord(value){if(value&&typeof value==="object"&&!Array.isArray(value))return value;return null}function isSha256Hex(value){return/^[a-f0-9]{64}$/i.test(value)}function isUuid(value){return/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value)}function serializeLedgerEvent(event){return JSON.stringify(event)}function computeLedgerEventHash(event){return crypto3.createHash("sha256").update(serializeLedgerEvent(event),"utf8").digest("hex")}function extractPlanEpochCandidates(events,expectedPlanId){if(events.length===0)throw Error("Plan ledger is empty; missing plan_created root.");let rootEvent=events[0];if(rootEvent.event_type!=="plan_created")throw Error(`Plan ledger root must be plan_created; found ${rootEvent.event_type} at seq ${rootEvent.seq}.`);if(rootEvent.plan_id!==expectedPlanId)throw Error(`Plan ledger identity mismatch: expected ${expectedPlanId} but found ${rootEvent.plan_id}.`);let rootEventHash=computeLedgerEventHash(rootEvent),candidates=[],rootPlanEpoch=asRecord(rootEvent.payload)?.plan_epoch;if(typeof rootPlanEpoch==="string"&&rootPlanEpoch.length>0){if(!isUuid(rootPlanEpoch))throw Error("Plan ledger root carries an invalid plan_epoch.");candidates.push({planEpoch:rootPlanEpoch,rootEventHash,source:"root"})}for(let event of events){if(event.event_type!=="snapshot"||event.source!=="plan_epoch_adopted")continue;if(event.plan_id!==expectedPlanId)throw Error(`Plan epoch adoption snapshot at seq ${event.seq} belongs to ${event.plan_id}, expected ${expectedPlanId}.`);let payload=asRecord(event.payload),planEpoch=payload?.plan_epoch,rootHash=payload?.root_event_hash,embeddedPlan=PlanSchema.safeParse(payload?.plan);if(!embeddedPlan.success)throw Error(`Plan epoch adoption snapshot at seq ${event.seq} carries an invalid embedded plan.`);let payloadHash=payload?.payload_hash;if(typeof planEpoch!=="string"||!isUuid(planEpoch))throw Error(`Plan epoch adoption snapshot at seq ${event.seq} has an invalid plan_epoch.`);if(typeof rootHash!=="string"||!isSha256Hex(rootHash))throw Error(`Plan epoch adoption snapshot at seq ${event.seq} has an invalid root_event_hash.`);if(rootHash!==rootEventHash)throw Error(`Plan epoch adoption snapshot at seq ${event.seq} does not match the canonical ledger root.`);if(typeof payloadHash!=="string")throw Error(`Plan epoch adoption snapshot at seq ${event.seq} is missing payload_hash.`);if(derivePlanId(embeddedPlan.data)!==expectedPlanId)throw Error(`Plan epoch adoption snapshot at seq ${event.seq} embeds a different plan identity.`);if(computePlanHash(embeddedPlan.data)!==payloadHash)throw Error(`Plan epoch adoption snapshot at seq ${event.seq} has a mismatched payload_hash.`);candidates.push({planEpoch,rootEventHash:rootHash,source:"plan_epoch_adopted"})}return candidates}function writeFileFsyncedThenRename(tempPath,targetPath,data){let fd=fs15.openSync(tempPath,"w");try{fs15.writeFileSync(fd,data,"utf8"),fs15.fsyncSync(fd)}finally{fs15.closeSync(fd)}fs15.renameSync(tempPath,targetPath)}function fsyncRecoveryDirectory(directory){let fd;try{fd=fs15.openSync(directory,"r"),fs15.fsyncSync(fd)}catch(error49){let code=error49.code;if(process.platform==="win32"&&["EPERM","EACCES","EINVAL","EBADF","EISDIR","ENOTSUP"].includes(code??"")){log(`[ledger] Directory fsync unavailable for recovery archive ${directory}: ${error49 instanceof Error?error49.message:String(error49)}`);return}throw Error(`Failed to fsync recovery archive directory before canonical replacement: ${error49 instanceof Error?error49.message:String(error49)}`)}finally{if(fd!==void 0)fs15.closeSync(fd)}}function findRawMalformedSuffix(content){let decoder=new TextDecoder("utf-8",{fatal:!0}),lineStart=0;for(let index=0;index<=content.length;index++){if(index<content.length&&content[index]!==10)continue;let lineEnd=index;if(lineEnd>lineStart&&content[lineEnd-1]===13)lineEnd--;let line=content.subarray(lineStart,lineEnd);if(line.length>0)try{JSON.parse(decoder.decode(line))}catch{return content.subarray(lineStart)}lineStart=index+1}return Buffer.alloc(0)}function computePlanHash(plan){let normalized={schema_version:plan.schema_version,title:plan.title,swarm:plan.swarm,current_phase:plan.current_phase,migration_status:plan.migration_status,execution_profile:normalizeExecutionProfileForHash(plan.execution_profile),phases:plan.phases.map((phase)=>({id:phase.id,name:phase.name,status:phase.status,required_agents:phase.required_agents?[...phase.required_agents].sort():void 0,tasks:phase.tasks.map((task)=>({id:task.id,phase:task.phase,status:task.status,size:task.size,description:task.description,depends:[...task.depends].sort(),acceptance:task.acceptance,files_touched:[...task.files_touched].sort(),evidence_path:task.evidence_path,blocked_reason:task.blocked_reason}))}))},jsonString=JSON.stringify(normalized);return crypto3.createHash("sha256").update(jsonString,"utf8").digest("hex")}function computePlanStructureHash(plan){let normalized={schema_version:plan.schema_version,title:plan.title,swarm:plan.swarm,current_phase:plan.current_phase,migration_status:plan.migration_status,execution_profile:normalizeExecutionProfileForHash(plan.execution_profile),phases:plan.phases.map((phase)=>({id:phase.id,name:phase.name,required_agents:phase.required_agents?[...phase.required_agents].sort():void 0,tasks:phase.tasks.map((task)=>({id:task.id,phase:task.phase,size:task.size,description:task.description,depends:[...task.depends].sort(),acceptance:task.acceptance,files_touched:[...task.files_touched].sort(),evidence_path:task.evidence_path,blocked_reason:task.blocked_reason}))}))},jsonString=JSON.stringify(normalized);return crypto3.createHash("sha256").update(jsonString,"utf8").digest("hex")}function computeCurrentPlanHash(directory){let planPath=getPlanJsonPath(directory);try{let content=fs15.readFileSync(planPath,"utf8"),plan=JSON.parse(content);return computePlanHash(plan)}catch{return""}}async function ledgerExists(directory){let ledgerPath=getLedgerPath(directory);return fs15.existsSync(ledgerPath)}async function getLatestLedgerSeq(directory){let ledgerPath=getLedgerPath(directory);if(!fs15.existsSync(ledgerPath))return 0;try{let lines=fs15.readFileSync(ledgerPath,"utf8").trim().split(`
|
|
@@ -873,14 +873,14 @@ ${warnings.map((w)=>`Detected signal: ${w}`).join(`
|
|
|
873
873
|
`),validStartMs=[];for(let line of lines){if(!line.trim())continue;try{let parsed=JSON.parse(line);if(typeof parsed.startMs==="number"&&Number.isFinite(parsed.startMs))validStartMs.push(parsed.startMs)}catch{}}if(validStartMs.length===0)return null;return new Date(Math.min(...validStartMs)).toISOString()}catch{return null}}var SESSION_START_FILE="session-start.jsonl";var init_session_start_store=()=>{};import{execFile as execFile2}from"node:child_process";function markSuggested(sessionId){if(_suggestedSessions.has(sessionId))return;if(_suggestedSessions.size>=MAX_SUGGESTED_SESSIONS){let oldest=_suggestedSessions.values().next().value;if(oldest!==void 0)_suggestedSessions.delete(oldest)}_suggestedSessions.add(sessionId)}async function countWorktrees(directory){let gitExecutable;try{gitExecutable=await resolveGitExecutableAsync()}catch{return 0}return new Promise((resolve43)=>{try{let child=execFile2(gitExecutable,["-C",directory,"worktree","list","--porcelain"],{timeout:GIT_TIMEOUT_MS3,windowsHide:!0,encoding:"utf-8"},(err,stdout)=>{if(err||typeof stdout!=="string"){resolve43(0);return}let count=0;for(let line of stdout.split(`
|
|
874
874
|
`))if(line.startsWith("worktree "))count++;resolve43(count)});try{child.stdin?.end()}catch{}child.on("error",()=>resolve43(0))}catch{resolve43(0)}})}async function maybeSuggestWorktreeLink(directory,sessionId){try{if(!directory||!sessionId)return;if(_suggestedSessions.has(sessionId))return;if(markSuggested(sessionId),isLinked(directory))return;let worktrees=await countWorktrees(directory);if(worktrees>1)advisoryWarn(`[opencode-swarm] Detected ${worktrees} git worktrees of this repo. Run \`/swarm link\` in each to share swarm knowledge across them (or \`/swarm link <name>\` to share with similar projects).`)}catch{}}var GIT_TIMEOUT_MS3=1500,MAX_SUGGESTED_SESSIONS=500,_suggestedSessions;var init_worktree_link_suggestion=__esm(()=>{init_knowledge_link();init_warning_buffer();init_git_executable();_suggestedSessions=new Set});class AgentRunContext{runId;activeToolCalls;activeAgent;delegationChains;agentSessions;environmentProfiles;toolAggregates;constructor(runId,toolAggregates){this.runId=runId,this.activeToolCalls=new Map,this.activeAgent=new Map,this.delegationChains=new Map,this.agentSessions=new Map,this.environmentProfiles=new Map,this.toolAggregates=toolAggregates}}var exports_pr_subscriptions={};__export(exports_pr_subscriptions,{updateSnapshot:()=>updateSnapshot,unsubscribe:()=>unsubscribe,sweepStale:()=>sweepStale,subscribe:()=>subscribe,setOnSubscriptionCreated:()=>setOnSubscriptionCreated,lookupByPr:()=>lookupByPr,listActive:()=>listActive,buildCorrelationId:()=>buildCorrelationId,PR_SUBSCRIPTIONS_FILE:()=>PR_SUBSCRIPTIONS_FILE});import*as fs51 from"node:fs";import*as path82 from"node:path";function setOnSubscriptionCreated(callback){onSubscriptionCreated=callback}function storePath2(directory){return validateSwarmPath(directory,PR_SUBSCRIPTIONS_FILE)}function ensureSwarmDir3(directory){fs51.mkdirSync(path82.resolve(directory,".swarm","pr-monitor"),{recursive:!0})}function buildCorrelationId(sessionID,repoFullName,prNumber){return`${sessionID}::${repoFullName}::${prNumber}`}function readAllRecords(directory){let raw;try{raw=fs51.readFileSync(storePath2(directory),"utf-8")}catch(err){if(err.code==="ENOENT")return[];return log(`[pr-monitor] readAllRecords failed: ${err instanceof Error?err.message:String(err)}`),[]}let folded=new Map;for(let line of raw.split(`
|
|
875
875
|
`)){let trimmed=line.trim();if(trimmed.length===0)continue;let parsedJson;try{parsedJson=JSON.parse(trimmed)}catch{continue}let result=RecordSchema2.safeParse(parsedJson);if(!result.success)continue;folded.set(result.data.correlationId,result.data)}return[...folded.values()]}function appendRecord3(directory,record2){let result=RecordSchema2.safeParse(record2);if(!result.success)throw Error(`Invalid subscription record: ${result.error.message}`);ensureSwarmDir3(directory),fs51.appendFileSync(storePath2(directory),`${JSON.stringify(record2)}
|
|
876
|
-
`,"utf-8")}async function subscribe(directory,input){if(!directory||directory.trim()==="")throw Error("directory is required");if(!input.sessionID||input.sessionID.trim()==="")throw Error("sessionID is required and must be non-empty");if(!input.repoFullName||input.repoFullName.trim()==="")throw Error("repoFullName is required and must be non-empty");if(!input.prUrl||input.prUrl.trim()==="")throw Error("prUrl is required and must be non-empty");if(!input.prNumber||!Number.isInteger(input.prNumber)||input.prNumber<=0)throw Error("prNumber is required and must be a positive integer");let correlationId=buildCorrelationId(input.sessionID,input.repoFullName,input.prNumber),now=Date.now();return withEvidenceLock(directory,PR_SUBSCRIPTIONS_FILE,STORE_LOCK_AGENT2,STORE_LOCK_TASK2,async()=>{let existing=readAllRecords(directory),match=existing.find((r)=>r.correlationId===correlationId&&r.status==="active");if(match)return onSubscriptionCreated?.(directory,match),match;if(input.maxSubscriptions!==void 0&&input.maxSubscriptions>0){let activeCount=existing.filter((r)=>r.status==="active").length;if(activeCount>=input.maxSubscriptions)throw Error(`PR subscription limit reached: ${activeCount}/${input.maxSubscriptions}`)}let record2={correlationId,sessionID:input.sessionID,prNumber:input.prNumber,repoFullName:input.repoFullName,prUrl:input.prUrl,lastCheckedAt:now,isWatching:!0,hasUnaddressedEvents:!1,status:"active",createdAt:now,updatedAt:now,errorCount:0};return appendRecord3(directory,record2),onSubscriptionCreated?.(directory,record2),record2})}async function unsubscribe(directory,correlationId){if(!correlationId)return null;return withEvidenceLock(directory,PR_SUBSCRIPTIONS_FILE,STORE_LOCK_AGENT2,STORE_LOCK_TASK2,async()=>{let match=readAllRecords(directory).find((r)=>r.correlationId===correlationId&&r.status==="active");if(!match)return null;let now=Date.now(),removed={...match,status:"removed",isWatching:!1,updatedAt:now};return appendRecord3(directory,removed),removed})}async function listActive(directory){return readAllRecords(directory).filter((r)=>r.status==="active")}async function lookupByPr(directory,repoFullName,prNumber){for(let record2 of readAllRecords(directory))if(record2.status==="active"&&record2.repoFullName===repoFullName&&record2.prNumber===prNumber)return record2;return null}async function updateSnapshot(directory,correlationId,updates){if(!correlationId)return null;return withEvidenceLock(directory,PR_SUBSCRIPTIONS_FILE,STORE_LOCK_AGENT2,STORE_LOCK_TASK2,async()=>{let match=readAllRecords(directory).find((r)=>r.correlationId===correlationId&&r.status==="active");if(!match)return null;let updated={...match,...updates,correlationId,sessionID:match.sessionID,repoFullName:match.repoFullName,prNumber:match.prNumber,prUrl:match.prUrl,createdAt:match.createdAt,updatedAt:Date.now()};return appendRecord3(directory,updated),updated})}async function sweepStale(directory,ttlDays,mergedPrs){if(!ttlDays||ttlDays<=0)return 0;let ttlMs=ttlDays*86400000,now=Date.now();try{return await withEvidenceLock(directory,PR_SUBSCRIPTIONS_FILE,STORE_LOCK_AGENT2,STORE_LOCK_TASK2,async()=>{let swept=0;for(let record2 of readAllRecords(directory)){if(record2.status!=="active")continue;let prKey=`${record2.repoFullName}::${record2.prNumber}`,isMerged=mergedPrs?.has(prKey)??!1,isStale=now-record2.updatedAt>ttlMs;if(isMerged){appendRecord3(directory,{...record2,status:"expired",isWatching:!1,updatedAt:now}),swept+=1,log(`[pr-monitor] Swept subscription: merged/closed: ${prKey}`);continue}if(isStale&&!record2.hasUnaddressedEvents)appendRecord3(directory,{...record2,status:"expired",isWatching:!1,updatedAt:now}),swept+=1,log(`[pr-monitor] Swept subscription: stale (TTL ${ttlDays}d): ${prKey}`)}return swept})}catch(err){return log(`[pr-monitor] sweepStale failed: ${err instanceof Error?err.message:String(err)}`),0}}var PR_SUBSCRIPTIONS_FILE="pr-monitor/subscriptions.jsonl",STORE_LOCK_AGENT2="pr-monitor",STORE_LOCK_TASK2="pr-subscriptions",onSubscriptionCreated=null,RecordSchema2;var init_pr_subscriptions=__esm(()=>{init_zod();init_lock();init_utils2();init_utils();RecordSchema2=exports_external.object({correlationId:exports_external.string().min(1),sessionID:exports_external.string().min(1),prNumber:exports_external.number().int().positive(),repoFullName:exports_external.string().regex(/^[^/]+\/[^/]+$/,"Must be owner/repo format"),prUrl:exports_external.string().min(1).regex(/^https:\/\/github\.com\/[^/]+\/[^/]+\/pull\/\d+$/,"Must be a valid GitHub PR URL"),headRefOid:exports_external.string().optional(),lastCheckedAt:exports_external.number(),lastCommentId:exports_external.string().optional(),lastCheckRunSet:exports_external.string().optional(),mergeableState:exports_external.string().optional(),mergeGroupRunStatus:exports_external.string().optional(),mergeGroupRunConclusion:exports_external.string().optional(),mergeGroupRunHtmlUrl:exports_external.string().optional(),isWatching:exports_external.boolean(),hasUnaddressedEvents:exports_external.boolean(),status:exports_external.enum(["active","removed","expired"]),createdAt:exports_external.number(),updatedAt:exports_external.number(),errorCount:exports_external.number().int().min(0),customPollIntervalSeconds:exports_external.number().int().positive().optional(),customFailureThreshold:exports_external.number().int().min(0).optional(),customCooldownSeconds:exports_external.number().int().min(0).optional()}).strict()});var exports_state={};__export(exports_state,{updateTaskWorkflowCache:()=>updateTaskWorkflowCache,updateAgentEventTime:()=>updateAgentEventTime,takeReviewerScopeGeneration:()=>takeReviewerScopeGeneration,sweepStaleSessions:()=>sweepStaleSessions,swarmState:()=>swarmState,startReviewerScopeGeneration:()=>startReviewerScopeGeneration,startAgentSession:()=>startAgentSession,settleReviewerScopeMergeback:()=>settleReviewerScopeMergeback,setSessionEnvironment:()=>setSessionEnvironment,setSessionBudget:()=>setSessionBudget,setLiveContextWindow:()=>setLiveContextWindow,setCriticalShownIds:()=>setCriticalShownIds,reviewerScopeGenerationHasDeclaredOverlap:()=>reviewerScopeGenerationHasDeclaredOverlap,resolveSessionWorkspaceDirectory:()=>resolveSessionWorkspaceDirectory,resetSwarmStatePreservingSingletons:()=>resetSwarmStatePreservingSingletons,resetSwarmState:()=>resetSwarmState,resetModifiedFilesForTask:()=>resetModifiedFilesForTask,rehydrateSessionFromDisk:()=>rehydrateSessionFromDisk,rehydratePrSubscriptions:()=>rehydratePrSubscriptions,recordStageBCompletion:()=>recordStageBCompletion,recordSessionWorkspaceRoot:()=>recordSessionWorkspaceRoot,recordReviewerScopeGenerationFileFingerprint:()=>recordReviewerScopeGenerationFileFingerprint,recordReviewerScopeGenerationFile:()=>recordReviewerScopeGenerationFile,recordReviewerScopeGenerationCaptureFailure:()=>recordReviewerScopeGenerationCaptureFailure,recordPhaseAgentDispatch:()=>recordPhaseAgentDispatch,recordModifiedFilesForTask:()=>recordModifiedFilesForTask,recordModifiedFileForTask:()=>recordModifiedFileForTask,pruneOldWindows:()=>pruneOldWindows,peekReviewerScopeGenerationClaim:()=>peekReviewerScopeGenerationClaim,peekReviewerScopeGenerationByStatus:()=>peekReviewerScopeGenerationByStatus,peekReadyReviewerScopeGeneration:()=>peekReadyReviewerScopeGeneration,maybeSweepStaleSessions:()=>maybeSweepStaleSessions,markReviewerScopeGenerationReady:()=>markReviewerScopeGenerationReady,markReviewerScopeGenerationNoChange:()=>markReviewerScopeGenerationNoChange,markReviewerScopeGenerationMergebackPending:()=>markReviewerScopeGenerationMergebackPending,isReviewerScopeGenerationCurrent:()=>isReviewerScopeGenerationCurrent,isCouncilGateActive:()=>isCouncilGateActive,incrementGateDenialCount:()=>incrementGateDenialCount,hasBothStageBCompletions:()=>hasBothStageBCompletions,hasActiveTurboMode:()=>hasActiveTurboMode,hasActiveLeanTurbo:()=>hasActiveLeanTurbo,hasActiveFullAuto:()=>hasActiveFullAuto,hasActiveEpicMode:()=>hasActiveEpicMode,getTaskState:()=>getTaskState,getSessionEnvironment:()=>getSessionEnvironment,getSessionBudgetTokens:()=>getSessionBudgetTokens,getSessionBudgetPct:()=>getSessionBudgetPct,getRunContext:()=>getRunContext,getReviewerScopeOwnershipHistory:()=>getReviewerScopeOwnershipHistory,getReviewerScopeGenerationForCoderCall:()=>getReviewerScopeGenerationForCoderCall,getResolvedAutoProceed:()=>getResolvedAutoProceed,getModifiedFilesForTask:()=>getModifiedFilesForTask,getLiveContextWindow:()=>getLiveContextWindow,getLiveContextModelIdentity:()=>getLiveContextModelIdentity,getDisplayBudget:()=>getDisplayBudget,getAgentSession:()=>getAgentSession,getActiveWindow:()=>getActiveWindow,getActiveFullAutoSessionID:()=>getActiveFullAutoSessionID,ensureSessionEnvironment:()=>ensureSessionEnvironment,ensureAgentSession:()=>ensureAgentSession,endAgentSession:()=>endAgentSession,discardReviewerScopeGenerationForCoderCall:()=>discardReviewerScopeGenerationForCoderCall,discardReviewerScopeGenerationClaim:()=>discardReviewerScopeGenerationClaim,defaultRunContext:()=>defaultRunContext,completeModifiedFilesForTask:()=>completeModifiedFilesForTask,clearGateDenialCount:()=>clearGateDenialCount,clearCriticalShownIds:()=>clearCriticalShownIds,claimReviewerScopeGeneration:()=>claimReviewerScopeGeneration,canAdvanceTaskState:()=>canAdvanceTaskState,buildRehydrationCache:()=>buildRehydrationCache,buildGateDenialDirectiveKey:()=>buildGateDenialDirectiveKey,beginInvocation:()=>beginInvocation,attachReviewerScopeGenerationDispatchSnapshot:()=>attachReviewerScopeGenerationDispatchSnapshot,applyRehydrationCache:()=>applyRehydrationCache,advanceTaskStateAndPersist:()=>advanceTaskStateAndPersist,advanceTaskState:()=>advanceTaskState,addKnowledgeAckDedup:()=>addKnowledgeAckDedup,_resetCouncilDisagreementWarnings:()=>_resetCouncilDisagreementWarnings,_internals:()=>_internals65,REVIEWER_SCOPE_GENERATION_TTL_MS:()=>REVIEWER_SCOPE_GENERATION_TTL_MS,MAX_TRACKED_TASK_FILE_ATTRIBUTIONS:()=>MAX_TRACKED_TASK_FILE_ATTRIBUTIONS,MAX_TRACKED_KNOWLEDGE_ACKS:()=>MAX_TRACKED_KNOWLEDGE_ACKS,MAX_TRACKED_GATE_DENIALS:()=>MAX_TRACKED_GATE_DENIALS,MAX_TRACKED_CRITICAL_SHOWN:()=>MAX_TRACKED_CRITICAL_SHOWN,MAX_TRACKED_CONTEXT_WINDOWS:()=>MAX_TRACKED_CONTEXT_WINDOWS,MAX_TRACKED_BUDGET_SESSIONS:()=>MAX_TRACKED_BUDGET_SESSIONS,MAX_REVIEWER_SCOPE_OWNERSHIP_HISTORY:()=>MAX_REVIEWER_SCOPE_OWNERSHIP_HISTORY,MAX_REVIEWER_SCOPE_GENERATION_FILES:()=>MAX_REVIEWER_SCOPE_GENERATION_FILES,MAX_REVIEWER_SCOPE_GENERATIONS:()=>MAX_REVIEWER_SCOPE_GENERATIONS,AgentRunContext:()=>AgentRunContext});import{randomUUID as randomUUID13}from"node:crypto";import*as fs52 from"node:fs/promises";import*as path83 from"node:path";function compareWorkflowStatePrecedence(left,right){return compareTaskWorkflowStateRank(left,right)}function cloneReviewerScopeGeneration(generation){return{...generation,declaredFiles:[...generation.declaredFiles],modifiedFiles:[...generation.modifiedFiles],modifiedFileFingerprints:generation.modifiedFileFingerprints.map((entry)=>({...entry})),captureFailures:generation.captureFailures.map((entry)=>({...entry})),reviewerDispatchScope:generation.reviewerDispatchScope?{...generation.reviewerDispatchScope,files:[...generation.reviewerDispatchScope.files]}:void 0}}function cloneReviewerScopeOwnershipTombstone(tombstone){return{...tombstone,declaredFiles:[...tombstone.declaredFiles],modifiedFiles:[...tombstone.modifiedFiles],modifiedFileFingerprints:tombstone.modifiedFileFingerprints.map((fingerprint2)=>({...fingerprint2}))}}function createNonTransientCircuitState(agentName,invocationId){return{ownerAgent:stripKnownSwarmPrefix(agentName),ownerInvocationId:invocationId,category:null,sameCategoryCount:0,hardStop:!1,lastSignal:null}}function getRunContext(runId){if(!runId)return defaultRunContext;return _runContexts.get(runId)??defaultRunContext}function resetSwarmState(){swarmState.activeToolCalls.clear(),swarmState.toolAggregates.clear(),swarmState.activeAgent.clear(),swarmState.delegationChains.clear(),swarmState.pendingEvents=0,swarmState.lastBudgetBySession.clear(),swarmState.liveContextWindows.clear(),swarmState.agentSessions.clear(),_lastIdleSweepAtMs=0,clearTrajectoryCache(),clearTrajectoryStepCounters(),swarmState.pendingRehydrations.clear(),swarmState.opencodeClient=null,swarmState.curatorInitAgentNames=[],swarmState.curatorPhaseAgentNames=[],swarmState.curatorPostmortemAgentNames=[],swarmState.curatorConsolidationAgentNames=[],swarmState.skillImproverAgentNames=[],swarmState.specWriterAgentNames=[],swarmState.currentCriticalShownIds.clear(),swarmState.knowledgeAckDedup.clear(),swarmState.gateDenialCounts.clear(),swarmState.generatedAgentNames=[],_rehydrationCache=null,swarmState.fullAutoEnabledInConfig=!1,swarmState.environmentProfiles.clear(),clearAllActionCircuits(),clearAllTaskModelRoutingState(),clearPendingCoderScope();for(let binding of clearScopeBindings())clearScopeBindingFromDisk({directory:binding.workspaceIdentity,binding});resetStandardWorktreeIsolationState(),resetRealtimeLearningNudgeState(),_councilDisagreementWarned.clear()}function resetSwarmStatePreservingSingletons(){let{opencodeClient:preservedOpencodeClient,fullAutoEnabledInConfig:preservedFullAutoEnabledInConfig,curatorInitAgentNames:preservedCuratorInitAgentNames,curatorPhaseAgentNames:preservedCuratorPhaseAgentNames,curatorPostmortemAgentNames:preservedCuratorPostmortemAgentNames,curatorConsolidationAgentNames:preservedCuratorConsolidationAgentNames,skillImproverAgentNames:preservedSkillImproverAgentNames,specWriterAgentNames:preservedSpecWriterAgentNames,generatedAgentNames:preservedGeneratedAgentNames}=swarmState;resetSwarmState(),swarmState.opencodeClient=preservedOpencodeClient,swarmState.fullAutoEnabledInConfig=preservedFullAutoEnabledInConfig,swarmState.curatorInitAgentNames=preservedCuratorInitAgentNames,swarmState.curatorPhaseAgentNames=preservedCuratorPhaseAgentNames,swarmState.curatorPostmortemAgentNames=preservedCuratorPostmortemAgentNames,swarmState.curatorConsolidationAgentNames=preservedCuratorConsolidationAgentNames,swarmState.skillImproverAgentNames=preservedSkillImproverAgentNames,swarmState.specWriterAgentNames=preservedSpecWriterAgentNames,swarmState.generatedAgentNames=preservedGeneratedAgentNames}function isBoundedGenerationValue(value,maxLength){return value.length>0&&value.length<=maxLength&&!Array.from(value).some((char)=>{let code=char.charCodeAt(0);return code<=31||code===127})}function reviewerScopeGenerationKey(taskId,coderCallID,generation){return`${taskId}\x00${coderCallID}\x00${generation}`}function reviewerScopeOwnershipKey(taskId,coderCallID,generation,sessionIncarnation){return`${taskId}\x00${coderCallID}\x00${generation}\x00${sessionIncarnation}`}function ensureReviewerScopeGenerationState(session){return session.reviewerScopeGenerations??=new Map,session.reviewerScopeGenerationCounter??=0,session.reviewerScopeIncarnation??=randomUUID13(),session.reviewerScopeLatestGenerationByTask??=new Map,session.reviewerScopeOwnershipHistory??=new Map,{generations:session.reviewerScopeGenerations,counter:session.reviewerScopeGenerationCounter,incarnation:session.reviewerScopeIncarnation,latestByTask:session.reviewerScopeLatestGenerationByTask,ownershipHistory:session.reviewerScopeOwnershipHistory}}function sweepReviewerScopeGenerations(session,now){let{generations}=ensureReviewerScopeGenerationState(session);for(let[key,entry]of generations){if(entry.status==="claimed"||entry.status==="mergeback_pending"||entry.status==="mergeback_mismatch")continue;if(!Number.isFinite(entry.createdAt)||now<entry.createdAt||now-entry.createdAt>REVIEWER_SCOPE_GENERATION_TTL_MS)generations.delete(key)}}function startReviewerScopeGeneration(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session||!isBoundedGenerationValue(input.taskId,512)||!isBoundedGenerationValue(input.coderCallID,512)||!input.captureDirectory.trim()||!input.workspaceIdentity.trim())return null;let now=input.createdAt??Date.now();sweepReviewerScopeGenerations(session,now);let{generations,counter,incarnation,latestByTask}=ensureReviewerScopeGenerationState(session);for(let[key2,entry]of generations)if(entry.taskId===input.taskId&&entry.status!=="claimed")generations.delete(key2);while(generations.size>=MAX_REVIEWER_SCOPE_GENERATIONS){let oldestUnclaimed=[...generations.entries()].find(([,entry])=>entry.status!=="claimed")?.[0];if(!oldestUnclaimed)return null;generations.delete(oldestUnclaimed)}session.reviewerScopeGenerationCounter=counter>=Number.MAX_SAFE_INTEGER?1:counter+1;let generation={taskId:input.taskId,coderCallID:input.coderCallID,generation:session.reviewerScopeGenerationCounter,sessionIncarnation:incarnation,background:input.background===!0,captureDirectory:input.captureDirectory,workspaceIdentity:input.workspaceIdentity,declaredFiles:[...new Set(input.declaredFiles??[])],modifiedFiles:[],modifiedFileFingerprints:[],captureFailures:[],status:"collecting",createdAt:now};if(!latestByTask.has(generation.taskId))while(latestByTask.size>=MAX_REVIEWER_SCOPE_GENERATIONS){let oldestTask=latestByTask.keys().next().value;if(!oldestTask)break;latestByTask.delete(oldestTask)}latestByTask.delete(generation.taskId),latestByTask.set(generation.taskId,{generation:generation.generation,coderCallID:generation.coderCallID,sessionIncarnation:generation.sessionIncarnation});let key=reviewerScopeGenerationKey(generation.taskId,generation.coderCallID,generation.generation);return generations.set(key,generation),cloneReviewerScopeGeneration(generation)}function recordReviewerScopeGenerationFile(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session||!isBoundedGenerationValue(input.file,4096)||!isBoundedGenerationValue(input.taskId,512)||!isBoundedGenerationValue(input.coderCallID,512))return!1;sweepReviewerScopeGenerations(session,input.now??Date.now());let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.values()].filter((entry)=>entry.taskId===input.taskId&&entry.coderCallID===input.coderCallID&&entry.status==="collecting");if(matches.length!==1)return!1;let generation=matches[0];if(generation.modifiedFiles.includes(input.file))return!0;if(generation.modifiedFiles.length>=MAX_REVIEWER_SCOPE_GENERATION_FILES){let key=reviewerScopeGenerationKey(generation.taskId,generation.coderCallID,generation.generation);return generations.delete(key),!1}return generation.modifiedFiles.push(input.file),!0}function recordReviewerScopeGenerationFileFingerprint(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return!1;let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.values()].filter((entry)=>entry.taskId===input.taskId&&entry.coderCallID===input.coderCallID&&entry.status==="collecting");if(matches.length!==1)return!1;let generation=matches[0];if(!generation.modifiedFiles.includes(input.fingerprint.file))return!1;generation.captureFailures=generation.captureFailures.filter((entry)=>entry.file!==input.fingerprint.file);let existingIndex=generation.modifiedFileFingerprints.findIndex((entry)=>entry.file===input.fingerprint.file);if(existingIndex>=0)return generation.modifiedFileFingerprints[existingIndex]={...input.fingerprint},!0;if(generation.modifiedFileFingerprints.length>=MAX_REVIEWER_SCOPE_GENERATION_FILES)return!1;return generation.modifiedFileFingerprints.push({...input.fingerprint}),!0}function recordReviewerScopeGenerationCaptureFailure(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session||!isBoundedGenerationValue(input.file,4096))return!1;let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.values()].filter((entry)=>entry.taskId===input.taskId&&entry.coderCallID===input.coderCallID&&entry.status==="collecting");if(matches.length!==1)return!1;let generation=matches[0],now=input.at??Date.now();generation.modifiedFileFingerprints=generation.modifiedFileFingerprints.filter((entry)=>entry.file!==input.file);let existingIndex=generation.captureFailures.findIndex((entry)=>entry.file===input.file);if(existingIndex>=0){let existing=generation.captureFailures[existingIndex];return generation.captureFailures[existingIndex]={...existing,code:input.code,retryable:input.retryable,attempts:existing.attempts+1,at:now},!0}if(generation.captureFailures.length>=MAX_REVIEWER_SCOPE_GENERATION_FILES)generation.captureFailures.shift();return generation.captureFailures.push({file:input.file,code:input.code,retryable:input.retryable,attempts:1,at:now}),!0}function markReviewerScopeGenerationReady(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return!1;let now=input.readyAt??Date.now();sweepReviewerScopeGenerations(session,now);let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.values()].filter((entry)=>entry.taskId===input.taskId&&entry.coderCallID===input.coderCallID&&(entry.status==="collecting"||entry.status==="ready"));if(matches.length!==1)return!1;let generation=matches[0];if(generation.status==="ready")return!0;if(input.primaryWorkspaceIdentity&&generation.workspaceIdentity!==input.primaryWorkspaceIdentity)return!1;if(!(generation.modifiedFiles.length===generation.modifiedFileFingerprints.length&&generation.modifiedFiles.every((file2)=>generation.modifiedFileFingerprints.some((entry)=>entry.file===file2))))return!1;return generation.status="ready",generation.readyAt=now,!0}function markReviewerScopeGenerationNoChange(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return!1;let now=input.at??Date.now();sweepReviewerScopeGenerations(session,now);let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.values()].filter((entry)=>entry.taskId===input.taskId&&entry.coderCallID===input.coderCallID&&entry.status==="collecting");if(matches.length!==1)return!1;let generation=matches[0];if(generation.modifiedFiles.length!==0)return!1;return generation.status="no_change",generation.readyAt=now,!0}function markReviewerScopeGenerationMergebackPending(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return!1;let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.values()].filter((entry)=>(input.taskId===void 0||entry.taskId===input.taskId)&&entry.coderCallID===input.coderCallID&&(entry.status==="collecting"||entry.status==="ready"));if(matches.length!==1)return!1;if(matches[0].status==="mergeback_pending")return!0;return matches[0].status="mergeback_pending",!0}function settleReviewerScopeMergeback(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return!1;let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.values()].filter((entry)=>(input.taskId===void 0||entry.taskId===input.taskId)&&entry.coderCallID===input.coderCallID&&entry.status==="mergeback_pending");if(matches.length!==1)return!1;let generation=matches[0],now=input.outcome.at??Date.now();if(input.outcome.verified){if(generation.status="ready",generation.readyAt===void 0)generation.readyAt=now;return generation.mergeback={verifiedAt:now,primaryWorkspaceIdentity:input.outcome.primaryWorkspaceIdentity},generation.captureDirectory=input.outcome.primaryDirectory,generation.workspaceIdentity=input.outcome.primaryWorkspaceIdentity,!0}return generation.status="mergeback_mismatch",generation.mergeback={failedAt:now,reason:input.outcome.reason},!0}function getReviewerScopeGenerationForCoderCall(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return null;sweepReviewerScopeGenerations(session,input.now??Date.now());let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.values()].filter((entry)=>entry.coderCallID===input.coderCallID&&(input.taskId===void 0||entry.taskId===input.taskId));return matches.length===1?cloneReviewerScopeGeneration(matches[0]):null}function peekReadyReviewerScopeGeneration(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return null;sweepReviewerScopeGenerations(session,input.now??Date.now());let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.values()].filter((entry)=>entry.taskId===input.taskId&&entry.status==="ready");return matches.length===1?cloneReviewerScopeGeneration(matches[0]):null}function peekReviewerScopeGenerationByStatus(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return null;sweepReviewerScopeGenerations(session,input.now??Date.now());let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.values()].filter((entry)=>entry.taskId===input.taskId&&entry.status===input.status);return matches.length===1?cloneReviewerScopeGeneration(matches[0]):null}function claimReviewerScopeGeneration(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session||!isBoundedGenerationValue(input.taskId,512)||!isBoundedGenerationValue(input.reviewerCallID,512))return null;sweepReviewerScopeGenerations(session,input.now??Date.now());let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.values()].filter((entry)=>entry.taskId===input.taskId&&entry.status==="ready");if(matches.length!==1)return null;return matches[0].status="claimed",matches[0].reviewerCallID=input.reviewerCallID,cloneReviewerScopeGeneration(matches[0])}function attachReviewerScopeGenerationDispatchSnapshot(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return!1;let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.values()].filter((entry)=>entry.taskId===input.taskId&&entry.reviewerCallID===input.reviewerCallID&&entry.status==="claimed"&&entry.coderCallID===input.snapshot.coderCallID&&entry.generation===input.snapshot.generation&&entry.sessionIncarnation===input.snapshot.sessionIncarnation);if(matches.length!==1)return!1;return matches[0].reviewerDispatchScope={...input.snapshot,files:[...input.snapshot.files]},!0}function takeReviewerScopeGeneration(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return null;sweepReviewerScopeGenerations(session,input.now??Date.now());let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.entries()].filter(([,entry])=>entry.taskId===input.taskId&&entry.reviewerCallID===input.reviewerCallID&&entry.status==="claimed");if(matches.length!==1)return null;let[key,generation]=matches[0];if(generation.background===!0&&generation.readyAt!==void 0&&Number.isFinite(generation.createdAt)&&Number.isFinite(generation.readyAt)){let{ownershipHistory}=ensureReviewerScopeGenerationState(session);while(ownershipHistory.size>=MAX_REVIEWER_SCOPE_OWNERSHIP_HISTORY){let oldestKey=ownershipHistory.keys().next().value;if(!oldestKey)break;ownershipHistory.delete(oldestKey)}let tombstone={parentSessionID:input.parentSessionID,taskId:generation.taskId,coderCallID:generation.coderCallID,generation:generation.generation,sessionIncarnation:generation.sessionIncarnation,background:!0,captureDirectory:generation.captureDirectory,workspaceIdentity:generation.workspaceIdentity,declaredFiles:[...generation.declaredFiles],modifiedFiles:[...generation.modifiedFiles],modifiedFileFingerprints:generation.modifiedFileFingerprints.map((fingerprint2)=>({...fingerprint2})),createdAt:generation.createdAt,readyAt:generation.readyAt??input.now??Date.now(),consumedAt:input.now??Date.now()};ownershipHistory.set(reviewerScopeOwnershipKey(tombstone.taskId,tombstone.coderCallID,tombstone.generation,tombstone.sessionIncarnation),tombstone)}return generations.delete(key),cloneReviewerScopeGeneration(generation)}function getReviewerScopeOwnershipHistory(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return[];let{ownershipHistory}=ensureReviewerScopeGenerationState(session);return[...ownershipHistory.values()].map(cloneReviewerScopeOwnershipTombstone)}function peekReviewerScopeGenerationClaim(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return null;sweepReviewerScopeGenerations(session,input.now??Date.now());let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.values()].filter((entry)=>entry.taskId===input.taskId&&entry.reviewerCallID===input.reviewerCallID&&entry.status==="claimed");return matches.length===1?cloneReviewerScopeGeneration(matches[0]):null}function discardReviewerScopeGenerationClaim(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return!1;let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.entries()].filter(([,entry])=>(input.taskId===void 0||entry.taskId===input.taskId)&&entry.reviewerCallID===input.reviewerCallID&&entry.status==="claimed");if(matches.length!==1)return!1;return generations.delete(matches[0][0]),!0}function reviewerScopeGenerationHasDeclaredOverlap(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return!1;let{generations}=ensureReviewerScopeGenerationState(session),declared=new Set(input.declaredFiles);return[...generations.values()].some((entry)=>entry.status==="collecting"&&(entry.taskId!==input.taskId||entry.coderCallID!==input.coderCallID)&&entry.declaredFiles.some((file2)=>declared.has(file2)))}function discardReviewerScopeGenerationForCoderCall(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return!1;let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.entries()].filter(([,entry])=>(input.taskId===void 0||entry.taskId===input.taskId)&&entry.coderCallID===input.coderCallID&&entry.status!=="claimed");if(matches.length!==1)return!1;return generations.delete(matches[0][0]),!0}function isReviewerScopeGenerationCurrent(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return!1;let{incarnation,latestByTask}=ensureReviewerScopeGenerationState(session),latest=latestByTask.get(input.taskId);return incarnation===input.sessionIncarnation&&latest?.generation===input.generation&&latest.coderCallID===input.coderCallID&&latest.sessionIncarnation===input.sessionIncarnation}function sweepStaleSessions(staleDurationMs=STALE_SESSION_TTL_MS,now=Date.now()){let staleIds=[];for(let[id,session]of swarmState.agentSessions)if(now-session.lastToolCallTime>staleDurationMs)staleIds.push(id);for(let id of staleIds)swarmState.agentSessions.delete(id),swarmState.delegationChains.delete(id),swarmState.activeAgent.delete(id);return staleIds}function maybeSweepStaleSessions(staleDurationMs=STALE_SESSION_TTL_MS,now=Date.now()){if(now-_lastIdleSweepAtMs<IDLE_SWEEP_COOLDOWN_MS)return[];return _lastIdleSweepAtMs=now,sweepStaleSessions(staleDurationMs,now)}function startAgentSession(sessionId,agentName,staleDurationMs=STALE_SESSION_TTL_MS,directory){let now=Date.now();sweepStaleSessions(staleDurationMs,now);let sessionState={agentName,lastToolCallTime:now,lastAgentEventTime:now,delegationActive:!1,activeInvocationId:0,lastInvocationIdByAgent:{},windows:{},nonTransientCircuit:createNonTransientCircuitState(agentName,0),pendingToolExecutions:new Map,lastCompactionHint:0,architectWriteCount:0,lastCoderDelegationTaskId:null,currentTaskId:null,gateLog:new Map,reviewerCallCount:new Map,lastGateFailure:null,partialGateWarningsIssuedForTask:new Set,completionGateWarnedForTask:new Set,selfFixAttempted:!1,selfCodingWarnedAtCount:0,catastrophicPhaseWarnings:new Set,lastPhaseCompleteTimestamp:0,lastPhaseCompletePhase:0,phaseAgentsDispatched:new Set,lastCompletedPhaseAgentsDispatched:new Set,qaSkipCount:0,qaSkipTaskIds:[],taskWorkflowStates:new Map,taskWorkflowCache:new Map,stageBCompletion:new Map,taskCouncilApproved:new Map,taskCouncilWorkflowGeneration:new Map,pendingCouncilRequirements:new Map,lastGateOutcome:null,declaredCoderScope:null,lastScopeViolation:null,scopeViolationDetected:!1,modifiedFilesByTask:new Map,modifiedFilesThisCoderTask:[],reviewerScopeGenerations:new Map,reviewerScopeGenerationCounter:0,reviewerScopeIncarnation:randomUUID13(),reviewerScopeLatestGenerationByTask:new Map,reviewerScopeOwnershipHistory:new Map,turboMode:!1,turboStrategy:void 0,leanTurboActive:!1,leanTurboCurrentPhase:void 0,maxConcurrencyOverride:void 0,epicModeActive:!1,qaGateSessionOverrides:{},fullAutoMode:!1,fullAutoInteractionCount:0,fullAutoDeadlockCount:0,fullAutoLastQuestionHash:null,model_fallback_index:0,modelFallbackExhausted:!1,coderRevisions:0,revisionLimitHit:!1,loopDetectionWindow:[],pendingAdvisoryMessages:[],sessionRehydratedAt:0,prmPatternCounts:new Map,prmEscalationLevel:0,prmLastPatternDetected:null,prmTrajectoryStep:0,prmHardStopPending:!1,prmHardStopInjectPending:!1,prmInjectedAdvisoryKeys:new Set,prmStruckEpisodes:new Map,prmLadderCounts:new Map,executionEpisodeArmed:!1,prSubscriptions:new Map};if(swarmState.agentSessions.set(sessionId,sessionState),directory){try{recordSessionStart(directory,now)}catch{}queueMicrotask(()=>{maybeSuggestWorktreeLink(directory,sessionId)})}if(telemetry.sessionStarted(sessionId,agentName),swarmState.activeAgent.set(sessionId,agentName),_internals65.applyRehydrationCache(sessionState),directory){let rehydrationPromise;rehydrationPromise=_internals65.rehydrateSessionFromDisk(directory,sessionState).then(async()=>{try{sessionState.prSubscriptions=await rehydratePrSubscriptions(sessionId,directory)}catch(err){warn("[state] PR subscription rehydration failed, starting with empty subscriptions:",err instanceof Error?err.message:String(err))}}).catch((err)=>{warn("[state] Rehydration failed:",err instanceof Error?err.message:String(err))}).finally(()=>{swarmState.pendingRehydrations.delete(rehydrationPromise)}),swarmState.pendingRehydrations.add(rehydrationPromise)}}function endAgentSession(sessionId){let removedBindings=clearScopeBindings((binding)=>binding.ownerSessionId===sessionId||binding.parentOwnerSessionId===sessionId);for(let binding of removedBindings)clearScopeBindingFromDisk({directory:binding.workspaceIdentity,binding});swarmState.agentSessions.delete(sessionId),swarmState.activeAgent.delete(sessionId),swarmState.delegationChains.delete(sessionId),clearRealtimeLearningNudgeSession(sessionId),resetSessionQueue(sessionId),resetPrmPatternSupport(sessionId)}function getAgentSession(sessionId){return swarmState.agentSessions.get(sessionId)}function ensureAgentSession(sessionId,agentName,directory){let now=Date.now(),session=swarmState.agentSessions.get(sessionId);if(session){if(agentName&&agentName!==session.agentName){let oldName=session.agentName;if(session.agentName=agentName,telemetry.agentActivated(sessionId,agentName,oldName),session.delegationActive=!1,session.lastAgentEventTime=now,session.nonTransientCircuit=createNonTransientCircuitState(agentName,0),!session.windows)session.activeInvocationId=0,session.lastInvocationIdByAgent={},session.windows={}}if(!session.windows)session.activeInvocationId=0,session.lastInvocationIdByAgent={},session.windows={};if(session.nonTransientCircuit===void 0)session.nonTransientCircuit=createNonTransientCircuitState(session.agentName,session.activeInvocationId??0);if(session.pendingToolExecutions===void 0)session.pendingToolExecutions=new Map;if(session.lastCompactionHint===void 0)session.lastCompactionHint=0;if(session.architectWriteCount===void 0)session.architectWriteCount=0;if(session.lastCoderDelegationTaskId===void 0)session.lastCoderDelegationTaskId=null;if(session.currentTaskId===void 0)session.currentTaskId=null;if(!session.gateLog)session.gateLog=new Map;if(!session.reviewerCallCount)session.reviewerCallCount=new Map;if(session.lastGateFailure===void 0)session.lastGateFailure=null;if(!session.partialGateWarningsIssuedForTask)session.partialGateWarningsIssuedForTask=new Set;if(!session.completionGateWarnedForTask)session.completionGateWarnedForTask=new Set;if(session.selfFixAttempted===void 0)session.selfFixAttempted=!1;if(session.selfCodingWarnedAtCount===void 0)session.selfCodingWarnedAtCount=0;if(!session.catastrophicPhaseWarnings)session.catastrophicPhaseWarnings=new Set;if(session.lastPhaseCompleteTimestamp===void 0)session.lastPhaseCompleteTimestamp=0;if(session.lastPhaseCompletePhase===void 0)session.lastPhaseCompletePhase=0;if(!session.phaseAgentsDispatched)session.phaseAgentsDispatched=new Set;if(!session.lastCompletedPhaseAgentsDispatched)session.lastCompletedPhaseAgentsDispatched=new Set;if(session.qaSkipCount===void 0)session.qaSkipCount=0;if(!session.qaSkipTaskIds)session.qaSkipTaskIds=[];if(!session.taskWorkflowStates)session.taskWorkflowStates=new Map;if(!session.taskWorkflowCache)session.taskWorkflowCache=new Map;if(!session.stageBCompletion)session.stageBCompletion=new Map;if(!session.taskCouncilApproved)session.taskCouncilApproved=new Map;if(!session.pendingCouncilRequirements)session.pendingCouncilRequirements=new Map;if(session.lastGateOutcome===void 0)session.lastGateOutcome=null;if(session.declaredCoderScope===void 0)session.declaredCoderScope=null;if(session.lastScopeViolation===void 0)session.lastScopeViolation=null;if(!(session.modifiedFilesByTask instanceof Map)){if(session.modifiedFilesByTask=new Map,isValidTaskId2(session.currentTaskId)&&Array.isArray(session.modifiedFilesThisCoderTask)&&session.modifiedFilesThisCoderTask.length>0)session.modifiedFilesByTask.set(session.currentTaskId,[...new Set(session.modifiedFilesThisCoderTask)])}if(projectModifiedFilesForActiveTask(session),!session.reviewerScopeGenerations)session.reviewerScopeGenerations=new Map;if(session.reviewerScopeGenerationCounter===void 0)session.reviewerScopeGenerationCounter=0;if(!session.reviewerScopeIncarnation)session.reviewerScopeIncarnation=randomUUID13();if(!session.reviewerScopeLatestGenerationByTask)session.reviewerScopeLatestGenerationByTask=new Map;if(!session.reviewerScopeOwnershipHistory)session.reviewerScopeOwnershipHistory=new Map;if(session.scopeViolationDetected===void 0)session.scopeViolationDetected=!1;if(session.turboMode===void 0)session.turboMode=!1;if(session.turboStrategy===void 0)session.turboStrategy=void 0;if(session.leanTurboActive===void 0)session.leanTurboActive=!1;if(session.leanTurboCurrentPhase===void 0)session.leanTurboCurrentPhase=void 0;if(session.epicModeActive===void 0)session.epicModeActive=!1;if(session.qaGateSessionOverrides===void 0)session.qaGateSessionOverrides={};if(session.model_fallback_index===void 0)session.model_fallback_index=0;if(session.modelFallbackExhausted===void 0)session.modelFallbackExhausted=!1;if(session.loopDetectionWindow===void 0)session.loopDetectionWindow=[];if(session.pendingAdvisoryMessages===void 0)session.pendingAdvisoryMessages=[];if(session.coderRevisions===void 0)session.coderRevisions=0;if(session.revisionLimitHit===void 0)session.revisionLimitHit=!1;if(session.sessionRehydratedAt===void 0)session.sessionRehydratedAt=0;if(session.prmPatternCounts===void 0)session.prmPatternCounts=new Map;if(session.prmEscalationLevel===void 0)session.prmEscalationLevel=0;if(session.prmLastPatternDetected===void 0)session.prmLastPatternDetected=null;if(session.prmTrajectoryStep===void 0)session.prmTrajectoryStep=0;if(session.prmHardStopPending===void 0)session.prmHardStopPending=!1;if(session.prmHardStopInjectPending===void 0)session.prmHardStopInjectPending=!1;if(!session.prmInjectedAdvisoryKeys)session.prmInjectedAdvisoryKeys=new Set;if(!session.prmStruckEpisodes)session.prmStruckEpisodes=new Map;if(!session.prmLadderCounts)session.prmLadderCounts=new Map;if(session.executionEpisodeArmed===void 0)session.executionEpisodeArmed=!1;if(!session.prSubscriptions)session.prSubscriptions=new Map;return session.lastToolCallTime=now,maybeSweepStaleSessions(),session}if(_internals65.startAgentSession(sessionId,agentName??"unknown",7200000,directory),session=swarmState.agentSessions.get(sessionId),!session)throw Error(`Failed to create guardrail session for ${sessionId}`);return session}function recordSessionWorkspaceRoot(sessionId,laneRoot){let trimmed=laneRoot.trim();if(!trimmed)return;let session=swarmState.agentSessions.get(sessionId);if(!session)return;session.workspaceDirectory=trimmed}function resolveSessionWorkspaceDirectory(sessionId,fallbackDirectory){let recorded=swarmState.agentSessions.get(sessionId)?.workspaceDirectory;if(recorded?.trim())return recorded;return fallbackDirectory}function updateAgentEventTime(sessionId){let session=swarmState.agentSessions.get(sessionId);if(session)session.lastAgentEventTime=Date.now()}function beginInvocation(sessionId,agentName){let session=swarmState.agentSessions.get(sessionId);if(!session)throw Error(`Cannot begin invocation: session ${sessionId} does not exist`);let stripped=stripKnownSwarmPrefix(agentName),lastId=session.lastInvocationIdByAgent[stripped]||0;if(lastId>0)clearInvocationActionCircuits(sessionId,lastId),clearPendingTaskModelRoutesForSession(sessionId);let newId=lastId+1;if(session.lastInvocationIdByAgent[stripped]=newId,session.activeInvocationId=newId,session.nonTransientCircuit=createNonTransientCircuitState(stripped,newId),stripped===ORCHESTRATOR_NAME)return null;let now=Date.now(),window2={id:newId,agentName:stripped,startedAtMs:now,toolCalls:0,consecutiveErrors:0,hardLimitHit:!1,lastSuccessTimeMs:now,recentToolCalls:[],warningIssued:!1,warningReason:"",transientRetryCount:0},key=`${stripped}:${newId}`;return session.windows[key]=window2,pruneOldWindows(sessionId,86400000,50),window2}function getActiveWindow(sessionId){let session=swarmState.agentSessions.get(sessionId);if(!session||!session.windows)return;let key=`${stripKnownSwarmPrefix(session.agentName)}:${session.activeInvocationId}`;return session.windows[key]}function pruneOldWindows(sessionId,maxAgeMs=86400000,maxWindows=50){let session=swarmState.agentSessions.get(sessionId);if(!session||!session.windows)return;let now=Date.now(),toKeep=Object.entries(session.windows).filter(([_,window2])=>now-window2.startedAtMs<maxAgeMs).sort((a,b)=>b[1].startedAtMs-a[1].startedAtMs).slice(0,maxWindows);session.windows=Object.fromEntries(toKeep)}function recordPhaseAgentDispatch(sessionId,agentName){let session=swarmState.agentSessions.get(sessionId);if(!session)return;if(!session.phaseAgentsDispatched)session.phaseAgentsDispatched=new Set;let normalizedName=stripKnownSwarmPrefix(agentName);session.phaseAgentsDispatched.add(normalizedName)}function ensureModifiedFilesByTask(session){if(!(session.modifiedFilesByTask instanceof Map))session.modifiedFilesByTask=new Map;return session.modifiedFilesByTask}function projectModifiedFilesForActiveTask(session){let taskId=session.currentTaskId;session.modifiedFilesThisCoderTask=isValidTaskId2(taskId)&&session.modifiedFilesByTask instanceof Map?[...session.modifiedFilesByTask.get(taskId)??[]]:[]}function ensureModifiedFileTaskSlot(session,taskId){if(!isValidTaskId2(taskId))return!1;let entries=ensureModifiedFilesByTask(session);if(entries.has(taskId))return!0;while(entries.size>=MAX_TRACKED_TASK_FILE_ATTRIBUTIONS){let reclaimable=[...entries.keys()].find((candidate)=>candidate!==taskId&&session.taskWorkflowStates?.get(candidate)==="complete");if(!reclaimable)return!1;entries.delete(reclaimable)}return entries.set(taskId,[]),!0}function recordModifiedFilesForTask(session,taskId,files){if(!ensureModifiedFileTaskSlot(session,taskId))return!1;let normalized=[...new Set(files.filter((file2)=>typeof file2==="string"&&file2.length>0))];if(session.modifiedFilesByTask.set(taskId,normalized),session.currentTaskId===taskId)projectModifiedFilesForActiveTask(session);return!0}function recordModifiedFileForTask(session,taskId,file2){if(typeof file2!=="string"||file2.length===0)return!1;let existing=getModifiedFilesForTask(session,taskId);if(existing.includes(file2))return!0;return recordModifiedFilesForTask(session,taskId,[...existing,file2])}function getModifiedFilesForTask(session,taskId){if(!isValidTaskId2(taskId))return[];return[...ensureModifiedFilesByTask(session).get(taskId)??[]]}function resetModifiedFilesForTask(session,taskId,options){if(!isValidTaskId2(taskId))return!1;let entries=ensureModifiedFilesByTask(session);if(options?.remove)entries.delete(taskId);else{if(!ensureModifiedFileTaskSlot(session,taskId))return!1;entries.set(taskId,[])}if(session.currentTaskId===taskId)projectModifiedFilesForActiveTask(session);return!0}function completeModifiedFilesForTask(session,taskId){if(!session.epicModeActive)resetModifiedFilesForTask(session,taskId,{remove:!0})}function isValidTaskId2(taskId){if(taskId===null||taskId===void 0)return!1;if(typeof taskId!=="string")return!1;return taskId.trim().length>0}function ensureTaskWorkflowCache(session){if(!session.taskWorkflowCache)session.taskWorkflowCache=new Map;return session.taskWorkflowCache}function updateTaskWorkflowCache(session,taskId,overrides){let cache2=ensureTaskWorkflowCache(session),existing=cache2.get(taskId);cache2.set(taskId,{generation:overrides.generation??existing?.generation??0,retryCount:overrides.retryCount??existing?.retryCount??0,lastOutcome:overrides.lastOutcome??existing?.lastOutcome??"none",lastTransitionId:overrides.lastTransitionId??existing?.lastTransitionId??null,updatedAt:overrides.updatedAt??existing?.updatedAt??""})}function advanceTaskState(session,taskId,newState2,options,councilConfig){if(!isValidTaskId2(taskId))return;if(!session||!(session.taskWorkflowStates instanceof Map))throw Error("INVALID_SESSION: session.taskWorkflowStates must be a Map instance");let current=session.taskWorkflowStates.get(taskId)??"idle",currentIndex=LINEAR_STATE_ORDER.indexOf(current),newIndex=LINEAR_STATE_ORDER.indexOf(newState2);if(currentIndex===-1||newIndex===-1||newIndex<=currentIndex)throw Error(`INVALID_TASK_STATE_TRANSITION: ${taskId} ${current} → ${newState2}`);if(newState2==="complete"&¤t!=="tests_run"){let councilEntry=session.taskCouncilApproved?.get(taskId),effectiveMinimum=councilConfig?.requireAllMembers?5:councilConfig?.minimumMembers??3,councilApproved=councilEntry?.verdict==="APPROVE"&&(councilEntry.quorumSize??0)>=effectiveMinimum,pastPreCheck=currentIndex>=LINEAR_STATE_ORDER.indexOf("pre_check_passed");if(!councilApproved||!pastPreCheck)throw Error(`INVALID_TASK_STATE_TRANSITION: ${taskId} cannot reach complete from ${current} — must pass through tests_run first (or have council APPROVE after pre_check)`)}if(session.taskWorkflowStates.set(taskId,newState2),updateTaskWorkflowCache(session,taskId,{updatedAt:new Date().toISOString()}),newState2==="complete")session.stageBCompletion?.delete(taskId),completeModifiedFilesForTask(session,taskId);if(options?.emitTelemetry!==!1)telemetry.taskStateChanged(options?.telemetrySessionId??session.agentName,taskId,newState2,current)}function canAdvanceTaskState(session,taskId,newState2,councilConfig){if(!isValidTaskId2(taskId))return!1;if(!session||!(session.taskWorkflowStates instanceof Map))return!1;let current=session.taskWorkflowStates.get(taskId)??"idle",currentIndex=LINEAR_STATE_ORDER.indexOf(current),newIndex=LINEAR_STATE_ORDER.indexOf(newState2);if(currentIndex===-1||newIndex===-1||newIndex<=currentIndex)return!1;if(newState2==="complete"&¤t!=="tests_run"){let councilEntry=session.taskCouncilApproved?.get(taskId),effectiveMinimum=councilConfig?.requireAllMembers?5:councilConfig?.minimumMembers??3,councilApproved=councilEntry?.verdict==="APPROVE"&&(councilEntry.quorumSize??0)>=effectiveMinimum,pastPreCheck=currentIndex>=LINEAR_STATE_ORDER.indexOf("pre_check_passed");if(!councilApproved||!pastPreCheck)return!1}return!0}async function advanceTaskStateAndPersist(session,taskId,newState2,_directory,options,councilConfig){if(newState2==="coder_delegated"||newState2==="complete")throw Error(`TASK_WORKFLOW_CENTRAL_TRANSACTION_REQUIRED: ${taskId} → ${newState2} must use exact-task durable transition APIs`);advanceTaskState(session,taskId,newState2,options,councilConfig)}function getTaskState(session,taskId){if(!isValidTaskId2(taskId))return"idle";if(!session.taskWorkflowStates)session.taskWorkflowStates=new Map;return session.taskWorkflowStates.get(taskId)??"idle"}function recordStageBCompletion(session,taskId,agent){if(!isValidTaskId2(taskId))return;if(!session.stageBCompletion)session.stageBCompletion=new Map;let existing=session.stageBCompletion.get(taskId);if(existing)existing.add(agent);else session.stageBCompletion.set(taskId,new Set([agent]))}function hasBothStageBCompletions(session,taskId){if(!isValidTaskId2(taskId))return!1;let completions=session.stageBCompletion?.get(taskId);if(!completions)return!1;return completions.has("reviewer")&&completions.has("test_engineer")}async function isCouncilGateActive(directory,council,sessionOverrides={}){let enabled=council?.enabled===!0,plan=null;try{plan=await loadPlanJsonOnly(directory)}catch{plan=null}if(!plan)return!1;let planId=derivePlanId(plan),lookup=null;try{lookup=getProfileLookupForIdentity(directory,plan)}catch(err){let msg=err instanceof Error?err.message:String(err);if(!(msg.includes("SQLITE_CANTOPEN")||msg.includes("ENOENT")))warn(`[isCouncilGateActive] getProfile threw unexpectedly for plan ${planId}: ${msg}. Treating council as inactive.`);lookup=null}if(!lookup||lookup.kind==="missing")return!1;if(lookup.kind==="unbound_legacy")return enabled&&lookup.profile.gates.council_mode===!0;let profile=lookup.profile,councilMode=getEffectiveGates(profile,sessionOverrides).council_mode===!0;if(enabled&&councilMode)return!0;if(enabled!==councilMode&&!_councilDisagreementWarned.has(planId))_councilDisagreementWarned.add(planId),warn(`[delegation-gate] Council mode mismatch for plan ${planId}: pluginConfig.council.enabled=${enabled}, QaGates.council_mode=${councilMode}. Falling back to Stage B (non-council) per-task advancement.`);return!1}function _resetCouncilDisagreementWarnings(){_councilDisagreementWarned.clear()}function planStatusToWorkflowState(status){switch(status){case"in_progress":return"idle";case"completed":return"complete";case"blocked":return"blocked";case"closed":return"closed";default:return"idle"}}function evidenceToWorkflowState(evidence2){let snapshot=getTaskWorkflowSnapshot(evidence2);return{state:snapshot.state,generation:snapshot.generation,authoritative:snapshot.authoritative,retryCount:snapshot.retryCount,lastOutcome:snapshot.lastOutcome,lastTransitionId:snapshot.lastTransitionId,updatedAt:snapshot.updatedAt}}async function readPlanFromDisk(directory){try{let planPath=path83.join(directory,".swarm","plan.json"),content=await fs52.readFile(planPath,"utf-8"),parsed=JSON.parse(content);return PlanSchema.parse(parsed)}catch{return null}}async function readGateEvidenceFromDisk(directory){let evidenceMap=new Map;try{let evidenceDir=path83.join(directory,".swarm","evidence"),entries=await fs52.readdir(evidenceDir,{withFileTypes:!0});for(let entry of entries){if(!entry.isFile()||!entry.name.endsWith(".json"))continue;let taskId=entry.name.replace(/\.json$/,"");if(!/^\d+\.\d+(\.\d+)*$/.test(taskId))continue;try{let filePath=path83.join(evidenceDir,entry.name),content=await fs52.readFile(filePath,"utf-8"),parsed=parseTaskEvidence(content,taskId);evidenceMap.set(taskId,parsed)}catch{}}}catch{}return evidenceMap}async function buildRehydrationCache(directory){let planTaskStates=new Map,plan=await readPlanFromDisk(directory);if(plan)for(let phase of plan.phases??[])for(let task of phase.tasks??[])planTaskStates.set(task.id,planStatusToWorkflowState(task.status));let evidenceMap=await readGateEvidenceFromDisk(directory),councilConfig;try{councilConfig=loadPluginConfig(directory).council}catch{councilConfig=void 0}_rehydrationCache={planTaskStates,evidenceMap,taskIdentityContext:{plan,councilConfig}}}function applyRehydrationCache(session){if(!_rehydrationCache)return;if(!session.taskWorkflowStates)session.taskWorkflowStates=new Map;if(!session.taskWorkflowCache)session.taskWorkflowCache=new Map;if(!session.taskCouncilApproved)session.taskCouncilApproved=new Map;let{planTaskStates,evidenceMap,taskIdentityContext}=_rehydrationCache;for(let[taskId,planState]of planTaskStates){let existingState=session.taskWorkflowStates.get(taskId),existingCache=ensureTaskWorkflowCache(session).get(taskId),evidence2=evidenceMap.get(taskId);if(evidence2){let derivedWorkflow=evidenceToWorkflowState(evidence2);if(derivedWorkflow.authoritative){session.taskWorkflowStates.set(taskId,derivedWorkflow.state),updateTaskWorkflowCache(session,taskId,{generation:derivedWorkflow.generation,retryCount:derivedWorkflow.retryCount,lastOutcome:derivedWorkflow.lastOutcome,lastTransitionId:derivedWorkflow.lastTransitionId,updatedAt:derivedWorkflow.updatedAt});continue}}if((existingCache?.generation??0)>0)continue;if(existingState==null||compareWorkflowStatePrecedence(planState,existingState)>0)session.taskWorkflowStates.set(taskId,planState)}let VALID_COUNCIL_VERDICTS=new Set(["APPROVE","REJECT","CONCERNS"]);for(let[taskId,evidence2]of evidenceMap){let council=evidence2.gates?.council;if(!council){session.taskCouncilApproved.delete(taskId);continue}let rawIdentityDigest=council.identity_digest;if(typeof rawIdentityDigest!=="string"||!/^[a-f0-9]{64}$/.test(rawIdentityDigest)){session.taskCouncilApproved.delete(taskId);continue}let expectedIdentity=computeCouncilReviewIdentity({level:"task",scope:{kind:"task",taskId},plan:taskIdentityContext.plan,config:taskIdentityContext.councilConfig});if(rawIdentityDigest!==expectedIdentity.identityDigest){session.taskCouncilApproved.delete(taskId);continue}let councilWorkflow=getTaskWorkflowSnapshot(evidence2);if(!councilWorkflow.authoritative||council.workflowGeneration!==councilWorkflow.generation||councilWorkflow.state!=="pre_check_passed"){session.taskCouncilApproved.delete(taskId);continue}let rawVerdict=council.verdict;if(!rawVerdict||typeof rawVerdict!=="string")continue;if(!VALID_COUNCIL_VERDICTS.has(rawVerdict))continue;let verdict=rawVerdict,roundNumber=council.roundNumber;if(typeof roundNumber!=="number"||!Number.isFinite(roundNumber))roundNumber=1;let rawQuorumSize=council.quorumSize,quorumSize=typeof rawQuorumSize==="number"&&Number.isFinite(rawQuorumSize)&&rawQuorumSize>=1?rawQuorumSize:1;session.taskCouncilApproved.set(taskId,{verdict,roundNumber,quorumSize})}}async function rehydrateSessionFromDisk(directory,session){await _internals65.buildRehydrationCache(directory),_internals65.applyRehydrationCache(session)}function hasActiveTurboMode(sessionID){if(sessionID)return swarmState.agentSessions.get(sessionID)?.turboMode===!0;for(let[_sessionId,session]of swarmState.agentSessions)if(session.turboMode===!0)return!0;return!1}function hasActiveFullAuto(sessionID){if(sessionID)return swarmState.agentSessions.get(sessionID)?.fullAutoMode===!0;for(let[_sessionId,session]of swarmState.agentSessions)if(session.fullAutoMode===!0)return!0;return!1}function getActiveFullAutoSessionID(){let activeId,activeLastToolCall=-1;for(let[id,session]of swarmState.agentSessions){if(session.fullAutoMode!==!0)continue;let lastToolCall=session.lastToolCallTime??0;if(activeId===void 0||lastToolCall>activeLastToolCall)activeId=id,activeLastToolCall=lastToolCall}return activeId}function hasActiveLeanTurbo(sessionID){if(sessionID){let session=swarmState.agentSessions.get(sessionID);return session?.turboMode===!0&&session?.turboStrategy==="lean"&&session?.leanTurboActive===!0}for(let[_sessionId,session]of swarmState.agentSessions)if(session.turboMode===!0&&session.turboStrategy==="lean"&&session.leanTurboActive===!0)return!0;return!1}function hasActiveEpicMode(sessionID){if(sessionID)return swarmState.agentSessions.get(sessionID)?.epicModeActive===!0;for(let[_sessionId,session]of swarmState.agentSessions)if(session.epicModeActive===!0)return!0;return!1}function getResolvedAutoProceed(session,planAutoProceed){return session.autoProceedOverride??planAutoProceed??!1}function setSessionEnvironment(sessionId,profile){swarmState.environmentProfiles.set(sessionId,profile)}function getSessionEnvironment(sessionId){return swarmState.environmentProfiles.get(sessionId)}function ensureSessionEnvironment(sessionId){let existing=swarmState.environmentProfiles.get(sessionId);if(existing)return existing;let profile=detectEnvironmentProfile();return swarmState.environmentProfiles.set(sessionId,profile),Promise.resolve().then(() => (init_telemetry(),exports_telemetry)).then(({telemetry:telemetry2})=>{telemetry2.environmentDetected(sessionId,profile.hostOS,profile.shellFamily,profile.executionMode)}).catch(()=>{}),profile}function setLiveContextWindow(sessionID,tokens,identity){if(!sessionID)return;let map2=swarmState.liveContextWindows,modelID=trimLiveContextIdentity(identity?.modelID),providerID=trimLiveContextIdentity(identity?.providerID),hasIdentity=Boolean(modelID||providerID),existing=map2.get(sessionID);if(!(typeof tokens==="number"&&Number.isFinite(tokens)&&tokens>=1)){if(!hasIdentity)return;if(existing&&liveContextIdentityMatches(existing,{modelID,providerID})&&existing.tokens!==void 0)return;if(map2.has(sessionID))map2.delete(sessionID);map2.set(sessionID,{modelID,providerID}),evictOldestLiveContextWindow(map2,sessionID);return}if(!hasIdentity&&existing&&(existing.modelID||existing.providerID))return;if(map2.has(sessionID))map2.delete(sessionID);map2.set(sessionID,{tokens:Math.floor(tokens),modelID,providerID}),evictOldestLiveContextWindow(map2,sessionID)}function getLiveContextWindow(sessionID,identity){if(!sessionID)return;let cached2=swarmState.liveContextWindows.get(sessionID);if(!cached2)return;if(identity&&!liveContextIdentityMatches(cached2,identity))return;return cached2.tokens}function getLiveContextModelIdentity(sessionID){if(!sessionID)return;let cached2=swarmState.liveContextWindows.get(sessionID);if(!cached2)return;return{modelID:cached2.modelID,providerID:cached2.providerID}}function evictOldestLiveContextWindow(map2,sessionID){if(map2.size<=MAX_TRACKED_CONTEXT_WINDOWS)return;let oldest=map2.keys().next().value;if(oldest!==void 0&&oldest!==sessionID)map2.delete(oldest)}function trimLiveContextIdentity(value){let trimmed=value?.trim();return trimmed?trimmed:void 0}function normalizeLiveContextIdentity(value){return trimLiveContextIdentity(value)?.toLowerCase()??""}function liveContextIdentityMatches(left,right){return normalizeLiveContextIdentity(left.modelID)===normalizeLiveContextIdentity(right.modelID)&&normalizeLiveContextIdentity(left.providerID)===normalizeLiveContextIdentity(right.providerID)}function setSessionBudget(sessionID,pct,tokens){let map2=swarmState.lastBudgetBySession;if(map2.has(sessionID))map2.delete(sessionID);if(map2.set(sessionID,{pct,tokens}),map2.size>MAX_TRACKED_BUDGET_SESSIONS){let oldest=map2.keys().next().value;if(oldest!==void 0&&oldest!==sessionID)map2.delete(oldest)}}function getSessionBudgetPct(sessionID){if(!sessionID)return 0;return swarmState.lastBudgetBySession.get(sessionID)?.pct??0}function getSessionBudgetTokens(sessionID){if(!sessionID)return 0;return swarmState.lastBudgetBySession.get(sessionID)?.tokens??0}function getDisplayBudget(){let best=null;for(let entry of swarmState.lastBudgetBySession.values())if(entry.pct>0&&(best===null||entry.pct>best.pct))best=entry;return best}function setCriticalShownIds(sessionID,value){let map2=swarmState.currentCriticalShownIds;if(map2.has(sessionID))map2.delete(sessionID);if(map2.set(sessionID,value),map2.size>MAX_TRACKED_CRITICAL_SHOWN){let oldest=map2.keys().next().value;if(oldest!==void 0&&oldest!==sessionID)map2.delete(oldest)}}function clearCriticalShownIds(sessionID){return swarmState.currentCriticalShownIds.delete(sessionID)}function buildGateDenialDirectiveKey(ids){return[...ids].sort().join(",")}function incrementGateDenialCount(sessionID,directiveKey){let map2=swarmState.gateDenialCounts,existing=map2.get(sessionID),count=existing&&existing.directiveKey===directiveKey?existing.count+1:1;if(map2.has(sessionID))map2.delete(sessionID);if(map2.set(sessionID,{count,directiveKey}),map2.size>MAX_TRACKED_GATE_DENIALS){let oldest=map2.keys().next().value;if(oldest!==void 0&&oldest!==sessionID)map2.delete(oldest)}return count}function clearGateDenialCount(sessionID){swarmState.gateDenialCounts.delete(sessionID)}function addKnowledgeAckDedup(key){let set2=swarmState.knowledgeAckDedup;if(set2.has(key))return;if(set2.add(key),set2.size>MAX_TRACKED_KNOWLEDGE_ACKS){let oldest=set2.values().next().value;if(oldest!==void 0)set2.delete(oldest)}}async function rehydratePrSubscriptions(sessionID,directory){let map2=new Map;try{let{listActive:listActive2}=await Promise.resolve().then(() => (init_pr_subscriptions(),exports_pr_subscriptions)),records=await listActive2(directory);for(let record2 of records){if(record2.sessionID!==sessionID)continue;let key=`${record2.repoFullName}::${record2.prNumber}`;map2.set(key,{prNumber:record2.prNumber,repoFullName:record2.repoFullName,prUrl:record2.prUrl,lastKnownStatus:record2.mergeableState??"unknown",lastPollTime:record2.lastCheckedAt,errorCount:record2.errorCount,isWatching:record2.isWatching})}}catch(err){warn(`[state] rehydratePrSubscriptions failed for session ${sessionID}: ${err instanceof Error?err.message:String(err)}`)}return map2}var _rehydrationCache=null,_councilDisagreementWarned,MAX_TRACKED_TASK_FILE_ATTRIBUTIONS=128,LINEAR_STATE_ORDER,_toolAggregates,defaultRunContext,_runContexts,swarmState,STALE_SESSION_TTL_MS=7200000,MAX_REVIEWER_SCOPE_GENERATION_FILES=256,MAX_REVIEWER_SCOPE_GENERATIONS=256,MAX_REVIEWER_SCOPE_OWNERSHIP_HISTORY=256,REVIEWER_SCOPE_GENERATION_TTL_MS,IDLE_SWEEP_COOLDOWN_MS=60000,_lastIdleSweepAtMs=0,MAX_TRACKED_BUDGET_SESSIONS=500,MAX_TRACKED_CRITICAL_SHOWN=500,MAX_TRACKED_KNOWLEDGE_ACKS=5000,MAX_TRACKED_GATE_DENIALS=500,MAX_TRACKED_CONTEXT_WINDOWS=500,_internals65;var init_state2=__esm(()=>{init_constants();init_loader();init_plan_schema();init_schema();init_council_review_identity();init_qa_gate_profile();init_action_circuit();init_gate_evidence();init_delegation_gate();init_realtime_learning_nudge();init_trajectory_step_state();init_candidate_queue();init_prm_pattern_support();init_task_model_routing();init_manager();init_utils3();init_trajectory_store();init_scope_binding();init_scope_persistence();init_session_start_store();init_worktree_link_suggestion();init_telemetry();init_logger();_councilDisagreementWarned=new Set,LINEAR_STATE_ORDER=["idle","coder_delegated","pre_check_passed","reviewer_run","tests_run","complete"];_toolAggregates=new Map,defaultRunContext=new AgentRunContext("default",_toolAggregates),_runContexts=new Map;swarmState={activeToolCalls:defaultRunContext.activeToolCalls,toolAggregates:defaultRunContext.toolAggregates,activeAgent:defaultRunContext.activeAgent,delegationChains:defaultRunContext.delegationChains,pendingEvents:0,opencodeClient:null,curatorInitAgentNames:[],curatorPhaseAgentNames:[],curatorPostmortemAgentNames:[],curatorConsolidationAgentNames:[],skillImproverAgentNames:[],specWriterAgentNames:[],currentCriticalShownIds:new Map,knowledgeAckDedup:new Set,gateDenialCounts:new Map,generatedAgentNames:[],lastBudgetBySession:new Map,liveContextWindows:new Map,agentSessions:defaultRunContext.agentSessions,pendingRehydrations:new Set,fullAutoEnabledInConfig:!1,environmentProfiles:defaultRunContext.environmentProfiles};REVIEWER_SCOPE_GENERATION_TTL_MS=STALE_SESSION_TTL_MS;_internals65={swarmState,resetSwarmState,ensureAgentSession,startAgentSession,getAgentSession,beginInvocation,getActiveWindow,advanceTaskState,getTaskState,hasActiveFullAuto,hasActiveTurboMode,hasActiveLeanTurbo,hasActiveEpicMode,buildRehydrationCache,applyRehydrationCache,rehydrateSessionFromDisk,isCouncilGateActive,defaultRunContext}});import{createHash as createHash34,randomUUID as randomUUID14}from"node:crypto";import{readFileSync as readFileSync28}from"node:fs";import*as fsp4 from"node:fs/promises";import*as path84 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_exports2.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_exports2.classifyPrWorkflowGitStateAsync(directory,{ignoredPaths:[path84.join(".swarm",workflowCheckoutMutationLockRelativePath()),path84.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:randomUUID14(),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 fsp4.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,path84.join(WORKFLOW_GATE_DIR,entry.name)),state=await readPrWorkflowGateStateFileFromDisk(statePath,entry.name);if(!state)continue;let expectedName=path84.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 fsp4.rm(workflowGateStatePath(directory,normalizedSessionID),{force:!0})}catch(error49){if(error49.code!=="ENOENT")throw error49}trackedStatesByProjectSession.delete(stateCacheKey(directory,normalizedSessionID))})}function isLiveSessionStatusType(type){return LIVE_SESSION_STATUS_TYPES.has(type)}async function probeAlivePrWorkflowLaneSessions(directory,records){let session=_test_exports2.getSessionOps(),statusOp=session?.status;if(!session||typeof statusOp!=="function")return{alive:new Set,degradedReason:"probe-unavailable"};let timeoutError=Error("PR workflow lane liveness probe exceeded its deadline"),response;try{response=await withTimeout((async()=>statusOp.call(session,{query:{directory}}))(),_test_exports2.laneLivenessProbeTimeoutMs,timeoutError)}catch(error49){return{alive:new Set,degradedReason:error49===timeoutError?"probe-timeout":"probe-error"}}try{if(response?.error)return{alive:new Set,degradedReason:"probe-error"};let data=response?.data;if(data===null||data===void 0)return{alive:new Set,degradedReason:"probe-no-data"};let accumulated=new Set;for(let record2 of records){let subagentSessionId=record2.subagentSessionId;if(!subagentSessionId)continue;let type=data[subagentSessionId]?.type;if(typeof type==="string"&&isLiveSessionStatusType(type))accumulated.add(subagentSessionId)}return{alive:accumulated}}catch{return{alive:new Set,degradedReason:"probe-error"}}}function describePrWorkflowLaneProbe(settlement){let parts=[];if(settlement.probedAliveLaneIds?.length)parts.push(`liveness probe reports still running: ${settlement.probedAliveLaneIds.slice(0,MAX_DISCLOSED_LANE_IDS).join(", ")}`);if(settlement.probeDegradedReason)parts.push(`liveness probe degraded (${settlement.probeDegradedReason})`);return parts.length>0?` (${parts.join("; ")})`:""}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(),open5=[],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 open5.push(record2)}if(presumedStale.length===0)return{openLaneIds:open5.map(prWorkflowLaneLabel),openLanes:open5.length,freshOpenLanes:open5.length,presumedStaleLaneIds:[]};let probe2;try{probe2=await _test_exports2.probeLaneLivenessAsync(directory,presumedStale)}catch{probe2={alive:new Set,degradedReason:"probe-error"}}let probeRetained=[],settled=[];for(let record2 of presumedStale)if(record2.subagentSessionId&&probe2.alive.has(record2.subagentSessionId))probeRetained.push(record2);else settled.push(record2);let probedAliveLaneIds=probeRetained.map(prWorkflowLaneLabel),openLaneIds=[...open5.map(prWorkflowLaneLabel),...probedAliveLaneIds],retentionDisclosure=probeRetained.length>0?`${probeRetained.length} lane(s) past the horizon retained: liveness probe reports still running: ${probedAliveLaneIds.slice(0,MAX_DISCLOSED_LANE_IDS).join(", ")}`:void 0,retentionFields={...probedAliveLaneIds.length>0?{probedAliveLaneIds,probeRetainedCorrelationIds:probeRetained.map((record2)=>record2.correlationId)}:{},...probe2.degradedReason?{probeDegradedReason:probe2.degradedReason}:{}};if(settled.length===0)return{openLaneIds,openLanes:openLaneIds.length,freshOpenLanes:open5.length,presumedStaleLaneIds:[],...retentionFields,disclosure:retentionDisclosure};let presumedStaleLaneIds=settled.map(prWorkflowLaneLabel),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(", ")}`+(probe2.degradedReason?`; settled despite liveness probe failure (${probe2.degradedReason})`:"; liveness probe found no live session")+(retentionDisclosure?`; ${retentionDisclosure}`:"");try{await _test_exports2.sweepStaleDelegationsAsync(directory,PR_WORKFLOW_STALE_LANE_TIMEOUT_MS,{statuses:PR_WORKFLOW_SWEEPABLE_LANE_STATUSES,excludeCorrelationIds:new Set(probeRetained.map((record2)=>record2.correlationId))})}catch{}try{await fsp4.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,probeStatus:probe2.degradedReason??"ok",probedAliveLanes:probedAliveLaneIds.slice(0,MAX_DISCLOSED_LANE_IDS),disclosure})}
|
|
876
|
+
`,"utf-8")}async function subscribe(directory,input){if(!directory||directory.trim()==="")throw Error("directory is required");if(!input.sessionID||input.sessionID.trim()==="")throw Error("sessionID is required and must be non-empty");if(!input.repoFullName||input.repoFullName.trim()==="")throw Error("repoFullName is required and must be non-empty");if(!input.prUrl||input.prUrl.trim()==="")throw Error("prUrl is required and must be non-empty");if(!input.prNumber||!Number.isInteger(input.prNumber)||input.prNumber<=0)throw Error("prNumber is required and must be a positive integer");let correlationId=buildCorrelationId(input.sessionID,input.repoFullName,input.prNumber),now=Date.now();return withEvidenceLock(directory,PR_SUBSCRIPTIONS_FILE,STORE_LOCK_AGENT2,STORE_LOCK_TASK2,async()=>{let existing=readAllRecords(directory),match=existing.find((r)=>r.correlationId===correlationId&&r.status==="active");if(match)return onSubscriptionCreated?.(directory,match),match;if(input.maxSubscriptions!==void 0&&input.maxSubscriptions>0){let activeCount=existing.filter((r)=>r.status==="active").length;if(activeCount>=input.maxSubscriptions)throw Error(`PR subscription limit reached: ${activeCount}/${input.maxSubscriptions}`)}let record2={correlationId,sessionID:input.sessionID,prNumber:input.prNumber,repoFullName:input.repoFullName,prUrl:input.prUrl,lastCheckedAt:now,isWatching:!0,hasUnaddressedEvents:!1,status:"active",createdAt:now,updatedAt:now,errorCount:0};return appendRecord3(directory,record2),onSubscriptionCreated?.(directory,record2),record2})}async function unsubscribe(directory,correlationId){if(!correlationId)return null;return withEvidenceLock(directory,PR_SUBSCRIPTIONS_FILE,STORE_LOCK_AGENT2,STORE_LOCK_TASK2,async()=>{let match=readAllRecords(directory).find((r)=>r.correlationId===correlationId&&r.status==="active");if(!match)return null;let now=Date.now(),removed={...match,status:"removed",isWatching:!1,updatedAt:now};return appendRecord3(directory,removed),removed})}async function listActive(directory){return readAllRecords(directory).filter((r)=>r.status==="active")}async function lookupByPr(directory,repoFullName,prNumber){for(let record2 of readAllRecords(directory))if(record2.status==="active"&&record2.repoFullName===repoFullName&&record2.prNumber===prNumber)return record2;return null}async function updateSnapshot(directory,correlationId,updates){if(!correlationId)return null;return withEvidenceLock(directory,PR_SUBSCRIPTIONS_FILE,STORE_LOCK_AGENT2,STORE_LOCK_TASK2,async()=>{let match=readAllRecords(directory).find((r)=>r.correlationId===correlationId&&r.status==="active");if(!match)return null;let updated={...match,...updates,correlationId,sessionID:match.sessionID,repoFullName:match.repoFullName,prNumber:match.prNumber,prUrl:match.prUrl,createdAt:match.createdAt,updatedAt:Date.now()};return appendRecord3(directory,updated),updated})}async function sweepStale(directory,ttlDays,mergedPrs){if(!ttlDays||ttlDays<=0)return 0;let ttlMs=ttlDays*86400000,now=Date.now();try{return await withEvidenceLock(directory,PR_SUBSCRIPTIONS_FILE,STORE_LOCK_AGENT2,STORE_LOCK_TASK2,async()=>{let swept=0;for(let record2 of readAllRecords(directory)){if(record2.status!=="active")continue;let prKey=`${record2.repoFullName}::${record2.prNumber}`,isMerged=mergedPrs?.has(prKey)??!1,isStale=now-record2.updatedAt>ttlMs;if(isMerged){appendRecord3(directory,{...record2,status:"expired",isWatching:!1,updatedAt:now}),swept+=1,log(`[pr-monitor] Swept subscription: merged/closed: ${prKey}`);continue}if(isStale&&!record2.hasUnaddressedEvents)appendRecord3(directory,{...record2,status:"expired",isWatching:!1,updatedAt:now}),swept+=1,log(`[pr-monitor] Swept subscription: stale (TTL ${ttlDays}d): ${prKey}`)}return swept})}catch(err){return log(`[pr-monitor] sweepStale failed: ${err instanceof Error?err.message:String(err)}`),0}}var PR_SUBSCRIPTIONS_FILE="pr-monitor/subscriptions.jsonl",STORE_LOCK_AGENT2="pr-monitor",STORE_LOCK_TASK2="pr-subscriptions",onSubscriptionCreated=null,RecordSchema2;var init_pr_subscriptions=__esm(()=>{init_zod();init_lock();init_utils2();init_utils();RecordSchema2=exports_external.object({correlationId:exports_external.string().min(1),sessionID:exports_external.string().min(1),prNumber:exports_external.number().int().positive(),repoFullName:exports_external.string().regex(/^[^/]+\/[^/]+$/,"Must be owner/repo format"),prUrl:exports_external.string().min(1).regex(/^https:\/\/github\.com\/[^/]+\/[^/]+\/pull\/\d+$/,"Must be a valid GitHub PR URL"),headRefOid:exports_external.string().optional(),lastCheckedAt:exports_external.number(),lastCommentId:exports_external.string().optional(),lastCheckRunSet:exports_external.string().optional(),mergeableState:exports_external.string().optional(),mergeGroupRunStatus:exports_external.string().optional(),mergeGroupRunConclusion:exports_external.string().optional(),mergeGroupRunHtmlUrl:exports_external.string().optional(),isWatching:exports_external.boolean(),hasUnaddressedEvents:exports_external.boolean(),status:exports_external.enum(["active","removed","expired"]),createdAt:exports_external.number(),updatedAt:exports_external.number(),errorCount:exports_external.number().int().min(0),customPollIntervalSeconds:exports_external.number().int().positive().optional(),customFailureThreshold:exports_external.number().int().min(0).optional(),customCooldownSeconds:exports_external.number().int().min(0).optional()}).strict()});var exports_state={};__export(exports_state,{updateTaskWorkflowCache:()=>updateTaskWorkflowCache,updateAgentEventTime:()=>updateAgentEventTime,takeReviewerScopeGeneration:()=>takeReviewerScopeGeneration,sweepStaleSessions:()=>sweepStaleSessions,swarmState:()=>swarmState,startReviewerScopeGeneration:()=>startReviewerScopeGeneration,startAgentSession:()=>startAgentSession,settleReviewerScopeMergeback:()=>settleReviewerScopeMergeback,setSessionEnvironment:()=>setSessionEnvironment,setSessionBudget:()=>setSessionBudget,setLiveContextWindow:()=>setLiveContextWindow,setCriticalShownIds:()=>setCriticalShownIds,reviewerScopeGenerationHasDeclaredOverlap:()=>reviewerScopeGenerationHasDeclaredOverlap,resolveSessionWorkspaceDirectory:()=>resolveSessionWorkspaceDirectory,resetSwarmStatePreservingSingletons:()=>resetSwarmStatePreservingSingletons,resetSwarmState:()=>resetSwarmState,resetModifiedFilesForTask:()=>resetModifiedFilesForTask,rehydrateSessionFromDisk:()=>rehydrateSessionFromDisk,rehydratePrSubscriptions:()=>rehydratePrSubscriptions,recordStageBCompletion:()=>recordStageBCompletion,recordSessionWorkspaceRoot:()=>recordSessionWorkspaceRoot,recordReviewerScopeGenerationFileFingerprint:()=>recordReviewerScopeGenerationFileFingerprint,recordReviewerScopeGenerationFile:()=>recordReviewerScopeGenerationFile,recordReviewerScopeGenerationCaptureFailure:()=>recordReviewerScopeGenerationCaptureFailure,recordPhaseAgentDispatch:()=>recordPhaseAgentDispatch,recordModifiedFilesForTask:()=>recordModifiedFilesForTask,recordModifiedFileForTask:()=>recordModifiedFileForTask,pruneOldWindows:()=>pruneOldWindows,peekReviewerScopeGenerationClaim:()=>peekReviewerScopeGenerationClaim,peekReviewerScopeGenerationByStatus:()=>peekReviewerScopeGenerationByStatus,peekReadyReviewerScopeGeneration:()=>peekReadyReviewerScopeGeneration,maybeSweepStaleSessions:()=>maybeSweepStaleSessions,markReviewerScopeGenerationReady:()=>markReviewerScopeGenerationReady,markReviewerScopeGenerationNoChange:()=>markReviewerScopeGenerationNoChange,markReviewerScopeGenerationMergebackPending:()=>markReviewerScopeGenerationMergebackPending,isReviewerScopeGenerationCurrent:()=>isReviewerScopeGenerationCurrent,isCouncilGateActive:()=>isCouncilGateActive,incrementGateDenialCount:()=>incrementGateDenialCount,hasBothStageBCompletions:()=>hasBothStageBCompletions,hasActiveTurboMode:()=>hasActiveTurboMode,hasActiveLeanTurbo:()=>hasActiveLeanTurbo,hasActiveFullAuto:()=>hasActiveFullAuto,hasActiveEpicMode:()=>hasActiveEpicMode,getTaskState:()=>getTaskState,getSessionEnvironment:()=>getSessionEnvironment,getSessionBudgetTokens:()=>getSessionBudgetTokens,getSessionBudgetPct:()=>getSessionBudgetPct,getRunContext:()=>getRunContext,getReviewerScopeOwnershipHistory:()=>getReviewerScopeOwnershipHistory,getReviewerScopeGenerationForCoderCall:()=>getReviewerScopeGenerationForCoderCall,getResolvedAutoProceed:()=>getResolvedAutoProceed,getModifiedFilesForTask:()=>getModifiedFilesForTask,getLiveContextWindow:()=>getLiveContextWindow,getLiveContextModelIdentity:()=>getLiveContextModelIdentity,getDisplayBudget:()=>getDisplayBudget,getAgentSession:()=>getAgentSession,getActiveWindow:()=>getActiveWindow,getActiveFullAutoSessionID:()=>getActiveFullAutoSessionID,ensureSessionEnvironment:()=>ensureSessionEnvironment,ensureAgentSession:()=>ensureAgentSession,endAgentSession:()=>endAgentSession,discardReviewerScopeGenerationForCoderCall:()=>discardReviewerScopeGenerationForCoderCall,discardReviewerScopeGenerationClaim:()=>discardReviewerScopeGenerationClaim,defaultRunContext:()=>defaultRunContext,completeModifiedFilesForTask:()=>completeModifiedFilesForTask,clearGateDenialCount:()=>clearGateDenialCount,clearCriticalShownIds:()=>clearCriticalShownIds,claimReviewerScopeGeneration:()=>claimReviewerScopeGeneration,canAdvanceTaskState:()=>canAdvanceTaskState,buildRehydrationCache:()=>buildRehydrationCache,buildGateDenialDirectiveKey:()=>buildGateDenialDirectiveKey,beginInvocation:()=>beginInvocation,attachReviewerScopeGenerationDispatchSnapshot:()=>attachReviewerScopeGenerationDispatchSnapshot,applyRehydrationCache:()=>applyRehydrationCache,advanceTaskStateAndPersist:()=>advanceTaskStateAndPersist,advanceTaskState:()=>advanceTaskState,addKnowledgeAckDedup:()=>addKnowledgeAckDedup,_resetCouncilDisagreementWarnings:()=>_resetCouncilDisagreementWarnings,_internals:()=>_internals65,REVIEWER_SCOPE_GENERATION_TTL_MS:()=>REVIEWER_SCOPE_GENERATION_TTL_MS,MAX_TRACKED_TASK_FILE_ATTRIBUTIONS:()=>MAX_TRACKED_TASK_FILE_ATTRIBUTIONS,MAX_TRACKED_KNOWLEDGE_ACKS:()=>MAX_TRACKED_KNOWLEDGE_ACKS,MAX_TRACKED_GATE_DENIALS:()=>MAX_TRACKED_GATE_DENIALS,MAX_TRACKED_CRITICAL_SHOWN:()=>MAX_TRACKED_CRITICAL_SHOWN,MAX_TRACKED_CONTEXT_WINDOWS:()=>MAX_TRACKED_CONTEXT_WINDOWS,MAX_TRACKED_BUDGET_SESSIONS:()=>MAX_TRACKED_BUDGET_SESSIONS,MAX_REVIEWER_SCOPE_OWNERSHIP_HISTORY:()=>MAX_REVIEWER_SCOPE_OWNERSHIP_HISTORY,MAX_REVIEWER_SCOPE_GENERATION_FILES:()=>MAX_REVIEWER_SCOPE_GENERATION_FILES,MAX_REVIEWER_SCOPE_GENERATIONS:()=>MAX_REVIEWER_SCOPE_GENERATIONS,AgentRunContext:()=>AgentRunContext});import{randomUUID as randomUUID13}from"node:crypto";import*as fs52 from"node:fs/promises";import*as path83 from"node:path";function compareWorkflowStatePrecedence(left,right){return compareTaskWorkflowStateRank(left,right)}function cloneReviewerScopeGeneration(generation){return{...generation,declaredFiles:[...generation.declaredFiles],modifiedFiles:[...generation.modifiedFiles],modifiedFileFingerprints:generation.modifiedFileFingerprints.map((entry)=>({...entry})),captureFailures:generation.captureFailures.map((entry)=>({...entry})),reviewerDispatchScope:generation.reviewerDispatchScope?{...generation.reviewerDispatchScope,files:[...generation.reviewerDispatchScope.files]}:void 0}}function cloneReviewerScopeOwnershipTombstone(tombstone){return{...tombstone,declaredFiles:[...tombstone.declaredFiles],modifiedFiles:[...tombstone.modifiedFiles],modifiedFileFingerprints:tombstone.modifiedFileFingerprints.map((fingerprint2)=>({...fingerprint2}))}}function createNonTransientCircuitState(agentName,invocationId){return{ownerAgent:stripKnownSwarmPrefix(agentName),ownerInvocationId:invocationId,category:null,sameCategoryCount:0,hardStop:!1,lastSignal:null}}function getRunContext(runId){if(!runId)return defaultRunContext;return _runContexts.get(runId)??defaultRunContext}function resetSwarmState(){swarmState.activeToolCalls.clear(),swarmState.toolAggregates.clear(),swarmState.activeAgent.clear(),swarmState.delegationChains.clear(),swarmState.pendingEvents=0,swarmState.lastBudgetBySession.clear(),swarmState.liveContextWindows.clear(),swarmState.agentSessions.clear(),_lastIdleSweepAtMs=0,clearTrajectoryCache(),clearTrajectoryStepCounters(),swarmState.pendingRehydrations.clear(),swarmState.opencodeClient=null,swarmState.curatorInitAgentNames=[],swarmState.curatorPhaseAgentNames=[],swarmState.curatorPostmortemAgentNames=[],swarmState.curatorConsolidationAgentNames=[],swarmState.skillImproverAgentNames=[],swarmState.specWriterAgentNames=[],swarmState.currentCriticalShownIds.clear(),swarmState.knowledgeAckDedup.clear(),swarmState.gateDenialCounts.clear(),swarmState.generatedAgentNames=[],_rehydrationCache=null,swarmState.fullAutoEnabledInConfig=!1,swarmState.environmentProfiles.clear(),clearAllActionCircuits(),clearAllTaskModelRoutingState(),clearPendingCoderScope();for(let binding of clearScopeBindings())clearScopeBindingFromDisk({directory:binding.workspaceIdentity,binding});resetStandardWorktreeIsolationState(),resetRealtimeLearningNudgeState(),_councilDisagreementWarned.clear()}function resetSwarmStatePreservingSingletons(){let{opencodeClient:preservedOpencodeClient,fullAutoEnabledInConfig:preservedFullAutoEnabledInConfig,curatorInitAgentNames:preservedCuratorInitAgentNames,curatorPhaseAgentNames:preservedCuratorPhaseAgentNames,curatorPostmortemAgentNames:preservedCuratorPostmortemAgentNames,curatorConsolidationAgentNames:preservedCuratorConsolidationAgentNames,skillImproverAgentNames:preservedSkillImproverAgentNames,specWriterAgentNames:preservedSpecWriterAgentNames,generatedAgentNames:preservedGeneratedAgentNames}=swarmState;resetSwarmState(),swarmState.opencodeClient=preservedOpencodeClient,swarmState.fullAutoEnabledInConfig=preservedFullAutoEnabledInConfig,swarmState.curatorInitAgentNames=preservedCuratorInitAgentNames,swarmState.curatorPhaseAgentNames=preservedCuratorPhaseAgentNames,swarmState.curatorPostmortemAgentNames=preservedCuratorPostmortemAgentNames,swarmState.curatorConsolidationAgentNames=preservedCuratorConsolidationAgentNames,swarmState.skillImproverAgentNames=preservedSkillImproverAgentNames,swarmState.specWriterAgentNames=preservedSpecWriterAgentNames,swarmState.generatedAgentNames=preservedGeneratedAgentNames}function isBoundedGenerationValue(value,maxLength){return value.length>0&&value.length<=maxLength&&!Array.from(value).some((char)=>{let code=char.charCodeAt(0);return code<=31||code===127})}function reviewerScopeGenerationKey(taskId,coderCallID,generation){return`${taskId}\x00${coderCallID}\x00${generation}`}function reviewerScopeOwnershipKey(taskId,coderCallID,generation,sessionIncarnation){return`${taskId}\x00${coderCallID}\x00${generation}\x00${sessionIncarnation}`}function ensureReviewerScopeGenerationState(session){return session.reviewerScopeGenerations??=new Map,session.reviewerScopeGenerationCounter??=0,session.reviewerScopeIncarnation??=randomUUID13(),session.reviewerScopeLatestGenerationByTask??=new Map,session.reviewerScopeOwnershipHistory??=new Map,{generations:session.reviewerScopeGenerations,counter:session.reviewerScopeGenerationCounter,incarnation:session.reviewerScopeIncarnation,latestByTask:session.reviewerScopeLatestGenerationByTask,ownershipHistory:session.reviewerScopeOwnershipHistory}}function sweepReviewerScopeGenerations(session,now){let{generations}=ensureReviewerScopeGenerationState(session);for(let[key,entry]of generations){if(entry.status==="claimed"||entry.status==="mergeback_pending"||entry.status==="mergeback_mismatch")continue;if(!Number.isFinite(entry.createdAt)||now<entry.createdAt||now-entry.createdAt>REVIEWER_SCOPE_GENERATION_TTL_MS)generations.delete(key)}}function startReviewerScopeGeneration(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session||!isBoundedGenerationValue(input.taskId,512)||!isBoundedGenerationValue(input.coderCallID,512)||!input.captureDirectory.trim()||!input.workspaceIdentity.trim())return null;let now=input.createdAt??Date.now();sweepReviewerScopeGenerations(session,now);let{generations,counter,incarnation,latestByTask}=ensureReviewerScopeGenerationState(session);for(let[key2,entry]of generations)if(entry.taskId===input.taskId&&entry.status!=="claimed")generations.delete(key2);while(generations.size>=MAX_REVIEWER_SCOPE_GENERATIONS){let oldestUnclaimed=[...generations.entries()].find(([,entry])=>entry.status!=="claimed")?.[0];if(!oldestUnclaimed)return null;generations.delete(oldestUnclaimed)}session.reviewerScopeGenerationCounter=counter>=Number.MAX_SAFE_INTEGER?1:counter+1;let generation={taskId:input.taskId,coderCallID:input.coderCallID,generation:session.reviewerScopeGenerationCounter,sessionIncarnation:incarnation,background:input.background===!0,captureDirectory:input.captureDirectory,workspaceIdentity:input.workspaceIdentity,declaredFiles:[...new Set(input.declaredFiles??[])],modifiedFiles:[],modifiedFileFingerprints:[],captureFailures:[],status:"collecting",createdAt:now};if(!latestByTask.has(generation.taskId))while(latestByTask.size>=MAX_REVIEWER_SCOPE_GENERATIONS){let oldestTask=latestByTask.keys().next().value;if(!oldestTask)break;latestByTask.delete(oldestTask)}latestByTask.delete(generation.taskId),latestByTask.set(generation.taskId,{generation:generation.generation,coderCallID:generation.coderCallID,sessionIncarnation:generation.sessionIncarnation});let key=reviewerScopeGenerationKey(generation.taskId,generation.coderCallID,generation.generation);return generations.set(key,generation),cloneReviewerScopeGeneration(generation)}function recordReviewerScopeGenerationFile(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session||!isBoundedGenerationValue(input.file,4096)||!isBoundedGenerationValue(input.taskId,512)||!isBoundedGenerationValue(input.coderCallID,512))return!1;sweepReviewerScopeGenerations(session,input.now??Date.now());let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.values()].filter((entry)=>entry.taskId===input.taskId&&entry.coderCallID===input.coderCallID&&entry.status==="collecting");if(matches.length!==1)return!1;let generation=matches[0];if(generation.modifiedFiles.includes(input.file))return!0;if(generation.modifiedFiles.length>=MAX_REVIEWER_SCOPE_GENERATION_FILES){let key=reviewerScopeGenerationKey(generation.taskId,generation.coderCallID,generation.generation);return generations.delete(key),!1}return generation.modifiedFiles.push(input.file),!0}function recordReviewerScopeGenerationFileFingerprint(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return!1;let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.values()].filter((entry)=>entry.taskId===input.taskId&&entry.coderCallID===input.coderCallID&&entry.status==="collecting");if(matches.length!==1)return!1;let generation=matches[0];if(!generation.modifiedFiles.includes(input.fingerprint.file))return!1;generation.captureFailures=generation.captureFailures.filter((entry)=>entry.file!==input.fingerprint.file);let existingIndex=generation.modifiedFileFingerprints.findIndex((entry)=>entry.file===input.fingerprint.file);if(existingIndex>=0)return generation.modifiedFileFingerprints[existingIndex]={...input.fingerprint},!0;if(generation.modifiedFileFingerprints.length>=MAX_REVIEWER_SCOPE_GENERATION_FILES)return!1;return generation.modifiedFileFingerprints.push({...input.fingerprint}),!0}function recordReviewerScopeGenerationCaptureFailure(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session||!isBoundedGenerationValue(input.file,4096))return!1;let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.values()].filter((entry)=>entry.taskId===input.taskId&&entry.coderCallID===input.coderCallID&&entry.status==="collecting");if(matches.length!==1)return!1;let generation=matches[0],now=input.at??Date.now();generation.modifiedFileFingerprints=generation.modifiedFileFingerprints.filter((entry)=>entry.file!==input.file);let existingIndex=generation.captureFailures.findIndex((entry)=>entry.file===input.file);if(existingIndex>=0){let existing=generation.captureFailures[existingIndex];return generation.captureFailures[existingIndex]={...existing,code:input.code,retryable:input.retryable,attempts:existing.attempts+1,at:now},!0}if(generation.captureFailures.length>=MAX_REVIEWER_SCOPE_GENERATION_FILES)generation.captureFailures.shift();return generation.captureFailures.push({file:input.file,code:input.code,retryable:input.retryable,attempts:1,at:now}),!0}function markReviewerScopeGenerationReady(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return!1;let now=input.readyAt??Date.now();sweepReviewerScopeGenerations(session,now);let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.values()].filter((entry)=>entry.taskId===input.taskId&&entry.coderCallID===input.coderCallID&&(entry.status==="collecting"||entry.status==="ready"));if(matches.length!==1)return!1;let generation=matches[0];if(generation.status==="ready")return!0;if(input.primaryWorkspaceIdentity&&generation.workspaceIdentity!==input.primaryWorkspaceIdentity)return!1;if(!(generation.modifiedFiles.length===generation.modifiedFileFingerprints.length&&generation.modifiedFiles.every((file2)=>generation.modifiedFileFingerprints.some((entry)=>entry.file===file2))))return!1;return generation.status="ready",generation.readyAt=now,!0}function markReviewerScopeGenerationNoChange(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return!1;let now=input.at??Date.now();sweepReviewerScopeGenerations(session,now);let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.values()].filter((entry)=>entry.taskId===input.taskId&&entry.coderCallID===input.coderCallID&&entry.status==="collecting");if(matches.length!==1)return!1;let generation=matches[0];if(generation.modifiedFiles.length!==0)return!1;return generation.status="no_change",generation.readyAt=now,!0}function markReviewerScopeGenerationMergebackPending(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return!1;let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.values()].filter((entry)=>(input.taskId===void 0||entry.taskId===input.taskId)&&entry.coderCallID===input.coderCallID&&(entry.status==="collecting"||entry.status==="ready"));if(matches.length!==1)return!1;if(matches[0].status==="mergeback_pending")return!0;return matches[0].status="mergeback_pending",!0}function settleReviewerScopeMergeback(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return!1;let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.values()].filter((entry)=>(input.taskId===void 0||entry.taskId===input.taskId)&&entry.coderCallID===input.coderCallID&&entry.status==="mergeback_pending");if(matches.length!==1)return!1;let generation=matches[0],now=input.outcome.at??Date.now();if(input.outcome.verified){if(generation.status="ready",generation.readyAt===void 0)generation.readyAt=now;return generation.mergeback={verifiedAt:now,primaryWorkspaceIdentity:input.outcome.primaryWorkspaceIdentity},generation.captureDirectory=input.outcome.primaryDirectory,generation.workspaceIdentity=input.outcome.primaryWorkspaceIdentity,!0}return generation.status="mergeback_mismatch",generation.mergeback={failedAt:now,reason:input.outcome.reason},!0}function getReviewerScopeGenerationForCoderCall(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return null;sweepReviewerScopeGenerations(session,input.now??Date.now());let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.values()].filter((entry)=>entry.coderCallID===input.coderCallID&&(input.taskId===void 0||entry.taskId===input.taskId));return matches.length===1?cloneReviewerScopeGeneration(matches[0]):null}function peekReadyReviewerScopeGeneration(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return null;sweepReviewerScopeGenerations(session,input.now??Date.now());let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.values()].filter((entry)=>entry.taskId===input.taskId&&entry.status==="ready");return matches.length===1?cloneReviewerScopeGeneration(matches[0]):null}function peekReviewerScopeGenerationByStatus(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return null;sweepReviewerScopeGenerations(session,input.now??Date.now());let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.values()].filter((entry)=>entry.taskId===input.taskId&&entry.status===input.status);return matches.length===1?cloneReviewerScopeGeneration(matches[0]):null}function claimReviewerScopeGeneration(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session||!isBoundedGenerationValue(input.taskId,512)||!isBoundedGenerationValue(input.reviewerCallID,512))return null;sweepReviewerScopeGenerations(session,input.now??Date.now());let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.values()].filter((entry)=>entry.taskId===input.taskId&&entry.status==="ready");if(matches.length!==1)return null;return matches[0].status="claimed",matches[0].reviewerCallID=input.reviewerCallID,cloneReviewerScopeGeneration(matches[0])}function attachReviewerScopeGenerationDispatchSnapshot(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return!1;let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.values()].filter((entry)=>entry.taskId===input.taskId&&entry.reviewerCallID===input.reviewerCallID&&entry.status==="claimed"&&entry.coderCallID===input.snapshot.coderCallID&&entry.generation===input.snapshot.generation&&entry.sessionIncarnation===input.snapshot.sessionIncarnation);if(matches.length!==1)return!1;return matches[0].reviewerDispatchScope={...input.snapshot,files:[...input.snapshot.files]},!0}function takeReviewerScopeGeneration(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return null;sweepReviewerScopeGenerations(session,input.now??Date.now());let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.entries()].filter(([,entry])=>entry.taskId===input.taskId&&entry.reviewerCallID===input.reviewerCallID&&entry.status==="claimed");if(matches.length!==1)return null;let[key,generation]=matches[0];if(generation.background===!0&&generation.readyAt!==void 0&&Number.isFinite(generation.createdAt)&&Number.isFinite(generation.readyAt)){let{ownershipHistory}=ensureReviewerScopeGenerationState(session);while(ownershipHistory.size>=MAX_REVIEWER_SCOPE_OWNERSHIP_HISTORY){let oldestKey=ownershipHistory.keys().next().value;if(!oldestKey)break;ownershipHistory.delete(oldestKey)}let tombstone={parentSessionID:input.parentSessionID,taskId:generation.taskId,coderCallID:generation.coderCallID,generation:generation.generation,sessionIncarnation:generation.sessionIncarnation,background:!0,captureDirectory:generation.captureDirectory,workspaceIdentity:generation.workspaceIdentity,declaredFiles:[...generation.declaredFiles],modifiedFiles:[...generation.modifiedFiles],modifiedFileFingerprints:generation.modifiedFileFingerprints.map((fingerprint2)=>({...fingerprint2})),createdAt:generation.createdAt,readyAt:generation.readyAt??input.now??Date.now(),consumedAt:input.now??Date.now()};ownershipHistory.set(reviewerScopeOwnershipKey(tombstone.taskId,tombstone.coderCallID,tombstone.generation,tombstone.sessionIncarnation),tombstone)}return generations.delete(key),cloneReviewerScopeGeneration(generation)}function getReviewerScopeOwnershipHistory(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return[];let{ownershipHistory}=ensureReviewerScopeGenerationState(session);return[...ownershipHistory.values()].map(cloneReviewerScopeOwnershipTombstone)}function peekReviewerScopeGenerationClaim(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return null;sweepReviewerScopeGenerations(session,input.now??Date.now());let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.values()].filter((entry)=>entry.taskId===input.taskId&&entry.reviewerCallID===input.reviewerCallID&&entry.status==="claimed");return matches.length===1?cloneReviewerScopeGeneration(matches[0]):null}function discardReviewerScopeGenerationClaim(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return!1;let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.entries()].filter(([,entry])=>(input.taskId===void 0||entry.taskId===input.taskId)&&entry.reviewerCallID===input.reviewerCallID&&entry.status==="claimed");if(matches.length!==1)return!1;return generations.delete(matches[0][0]),!0}function reviewerScopeGenerationHasDeclaredOverlap(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return!1;let{generations}=ensureReviewerScopeGenerationState(session),declared=new Set(input.declaredFiles);return[...generations.values()].some((entry)=>entry.status==="collecting"&&(entry.taskId!==input.taskId||entry.coderCallID!==input.coderCallID)&&entry.declaredFiles.some((file2)=>declared.has(file2)))}function discardReviewerScopeGenerationForCoderCall(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return!1;let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.entries()].filter(([,entry])=>(input.taskId===void 0||entry.taskId===input.taskId)&&entry.coderCallID===input.coderCallID&&entry.status!=="claimed");if(matches.length!==1)return!1;return generations.delete(matches[0][0]),!0}function isReviewerScopeGenerationCurrent(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return!1;let{incarnation,latestByTask}=ensureReviewerScopeGenerationState(session),latest=latestByTask.get(input.taskId);return incarnation===input.sessionIncarnation&&latest?.generation===input.generation&&latest.coderCallID===input.coderCallID&&latest.sessionIncarnation===input.sessionIncarnation}function sweepStaleSessions(staleDurationMs=STALE_SESSION_TTL_MS,now=Date.now()){let staleIds=[];for(let[id,session]of swarmState.agentSessions)if(now-session.lastToolCallTime>staleDurationMs)staleIds.push(id);for(let id of staleIds)swarmState.agentSessions.delete(id),swarmState.delegationChains.delete(id),swarmState.activeAgent.delete(id);return staleIds}function maybeSweepStaleSessions(staleDurationMs=STALE_SESSION_TTL_MS,now=Date.now()){if(now-_lastIdleSweepAtMs<IDLE_SWEEP_COOLDOWN_MS)return[];return _lastIdleSweepAtMs=now,sweepStaleSessions(staleDurationMs,now)}function startAgentSession(sessionId,agentName,staleDurationMs=STALE_SESSION_TTL_MS,directory){let now=Date.now();sweepStaleSessions(staleDurationMs,now);let sessionState={agentName,lastToolCallTime:now,lastAgentEventTime:now,delegationActive:!1,activeInvocationId:0,lastInvocationIdByAgent:{},windows:{},nonTransientCircuit:createNonTransientCircuitState(agentName,0),pendingToolExecutions:new Map,lastCompactionHint:0,architectWriteCount:0,lastCoderDelegationTaskId:null,currentTaskId:null,gateLog:new Map,reviewerCallCount:new Map,lastGateFailure:null,partialGateWarningsIssuedForTask:new Set,completionGateWarnedForTask:new Set,selfFixAttempted:!1,selfCodingWarnedAtCount:0,catastrophicPhaseWarnings:new Set,lastPhaseCompleteTimestamp:0,lastPhaseCompletePhase:0,phaseAgentsDispatched:new Set,lastCompletedPhaseAgentsDispatched:new Set,qaSkipCount:0,qaSkipTaskIds:[],taskWorkflowStates:new Map,taskWorkflowCache:new Map,stageBCompletion:new Map,taskCouncilApproved:new Map,taskCouncilWorkflowGeneration:new Map,pendingCouncilRequirements:new Map,lastGateOutcome:null,declaredCoderScope:null,lastScopeViolation:null,scopeViolationDetected:!1,modifiedFilesByTask:new Map,modifiedFilesThisCoderTask:[],reviewerScopeGenerations:new Map,reviewerScopeGenerationCounter:0,reviewerScopeIncarnation:randomUUID13(),reviewerScopeLatestGenerationByTask:new Map,reviewerScopeOwnershipHistory:new Map,turboMode:!1,turboStrategy:void 0,leanTurboActive:!1,leanTurboCurrentPhase:void 0,maxConcurrencyOverride:void 0,epicModeActive:!1,qaGateSessionOverrides:{},fullAutoMode:!1,fullAutoInteractionCount:0,fullAutoDeadlockCount:0,fullAutoLastQuestionHash:null,model_fallback_index:0,modelFallbackExhausted:!1,coderRevisions:0,revisionLimitHit:!1,loopDetectionWindow:[],pendingAdvisoryMessages:[],sessionRehydratedAt:0,prmPatternCounts:new Map,prmEscalationLevel:0,prmLastPatternDetected:null,prmTrajectoryStep:0,prmHardStopPending:!1,prmHardStopInjectPending:!1,prmInjectedAdvisoryKeys:new Set,prmStruckEpisodes:new Map,prmLadderCounts:new Map,executionEpisodeArmed:!1,prSubscriptions:new Map};if(swarmState.agentSessions.set(sessionId,sessionState),directory){try{recordSessionStart(directory,now)}catch{}queueMicrotask(()=>{maybeSuggestWorktreeLink(directory,sessionId)})}if(telemetry.sessionStarted(sessionId,agentName),swarmState.activeAgent.set(sessionId,agentName),_internals65.applyRehydrationCache(sessionState),directory){let rehydrationPromise;rehydrationPromise=_internals65.rehydrateSessionFromDisk(directory,sessionState).then(async()=>{try{sessionState.prSubscriptions=await rehydratePrSubscriptions(sessionId,directory)}catch(err){warn("[state] PR subscription rehydration failed, starting with empty subscriptions:",err instanceof Error?err.message:String(err))}}).catch((err)=>{warn("[state] Rehydration failed:",err instanceof Error?err.message:String(err))}).finally(()=>{swarmState.pendingRehydrations.delete(rehydrationPromise)}),swarmState.pendingRehydrations.add(rehydrationPromise)}}function endAgentSession(sessionId){let removedBindings=clearScopeBindings((binding)=>binding.ownerSessionId===sessionId||binding.parentOwnerSessionId===sessionId);for(let binding of removedBindings)clearScopeBindingFromDisk({directory:binding.workspaceIdentity,binding});swarmState.agentSessions.delete(sessionId),swarmState.activeAgent.delete(sessionId),swarmState.delegationChains.delete(sessionId),clearRealtimeLearningNudgeSession(sessionId),resetSessionQueue(sessionId),resetPrmPatternSupport(sessionId)}function getAgentSession(sessionId){return swarmState.agentSessions.get(sessionId)}function ensureAgentSession(sessionId,agentName,directory){let now=Date.now(),session=swarmState.agentSessions.get(sessionId);if(session){if(agentName&&agentName!==session.agentName){let oldName=session.agentName;if(session.agentName=agentName,telemetry.agentActivated(sessionId,agentName,oldName),session.delegationActive=!1,session.lastAgentEventTime=now,session.nonTransientCircuit=createNonTransientCircuitState(agentName,0),!session.windows)session.activeInvocationId=0,session.lastInvocationIdByAgent={},session.windows={}}if(!session.windows)session.activeInvocationId=0,session.lastInvocationIdByAgent={},session.windows={};if(session.nonTransientCircuit===void 0)session.nonTransientCircuit=createNonTransientCircuitState(session.agentName,session.activeInvocationId??0);if(session.pendingToolExecutions===void 0)session.pendingToolExecutions=new Map;if(session.lastCompactionHint===void 0)session.lastCompactionHint=0;if(session.architectWriteCount===void 0)session.architectWriteCount=0;if(session.lastCoderDelegationTaskId===void 0)session.lastCoderDelegationTaskId=null;if(session.currentTaskId===void 0)session.currentTaskId=null;if(!session.gateLog)session.gateLog=new Map;if(!session.reviewerCallCount)session.reviewerCallCount=new Map;if(session.lastGateFailure===void 0)session.lastGateFailure=null;if(!session.partialGateWarningsIssuedForTask)session.partialGateWarningsIssuedForTask=new Set;if(!session.completionGateWarnedForTask)session.completionGateWarnedForTask=new Set;if(session.selfFixAttempted===void 0)session.selfFixAttempted=!1;if(session.selfCodingWarnedAtCount===void 0)session.selfCodingWarnedAtCount=0;if(!session.catastrophicPhaseWarnings)session.catastrophicPhaseWarnings=new Set;if(session.lastPhaseCompleteTimestamp===void 0)session.lastPhaseCompleteTimestamp=0;if(session.lastPhaseCompletePhase===void 0)session.lastPhaseCompletePhase=0;if(!session.phaseAgentsDispatched)session.phaseAgentsDispatched=new Set;if(!session.lastCompletedPhaseAgentsDispatched)session.lastCompletedPhaseAgentsDispatched=new Set;if(session.qaSkipCount===void 0)session.qaSkipCount=0;if(!session.qaSkipTaskIds)session.qaSkipTaskIds=[];if(!session.taskWorkflowStates)session.taskWorkflowStates=new Map;if(!session.taskWorkflowCache)session.taskWorkflowCache=new Map;if(!session.stageBCompletion)session.stageBCompletion=new Map;if(!session.taskCouncilApproved)session.taskCouncilApproved=new Map;if(!session.pendingCouncilRequirements)session.pendingCouncilRequirements=new Map;if(session.lastGateOutcome===void 0)session.lastGateOutcome=null;if(session.declaredCoderScope===void 0)session.declaredCoderScope=null;if(session.lastScopeViolation===void 0)session.lastScopeViolation=null;if(!(session.modifiedFilesByTask instanceof Map)){if(session.modifiedFilesByTask=new Map,isValidTaskId2(session.currentTaskId)&&Array.isArray(session.modifiedFilesThisCoderTask)&&session.modifiedFilesThisCoderTask.length>0)session.modifiedFilesByTask.set(session.currentTaskId,[...new Set(session.modifiedFilesThisCoderTask)])}if(projectModifiedFilesForActiveTask(session),!session.reviewerScopeGenerations)session.reviewerScopeGenerations=new Map;if(session.reviewerScopeGenerationCounter===void 0)session.reviewerScopeGenerationCounter=0;if(!session.reviewerScopeIncarnation)session.reviewerScopeIncarnation=randomUUID13();if(!session.reviewerScopeLatestGenerationByTask)session.reviewerScopeLatestGenerationByTask=new Map;if(!session.reviewerScopeOwnershipHistory)session.reviewerScopeOwnershipHistory=new Map;if(session.scopeViolationDetected===void 0)session.scopeViolationDetected=!1;if(session.turboMode===void 0)session.turboMode=!1;if(session.turboStrategy===void 0)session.turboStrategy=void 0;if(session.leanTurboActive===void 0)session.leanTurboActive=!1;if(session.leanTurboCurrentPhase===void 0)session.leanTurboCurrentPhase=void 0;if(session.epicModeActive===void 0)session.epicModeActive=!1;if(session.qaGateSessionOverrides===void 0)session.qaGateSessionOverrides={};if(session.model_fallback_index===void 0)session.model_fallback_index=0;if(session.modelFallbackExhausted===void 0)session.modelFallbackExhausted=!1;if(session.loopDetectionWindow===void 0)session.loopDetectionWindow=[];if(session.pendingAdvisoryMessages===void 0)session.pendingAdvisoryMessages=[];if(session.coderRevisions===void 0)session.coderRevisions=0;if(session.revisionLimitHit===void 0)session.revisionLimitHit=!1;if(session.sessionRehydratedAt===void 0)session.sessionRehydratedAt=0;if(session.prmPatternCounts===void 0)session.prmPatternCounts=new Map;if(session.prmEscalationLevel===void 0)session.prmEscalationLevel=0;if(session.prmLastPatternDetected===void 0)session.prmLastPatternDetected=null;if(session.prmTrajectoryStep===void 0)session.prmTrajectoryStep=0;if(session.prmHardStopPending===void 0)session.prmHardStopPending=!1;if(session.prmHardStopInjectPending===void 0)session.prmHardStopInjectPending=!1;if(!session.prmInjectedAdvisoryKeys)session.prmInjectedAdvisoryKeys=new Set;if(!session.prmStruckEpisodes)session.prmStruckEpisodes=new Map;if(!session.prmLadderCounts)session.prmLadderCounts=new Map;if(session.executionEpisodeArmed===void 0)session.executionEpisodeArmed=!1;if(!session.prSubscriptions)session.prSubscriptions=new Map;return session.lastToolCallTime=now,maybeSweepStaleSessions(),session}if(_internals65.startAgentSession(sessionId,agentName??"unknown",7200000,directory),session=swarmState.agentSessions.get(sessionId),!session)throw Error(`Failed to create guardrail session for ${sessionId}`);return session}function recordSessionWorkspaceRoot(sessionId,laneRoot){let trimmed=laneRoot.trim();if(!trimmed)return;let session=swarmState.agentSessions.get(sessionId);if(!session)return;session.workspaceDirectory=trimmed}function resolveSessionWorkspaceDirectory(sessionId,fallbackDirectory){let recorded=swarmState.agentSessions.get(sessionId)?.workspaceDirectory;if(recorded?.trim())return recorded;return fallbackDirectory}function updateAgentEventTime(sessionId){let session=swarmState.agentSessions.get(sessionId);if(session)session.lastAgentEventTime=Date.now()}function beginInvocation(sessionId,agentName){let session=swarmState.agentSessions.get(sessionId);if(!session)throw Error(`Cannot begin invocation: session ${sessionId} does not exist`);let stripped=stripKnownSwarmPrefix(agentName),lastId=session.lastInvocationIdByAgent[stripped]||0;if(lastId>0)clearInvocationActionCircuits(sessionId,lastId),clearPendingTaskModelRoutesForSession(sessionId);let newId=lastId+1;if(session.lastInvocationIdByAgent[stripped]=newId,session.activeInvocationId=newId,session.nonTransientCircuit=createNonTransientCircuitState(stripped,newId),stripped===ORCHESTRATOR_NAME)return null;let now=Date.now(),window2={id:newId,agentName:stripped,startedAtMs:now,toolCalls:0,consecutiveErrors:0,hardLimitHit:!1,lastSuccessTimeMs:now,recentToolCalls:[],warningIssued:!1,warningReason:"",transientRetryCount:0},key=`${stripped}:${newId}`;return session.windows[key]=window2,pruneOldWindows(sessionId,86400000,50),window2}function getActiveWindow(sessionId){let session=swarmState.agentSessions.get(sessionId);if(!session||!session.windows)return;let key=`${stripKnownSwarmPrefix(session.agentName)}:${session.activeInvocationId}`;return session.windows[key]}function pruneOldWindows(sessionId,maxAgeMs=86400000,maxWindows=50){let session=swarmState.agentSessions.get(sessionId);if(!session||!session.windows)return;let now=Date.now(),toKeep=Object.entries(session.windows).filter(([_,window2])=>now-window2.startedAtMs<maxAgeMs).sort((a,b)=>b[1].startedAtMs-a[1].startedAtMs).slice(0,maxWindows);session.windows=Object.fromEntries(toKeep)}function recordPhaseAgentDispatch(sessionId,agentName){let session=swarmState.agentSessions.get(sessionId);if(!session)return;if(!session.phaseAgentsDispatched)session.phaseAgentsDispatched=new Set;let normalizedName=stripKnownSwarmPrefix(agentName);session.phaseAgentsDispatched.add(normalizedName)}function ensureModifiedFilesByTask(session){if(!(session.modifiedFilesByTask instanceof Map))session.modifiedFilesByTask=new Map;return session.modifiedFilesByTask}function projectModifiedFilesForActiveTask(session){let taskId=session.currentTaskId;session.modifiedFilesThisCoderTask=isValidTaskId2(taskId)&&session.modifiedFilesByTask instanceof Map?[...session.modifiedFilesByTask.get(taskId)??[]]:[]}function ensureModifiedFileTaskSlot(session,taskId){if(!isValidTaskId2(taskId))return!1;let entries=ensureModifiedFilesByTask(session);if(entries.has(taskId))return!0;while(entries.size>=MAX_TRACKED_TASK_FILE_ATTRIBUTIONS){let reclaimable=[...entries.keys()].find((candidate)=>candidate!==taskId&&session.taskWorkflowStates?.get(candidate)==="complete");if(!reclaimable)return!1;entries.delete(reclaimable)}return entries.set(taskId,[]),!0}function recordModifiedFilesForTask(session,taskId,files){if(!ensureModifiedFileTaskSlot(session,taskId))return!1;let normalized=[...new Set(files.filter((file2)=>typeof file2==="string"&&file2.length>0))];if(session.modifiedFilesByTask.set(taskId,normalized),session.currentTaskId===taskId)projectModifiedFilesForActiveTask(session);return!0}function recordModifiedFileForTask(session,taskId,file2){if(typeof file2!=="string"||file2.length===0)return!1;let existing=getModifiedFilesForTask(session,taskId);if(existing.includes(file2))return!0;return recordModifiedFilesForTask(session,taskId,[...existing,file2])}function getModifiedFilesForTask(session,taskId){if(!isValidTaskId2(taskId))return[];return[...ensureModifiedFilesByTask(session).get(taskId)??[]]}function resetModifiedFilesForTask(session,taskId,options){if(!isValidTaskId2(taskId))return!1;let entries=ensureModifiedFilesByTask(session);if(options?.remove)entries.delete(taskId);else{if(!ensureModifiedFileTaskSlot(session,taskId))return!1;entries.set(taskId,[])}if(session.currentTaskId===taskId)projectModifiedFilesForActiveTask(session);return!0}function completeModifiedFilesForTask(session,taskId){if(!session.epicModeActive)resetModifiedFilesForTask(session,taskId,{remove:!0})}function isValidTaskId2(taskId){if(taskId===null||taskId===void 0)return!1;if(typeof taskId!=="string")return!1;return taskId.trim().length>0}function ensureTaskWorkflowCache(session){if(!session.taskWorkflowCache)session.taskWorkflowCache=new Map;return session.taskWorkflowCache}function updateTaskWorkflowCache(session,taskId,overrides){let cache2=ensureTaskWorkflowCache(session),existing=cache2.get(taskId);cache2.set(taskId,{generation:overrides.generation??existing?.generation??0,retryCount:overrides.retryCount??existing?.retryCount??0,lastOutcome:overrides.lastOutcome??existing?.lastOutcome??"none",lastTransitionId:overrides.lastTransitionId??existing?.lastTransitionId??null,updatedAt:overrides.updatedAt??existing?.updatedAt??""})}function advanceTaskState(session,taskId,newState2,options,councilConfig){if(!isValidTaskId2(taskId))return;if(!session||!(session.taskWorkflowStates instanceof Map))throw Error("INVALID_SESSION: session.taskWorkflowStates must be a Map instance");let current=session.taskWorkflowStates.get(taskId)??"idle",currentIndex=LINEAR_STATE_ORDER.indexOf(current),newIndex=LINEAR_STATE_ORDER.indexOf(newState2);if(currentIndex===-1||newIndex===-1||newIndex<=currentIndex)throw Error(`INVALID_TASK_STATE_TRANSITION: ${taskId} ${current} → ${newState2}`);if(newState2==="complete"&¤t!=="tests_run"){let councilEntry=session.taskCouncilApproved?.get(taskId),effectiveMinimum=councilConfig?.requireAllMembers?5:councilConfig?.minimumMembers??3,councilApproved=councilEntry?.verdict==="APPROVE"&&(councilEntry.quorumSize??0)>=effectiveMinimum,pastPreCheck=currentIndex>=LINEAR_STATE_ORDER.indexOf("pre_check_passed");if(!councilApproved||!pastPreCheck)throw Error(`INVALID_TASK_STATE_TRANSITION: ${taskId} cannot reach complete from ${current} — must pass through tests_run first (or have council APPROVE after pre_check)`)}if(session.taskWorkflowStates.set(taskId,newState2),updateTaskWorkflowCache(session,taskId,{updatedAt:new Date().toISOString()}),newState2==="complete")session.stageBCompletion?.delete(taskId),completeModifiedFilesForTask(session,taskId);if(options?.emitTelemetry!==!1)telemetry.taskStateChanged(options?.telemetrySessionId??session.agentName,taskId,newState2,current)}function canAdvanceTaskState(session,taskId,newState2,councilConfig){if(!isValidTaskId2(taskId))return!1;if(!session||!(session.taskWorkflowStates instanceof Map))return!1;let current=session.taskWorkflowStates.get(taskId)??"idle",currentIndex=LINEAR_STATE_ORDER.indexOf(current),newIndex=LINEAR_STATE_ORDER.indexOf(newState2);if(currentIndex===-1||newIndex===-1||newIndex<=currentIndex)return!1;if(newState2==="complete"&¤t!=="tests_run"){let councilEntry=session.taskCouncilApproved?.get(taskId),effectiveMinimum=councilConfig?.requireAllMembers?5:councilConfig?.minimumMembers??3,councilApproved=councilEntry?.verdict==="APPROVE"&&(councilEntry.quorumSize??0)>=effectiveMinimum,pastPreCheck=currentIndex>=LINEAR_STATE_ORDER.indexOf("pre_check_passed");if(!councilApproved||!pastPreCheck)return!1}return!0}async function advanceTaskStateAndPersist(session,taskId,newState2,_directory,options,councilConfig){if(newState2==="coder_delegated"||newState2==="complete")throw Error(`TASK_WORKFLOW_CENTRAL_TRANSACTION_REQUIRED: ${taskId} → ${newState2} must use exact-task durable transition APIs`);advanceTaskState(session,taskId,newState2,options,councilConfig)}function getTaskState(session,taskId){if(!isValidTaskId2(taskId))return"idle";if(!session.taskWorkflowStates)session.taskWorkflowStates=new Map;return session.taskWorkflowStates.get(taskId)??"idle"}function recordStageBCompletion(session,taskId,agent){if(!isValidTaskId2(taskId))return;if(!session.stageBCompletion)session.stageBCompletion=new Map;let existing=session.stageBCompletion.get(taskId);if(existing)existing.add(agent);else session.stageBCompletion.set(taskId,new Set([agent]))}function hasBothStageBCompletions(session,taskId){if(!isValidTaskId2(taskId))return!1;let completions=session.stageBCompletion?.get(taskId);if(!completions)return!1;return completions.has("reviewer")&&completions.has("test_engineer")}async function isCouncilGateActive(directory,council,sessionOverrides={}){let enabled=council?.enabled===!0,plan=null;try{plan=await loadPlanJsonOnly(directory)}catch{plan=null}if(!plan)return!1;let planId=derivePlanId(plan),lookup=null;try{lookup=getProfileLookupForIdentity(directory,plan)}catch(err){let msg=err instanceof Error?err.message:String(err);if(!(msg.includes("SQLITE_CANTOPEN")||msg.includes("ENOENT")))warn(`[isCouncilGateActive] getProfile threw unexpectedly for plan ${planId}: ${msg}. Treating council as inactive.`);lookup=null}if(!lookup||lookup.kind==="missing")return!1;if(lookup.kind==="unbound_legacy")return enabled&&lookup.profile.gates.council_mode===!0;let profile=lookup.profile,councilMode=getEffectiveGates(profile,sessionOverrides).council_mode===!0;if(enabled&&councilMode)return!0;if(enabled!==councilMode&&!_councilDisagreementWarned.has(planId))_councilDisagreementWarned.add(planId),warn(`[delegation-gate] Council mode mismatch for plan ${planId}: pluginConfig.council.enabled=${enabled}, QaGates.council_mode=${councilMode}. Falling back to Stage B (non-council) per-task advancement.`);return!1}function _resetCouncilDisagreementWarnings(){_councilDisagreementWarned.clear()}function planStatusToWorkflowState(status){switch(status){case"in_progress":return"idle";case"completed":return"complete";case"blocked":return"blocked";case"closed":return"closed";default:return"idle"}}function evidenceToWorkflowState(evidence2){let snapshot=getTaskWorkflowSnapshot(evidence2);return{state:snapshot.state,generation:snapshot.generation,authoritative:snapshot.authoritative,retryCount:snapshot.retryCount,lastOutcome:snapshot.lastOutcome,lastTransitionId:snapshot.lastTransitionId,updatedAt:snapshot.updatedAt}}async function readPlanFromDisk(directory){try{let planPath=path83.join(directory,".swarm","plan.json"),content=await fs52.readFile(planPath,"utf-8"),parsed=JSON.parse(content);return PlanSchema.parse(parsed)}catch{return null}}async function readGateEvidenceFromDisk(directory){let evidenceMap=new Map;try{let evidenceDir=path83.join(directory,".swarm","evidence"),entries=await fs52.readdir(evidenceDir,{withFileTypes:!0});for(let entry of entries){if(!entry.isFile()||!entry.name.endsWith(".json"))continue;let taskId=entry.name.replace(/\.json$/,"");if(!/^\d+\.\d+(\.\d+)*$/.test(taskId))continue;try{let filePath=path83.join(evidenceDir,entry.name),content=await fs52.readFile(filePath,"utf-8"),parsed=parseTaskEvidence(content,taskId);evidenceMap.set(taskId,parsed)}catch{}}}catch{}return evidenceMap}async function buildRehydrationCache(directory){let planTaskStates=new Map,plan=await readPlanFromDisk(directory);if(plan)for(let phase of plan.phases??[])for(let task of phase.tasks??[])planTaskStates.set(task.id,planStatusToWorkflowState(task.status));let evidenceMap=await readGateEvidenceFromDisk(directory),councilConfig;try{councilConfig=loadPluginConfig(directory).council}catch{councilConfig=void 0}_rehydrationCache={planTaskStates,evidenceMap,taskIdentityContext:{plan,councilConfig}}}function applyRehydrationCache(session){if(!_rehydrationCache)return;if(!session.taskWorkflowStates)session.taskWorkflowStates=new Map;if(!session.taskWorkflowCache)session.taskWorkflowCache=new Map;if(!session.taskCouncilApproved)session.taskCouncilApproved=new Map;let{planTaskStates,evidenceMap,taskIdentityContext}=_rehydrationCache;for(let[taskId,planState]of planTaskStates){let existingState=session.taskWorkflowStates.get(taskId),existingCache=ensureTaskWorkflowCache(session).get(taskId),evidence2=evidenceMap.get(taskId);if(evidence2){let derivedWorkflow=evidenceToWorkflowState(evidence2);if(derivedWorkflow.authoritative){session.taskWorkflowStates.set(taskId,derivedWorkflow.state),updateTaskWorkflowCache(session,taskId,{generation:derivedWorkflow.generation,retryCount:derivedWorkflow.retryCount,lastOutcome:derivedWorkflow.lastOutcome,lastTransitionId:derivedWorkflow.lastTransitionId,updatedAt:derivedWorkflow.updatedAt});continue}}if((existingCache?.generation??0)>0)continue;if(existingState==null||compareWorkflowStatePrecedence(planState,existingState)>0)session.taskWorkflowStates.set(taskId,planState)}let VALID_COUNCIL_VERDICTS=new Set(["APPROVE","REJECT","CONCERNS"]);for(let[taskId,evidence2]of evidenceMap){let council=evidence2.gates?.council;if(!council){session.taskCouncilApproved.delete(taskId);continue}let rawIdentityDigest=council.identity_digest;if(typeof rawIdentityDigest!=="string"||!/^[a-f0-9]{64}$/.test(rawIdentityDigest)){session.taskCouncilApproved.delete(taskId);continue}let expectedIdentity=computeCouncilReviewIdentity({level:"task",scope:{kind:"task",taskId},plan:taskIdentityContext.plan,config:taskIdentityContext.councilConfig});if(rawIdentityDigest!==expectedIdentity.identityDigest){session.taskCouncilApproved.delete(taskId);continue}let councilWorkflow=getTaskWorkflowSnapshot(evidence2);if(!councilWorkflow.authoritative||council.workflowGeneration!==councilWorkflow.generation||councilWorkflow.state!=="pre_check_passed"){session.taskCouncilApproved.delete(taskId);continue}let rawVerdict=council.verdict;if(!rawVerdict||typeof rawVerdict!=="string")continue;if(!VALID_COUNCIL_VERDICTS.has(rawVerdict))continue;let verdict=rawVerdict,roundNumber=council.roundNumber;if(typeof roundNumber!=="number"||!Number.isFinite(roundNumber))roundNumber=1;let rawQuorumSize=council.quorumSize,quorumSize=typeof rawQuorumSize==="number"&&Number.isFinite(rawQuorumSize)&&rawQuorumSize>=1?rawQuorumSize:1;session.taskCouncilApproved.set(taskId,{verdict,roundNumber,quorumSize})}}async function rehydrateSessionFromDisk(directory,session){await _internals65.buildRehydrationCache(directory),_internals65.applyRehydrationCache(session)}function hasActiveTurboMode(sessionID){if(sessionID)return swarmState.agentSessions.get(sessionID)?.turboMode===!0;for(let[_sessionId,session]of swarmState.agentSessions)if(session.turboMode===!0)return!0;return!1}function hasActiveFullAuto(sessionID){if(sessionID)return swarmState.agentSessions.get(sessionID)?.fullAutoMode===!0;for(let[_sessionId,session]of swarmState.agentSessions)if(session.fullAutoMode===!0)return!0;return!1}function getActiveFullAutoSessionID(){let activeId,activeLastToolCall=-1;for(let[id,session]of swarmState.agentSessions){if(session.fullAutoMode!==!0)continue;let lastToolCall=session.lastToolCallTime??0;if(activeId===void 0||lastToolCall>activeLastToolCall)activeId=id,activeLastToolCall=lastToolCall}return activeId}function hasActiveLeanTurbo(sessionID){if(sessionID){let session=swarmState.agentSessions.get(sessionID);return session?.turboMode===!0&&session?.turboStrategy==="lean"&&session?.leanTurboActive===!0}for(let[_sessionId,session]of swarmState.agentSessions)if(session.turboMode===!0&&session.turboStrategy==="lean"&&session.leanTurboActive===!0)return!0;return!1}function hasActiveEpicMode(sessionID){if(sessionID)return swarmState.agentSessions.get(sessionID)?.epicModeActive===!0;for(let[_sessionId,session]of swarmState.agentSessions)if(session.epicModeActive===!0)return!0;return!1}function getResolvedAutoProceed(session,planAutoProceed){return session.autoProceedOverride??planAutoProceed??!1}function setSessionEnvironment(sessionId,profile){swarmState.environmentProfiles.set(sessionId,profile)}function getSessionEnvironment(sessionId){return swarmState.environmentProfiles.get(sessionId)}function ensureSessionEnvironment(sessionId){let existing=swarmState.environmentProfiles.get(sessionId);if(existing)return existing;let profile=detectEnvironmentProfile();return swarmState.environmentProfiles.set(sessionId,profile),Promise.resolve().then(() => (init_telemetry(),exports_telemetry)).then(({telemetry:telemetry2})=>{telemetry2.environmentDetected(sessionId,profile.hostOS,profile.shellFamily,profile.executionMode)}).catch(()=>{}),profile}function setLiveContextWindow(sessionID,tokens,identity){if(!sessionID)return;let map2=swarmState.liveContextWindows,modelID=trimLiveContextIdentity(identity?.modelID),providerID=trimLiveContextIdentity(identity?.providerID),hasIdentity=Boolean(modelID||providerID),existing=map2.get(sessionID);if(!(typeof tokens==="number"&&Number.isFinite(tokens)&&tokens>=1)){if(!hasIdentity)return;if(existing&&liveContextIdentityMatches(existing,{modelID,providerID})&&existing.tokens!==void 0)return;if(map2.has(sessionID))map2.delete(sessionID);map2.set(sessionID,{modelID,providerID}),evictOldestLiveContextWindow(map2,sessionID);return}if(!hasIdentity&&existing&&(existing.modelID||existing.providerID))return;if(map2.has(sessionID))map2.delete(sessionID);map2.set(sessionID,{tokens:Math.floor(tokens),modelID,providerID}),evictOldestLiveContextWindow(map2,sessionID)}function getLiveContextWindow(sessionID,identity){if(!sessionID)return;let cached2=swarmState.liveContextWindows.get(sessionID);if(!cached2)return;if(identity&&!liveContextIdentityMatches(cached2,identity))return;return cached2.tokens}function getLiveContextModelIdentity(sessionID){if(!sessionID)return;let cached2=swarmState.liveContextWindows.get(sessionID);if(!cached2)return;return{modelID:cached2.modelID,providerID:cached2.providerID}}function evictOldestLiveContextWindow(map2,sessionID){if(map2.size<=MAX_TRACKED_CONTEXT_WINDOWS)return;let oldest=map2.keys().next().value;if(oldest!==void 0&&oldest!==sessionID)map2.delete(oldest)}function trimLiveContextIdentity(value){let trimmed=value?.trim();return trimmed?trimmed:void 0}function normalizeLiveContextIdentity(value){return trimLiveContextIdentity(value)?.toLowerCase()??""}function liveContextIdentityMatches(left,right){return normalizeLiveContextIdentity(left.modelID)===normalizeLiveContextIdentity(right.modelID)&&normalizeLiveContextIdentity(left.providerID)===normalizeLiveContextIdentity(right.providerID)}function setSessionBudget(sessionID,pct,tokens){let map2=swarmState.lastBudgetBySession;if(map2.has(sessionID))map2.delete(sessionID);if(map2.set(sessionID,{pct,tokens}),map2.size>MAX_TRACKED_BUDGET_SESSIONS){let oldest=map2.keys().next().value;if(oldest!==void 0&&oldest!==sessionID)map2.delete(oldest)}}function getSessionBudgetPct(sessionID){if(!sessionID)return 0;return swarmState.lastBudgetBySession.get(sessionID)?.pct??0}function getSessionBudgetTokens(sessionID){if(!sessionID)return 0;return swarmState.lastBudgetBySession.get(sessionID)?.tokens??0}function getDisplayBudget(){let best=null;for(let entry of swarmState.lastBudgetBySession.values())if(entry.pct>0&&(best===null||entry.pct>best.pct))best=entry;return best}function setCriticalShownIds(sessionID,value){let map2=swarmState.currentCriticalShownIds;if(map2.has(sessionID))map2.delete(sessionID);if(map2.set(sessionID,value),map2.size>MAX_TRACKED_CRITICAL_SHOWN){let oldest=map2.keys().next().value;if(oldest!==void 0&&oldest!==sessionID)map2.delete(oldest)}}function clearCriticalShownIds(sessionID){return swarmState.currentCriticalShownIds.delete(sessionID)}function buildGateDenialDirectiveKey(ids){return[...ids].sort().join(",")}function incrementGateDenialCount(sessionID,directiveKey){let map2=swarmState.gateDenialCounts,existing=map2.get(sessionID),count=existing&&existing.directiveKey===directiveKey?existing.count+1:1;if(map2.has(sessionID))map2.delete(sessionID);if(map2.set(sessionID,{count,directiveKey}),map2.size>MAX_TRACKED_GATE_DENIALS){let oldest=map2.keys().next().value;if(oldest!==void 0&&oldest!==sessionID)map2.delete(oldest)}return count}function clearGateDenialCount(sessionID){swarmState.gateDenialCounts.delete(sessionID)}function addKnowledgeAckDedup(key){let set2=swarmState.knowledgeAckDedup;if(set2.has(key))return;if(set2.add(key),set2.size>MAX_TRACKED_KNOWLEDGE_ACKS){let oldest=set2.values().next().value;if(oldest!==void 0)set2.delete(oldest)}}async function rehydratePrSubscriptions(sessionID,directory){let map2=new Map;try{let{listActive:listActive2}=await Promise.resolve().then(() => (init_pr_subscriptions(),exports_pr_subscriptions)),records=await listActive2(directory);for(let record2 of records){if(record2.sessionID!==sessionID)continue;let key=`${record2.repoFullName}::${record2.prNumber}`;map2.set(key,{prNumber:record2.prNumber,repoFullName:record2.repoFullName,prUrl:record2.prUrl,lastKnownStatus:record2.mergeableState??"unknown",lastPollTime:record2.lastCheckedAt,errorCount:record2.errorCount,isWatching:record2.isWatching})}}catch(err){warn(`[state] rehydratePrSubscriptions failed for session ${sessionID}: ${err instanceof Error?err.message:String(err)}`)}return map2}var _rehydrationCache=null,_councilDisagreementWarned,MAX_TRACKED_TASK_FILE_ATTRIBUTIONS=128,LINEAR_STATE_ORDER,_toolAggregates,defaultRunContext,_runContexts,swarmState,STALE_SESSION_TTL_MS=7200000,MAX_REVIEWER_SCOPE_GENERATION_FILES=256,MAX_REVIEWER_SCOPE_GENERATIONS=256,MAX_REVIEWER_SCOPE_OWNERSHIP_HISTORY=256,REVIEWER_SCOPE_GENERATION_TTL_MS,IDLE_SWEEP_COOLDOWN_MS=60000,_lastIdleSweepAtMs=0,MAX_TRACKED_BUDGET_SESSIONS=500,MAX_TRACKED_CRITICAL_SHOWN=500,MAX_TRACKED_KNOWLEDGE_ACKS=5000,MAX_TRACKED_GATE_DENIALS=500,MAX_TRACKED_CONTEXT_WINDOWS=500,_internals65;var init_state2=__esm(()=>{init_constants();init_loader();init_plan_schema();init_schema();init_council_review_identity();init_qa_gate_profile();init_action_circuit();init_gate_evidence();init_delegation_gate();init_realtime_learning_nudge();init_trajectory_step_state();init_candidate_queue();init_prm_pattern_support();init_task_model_routing();init_manager();init_utils3();init_trajectory_store();init_scope_binding();init_scope_persistence();init_session_start_store();init_worktree_link_suggestion();init_telemetry();init_logger();_councilDisagreementWarned=new Set,LINEAR_STATE_ORDER=["idle","coder_delegated","pre_check_passed","reviewer_run","tests_run","complete"];_toolAggregates=new Map,defaultRunContext=new AgentRunContext("default",_toolAggregates),_runContexts=new Map;swarmState={activeToolCalls:defaultRunContext.activeToolCalls,toolAggregates:defaultRunContext.toolAggregates,activeAgent:defaultRunContext.activeAgent,delegationChains:defaultRunContext.delegationChains,pendingEvents:0,opencodeClient:null,curatorInitAgentNames:[],curatorPhaseAgentNames:[],curatorPostmortemAgentNames:[],curatorConsolidationAgentNames:[],skillImproverAgentNames:[],specWriterAgentNames:[],currentCriticalShownIds:new Map,knowledgeAckDedup:new Set,gateDenialCounts:new Map,generatedAgentNames:[],lastBudgetBySession:new Map,liveContextWindows:new Map,agentSessions:defaultRunContext.agentSessions,pendingRehydrations:new Set,fullAutoEnabledInConfig:!1,environmentProfiles:defaultRunContext.environmentProfiles};REVIEWER_SCOPE_GENERATION_TTL_MS=STALE_SESSION_TTL_MS;_internals65={swarmState,resetSwarmState,ensureAgentSession,startAgentSession,getAgentSession,beginInvocation,getActiveWindow,advanceTaskState,getTaskState,hasActiveFullAuto,hasActiveTurboMode,hasActiveLeanTurbo,hasActiveEpicMode,buildRehydrationCache,applyRehydrationCache,rehydrateSessionFromDisk,isCouncilGateActive,defaultRunContext}});import{createHash as createHash34,randomUUID as randomUUID14}from"node:crypto";import{readFileSync as readFileSync28}from"node:fs";import*as fsp4 from"node:fs/promises";import*as path84 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_exports2.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_exports2.classifyPrWorkflowGitStateAsync(directory,{ignoredPaths:[path84.join(".swarm",workflowCheckoutMutationLockRelativePath()),path84.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:randomUUID14(),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 fsp4.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,path84.join(WORKFLOW_GATE_DIR,entry.name)),state=await readPrWorkflowGateStateFileFromDisk(statePath,entry.name);if(!state)continue;let expectedName=path84.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 fsp4.rm(workflowGateStatePath(directory,normalizedSessionID),{force:!0})}catch(error49){if(error49.code!=="ENOENT")throw error49}trackedStatesByProjectSession.delete(stateCacheKey(directory,normalizedSessionID))})}function isLiveSessionStatusType(type){return LIVE_SESSION_STATUS_TYPES.has(type)}async function probePrWorkflowLaneSessionStatusTypes(directory,records,timeoutMs){let session=_test_exports2.getSessionOps(),statusOp=session?.status;if(!session||typeof statusOp!=="function")return{statuses:new Map,degradedReason:"probe-unavailable"};let timeoutError=Error("PR workflow lane liveness probe exceeded its deadline"),response;try{response=await withTimeout((async()=>statusOp.call(session,{query:{directory}}))(),timeoutMs??_test_exports2.laneLivenessProbeTimeoutMs,timeoutError)}catch(error49){return{statuses:new Map,degradedReason:error49===timeoutError?"probe-timeout":"probe-error"}}try{if(response?.error)return{statuses:new Map,degradedReason:"probe-error"};let data=response?.data;if(data===null||data===void 0)return{statuses:new Map,degradedReason:"probe-no-data"};let statuses=new Map;for(let record2 of records){let subagentSessionId=record2.subagentSessionId;if(!subagentSessionId)continue;let type=data[subagentSessionId]?.type;if(typeof type==="string")statuses.set(subagentSessionId,type)}return{statuses}}catch{return{statuses:new Map,degradedReason:"probe-error"}}}async function probeAlivePrWorkflowLaneSessions(directory,records){let probe2=await probePrWorkflowLaneSessionStatusTypes(directory,records);if(probe2.degradedReason)return{alive:new Set,degradedReason:probe2.degradedReason};let alive=new Set;for(let[sessionId,type]of probe2.statuses)if(isLiveSessionStatusType(type))alive.add(sessionId);return{alive}}async function collectPrWorkflowPendingLaneLiveness(directory,records,options={}){let now=0,pastThreshold=[],degraded=(record2,reason)=>({laneId:record2.laneId??record2.correlationId,pendingMs:Math.max(0,now-record2.updatedAt),hostStatus:"unknown",stalledSuspect:!0,degradedReason:reason});try{now=_test_exports2.nowMs();let threshold=_test_exports2.pendingLaneLivenessThresholdMs;if(pastThreshold=records.filter((record2)=>(record2.status==="pending"||record2.status==="running"||record2.status==="ingesting")&&record2.mode!==void 0&&PR_WORKFLOW_PENDING_LIVENESS_MODES.has(record2.mode)&&now-record2.updatedAt>threshold),pastThreshold.length===0)return[];let budgetMs=Math.max(0,Math.min(_test_exports2.laneLivenessProbeTimeoutMs,options.probeBudgetMs??Number.POSITIVE_INFINITY));if(budgetMs<=0)return pastThreshold.map((record2)=>degraded(record2,"probe-timeout"));let probe2=await probePrWorkflowLaneSessionStatusTypes(directory,pastThreshold,budgetMs),advisories=[];for(let record2 of pastThreshold){let pendingMs=now-record2.updatedAt,laneId=record2.laneId??record2.correlationId;if(probe2.degradedReason){advisories.push({laneId,pendingMs,hostStatus:"unknown",stalledSuspect:!0,degradedReason:probe2.degradedReason});continue}let subagentSessionId=record2.subagentSessionId,type=subagentSessionId?probe2.statuses.get(subagentSessionId):void 0;if(type===void 0){advisories.push({laneId,pendingMs,hostStatus:subagentSessionId?"absent":"unknown",stalledSuspect:!0});continue}advisories.push({laneId,pendingMs,hostStatus:type,stalledSuspect:!isLiveSessionStatusType(type)})}return advisories}catch{return pastThreshold.map((record2)=>degraded(record2,"advisory-unavailable"))}}function describePrWorkflowLaneProbe(settlement){let parts=[];if(settlement.probedAliveLaneIds?.length)parts.push(`liveness probe reports still running: ${settlement.probedAliveLaneIds.slice(0,MAX_DISCLOSED_LANE_IDS).join(", ")}`);if(settlement.probeDegradedReason)parts.push(`liveness probe degraded (${settlement.probeDegradedReason})`);return parts.length>0?` (${parts.join("; ")})`:""}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(),open5=[],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 open5.push(record2)}if(presumedStale.length===0)return{openLaneIds:open5.map(prWorkflowLaneLabel),openLanes:open5.length,freshOpenLanes:open5.length,presumedStaleLaneIds:[]};let probe2;try{probe2=await _test_exports2.probeLaneLivenessAsync(directory,presumedStale)}catch{probe2={alive:new Set,degradedReason:"probe-error"}}let probeRetained=[],settled=[];for(let record2 of presumedStale)if(record2.subagentSessionId&&probe2.alive.has(record2.subagentSessionId))probeRetained.push(record2);else settled.push(record2);let probedAliveLaneIds=probeRetained.map(prWorkflowLaneLabel),openLaneIds=[...open5.map(prWorkflowLaneLabel),...probedAliveLaneIds],retentionDisclosure=probeRetained.length>0?`${probeRetained.length} lane(s) past the horizon retained: liveness probe reports still running: ${probedAliveLaneIds.slice(0,MAX_DISCLOSED_LANE_IDS).join(", ")}`:void 0,retentionFields={...probedAliveLaneIds.length>0?{probedAliveLaneIds,probeRetainedCorrelationIds:probeRetained.map((record2)=>record2.correlationId)}:{},...probe2.degradedReason?{probeDegradedReason:probe2.degradedReason}:{}};if(settled.length===0)return{openLaneIds,openLanes:openLaneIds.length,freshOpenLanes:open5.length,presumedStaleLaneIds:[],...retentionFields,disclosure:retentionDisclosure};let presumedStaleLaneIds=settled.map(prWorkflowLaneLabel),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(", ")}`+(probe2.degradedReason?`; settled despite liveness probe failure (${probe2.degradedReason})`:"; liveness probe found no live session")+(retentionDisclosure?`; ${retentionDisclosure}`:"");try{await _test_exports2.sweepStaleDelegationsAsync(directory,PR_WORKFLOW_STALE_LANE_TIMEOUT_MS,{statuses:PR_WORKFLOW_SWEEPABLE_LANE_STATUSES,excludeCorrelationIds:new Set(probeRetained.map((record2)=>record2.correlationId))})}catch{}try{await fsp4.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,probeStatus:probe2.degradedReason??"ok",probedAliveLanes:probedAliveLaneIds.slice(0,MAX_DISCLOSED_LANE_IDS),disclosure})}
|
|
877
877
|
`,"utf-8")}catch{}return{openLaneIds,openLanes:openLaneIds.length,freshOpenLanes:open5.length,presumedStaleLaneIds,...retentionFields,disclosure}}async function finalizeOverriddenProbeRetainedLanes(directory,sessionID,correlationIds){try{await _test_exports2.sweepStaleDelegationsAsync(directory,PR_WORKFLOW_STALE_LANE_TIMEOUT_MS,{statuses:PR_WORKFLOW_SWEEPABLE_LANE_STATUSES,includeCorrelationIds:new Set(correlationIds)})}catch{}let targeted=new Set(correlationIds),outcome={sessionOpenLaneIds:[],finalizedLaneIds:[],sparedLaneDescriptions:[]};for(let record2 of readDelegations(directory)){if(isOpenPrWorkflowLane(record2,sessionID))outcome.sessionOpenLaneIds.push(record2.correlationId);if(!targeted.has(record2.correlationId))continue;if(record2.status==="stale")outcome.finalizedLaneIds.push(record2.correlationId);else if(record2.status!=="pending"&&record2.status!=="running")outcome.sparedLaneDescriptions.push(`${record2.correlationId} (${record2.status})`)}return outcome}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),probeRetainedLanes=laneSettlement.probedAliveLaneIds??[],overridesProbeRetention=options.kind==="force"&&laneSettlement.freshOpenLanes===0&&probeRetainedLanes.length>0;if(laneSettlement.openLanes>0&&!overridesProbeRetention){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.`+describePrWorkflowLaneProbe(laneSettlement))}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 overrideTargetedLaneIds=overridesProbeRetention?laneSettlement.probeRetainedCorrelationIds??[]:[],probeRetentionOverrideDecision=overridesProbeRetention?`force abort overrode ${probeRetainedLanes.length} lane(s) past the staleness horizon that the liveness probe reported as still running: ${probeRetainedLanes.slice(0,MAX_DISCLOSED_LANE_IDS).join(", ")}. Their sessions were NOT stopped and their output was NOT collected.`:void 0,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}:{},...probeRetainedLanes.length>0?{probeRetainedLanes:probeRetainedLanes.slice(0,MAX_DISCLOSED_LANE_IDS)}:{},...probeRetentionOverrideDecision?{probeRetentionOverrideDisclosure:probeRetentionOverrideDecision}:{},...overridesProbeRetention?{probeRetentionOverrideLanes:overrideTargetedLaneIds.slice(0,MAX_DISCLOSED_LANE_IDS)}:{},...laneSettlement.probeDegradedReason?{probeStatus:laneSettlement.probeDegradedReason}:{},...recovery.salvaged?{stateSalvaged:!0,stateSalvageDisclosure:recovery.disclosure,...recovery.revisionSalvageable?{}:{casEscapeDisclosure:CAS_ESCAPE_DISCLOSURE}}:{},reason:sanitizedReason};try{let eventsPath=validateSwarmPath(directory,"events.jsonl");await fsp4.appendFile(eventsPath,`${JSON.stringify(abortEvent)}
|
|
878
878
|
`,"utf-8")}catch{}let casEscape=recovery.salvaged&&!recovery.revisionSalvageable;await _test_exports2.beforeAbortClear?.();try{await clearPrWorkflowGateState(directory,sessionID,casEscape?void 0:state.revision,{allowSalvagedRead:recovery.salvaged})}catch(error49){try{await fsp4.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,...overridesProbeRetention?{probeRetentionOverrideLanes:overrideTargetedLaneIds.slice(0,MAX_DISCLOSED_LANE_IDS),probeRetentionOverrideFinalized:!1}:{},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."+(overridesProbeRetention?" The probe-retention override finalized no record: it runs only after the clear succeeds, and this clear failed. Other lanes in the same settlement "+"batch may already have been finalized as presumed-stale, and a concurrent abort for this session may have finalized more — revalidate the lane records rather than assuming they are untouched.":"")})}
|
|
879
879
|
`,"utf-8")}catch{}throw error49}let overrideOutcome=overridesProbeRetention?await finalizeOverriddenProbeRetainedLanes(directory,state.sessionID,overrideTargetedLaneIds):{sessionOpenLaneIds:[],finalizedLaneIds:[],sparedLaneDescriptions:[]},probeRetentionOverrideDisclosure=probeRetentionOverrideDecision?probeRetentionOverrideDecision+(overrideOutcome.finalizedLaneIds.length===0?"":` Their delegation records were finalized (correlationId: ${overrideOutcome.finalizedLaneIds.slice(0,MAX_DISCLOSED_LANE_IDS).join(", ")}); whatever those lanes still produce is no longer collectable.`)+(overrideOutcome.sparedLaneDescriptions.length===0?"":` ${overrideOutcome.sparedLaneDescriptions.length} of the overridden lane(s) were NOT finalized: the sweep left those records intact at the status they had already reached (${overrideOutcome.sparedLaneDescriptions.slice(0,MAX_DISCLOSED_LANE_IDS).join(", ")}). This abort did not discard them — check collect_lane_results before assuming that work is gone.`)+(overrideOutcome.sessionOpenLaneIds.length===0?" A new PR workflow can now be started for this session.":` WARNING: ${overrideOutcome.sessionOpenLaneIds.length} PR workflow delegation record(s) for this session are still open (correlationId: ${overrideOutcome.sessionOpenLaneIds.slice(0,MAX_DISCLOSED_LANE_IDS).join(", ")}) and will keep refusing PR workflow checkout preparation for this session until they settle.`):void 0;return{mode:state.mode,...state.prHeadSha?{prHeadSha:state.prHeadSha}:{},openLanes:laneSettlement.openLanes,...laneSettlement.presumedStaleLaneIds.length>0?{presumedStaleLanes:laneSettlement.presumedStaleLaneIds,presumedStaleDisclosure:laneSettlement.disclosure}:{},...probeRetainedLanes.length>0?{probeRetainedLanes}:{},...probeRetentionOverrideDisclosure?{probeRetentionOverrideDisclosure}:{},...laneSettlement.probeDegradedReason?{probeDegradedReason:laneSettlement.probeDegradedReason}:{},...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_exports2.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 fsp4.appendFile(eventsPath,`${JSON.stringify({type:"pr_feedback_rebound",timestamp:isoNow(),sessionID:state.sessionID,previousPrHeadSha:state.prHeadSha,prHeadSha:normalizedHead,rebindCount:nextState.prFeedbackRebindCount})}
|
|
880
|
-
`,"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_exports2.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_exports2.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_exports2.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_exports2.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_exports2.resolveCurrentUpstreamPushTargetAsync(directory),matchingRemoteRefs=await _test_exports2.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_exports2.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_exports2.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_exports2.afterPrFeedbackTrackingSwitch?.();let attachedHead=(await _test_exports2.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_exports2.resolveIsWorkingTreeCleanAsync(directory)!==!0)throw Error("BLOCKED: PR_FEEDBACK requires a clean working tree after checkout attachment");let attachedUpstream=await _test_exports2.resolveCurrentUpstreamPushTargetAsync(directory);if(!attachedUpstream)throw Error("BLOCKED: PR_FEEDBACK could not resolve the attached branch upstream after checkout promotion");if(!(await _test_exports2.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}function snapshotPrReviewResiliencePolicy(policy){return{enabled:policy?.enabled??!0,canaryProbeMs:policy?.canary_probe_ms??300000,statusProbeTimeoutMs:policy?.status_probe_timeout_ms??2000,correlatedFailureThreshold:policy?.correlated_failure_threshold??2,maxRetryAttemptsAfterInitial:policy?.max_retry_attempts_after_initial??2}}function declaredBaseDimensions(lanes){return lanes.flatMap((lane)=>lane.ownedWorkflowLanes?.length?lane.ownedWorkflowLanes:[lane.workflowLane])}function exactDimensionPartition(actual,expected){return actual.length===expected.length&&new Set(actual).size===expected.length&&expected.every((dimension)=>actual.includes(dimension))}function latestDelegationRecord(records){return[...records].sort((left,right)=>{let leftKey=left.completedAt??left.updatedAt??left.createdAt;return(right.completedAt??right.updatedAt??right.createdAt)-leftKey})[0]??null}function batchLaneRecords(directory,state,batchId,laneId){return findByBatchId(directory,batchId,{parentSessionId:state.sessionID}).filter((record2)=>record2.laneId===laneId)}function baseLaneDimensions(lane){return lane.ownedWorkflowLanes?.length?lane.ownedWorkflowLanes:[lane.workflowLane]}function batchIsTerminal(directory,state,batchId){let records=findByBatchId(directory,batchId,{parentSessionId:state.sessionID});return records.length>0&&records.every((record2)=>TERMINAL_FAILED_DELEGATION_STATUSES.has(record2.status)||record2.status==="consumed")}function effectivePrReviewResiliencePolicy(state,requestedPolicy){return state.prReviewResilience?.policy??snapshotPrReviewResiliencePolicy(requestedPolicy)}function normalizeFailureSignatureText(value){return value.toLowerCase().replace(/\b\d{4}-\d{2}-\d{2}t\d{2}:\d{2}:\d{2}(?:\.\d{1,6})?(?:z|[+-]\d{2}:\d{2})\b/g,"<iso-timestamp>").replace(/\b\d{10,16}\b/g,"<epoch>").replace(/\b((?:session|request|trace|correlation|run)(?:[_-]?id)?)\s*[:=]\s*([a-z0-9._:-]*[0-9_-][a-z0-9._:-]*)\b/g,"$1=<id>").replace(/\b((?:session|sess|request|req|trace|correlation|corr|run)(?:[_-]?id)?)\s+((?:(?:sess?|req|trace|corr|run)[_-][a-z0-9._:-]+|[a-z][a-z0-9._:-]*\d[a-z0-9._:-]*))\b/g,"$1 <id>").replace(/\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/g,"<uuid>").replace(/\b[0-9a-f]{16,64}\b/g,"<hex>").replace(/[a-z]:\\[^\s)]+/gi,"<path>").replace(/(?:\/[\w.@:-]+)+/g,"<path>").replace(/\s+/g," ").trim().slice(0,160)}function classifyTerminalFailureSignature(record2){if(!TERMINAL_FAILED_DELEGATION_STATUSES.has(record2.status))return null;let result=record2.terminalResult?.result??record2.result;if(!result)return`terminal-zero-output:${record2.status}`;let outputRef=result.outputRef?.trim(),text=result.text?.trim()??"";if(!outputRef&&text.length===0&&(result.chars??0)===0)return`terminal-zero-output:${record2.status}`;let errorText=result.error?.trim();if(errorText)return`terminal-error-output:${record2.status}:${normalizeFailureSignatureText(errorText)}`;if(record2.status==="completed")return null;return`terminal-nonzero-output:${record2.status}`}function computePrReviewResilienceCircuit(directory,state,policy){let signatures=new Map;for(let batch of state.prReviewBaseDispatches??[])for(let lane of batch.lanes){let latest=latestDelegationRecord(batchLaneRecords(directory,state,batch.batchId,lane.laneId));if(!latest)continue;let signature=classifyTerminalFailureSignature(latest);if(!signature)continue;let current=signatures.get(signature)??{dimensions:new Set,contributors:[]};for(let dimension of baseLaneDimensions(lane)){if(current.dimensions.has(dimension))continue;current.dimensions.add(dimension),current.contributors.push({batchId:batch.batchId,laneId:lane.laneId})}signatures.set(signature,current)}let opened=[...signatures.entries()].filter(([,entry])=>entry.dimensions.size>=policy.correlatedFailureThreshold).sort((left,right)=>right[1].dimensions.size-left[1].dimensions.size||left[0].localeCompare(right[0]))[0];if(!opened)return null;return{signature:opened[0],count:opened[1].dimensions.size,contributors:opened[1].contributors,openedAt:state.prReviewResilience?.circuit?.openedAt??isoNow()}}function formatPrReviewResilienceCircuitOpenMessage(circuit){return`BLOCKED: PR_REVIEW base dispatch circuit is open after ${circuit.count} correlated terminal failures (${circuit.signature}); collect every launched lane, abort_pr_workflow, and stop without partial findings`}async function preflightPrReviewResilienceCircuitBeforePrune(directory,state,previous,policy){let nextState=state,nextPrevious=previous,snapshot=nextState.prReviewResilience;if(!snapshot){if(snapshot={policy,attempts:[]},nextPrevious.length>0)nextState=await writeStateWhileLocked(directory,{...nextState,updatedAt:isoNow(),prReviewResilience:snapshot}),nextPrevious=nextState.prReviewBaseDispatches??[],snapshot=nextState.prReviewResilience??snapshot}if(snapshot.circuit)throw new PrReviewResilienceCircuitOpenError(formatPrReviewResilienceCircuitOpenMessage(snapshot.circuit));let circuit=computePrReviewResilienceCircuit(directory,nextState,policy);if(!circuit)return{state:nextState,previous:nextPrevious};let nextResilience={...snapshot,circuit};if(!nextState.prReviewResilience||nextState.prReviewResilience.circuit?.signature!==circuit.signature||nextState.prReviewResilience.circuit?.count!==circuit.count)nextState=await writeStateWhileLocked(directory,{...nextState,updatedAt:isoNow(),prReviewResilience:nextResilience}),nextPrevious=nextState.prReviewBaseDispatches??[];throw new PrReviewResilienceCircuitOpenError(formatPrReviewResilienceCircuitOpenMessage(circuit))}async function probeResilienceCanaryLiveness(directory,records,timeoutMs){let session=_test_exports2.getSessionOps(),status=session?.status;if(!session||typeof status!=="function")return{live:!1,reason:"status probe unavailable"};let timeoutError=Error("PR workflow resilience canary probe exceeded its deadline"),response;try{response=await withTimeout((async()=>status.call(session,{query:{directory}}))(),timeoutMs,timeoutError)}catch(error49){return{live:!1,reason:error49===timeoutError?"status probe timed out":"status probe failed"}}if(response?.error)return{live:!1,reason:"status probe errored"};if(!response?.data)return{live:!1,reason:"status probe returned no data"};for(let record2 of records){let type=response.data[record2.subagentSessionId]?.type;if(type==="busy"||type==="retry")return{live:!0}}return{live:!1,reason:"status probe did not report busy/retry"}}async function evaluatePrReviewResilienceAttempt(directory,state,attempt,revisionDigest,policy){let attempts=summarizePrReviewBaseDimensionAttempts(directory,state,revisionDigest),remaining=attempt.targetDimensions.filter((dimension)=>!attempts.successful.has(dimension)&&!attempts.inFlight.has(dimension)),inFlight=attempt.targetDimensions.filter((dimension)=>attempts.inFlight.has(dimension));if(remaining.length===0&&inFlight.length===0)return{remaining:[],inFlight:[],canaryState:"success",fanoutSettled:Boolean(attempt.fanoutBatchId)};if(attempts.successful.has(attempt.canaryWorkflowLane))return{remaining,inFlight,canaryState:"success",fanoutSettled:attempt.fanoutBatchId?batchIsTerminal(directory,state,attempt.fanoutBatchId):!1};let canaryRecords=batchLaneRecords(directory,state,attempt.canaryBatchId,attempt.canaryLaneId);if(canaryRecords.length>0&&canaryRecords.every((record2)=>TERMINAL_FAILED_DELEGATION_STATUSES.has(record2.status)))return{remaining,inFlight,canaryState:"failed",fanoutSettled:!1};let admittedAtMs=Date.parse(attempt.admittedAt);if(Number.isFinite(admittedAtMs)&&_test_exports2.nowMs()-admittedAtMs<policy.canaryProbeMs)return{remaining,inFlight,canaryState:"waiting",reason:"canary probe horizon has not elapsed yet",fanoutSettled:!1};let probe2=await probeResilienceCanaryLiveness(directory,canaryRecords,policy.statusProbeTimeoutMs);if(probe2.live)return{remaining,inFlight,canaryState:"live",fanoutSettled:!1};return{remaining,inFlight,canaryState:"waiting",reason:probe2.reason,fanoutSettled:!1}}function unresolvedPrReviewBaseDimensions(attempts){return PR_REVIEW_BASE_DIMENSION_IDS.filter((dimension)=>!attempts.successful.has(dimension)&&!attempts.inFlight.has(dimension))}async function enforcePrReviewBaseDimensions(directory,sessionID,lanes,options){let normalizedSessionID=normalizeSessionID(sessionID);return withPrWorkflowCheckoutMutationLock(directory,async()=>withSessionStateMutation(directory,normalizedSessionID,async()=>enforcePrReviewBaseDimensionsWhileLocked(directory,normalizedSessionID,lanes,options)))}async function enforcePrReviewBaseDimensionsWhileLocked(directory,normalizedSessionID,lanes,options){let state=await bindPrWorkflowHeadWhileLocked(directory,normalizedSessionID,options.prHeadSha);if(state.mode!=="PR_REVIEW")throw wrongModeError(state,"PR_REVIEW");let normalizedLanes=normalizeWorkflowLanes(lanes),claimedDimensionIds=declaredBaseDimensions(normalizedLanes);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`);let depthTier=state.prReviewDepthTier??"L",requestedWaveStage=options.prReviewWaveStage,requestedWaveAttempt=options.prReviewWaveAttempt;if(requestedWaveStage===void 0!==(requestedWaveAttempt===void 0))throw Error("BLOCKED: PR_REVIEW staged base dispatch requires both pr_review_wave_stage and pr_review_wave_attempt together");let resiliencePolicy=effectivePrReviewResiliencePolicy(state,options.prReviewResiliencePolicy);if(previous.length>=MAX_WORKFLOW_BATCHES&&requestedWaveStage!==void 0&&requestedWaveAttempt!==void 0&&depthTier!=="S"&&resiliencePolicy.enabled)({state,previous}=await preflightPrReviewResilienceCircuitBeforePrune(directory,state,previous,resiliencePolicy));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 nextResilience=state.prReviewResilience;if(!nextResilience){if(nextResilience={policy:resiliencePolicy,attempts:[]},previous.length>0)state=await writeStateWhileLocked(directory,{...state,updatedAt:isoNow(),prReviewResilience:nextResilience}),previous=state.prReviewBaseDispatches??[]}if(resiliencePolicy.enabled&&depthTier!=="S"&&requestedWaveStage===void 0)throw Error("BLOCKED: PR_REVIEW base dispatch at depth tier M or L requires canary-first staged admission while pr_review_resilience is enabled");if(requestedWaveStage!==void 0&&requestedWaveAttempt!==void 0){if(depthTier==="S"||!resiliencePolicy.enabled)throw Error("BLOCKED: staged PR_REVIEW base dispatch is valid only when pr_review_resilience is enabled at depth tier M or L");let revisionDigest=options.revisionDigest;if(!revisionDigest)revisionDigest=(await createPrReviewGateContext(directory,state)).revisionDigest;let snapshot=nextResilience??{policy:resiliencePolicy,attempts:[]};if(snapshot.circuit)throw new PrReviewResilienceCircuitOpenError(formatPrReviewResilienceCircuitOpenMessage(snapshot.circuit));let circuit=computePrReviewResilienceCircuit(directory,state,snapshot.policy);if(circuit){if(nextResilience={...snapshot,circuit},!state.prReviewResilience||state.prReviewResilience.circuit?.signature!==circuit.signature||state.prReviewResilience.circuit?.count!==circuit.count)await writeStateWhileLocked(directory,{...state,updatedAt:isoNow(),prReviewResilience:nextResilience});throw new PrReviewResilienceCircuitOpenError(formatPrReviewResilienceCircuitOpenMessage(circuit))}let lastAttempt=snapshot.attempts.at(-1);if(requestedWaveStage==="canary"){let target=[...PR_REVIEW_BASE_DIMENSION_IDS],expectedAttempt=0,globalInFlight=[];if(lastAttempt){let globalAttempts=summarizePrReviewBaseDimensionAttempts(directory,state,revisionDigest);globalInFlight=PR_REVIEW_BASE_DIMENSION_IDS.filter((dimension)=>globalAttempts.inFlight.has(dimension));let globalTarget=unresolvedPrReviewBaseDimensions(globalAttempts),evaluated=await evaluatePrReviewResilienceAttempt(directory,state,lastAttempt,revisionDigest,snapshot.policy);if(!lastAttempt.fanoutBatchId)if(evaluated.canaryState==="success"){if(evaluated.remaining.length>0)throw Error(`BLOCKED: PR_REVIEW base attempt ${lastAttempt.attempt} requires its fanout batch before a later retry attempt`);if(globalTarget.length===0)throw new PrReviewResilienceRetryExhaustedError("BLOCKED: PR_REVIEW base dispatch has no unresolved obligations remaining");target=[...globalTarget]}else{if(evaluated.canaryState==="live")throw Error(`BLOCKED: PR_REVIEW base attempt ${lastAttempt.attempt} canary is still live; fanout is the next admissible stage`);if(evaluated.canaryState==="waiting")throw Error(`BLOCKED: PR_REVIEW base attempt ${lastAttempt.attempt} canary is not yet proven successful or live: ${evaluated.reason??"probe failed closed"}`);target=[...globalTarget]}else{if(!batchIsTerminal(directory,state,lastAttempt.fanoutBatchId))throw Error(`BLOCKED: PR_REVIEW base attempt ${lastAttempt.attempt} fanout is still in flight`);target=[...globalTarget]}expectedAttempt=lastAttempt.attempt+1}else if(previous.length>0){let globalAttempts=summarizePrReviewBaseDimensionAttempts(directory,state,revisionDigest);globalInFlight=PR_REVIEW_BASE_DIMENSION_IDS.filter((dimension)=>globalAttempts.inFlight.has(dimension)),target=unresolvedPrReviewBaseDimensions(globalAttempts)}if(target.length===0){if(globalInFlight.length>0)throw Error(lastAttempt?`BLOCKED: PR_REVIEW base attempt ${lastAttempt.attempt} still has in-flight obligations that cannot be retried yet: ${globalInFlight.join(", ")}`:`BLOCKED: PR_REVIEW base still has in-flight obligations that cannot be retried yet: ${globalInFlight.join(", ")}`);throw new PrReviewResilienceRetryExhaustedError("BLOCKED: PR_REVIEW base dispatch has no unresolved obligations remaining")}if(requestedWaveAttempt!==expectedAttempt||requestedWaveAttempt>snapshot.policy.maxRetryAttemptsAfterInitial)throw new PrReviewResilienceRetryExhaustedError(`BLOCKED: PR_REVIEW base allows attempt 0 plus at most ${snapshot.policy.maxRetryAttemptsAfterInitial} retry attempts`);if(normalizedLanes.length!==1||(normalizedLanes[0]?.ownedWorkflowLanes?.length??1)!==1)throw Error("BLOCKED: PR_REVIEW staged canary dispatch requires exactly one singleton base lane");let canaryDimension=normalizedLanes[0].workflowLane;if(!target.includes(canaryDimension))throw Error(`BLOCKED: PR_REVIEW canary lane must target one unresolved base obligation from: ${target.join(", ")}`);nextResilience={policy:snapshot.policy,attempts:[...snapshot.attempts,{attempt:requestedWaveAttempt,targetDimensions:target,canaryBatchId:batchId,canaryLaneId:normalizedLanes[0].laneId,canaryWorkflowLane:canaryDimension,admittedAt:isoNow()}]}}else{if(!lastAttempt||lastAttempt.attempt!==requestedWaveAttempt||lastAttempt.fanoutBatchId)throw Error(`BLOCKED: PR_REVIEW base fanout must follow the recorded canary for attempt ${requestedWaveAttempt}`);let evaluated=await evaluatePrReviewResilienceAttempt(directory,state,lastAttempt,revisionDigest,snapshot.policy);if(evaluated.canaryState==="failed")throw Error(`BLOCKED: PR_REVIEW base attempt ${requestedWaveAttempt} canary failed; close the attempt and carry the unresolved target into the next retry`);if(evaluated.canaryState==="waiting")throw Error(`BLOCKED: PR_REVIEW base attempt ${requestedWaveAttempt} canary is not yet proven successful or live: ${evaluated.reason??"probe failed closed"}`);let remainingTarget=lastAttempt.targetDimensions.filter((dimension)=>dimension!==lastAttempt.canaryWorkflowLane&&evaluated.remaining.includes(dimension));if(remainingTarget.length===0)throw Error(`BLOCKED: PR_REVIEW base attempt ${requestedWaveAttempt} has no remaining unresolved obligations for fanout`);if(!exactDimensionPartition(declaredBaseDimensions(normalizedLanes),remainingTarget))throw Error(`BLOCKED: PR_REVIEW base fanout must partition the remaining unresolved obligations exactly once: ${remainingTarget.join(", ")}`);if(requestedWaveAttempt===0){let combinedDimensions=[lastAttempt.canaryWorkflowLane,...declaredBaseDimensions(normalizedLanes)];if(!exactDimensionPartition(combinedDimensions,lastAttempt.targetDimensions))throw Error("BLOCKED: PR_REVIEW base attempt 0 canary plus fanout must partition all six base dimensions exactly once");if(depthTier==="M"&&normalizedLanes.length+1<PR_REVIEW_BASE_LANE_FLOORS.M)throw Error(`BLOCKED: PR_REVIEW base attempt 0 at depth tier M requires at least ${PR_REVIEW_BASE_LANE_FLOORS.M} combined canary+fanout lanes`);if(depthTier==="L"&&(normalizedLanes.length+1!==PR_REVIEW_BASE_DIMENSION_IDS.length||normalizedLanes.some((lane)=>(lane.ownedWorkflowLanes?.length??1)!==1)))throw Error("BLOCKED: PR_REVIEW base attempt 0 at depth tier L requires six singleton combined canary+fanout lanes")}nextResilience={...snapshot,attempts:[...snapshot.attempts.slice(0,-1),{...lastAttempt,fanoutBatchId:batchId}]}}}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,...nextResilience?{prReviewResilience:nextResilience}:{}};return writeStateWhileLocked(directory,nextState)}async function rollbackPrReviewBaseAdmissionIfUnlaunched(directory,sessionID,batchId){let normalizedSessionID=normalizeSessionID(sessionID),normalizedBatchId=normalizeBatchId(batchId);return withPrWorkflowCheckoutMutationLock(directory,async()=>withSessionStateMutation(directory,normalizedSessionID,async()=>{let state=await readPrWorkflowGateState(directory,normalizedSessionID);if(!state||state.mode!=="PR_REVIEW")return!1;let currentBaseDispatches=state.prReviewBaseDispatches??[];if(currentBaseDispatches.at(-1)?.batchId!==normalizedBatchId)return!1;if(findByBatchId(directory,normalizedBatchId,{parentSessionId:normalizedSessionID}).length>0)return!1;let nextBaseDispatches=currentBaseDispatches.slice(0,-1),lastAttempt=state.prReviewResilience?.attempts.at(-1),nextResilience=state.prReviewResilience;if(lastAttempt?.canaryBatchId===normalizedBatchId)nextResilience=nextResilience?{...nextResilience,attempts:nextResilience.attempts.slice(0,-1)}:nextResilience;else if(lastAttempt?.fanoutBatchId===normalizedBatchId)nextResilience=nextResilience?{...nextResilience,attempts:[...nextResilience.attempts.slice(0,-1),{...lastAttempt,fanoutBatchId:void 0}]}:nextResilience;let shouldKeepResilience=nextBaseDispatches.length>0&&Boolean(nextResilience?.policy)||Boolean(nextResilience?.circuit)||(nextResilience?.attempts.length??0)>0;return await writeStateWhileLocked(directory,{...state,updatedAt:isoNow(),prReviewBaseDispatches:nextBaseDispatches,...nextBaseDispatches.length>0?{prReviewBaseDispatch:nextBaseDispatches.at(-1)}:{prReviewBaseDispatch:void 0},...shouldKeepResilience?{prReviewResilience:nextResilience}:{prReviewResilience:void 0}}),!0}))}function summarizePrReviewBaseDimensionAttempts(directory,state,revisionDigest){let successful2=new Set,inFlight=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)successful2.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 semanticallyValidLaneIds=new Set(recordsPassingBatchIntegrity(directory,state,batch.batchId,batch.lanes,"swarm-pr-review:base",batch.validatedAt).filter((qualified)=>hasRevisionIndependentDiscoverySemantics(directory,qualified)).map((qualified)=>qualified.record.laneId)),records=findByBatchId(directory,batch.batchId,{parentSessionId:state.sessionID});for(let lane of batch.lanes){if(semanticallyValidLaneIds.has(lane.laneId))continue;let laneRecords=records.filter((record2)=>record2.laneId===lane.laneId);if(laneRecords.length===0)continue;if(!laneRecords.every((record2)=>TERMINAL_FAILED_DELEGATION_STATUSES.has(record2.status))){for(let dimension of lane.ownedWorkflowLanes?.length?lane.ownedWorkflowLanes:[lane.workflowLane])inFlight.add(dimension);continue}for(let dimension of lane.ownedWorkflowLanes?.length?lane.ownedWorkflowLanes:[lane.workflowLane])terminallyFailed.add(dimension)}}return{successful:successful2,inFlight,dedicatedSuccessful,terminallyFailed}}function hasRevisionIndependentDiscoverySemantics(directory,qualified){let ref=qualified.record.result?.outputRef?.trim();if(!ref)return!1;let artifact=readLaneOutput(directory,ref)?.artifact??null;if(!artifact?.revisionDigest?.trim())return!1;return validatePrReviewDiscoveryLaneCompletion({record:qualified.record,result:qualified.record.result,artifact,expected:{mode:"swarm-pr-review:base",workflowLane:qualified.expectedWorkflowLane,ownedWorkflowLanes:qualified.expectedOwnedLanes,prHeadSha:qualified.record.workspace?.prHeadSha??"",gitHead:qualified.record.workspace?.gitHead??"",revisionDigest:artifact.revisionDigest,reviewScope:qualified.record.workspace?.scope??void 0}}).ok}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 successful2=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)=>successful2.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 successful2=successfulObligationsFromExactBatch(directory,state,batch.batchId,batch.lanes,"swarm-pr-review:base",batch.validatedAt,!0,new Set,ctx.revisionDigest,malformedDiagnostics);for(let obligation of successful2)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),assertStringSetSubset(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,reviewerItemBindingKeyEncoding:"prefixed-v1"}:{}};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=createHash34("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_exports2.resolveCurrentGitHeadAsync(directory))?.trim()!==armed.localHead)throw Error("BLOCKED: PR_FEEDBACK current Git HEAD changed after publication was armed");if(await _test_exports2.resolveIsWorkingTreeCleanAsync(directory)!==!0)throw Error("BLOCKED: PR_FEEDBACK working tree changed after publication was armed");let currentTarget=await _test_exports2.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 normalizedPath2=artifactPath.trim();if(!normalizedPath2)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:normalizedPath2,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 (write_pr_review_trigger_eval must complete first)");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())){let actualSet=new Set(normalizedFindingIds),expectedSet=new Set(expectedFindingIds),missing=[...expectedSet].filter((id)=>!actualSet.has(id)),extra=[...actualSet].filter((id)=>!expectedSet.has(id)),duplicates=[...new Set(findingIds.filter((id,index)=>findingIds.indexOf(id)!==index))].sort();throw Error(`BLOCKED: PR_REVIEW ${boundary} findings must exactly cover the discovered candidate inventory; missing: ${missing.join(", ")||"(none)"}; extra: ${extra.join(", ")||"(none)"}; duplicates: ${duplicates.join(", ")||"(none)"}`)}return state}async function assertPrReviewArtifactRecordsMatchAuthoritativeVerdicts(directory,sessionID,boundary,records){let state=await requireBoundState(directory,sessionID,"PR_REVIEW"),violations=[],report=(findingId,field,expected,actual)=>{violations.push({findingId,detail:`${field} expected ${expected}, got ${actual}`})},reportSeverity=(record2,expected)=>{if(record2.severity===expected)return;let raw=record2.severity,actual=raw===void 0?"(omitted)":raw===null?"(null)":raw===""?"(empty)":`"${raw}"`;report(record2.finding_id,"severity",`"${expected}"`,actual)};if(boundary==="post_explorer"){let candidateSeverities=derivePrReviewCandidateSeverities(directory,state,await createPrReviewGateContext(directory,state));for(let record2 of records){if(record2.status!=="PENDING")report(record2.finding_id,"status",'"PENDING"',`"${record2.status}"`);if(record2.next_action!=="route_to_reviewer")report(record2.finding_id,"next_action",'"route_to_reviewer"',`"${record2.next_action}"`);let candidateSeverity=candidateSeverities.get(record2.finding_id);if(candidateSeverity){reportSeverity(record2,candidateSeverity);continue}if(record2.finding_id===PR_REVIEW_CLEAN_SENTINEL_ID){reportSeverity(record2,"NONE");continue}violations.push({findingId:record2.finding_id,detail:"no authoritative candidate severity (absent from the derived candidate inventory)"})}}else{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){violations.push({findingId:record2.finding_id,detail:"no authoritative reviewer verdict (absent from the settled reviewer map)"});continue}let requiresCritic=reviewer.classification==="CONFIRMED"&&["CRITICAL","HIGH","MEDIUM"].includes(reviewer.severity),expectedStatus=reviewer.classification==="UNVERIFIED"?"PENDING":reviewer.classification;if(boundary==="post_reviewer"){if(record2.status!==expectedStatus)report(record2.finding_id,"status",`"${expectedStatus}"`,`"${record2.status}"`);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)report(record2.finding_id,"next_action",`"${expectedAction}"`,`"${record2.next_action}"`);reportSeverity(record2,reviewer.severity);continue}if(!requiresCritic){let expectedAction=reviewer.classification==="CONFIRMED"||reviewer.classification==="PRE_EXISTING"?"report":reviewer.classification==="DISPROVED"?"suppress_with_reason":"route_to_reviewer";if(record2.status!==expectedStatus)report(record2.finding_id,"status",`"${expectedStatus}"`,`"${record2.status}"`);if(record2.next_action!==expectedAction)report(record2.finding_id,"next_action",`"${expectedAction}"`,`"${record2.next_action}"`);reportSeverity(record2,reviewer.severity);continue}let critic=criticVerdicts?.get(record2.finding_id);if(!critic){reportSeverity(record2,reviewer.severity),violations.push({findingId:record2.finding_id,detail:"no authoritative critic verdict (absent from the settled critic map)"});continue}if(critic.status==="DISPROVED"){if(record2.status!=="DISPROVED")report(record2.finding_id,"status",'"DISPROVED"',`"${record2.status}"`);if(record2.next_action!=="suppress_with_reason")report(record2.finding_id,"next_action",'"suppress_with_reason"',`"${record2.next_action}"`)}else{if(record2.status!=="CONFIRMED")report(record2.finding_id,"status",'"CONFIRMED"',`"${record2.status}"`);if(!["report","handoff_to_feedback"].includes(record2.next_action))report(record2.finding_id,"next_action",'"report" or "handoff_to_feedback"',`"${record2.next_action}"`)}reportSeverity(record2,critic.severity)}}if(violations.length>0){violations.sort((left,right)=>left.findingId<right.findingId?-1:left.findingId>right.findingId?1:0);let lines=violations.map((violation)=>` ${violation.findingId}: ${violation.detail}`);throw Error(`BLOCKED: PR_REVIEW ${boundary} artifact invalid — ${violations.length} violation(s):
|
|
880
|
+
`,"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_exports2.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_exports2.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_exports2.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_exports2.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_exports2.resolveCurrentUpstreamPushTargetAsync(directory),matchingRemoteRefs=await _test_exports2.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_exports2.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_exports2.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_exports2.afterPrFeedbackTrackingSwitch?.();let attachedHead=(await _test_exports2.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_exports2.resolveIsWorkingTreeCleanAsync(directory)!==!0)throw Error("BLOCKED: PR_FEEDBACK requires a clean working tree after checkout attachment");let attachedUpstream=await _test_exports2.resolveCurrentUpstreamPushTargetAsync(directory);if(!attachedUpstream)throw Error("BLOCKED: PR_FEEDBACK could not resolve the attached branch upstream after checkout promotion");if(!(await _test_exports2.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}function snapshotPrReviewResiliencePolicy(policy){return{enabled:policy?.enabled??!0,canaryProbeMs:policy?.canary_probe_ms??300000,statusProbeTimeoutMs:policy?.status_probe_timeout_ms??2000,correlatedFailureThreshold:policy?.correlated_failure_threshold??2,maxRetryAttemptsAfterInitial:policy?.max_retry_attempts_after_initial??2}}function declaredBaseDimensions(lanes){return lanes.flatMap((lane)=>lane.ownedWorkflowLanes?.length?lane.ownedWorkflowLanes:[lane.workflowLane])}function exactDimensionPartition(actual,expected){return actual.length===expected.length&&new Set(actual).size===expected.length&&expected.every((dimension)=>actual.includes(dimension))}function latestDelegationRecord(records){return[...records].sort((left,right)=>{let leftKey=left.completedAt??left.updatedAt??left.createdAt;return(right.completedAt??right.updatedAt??right.createdAt)-leftKey})[0]??null}function batchLaneRecords(directory,state,batchId,laneId){return findByBatchId(directory,batchId,{parentSessionId:state.sessionID}).filter((record2)=>record2.laneId===laneId)}function baseLaneDimensions(lane){return lane.ownedWorkflowLanes?.length?lane.ownedWorkflowLanes:[lane.workflowLane]}function batchIsTerminal(directory,state,batchId){let records=findByBatchId(directory,batchId,{parentSessionId:state.sessionID});return records.length>0&&records.every((record2)=>TERMINAL_FAILED_DELEGATION_STATUSES.has(record2.status)||record2.status==="consumed")}function effectivePrReviewResiliencePolicy(state,requestedPolicy){return state.prReviewResilience?.policy??snapshotPrReviewResiliencePolicy(requestedPolicy)}function normalizeFailureSignatureText(value){return value.toLowerCase().replace(/\b\d{4}-\d{2}-\d{2}t\d{2}:\d{2}:\d{2}(?:\.\d{1,6})?(?:z|[+-]\d{2}:\d{2})\b/g,"<iso-timestamp>").replace(/\b\d{10,16}\b/g,"<epoch>").replace(/\b((?:session|request|trace|correlation|run)(?:[_-]?id)?)\s*[:=]\s*([a-z0-9._:-]*[0-9_-][a-z0-9._:-]*)\b/g,"$1=<id>").replace(/\b((?:session|sess|request|req|trace|correlation|corr|run)(?:[_-]?id)?)\s+((?:(?:sess?|req|trace|corr|run)[_-][a-z0-9._:-]+|[a-z][a-z0-9._:-]*\d[a-z0-9._:-]*))\b/g,"$1 <id>").replace(/\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/g,"<uuid>").replace(/\b[0-9a-f]{16,64}\b/g,"<hex>").replace(/[a-z]:\\[^\s)]+/gi,"<path>").replace(/(?:\/[\w.@:-]+)+/g,"<path>").replace(/\s+/g," ").trim().slice(0,160)}function classifyTerminalFailureSignature(record2){if(!TERMINAL_FAILED_DELEGATION_STATUSES.has(record2.status))return null;let result=record2.terminalResult?.result??record2.result;if(!result)return`terminal-zero-output:${record2.status}`;let outputRef=result.outputRef?.trim(),text=result.text?.trim()??"";if(!outputRef&&text.length===0&&(result.chars??0)===0)return`terminal-zero-output:${record2.status}`;let errorText=result.error?.trim();if(errorText)return`terminal-error-output:${record2.status}:${normalizeFailureSignatureText(errorText)}`;if(record2.status==="completed")return null;return`terminal-nonzero-output:${record2.status}`}function computePrReviewResilienceCircuit(directory,state,policy){let signatures=new Map;for(let batch of state.prReviewBaseDispatches??[])for(let lane of batch.lanes){let latest=latestDelegationRecord(batchLaneRecords(directory,state,batch.batchId,lane.laneId));if(!latest)continue;let signature=classifyTerminalFailureSignature(latest);if(!signature)continue;let current=signatures.get(signature)??{dimensions:new Set,contributors:[]};for(let dimension of baseLaneDimensions(lane)){if(current.dimensions.has(dimension))continue;current.dimensions.add(dimension),current.contributors.push({batchId:batch.batchId,laneId:lane.laneId})}signatures.set(signature,current)}let opened=[...signatures.entries()].filter(([,entry])=>entry.dimensions.size>=policy.correlatedFailureThreshold).sort((left,right)=>right[1].dimensions.size-left[1].dimensions.size||left[0].localeCompare(right[0]))[0];if(!opened)return null;return{signature:opened[0],count:opened[1].dimensions.size,contributors:opened[1].contributors,openedAt:state.prReviewResilience?.circuit?.openedAt??isoNow()}}function formatPrReviewResilienceCircuitOpenMessage(circuit){return`BLOCKED: PR_REVIEW base dispatch circuit is open after ${circuit.count} correlated terminal failures (${circuit.signature}); collect every launched lane, abort_pr_workflow, and stop without partial findings`}async function preflightPrReviewResilienceCircuitBeforePrune(directory,state,previous,policy){let nextState=state,nextPrevious=previous,snapshot=nextState.prReviewResilience;if(!snapshot){if(snapshot={policy,attempts:[]},nextPrevious.length>0)nextState=await writeStateWhileLocked(directory,{...nextState,updatedAt:isoNow(),prReviewResilience:snapshot}),nextPrevious=nextState.prReviewBaseDispatches??[],snapshot=nextState.prReviewResilience??snapshot}if(snapshot.circuit)throw new PrReviewResilienceCircuitOpenError(formatPrReviewResilienceCircuitOpenMessage(snapshot.circuit));let circuit=computePrReviewResilienceCircuit(directory,nextState,policy);if(!circuit)return{state:nextState,previous:nextPrevious};let nextResilience={...snapshot,circuit};if(!nextState.prReviewResilience||nextState.prReviewResilience.circuit?.signature!==circuit.signature||nextState.prReviewResilience.circuit?.count!==circuit.count)nextState=await writeStateWhileLocked(directory,{...nextState,updatedAt:isoNow(),prReviewResilience:nextResilience}),nextPrevious=nextState.prReviewBaseDispatches??[];throw new PrReviewResilienceCircuitOpenError(formatPrReviewResilienceCircuitOpenMessage(circuit))}async function probeResilienceCanaryLiveness(directory,records,timeoutMs){let session=_test_exports2.getSessionOps(),status=session?.status;if(!session||typeof status!=="function")return{live:!1,reason:"status probe unavailable"};let timeoutError=Error("PR workflow resilience canary probe exceeded its deadline"),response;try{response=await withTimeout((async()=>status.call(session,{query:{directory}}))(),timeoutMs,timeoutError)}catch(error49){return{live:!1,reason:error49===timeoutError?"status probe timed out":"status probe failed"}}if(response?.error)return{live:!1,reason:"status probe errored"};if(!response?.data)return{live:!1,reason:"status probe returned no data"};for(let record2 of records){let type=response.data[record2.subagentSessionId]?.type;if(type==="busy"||type==="retry")return{live:!0}}return{live:!1,reason:"status probe did not report busy/retry"}}async function evaluatePrReviewResilienceAttempt(directory,state,attempt,revisionDigest,policy){let attempts=summarizePrReviewBaseDimensionAttempts(directory,state,revisionDigest),remaining=attempt.targetDimensions.filter((dimension)=>!attempts.successful.has(dimension)&&!attempts.inFlight.has(dimension)),inFlight=attempt.targetDimensions.filter((dimension)=>attempts.inFlight.has(dimension));if(remaining.length===0&&inFlight.length===0)return{remaining:[],inFlight:[],canaryState:"success",fanoutSettled:Boolean(attempt.fanoutBatchId)};if(attempts.successful.has(attempt.canaryWorkflowLane))return{remaining,inFlight,canaryState:"success",fanoutSettled:attempt.fanoutBatchId?batchIsTerminal(directory,state,attempt.fanoutBatchId):!1};let canaryRecords=batchLaneRecords(directory,state,attempt.canaryBatchId,attempt.canaryLaneId);if(canaryRecords.length>0&&canaryRecords.every((record2)=>TERMINAL_FAILED_DELEGATION_STATUSES.has(record2.status)))return{remaining,inFlight,canaryState:"failed",fanoutSettled:!1};let admittedAtMs=Date.parse(attempt.admittedAt);if(Number.isFinite(admittedAtMs)&&_test_exports2.nowMs()-admittedAtMs<policy.canaryProbeMs)return{remaining,inFlight,canaryState:"waiting",reason:"canary probe horizon has not elapsed yet",fanoutSettled:!1};let probe2=await probeResilienceCanaryLiveness(directory,canaryRecords,policy.statusProbeTimeoutMs);if(probe2.live)return{remaining,inFlight,canaryState:"live",fanoutSettled:!1};return{remaining,inFlight,canaryState:"waiting",reason:probe2.reason,fanoutSettled:!1}}function unresolvedPrReviewBaseDimensions(attempts){return PR_REVIEW_BASE_DIMENSION_IDS.filter((dimension)=>!attempts.successful.has(dimension)&&!attempts.inFlight.has(dimension))}async function enforcePrReviewBaseDimensions(directory,sessionID,lanes,options){let normalizedSessionID=normalizeSessionID(sessionID);return withPrWorkflowCheckoutMutationLock(directory,async()=>withSessionStateMutation(directory,normalizedSessionID,async()=>enforcePrReviewBaseDimensionsWhileLocked(directory,normalizedSessionID,lanes,options)))}async function enforcePrReviewBaseDimensionsWhileLocked(directory,normalizedSessionID,lanes,options){let state=await bindPrWorkflowHeadWhileLocked(directory,normalizedSessionID,options.prHeadSha);if(state.mode!=="PR_REVIEW")throw wrongModeError(state,"PR_REVIEW");let normalizedLanes=normalizeWorkflowLanes(lanes),claimedDimensionIds=declaredBaseDimensions(normalizedLanes);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`);let depthTier=state.prReviewDepthTier??"L",requestedWaveStage=options.prReviewWaveStage,requestedWaveAttempt=options.prReviewWaveAttempt;if(requestedWaveStage===void 0!==(requestedWaveAttempt===void 0))throw Error("BLOCKED: PR_REVIEW staged base dispatch requires both pr_review_wave_stage and pr_review_wave_attempt together");let resiliencePolicy=effectivePrReviewResiliencePolicy(state,options.prReviewResiliencePolicy);if(previous.length>=MAX_WORKFLOW_BATCHES&&requestedWaveStage!==void 0&&requestedWaveAttempt!==void 0&&depthTier!=="S"&&resiliencePolicy.enabled)({state,previous}=await preflightPrReviewResilienceCircuitBeforePrune(directory,state,previous,resiliencePolicy));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 nextResilience=state.prReviewResilience;if(!nextResilience){if(nextResilience={policy:resiliencePolicy,attempts:[]},previous.length>0)state=await writeStateWhileLocked(directory,{...state,updatedAt:isoNow(),prReviewResilience:nextResilience}),previous=state.prReviewBaseDispatches??[]}if(resiliencePolicy.enabled&&depthTier!=="S"&&requestedWaveStage===void 0)throw Error("BLOCKED: PR_REVIEW base dispatch at depth tier M or L requires canary-first staged admission while pr_review_resilience is enabled");if(requestedWaveStage!==void 0&&requestedWaveAttempt!==void 0){if(depthTier==="S"||!resiliencePolicy.enabled)throw Error("BLOCKED: staged PR_REVIEW base dispatch is valid only when pr_review_resilience is enabled at depth tier M or L");let revisionDigest=options.revisionDigest;if(!revisionDigest)revisionDigest=(await createPrReviewGateContext(directory,state)).revisionDigest;let snapshot=nextResilience??{policy:resiliencePolicy,attempts:[]};if(snapshot.circuit)throw new PrReviewResilienceCircuitOpenError(formatPrReviewResilienceCircuitOpenMessage(snapshot.circuit));let circuit=computePrReviewResilienceCircuit(directory,state,snapshot.policy);if(circuit){if(nextResilience={...snapshot,circuit},!state.prReviewResilience||state.prReviewResilience.circuit?.signature!==circuit.signature||state.prReviewResilience.circuit?.count!==circuit.count)await writeStateWhileLocked(directory,{...state,updatedAt:isoNow(),prReviewResilience:nextResilience});throw new PrReviewResilienceCircuitOpenError(formatPrReviewResilienceCircuitOpenMessage(circuit))}let lastAttempt=snapshot.attempts.at(-1);if(requestedWaveStage==="canary"){let target=[...PR_REVIEW_BASE_DIMENSION_IDS],expectedAttempt=0,globalInFlight=[];if(lastAttempt){let globalAttempts=summarizePrReviewBaseDimensionAttempts(directory,state,revisionDigest);globalInFlight=PR_REVIEW_BASE_DIMENSION_IDS.filter((dimension)=>globalAttempts.inFlight.has(dimension));let globalTarget=unresolvedPrReviewBaseDimensions(globalAttempts),evaluated=await evaluatePrReviewResilienceAttempt(directory,state,lastAttempt,revisionDigest,snapshot.policy);if(!lastAttempt.fanoutBatchId)if(evaluated.canaryState==="success"){if(evaluated.remaining.length>0)throw Error(`BLOCKED: PR_REVIEW base attempt ${lastAttempt.attempt} requires its fanout batch before a later retry attempt`);if(globalTarget.length===0)throw new PrReviewResilienceRetryExhaustedError("BLOCKED: PR_REVIEW base dispatch has no unresolved obligations remaining");target=[...globalTarget]}else{if(evaluated.canaryState==="live")throw Error(`BLOCKED: PR_REVIEW base attempt ${lastAttempt.attempt} canary is still live; fanout is the next admissible stage`);if(evaluated.canaryState==="waiting")throw Error(`BLOCKED: PR_REVIEW base attempt ${lastAttempt.attempt} canary is not yet proven successful or live: ${evaluated.reason??"probe failed closed"}`);target=[...globalTarget]}else{if(!batchIsTerminal(directory,state,lastAttempt.fanoutBatchId))throw Error(`BLOCKED: PR_REVIEW base attempt ${lastAttempt.attempt} fanout is still in flight`);target=[...globalTarget]}expectedAttempt=lastAttempt.attempt+1}else if(previous.length>0){let globalAttempts=summarizePrReviewBaseDimensionAttempts(directory,state,revisionDigest);globalInFlight=PR_REVIEW_BASE_DIMENSION_IDS.filter((dimension)=>globalAttempts.inFlight.has(dimension)),target=unresolvedPrReviewBaseDimensions(globalAttempts)}if(target.length===0){if(globalInFlight.length>0)throw Error(lastAttempt?`BLOCKED: PR_REVIEW base attempt ${lastAttempt.attempt} still has in-flight obligations that cannot be retried yet: ${globalInFlight.join(", ")}`:`BLOCKED: PR_REVIEW base still has in-flight obligations that cannot be retried yet: ${globalInFlight.join(", ")}`);throw new PrReviewResilienceRetryExhaustedError("BLOCKED: PR_REVIEW base dispatch has no unresolved obligations remaining")}if(requestedWaveAttempt!==expectedAttempt||requestedWaveAttempt>snapshot.policy.maxRetryAttemptsAfterInitial)throw new PrReviewResilienceRetryExhaustedError(`BLOCKED: PR_REVIEW base allows attempt 0 plus at most ${snapshot.policy.maxRetryAttemptsAfterInitial} retry attempts`);if(normalizedLanes.length!==1||(normalizedLanes[0]?.ownedWorkflowLanes?.length??1)!==1)throw Error("BLOCKED: PR_REVIEW staged canary dispatch requires exactly one singleton base lane");let canaryDimension=normalizedLanes[0].workflowLane;if(!target.includes(canaryDimension))throw Error(`BLOCKED: PR_REVIEW canary lane must target one unresolved base obligation from: ${target.join(", ")}`);nextResilience={policy:snapshot.policy,attempts:[...snapshot.attempts,{attempt:requestedWaveAttempt,targetDimensions:target,canaryBatchId:batchId,canaryLaneId:normalizedLanes[0].laneId,canaryWorkflowLane:canaryDimension,admittedAt:isoNow()}]}}else{if(!lastAttempt||lastAttempt.attempt!==requestedWaveAttempt||lastAttempt.fanoutBatchId)throw Error(`BLOCKED: PR_REVIEW base fanout must follow the recorded canary for attempt ${requestedWaveAttempt}`);let evaluated=await evaluatePrReviewResilienceAttempt(directory,state,lastAttempt,revisionDigest,snapshot.policy);if(evaluated.canaryState==="failed")throw Error(`BLOCKED: PR_REVIEW base attempt ${requestedWaveAttempt} canary failed; close the attempt and carry the unresolved target into the next retry`);if(evaluated.canaryState==="waiting")throw Error(`BLOCKED: PR_REVIEW base attempt ${requestedWaveAttempt} canary is not yet proven successful or live: ${evaluated.reason??"probe failed closed"}`);let remainingTarget=lastAttempt.targetDimensions.filter((dimension)=>dimension!==lastAttempt.canaryWorkflowLane&&evaluated.remaining.includes(dimension));if(remainingTarget.length===0)throw Error(`BLOCKED: PR_REVIEW base attempt ${requestedWaveAttempt} has no remaining unresolved obligations for fanout`);if(!exactDimensionPartition(declaredBaseDimensions(normalizedLanes),remainingTarget))throw Error(`BLOCKED: PR_REVIEW base fanout must partition the remaining unresolved obligations exactly once: ${remainingTarget.join(", ")}`);if(requestedWaveAttempt===0){let combinedDimensions=[lastAttempt.canaryWorkflowLane,...declaredBaseDimensions(normalizedLanes)];if(!exactDimensionPartition(combinedDimensions,lastAttempt.targetDimensions))throw Error("BLOCKED: PR_REVIEW base attempt 0 canary plus fanout must partition all six base dimensions exactly once");if(depthTier==="M"&&normalizedLanes.length+1<PR_REVIEW_BASE_LANE_FLOORS.M)throw Error(`BLOCKED: PR_REVIEW base attempt 0 at depth tier M requires at least ${PR_REVIEW_BASE_LANE_FLOORS.M} combined canary+fanout lanes`);if(depthTier==="L"&&(normalizedLanes.length+1!==PR_REVIEW_BASE_DIMENSION_IDS.length||normalizedLanes.some((lane)=>(lane.ownedWorkflowLanes?.length??1)!==1)))throw Error("BLOCKED: PR_REVIEW base attempt 0 at depth tier L requires six singleton combined canary+fanout lanes")}nextResilience={...snapshot,attempts:[...snapshot.attempts.slice(0,-1),{...lastAttempt,fanoutBatchId:batchId}]}}}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,...nextResilience?{prReviewResilience:nextResilience}:{}};return writeStateWhileLocked(directory,nextState)}async function rollbackPrReviewBaseAdmissionIfUnlaunched(directory,sessionID,batchId){let normalizedSessionID=normalizeSessionID(sessionID),normalizedBatchId=normalizeBatchId(batchId);return withPrWorkflowCheckoutMutationLock(directory,async()=>withSessionStateMutation(directory,normalizedSessionID,async()=>{let state=await readPrWorkflowGateState(directory,normalizedSessionID);if(!state||state.mode!=="PR_REVIEW")return!1;let currentBaseDispatches=state.prReviewBaseDispatches??[];if(currentBaseDispatches.at(-1)?.batchId!==normalizedBatchId)return!1;if(findByBatchId(directory,normalizedBatchId,{parentSessionId:normalizedSessionID}).length>0)return!1;let nextBaseDispatches=currentBaseDispatches.slice(0,-1),lastAttempt=state.prReviewResilience?.attempts.at(-1),nextResilience=state.prReviewResilience;if(lastAttempt?.canaryBatchId===normalizedBatchId)nextResilience=nextResilience?{...nextResilience,attempts:nextResilience.attempts.slice(0,-1)}:nextResilience;else if(lastAttempt?.fanoutBatchId===normalizedBatchId)nextResilience=nextResilience?{...nextResilience,attempts:[...nextResilience.attempts.slice(0,-1),{...lastAttempt,fanoutBatchId:void 0}]}:nextResilience;let shouldKeepResilience=nextBaseDispatches.length>0&&Boolean(nextResilience?.policy)||Boolean(nextResilience?.circuit)||(nextResilience?.attempts.length??0)>0;return await writeStateWhileLocked(directory,{...state,updatedAt:isoNow(),prReviewBaseDispatches:nextBaseDispatches,...nextBaseDispatches.length>0?{prReviewBaseDispatch:nextBaseDispatches.at(-1)}:{prReviewBaseDispatch:void 0},...shouldKeepResilience?{prReviewResilience:nextResilience}:{prReviewResilience:void 0}}),!0}))}function summarizePrReviewBaseDimensionAttempts(directory,state,revisionDigest){let successful2=new Set,inFlight=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)successful2.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 semanticallyValidLaneIds=new Set(recordsPassingBatchIntegrity(directory,state,batch.batchId,batch.lanes,"swarm-pr-review:base",batch.validatedAt).filter((qualified)=>hasRevisionIndependentDiscoverySemantics(directory,qualified)).map((qualified)=>qualified.record.laneId)),records=findByBatchId(directory,batch.batchId,{parentSessionId:state.sessionID});for(let lane of batch.lanes){if(semanticallyValidLaneIds.has(lane.laneId))continue;let laneRecords=records.filter((record2)=>record2.laneId===lane.laneId);if(laneRecords.length===0)continue;if(!laneRecords.every((record2)=>TERMINAL_FAILED_DELEGATION_STATUSES.has(record2.status))){for(let dimension of lane.ownedWorkflowLanes?.length?lane.ownedWorkflowLanes:[lane.workflowLane])inFlight.add(dimension);continue}for(let dimension of lane.ownedWorkflowLanes?.length?lane.ownedWorkflowLanes:[lane.workflowLane])terminallyFailed.add(dimension)}}return{successful:successful2,inFlight,dedicatedSuccessful,terminallyFailed}}function hasRevisionIndependentDiscoverySemantics(directory,qualified){let ref=qualified.record.result?.outputRef?.trim();if(!ref)return!1;let artifact=readLaneOutput(directory,ref)?.artifact??null;if(!artifact?.revisionDigest?.trim())return!1;return validatePrReviewDiscoveryLaneCompletion({record:qualified.record,result:qualified.record.result,artifact,expected:{mode:"swarm-pr-review:base",workflowLane:qualified.expectedWorkflowLane,ownedWorkflowLanes:qualified.expectedOwnedLanes,prHeadSha:qualified.record.workspace?.prHeadSha??"",gitHead:qualified.record.workspace?.gitHead??"",revisionDigest:artifact.revisionDigest,reviewScope:qualified.record.workspace?.scope??void 0}}).ok}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 successful2=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)=>successful2.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 successful2=successfulObligationsFromExactBatch(directory,state,batch.batchId,batch.lanes,"swarm-pr-review:base",batch.validatedAt,!0,new Set,ctx.revisionDigest,malformedDiagnostics);for(let obligation of successful2)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),assertStringSetSubset(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,reviewerItemBindingKeyEncoding:"prefixed-v1"}:{}};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=createHash34("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_exports2.resolveCurrentGitHeadAsync(directory))?.trim()!==armed.localHead)throw Error("BLOCKED: PR_FEEDBACK current Git HEAD changed after publication was armed");if(await _test_exports2.resolveIsWorkingTreeCleanAsync(directory)!==!0)throw Error("BLOCKED: PR_FEEDBACK working tree changed after publication was armed");let currentTarget=await _test_exports2.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 normalizedPath2=artifactPath.trim();if(!normalizedPath2)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:normalizedPath2,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"),baseOnlyExplorerCheckpoint=boundary==="post_explorer"&&!state.prReviewTriggerEvalPath;if(!state.prReviewTriggerEvalPath&&!baseOnlyExplorerCheckpoint)throw Error("BLOCKED: PR_REVIEW findings persistence requires the trigger evaluation artifact (write_pr_review_trigger_eval must complete first)");if(baseOnlyExplorerCheckpoint)state=await assertPrReviewBaseCoverageSettled(directory,sessionID);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())){let actualSet=new Set(normalizedFindingIds),expectedSet=new Set(expectedFindingIds),missing=[...expectedSet].filter((id)=>!actualSet.has(id)),extra=[...actualSet].filter((id)=>!expectedSet.has(id)),duplicates=[...new Set(findingIds.filter((id,index)=>findingIds.indexOf(id)!==index))].sort();throw Error(`BLOCKED: PR_REVIEW ${boundary} findings must exactly cover the discovered candidate inventory; missing: ${missing.join(", ")||"(none)"}; extra: ${extra.join(", ")||"(none)"}; duplicates: ${duplicates.join(", ")||"(none)"}`)}return state}async function assertPrReviewArtifactRecordsMatchAuthoritativeVerdicts(directory,sessionID,boundary,records){let state=await requireBoundState(directory,sessionID,"PR_REVIEW"),violations=[],report=(findingId,field,expected,actual)=>{violations.push({findingId,detail:`${field} expected ${expected}, got ${actual}`})},reportSeverity=(record2,expected)=>{if(record2.severity===expected)return;let raw=record2.severity,actual=raw===void 0?"(omitted)":raw===null?"(null)":raw===""?"(empty)":`"${raw}"`;report(record2.finding_id,"severity",`"${expected}"`,actual)};if(boundary==="post_explorer"){let candidateSeverities=derivePrReviewCandidateSeverities(directory,state,await createPrReviewGateContext(directory,state));for(let record2 of records){if(record2.status!=="PENDING")report(record2.finding_id,"status",'"PENDING"',`"${record2.status}"`);if(record2.next_action!=="route_to_reviewer")report(record2.finding_id,"next_action",'"route_to_reviewer"',`"${record2.next_action}"`);let candidateSeverity=candidateSeverities.get(record2.finding_id);if(candidateSeverity){reportSeverity(record2,candidateSeverity);continue}if(record2.finding_id===PR_REVIEW_CLEAN_SENTINEL_ID){reportSeverity(record2,"NONE");continue}violations.push({findingId:record2.finding_id,detail:"no authoritative candidate severity (absent from the derived candidate inventory)"})}}else{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){violations.push({findingId:record2.finding_id,detail:"no authoritative reviewer verdict (absent from the settled reviewer map)"});continue}let requiresCritic=reviewer.classification==="CONFIRMED"&&["CRITICAL","HIGH","MEDIUM"].includes(reviewer.severity),expectedStatus=reviewer.classification==="UNVERIFIED"?"PENDING":reviewer.classification;if(boundary==="post_reviewer"){if(record2.status!==expectedStatus)report(record2.finding_id,"status",`"${expectedStatus}"`,`"${record2.status}"`);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)report(record2.finding_id,"next_action",`"${expectedAction}"`,`"${record2.next_action}"`);reportSeverity(record2,reviewer.severity);continue}if(!requiresCritic){let expectedAction=reviewer.classification==="CONFIRMED"||reviewer.classification==="PRE_EXISTING"?"report":reviewer.classification==="DISPROVED"?"suppress_with_reason":"route_to_reviewer";if(record2.status!==expectedStatus)report(record2.finding_id,"status",`"${expectedStatus}"`,`"${record2.status}"`);if(record2.next_action!==expectedAction)report(record2.finding_id,"next_action",`"${expectedAction}"`,`"${record2.next_action}"`);reportSeverity(record2,reviewer.severity);continue}let critic=criticVerdicts?.get(record2.finding_id);if(!critic){reportSeverity(record2,reviewer.severity),violations.push({findingId:record2.finding_id,detail:"no authoritative critic verdict (absent from the settled critic map)"});continue}if(critic.status==="DISPROVED"){if(record2.status!=="DISPROVED")report(record2.finding_id,"status",'"DISPROVED"',`"${record2.status}"`);if(record2.next_action!=="suppress_with_reason")report(record2.finding_id,"next_action",'"suppress_with_reason"',`"${record2.next_action}"`)}else{if(record2.status!=="CONFIRMED")report(record2.finding_id,"status",'"CONFIRMED"',`"${record2.status}"`);if(!["report","handoff_to_feedback"].includes(record2.next_action))report(record2.finding_id,"next_action",'"report" or "handoff_to_feedback"',`"${record2.next_action}"`)}reportSeverity(record2,critic.severity)}}if(violations.length>0){violations.sort((left,right)=>left.findingId<right.findingId?-1:left.findingId>right.findingId?1:0);let lines=violations.map((violation)=>` ${violation.findingId}: ${violation.detail}`);throw Error(`BLOCKED: PR_REVIEW ${boundary} artifact invalid — ${violations.length} violation(s):
|
|
881
881
|
${lines.join(`
|
|
882
882
|
`)}`)}}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,"/"),relative25=normalized.startsWith(".swarm/")?normalized.slice(7):normalized,matched=relative25.match(PR_REVIEW_HANDOFF_RELATIVE_PATH_PATTERN);if(!matched)return null;return{runId:matched[1],relativePath:relative25}}async function readBoundedSwarmRegularFile(directory,relativePath,maxBytes,label){let absPath=validateSwarmPath(directory,relativePath),swarmRoot=path84.resolve(directory,".swarm"),rootStat,artifactStat;try{rootStat=await fsp4.lstat(swarmRoot,{bigint:!0}),artifactStat=await fsp4.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([fsp4.realpath(swarmRoot),fsp4.realpath(absPath)]),relativeRealPath=path84.relative(realRoot,realArtifact);if(relativeRealPath===""||relativeRealPath===".."||relativeRealPath.startsWith(`..${path84.sep}`)||path84.isAbsolute(relativeRealPath))throw Error(`BLOCKED: ${label} escapes the project .swarm directory`);await _test_exports2.beforeBoundedSwarmFileOpen?.();let handle=await fsp4.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([fsp4.lstat(swarmRoot,{bigint:!0}),fsp4.lstat(absPath,{bigint:!0}),fsp4.realpath(swarmRoot),fsp4.realpath(absPath)]),postRelativeRealPath=path84.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(`..${path84.sep}`)||path84.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=path84.normalize(path84.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:createHash34("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-${createHash34("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)`+describePrWorkflowLaneProbe(laneSettlement));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_exports2.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:randomUUID14(),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),isShellTool3=normalizedTool==="bash"||normalizedTool==="shell",isReadOnlyShell=!1,shellPermissionEnvelope=null;if(isShellTool3&&command.length>0){let trackingFetchTarget=state.prHeadSha?await _test_exports2.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),isTrustedWorkflowTool=trustedCapability!==null&&isTrustedPrWorkflowToolInvocationSafe(normalizedTool,args2??{}),isAllowlistedReadOnlyTool=normalizedTool!=="build_check"&&isAllowedPrReviewReadOnlyToolName(normalizedTool),readOnlyArgumentClassification=isAllowlistedReadOnlyTool?classifyReadOnlyToolArguments(normalizedTool,args2??{}):null,isNamedReadOnlyTool=isTrustedWorkflowTool||isAllowlistedReadOnlyTool&&readOnlyArgumentClassification?.safe===!0,isRecoverySafeEvidenceTool=trustedCapability==="observe"&&isTrustedPrWorkflowToolInvocationSafe(normalizedTool,args2??{})||isAllowlistedReadOnlyTool&&readOnlyArgumentClassification?.safe===!0;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(state.mode==="PR_REVIEW"&&isAllowlistedReadOnlyTool&&readOnlyArgumentClassification?.safe===!1)throw Error(`BLOCKED: PR_REVIEW is read-only; tool "${normalizedTool}" rejected argument "${readOnlyArgumentClassification.path}": ${readOnlyArgumentClassification.constraint}`);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=isShellTool3&&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=isShellTool3&&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&&!isShellTool3&&!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)`+describePrWorkflowLaneProbe(laneSettlement));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_exports2.resolveCurrentGitHeadAsync(directory))?.trim();if(!localHead)throw Error("BLOCKED: PR_FEEDBACK cannot arm publication without a verified local Git HEAD");let commitCount=await _test_exports2.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_exports2.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 fsp4.appendFile(eventsPath,`${JSON.stringify({type:"pr_feedback_verified_no_change",timestamp:isoNow(),sessionID:state.sessionID,prHeadSha:state.prHeadSha,items:inventory.length})}
|
|
883
|
-
`,"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_exports2.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_exports2.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_exports2.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_exports2.resolveCurrentGitHeadAsync(directory))?.trim(),remoteRefs=publishedHead?await _test_exports2.resolveRemoteRefsContainingHeadAsync(directory,publishedHead):null,remoteHead=await _test_exports2.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_exports2.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){if(reviewItemIds.length>MAX_PR_REVIEW_COLLECTION_RECEIPT_ITEM_IDS)throw Error(`BLOCKED: PR workflow review_item_ids may not exceed ${MAX_PR_REVIEW_COLLECTION_RECEIPT_ITEM_IDS} entries`);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 unsafeReadOnlyArgument(path85,constraint,value){return{safe:!1,path:path85||"(root)",constraint,value}}function readOnlyArgumentPath(parent,key){return parent?`${parent}.${key}`:key}function classifyReadOnlyToolArguments(toolName,value,key="",path85="",depth=0){if(depth>8)return unsafeReadOnlyArgument(path85,"argument nesting exceeds the read-only depth limit of 8",value);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 unsafeReadOnlyArgument(path85,"argument name is mutation-bearing and is not allowed for read-only tools",value);if(keyTokens.some((token)=>/^(?:method|verb)$/i.test(token)))return typeof value==="string"&&/^(?:GET|HEAD)$/i.test(value.trim())?{safe:!0}:unsafeReadOnlyArgument(path85,"HTTP method/verb must be GET or HEAD for a read-only tool",value);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())?{safe:!0}:unsafeReadOnlyArgument(path85,"action/operation must name a recognized observation operation",value);if(/^mode$/i.test(key)&&typeof value==="string")return(toolName==="search"?/^(?:r|rb|read|literal|regex)$/i:/^(?:r|rb|read)$/i).test(value.trim())?{safe:!0}:unsafeReadOnlyArgument(path85,toolName==="search"?"search mode must be one of r, rb, read, literal, or regex":"mode must be one of r, rb, or read for a read-only tool",value);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 unsafeReadOnlyArgument(path85,"query/request text contains a mutating operation",value);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)?unsafeReadOnlyArgument(path85,"string value contains a mutating command or request",value):{safe:!0}}if(value===null||value===void 0||typeof value==="number"||typeof value==="boolean")return{safe:!0};if(Array.isArray(value)){for(let index=0;index<value.length;index++){let result=classifyReadOnlyToolArguments(toolName,value[index],key,`${path85}[${index}]`,depth+1);if(!result.safe)return result}return{safe:!0}}if(typeof value==="object"){for(let[childKey,childValue]of Object.entries(value)){let result=classifyReadOnlyToolArguments(toolName,childValue,childKey,readOnlyArgumentPath(path85,childKey),depth+1);if(!result.safe)return result}return{safe:!0}}return unsafeReadOnlyArgument(path85,"argument type is not supported by the read-only classifier",value)}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_exports2.resolvePrWorkflowRevisionDigestDetailed!==resolvePrWorkflowRevisionDigestDetailed)return _test_exports2.resolvePrWorkflowRevisionDigestDetailed(directory,baseHeadSha);if(_test_exports2.resolvePrWorkflowRevisionDigest!==resolvePrWorkflowRevisionDigest){let digest2=_test_exports2.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 assertStringSetSubset(actual,expected,label){let actualSet=new Set(actual),expectedSet=new Set(expected),extra=[...actualSet].filter((value)=>!expectedSet.has(value));if(actual.length===0||actual.length!==actualSet.size||extra.length>0)throw Error(`BLOCKED: ${label} must be a non-empty subset of the mechanically derived inventory; 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 successful2=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)=>successful2.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 successful2=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(successful2.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(readFileSync28(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=[],candidateSeverities=new Map,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);let extracted=extractCandidateRows(artifact.text,resolvePrReviewRowFamily(source.workflowLane,source.mode),source.creditedLanes);for(let row of extracted)if(candidateIds.push(row.candidateId),row.severity&&!candidateSeverities.has(row.candidateId))candidateSeverities.set(row.candidateId,row.severity)}}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.candidateSeverities=candidateSeverities,ctx.candidateInventory=candidateIds.length>0?candidateIds.sort():[PR_REVIEW_CLEAN_SENTINEL_ID],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,severity:isCandidateSeverity(analysis.values.severity)?analysis.values.severity:null,evidence:candidateFields.slice(2).join("\x00"),lineNumber:index+1})}return{rows,issues}}function extractCandidateRows(text,fallbackFamily,scopeToLanes){let inScope=(lane)=>!scopeToLanes||lane!==void 0&&scopeToLanes.includes(lane);return parseCanonicalCandidateRows(text,fallbackFamily).rows.filter((row)=>inScope(row.workflowLane))}function extractCandidateIds(text,fallbackFamily,scopeToLanes){return extractCandidateRows(text,fallbackFamily,scopeToLanes).map((row)=>row.candidateId)}function derivePrReviewCandidateSeverities(directory,state,ctx){if(!ctx.candidateSeverities)derivePrReviewCandidateInventory(directory,state,ctx);if(!ctx.candidateSeverities)throw Error("BLOCKED: PR_REVIEW candidate severity authority is unavailable for this gate context");return ctx.candidateSeverities}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 successful2=successfulObligationsFromExactBatch(directory,state,batch.batchId,batch.lanes,`swarm-pr-review:${phase}`,batch.validatedAt,!0,forbiddenSubagentSessionIds,ctx.revisionDigest,void 0,reviewerClaims);return successful2.size===batch.lanes.length&&batch.lanes.every((lane)=>successful2.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??[],{markerRows,parsed}=parsePrReviewVerdictRows(artifact.text,declaredItems,phase,reviewerClaims);if(!verdictRowsContainOnlyAssignedIds(markerRows,declaredItems)){appendCompositionDiagnostic(diagnostics,`${phase} lane "${qualified.expectedLane.laneId}" contains an unassigned verdict row; it contributes no claims`);continue}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 bindings=coherence.reviewerItemBindings,bindingKey2=coherence.reviewerItemBindingKeyEncoding==="prefixed-v1"?reviewerItemBindingKey(itemId):itemId,bound=bindings&&Object.hasOwn(bindings,bindingKey2)?bindings[bindingKey2]:void 0,current=reviewerClaims?.get(itemId)?.rowDigest;return Boolean(bound&¤t&&bound===current)}function reviewerItemBindingKey(itemId){return`${REVIEWER_ITEM_BINDING_KEY_PREFIX}${itemId}`}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[reviewerItemBindingKey(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&&!args2.allowTranscriptIncompleteRecovery)return failedLaneValidation("result.transcript_incomplete","false outside discovery candidate recovery",!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,allowTranscriptIncompleteRecovery:args2.expectedMode==="swarm-pr-review:base"||args2.expectedMode==="swarm-pr-review:micro"});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 successful2=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)successful2.add(obligation);return successful2}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";return analyzePrReviewVerdictRowContract(artifact.text,reviewItemIds??[],phase,reviewerClaims).ok}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,cleanAttestationSalvaged=!1,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,coverageKind:null,salvaged,repairKinds,cleanAttestationSalvaged,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);if(parsed.clean_attestation_salvaged)cleanAttestationSalvaged=!0,salvaged=!0,appendBoundedCandidateIssue(issues,parsed.clean_attestation_salvage_reason??"CLEAN attestation discredited; candidate rows retained");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)||Boolean(parsed.clean_attestation_salvaged)||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,coverageKind:null,salvaged,repairKinds,cleanAttestationSalvaged,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,coverageKind:"candidate",salvaged,repairKinds,cleanAttestationSalvaged};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,coverageKind:"clean",salvaged,repairKinds,cleanAttestationSalvaged};return{covered:!1,evidence:null,issues,coverageKind:null,salvaged,repairKinds,cleanAttestationSalvaged,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,allowTranscriptIncompleteRecovery:input.expected.mode==="swarm-pr-review:base"||input.expected.mode==="swarm-pr-review:micro"});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=[],recoveries=[],previewTruncated=input.result.truncated===!0,transcriptIncomplete=input.result.transcriptIncomplete===!0;for(let{workflowLane,analysis}of analyses){if(!analysis.covered)continue;let laneRecoveries=[];if(previewTruncated)laneRecoveries.push({workflowLane,kind:"truncated-preview-durable-artifact",reason:"inline preview truncated; durable artifact retained exact coverage"});if(transcriptIncomplete){if(analysis.coverageKind==="candidate")laneRecoveries.push({workflowLane,kind:"transcript-incomplete-terminal-candidate",reason:"partial transcript accepted only because a durable [CANDIDATE] row proved this lane"});else if(analysis.coverageKind==="clean")return failedLaneValidation("result.transcript_incomplete","complete transcript for every [CLEAN] attestation",`workflow lane ${workflowLane} was covered only by [CLEAN] after a partial transcript fetch`)}if(laneRecoveries.length===0&&!analysis.salvaged&&analysis.issues.length===0)continue;if(salvagedLanes.push(workflowLane),analysis.repairKinds.length>0)laneRecoveries.push({workflowLane,kind:"parser-normalization",reason:`structural repairs applied: ${analysis.repairKinds.join(", ")}`});if(analysis.cleanAttestationSalvaged)laneRecoveries.push({workflowLane,kind:"clean-attestation-salvaged",reason:"a conflicting [CLEAN] attestation was discredited while the independently validated candidate rows were retained"});if(analysis.issues.length>0)laneRecoveries.push({workflowLane,kind:"parser-row-recovery",reason:"one or more malformed or out-of-ownership rows were dropped while retaining valid coverage"});recoveries.push(...laneRecoveries);let reason=laneRecoveries.map((recovery)=>recovery.reason).join("; ");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,recoveries}:{ok:!0}}async function validatePrWorkflowTransportRecovery(input){let mode=input.record.mode?.trim();if(!(mode==="swarm-pr-review:reviewer"||mode==="swarm-pr-review:critic")&&input.result.truncated!==!0&&input.result.transcriptIncomplete!==!0)return{ok:!0};let workflowLane=input.record.workflowLane?.trim();if(!mode||!workflowLane)return{ok:!1,reason:"structured workflow transport recovery requires non-empty mode and workflow_lane provenance"};let state=await requireAnyActiveState(input.directory,input.record.parentSessionId),batchId=input.record.batchId?.trim(),laneId=input.record.laneId?.trim(),verdictPhase=mode==="swarm-pr-review:reviewer"?"reviewer":mode==="swarm-pr-review:critic"?"critic":null,declaredItemIds=(verdictPhase?(state.prReviewValidationBatches??[]).find((candidate)=>candidate.batchId===batchId&&candidate.phase===verdictPhase)?.lanes.find((candidate)=>candidate.laneId===laneId):void 0)?.reviewItemIds??[],rejectedReceipt=declaredItemIds.length>0?{assignedReviewItemIds:[...declaredItemIds],acceptedReviewItemIds:[],rejectedReviewItemIds:[...declaredItemIds]}:void 0,recordIntegrity=analyzeLaneRecordResultIntegrity({record:input.record,result:input.result,expected:{mode,workflowLane,ownedWorkflowLanes:[workflowLane],prHeadSha:input.record.workspace?.prHeadSha??"",gitHead:input.record.workspace?.gitHead??"",checkWorkflowLane:!0},requireCompleted:!1,allowTranscriptIncompleteRecovery:!1});if(!recordIntegrity.ok)return{ok:!1,reason:formatPrReviewLaneValidationFailure(recordIntegrity.failure),failure:recordIntegrity.failure,...rejectedReceipt?{receipt:rejectedReceipt}:{}};let artifactIntegrity=analyzeLaneArtifactIntegrity({record:input.record,result:input.result,artifact:input.artifact,expected:{mode,workflowLane,prHeadSha:input.record.workspace?.prHeadSha??"",gitHead:input.record.workspace?.gitHead??"",revisionDigest:input.revisionDigest,reviewScope:input.record.workspace?.scope??void 0}});if(!artifactIntegrity.ok)return{ok:!1,reason:formatPrReviewLaneValidationFailure(artifactIntegrity.failure),failure:artifactIntegrity.failure,...rejectedReceipt?{receipt:rejectedReceipt}:{}};let expectedMode=mode.startsWith("swarm-pr-review:")?"PR_REVIEW":mode.startsWith("swarm-pr-feedback:")?"PR_FEEDBACK":null;if(!expectedMode)return{ok:!1,reason:`structured workflow transport recovery does not support mode "${mode}"`,...rejectedReceipt?{receipt:rejectedReceipt}:{}};if(state.mode!==expectedMode)return{ok:!1,reason:`active workflow mode mismatch; expected ${expectedMode}, got ${state.mode}`,...rejectedReceipt?{receipt:rejectedReceipt}:{}};let artifactText=input.artifact?.text??"",prReviewGateContext=state.mode==="PR_REVIEW"?{revisionDigest:input.revisionDigest}:void 0;if(!batchId||!laneId)return{ok:!1,reason:"structured workflow transport recovery requires non-empty batch_id and lane_id provenance",...rejectedReceipt?{receipt:rejectedReceipt}:{}};if(mode==="swarm-pr-review:reviewer"||mode==="swarm-pr-review:critic"){let phase=verdictPhase??"reviewer",lane=(state.prReviewValidationBatches??[]).find((candidate)=>candidate.batchId===batchId&&candidate.phase===phase)?.lanes.find((candidate)=>candidate.laneId===laneId);if(!lane||lane.workflowLane!==workflowLane)return{ok:!1,reason:"no matching declared reviewer/critic lane ownership was found for this transport recovery",...rejectedReceipt?{receipt:rejectedReceipt}:{}};let itemIds=lane.reviewItemIds??[],reviewerClaims=phase==="critic"?authoritativeReviewerClaims(input.directory,state,prReviewGateContext??{revisionDigest:input.revisionDigest}):void 0;if(phase==="critic"&&(!reviewerClaims||reviewerClaims.size===0))return{ok:!1,reason:"critic transport recovery requires authoritative settled reviewer claims for every assigned item",...rejectedReceipt?{receipt:rejectedReceipt}:{}};let analysis=analyzePrReviewVerdictRowContract(artifactText,itemIds,phase,reviewerClaims);if(!analysis.ok){let failure=failedLaneValidation(phase==="reviewer"?"reviewer.verdict_rows":"critic.verdict_rows",analysis.expected,analysis.actual).failure;return{ok:!1,reason:formatPrReviewLaneValidationFailure(failure),failure,receipt:{assignedReviewItemIds:[...itemIds],acceptedReviewItemIds:[],rejectedReviewItemIds:[...itemIds]}}}let receipt={assignedReviewItemIds:[...itemIds],acceptedReviewItemIds:[...itemIds],rejectedReviewItemIds:[]};return input.result.truncated===!0?{ok:!0,receipt,recoveries:[{workflowLane,kind:"truncated-preview-durable-artifact",reason:"inline preview truncated; durable artifact retained exact coverage"}]}:{ok:!0,receipt}}else if(mode==="swarm-pr-feedback:verification"){let lane=(state.prFeedbackVerifications??[]).find((candidate)=>candidate.batchId===batchId)?.ownership.find((candidate)=>candidate.laneId===laneId);if(!lane||workflowLane!==lane.laneId)return{ok:!1,reason:"no matching declared PR_FEEDBACK verification ownership was found for this transport recovery"};let itemIds=lane?.ownedItemIds??[];if(itemIds.length===0||!feedbackArtifactTextCoversItems(artifactText,itemIds))return{ok:!1,reason:"every assigned PR_FEEDBACK verification item requires one exact [FEEDBACK-VERIFIED] row in the durable artifact"}}else{let feedbackPhase={"swarm-pr-feedback:stage-b-reviewer":{phase:"stage-b-reviewer",marker:"[STAGE-B-REVIEW]",verdict:"APPROVE"},"swarm-pr-feedback:stage-b-test":{phase:"stage-b-test",marker:"[STAGE-B-TEST]",verdict:"PASS"},"swarm-pr-feedback:closeout-reviewer":{phase:"closeout-reviewer",marker:"[CLOSEOUT-REVIEW]",verdict:"APPROVE"},"swarm-pr-feedback:closeout-critic":{phase:"closeout-critic",marker:"[CLOSEOUT-CRITIC]",verdict:"APPROVE"}}[mode];if(!feedbackPhase)return{ok:!1,reason:`structured workflow transport recovery does not support mode "${mode}"`};let batch=(state.prFeedbackGateBatches??[]).find((candidate)=>candidate.batchId===batchId&&candidate.phase===feedbackPhase.phase&&candidate.laneId===laneId);if(!batch||workflowLane!==feedbackPhase.phase)return{ok:!1,reason:"no matching declared ordered PR_FEEDBACK lane provenance was found for this transport recovery"};let itemIds=batch?.itemIds??[];if(itemIds.length===0||!itemIds.every((itemId)=>artifactHasExactPositiveVerdictRow(artifactText,feedbackPhase.marker,itemId,feedbackPhase.verdict)))return{ok:!1,reason:"every assigned ordered PR_FEEDBACK item requires one exact positive verdict row in the durable artifact"}}return input.result.truncated===!0?{ok:!0,recoveries:[{workflowLane,kind:"truncated-preview-durable-artifact",reason:"inline preview truncated; durable artifact retained exact coverage"}]}:{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 indexVerdictRows(text,marker,fieldCount){let markerRows=[],rowsByItemId=new Map;for(let line of text.split(/\r?\n/)){let fields=pipeFieldsCapped(line,fieldCount);if(fields[0]!==marker)continue;markerRows.push(fields);let itemId=fields[1]??"",rows=rowsByItemId.get(itemId);if(rows)rows.push(fields);else rowsByItemId.set(itemId,[fields])}return{markerRows,rowsByItemId}}function validateReviewerVerdictFields(fields){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[2]==="DISPROVED"&&fields[4]!=="NONE")return null;if(fields[7].length<8||fields[8].length<5||fields[9].length<3)return null;return fields}function reviewerVerdictRowDigest(fields){return createHash34("sha256").update(fields.join("\x00")).digest("hex")}function parseLaneItemVerdicts(text,itemIds,phase,reviewerClaims){return parsePrReviewVerdictRows(text,itemIds,phase,reviewerClaims).parsed}function parsePrReviewVerdictRows(text,itemIds,phase,reviewerClaims){let parsed=new Map,marker=phase==="reviewer"?"[REVIEWED]":"[CRITIC]",{markerRows,rowsByItemId}=indexVerdictRows(text,marker,phase==="reviewer"?10:6);for(let itemId of itemIds){if(phase==="reviewer"){let rows2=rowsByItemId.get(itemId),fields=rows2?.length===1?validateReviewerVerdictFields(rows2[0]):null;if(!fields)continue;parsed.set(itemId,{classification:fields[2],severity:fields[4],rowDigest:reviewerVerdictRowDigest(fields)});continue}let rows=rowsByItemId.get(itemId),verdict=rows?.length===1?validateCriticVerdictFields(rows[0],reviewerClaims?.get(itemId)?.severity):null;if(!verdict)continue;parsed.set(itemId,{classification:verdict.status,severity:verdict.severity})}return{markerRows,parsed}}function analyzePrReviewVerdictRowContract(text,itemIds,phase,reviewerClaims){let marker=phase==="reviewer"?"[REVIEWED]":"[CRITIC]",assigned=new Set(itemIds),{markerRows,parsed}=parsePrReviewVerdictRows(text,itemIds,phase,reviewerClaims),observedIds=markerRows.map((fields)=>fields[1]||"(missing)"),unexpectedIds=[...new Set(observedIds.filter((itemId)=>!assigned.has(itemId)))],invalidOrMissingIds=itemIds.filter((itemId)=>!parsed.has(itemId));return{ok:verdictRowIdsMatchExactly(markerRows,itemIds)&&invalidOrMissingIds.length===0,expected:`exactly one parseable ${marker} row for assigned IDs ${JSON.stringify(itemIds)} and no other ${marker} IDs`,actual:JSON.stringify({rowCount:markerRows.length,observedIds,invalidOrMissingIds,unexpectedIds})}}function verdictRowIdsMatchExactly(markerRows,itemIds){if(itemIds.length===0||markerRows.length!==itemIds.length)return!1;let assigned=new Set(itemIds);if(assigned.size!==itemIds.length)return!1;let observed=new Set;for(let fields of markerRows){let itemId=fields[1]??"";if(!assigned.has(itemId)||observed.has(itemId))return!1;observed.add(itemId)}return observed.size===assigned.size}function verdictRowsContainOnlyAssignedIds(markerRows,itemIds){if(itemIds.length===0)return!1;let assigned=new Set(itemIds);return markerRows.every((fields)=>assigned.has(fields[1]??""))}function parseCriticVerdict(text,itemId,reviewerSeverity){let rows=indexVerdictRows(text,"[CRITIC]",6).rowsByItemId.get(itemId);if(!rows||rows.length!==1)return null;return validateCriticVerdictFields(rows[0],reviewerSeverity)}function validateCriticVerdictFields(fields,reviewerSeverity){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 reviewerRank=REVIEW_SEVERITY_RANK.get(reviewerSeverity),criticRank=REVIEW_SEVERITY_RANK.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 feedbackArtifactTextCoversItems(text,itemIds){let rows=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 path84.join(WORKFLOW_GATE_DIR,"checkout.lock")}function workflowCheckoutMutationLockPath(directory){return validateSwarmPath(directory,workflowCheckoutMutationLockRelativePath())}function openCheckoutLockFile(lockPath){return fsp4.open(lockPath,"wx")}function removeCheckoutLockFile(lockPath){return fsp4.rm(lockPath)}function checkoutMutationProjectKey(directory){return normalizeComparableFsPath(directory)}async function withCheckoutMutationDeadline(promise2,phase){let timeout;try{return await Promise.race([promise2,new Promise((resolve45)=>{timeout=setTimeout(()=>{resolve45({status:"timeout",error:new PrWorkflowCheckoutMutationTimeoutError(phase)})},_test_exports2.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((resolve45)=>{release=resolve45}),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_exports2.openCheckoutLock(lockPath),lock={ownerToken:randomUUID14(),pid:process.pid,createdAtMs:_test_exports2.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_exports2.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_exports2.isProcessAlive(lock.pid))return!1;return removeCheckoutMutationLockIfOwned(lockPath,lock.ownerToken)}try{let stat11=await fsp4.stat(lockPath);if(_test_exports2.nowMs()-stat11.mtimeMs<STATE_MUTATION_LOCK_UNINITIALIZED_STALE_MS)return!1;return await fsp4.rm(lockPath,{force:!0}),!0}catch(error49){if(error49.code==="ENOENT")return!0;throw error49}}async function readCheckoutMutationLock(lockPath){let raw;try{raw=await fsp4.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_exports2.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_exports2.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((resolve45)=>{release=resolve45}),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 fsp4.open(lockPath,"wx"),lock={ownerToken:randomUUID14(),pid:process.pid,createdAtMs:_test_exports2.nowMs()},writeError;try{await _test_exports2.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_exports2.isProcessAlive(lock.pid))return!1;return removeSessionStateMutationLockIfOwned(lockPath,lock.ownerToken)}try{let stat11=await fsp4.stat(lockPath);if(_test_exports2.nowMs()-stat11.mtimeMs<STATE_MUTATION_LOCK_UNINITIALIZED_STALE_MS)return!1;return await fsp4.rm(lockPath,{force:!0}),!0}catch(error49){if(error49.code==="ENOENT")return!0;throw error49}}async function readSessionStateMutationLock(lockPath){let raw;try{raw=await fsp4.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 fsp4.rm(lockPath),!0}catch(error49){if(error49.code==="ENOENT")return!1;throw error49}}function isProcessAlive3(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 fsp4.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 fsp4.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=path84.normalize(path84.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 path84.join(WORKFLOW_GATE_DIR,`${prWorkflowSessionFileStem(sessionID)}.lock`)}function workflowGateStateRelativePath(sessionID){return path84.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=createHash34("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=path84.resolve(directory,".swarm"),parentPath=path84.dirname(path84.resolve(filePath)),relativeParent=path84.relative(swarmRoot,parentPath);if(relativeParent===".."||relativeParent.startsWith(`..${path84.sep}`)||path84.isAbsolute(relativeParent))throw Error("BLOCKED: PR workflow atomic destination escapes the project .swarm directory");await fsp4.mkdir(swarmRoot,{recursive:!0});let currentPath=swarmRoot,currentIdentity=await assertSafeDirectory(currentPath,void 0);for(let segment of relativeParent.split(path84.sep).filter(Boolean)){let nextPath=path84.join(currentPath,segment);await _test_exports2.beforeSafeDirectoryCreate?.(currentPath,nextPath),await assertSafeDirectory(currentPath,currentIdentity);try{await fsp4.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([fsp4.realpath(currentPath),fsp4.realpath(nextPath)]);if(normalizeComparableFsPath(path84.dirname(realNext))!==normalizeComparableFsPath(realCurrent))throw Error("BLOCKED: PR workflow directory creation escaped the project .swarm tree");currentPath=nextPath,currentIdentity=nextIdentity}let realRoot=await fsp4.realpath(swarmRoot),realParent=await fsp4.realpath(parentPath),relativeRealParent=path84.relative(realRoot,realParent);if(relativeRealParent===".."||relativeRealParent.startsWith(`..${path84.sep}`)||path84.isAbsolute(relativeRealParent))throw Error("BLOCKED: PR workflow atomic parent escapes the project .swarm directory");return realParent}async function assertSafeDirectory(directoryPath,expectedIdentity){let stat11=await fsp4.lstat(directoryPath,{bigint:!0});if(stat11.isSymbolicLink()||!stat11.isDirectory()||expectedIdentity&&!sameBigIntFileIdentity(stat11,expectedIdentity))throw Error("BLOCKED: PR workflow .swarm path must be a real directory and must not change during the operation");return{dev:stat11.dev,ino:stat11.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[stat11,realRoot,realFile,realParent]=await Promise.all([fsp4.lstat(filePath,{bigint:!0}),fsp4.realpath(path84.resolve(directory,".swarm")),fsp4.realpath(filePath),fsp4.realpath(path84.dirname(filePath))]),relativeFile=path84.relative(realRoot,realFile);if(stat11.isSymbolicLink()||!stat11.isFile()||!sameBigIntFileIdentity(stat11,expectedIdentity)||normalizeComparableFsPath(realParent)!==normalizeComparableFsPath(expectedParent)||relativeFile===""||relativeFile===".."||relativeFile.startsWith(`..${path84.sep}`)||path84.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}.${randomUUID14()}`,tempIdentity,lastError;try{let handle=await fsp4.open(tempPath,"wx");try{await _test_exports2.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_exports2.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_exports2.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 fsp4.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((resolve45)=>setTimeout(resolve45,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_PR_REVIEW_BASE_LANES_PER_BATCH,MAX_PR_REVIEW_RESILIENCE_CIRCUIT_CONTRIBUTORS,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,PrReviewResiliencePolicyRecordSchema,PrReviewResilienceAttemptRecordSchema,PrReviewResilienceCircuitRecordSchema,PrReviewResilienceStateRecordSchema,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",PR_WORKFLOW_LANE_LIVENESS_PROBE_TIMEOUT_MS=5000,LIVE_SESSION_STATUS_TYPES,defaultGetSessionOps=()=>swarmState.opencodeClient?.session??null,PrReviewResilienceCircuitOpenError,PrReviewResilienceRetryExhaustedError,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_exports2,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,PR_REVIEW_CLEAN_SENTINEL_ID="CLEAN-REVIEW",MAX_COMPOSITION_DIAGNOSTICS=16,MAX_UNCLAIMED_ITEMS_IN_MESSAGE=50,REVIEWER_ITEM_BINDING_KEY_PREFIX="item:",REVIEWER_CLASSIFICATIONS,REVIEWER_EVIDENCE_TYPES,REVIEW_SEVERITIES,REVIEW_SEVERITY_RANK,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_collection_receipt();init_pr_review_trigger_contract();init_workspace_snapshot();init_constants();init_schema();init_pr_workflow_state();init_state2();init_tool_metadata();init_logger();init_timeout();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_REVIEW_BASE_LANES_PER_BATCH=PR_REVIEW_BASE_DIMENSION_IDS.length,MAX_PR_REVIEW_RESILIENCE_CIRCUIT_CONTRIBUTORS=MAX_WORKFLOW_BATCHES*MAX_PR_REVIEW_BASE_LANES_PER_BATCH,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).max(MAX_PR_REVIEW_BASE_LANES_PER_BATCH),validatedAt:exports_external.string().min(1)}).strict(),PrReviewResiliencePolicyRecordSchema=exports_external.object({enabled:exports_external.boolean(),canaryProbeMs:exports_external.number().int().positive(),statusProbeTimeoutMs:exports_external.number().int().positive(),correlatedFailureThreshold:exports_external.number().int().min(2).max(8),maxRetryAttemptsAfterInitial:exports_external.number().int().min(0).max(2)}).strict(),PrReviewResilienceAttemptRecordSchema=exports_external.object({attempt:exports_external.union([exports_external.literal(0),exports_external.literal(1),exports_external.literal(2)]),targetDimensions:exports_external.array(PrReviewBaseDimensionIdSchema).min(1).max(PR_REVIEW_BASE_DIMENSION_IDS.length),canaryBatchId:exports_external.string().min(1),canaryLaneId:exports_external.string().min(1),canaryWorkflowLane:PrReviewBaseDimensionIdSchema,admittedAt:exports_external.string().min(1),fanoutBatchId:exports_external.string().min(1).optional()}).strict(),PrReviewResilienceCircuitRecordSchema=exports_external.object({signature:exports_external.string().min(1).max(512),count:exports_external.number().int().min(2).max(MAX_PR_REVIEW_RESILIENCE_CIRCUIT_CONTRIBUTORS),contributors:exports_external.array(exports_external.object({batchId:exports_external.string().min(1),laneId:exports_external.string().min(1)}).strict()).min(2).max(MAX_PR_REVIEW_RESILIENCE_CIRCUIT_CONTRIBUTORS),openedAt:exports_external.string().min(1)}).strict(),PrReviewResilienceStateRecordSchema=exports_external.object({policy:PrReviewResiliencePolicyRecordSchema,attempts:exports_external.array(PrReviewResilienceAttemptRecordSchema).max(3),circuit:PrReviewResilienceCircuitRecordSchema.optional()}).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).max(MAX_PR_REVIEW_COLLECTION_RECEIPT_ITEM_IDS).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(),reviewerItemBindingKeyEncoding:exports_external.literal("prefixed-v1").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(),prReviewResilience:PrReviewResilienceStateRecordSchema.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"]),LIVE_SESSION_STATUS_TYPES=new Set(["busy","retry"]);PrReviewResilienceCircuitOpenError=class PrReviewResilienceCircuitOpenError extends Error{code="PR_REVIEW_RESILIENCE_CIRCUIT_OPEN";constructor(message){super(message);this.name="PrReviewResilienceCircuitOpenError"}};PrReviewResilienceRetryExhaustedError=class PrReviewResilienceRetryExhaustedError extends Error{code="PR_REVIEW_RESILIENCE_RETRY_EXHAUSTED";constructor(message){super(message);this.name="PrReviewResilienceRetryExhaustedError"}};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_exports2={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_exports2.beforeTerminalClear=void 0,_test_exports2.beforeAbortClear=void 0,_test_exports2.beforePrFeedbackTransitionLock=void 0,_test_exports2.beforePrFeedbackTrackingSwitch=void 0,_test_exports2.afterPrFeedbackTrackingSwitch=void 0,_test_exports2.beforePrFeedbackTrackingPersist=void 0,_test_exports2.beforeBoundedSwarmFileOpen=void 0,_test_exports2.beforeSessionStateLockWrite=void 0,_test_exports2.beforeCheckoutLockWrite=void 0,_test_exports2.beforeSafeDirectoryCreate=void 0,_test_exports2.beforeAtomicTempWrite=void 0,_test_exports2.beforeAtomicRename=void 0,_test_exports2.openCheckoutLock=openCheckoutLockFile,_test_exports2.removeCheckoutLock=removeCheckoutLockFile,_test_exports2.checkoutMutationActionTimeoutMs=CHECKOUT_MUTATION_ACTION_TIMEOUT_MS,_test_exports2.classifyPrWorkflowGitStateAsync=classifyPrWorkflowGitState,_test_exports2.sweepStaleDelegationsAsync=sweepStaleDelegations,_test_exports2.probeLaneLivenessAsync=probeAlivePrWorkflowLaneSessions,_test_exports2.getSessionOps=defaultGetSessionOps,_test_exports2.laneLivenessProbeTimeoutMs=PR_WORKFLOW_LANE_LIVENESS_PROBE_TIMEOUT_MS},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,sweepStaleDelegationsAsync:sweepStaleDelegations,probeLaneLivenessAsync:probeAlivePrWorkflowLaneSessions,getSessionOps:defaultGetSessionOps,laneLivenessProbeTimeoutMs:PR_WORKFLOW_LANE_LIVENESS_PROBE_TIMEOUT_MS,resolveCurrentGitHead,resolveCurrentGitHeadAsync,resolveCurrentUpstreamPushTarget,resolveCurrentUpstreamPushTargetAsync,resolveCurrentUpstreamRemoteRef,resolveExactRemoteBranchHead,resolveExactRemoteBranchHeadAsync,resolveCommitCountSince,resolveCommitCountSinceAsync,resolveIsWorkingTreeClean,resolveIsWorkingTreeCleanAsync,resolveIsExactSingleChildCommit,resolveIsExactSingleChildCommitAsync,resolvePrReviewDiffStats,resolvePrReviewDiffStatsAsync,resolvePrWorkflowRevisionDigest,MAX_WORKFLOW_BATCHES,MAX_PR_REVIEW_RESILIENCE_CIRCUIT_CONTRIBUTORS,MAX_RETIRED_REVIEWER_SESSION_IDS,MAX_RETIRED_CONSOLIDATED_LANES,MAX_RETIRED_FEEDBACK_ITEM_OWNERS,resolvePrWorkflowRevisionDigestDetailed,resolveRemoteRefsContainingHead,resolveRemoteRefsContainingHeadAsync,parseCriticVerdict,analyzePrReviewVerdictRowContract,parseLaneItemVerdicts,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:isProcessAlive3,isSafeStandaloneGitCommit,rename:fsp4.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"]),REVIEW_SEVERITY_RANK=new Map([["NONE",0],["INFO",1],["LOW",2],["MEDIUM",3],["HIGH",4],["CRITICAL",5]]),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.
|
|
883
|
+
`,"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_exports2.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_exports2.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_exports2.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_exports2.resolveCurrentGitHeadAsync(directory))?.trim(),remoteRefs=publishedHead?await _test_exports2.resolveRemoteRefsContainingHeadAsync(directory,publishedHead):null,remoteHead=await _test_exports2.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_exports2.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){if(reviewItemIds.length>MAX_PR_REVIEW_COLLECTION_RECEIPT_ITEM_IDS)throw Error(`BLOCKED: PR workflow review_item_ids may not exceed ${MAX_PR_REVIEW_COLLECTION_RECEIPT_ITEM_IDS} entries`);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 unsafeReadOnlyArgument(path85,constraint,value){return{safe:!1,path:path85||"(root)",constraint,value}}function readOnlyArgumentPath(parent,key){return parent?`${parent}.${key}`:key}function classifyReadOnlyToolArguments(toolName,value,key="",path85="",depth=0){if(depth>8)return unsafeReadOnlyArgument(path85,"argument nesting exceeds the read-only depth limit of 8",value);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 unsafeReadOnlyArgument(path85,"argument name is mutation-bearing and is not allowed for read-only tools",value);if(keyTokens.some((token)=>/^(?:method|verb)$/i.test(token)))return typeof value==="string"&&/^(?:GET|HEAD)$/i.test(value.trim())?{safe:!0}:unsafeReadOnlyArgument(path85,"HTTP method/verb must be GET or HEAD for a read-only tool",value);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())?{safe:!0}:unsafeReadOnlyArgument(path85,"action/operation must name a recognized observation operation",value);if(/^mode$/i.test(key)&&typeof value==="string")return(toolName==="search"?/^(?:r|rb|read|literal|regex)$/i:/^(?:r|rb|read)$/i).test(value.trim())?{safe:!0}:unsafeReadOnlyArgument(path85,toolName==="search"?"search mode must be one of r, rb, read, literal, or regex":"mode must be one of r, rb, or read for a read-only tool",value);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 unsafeReadOnlyArgument(path85,"query/request text contains a mutating operation",value);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)?unsafeReadOnlyArgument(path85,"string value contains a mutating command or request",value):{safe:!0}}if(value===null||value===void 0||typeof value==="number"||typeof value==="boolean")return{safe:!0};if(Array.isArray(value)){for(let index=0;index<value.length;index++){let result=classifyReadOnlyToolArguments(toolName,value[index],key,`${path85}[${index}]`,depth+1);if(!result.safe)return result}return{safe:!0}}if(typeof value==="object"){for(let[childKey,childValue]of Object.entries(value)){let result=classifyReadOnlyToolArguments(toolName,childValue,childKey,readOnlyArgumentPath(path85,childKey),depth+1);if(!result.safe)return result}return{safe:!0}}return unsafeReadOnlyArgument(path85,"argument type is not supported by the read-only classifier",value)}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_exports2.resolvePrWorkflowRevisionDigestDetailed!==resolvePrWorkflowRevisionDigestDetailed)return _test_exports2.resolvePrWorkflowRevisionDigestDetailed(directory,baseHeadSha);if(_test_exports2.resolvePrWorkflowRevisionDigest!==resolvePrWorkflowRevisionDigest){let digest2=_test_exports2.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 assertStringSetSubset(actual,expected,label){let actualSet=new Set(actual),expectedSet=new Set(expected),extra=[...actualSet].filter((value)=>!expectedSet.has(value));if(actual.length===0||actual.length!==actualSet.size||extra.length>0)throw Error(`BLOCKED: ${label} must be a non-empty subset of the mechanically derived inventory; 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 successful2=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)=>successful2.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;if(state.prReviewTriggerEvalPath)for(let batch of[...state.prReviewValidationBatches??[]].reverse()){if(batch.phase!=="council")continue;let successful2=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(successful2.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(readFileSync28(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=[],candidateSeverities=new Map,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);let extracted=extractCandidateRows(artifact.text,resolvePrReviewRowFamily(source.workflowLane,source.mode),source.creditedLanes);for(let row of extracted)if(candidateIds.push(row.candidateId),row.severity&&!candidateSeverities.has(row.candidateId))candidateSeverities.set(row.candidateId,row.severity)}}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.candidateSeverities=candidateSeverities,ctx.candidateInventory=candidateIds.length>0?candidateIds.sort():[PR_REVIEW_CLEAN_SENTINEL_ID],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,severity:isCandidateSeverity(analysis.values.severity)?analysis.values.severity:null,evidence:candidateFields.slice(2).join("\x00"),lineNumber:index+1})}return{rows,issues}}function extractCandidateRows(text,fallbackFamily,scopeToLanes){let inScope=(lane)=>!scopeToLanes||lane!==void 0&&scopeToLanes.includes(lane);return parseCanonicalCandidateRows(text,fallbackFamily).rows.filter((row)=>inScope(row.workflowLane))}function extractCandidateIds(text,fallbackFamily,scopeToLanes){return extractCandidateRows(text,fallbackFamily,scopeToLanes).map((row)=>row.candidateId)}function derivePrReviewCandidateSeverities(directory,state,ctx){if(!ctx.candidateSeverities)derivePrReviewCandidateInventory(directory,state,ctx);if(!ctx.candidateSeverities)throw Error("BLOCKED: PR_REVIEW candidate severity authority is unavailable for this gate context");return ctx.candidateSeverities}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 successful2=successfulObligationsFromExactBatch(directory,state,batch.batchId,batch.lanes,`swarm-pr-review:${phase}`,batch.validatedAt,!0,forbiddenSubagentSessionIds,ctx.revisionDigest,void 0,reviewerClaims);return successful2.size===batch.lanes.length&&batch.lanes.every((lane)=>successful2.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??[],{markerRows,parsed}=parsePrReviewVerdictRows(artifact.text,declaredItems,phase,reviewerClaims);if(!verdictRowsContainOnlyAssignedIds(markerRows,declaredItems)){appendCompositionDiagnostic(diagnostics,`${phase} lane "${qualified.expectedLane.laneId}" contains an unassigned verdict row; it contributes no claims`);continue}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 bindings=coherence.reviewerItemBindings,bindingKey2=coherence.reviewerItemBindingKeyEncoding==="prefixed-v1"?reviewerItemBindingKey(itemId):itemId,bound=bindings&&Object.hasOwn(bindings,bindingKey2)?bindings[bindingKey2]:void 0,current=reviewerClaims?.get(itemId)?.rowDigest;return Boolean(bound&¤t&&bound===current)}function reviewerItemBindingKey(itemId){return`${REVIEWER_ITEM_BINDING_KEY_PREFIX}${itemId}`}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[reviewerItemBindingKey(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&&!args2.allowTranscriptIncompleteRecovery)return failedLaneValidation("result.transcript_incomplete","false outside discovery candidate recovery",!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,allowTranscriptIncompleteRecovery:args2.expectedMode==="swarm-pr-review:base"||args2.expectedMode==="swarm-pr-review:micro"});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 successful2=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)successful2.add(obligation);return successful2}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";return analyzePrReviewVerdictRowContract(artifact.text,reviewItemIds??[],phase,reviewerClaims).ok}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,cleanAttestationSalvaged=!1,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,coverageKind:null,salvaged,repairKinds,cleanAttestationSalvaged,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);if(parsed.clean_attestation_salvaged)cleanAttestationSalvaged=!0,salvaged=!0,appendBoundedCandidateIssue(issues,parsed.clean_attestation_salvage_reason??"CLEAN attestation discredited; candidate rows retained");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)||Boolean(parsed.clean_attestation_salvaged)||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,coverageKind:null,salvaged,repairKinds,cleanAttestationSalvaged,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,coverageKind:"candidate",salvaged,repairKinds,cleanAttestationSalvaged};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,coverageKind:"clean",salvaged,repairKinds,cleanAttestationSalvaged};return{covered:!1,evidence:null,issues,coverageKind:null,salvaged,repairKinds,cleanAttestationSalvaged,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,allowTranscriptIncompleteRecovery:input.expected.mode==="swarm-pr-review:base"||input.expected.mode==="swarm-pr-review:micro"});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=[],recoveries=[],previewTruncated=input.result.truncated===!0,transcriptIncomplete=input.result.transcriptIncomplete===!0;for(let{workflowLane,analysis}of analyses){if(!analysis.covered)continue;let laneRecoveries=[];if(previewTruncated)laneRecoveries.push({workflowLane,kind:"truncated-preview-durable-artifact",reason:"inline preview truncated; durable artifact retained exact coverage"});if(transcriptIncomplete){if(analysis.coverageKind==="candidate")laneRecoveries.push({workflowLane,kind:"transcript-incomplete-terminal-candidate",reason:"partial transcript accepted only because a durable [CANDIDATE] row proved this lane"});else if(analysis.coverageKind==="clean")return failedLaneValidation("result.transcript_incomplete","complete transcript for every [CLEAN] attestation",`workflow lane ${workflowLane} was covered only by [CLEAN] after a partial transcript fetch`)}if(laneRecoveries.length===0&&!analysis.salvaged&&analysis.issues.length===0)continue;if(salvagedLanes.push(workflowLane),analysis.repairKinds.length>0)laneRecoveries.push({workflowLane,kind:"parser-normalization",reason:`structural repairs applied: ${analysis.repairKinds.join(", ")}`});if(analysis.cleanAttestationSalvaged)laneRecoveries.push({workflowLane,kind:"clean-attestation-salvaged",reason:"a conflicting [CLEAN] attestation was discredited while the independently validated candidate rows were retained"});if(analysis.issues.length>0)laneRecoveries.push({workflowLane,kind:"parser-row-recovery",reason:"one or more malformed or out-of-ownership rows were dropped while retaining valid coverage"});recoveries.push(...laneRecoveries);let reason=laneRecoveries.map((recovery)=>recovery.reason).join("; ");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,recoveries}:{ok:!0}}async function validatePrWorkflowTransportRecovery(input){let mode=input.record.mode?.trim();if(!(mode==="swarm-pr-review:reviewer"||mode==="swarm-pr-review:critic")&&input.result.truncated!==!0&&input.result.transcriptIncomplete!==!0)return{ok:!0};let workflowLane=input.record.workflowLane?.trim();if(!mode||!workflowLane)return{ok:!1,reason:"structured workflow transport recovery requires non-empty mode and workflow_lane provenance"};let state=await requireAnyActiveState(input.directory,input.record.parentSessionId),batchId=input.record.batchId?.trim(),laneId=input.record.laneId?.trim(),verdictPhase=mode==="swarm-pr-review:reviewer"?"reviewer":mode==="swarm-pr-review:critic"?"critic":null,declaredItemIds=(verdictPhase?(state.prReviewValidationBatches??[]).find((candidate)=>candidate.batchId===batchId&&candidate.phase===verdictPhase)?.lanes.find((candidate)=>candidate.laneId===laneId):void 0)?.reviewItemIds??[],rejectedReceipt=declaredItemIds.length>0?{assignedReviewItemIds:[...declaredItemIds],acceptedReviewItemIds:[],rejectedReviewItemIds:[...declaredItemIds]}:void 0,recordIntegrity=analyzeLaneRecordResultIntegrity({record:input.record,result:input.result,expected:{mode,workflowLane,ownedWorkflowLanes:[workflowLane],prHeadSha:input.record.workspace?.prHeadSha??"",gitHead:input.record.workspace?.gitHead??"",checkWorkflowLane:!0},requireCompleted:!1,allowTranscriptIncompleteRecovery:!1});if(!recordIntegrity.ok)return{ok:!1,reason:formatPrReviewLaneValidationFailure(recordIntegrity.failure),failure:recordIntegrity.failure,...rejectedReceipt?{receipt:rejectedReceipt}:{}};let artifactIntegrity=analyzeLaneArtifactIntegrity({record:input.record,result:input.result,artifact:input.artifact,expected:{mode,workflowLane,prHeadSha:input.record.workspace?.prHeadSha??"",gitHead:input.record.workspace?.gitHead??"",revisionDigest:input.revisionDigest,reviewScope:input.record.workspace?.scope??void 0}});if(!artifactIntegrity.ok)return{ok:!1,reason:formatPrReviewLaneValidationFailure(artifactIntegrity.failure),failure:artifactIntegrity.failure,...rejectedReceipt?{receipt:rejectedReceipt}:{}};let expectedMode=mode.startsWith("swarm-pr-review:")?"PR_REVIEW":mode.startsWith("swarm-pr-feedback:")?"PR_FEEDBACK":null;if(!expectedMode)return{ok:!1,reason:`structured workflow transport recovery does not support mode "${mode}"`,...rejectedReceipt?{receipt:rejectedReceipt}:{}};if(state.mode!==expectedMode)return{ok:!1,reason:`active workflow mode mismatch; expected ${expectedMode}, got ${state.mode}`,...rejectedReceipt?{receipt:rejectedReceipt}:{}};let artifactText=input.artifact?.text??"",prReviewGateContext=state.mode==="PR_REVIEW"?{revisionDigest:input.revisionDigest}:void 0;if(!batchId||!laneId)return{ok:!1,reason:"structured workflow transport recovery requires non-empty batch_id and lane_id provenance",...rejectedReceipt?{receipt:rejectedReceipt}:{}};if(mode==="swarm-pr-review:reviewer"||mode==="swarm-pr-review:critic"){let phase=verdictPhase??"reviewer",lane=(state.prReviewValidationBatches??[]).find((candidate)=>candidate.batchId===batchId&&candidate.phase===phase)?.lanes.find((candidate)=>candidate.laneId===laneId);if(!lane||lane.workflowLane!==workflowLane)return{ok:!1,reason:"no matching declared reviewer/critic lane ownership was found for this transport recovery",...rejectedReceipt?{receipt:rejectedReceipt}:{}};let itemIds=lane.reviewItemIds??[],reviewerClaims=phase==="critic"?authoritativeReviewerClaims(input.directory,state,prReviewGateContext??{revisionDigest:input.revisionDigest}):void 0;if(phase==="critic"&&(!reviewerClaims||reviewerClaims.size===0))return{ok:!1,reason:"critic transport recovery requires authoritative settled reviewer claims for every assigned item",...rejectedReceipt?{receipt:rejectedReceipt}:{}};let analysis=analyzePrReviewVerdictRowContract(artifactText,itemIds,phase,reviewerClaims);if(!analysis.ok){let failure=failedLaneValidation(phase==="reviewer"?"reviewer.verdict_rows":"critic.verdict_rows",analysis.expected,analysis.actual).failure;return{ok:!1,reason:formatPrReviewLaneValidationFailure(failure),failure,receipt:{assignedReviewItemIds:[...itemIds],acceptedReviewItemIds:[],rejectedReviewItemIds:[...itemIds]}}}let receipt={assignedReviewItemIds:[...itemIds],acceptedReviewItemIds:[...itemIds],rejectedReviewItemIds:[]};return input.result.truncated===!0?{ok:!0,receipt,recoveries:[{workflowLane,kind:"truncated-preview-durable-artifact",reason:"inline preview truncated; durable artifact retained exact coverage"}]}:{ok:!0,receipt}}else if(mode==="swarm-pr-feedback:verification"){let lane=(state.prFeedbackVerifications??[]).find((candidate)=>candidate.batchId===batchId)?.ownership.find((candidate)=>candidate.laneId===laneId);if(!lane||workflowLane!==lane.laneId)return{ok:!1,reason:"no matching declared PR_FEEDBACK verification ownership was found for this transport recovery"};let itemIds=lane?.ownedItemIds??[];if(itemIds.length===0||!feedbackArtifactTextCoversItems(artifactText,itemIds))return{ok:!1,reason:"every assigned PR_FEEDBACK verification item requires one exact [FEEDBACK-VERIFIED] row in the durable artifact"}}else{let feedbackPhase={"swarm-pr-feedback:stage-b-reviewer":{phase:"stage-b-reviewer",marker:"[STAGE-B-REVIEW]",verdict:"APPROVE"},"swarm-pr-feedback:stage-b-test":{phase:"stage-b-test",marker:"[STAGE-B-TEST]",verdict:"PASS"},"swarm-pr-feedback:closeout-reviewer":{phase:"closeout-reviewer",marker:"[CLOSEOUT-REVIEW]",verdict:"APPROVE"},"swarm-pr-feedback:closeout-critic":{phase:"closeout-critic",marker:"[CLOSEOUT-CRITIC]",verdict:"APPROVE"}}[mode];if(!feedbackPhase)return{ok:!1,reason:`structured workflow transport recovery does not support mode "${mode}"`};let batch=(state.prFeedbackGateBatches??[]).find((candidate)=>candidate.batchId===batchId&&candidate.phase===feedbackPhase.phase&&candidate.laneId===laneId);if(!batch||workflowLane!==feedbackPhase.phase)return{ok:!1,reason:"no matching declared ordered PR_FEEDBACK lane provenance was found for this transport recovery"};let itemIds=batch?.itemIds??[];if(itemIds.length===0||!itemIds.every((itemId)=>artifactHasExactPositiveVerdictRow(artifactText,feedbackPhase.marker,itemId,feedbackPhase.verdict)))return{ok:!1,reason:"every assigned ordered PR_FEEDBACK item requires one exact positive verdict row in the durable artifact"}}return input.result.truncated===!0?{ok:!0,recoveries:[{workflowLane,kind:"truncated-preview-durable-artifact",reason:"inline preview truncated; durable artifact retained exact coverage"}]}:{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 indexVerdictRows(text,marker,fieldCount){let markerRows=[],rowsByItemId=new Map;for(let line of text.split(/\r?\n/)){let fields=pipeFieldsCapped(line,fieldCount);if(fields[0]!==marker)continue;markerRows.push(fields);let itemId=fields[1]??"",rows=rowsByItemId.get(itemId);if(rows)rows.push(fields);else rowsByItemId.set(itemId,[fields])}return{markerRows,rowsByItemId}}function validateReviewerVerdictFields(fields){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[2]==="DISPROVED"&&fields[4]!=="NONE")return null;if(fields[7].length<8||fields[8].length<5||fields[9].length<3)return null;return fields}function reviewerVerdictRowDigest(fields){return createHash34("sha256").update(fields.join("\x00")).digest("hex")}function parseLaneItemVerdicts(text,itemIds,phase,reviewerClaims){return parsePrReviewVerdictRows(text,itemIds,phase,reviewerClaims).parsed}function parsePrReviewVerdictRows(text,itemIds,phase,reviewerClaims){let parsed=new Map,marker=phase==="reviewer"?"[REVIEWED]":"[CRITIC]",{markerRows,rowsByItemId}=indexVerdictRows(text,marker,phase==="reviewer"?10:6);for(let itemId of itemIds){if(phase==="reviewer"){let rows2=rowsByItemId.get(itemId),fields=rows2?.length===1?validateReviewerVerdictFields(rows2[0]):null;if(!fields)continue;parsed.set(itemId,{classification:fields[2],severity:fields[4],rowDigest:reviewerVerdictRowDigest(fields)});continue}let rows=rowsByItemId.get(itemId),verdict=rows?.length===1?validateCriticVerdictFields(rows[0],reviewerClaims?.get(itemId)?.severity):null;if(!verdict)continue;parsed.set(itemId,{classification:verdict.status,severity:verdict.severity})}return{markerRows,parsed}}function analyzePrReviewVerdictRowContract(text,itemIds,phase,reviewerClaims){let marker=phase==="reviewer"?"[REVIEWED]":"[CRITIC]",assigned=new Set(itemIds),{markerRows,parsed}=parsePrReviewVerdictRows(text,itemIds,phase,reviewerClaims),observedIds=markerRows.map((fields)=>fields[1]||"(missing)"),unexpectedIds=[...new Set(observedIds.filter((itemId)=>!assigned.has(itemId)))],invalidOrMissingIds=itemIds.filter((itemId)=>!parsed.has(itemId));return{ok:verdictRowIdsMatchExactly(markerRows,itemIds)&&invalidOrMissingIds.length===0,expected:`exactly one parseable ${marker} row for assigned IDs ${JSON.stringify(itemIds)} and no other ${marker} IDs`,actual:JSON.stringify({rowCount:markerRows.length,observedIds,invalidOrMissingIds,unexpectedIds})}}function verdictRowIdsMatchExactly(markerRows,itemIds){if(itemIds.length===0||markerRows.length!==itemIds.length)return!1;let assigned=new Set(itemIds);if(assigned.size!==itemIds.length)return!1;let observed=new Set;for(let fields of markerRows){let itemId=fields[1]??"";if(!assigned.has(itemId)||observed.has(itemId))return!1;observed.add(itemId)}return observed.size===assigned.size}function verdictRowsContainOnlyAssignedIds(markerRows,itemIds){if(itemIds.length===0)return!1;let assigned=new Set(itemIds);return markerRows.every((fields)=>assigned.has(fields[1]??""))}function parseCriticVerdict(text,itemId,reviewerSeverity){let rows=indexVerdictRows(text,"[CRITIC]",6).rowsByItemId.get(itemId);if(!rows||rows.length!==1)return null;return validateCriticVerdictFields(rows[0],reviewerSeverity)}function validateCriticVerdictFields(fields,reviewerSeverity){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 reviewerRank=REVIEW_SEVERITY_RANK.get(reviewerSeverity),criticRank=REVIEW_SEVERITY_RANK.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 feedbackArtifactTextCoversItems(text,itemIds){let rows=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 path84.join(WORKFLOW_GATE_DIR,"checkout.lock")}function workflowCheckoutMutationLockPath(directory){return validateSwarmPath(directory,workflowCheckoutMutationLockRelativePath())}function openCheckoutLockFile(lockPath){return fsp4.open(lockPath,"wx")}function removeCheckoutLockFile(lockPath){return fsp4.rm(lockPath)}function checkoutMutationProjectKey(directory){return normalizeComparableFsPath(directory)}async function withCheckoutMutationDeadline(promise2,phase){let timeout;try{return await Promise.race([promise2,new Promise((resolve45)=>{timeout=setTimeout(()=>{resolve45({status:"timeout",error:new PrWorkflowCheckoutMutationTimeoutError(phase)})},_test_exports2.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((resolve45)=>{release=resolve45}),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_exports2.openCheckoutLock(lockPath),lock={ownerToken:randomUUID14(),pid:process.pid,createdAtMs:_test_exports2.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_exports2.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_exports2.isProcessAlive(lock.pid))return!1;return removeCheckoutMutationLockIfOwned(lockPath,lock.ownerToken)}try{let stat11=await fsp4.stat(lockPath);if(_test_exports2.nowMs()-stat11.mtimeMs<STATE_MUTATION_LOCK_UNINITIALIZED_STALE_MS)return!1;return await fsp4.rm(lockPath,{force:!0}),!0}catch(error49){if(error49.code==="ENOENT")return!0;throw error49}}async function readCheckoutMutationLock(lockPath){let raw;try{raw=await fsp4.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_exports2.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_exports2.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((resolve45)=>{release=resolve45}),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 fsp4.open(lockPath,"wx"),lock={ownerToken:randomUUID14(),pid:process.pid,createdAtMs:_test_exports2.nowMs()},writeError;try{await _test_exports2.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_exports2.isProcessAlive(lock.pid))return!1;return removeSessionStateMutationLockIfOwned(lockPath,lock.ownerToken)}try{let stat11=await fsp4.stat(lockPath);if(_test_exports2.nowMs()-stat11.mtimeMs<STATE_MUTATION_LOCK_UNINITIALIZED_STALE_MS)return!1;return await fsp4.rm(lockPath,{force:!0}),!0}catch(error49){if(error49.code==="ENOENT")return!0;throw error49}}async function readSessionStateMutationLock(lockPath){let raw;try{raw=await fsp4.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 fsp4.rm(lockPath),!0}catch(error49){if(error49.code==="ENOENT")return!1;throw error49}}function isProcessAlive3(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 fsp4.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 fsp4.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=path84.normalize(path84.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 path84.join(WORKFLOW_GATE_DIR,`${prWorkflowSessionFileStem(sessionID)}.lock`)}function workflowGateStateRelativePath(sessionID){return path84.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=createHash34("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=path84.resolve(directory,".swarm"),parentPath=path84.dirname(path84.resolve(filePath)),relativeParent=path84.relative(swarmRoot,parentPath);if(relativeParent===".."||relativeParent.startsWith(`..${path84.sep}`)||path84.isAbsolute(relativeParent))throw Error("BLOCKED: PR workflow atomic destination escapes the project .swarm directory");await fsp4.mkdir(swarmRoot,{recursive:!0});let currentPath=swarmRoot,currentIdentity=await assertSafeDirectory(currentPath,void 0);for(let segment of relativeParent.split(path84.sep).filter(Boolean)){let nextPath=path84.join(currentPath,segment);await _test_exports2.beforeSafeDirectoryCreate?.(currentPath,nextPath),await assertSafeDirectory(currentPath,currentIdentity);try{await fsp4.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([fsp4.realpath(currentPath),fsp4.realpath(nextPath)]);if(normalizeComparableFsPath(path84.dirname(realNext))!==normalizeComparableFsPath(realCurrent))throw Error("BLOCKED: PR workflow directory creation escaped the project .swarm tree");currentPath=nextPath,currentIdentity=nextIdentity}let realRoot=await fsp4.realpath(swarmRoot),realParent=await fsp4.realpath(parentPath),relativeRealParent=path84.relative(realRoot,realParent);if(relativeRealParent===".."||relativeRealParent.startsWith(`..${path84.sep}`)||path84.isAbsolute(relativeRealParent))throw Error("BLOCKED: PR workflow atomic parent escapes the project .swarm directory");return realParent}async function assertSafeDirectory(directoryPath,expectedIdentity){let stat11=await fsp4.lstat(directoryPath,{bigint:!0});if(stat11.isSymbolicLink()||!stat11.isDirectory()||expectedIdentity&&!sameBigIntFileIdentity(stat11,expectedIdentity))throw Error("BLOCKED: PR workflow .swarm path must be a real directory and must not change during the operation");return{dev:stat11.dev,ino:stat11.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[stat11,realRoot,realFile,realParent]=await Promise.all([fsp4.lstat(filePath,{bigint:!0}),fsp4.realpath(path84.resolve(directory,".swarm")),fsp4.realpath(filePath),fsp4.realpath(path84.dirname(filePath))]),relativeFile=path84.relative(realRoot,realFile);if(stat11.isSymbolicLink()||!stat11.isFile()||!sameBigIntFileIdentity(stat11,expectedIdentity)||normalizeComparableFsPath(realParent)!==normalizeComparableFsPath(expectedParent)||relativeFile===""||relativeFile===".."||relativeFile.startsWith(`..${path84.sep}`)||path84.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}.${randomUUID14()}`,tempIdentity,lastError;try{let handle=await fsp4.open(tempPath,"wx");try{await _test_exports2.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_exports2.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_exports2.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 fsp4.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((resolve45)=>setTimeout(resolve45,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_PR_REVIEW_BASE_LANES_PER_BATCH,MAX_PR_REVIEW_RESILIENCE_CIRCUIT_CONTRIBUTORS,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,PrReviewResiliencePolicyRecordSchema,PrReviewResilienceAttemptRecordSchema,PrReviewResilienceCircuitRecordSchema,PrReviewResilienceStateRecordSchema,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",PR_WORKFLOW_LANE_LIVENESS_PROBE_TIMEOUT_MS=5000,PR_WORKFLOW_PENDING_LIVENESS_THRESHOLD_MS=180000,PR_WORKFLOW_PENDING_LIVENESS_MODES,LIVE_SESSION_STATUS_TYPES,defaultGetSessionOps=()=>swarmState.opencodeClient?.session??null,PrReviewResilienceCircuitOpenError,PrReviewResilienceRetryExhaustedError,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_exports2,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,PR_REVIEW_CLEAN_SENTINEL_ID="CLEAN-REVIEW",MAX_COMPOSITION_DIAGNOSTICS=16,MAX_UNCLAIMED_ITEMS_IN_MESSAGE=50,REVIEWER_ITEM_BINDING_KEY_PREFIX="item:",REVIEWER_CLASSIFICATIONS,REVIEWER_EVIDENCE_TYPES,REVIEW_SEVERITIES,REVIEW_SEVERITY_RANK,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_collection_receipt();init_pr_review_trigger_contract();init_workspace_snapshot();init_constants();init_schema();init_pr_workflow_state();init_state2();init_tool_metadata();init_logger();init_timeout();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_REVIEW_BASE_LANES_PER_BATCH=PR_REVIEW_BASE_DIMENSION_IDS.length,MAX_PR_REVIEW_RESILIENCE_CIRCUIT_CONTRIBUTORS=MAX_WORKFLOW_BATCHES*MAX_PR_REVIEW_BASE_LANES_PER_BATCH,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).max(MAX_PR_REVIEW_BASE_LANES_PER_BATCH),validatedAt:exports_external.string().min(1)}).strict(),PrReviewResiliencePolicyRecordSchema=exports_external.object({enabled:exports_external.boolean(),canaryProbeMs:exports_external.number().int().positive(),statusProbeTimeoutMs:exports_external.number().int().positive(),correlatedFailureThreshold:exports_external.number().int().min(2).max(8),maxRetryAttemptsAfterInitial:exports_external.number().int().min(0).max(2)}).strict(),PrReviewResilienceAttemptRecordSchema=exports_external.object({attempt:exports_external.union([exports_external.literal(0),exports_external.literal(1),exports_external.literal(2)]),targetDimensions:exports_external.array(PrReviewBaseDimensionIdSchema).min(1).max(PR_REVIEW_BASE_DIMENSION_IDS.length),canaryBatchId:exports_external.string().min(1),canaryLaneId:exports_external.string().min(1),canaryWorkflowLane:PrReviewBaseDimensionIdSchema,admittedAt:exports_external.string().min(1),fanoutBatchId:exports_external.string().min(1).optional()}).strict(),PrReviewResilienceCircuitRecordSchema=exports_external.object({signature:exports_external.string().min(1).max(512),count:exports_external.number().int().min(2).max(MAX_PR_REVIEW_RESILIENCE_CIRCUIT_CONTRIBUTORS),contributors:exports_external.array(exports_external.object({batchId:exports_external.string().min(1),laneId:exports_external.string().min(1)}).strict()).min(2).max(MAX_PR_REVIEW_RESILIENCE_CIRCUIT_CONTRIBUTORS),openedAt:exports_external.string().min(1)}).strict(),PrReviewResilienceStateRecordSchema=exports_external.object({policy:PrReviewResiliencePolicyRecordSchema,attempts:exports_external.array(PrReviewResilienceAttemptRecordSchema).max(3),circuit:PrReviewResilienceCircuitRecordSchema.optional()}).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).max(MAX_PR_REVIEW_COLLECTION_RECEIPT_ITEM_IDS).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(),reviewerItemBindingKeyEncoding:exports_external.literal("prefixed-v1").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(),prReviewResilience:PrReviewResilienceStateRecordSchema.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"]),PR_WORKFLOW_PENDING_LIVENESS_MODES=new Set(["swarm-pr-review:base","swarm-pr-review:micro","swarm-pr-review:council","swarm-pr-review:reviewer","swarm-pr-review:critic"]),LIVE_SESSION_STATUS_TYPES=new Set(["busy","retry"]);PrReviewResilienceCircuitOpenError=class PrReviewResilienceCircuitOpenError extends Error{code="PR_REVIEW_RESILIENCE_CIRCUIT_OPEN";constructor(message){super(message);this.name="PrReviewResilienceCircuitOpenError"}};PrReviewResilienceRetryExhaustedError=class PrReviewResilienceRetryExhaustedError extends Error{code="PR_REVIEW_RESILIENCE_RETRY_EXHAUSTED";constructor(message){super(message);this.name="PrReviewResilienceRetryExhaustedError"}};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_exports2={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_exports2.beforeTerminalClear=void 0,_test_exports2.beforeAbortClear=void 0,_test_exports2.beforePrFeedbackTransitionLock=void 0,_test_exports2.beforePrFeedbackTrackingSwitch=void 0,_test_exports2.afterPrFeedbackTrackingSwitch=void 0,_test_exports2.beforePrFeedbackTrackingPersist=void 0,_test_exports2.beforeBoundedSwarmFileOpen=void 0,_test_exports2.beforeSessionStateLockWrite=void 0,_test_exports2.beforeCheckoutLockWrite=void 0,_test_exports2.beforeSafeDirectoryCreate=void 0,_test_exports2.beforeAtomicTempWrite=void 0,_test_exports2.beforeAtomicRename=void 0,_test_exports2.openCheckoutLock=openCheckoutLockFile,_test_exports2.removeCheckoutLock=removeCheckoutLockFile,_test_exports2.checkoutMutationActionTimeoutMs=CHECKOUT_MUTATION_ACTION_TIMEOUT_MS,_test_exports2.classifyPrWorkflowGitStateAsync=classifyPrWorkflowGitState,_test_exports2.sweepStaleDelegationsAsync=sweepStaleDelegations,_test_exports2.probeLaneLivenessAsync=probeAlivePrWorkflowLaneSessions,_test_exports2.getSessionOps=defaultGetSessionOps,_test_exports2.laneLivenessProbeTimeoutMs=PR_WORKFLOW_LANE_LIVENESS_PROBE_TIMEOUT_MS,_test_exports2.pendingLaneLivenessThresholdMs=PR_WORKFLOW_PENDING_LIVENESS_THRESHOLD_MS},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,sweepStaleDelegationsAsync:sweepStaleDelegations,probeLaneLivenessAsync:probeAlivePrWorkflowLaneSessions,getSessionOps:defaultGetSessionOps,laneLivenessProbeTimeoutMs:PR_WORKFLOW_LANE_LIVENESS_PROBE_TIMEOUT_MS,pendingLaneLivenessThresholdMs:PR_WORKFLOW_PENDING_LIVENESS_THRESHOLD_MS,resolveCurrentGitHead,resolveCurrentGitHeadAsync,resolveCurrentUpstreamPushTarget,resolveCurrentUpstreamPushTargetAsync,resolveCurrentUpstreamRemoteRef,resolveExactRemoteBranchHead,resolveExactRemoteBranchHeadAsync,resolveCommitCountSince,resolveCommitCountSinceAsync,resolveIsWorkingTreeClean,resolveIsWorkingTreeCleanAsync,resolveIsExactSingleChildCommit,resolveIsExactSingleChildCommitAsync,resolvePrReviewDiffStats,resolvePrReviewDiffStatsAsync,resolvePrWorkflowRevisionDigest,MAX_WORKFLOW_BATCHES,MAX_PR_REVIEW_RESILIENCE_CIRCUIT_CONTRIBUTORS,MAX_RETIRED_REVIEWER_SESSION_IDS,MAX_RETIRED_CONSOLIDATED_LANES,MAX_RETIRED_FEEDBACK_ITEM_OWNERS,resolvePrWorkflowRevisionDigestDetailed,resolveRemoteRefsContainingHead,resolveRemoteRefsContainingHeadAsync,parseCriticVerdict,analyzePrReviewVerdictRowContract,parseLaneItemVerdicts,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:isProcessAlive3,isSafeStandaloneGitCommit,rename:fsp4.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"]),REVIEW_SEVERITY_RANK=new Map([["NONE",0],["INFO",1],["LOW",2],["MEDIUM",3],["HIGH",4],["CRITICAL",5]]),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.
|
|
884
884
|
|
|
885
885
|
${USAGE}`;if(!sessionID?.trim())return`Error: abort-pr-workflow requires an active sessionID.
|
|
886
886
|
|
|
@@ -2867,9 +2867,9 @@ Flags:
|
|
|
2867
2867
|
`)}var init_recall_planner=__esm(()=>{init_role_profiles()});import{appendFile as appendFile18,mkdir as mkdir37}from"node:fs/promises";import*as path155 from"node:path";async function appendMemoryRunLog(directory,runId,event){let safeRunId=sanitizeRunId(runId),relativePath2=path155.join("runs",safeRunId,"memory.jsonl"),filePath=validateSwarmPath(directory,relativePath2);await mkdir37(path155.dirname(filePath),{recursive:!0}),await appendFile18(filePath,`${JSON.stringify({...event,runId:safeRunId,timestamp:event.timestamp??new Date().toISOString()})}
|
|
2868
2868
|
`,"utf-8")}function sanitizeRunId(runId){return(runId?.trim()||"unknown").replace(/[^A-Za-z0-9._-]/g,"_").slice(0,80)||"unknown"}var init_run_log=__esm(()=>{init_utils2()});import{appendFile as appendFile19,mkdir as mkdir38}from"node:fs/promises";import*as path156 from"node:path";function createMemoryLifecycleHooks(options){let internals={createGateway:options.createGateway??createMemoryGateway,appendRunLog:options.appendRunLog??appendMemoryRunLog};return{messagesTransform:async(input,output)=>{await injectIntoMessages(input,output,options,internals)},toolAfter:async(input,output)=>{await captureTaskOutputProposals(input,output,options,internals)}}}async function injectIntoMessages(input,output,options,internals){let messages=output?.messages;if(!Array.isArray(messages)||messages.length===0)return;if(messagesContainRecall(messages))return;let sessionID=getSessionID(input,messages),agentRole=resolveMessageAgent(messages,options,sessionID),latestUserText=latestTextForRole(messages,"user");if(!latestUserText)return;let agentTask=extractTaskToolPrompt(messages)??latestUserText,unitId=options.getActiveTaskId?.(sessionID),result=await recallForAgent({directory:options.directory,config:options.config,sessionID,agentRole,agentId:agentRole,userGoal:latestUserText,agentTask,unitId,createGateway:internals.createGateway,appendRunLog:internals.appendRunLog});if(result)await maybeWriteUnitIdProbe({directory:options.directory,sessionID,agentRole,unitId,agentTask,bundleId:result.bundle.id});if(!result||result.bundle.items.length===0)return;let insertAt=recallMessageInsertIndex(messages),recallMessage={info:{role:"system",agent:agentRole,sessionID},parts:[{type:"text",text:result.bundle.promptBlock}]};messages.splice(insertAt,0,recallMessage),await internals.appendRunLog(options.directory,sessionID,{event:"prompt_injected",runId:sessionID??"unknown",agentRole,agentId:agentRole,bundleId:result.bundle.id,memoryIds:result.bundle.items.map((item)=>item.record.id),tokenEstimate:result.bundle.tokenEstimate,metadata:{surface:"chat_messages"}})}async function captureTaskOutputProposals(input,output,options,internals){let task=parseTaskToolInput(input);if(!task)return;let outputText2=output?.output;if(typeof outputText2!=="string"||!outputText2.includes("memoryProposals")&&!outputText2.includes("curatorMemoryDecisions"))return;let extracted=outputText2.includes("memoryProposals")?extractMemoryProposalsFromAgentOutput(outputText2):{proposals:[]};if(extracted.error){await internals.appendRunLog(options.directory,task.sessionID,{event:"proposal_rejected_by_validation",runId:task.sessionID??"unknown",agentRole:task.agentRole,agentId:task.agentRole,rejectionReason:extracted.error});return}let decisionExtraction=outputText2.includes("curatorMemoryDecisions")?extractCuratorMemoryDecisionsFromAgentOutput(outputText2):{decisions:[]};if(decisionExtraction.error){await internals.appendRunLog(options.directory,task.sessionID,{event:"curator_decision_rejected_by_validation",runId:task.sessionID??"unknown",agentRole:task.agentRole,agentId:task.agentRole,rejectionReason:decisionExtraction.error});return}if(extracted.proposals.length===0&&decisionExtraction.decisions.length===0)return;let gateway=internals.createGateway({directory:options.directory,sessionID:task.sessionID,agentRole:task.agentRole,agentId:task.agentRole,runId:task.sessionID},{config:options.config});if(!gateway.isEnabled()){await gateway.dispose?.();return}try{for(let proposalInput of extracted.proposals)try{let proposal=await gateway.propose(proposalInput);await internals.appendRunLog(options.directory,task.sessionID,{event:proposal.status==="pending"?"proposal_created":"proposal_rejected_by_validation",runId:task.sessionID??"unknown",agentRole:task.agentRole,agentId:task.agentRole,proposalId:proposal.id,rejectionReason:proposal.rejectionReason})}catch(err){await internals.appendRunLog(options.directory,task.sessionID,{event:"proposal_rejected_by_validation",runId:task.sessionID??"unknown",agentRole:task.agentRole,agentId:task.agentRole,rejectionReason:err instanceof Error?err.message:String(err)})}if(decisionExtraction.decisions.length>0&&!isCuratorAgent(task.agentRole)){await internals.appendRunLog(options.directory,task.sessionID,{event:"curator_decision_rejected_by_validation",runId:task.sessionID??"unknown",agentRole:task.agentRole,agentId:task.agentRole,rejectionReason:"only curator agents may emit curatorMemoryDecisions"});return}if(decisionExtraction.decisions.length>0){let applyCuratorDecisionMethod=gateway.applyCuratorDecision;if(!applyCuratorDecisionMethod){await internals.appendRunLog(options.directory,task.sessionID,{event:"curator_decision_rejected_by_validation",runId:task.sessionID??"unknown",agentRole:task.agentRole,agentId:task.agentRole,rejectionReason:"memory gateway does not support curator decisions"});return}let applyCuratorDecision=applyCuratorDecisionMethod.bind(gateway);for(let decision of decisionExtraction.decisions)try{let change=await applyCuratorDecision(decision);await internals.appendRunLog(options.directory,task.sessionID,{event:"curator_decision_applied",runId:task.sessionID??"unknown",agentRole:task.agentRole,agentId:task.agentRole,proposalId:change.proposalId,memoryIds:[change.memoryId,change.targetMemoryId,change.oldMemoryId,change.replacementMemoryId].filter((id)=>Boolean(id)),rejectionReason:change.reason,metadata:{action:change.action,proposalStatus:change.proposalStatus,eventId:change.eventId}})}catch(err){await internals.appendRunLog(options.directory,task.sessionID,{event:"curator_decision_rejected_by_validation",runId:task.sessionID??"unknown",agentRole:task.agentRole,agentId:task.agentRole,proposalId:decision.proposalId,rejectionReason:err instanceof Error?err.message:String(err),metadata:{action:decision.action}})}}}finally{await gateway.dispose?.()}}async function recallForAgent(input){let gateway=input.createGateway({directory:input.directory,sessionID:input.sessionID,agentRole:input.agentRole,agentId:input.agentId,runId:input.sessionID,unitId:input.unitId},{config:input.config});try{let resolvedConfig=resolveMemoryConfig(input.config);if(!gateway.isEnabled())return await logInjectionSkipped(input,"disabled"),null;if(!resolvedConfig.recall.injection.enabled)return await logInjectionSkipped(input,"disabled"),null;let scopes=gateway.deriveAllowedScopes(),planInput={userGoal:compactText(input.userGoal),runId:input.sessionID??"unknown",agentRole:input.agentRole,agentId:input.agentId,agentTask:compactText(input.agentTask),touchedFiles:extractTouchedFiles(input.agentTask)},plan=buildMemoryRecallPlan(planInput,{scopes});plan.maxItems=resolvedConfig.recall.injection.maxItems,plan.tokenBudget=resolvedConfig.recall.injection.tokenBudget,await input.appendRunLog(input.directory,input.sessionID,{event:"recall_requested",runId:input.sessionID??"unknown",agentRole:input.agentRole,agentId:input.agentId,metadata:{kinds:plan.kinds,maxItems:plan.maxItems,tokenBudget:plan.tokenBudget,scopeTypes:plan.scopes.map((scope)=>scope.type)}});let recallInput={query:plan.query,task:planInput.agentTask,mode:"injection",scopes:plan.scopes,kinds:plan.kinds,maxItems:plan.maxItems,tokenBudget:plan.tokenBudget,minScore:resolvedConfig.recall.injection.minScore,requireQuerySignal:resolvedConfig.recall.injection.requireQuerySignal},bundle=await gateway.recall(recallInput);if(await input.appendRunLog(input.directory,input.sessionID,{event:"recall_returned",runId:input.sessionID??"unknown",agentRole:input.agentRole,agentId:input.agentId,bundleId:bundle.id,memoryIds:bundle.items.map((item)=>item.record.id),scores:bundle.items.map((item)=>item.score),tokenEstimate:bundle.tokenEstimate}),bundle.items.length===0)await logInjectionSkipped(input,bundle.diagnostics?.injectionSkipReason??"no_results",bundle);return{bundle,scopes}}finally{await gateway.dispose?.()}}async function logInjectionSkipped(input,reason,bundle){await input.appendRunLog(input.directory,input.sessionID,{event:"prompt_injection_skipped",runId:input.sessionID??"unknown",agentRole:input.agentRole,agentId:input.agentId,bundleId:bundle?.id,memoryIds:bundle?.items.map((item)=>item.record.id),scores:bundle?.items.map((item)=>item.score),tokenEstimate:bundle?.tokenEstimate,rejectionReason:reason,metadata:{reason,candidateCount:bundle?.diagnostics?.candidateCount,preScoredFilteredCount:bundle?.diagnostics?.preScoredFilteredCount,noSignalCount:bundle?.diagnostics?.noSignalCount,belowThresholdCount:bundle?.diagnostics?.belowThresholdCount}})}async function maybeWriteUnitIdProbe(input){if(process.env.OPENCODE_SWARM_MEMORY_UNITID_PROBE!=="1")return;try{let match=input.agentTask.match(UNITID_PROBE_TASK_ID_PATTERN),record3={sessionID:input.sessionID,agentRole:input.agentRole,resolvedUnitId:input.unitId??null,promptTaskIdCandidate:match?match[1]:null,agentTaskSnippet:input.agentTask.slice(0,160),bundleId:input.bundleId,timestamp:new Date().toISOString()},filePath=validateSwarmPath(input.directory,path156.join("memory","unitid-probe.jsonl"));await mkdir38(path156.dirname(filePath),{recursive:!0}),await appendFile19(filePath,`${JSON.stringify(record3)}
|
|
2869
2869
|
`,"utf-8")}catch{}}function parseTaskToolInput(input){let record3=input,rawTool=typeof record3.tool==="string"?record3.tool:void 0,toolName=rawTool?normalizeToolName(rawTool)??rawTool:void 0;if(toolName!=="Task"&&toolName!=="task")return null;if(!record3.args||typeof record3.args!=="object")return null;let args2=record3.args,prompt=args2.prompt;if(typeof prompt!=="string"||prompt.trim().length===0)return null;let target=typeof args2.subagent_type==="string"?args2.subagent_type:typeof args2.agent==="string"?args2.agent:typeof record3.agent==="string"?record3.agent:"architect";return{sessionID:typeof record3.sessionID==="string"?record3.sessionID:void 0,agentRole:stripKnownSwarmPrefix(target),prompt}}function isCuratorAgent(agentRole){return agentRole==="curator"||agentRole==="curator_init"||agentRole==="curator_phase"||agentRole==="curator_postmortem"}function messagesContainRecall(messages){return messages.some((message)=>message?.parts?.some((part)=>{let text=part?.text;if(typeof text!=="string")return!1;return RECALL_BUNDLE_MARKER_RE.test(text)||text.includes(MEMORY_SENTINEL)}))}function getSessionID(input,messages){let inputSession=input?.sessionID;if(typeof inputSession==="string")return inputSession;for(let message of messages){let sessionID=message?.info?.sessionID;if(typeof sessionID==="string")return sessionID}return}function resolveMessageAgent(messages,options,sessionID){let configured=options.getActiveAgentName?.(sessionID);if(configured)return stripKnownSwarmPrefix(configured);for(let message of messages){let agent=message?.info?.agent;if(typeof agent==="string")return stripKnownSwarmPrefix(agent)}return"architect"}function latestTextForRole(messages,role){for(let i=messages.length-1;i>=0;i--){let message=messages[i];if(message.info?.role!==role||!Array.isArray(message.parts))continue;let text=message.parts.map((part)=>part?.text).filter((partText)=>typeof partText==="string").join(`
|
|
2870
|
-
`).trim();if(text)return text}return null}function extractTaskToolPrompt(messages){for(let i=messages.length-1;i>=0;i--){let msg=messages[i];if((msg.role??msg.info?.role)!=="assistant")continue;let content=Array.isArray(msg.content)?msg.content:Array.isArray(msg.parts)?msg.parts:[];for(let j=content.length-1;j>=0;j--){let block=content[j];if(block&&typeof block==="object"){let b=block;if(b.type==="tool_use"&&b.name==="Task"){let prompt=b.input?.prompt;if(typeof prompt==="string"&&prompt.length>0)return prompt}}}}return null}function recallMessageInsertIndex(messages){for(let i=messages.length-1;i>=0;i--)if(messages[i]?.info?.role==="user")return i;return messages.length}function extractTouchedFiles(text){let matches=text.match(/\b(?:src|tests|test|docs|scripts|packages)\/[A-Za-z0-9._/@+-]+/g);return Array.from(new Set(matches??[])).slice(0,20)}function compactText(text){let compacted=text.replace(/\s+/g," ").trim();if(compacted.length<=2000)return compacted;return Array.from(compacted).slice(0,2000).join("")}var MEMORY_SENTINEL,UNITID_PROBE_TASK_ID_PATTERN;var init_injector=__esm(()=>{init_agent_output_schema();init_schema();init_normalize_tool_name();init_utils2();init_config2();init_gateway();init_recall_planner();init_run_log();init_sentinel();MEMORY_SENTINEL=MEMORY_RECALL_SENTINEL;UNITID_PROBE_TASK_ID_PATTERN=/\bTASK:\s*(\d+(?:\.\d+)+)\b/});function containerScopedDefaultVisibility(grammarId,containerType){if(containerType==="interface_declaration")return"public";switch(grammarId){case"kotlin":return"public";case"java":return"package";default:return containerType===void 0?"internal":"private"}}function collectCommonJsExports(source){let sanitized=maskCommentsAndStrings(source),exportsByLocal=new Map,add2=(localName,exportedName,sourceIndex)=>{if(!isIdentifier(localName)||!isIdentifier(exportedName))return;let existing=exportsByLocal.get(localName);if(existing&&existing.sourceIndex<=sourceIndex)return;exportsByLocal.set(localName,{localName,exportedName,exportedReason:"explicit_export",sourceIndex})};for(let match of sanitized.matchAll(/\bmodule\s*\.\s*exports\s*=\s*([A-Za-z_$][\w$]*)\b/g))add2(match[1],match[1],match.index??0);for(let match of sanitized.matchAll(/\bmodule\s*\.\s*exports\s*=\s*\{([^}]*)\}/g)){let body=match[1],baseIndex=match.index??0;for(let part of body.split(",")){let entry=part.trim();if(!entry)continue;let alias=entry.match(/^([A-Za-z_$][\w$]*)\s*:\s*([A-Za-z_$][\w$]*)$/);if(alias){add2(alias[2],alias[1],baseIndex+match[0].indexOf(part));continue}let shorthand=entry.match(/^([A-Za-z_$][\w$]*)$/);if(shorthand)add2(shorthand[1],shorthand[1],baseIndex+match[0].indexOf(part))}}for(let match of sanitized.matchAll(/\b(?:module\s*\.\s*exports|exports)\s*\.\s*([A-Za-z_$][\w$]*)\s*=\s*([A-Za-z_$][\w$]*)\b/g))add2(match[2],match[1],match.index??0);return exportsByLocal}function collectPythonAllNames(source){let match=source.match(/__all__\s*=\s*([[({])([\s\S]*?)[\])}]/);if(!match)return null;let body=match[2].trim();if(!body)return new Set;let names=new Set;for(let part of body.split(",")){let trimmed=part.trim();if(!trimmed)continue;let stringMatch=trimmed.match(/^['"]([^'"]+)['"]$/);if(!stringMatch)return null;names.add(stringMatch[1])}return names}function getSymbolVisibilityInfo(ctx){if(hasPrivateContainer(ctx.defNode,ctx.grammarId))return{...PRIVATE_INFO};if(ctx.explicitExported||ctx.commonJsExport)return{exported:!0,visibility:"public",exportedReason:"explicit_export",apiSurfaceKind:"export"};let ownVisibility=visibilityFromText(ctx.grammarId,ctx.defNode.text);if(ctx.kind==="method"){if(ctx.grammarId==="go")return isUppercasePublic(ctx.localName)?{...PUBLIC_INFO,exportedReason:"naming_convention"}:{...PRIVATE_INFO};if(ctx.grammarId==="python"&&ctx.pythonParentClassExported){let isPrivate=ctx.localName.startsWith("_"),isInit=ctx.localName==="__init__";if(isPrivate||isInit)return{...PRIVATE_INFO};return{exported:!0,visibility:"public",exportedReason:"modifier",apiSurfaceKind:"public"}}if(ownVisibility==="unknown"&&CONTAINER_SCOPED_GRAMMARS.has(ctx.grammarId)){let implicit=containerScopedDefaultVisibility(ctx.grammarId,ctx.parentContainerType);return{exported:!1,visibility:implicit,exportedReason:"module_public",apiSurfaceKind:implicit==="private"?"private":"public"}}return{exported:!1,visibility:ownVisibility,exportedReason:ownVisibility==="unknown"?"unknown":"modifier",apiSurfaceKind:ownVisibility==="private"?"private":"public"}}if(!ctx.isTopLevel&&isMemberLikeNode(ctx.defNode))return{exported:!1,visibility:ownVisibility==="unknown"?"public":ownVisibility,exportedReason:ownVisibility==="unknown"?"module_public":"modifier",apiSurfaceKind:ownVisibility==="private"?"private":"public"};if(!ctx.isTopLevel&&CONTAINER_SCOPED_GRAMMARS.has(ctx.grammarId)&&TYPE_DECLARATION_NODE_TYPES.has(ctx.defNode.type)){let nestedVisibility=ownVisibility==="unknown"?containerScopedDefaultVisibility(ctx.grammarId,ctx.parentContainerType):ownVisibility;return{exported:!1,visibility:nestedVisibility,exportedReason:ownVisibility==="unknown"?"module_public":"modifier",apiSurfaceKind:nestedVisibility==="private"?"private":"public"}}if(!ctx.isTopLevel)return{...PRIVATE_INFO};switch(ctx.grammarId){case"typescript":case"javascript":case"tsx":return{...PRIVATE_INFO};case"python":return pythonVisibility(ctx);case"rust":return rustVisibility(ctx);case"go":return isUppercasePublic(ctx.localName)?{...PUBLIC_INFO,exportedReason:"naming_convention"}:{...PRIVATE_INFO};case"java":case"kotlin":case"csharp":case"swift":case"php":return modifierLanguageVisibility(ctx);case"cpp":return cppVisibility(ctx);case"dart":return ctx.localName.startsWith("_")?{...PRIVATE_INFO}:{...PUBLIC_INFO,exportedReason:"naming_convention"};case"ruby":return ctx.localName.startsWith("_")?{...PRIVATE_INFO}:{...PUBLIC_INFO,exportedReason:"module_public"};default:return{exported:!1,visibility:"unknown",exportedReason:"unknown",apiSurfaceKind:"unknown"}}}function pythonVisibility(ctx){if(ctx.pythonAllNames)return ctx.pythonAllNames.has(ctx.localName)?{exported:!0,visibility:"public",exportedReason:"module_public",apiSurfaceKind:"public"}:{...PRIVATE_INFO};return ctx.localName.startsWith("_")?{...PRIVATE_INFO}:{...PUBLIC_INFO,exportedReason:"naming_convention"}}function rustVisibility(ctx){let text=ctx.defNode.text.trimStart();if(!/^pub\b|^pub\s*\(/.test(text))return{...PRIVATE_INFO};return{exported:!0,visibility:/^pub\s*\(\s*(crate|super|in\b)/.test(text)?"internal":"public",exportedReason:"modifier",apiSurfaceKind:"public"}}function modifierLanguageVisibility(ctx){if(ctx.grammarId==="php"&&ctx.localName.startsWith("_"))return{...PRIVATE_INFO};let visibility=visibilityFromText(ctx.grammarId,ctx.defNode.text);if(visibility==="private")return{...PRIVATE_INFO};if(visibility==="unknown")return{exported:!0,visibility:ctx.grammarId==="java"?"package":defaultModuleVisibility(ctx.grammarId),exportedReason:"module_public",apiSurfaceKind:"public"};return{exported:!0,visibility,exportedReason:"modifier",apiSurfaceKind:"public"}}function cppVisibility(ctx){let text=ctx.defNode.text.trimStart();if(/^static\b/.test(text)||ctx.localName.startsWith("_"))return{...PRIVATE_INFO};return{exported:!0,visibility:"public",exportedReason:"namespace_public",apiSurfaceKind:"public"}}function visibilityFromText(grammarId,text){let normalized=declarationPrefix(grammarId,text).trimStart();if(/\b(private|fileprivate)\b/.test(normalized))return"private";if(/\bprotected\b/.test(normalized))return"protected";if(/\binternal\b/.test(normalized))return"internal";if(/\b(public|open)\b/.test(normalized))return"public";if(grammarId==="rust"&&/^pub\s*\(\s*(crate|super|in\b)/.test(normalized))return"internal";if(grammarId==="rust"&&/^pub\b|^pub\s*\(/.test(normalized))return"public";return"unknown"}function endOfStringLiteral(text,quote){let q=text[quote],verbatim=q==='"'&&text[quote-1]==="@",i=quote+1;while(i<text.length){if(verbatim){if(text[i]===q){if(text[i+1]===q){i+=2;continue}return i}i++;continue}if(text[i]==="\\"){i+=2;continue}if(text[i]===q)return i;i++}return text.length}function skipBalanced(text,open5,ignoreQuotes=!1){let openCh=text[open5],closeCh=openCh==="("?")":"]",depth=0;for(let i=open5;i<text.length;i++){let ch=text[i];if(!ignoreQuotes&&(ch==='"'||ch==="'")){i=endOfStringLiteral(text,i);continue}if(ch===openCh)depth++;else if(ch===closeCh){if(depth--,depth===0)return i+1}}return-1}function skipBalancedResilient(text,open5){let strict=skipBalanced(text,open5);if(strict!==-1)return strict;return skipBalanced(text,open5,!0)}function stripLeadingAnnotations(text){let i=0;for(;;){while(i<text.length&&/\s/.test(text[i]))i++;let ch=text[i];if(ch==="/"&&text[i+1]==="*"){let end=text.indexOf("*/",i+2);if(end===-1)return"";i=end+2;continue}if(ch==="/"&&text[i+1]==="/"){let end=text.indexOf(`
|
|
2870
|
+
`).trim();if(text)return text}return null}function extractTaskToolPrompt(messages){for(let i=messages.length-1;i>=0;i--){let msg=messages[i];if((msg.role??msg.info?.role)!=="assistant")continue;let content=Array.isArray(msg.content)?msg.content:Array.isArray(msg.parts)?msg.parts:[];for(let j=content.length-1;j>=0;j--){let block=content[j];if(block&&typeof block==="object"){let b=block;if(b.type==="tool_use"&&b.name==="Task"){let prompt=b.input?.prompt;if(typeof prompt==="string"&&prompt.length>0)return prompt}}}}return null}function recallMessageInsertIndex(messages){for(let i=messages.length-1;i>=0;i--)if(messages[i]?.info?.role==="user")return i;return messages.length}function extractTouchedFiles(text){let matches=text.match(/\b(?:src|tests|test|docs|scripts|packages)\/[A-Za-z0-9._/@+-]+/g);return Array.from(new Set(matches??[])).slice(0,20)}function compactText(text){let compacted=text.replace(/\s+/g," ").trim();if(compacted.length<=2000)return compacted;return Array.from(compacted).slice(0,2000).join("")}var MEMORY_SENTINEL,UNITID_PROBE_TASK_ID_PATTERN;var init_injector=__esm(()=>{init_agent_output_schema();init_schema();init_normalize_tool_name();init_utils2();init_config2();init_gateway();init_recall_planner();init_run_log();init_sentinel();MEMORY_SENTINEL=MEMORY_RECALL_SENTINEL;UNITID_PROBE_TASK_ID_PATTERN=/\bTASK:\s*(\d+(?:\.\d+)+)\b/});function containerScopedDefaultVisibility(grammarId,containerType){if(containerType==="interface_declaration")return"public";switch(grammarId){case"kotlin":return"public";case"java":return"package";case"swift":return"internal";case"cpp":return containerType==="struct_specifier"||containerType==="union_specifier"?"public":"private";default:return containerType===void 0?"internal":"private"}}function collectCommonJsExports(source){let sanitized=maskCommentsAndStrings(source),exportsByLocal=new Map,add2=(localName,exportedName,sourceIndex)=>{if(!isIdentifier(localName)||!isIdentifier(exportedName))return;let existing=exportsByLocal.get(localName);if(existing&&existing.sourceIndex<=sourceIndex)return;exportsByLocal.set(localName,{localName,exportedName,exportedReason:"explicit_export",sourceIndex})};for(let match of sanitized.matchAll(/\bmodule\s*\.\s*exports\s*=\s*([A-Za-z_$][\w$]*)\b/g))add2(match[1],match[1],match.index??0);for(let match of sanitized.matchAll(/\bmodule\s*\.\s*exports\s*=\s*\{([^}]*)\}/g)){let body=match[1],baseIndex=match.index??0;for(let part of body.split(",")){let entry=part.trim();if(!entry)continue;let alias=entry.match(/^([A-Za-z_$][\w$]*)\s*:\s*([A-Za-z_$][\w$]*)$/);if(alias){add2(alias[2],alias[1],baseIndex+match[0].indexOf(part));continue}let shorthand=entry.match(/^([A-Za-z_$][\w$]*)$/);if(shorthand)add2(shorthand[1],shorthand[1],baseIndex+match[0].indexOf(part))}}for(let match of sanitized.matchAll(/\b(?:module\s*\.\s*exports|exports)\s*\.\s*([A-Za-z_$][\w$]*)\s*=\s*([A-Za-z_$][\w$]*)\b/g))add2(match[2],match[1],match.index??0);return exportsByLocal}function collectPythonAllNames(source){let match=source.match(/__all__\s*=\s*([[({])([\s\S]*?)[\])}]/);if(!match)return null;let body=match[2].trim();if(!body)return new Set;let names=new Set;for(let part of body.split(",")){let trimmed=part.trim();if(!trimmed)continue;let stringMatch=trimmed.match(/^['"]([^'"]+)['"]$/);if(!stringMatch)return null;names.add(stringMatch[1])}return names}function getSymbolVisibilityInfo(ctx){if(hasPrivateContainer(ctx.defNode,ctx.grammarId))return{...PRIVATE_INFO};if(ctx.explicitExported||ctx.commonJsExport)return{exported:!0,visibility:"public",exportedReason:"explicit_export",apiSurfaceKind:"export"};let ownVisibility=visibilityFromText(ctx.grammarId,ctx.defNode.text);if(ctx.kind==="method"){if(ctx.grammarId==="go")return isUppercasePublic(ctx.localName)?{...PUBLIC_INFO,exportedReason:"naming_convention"}:{...PRIVATE_INFO};if(ctx.grammarId==="python"&&ctx.pythonParentClassExported){let isPrivate=ctx.localName.startsWith("_"),isInit=ctx.localName==="__init__";if(isPrivate||isInit)return{...PRIVATE_INFO};return{exported:!0,visibility:"public",exportedReason:"modifier",apiSurfaceKind:"public"}}if(ownVisibility==="unknown"&&CONTAINER_SCOPED_GRAMMARS.has(ctx.grammarId)){let implicit=containerScopedDefaultVisibility(ctx.grammarId,ctx.parentContainerType);return{exported:!1,visibility:implicit,exportedReason:"module_public",apiSurfaceKind:implicit==="private"?"private":"public"}}return{exported:!1,visibility:ownVisibility,exportedReason:ownVisibility==="unknown"?"unknown":"modifier",apiSurfaceKind:ownVisibility==="private"?"private":"public"}}if(!ctx.isTopLevel&&isMemberLikeNode(ctx.defNode))return{exported:!1,visibility:ownVisibility==="unknown"?"public":ownVisibility,exportedReason:ownVisibility==="unknown"?"module_public":"modifier",apiSurfaceKind:ownVisibility==="private"?"private":"public"};if(!ctx.isTopLevel&&CONTAINER_SCOPED_GRAMMARS.has(ctx.grammarId)&&TYPE_DECLARATION_NODE_TYPES.has(ctx.defNode.type)){let nestedVisibility=ownVisibility==="unknown"?containerScopedDefaultVisibility(ctx.grammarId,ctx.parentContainerType):ownVisibility;return{exported:!1,visibility:nestedVisibility,exportedReason:ownVisibility==="unknown"?"module_public":"modifier",apiSurfaceKind:nestedVisibility==="private"?"private":"public"}}if(!ctx.isTopLevel)return{...PRIVATE_INFO};switch(ctx.grammarId){case"typescript":case"javascript":case"tsx":return{...PRIVATE_INFO};case"python":return pythonVisibility(ctx);case"rust":return rustVisibility(ctx);case"go":return isUppercasePublic(ctx.localName)?{...PUBLIC_INFO,exportedReason:"naming_convention"}:{...PRIVATE_INFO};case"java":case"kotlin":case"csharp":case"swift":case"php":return modifierLanguageVisibility(ctx);case"cpp":return cppVisibility(ctx);case"dart":return ctx.localName.startsWith("_")?{...PRIVATE_INFO}:{...PUBLIC_INFO,exportedReason:"naming_convention"};case"ruby":return ctx.localName.startsWith("_")?{...PRIVATE_INFO}:{...PUBLIC_INFO,exportedReason:"module_public"};default:return{exported:!1,visibility:"unknown",exportedReason:"unknown",apiSurfaceKind:"unknown"}}}function pythonVisibility(ctx){if(ctx.pythonAllNames)return ctx.pythonAllNames.has(ctx.localName)?{exported:!0,visibility:"public",exportedReason:"module_public",apiSurfaceKind:"public"}:{...PRIVATE_INFO};return ctx.localName.startsWith("_")?{...PRIVATE_INFO}:{...PUBLIC_INFO,exportedReason:"naming_convention"}}function rustVisibility(ctx){let text=ctx.defNode.text.trimStart();if(!/^pub\b|^pub\s*\(/.test(text))return{...PRIVATE_INFO};return{exported:!0,visibility:/^pub\s*\(\s*(crate|super|in\b)/.test(text)?"internal":"public",exportedReason:"modifier",apiSurfaceKind:"public"}}function modifierLanguageVisibility(ctx){if(ctx.grammarId==="php"&&ctx.localName.startsWith("_"))return{...PRIVATE_INFO};let visibility=visibilityFromText(ctx.grammarId,ctx.defNode.text);if(visibility==="private")return{...PRIVATE_INFO};if(visibility==="unknown")return{exported:!0,visibility:ctx.grammarId==="java"?"package":defaultModuleVisibility(ctx.grammarId),exportedReason:"module_public",apiSurfaceKind:"public"};return{exported:!0,visibility,exportedReason:"modifier",apiSurfaceKind:"public"}}function cppVisibility(ctx){if(isInsideAnonymousNamespace(ctx.defNode))return{...PRIVATE_INFO};let text=ctx.defNode.text.trimStart();if(/^static\b/.test(text)||ctx.localName.startsWith("_"))return{...PRIVATE_INFO};return{exported:!0,visibility:"public",exportedReason:"namespace_public",apiSurfaceKind:"public"}}function isInsideAnonymousNamespace(node){let current=node.parent;while(current){if(current.type==="namespace_definition"){if(!current.children.some((child)=>child!==null&&child.type==="namespace_identifier"))return!0}current=current.parent}return!1}function visibilityFromText(grammarId,text){let normalized=declarationPrefix(grammarId,text).trimStart();if(/\b(private|fileprivate)\b/.test(normalized))return"private";if(/\bprotected\b/.test(normalized))return"protected";if(/\binternal\b/.test(normalized))return"internal";if(/\b(public|open)\b/.test(normalized))return"public";if(grammarId==="rust"&&/^pub\s*\(\s*(crate|super|in\b)/.test(normalized))return"internal";if(grammarId==="rust"&&/^pub\b|^pub\s*\(/.test(normalized))return"public";return"unknown"}function endOfStringLiteral(text,quote){let q=text[quote],verbatim=q==='"'&&text[quote-1]==="@",i=quote+1;while(i<text.length){if(verbatim){if(text[i]===q){if(text[i+1]===q){i+=2;continue}return i}i++;continue}if(text[i]==="\\"){i+=2;continue}if(text[i]===q)return i;i++}return text.length}function skipBalanced(text,open5,ignoreQuotes=!1){let openCh=text[open5],closeCh=openCh==="("?")":"]",depth=0;for(let i=open5;i<text.length;i++){let ch=text[i];if(!ignoreQuotes&&(ch==='"'||ch==="'")){i=endOfStringLiteral(text,i);continue}if(ch===openCh)depth++;else if(ch===closeCh){if(depth--,depth===0)return i+1}}return-1}function skipBalancedResilient(text,open5){let strict=skipBalanced(text,open5);if(strict!==-1)return strict;return skipBalanced(text,open5,!0)}function stripLeadingAnnotations(text){let i=0;for(;;){while(i<text.length&&/\s/.test(text[i]))i++;let ch=text[i];if(ch==="/"&&text[i+1]==="*"){let end=text.indexOf("*/",i+2);if(end===-1)return"";i=end+2;continue}if(ch==="/"&&text[i+1]==="/"){let end=text.indexOf(`
|
|
2871
2871
|
`,i+2);if(end===-1)return"";i=end+1;continue}if(ch==="@"){let j=i+1;while(j<text.length&&/[\w.:]/.test(text[j]))j++;let k=j;while(k<text.length&&/\s/.test(text[k]))k++;if(text[k]==="("){let end=skipBalancedResilient(text,k);if(end===-1)return text.slice(i);i=end}else if(j===i+1)i=j;else i=j;continue}if(ch==="["){let end=skipBalancedResilient(text,i);if(end===-1)return text.slice(i);i=end;continue}return text.slice(i)}}function maskStringLiterals(text){let out="";for(let i=0;i<text.length;i++){let ch=text[i];if(ch!=='"'&&ch!=="'"){out+=ch;continue}let end=endOfStringLiteral(text,i);if(out+=ch,out+=" ".repeat(Math.max(0,Math.min(end,text.length)-i-1)),end<text.length)out+=text[end];i=end}return out}function declarationPrefix(grammarId,text){if(!ANNOTATED_DECLARATION_GRAMMARS.has(grammarId)){let bodyStart2=text.search(/[{\n]/);return bodyStart2===-1?text:text.slice(0,bodyStart2)}let stripped=stripLeadingAnnotations(text),window2=stripped.length>HEADER_SCAN_LIMIT?stripped.slice(0,HEADER_SCAN_LIMIT):stripped,scanned=maskStringLiterals(window2),bodyStart=scanned.search(/[{\n]/);return bodyStart===-1?scanned:scanned.slice(0,bodyStart)}function defaultModuleVisibility(grammarId){switch(grammarId){case"swift":case"csharp":return"internal";case"kotlin":return"public";case"php":return"public";default:return"public"}}function hasPrivateContainer(node,grammarId){let current=node.parent;while(current){if(isContainerNode(current)&&visibilityFromText(grammarId,current.text)==="private")return!0;current=current.parent}return!1}function isContainerNode(node){return/(?:class|struct|interface|object|protocol|namespace|module)/.test(node.type)||/^(?:enum|record)_declaration$/.test(node.type)}function isMemberLikeNode(node){return/(?:method|function)_declaration|function_definition/.test(node.type)}function isUppercasePublic(name){return/^[A-Z]/.test(name)}function isIdentifier(value){return/^[A-Za-z_$][\w$]*$/.test(value)}function maskCommentsAndStrings(source){let chars=[...source],i=0;while(i<chars.length){let ch=chars[i],next=chars[i+1];if(ch==="/"&&next==="/"){chars[i++]=" ",chars[i++]=" ";while(i<chars.length&&chars[i]!==`
|
|
2872
|
-
`)chars[i++]=" ";continue}if(ch==="/"&&next==="*"){chars[i++]=" ",chars[i++]=" ";while(i<chars.length){let end=chars[i]==="*"&&chars[i+1]==="/";if(chars[i++]=" ",end){chars[i++]=" ";break}}continue}if(ch==='"'||ch==="'"||ch==="`"){let quote=ch;chars[i++]=" ";while(i<chars.length){if(chars[i]==="\\"){if(chars[i++]=" ",i<chars.length)chars[i++]=" ";continue}let done=chars[i]===quote;if(chars[i++]=" ",done)break}continue}i++}return chars.join("")}var PUBLIC_INFO,PRIVATE_INFO,CONTAINER_SCOPED_GRAMMARS,TYPE_DECLARATION_NODE_TYPES,ANNOTATED_DECLARATION_GRAMMARS,HEADER_SCAN_LIMIT=4096;var init_symbol_visibility=__esm(()=>{PUBLIC_INFO={exported:!0,visibility:"public",exportedReason:"top_level_public",apiSurfaceKind:"public"},PRIVATE_INFO={exported:!1,visibility:"private",exportedReason:"unknown",apiSurfaceKind:"private"},CONTAINER_SCOPED_GRAMMARS=new Set(["java","kotlin","csharp"]),TYPE_DECLARATION_NODE_TYPES=new Set(["class_declaration","interface_declaration","enum_declaration","record_declaration","struct_declaration","object_declaration"]);ANNOTATED_DECLARATION_GRAMMARS=new Set(["java","kotlin","csharp"])});async function extractFileSymbols(grammarId,source){let treeRef={value:null},timeoutId;try{return await Promise.race([(async()=>{try{if(!_QueryCtor)_QueryCtor=(await import("web-tree-sitter")).Query;let{loadGrammar:loadGrammarDynamic}=await Promise.resolve().then(() => (init_runtime(),exports_runtime)),parser=await loadGrammarDynamic(grammarId);if(treeRef.value=parser.parse(source),!treeRef.value)return null;let qs=QUERIES2[grammarId];if(!qs)return null;return buildFacts(treeRef.value,qs,grammarId)}finally{if(treeRef.value)treeRef.value.delete(),treeRef.value=null}})(),new Promise((_,reject)=>{timeoutId=setTimeout(()=>reject(Error("AST_TIMEOUT")),AST_TIMEOUT_MS3)})]).finally(()=>{if(timeoutId)clearTimeout(timeoutId)})}catch{return null}}function asTs(node){return node}function buildFacts(tree,qs,grammarId){let root=asTs(tree.rootNode),lang=tree.language;if(!lang)return{defs:[],imports:[],refs:[]};let defMatches=safeMatches(lang,qs.defs,root),importMatches=safeMatches(lang,qs.imports,root),refMatches=safeMatches(lang,qs.refs,root),exportMatches=safeMatches(lang,qs.exports,root),exportNodes=[];for(let m of exportMatches){let cap=m.captures.find((c)=>c.name==="export");if(cap)exportNodes.push(asTs(cap.node))}let commonJsExports=isEsMGrammar(grammarId)?collectCommonJsExports(root.text):new Map,pythonAllNames=grammarId==="python"?collectPythonAllNames(root.text):null,defs=[],defNodes=[],defNameKeys=new Set;for(let m of defMatches){let defCap=m.captures.find((c)=>c.name.endsWith(".def")),nameCaps=m.captures.filter((c)=>c.name.endsWith(".name"));if(!defCap||nameCaps.length===0)continue;let kindKey=defCap.name.replace(/\.def$/,""),originalDefNode=asTs(defCap.node),defNode=originalDefNode,kind=Object.hasOwn(CAPTURE_KIND,kindKey)?CAPTURE_KIND[kindKey]:"function";if(grammarId==="python"&&kindKey==="func"&&hasAncestorOfType(originalDefNode,"class_definition"))kind="method";if(grammarId==="rust"&&kindKey==="func"&&hasAncestorOfType(originalDefNode,"impl_item"))kind="method";let parentContainerType;if(JVM_GRAMMARS.has(grammarId)){if(parentContainerType=nearestAncestorType(originalDefNode,JVM_CONTAINER_TYPES),parentContainerType!==void 0&&(kindKey==="func"||kindKey==="ctor"))kind="method"}let explicitExported=exportNodes.some((en)=>isNodeInside(en,defNode)),isDefaultExport=!1;if(explicitExported&&isEsMGrammar(grammarId))isDefaultExport=exportNodes.some((en)=>isDefaultExportStatement(en)&&isOwnExportDeclaration(en,defNode));if(grammarId==="dart"&&defNode.type==="function_signature"){let rawBody=defNode.nextSibling;if(rawBody){let bodyNode=asTs(rawBody);if(bodyNode.type==="function_body")defNode=asTs({...defNode,endIndex:bodyNode.endIndex,endPosition:bodyNode.endPosition})}}if(grammarId==="python"&&defNode.parent?.type==="decorated_definition")defNode=asTs(defNode.parent);let pythonParentClassExported=!1;if(grammarId==="python"&&kind==="method"){let current=originalDefNode.parent;while(current){if(current.type==="class_definition"){let classNameNode=current.children?.find((c)=>c!=null&&c.type==="identifier");if(classNameNode){let className=classNameNode.text;pythonParentClassExported=pythonAllNames?pythonAllNames.has(className):!className.startsWith("_")}break}current=current.parent}}for(let nc of nameCaps){let nameNode=asTs(nc.node),localName=nameNode.text,commonJsExport=commonJsExports.get(localName),visibilityInfo=getSymbolVisibilityInfo({grammarId,localName,kind,defNode:originalDefNode,rootNode:root,isTopLevel:isTopLevelDef(originalDefNode,root),explicitExported,commonJsExport,pythonAllNames,pythonParentClassExported,parentContainerType}),exportedName=isDefaultExport?"default":commonJsExport?.exportedName??localName;defs.push({name:exportedName,kind,exported:visibilityInfo.exported,visibilityInfo,startLine:defNode.startPosition.row+1,endLine:defNode.endPosition.row+1}),defNodes.push({node:defNode,name:localName}),defNameKeys.add(nodeKey(nameNode))}}let importsWithIndex=[],addImport=(entry,node)=>{if(!entry)return;for(let item of Array.isArray(entry)?entry:[entry]){let pythonExportedBindings=grammarId==="python"&&pythonAllNames&&item.bindings.length>0?item.bindings.filter((binding)=>pythonAllNames.has(binding.local)).map((binding)=>({imported:binding.imported,exported:binding.local})):[],normalizedItem=pythonExportedBindings.length>0?{...item,reExport:!0,exportedBindings:pythonExportedBindings}:item;importsWithIndex.push({index:node.startIndex,entry:normalizedItem.reExport?{...normalizedItem,startLine:node.startPosition.row+1,endLine:node.endPosition.row+1}:normalizedItem})}};for(let m of importMatches){let importCap=m.captures.find((c)=>c.name==="import");if(importCap){let importNode=asTs(importCap.node),rawText=importNode.text.trim();if(grammarId==="go"&&rawText.startsWith("import (")){let seenGoSpecifiers=new Set,specListNode=importNode.children.find((c)=>c!==null&&c.type==="import_spec_list");if(specListNode){for(let spec of asTs(specListNode).children)if(spec&&spec.type==="import_spec"){let parsed=parseGoImportHardened(spec.text.trim());if(parsed)seenGoSpecifiers.add(parsed.specifier);addImport(parsed,asTs(spec))}}for(let parsed of parseGoBlockImports(rawText)){if(seenGoSpecifiers.has(parsed.specifier))continue;addImport(parsed,importNode)}}else{let parsed=parseImport(grammarId,rawText);addImport(parsed,importNode)}}if(grammarId==="ruby"){let reqName=m.captures.find((c)=>c.name==="require.name"),reqSpec=m.captures.find((c)=>c.name==="require.specifier");if(reqName&&reqSpec){let fnText=asTs(reqName.node).text;if(fnText==="require"||fnText==="require_relative"){let callNode=asTs(reqName.node).parent,rawText=callNode?callNode.text:asTs(reqSpec.node).text,parsed=parseRubyRequire(rawText);addImport(parsed,asTs(callNode??reqSpec.node))}}}if(isEsMGrammar(grammarId)){let reqName=m.captures.find((c)=>c.name==="require.name"),reqSpec=m.captures.find((c)=>c.name==="require.specifier");if(reqName&&reqSpec){if(asTs(reqName.node).text==="require"){let specText=asTs(reqSpec.node).text.replace(/['"]/g,"");addImport({specifier:specText,importType:"commonjs",bindings:[]},asTs(reqName.node))}}}}if(isEsMGrammar(grammarId))for(let exportNode of exportNodes)addImport(parseImport(grammarId,exportNode.text.trim()),exportNode);let imports=importsWithIndex.sort((a,b)=>a.index-b.index).map((item)=>item.entry),topLevelDefs=defNodes.filter((d)=>isTopLevelDef(d.node,root)).map((d)=>({name:d.name,node:d.node})),refs=[];for(let m of refMatches){let cap=m.captures.find((c)=>c.name==="ref.identifier");if(!cap)continue;let refNode=asTs(cap.node);if(defNameKeys.has(nodeKey(refNode)))continue;if(hasAncestorOfType(refNode,"import_statement"))continue;if(isInsideImportStatement(refNode))continue;if(hasAncestorOfType(refNode,PARAM_TYPES))continue;if(refNode.text==="require"&&isInsideRequireCall(refNode))continue;refs.push({identifier:refNode.text,line:refNode.startPosition.row+1,enclosingDecl:findEnclosingDecl(refNode,topLevelDefs)})}if(isEsMGrammar(grammarId))for(let en of exportNodes){if(!isDefaultExportStatement(en))continue;let owner=en.childForFieldName?.("declaration")??en.childForFieldName?.("value");if(!owner)continue;if(defs.some((d)=>d.startLine===owner.startPosition.row+1&&d.name==="default"))continue;let kind=owner.type.includes("class")?"class":"function";defs.push({name:"default",kind,exported:!0,startLine:owner.startPosition.row+1,endLine:owner.endPosition.row+1})}return{defs,imports,refs}}function safeMatches(lang,pattern,root){if(!_QueryCtor)return[];try{return new _QueryCtor(lang,pattern).matches(root)}catch{return[]}}function parseEsmImport(text){let t=text.trim(),sideEffect=t.match(/^import\s+['"]([^'"]+)['"]/);if(sideEffect)return{specifier:sideEffect[1],importType:"sideeffect",bindings:[]};let reExportAllAs=t.match(/^export\s+\*\s+as\s+([A-Za-z_$][\w$]*)\s+from\s+['"]([^'"]+)['"]/);if(reExportAllAs)return{specifier:reExportAllAs[2],importType:"namespace",bindings:[{imported:"*",local:reExportAllAs[1]}],reExport:!0,exportedBindings:[{imported:"*",exported:reExportAllAs[1]}]};let reExportAll=t.match(/^export\s+\*\s+from\s+['"]([^'"]+)['"]/);if(reExportAll)return{specifier:reExportAll[1],importType:"namespace",bindings:[],reExport:!0};let namedTypeReExport=t.match(/^export\s+type\s+\{([^}]+)\}\s+from\s+['"]([^'"]+)['"]/);if(namedTypeReExport)return{specifier:namedTypeReExport[2],importType:"type",bindings:[],reExport:!0};let namedReExport=t.match(/^export\s+\{([^}]+)\}\s+from\s+['"]([^'"]+)['"]/);if(namedReExport){let bindings=[],exportedBindings=[];for(let rawPart of namedReExport[1].split(",")){let p=rawPart.trim();if(!p)continue;if(/^type\s+/.test(p))continue;let alias=p.match(/^([A-Za-z_$][\w$]*)\s+as\s+([A-Za-z_$][\w$]*)$/),imported=alias?alias[1]:p,exported=alias?alias[2]:p;if(!/^[A-Za-z_$][\w$]*$/.test(imported))continue;if(!/^[A-Za-z_$][\w$]*$/.test(exported))continue;bindings.push({imported,local:exported}),exportedBindings.push({imported,exported})}return{specifier:namedReExport[2],importType:"named",bindings,reExport:!0,exportedBindings}}let isTypeOnlyImport=/^import\s+type\s/.test(t),withoutTypeQualifier=t.replace(/^import\s+type\s+/,"import "),named=withoutTypeQualifier.match(/^import\s+\{([^}]+)\}\s+from\s+['"]([^'"]+)['"]/);if(named){if(isTypeOnlyImport)return{specifier:named[2],importType:"named",bindings:[]};let bindings=[];for(let part of named[1].split(",")){let p=part.trim();if(!p)continue;if(/^type\s+/.test(p))continue;let stripped=p.replace(/^type\s+/,"");if(!stripped)continue;let alias=stripped.match(/^([A-Za-z_$][\w$]*)\s+as\s+([A-Za-z_$][\w$]*)$/);if(alias)bindings.push({imported:alias[1],local:alias[2]});else if(/^[A-Za-z_$][\w$]*$/.test(stripped))bindings.push({imported:stripped,local:stripped})}return{specifier:named[2],importType:"named",bindings}}let combined=withoutTypeQualifier.match(/^import\s+([A-Za-z_$][\w$]*)\s*,\s*\*\s+as\s+([A-Za-z_$][\w$]*)\s+from\s+['"]([^'"]+)['"]/);if(combined){if(isTypeOnlyImport)return{specifier:combined[3],importType:"named",bindings:[]};return{specifier:combined[3],importType:"named",bindings:[{imported:"default",local:combined[1]},{imported:"*",local:combined[2]}]}}let combinedNamed=withoutTypeQualifier.match(/^import\s+([A-Za-z_$][\w$]*)\s*,\s*\{([^}]+)\}\s+from\s+['"]([^'"]+)['"]/);if(combinedNamed){if(isTypeOnlyImport)return{specifier:combinedNamed[3],importType:"named",bindings:[]};let bindings=[{imported:"default",local:combinedNamed[1]}];for(let part of combinedNamed[2].split(",")){let p=part.trim();if(!p)continue;if(/^type\s+/.test(p))continue;let stripped=p.replace(/^type\s+/,"");if(!stripped)continue;let alias=stripped.match(/^([A-Za-z_$][\w$]*)\s+as\s+([A-Za-z_$][\w$]*)$/);if(alias)bindings.push({imported:alias[1],local:alias[2]});else if(/^[A-Za-z_$][\w$]*$/.test(stripped))bindings.push({imported:stripped,local:stripped})}return{specifier:combinedNamed[3],importType:"named",bindings}}let ns=t.match(/^import\s+\*\s+as\s+([A-Za-z_$][\w$]*)\s+from\s+['"]([^'"]+)['"]/);if(ns)return{specifier:ns[2],importType:"namespace",bindings:[{imported:"*",local:ns[1]}]};let def=t.match(/^import\s+([A-Za-z_$][\w$]*)\s+from\s+['"]([^'"]+)['"]/);if(def)return{specifier:def[2],importType:"default",bindings:[{imported:"default",local:def[1]}]};return null}function parseImport(grammarId,text){switch(grammarId){case"python":return parsePythonImportHardened(text);case"rust":return parseRustUseHardened(text);case"go":return parseGoImportHardened(text);case"java":return parseJavaImport(text);case"kotlin":return parseKotlinImport(text);case"csharp":return parseCSharpUsing(text);case"cpp":return parseCppInclude(text);case"swift":return parseSwiftImport(text);case"dart":return parseDartImport(text);case"ruby":return parseRubyRequire(text);case"php":return parsePhpUse(text);case"typescript":case"tsx":case"javascript":return parseEsmImport(text);default:return null}}function parsePythonImportHardened(text){let t=text.trim(),fullImport=t.match(/^import\s+(.+)$/);if(fullImport){let entries=[];for(let rawPart of fullImport[1].split(",")){let part=rawPart.trim();if(!part)continue;let alias=part.match(/^([\w.]+)\s+as\s+(\w+)$/),specifier=alias?alias[1]:part,local=alias?alias[2]:specifier.split(".")[0];if(!specifier||!/^\w+$/.test(local))continue;entries.push({specifier,importType:alias?"named":"namespace",bindings:[{imported:specifier,local}]})}if(entries.length===0)return null;return entries.length===1?entries[0]:entries}let fromImport=t.match(/^from\s+(\S+)\s+import\s+(.+)$/);if(!fromImport)return null;let bindings=[];for(let rawPart of fromImport[2].split(",")){let part=rawPart.trim();if(!part)continue;if(part==="*")return{specifier:normalizePythonModuleSpecifier(fromImport[1]),importType:"namespace",bindings:[]};let alias=part.match(/^(\w+)\s+as\s+(\w+)$/);if(alias)bindings.push({imported:alias[1],local:alias[2]});else if(/^\w+$/.test(part))bindings.push({imported:part,local:part})}return{specifier:normalizePythonModuleSpecifier(fromImport[1]),importType:"named",bindings}}function normalizePythonModuleSpecifier(specifier){let leadingDots=specifier.match(/^\.+/)?.[0].length??0;if(leadingDots===0)return specifier;let rest=specifier.slice(leadingDots).replace(/\./g,"/");return`${leadingDots===1?"./":"../".repeat(leadingDots-1)}${rest}`}function parseRustUseHardened(text){let t=text.trim(),aliased=t.match(/^use\s+(.+?)\s+as\s+(\w+)\s*;?\s*$/);if(aliased){let parts2=aliased[1].trim().split("::").filter(Boolean),imported2=parts2.pop()??aliased[1].trim();return{specifier:parts2.length>0?parts2.join("::"):aliased[1].trim(),importType:"named",bindings:[{imported:imported2,local:aliased[2]}]}}let grouped=t.match(/^use\s+(.+?)::\{(.+)\}\s*;?\s*$/);if(grouped){let base=grouped[1].trim(),bindings=[];for(let rawPart of grouped[2].split(",")){let part=rawPart.trim();if(!part)continue;let alias=part.match(/^(\w+)\s+as\s+(\w+)$/);if(alias)bindings.push({imported:alias[1],local:alias[2]});else if(/^\w+$/.test(part)){let local2=part==="self"?base.split("::").pop()||base:part;bindings.push({imported:part,local:local2})}}return{specifier:base,importType:"named",bindings}}let simple=t.match(/^use\s+(.+?)\s*;?\s*$/);if(!simple)return null;let parts=simple[1].trim().split("::").filter(Boolean),imported=parts.pop()??simple[1].trim(),specifier=parts.length>0?parts.join("::"):simple[1].trim(),local=imported;return{specifier,importType:"named",bindings:/^\w+$/.test(imported)?[{imported,local}]:[]}}function parseGoBlockImports(text){let entries=[],body=text.match(/^import\s*\(([\s\S]*?)\)\s*$/)?.[1];if(!body)return entries;for(let line of body.split(/\r?\n/)){let trimmed=line.trim();if(!trimmed||trimmed.startsWith("//"))continue;let parsed=parseGoImportHardened(trimmed);if(parsed)entries.push(parsed)}return entries}function parseGoImportHardened(text){let t=text.trim();if(t.startsWith("import ("))return null;let aliased=t.match(/^(?!import\b)([\w._]+)\s+["`]([^"`]+)["`]$/)??t.match(/^import\s+([\w._]+)\s+["`]([^"`]+)["`]/);if(aliased){if(aliased[1]==="_")return{specifier:aliased[2],importType:"sideeffect",bindings:[]};if(aliased[1]===".")return{specifier:aliased[2],importType:"namespace",bindings:[{imported:"*",local:"."}]};return{specifier:aliased[2],importType:"named",bindings:[{imported:aliased[2],local:aliased[1]}]}}let simple=t.match(/^import\s+["`]([^"`]+)["`]|^["`]([^"`]+)["`]$/);if(!simple)return null;return{specifier:simple[1]??simple[2],importType:"namespace",bindings:[]}}function finalDottedSegment(path157){let withoutGenerics=path157.replace(/<.*>$/s,""),lastDot=withoutGenerics.lastIndexOf(".");return lastDot===-1?withoutGenerics:withoutGenerics.slice(lastDot+1)}function parseJavaImport(text){let m=text.trim().match(/^import\s+(static\s+)?([^;\s]+)\s*;?\s*$/);if(!m)return null;let isStatic=Boolean(m[1]),path157=m[2],last=finalDottedSegment(path157);if(last==="*")return{specifier:path157,importType:"namespace",bindings:[]};let lastDot=path157.lastIndexOf(".");return{specifier:isStatic&&lastDot!==-1?path157.slice(0,lastDot):path157,importType:"named",bindings:[{imported:last,local:last}]}}function parseKotlinImport(text){let t=text.trim(),aliased=t.match(/^import\s+([^;\s]+)\s+as\s+(\w+)/);if(aliased)return{specifier:aliased[1],importType:"named",bindings:[{imported:finalDottedSegment(aliased[1]),local:aliased[2]}]};let simple=t.match(/^import\s+([^;\s]+)/);if(!simple)return null;let path157=simple[1],last=finalDottedSegment(path157);if(last==="*")return{specifier:path157,importType:"namespace",bindings:[]};return{specifier:path157,importType:"named",bindings:[{imported:last,local:last}]}}function parseCSharpUsing(text){let m=text.trim().match(/^(?:global\s+)?using\s+(?:static\s+)?([^=;\s]+)\s*(?:=\s*(.+?))?\s*;?\s*$/);if(!m)return null;if(m[2]){let target=m[2].trim();return{specifier:target,importType:"named",bindings:[{imported:finalDottedSegment(target),local:m[1].trim()}]}}return{specifier:m[1].trim(),importType:"namespace",bindings:[]}}function parseCppInclude(text){let t=text.trim(),include=t.match(/^#\s*include\s+[<"]([^>"]+)[>"]/);if(include)return{specifier:include[1],importType:"namespace",bindings:[]};let using=t.match(/^using\s+(?:namespace\s+)?(.+?)\s*;?\s*$/);if(using)return{specifier:using[1].trim(),importType:"namespace",bindings:[]};return null}function parseSwiftImport(text){let m=text.trim().match(/^import\s+(?:class\s+)?([^;\s]+)/);if(m)return{specifier:m[1],importType:"namespace",bindings:[]};return null}function parseDartImport(text){let t=text.trim(),m=t.match(/^import\s+['"]([^'"]+)['"]\s+as\s+(\w+)/);if(m)return{specifier:m[1],importType:"named",bindings:[{imported:m[1],local:m[2]}]};let simple=t.match(/^import\s+['"]([^'"]+)['"]/);if(simple)return{specifier:simple[1],importType:"namespace",bindings:[]};return null}function parseRubyRequire(text){let t=text.trim(),stripped=t.replace(/^(?:require(?:_relative)?)\s+['"]?/,"").replace(/['"]$/,"");if(!stripped||stripped===t)return null;let isRelative=stripped.startsWith("./")||stripped.startsWith("../");return{specifier:stripped,importType:isRelative?"default":"namespace",bindings:[]}}function parsePhpUse(text){let t=text.trim(),m=t.match(/^use\s+(?:(?:function|const)\s+)?([^;\s]+)\s+as\s+(\w+)\s*;?\s*$/i);if(m)return{specifier:m[1],importType:"named",bindings:[{imported:m[1],local:m[2]}]};let simple=t.match(/^use\s+(?:(?:function|const)\s+)?([^;\s]+)\s*;?\s*$/i);if(simple)return{specifier:simple[1],importType:"namespace",bindings:[]};return null}function isTopLevelDef(defNode,root){let parent=defNode.parent;while(parent&&parent!==root){if(DEF_TYPES.has(parent.type))return!1;parent=parent.parent}return!0}function findEnclosingDecl(refNode,topLevelDefs){let best=null,bestDist=1/0;for(let def of topLevelDefs)if(isNodeInside(def.node,refNode)){let dist=refNode.startPosition.row-def.node.startPosition.row;if(dist<bestDist)bestDist=dist,best=def}return best?.name??"<module>"}function isNodeInside(outer,inner){return inner.startIndex>=outer.startIndex&&inner.endIndex<=outer.endIndex}function nearestAncestorType(node,types2){let current=node.parent;while(current){if(types2.has(current.type))return current.type;current=current.parent}return}function hasAncestorOfType(node,types2){let typeSet=typeof types2==="string"?new Set([types2]):types2,current=node.parent;while(current){if(typeSet.has(current.type))return!0;current=current.parent}return!1}function isInsideRequireCall(node){let current=node.parent;while(current){if(current.type==="call_expression"){let fn2=current.children.find((c)=>c&&c.type==="identifier");if(fn2&&fn2.text==="require")return!0}if(DEF_TYPES.has(current.type))return!1;current=current.parent}return!1}function isInsideImportStatement(node){return hasAncestorOfType(node,IMPORT_ANCESTOR_TYPES)}function nodeKey(node){return`${node.startPosition.row},${node.startPosition.column}-${node.endPosition.row},${node.endPosition.column}`}function isOwnExportDeclaration(en,defNode){let owner=en.childForFieldName?.("declaration")??en.childForFieldName?.("value");if(owner)return owner.startIndex===defNode.startIndex&&owner.endIndex===defNode.endIndex;return isNodeInside(en,defNode)}function isDefaultExportStatement(en){if(en.children.some((c)=>c!==null&&c.type==="default"))return!0;return/^export\s+default\b/.test(en.text)}function isEsMGrammar(grammarId){return grammarId==="typescript"||grammarId==="tsx"||grammarId==="javascript"}var _QueryCtor=null,AST_TIMEOUT_MS3=500,QUERIES2,CAPTURE_KIND,DEF_TYPES,JVM_GRAMMARS,JVM_CONTAINER_TYPES,PARAM_TYPES,IMPORT_ANCESTOR_TYPES;var init_symbol_graph=__esm(()=>{init_symbol_visibility();QUERIES2={typescript:{defs:`
|
|
2872
|
+
`)chars[i++]=" ";continue}if(ch==="/"&&next==="*"){chars[i++]=" ",chars[i++]=" ";while(i<chars.length){let end=chars[i]==="*"&&chars[i+1]==="/";if(chars[i++]=" ",end){chars[i++]=" ";break}}continue}if(ch==='"'||ch==="'"||ch==="`"){let quote=ch;chars[i++]=" ";while(i<chars.length){if(chars[i]==="\\"){if(chars[i++]=" ",i<chars.length)chars[i++]=" ";continue}let done=chars[i]===quote;if(chars[i++]=" ",done)break}continue}i++}return chars.join("")}var PUBLIC_INFO,PRIVATE_INFO,CONTAINER_SCOPED_GRAMMARS,TYPE_DECLARATION_NODE_TYPES,ANNOTATED_DECLARATION_GRAMMARS,HEADER_SCAN_LIMIT=4096;var init_symbol_visibility=__esm(()=>{PUBLIC_INFO={exported:!0,visibility:"public",exportedReason:"top_level_public",apiSurfaceKind:"public"},PRIVATE_INFO={exported:!1,visibility:"private",exportedReason:"unknown",apiSurfaceKind:"private"},CONTAINER_SCOPED_GRAMMARS=new Set(["java","kotlin","csharp","swift","cpp"]),TYPE_DECLARATION_NODE_TYPES=new Set(["class_declaration","interface_declaration","enum_declaration","record_declaration","struct_declaration","object_declaration"]);ANNOTATED_DECLARATION_GRAMMARS=new Set(["java","kotlin","csharp","swift"])});async function extractFileSymbols(grammarId,source){let treeRef={value:null},timeoutId;try{return await Promise.race([(async()=>{try{if(!_QueryCtor)_QueryCtor=(await import("web-tree-sitter")).Query;let{loadGrammar:loadGrammarDynamic}=await Promise.resolve().then(() => (init_runtime(),exports_runtime)),parser=await loadGrammarDynamic(grammarId);if(treeRef.value=parser.parse(source),!treeRef.value)return null;let qs=QUERIES2[grammarId];if(!qs)return null;return buildFacts(treeRef.value,qs,grammarId)}finally{if(treeRef.value)treeRef.value.delete(),treeRef.value=null}})(),new Promise((_,reject)=>{timeoutId=setTimeout(()=>reject(Error("AST_TIMEOUT")),AST_TIMEOUT_MS3)})]).finally(()=>{if(timeoutId)clearTimeout(timeoutId)})}catch{return null}}function asTs(node){return node}function buildFacts(tree,qs,grammarId){let root=asTs(tree.rootNode),lang=tree.language;if(!lang)return{defs:[],imports:[],refs:[]};let defMatches=safeMatches(lang,qs.defs,root),importMatches=safeMatches(lang,qs.imports,root),refMatches=safeMatches(lang,qs.refs,root),exportMatches=safeMatches(lang,qs.exports,root),exportNodes=[];for(let m of exportMatches){let cap=m.captures.find((c)=>c.name==="export");if(cap)exportNodes.push(asTs(cap.node))}let commonJsExports=isEsMGrammar(grammarId)?collectCommonJsExports(root.text):new Map,pythonAllNames=grammarId==="python"?collectPythonAllNames(root.text):null,defs=[],defNodes=[],defNameKeys=new Set;for(let m of defMatches){let defCap=m.captures.find((c)=>c.name.endsWith(".def")),nameCaps=m.captures.filter((c)=>c.name.endsWith(".name"));if(!defCap||nameCaps.length===0)continue;let kindKey=defCap.name.replace(/\.def$/,""),originalDefNode=asTs(defCap.node),defNode=originalDefNode,kind=Object.hasOwn(CAPTURE_KIND,kindKey)?CAPTURE_KIND[kindKey]:"function";if(grammarId==="python"&&kindKey==="func"&&hasAncestorOfType(originalDefNode,"class_definition"))kind="method";if(grammarId==="rust"&&kindKey==="func"&&hasAncestorOfType(originalDefNode,"impl_item"))kind="method";let parentContainerType;if(JVM_GRAMMARS.has(grammarId)){if(parentContainerType=nearestAncestorType(originalDefNode,JVM_CONTAINER_TYPES),parentContainerType!==void 0&&(kindKey==="func"||kindKey==="ctor"))kind="method"}if(grammarId==="cpp"||grammarId==="swift"){if(parentContainerType=nearestAncestorType(originalDefNode,NATIVE_CONTAINER_TYPES),parentContainerType!==void 0&&kindKey==="func")kind="method"}let explicitExported=exportNodes.some((en)=>isNodeInside(en,defNode)),isDefaultExport=!1;if(explicitExported&&isEsMGrammar(grammarId))isDefaultExport=exportNodes.some((en)=>isDefaultExportStatement(en)&&isOwnExportDeclaration(en,defNode));if(grammarId==="dart"&&defNode.type==="function_signature"){let rawBody=defNode.nextSibling;if(rawBody){let bodyNode=asTs(rawBody);if(bodyNode.type==="function_body")defNode=asTs({...defNode,endIndex:bodyNode.endIndex,endPosition:bodyNode.endPosition})}}if(grammarId==="python"&&defNode.parent?.type==="decorated_definition")defNode=asTs(defNode.parent);let pythonParentClassExported=!1;if(grammarId==="python"&&kind==="method"){let current=originalDefNode.parent;while(current){if(current.type==="class_definition"){let classNameNode=current.children?.find((c)=>c!=null&&c.type==="identifier");if(classNameNode){let className=classNameNode.text;pythonParentClassExported=pythonAllNames?pythonAllNames.has(className):!className.startsWith("_")}break}current=current.parent}}for(let nc of nameCaps){let nameNode=asTs(nc.node),localName=nameNode.text,commonJsExport=commonJsExports.get(localName),visibilityInfo=getSymbolVisibilityInfo({grammarId,localName,kind,defNode:originalDefNode,rootNode:root,isTopLevel:isTopLevelDef(originalDefNode,root),explicitExported,commonJsExport,pythonAllNames,pythonParentClassExported,parentContainerType});if(grammarId==="swift"&&kindKey==="extension")visibilityInfo={...visibilityInfo,exported:!1};let exportedName=isDefaultExport?"default":commonJsExport?.exportedName??localName;defs.push({name:exportedName,kind,exported:visibilityInfo.exported,visibilityInfo,startLine:defNode.startPosition.row+1,endLine:defNode.endPosition.row+1}),defNodes.push({node:defNode,name:localName}),defNameKeys.add(nodeKey(nameNode))}}let importsWithIndex=[],addImport=(entry,node)=>{if(!entry)return;for(let item of Array.isArray(entry)?entry:[entry]){let pythonExportedBindings=grammarId==="python"&&pythonAllNames&&item.bindings.length>0?item.bindings.filter((binding)=>pythonAllNames.has(binding.local)).map((binding)=>({imported:binding.imported,exported:binding.local})):[],normalizedItem=pythonExportedBindings.length>0?{...item,reExport:!0,exportedBindings:pythonExportedBindings}:item;importsWithIndex.push({index:node.startIndex,entry:normalizedItem.reExport?{...normalizedItem,startLine:node.startPosition.row+1,endLine:node.endPosition.row+1}:normalizedItem})}};for(let m of importMatches){let importCap=m.captures.find((c)=>c.name==="import");if(importCap){let importNode=asTs(importCap.node),rawText=importNode.text.trim();if(grammarId==="go"&&rawText.startsWith("import (")){let seenGoSpecifiers=new Set,specListNode=importNode.children.find((c)=>c!==null&&c.type==="import_spec_list");if(specListNode){for(let spec of asTs(specListNode).children)if(spec&&spec.type==="import_spec"){let parsed=parseGoImportHardened(spec.text.trim());if(parsed)seenGoSpecifiers.add(parsed.specifier);addImport(parsed,asTs(spec))}}for(let parsed of parseGoBlockImports(rawText)){if(seenGoSpecifiers.has(parsed.specifier))continue;addImport(parsed,importNode)}}else{let parsed=parseImport(grammarId,rawText);addImport(parsed,importNode)}}if(grammarId==="ruby"){let reqName=m.captures.find((c)=>c.name==="require.name"),reqSpec=m.captures.find((c)=>c.name==="require.specifier");if(reqName&&reqSpec){let fnText=asTs(reqName.node).text;if(fnText==="require"||fnText==="require_relative"){let callNode=asTs(reqName.node).parent,rawText=callNode?callNode.text:asTs(reqSpec.node).text,parsed=parseRubyRequire(rawText);addImport(parsed,asTs(callNode??reqSpec.node))}}}if(isEsMGrammar(grammarId)){let reqName=m.captures.find((c)=>c.name==="require.name"),reqSpec=m.captures.find((c)=>c.name==="require.specifier");if(reqName&&reqSpec){if(asTs(reqName.node).text==="require"){let specText=asTs(reqSpec.node).text.replace(/['"]/g,"");addImport({specifier:specText,importType:"commonjs",bindings:[]},asTs(reqName.node))}}}}if(isEsMGrammar(grammarId))for(let exportNode of exportNodes)addImport(parseImport(grammarId,exportNode.text.trim()),exportNode);let imports=importsWithIndex.sort((a,b)=>a.index-b.index).map((item)=>item.entry),topLevelDefs=defNodes.filter((d)=>isTopLevelDef(d.node,root)).map((d)=>({name:d.name,node:d.node})),refs=[],refParamTypes=grammarId==="swift"?SWIFT_REF_PARAM_TYPES:PARAM_TYPES;for(let m of refMatches){let cap=m.captures.find((c)=>c.name==="ref.identifier");if(!cap)continue;let refNode=asTs(cap.node);if(defNameKeys.has(nodeKey(refNode)))continue;if(hasAncestorOfType(refNode,"import_statement"))continue;if(isInsideImportStatement(refNode))continue;if(hasAncestorOfType(refNode,refParamTypes))continue;if(refNode.text==="require"&&isInsideRequireCall(refNode))continue;refs.push({identifier:refNode.text,line:refNode.startPosition.row+1,enclosingDecl:findEnclosingDecl(refNode,topLevelDefs)})}if(isEsMGrammar(grammarId))for(let en of exportNodes){if(!isDefaultExportStatement(en))continue;let owner=en.childForFieldName?.("declaration")??en.childForFieldName?.("value");if(!owner)continue;if(defs.some((d)=>d.startLine===owner.startPosition.row+1&&d.name==="default"))continue;let kind=owner.type.includes("class")?"class":"function";defs.push({name:"default",kind,exported:!0,startLine:owner.startPosition.row+1,endLine:owner.endPosition.row+1})}return{defs,imports,refs}}function safeMatches(lang,pattern,root){if(!_QueryCtor)return[];try{return new _QueryCtor(lang,pattern).matches(root)}catch{return[]}}function parseEsmImport(text){let t=text.trim(),sideEffect=t.match(/^import\s+['"]([^'"]+)['"]/);if(sideEffect)return{specifier:sideEffect[1],importType:"sideeffect",bindings:[]};let reExportAllAs=t.match(/^export\s+\*\s+as\s+([A-Za-z_$][\w$]*)\s+from\s+['"]([^'"]+)['"]/);if(reExportAllAs)return{specifier:reExportAllAs[2],importType:"namespace",bindings:[{imported:"*",local:reExportAllAs[1]}],reExport:!0,exportedBindings:[{imported:"*",exported:reExportAllAs[1]}]};let reExportAll=t.match(/^export\s+\*\s+from\s+['"]([^'"]+)['"]/);if(reExportAll)return{specifier:reExportAll[1],importType:"namespace",bindings:[],reExport:!0};let namedTypeReExport=t.match(/^export\s+type\s+\{([^}]+)\}\s+from\s+['"]([^'"]+)['"]/);if(namedTypeReExport)return{specifier:namedTypeReExport[2],importType:"type",bindings:[],reExport:!0};let namedReExport=t.match(/^export\s+\{([^}]+)\}\s+from\s+['"]([^'"]+)['"]/);if(namedReExport){let bindings=[],exportedBindings=[];for(let rawPart of namedReExport[1].split(",")){let p=rawPart.trim();if(!p)continue;if(/^type\s+/.test(p))continue;let alias=p.match(/^([A-Za-z_$][\w$]*)\s+as\s+([A-Za-z_$][\w$]*)$/),imported=alias?alias[1]:p,exported=alias?alias[2]:p;if(!/^[A-Za-z_$][\w$]*$/.test(imported))continue;if(!/^[A-Za-z_$][\w$]*$/.test(exported))continue;bindings.push({imported,local:exported}),exportedBindings.push({imported,exported})}return{specifier:namedReExport[2],importType:"named",bindings,reExport:!0,exportedBindings}}let isTypeOnlyImport=/^import\s+type\s/.test(t),withoutTypeQualifier=t.replace(/^import\s+type\s+/,"import "),named=withoutTypeQualifier.match(/^import\s+\{([^}]+)\}\s+from\s+['"]([^'"]+)['"]/);if(named){if(isTypeOnlyImport)return{specifier:named[2],importType:"named",bindings:[]};let bindings=[];for(let part of named[1].split(",")){let p=part.trim();if(!p)continue;if(/^type\s+/.test(p))continue;let stripped=p.replace(/^type\s+/,"");if(!stripped)continue;let alias=stripped.match(/^([A-Za-z_$][\w$]*)\s+as\s+([A-Za-z_$][\w$]*)$/);if(alias)bindings.push({imported:alias[1],local:alias[2]});else if(/^[A-Za-z_$][\w$]*$/.test(stripped))bindings.push({imported:stripped,local:stripped})}return{specifier:named[2],importType:"named",bindings}}let combined=withoutTypeQualifier.match(/^import\s+([A-Za-z_$][\w$]*)\s*,\s*\*\s+as\s+([A-Za-z_$][\w$]*)\s+from\s+['"]([^'"]+)['"]/);if(combined){if(isTypeOnlyImport)return{specifier:combined[3],importType:"named",bindings:[]};return{specifier:combined[3],importType:"named",bindings:[{imported:"default",local:combined[1]},{imported:"*",local:combined[2]}]}}let combinedNamed=withoutTypeQualifier.match(/^import\s+([A-Za-z_$][\w$]*)\s*,\s*\{([^}]+)\}\s+from\s+['"]([^'"]+)['"]/);if(combinedNamed){if(isTypeOnlyImport)return{specifier:combinedNamed[3],importType:"named",bindings:[]};let bindings=[{imported:"default",local:combinedNamed[1]}];for(let part of combinedNamed[2].split(",")){let p=part.trim();if(!p)continue;if(/^type\s+/.test(p))continue;let stripped=p.replace(/^type\s+/,"");if(!stripped)continue;let alias=stripped.match(/^([A-Za-z_$][\w$]*)\s+as\s+([A-Za-z_$][\w$]*)$/);if(alias)bindings.push({imported:alias[1],local:alias[2]});else if(/^[A-Za-z_$][\w$]*$/.test(stripped))bindings.push({imported:stripped,local:stripped})}return{specifier:combinedNamed[3],importType:"named",bindings}}let ns=t.match(/^import\s+\*\s+as\s+([A-Za-z_$][\w$]*)\s+from\s+['"]([^'"]+)['"]/);if(ns)return{specifier:ns[2],importType:"namespace",bindings:[{imported:"*",local:ns[1]}]};let def=t.match(/^import\s+([A-Za-z_$][\w$]*)\s+from\s+['"]([^'"]+)['"]/);if(def)return{specifier:def[2],importType:"default",bindings:[{imported:"default",local:def[1]}]};return null}function parseImport(grammarId,text){switch(grammarId){case"python":return parsePythonImportHardened(text);case"rust":return parseRustUseHardened(text);case"go":return parseGoImportHardened(text);case"java":return parseJavaImport(text);case"kotlin":return parseKotlinImport(text);case"csharp":return parseCSharpUsing(text);case"cpp":return parseCppInclude(text);case"swift":return parseSwiftImport(text);case"dart":return parseDartImport(text);case"ruby":return parseRubyRequire(text);case"php":return parsePhpUse(text);case"typescript":case"tsx":case"javascript":return parseEsmImport(text);default:return null}}function parsePythonImportHardened(text){let t=text.trim(),fullImport=t.match(/^import\s+(.+)$/);if(fullImport){let entries=[];for(let rawPart of fullImport[1].split(",")){let part=rawPart.trim();if(!part)continue;let alias=part.match(/^([\w.]+)\s+as\s+(\w+)$/),specifier=alias?alias[1]:part,local=alias?alias[2]:specifier.split(".")[0];if(!specifier||!/^\w+$/.test(local))continue;entries.push({specifier,importType:alias?"named":"namespace",bindings:[{imported:specifier,local}]})}if(entries.length===0)return null;return entries.length===1?entries[0]:entries}let fromImport=t.match(/^from\s+(\S+)\s+import\s+(.+)$/);if(!fromImport)return null;let bindings=[];for(let rawPart of fromImport[2].split(",")){let part=rawPart.trim();if(!part)continue;if(part==="*")return{specifier:normalizePythonModuleSpecifier(fromImport[1]),importType:"namespace",bindings:[]};let alias=part.match(/^(\w+)\s+as\s+(\w+)$/);if(alias)bindings.push({imported:alias[1],local:alias[2]});else if(/^\w+$/.test(part))bindings.push({imported:part,local:part})}return{specifier:normalizePythonModuleSpecifier(fromImport[1]),importType:"named",bindings}}function normalizePythonModuleSpecifier(specifier){let leadingDots=specifier.match(/^\.+/)?.[0].length??0;if(leadingDots===0)return specifier;let rest=specifier.slice(leadingDots).replace(/\./g,"/");return`${leadingDots===1?"./":"../".repeat(leadingDots-1)}${rest}`}function parseRustUseHardened(text){let t=text.trim(),aliased=t.match(/^use\s+(.+?)\s+as\s+(\w+)\s*;?\s*$/);if(aliased){let parts2=aliased[1].trim().split("::").filter(Boolean),imported2=parts2.pop()??aliased[1].trim();return{specifier:parts2.length>0?parts2.join("::"):aliased[1].trim(),importType:"named",bindings:[{imported:imported2,local:aliased[2]}]}}let grouped=t.match(/^use\s+(.+?)::\{(.+)\}\s*;?\s*$/);if(grouped){let base=grouped[1].trim(),bindings=[];for(let rawPart of grouped[2].split(",")){let part=rawPart.trim();if(!part)continue;let alias=part.match(/^(\w+)\s+as\s+(\w+)$/);if(alias)bindings.push({imported:alias[1],local:alias[2]});else if(/^\w+$/.test(part)){let local2=part==="self"?base.split("::").pop()||base:part;bindings.push({imported:part,local:local2})}}return{specifier:base,importType:"named",bindings}}let simple=t.match(/^use\s+(.+?)\s*;?\s*$/);if(!simple)return null;let parts=simple[1].trim().split("::").filter(Boolean),imported=parts.pop()??simple[1].trim(),specifier=parts.length>0?parts.join("::"):simple[1].trim(),local=imported;return{specifier,importType:"named",bindings:/^\w+$/.test(imported)?[{imported,local}]:[]}}function parseGoBlockImports(text){let entries=[],body=text.match(/^import\s*\(([\s\S]*?)\)\s*$/)?.[1];if(!body)return entries;for(let line of body.split(/\r?\n/)){let trimmed=line.trim();if(!trimmed||trimmed.startsWith("//"))continue;let parsed=parseGoImportHardened(trimmed);if(parsed)entries.push(parsed)}return entries}function parseGoImportHardened(text){let t=text.trim();if(t.startsWith("import ("))return null;let aliased=t.match(/^(?!import\b)([\w._]+)\s+["`]([^"`]+)["`]$/)??t.match(/^import\s+([\w._]+)\s+["`]([^"`]+)["`]/);if(aliased){if(aliased[1]==="_")return{specifier:aliased[2],importType:"sideeffect",bindings:[]};if(aliased[1]===".")return{specifier:aliased[2],importType:"namespace",bindings:[{imported:"*",local:"."}]};return{specifier:aliased[2],importType:"named",bindings:[{imported:aliased[2],local:aliased[1]}]}}let simple=t.match(/^import\s+["`]([^"`]+)["`]|^["`]([^"`]+)["`]$/);if(!simple)return null;return{specifier:simple[1]??simple[2],importType:"namespace",bindings:[]}}function finalDottedSegment(path157){let withoutGenerics=path157.replace(/<.*>$/s,""),lastDot=withoutGenerics.lastIndexOf(".");return lastDot===-1?withoutGenerics:withoutGenerics.slice(lastDot+1)}function parseJavaImport(text){let m=text.trim().match(/^import\s+(static\s+)?([^;\s]+)\s*;?\s*$/);if(!m)return null;let isStatic=Boolean(m[1]),path157=m[2],last=finalDottedSegment(path157);if(last==="*")return{specifier:path157,importType:"namespace",bindings:[]};let lastDot=path157.lastIndexOf(".");return{specifier:isStatic&&lastDot!==-1?path157.slice(0,lastDot):path157,importType:"named",bindings:[{imported:last,local:last}]}}function parseKotlinImport(text){let t=text.trim(),aliased=t.match(/^import\s+([^;\s]+)\s+as\s+(\w+)/);if(aliased)return{specifier:aliased[1],importType:"named",bindings:[{imported:finalDottedSegment(aliased[1]),local:aliased[2]}]};let simple=t.match(/^import\s+([^;\s]+)/);if(!simple)return null;let path157=simple[1],last=finalDottedSegment(path157);if(last==="*")return{specifier:path157,importType:"namespace",bindings:[]};return{specifier:path157,importType:"named",bindings:[{imported:last,local:last}]}}function parseCSharpUsing(text){let m=text.trim().match(/^(?:global\s+)?using\s+(?:static\s+)?([^=;\s]+)\s*(?:=\s*(.+?))?\s*;?\s*$/);if(!m)return null;if(m[2]){let target=m[2].trim();return{specifier:target,importType:"named",bindings:[{imported:finalDottedSegment(target),local:m[1].trim()}]}}return{specifier:m[1].trim(),importType:"namespace",bindings:[]}}function parseCppInclude(text){let t=text.trim(),quoted=t.match(/^#\s*include\s+"([^"]+)"/);if(quoted){let raw=quoted[1];return{specifier:raw.startsWith(".")?raw:`./${raw}`,importType:"namespace",bindings:[]}}let angle=t.match(/^#\s*include\s+<([^>]+)>/);if(angle)return{specifier:angle[1],importType:"namespace",bindings:[]};let using=t.match(/^using\s+(?:namespace\s+)?(.+?)\s*;?\s*$/);if(using)return{specifier:using[1].trim(),importType:"namespace",bindings:[]};return null}function parseSwiftImport(text){let t=text.trim(),attrs=/^(?:@\w+(?:\([^)\n]*\))?\s+)*/.source,m=t.match(new RegExp(`${attrs}import\\s+((?:class|struct|enum|protocol|typealias|func|var|let)\\s+)?([A-Za-z_]\\w*(?:\\.[A-Za-z_]\\w*)*)\\s*$`));if(!m)return null;let path157=m[2].split(".");if(m[1]!==void 0&&path157.length>=2){let imported=path157[path157.length-1];return{specifier:path157[0],importType:"named",bindings:[{imported,local:imported}]}}return{specifier:m[2],importType:"namespace",bindings:[]}}function parseDartImport(text){let t=text.trim(),m=t.match(/^import\s+['"]([^'"]+)['"]\s+as\s+(\w+)/);if(m)return{specifier:m[1],importType:"named",bindings:[{imported:m[1],local:m[2]}]};let simple=t.match(/^import\s+['"]([^'"]+)['"]/);if(simple)return{specifier:simple[1],importType:"namespace",bindings:[]};return null}function parseRubyRequire(text){let t=text.trim(),stripped=t.replace(/^(?:require(?:_relative)?)\s+['"]?/,"").replace(/['"]$/,"");if(!stripped||stripped===t)return null;let isRelative=stripped.startsWith("./")||stripped.startsWith("../");return{specifier:stripped,importType:isRelative?"default":"namespace",bindings:[]}}function parsePhpUse(text){let t=text.trim(),m=t.match(/^use\s+(?:(?:function|const)\s+)?([^;\s]+)\s+as\s+(\w+)\s*;?\s*$/i);if(m)return{specifier:m[1],importType:"named",bindings:[{imported:m[1],local:m[2]}]};let simple=t.match(/^use\s+(?:(?:function|const)\s+)?([^;\s]+)\s*;?\s*$/i);if(simple)return{specifier:simple[1],importType:"namespace",bindings:[]};return null}function isTopLevelDef(defNode,root){let parent=defNode.parent;while(parent&&parent!==root){if(DEF_TYPES.has(parent.type))return!1;parent=parent.parent}return!0}function findEnclosingDecl(refNode,topLevelDefs){let best=null,bestDist=1/0;for(let def of topLevelDefs)if(isNodeInside(def.node,refNode)){let dist=refNode.startPosition.row-def.node.startPosition.row;if(dist<bestDist)bestDist=dist,best=def}return best?.name??"<module>"}function isNodeInside(outer,inner){return inner.startIndex>=outer.startIndex&&inner.endIndex<=outer.endIndex}function nearestAncestorType(node,types2){let current=node.parent;while(current){if(types2.has(current.type))return current.type;current=current.parent}return}function hasAncestorOfType(node,types2){let typeSet=typeof types2==="string"?new Set([types2]):types2,current=node.parent;while(current){if(typeSet.has(current.type))return!0;current=current.parent}return!1}function isInsideRequireCall(node){let current=node.parent;while(current){if(current.type==="call_expression"){let fn2=current.children.find((c)=>c&&c.type==="identifier");if(fn2&&fn2.text==="require")return!0}if(DEF_TYPES.has(current.type))return!1;current=current.parent}return!1}function isInsideImportStatement(node){return hasAncestorOfType(node,IMPORT_ANCESTOR_TYPES)}function nodeKey(node){return`${node.startPosition.row},${node.startPosition.column}-${node.endPosition.row},${node.endPosition.column}`}function isOwnExportDeclaration(en,defNode){let owner=en.childForFieldName?.("declaration")??en.childForFieldName?.("value");if(owner)return owner.startIndex===defNode.startIndex&&owner.endIndex===defNode.endIndex;return isNodeInside(en,defNode)}function isDefaultExportStatement(en){if(en.children.some((c)=>c!==null&&c.type==="default"))return!0;return/^export\s+default\b/.test(en.text)}function isEsMGrammar(grammarId){return grammarId==="typescript"||grammarId==="tsx"||grammarId==="javascript"}var _QueryCtor=null,AST_TIMEOUT_MS3=500,QUERIES2,CAPTURE_KIND,DEF_TYPES,JVM_GRAMMARS,JVM_CONTAINER_TYPES,NATIVE_CONTAINER_TYPES,PARAM_TYPES,SWIFT_REF_PARAM_TYPES,IMPORT_ANCESTOR_TYPES;var init_symbol_graph=__esm(()=>{init_symbol_visibility();QUERIES2={typescript:{defs:`
|
|
2873
2873
|
(function_declaration name: (identifier) @func.name) @func.def
|
|
2874
2874
|
(generator_function_declaration name: (identifier) @func.name) @func.def
|
|
2875
2875
|
(class_declaration name: (type_identifier) @class.name) @class.def
|
|
@@ -3029,23 +3029,66 @@ Flags:
|
|
|
3029
3029
|
declarator: (identifier) @func.name
|
|
3030
3030
|
)
|
|
3031
3031
|
) @func.def
|
|
3032
|
+
(function_definition
|
|
3033
|
+
declarator: (pointer_declarator
|
|
3034
|
+
declarator: (function_declarator
|
|
3035
|
+
declarator: (identifier) @func.name
|
|
3036
|
+
)
|
|
3037
|
+
)
|
|
3038
|
+
) @func.def
|
|
3039
|
+
(function_definition
|
|
3040
|
+
(function_declarator
|
|
3041
|
+
declarator: (qualified_identifier (identifier) @func.name)
|
|
3042
|
+
)
|
|
3043
|
+
) @func.def
|
|
3044
|
+
(declaration
|
|
3045
|
+
declarator: (function_declarator
|
|
3046
|
+
declarator: (identifier) @func.name
|
|
3047
|
+
)
|
|
3048
|
+
) @func.def
|
|
3049
|
+
(declaration
|
|
3050
|
+
declarator: (pointer_declarator
|
|
3051
|
+
declarator: (function_declarator
|
|
3052
|
+
declarator: (identifier) @func.name
|
|
3053
|
+
)
|
|
3054
|
+
)
|
|
3055
|
+
) @func.def
|
|
3056
|
+
(function_definition
|
|
3057
|
+
(function_declarator
|
|
3058
|
+
declarator: (field_identifier) @method.name
|
|
3059
|
+
)
|
|
3060
|
+
) @method.def
|
|
3061
|
+
(field_declaration
|
|
3062
|
+
(function_declarator
|
|
3063
|
+
declarator: (field_identifier) @method.name
|
|
3064
|
+
)
|
|
3065
|
+
) @method.def
|
|
3032
3066
|
(class_specifier name: (type_identifier) @class.name) @class.def
|
|
3033
3067
|
(struct_specifier name: (type_identifier) @struct.name) @struct.def
|
|
3068
|
+
(enum_specifier name: (type_identifier) @enum.name) @enum.def
|
|
3069
|
+
(type_definition declarator: (type_identifier) @type.name) @type.def
|
|
3034
3070
|
`,imports:`
|
|
3035
3071
|
(preproc_include) @import
|
|
3036
3072
|
(using_declaration) @import
|
|
3037
3073
|
`,refs:`
|
|
3038
3074
|
(identifier) @ref.identifier
|
|
3039
3075
|
(namespace_identifier) @ref.identifier
|
|
3076
|
+
(type_identifier) @ref.identifier
|
|
3040
3077
|
`,exports:""},swift:{defs:`
|
|
3041
3078
|
(function_declaration name: (simple_identifier) @func.name) @func.def
|
|
3079
|
+
(protocol_function_declaration name: (simple_identifier) @func.name) @func.def
|
|
3042
3080
|
(class_declaration name: (type_identifier) @class.name) @class.def
|
|
3081
|
+
(class_declaration
|
|
3082
|
+
name: (user_type (type_identifier) @extension.name)
|
|
3083
|
+
) @extension.def
|
|
3043
3084
|
(protocol_declaration name: (type_identifier) @protocol.name) @protocol.def
|
|
3085
|
+
(typealias_declaration name: (type_identifier) @type.name) @type.def
|
|
3044
3086
|
`,imports:`
|
|
3045
3087
|
(import_declaration) @import
|
|
3046
3088
|
`,refs:`
|
|
3047
3089
|
(identifier) @ref.identifier
|
|
3048
3090
|
(simple_identifier) @ref.identifier
|
|
3091
|
+
(type_identifier) @ref.identifier
|
|
3049
3092
|
`,exports:""},dart:{defs:`
|
|
3050
3093
|
(function_signature
|
|
3051
3094
|
name: (identifier) @func.name
|
|
@@ -3077,7 +3120,7 @@ Flags:
|
|
|
3077
3120
|
(namespace_use_declaration) @import
|
|
3078
3121
|
`,refs:`
|
|
3079
3122
|
(name) @ref.identifier
|
|
3080
|
-
`,exports:""}},CAPTURE_KIND={func:"function",class:"class",const:"const",type:"type",interface:"interface",enum:"enum",method:"method",struct:"type",trait:"interface",mod:"type",object:"class",mixin:"type",protocol:"interface",record:"class",ctor:"method"},DEF_TYPES=new Set(["function_declaration","class_declaration","variable_declaration","type_alias_declaration","interface_declaration","enum_declaration","method_definition","function_item","function_signature","class_specifier","struct_specifier","struct_item","struct_declaration","record_declaration","constructor_declaration","method_declaration","type_declaration","object_declaration","protocol_declaration","mixin_declaration","function_definition","generator_function_declaration","class_definition","lexical_declaration","impl_item","enum_item","trait_item","mod_item","var_declaration","const_declaration","method","class"]),JVM_GRAMMARS=new Set(["java","kotlin","csharp"]),JVM_CONTAINER_TYPES=new Set(["class_declaration","interface_declaration","struct_declaration","object_declaration","enum_declaration","record_declaration"]),PARAM_TYPES=new Set(["formal_parameters","required_parameter","optional_parameter","rest_parameter","array_pattern","object_pattern"]);IMPORT_ANCESTOR_TYPES=new Set(["import_statement","import_from_statement","import_declaration","import_header","use_declaration","using_directive","namespace_use_declaration","library_import"])});import*as fs82 from"node:fs";import*as path157 from"node:path";function containsWindowsAttacks(str){if(/:[^\\/]/.test(str))return!0;let parts=str.split(/[/\\]/);for(let part of parts)if(WINDOWS_RESERVED_NAMES2.test(part))return!0;return!1}function isPathInWorkspace(filePath,workspace){try{let resolvedPath=path157.resolve(workspace,filePath),realWorkspace=fs82.realpathSync(workspace),realResolvedPath=fs82.realpathSync(resolvedPath),relativePath2=path157.relative(realWorkspace,realResolvedPath);if(relativePath2.startsWith("..")||path157.isAbsolute(relativePath2))return!1;return!0}catch{return!1}}function validatePathForRead(filePath,workspace){return isPathInWorkspace(filePath,workspace)}function readValidatedSourceFile(filePath,cwd){let fullPath=path157.join(cwd,filePath);if(!validatePathForRead(fullPath,cwd))return null;try{if(fs82.statSync(fullPath).size>MAX_FILE_SIZE_BYTES3)return null;return fs82.readFileSync(fullPath,"utf-8")}catch{return null}}function extractTSSymbols(filePath,cwd){let fullPath=path157.join(cwd,filePath);if(!validatePathForRead(fullPath,cwd))return[];let content;try{let stats2=fs82.statSync(fullPath);if(stats2.size>MAX_FILE_SIZE_BYTES3)throw Error(`File too large: ${stats2.size} bytes (max: ${MAX_FILE_SIZE_BYTES3})`);content=fs82.readFileSync(fullPath,"utf-8")}catch{return[]}let lines=content.split(`
|
|
3123
|
+
`,exports:""}},CAPTURE_KIND={func:"function",class:"class",const:"const",type:"type",interface:"interface",enum:"enum",method:"method",struct:"type",trait:"interface",mod:"type",object:"class",mixin:"type",protocol:"interface",record:"class",ctor:"method",extension:"type"},DEF_TYPES=new Set(["function_declaration","class_declaration","variable_declaration","type_alias_declaration","interface_declaration","enum_declaration","method_definition","function_item","function_signature","class_specifier","struct_specifier","struct_item","struct_declaration","record_declaration","constructor_declaration","method_declaration","type_declaration","object_declaration","protocol_declaration","mixin_declaration","function_definition","generator_function_declaration","class_definition","lexical_declaration","impl_item","enum_item","trait_item","mod_item","var_declaration","const_declaration","method","class"]),JVM_GRAMMARS=new Set(["java","kotlin","csharp"]),JVM_CONTAINER_TYPES=new Set(["class_declaration","interface_declaration","struct_declaration","object_declaration","enum_declaration","record_declaration"]),NATIVE_CONTAINER_TYPES=new Set(["class_specifier","struct_specifier","union_specifier","class_declaration","protocol_declaration"]),PARAM_TYPES=new Set(["formal_parameters","required_parameter","optional_parameter","rest_parameter","array_pattern","object_pattern"]),SWIFT_REF_PARAM_TYPES=new Set([...PARAM_TYPES,"parameter"]);IMPORT_ANCESTOR_TYPES=new Set(["import_statement","import_from_statement","import_declaration","import_header","use_declaration","using_directive","namespace_use_declaration","library_import"])});import*as fs82 from"node:fs";import*as path157 from"node:path";function containsWindowsAttacks(str){if(/:[^\\/]/.test(str))return!0;let parts=str.split(/[/\\]/);for(let part of parts)if(WINDOWS_RESERVED_NAMES2.test(part))return!0;return!1}function isPathInWorkspace(filePath,workspace){try{let resolvedPath=path157.resolve(workspace,filePath),realWorkspace=fs82.realpathSync(workspace),realResolvedPath=fs82.realpathSync(resolvedPath),relativePath2=path157.relative(realWorkspace,realResolvedPath);if(relativePath2.startsWith("..")||path157.isAbsolute(relativePath2))return!1;return!0}catch{return!1}}function validatePathForRead(filePath,workspace){return isPathInWorkspace(filePath,workspace)}function readValidatedSourceFile(filePath,cwd){let fullPath=path157.join(cwd,filePath);if(!validatePathForRead(fullPath,cwd))return null;try{if(fs82.statSync(fullPath).size>MAX_FILE_SIZE_BYTES3)return null;return fs82.readFileSync(fullPath,"utf-8")}catch{return null}}function extractTSSymbols(filePath,cwd){let fullPath=path157.join(cwd,filePath);if(!validatePathForRead(fullPath,cwd))return[];let content;try{let stats2=fs82.statSync(fullPath);if(stats2.size>MAX_FILE_SIZE_BYTES3)throw Error(`File too large: ${stats2.size} bytes (max: ${MAX_FILE_SIZE_BYTES3})`);content=fs82.readFileSync(fullPath,"utf-8")}catch{return[]}let lines=content.split(`
|
|
3081
3124
|
`),symbols=[];for(let i=0;i<lines.length;i++){let line=lines[i],lineNum=i+1,jsdoc;if(i>0&&lines[i-1].trim().endsWith("*/")){let jsdocLines=[];for(let j=i-1;j>=0;j--)if(jsdocLines.unshift(lines[j]),lines[j].trim().startsWith("/**"))break;if(jsdoc=jsdocLines.join(`
|
|
3082
3125
|
`).trim(),jsdoc.length>300)jsdoc=`${jsdoc.substring(0,300)}...`}let fnMatch=line.match(/^export\s+(?:async\s+)?function\s+(\w+)\s*(<[^>]*>)?\s*\(([^)]*)\)(?:\s*:\s*(.+?))?(?:\s*\{|$)/);if(fnMatch){symbols.push({name:fnMatch[1],kind:"function",exported:!0,signature:`function ${fnMatch[1]}${fnMatch[2]||""}(${fnMatch[3].trim()})${fnMatch[4]?`: ${fnMatch[4].trim()}`:""}`,line:lineNum,jsdoc});continue}let constMatch=line.match(/^export\s+const\s+(\w+)(?:\s*:\s*(.+?))?\s*=/);if(constMatch){let restOfLine=line.substring(line.indexOf("=")+1).trim(),isArrow=restOfLine.startsWith("(")||restOfLine.startsWith("async (")||restOfLine.match(/^\w+\s*=>/);symbols.push({name:constMatch[1],kind:isArrow?"function":"const",exported:!0,signature:`const ${constMatch[1]}${constMatch[2]?`: ${constMatch[2].trim()}`:""}`,line:lineNum,jsdoc});continue}let classMatch=line.match(/^export\s+(?:abstract\s+)?class\s+(\w+)(?:\s+(?:extends|implements)\s+(.+?))?(?:\s*\{|$)/);if(classMatch){symbols.push({name:classMatch[1],kind:"class",exported:!0,signature:`class ${classMatch[1]}${classMatch[2]?` extends/implements ${classMatch[2].trim()}`:""}`,line:lineNum,jsdoc});let braceDepth=(line.match(/\{/g)||[]).length-(line.match(/\}/g)||[]).length;for(let j=i+1;j<lines.length&&braceDepth>0;j++){let memberLine=lines[j];braceDepth+=(memberLine.match(/\{/g)||[]).length-(memberLine.match(/\}/g)||[]).length;let methodMatch=memberLine.match(/^\s+(?:public\s+)?(?:async\s+)?(\w+)\s*\(([^)]*)\)(?:\s*:\s*(.+?))?(?:\s*\{|;|$)/);if(methodMatch&&!memberLine.includes("private")&&!memberLine.includes("protected")&&!memberLine.trim().startsWith("//"))symbols.push({name:`${classMatch[1]}.${methodMatch[1]}`,kind:"method",exported:!0,signature:`${methodMatch[1]}(${methodMatch[2].trim()})${methodMatch[3]?`: ${methodMatch[3].trim()}`:""}`,line:j+1});let propMatch=memberLine.match(/^\s+(?:public\s+)?(?:readonly\s+)?(\w+)(?:\?)?:\s*(.+?)(?:\s*[;=]|$)/);if(propMatch&&!memberLine.includes("private")&&!memberLine.includes("protected")&&!memberLine.trim().startsWith("//"))symbols.push({name:`${classMatch[1]}.${propMatch[1]}`,kind:"property",exported:!0,signature:`${propMatch[1]}: ${propMatch[2].trim()}`,line:j+1})}continue}let ifaceMatch=line.match(/^export\s+interface\s+(\w+)(?:\s*<([^>]+)>)?(?:\s+extends\s+(.+?))?(?:\s*\{|$)/);if(ifaceMatch){symbols.push({name:ifaceMatch[1],kind:"interface",exported:!0,signature:`interface ${ifaceMatch[1]}${ifaceMatch[2]?`<${ifaceMatch[2]}>`:""}${ifaceMatch[3]?` extends ${ifaceMatch[3].trim()}`:""}`,line:lineNum,jsdoc});continue}let typeMatch=line.match(/^export\s+type\s+(\w+)(?:\s*<([^>]+)>)?\s*=/);if(typeMatch){let typeValue=line.substring(line.indexOf("=")+1).trim().substring(0,100);symbols.push({name:typeMatch[1],kind:"type",exported:!0,signature:`type ${typeMatch[1]}${typeMatch[2]?`<${typeMatch[2]}>`:""} = ${typeValue}`,line:lineNum,jsdoc});continue}let enumMatch=line.match(/^export\s+(?:const\s+)?enum\s+(\w+)/);if(enumMatch){symbols.push({name:enumMatch[1],kind:"enum",exported:!0,signature:`enum ${enumMatch[1]}`,line:lineNum,jsdoc});continue}let defaultMatch=line.match(/^export\s+default\s+(?:function\s+)?(\w+)/);if(defaultMatch)symbols.push({name:defaultMatch[1],kind:"function",exported:!0,signature:`default ${defaultMatch[1]}`,line:lineNum,jsdoc})}return symbols.sort((a,b)=>{if(a.line!==b.line)return a.line-b.line;return a.name.localeCompare(b.name)})}function extractPythonSymbols(filePath,cwd){let content=readValidatedSourceFile(filePath,cwd);if(content===null)return[];let lines=content.split(`
|
|
3083
3126
|
`),symbols=[],explicitExports=collectPythonAllNames(content),isExplicitlyExported=(name)=>explicitExports?explicitExports.has(name):!name.startsWith("_"),isPackageInit=["__init__.py","__init__.pyw"].includes(path157.basename(filePath)),seenNames=new Set,currentClass=null,addSymbol=(symbol3)=>{if(seenNames.has(symbol3.name))return;seenNames.add(symbol3.name),symbols.push(symbol3)};for(let i=0;i<lines.length;i++){let line=lines[i],indent=line.match(/^\s*/)?.[0].length??0;if(indent===0)currentClass=null;if(currentClass&&indent>currentClass.indent){let methodMatch=line.trim().match(/^(?:async\s+)?def\s+(\w+)\s*\(([^)]*)\)(?:\s*->\s*(.+?))?:/);if(methodMatch){let name=`${currentClass.name}.${methodMatch[1]}`;addSymbol({name,kind:"method",exported:currentClass.exported&&!methodMatch[1].startsWith("_")&&methodMatch[1]!=="__init__",signature:`def ${methodMatch[1]}(${methodMatch[2].trim()})${methodMatch[3]?` -> ${methodMatch[3].trim()}`:""}`,line:i+1});continue}}if(line.startsWith(" ")||line.startsWith("\t"))continue;let fnMatch=line.match(/^(?:async\s+)?def\s+(\w+)\s*\(([^)]*)\)(?:\s*->\s*(.+?))?:/);if(fnMatch){let exported=isExplicitlyExported(fnMatch[1]);addSymbol({name:fnMatch[1],kind:"function",exported,signature:`def ${fnMatch[1]}(${fnMatch[2].trim()})${fnMatch[3]?` -> ${fnMatch[3].trim()}`:""}`,line:i+1})}let classMatch=line.match(/^class\s+(\w+)(?:\(([^)]*)\))?:/);if(classMatch){let exported=isExplicitlyExported(classMatch[1]);currentClass={name:classMatch[1],exported,indent},addSymbol({name:classMatch[1],kind:"class",exported,signature:`class ${classMatch[1]}${classMatch[2]?`(${classMatch[2].trim()})`:""}`,line:i+1})}let constMatch=line.match(/^([A-Z][A-Z0-9_]+)\s*[:=]/);if(constMatch)addSymbol({name:constMatch[1],kind:"const",exported:isExplicitlyExported(constMatch[1]),signature:line.trim().substring(0,100),line:i+1});let importMatch=line.match(/^from\s+[\w.]+\s+import\s+(.+?)(?:\s*#.*)?$/);if(importMatch&&(isPackageInit||explicitExports))for(let rawPart of importMatch[1].split(",")){let part=rawPart.trim();if(!part||part==="*")continue;let alias=part.match(/^(\w+)\s+as\s+(\w+)$/),importedName=alias?alias[1]:part,localName=alias?alias[2]:part;if(!/^\w+$/.test(importedName)||!/^\w+$/.test(localName))continue;let exported=isExplicitlyExported(localName);if(!exported&&explicitExports)continue;addSymbol({name:localName,kind:"variable",exported,signature:line.trim().substring(0,100),line:i+1})}}return symbols.sort((a,b)=>{if(a.line!==b.line)return a.line-b.line;return a.name.localeCompare(b.name)})}function extractRustSymbols(filePath,cwd){let content=readValidatedSourceFile(filePath,cwd);if(content===null)return[];let symbols=[],lines=content.split(`
|
|
@@ -3090,7 +3133,7 @@ Flags:
|
|
|
3090
3133
|
`){out+=ch,i++;continue}out+=text.slice(i,j+1),i=j+1;continue}out+=ch,i++}return out}function quoteRunLength(text,i){let n=0;while(text[i+n]==='"')n++;return n}function findClosingQuoteRun(text,from,delim,escapes){let j=from;while(j<text.length){if(escapes&&text[j]==="\\"){j+=2;continue}if(text[j]!=='"'){j++;continue}let runLen=quoteRunLength(text,j);if(runLen>=delim)return j+runLen-delim;j+=runLen}return-1}function matchVerbatimPrefix(text,i){if(text.startsWith('@"',i))return 2;if(text.startsWith('$@"',i)||text.startsWith('@$"',i))return 3;return 0}function sourceBoundaryForLanguage(language,content){if(language!=="java"&&language!=="kotlin"&&language!=="csharp")return null;let scanned=maskMultilineStringLiterals(content,language);if(language==="java"||language==="kotlin"){let pkg=scanned.match(/^[ \t]*package[ \t]+([A-Za-z_][\w.]*)[ \t]*;?/m);if(pkg?.[1])return pkg[1];return null}if(language==="csharp"){let ns=scanned.match(/^[ \t]*namespace[ \t]+([A-Za-z_][\w.]*)\s*[;{]/m);if(ns?.[1])return ns[1];return null}return null}function inferRoles(moduleName,content){let normalized=normalizeModuleName(moduleName).toLowerCase(),roles=new Set;if(/(^|\/)(__tests__|tests?)\//.test(normalized)||/\.(test|spec)\.[cm]?[jt]sx?$/.test(normalized))addRole(roles,"test_file");if(/(^|\/)(app\/api|pages\/api)\//.test(normalized)||/(^|\/)(routes?|controllers?)\//.test(normalized)||/\/route\.[cm]?[jt]sx?$/.test(normalized)||/\b(router|app|server)\s*\.\s*(get|post|put|patch|delete|all)\s*\(/i.test(content))addRole(roles,"api_route");if(/(^|\/)middleware\.[cm]?[jt]sx?$/.test(normalized))addRole(roles,"middleware");if(normalized.startsWith("src/tools/"))addRole(roles,"swarm_tool");if(normalized.startsWith("src/hooks/"))addRole(roles,"hook");if(normalized.startsWith("src/agents/"))addRole(roles,"agent");if(normalized.startsWith("src/cli/")||normalized.startsWith("src/commands/"))addRole(roles,"cli_command");if(normalized.startsWith("src/config/")||/(^|\/)(config|settings)\.[cm]?[jt]s$/.test(normalized))addRole(roles,"config");if(/(^|\/)(schema|schemas|types)\//.test(normalized)||/\b(z\.object|type\s+\w+\s*=|interface\s+\w+)/.test(content))addRole(roles,"schema");if(/(^|\/)(db|database|repositories?|models?|migrations?)\//.test(normalized)||/\b(prisma|drizzle|sequelize|knex|sqlite|sql`|db\.)/i.test(content))addRole(roles,"data_module");if(/(^|\/)(services?|lib|utils?)\//.test(normalized)||/\bexport\s+(async\s+)?function\b/.test(content))addRole(roles,"service_module");if(/\.(md|mdx|rst)$/.test(normalized))addRole(roles,"documentation");if(roles.size===0)addRole(roles,"source_module");return uniqueSorted(roles)}function pathRouteFromModule(moduleName){let parts=normalizeModuleName(moduleName).split("/"),appApi=parts.findIndex((part,index)=>{return part==="api"&&index>0&&parts[index-1]==="app"});if(appApi>=0)return`/${parts.slice(appApi).filter((part)=>!/^route\.[cm]?[jt]sx?$/.test(part)).map(routeSegment).join("/")}`.replace(/\/+/g,"/");let pagesApi=parts.findIndex((part,index)=>{return part==="api"&&index>0&&parts[index-1]==="pages"});if(pagesApi>=0){let last=parts[parts.length-1]?.replace(/\.[^.]+$/,"");return`/${[...parts.slice(pagesApi,-1),last].filter(Boolean).map(routeSegment).join("/")}`.replace(/\/+/g,"/")}return null}function routeSegment(segment){return segment.replace(/^\[(\.\.\.)?(.+)]$/,(_m,rest,name)=>rest?`:${name}*`:`:${name}`).replace(/\.[^.]+$/,"")}function extractRoutes(moduleName,content){let routes=[],pathRoute=pathRouteFromModule(moduleName),lines=content.split(/\r?\n/);for(let i=0;i<lines.length;i++){let line=lines[i];for(let method of HTTP_METHODS){let exportPattern=new RegExp(`\\bexport\\s+(?:async\\s+)?(?:function|const)\\s+${method}\\b`);if(pathRoute&&exportPattern.test(line))routes.push({method,path:pathRoute,line:i+1,source:"handler_export"})}let routerMatch=line.match(/\b(?:router|app|server)\s*\.\s*(get|post|put|patch|delete|options|head|all)\s*\(\s*['"`]([^'"`\0\r\n]+)['"`]/i);if(routerMatch)routes.push({method:routerMatch[1].toUpperCase(),path:routerMatch[2],line:i+1,source:"router_call"})}if(pathRoute&&routes.length===0)routes.push({method:"ALL",path:pathRoute,source:"file_path"});return routes.slice(0,MAX_FACTS_PER_KIND)}function classifyDataOperation(line){let trimmed=line.trim(),lower=trimmed.toLowerCase(),evidence2=trimmed.slice(0,160),operation=null,access5="unknown",entity;if(/\b(transaction|begintransaction|commit|rollback)\b/i.test(trimmed))operation="transaction",access5="database";if(/\b(migrate|migration|schema\.alter|createTable|dropTable)\b/i.test(trimmed))operation="migration",access5="database";if(/\b(findMany|findUnique|findFirst|select|query|count|aggregate)\b/.test(trimmed))operation??="read";if(/\b(create|insert|update|upsert|save|patch)\b/.test(trimmed))operation??="write";if(/\b(delete|deleteMany|remove|destroy)\b/.test(trimmed))operation="delete";if(/\b(sql`|\bselect\b|\binsert\b|\bupdate\b|\bdelete\b|\bfrom\b)/i.test(trimmed))access5="sql";if(/\b(prisma|drizzle|sequelize|knex|db\.|database\.|repository\.)/i.test(trimmed))access5=access5==="sql"?"sql":"orm";if(/\b(readFile|writeFile|appendFile|rmSync|unlink)\b/.test(trimmed))access5="filesystem",operation??=lower.includes("read")?"read":"write";if(/\b(fetch|axios|http\.|https\.)\b/.test(trimmed))access5="network",operation??="read";let entityMatch=trimmed.match(/\b(?:prisma|db|database)\.(\w+)/i);if(entityMatch)entity=entityMatch[1];if(!operation)return null;return{operation,access:access5,entity,line:0,evidence:evidence2}}function extractDataOperations(content){let facts=[],lines=content.split(/\r?\n/);for(let i=0;i<lines.length;i++){let fact=classifyDataOperation(lines[i]);if(!fact)continue;if(fact.line=i+1,facts.push(fact),facts.length>=MAX_FACTS_PER_KIND)break}return facts}function extractSecurityFacts(content){let facts=[],lines=content.split(/\r?\n/),push=(kind,line,evidence2,confidence)=>{facts.push({kind,line,evidence:evidence2.trim().slice(0,160),confidence})};for(let i=0;i<lines.length&&facts.length<MAX_FACTS_PER_KIND;i++){let line=lines[i];if(/\b(requireAuth|requireUser|getServerSession|currentUser|verifyToken|jwt|isAuthenticated|ctx\.user|session)\b/i.test(line))push("authentication",i+1,line,"high");if(/\b(requireRole|hasPermission|authorize|authorization|isAdmin|rbac|policy\.check|can\()\b/i.test(line))push("authorization",i+1,line,"high");if(/\b(z\.object|safeParse|\.parse\(|joi\.|yup\.|validate\w*)\b/i.test(line))push("input_validation",i+1,line,"high");if(/\b(csrf|csrfToken|sameSite)\b/i.test(line))push("csrf",i+1,line,"medium");if(/\b(sanitize|escapeHtml|DOMPurify|xss)\b/i.test(line))push("sanitization",i+1,line,"medium");if(/\b(secret|api[_-]?key|token|password)\b/i.test(line))push("secret_handling",i+1,line,"low")}return facts}function extractConventions(moduleName,roles,routes){let conventions=[];if(roles.includes("test_file"))conventions.push({name:"test_file_naming",evidence:`${path159.basename(moduleName)} matches test/spec naming`});if(routes.some((route)=>route.source==="handler_export"))conventions.push({name:"next_app_route_handler",evidence:"HTTP method exports map to route handlers"});if(roles.includes("swarm_tool"))conventions.push({name:"swarm_tool_module",evidence:"module lives under src/tools"});if(roles.includes("hook"))conventions.push({name:"hook_module",evidence:"module lives under src/hooks"});return conventions}function buildFindings(roles,routes,dataOperations,security){let findings=[],hasAuth=security.some((fact)=>fact.kind==="authentication"||fact.kind==="authorization"||fact.kind==="csrf"),hasValidation=security.some((fact)=>fact.kind==="input_validation"||fact.kind==="sanitization"),mutatingRoute=routes.some((route)=>["POST","PUT","PATCH","DELETE","ALL"].includes(route.method)),writes=dataOperations.filter((fact)=>["write","delete","migration"].includes(fact.operation)),hasTransaction=dataOperations.some((fact)=>fact.operation==="transaction");if(roles.includes("api_route")&&routes.length>0&&!hasAuth)findings.push({code:"api_route_without_detected_auth",severity:"medium",message:"No authentication, authorization, or CSRF guard was detected near this route.",line:routes[0]?.line});if(mutatingRoute&&!hasValidation)findings.push({code:"mutating_route_without_detected_validation",severity:"medium",message:"Route appears to mutate state without a detected validation or sanitization fact.",line:routes.find((route)=>["POST","PUT","PATCH","DELETE","ALL"].includes(route.method))?.line});if(writes.length>1&&!hasTransaction)findings.push({code:"multiple_writes_without_detected_transaction",severity:"low",message:"Multiple write/delete operations were detected without a transaction fact.",line:writes[0]?.line});return findings}function extractFileOntology(input){let moduleName=normalizeModuleName(input.moduleName),content=stripComments(input.content),roles=inferRoles(moduleName,content),routes=extractRoutes(moduleName,content),dataOperations=extractDataOperations(content),security=extractSecurityFacts(content),conventions=extractConventions(moduleName,roles,routes),findings=buildFindings(roles,routes,dataOperations,security);return{roles,packageBoundary:sourceBoundaryForLanguage(input.language,content)??boundaryForModule(moduleName,input.hasManifest),routes,dataOperations,security,conventions,findings}}var HTTP_METHODS,MAX_FACTS_PER_KIND=50,blankKeepingNewlines=(m)=>m.replace(/[^\n]/g," ");var init_ontology=__esm(()=>{init_types3();HTTP_METHODS=["GET","POST","PUT","PATCH","DELETE","OPTIONS","HEAD"]});import{realpathSync as realpathSync26}from"node:fs";function safeRealpathSync(targetPath,fallback,realpathResolver=realpathSync26){try{return realpathResolver(targetPath)}catch(error93){if(error93 instanceof Error&&error93.code==="ENOENT")return fallback;return null}}var init_safe_realpath=()=>{};function validateWorkspace(workspace){if(!workspace||typeof workspace!=="string"||workspace.trim()==="")throw Error("Invalid workspace: must be a non-empty string");if(containsControlChars(workspace))throw Error("Invalid workspace: control characters detected");if(containsPathTraversal(workspace))throw Error("Invalid workspace: path traversal detected")}function validateGraphNode(node){if(!node||typeof node!=="object")throw Error("Invalid node: must be an object");if(!node.filePath||typeof node.filePath!=="string")throw Error("Invalid node: filePath is required");if(!node.filePath.startsWith("/")&&!/^[A-Za-z]:[/\\]/.test(node.filePath))throw Error("Invalid node: filePath must be absolute");if(containsPathTraversal(node.filePath))throw Error("Invalid node: filePath contains path traversal");if(containsControlChars(node.filePath))throw Error("Invalid node: filePath contains control characters");if(!node.moduleName||typeof node.moduleName!=="string")throw Error("Invalid node: moduleName is required");if(node.moduleName.startsWith("/")||node.moduleName.startsWith("\\")||/^[A-Za-z]:[/\\]/.test(node.moduleName))throw Error("Invalid node: moduleName must be relative");if(containsPathTraversal(node.moduleName))throw Error("Invalid node: moduleName contains path traversal");if(containsControlChars(node.moduleName))throw Error("Invalid node: moduleName contains control characters");if(typeof node.language!=="string")throw Error("Invalid node: language is required");if(typeof node.mtime!=="string")throw Error("Invalid node: mtime is required");if(node.sizeBytes===void 0!==(node.mtimeMs===void 0))throw Error("Invalid node: sizeBytes and mtimeMs must either both be present or both be absent");if(node.sizeBytes!==void 0&&(typeof node.sizeBytes!=="number"||!Number.isFinite(node.sizeBytes)||node.sizeBytes<0))throw Error("Invalid node: sizeBytes must be a finite non-negative number");if(node.mtimeMs!==void 0&&(typeof node.mtimeMs!=="number"||!Number.isFinite(node.mtimeMs)||node.mtimeMs<0))throw Error("Invalid node: mtimeMs must be a finite non-negative number");if(!Array.isArray(node.exports))throw Error("Invalid node: exports must be an array");for(let exp of node.exports){if(typeof exp!=="string")throw Error("Invalid node: exports must be an array of strings");if(containsControlChars(exp)){let preview=exp.slice(0,120);throw Error(`Invalid node: exports contains control characters (file=${node.filePath}, value="${preview}")`)}}if(!Array.isArray(node.imports))throw Error("Invalid node: imports must be an array");for(let imp of node.imports){if(typeof imp!=="string")throw Error("Invalid node: imports must be an array of strings");if(containsControlChars(imp)){let preview=imp.slice(0,120);throw Error(`Invalid node: imports contains control characters (file=${node.filePath}, value="${preview}")`)}}if(node.exportLines!==void 0){if(typeof node.exportLines!=="object"||node.exportLines===null||Array.isArray(node.exportLines))throw Error("Invalid node: exportLines must be an object");for(let[name,line]of Object.entries(node.exportLines)){if(containsControlChars(name))throw Error("Invalid node: exportLines key contains control characters");if(typeof line!=="number"||!Number.isFinite(line)||line<0)throw Error("Invalid node: exportLines values must be non-negative numbers")}}if(node.exportRanges!==void 0){if(typeof node.exportRanges!=="object"||node.exportRanges===null||Array.isArray(node.exportRanges))throw Error("Invalid node: exportRanges must be an object");for(let[name,range]of Object.entries(node.exportRanges)){if(containsControlChars(name))throw Error("Invalid node: exportRanges key contains control characters");if(typeof range!=="object"||range===null||Array.isArray(range))throw Error("Invalid node: exportRanges values must be objects");let r=range;if(typeof r.startLine!=="number"||!Number.isFinite(r.startLine)||!Number.isInteger(r.startLine)||r.startLine<1||typeof r.endLine!=="number"||!Number.isFinite(r.endLine)||!Number.isInteger(r.endLine)||r.endLine<1)throw Error("Invalid node: exportRanges value must have positive integer startLine and endLine (1-based)");if(r.startLine>r.endLine)throw Error("Invalid node: exportRanges value must have startLine <= endLine")}}if(node.ontology!==void 0)validateOntologyStrings(node)}function validateOntologyStrings(node){let ontology=node.ontology;if(!ontology||typeof ontology!=="object")throw Error("Invalid node: ontology must be an object");let values=[...ontology.roles??[],ontology.packageBoundary,...(ontology.routes??[]).flatMap((route)=>[route.method,route.path,route.source]),...(ontology.dataOperations??[]).flatMap((fact)=>[fact.operation,fact.access,fact.entity??"",fact.evidence]),...(ontology.security??[]).flatMap((fact)=>[fact.kind,fact.evidence,fact.confidence]),...(ontology.conventions??[]).flatMap((fact)=>[fact.name,fact.evidence]),...(ontology.findings??[]).flatMap((finding)=>[finding.code,finding.severity,finding.message])];for(let value of values){if(typeof value!=="string")throw Error("Invalid node: ontology contains non-string value");if(containsControlChars(value)){let preview=value.slice(0,120);throw Error(`Invalid node: ontology contains control characters (file=${node.filePath}, value="${preview}")`)}}for(let role of ontology.roles??[])validateAllowedOntologyValue(node,"ontology.roles",role,FILE_ROLE_SET);for(let route of ontology.routes??[])validateAllowedOntologyValue(node,"ontology.routes.method",route.method,ROUTE_METHOD_SET),validateAllowedOntologyValue(node,"ontology.routes.source",route.source,ROUTE_SOURCE_SET);for(let fact of ontology.dataOperations??[])validateAllowedOntologyValue(node,"ontology.dataOperations.operation",fact.operation,DATA_OPERATION_SET),validateAllowedOntologyValue(node,"ontology.dataOperations.access",fact.access,DATA_ACCESS_SET);for(let fact of ontology.security??[])validateAllowedOntologyValue(node,"ontology.security.kind",fact.kind,SECURITY_KIND_SET),validateAllowedOntologyValue(node,"ontology.security.confidence",fact.confidence,SECURITY_CONFIDENCE_SET);for(let finding of ontology.findings??[])validateOntologyName(node,"ontology.findings.code",finding.code),validateAllowedOntologyValue(node,"ontology.findings.severity",finding.severity,ONTOLOGY_FINDING_SEVERITY_SET)}function validateOntologyName(node,field,value){if(ONTOLOGY_NAME_PATTERN.test(value))return;let preview=value.slice(0,120);throw Error(`Invalid node: ${field} must be lower_snake_case (file=${node.filePath}, value="${preview}")`)}function validateAllowedOntologyValue(node,field,value,allowed){if(allowed.has(value))return;let preview=value.slice(0,120);throw Error(`Invalid node: ${field} contains invalid value (file=${node.filePath}, value="${preview}")`)}function validateGraphEdge(edge){if(!edge||typeof edge!=="object")throw Error("Invalid edge: must be an object");if(!edge.source||typeof edge.source!=="string")throw Error("Invalid edge: source is required");if(!edge.target||typeof edge.target!=="string")throw Error("Invalid edge: target is required");if(containsPathTraversal(edge.source)||containsPathTraversal(edge.target))throw Error("Invalid edge: path traversal detected");if(containsControlChars(edge.source)||containsControlChars(edge.target))throw Error("Invalid edge: control characters detected");if(!edge.importSpecifier||typeof edge.importSpecifier!=="string")throw Error("Invalid edge: importSpecifier is required");if(containsControlChars(edge.importSpecifier))throw Error("Invalid edge: importSpecifier contains control characters");if(!IMPORT_TYPE_SET.has(edge.importType))throw Error("Invalid edge: importType is invalid");if(edge.importedSymbols!==void 0){if(!Array.isArray(edge.importedSymbols))throw Error("Invalid edge: importedSymbols must be an array");for(let symbol3 of edge.importedSymbols){if(typeof symbol3!=="string")throw Error("Invalid edge: importedSymbols must be an array of strings");if(containsControlChars(symbol3))throw Error("Invalid edge: importedSymbols contains control characters")}}if(edge.usedSymbols!==void 0){if(!Array.isArray(edge.usedSymbols))throw Error("Invalid edge: usedSymbols must be an array");for(let symbol3 of edge.usedSymbols){if(typeof symbol3!=="string")throw Error("Invalid edge: usedSymbols must be an array of strings");if(containsControlChars(symbol3))throw Error("Invalid edge: usedSymbols contains control characters")}}if(edge.targetKind!==void 0&&edge.targetKind!=="node"&&edge.targetKind!=="asset")throw Error('Invalid edge: targetKind must be "node" or "asset"')}var FILE_ROLE_SET,ROUTE_METHOD_SET,ROUTE_SOURCE_SET,DATA_OPERATION_SET,DATA_ACCESS_SET,SECURITY_KIND_SET,SECURITY_CONFIDENCE_SET,ONTOLOGY_FINDING_SEVERITY_SET,IMPORT_TYPE_SET,ONTOLOGY_NAME_PATTERN;var init_validation=__esm(()=>{init_path_security();init_types3();FILE_ROLE_SET=new Set(FILE_ROLE_VALUES),ROUTE_METHOD_SET=new Set(ROUTE_METHOD_VALUES),ROUTE_SOURCE_SET=new Set(ROUTE_SOURCE_VALUES),DATA_OPERATION_SET=new Set(DATA_OPERATION_VALUES),DATA_ACCESS_SET=new Set(DATA_ACCESS_VALUES),SECURITY_KIND_SET=new Set(SECURITY_KIND_VALUES),SECURITY_CONFIDENCE_SET=new Set(SECURITY_CONFIDENCE_VALUES),ONTOLOGY_FINDING_SEVERITY_SET=new Set(ONTOLOGY_FINDING_SEVERITY_VALUES),IMPORT_TYPE_SET=new Set(IMPORT_TYPE_VALUES),ONTOLOGY_NAME_PATTERN=/^[a-z][a-z0-9_]*$/});import*as fsSync11 from"node:fs";import{existsSync as existsSync80,realpathSync as realpathSync27}from"node:fs";import*as fsPromises6 from"node:fs/promises";import*as os27 from"node:os";import*as path160 from"node:path";function resolveSkipDirectories(excludeDirs){let extras=excludeDirs?.filter((d)=>d.length>0)??[];if(extras.length===0)return SKIP_DIRECTORIES2;return new Set([...SKIP_DIRECTORIES2,...extras])}function isScannableSourcePath(p){return SUPPORTED_EXTENSIONS.has(path160.extname(p).toLowerCase())}function isAssetEdge(edge){if(edge.targetKind==="asset")return!0;if(edge.targetKind==="node")return!1;return!isScannableSourcePath(edge.target)}function upsertNode(graph,node){validateGraphNode(node);let key=normalizeGraphPath(node.filePath);graph.nodes[key]=node,updateGraphMetadata(graph)}function addEdge(graph,edge){if(validateGraphEdge(edge),!graph.edges.some((e)=>e.source===edge.source&&e.target===edge.target&&e.importSpecifier===edge.importSpecifier))graph.edges.push(edge),updateGraphMetadata(graph)}function buildLoopEdgeKey(edge){return`${edge.source}\x00${edge.target}\x00${edge.importSpecifier}`}function appendNodeFast(graph,node){validateGraphNode(node),graph.nodes[normalizeGraphPath(node.filePath)]=node}function appendEdgeFast(graph,edge,seenEdgeKeys){validateGraphEdge(edge);let key=buildLoopEdgeKey(edge);if(seenEdgeKeys.has(key))return;seenEdgeKeys.add(key),graph.edges.push(edge)}function isJvmParentProbeLanguage(sourceFile){let ext=path160.extname(sourceFile).toLowerCase();return ext===".java"||ext===".kt"||ext===".kts"}function jvmDotnetSiblingExtensions(sourceFile){switch(path160.extname(sourceFile).toLowerCase()){case".java":return[".java"];case".kt":case".kts":return[".kt",".kts"];case".cs":case".csx":return[".cs",".csx"];default:return[]}}function firstSourceFileIn(directory,extensions){try{if(!fsSync11.statSync(directory).isDirectory())return null;let matching=fsSync11.readdirSync(directory).filter((entry)=>extensions.some((ext)=>entry.toLowerCase().endsWith(ext))).sort(),nonTest=matching.filter((entry)=>!JVM_DOTNET_TEST_FILE_RE.test(entry)),entries=nonTest.length>0?nonTest:matching,preferred=entries.find((entry)=>path160.basename(entry,path160.extname(entry)).toLowerCase()===path160.basename(directory).toLowerCase());for(let entry of preferred?[preferred,...entries]:entries){let candidate=path160.join(directory,entry);try{if(fsSync11.statSync(candidate).isFile())return candidate}catch{}}return null}catch{return null}}function findDottedModuleCandidate(workspaceRoot,sourceFile,specifier){if(!/^[A-Za-z_][\w.]*(?:\.\*)?$/.test(specifier))return null;let extensions=jvmDotnetSiblingExtensions(sourceFile);if(extensions.length===0)return null;let isWildcard=specifier.endsWith(".*"),parts=specifier.replace(/\.\*$/,"").split(".").filter(Boolean);if(parts.length===0)return null;let full=parts.join(path160.sep),parent=!isWildcard&&parts.length>1?parts.slice(0,-1).join(path160.sep):null;for(let rootPrefix of JVM_DOTNET_DOTTED_ROOTS){let fullBase=path160.join(workspaceRoot,rootPrefix,full);for(let ext of extensions)if(existsSync80(fullBase+ext))return fullBase+ext}for(let rootPrefix of JVM_DOTNET_DOTTED_ROOTS){let inPackage=firstSourceFileIn(path160.join(workspaceRoot,rootPrefix,full),extensions);if(inPackage)return inPackage}if(parent===null||!isJvmParentProbeLanguage(sourceFile))return null;for(let rootPrefix of JVM_DOTNET_DOTTED_ROOTS){let parentBase=path160.join(workspaceRoot,rootPrefix,parent);for(let ext of extensions)if(existsSync80(parentBase+ext))return parentBase+ext}return null}function resolveModuleSpecifier(workspaceRoot,sourceFile,specifier){if(containsControlChars(specifier))return null;if(specifier.startsWith("/")||specifier.startsWith("\\"))return null;if(/^[A-Za-z]:[/\\]/.test(specifier))return null;if(specifier.startsWith("http://")||specifier.startsWith("https://"))return null;try{let normalizedSpecifier=specifier,rustParts=specifier.split("::").filter(Boolean);if(rustParts[0]==="crate"){let target=path160.join(workspaceRoot,...rustParts.slice(1));if(!(existsSync80(target)||existsSync80(`${target}.rs`)||existsSync80(path160.join(target,"mod.rs"))))target=path160.join(path160.dirname(sourceFile),...rustParts.slice(1));if(normalizedSpecifier=path160.relative(path160.dirname(sourceFile),target).replace(/\\/g,"/"),!normalizedSpecifier.startsWith("."))normalizedSpecifier=`./${normalizedSpecifier}`}else if(rustParts[0]==="self")normalizedSpecifier=`./${rustParts.slice(1).join("/")}`;else if(rustParts[0]==="super"){let superCount=0;while(rustParts[superCount]==="super")superCount++;normalizedSpecifier=`${"../".repeat(superCount)}${rustParts.slice(superCount).join("/")}`}else{let dottedTarget=findDottedModuleCandidate(workspaceRoot,sourceFile,normalizedSpecifier);if(dottedTarget!==null){if(normalizedSpecifier=path160.relative(path160.dirname(sourceFile),dottedTarget).replace(/\\/g,"/"),!normalizedSpecifier.startsWith("."))normalizedSpecifier=`./${normalizedSpecifier}`}}if(normalizedSpecifier.startsWith(".")){let sourceDir=path160.dirname(sourceFile),resolved=path160.resolve(sourceDir,normalizedSpecifier),initialRealResolved=_internals125.safeRealpathSync(resolved,resolved);if(initialRealResolved===null)return null;let realResolved=initialRealResolved,realRoot=_internals125.safeRealpathSync(workspaceRoot,path160.normalize(workspaceRoot));if(realRoot===null)return null;let findDirectoryEntry=(directory)=>{for(let initName of["__init__.py","__init__.pyw","mod.rs"]){let candidate=path160.join(directory,initName);if(existsSync80(candidate))return candidate}if(path160.extname(sourceFile).toLowerCase()===".go"){let basenameCandidate=path160.join(directory,`${path160.basename(directory)}.go`);if(existsSync80(basenameCandidate))return basenameCandidate;try{let firstGo=fsSync11.readdirSync(directory).filter((entry)=>entry.endsWith(".go")&&!entry.endsWith("_test.go")).sort((a,b)=>a.localeCompare(b))[0];if(firstGo)return path160.join(directory,firstGo)}catch{return null}}return null};if(existsSync80(resolved))try{if(fsSync11.statSync(resolved).isDirectory()){let found=findDirectoryEntry(resolved);if(!found)return null;let foundRealPath=_internals125.safeRealpathSync(found,found);if(foundRealPath===null)return null;realResolved=foundRealPath,resolved=found}}catch{return null}if(!existsSync80(resolved)){let EXTENSIONS=path160.extname(sourceFile).toLowerCase()===".pyw"?[".pyw",".py",".rs",".go",".ts",".tsx",".js",".jsx",".mjs",".cjs",".json"]:[".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".pyw",".rs",".go",".json"],found=null;for(let ext of EXTENSIONS){let candidate=resolved+ext;if(existsSync80(candidate)){found=candidate;break}}if(!found)found=findDirectoryEntry(resolved);if(found){let foundRealPath=_internals125.safeRealpathSync(found,found);if(foundRealPath===null)return null;realResolved=foundRealPath,resolved=found}else return null}let normalizedResolved=path160.normalize(realResolved),normalizedRoot=path160.normalize(realRoot);if(!normalizedResolved.startsWith(normalizedRoot+path160.sep)&&normalizedResolved!==normalizedRoot)return null;return resolved}return null}catch{return null}}function isRefusedWorkspaceRoot(target){let resolved;try{resolved=realpathSync27(target)}catch{resolved=path160.resolve(target)}let refused=new Set,add2=(p)=>{if(typeof p==="string"&&p.length>0)refused.add(path160.resolve(p))};if(add2(os27.homedir()),add2(os27.tmpdir()),add2("/"),add2("/Users"),add2("/home"),add2("/root"),process.platform==="win32")add2("C:\\"),add2("C:\\Users");return refused.has(resolved)}function createEmptyDiagnostics(){return{extractionFailures:[],unresolvedImports:[],oversizedFiles:[],unsupportedFiles:[],binaryFiles:[],unreadableFiles:[],validationSkippedFiles:[],extractorInputWitnesses:[],lowConfidenceEdgeCount:0,walkTruncated:!1,incrementalFallbacks:0}}function diagnosticsHaveEntries(diagnostics){return(diagnostics.extractionFailures?.length??0)>0||(diagnostics.unresolvedImports?.length??0)>0||(diagnostics.oversizedFiles?.length??0)>0||(diagnostics.unsupportedFiles?.length??0)>0||(diagnostics.binaryFiles?.length??0)>0||(diagnostics.unreadableFiles?.length??0)>0||(diagnostics.validationSkippedFiles?.length??0)>0||(diagnostics.extractorInputWitnesses?.length??0)>0||(diagnostics.lowConfidenceEdgeCount??0)>0||diagnostics.walkTruncated===!0||diagnostics.walkTruncationReason!==void 0||(diagnostics.incrementalFallbacks??0)>0}function pushCapped(target,value){if(target.length<MAX_DIAGNOSTIC_ENTRIES)target.push(value)}function pushInputWitness(target,value){if(target.length<MAX_EXTRACTOR_INPUT_WITNESSES)target.push(value)}function mergeDiagnostics(target,source){if(!source)return;for(let entry of source.extractionFailures??[])pushCapped(target.extractionFailures,entry);for(let entry of source.unresolvedImports??[])pushCapped(target.unresolvedImports,entry);for(let entry of source.oversizedFiles??[])pushCapped(target.oversizedFiles,entry);for(let entry of source.unsupportedFiles??[])pushCapped(target.unsupportedFiles,entry);for(let entry of source.binaryFiles??[])pushCapped(target.binaryFiles,entry);for(let entry of source.unreadableFiles??[])pushCapped(target.unreadableFiles,entry);for(let entry of source.validationSkippedFiles??[])pushCapped(target.validationSkippedFiles,entry);for(let entry of source.extractorInputWitnesses??[])pushInputWitness(target.extractorInputWitnesses,entry);target.lowConfidenceEdgeCount+=source.lowConfidenceEdgeCount??0,target.incrementalFallbacks+=source.incrementalFallbacks??0}function isRelativeImportSpecifier(specifier){return specifier==="."||specifier===".."||specifier.startsWith("./")||specifier.startsWith("../")}function unresolvedRelativeImportsFor(parsedImports,filePath,absoluteRoot){let unresolved=[],moduleName=toModuleName(filePath,absoluteRoot);for(let parsed of parsedImports){if(!isRelativeImportSpecifier(parsed.specifier))continue;if(resolveModuleSpecifier(absoluteRoot,filePath,parsed.specifier)===null)unresolved.push({file:moduleName,specifier:parsed.specifier})}return unresolved}function stripComments2(content){let out="",i=0,n=content.length,state="code",prevSignificant="",regexInClass=!1;while(i<n){let ch=content[i],next=i+1<n?content[i+1]:"";switch(state){case"code":if(ch==="/"&&next==="/")state="line",i+=2;else if(ch==="/"&&next==="*")state="block",i+=2;else if(ch==="/"&®EX_ALLOWED_AFTER.has(prevSignificant))state="regex",regexInClass=!1,out+=ch,i+=1;else{if(ch==="'")state="single";else if(ch==='"')state="double";else if(ch==="`")state="template";if(out+=ch,ch.trim()!=="")prevSignificant=ch;i+=1}break;case"single":case"double":case"template":{let quote=state==="single"?"'":state==="double"?'"':"`";if(ch==="\\")out+=ch+next,i+=2;else{if(ch===quote)state="code",prevSignificant=quote;out+=ch,i+=1}break}case"regex":if(ch==="\\")out+=ch+next,i+=2;else if(ch===`
|
|
3091
3134
|
`)state="code",out+=ch,i+=1;else{if(ch==="[")regexInClass=!0;else if(ch==="]")regexInClass=!1;else if(ch==="/"&&!regexInClass)state="code",prevSignificant="/";out+=ch,i+=1}break;case"line":if(ch===`
|
|
3092
3135
|
`)state="code",out+=ch;i+=1;break;case"block":if(ch==="*"&&next==="/")state="code",i+=2;else{if(ch===`
|
|
3093
|
-
`)out+=ch;i+=1}break}}return out}function parseFileImports(rawContent,sourceFile,workspaceRoot){let ext=sourceFile?path160.extname(sourceFile).toLowerCase():"";if(ext===".py"||ext===".pyw")return parsePythonFileImports(rawContent,sourceFile);if(ext===".rs")return parseRustFileImports(rawContent,sourceFile,workspaceRoot);if(ext===".go")return parseGoFileImports(rawContent);if(ext===".java")return parseJavaFileImports(rawContent);if(ext===".kt"||ext===".kts")return parseKotlinFileImports(rawContent);if(ext===".cs"||ext===".csx")return parseCSharpFileImports(rawContent);let imports=[],content=stripComments2(rawContent),importRegex=/import\s+(?:\{[\s\S]*?\}|(?:\*\s+as\s+\w+)|\w+)\s+from\s+['"`]([^'"`\0\t\r\n]+)['"`]|import\s+['"`]([^'"`\0\t\r\n]+)['"`]|require\s*\(\s*['"`]([^'"`\0\t\r\n]+)['"`]\s*\)|export\s*\{[^}]*\}\s*from\s+['"`]([^'"`\0\t\r\n]+)['"`]|export\s+\*(?:\s+as\s+\w+)?\s+from\s+['"`]([^'"`\0\t\r\n]+)['"`]|import\s*\(\s*['"`]([^'"`\0\t\r\n]+)['"`]\s*\)/g;for(let match of content.matchAll(importRegex)){let modulePath=match[1]||match[2]||match[3]||match[4]||match[5]||match[6];if(!modulePath)continue;if(containsControlChars(modulePath))continue;let matchedString=match[0],importType="named";if(matchedString.includes("* as"))importType="namespace";else if(/^import\s*\(/.test(matchedString))importType="sideeffect";else if(/^export\s*\{/.test(matchedString))importType="named";else if(/^export\s+\*/.test(matchedString))importType="namespace";else if(/^import\s+\{/.test(matchedString))importType="named";else if(/^import\s+\w+\s+from\s+['"`]/.test(matchedString))importType="default";else if(/^import\s+['"`]/m.test(matchedString))importType="sideeffect";else if(matchedString.includes("require("))importType="require";imports.push({specifier:modulePath,importType,importedSymbols:parseImportedSymbols(matchedString,importType),bindings:parseImportBindings(matchedString,importType),reExport:/^\s*export\b/.test(matchedString)})}return imports}function makeParsedImport(specifier,importType,bindings,reExport=!1){if(!specifier||containsControlChars(specifier))return null;return{specifier,importType,importedSymbols:bindings.map((binding)=>binding.imported),bindings,reExport}}function finalDottedSegment2(value){let parts=value.split(".").filter(Boolean);return parts[parts.length-1]??value}function parseJavaFileImports(rawContent){let imports=[],content=maskMultilineStringLiterals(stripComments2(rawContent),"java"),re=/^[ \t]*import[ \t]+(static[ \t]+)?([A-Za-z_][\w.]*(?:\.\*)?)[ \t]*;?[ \t]*\r?$/gm;for(let m=re.exec(content);m!==null;m=re.exec(content)){let isStatic=Boolean(m[1]),raw=m[2];if(raw.endsWith(".*")){let parsed2=makeParsedImport(raw,"namespace",[]);if(parsed2)imports.push(parsed2);continue}let imported=finalDottedSegment2(raw),specifier=isStatic?raw.split(".").slice(0,-1).join("."):raw,parsed=makeParsedImport(specifier,"named",[{imported,local:imported}]);if(parsed)imports.push(parsed)}return imports}function parseKotlinFileImports(rawContent){let imports=[],content=stripComments2(rawContent),re=/^[ \t]*import[ \t]+([A-Za-z_][\w.]*(?:\.\*)?)(?:[ \t]+as[ \t]+([A-Za-z_]\w*))?[ \t]*;?[ \t]*\r?$/gm;for(let m=re.exec(content);m!==null;m=re.exec(content)){let raw=m[1],alias=m[2];if(raw.endsWith(".*")){let parsed2=makeParsedImport(raw,"namespace",[]);if(parsed2)imports.push(parsed2);continue}let imported=finalDottedSegment2(raw),parsed=makeParsedImport(raw,"named",[{imported,local:alias??imported}]);if(parsed)imports.push(parsed)}return imports}function parseCSharpFileImports(rawContent){let imports=[],content=stripComments2(rawContent),re=/^[ \t]*(?:global[ \t]+)?using[ \t]+(static[ \t]+)?(?:([A-Za-z_]\w*)[ \t]*=[ \t]*)?([A-Za-z_][\w.]*)[ \t]*;[ \t]*\r?$/gm;for(let m=re.exec(content);m!==null;m=re.exec(content)){let alias=m[2],specifier=m[3],parsed=alias?makeParsedImport(specifier,"named",[{imported:finalDottedSegment2(specifier),local:alias}]):makeParsedImport(specifier,"namespace",[]);if(parsed)imports.push(parsed)}return imports}function parsePythonFileImports(rawContent,sourceFile){let imports=[],isPackageInit=sourceFile?["__init__.py","__init__.pyw"].includes(path160.basename(sourceFile)):!1;for(let line of rawContent.split(/\r?\n/)){let trimmed=line.trim();if(!trimmed||trimmed.startsWith("#"))continue;let fullImport=trimmed.match(/^import\s+(.+?)(?:\s*#.*)?$/);if(fullImport){for(let rawPart of fullImport[1].split(",")){let part=rawPart.trim();if(!part)continue;let alias=part.match(/^([\w.]+)\s+as\s+(\w+)$/),specifier=alias?alias[1]:part,local=alias?alias[2]:specifier.split(".")[0];if(!/^\w+$/.test(local))continue;let parsed2=makeParsedImport(specifier,"namespace",[{imported:specifier,local}]);if(parsed2)imports.push(parsed2)}continue}let fromImport=trimmed.match(/^from\s+(\S+)\s+import\s+(.+?)(?:\s*#.*)?$/);if(!fromImport)continue;if(fromImport[2].trim()==="*"){let parsed2=makeParsedImport(normalizePythonModuleSpecifier2(fromImport[1]),"namespace",[],isPackageInit);if(parsed2)imports.push(parsed2);continue}let bindings=[];for(let rawPart of fromImport[2].split(",")){let part=rawPart.trim();if(!part)continue;let alias=part.match(/^(\w+)\s+as\s+(\w+)$/);if(alias)bindings.push({imported:alias[1],local:alias[2]});else if(/^\w+$/.test(part))bindings.push({imported:part,local:part})}let parsed=makeParsedImport(normalizePythonModuleSpecifier2(fromImport[1]),"named",bindings,isPackageInit);if(parsed)imports.push(parsed)}return imports}function normalizePythonModuleSpecifier2(specifier){let leadingDots=specifier.match(/^\.+/)?.[0].length??0;if(leadingDots===0)return specifier;let rest=specifier.slice(leadingDots).replace(/\./g,"/");return`${leadingDots===1?"./":"../".repeat(leadingDots-1)}${rest}`}function rustModulePathToSpecifier(modulePath,sourceFile,workspaceRoot){let parts=modulePath.split("::").filter(Boolean);if(parts.length===0)return modulePath;if(parts[0]==="self")return`./${parts.slice(1).join("/")}`;if(parts[0]==="super"){let superCount=0;while(parts[superCount]==="super")superCount++;return`${"../".repeat(superCount)}${parts.slice(superCount).join("/")}`}if(parts[0]==="crate"&&sourceFile&&workspaceRoot){let target=path160.join(workspaceRoot,...parts.slice(1)),relative36=path160.relative(path160.dirname(sourceFile),target).replace(/\\/g,"/");if(!relative36.startsWith("."))relative36=`./${relative36}`;return relative36}return modulePath}function parseRustFileImports(rawContent,sourceFile,workspaceRoot){let imports=[];for(let line of rawContent.split(/\r?\n/)){let trimmed=line.trim();if(!trimmed.startsWith("use "))continue;let grouped=trimmed.match(/^use\s+(.+?)::\{(.+)\}\s*;?\s*$/);if(grouped){let specifier2=rustModulePathToSpecifier(grouped[1].trim(),sourceFile,workspaceRoot),bindings=[];for(let rawPart of grouped[2].split(",")){let part=rawPart.trim();if(!part)continue;let alias2=part.match(/^(\w+)\s+as\s+(\w+)$/);if(alias2)bindings.push({imported:alias2[1],local:alias2[2]});else if(/^\w+$/.test(part)){let local2=part==="self"?grouped[1].split("::").pop()||grouped[1]:part;bindings.push({imported:part,local:local2})}}let parsed2=makeParsedImport(specifier2,"named",bindings);if(parsed2)imports.push(parsed2);continue}let simple=trimmed.match(/^use\s+(.+?)\s*;?\s*$/);if(!simple)continue;let rawPath=simple[1].trim(),alias=rawPath.match(/^(.+?)\s+as\s+(\w+)$/),fullPath=(alias?alias[1]:rawPath).trim(),parts=fullPath.split("::").filter(Boolean),imported=parts.pop()??fullPath,specifier=rustModulePathToSpecifier(parts.join("::")||fullPath,sourceFile,workspaceRoot),local=alias?alias[2]:imported,parsed=makeParsedImport(specifier,"named",/^\w+$/.test(imported)&&/^\w+$/.test(local)?[{imported,local}]:[]);if(parsed)imports.push(parsed)}return imports}function parseGoFileImports(rawContent){let imports=[],content=stripComments2(rawContent),parseSpec=(text)=>{let spec=text.trim();if(!spec)return;let aliased=spec.match(/^([\w._]+)\s+["`]([^"`]+)["`]$/);if(aliased){if(aliased[1]==="_"){let parsed2=makeParsedImport(aliased[2],"sideeffect",[]);if(parsed2)imports.push(parsed2);return}if(aliased[1]==="."){let parsed2=makeParsedImport(aliased[2],"namespace",[{imported:"*",local:"."}]);if(parsed2)imports.push(parsed2);return}let parsed=makeParsedImport(aliased[2],"named",[{imported:aliased[2],local:aliased[1]}]);if(parsed)imports.push(parsed);return}let simple=spec.match(/^["`]([^"`]+)["`]$/);if(simple){let parsed=makeParsedImport(simple[1],"namespace",[]);if(parsed)imports.push(parsed)}};for(let block of content.matchAll(/import\s*\(([\s\S]*?)\)/g))for(let line of block[1].split(/\r?\n/))parseSpec(line);let withoutBlocks=content.replace(/import\s*\([\s\S]*?\)/g,"");for(let match of withoutBlocks.matchAll(/^\s*import\s+(.+)$/gm))parseSpec(match[1]);return imports}function parseImportBindings(matchedString,importType){if(importType==="namespace")return[];if(importType==="default"){let defaultMatch=matchedString.match(/^import\s+(\w+)\s+from\s+['"`]/);return defaultMatch?[{imported:"default",local:defaultMatch[1]}]:[]}if(importType!=="named")return[];let braceMatch=matchedString.match(/\{\s*([\s\S]*?)\s*\}/);if(!braceMatch)return[];let bindings=[],seen=new Set;for(let rawPart of braceMatch[1].split(",")){let part=rawPart.trim().replace(/^type\s+/,"");if(!part)continue;let aliasSplit=part.split(/\s+as\s+/i),imported=aliasSplit[0].trim(),local=(aliasSplit[1]??aliasSplit[0]).trim();if(!/^[A-Za-z_$][\w$]*$/.test(imported))continue;if(!/^[A-Za-z_$][\w$]*$/.test(local))continue;if(seen.has(imported))continue;seen.add(imported),bindings.push({imported,local})}return bindings}function computeUsedSymbols(strippedContent,bindings){if(bindings.length===0)return[];let used=new Set;for(let binding of bindings){if(!SAFE_USAGE_IDENTIFIER.test(binding.local)){used.add(binding.imported);continue}let re=new RegExp(`\\b${binding.local}\\b`,"g"),count=0;for(let _match of strippedContent.matchAll(re))if(count++,count>1)break;if(count>1)used.add(binding.imported)}return[...used].sort((a,b)=>a.localeCompare(b))}function usedSymbolsForImport(parsed,strippedContent){if(parsed.importType==="namespace"||parsed.importType==="sideeffect"||parsed.importType==="require")return;if(parsed.reExport)return[...new Set(parsed.bindings.map((b)=>b.imported))].sort((a,b)=>a.localeCompare(b));return computeUsedSymbols(strippedContent,parsed.bindings)}function collectExports(symbols2){let exported=symbols2.filter((s)=>s.exported),exports=exported.map((s)=>s.signature===`default ${s.name}`?"default":s.name),exportLines=Object.create(null);for(let i=0;i<exported.length;i++){let s=exported[i],name=exports[i];if(typeof s.line==="number"&&Number.isFinite(s.line)&&exportLines[name]===void 0)exportLines[name]=s.line}return{exports,exportLines}}function parseImportedSymbols(matchedString,importType){if(importType==="namespace")return["*"];if(importType==="default")return matchedString.match(/^import\s+(\w+)\s+from\s+['"`]/)?["default"]:[];if(importType!=="named")return[];let braceMatch=matchedString.match(/\{\s*([\s\S]*?)\s*\}/);if(!braceMatch)return[];let symbols2=new Set;for(let rawPart of braceMatch[1].split(",")){let part=rawPart.trim();if(!part)continue;let cleaned=part.replace(/^type\s+/,"").split(/\s+as\s+/i)[0].trim();if(/^[A-Za-z_$][\w$]*$/.test(cleaned))symbols2.add(cleaned)}return[...symbols2].sort((a,b)=>a.localeCompare(b))}function isGraphWideInputPath(filePath){return MANIFEST_BASENAMES.has(path160.basename(filePath))}function recordManifestDir(manifestDirs,absoluteRoot,dir,entryName){if(!MANIFEST_BASENAMES.has(entryName))return;let rel=path160.relative(absoluteRoot,dir).split(path160.sep).join("/");if(rel.startsWith("./"))rel=rel.slice(2);manifestDirs.add(rel)}function isWalkBudgetExceeded(ctx){if(ctx.abortReason!==void 0)return!0;if(_internals125.now()-ctx.startedAt>ctx.walkBudgetMs)return ctx.abortReason="budget",!0;return!1}function isFileCapReached(ctx,filesLength){if(filesLength>=ctx.maxFiles)return ctx.abortReason="cap",!0;return!1}async function canonicalDirKeyAsync(dir){try{return await fsPromises6.realpath(dir)}catch{return null}}async function walkRepoGraphInputs(dir,options){let absoluteRoot=path160.resolve(dir),stats2={filesScanned:0,skippedDirs:0,skippedFiles:0,truncated:!1,_absoluteRoot:absoluteRoot},ctx={stats:stats2,seenRealPaths:new Set,startedAt:_internals125.now(),walkBudgetMs:options?.walkBudgetMs??DEFAULT_WALK_BUDGET_MS,maxFiles:options?.maxFiles??DEFAULT_WALK_FILE_CAP,followSymlinks:options?.followSymlinks??!1,skipDirs:resolveSkipDirectories(options?.excludeDirs),manifestDirs:new Set,manifestWitnesses:[]},files=[],manifestFiles=[],metadata=[],unreadableDirectories=[],unreadableFiles=[],queue=[absoluteRoot],processed=0;while(queue.length>0){if(isWalkBudgetExceeded(ctx)||isFileCapReached(ctx,files.length))break;let current=queue.shift(),key=await canonicalDirKeyAsync(current);if(key!==null){if(ctx.seenRealPaths.has(key)){ctx.stats.skippedDirs++;continue}ctx.seenRealPaths.add(key)}else unreadableDirectories.push(current);let entries;try{entries=await fsPromises6.readdir(current,{withFileTypes:!0})}catch{unreadableDirectories.push(current);continue}entries.sort((a,b)=>a.name.toLowerCase().localeCompare(b.name.toLowerCase()));let absoluteRoot2=ctx.stats._absoluteRoot;for(let entry of entries){if(isWalkBudgetExceeded(ctx)||isFileCapReached(ctx,files.length))break;if(ctx.skipDirs.has(entry.name)){ctx.stats.skippedDirs++;continue}let fullPath=path160.join(current,entry.name);if(entry.isSymbolicLink()&&!ctx.followSymlinks){ctx.stats.skippedDirs++;continue}if(entry.isDirectory())queue.push(fullPath);else if(entry.isFile()){if(absoluteRoot2!==void 0)recordManifestDir(ctx.manifestDirs,absoluteRoot2,current,entry.name);let ext=path160.extname(fullPath).toLowerCase(),isSource=SUPPORTED_EXTENSIONS.has(ext),isManifest=isGraphWideInputPath(fullPath);if(isSource)files.push(fullPath);if(isManifest)manifestFiles.push(fullPath);if(options?.captureMetadata&&(isSource||isManifest)||options?.captureManifestMetadata&&isManifest)try{let fileStats=await fsPromises6.stat(fullPath);metadata.push({absolutePath:fullPath,kind:isManifest?"manifest":"source",sizeBytes:fileStats.size,mtimeMs:fileStats.mtimeMs})}catch{unreadableFiles.push(fullPath)}}if(processed++,processed%ASYNC_WALK_YIELD_INTERVAL===0)await yieldToEventLoop()}}if(ctx.abortReason==="cap"||ctx.abortReason==="budget")ctx.stats.truncated=!0;return{sourceFiles:files,manifestFiles,metadata,manifestDirs:ctx.manifestDirs,truncated:stats2.truncated,truncationReason:ctx.abortReason,incomplete:stats2.truncated||unreadableDirectories.length>0||unreadableFiles.length>0,unreadableDirectories,unreadableFiles,probedFiles:metadata.length,elapsedMs:Math.max(0,_internals125.now()-ctx.startedAt)}}function toModuleName(filePath,workspaceRoot){return path160.relative(workspaceRoot,filePath).split(path160.sep).join("/")}function getLanguage(filePath){let ext=path160.extname(filePath).toLowerCase(),jsFamilyLanguage=JS_FAMILY_EXTENSION_TO_LANGUAGE[ext];if(jsFamilyLanguage)return jsFamilyLanguage;return EXTENSION_TO_LANGUAGE[ext]??"unknown"}function isBinaryContent(content){if(content.includes("\x00"))return!0;return!1}function scanFile(filePath,absoluteRoot,maxFileSize,hasManifest){let content,fileStats;try{if(fileStats=fsSync11.statSync(filePath),fileStats.size>maxFileSize)return{node:null,edges:[]};content=fsSync11.readFileSync(filePath,"utf-8")}catch{return{node:null,edges:[]}}if(isBinaryContent(content))return{node:null,edges:[]};let ext=path160.extname(filePath).toLowerCase(),exports=[],exportLines={};try{if([".ts",".tsx",".js",".jsx",".mjs",".cjs"].includes(ext)){let relativePath2=path160.relative(absoluteRoot,filePath);({exports,exportLines}=collectExports(_internals125.extractTSSymbols(relativePath2,absoluteRoot)))}else if(ext===".py"||ext===".pyw"){let relativePath2=path160.relative(absoluteRoot,filePath);({exports,exportLines}=collectExports(_internals125.extractPythonSymbols(relativePath2,absoluteRoot)))}else if(ext===".rs"){let relativePath2=path160.relative(absoluteRoot,filePath);({exports,exportLines}=collectExports(_internals125.extractRustSymbols(relativePath2,absoluteRoot)))}else if(ext===".go"){let relativePath2=path160.relative(absoluteRoot,filePath);({exports,exportLines}=collectExports(_internals125.extractGoSymbols(relativePath2,absoluteRoot)))}let parsedImports=_internals125.parseFileImports(content,filePath,absoluteRoot),strippedForUsage=parsedImports.length>0?_internals125.stripComments(content):"",moduleName=toModuleName(filePath,absoluteRoot),node={filePath,moduleName,exports,...Object.keys(exportLines).length>0?{exportLines}:{},imports:parsedImports.map((p)=>p.specifier),language:getLanguage(filePath),mtime:fileStats.mtime.toISOString(),sizeBytes:fileStats.size,mtimeMs:fileStats.mtimeMs,ontology:_internals125.extractFileOntology({moduleName,filePath,content,language:getLanguage(filePath),exports,imports:parsedImports.map((p)=>p.specifier),hasManifest})},edges=[],sortedImports=[...parsedImports].sort((a,b)=>a.specifier.localeCompare(b.specifier));for(let parsed of sortedImports){let resolvedTarget=resolveModuleSpecifier(absoluteRoot,filePath,parsed.specifier);if(resolvedTarget!==null){let usedSymbols=usedSymbolsForImport(parsed,strippedForUsage);edges.push({source:filePath,target:resolvedTarget,importSpecifier:parsed.specifier,importType:parsed.importType,importedSymbols:parsed.importedSymbols,...usedSymbols!==void 0?{usedSymbols}:{},targetKind:isScannableSourcePath(resolvedTarget)?"node":"asset"})}}return{node,edges}}catch{return{node:null,edges:[]}}}async function scanFileAsync(filePath,absoluteRoot,maxFileSize,hasManifest){let content,fileStats;try{if(fileStats=await fsPromises6.stat(filePath),fileStats.size>maxFileSize){let moduleName2=toModuleName(filePath,absoluteRoot);return{node:null,edges:[],symbolEdges:[],diagnostics:{oversizedFiles:[moduleName2]},inputWitness:{file:moduleName2,kind:"stable-skip",sizeBytes:fileStats.size,mtimeMs:fileStats.mtimeMs}}}content=await fsPromises6.readFile(filePath,"utf-8")}catch{return{node:null,edges:[],symbolEdges:[],diagnostics:{unreadableFiles:[toModuleName(filePath,absoluteRoot)]}}}if(isBinaryContent(content)){let moduleName2=toModuleName(filePath,absoluteRoot);return{node:null,edges:[],symbolEdges:[],diagnostics:{binaryFiles:[moduleName2]},inputWitness:{file:moduleName2,kind:"stable-skip",sizeBytes:fileStats.size,mtimeMs:fileStats.mtimeMs}}}let grammarId=getLanguage(filePath),facts=await _internals125.extractFileSymbols(grammarId,content);if(facts===null){let fallback=scanFile(filePath,absoluteRoot,maxFileSize,hasManifest),parsedImports=[];try{parsedImports=_internals125.parseFileImports(content,filePath,absoluteRoot)}catch{parsedImports=[]}return{...fallback,symbolEdges:[],diagnostics:{extractionFailures:[{file:toModuleName(filePath,absoluteRoot),language:grammarId,reason:"symbol_extraction_failed"}],unresolvedImports:unresolvedRelativeImportsFor(parsedImports,filePath,absoluteRoot)}}}let exportedDefs=facts.defs.filter((d)=>d.exported),exports=exportedDefs.map((d)=>d.name),exportLines=Object.create(null),exportRanges=Object.create(null);for(let d of exportedDefs)exportLines[d.name]=d.startLine;let isWidenedGrammar=JVM_DOTNET_RANGE_GRAMMARS.has(grammarId),rangeIsExported=Object.create(null);for(let d of isWidenedGrammar?facts.defs:exportedDefs){if(isWidenedGrammar&&(!Number.isInteger(d.startLine)||!Number.isInteger(d.endLine)||d.startLine<1||d.endLine<d.startLine))continue;let next={startLine:d.startLine,endLine:d.endLine},prev=exportRanges[d.name];if(isWidenedGrammar&&prev!==void 0){let prevExported=rangeIsExported[d.name]===!0;if(d.exported!==prevExported){if(!d.exported)continue}else if(d.exported);else continue}exportRanges[d.name]=next,rangeIsExported[d.name]=d.exported}let exportsSet=new Set(exports),isPythonPackageInit=grammarId==="python"&&["__init__.py","__init__.pyw"].includes(path160.basename(filePath));for(let imp of facts.imports){let packageInitBindings=isPythonPackageInit&&imp.bindings.length>0?imp.bindings.filter((binding)=>!binding.local.startsWith("_")).map((binding)=>({imported:binding.imported,exported:binding.local})):[],exportedBindings=imp.reExport&&imp.exportedBindings?imp.exportedBindings:packageInitBindings;if(exportedBindings.length===0)continue;for(let binding of exportedBindings){if(binding.imported==="*"){if(!exportsSet.has(binding.exported))exportsSet.add(binding.exported),exports.push(binding.exported);if(imp.startLine!==void 0&&exportLines[binding.exported]===void 0)exportLines[binding.exported]=imp.startLine;if(imp.startLine!==void 0&&imp.endLine!==void 0&&exportRanges[binding.exported]===void 0)exportRanges[binding.exported]={startLine:imp.startLine,endLine:imp.endLine};continue}if(!exportsSet.has(binding.exported))exportsSet.add(binding.exported),exports.push(binding.exported);if(imp.startLine!==void 0&&exportLines[binding.exported]===void 0)exportLines[binding.exported]=imp.startLine;if(imp.startLine!==void 0&&imp.endLine!==void 0&&exportRanges[binding.exported]===void 0)exportRanges[binding.exported]={startLine:imp.startLine,endLine:imp.endLine}}}let imports=facts.imports.map((i)=>i.specifier),moduleName=toModuleName(filePath,absoluteRoot),language=grammarId,node={filePath,moduleName,exports,...Object.keys(exportLines).length>0?{exportLines}:{},...Object.keys(exportRanges).length>0?{exportRanges}:{},imports,language,mtime:fileStats.mtime.toISOString(),sizeBytes:fileStats.size,mtimeMs:fileStats.mtimeMs,ontology:_internals125.extractFileOntology({moduleName,filePath,content,language,exports,imports,hasManifest})},edges=[],sortedImports=[...facts.imports].sort((a,b)=>a.specifier.localeCompare(b.specifier));for(let imp of sortedImports){let edgeImportType=imp.importType==="commonjs"?"require":imp.importType,resolvedTarget=resolveModuleSpecifier(absoluteRoot,filePath,imp.specifier);if(resolvedTarget!==null){let usedBindings=imp.reExport?imp.bindings:imp.bindings.filter((b)=>facts.refs.some((r)=>r.identifier===b.local)),usedSymbols=edgeImportType!=="namespace"&&edgeImportType!=="require"&&edgeImportType!=="sideeffect"?usedBindings.map((b)=>b.imported):void 0;edges.push({source:filePath,target:resolvedTarget,importSpecifier:imp.specifier,importType:edgeImportType,importedSymbols:imp.bindings.map((b)=>b.imported),...usedSymbols!==void 0?{usedSymbols}:{},targetKind:isScannableSourcePath(resolvedTarget)?"node":"asset"})}}let unresolvedImports=sortedImports.filter((imp)=>isRelativeImportSpecifier(imp.specifier)).filter((imp)=>resolveModuleSpecifier(absoluteRoot,filePath,imp.specifier)===null).map((imp)=>({file:moduleName,specifier:imp.specifier})),symbolEdges=[],localToImported=new Map;for(let imp of facts.imports){if(imp.reExport)continue;for(let binding of imp.bindings)localToImported.set(binding.local,{specifier:imp.specifier,imported:binding.imported})}let seenSymbolEdgeKeys=new Set;for(let ref of facts.refs){let mapping=localToImported.get(ref.identifier);if(!mapping)continue;let resolvedTarget=resolveModuleSpecifier(absoluteRoot,filePath,mapping.specifier);if(!resolvedTarget)continue;let fromSymbol=ref.enclosingDecl??"<module>",key=filePath+"\x00"+fromSymbol+"\x00"+resolvedTarget+"\x00"+mapping.imported;if(seenSymbolEdgeKeys.has(key))continue;seenSymbolEdgeKeys.add(key),symbolEdges.push({fromFile:filePath,fromSymbol,toFile:resolvedTarget,toSymbol:mapping.imported})}for(let imp of facts.imports){let packageInitBindings=isPythonPackageInit&&imp.bindings.length>0?imp.bindings.filter((binding)=>!binding.local.startsWith("_")).map((binding)=>({imported:binding.imported,exported:binding.local})):[],exportedBindings=imp.reExport&&imp.exportedBindings?imp.exportedBindings:packageInitBindings;if(exportedBindings.length===0)continue;let resolvedTarget=resolveModuleSpecifier(absoluteRoot,filePath,imp.specifier);if(!resolvedTarget)continue;for(let binding of exportedBindings){if(binding.imported==="*")continue;let key=filePath+"\x00"+binding.exported+"\x00"+resolvedTarget+"\x00"+binding.imported;if(seenSymbolEdgeKeys.has(key))continue;seenSymbolEdgeKeys.add(key),symbolEdges.push({fromFile:filePath,fromSymbol:binding.exported,toFile:resolvedTarget,toSymbol:binding.imported})}}return{node,edges,symbolEdges,diagnostics:unresolvedImports.length>0?{unresolvedImports}:void 0}}function reconcileEdgeTargetKinds(graph){let known=new Set,knownFolded=new Set;for(let key of Object.keys(graph.nodes))known.add(toComparablePath(key)),knownFolded.add(toComparablePath(key).toLowerCase());for(let node of Object.values(graph.nodes))known.add(toComparablePath(node.filePath)),knownFolded.add(toComparablePath(node.filePath).toLowerCase());let isKnown=(p)=>{let normalized=toComparablePath(p);return known.has(normalized)||knownFolded.has(normalized.toLowerCase())},reclassified=0;for(let edge of graph.edges){if(edge.targetKind!=="node")continue;if(isKnown(edge.target))continue;edge.targetKind="asset",reclassified++}if(graph.symbolEdges)graph.symbolEdges=graph.symbolEdges.filter((se)=>isKnown(se.fromFile)&&isKnown(se.toFile));return reclassified}function toComparablePath(p){return normalizeGraphPath(p)}async function buildWorkspaceGraphAsync(workspaceRoot,options){validateWorkspace(workspaceRoot);let maxFileSize=options?.maxFileSizeBytes??1048576,maxFiles=options?.maxFiles??DEFAULT_WALK_FILE_CAP,walkBudgetMs=options?.walkBudgetMs??DEFAULT_WALK_BUDGET_MS,followSymlinks=options?.followSymlinks??!1,absoluteRoot=path160.resolve(workspaceRoot);if(!existsSync80(absoluteRoot))throw Error(`Workspace directory does not exist: ${workspaceRoot}`);if(isRefusedWorkspaceRoot(absoluteRoot))throw Error(`Refusing to scan top-level system path as workspace: ${absoluteRoot}. Set workspaceRoot to a project directory.`);let graph=createEmptyGraph(workspaceRoot),stats2={filesScanned:0,skippedDirs:0,skippedFiles:0,truncated:!1,_absoluteRoot:absoluteRoot},diagnostics=createEmptyDiagnostics(),walked=await walkRepoGraphInputs(absoluteRoot,{walkBudgetMs,maxFiles,followSymlinks,excludeDirs:options?.excludeDirs,captureManifestMetadata:!0}),sourceFiles=walked.sourceFiles;stats2.truncated=walked.truncated;for(let input of walked.metadata){if(input.kind!=="manifest")continue;let relative36=toModuleName(input.absolutePath,absoluteRoot);pushInputWitness(diagnostics.extractorInputWitnesses,{file:relative36,kind:"manifest",sizeBytes:input.sizeBytes,mtimeMs:input.mtimeMs})}if(sourceFiles.sort((a,b)=>{let normA=normalizeGraphPath(a),normB=normalizeGraphPath(b);return normA.localeCompare(normB)}),stats2.truncated)warn(`[repo-graph] Walk truncated: collected ${sourceFiles.length} files within ${walkBudgetMs}ms / ${maxFiles}-file budget.`);let hasManifest=(relDir)=>walked.manifestDirs.has(relDir),seenEdges=new Set,seenSymbolEdges=new Set,allSymbolEdges=[],processedSinceYield=0;for(let filePath of sourceFiles){let result=await scanFileAsync(filePath,absoluteRoot,maxFileSize,hasManifest);if(mergeDiagnostics(diagnostics,result.diagnostics),result.inputWitness)pushInputWitness(diagnostics.extractorInputWitnesses,result.inputWitness);if(result.node){let appended=!1;try{appendNodeFast(graph,result.node),appended=!0}catch{stats2.skippedFiles++,pushCapped(diagnostics.validationSkippedFiles,result.node.moduleName),pushInputWitness(diagnostics.extractorInputWitnesses,{file:result.node.moduleName,kind:"stable-skip",sizeBytes:result.node.sizeBytes,mtimeMs:result.node.mtimeMs})}if(appended){for(let edge of result.edges)try{appendEdgeFast(graph,edge,seenEdges)}catch{}for(let symbolEdge of result.symbolEdges){let key=symbolEdge.fromFile+"\x00"+symbolEdge.fromSymbol+"\x00"+symbolEdge.toFile+"\x00"+symbolEdge.toSymbol;if(!seenSymbolEdges.has(key))seenSymbolEdges.add(key),allSymbolEdges.push(symbolEdge)}stats2.filesScanned++}}else stats2.skippedFiles++;if(processedSinceYield++,processedSinceYield%ASYNC_SCAN_YIELD_INTERVAL===0)await yieldToEventLoop()}if(graph.metadata={generatedAt:new Date().toISOString(),generator:"repo-graph",nodeCount:Object.keys(graph.nodes).length,edgeCount:graph.edges.length},allSymbolEdges.length>0)graph.symbolEdges=allSymbolEdges;if(reconcileEdgeTargetKinds(graph),diagnostics.walkTruncated=stats2.truncated,diagnostics.walkTruncationReason=walked.truncationReason,graph.diagnostics=diagnosticsHaveEntries(diagnostics)?diagnostics:createEmptyDiagnostics(),stats2.skippedFiles>0||stats2.skippedDirs>0||stats2.truncated)log(`[repo-graph] Scan stats: ${stats2.filesScanned} files scanned, ${stats2.skippedFiles} files skipped, ${stats2.skippedDirs} dirs skipped`+(stats2.truncated?", TRUNCATED":""));return graph}var _internals125,SKIP_DIRECTORIES2,SUPPORTED_EXTENSIONS,DEFAULT_WALK_FILE_CAP=1e4,DEFAULT_WALK_BUDGET_MS=5000,ASYNC_WALK_YIELD_INTERVAL=200,ASYNC_SCAN_YIELD_INTERVAL=16,MAX_DIAGNOSTIC_ENTRIES=200,MAX_EXTRACTOR_INPUT_WITNESSES=100256,EXTENSION_TO_LANGUAGE,JS_FAMILY_EXTENSION_TO_LANGUAGE,JVM_DOTNET_DOTTED_ROOTS,JVM_DOTNET_TEST_FILE_RE,REGEX_ALLOWED_AFTER,SAFE_USAGE_IDENTIFIER,MANIFEST_BASENAMES,JVM_DOTNET_RANGE_GRAMMARS;var init_builder=__esm(()=>{init_profiles();init_symbol_graph();init_logger();init_path_security();init_timeout();init_symbols();init_ontology();init_safe_realpath();init_types3();init_validation();_internals125={now:Date.now,safeRealpathSync,extractTSSymbols,extractPythonSymbols,extractRustSymbols,extractGoSymbols,parseFileImports,extractFileOntology,stripComments:stripComments2,computeUsedSymbols,extractFileSymbols},SKIP_DIRECTORIES2=new Set(["node_modules",".git","dist","build","out","coverage",".next",".nuxt",".cache","vendor",".svn",".hg",".svelte-kit"]);SUPPORTED_EXTENSIONS=new Set(LANGUAGE_REGISTRY.getAll().filter((p)=>!p.parserOnly).flatMap((p)=>p.extensions));EXTENSION_TO_LANGUAGE={};for(let profile of LANGUAGE_REGISTRY.getAll()){if(profile.parserOnly)continue;for(let ext of profile.extensions)EXTENSION_TO_LANGUAGE[ext]=profile.treeSitter.grammarId}JS_FAMILY_EXTENSION_TO_LANGUAGE={".js":"javascript",".jsx":"javascript",".mjs":"javascript",".cjs":"javascript",".ts":"typescript",".tsx":"tsx"};JVM_DOTNET_DOTTED_ROOTS=["","src","src/main/java","src/main/kotlin"];JVM_DOTNET_TEST_FILE_RE=/\w(?:Tests?|Spec)\.[A-Za-z]+$/;REGEX_ALLOWED_AFTER=new Set("(,=:[!&|?{};*+-~^<>%".split(""));SAFE_USAGE_IDENTIFIER=/^[A-Za-z_][A-Za-z0-9_]*$/;MANIFEST_BASENAMES=new Set(["package.json","Cargo.toml","pyproject.toml","go.mod"]);JVM_DOTNET_RANGE_GRAMMARS=new Set(["java","kotlin","csharp"])});import*as fs83 from"node:fs";import*as path161 from"node:path";function normalizeLookupPath(input){return normalizeGraphPath(input).replace(/^(?:\.\/)+/,"")}function graphRoot(graph){return path161.resolve(graph.workspaceRoot)}function toModuleName2(graph,input){let normalized=normalizeLookupPath(input);if(path161.isAbsolute(normalized)||/^[A-Za-z]:\//.test(normalized))return normalizeLookupPath(path161.relative(graphRoot(graph),normalized));return normalized}function absoluteKeyForModule(graph,moduleName){return normalizeGraphPath(path161.resolve(graphRoot(graph),moduleName))}function getGraphNode(graph,input){let moduleName=toModuleName2(graph,input),direct=graph.nodes[absoluteKeyForModule(graph,moduleName)];if(direct)return direct;return getQueryIndexes(graph).moduleNameIndex.get(moduleName)}function moduleNameForEdgePath(graph,edgePath){let key=normalizeGraphPath(edgePath),node=graph.nodes[key];if(node)return normalizeLookupPath(node.moduleName);return normalizeLookupPath(path161.relative(graphRoot(graph),edgePath))}function buildReverseIndex(graph){let reverse=new Map,forward=new Map,moduleNameIndex=new Map;for(let node of Object.values(graph.nodes))moduleNameIndex.set(normalizeLookupPath(node.moduleName),node);for(let edge of graph.edges){if(isAssetEdge(edge))continue;let source=normalizeGraphPath(edge.source),target=normalizeGraphPath(edge.target),sourceRef={file:moduleNameForEdgePath(graph,edge.source),importType:edge.importType},targetRef={file:moduleNameForEdgePath(graph,edge.target),importType:edge.importType},reverseRefs=reverse.get(target);if(reverseRefs)reverseRefs.push(sourceRef);else reverse.set(target,[sourceRef]);let forwardRefs=forward.get(source);if(forwardRefs)forwardRefs.push(targetRef);else forward.set(source,[targetRef])}for(let refs of reverse.values())refs.sort((a,b)=>a.file.localeCompare(b.file));for(let refs of forward.values())refs.sort((a,b)=>a.file.localeCompare(b.file));return cachedReverseIndex={graph,index:reverse,forwardIndex:forward,moduleNameIndex},reverse}function getQueryIndexes(graph){if(cachedReverseIndex&&cachedReverseIndex.graph===graph)return cachedReverseIndex;return buildReverseIndex(graph),cachedReverseIndex}function getReverseIndex(graph){return getQueryIndexes(graph).index}function getForwardIndex(graph){return getQueryIndexes(graph).forwardIndex}function resetQueryCache(){cachedReverseIndex=null}function isSafeHealthPath(value){if(typeof value!=="string")return!1;if(value.length===0||value.length>MAX_HEALTH_PATH_LENGTH)return!1;if(containsControlChars(value)||containsPathTraversal(value))return!1;if(path161.isAbsolute(value)||/^[A-Za-z]:[\\/]/.test(value))return!1;return!0}function isSafeHealthText(value){if(typeof value!=="string")return!1;if(value.length===0||value.length>MAX_HEALTH_PATH_LENGTH)return!1;if(containsControlChars(value))return!1;return!0}function cap(entries){return entries.slice(0,GRAPH_HEALTH_OUTPUT_LIMIT)}function sanitizeExtractionFailures(value){if(!Array.isArray(value))return[];let entries=[];for(let raw of value){if(!raw||typeof raw!=="object")continue;let entry=raw;if(isSafeHealthPath(entry.file)&&isSafeHealthText(entry.language)&&isSafeHealthText(entry.reason))entries.push({file:entry.file,language:entry.language,reason:entry.reason})}return cap(entries)}function sanitizeUnresolvedImports(value){if(!Array.isArray(value))return[];let entries=[];for(let raw of value){if(!raw||typeof raw!=="object")continue;let entry=raw;if(isSafeHealthPath(entry.file)&&isSafeHealthText(entry.specifier))entries.push({file:entry.file,specifier:entry.specifier})}return cap(entries)}function sanitizePathList(value){if(!Array.isArray(value))return[];return cap(value.filter(isSafeHealthPath))}function getProbeStaleFiles(probe2,workspaceRoot){if(!probe2)return[];let root=path161.resolve(workspaceRoot),stale=new Set;for(let absolutePath2 of[...probe2.changed,...probe2.removed]){if(typeof absolutePath2!=="string"||!path161.isAbsolute(absolutePath2))continue;let relative37=normalizeGraphPath(path161.relative(root,absolutePath2));if(!isSafeHealthPath(relative37))continue;stale.add(relative37)}return[...stale].sort((a,b)=>a.localeCompare(b)).slice(0,GRAPH_HEALTH_OUTPUT_LIMIT)}function getGraphHealth(graph,workspaceRoot,probe2){let probeState=probe2?.state??"no-fingerprint";if(!graph)return{schemaVersion:null,fresh:!1,probeState,staleFiles:[],extractionFailures:[],unresolvedImports:[],oversizedFiles:[],unsupportedFiles:[],binaryFiles:[],unreadableFiles:[],validationSkippedFiles:[],lowConfidenceEdgeCount:0,walkTruncated:!1,walkTruncationReason:null,incrementalFallbacks:0,notes:['No repo graph found at .swarm/repo-graph.json. Run repo_map with action="build" first.']};let diagnostics=graph.diagnostics,fresh=probeState==="clean",staleFiles=getProbeStaleFiles(probe2,workspaceRoot??graph.workspaceRoot),notes=[];if(probeState==="drifted")notes.push('Graph content is stale relative to the workspace. Run repo_map with action="build" if automatic refresh is unavailable.');else if(probeState==="no-fingerprint")notes.push('Graph has no matching content fingerprint. Run repo_map with action="build" to certify it.');else if(probeState==="inconclusive")notes.push("Graph freshness is unknown because the bounded workspace probe did not complete; no refresh or deletion was attempted.");if(!diagnostics)notes.push('Graph has no recorded diagnostics. Rebuild with repo_map action="build" to collect health details.');let binaryFiles=sanitizePathList(diagnostics?.binaryFiles),binaryCount=binaryFiles.length;if(binaryCount>0)notes.push(`${binaryCount} binary files skipped during last build.`);let unreadableFiles=sanitizePathList(diagnostics?.unreadableFiles),unreadableCount=unreadableFiles.length;if(unreadableCount>0)notes.push(`${unreadableCount} unreadable files skipped during last build.`);let walkTruncated=diagnostics?.walkTruncated===!0,rawReason=diagnostics?.walkTruncationReason,walkTruncationReason=rawReason==="budget"||rawReason==="cap"?rawReason:null,incrementalFallbacks=typeof diagnostics?.incrementalFallbacks==="number"&&Number.isFinite(diagnostics.incrementalFallbacks)&&diagnostics.incrementalFallbacks>0?Math.floor(diagnostics.incrementalFallbacks):0;if(walkTruncated)notes.push("Graph is INCOMPLETE: walk hit the file-cap/wall-clock budget — results may be missing files."+(walkTruncationReason?` (reason: ${walkTruncationReason})`:""));if(incrementalFallbacks>0)notes.push(`${incrementalFallbacks} incremental update(s) fell back to a full rebuild (validation failure or concurrent modification).`);return{schemaVersion:graph.schema_version,fresh,probeState,staleFiles,extractionFailures:sanitizeExtractionFailures(diagnostics?.extractionFailures),unresolvedImports:sanitizeUnresolvedImports(diagnostics?.unresolvedImports),oversizedFiles:sanitizePathList(diagnostics?.oversizedFiles),unsupportedFiles:sanitizePathList(diagnostics?.unsupportedFiles),binaryFiles,unreadableFiles,validationSkippedFiles:sanitizePathList(diagnostics?.validationSkippedFiles),lowConfidenceEdgeCount:typeof diagnostics?.lowConfidenceEdgeCount==="number"&&Number.isFinite(diagnostics.lowConfidenceEdgeCount)&&diagnostics.lowConfidenceEdgeCount>0?Math.floor(diagnostics.lowConfidenceEdgeCount):0,walkTruncated,walkTruncationReason,incrementalFallbacks,notes}}function getImporters(graph,filePath){let node=getGraphNode(graph,filePath);if(!node)return[];return getReverseIndex(graph).get(normalizeGraphPath(node.filePath))??[]}function getDependencies(graph,filePath){let node=getGraphNode(graph,filePath);if(!node)return[];let sourceKey=normalizeGraphPath(node.filePath);return getForwardIndex(graph).get(sourceKey)??[]}function getSymbolConsumers(graph,filePath,symbolName){let node=getGraphNode(graph,filePath);if(!node)return[];let targetKey=normalizeGraphPath(node.filePath),refs=[];for(let edge of graph.edges){if(isAssetEdge(edge))continue;if(normalizeGraphPath(edge.target)!==targetKey)continue;let importedSymbols=edge.importedSymbols??[];if(edge.importType==="namespace"){refs.push({file:moduleNameForEdgePath(graph,edge.source),importedAs:"*"});continue}if(importedSymbols.includes(symbolName))refs.push({file:moduleNameForEdgePath(graph,edge.source),importedAs:symbolName})}return refs.sort((a,b)=>a.file.localeCompare(b.file)),refs}function getCallers(graph,filePath,symbolName){let node=getGraphNode(graph,filePath);if(!node)return[];let targetKey=normalizeGraphPath(node.filePath),refs=[],seen=new Set;for(let edge of graph.edges){if(isAssetEdge(edge))continue;if(normalizeGraphPath(edge.target)!==targetKey)continue;let file3=moduleNameForEdgePath(graph,edge.source);if(seen.has(file3))continue;if(edge.usedSymbols!==void 0){if(edge.usedSymbols.includes(symbolName))seen.add(file3),refs.push({file:file3,resolution:"used"});continue}let imported=edge.importedSymbols??[];if(edge.importType==="namespace"||imported.includes(symbolName))seen.add(file3),refs.push({file:file3,resolution:"imported"})}return refs.sort((a,b)=>a.file.localeCompare(b.file)),refs}function getDeadExports(graph,options){if(!isSchemaVersionAtLeast(graph.schema_version,"1.1.0"))return{schemaSupported:!1,analyzedFiles:0,skippedUnresolvable:0,candidates:[],note:'Graph predates schema 1.1.0 (no usedSymbols data). Run repo_map action="build" to enable dead_exports.'};let usage=new Map;for(let edge of graph.edges){if(isAssetEdge(edge))continue;let target=normalizeGraphPath(edge.target),entry=usage.get(target);if(!entry)entry={used:new Set,unresolvable:!1},usage.set(target,entry);if(edge.importType==="namespace"||edge.importType==="sideeffect"||edge.importType==="require")entry.unresolvable=!0;else if(edge.usedSymbols)for(let symbol3 of edge.usedSymbols)entry.used.add(symbol3)}let reverse=getReverseIndex(graph),candidates=[],analyzedFiles=0,skippedUnresolvable=0;for(let node of Object.values(graph.nodes)){if(node.exports.length===0)continue;let key=normalizeGraphPath(node.filePath),importerCount=reverse.get(key)?.length??0;if(importerCount===0)continue;if((node.ontology?.roles??[]).some((r)=>DEAD_EXPORT_EXCLUDED_ROLES.has(r)))continue;let entry=usage.get(key);if(entry?.unresolvable){skippedUnresolvable++;continue}analyzedFiles++;let used=entry?.used??new Set;for(let symbol3 of node.exports){if(symbol3==="default")continue;if(used.has(symbol3))continue;candidates.push({file:node.moduleName,symbol:symbol3,line:node.exportLines!==void 0&&Object.hasOwn(node.exportLines,symbol3)?node.exportLines[symbol3]:void 0,importerCount})}}candidates.sort((a,b)=>a.file.localeCompare(b.file)||a.symbol.localeCompare(b.symbol));let limit=options?.maxCandidates??100,truncated=candidates.length>limit;return{schemaSupported:!0,analyzedFiles,skippedUnresolvable,candidates:candidates.slice(0,limit),note:"Advisory: exported symbols with no detected in-repo reference, limited to files imported by >=1 other file. Regex analysis cannot see dynamic dispatch, string-keyed access, or namespace/barrel re-export usage; verify before removing."+(truncated?` Showing ${limit} of ${candidates.length}.`:"")}}function getBlastRadius(graph,filePaths,maxDepth=3){let targetNodes=filePaths.map((filePath)=>getGraphNode(graph,filePath)).filter((node)=>node!==void 0),targets=targetNodes.map((node)=>normalizeLookupPath(node.moduleName));if(maxDepth<=0||targetNodes.length===0)return{target:filePaths.map((filePath)=>toModuleName2(graph,filePath)),directDependents:[],transitiveDependents:[],depthReached:0,totalDependents:0,riskLevel:"low"};let reverse=getReverseIndex(graph),visited=new Set(targetNodes.map((node)=>normalizeGraphPath(node.filePath))),direct=new Set,transitive=new Set,depthReached=0,queue=targetNodes.map((node)=>({key:normalizeGraphPath(node.filePath),depth:0}));while(queue.length>0){let next=[];for(let{key,depth}of queue){let importers=reverse.get(key)??[];for(let ref of importers){let importerNode=getGraphNode(graph,ref.file);if(!importerNode)continue;let importerKey=normalizeGraphPath(importerNode.filePath);if(visited.has(importerKey))continue;if(visited.add(importerKey),depth===0)direct.add(ref.file);else transitive.add(ref.file);if(depthReached=Math.max(depthReached,depth+1),depth+1<maxDepth)next.push({key:importerKey,depth:depth+1})}}queue=next}let totalDependents=direct.size+transitive.size;return{target:targets,directDependents:[...direct].sort(),transitiveDependents:[...transitive].sort(),depthReached,totalDependents,riskLevel:classifyRisk(totalDependents)}}function classifyRisk(count){if(count<=3)return"low";if(count<=10)return"medium";if(count<=25)return"high";return"critical"}function getKeyFiles(graph,topN=10){let reverse=getReverseIndex(graph),scored=Object.values(graph.nodes).map((node)=>({node,inDegree:reverse.get(normalizeGraphPath(node.filePath))?.length??0}));return scored.sort((a,b)=>{if(b.inDegree!==a.inDegree)return b.inDegree-a.inDegree;return a.node.moduleName.localeCompare(b.node.moduleName)}),scored.slice(0,topN).map((item)=>item.node)}function getFileOntology(graph,filePath){return getGraphNode(graph,filePath)?.ontology??null}function getLocalizationContext(graph,filePath,options={}){let target=toModuleName2(graph,filePath),node=getGraphNode(graph,target),importers=getImporters(graph,target),dependencies=getDependencies(graph,target),blast=getBlastRadius(graph,[target],options.maxDepth??2),externalSymbols=collectExternallyUsedSymbols(graph,node),summary=formatLocalizationSummary({target,importers,dependencies,blast,externalSymbols,ontology:node?.ontology??null,maxImporters:options.maxImporters??5,maxDeps:options.maxDeps??5});return{target,importerCount:importers.length,importers:importers.slice(0,options.maxImporters??5),dependencyCount:dependencies.length,dependencies:dependencies.slice(0,options.maxDeps??5),exportedSymbolsUsedExternally:externalSymbols,blastRadius:blast,summary}}function getContextPack(graph,file3,symbol3,options={}){if(!isSchemaVersionAtLeast(graph.schema_version,"1.2.0"))return{schemaSupported:!1,target:{file:file3,symbol:symbol3},spans:[],truncated:!1,estimatedTokens:0,note:'rebuild with repo_map action="build"'};let maxDepth=options.maxDepth??2,maxTokens=options.maxTokens??4000,targetNode=getGraphNode(graph,file3);if(!targetNode)return{schemaSupported:!0,target:{file:file3,symbol:symbol3},spans:[],truncated:!1,estimatedTokens:0,note:"Target file not found in graph"};let targetFile=normalizeGraphPath(targetNode.filePath),forward=new Map,reverse=new Map,symbolEdges=graph.symbolEdges??[];for(let edge of symbolEdges){let fromKey=`${normalizeGraphPath(edge.fromFile)}\x00${edge.fromSymbol}`,toKey=`${normalizeGraphPath(edge.toFile)}\x00${edge.toSymbol}`,fromEdges=forward.get(fromKey);if(fromEdges)fromEdges.push(edge);else forward.set(fromKey,[edge]);let toEdges=reverse.get(toKey);if(toEdges)toEdges.push(edge);else reverse.set(toKey,[edge])}let targetKey=`${targetFile}\x00${symbol3}`,visited=new Map,queue=[{key:targetKey,depth:0}];visited.set(targetKey,0);let reached=[],queueHead=0;while(queueHead<queue.length){let{key,depth}=queue[queueHead];queueHead++;let[curFile,curSymbol]=key.split("\x00",2);if(reached.push({file:curFile,symbol:curSymbol,depth}),depth>=maxDepth)continue;let outEdges=forward.get(key)??[];for(let edge of outEdges){let nextKey=`${normalizeGraphPath(edge.toFile)}\x00${edge.toSymbol}`;if(!visited.has(nextKey))visited.set(nextKey,depth+1),queue.push({key:nextKey,depth:depth+1})}let inEdges=reverse.get(key)??[];for(let edge of inEdges){let nextKey=`${normalizeGraphPath(edge.fromFile)}\x00${edge.fromSymbol}`;if(!visited.has(nextKey))visited.set(nextKey,depth+1),queue.push({key:nextKey,depth:depth+1})}}let TOKENS_PER_LINE=12,TOKENS_PER_SIGNATURE=10,spansWithDepth=[];for(let{file:symFile,symbol:sym,depth:d}of reached){let ranges=graph.nodes[symFile]?.exportRanges,range=ranges!==void 0&&Object.hasOwn(ranges,sym)?ranges[sym]:void 0;if(!range){spansWithDepth.push({span:{file:symFile,symbol:sym,startLine:1,endLine:1,mode:"signature",note:"internal symbol — span unavailable"},depth:d});continue}let mode=d===0?"full":d<maxDepth?"full":"signature";spansWithDepth.push({span:{file:symFile,symbol:sym,startLine:range.startLine,endLine:range.endLine,mode},depth:d})}spansWithDepth.sort((a,b)=>{let aIsTarget=a.span.file===targetFile&&a.span.symbol===symbol3?0:1,bIsTarget=b.span.file===targetFile&&b.span.symbol===symbol3?0:1;if(aIsTarget!==bIsTarget)return aIsTarget-bIsTarget;if(a.depth!==b.depth)return a.depth-b.depth;let fileCmp=a.span.file.localeCompare(b.span.file);if(fileCmp!==0)return fileCmp;return a.span.symbol.localeCompare(b.span.symbol)});let includeSource=options.includeSource??!1,directory=options.directory??graph.workspaceRoot,MAX_SOURCE_LINES=80,estimatedTokens=0,finalSpans=[],truncated=!1;for(let{span}of spansWithDepth){let spanTokens=span.mode==="full"?(span.endLine-span.startLine+1)*TOKENS_PER_LINE:TOKENS_PER_SIGNATURE;if(finalSpans.length>0&&estimatedTokens+spanTokens>maxTokens){truncated=!0;break}if(includeSource&&!span.note&&span.mode==="full"){let absPath=path161.isAbsolute(span.file)?span.file:path161.resolve(directory,span.file),resolved=path161.resolve(absPath),resolvedDir=path161.resolve(directory);if(resolved.startsWith(resolvedDir+path161.sep)||resolved===resolvedDir)try{let lines=fs83.readFileSync(resolved,"utf-8").split(`
|
|
3136
|
+
`)out+=ch;i+=1}break}}return out}function parseFileImports(rawContent,sourceFile,workspaceRoot){let ext=sourceFile?path160.extname(sourceFile).toLowerCase():"";if(ext===".py"||ext===".pyw")return parsePythonFileImports(rawContent,sourceFile);if(ext===".rs")return parseRustFileImports(rawContent,sourceFile,workspaceRoot);if(ext===".go")return parseGoFileImports(rawContent);if(ext===".java")return parseJavaFileImports(rawContent);if(ext===".kt"||ext===".kts")return parseKotlinFileImports(rawContent);if(ext===".cs"||ext===".csx")return parseCSharpFileImports(rawContent);let imports=[],content=stripComments2(rawContent),importRegex=/import\s+(?:\{[\s\S]*?\}|(?:\*\s+as\s+\w+)|\w+)\s+from\s+['"`]([^'"`\0\t\r\n]+)['"`]|import\s+['"`]([^'"`\0\t\r\n]+)['"`]|require\s*\(\s*['"`]([^'"`\0\t\r\n]+)['"`]\s*\)|export\s*\{[^}]*\}\s*from\s+['"`]([^'"`\0\t\r\n]+)['"`]|export\s+\*(?:\s+as\s+\w+)?\s+from\s+['"`]([^'"`\0\t\r\n]+)['"`]|import\s*\(\s*['"`]([^'"`\0\t\r\n]+)['"`]\s*\)/g;for(let match of content.matchAll(importRegex)){let modulePath=match[1]||match[2]||match[3]||match[4]||match[5]||match[6];if(!modulePath)continue;if(containsControlChars(modulePath))continue;let matchedString=match[0],importType="named";if(matchedString.includes("* as"))importType="namespace";else if(/^import\s*\(/.test(matchedString))importType="sideeffect";else if(/^export\s*\{/.test(matchedString))importType="named";else if(/^export\s+\*/.test(matchedString))importType="namespace";else if(/^import\s+\{/.test(matchedString))importType="named";else if(/^import\s+\w+\s+from\s+['"`]/.test(matchedString))importType="default";else if(/^import\s+['"`]/m.test(matchedString))importType="sideeffect";else if(matchedString.includes("require("))importType="require";imports.push({specifier:modulePath,importType,importedSymbols:parseImportedSymbols(matchedString,importType),bindings:parseImportBindings(matchedString,importType),reExport:/^\s*export\b/.test(matchedString)})}return imports}function makeParsedImport(specifier,importType,bindings,reExport=!1){if(!specifier||containsControlChars(specifier))return null;return{specifier,importType,importedSymbols:bindings.map((binding)=>binding.imported),bindings,reExport}}function finalDottedSegment2(value){let parts=value.split(".").filter(Boolean);return parts[parts.length-1]??value}function parseJavaFileImports(rawContent){let imports=[],content=maskMultilineStringLiterals(stripComments2(rawContent),"java"),re=/^[ \t]*import[ \t]+(static[ \t]+)?([A-Za-z_][\w.]*(?:\.\*)?)[ \t]*;?[ \t]*\r?$/gm;for(let m=re.exec(content);m!==null;m=re.exec(content)){let isStatic=Boolean(m[1]),raw=m[2];if(raw.endsWith(".*")){let parsed2=makeParsedImport(raw,"namespace",[]);if(parsed2)imports.push(parsed2);continue}let imported=finalDottedSegment2(raw),specifier=isStatic?raw.split(".").slice(0,-1).join("."):raw,parsed=makeParsedImport(specifier,"named",[{imported,local:imported}]);if(parsed)imports.push(parsed)}return imports}function parseKotlinFileImports(rawContent){let imports=[],content=stripComments2(rawContent),re=/^[ \t]*import[ \t]+([A-Za-z_][\w.]*(?:\.\*)?)(?:[ \t]+as[ \t]+([A-Za-z_]\w*))?[ \t]*;?[ \t]*\r?$/gm;for(let m=re.exec(content);m!==null;m=re.exec(content)){let raw=m[1],alias=m[2];if(raw.endsWith(".*")){let parsed2=makeParsedImport(raw,"namespace",[]);if(parsed2)imports.push(parsed2);continue}let imported=finalDottedSegment2(raw),parsed=makeParsedImport(raw,"named",[{imported,local:alias??imported}]);if(parsed)imports.push(parsed)}return imports}function parseCSharpFileImports(rawContent){let imports=[],content=stripComments2(rawContent),re=/^[ \t]*(?:global[ \t]+)?using[ \t]+(static[ \t]+)?(?:([A-Za-z_]\w*)[ \t]*=[ \t]*)?([A-Za-z_][\w.]*)[ \t]*;[ \t]*\r?$/gm;for(let m=re.exec(content);m!==null;m=re.exec(content)){let alias=m[2],specifier=m[3],parsed=alias?makeParsedImport(specifier,"named",[{imported:finalDottedSegment2(specifier),local:alias}]):makeParsedImport(specifier,"namespace",[]);if(parsed)imports.push(parsed)}return imports}function parsePythonFileImports(rawContent,sourceFile){let imports=[],isPackageInit=sourceFile?["__init__.py","__init__.pyw"].includes(path160.basename(sourceFile)):!1;for(let line of rawContent.split(/\r?\n/)){let trimmed=line.trim();if(!trimmed||trimmed.startsWith("#"))continue;let fullImport=trimmed.match(/^import\s+(.+?)(?:\s*#.*)?$/);if(fullImport){for(let rawPart of fullImport[1].split(",")){let part=rawPart.trim();if(!part)continue;let alias=part.match(/^([\w.]+)\s+as\s+(\w+)$/),specifier=alias?alias[1]:part,local=alias?alias[2]:specifier.split(".")[0];if(!/^\w+$/.test(local))continue;let parsed2=makeParsedImport(specifier,"namespace",[{imported:specifier,local}]);if(parsed2)imports.push(parsed2)}continue}let fromImport=trimmed.match(/^from\s+(\S+)\s+import\s+(.+?)(?:\s*#.*)?$/);if(!fromImport)continue;if(fromImport[2].trim()==="*"){let parsed2=makeParsedImport(normalizePythonModuleSpecifier2(fromImport[1]),"namespace",[],isPackageInit);if(parsed2)imports.push(parsed2);continue}let bindings=[];for(let rawPart of fromImport[2].split(",")){let part=rawPart.trim();if(!part)continue;let alias=part.match(/^(\w+)\s+as\s+(\w+)$/);if(alias)bindings.push({imported:alias[1],local:alias[2]});else if(/^\w+$/.test(part))bindings.push({imported:part,local:part})}let parsed=makeParsedImport(normalizePythonModuleSpecifier2(fromImport[1]),"named",bindings,isPackageInit);if(parsed)imports.push(parsed)}return imports}function normalizePythonModuleSpecifier2(specifier){let leadingDots=specifier.match(/^\.+/)?.[0].length??0;if(leadingDots===0)return specifier;let rest=specifier.slice(leadingDots).replace(/\./g,"/");return`${leadingDots===1?"./":"../".repeat(leadingDots-1)}${rest}`}function rustModulePathToSpecifier(modulePath,sourceFile,workspaceRoot){let parts=modulePath.split("::").filter(Boolean);if(parts.length===0)return modulePath;if(parts[0]==="self")return`./${parts.slice(1).join("/")}`;if(parts[0]==="super"){let superCount=0;while(parts[superCount]==="super")superCount++;return`${"../".repeat(superCount)}${parts.slice(superCount).join("/")}`}if(parts[0]==="crate"&&sourceFile&&workspaceRoot){let target=path160.join(workspaceRoot,...parts.slice(1)),relative36=path160.relative(path160.dirname(sourceFile),target).replace(/\\/g,"/");if(!relative36.startsWith("."))relative36=`./${relative36}`;return relative36}return modulePath}function parseRustFileImports(rawContent,sourceFile,workspaceRoot){let imports=[];for(let line of rawContent.split(/\r?\n/)){let trimmed=line.trim();if(!trimmed.startsWith("use "))continue;let grouped=trimmed.match(/^use\s+(.+?)::\{(.+)\}\s*;?\s*$/);if(grouped){let specifier2=rustModulePathToSpecifier(grouped[1].trim(),sourceFile,workspaceRoot),bindings=[];for(let rawPart of grouped[2].split(",")){let part=rawPart.trim();if(!part)continue;let alias2=part.match(/^(\w+)\s+as\s+(\w+)$/);if(alias2)bindings.push({imported:alias2[1],local:alias2[2]});else if(/^\w+$/.test(part)){let local2=part==="self"?grouped[1].split("::").pop()||grouped[1]:part;bindings.push({imported:part,local:local2})}}let parsed2=makeParsedImport(specifier2,"named",bindings);if(parsed2)imports.push(parsed2);continue}let simple=trimmed.match(/^use\s+(.+?)\s*;?\s*$/);if(!simple)continue;let rawPath=simple[1].trim(),alias=rawPath.match(/^(.+?)\s+as\s+(\w+)$/),fullPath=(alias?alias[1]:rawPath).trim(),parts=fullPath.split("::").filter(Boolean),imported=parts.pop()??fullPath,specifier=rustModulePathToSpecifier(parts.join("::")||fullPath,sourceFile,workspaceRoot),local=alias?alias[2]:imported,parsed=makeParsedImport(specifier,"named",/^\w+$/.test(imported)&&/^\w+$/.test(local)?[{imported,local}]:[]);if(parsed)imports.push(parsed)}return imports}function parseGoFileImports(rawContent){let imports=[],content=stripComments2(rawContent),parseSpec=(text)=>{let spec=text.trim();if(!spec)return;let aliased=spec.match(/^([\w._]+)\s+["`]([^"`]+)["`]$/);if(aliased){if(aliased[1]==="_"){let parsed2=makeParsedImport(aliased[2],"sideeffect",[]);if(parsed2)imports.push(parsed2);return}if(aliased[1]==="."){let parsed2=makeParsedImport(aliased[2],"namespace",[{imported:"*",local:"."}]);if(parsed2)imports.push(parsed2);return}let parsed=makeParsedImport(aliased[2],"named",[{imported:aliased[2],local:aliased[1]}]);if(parsed)imports.push(parsed);return}let simple=spec.match(/^["`]([^"`]+)["`]$/);if(simple){let parsed=makeParsedImport(simple[1],"namespace",[]);if(parsed)imports.push(parsed)}};for(let block of content.matchAll(/import\s*\(([\s\S]*?)\)/g))for(let line of block[1].split(/\r?\n/))parseSpec(line);let withoutBlocks=content.replace(/import\s*\([\s\S]*?\)/g,"");for(let match of withoutBlocks.matchAll(/^\s*import\s+(.+)$/gm))parseSpec(match[1]);return imports}function parseImportBindings(matchedString,importType){if(importType==="namespace")return[];if(importType==="default"){let defaultMatch=matchedString.match(/^import\s+(\w+)\s+from\s+['"`]/);return defaultMatch?[{imported:"default",local:defaultMatch[1]}]:[]}if(importType!=="named")return[];let braceMatch=matchedString.match(/\{\s*([\s\S]*?)\s*\}/);if(!braceMatch)return[];let bindings=[],seen=new Set;for(let rawPart of braceMatch[1].split(",")){let part=rawPart.trim().replace(/^type\s+/,"");if(!part)continue;let aliasSplit=part.split(/\s+as\s+/i),imported=aliasSplit[0].trim(),local=(aliasSplit[1]??aliasSplit[0]).trim();if(!/^[A-Za-z_$][\w$]*$/.test(imported))continue;if(!/^[A-Za-z_$][\w$]*$/.test(local))continue;if(seen.has(imported))continue;seen.add(imported),bindings.push({imported,local})}return bindings}function computeUsedSymbols(strippedContent,bindings){if(bindings.length===0)return[];let used=new Set;for(let binding of bindings){if(!SAFE_USAGE_IDENTIFIER.test(binding.local)){used.add(binding.imported);continue}let re=new RegExp(`\\b${binding.local}\\b`,"g"),count=0;for(let _match of strippedContent.matchAll(re))if(count++,count>1)break;if(count>1)used.add(binding.imported)}return[...used].sort((a,b)=>a.localeCompare(b))}function usedSymbolsForImport(parsed,strippedContent){if(parsed.importType==="namespace"||parsed.importType==="sideeffect"||parsed.importType==="require")return;if(parsed.reExport)return[...new Set(parsed.bindings.map((b)=>b.imported))].sort((a,b)=>a.localeCompare(b));return computeUsedSymbols(strippedContent,parsed.bindings)}function collectExports(symbols2){let exported=symbols2.filter((s)=>s.exported),exports=exported.map((s)=>s.signature===`default ${s.name}`?"default":s.name),exportLines=Object.create(null);for(let i=0;i<exported.length;i++){let s=exported[i],name=exports[i];if(typeof s.line==="number"&&Number.isFinite(s.line)&&exportLines[name]===void 0)exportLines[name]=s.line}return{exports,exportLines}}function parseImportedSymbols(matchedString,importType){if(importType==="namespace")return["*"];if(importType==="default")return matchedString.match(/^import\s+(\w+)\s+from\s+['"`]/)?["default"]:[];if(importType!=="named")return[];let braceMatch=matchedString.match(/\{\s*([\s\S]*?)\s*\}/);if(!braceMatch)return[];let symbols2=new Set;for(let rawPart of braceMatch[1].split(",")){let part=rawPart.trim();if(!part)continue;let cleaned=part.replace(/^type\s+/,"").split(/\s+as\s+/i)[0].trim();if(/^[A-Za-z_$][\w$]*$/.test(cleaned))symbols2.add(cleaned)}return[...symbols2].sort((a,b)=>a.localeCompare(b))}function isGraphWideInputPath(filePath){return MANIFEST_BASENAMES.has(path160.basename(filePath))}function recordManifestDir(manifestDirs,absoluteRoot,dir,entryName){if(!MANIFEST_BASENAMES.has(entryName))return;let rel=path160.relative(absoluteRoot,dir).split(path160.sep).join("/");if(rel.startsWith("./"))rel=rel.slice(2);manifestDirs.add(rel)}function isWalkBudgetExceeded(ctx){if(ctx.abortReason!==void 0)return!0;if(_internals125.now()-ctx.startedAt>ctx.walkBudgetMs)return ctx.abortReason="budget",!0;return!1}function isFileCapReached(ctx,filesLength){if(filesLength>=ctx.maxFiles)return ctx.abortReason="cap",!0;return!1}async function canonicalDirKeyAsync(dir){try{return await fsPromises6.realpath(dir)}catch{return null}}async function walkRepoGraphInputs(dir,options){let absoluteRoot=path160.resolve(dir),stats2={filesScanned:0,skippedDirs:0,skippedFiles:0,truncated:!1,_absoluteRoot:absoluteRoot},ctx={stats:stats2,seenRealPaths:new Set,startedAt:_internals125.now(),walkBudgetMs:options?.walkBudgetMs??DEFAULT_WALK_BUDGET_MS,maxFiles:options?.maxFiles??DEFAULT_WALK_FILE_CAP,followSymlinks:options?.followSymlinks??!1,skipDirs:resolveSkipDirectories(options?.excludeDirs),manifestDirs:new Set,manifestWitnesses:[]},files=[],manifestFiles=[],metadata=[],unreadableDirectories=[],unreadableFiles=[],queue=[absoluteRoot],processed=0;while(queue.length>0){if(isWalkBudgetExceeded(ctx)||isFileCapReached(ctx,files.length))break;let current=queue.shift(),key=await canonicalDirKeyAsync(current);if(key!==null){if(ctx.seenRealPaths.has(key)){ctx.stats.skippedDirs++;continue}ctx.seenRealPaths.add(key)}else unreadableDirectories.push(current);let entries;try{entries=await fsPromises6.readdir(current,{withFileTypes:!0})}catch{unreadableDirectories.push(current);continue}entries.sort((a,b)=>a.name.toLowerCase().localeCompare(b.name.toLowerCase()));let absoluteRoot2=ctx.stats._absoluteRoot;for(let entry of entries){if(isWalkBudgetExceeded(ctx)||isFileCapReached(ctx,files.length))break;if(ctx.skipDirs.has(entry.name)){ctx.stats.skippedDirs++;continue}let fullPath=path160.join(current,entry.name);if(entry.isSymbolicLink()&&!ctx.followSymlinks){ctx.stats.skippedDirs++;continue}if(entry.isDirectory())queue.push(fullPath);else if(entry.isFile()){if(absoluteRoot2!==void 0)recordManifestDir(ctx.manifestDirs,absoluteRoot2,current,entry.name);let ext=path160.extname(fullPath).toLowerCase(),isSource=SUPPORTED_EXTENSIONS.has(ext),isManifest=isGraphWideInputPath(fullPath);if(isSource)files.push(fullPath);if(isManifest)manifestFiles.push(fullPath);if(options?.captureMetadata&&(isSource||isManifest)||options?.captureManifestMetadata&&isManifest)try{let fileStats=await fsPromises6.stat(fullPath);metadata.push({absolutePath:fullPath,kind:isManifest?"manifest":"source",sizeBytes:fileStats.size,mtimeMs:fileStats.mtimeMs})}catch{unreadableFiles.push(fullPath)}}if(processed++,processed%ASYNC_WALK_YIELD_INTERVAL===0)await yieldToEventLoop()}}if(ctx.abortReason==="cap"||ctx.abortReason==="budget")ctx.stats.truncated=!0;return{sourceFiles:files,manifestFiles,metadata,manifestDirs:ctx.manifestDirs,truncated:stats2.truncated,truncationReason:ctx.abortReason,incomplete:stats2.truncated||unreadableDirectories.length>0||unreadableFiles.length>0,unreadableDirectories,unreadableFiles,probedFiles:metadata.length,elapsedMs:Math.max(0,_internals125.now()-ctx.startedAt)}}function toModuleName(filePath,workspaceRoot){return path160.relative(workspaceRoot,filePath).split(path160.sep).join("/")}function getLanguage(filePath){let ext=path160.extname(filePath).toLowerCase(),jsFamilyLanguage=JS_FAMILY_EXTENSION_TO_LANGUAGE[ext];if(jsFamilyLanguage)return jsFamilyLanguage;return EXTENSION_TO_LANGUAGE[ext]??"unknown"}function isBinaryContent(content){if(content.includes("\x00"))return!0;return!1}function scanFile(filePath,absoluteRoot,maxFileSize,hasManifest){let content,fileStats;try{if(fileStats=fsSync11.statSync(filePath),fileStats.size>maxFileSize)return{node:null,edges:[]};content=fsSync11.readFileSync(filePath,"utf-8")}catch{return{node:null,edges:[]}}if(isBinaryContent(content))return{node:null,edges:[]};let ext=path160.extname(filePath).toLowerCase(),exports=[],exportLines={};try{if([".ts",".tsx",".js",".jsx",".mjs",".cjs"].includes(ext)){let relativePath2=path160.relative(absoluteRoot,filePath);({exports,exportLines}=collectExports(_internals125.extractTSSymbols(relativePath2,absoluteRoot)))}else if(ext===".py"||ext===".pyw"){let relativePath2=path160.relative(absoluteRoot,filePath);({exports,exportLines}=collectExports(_internals125.extractPythonSymbols(relativePath2,absoluteRoot)))}else if(ext===".rs"){let relativePath2=path160.relative(absoluteRoot,filePath);({exports,exportLines}=collectExports(_internals125.extractRustSymbols(relativePath2,absoluteRoot)))}else if(ext===".go"){let relativePath2=path160.relative(absoluteRoot,filePath);({exports,exportLines}=collectExports(_internals125.extractGoSymbols(relativePath2,absoluteRoot)))}let parsedImports=_internals125.parseFileImports(content,filePath,absoluteRoot),strippedForUsage=parsedImports.length>0?_internals125.stripComments(content):"",moduleName=toModuleName(filePath,absoluteRoot),node={filePath,moduleName,exports,...Object.keys(exportLines).length>0?{exportLines}:{},imports:parsedImports.map((p)=>p.specifier),language:getLanguage(filePath),mtime:fileStats.mtime.toISOString(),sizeBytes:fileStats.size,mtimeMs:fileStats.mtimeMs,ontology:_internals125.extractFileOntology({moduleName,filePath,content,language:getLanguage(filePath),exports,imports:parsedImports.map((p)=>p.specifier),hasManifest})},edges=[],sortedImports=[...parsedImports].sort((a,b)=>a.specifier.localeCompare(b.specifier));for(let parsed of sortedImports){let resolvedTarget=resolveModuleSpecifier(absoluteRoot,filePath,parsed.specifier);if(resolvedTarget!==null){let usedSymbols=usedSymbolsForImport(parsed,strippedForUsage);edges.push({source:filePath,target:resolvedTarget,importSpecifier:parsed.specifier,importType:parsed.importType,importedSymbols:parsed.importedSymbols,...usedSymbols!==void 0?{usedSymbols}:{},targetKind:isScannableSourcePath(resolvedTarget)?"node":"asset"})}}return{node,edges}}catch{return{node:null,edges:[]}}}async function scanFileAsync(filePath,absoluteRoot,maxFileSize,hasManifest){let content,fileStats;try{if(fileStats=await fsPromises6.stat(filePath),fileStats.size>maxFileSize){let moduleName2=toModuleName(filePath,absoluteRoot);return{node:null,edges:[],symbolEdges:[],diagnostics:{oversizedFiles:[moduleName2]},inputWitness:{file:moduleName2,kind:"stable-skip",sizeBytes:fileStats.size,mtimeMs:fileStats.mtimeMs}}}content=await fsPromises6.readFile(filePath,"utf-8")}catch{return{node:null,edges:[],symbolEdges:[],diagnostics:{unreadableFiles:[toModuleName(filePath,absoluteRoot)]}}}if(isBinaryContent(content)){let moduleName2=toModuleName(filePath,absoluteRoot);return{node:null,edges:[],symbolEdges:[],diagnostics:{binaryFiles:[moduleName2]},inputWitness:{file:moduleName2,kind:"stable-skip",sizeBytes:fileStats.size,mtimeMs:fileStats.mtimeMs}}}let grammarId=getLanguage(filePath),facts=await _internals125.extractFileSymbols(grammarId,content);if(facts===null){let fallback=scanFile(filePath,absoluteRoot,maxFileSize,hasManifest),parsedImports=[];try{parsedImports=_internals125.parseFileImports(content,filePath,absoluteRoot)}catch{parsedImports=[]}return{...fallback,symbolEdges:[],diagnostics:{extractionFailures:[{file:toModuleName(filePath,absoluteRoot),language:grammarId,reason:"symbol_extraction_failed"}],unresolvedImports:unresolvedRelativeImportsFor(parsedImports,filePath,absoluteRoot)}}}let exportedDefs=facts.defs.filter((d)=>d.exported),exports=exportedDefs.map((d)=>d.name),exportLines=Object.create(null),exportRanges=Object.create(null);for(let d of exportedDefs)exportLines[d.name]=d.startLine;let isWidenedGrammar=RANGE_WIDENED_GRAMMARS.has(grammarId),rangeIsExported=Object.create(null);for(let d of isWidenedGrammar?facts.defs:exportedDefs){if(isWidenedGrammar&&(!Number.isInteger(d.startLine)||!Number.isInteger(d.endLine)||d.startLine<1||d.endLine<d.startLine))continue;let next={startLine:d.startLine,endLine:d.endLine},prev=exportRanges[d.name];if(isWidenedGrammar&&prev!==void 0){let prevExported=rangeIsExported[d.name]===!0;if(d.exported!==prevExported){if(!d.exported)continue}else if(d.exported);else continue}exportRanges[d.name]=next,rangeIsExported[d.name]=d.exported}let exportsSet=new Set(exports),isPythonPackageInit=grammarId==="python"&&["__init__.py","__init__.pyw"].includes(path160.basename(filePath));for(let imp of facts.imports){let packageInitBindings=isPythonPackageInit&&imp.bindings.length>0?imp.bindings.filter((binding)=>!binding.local.startsWith("_")).map((binding)=>({imported:binding.imported,exported:binding.local})):[],exportedBindings=imp.reExport&&imp.exportedBindings?imp.exportedBindings:packageInitBindings;if(exportedBindings.length===0)continue;for(let binding of exportedBindings){if(binding.imported==="*"){if(!exportsSet.has(binding.exported))exportsSet.add(binding.exported),exports.push(binding.exported);if(imp.startLine!==void 0&&exportLines[binding.exported]===void 0)exportLines[binding.exported]=imp.startLine;if(imp.startLine!==void 0&&imp.endLine!==void 0&&exportRanges[binding.exported]===void 0)exportRanges[binding.exported]={startLine:imp.startLine,endLine:imp.endLine};continue}if(!exportsSet.has(binding.exported))exportsSet.add(binding.exported),exports.push(binding.exported);if(imp.startLine!==void 0&&exportLines[binding.exported]===void 0)exportLines[binding.exported]=imp.startLine;if(imp.startLine!==void 0&&imp.endLine!==void 0&&exportRanges[binding.exported]===void 0)exportRanges[binding.exported]={startLine:imp.startLine,endLine:imp.endLine}}}let imports=facts.imports.map((i)=>i.specifier),moduleName=toModuleName(filePath,absoluteRoot),language=grammarId,node={filePath,moduleName,exports,...Object.keys(exportLines).length>0?{exportLines}:{},...Object.keys(exportRanges).length>0?{exportRanges}:{},imports,language,mtime:fileStats.mtime.toISOString(),sizeBytes:fileStats.size,mtimeMs:fileStats.mtimeMs,ontology:_internals125.extractFileOntology({moduleName,filePath,content,language,exports,imports,hasManifest})},edges=[],sortedImports=[...facts.imports].sort((a,b)=>a.specifier.localeCompare(b.specifier));for(let imp of sortedImports){let edgeImportType=imp.importType==="commonjs"?"require":imp.importType,resolvedTarget=resolveModuleSpecifier(absoluteRoot,filePath,imp.specifier);if(resolvedTarget!==null){let usedBindings=imp.reExport?imp.bindings:imp.bindings.filter((b)=>facts.refs.some((r)=>r.identifier===b.local)),usedSymbols=edgeImportType!=="namespace"&&edgeImportType!=="require"&&edgeImportType!=="sideeffect"?usedBindings.map((b)=>b.imported):void 0;edges.push({source:filePath,target:resolvedTarget,importSpecifier:imp.specifier,importType:edgeImportType,importedSymbols:imp.bindings.map((b)=>b.imported),...usedSymbols!==void 0?{usedSymbols}:{},targetKind:isScannableSourcePath(resolvedTarget)?"node":"asset"})}}let unresolvedImports=sortedImports.filter((imp)=>isRelativeImportSpecifier(imp.specifier)).filter((imp)=>resolveModuleSpecifier(absoluteRoot,filePath,imp.specifier)===null).map((imp)=>({file:moduleName,specifier:imp.specifier})),symbolEdges=[],localToImported=new Map;for(let imp of facts.imports){if(imp.reExport)continue;for(let binding of imp.bindings)localToImported.set(binding.local,{specifier:imp.specifier,imported:binding.imported})}let seenSymbolEdgeKeys=new Set;for(let ref of facts.refs){let mapping=localToImported.get(ref.identifier);if(!mapping)continue;let resolvedTarget=resolveModuleSpecifier(absoluteRoot,filePath,mapping.specifier);if(!resolvedTarget)continue;let fromSymbol=ref.enclosingDecl??"<module>",key=filePath+"\x00"+fromSymbol+"\x00"+resolvedTarget+"\x00"+mapping.imported;if(seenSymbolEdgeKeys.has(key))continue;seenSymbolEdgeKeys.add(key),symbolEdges.push({fromFile:filePath,fromSymbol,toFile:resolvedTarget,toSymbol:mapping.imported})}for(let imp of facts.imports){let packageInitBindings=isPythonPackageInit&&imp.bindings.length>0?imp.bindings.filter((binding)=>!binding.local.startsWith("_")).map((binding)=>({imported:binding.imported,exported:binding.local})):[],exportedBindings=imp.reExport&&imp.exportedBindings?imp.exportedBindings:packageInitBindings;if(exportedBindings.length===0)continue;let resolvedTarget=resolveModuleSpecifier(absoluteRoot,filePath,imp.specifier);if(!resolvedTarget)continue;for(let binding of exportedBindings){if(binding.imported==="*")continue;let key=filePath+"\x00"+binding.exported+"\x00"+resolvedTarget+"\x00"+binding.imported;if(seenSymbolEdgeKeys.has(key))continue;seenSymbolEdgeKeys.add(key),symbolEdges.push({fromFile:filePath,fromSymbol:binding.exported,toFile:resolvedTarget,toSymbol:binding.imported})}}return{node,edges,symbolEdges,diagnostics:unresolvedImports.length>0?{unresolvedImports}:void 0}}function reconcileEdgeTargetKinds(graph){let known=new Set,knownFolded=new Set;for(let key of Object.keys(graph.nodes))known.add(toComparablePath(key)),knownFolded.add(toComparablePath(key).toLowerCase());for(let node of Object.values(graph.nodes))known.add(toComparablePath(node.filePath)),knownFolded.add(toComparablePath(node.filePath).toLowerCase());let isKnown=(p)=>{let normalized=toComparablePath(p);return known.has(normalized)||knownFolded.has(normalized.toLowerCase())},reclassified=0;for(let edge of graph.edges){if(edge.targetKind!=="node")continue;if(isKnown(edge.target))continue;edge.targetKind="asset",reclassified++}if(graph.symbolEdges)graph.symbolEdges=graph.symbolEdges.filter((se)=>isKnown(se.fromFile)&&isKnown(se.toFile));return reclassified}function toComparablePath(p){return normalizeGraphPath(p)}async function buildWorkspaceGraphAsync(workspaceRoot,options){validateWorkspace(workspaceRoot);let maxFileSize=options?.maxFileSizeBytes??1048576,maxFiles=options?.maxFiles??DEFAULT_WALK_FILE_CAP,walkBudgetMs=options?.walkBudgetMs??DEFAULT_WALK_BUDGET_MS,followSymlinks=options?.followSymlinks??!1,absoluteRoot=path160.resolve(workspaceRoot);if(!existsSync80(absoluteRoot))throw Error(`Workspace directory does not exist: ${workspaceRoot}`);if(isRefusedWorkspaceRoot(absoluteRoot))throw Error(`Refusing to scan top-level system path as workspace: ${absoluteRoot}. Set workspaceRoot to a project directory.`);let graph=createEmptyGraph(workspaceRoot),stats2={filesScanned:0,skippedDirs:0,skippedFiles:0,truncated:!1,_absoluteRoot:absoluteRoot},diagnostics=createEmptyDiagnostics(),walked=await walkRepoGraphInputs(absoluteRoot,{walkBudgetMs,maxFiles,followSymlinks,excludeDirs:options?.excludeDirs,captureManifestMetadata:!0}),sourceFiles=walked.sourceFiles;stats2.truncated=walked.truncated;for(let input of walked.metadata){if(input.kind!=="manifest")continue;let relative36=toModuleName(input.absolutePath,absoluteRoot);pushInputWitness(diagnostics.extractorInputWitnesses,{file:relative36,kind:"manifest",sizeBytes:input.sizeBytes,mtimeMs:input.mtimeMs})}if(sourceFiles.sort((a,b)=>{let normA=normalizeGraphPath(a),normB=normalizeGraphPath(b);return normA.localeCompare(normB)}),stats2.truncated)warn(`[repo-graph] Walk truncated: collected ${sourceFiles.length} files within ${walkBudgetMs}ms / ${maxFiles}-file budget.`);let hasManifest=(relDir)=>walked.manifestDirs.has(relDir),seenEdges=new Set,seenSymbolEdges=new Set,allSymbolEdges=[],processedSinceYield=0;for(let filePath of sourceFiles){let result=await scanFileAsync(filePath,absoluteRoot,maxFileSize,hasManifest);if(mergeDiagnostics(diagnostics,result.diagnostics),result.inputWitness)pushInputWitness(diagnostics.extractorInputWitnesses,result.inputWitness);if(result.node){let appended=!1;try{appendNodeFast(graph,result.node),appended=!0}catch{stats2.skippedFiles++,pushCapped(diagnostics.validationSkippedFiles,result.node.moduleName),pushInputWitness(diagnostics.extractorInputWitnesses,{file:result.node.moduleName,kind:"stable-skip",sizeBytes:result.node.sizeBytes,mtimeMs:result.node.mtimeMs})}if(appended){for(let edge of result.edges)try{appendEdgeFast(graph,edge,seenEdges)}catch{}for(let symbolEdge of result.symbolEdges){let key=symbolEdge.fromFile+"\x00"+symbolEdge.fromSymbol+"\x00"+symbolEdge.toFile+"\x00"+symbolEdge.toSymbol;if(!seenSymbolEdges.has(key))seenSymbolEdges.add(key),allSymbolEdges.push(symbolEdge)}stats2.filesScanned++}}else stats2.skippedFiles++;if(processedSinceYield++,processedSinceYield%ASYNC_SCAN_YIELD_INTERVAL===0)await yieldToEventLoop()}if(graph.metadata={generatedAt:new Date().toISOString(),generator:"repo-graph",nodeCount:Object.keys(graph.nodes).length,edgeCount:graph.edges.length},allSymbolEdges.length>0)graph.symbolEdges=allSymbolEdges;if(reconcileEdgeTargetKinds(graph),diagnostics.walkTruncated=stats2.truncated,diagnostics.walkTruncationReason=walked.truncationReason,graph.diagnostics=diagnosticsHaveEntries(diagnostics)?diagnostics:createEmptyDiagnostics(),stats2.skippedFiles>0||stats2.skippedDirs>0||stats2.truncated)log(`[repo-graph] Scan stats: ${stats2.filesScanned} files scanned, ${stats2.skippedFiles} files skipped, ${stats2.skippedDirs} dirs skipped`+(stats2.truncated?", TRUNCATED":""));return graph}var _internals125,SKIP_DIRECTORIES2,SUPPORTED_EXTENSIONS,DEFAULT_WALK_FILE_CAP=1e4,DEFAULT_WALK_BUDGET_MS=5000,ASYNC_WALK_YIELD_INTERVAL=200,ASYNC_SCAN_YIELD_INTERVAL=16,MAX_DIAGNOSTIC_ENTRIES=200,MAX_EXTRACTOR_INPUT_WITNESSES=100256,EXTENSION_TO_LANGUAGE,JS_FAMILY_EXTENSION_TO_LANGUAGE,JVM_DOTNET_DOTTED_ROOTS,JVM_DOTNET_TEST_FILE_RE,REGEX_ALLOWED_AFTER,SAFE_USAGE_IDENTIFIER,MANIFEST_BASENAMES,RANGE_WIDENED_GRAMMARS;var init_builder=__esm(()=>{init_profiles();init_symbol_graph();init_logger();init_path_security();init_timeout();init_symbols();init_ontology();init_safe_realpath();init_types3();init_validation();_internals125={now:Date.now,safeRealpathSync,extractTSSymbols,extractPythonSymbols,extractRustSymbols,extractGoSymbols,parseFileImports,extractFileOntology,stripComments:stripComments2,computeUsedSymbols,extractFileSymbols},SKIP_DIRECTORIES2=new Set(["node_modules",".git","dist","build","out","coverage",".next",".nuxt",".cache","vendor",".svn",".hg",".svelte-kit"]);SUPPORTED_EXTENSIONS=new Set(LANGUAGE_REGISTRY.getAll().filter((p)=>!p.parserOnly).flatMap((p)=>p.extensions));EXTENSION_TO_LANGUAGE={};for(let profile of LANGUAGE_REGISTRY.getAll()){if(profile.parserOnly)continue;for(let ext of profile.extensions)EXTENSION_TO_LANGUAGE[ext]=profile.treeSitter.grammarId}JS_FAMILY_EXTENSION_TO_LANGUAGE={".js":"javascript",".jsx":"javascript",".mjs":"javascript",".cjs":"javascript",".ts":"typescript",".tsx":"tsx"};JVM_DOTNET_DOTTED_ROOTS=["","src","src/main/java","src/main/kotlin"];JVM_DOTNET_TEST_FILE_RE=/\w(?:Tests?|Spec)\.[A-Za-z]+$/;REGEX_ALLOWED_AFTER=new Set("(,=:[!&|?{};*+-~^<>%".split(""));SAFE_USAGE_IDENTIFIER=/^[A-Za-z_][A-Za-z0-9_]*$/;MANIFEST_BASENAMES=new Set(["package.json","Cargo.toml","pyproject.toml","go.mod"]);RANGE_WIDENED_GRAMMARS=new Set(["java","kotlin","csharp","cpp","swift"])});import*as fs83 from"node:fs";import*as path161 from"node:path";function normalizeLookupPath(input){return normalizeGraphPath(input).replace(/^(?:\.\/)+/,"")}function graphRoot(graph){return path161.resolve(graph.workspaceRoot)}function toModuleName2(graph,input){let normalized=normalizeLookupPath(input);if(path161.isAbsolute(normalized)||/^[A-Za-z]:\//.test(normalized))return normalizeLookupPath(path161.relative(graphRoot(graph),normalized));return normalized}function absoluteKeyForModule(graph,moduleName){return normalizeGraphPath(path161.resolve(graphRoot(graph),moduleName))}function getGraphNode(graph,input){let moduleName=toModuleName2(graph,input),direct=graph.nodes[absoluteKeyForModule(graph,moduleName)];if(direct)return direct;return getQueryIndexes(graph).moduleNameIndex.get(moduleName)}function moduleNameForEdgePath(graph,edgePath){let key=normalizeGraphPath(edgePath),node=graph.nodes[key];if(node)return normalizeLookupPath(node.moduleName);return normalizeLookupPath(path161.relative(graphRoot(graph),edgePath))}function buildReverseIndex(graph){let reverse=new Map,forward=new Map,moduleNameIndex=new Map;for(let node of Object.values(graph.nodes))moduleNameIndex.set(normalizeLookupPath(node.moduleName),node);for(let edge of graph.edges){if(isAssetEdge(edge))continue;let source=normalizeGraphPath(edge.source),target=normalizeGraphPath(edge.target),sourceRef={file:moduleNameForEdgePath(graph,edge.source),importType:edge.importType},targetRef={file:moduleNameForEdgePath(graph,edge.target),importType:edge.importType},reverseRefs=reverse.get(target);if(reverseRefs)reverseRefs.push(sourceRef);else reverse.set(target,[sourceRef]);let forwardRefs=forward.get(source);if(forwardRefs)forwardRefs.push(targetRef);else forward.set(source,[targetRef])}for(let refs of reverse.values())refs.sort((a,b)=>a.file.localeCompare(b.file));for(let refs of forward.values())refs.sort((a,b)=>a.file.localeCompare(b.file));return cachedReverseIndex={graph,index:reverse,forwardIndex:forward,moduleNameIndex},reverse}function getQueryIndexes(graph){if(cachedReverseIndex&&cachedReverseIndex.graph===graph)return cachedReverseIndex;return buildReverseIndex(graph),cachedReverseIndex}function getReverseIndex(graph){return getQueryIndexes(graph).index}function getForwardIndex(graph){return getQueryIndexes(graph).forwardIndex}function resetQueryCache(){cachedReverseIndex=null}function isSafeHealthPath(value){if(typeof value!=="string")return!1;if(value.length===0||value.length>MAX_HEALTH_PATH_LENGTH)return!1;if(containsControlChars(value)||containsPathTraversal(value))return!1;if(path161.isAbsolute(value)||/^[A-Za-z]:[\\/]/.test(value))return!1;return!0}function isSafeHealthText(value){if(typeof value!=="string")return!1;if(value.length===0||value.length>MAX_HEALTH_PATH_LENGTH)return!1;if(containsControlChars(value))return!1;return!0}function cap(entries){return entries.slice(0,GRAPH_HEALTH_OUTPUT_LIMIT)}function sanitizeExtractionFailures(value){if(!Array.isArray(value))return[];let entries=[];for(let raw of value){if(!raw||typeof raw!=="object")continue;let entry=raw;if(isSafeHealthPath(entry.file)&&isSafeHealthText(entry.language)&&isSafeHealthText(entry.reason))entries.push({file:entry.file,language:entry.language,reason:entry.reason})}return cap(entries)}function sanitizeUnresolvedImports(value){if(!Array.isArray(value))return[];let entries=[];for(let raw of value){if(!raw||typeof raw!=="object")continue;let entry=raw;if(isSafeHealthPath(entry.file)&&isSafeHealthText(entry.specifier))entries.push({file:entry.file,specifier:entry.specifier})}return cap(entries)}function sanitizePathList(value){if(!Array.isArray(value))return[];return cap(value.filter(isSafeHealthPath))}function getProbeStaleFiles(probe2,workspaceRoot){if(!probe2)return[];let root=path161.resolve(workspaceRoot),stale=new Set;for(let absolutePath2 of[...probe2.changed,...probe2.removed]){if(typeof absolutePath2!=="string"||!path161.isAbsolute(absolutePath2))continue;let relative37=normalizeGraphPath(path161.relative(root,absolutePath2));if(!isSafeHealthPath(relative37))continue;stale.add(relative37)}return[...stale].sort((a,b)=>a.localeCompare(b)).slice(0,GRAPH_HEALTH_OUTPUT_LIMIT)}function getGraphHealth(graph,workspaceRoot,probe2){let probeState=probe2?.state??"no-fingerprint";if(!graph)return{schemaVersion:null,fresh:!1,probeState,staleFiles:[],extractionFailures:[],unresolvedImports:[],oversizedFiles:[],unsupportedFiles:[],binaryFiles:[],unreadableFiles:[],validationSkippedFiles:[],lowConfidenceEdgeCount:0,walkTruncated:!1,walkTruncationReason:null,incrementalFallbacks:0,notes:['No repo graph found at .swarm/repo-graph.json. Run repo_map with action="build" first.']};let diagnostics=graph.diagnostics,fresh=probeState==="clean",staleFiles=getProbeStaleFiles(probe2,workspaceRoot??graph.workspaceRoot),notes=[];if(probeState==="drifted")notes.push('Graph content is stale relative to the workspace. Run repo_map with action="build" if automatic refresh is unavailable.');else if(probeState==="no-fingerprint")notes.push('Graph has no matching content fingerprint. Run repo_map with action="build" to certify it.');else if(probeState==="inconclusive")notes.push("Graph freshness is unknown because the bounded workspace probe did not complete; no refresh or deletion was attempted.");if(!diagnostics)notes.push('Graph has no recorded diagnostics. Rebuild with repo_map action="build" to collect health details.');let binaryFiles=sanitizePathList(diagnostics?.binaryFiles),binaryCount=binaryFiles.length;if(binaryCount>0)notes.push(`${binaryCount} binary files skipped during last build.`);let unreadableFiles=sanitizePathList(diagnostics?.unreadableFiles),unreadableCount=unreadableFiles.length;if(unreadableCount>0)notes.push(`${unreadableCount} unreadable files skipped during last build.`);let walkTruncated=diagnostics?.walkTruncated===!0,rawReason=diagnostics?.walkTruncationReason,walkTruncationReason=rawReason==="budget"||rawReason==="cap"?rawReason:null,incrementalFallbacks=typeof diagnostics?.incrementalFallbacks==="number"&&Number.isFinite(diagnostics.incrementalFallbacks)&&diagnostics.incrementalFallbacks>0?Math.floor(diagnostics.incrementalFallbacks):0;if(walkTruncated)notes.push("Graph is INCOMPLETE: walk hit the file-cap/wall-clock budget — results may be missing files."+(walkTruncationReason?` (reason: ${walkTruncationReason})`:""));if(incrementalFallbacks>0)notes.push(`${incrementalFallbacks} incremental update(s) fell back to a full rebuild (validation failure or concurrent modification).`);return{schemaVersion:graph.schema_version,fresh,probeState,staleFiles,extractionFailures:sanitizeExtractionFailures(diagnostics?.extractionFailures),unresolvedImports:sanitizeUnresolvedImports(diagnostics?.unresolvedImports),oversizedFiles:sanitizePathList(diagnostics?.oversizedFiles),unsupportedFiles:sanitizePathList(diagnostics?.unsupportedFiles),binaryFiles,unreadableFiles,validationSkippedFiles:sanitizePathList(diagnostics?.validationSkippedFiles),lowConfidenceEdgeCount:typeof diagnostics?.lowConfidenceEdgeCount==="number"&&Number.isFinite(diagnostics.lowConfidenceEdgeCount)&&diagnostics.lowConfidenceEdgeCount>0?Math.floor(diagnostics.lowConfidenceEdgeCount):0,walkTruncated,walkTruncationReason,incrementalFallbacks,notes}}function getImporters(graph,filePath){let node=getGraphNode(graph,filePath);if(!node)return[];return getReverseIndex(graph).get(normalizeGraphPath(node.filePath))??[]}function getDependencies(graph,filePath){let node=getGraphNode(graph,filePath);if(!node)return[];let sourceKey=normalizeGraphPath(node.filePath);return getForwardIndex(graph).get(sourceKey)??[]}function getSymbolConsumers(graph,filePath,symbolName){let node=getGraphNode(graph,filePath);if(!node)return[];let targetKey=normalizeGraphPath(node.filePath),refs=[];for(let edge of graph.edges){if(isAssetEdge(edge))continue;if(normalizeGraphPath(edge.target)!==targetKey)continue;let importedSymbols=edge.importedSymbols??[];if(edge.importType==="namespace"){refs.push({file:moduleNameForEdgePath(graph,edge.source),importedAs:"*"});continue}if(importedSymbols.includes(symbolName))refs.push({file:moduleNameForEdgePath(graph,edge.source),importedAs:symbolName})}return refs.sort((a,b)=>a.file.localeCompare(b.file)),refs}function getCallers(graph,filePath,symbolName){let node=getGraphNode(graph,filePath);if(!node)return[];let targetKey=normalizeGraphPath(node.filePath),refs=[],seen=new Set;for(let edge of graph.edges){if(isAssetEdge(edge))continue;if(normalizeGraphPath(edge.target)!==targetKey)continue;let file3=moduleNameForEdgePath(graph,edge.source);if(seen.has(file3))continue;if(edge.usedSymbols!==void 0){if(edge.usedSymbols.includes(symbolName))seen.add(file3),refs.push({file:file3,resolution:"used"});continue}let imported=edge.importedSymbols??[];if(edge.importType==="namespace"||imported.includes(symbolName))seen.add(file3),refs.push({file:file3,resolution:"imported"})}return refs.sort((a,b)=>a.file.localeCompare(b.file)),refs}function getDeadExports(graph,options){if(!isSchemaVersionAtLeast(graph.schema_version,"1.1.0"))return{schemaSupported:!1,analyzedFiles:0,skippedUnresolvable:0,candidates:[],note:'Graph predates schema 1.1.0 (no usedSymbols data). Run repo_map action="build" to enable dead_exports.'};let usage=new Map;for(let edge of graph.edges){if(isAssetEdge(edge))continue;let target=normalizeGraphPath(edge.target),entry=usage.get(target);if(!entry)entry={used:new Set,unresolvable:!1},usage.set(target,entry);if(edge.importType==="namespace"||edge.importType==="sideeffect"||edge.importType==="require")entry.unresolvable=!0;else if(edge.usedSymbols)for(let symbol3 of edge.usedSymbols)entry.used.add(symbol3)}let reverse=getReverseIndex(graph),candidates=[],analyzedFiles=0,skippedUnresolvable=0;for(let node of Object.values(graph.nodes)){if(node.exports.length===0)continue;let key=normalizeGraphPath(node.filePath),importerCount=reverse.get(key)?.length??0;if(importerCount===0)continue;if((node.ontology?.roles??[]).some((r)=>DEAD_EXPORT_EXCLUDED_ROLES.has(r)))continue;let entry=usage.get(key);if(entry?.unresolvable){skippedUnresolvable++;continue}analyzedFiles++;let used=entry?.used??new Set;for(let symbol3 of node.exports){if(symbol3==="default")continue;if(used.has(symbol3))continue;candidates.push({file:node.moduleName,symbol:symbol3,line:node.exportLines!==void 0&&Object.hasOwn(node.exportLines,symbol3)?node.exportLines[symbol3]:void 0,importerCount})}}candidates.sort((a,b)=>a.file.localeCompare(b.file)||a.symbol.localeCompare(b.symbol));let limit=options?.maxCandidates??100,truncated=candidates.length>limit;return{schemaSupported:!0,analyzedFiles,skippedUnresolvable,candidates:candidates.slice(0,limit),note:"Advisory: exported symbols with no detected in-repo reference, limited to files imported by >=1 other file. Regex analysis cannot see dynamic dispatch, string-keyed access, or namespace/barrel re-export usage; verify before removing."+(truncated?` Showing ${limit} of ${candidates.length}.`:"")}}function getBlastRadius(graph,filePaths,maxDepth=3){let targetNodes=filePaths.map((filePath)=>getGraphNode(graph,filePath)).filter((node)=>node!==void 0),targets=targetNodes.map((node)=>normalizeLookupPath(node.moduleName));if(maxDepth<=0||targetNodes.length===0)return{target:filePaths.map((filePath)=>toModuleName2(graph,filePath)),directDependents:[],transitiveDependents:[],depthReached:0,totalDependents:0,riskLevel:"low"};let reverse=getReverseIndex(graph),visited=new Set(targetNodes.map((node)=>normalizeGraphPath(node.filePath))),direct=new Set,transitive=new Set,depthReached=0,queue=targetNodes.map((node)=>({key:normalizeGraphPath(node.filePath),depth:0}));while(queue.length>0){let next=[];for(let{key,depth}of queue){let importers=reverse.get(key)??[];for(let ref of importers){let importerNode=getGraphNode(graph,ref.file);if(!importerNode)continue;let importerKey=normalizeGraphPath(importerNode.filePath);if(visited.has(importerKey))continue;if(visited.add(importerKey),depth===0)direct.add(ref.file);else transitive.add(ref.file);if(depthReached=Math.max(depthReached,depth+1),depth+1<maxDepth)next.push({key:importerKey,depth:depth+1})}}queue=next}let totalDependents=direct.size+transitive.size;return{target:targets,directDependents:[...direct].sort(),transitiveDependents:[...transitive].sort(),depthReached,totalDependents,riskLevel:classifyRisk(totalDependents)}}function classifyRisk(count){if(count<=3)return"low";if(count<=10)return"medium";if(count<=25)return"high";return"critical"}function getKeyFiles(graph,topN=10){let reverse=getReverseIndex(graph),scored=Object.values(graph.nodes).map((node)=>({node,inDegree:reverse.get(normalizeGraphPath(node.filePath))?.length??0}));return scored.sort((a,b)=>{if(b.inDegree!==a.inDegree)return b.inDegree-a.inDegree;return a.node.moduleName.localeCompare(b.node.moduleName)}),scored.slice(0,topN).map((item)=>item.node)}function getFileOntology(graph,filePath){return getGraphNode(graph,filePath)?.ontology??null}function getLocalizationContext(graph,filePath,options={}){let target=toModuleName2(graph,filePath),node=getGraphNode(graph,target),importers=getImporters(graph,target),dependencies=getDependencies(graph,target),blast=getBlastRadius(graph,[target],options.maxDepth??2),externalSymbols=collectExternallyUsedSymbols(graph,node),summary=formatLocalizationSummary({target,importers,dependencies,blast,externalSymbols,ontology:node?.ontology??null,maxImporters:options.maxImporters??5,maxDeps:options.maxDeps??5});return{target,importerCount:importers.length,importers:importers.slice(0,options.maxImporters??5),dependencyCount:dependencies.length,dependencies:dependencies.slice(0,options.maxDeps??5),exportedSymbolsUsedExternally:externalSymbols,blastRadius:blast,summary}}function getContextPack(graph,file3,symbol3,options={}){if(!isSchemaVersionAtLeast(graph.schema_version,"1.2.0"))return{schemaSupported:!1,target:{file:file3,symbol:symbol3},spans:[],truncated:!1,estimatedTokens:0,note:'rebuild with repo_map action="build"'};let maxDepth=options.maxDepth??2,maxTokens=options.maxTokens??4000,targetNode=getGraphNode(graph,file3);if(!targetNode)return{schemaSupported:!0,target:{file:file3,symbol:symbol3},spans:[],truncated:!1,estimatedTokens:0,note:"Target file not found in graph"};let targetFile=normalizeGraphPath(targetNode.filePath),forward=new Map,reverse=new Map,symbolEdges=graph.symbolEdges??[];for(let edge of symbolEdges){let fromKey=`${normalizeGraphPath(edge.fromFile)}\x00${edge.fromSymbol}`,toKey=`${normalizeGraphPath(edge.toFile)}\x00${edge.toSymbol}`,fromEdges=forward.get(fromKey);if(fromEdges)fromEdges.push(edge);else forward.set(fromKey,[edge]);let toEdges=reverse.get(toKey);if(toEdges)toEdges.push(edge);else reverse.set(toKey,[edge])}let targetKey=`${targetFile}\x00${symbol3}`,visited=new Map,queue=[{key:targetKey,depth:0}];visited.set(targetKey,0);let reached=[],queueHead=0;while(queueHead<queue.length){let{key,depth}=queue[queueHead];queueHead++;let[curFile,curSymbol]=key.split("\x00",2);if(reached.push({file:curFile,symbol:curSymbol,depth}),depth>=maxDepth)continue;let outEdges=forward.get(key)??[];for(let edge of outEdges){let nextKey=`${normalizeGraphPath(edge.toFile)}\x00${edge.toSymbol}`;if(!visited.has(nextKey))visited.set(nextKey,depth+1),queue.push({key:nextKey,depth:depth+1})}let inEdges=reverse.get(key)??[];for(let edge of inEdges){let nextKey=`${normalizeGraphPath(edge.fromFile)}\x00${edge.fromSymbol}`;if(!visited.has(nextKey))visited.set(nextKey,depth+1),queue.push({key:nextKey,depth:depth+1})}}let TOKENS_PER_LINE=12,TOKENS_PER_SIGNATURE=10,spansWithDepth=[];for(let{file:symFile,symbol:sym,depth:d}of reached){let ranges=graph.nodes[symFile]?.exportRanges,range=ranges!==void 0&&Object.hasOwn(ranges,sym)?ranges[sym]:void 0;if(!range){spansWithDepth.push({span:{file:symFile,symbol:sym,startLine:1,endLine:1,mode:"signature",note:"internal symbol — span unavailable"},depth:d});continue}let mode=d===0?"full":d<maxDepth?"full":"signature";spansWithDepth.push({span:{file:symFile,symbol:sym,startLine:range.startLine,endLine:range.endLine,mode},depth:d})}spansWithDepth.sort((a,b)=>{let aIsTarget=a.span.file===targetFile&&a.span.symbol===symbol3?0:1,bIsTarget=b.span.file===targetFile&&b.span.symbol===symbol3?0:1;if(aIsTarget!==bIsTarget)return aIsTarget-bIsTarget;if(a.depth!==b.depth)return a.depth-b.depth;let fileCmp=a.span.file.localeCompare(b.span.file);if(fileCmp!==0)return fileCmp;return a.span.symbol.localeCompare(b.span.symbol)});let includeSource=options.includeSource??!1,directory=options.directory??graph.workspaceRoot,MAX_SOURCE_LINES=80,estimatedTokens=0,finalSpans=[],truncated=!1;for(let{span}of spansWithDepth){let spanTokens=span.mode==="full"?(span.endLine-span.startLine+1)*TOKENS_PER_LINE:TOKENS_PER_SIGNATURE;if(finalSpans.length>0&&estimatedTokens+spanTokens>maxTokens){truncated=!0;break}if(includeSource&&!span.note&&span.mode==="full"){let absPath=path161.isAbsolute(span.file)?span.file:path161.resolve(directory,span.file),resolved=path161.resolve(absPath),resolvedDir=path161.resolve(directory);if(resolved.startsWith(resolvedDir+path161.sep)||resolved===resolvedDir)try{let lines=fs83.readFileSync(resolved,"utf-8").split(`
|
|
3094
3137
|
`),start=Math.max(0,span.startLine-1),end=Math.min(lines.length,span.startLine-1+MAX_SOURCE_LINES,span.endLine),slice=lines.slice(start,end);span.text=slice.join(`
|
|
3095
3138
|
`),spanTokens=slice.length*TOKENS_PER_LINE}catch{span.note="source read failed"}}finalSpans.push(span),estimatedTokens+=spanTokens}let result={schemaSupported:!0,target:{file:targetFile,symbol:symbol3},spans:finalSpans,truncated,estimatedTokens};if(includeSource)result.sourceIncluded=!0;return result}function collectExternallyUsedSymbols(graph,node){if(!node)return[];let exported=new Set(node.exports),used=new Set,targetKey=normalizeGraphPath(node.filePath);for(let edge of graph.edges){if(isAssetEdge(edge))continue;if(normalizeGraphPath(edge.target)!==targetKey)continue;for(let symbol3 of edge.importedSymbols??[])if(exported.has(symbol3))used.add(symbol3)}return[...used].sort((a,b)=>a.localeCompare(b))}function formatLocalizationSummary(opts){let importerList=opts.importers.length===0?"(none)":opts.importers.slice(0,opts.maxImporters).map((ref)=>ref.file).join(", ")+(opts.importers.length>opts.maxImporters?`, +${opts.importers.length-opts.maxImporters} more`:""),depList=opts.dependencies.length===0?"(none)":opts.dependencies.slice(0,opts.maxDeps).map((ref)=>ref.file).join(", ")+(opts.dependencies.length>opts.maxDeps?`, +${opts.dependencies.length-opts.maxDeps} more`:""),symbolList=opts.externalSymbols.length===0?"(none used externally)":opts.externalSymbols.slice(0,8).join(", ")+(opts.externalSymbols.length>8?`, +${opts.externalSymbols.length-8} more`:""),roles=opts.ontology?.roles.join(", ")||"unknown",findings=opts.ontology?.findings.length??0;return["LOCALIZATION CONTEXT",` Target: ${opts.target}`,` Roles: ${roles}`,` Imported by (${opts.importers.length}): ${importerList}`,` Imports (${opts.dependencies.length}): ${depList}`,` Exports used externally: ${symbolList}`,` Blast radius: ${opts.blast.totalDependents} files (${opts.blast.riskLevel} risk)`,` Ontology findings: ${findings}`].join(`
|
|
3096
3139
|
`)}function getPackageBoundaries(graph,topN=25){return summarizePackageBoundaries(Object.values(graph.nodes),graph.edges,topN)}function summarizePackageBoundaries(nodes,edges,topN){let groups=new Map,ensure=(node)=>{let name=node.ontology?.packageBoundary||inferBoundary(node.moduleName),group=groups.get(name);if(!group)group={name,root:name,fileCount:0,roles:{},dependsOn:[],dependedOnBy:[],routeCount:0,dataOperationCount:0,findingCount:0,publicFiles:[]},groups.set(name,group);return group},boundaryByPath=new Map;for(let node of nodes){let group=ensure(node);boundaryByPath.set(normalizeGraphPath(node.filePath),group.name),group.fileCount++;let ontology=node.ontology;for(let role of ontology?.roles??["source_module"])group.roles[role]=(group.roles[role]??0)+1;if(group.routeCount+=ontology?.routes.length??0,group.dataOperationCount+=ontology?.dataOperations.length??0,group.findingCount+=ontology?.findings.length??0,node.exports.length>0)group.publicFiles.push(node.moduleName)}let dependsOn=new Map,dependedOnBy=new Map;for(let edge of edges){if(isAssetEdge(edge))continue;let sourceBoundary=boundaryByPath.get(normalizeGraphPath(edge.source)),targetBoundary=boundaryByPath.get(normalizeGraphPath(edge.target));if(!sourceBoundary||!targetBoundary||sourceBoundary===targetBoundary)continue;if(!dependsOn.has(sourceBoundary))dependsOn.set(sourceBoundary,new Set);if(!dependedOnBy.has(targetBoundary))dependedOnBy.set(targetBoundary,new Set);dependsOn.get(sourceBoundary)?.add(targetBoundary),dependedOnBy.get(targetBoundary)?.add(sourceBoundary)}for(let group of groups.values())group.dependsOn=[...dependsOn.get(group.name)??[]].sort(),group.dependedOnBy=[...dependedOnBy.get(group.name)??[]].sort(),group.publicFiles.sort((a,b)=>a.localeCompare(b)),group.publicFiles=group.publicFiles.slice(0,20);return[...groups.values()].sort((a,b)=>{if(b.findingCount!==a.findingCount)return b.findingCount-a.findingCount;if(b.fileCount!==a.fileCount)return b.fileCount-a.fileCount;return a.name.localeCompare(b.name)}).slice(0,topN)}function summarizeSelectedPackageBoundaries(graph,nodes,topN=25){let summaries=summarizePackageBoundaries(nodes,[],topN),boundaryByModule=new Map;for(let node of nodes)boundaryByModule.set(normalizeLookupPath(node.moduleName),node.ontology?.packageBoundary??inferBoundary(node.moduleName));let byName=new Map(summaries.map((summary)=>[summary.name,summary])),dependsOn=new Map,dependedOnBy=new Map;for(let node of nodes){let sourceBoundary=boundaryByModule.get(normalizeLookupPath(node.moduleName));if(!sourceBoundary)continue;for(let dep of getDependencies(graph,node.moduleName)){let targetBoundary=boundaryByModule.get(normalizeLookupPath(dep.file));if(!targetBoundary||sourceBoundary===targetBoundary||!byName.has(sourceBoundary)||!byName.has(targetBoundary))continue;if(!dependsOn.has(sourceBoundary))dependsOn.set(sourceBoundary,new Set);if(!dependedOnBy.has(targetBoundary))dependedOnBy.set(targetBoundary,new Set);dependsOn.get(sourceBoundary)?.add(targetBoundary),dependedOnBy.get(targetBoundary)?.add(sourceBoundary)}}for(let summary of summaries)summary.dependsOn=[...dependsOn.get(summary.name)??[]].sort(),summary.dependedOnBy=[...dependedOnBy.get(summary.name)??[]].sort();return summaries}function inferBoundary(moduleName){return inferPackageBoundary(moduleName)}function buildOntologyPreflightPacket(graph,filePaths=[],options={}){let maxFiles=options.maxFiles??12,maxFindings=options.maxFindings??20,boundedNodes=(filePaths.length>0?filePaths.map((filePath)=>getGraphNode(graph,filePath)).filter((node)=>node!==void 0):getKeyFiles(graph,maxFiles)).slice(0,maxFiles),findings=boundedNodes.flatMap((node)=>(node.ontology?.findings??[]).map((finding)=>({file:node.moduleName,...finding}))).slice(0,maxFindings),routes=boundedNodes.flatMap((node)=>(node.ontology?.routes??[]).map((route)=>({file:node.moduleName,...route}))),dataOperations=boundedNodes.flatMap((node)=>(node.ontology?.dataOperations??[]).map((fact)=>({file:node.moduleName,...fact}))),security=boundedNodes.flatMap((node)=>(node.ontology?.security??[]).map((fact)=>({file:node.moduleName,...fact})));return{generatedAt:new Date().toISOString(),targets:boundedNodes.map((node)=>node.moduleName),summary:{fileCount:Object.keys(graph.nodes).length,edgeCount:graph.edges.length,targetCount:boundedNodes.length,findingCount:findings.length,routeCount:routes.length,dataOperationCount:dataOperations.length,securityFactCount:security.length},files:boundedNodes.map((node)=>({file:node.moduleName,roles:node.ontology?.roles??[],packageBoundary:node.ontology?.packageBoundary??inferBoundary(node.moduleName),importerCount:getImporters(graph,node.moduleName).length,dependencyCount:getDependencies(graph,node.moduleName).length,routeCount:node.ontology?.routes.length??0,dataOperationCount:node.ontology?.dataOperations.length??0,securityFactCount:node.ontology?.security.length??0,findingCount:node.ontology?.findings.length??0})),routes,dataOperations,security,findings,packageBoundaries:summarizeSelectedPackageBoundaries(graph,boundedNodes,options.maxBoundaries??10)}}var GRAPH_HEALTH_OUTPUT_LIMIT=50,MAX_HEALTH_PATH_LENGTH=500,cachedReverseIndex=null,DEAD_EXPORT_EXCLUDED_ROLES;var init_query=__esm(()=>{init_path_security();init_builder();init_types3();DEAD_EXPORT_EXCLUDED_ROLES=new Set(["api_route","cli_command","test_file","agent","hook","middleware"])});import*as path162 from"node:path";function normalizeWorkspace(workspace){let resolved=path162.normalize(path162.resolve(workspace));return process.platform==="win32"?resolved.toLowerCase():resolved}function touch(key,entry){return workspaceCache.delete(key),workspaceCache.set(key,entry),entry}function getEntry(workspace){let key=normalizeWorkspace(workspace),entry=workspaceCache.get(key);return entry?touch(key,entry):void 0}function setEntry(workspace,entry){let key=normalizeWorkspace(workspace);touch(key,entry);while(workspaceCache.size>MAX_CACHED_WORKSPACES){let oldestKey=workspaceCache.keys().next().value;if(oldestKey===void 0)break;workspaceCache.delete(oldestKey)}}function getCachedGraph(workspace){return getEntry(workspace)?.graph}function setCachedGraph(workspace,graph,mtime){setEntry(workspace,{graph,dirty:!1,...mtime===void 0?{}:{mtime}})}function isDirty(workspace){return getEntry(workspace)?.dirty??!1}function clearCache(workspace){workspaceCache.delete(normalizeWorkspace(workspace))}function getCachedMtime(workspace){return getEntry(workspace)?.mtime}var MAX_CACHED_WORKSPACES=16,workspaceCache;var init_cache=__esm(()=>{workspaceCache=new Map});import{createHash as createHash52}from"node:crypto";import*as fsPromises7 from"node:fs/promises";import*as path163 from"node:path";function normalizeRoot(root){let resolved=path163.normalize(path163.resolve(root));return process.platform==="win32"?resolved.toLowerCase():resolved}function normalizedExcludes(options){return[...new Set((options?.excludeDirs??[]).filter(Boolean))].sort((a,b)=>a.localeCompare(b))}function exclusionStamp(options){return createHash52("sha256").update(JSON.stringify({excludeDirs:normalizedExcludes(options),followSymlinks:options?.followSymlinks??!1})).digest("hex")}function optionSignature(options){return JSON.stringify({walkBudgetMs:options?.walkBudgetMs??DEFAULT_WALK_BUDGET_MS2,maxFiles:options?.maxFiles??DEFAULT_MAX_FILES,followSymlinks:options?.followSymlinks??!1,excludeDirs:normalizedExcludes(options)})}function touchCache(rootKey,entry){probeCache.delete(rootKey),probeCache.set(rootKey,entry);while(probeCache.size>MAX_CACHE_ENTRIES4){let oldest=probeCache.keys().next().value;if(oldest===void 0)break;probeCache.delete(oldest)}}function invalidateFreshnessCache(root){if(root===void 0){probeCache.clear();return}probeCache.delete(normalizeRoot(root))}function fingerprintPath(root){let target=validateSwarmPath(root,REPO_GRAPH_FINGERPRINT_FILENAME);return validateSymlinkBoundary(target,root),target}async function writeFingerprintAtomic(root,data){let target=fingerprintPath(root),temp=path163.join(path163.dirname(target),`.repo-graph.fingerprint.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2,10)}.tmp`);validateSymlinkBoundary(temp,root);try{await _internals126.bunWrite(temp,data);let lastError;for(let attempt=0;attempt<WINDOWS_RENAME_MAX_RETRIES4;attempt++)try{await _internals126.fsRename(temp,target),lastError=void 0;break}catch(error93){lastError=error93;let code=error93.code;if(code!=="EEXIST"&&code!=="EPERM"&&code!=="EBUSY"||attempt===WINDOWS_RENAME_MAX_RETRIES4-1)break;await new Promise((resolve72)=>setTimeout(resolve72,_internals126.retryDelayMs))}if(lastError!==void 0)throw lastError}finally{try{await _internals126.fsUnlink(temp)}catch{}}}async function refuseFingerprint(root){try{await _internals126.fsUnlink(fingerprintPath(root))}catch{}return invalidateFreshnessCache(root),!1}function safeRelativePath(value){if(value.length===0||value.length>MAX_RELATIVE_PATH_LENGTH||containsControlChars(value)||path163.isAbsolute(value)||/^[A-Za-z]:[/\\]/.test(value))return null;let normalized=value.replace(/\\/g,"/").replace(/^(?:\.\/)+/,"");if(normalized.length===0||normalized.split("/").some((segment)=>segment===".."||segment===""))return null;return normalized}function relativeFromRoot(root,absolutePath2){let relative38=path163.relative(path163.resolve(root),path163.resolve(absolutePath2));if(relative38.startsWith("..")||path163.isAbsolute(relative38))return null;return safeRelativePath(relative38)}function absoluteFromRelative(root,relativePath2){let safe=safeRelativePath(relativePath2);if(safe===null)return null;let resolvedRoot=path163.resolve(root),absolute=path163.resolve(resolvedRoot,safe),relative38=path163.relative(resolvedRoot,absolute);if(relative38.startsWith("..")||path163.isAbsolute(relative38))return null;return absolute}function validMetadata(value){if(!value||typeof value!=="object"||Array.isArray(value))return!1;let record3=value;return Object.keys(record3).length===2&&typeof record3.size==="number"&&Number.isFinite(record3.size)&&record3.size>=0&&typeof record3.mtimeMs==="number"&&Number.isFinite(record3.mtimeMs)&&record3.mtimeMs>=0}function parseFingerprint(value,options){if(!value||typeof value!=="object"||Array.isArray(value))return null;let record3=value;if(Object.keys(record3).sort().join(",")!=="exclusionStamp,extractorStamp,files,schema_version"||record3.schema_version!==FINGERPRINT_SCHEMA_VERSION||record3.extractorStamp!==EXTRACTOR_STAMP||record3.exclusionStamp!==exclusionStamp(options)||!record3.files||typeof record3.files!=="object"||Array.isArray(record3.files))return null;let rawFiles=record3.files,entries=Object.entries(rawFiles);if(entries.length>MAX_FINGERPRINT_ENTRIES)return null;let files=Object.create(null);for(let[rawPath,metadata]of entries){let safe=safeRelativePath(rawPath);if(safe===null||safe!==rawPath||!validMetadata(metadata))return null;files[safe]=metadata}return{schema_version:FINGERPRINT_SCHEMA_VERSION,extractorStamp:EXTRACTOR_STAMP,exclusionStamp:exclusionStamp(options),files}}function emptyProbe(state,elapsedMs){return{state,changed:[],removed:[],truncated:!1,probedFiles:0,elapsedMs:Math.max(0,elapsedMs)}}async function readFingerprint(root,options){let target=fingerprintPath(root),handle=await _internals126.open(target,"r");try{let stats2=await handle.stat();if(stats2.size>MAX_FINGERPRINT_BYTES)return null;let buffer=Buffer.alloc(stats2.size),offset=0;while(offset<buffer.length){let read=await handle.read(buffer,offset,buffer.length-offset,offset);if(read.bytesRead===0)break;offset+=read.bytesRead}let data=buffer.subarray(0,offset).toString("utf8");return parseFingerprint(JSON.parse(data),options)}finally{await handle.close()}}async function probeUncached(root,options){let startedAt=_internals126.now(),fingerprint2;try{fingerprint2=await readFingerprint(root,options)}catch{fingerprint2=null}if(fingerprint2===null)return emptyProbe("no-fingerprint",_internals126.now()-startedAt);let walk;try{walk=await _internals126.walkRepoGraphInputs(root,{walkBudgetMs:options?.walkBudgetMs,maxFiles:options?.maxFiles,followSymlinks:options?.followSymlinks,excludeDirs:options?.excludeDirs,captureMetadata:!0})}catch{return{...emptyProbe("inconclusive",_internals126.now()-startedAt),truncated:!1}}let current=new Map,changed2=[];for(let input of walk.metadata){let relative38=relativeFromRoot(root,input.absolutePath);if(relative38===null)continue;let metadata={size:input.sizeBytes,mtimeMs:input.mtimeMs};current.set(relative38,metadata);let previous=fingerprint2.files[relative38];if(previous===void 0||previous.size!==metadata.size||previous.mtimeMs!==metadata.mtimeMs)changed2.push(path163.resolve(input.absolutePath))}let incomplete=walk.incomplete,removed=[];if(!incomplete){for(let relative38 of Object.keys(fingerprint2.files))if(!current.has(relative38)){let absolute=absoluteFromRelative(root,relative38);if(absolute!==null)removed.push(absolute)}}return changed2.sort((a,b)=>a.localeCompare(b)),removed.sort((a,b)=>a.localeCompare(b)),{state:incomplete?"inconclusive":changed2.length>0||removed.length>0?"drifted":"clean",changed:changed2,removed:incomplete?[]:removed,truncated:walk.truncated,probedFiles:walk.probedFiles,elapsedMs:Math.max(0,_internals126.now()-startedAt)}}async function probeFreshness(root,options){let rootKey=normalizeRoot(root),signature=optionSignature(options),now2=_internals126.now(),cached3=probeCache.get(rootKey);if(cached3?.signature===signature){if(cached3.value&&cached3.expiresAt>now2)return touchCache(rootKey,cached3),cached3.value;if(cached3.inFlight)return touchCache(rootKey,cached3),cached3.inFlight}let inFlight=probeUncached(root,options),entry={signature,expiresAt:0,inFlight};touchCache(rootKey,entry);try{let value=await inFlight;if(probeCache.get(rootKey)?.inFlight===inFlight)entry.value=value,entry.expiresAt=_internals126.now()+CACHE_TTL_MS3,entry.inFlight=void 0,touchCache(rootKey,entry);return value}catch{if(probeCache.get(rootKey)?.inFlight===inFlight)probeCache.delete(rootKey);return emptyProbe("inconclusive",0)}}function diagnosticPaths(root,diagnostics){let reportedStable=new Set;for(let raw of[...diagnostics?.oversizedFiles??[],...diagnostics?.binaryFiles??[],...diagnostics?.validationSkippedFiles??[]]){let safe=safeRelativePath(raw);if(safe===null)return null;if(absoluteFromRelative(root,safe)===null)return null;reportedStable.add(safe)}let witnesses=new Map,stable=new Set;for(let witness of diagnostics?.extractorInputWitnesses??[]){let safe=safeRelativePath(witness.file);if(safe===null||witness.kind!=="manifest"&&witness.kind!=="stable-skip"||!Number.isFinite(witness.sizeBytes)||witness.sizeBytes<0||!Number.isFinite(witness.mtimeMs)||witness.mtimeMs<0||witnesses.has(safe))return null;if(witnesses.set(safe,{...witness,file:safe}),witness.kind==="stable-skip")stable.add(safe)}for(let relative38 of reportedStable)if(witnesses.get(relative38)?.kind!=="stable-skip")return null;return{stable,witnesses}}async function writeFingerprint(root,graph,options){invalidateFreshnessCache(root);try{let walk=await _internals126.walkRepoGraphInputs(root,{walkBudgetMs:options?.walkBudgetMs,maxFiles:options?.maxFiles,followSymlinks:options?.followSymlinks,excludeDirs:options?.excludeDirs,captureMetadata:!0});if(walk.unreadableDirectories.length>0||walk.unreadableFiles.length>0)return refuseFingerprint(root);let certifiedInputs=diagnosticPaths(root,graph.diagnostics);if(certifiedInputs===null)return refuseFingerprint(root);let current=new Map;for(let input of walk.metadata){let relative38=relativeFromRoot(root,input.absolutePath);if(relative38===null)return refuseFingerprint(root);current.set(relative38,{size:input.sizeBytes,mtimeMs:input.mtimeMs})}for(let[relative38,witness]of certifiedInputs.witnesses){let observed=current.get(relative38);if(observed===void 0||observed.size!==witness.sizeBytes||observed.mtimeMs!==witness.mtimeMs)return refuseFingerprint(root)}let nodePaths=new Set;for(let node of Object.values(graph.nodes)){let relative38=relativeFromRoot(root,node.filePath);if(relative38===null)return refuseFingerprint(root);if(typeof node.sizeBytes!=="number"||!Number.isFinite(node.sizeBytes)||node.sizeBytes<0||typeof node.mtimeMs!=="number"||!Number.isFinite(node.mtimeMs)||node.mtimeMs<0)return refuseFingerprint(root);let observed=current.get(relative38);if(observed===void 0||observed.size!==node.sizeBytes||observed.mtimeMs!==node.mtimeMs)return refuseFingerprint(root);nodePaths.add(relative38)}for(let input of walk.metadata){let relative38=relativeFromRoot(root,input.absolutePath);if(relative38===null)return refuseFingerprint(root);if(input.kind==="manifest"&&certifiedInputs.witnesses.get(relative38)?.kind!=="manifest")return refuseFingerprint(root);if(input.kind!=="source")continue;if(!nodePaths.has(relative38)&&!certifiedInputs.stable.has(relative38))return refuseFingerprint(root)}let files=Object.create(null);for(let relative38 of[...current.keys()].sort((a,b)=>a.localeCompare(b)))files[relative38]=current.get(relative38);if(Object.keys(files).length>MAX_FINGERPRINT_ENTRIES)return refuseFingerprint(root);let sidecar={schema_version:FINGERPRINT_SCHEMA_VERSION,extractorStamp:EXTRACTOR_STAMP,exclusionStamp:exclusionStamp(options),files},serialized2=`${JSON.stringify(sidecar,null,2)}
|
|
@@ -6715,7 +6758,7 @@ MICRO WORKED EXAMPLE:
|
|
|
6715
6758
|
${CANDIDATE_HEADERS.micro_lane}
|
|
6716
6759
|
[CANDIDATE] | example-micro-001 | example-micro | MEDIUM | correctness | src/a.ts:12 | claim without pipes | invariant without pipes | evidence without pipes | HIGH
|
|
6717
6760
|
Zero findings: ${CLEAN_TEMPLATES.micro_lane}
|
|
6718
|
-
${EXPLORER_CANDIDATE_COMMON_END}`,READ_ONLY_LANE_ROLES=new Set(["explorer","reviewer","test_engineer","critic","critic_oversight","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","critic_finding_validator","sme","researcher","council_generalist","council_skeptic","council_domain_expert"]),READ_ONLY_TOOL_DENYLIST=[...new Set([...WRITE_TOOL_NAMES,"extract_code_blocks","multiedit","multi_edit","todo_write","save_plan","update_task_status","phase_complete","declare_scope","declare_council_criteria","submit_council_verdicts","submit_phase_council_verdicts","set_qa_gates","write_retro","write_drift_evidence","write_hallucination_evidence","write_mutation_evidence","knowledge_add","knowledge_remove","consensus_mine","summarize_work","doc_scan","lint"])],LaneSchema=exports_external.object({id:exports_external.string().min(1).max(80).regex(/^[A-Za-z0-9][A-Za-z0-9_.-]*$/).describe("Stable lane identifier, unique within this dispatch batch"),agent:exports_external.string().min(1).max(120).describe("Read-only swarm agent name, including any generated swarm prefix"),prompt:exports_external.string().min(1).max(MAX_PROMPT_CHARS).describe("Full lane prompt to send to the requested agent"),workflow_lane:exports_external.string().min(1).max(120).optional().describe("Required mechanical policy identifier in PR workflows; distinct from the retry-safe lane id"),owned_workflow_lanes:exports_external.array(exports_external.string().trim().min(1).max(120)).min(1).max(11).optional().describe("Complete dimension/family set a consolidated PR-review base or micro lane covers under the controller-computed depth tier; must include workflow_lane. Omit for singleton lanes."),feedback_item_ids:exports_external.array(exports_external.string().trim().min(1).max(120)).min(1).optional().describe("PR-feedback ledger item IDs owned exclusively by this lane"),review_item_ids:exports_external.array(exports_external.string().trim().min(1).max(160)).min(1).max(MAX_PR_REVIEW_COLLECTION_RECEIPT_ITEM_IDS).optional().describe("Candidate/finding IDs owned by a PR-review reviewer or critic lane; every ID requires a parseable verdict row")}),DispatchLanesArgsSchema=exports_external.object({lanes:exports_external.array(LaneSchema).min(1).max(MAX_LANES).describe("Read-only lane specs to dispatch concurrently"),common_prompt:exports_external.string().min(1).regex(/\S/,"common_prompt must contain non-whitespace content").max(MAX_PROMPT_CHARS-COMMON_PROMPT_SEPARATOR.length-1).optional().describe("Optional shared context prepended to every lane prompt. Send large shared context (PR diff, obligation ledger, scope) ONCE here instead of inlining the same blob into each lane prompt; this keeps the tool-call payload small and avoids malformed/truncated tool-call JSON. Combined common_prompt + per-lane prompt must not exceed the per-lane character limit."),max_concurrent:exports_external.number().int().min(1).max(MAX_LANES).optional().describe("Maximum lanes in flight at once; defaults to lane count"),timeout_ms:exports_external.number().int().min(10).max(MAX_TIMEOUT_MS4).optional().describe("Per-lane timeout in milliseconds. For blocking dispatch this covers session create and prompt execution; for async dispatch this covers launch only, never lane runtime."),orientation:exports_external.boolean().optional().describe("Prepend a bounded, deterministic repo-graph orientation block (mission-relevant files, repo hubs, freshness line) to common_prompt when the repo graph is fresh and relevant. No schema default: availability depends on graph state, resolved at execute time (omitted ⇒ attempted, skipped when no fresh graph exists). Explicitly false disables the block entirely.")}),DispatchLanesAsyncArgsSchema=DispatchLanesArgsSchema.extend({launch_timeout_ms:exports_external.number().int().min(10).max(MAX_TIMEOUT_MS4).optional().describe("Async launch acceptance timeout in milliseconds. This only bounds session creation and promptAsync acceptance; it is never a lane runtime timeout. Deprecated alias: timeout_ms."),batch_id:exports_external.string().min(1).max(MAX_BATCH_ID_CHARS).regex(/^[A-Za-z0-9][A-Za-z0-9_.:-]*$/).optional().describe("Stable async batch id for later collection; generated when omitted"),mode:exports_external.string().min(1).max(80).optional().describe('Advisory workflow mode, such as deep-dive. PR-review stages are COLON-SUFFIXED and the suffix is required. Accepted values: swarm-pr-review:base, swarm-pr-review:micro, swarm-pr-review:council, swarm-pr-review:reviewer, swarm-pr-review:critic, swarm-pr-feedback:verification. A bare "swarm-pr-review" does NOT enter the PR-review path — it skips the merge-base bind and later fails with "exact merge-base scope was not verified".'),pr_head_sha:exports_external.string().min(1).max(80).optional().describe("Full 40-char SHA of the PR head commit under review. Required when mode starts with swarm-pr-review: or swarm-pr-feedback:."),base_sha:exports_external.string().regex(/^[0-9a-f]{6,64}$/i).optional().describe("Exact merge base of base_ref and pr_head_sha — NOT the base branch tip. The controller recomputes `git merge-base -- <base_ref> <pr_head_sha>` and rejects any mismatch. Required when mode starts with swarm-pr-review:."),base_ref:exports_external.string().regex(/^(?!-)[A-Za-z0-9][A-Za-z0-9._/-]{0,255}$/).optional().describe("Base branch ref used to recompute the merge base. Use the REMOTE-TRACKING form (origin/main), and compute base_sha against that same ref. A local branch ref (main, refs/heads/main) is only as fresh as the last fetch — the PR-review preflight fetches refs/pull/<N>/head and not the base branch, so a local ref commonly resolves to a different merge base and the dispatch is rejected. Required when mode starts with swarm-pr-review:."),scope:exports_external.string().min(1).max(500).optional(),trigger_evaluation:exports_external.array(PrReviewInlineTriggerRowSchema).min(1).optional().describe("Complete repository-agnostic trigger ledger required for the first swarm-pr-review:micro dispatch. The first successful micro dispatch freezes it in same-session workflow state; any subsequent micro batch may omit this property and reuse that exact frozen ledger. If supplied later, it must remain exactly identical. MATCHED families are dispatched and inapplicable families are NOT_TRIGGERED."),feedback_inventory:exports_external.array(exports_external.string().trim().min(1).max(120)).min(1).optional().describe("Complete immutable feedback item inventory required for swarm-pr-feedback:verification"),pr_review_wave_stage:exports_external.enum(["canary","fanout"]).optional().describe('PR_REVIEW base-only staged dispatch marker. Required with pr_review_wave_attempt at depth tier M or L while pr_review_resilience is enabled. Use "canary" for the singleton probe lane and "fanout" for the follow-up batch that partitions the remaining unresolved base obligations.'),pr_review_wave_attempt:exports_external.number().int().min(0).max(2).optional().describe("PR_REVIEW base-only staged attempt number, required together with pr_review_wave_stage at depth tier M or L while resilience is enabled: attempt 0 is the initial wave, followed by at most two retry attempts (1 and 2) over the exact unresolved-obligation target left by the previous attempt.")}),CollectLaneResultsArgsSchema=exports_external.object({batch_id:exports_external.string().min(1).max(MAX_BATCH_ID_CHARS),wait:exports_external.boolean().optional().describe("Poll until all lanes settle or timeout"),timeout_ms:exports_external.number().int().min(0).max(MAX_COLLECT_TIMEOUT_MS).optional().describe("Total wait budget when wait=true"),include_pending:exports_external.boolean().optional().describe("Include pending/running lanes in lane_results. Defaults to true for non-blocking polls and false for wait=true joins."),cancel_pending:exports_external.boolean().optional().describe("Abort and mark pending/running lanes cancelled")});function validatePrReviewMicroDispatch(args2,depthTier){let evaluation=args2.trigger_evaluation;if(!evaluation)throw Error("BLOCKED: initial PR_REVIEW micro dispatch requires the complete trigger_evaluation ledger; after the first successful same-session micro dispatch freezes it, a later micro batch may omit the property and reuse that exact ledger");let validated;try{validated=validatePrReviewInlineTriggerLedger(evaluation)}catch(error93){throw Error(`BLOCKED: ${error93 instanceof Error?error93.message:String(error93)}`)}let required3=new Set(validated.matchedIds),laneOwnership=args2.lanes.map((lane)=>({label:lane.workflow_lane??"",owned:lane.owned_workflow_lanes?.length?lane.owned_workflow_lanes:lane.workflow_lane?[lane.workflow_lane]:[]}));if(depthTier==="L"&&laneOwnership.some((lane)=>lane.owned.length!==1))throw Error("BLOCKED: PR_REVIEW micro dispatch at depth tier L requires one dedicated lane per risk family; consolidated owned_workflow_lanes are allowed only at tiers S and M");let flattened=laneOwnership.flatMap((lane)=>lane.owned),duplicates=flattened.filter((value,index)=>flattened.indexOf(value)!==index),unmatched=flattened.filter((triggerId)=>!required3.has(triggerId)),invalidLabels=laneOwnership.filter((lane)=>lane.label.length===0||!lane.owned.includes(lane.label)).map((lane)=>lane.label||"(missing workflow_lane)");if(invalidLabels.length>0||duplicates.length>0||unmatched.length>0)throw Error(`BLOCKED: PR_REVIEW micro lanes must have unique workflow_lane IDs from the mandatory repository-agnostic lane set, with workflow_lane contained in its own owned set; invalid: ${[...new Set([...invalidLabels,...duplicates,...unmatched])].join(", ")}`);let coversAllFamilies=required3.size>0&&[...required3].every((id)=>flattened.includes(id)),microFloor=Math.min(PR_REVIEW_MICRO_LANE_FLOORS[depthTier],required3.size);if(coversAllFamilies&&laneOwnership.length<microFloor)throw Error(`BLOCKED: PR_REVIEW micro dispatch at depth tier ${depthTier} covering all ${required3.size} matched risk families requires at least ${microFloor} lanes; received ${laneOwnership.length}. Partial retry batches covering a subset of matched families are exempt; NOT_TRIGGERED families must not be dispatched.`)}var _internals208={getSessionOps:()=>swarmState.opencodeClient?.session??null,getGeneratedAgentNames:()=>swarmState.generatedAgentNames,createParallelDispatcher,loadPluginConfig,resolvePrWorkflowRevisionDigestAsync,resolveExactMergeBaseAsync,validatePrWorkflowTransportRecovery,now:()=>Date.now(),sleep:sleep3};function effectivePrReviewResilienceConfig(configured,gateState){let policy=gateState?.prReviewResilience?.policy;if(!policy)return configured;return{enabled:policy.enabled,canary_probe_ms:policy.canaryProbeMs,status_probe_timeout_ms:policy.statusProbeTimeoutMs,correlated_failure_threshold:policy.correlatedFailureThreshold,max_retry_attempts_after_initial:policy.maxRetryAttemptsAfterInitial}}async function executeDispatchLanes(args2,directory,context={}){let parsed=DispatchLanesArgsSchema.safeParse(args2);if(!parsed.success)return failureResult2({failure_class:"invalid_args",message:"Invalid dispatch_lanes arguments",errors:boundZodIssues(parsed.error.issues)});let duplicateLaneIds=findDuplicateLaneIds(parsed.data.lanes);if(duplicateLaneIds.length>0)return failureResult2({failure_class:"invalid_args",message:"Lane IDs must be unique within one dispatch_lanes batch",errors:duplicateLaneIds.map((id)=>`Duplicate lane id: ${id}`)});if(context.sessionID?.trim())try{await enforcePrWorkflowDispatchLanesAsync(directory,context.sessionID,"dispatch_lanes")}catch(error93){return failureResult2({failure_class:"invalid_args",message:error93 instanceof Error?error93.message:"PR workflow gate rejected dispatch"})}let session=_internals208.getSessionOps();if(!session)return failureResult2({failure_class:"no_client",message:"OpenCode session client is not available"});let orientedCommonPrompt=await augmentCommonPromptWithOrientation(directory,parsed.data.lanes,parsed.data.common_prompt,parsed.data.orientation,context.sessionID),common=applyCommonPrompt(parsed.data.lanes,orientedCommonPrompt);if(!common.ok)return failureResult2({failure_class:"invalid_args",message:"Invalid dispatch_lanes arguments",errors:common.errors});let requiresMandatoryExplorerFormat=common.lanes.some((lane)=>lane.workflow_lane!==void 0||(lane.owned_workflow_lanes?.length??0)>0),formatted=applyExplorerFormatSuffix(common.lanes,{failClosed:requiresMandatoryExplorerFormat});if(!formatted.ok)return failureResult2({failure_class:"invalid_args",message:"Invalid explorer output-format contract",errors:formatted.errors});let lanes=formatted.lanes,maxConcurrent=Math.min(parsed.data.max_concurrent??lanes.length,lanes.length,MAX_LANES),timeoutMs=parsed.data.timeout_ms??DEFAULT_TIMEOUT_MS5,dispatcher=_internals208.createParallelDispatcher({enabled:!0,maxConcurrentTasks:maxConcurrent,evidenceLockTimeoutMs:0}),limit=pLimit(maxConcurrent);try{let laneResults=await Promise.all(lanes.map((lane)=>limit(()=>runLane(session,dispatcher,lane,directory,timeoutMs,context))));return buildResult(laneResults,maxConcurrent,timeoutMs)}finally{dispatcher.shutdown()}}async function executeDispatchLanesAsync(args2,directory,context={}){let parsed=DispatchLanesAsyncArgsSchema.safeParse(args2);if(!parsed.success)return asyncFailureResult({failure_class:"invalid_args",message:"Invalid dispatch_lanes_async arguments",errors:boundZodIssues(parsed.error.issues)});if(typeof parsed.data.mode==="string"){let normalizedMode=parsed.data.mode.trim();parsed.data.mode=normalizedMode.length>0?normalizedMode:void 0}let duplicateLaneIds=findDuplicateLaneIds(parsed.data.lanes);if(duplicateLaneIds.length>0)return asyncFailureResult({failure_class:"invalid_args",message:"Lane IDs must be unique within one dispatch_lanes_async batch",errors:duplicateLaneIds.map((id)=>`Duplicate lane id: ${id}`)});let requestedBatchId=parsed.data.batch_id??makeBatchId(),session=_internals208.getSessionOps();if(!session||typeof session.promptAsync!=="function")return asyncFailureResult({failure_class:"no_client",message:"OpenCode session promptAsync client is not available"});let orientedCommonPrompt=await augmentCommonPromptWithOrientation(directory,parsed.data.lanes,parsed.data.common_prompt,parsed.data.orientation,context.sessionID),common=applyCommonPrompt(parsed.data.lanes,orientedCommonPrompt);if(!common.ok)return asyncFailureResult({failure_class:"invalid_args",message:"Invalid dispatch_lanes_async arguments",errors:common.errors});let lanes=common.lanes,batchId=requestedBatchId;if(findByBatchId(directory,batchId).length>0)return asyncFailureResult({failure_class:"invalid_args",message:`Async lane batch already exists: ${batchId}`,errors:[`batch_id must be unique: ${batchId}`]});let verifiedPrHead,workflowRevisionDigest,verifiedReviewBaseSha,bareWorkflowMode=["swarm-pr-review","swarm-pr-feedback"].find((prefix)=>parsed.data.mode?.trim()===prefix);if(bareWorkflowMode)return asyncFailureResult({failure_class:"invalid_args",message:bareWorkflowMode==="swarm-pr-review"?'BLOCKED: mode "swarm-pr-review" is missing its required stage suffix. Use one of: swarm-pr-review:base, swarm-pr-review:micro, swarm-pr-review:council, swarm-pr-review:reviewer, swarm-pr-review:critic.':'BLOCKED: mode "swarm-pr-feedback" is missing its required stage suffix. Use swarm-pr-feedback:verification.'});if((parsed.data.pr_review_wave_stage!==void 0||parsed.data.pr_review_wave_attempt!==void 0)&&parsed.data.mode!=="swarm-pr-review:base")return asyncFailureResult({failure_class:"invalid_args",message:'BLOCKED: pr_review_wave_stage and pr_review_wave_attempt are valid only when mode is exactly "swarm-pr-review:base".'});if(context.sessionID?.trim()&&parsed.data.pr_head_sha&&(parsed.data.mode?.startsWith("swarm-pr-review:")||parsed.data.mode?.startsWith("swarm-pr-feedback:")))try{verifiedPrHead=await assertCurrentCheckoutHead(directory,parsed.data.pr_head_sha,parsed.data.mode?.startsWith("swarm-pr-feedback:")?"PR_FEEDBACK":"PR_REVIEW");let resolvedDigest=_internals208.resolvePrWorkflowRevisionDigestAsync!==resolvePrWorkflowRevisionDigestAsync?await _internals208.resolvePrWorkflowRevisionDigestAsync(directory,parsed.data.pr_head_sha).then((digest3)=>digest3?{ok:!0,digest:digest3}:{ok:!1,reason:"seam-unavailable"}):await resolvePrWorkflowRevisionDigestDetailedAsync(directory,parsed.data.pr_head_sha);if(!resolvedDigest.ok)throw Error(`BLOCKED: PR workflow could not compute a bounded current-revision digest for pr_head_sha "${parsed.data.pr_head_sha}"; `+describePrWorkflowRevisionDigestFailure(resolvedDigest));if(workflowRevisionDigest=resolvedDigest.digest,parsed.data.mode?.startsWith("swarm-pr-review:")){if(!parsed.data.base_sha||!parsed.data.base_ref)throw Error("BLOCKED: PR_REVIEW dispatch requires exact base_sha and base_ref");let resolvedBase=await _internals208.resolveExactMergeBaseAsync(directory,parsed.data.base_ref,parsed.data.pr_head_sha);if(!resolvedBase)throw Error(`BLOCKED: PR_REVIEW could not resolve a merge base for base_ref="${parsed.data.base_ref}" and pr_head_sha=${parsed.data.pr_head_sha} in "${directory}". The ref may not exist locally — the PR-review preflight fetches only refs/pull/<N>/head, not the base branch. Fetch it and pass the remote-tracking form using two separate standalone commands. First run: git -C "${directory}" fetch origin <base-branch>. Then run: git -C "${directory}" merge-base -- origin/<base-branch> ${parsed.data.pr_head_sha}`);if(resolvedBase.toLowerCase()!==parsed.data.base_sha.toLowerCase())throw Error(`BLOCKED: PR_REVIEW merge-base mismatch. git merge-base -- "${parsed.data.base_ref}" ${parsed.data.pr_head_sha} in "${directory}" resolved to ${resolvedBase}, but base_sha=${parsed.data.base_sha} was passed. If you computed base_sha against a remote-tracking ref, pass that SAME ref as base_ref — a local branch of the same name (main, refs/heads/main) may be stale and yields a different merge base. Verify with: git -C "${directory}" merge-base -- "${parsed.data.base_ref}" ${parsed.data.pr_head_sha}`);verifiedReviewBaseSha=resolvedBase}}catch(error93){return asyncFailureResult({failure_class:"invalid_args",message:error93 instanceof Error?error93.message:"PR workflow checkout head verification failed"})}if(parsed.data.mode?.startsWith("swarm-pr-review:")&&!parsed.data.pr_head_sha)return asyncFailureResult({failure_class:"invalid_args",message:"BLOCKED: active PR_REVIEW dispatch requires pr_head_sha"});if(parsed.data.mode?.startsWith("swarm-pr-feedback:")&&!parsed.data.pr_head_sha)return asyncFailureResult({failure_class:"invalid_args",message:"BLOCKED: PR_FEEDBACK dispatch requires pr_head_sha"});let contracted=applyPrWorkflowPromptContract(lanes,{mode:parsed.data.mode,prHeadSha:verifiedPrHead,revisionDigest:workflowRevisionDigest,scope:verifiedReviewBaseSha?`complete PR diff ${verifiedReviewBaseSha}...${verifiedPrHead}`:"the complete immutable feedback inventory on the exact checked-out revision",callerFocus:parsed.data.scope});if(!contracted.ok)return asyncFailureResult({failure_class:"invalid_args",message:"Invalid mandatory PR workflow prompt contract",errors:contracted.errors});let formatted=applyExplorerFormatSuffix(contracted.lanes,{failClosed:Boolean(parsed.data.mode?.startsWith("swarm-pr-review:")||parsed.data.mode?.startsWith("swarm-pr-feedback:")),mode:parsed.data.mode});if(!formatted.ok)return asyncFailureResult({failure_class:"invalid_args",message:"Invalid mandatory PR workflow explorer output contract",errors:formatted.errors});if(lanes=formatted.lanes,context.sessionID?.trim())try{let gateState=await enforcePrWorkflowDispatchLanesAsync(directory,context.sessionID,"dispatch_lanes_async");if(!gateState&&parsed.data.mode?.startsWith("swarm-pr-review:"))gateState=await activatePrWorkflow(directory,context.sessionID,"PR_REVIEW",{requireCheckoutPreflight:!0});else if(!gateState&&parsed.data.mode==="swarm-pr-feedback:verification")gateState=await activatePrWorkflow(directory,context.sessionID,"PR_FEEDBACK",{requireCheckoutPreflight:!0});if(gateState?.mode==="PR_REVIEW"){let headSha=parsed.data.pr_head_sha;if(!headSha)throw Error("BLOCKED: active PR_REVIEW dispatch requires pr_head_sha");if(!verifiedReviewBaseSha||!parsed.data.base_ref)throw Error("BLOCKED: PR_REVIEW exact merge-base scope was not verified");gateState=await bindPrReviewBase(directory,context.sessionID,{prHeadSha:headSha,baseRef:parsed.data.base_ref,baseSha:verifiedReviewBaseSha});let laneSpecs=parsed.data.lanes.map((lane)=>({laneId:lane.id,workflowLane:lane.workflow_lane,reviewItemIds:lane.review_item_ids,ownedWorkflowLanes:lane.owned_workflow_lanes})),depthTier=gateState.prReviewDepthTier??"L";if(parsed.data.mode==="swarm-pr-review:base"){let configuredResilience=_internals208.loadPluginConfig(directory).pr_review_resilience??DEFAULT_PR_REVIEW_RESILIENCE_CONFIG,effectiveResilience=effectivePrReviewResilienceConfig(configuredResilience,gateState),waveStage=parsed.data.pr_review_wave_stage,waveAttempt=parsed.data.pr_review_wave_attempt;if(waveStage===void 0!==(waveAttempt===void 0))throw Error("BLOCKED: PR_REVIEW staged base dispatch requires both pr_review_wave_stage and pr_review_wave_attempt together");if(waveStage!==void 0&&waveAttempt!==void 0&&(!effectiveResilience.enabled||depthTier==="S"))throw Error("BLOCKED: staged PR_REVIEW base dispatch is valid only when pr_review_resilience is enabled at depth tier M or L");if(effectiveResilience.enabled&&depthTier!=="S"&&(waveStage===void 0||waveAttempt===void 0))throw Error("BLOCKED: PR_REVIEW base dispatch at depth tier M or L requires canary-first pr_review_wave_stage and pr_review_wave_attempt while pr_review_resilience is enabled");let stagedBaseDispatch=effectiveResilience.enabled&&depthTier!=="S"&&waveStage!==void 0&&waveAttempt!==void 0;if((gateState.prReviewBaseDispatches?.length??0)===0&&!stagedBaseDispatch){let ownedDimensionIds=parsed.data.lanes.flatMap((lane)=>lane.owned_workflow_lanes?.length?lane.owned_workflow_lanes:lane.workflow_lane?[lane.workflow_lane]:[]),coversAllSixExactlyOnce=ownedDimensionIds.length===PR_REVIEW_BASE_DIMENSION_IDS.length&&new Set(ownedDimensionIds).size===PR_REVIEW_BASE_DIMENSION_IDS.length&&PR_REVIEW_BASE_DIMENSION_IDS.every((dimensionId)=>ownedDimensionIds.includes(dimensionId));if(depthTier==="L"){if(parsed.data.lanes.length!==6||parsed.data.max_concurrent!==6||parsed.data.lanes.some((lane)=>(lane.owned_workflow_lanes?.length??1)!==1))throw Error(`BLOCKED: initial PR_REVIEW base dispatch requires exactly six lanes and max_concurrent: 6 at depth tier L (consolidated owned_workflow_lanes are allowed only at tiers S and M); each lane owns exactly one dimension and may set workflow_lane to it, omitting owned_workflow_lanes; valid dimensions: ${PR_REVIEW_BASE_DIMENSION_IDS.join(", ")}`)}else if(!coversAllSixExactlyOnce||parsed.data.lanes.length<PR_REVIEW_BASE_LANE_FLOORS[depthTier]||parsed.data.lanes.length>PR_REVIEW_BASE_DIMENSION_IDS.length||parsed.data.max_concurrent!==parsed.data.lanes.length)throw Error(`BLOCKED: initial PR_REVIEW base dispatch at depth tier ${depthTier} requires between ${PR_REVIEW_BASE_LANE_FLOORS[depthTier]} and ${PR_REVIEW_BASE_DIMENSION_IDS.length} lanes whose owned_workflow_lanes partition all six dimensions exactly once, with max_concurrent equal to the lane count; valid dimensions: ${PR_REVIEW_BASE_DIMENSION_IDS.join(", ")}; a lane with one dimension may set workflow_lane to it and omit owned_workflow_lanes`)}if(stagedBaseDispatch){if(waveStage==="canary"){if(parsed.data.lanes.length!==1||parsed.data.max_concurrent!==1||parsed.data.lanes.some((lane)=>(lane.owned_workflow_lanes?.length??1)!==1))throw Error("BLOCKED: PR_REVIEW staged base canary requires exactly one singleton lane and max_concurrent: 1")}else if(parsed.data.max_concurrent!==parsed.data.lanes.length)throw Error("BLOCKED: PR_REVIEW staged base fanout requires max_concurrent equal to the lane count")}for(let lane of parsed.data.lanes)if(resolveGeneratedAgentRole(lane.agent,swarmState.generatedAgentNames)!=="explorer")throw Error(`BLOCKED: PR_REVIEW base lane "${lane.id}" must use the explorer role`);await enforcePrReviewBaseDimensions(directory,context.sessionID,laneSpecs,{batchId,prHeadSha:headSha,revisionDigest:workflowRevisionDigest,prReviewWaveStage:waveStage,prReviewWaveAttempt:waveAttempt,prReviewResiliencePolicy:effectiveResilience})}else if(parsed.data.mode==="swarm-pr-review:micro"){if(await assertPrReviewBaseCoverageSettled(directory,context.sessionID),gateState.prHeadSha&&gateState.prHeadSha!==headSha)throw Error(`BLOCKED: PR_REVIEW head mismatch; expected "${gateState.prHeadSha}", received "${headSha}"`);for(let lane of parsed.data.lanes)if(resolveGeneratedAgentRole(lane.agent,swarmState.generatedAgentNames)!=="explorer")throw Error(`BLOCKED: PR_REVIEW micro lane "${lane.id}" must use the explorer role`);let effectiveTriggerEvaluation=parsed.data.trigger_evaluation!==void 0?parsed.data.trigger_evaluation:gateState.prReviewTriggerLedger;validatePrReviewMicroDispatch({...parsed.data,trigger_evaluation:effectiveTriggerEvaluation},depthTier),gateState=await bindPrReviewTriggerLedger(directory,context.sessionID,effectiveTriggerEvaluation)}else if(parsed.data.mode==="swarm-pr-review:council"||parsed.data.mode==="swarm-pr-review:reviewer"||parsed.data.mode==="swarm-pr-review:critic"){let phase=parsed.data.mode.endsWith(":council")?"council":parsed.data.mode.endsWith(":reviewer")?"reviewer":"critic";if(parsed.data.lanes.some((lane)=>lane.owned_workflow_lanes))throw Error(`BLOCKED: PR_REVIEW ${phase} lanes must not declare owned_workflow_lanes; depth-tier consolidation applies only to base and micro discovery lanes`);for(let lane of parsed.data.lanes){let role=resolveGeneratedAgentRole(lane.agent,swarmState.generatedAgentNames);if(phase==="council"&&!role.startsWith("council_")||phase==="reviewer"&&role!=="reviewer"||phase==="critic"&&!role.startsWith("critic"))throw Error(`BLOCKED: PR_REVIEW ${phase} lane "${lane.id}" uses invalid role "${role||lane.agent}"`)}await recordPrReviewValidationBatch(directory,context.sessionID,phase,laneSpecs,{batchId,prHeadSha:headSha})}else throw Error("BLOCKED: active PR_REVIEW requires a structured base, micro, council, reviewer, or critic mode")}else if(gateState?.mode==="PR_FEEDBACK"){let headSha=parsed.data.pr_head_sha;if(!headSha)throw Error("BLOCKED: PR_FEEDBACK dispatch requires pr_head_sha");if(parsed.data.lanes.some((lane)=>lane.owned_workflow_lanes))throw Error("BLOCKED: PR_FEEDBACK lanes must not declare owned_workflow_lanes; depth-tier consolidation applies only to PR_REVIEW base and micro discovery lanes");if(parsed.data.mode==="swarm-pr-feedback:verification")await declarePrFeedbackInventory(directory,context.sessionID,parsed.data.feedback_inventory??[],{prHeadSha:headSha}),await enforcePrFeedbackVerificationOwnership(directory,context.sessionID,parsed.data.lanes.map((lane)=>({laneId:lane.id,ownedItemIds:lane.feedback_item_ids??[]})),{batchId,prHeadSha:headSha});else if(parsed.data.mode==="swarm-pr-feedback:stage-b-reviewer"||parsed.data.mode==="swarm-pr-feedback:stage-b-test"||parsed.data.mode==="swarm-pr-feedback:closeout-reviewer"||parsed.data.mode==="swarm-pr-feedback:closeout-critic"){if(parsed.data.lanes.length!==1||parsed.data.max_concurrent!==1)throw Error("BLOCKED: each ordered PR_FEEDBACK gate requires exactly one lane and max_concurrent: 1");let phase=parsed.data.mode.slice(18),lane=parsed.data.lanes[0],role=resolveGeneratedAgentRole(lane.agent,swarmState.generatedAgentNames),expectedRole=phase==="stage-b-test"?"test_engineer":phase==="closeout-critic"?"critic":"reviewer";if(lane.workflow_lane!==phase||(expectedRole==="critic"?!role.startsWith("critic"):role!==expectedRole))throw Error(`BLOCKED: PR_FEEDBACK ${phase} requires workflow_lane "${phase}" and role "${expectedRole}"`);await recordPrFeedbackGateBatch(directory,context.sessionID,phase,{laneId:lane.id,ownedItemIds:lane.feedback_item_ids??[]},{batchId,prHeadSha:headSha,revisionDigest:workflowRevisionDigest??""})}else throw Error("BLOCKED: active PR_FEEDBACK requires structured verification, Stage B reviewer/test, and closeout reviewer/critic modes")}}catch(error93){return asyncFailureResult({failure_class:error93 instanceof PrReviewResilienceCircuitOpenError?"circuit_open":error93 instanceof PrReviewResilienceRetryExhaustedError?"retry_exhausted":"invalid_args",message:error93 instanceof Error?error93.message:"PR workflow gate rejected dispatch"})}let canonicalWorkflowScope=verifiedReviewBaseSha?`complete PR diff ${verifiedReviewBaseSha}...${verifiedPrHead}`:parsed.data.mode?.startsWith("swarm-pr-feedback:")?"the complete immutable feedback inventory on the exact checked-out revision":parsed.data.scope,maxConcurrent=Math.min(parsed.data.max_concurrent??lanes.length,lanes.length,MAX_LANES),launchTimeoutMs=parsed.data.launch_timeout_ms??parsed.data.timeout_ms??DEFAULT_ASYNC_LAUNCH_TIMEOUT_MS,dispatcher=_internals208.createParallelDispatcher({enabled:!0,maxConcurrentTasks:maxConcurrent,evidenceLockTimeoutMs:0}),limit=pLimit(maxConcurrent);try{let laneResults=await Promise.all(lanes.map((lane)=>limit(()=>launchAsyncLane({session,dispatcher,lane,directory,timeoutMs:launchTimeoutMs,context,batchId,mode:parsed.data.mode,prHeadSha:parsed.data.pr_head_sha,gitHead:verifiedPrHead,dirtyHash:workflowRevisionDigest,scope:canonicalWorkflowScope}))));if(parsed.data.mode==="swarm-pr-review:base"&&context.sessionID?.trim()&&parsed.data.pr_review_wave_stage!==void 0)try{await rollbackPrReviewBaseAdmissionIfUnlaunched(directory,context.sessionID,batchId)}catch(error93){throw log("pr-review base-admission rollback failed",{batchId,sessionID:context.sessionID,error:error93 instanceof Error?error93.message:String(error93)}),error93}let failed=laneResults.filter((lane)=>lane.status==="failed"),rejected=laneResults.filter((lane)=>lane.status==="rejected"),pending=laneResults.filter((lane)=>lane.status==="pending");return{success:failed.length===0&&rejected.length===0,batch_id:batchId,dispatched:laneResults.length,pending:pending.length,failed:failed.length,rejected:rejected.length,max_concurrent:maxConcurrent,launch_timeout_ms:launchTimeoutMs,timeout_ms:launchTimeoutMs,lane_results:laneResults}}finally{dispatcher.shutdown()}}async function executeCollectLaneResults(args2,directory,context={}){let parsed=CollectLaneResultsArgsSchema.safeParse(args2);if(!parsed.success)return collectFailureResult({failure_class:"invalid_args",batch_id:"",message:"Invalid collect_lane_results arguments",errors:boundZodIssues(parsed.error.issues)});let session=_internals208.getSessionOps();if(!session||typeof session.messages!=="function")return collectFailureResult({failure_class:"no_client",batch_id:parsed.data.batch_id,message:"OpenCode session messages client is not available"});let timeoutMs=parsed.data.timeout_ms??DEFAULT_COLLECT_TIMEOUT_MS,deadline=_internals208.now()+timeoutMs,hostTimeouts=new Set,receiptAppendFailureLogs=new Set,batchFilter=context.sessionID!==void 0?{parentSessionId:context.sessionID}:void 0,records=findByBatchId(directory,parsed.data.batch_id,batchFilter);if(records.length===0)return collectFailureResult({failure_class:"not_found",batch_id:parsed.data.batch_id,message:`No async lane batch found for ${parsed.data.batch_id}`});let keepPolling=!0,pollIntervalMs=COLLECT_POLL_INTERVAL_MS;while(keepPolling){if(await collectOnce(session,directory,records,parsed.data.cancel_pending===!0,deadline,hostTimeouts,receiptAppendFailureLogs),await sweepStaleAsyncLaneRecords(session,directory,records,DEFAULT_ASYNC_STALE_TIMEOUT_MS,deadline,hostTimeouts),records=findByBatchId(directory,parsed.data.batch_id,batchFilter),allSettled(records)||parsed.data.wait!==!0){keepPolling=!1;continue}if(_internals208.now()>=deadline){keepPolling=!1;continue}await _internals208.sleep(Math.min(pollIntervalMs,Math.max(0,deadline-_internals208.now()))),pollIntervalMs=nextCollectPollInterval(pollIntervalMs)}let reviewReceiptFallbacks=await resolvePrReviewReceiptFallbacks(directory,context.sessionID,records),result=buildCollectResult(parsed.data.batch_id,records,parsed.data.include_pending??parsed.data.wait!==!0,{directory,sessionID:context.sessionID,reviewReceipts:reviewReceiptFallbacks});if(hostTimeouts.size>0)result.message=result.pending>0?"Collection deadline exhausted while waiting for OpenCode host calls; pending lanes remain safe to retry.":"Collection recovered and settled all lanes despite bounded OpenCode host-call timeouts; no collection retry is required.",result.errors=[...hostTimeouts];return result}async function createLaneSession(args2){let generation=1,decision=args2.dispatcher.dispatch(args2.lane.id);while(!0){if(decision.action!=="dispatch")return{ok:!1,generation,error:`dispatcher ${decision.action}: ${decision.reason}`};let createTimeoutMessage=`Lane "${args2.lane.id}" session.create timed out after ${args2.timeoutMs}ms`,createPromise;try{createPromise=args2.session.create(buildLaneSessionCreateArgs(args2.directory,args2.lane,args2.context))}catch(error93){createPromise=Promise.reject(error93)}let createTimedOut=!1;createPromise.then((result)=>{if(createTimedOut&&result.data?.id)scheduleSessionCleanup(args2.session,result.data.id)}).catch(()=>{return});let failureSignal,failureMessage;try{let result=await withTimeout2(createPromise,args2.timeoutMs,createTimeoutMessage);if(result.data?.id)return{ok:!0,sessionId:result.data.id,generation,slotId:decision.slot.slotId,runId:decision.slot.runId};failureSignal=result.error,failureMessage=result.error===void 0||result.error===null?"session.create failed: malformed response without a session id":`session.create failed: ${formatError3(result.error)}`}catch(error93){if(failureSignal=error93,failureMessage=formatError3(error93),failureMessage===createTimeoutMessage)createTimedOut=!0}if((createTimedOut||isRetryableSessionCreateFailure(failureSignal))&&generation<MAX_SESSION_CREATE_GENERATIONS){args2.dispatcher.releaseSlot(decision.slot.slotId),generation++,decision=args2.dispatcher.dispatch(args2.lane.id);continue}return{ok:!1,error:failureMessage,generation,slotId:decision.slot.slotId,runId:decision.slot.runId}}}function isRetryableSessionCreateFailure(error93){if(error93===void 0||error93===null)return!1;let seen=new WeakSet,pending=[{value:error93,depth:0}],visited=0,signalChars=0,transient=!1,permanent=!1,truncated=!1;while(pending.length>0&&visited<MAX_CREATE_FAILURE_WALK_NODES){let current=pending.shift();visited++;let{value,depth,key}=current;if((key==="isRetryable"||key==="retryable")&&value===!1)permanent=!0;if(typeof value==="number"&&Number.isInteger(value)){if(key===void 0||CREATE_FAILURE_STATUS_KEYS.has(key)){if(TRANSIENT_CREATE_STATUS_CODES.has(value))transient=!0;if(PERMANENT_CREATE_STATUS_CODES.has(value))permanent=!0}continue}if(typeof value==="string"){if(key!==void 0&&!CREATE_FAILURE_SCALAR_KEYS.has(key))continue;if(key!==void 0&&CREATE_FAILURE_STATUS_KEYS.has(key)&&/^\d+$/.test(value)){let numericStatus=Number(value);if(TRANSIENT_CREATE_STATUS_CODES.has(numericStatus))transient=!0;if(PERMANENT_CREATE_STATUS_CODES.has(numericStatus))permanent=!0}let remaining=MAX_CREATE_FAILURE_SIGNAL_CHARS-signalChars;if(remaining<=0){truncated=!0;continue}let signal2=value.slice(0,remaining);if(signal2.length<value.length)truncated=!0;if(signalChars+=signal2.length,PERMANENT_CREATE_SIGNAL_PATTERN.test(signal2))permanent=!0;if(TRANSIENT_CREATE_SIGNAL_PATTERN.test(signal2))transient=!0;continue}if(typeof value!=="object"&&typeof value!=="function"||value===null)continue;let object3=value;if(seen.has(object3))continue;if(seen.add(object3),depth>=MAX_CREATE_FAILURE_WALK_DEPTH){truncated=!0;continue}let isArray=!1;try{isArray=Array.isArray(object3)}catch{truncated=!0;continue}if(isArray){let arrayLength;try{let lengthDescriptor=Object.getOwnPropertyDescriptor(object3,"length");if(!lengthDescriptor||!("value"in lengthDescriptor)||typeof lengthDescriptor.value!=="number"||!Number.isSafeInteger(lengthDescriptor.value)||lengthDescriptor.value<0){truncated=!0;continue}arrayLength=lengthDescriptor.value}catch{truncated=!0;continue}let remainingNodes=MAX_CREATE_FAILURE_WALK_NODES-visited,itemCount=Math.min(arrayLength,remainingNodes);if(itemCount<arrayLength)truncated=!0;for(let index=0;index<itemCount;index++){let descriptor;try{descriptor=Object.getOwnPropertyDescriptor(object3,index)}catch{truncated=!0;continue}if(!descriptor)continue;if(!("value"in descriptor)){truncated=!0;continue}pending.push({value:descriptor.value,depth:depth+1,key})}continue}for(let propertyKey of CREATE_FAILURE_FIELD_KEYS){if(pending.length+visited>=MAX_CREATE_FAILURE_WALK_NODES){truncated=!0;break}let descriptor;try{descriptor=Object.getOwnPropertyDescriptor(object3,propertyKey)}catch{truncated=!0;continue}if(!descriptor)continue;if(!("value"in descriptor)){truncated=!0;continue}pending.push({value:descriptor.value,depth:depth+1,key:propertyKey})}}if(pending.length>0)truncated=!0;return transient&&!permanent&&!truncated}async function launchAsyncLane(args2){let validation2=validateLaneAgent(args2.lane.agent,args2.context),role=validation2.role,startedAt=isoNow2();if(!validation2.ok)return{id:args2.lane.id,agent:args2.lane.agent,role,status:"rejected",started_at:startedAt,completed_at:isoNow2(),error:validation2.error};let create=await createLaneSession({session:args2.session,dispatcher:args2.dispatcher,lane:args2.lane,directory:args2.directory,timeoutMs:args2.timeoutMs,context:args2.context});try{if(!create.ok)return failedLane(args2.lane,role,startedAt,create.error,create.slotId,create.runId,void 0,create.generation);let sessionId=create.sessionId,pendingOutcome=await recordPendingDelegationDetailed(args2.directory,{correlationId:sessionId,jobId:null,subagentSessionId:sessionId,parentSessionId:args2.context.sessionID?.trim()||`dispatch_lanes_async:${args2.batchId}`,callID:args2.batchId,normalizedAgent:role,swarmPrefixedAgent:args2.lane.agent,planTaskId:null,evidenceTaskId:null,batchId:args2.batchId,laneId:args2.lane.id,mode:args2.mode??"advisory",workflowLane:args2.lane.workflow_lane,ownedWorkflowLanes:args2.lane.owned_workflow_lanes,promptHash:promptHash(args2.lane,args2.directory,args2.batchId),workspace:{directory:args2.directory,gitHead:args2.gitHead??null,dirtyHash:args2.dirtyHash??null,prHeadSha:args2.prHeadSha??null,scope:args2.scope??null},generation:create.generation});if(pendingOutcome.status==="duplicate"||pendingOutcome.status==="conflict")return failedLane(args2.lane,role,startedAt,pendingOutcome.status==="duplicate"?"Async lane session.create returned an already-recorded correlation id":"Async lane session.create returned a correlation id owned by a different background delegation",create.slotId,create.runId,sessionId,create.generation);if(pendingOutcome.status==="failed")return cleanupAsyncLaunchSession(args2.session,sessionId),failedLane(args2.lane,role,startedAt,"Failed to record async lane in background delegation ledger",create.slotId,create.runId,sessionId,create.generation);return scheduleAsyncLanePrompt({session:args2.session,directory:args2.directory,sessionId,lane:args2.lane,timeoutMs:args2.timeoutMs}),{id:args2.lane.id,agent:args2.lane.agent,role,status:"pending",session_id:sessionId,slot_id:create.slotId,run_id:create.runId,generation:create.generation,started_at:startedAt,completed_at:isoNow2()}}catch(error93){return failedLane(args2.lane,role,startedAt,formatError3(error93),create.slotId,create.runId,create.ok?create.sessionId:void 0,create.generation)}finally{if(create.slotId)args2.dispatcher.releaseSlot(create.slotId)}}async function collectOnce(session,directory,records,cancelPending,deadline,hostTimeouts,receiptAppendFailureLogs){let activeRecords=records.filter((record3)=>record3.status==="pending"||record3.status==="running"),pendingSettlements=[];for(let index=0;index<activeRecords.length;index++){let record3=activeRecords[index],remainingLaneCount=activeRecords.length-index,needsRevisionDigest=Boolean(record3.workspace?.prHeadSha),laneBudgets=reserveCollectionLaneCallBudgets(deadline,remainingLaneCount,typeof session.status==="function",needsRevisionDigest);if(cancelPending){if(typeof session.abort==="function"){let timeoutCount=hostTimeouts.size;try{await withCollectionDeadline(()=>session.abort({path:{id:record3.subagentSessionId}}),deadline,`session.abort for lane session "${record3.subagentSessionId}"`,hostTimeouts,laneBudgets.laneBudgetMs)}catch{if(hostTimeouts.size>timeoutCount)continue}}await appendDelegationTransition(directory,record3.correlationId,{status:"cancelled"});continue}let readiness=await getLaneCollectionReadiness(session,directory,record3.subagentSessionId,deadline,hostTimeouts,laneBudgets.statusBudgetMs);if(readiness==="busy")continue;let messages;try{messages=await withCollectionDeadline(()=>session.messages({path:{id:record3.subagentSessionId},query:{directory,limit:ASYNC_MESSAGE_FETCH_LIMIT}}),deadline,`session.messages for lane "${record3.laneId??record3.correlationId}"`,hostTimeouts,laneBudgets.messagesBudgetMs)}catch{continue}if(!messages.data)continue;let transcript=extractAssistantTranscript(messages.data);if(!transcript.text)continue;if(readiness==="unknown"&&!transcript.terminalAssistantProof)continue;pendingSettlements.push(settleCollectedLane({directory,record:record3,transcript,deadline,hostTimeouts,revisionDigestBudgetMs:laneBudgets.revisionDigestBudgetMs,receiptAppendFailureLogs}))}await Promise.all(pendingSettlements)}async function settleCollectedLane(args2){let{directory,record:record3,transcript,deadline,hostTimeouts,receiptAppendFailureLogs}=args2,collectedRevisionDigest,prHeadSha=record3.workspace?.prHeadSha;if(prHeadSha)try{collectedRevisionDigest=await withCollectionDeadline(()=>_internals208.resolvePrWorkflowRevisionDigestAsync(directory,prHeadSha),deadline,`revision digest for lane "${record3.laneId??record3.correlationId}"`,hostTimeouts,args2.revisionDigestBudgetMs)??void 0}catch{return}let output=prepareLaneOutput({directory,batchId:record3.batchId??record3.callID,laneId:record3.laneId??record3.correlationId,agent:record3.swarmPrefixedAgent,role:record3.normalizedAgent,sessionId:record3.subagentSessionId,parentSessionId:record3.parentSessionId,mode:record3.mode,workflowLane:record3.workflowLane,prHeadSha:record3.workspace?.prHeadSha??void 0,gitHead:record3.workspace?.gitHead??void 0,revisionDigest:collectedRevisionDigest,scope:record3.workspace?.scope??void 0,source:"collect_lane_results",text:transcript.text,messageCount:transcript.messageCount,transcriptIncomplete:transcript.transcriptIncomplete}),prospectiveResult={text:output.output,chars:output.output_chars,truncated:output.output_truncated,digest:output.output_digest,...output.output_ref?{outputRef:output.output_ref}:{},outputPreviewChars:output.output.length,...output.output_degraded!==void 0?{outputDegraded:output.output_degraded}:{},...output.output_artifact_error?{outputArtifactError:output.output_artifact_error}:{},...output.transcript_incomplete!==void 0?{transcriptIncomplete:output.transcript_incomplete}:{},messageCount:transcript.messageCount},terminalStatus="completed";if(record3.mode==="swarm-pr-review:base"||record3.mode==="swarm-pr-review:micro"||record3.mode==="swarm-pr-review:council"){let artifact=output.output_ref?readLaneOutput(directory,output.output_ref)?.artifact??null:null,validation2=validatePrReviewDiscoveryLaneCompletion({record:record3,result:prospectiveResult,artifact,expected:{mode:record3.mode,workflowLane:record3.workflowLane??"",ownedWorkflowLanes:record3.ownedWorkflowLanes,prHeadSha:record3.workspace?.prHeadSha??"",gitHead:record3.workspace?.gitHead??"",revisionDigest:collectedRevisionDigest??"",reviewScope:record3.workspace?.scope??void 0}});if(validation2.ok&&validation2.salvaged?.length){if(prospectiveResult.salvagedWorkflowLanes=[...validation2.salvaged],validation2.recoveries?.length)prospectiveResult.salvagedWorkflowLaneRecoveries=[...validation2.recoveries]}if(!validation2.ok){terminalStatus="error";let family=record3.mode==="swarm-pr-review:base"?"base_explorer":"micro_lane";prospectiveResult.error=`PR_REVIEW_DISCOVERY_CONTRACT_INVALID: batch=${record3.batchId??"(missing)"} lane=${record3.laneId??"(missing)"} workflow_lane=${record3.workflowLane??"(missing)"} ${formatPrReviewLaneValidationFailure(validation2.failure)}; expected candidate row: ${CANDIDATE_HEADERS[family]}; expected clean row: ${CLEAN_TEMPLATES[family]}`,prospectiveResult.error=prospectiveResult.error.slice(0,1024)}}let isPrReviewVerdictLane=record3.mode==="swarm-pr-review:reviewer"||record3.mode==="swarm-pr-review:critic";if((isPrReviewVerdictLane||record3.mode==="swarm-pr-feedback:verification"||record3.mode==="swarm-pr-feedback:stage-b-reviewer"||record3.mode==="swarm-pr-feedback:stage-b-test"||record3.mode==="swarm-pr-feedback:closeout-reviewer"||record3.mode==="swarm-pr-feedback:closeout-critic")&&(isPrReviewVerdictLane||prospectiveResult.truncated===!0||prospectiveResult.transcriptIncomplete===!0)){let artifact=output.output_ref?readLaneOutput(directory,output.output_ref)?.artifact??null:null,transportValidationOperation=`transport recovery validation for lane "${record3.laneId??record3.correlationId}"`,transportValidationDeadlineDiagnosticPrefix=`${transportValidationOperation} exceeded the remaining collect_lane_results budget (`,validation2;try{validation2=await withCollectionDeadline(()=>_internals208.validatePrWorkflowTransportRecovery({directory,record:record3,result:prospectiveResult,artifact,revisionDigest:collectedRevisionDigest??""}),deadline,transportValidationOperation,hostTimeouts)}catch(error93){if(formatError3(error93).startsWith(transportValidationDeadlineDiagnosticPrefix))return;terminalStatus="error",prospectiveResult.error=`PR_WORKFLOW_CONTRACT_INVALID: batch=${record3.batchId??"(missing)"} lane=${record3.laneId??"(missing)"} workflow_lane=${record3.workflowLane??"(missing)"} `+formatError3(error93),prospectiveResult.error=prospectiveResult.error.slice(0,1024),await appendDelegationTransition(directory,record3.correlationId,{status:terminalStatus,result:prospectiveResult});return}if(validation2.receipt){let resultWithReceipt=appendPrReviewCollectionReceipt(record3,prospectiveResult,validation2.receipt);if(!resultWithReceipt){if(consumePrReviewReceiptAppendFailureLog(receiptAppendFailureLogs,record3.parentSessionId,record3.correlationId))log(`[dispatch-lanes] withheld PR-review terminal result without receipt: correlation=${record3.correlationId} batch=${record3.batchId??"(missing)"} lane=${record3.laneId??"(missing)"}`);return}prospectiveResult=resultWithReceipt}if(!validation2.ok){terminalStatus="error";let errorCode=validation2.failure?.predicate==="reviewer.verdict_rows"||validation2.failure?.predicate==="critic.verdict_rows"?"PR_REVIEW_VERDICT_CONTRACT_INVALID":"PR_WORKFLOW_CONTRACT_INVALID";prospectiveResult.error=`${errorCode}: batch=${record3.batchId??"(missing)"} lane=${record3.laneId??"(missing)"} workflow_lane=${record3.workflowLane??"(missing)"} ${validation2.reason}`,prospectiveResult.error=prospectiveResult.error.slice(0,1024)}else if(validation2.recoveries?.length){let workflowLane=record3.workflowLane?.trim();if(workflowLane)prospectiveResult.salvagedWorkflowLanes=[workflowLane];prospectiveResult.salvagedWorkflowLaneRecoveries=[...prospectiveResult.salvagedWorkflowLaneRecoveries??[],...validation2.recoveries]}}await appendDelegationTransition(directory,record3.correlationId,{status:terminalStatus,result:prospectiveResult})}function consumePrReviewReceiptAppendFailureLog(loggedFailures,parentSessionId,correlationId){let key=`${parentSessionId}\x00${correlationId}`;if(loggedFailures.has(key))return!1;return loggedFailures.add(key),!0}function scheduleAsyncLanePrompt(args2){queueMicrotask(()=>{startAsyncLanePrompt(args2).catch(async(error93)=>{let message=formatError3(error93);await appendAsyncLaneLaunchError(args2.directory,args2.session,args2.sessionId,message)})})}async function startAsyncLanePrompt(args2){let promptController=new AbortController,baseRole=stripKnownSwarmPrefix(args2.lane.agent),swarmID=baseRole!==args2.lane.agent?args2.lane.agent.slice(0,args2.lane.agent.length-baseRole.length-1):void 0,swarmAgents=getSwarmAgents(swarmID),promptResult;try{promptResult=(await dispatchWithModelFallback({dispatch:async(model,context)=>{let result=await withTimeout2(args2.session.promptAsync({path:{id:args2.sessionId},query:{directory:args2.directory},body:{agent:args2.lane.agent,...model?{model}:{},tools:buildReadOnlyTools(),parts:[{type:"text",text:args2.lane.prompt}]},signal:promptController.signal}),context.remainingMs??args2.timeoutMs,`Lane "${args2.lane.id}" session.promptAsync launch timed out after ${context.remainingMs??args2.timeoutMs}ms`,promptController);if(result.error)throw Error(`session.promptAsync launch failed: ${formatError3(result.error)}`);return result},classify:(error93)=>{let message=error93 instanceof Error?error93.message:String(error93);if(/timed out/i.test(message))return"permanent";return isTransientProviderError(message)?"transient":"permanent"},maxTransientRetriesPerModel:0,deadlineAtMs:_internals208.now()+args2.timeoutMs,now:_internals208.now,scope:{sessionID:args2.sessionId,invocationID:`dispatch-lanes-async:${args2.lane.id}`,swarmID,role:baseRole},primaryModel:swarmAgents?.[baseRole]?.model,fallbackModels:swarmAgents?.[baseRole]?.fallback_models??[]})).result}catch(error93){await appendAsyncLaneLaunchError(args2.directory,args2.session,args2.sessionId,formatError3(error93));return}if(promptResult.error){await appendAsyncLaneLaunchError(args2.directory,args2.session,args2.sessionId,`session.promptAsync launch failed: ${formatError3(promptResult.error)}`);return}await appendDelegationTransition(args2.directory,args2.sessionId,{status:"running"})}async function appendAsyncLaneLaunchError(directory,session,sessionId,message){await appendDelegationTransition(directory,sessionId,{status:"error",result:{error:message,chars:message.length,truncated:!1,digest:digestText2(message)}}),cleanupAsyncLaunchSession(session,sessionId)}async function getLaneCollectionReadiness(session,directory,sessionId,deadline,hostTimeouts,statusBudgetMs){if(typeof session.status!=="function")return"unknown";if(statusBudgetMs<=0)return"unknown";try{let status=await withCollectionDeadline(()=>session.status({query:{directory}}),deadline,`session.status for lane session "${sessionId}"`,hostTimeouts,statusBudgetMs);if(status.error||!status.data)return"unknown";let current=status.data[sessionId];if(current===void 0)return"unknown";if(current.type==="idle")return"idle";if(current.type==="busy"||current.type==="retry")return"busy";return"unknown"}catch{return"unknown"}}async function sweepStaleAsyncLaneRecords(session,directory,records,staleTimeoutMs,deadline,hostTimeouts){if(staleTimeoutMs<=0)return;let now2=_internals208.now();for(let record3 of records){let currentBeforeReadiness=getCurrentStaleSweepCandidate(directory,record3,staleTimeoutMs,now2);if(!currentBeforeReadiness)continue;if(await getLaneCollectionReadiness(session,directory,currentBeforeReadiness.subagentSessionId,deadline,hostTimeouts,reserveCollectionLaneCallBudgets(deadline,records.length,typeof session.status==="function").statusBudgetMs)!=="idle")continue;let currentAfterReadiness=getCurrentStaleSweepCandidate(directory,record3,staleTimeoutMs,now2);if(!currentAfterReadiness)continue;await appendDelegationTransition(directory,currentAfterReadiness.correlationId,{status:"stale",expectedCurrentStatuses:["pending","running","ingestion_error"]})}}function getCurrentStaleSweepCandidate(directory,record3,staleTimeoutMs,now2){let current=findByCorrelationId(directory,record3.correlationId);if(!current)return null;if(current.subagentSessionId!==record3.subagentSessionId)return null;if((current.generation??1)!==(record3.generation??1))return null;if(current.status!=="pending"&¤t.status!=="running"&¤t.status!=="ingestion_error")return null;if(now2-current.updatedAt<=staleTimeoutMs)return null;return current}function extractAssistantTranscript(messages){let assistantTexts=[],lastAssistantInfo;for(let message of messages){if(message.info?.role!=="assistant")continue;lastAssistantInfo=message.info;let text=extractText3(message.parts);if(text.trim().length>0)assistantTexts.push(text)}let completedAt=lastAssistantInfo?.time?.completed,finish=typeof lastAssistantInfo?.finish==="string"?lastAssistantInfo.finish.toLowerCase():"",terminalAssistantFinish=finish==="stop"||finish==="length"||finish==="content-filter";return{text:assistantTexts.join(`
|
|
6761
|
+
${EXPLORER_CANDIDATE_COMMON_END}`,READ_ONLY_LANE_ROLES=new Set(["explorer","reviewer","test_engineer","critic","critic_oversight","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","critic_finding_validator","sme","researcher","council_generalist","council_skeptic","council_domain_expert"]),READ_ONLY_TOOL_DENYLIST=[...new Set([...WRITE_TOOL_NAMES,"extract_code_blocks","multiedit","multi_edit","todo_write","save_plan","update_task_status","phase_complete","declare_scope","declare_council_criteria","submit_council_verdicts","submit_phase_council_verdicts","set_qa_gates","write_retro","write_drift_evidence","write_hallucination_evidence","write_mutation_evidence","knowledge_add","knowledge_remove","consensus_mine","summarize_work","doc_scan","lint"])],LaneSchema=exports_external.object({id:exports_external.string().min(1).max(80).regex(/^[A-Za-z0-9][A-Za-z0-9_.-]*$/).describe("Stable lane identifier, unique within this dispatch batch"),agent:exports_external.string().min(1).max(120).describe("Read-only swarm agent name, including any generated swarm prefix"),prompt:exports_external.string().min(1).max(MAX_PROMPT_CHARS).describe("Full lane prompt to send to the requested agent"),workflow_lane:exports_external.string().min(1).max(120).optional().describe("Required mechanical policy identifier in PR workflows; distinct from the retry-safe lane id"),owned_workflow_lanes:exports_external.array(exports_external.string().trim().min(1).max(120)).min(1).max(11).optional().describe("Complete dimension/family set a consolidated PR-review base or micro lane covers under the controller-computed depth tier; must include workflow_lane. Omit for singleton lanes."),feedback_item_ids:exports_external.array(exports_external.string().trim().min(1).max(120)).min(1).optional().describe("PR-feedback ledger item IDs owned exclusively by this lane"),review_item_ids:exports_external.array(exports_external.string().trim().min(1).max(160)).min(1).max(MAX_PR_REVIEW_COLLECTION_RECEIPT_ITEM_IDS).optional().describe("Candidate/finding IDs owned by a PR-review reviewer or critic lane; every ID requires a parseable verdict row")}),DispatchLanesArgsSchema=exports_external.object({lanes:exports_external.array(LaneSchema).min(1).max(MAX_LANES).describe("Read-only lane specs to dispatch concurrently"),common_prompt:exports_external.string().min(1).regex(/\S/,"common_prompt must contain non-whitespace content").max(MAX_PROMPT_CHARS-COMMON_PROMPT_SEPARATOR.length-1).optional().describe("Optional shared context prepended to every lane prompt. Send large shared context (PR diff, obligation ledger, scope) ONCE here instead of inlining the same blob into each lane prompt; this keeps the tool-call payload small and avoids malformed/truncated tool-call JSON. Combined common_prompt + per-lane prompt must not exceed the per-lane character limit."),max_concurrent:exports_external.number().int().min(1).max(MAX_LANES).optional().describe("Maximum lanes in flight at once; defaults to lane count"),timeout_ms:exports_external.number().int().min(10).max(MAX_TIMEOUT_MS4).optional().describe("Per-lane timeout in milliseconds. For blocking dispatch this covers session create and prompt execution; for async dispatch this covers launch only, never lane runtime."),orientation:exports_external.boolean().optional().describe("Prepend a bounded, deterministic repo-graph orientation block (mission-relevant files, repo hubs, freshness line) to common_prompt when the repo graph is fresh and relevant. No schema default: availability depends on graph state, resolved at execute time (omitted ⇒ attempted, skipped when no fresh graph exists). Explicitly false disables the block entirely.")}),DispatchLanesAsyncArgsSchema=DispatchLanesArgsSchema.extend({launch_timeout_ms:exports_external.number().int().min(10).max(MAX_TIMEOUT_MS4).optional().describe("Async launch acceptance timeout in milliseconds. This only bounds session creation and promptAsync acceptance; it is never a lane runtime timeout. Deprecated alias: timeout_ms."),batch_id:exports_external.string().min(1).max(MAX_BATCH_ID_CHARS).regex(/^[A-Za-z0-9][A-Za-z0-9_.:-]*$/).optional().describe("Stable async batch id for later collection; generated when omitted"),mode:exports_external.string().min(1).max(80).optional().describe('Advisory workflow mode, such as deep-dive. PR-review stages are COLON-SUFFIXED and the suffix is required. Accepted values: swarm-pr-review:base, swarm-pr-review:micro, swarm-pr-review:council, swarm-pr-review:reviewer, swarm-pr-review:critic, swarm-pr-feedback:verification. A bare "swarm-pr-review" does NOT enter the PR-review path — it skips the merge-base bind and later fails with "exact merge-base scope was not verified".'),pr_head_sha:exports_external.string().min(1).max(80).optional().describe("Full 40-char SHA of the PR head commit under review. Required when mode starts with swarm-pr-review: or swarm-pr-feedback:."),base_sha:exports_external.string().regex(/^[0-9a-f]{6,64}$/i).optional().describe("Exact merge base of base_ref and pr_head_sha — NOT the base branch tip. The controller recomputes `git merge-base -- <base_ref> <pr_head_sha>` and rejects any mismatch. Required when mode starts with swarm-pr-review:."),base_ref:exports_external.string().regex(/^(?!-)[A-Za-z0-9][A-Za-z0-9._/-]{0,255}$/).optional().describe("Base branch ref used to recompute the merge base. Use the REMOTE-TRACKING form (origin/main), and compute base_sha against that same ref. A local branch ref (main, refs/heads/main) is only as fresh as the last fetch — the PR-review preflight fetches refs/pull/<N>/head and not the base branch, so a local ref commonly resolves to a different merge base and the dispatch is rejected. Required when mode starts with swarm-pr-review:."),scope:exports_external.string().min(1).max(500).optional(),trigger_evaluation:exports_external.array(PrReviewInlineTriggerRowSchema).min(1).optional().describe("Complete repository-agnostic trigger ledger required for the first swarm-pr-review:micro dispatch. The first successful micro dispatch freezes it in same-session workflow state; any subsequent micro batch may omit this property and reuse that exact frozen ledger. If supplied later, it must remain exactly identical. MATCHED families are dispatched and inapplicable families are NOT_TRIGGERED."),feedback_inventory:exports_external.array(exports_external.string().trim().min(1).max(120)).min(1).optional().describe("Complete immutable feedback item inventory required for swarm-pr-feedback:verification"),pr_review_wave_stage:exports_external.enum(["canary","fanout"]).optional().describe('PR_REVIEW base-only staged dispatch marker. Required with pr_review_wave_attempt at depth tier M or L while pr_review_resilience is enabled. Use "canary" for the singleton probe lane and "fanout" for the follow-up batch that partitions the remaining unresolved base obligations.'),pr_review_wave_attempt:exports_external.number().int().min(0).max(2).optional().describe("PR_REVIEW base-only staged attempt number, required together with pr_review_wave_stage at depth tier M or L while resilience is enabled: attempt 0 is the initial wave, followed by at most two retry attempts (1 and 2) over the exact unresolved-obligation target left by the previous attempt.")}),CollectLaneResultsArgsSchema=exports_external.object({batch_id:exports_external.string().min(1).max(MAX_BATCH_ID_CHARS),wait:exports_external.boolean().optional().describe("Poll until all lanes settle or timeout"),timeout_ms:exports_external.number().int().min(0).max(MAX_COLLECT_TIMEOUT_MS).optional().describe("Total wait budget when wait=true"),include_pending:exports_external.boolean().optional().describe("Include pending/running lanes in lane_results. Defaults to true for non-blocking polls and false for wait=true joins."),cancel_pending:exports_external.boolean().optional().describe("Abort and mark pending/running lanes cancelled")});function validatePrReviewMicroDispatch(args2,depthTier){let evaluation=args2.trigger_evaluation;if(!evaluation)throw Error("BLOCKED: initial PR_REVIEW micro dispatch requires the complete trigger_evaluation ledger; after the first successful same-session micro dispatch freezes it, a later micro batch may omit the property and reuse that exact ledger");let validated;try{validated=validatePrReviewInlineTriggerLedger(evaluation)}catch(error93){throw Error(`BLOCKED: ${error93 instanceof Error?error93.message:String(error93)}`)}let required3=new Set(validated.matchedIds),laneOwnership=args2.lanes.map((lane)=>({label:lane.workflow_lane??"",owned:lane.owned_workflow_lanes?.length?lane.owned_workflow_lanes:lane.workflow_lane?[lane.workflow_lane]:[]}));if(depthTier==="L"&&laneOwnership.some((lane)=>lane.owned.length!==1))throw Error("BLOCKED: PR_REVIEW micro dispatch at depth tier L requires one dedicated lane per risk family; consolidated owned_workflow_lanes are allowed only at tiers S and M");let flattened=laneOwnership.flatMap((lane)=>lane.owned),duplicates=flattened.filter((value,index)=>flattened.indexOf(value)!==index),unmatched=flattened.filter((triggerId)=>!required3.has(triggerId)),invalidLabels=laneOwnership.filter((lane)=>lane.label.length===0||!lane.owned.includes(lane.label)).map((lane)=>lane.label||"(missing workflow_lane)");if(invalidLabels.length>0||duplicates.length>0||unmatched.length>0)throw Error(`BLOCKED: PR_REVIEW micro lanes must have unique workflow_lane IDs from the mandatory repository-agnostic lane set, with workflow_lane contained in its own owned set; invalid: ${[...new Set([...invalidLabels,...duplicates,...unmatched])].join(", ")}`);let coversAllFamilies=required3.size>0&&[...required3].every((id)=>flattened.includes(id)),microFloor=Math.min(PR_REVIEW_MICRO_LANE_FLOORS[depthTier],required3.size);if(coversAllFamilies&&laneOwnership.length<microFloor)throw Error(`BLOCKED: PR_REVIEW micro dispatch at depth tier ${depthTier} covering all ${required3.size} matched risk families requires at least ${microFloor} lanes; received ${laneOwnership.length}. Partial retry batches covering a subset of matched families are exempt; NOT_TRIGGERED families must not be dispatched.`)}var _internals208={getSessionOps:()=>swarmState.opencodeClient?.session??null,getGeneratedAgentNames:()=>swarmState.generatedAgentNames,createParallelDispatcher,loadPluginConfig,resolvePrWorkflowRevisionDigestAsync,resolveExactMergeBaseAsync,validatePrWorkflowTransportRecovery,now:()=>Date.now(),sleep:sleep3};function effectivePrReviewResilienceConfig(configured,gateState){let policy=gateState?.prReviewResilience?.policy;if(!policy)return configured;return{enabled:policy.enabled,canary_probe_ms:policy.canaryProbeMs,status_probe_timeout_ms:policy.statusProbeTimeoutMs,correlated_failure_threshold:policy.correlatedFailureThreshold,max_retry_attempts_after_initial:policy.maxRetryAttemptsAfterInitial}}async function executeDispatchLanes(args2,directory,context={}){let parsed=DispatchLanesArgsSchema.safeParse(args2);if(!parsed.success)return failureResult2({failure_class:"invalid_args",message:"Invalid dispatch_lanes arguments",errors:boundZodIssues(parsed.error.issues)});let duplicateLaneIds=findDuplicateLaneIds(parsed.data.lanes);if(duplicateLaneIds.length>0)return failureResult2({failure_class:"invalid_args",message:"Lane IDs must be unique within one dispatch_lanes batch",errors:duplicateLaneIds.map((id)=>`Duplicate lane id: ${id}`)});if(context.sessionID?.trim())try{await enforcePrWorkflowDispatchLanesAsync(directory,context.sessionID,"dispatch_lanes")}catch(error93){return failureResult2({failure_class:"invalid_args",message:error93 instanceof Error?error93.message:"PR workflow gate rejected dispatch"})}let session=_internals208.getSessionOps();if(!session)return failureResult2({failure_class:"no_client",message:"OpenCode session client is not available"});let orientedCommonPrompt=await augmentCommonPromptWithOrientation(directory,parsed.data.lanes,parsed.data.common_prompt,parsed.data.orientation,context.sessionID),common=applyCommonPrompt(parsed.data.lanes,orientedCommonPrompt);if(!common.ok)return failureResult2({failure_class:"invalid_args",message:"Invalid dispatch_lanes arguments",errors:common.errors});let requiresMandatoryExplorerFormat=common.lanes.some((lane)=>lane.workflow_lane!==void 0||(lane.owned_workflow_lanes?.length??0)>0),formatted=applyExplorerFormatSuffix(common.lanes,{failClosed:requiresMandatoryExplorerFormat});if(!formatted.ok)return failureResult2({failure_class:"invalid_args",message:"Invalid explorer output-format contract",errors:formatted.errors});let lanes=formatted.lanes,maxConcurrent=Math.min(parsed.data.max_concurrent??lanes.length,lanes.length,MAX_LANES),timeoutMs=parsed.data.timeout_ms??DEFAULT_TIMEOUT_MS5,dispatcher=_internals208.createParallelDispatcher({enabled:!0,maxConcurrentTasks:maxConcurrent,evidenceLockTimeoutMs:0}),limit=pLimit(maxConcurrent);try{let laneResults=await Promise.all(lanes.map((lane)=>limit(()=>runLane(session,dispatcher,lane,directory,timeoutMs,context))));return buildResult(laneResults,maxConcurrent,timeoutMs)}finally{dispatcher.shutdown()}}async function executeDispatchLanesAsync(args2,directory,context={}){let parsed=DispatchLanesAsyncArgsSchema.safeParse(args2);if(!parsed.success)return asyncFailureResult({failure_class:"invalid_args",message:"Invalid dispatch_lanes_async arguments",errors:boundZodIssues(parsed.error.issues)});if(typeof parsed.data.mode==="string"){let normalizedMode=parsed.data.mode.trim();parsed.data.mode=normalizedMode.length>0?normalizedMode:void 0}let duplicateLaneIds=findDuplicateLaneIds(parsed.data.lanes);if(duplicateLaneIds.length>0)return asyncFailureResult({failure_class:"invalid_args",message:"Lane IDs must be unique within one dispatch_lanes_async batch",errors:duplicateLaneIds.map((id)=>`Duplicate lane id: ${id}`)});let requestedBatchId=parsed.data.batch_id??makeBatchId(),session=_internals208.getSessionOps();if(!session||typeof session.promptAsync!=="function")return asyncFailureResult({failure_class:"no_client",message:"OpenCode session promptAsync client is not available"});let orientedCommonPrompt=await augmentCommonPromptWithOrientation(directory,parsed.data.lanes,parsed.data.common_prompt,parsed.data.orientation,context.sessionID),common=applyCommonPrompt(parsed.data.lanes,orientedCommonPrompt);if(!common.ok)return asyncFailureResult({failure_class:"invalid_args",message:"Invalid dispatch_lanes_async arguments",errors:common.errors});let lanes=common.lanes,batchId=requestedBatchId;if(findByBatchId(directory,batchId).length>0)return asyncFailureResult({failure_class:"invalid_args",message:`Async lane batch already exists: ${batchId}`,errors:[`batch_id must be unique: ${batchId}`]});let verifiedPrHead,workflowRevisionDigest,verifiedReviewBaseSha,bareWorkflowMode=["swarm-pr-review","swarm-pr-feedback"].find((prefix)=>parsed.data.mode?.trim()===prefix);if(bareWorkflowMode)return asyncFailureResult({failure_class:"invalid_args",message:bareWorkflowMode==="swarm-pr-review"?'BLOCKED: mode "swarm-pr-review" is missing its required stage suffix. Use one of: swarm-pr-review:base, swarm-pr-review:micro, swarm-pr-review:council, swarm-pr-review:reviewer, swarm-pr-review:critic.':'BLOCKED: mode "swarm-pr-feedback" is missing its required stage suffix. Use swarm-pr-feedback:verification.'});if((parsed.data.pr_review_wave_stage!==void 0||parsed.data.pr_review_wave_attempt!==void 0)&&parsed.data.mode!=="swarm-pr-review:base")return asyncFailureResult({failure_class:"invalid_args",message:'BLOCKED: pr_review_wave_stage and pr_review_wave_attempt are valid only when mode is exactly "swarm-pr-review:base".'});if(context.sessionID?.trim()&&parsed.data.pr_head_sha&&(parsed.data.mode?.startsWith("swarm-pr-review:")||parsed.data.mode?.startsWith("swarm-pr-feedback:")))try{verifiedPrHead=await assertCurrentCheckoutHead(directory,parsed.data.pr_head_sha,parsed.data.mode?.startsWith("swarm-pr-feedback:")?"PR_FEEDBACK":"PR_REVIEW");let resolvedDigest=_internals208.resolvePrWorkflowRevisionDigestAsync!==resolvePrWorkflowRevisionDigestAsync?await _internals208.resolvePrWorkflowRevisionDigestAsync(directory,parsed.data.pr_head_sha).then((digest3)=>digest3?{ok:!0,digest:digest3}:{ok:!1,reason:"seam-unavailable"}):await resolvePrWorkflowRevisionDigestDetailedAsync(directory,parsed.data.pr_head_sha);if(!resolvedDigest.ok)throw Error(`BLOCKED: PR workflow could not compute a bounded current-revision digest for pr_head_sha "${parsed.data.pr_head_sha}"; `+describePrWorkflowRevisionDigestFailure(resolvedDigest));if(workflowRevisionDigest=resolvedDigest.digest,parsed.data.mode?.startsWith("swarm-pr-review:")){if(!parsed.data.base_sha||!parsed.data.base_ref)throw Error("BLOCKED: PR_REVIEW dispatch requires exact base_sha and base_ref");let resolvedBase=await _internals208.resolveExactMergeBaseAsync(directory,parsed.data.base_ref,parsed.data.pr_head_sha);if(!resolvedBase)throw Error(`BLOCKED: PR_REVIEW could not resolve a merge base for base_ref="${parsed.data.base_ref}" and pr_head_sha=${parsed.data.pr_head_sha} in "${directory}". The ref may not exist locally — the PR-review preflight fetches only refs/pull/<N>/head, not the base branch. Fetch it and pass the remote-tracking form using two separate standalone commands. First run: git -C "${directory}" fetch origin <base-branch>. Then run: git -C "${directory}" merge-base -- origin/<base-branch> ${parsed.data.pr_head_sha}`);if(resolvedBase.toLowerCase()!==parsed.data.base_sha.toLowerCase())throw Error(`BLOCKED: PR_REVIEW merge-base mismatch. git merge-base -- "${parsed.data.base_ref}" ${parsed.data.pr_head_sha} in "${directory}" resolved to ${resolvedBase}, but base_sha=${parsed.data.base_sha} was passed. If you computed base_sha against a remote-tracking ref, pass that SAME ref as base_ref — a local branch of the same name (main, refs/heads/main) may be stale and yields a different merge base. Verify with: git -C "${directory}" merge-base -- "${parsed.data.base_ref}" ${parsed.data.pr_head_sha}`);verifiedReviewBaseSha=resolvedBase}}catch(error93){return asyncFailureResult({failure_class:"invalid_args",message:error93 instanceof Error?error93.message:"PR workflow checkout head verification failed"})}if(parsed.data.mode?.startsWith("swarm-pr-review:")&&!parsed.data.pr_head_sha)return asyncFailureResult({failure_class:"invalid_args",message:"BLOCKED: active PR_REVIEW dispatch requires pr_head_sha"});if(parsed.data.mode?.startsWith("swarm-pr-feedback:")&&!parsed.data.pr_head_sha)return asyncFailureResult({failure_class:"invalid_args",message:"BLOCKED: PR_FEEDBACK dispatch requires pr_head_sha"});let contracted=applyPrWorkflowPromptContract(lanes,{mode:parsed.data.mode,prHeadSha:verifiedPrHead,revisionDigest:workflowRevisionDigest,scope:verifiedReviewBaseSha?`complete PR diff ${verifiedReviewBaseSha}...${verifiedPrHead}`:"the complete immutable feedback inventory on the exact checked-out revision",callerFocus:parsed.data.scope});if(!contracted.ok)return asyncFailureResult({failure_class:"invalid_args",message:"Invalid mandatory PR workflow prompt contract",errors:contracted.errors});let formatted=applyExplorerFormatSuffix(contracted.lanes,{failClosed:Boolean(parsed.data.mode?.startsWith("swarm-pr-review:")||parsed.data.mode?.startsWith("swarm-pr-feedback:")),mode:parsed.data.mode});if(!formatted.ok)return asyncFailureResult({failure_class:"invalid_args",message:"Invalid mandatory PR workflow explorer output contract",errors:formatted.errors});if(lanes=formatted.lanes,context.sessionID?.trim())try{let gateState=await enforcePrWorkflowDispatchLanesAsync(directory,context.sessionID,"dispatch_lanes_async");if(!gateState&&parsed.data.mode?.startsWith("swarm-pr-review:"))gateState=await activatePrWorkflow(directory,context.sessionID,"PR_REVIEW",{requireCheckoutPreflight:!0});else if(!gateState&&parsed.data.mode==="swarm-pr-feedback:verification")gateState=await activatePrWorkflow(directory,context.sessionID,"PR_FEEDBACK",{requireCheckoutPreflight:!0});if(gateState?.mode==="PR_REVIEW"){let headSha=parsed.data.pr_head_sha;if(!headSha)throw Error("BLOCKED: active PR_REVIEW dispatch requires pr_head_sha");if(!verifiedReviewBaseSha||!parsed.data.base_ref)throw Error("BLOCKED: PR_REVIEW exact merge-base scope was not verified");gateState=await bindPrReviewBase(directory,context.sessionID,{prHeadSha:headSha,baseRef:parsed.data.base_ref,baseSha:verifiedReviewBaseSha});let laneSpecs=parsed.data.lanes.map((lane)=>({laneId:lane.id,workflowLane:lane.workflow_lane,reviewItemIds:lane.review_item_ids,ownedWorkflowLanes:lane.owned_workflow_lanes})),depthTier=gateState.prReviewDepthTier??"L";if(parsed.data.mode==="swarm-pr-review:base"){let configuredResilience=_internals208.loadPluginConfig(directory).pr_review_resilience??DEFAULT_PR_REVIEW_RESILIENCE_CONFIG,effectiveResilience=effectivePrReviewResilienceConfig(configuredResilience,gateState),waveStage=parsed.data.pr_review_wave_stage,waveAttempt=parsed.data.pr_review_wave_attempt;if(waveStage===void 0!==(waveAttempt===void 0))throw Error("BLOCKED: PR_REVIEW staged base dispatch requires both pr_review_wave_stage and pr_review_wave_attempt together");if(waveStage!==void 0&&waveAttempt!==void 0&&(!effectiveResilience.enabled||depthTier==="S"))throw Error("BLOCKED: staged PR_REVIEW base dispatch is valid only when pr_review_resilience is enabled at depth tier M or L");if(effectiveResilience.enabled&&depthTier!=="S"&&(waveStage===void 0||waveAttempt===void 0))throw Error("BLOCKED: PR_REVIEW base dispatch at depth tier M or L requires canary-first pr_review_wave_stage and pr_review_wave_attempt while pr_review_resilience is enabled");let stagedBaseDispatch=effectiveResilience.enabled&&depthTier!=="S"&&waveStage!==void 0&&waveAttempt!==void 0;if((gateState.prReviewBaseDispatches?.length??0)===0&&!stagedBaseDispatch){let ownedDimensionIds=parsed.data.lanes.flatMap((lane)=>lane.owned_workflow_lanes?.length?lane.owned_workflow_lanes:lane.workflow_lane?[lane.workflow_lane]:[]),coversAllSixExactlyOnce=ownedDimensionIds.length===PR_REVIEW_BASE_DIMENSION_IDS.length&&new Set(ownedDimensionIds).size===PR_REVIEW_BASE_DIMENSION_IDS.length&&PR_REVIEW_BASE_DIMENSION_IDS.every((dimensionId)=>ownedDimensionIds.includes(dimensionId));if(depthTier==="L"){if(parsed.data.lanes.length!==6||parsed.data.max_concurrent!==6||parsed.data.lanes.some((lane)=>(lane.owned_workflow_lanes?.length??1)!==1))throw Error(`BLOCKED: initial PR_REVIEW base dispatch requires exactly six lanes and max_concurrent: 6 at depth tier L (consolidated owned_workflow_lanes are allowed only at tiers S and M); each lane owns exactly one dimension and may set workflow_lane to it, omitting owned_workflow_lanes; valid dimensions: ${PR_REVIEW_BASE_DIMENSION_IDS.join(", ")}`)}else if(!coversAllSixExactlyOnce||parsed.data.lanes.length<PR_REVIEW_BASE_LANE_FLOORS[depthTier]||parsed.data.lanes.length>PR_REVIEW_BASE_DIMENSION_IDS.length||parsed.data.max_concurrent!==parsed.data.lanes.length)throw Error(`BLOCKED: initial PR_REVIEW base dispatch at depth tier ${depthTier} requires between ${PR_REVIEW_BASE_LANE_FLOORS[depthTier]} and ${PR_REVIEW_BASE_DIMENSION_IDS.length} lanes whose owned_workflow_lanes partition all six dimensions exactly once, with max_concurrent equal to the lane count; valid dimensions: ${PR_REVIEW_BASE_DIMENSION_IDS.join(", ")}; a lane with one dimension may set workflow_lane to it and omit owned_workflow_lanes`)}if(stagedBaseDispatch){if(waveStage==="canary"){if(parsed.data.lanes.length!==1||parsed.data.max_concurrent!==1||parsed.data.lanes.some((lane)=>(lane.owned_workflow_lanes?.length??1)!==1))throw Error("BLOCKED: PR_REVIEW staged base canary requires exactly one singleton lane and max_concurrent: 1")}else if(parsed.data.max_concurrent!==parsed.data.lanes.length)throw Error("BLOCKED: PR_REVIEW staged base fanout requires max_concurrent equal to the lane count")}for(let lane of parsed.data.lanes)if(resolveGeneratedAgentRole(lane.agent,swarmState.generatedAgentNames)!=="explorer")throw Error(`BLOCKED: PR_REVIEW base lane "${lane.id}" must use the explorer role`);await enforcePrReviewBaseDimensions(directory,context.sessionID,laneSpecs,{batchId,prHeadSha:headSha,revisionDigest:workflowRevisionDigest,prReviewWaveStage:waveStage,prReviewWaveAttempt:waveAttempt,prReviewResiliencePolicy:effectiveResilience})}else if(parsed.data.mode==="swarm-pr-review:micro"){if(await assertPrReviewBaseCoverageSettled(directory,context.sessionID),gateState.prHeadSha&&gateState.prHeadSha!==headSha)throw Error(`BLOCKED: PR_REVIEW head mismatch; expected "${gateState.prHeadSha}", received "${headSha}"`);for(let lane of parsed.data.lanes)if(resolveGeneratedAgentRole(lane.agent,swarmState.generatedAgentNames)!=="explorer")throw Error(`BLOCKED: PR_REVIEW micro lane "${lane.id}" must use the explorer role`);let effectiveTriggerEvaluation=parsed.data.trigger_evaluation!==void 0?parsed.data.trigger_evaluation:gateState.prReviewTriggerLedger;validatePrReviewMicroDispatch({...parsed.data,trigger_evaluation:effectiveTriggerEvaluation},depthTier),gateState=await bindPrReviewTriggerLedger(directory,context.sessionID,effectiveTriggerEvaluation)}else if(parsed.data.mode==="swarm-pr-review:council"||parsed.data.mode==="swarm-pr-review:reviewer"||parsed.data.mode==="swarm-pr-review:critic"){let phase=parsed.data.mode.endsWith(":council")?"council":parsed.data.mode.endsWith(":reviewer")?"reviewer":"critic";if(parsed.data.lanes.some((lane)=>lane.owned_workflow_lanes))throw Error(`BLOCKED: PR_REVIEW ${phase} lanes must not declare owned_workflow_lanes; depth-tier consolidation applies only to base and micro discovery lanes`);for(let lane of parsed.data.lanes){let role=resolveGeneratedAgentRole(lane.agent,swarmState.generatedAgentNames);if(phase==="council"&&!role.startsWith("council_")||phase==="reviewer"&&role!=="reviewer"||phase==="critic"&&!role.startsWith("critic"))throw Error(`BLOCKED: PR_REVIEW ${phase} lane "${lane.id}" uses invalid role "${role||lane.agent}"`)}await recordPrReviewValidationBatch(directory,context.sessionID,phase,laneSpecs,{batchId,prHeadSha:headSha})}else throw Error("BLOCKED: active PR_REVIEW requires a structured base, micro, council, reviewer, or critic mode")}else if(gateState?.mode==="PR_FEEDBACK"){let headSha=parsed.data.pr_head_sha;if(!headSha)throw Error("BLOCKED: PR_FEEDBACK dispatch requires pr_head_sha");if(parsed.data.lanes.some((lane)=>lane.owned_workflow_lanes))throw Error("BLOCKED: PR_FEEDBACK lanes must not declare owned_workflow_lanes; depth-tier consolidation applies only to PR_REVIEW base and micro discovery lanes");if(parsed.data.mode==="swarm-pr-feedback:verification")await declarePrFeedbackInventory(directory,context.sessionID,parsed.data.feedback_inventory??[],{prHeadSha:headSha}),await enforcePrFeedbackVerificationOwnership(directory,context.sessionID,parsed.data.lanes.map((lane)=>({laneId:lane.id,ownedItemIds:lane.feedback_item_ids??[]})),{batchId,prHeadSha:headSha});else if(parsed.data.mode==="swarm-pr-feedback:stage-b-reviewer"||parsed.data.mode==="swarm-pr-feedback:stage-b-test"||parsed.data.mode==="swarm-pr-feedback:closeout-reviewer"||parsed.data.mode==="swarm-pr-feedback:closeout-critic"){if(parsed.data.lanes.length!==1||parsed.data.max_concurrent!==1)throw Error("BLOCKED: each ordered PR_FEEDBACK gate requires exactly one lane and max_concurrent: 1");let phase=parsed.data.mode.slice(18),lane=parsed.data.lanes[0],role=resolveGeneratedAgentRole(lane.agent,swarmState.generatedAgentNames),expectedRole=phase==="stage-b-test"?"test_engineer":phase==="closeout-critic"?"critic":"reviewer";if(lane.workflow_lane!==phase||(expectedRole==="critic"?!role.startsWith("critic"):role!==expectedRole))throw Error(`BLOCKED: PR_FEEDBACK ${phase} requires workflow_lane "${phase}" and role "${expectedRole}"`);await recordPrFeedbackGateBatch(directory,context.sessionID,phase,{laneId:lane.id,ownedItemIds:lane.feedback_item_ids??[]},{batchId,prHeadSha:headSha,revisionDigest:workflowRevisionDigest??""})}else throw Error("BLOCKED: active PR_FEEDBACK requires structured verification, Stage B reviewer/test, and closeout reviewer/critic modes")}}catch(error93){return asyncFailureResult({failure_class:error93 instanceof PrReviewResilienceCircuitOpenError?"circuit_open":error93 instanceof PrReviewResilienceRetryExhaustedError?"retry_exhausted":"invalid_args",message:error93 instanceof Error?error93.message:"PR workflow gate rejected dispatch"})}let canonicalWorkflowScope=verifiedReviewBaseSha?`complete PR diff ${verifiedReviewBaseSha}...${verifiedPrHead}`:parsed.data.mode?.startsWith("swarm-pr-feedback:")?"the complete immutable feedback inventory on the exact checked-out revision":parsed.data.scope,maxConcurrent=Math.min(parsed.data.max_concurrent??lanes.length,lanes.length,MAX_LANES),launchTimeoutMs=parsed.data.launch_timeout_ms??parsed.data.timeout_ms??DEFAULT_ASYNC_LAUNCH_TIMEOUT_MS,dispatcher=_internals208.createParallelDispatcher({enabled:!0,maxConcurrentTasks:maxConcurrent,evidenceLockTimeoutMs:0}),limit=pLimit(maxConcurrent);try{let laneResults=await Promise.all(lanes.map((lane)=>limit(()=>launchAsyncLane({session,dispatcher,lane,directory,timeoutMs:launchTimeoutMs,context,batchId,mode:parsed.data.mode,prHeadSha:parsed.data.pr_head_sha,gitHead:verifiedPrHead,dirtyHash:workflowRevisionDigest,scope:canonicalWorkflowScope}))));if(parsed.data.mode==="swarm-pr-review:base"&&context.sessionID?.trim()&&parsed.data.pr_review_wave_stage!==void 0)try{await rollbackPrReviewBaseAdmissionIfUnlaunched(directory,context.sessionID,batchId)}catch(error93){throw log("pr-review base-admission rollback failed",{batchId,sessionID:context.sessionID,error:error93 instanceof Error?error93.message:String(error93)}),error93}let failed=laneResults.filter((lane)=>lane.status==="failed"),rejected=laneResults.filter((lane)=>lane.status==="rejected"),pending=laneResults.filter((lane)=>lane.status==="pending");return{success:failed.length===0&&rejected.length===0,batch_id:batchId,dispatched:laneResults.length,pending:pending.length,failed:failed.length,rejected:rejected.length,max_concurrent:maxConcurrent,launch_timeout_ms:launchTimeoutMs,timeout_ms:launchTimeoutMs,lane_results:laneResults}}finally{dispatcher.shutdown()}}async function executeCollectLaneResults(args2,directory,context={}){let parsed=CollectLaneResultsArgsSchema.safeParse(args2);if(!parsed.success)return collectFailureResult({failure_class:"invalid_args",batch_id:"",message:"Invalid collect_lane_results arguments",errors:boundZodIssues(parsed.error.issues)});let session=_internals208.getSessionOps();if(!session||typeof session.messages!=="function")return collectFailureResult({failure_class:"no_client",batch_id:parsed.data.batch_id,message:"OpenCode session messages client is not available"});let timeoutMs=parsed.data.timeout_ms??DEFAULT_COLLECT_TIMEOUT_MS,deadline=_internals208.now()+timeoutMs,hostTimeouts=new Set,receiptAppendFailureLogs=new Set,batchFilter=context.sessionID!==void 0?{parentSessionId:context.sessionID}:void 0,records=findByBatchId(directory,parsed.data.batch_id,batchFilter);if(records.length===0)return collectFailureResult({failure_class:"not_found",batch_id:parsed.data.batch_id,message:`No async lane batch found for ${parsed.data.batch_id}`});let keepPolling=!0,pollIntervalMs=COLLECT_POLL_INTERVAL_MS;while(keepPolling){if(await collectOnce(session,directory,records,parsed.data.cancel_pending===!0,deadline,hostTimeouts,receiptAppendFailureLogs),await sweepStaleAsyncLaneRecords(session,directory,records,DEFAULT_ASYNC_STALE_TIMEOUT_MS,deadline,hostTimeouts),records=findByBatchId(directory,parsed.data.batch_id,batchFilter),allSettled(records)||parsed.data.wait!==!0){keepPolling=!1;continue}if(_internals208.now()>=deadline){keepPolling=!1;continue}await _internals208.sleep(Math.min(pollIntervalMs,Math.max(0,deadline-_internals208.now()))),pollIntervalMs=nextCollectPollInterval(pollIntervalMs)}let reviewReceiptFallbacks=await resolvePrReviewReceiptFallbacks(directory,context.sessionID,records),result=buildCollectResult(parsed.data.batch_id,records,parsed.data.include_pending??parsed.data.wait!==!0,{directory,sessionID:context.sessionID,reviewReceipts:reviewReceiptFallbacks});if(result.pending>0){let pendingLiveness=await collectPrWorkflowPendingLaneLiveness(directory,records,{probeBudgetMs:Math.max(0,deadline-_internals208.now())});if(pendingLiveness.length>0)result.pending_liveness=pendingLiveness}if(hostTimeouts.size>0)result.message=result.pending>0?"Collection deadline exhausted while waiting for OpenCode host calls; pending lanes remain safe to retry.":"Collection recovered and settled all lanes despite bounded OpenCode host-call timeouts; no collection retry is required.",result.errors=[...hostTimeouts];return result}async function createLaneSession(args2){let generation=1,decision=args2.dispatcher.dispatch(args2.lane.id);while(!0){if(decision.action!=="dispatch")return{ok:!1,generation,error:`dispatcher ${decision.action}: ${decision.reason}`};let createTimeoutMessage=`Lane "${args2.lane.id}" session.create timed out after ${args2.timeoutMs}ms`,createPromise;try{createPromise=args2.session.create(buildLaneSessionCreateArgs(args2.directory,args2.lane,args2.context))}catch(error93){createPromise=Promise.reject(error93)}let createTimedOut=!1;createPromise.then((result)=>{if(createTimedOut&&result.data?.id)scheduleSessionCleanup(args2.session,result.data.id)}).catch(()=>{return});let failureSignal,failureMessage;try{let result=await withTimeout2(createPromise,args2.timeoutMs,createTimeoutMessage);if(result.data?.id)return{ok:!0,sessionId:result.data.id,generation,slotId:decision.slot.slotId,runId:decision.slot.runId};failureSignal=result.error,failureMessage=result.error===void 0||result.error===null?"session.create failed: malformed response without a session id":`session.create failed: ${formatError3(result.error)}`}catch(error93){if(failureSignal=error93,failureMessage=formatError3(error93),failureMessage===createTimeoutMessage)createTimedOut=!0}if((createTimedOut||isRetryableSessionCreateFailure(failureSignal))&&generation<MAX_SESSION_CREATE_GENERATIONS){args2.dispatcher.releaseSlot(decision.slot.slotId),generation++,decision=args2.dispatcher.dispatch(args2.lane.id);continue}return{ok:!1,error:failureMessage,generation,slotId:decision.slot.slotId,runId:decision.slot.runId}}}function isRetryableSessionCreateFailure(error93){if(error93===void 0||error93===null)return!1;let seen=new WeakSet,pending=[{value:error93,depth:0}],visited=0,signalChars=0,transient=!1,permanent=!1,truncated=!1;while(pending.length>0&&visited<MAX_CREATE_FAILURE_WALK_NODES){let current=pending.shift();visited++;let{value,depth,key}=current;if((key==="isRetryable"||key==="retryable")&&value===!1)permanent=!0;if(typeof value==="number"&&Number.isInteger(value)){if(key===void 0||CREATE_FAILURE_STATUS_KEYS.has(key)){if(TRANSIENT_CREATE_STATUS_CODES.has(value))transient=!0;if(PERMANENT_CREATE_STATUS_CODES.has(value))permanent=!0}continue}if(typeof value==="string"){if(key!==void 0&&!CREATE_FAILURE_SCALAR_KEYS.has(key))continue;if(key!==void 0&&CREATE_FAILURE_STATUS_KEYS.has(key)&&/^\d+$/.test(value)){let numericStatus=Number(value);if(TRANSIENT_CREATE_STATUS_CODES.has(numericStatus))transient=!0;if(PERMANENT_CREATE_STATUS_CODES.has(numericStatus))permanent=!0}let remaining=MAX_CREATE_FAILURE_SIGNAL_CHARS-signalChars;if(remaining<=0){truncated=!0;continue}let signal2=value.slice(0,remaining);if(signal2.length<value.length)truncated=!0;if(signalChars+=signal2.length,PERMANENT_CREATE_SIGNAL_PATTERN.test(signal2))permanent=!0;if(TRANSIENT_CREATE_SIGNAL_PATTERN.test(signal2))transient=!0;continue}if(typeof value!=="object"&&typeof value!=="function"||value===null)continue;let object3=value;if(seen.has(object3))continue;if(seen.add(object3),depth>=MAX_CREATE_FAILURE_WALK_DEPTH){truncated=!0;continue}let isArray=!1;try{isArray=Array.isArray(object3)}catch{truncated=!0;continue}if(isArray){let arrayLength;try{let lengthDescriptor=Object.getOwnPropertyDescriptor(object3,"length");if(!lengthDescriptor||!("value"in lengthDescriptor)||typeof lengthDescriptor.value!=="number"||!Number.isSafeInteger(lengthDescriptor.value)||lengthDescriptor.value<0){truncated=!0;continue}arrayLength=lengthDescriptor.value}catch{truncated=!0;continue}let remainingNodes=MAX_CREATE_FAILURE_WALK_NODES-visited,itemCount=Math.min(arrayLength,remainingNodes);if(itemCount<arrayLength)truncated=!0;for(let index=0;index<itemCount;index++){let descriptor;try{descriptor=Object.getOwnPropertyDescriptor(object3,index)}catch{truncated=!0;continue}if(!descriptor)continue;if(!("value"in descriptor)){truncated=!0;continue}pending.push({value:descriptor.value,depth:depth+1,key})}continue}for(let propertyKey of CREATE_FAILURE_FIELD_KEYS){if(pending.length+visited>=MAX_CREATE_FAILURE_WALK_NODES){truncated=!0;break}let descriptor;try{descriptor=Object.getOwnPropertyDescriptor(object3,propertyKey)}catch{truncated=!0;continue}if(!descriptor)continue;if(!("value"in descriptor)){truncated=!0;continue}pending.push({value:descriptor.value,depth:depth+1,key:propertyKey})}}if(pending.length>0)truncated=!0;return transient&&!permanent&&!truncated}async function launchAsyncLane(args2){let validation2=validateLaneAgent(args2.lane.agent,args2.context),role=validation2.role,startedAt=isoNow2();if(!validation2.ok)return{id:args2.lane.id,agent:args2.lane.agent,role,status:"rejected",started_at:startedAt,completed_at:isoNow2(),error:validation2.error};let create=await createLaneSession({session:args2.session,dispatcher:args2.dispatcher,lane:args2.lane,directory:args2.directory,timeoutMs:args2.timeoutMs,context:args2.context});try{if(!create.ok)return failedLane(args2.lane,role,startedAt,create.error,create.slotId,create.runId,void 0,create.generation);let sessionId=create.sessionId,pendingOutcome=await recordPendingDelegationDetailed(args2.directory,{correlationId:sessionId,jobId:null,subagentSessionId:sessionId,parentSessionId:args2.context.sessionID?.trim()||`dispatch_lanes_async:${args2.batchId}`,callID:args2.batchId,normalizedAgent:role,swarmPrefixedAgent:args2.lane.agent,planTaskId:null,evidenceTaskId:null,batchId:args2.batchId,laneId:args2.lane.id,mode:args2.mode??"advisory",workflowLane:args2.lane.workflow_lane,ownedWorkflowLanes:args2.lane.owned_workflow_lanes,promptHash:promptHash(args2.lane,args2.directory,args2.batchId),workspace:{directory:args2.directory,gitHead:args2.gitHead??null,dirtyHash:args2.dirtyHash??null,prHeadSha:args2.prHeadSha??null,scope:args2.scope??null},generation:create.generation});if(pendingOutcome.status==="duplicate"||pendingOutcome.status==="conflict")return failedLane(args2.lane,role,startedAt,pendingOutcome.status==="duplicate"?"Async lane session.create returned an already-recorded correlation id":"Async lane session.create returned a correlation id owned by a different background delegation",create.slotId,create.runId,sessionId,create.generation);if(pendingOutcome.status==="failed")return cleanupAsyncLaunchSession(args2.session,sessionId),failedLane(args2.lane,role,startedAt,"Failed to record async lane in background delegation ledger",create.slotId,create.runId,sessionId,create.generation);return scheduleAsyncLanePrompt({session:args2.session,directory:args2.directory,sessionId,lane:args2.lane,timeoutMs:args2.timeoutMs}),{id:args2.lane.id,agent:args2.lane.agent,role,status:"pending",session_id:sessionId,slot_id:create.slotId,run_id:create.runId,generation:create.generation,started_at:startedAt,completed_at:isoNow2()}}catch(error93){return failedLane(args2.lane,role,startedAt,formatError3(error93),create.slotId,create.runId,create.ok?create.sessionId:void 0,create.generation)}finally{if(create.slotId)args2.dispatcher.releaseSlot(create.slotId)}}async function collectOnce(session,directory,records,cancelPending,deadline,hostTimeouts,receiptAppendFailureLogs){let activeRecords=records.filter((record3)=>record3.status==="pending"||record3.status==="running"),pendingSettlements=[];for(let index=0;index<activeRecords.length;index++){let record3=activeRecords[index],remainingLaneCount=activeRecords.length-index,needsRevisionDigest=Boolean(record3.workspace?.prHeadSha),laneBudgets=reserveCollectionLaneCallBudgets(deadline,remainingLaneCount,typeof session.status==="function",needsRevisionDigest);if(cancelPending){if(typeof session.abort==="function"){let timeoutCount=hostTimeouts.size;try{await withCollectionDeadline(()=>session.abort({path:{id:record3.subagentSessionId}}),deadline,`session.abort for lane session "${record3.subagentSessionId}"`,hostTimeouts,laneBudgets.laneBudgetMs)}catch{if(hostTimeouts.size>timeoutCount)continue}}await appendDelegationTransition(directory,record3.correlationId,{status:"cancelled"});continue}let readiness=await getLaneCollectionReadiness(session,directory,record3.subagentSessionId,deadline,hostTimeouts,laneBudgets.statusBudgetMs);if(readiness==="busy")continue;let messages;try{messages=await withCollectionDeadline(()=>session.messages({path:{id:record3.subagentSessionId},query:{directory,limit:ASYNC_MESSAGE_FETCH_LIMIT}}),deadline,`session.messages for lane "${record3.laneId??record3.correlationId}"`,hostTimeouts,laneBudgets.messagesBudgetMs)}catch{continue}if(!messages.data)continue;let transcript=extractAssistantTranscript(messages.data);if(!transcript.text)continue;if(readiness==="unknown"&&!transcript.terminalAssistantProof)continue;pendingSettlements.push(settleCollectedLane({directory,record:record3,transcript,deadline,hostTimeouts,revisionDigestBudgetMs:laneBudgets.revisionDigestBudgetMs,receiptAppendFailureLogs}))}await Promise.all(pendingSettlements)}async function settleCollectedLane(args2){let{directory,record:record3,transcript,deadline,hostTimeouts,receiptAppendFailureLogs}=args2,collectedRevisionDigest,prHeadSha=record3.workspace?.prHeadSha;if(prHeadSha)try{collectedRevisionDigest=await withCollectionDeadline(()=>_internals208.resolvePrWorkflowRevisionDigestAsync(directory,prHeadSha),deadline,`revision digest for lane "${record3.laneId??record3.correlationId}"`,hostTimeouts,args2.revisionDigestBudgetMs)??void 0}catch{return}let output=prepareLaneOutput({directory,batchId:record3.batchId??record3.callID,laneId:record3.laneId??record3.correlationId,agent:record3.swarmPrefixedAgent,role:record3.normalizedAgent,sessionId:record3.subagentSessionId,parentSessionId:record3.parentSessionId,mode:record3.mode,workflowLane:record3.workflowLane,prHeadSha:record3.workspace?.prHeadSha??void 0,gitHead:record3.workspace?.gitHead??void 0,revisionDigest:collectedRevisionDigest,scope:record3.workspace?.scope??void 0,source:"collect_lane_results",text:transcript.text,messageCount:transcript.messageCount,transcriptIncomplete:transcript.transcriptIncomplete}),prospectiveResult={text:output.output,chars:output.output_chars,truncated:output.output_truncated,digest:output.output_digest,...output.output_ref?{outputRef:output.output_ref}:{},outputPreviewChars:output.output.length,...output.output_degraded!==void 0?{outputDegraded:output.output_degraded}:{},...output.output_artifact_error?{outputArtifactError:output.output_artifact_error}:{},...output.transcript_incomplete!==void 0?{transcriptIncomplete:output.transcript_incomplete}:{},messageCount:transcript.messageCount},terminalStatus="completed";if(record3.mode==="swarm-pr-review:base"||record3.mode==="swarm-pr-review:micro"||record3.mode==="swarm-pr-review:council"){let artifact=output.output_ref?readLaneOutput(directory,output.output_ref)?.artifact??null:null,validation2=validatePrReviewDiscoveryLaneCompletion({record:record3,result:prospectiveResult,artifact,expected:{mode:record3.mode,workflowLane:record3.workflowLane??"",ownedWorkflowLanes:record3.ownedWorkflowLanes,prHeadSha:record3.workspace?.prHeadSha??"",gitHead:record3.workspace?.gitHead??"",revisionDigest:collectedRevisionDigest??"",reviewScope:record3.workspace?.scope??void 0}});if(validation2.ok&&validation2.salvaged?.length){if(prospectiveResult.salvagedWorkflowLanes=[...validation2.salvaged],validation2.recoveries?.length)prospectiveResult.salvagedWorkflowLaneRecoveries=[...validation2.recoveries]}if(!validation2.ok){terminalStatus="error";let family=record3.mode==="swarm-pr-review:base"?"base_explorer":"micro_lane";prospectiveResult.error=`PR_REVIEW_DISCOVERY_CONTRACT_INVALID: batch=${record3.batchId??"(missing)"} lane=${record3.laneId??"(missing)"} workflow_lane=${record3.workflowLane??"(missing)"} ${formatPrReviewLaneValidationFailure(validation2.failure)}; expected candidate row: ${CANDIDATE_HEADERS[family]}; expected clean row: ${CLEAN_TEMPLATES[family]}`,prospectiveResult.error=prospectiveResult.error.slice(0,1024)}}let isPrReviewVerdictLane=record3.mode==="swarm-pr-review:reviewer"||record3.mode==="swarm-pr-review:critic";if((isPrReviewVerdictLane||record3.mode==="swarm-pr-feedback:verification"||record3.mode==="swarm-pr-feedback:stage-b-reviewer"||record3.mode==="swarm-pr-feedback:stage-b-test"||record3.mode==="swarm-pr-feedback:closeout-reviewer"||record3.mode==="swarm-pr-feedback:closeout-critic")&&(isPrReviewVerdictLane||prospectiveResult.truncated===!0||prospectiveResult.transcriptIncomplete===!0)){let artifact=output.output_ref?readLaneOutput(directory,output.output_ref)?.artifact??null:null,transportValidationOperation=`transport recovery validation for lane "${record3.laneId??record3.correlationId}"`,transportValidationDeadlineDiagnosticPrefix=`${transportValidationOperation} exceeded the remaining collect_lane_results budget (`,validation2;try{validation2=await withCollectionDeadline(()=>_internals208.validatePrWorkflowTransportRecovery({directory,record:record3,result:prospectiveResult,artifact,revisionDigest:collectedRevisionDigest??""}),deadline,transportValidationOperation,hostTimeouts)}catch(error93){if(formatError3(error93).startsWith(transportValidationDeadlineDiagnosticPrefix))return;terminalStatus="error",prospectiveResult.error=`PR_WORKFLOW_CONTRACT_INVALID: batch=${record3.batchId??"(missing)"} lane=${record3.laneId??"(missing)"} workflow_lane=${record3.workflowLane??"(missing)"} `+formatError3(error93),prospectiveResult.error=prospectiveResult.error.slice(0,1024),await appendDelegationTransition(directory,record3.correlationId,{status:terminalStatus,result:prospectiveResult});return}if(validation2.receipt){let resultWithReceipt=appendPrReviewCollectionReceipt(record3,prospectiveResult,validation2.receipt);if(!resultWithReceipt){if(consumePrReviewReceiptAppendFailureLog(receiptAppendFailureLogs,record3.parentSessionId,record3.correlationId))log(`[dispatch-lanes] withheld PR-review terminal result without receipt: correlation=${record3.correlationId} batch=${record3.batchId??"(missing)"} lane=${record3.laneId??"(missing)"}`);return}prospectiveResult=resultWithReceipt}if(!validation2.ok){terminalStatus="error";let errorCode=validation2.failure?.predicate==="reviewer.verdict_rows"||validation2.failure?.predicate==="critic.verdict_rows"?"PR_REVIEW_VERDICT_CONTRACT_INVALID":"PR_WORKFLOW_CONTRACT_INVALID";prospectiveResult.error=`${errorCode}: batch=${record3.batchId??"(missing)"} lane=${record3.laneId??"(missing)"} workflow_lane=${record3.workflowLane??"(missing)"} ${validation2.reason}`,prospectiveResult.error=prospectiveResult.error.slice(0,1024)}else if(validation2.recoveries?.length){let workflowLane=record3.workflowLane?.trim();if(workflowLane)prospectiveResult.salvagedWorkflowLanes=[workflowLane];prospectiveResult.salvagedWorkflowLaneRecoveries=[...prospectiveResult.salvagedWorkflowLaneRecoveries??[],...validation2.recoveries]}}await appendDelegationTransition(directory,record3.correlationId,{status:terminalStatus,result:prospectiveResult})}function consumePrReviewReceiptAppendFailureLog(loggedFailures,parentSessionId,correlationId){let key=`${parentSessionId}\x00${correlationId}`;if(loggedFailures.has(key))return!1;return loggedFailures.add(key),!0}function scheduleAsyncLanePrompt(args2){queueMicrotask(()=>{startAsyncLanePrompt(args2).catch(async(error93)=>{let message=formatError3(error93);await appendAsyncLaneLaunchError(args2.directory,args2.session,args2.sessionId,message)})})}async function startAsyncLanePrompt(args2){let promptController=new AbortController,baseRole=stripKnownSwarmPrefix(args2.lane.agent),swarmID=baseRole!==args2.lane.agent?args2.lane.agent.slice(0,args2.lane.agent.length-baseRole.length-1):void 0,swarmAgents=getSwarmAgents(swarmID),promptResult;try{promptResult=(await dispatchWithModelFallback({dispatch:async(model,context)=>{let result=await withTimeout2(args2.session.promptAsync({path:{id:args2.sessionId},query:{directory:args2.directory},body:{agent:args2.lane.agent,...model?{model}:{},tools:buildReadOnlyTools(),parts:[{type:"text",text:args2.lane.prompt}]},signal:promptController.signal}),context.remainingMs??args2.timeoutMs,`Lane "${args2.lane.id}" session.promptAsync launch timed out after ${context.remainingMs??args2.timeoutMs}ms`,promptController);if(result.error)throw Error(`session.promptAsync launch failed: ${formatError3(result.error)}`);return result},classify:(error93)=>{let message=error93 instanceof Error?error93.message:String(error93);if(/timed out/i.test(message))return"permanent";return isTransientProviderError(message)?"transient":"permanent"},maxTransientRetriesPerModel:0,deadlineAtMs:_internals208.now()+args2.timeoutMs,now:_internals208.now,scope:{sessionID:args2.sessionId,invocationID:`dispatch-lanes-async:${args2.lane.id}`,swarmID,role:baseRole},primaryModel:swarmAgents?.[baseRole]?.model,fallbackModels:swarmAgents?.[baseRole]?.fallback_models??[]})).result}catch(error93){await appendAsyncLaneLaunchError(args2.directory,args2.session,args2.sessionId,formatError3(error93));return}if(promptResult.error){await appendAsyncLaneLaunchError(args2.directory,args2.session,args2.sessionId,`session.promptAsync launch failed: ${formatError3(promptResult.error)}`);return}await appendDelegationTransition(args2.directory,args2.sessionId,{status:"running"})}async function appendAsyncLaneLaunchError(directory,session,sessionId,message){await appendDelegationTransition(directory,sessionId,{status:"error",result:{error:message,chars:message.length,truncated:!1,digest:digestText2(message)}}),cleanupAsyncLaunchSession(session,sessionId)}async function getLaneCollectionReadiness(session,directory,sessionId,deadline,hostTimeouts,statusBudgetMs){if(typeof session.status!=="function")return"unknown";if(statusBudgetMs<=0)return"unknown";try{let status=await withCollectionDeadline(()=>session.status({query:{directory}}),deadline,`session.status for lane session "${sessionId}"`,hostTimeouts,statusBudgetMs);if(status.error||!status.data)return"unknown";let current=status.data[sessionId];if(current===void 0)return"unknown";if(current.type==="idle")return"idle";if(current.type==="busy"||current.type==="retry")return"busy";return"unknown"}catch{return"unknown"}}async function sweepStaleAsyncLaneRecords(session,directory,records,staleTimeoutMs,deadline,hostTimeouts){if(staleTimeoutMs<=0)return;let now2=_internals208.now();for(let record3 of records){let currentBeforeReadiness=getCurrentStaleSweepCandidate(directory,record3,staleTimeoutMs,now2);if(!currentBeforeReadiness)continue;if(await getLaneCollectionReadiness(session,directory,currentBeforeReadiness.subagentSessionId,deadline,hostTimeouts,reserveCollectionLaneCallBudgets(deadline,records.length,typeof session.status==="function").statusBudgetMs)!=="idle")continue;let currentAfterReadiness=getCurrentStaleSweepCandidate(directory,record3,staleTimeoutMs,now2);if(!currentAfterReadiness)continue;await appendDelegationTransition(directory,currentAfterReadiness.correlationId,{status:"stale",expectedCurrentStatuses:["pending","running","ingestion_error"]})}}function getCurrentStaleSweepCandidate(directory,record3,staleTimeoutMs,now2){let current=findByCorrelationId(directory,record3.correlationId);if(!current)return null;if(current.subagentSessionId!==record3.subagentSessionId)return null;if((current.generation??1)!==(record3.generation??1))return null;if(current.status!=="pending"&¤t.status!=="running"&¤t.status!=="ingestion_error")return null;if(now2-current.updatedAt<=staleTimeoutMs)return null;return current}function extractAssistantTranscript(messages){let assistantTexts=[],lastAssistantInfo;for(let message of messages){if(message.info?.role!=="assistant")continue;lastAssistantInfo=message.info;let text=extractText3(message.parts);if(text.trim().length>0)assistantTexts.push(text)}let completedAt=lastAssistantInfo?.time?.completed,finish=typeof lastAssistantInfo?.finish==="string"?lastAssistantInfo.finish.toLowerCase():"",terminalAssistantFinish=finish==="stop"||finish==="length"||finish==="content-filter";return{text:assistantTexts.join(`
|
|
6719
6762
|
|
|
6720
6763
|
`),messageCount:assistantTexts.length,transcriptIncomplete:messages.length>=ASYNC_MESSAGE_FETCH_LIMIT||finish==="length"||finish==="content-filter",terminalAssistantProof:typeof completedAt==="number"&&Number.isFinite(completedAt)&&terminalAssistantFinish&&lastAssistantInfo?.error===void 0}}function reserveCollectionLaneCallBudgets(deadline,remainingLaneCount,hasStatusCall,hasRevisionDigestCall=!1){let remainingMs2=Math.max(0,deadline-_internals208.now());if(remainingMs2===0)return{laneBudgetMs:0,statusBudgetMs:0,messagesBudgetMs:0,revisionDigestBudgetMs:0};let laneBudgetMs=Math.min(remainingMs2,Math.max(1,Math.floor(remainingMs2/Math.max(1,remainingLaneCount)))),callCount=1+Number(hasStatusCall)+Number(hasRevisionDigestCall),statusBudgetMs=hasStatusCall?Math.min(MAX_STATUS_CALL_BUDGET_MS,Math.floor(laneBudgetMs/callCount)):0,afterStatusMs=laneBudgetMs-statusBudgetMs,revisionDigestBudgetMs=hasRevisionDigestCall?Math.floor(afterStatusMs/2):0;return{laneBudgetMs,statusBudgetMs,messagesBudgetMs:afterStatusMs-revisionDigestBudgetMs,revisionDigestBudgetMs}}function nextCollectPollInterval(currentMs){if(currentMs<=0)return COLLECT_POLL_INTERVAL_MS;return Math.min(currentMs*2,MAX_COLLECT_POLL_INTERVAL_MS)}async function runLane(session,dispatcher,lane,directory,timeoutMs,context){let validation2=validateLaneAgent(lane.agent,context),role=validation2.role,startedAt=isoNow2();if(!validation2.ok)return{id:lane.id,agent:lane.agent,role,status:"rejected",started_at:startedAt,completed_at:isoNow2(),error:validation2.error};let promptController=new AbortController,create=await createLaneSession({session,dispatcher,lane,directory,timeoutMs,context}),sessionId=create.ok?create.sessionId:void 0;try{if(!create.ok)return failedLane(lane,role,startedAt,create.error,create.slotId,create.runId,void 0,create.generation);sessionId=create.sessionId;let createdSessionId=sessionId,baseRole=stripKnownSwarmPrefix(lane.agent),swarmID=baseRole!==lane.agent?lane.agent.slice(0,lane.agent.length-baseRole.length-1):void 0,swarmAgents=getSwarmAgents(swarmID),promptResult=(await dispatchWithModelFallback({dispatch:async(model,context2)=>{let result=await withTimeout2(session.prompt({path:{id:createdSessionId},body:{agent:lane.agent,...model?{model}:{},tools:buildReadOnlyTools(),parts:[{type:"text",text:lane.prompt}]},signal:promptController.signal}),context2.remainingMs??timeoutMs,`Lane "${lane.id}" session.prompt timed out after ${context2.remainingMs??timeoutMs}ms`,promptController);if(!result.data)throw Error(`session.prompt failed: ${formatError3(result.error)}`);return result},classify:(error93)=>{let message=error93 instanceof Error?error93.message:String(error93);if(/timed out/i.test(message))return"permanent";return isTransientProviderError(message)?"transient":"permanent"},maxTransientRetriesPerModel:0,deadlineAtMs:_internals208.now()+timeoutMs,now:_internals208.now,scope:{sessionID:sessionId,invocationID:`dispatch-lanes-sync:${lane.id}`,swarmID,role:baseRole},primaryModel:swarmAgents?.[baseRole]?.model,fallbackModels:swarmAgents?.[baseRole]?.fallback_models??[]})).result;if(!promptResult.data)return failedLane(lane,role,startedAt,`session.prompt failed: ${formatError3(promptResult.error)}`,create.slotId,create.runId,sessionId,create.generation);let laneOutput=prepareLaneOutput({directory,batchId:`blocking:${sessionId}`,laneId:lane.id,agent:lane.agent,role,sessionId,parentSessionId:context.sessionID,source:"dispatch_lanes",text:extractText3(promptResult.data.parts)});return{id:lane.id,agent:lane.agent,role,status:"completed",session_id:sessionId,slot_id:create.slotId,run_id:create.runId,generation:create.generation,started_at:startedAt,completed_at:isoNow2(),...laneOutput}}catch(error93){return failedLane(lane,role,startedAt,formatError3(error93),create.slotId,create.runId,sessionId,create.generation)}finally{if(create.slotId)dispatcher.releaseSlot(create.slotId);if(promptController.abort(),sessionId)scheduleSessionCleanup(session,sessionId)}}function buildResult(laneResults,maxConcurrent,timeoutMs){let completed=laneResults.filter((lane)=>lane.status==="completed"),failed=laneResults.filter((lane)=>lane.status==="failed"),rejected=laneResults.filter((lane)=>lane.status==="rejected");return{success:failed.length===0&&rejected.length===0,dispatched:laneResults.length,completed:completed.length,failed:failed.length,rejected:rejected.length,max_concurrent:maxConcurrent,timeout_ms:timeoutMs,lane_results:laneResults}}function buildCollectResult(batchId,records,includePending,deliveryContext){let laneResults=records.filter((record3)=>includePending||record3.status!=="pending"&&record3.status!=="running"&&record3.status!=="ingesting").map((record3)=>recordToLaneResult(record3,batchId,deliveryContext)),completed=records.filter((record3)=>record3.status==="completed"),failed=records.filter((record3)=>record3.status==="error"||record3.status==="ingestion_error"),cancelled=records.filter((record3)=>record3.status==="cancelled"),stale=records.filter((record3)=>record3.status==="stale"),pending=records.filter((record3)=>record3.status==="pending"||record3.status==="running"||record3.status==="ingesting"),consumed=records.filter((record3)=>record3.status==="consumed");return{success:pending.length===0&&failed.length===0&&cancelled.length===0&&stale.length===0,batch_id:batchId,total:records.length,completed:completed.length,failed:failed.length,cancelled:cancelled.length,stale:stale.length,pending:pending.length,consumed:consumed.length,all_settled:pending.length===0,lane_results:laneResults}}async function resolvePrReviewReceiptFallbacks(directory,sessionID,records){let receipts=new Map;if(!sessionID)return receipts;let unresolved=records.filter((record3)=>(record3.mode==="swarm-pr-review:reviewer"||record3.mode==="swarm-pr-review:critic")&&!parsePrReviewCollectionReceipt(record3)&&record3.result!==void 0&&parsePrReviewCollectionReceiptShedMarker(record3,record3.result)!==null);if(unresolved.length===0)return receipts;let state;try{state=await readPrWorkflowGateState(directory,sessionID)}catch(error93){return log(`[dispatch-lanes] unable to reconstruct compacted PR-review receipts: ${formatError3(error93)}`),receipts}if(!state||state.mode!=="PR_REVIEW")return receipts;return resolvePrReviewReceiptFallbacksFromState(unresolved,state)}function resolvePrReviewReceiptFallbacksFromState(records,state){let receipts=new Map;for(let record3 of records){let phase=record3.mode==="swarm-pr-review:reviewer"?"reviewer":record3.mode==="swarm-pr-review:critic"?"critic":null;if(!phase||!record3.batchId||!record3.laneId)continue;if(record3.status!=="completed"&&record3.status!=="error"&&record3.status!=="ingestion_error"&&record3.status!=="cancelled"&&record3.status!=="stale")continue;let itemIds=(state.prReviewValidationBatches??[]).find((batch)=>batch.batchId===record3.batchId&&batch.phase===phase)?.lanes.find((candidate2)=>candidate2.laneId===record3.laneId&&candidate2.workflowLane===record3.workflowLane)?.reviewItemIds??[];if(itemIds.length===0)continue;let marker=record3.result?parsePrReviewCollectionReceiptShedMarker(record3,record3.result):null,projected=marker?projectPrReviewCollectionReceiptShedMarker(marker,itemIds):null;if(projected)receipts.set(record3.correlationId,projected)}return receipts}function appendPrReviewCollectionReceipt(record3,result,receipt){let sanitizedPreview=(result.text??"").split(/\r?\n/).filter((line)=>!line.startsWith(PR_REVIEW_COLLECTION_RECEIPT_PREFIX)&&!line.startsWith(PR_REVIEW_COLLECTION_RECEIPT_SHED_PREFIX)).join(`
|
|
6721
6764
|
`),footer=encodePrReviewCollectionReceiptFooter(record3,result,receipt)??encodePrReviewCollectionReceiptShedMarkerFromReceipt(record3,result,receipt);if(!footer)return null;let text=sanitizedPreview?`${sanitizedPreview}
|
|
@@ -6741,7 +6784,7 @@ This controller block is authoritative over conflicting caller text. Inspect the
|
|
|
6741
6784
|
Terminate with the required protocol rows directly: no planning preamble, no recap, and no more than ${outputCap} characters of substantive output before any retrieval hint.${budgetParagraph}${shellRulesParagraph}
|
|
6742
6785
|
[END CONTROLLER-BOUND PR WORKFLOW CONTRACT]`,prompt=`${lane.prompt}${contract}`;if(prompt.length>MAX_PROMPT_CHARS)errors5.push(`Lane "${lane.id}" prompt plus mandatory PR workflow contract is ${prompt.length} chars; max ${MAX_PROMPT_CHARS} (a repo-graph orientation block may have been prepended to common_prompt — retry with orientation: false to exclude it)`);return{...lane,prompt}});return errors5.length>0?{ok:!1,errors:errors5}:{ok:!0,lanes:contracted}}function findDuplicateLaneIds(lanes){let seen=new Set,duplicates=new Set;for(let lane of lanes){if(seen.has(lane.id))duplicates.add(lane.id);seen.add(lane.id)}return[...duplicates]}function scheduleSessionCleanup(session,sessionId){teardownEphemeralSession(session,sessionId)}function cleanupAsyncLaunchSession(session,sessionId){teardownEphemeralSession(session,sessionId)}async function withCollectionDeadline(operationPromise,deadline,operation,hostTimeouts,budgetMs){let remainingMs2=Math.max(0,deadline-_internals208.now()),allowedMs=budgetMs===void 0?remainingMs2:Math.min(remainingMs2,Math.max(0,budgetMs)),diagnostic=`${operation} exceeded the remaining collect_lane_results budget (${allowedMs}ms)`;if(allowedMs===0)throw hostTimeouts.add(diagnostic),Error(diagnostic);try{return await withTimeout2(operationPromise(),allowedMs,diagnostic)}catch(error93){if(formatError3(error93)===diagnostic)hostTimeouts.add(diagnostic);throw error93}}async function withTimeout2(promise3,timeoutMs,message,controller){let timeout;try{return await Promise.race([promise3,new Promise((_,reject2)=>{timeout=setTimeout(()=>{controller?.abort(),reject2(Error(message))},timeoutMs)})])}finally{if(timeout)clearTimeout(timeout)}}function extractText3(parts){if(!Array.isArray(parts))return"";return parts.filter((part)=>part.type==="text").map((part)=>part.text??"").join(`
|
|
6743
6786
|
`)}function formatError3(error93){if(error93 instanceof Error)return error93.message;let text;if(typeof error93==="string")text=error93;else if(typeof error93==="object"&&error93!==null)try{text=JSON.stringify(error93)}catch{text=String(error93)}else text=String(error93);return boundErrorString(text)}function boundErrorString(text){if(text.length<=MAX_ERROR_CHARS)return text;return`${text.slice(0,MAX_ERROR_CHARS)}${ERROR_TRUNCATION_SUFFIX}`}function isoNow2(){return new Date(_internals208.now()).toISOString()}function buildLaneSessionCreateArgs(directory,lane,context){let parentID=context.sessionID?.trim(),escapedAgent=lane.agent.replace(/\(/g,"(").replace(/\)/g,")");return{body:{...parentID?{parentID}:{},title:`${lane.id} (${escapedAgent})`},query:{directory}}}function makeBatchId(){return`lanes-${_internals208.now().toString(36)}`}function promptHash(lane,directory,batchId){return digestText2(JSON.stringify({batchId,laneId:lane.id,agent:lane.agent,directory,prompt:lane.prompt.replace(/\r\n/g,`
|
|
6744
|
-
`)}))}function digestText2(text){return createHash62("sha256").update(text).digest("hex")}function sleep3(ms){if(ms<=0)return Promise.resolve();return new Promise((resolve113)=>{setTimeout(resolve113,ms)})}var dispatch_lanes=createSwarmTool({description:"Dispatch multiple read-only exploration/review lanes concurrently and BLOCK until every lane finishes, returning a structured join result. This blocks the caller until completion; for non-blocking dispatch that lets you keep working while lanes run, prefer dispatch_lanes_async + collect_lane_results and use this blocking variant only when promptAsync is unavailable. Keep each lane prompt compact: send large shared context once via common_prompt (or have lanes read it from a file by absolute path) instead of inlining it into every lane prompt. A bounded repo-graph orientation block is prepended to common_prompt by default when the graph is fresh and relevant (set orientation: false to disable).",args:{lanes:DispatchLanesArgsSchema.shape.lanes,common_prompt:DispatchLanesArgsSchema.shape.common_prompt,max_concurrent:DispatchLanesArgsSchema.shape.max_concurrent,timeout_ms:DispatchLanesArgsSchema.shape.timeout_ms,orientation:DispatchLanesArgsSchema.shape.orientation},execute:async(args2,directory,ctx)=>{let result=await executeDispatchLanes(args2,directory,{callerAgent:getContextAgent(ctx),sessionID:getContextSessionID(ctx)});return JSON.stringify(result,null,2)}}),dispatch_lanes_async=createSwarmTool({description:"Launch multiple read-only advisory lanes with OpenCode promptAsync and return IMMEDIATELY with a batch id and lane session handles (non-blocking). launch_timeout_ms only bounds session creation and promptAsync acceptance; it is NOT a lane runtime timeout. After launching, keep working on non-dependent investigation while lanes run — poll incrementally with collect_lane_results (wait omitted or false) to process settled lanes as they complete, or use wait: true only at workflow boundaries where all results are needed. Keep each lane prompt compact: send large shared context once via common_prompt (or have lanes read it from a file by absolute path) instead of inlining it into every lane prompt, which can produce oversized or malformed tool-call JSON. A bounded repo-graph orientation block is prepended to common_prompt by default when the graph is fresh and relevant (set orientation: false to disable).",args:{lanes:DispatchLanesAsyncArgsSchema.shape.lanes,common_prompt:DispatchLanesAsyncArgsSchema.shape.common_prompt,max_concurrent:DispatchLanesAsyncArgsSchema.shape.max_concurrent,launch_timeout_ms:DispatchLanesAsyncArgsSchema.shape.launch_timeout_ms,timeout_ms:DispatchLanesAsyncArgsSchema.shape.timeout_ms,batch_id:DispatchLanesAsyncArgsSchema.shape.batch_id,mode:DispatchLanesAsyncArgsSchema.shape.mode,pr_head_sha:DispatchLanesAsyncArgsSchema.shape.pr_head_sha,base_sha:DispatchLanesAsyncArgsSchema.shape.base_sha,base_ref:DispatchLanesAsyncArgsSchema.shape.base_ref,scope:DispatchLanesAsyncArgsSchema.shape.scope,trigger_evaluation:DispatchLanesAsyncArgsSchema.shape.trigger_evaluation,feedback_inventory:DispatchLanesAsyncArgsSchema.shape.feedback_inventory,pr_review_wave_stage:DispatchLanesAsyncArgsSchema.shape.pr_review_wave_stage,pr_review_wave_attempt:DispatchLanesAsyncArgsSchema.shape.pr_review_wave_attempt,orientation:DispatchLanesAsyncArgsSchema.shape.orientation},execute:async(args2,directory,ctx)=>{let result=await executeDispatchLanesAsync(args2,directory,{callerAgent:getContextAgent(ctx),sessionID:getContextSessionID(ctx)});return JSON.stringify(result,null,2)}}),collect_lane_results=createSwarmTool({description:"Collect or poll results for a dispatch_lanes_async batch. Supports two modes: (1) non-blocking poll (wait omitted or false) — performs one collection pass and returns current lane status, including pending lane identities by default, and any settled results so you can process completed lanes while continuing independent work; (2) blocking join (wait: true) — polls until all lanes settle or the collection wait budget expires. Busy/retry lanes do not become stale solely because they run for a long time. Does not advance workflow gates.",args:{batch_id:CollectLaneResultsArgsSchema.shape.batch_id,wait:CollectLaneResultsArgsSchema.shape.wait,timeout_ms:CollectLaneResultsArgsSchema.shape.timeout_ms,include_pending:CollectLaneResultsArgsSchema.shape.include_pending,cancel_pending:CollectLaneResultsArgsSchema.shape.cancel_pending},execute:async(args2,directory,ctx)=>{let result=await executeCollectLaneResults(args2,directory,{sessionID:getContextSessionID(ctx)});return JSON.stringify(result,null,2)}});function getContextAgent(ctx){if(!ctx||typeof ctx!=="object")return;let value=ctx.agent;return typeof value==="string"?value:void 0}function getContextSessionID(ctx){if(!ctx||typeof ctx!=="object")return;let value=ctx.sessionID;return typeof value==="string"?value:void 0}init_doc_scan();init_zod();init_create_tool();var DOMAIN_PATTERNS={windows:[/\bwindows\b/i,/\bwin32\b/i,/\bregistry\b/i,/\bregedit\b/i,/\bwmi\b/i,/\bcim\b/i,/\bservice\b/i,/\bevent\s*log\b/i,/\bscheduled\s*task\b/i,/\bgpo\b/i,/\bgroup\s*policy\b/i,/\bmsi\b/i,/\binstaller\b/i,/\bwinrm\b/i],powershell:[/\bpowershell\b/i,/\bpwsh\b/i,/\bps1\b/i,/\bcmdlet\b/i,/\bget-\w+/i,/\bset-\w+/i,/\bnew-\w+/i,/\bremove-\w+/i,/\binvoke-\w+/i,/\bpester\b/i],python:[/\bpython\b/i,/\bpip\b/i,/\bpypi\b/i,/\bdjango\b/i,/\bflask\b/i,/\bpandas\b/i,/\bnumpy\b/i,/\bpytest\b/i,/\bvenv\b/i,/\bconda\b/i],oracle:[/\boracle\b/i,/\bsqlplus\b/i,/\bplsql\b/i,/\btnsnames\b/i,/\bpdb\b/i,/\bcdb\b/i,/\btablespace\b/i,/\brman\b/i,/\bdataguard\b/i,/\basm\b/i,/\brac\b/i,/\bora-\d+/i],network:[/\bnetwork\b/i,/\bfirewall\b/i,/\bdns\b/i,/\bdhcp\b/i,/\btcp\b/i,/\budp\b/i,/\bip\s*address\b/i,/\bsubnet\b/i,/\bvlan\b/i,/\brouting\b/i,/\bswitch\b/i,/\bload\s*balanc/i,/\bproxy\b/i,/\bssl\b/i,/\btls\b/i,/\bcertificate\b/i],security:[/\bstig\b/i,/\bdisa\b/i,/\bcve\b/i,/\bvulnerabil/i,/\bharden\b/i,/\baudit\b/i,/\bcompliance\b/i,/\bscap\b/i,/\bfips\b/i,/\bcac\b/i,/\bpki\b/i,/\bencrypt/i],linux:[/\blinux\b/i,/\bubuntu\b/i,/\brhel\b/i,/\bcentos\b/i,/\bbash\b/i,/\bsystemd\b/i,/\bsystemctl\b/i,/\byum\b/i,/\bapt\b/i,/\bcron\b/i,/\bchmod\b/i,/\bchown\b/i],vmware:[/\bvmware\b/i,/\bvsphere\b/i,/\besxi\b/i,/\bvcenter\b/i,/\bvsan\b/i,/\bnsx\b/i,/\bvmotion\b/i,/\bdatastore\b/i,/\bpowercli\b/i,/\bova\b/i,/\bovf\b/i],azure:[/\bazure\b/i,/\baz\s+\w+/i,/\bentra\b/i,/\baad\b/i,/\bazure\s*ad\b/i,/\barm\s*template\b/i,/\bbicep\b/i,/\bazure\s*devops\b/i,/\bblob\b/i,/\bkeyvault\b/i],active_directory:[/\bactive\s*directory\b/i,/\bad\s+\w+/i,/\bldap\b/i,/\bdomain\s*controller\b/i,/\bgpupdate\b/i,/\bdsquery\b/i,/\bdsmod\b/i,/\baduc\b/i,/\bkerberos\b/i,/\bspn\b/i],ui_ux:[/\bui\b/i,/\bux\b/i,/\buser\s+experience\b/i,/\buser\s+interface\b/i,/\bvisual\s+design\b/i,/\binteraction\s+design\b/i,/\bdesign\s+system\b/i,/\bwireframe\b/i,/\bprototype\b/i,/\baccessibility\b/i,/\btypography\b/i,/\blayout\b/i,/\bresponsive\b/i]},detect_domains=createSwarmTool({description:"Detect which SME domains are relevant for a given text. Returns a list of domain names (windows, powershell, python, oracle, network, security, linux, vmware, azure, active_directory, ui_ux) that match patterns in the input text.",args:{text:exports_external.string().describe("The text to analyze for domain patterns")},execute:async(args2)=>{let text=(typeof args2.text==="string"?args2.text:String(args2.text)).toLowerCase(),detected=[];for(let[domain3,patterns]of Object.entries(DOMAIN_PATTERNS))for(let pattern of patterns)if(pattern.test(text)){detected.push(domain3);break}if(detected.length===0)return"No specific domains detected. The Architect should determine requirements from context.";return`Detected domains: ${detected.join(", ")}
|
|
6787
|
+
`)}))}function digestText2(text){return createHash62("sha256").update(text).digest("hex")}function sleep3(ms){if(ms<=0)return Promise.resolve();return new Promise((resolve113)=>{setTimeout(resolve113,ms)})}var dispatch_lanes=createSwarmTool({description:"Dispatch multiple read-only exploration/review lanes concurrently and BLOCK until every lane finishes, returning a structured join result. This blocks the caller until completion; for non-blocking dispatch that lets you keep working while lanes run, prefer dispatch_lanes_async + collect_lane_results and use this blocking variant only when promptAsync is unavailable. Keep each lane prompt compact: send large shared context once via common_prompt (or have lanes read it from a file by absolute path) instead of inlining it into every lane prompt. A bounded repo-graph orientation block is prepended to common_prompt by default when the graph is fresh and relevant (set orientation: false to disable).",args:{lanes:DispatchLanesArgsSchema.shape.lanes,common_prompt:DispatchLanesArgsSchema.shape.common_prompt,max_concurrent:DispatchLanesArgsSchema.shape.max_concurrent,timeout_ms:DispatchLanesArgsSchema.shape.timeout_ms,orientation:DispatchLanesArgsSchema.shape.orientation},execute:async(args2,directory,ctx)=>{let result=await executeDispatchLanes(args2,directory,{callerAgent:getContextAgent(ctx),sessionID:getContextSessionID(ctx)});return JSON.stringify(result,null,2)}}),dispatch_lanes_async=createSwarmTool({description:"Launch multiple read-only advisory lanes with OpenCode promptAsync and return IMMEDIATELY with a batch id and lane session handles (non-blocking). launch_timeout_ms only bounds session creation and promptAsync acceptance; it is NOT a lane runtime timeout. After launching, keep working on non-dependent investigation while lanes run — poll incrementally with collect_lane_results (wait omitted or false) to process settled lanes as they complete, or use wait: true only at workflow boundaries where all results are needed. Keep each lane prompt compact: send large shared context once via common_prompt (or have lanes read it from a file by absolute path) instead of inlining it into every lane prompt, which can produce oversized or malformed tool-call JSON. A bounded repo-graph orientation block is prepended to common_prompt by default when the graph is fresh and relevant (set orientation: false to disable).",args:{lanes:DispatchLanesAsyncArgsSchema.shape.lanes,common_prompt:DispatchLanesAsyncArgsSchema.shape.common_prompt,max_concurrent:DispatchLanesAsyncArgsSchema.shape.max_concurrent,launch_timeout_ms:DispatchLanesAsyncArgsSchema.shape.launch_timeout_ms,timeout_ms:DispatchLanesAsyncArgsSchema.shape.timeout_ms,batch_id:DispatchLanesAsyncArgsSchema.shape.batch_id,mode:DispatchLanesAsyncArgsSchema.shape.mode,pr_head_sha:DispatchLanesAsyncArgsSchema.shape.pr_head_sha,base_sha:DispatchLanesAsyncArgsSchema.shape.base_sha,base_ref:DispatchLanesAsyncArgsSchema.shape.base_ref,scope:DispatchLanesAsyncArgsSchema.shape.scope,trigger_evaluation:DispatchLanesAsyncArgsSchema.shape.trigger_evaluation,feedback_inventory:DispatchLanesAsyncArgsSchema.shape.feedback_inventory,pr_review_wave_stage:DispatchLanesAsyncArgsSchema.shape.pr_review_wave_stage,pr_review_wave_attempt:DispatchLanesAsyncArgsSchema.shape.pr_review_wave_attempt,orientation:DispatchLanesAsyncArgsSchema.shape.orientation},execute:async(args2,directory,ctx)=>{let result=await executeDispatchLanesAsync(args2,directory,{callerAgent:getContextAgent(ctx),sessionID:getContextSessionID(ctx)});return JSON.stringify(result,null,2)}}),collect_lane_results=createSwarmTool({description:"Collect or poll results for a dispatch_lanes_async batch. Supports two modes: (1) non-blocking poll (wait omitted or false) — performs one collection pass and returns current lane status, including pending lane identities by default, and any settled results so you can process completed lanes while continuing independent work; (2) blocking join (wait: true) — polls until all lanes settle or the collection wait budget expires. Busy/retry lanes do not become stale solely because they run for a long time; pr-review lanes pending for minutes additionally carry an alert-only pending_liveness diagnostic (lane id, elapsed ms, host session status, stalledSuspect) that never cancels or replaces anything. Does not advance workflow gates.",args:{batch_id:CollectLaneResultsArgsSchema.shape.batch_id,wait:CollectLaneResultsArgsSchema.shape.wait,timeout_ms:CollectLaneResultsArgsSchema.shape.timeout_ms,include_pending:CollectLaneResultsArgsSchema.shape.include_pending,cancel_pending:CollectLaneResultsArgsSchema.shape.cancel_pending},execute:async(args2,directory,ctx)=>{let result=await executeCollectLaneResults(args2,directory,{sessionID:getContextSessionID(ctx)});return JSON.stringify(result,null,2)}});function getContextAgent(ctx){if(!ctx||typeof ctx!=="object")return;let value=ctx.agent;return typeof value==="string"?value:void 0}function getContextSessionID(ctx){if(!ctx||typeof ctx!=="object")return;let value=ctx.sessionID;return typeof value==="string"?value:void 0}init_doc_scan();init_zod();init_create_tool();var DOMAIN_PATTERNS={windows:[/\bwindows\b/i,/\bwin32\b/i,/\bregistry\b/i,/\bregedit\b/i,/\bwmi\b/i,/\bcim\b/i,/\bservice\b/i,/\bevent\s*log\b/i,/\bscheduled\s*task\b/i,/\bgpo\b/i,/\bgroup\s*policy\b/i,/\bmsi\b/i,/\binstaller\b/i,/\bwinrm\b/i],powershell:[/\bpowershell\b/i,/\bpwsh\b/i,/\bps1\b/i,/\bcmdlet\b/i,/\bget-\w+/i,/\bset-\w+/i,/\bnew-\w+/i,/\bremove-\w+/i,/\binvoke-\w+/i,/\bpester\b/i],python:[/\bpython\b/i,/\bpip\b/i,/\bpypi\b/i,/\bdjango\b/i,/\bflask\b/i,/\bpandas\b/i,/\bnumpy\b/i,/\bpytest\b/i,/\bvenv\b/i,/\bconda\b/i],oracle:[/\boracle\b/i,/\bsqlplus\b/i,/\bplsql\b/i,/\btnsnames\b/i,/\bpdb\b/i,/\bcdb\b/i,/\btablespace\b/i,/\brman\b/i,/\bdataguard\b/i,/\basm\b/i,/\brac\b/i,/\bora-\d+/i],network:[/\bnetwork\b/i,/\bfirewall\b/i,/\bdns\b/i,/\bdhcp\b/i,/\btcp\b/i,/\budp\b/i,/\bip\s*address\b/i,/\bsubnet\b/i,/\bvlan\b/i,/\brouting\b/i,/\bswitch\b/i,/\bload\s*balanc/i,/\bproxy\b/i,/\bssl\b/i,/\btls\b/i,/\bcertificate\b/i],security:[/\bstig\b/i,/\bdisa\b/i,/\bcve\b/i,/\bvulnerabil/i,/\bharden\b/i,/\baudit\b/i,/\bcompliance\b/i,/\bscap\b/i,/\bfips\b/i,/\bcac\b/i,/\bpki\b/i,/\bencrypt/i],linux:[/\blinux\b/i,/\bubuntu\b/i,/\brhel\b/i,/\bcentos\b/i,/\bbash\b/i,/\bsystemd\b/i,/\bsystemctl\b/i,/\byum\b/i,/\bapt\b/i,/\bcron\b/i,/\bchmod\b/i,/\bchown\b/i],vmware:[/\bvmware\b/i,/\bvsphere\b/i,/\besxi\b/i,/\bvcenter\b/i,/\bvsan\b/i,/\bnsx\b/i,/\bvmotion\b/i,/\bdatastore\b/i,/\bpowercli\b/i,/\bova\b/i,/\bovf\b/i],azure:[/\bazure\b/i,/\baz\s+\w+/i,/\bentra\b/i,/\baad\b/i,/\bazure\s*ad\b/i,/\barm\s*template\b/i,/\bbicep\b/i,/\bazure\s*devops\b/i,/\bblob\b/i,/\bkeyvault\b/i],active_directory:[/\bactive\s*directory\b/i,/\bad\s+\w+/i,/\bldap\b/i,/\bdomain\s*controller\b/i,/\bgpupdate\b/i,/\bdsquery\b/i,/\bdsmod\b/i,/\baduc\b/i,/\bkerberos\b/i,/\bspn\b/i],ui_ux:[/\bui\b/i,/\bux\b/i,/\buser\s+experience\b/i,/\buser\s+interface\b/i,/\bvisual\s+design\b/i,/\binteraction\s+design\b/i,/\bdesign\s+system\b/i,/\bwireframe\b/i,/\bprototype\b/i,/\baccessibility\b/i,/\btypography\b/i,/\blayout\b/i,/\bresponsive\b/i]},detect_domains=createSwarmTool({description:"Detect which SME domains are relevant for a given text. Returns a list of domain names (windows, powershell, python, oracle, network, security, linux, vmware, azure, active_directory, ui_ux) that match patterns in the input text.",args:{text:exports_external.string().describe("The text to analyze for domain patterns")},execute:async(args2)=>{let text=(typeof args2.text==="string"?args2.text:String(args2.text)).toLowerCase(),detected=[];for(let[domain3,patterns]of Object.entries(DOMAIN_PATTERNS))for(let pattern of patterns)if(pattern.test(text)){detected.push(domain3);break}if(detected.length===0)return"No specific domains detected. The Architect should determine requirements from context.";return`Detected domains: ${detected.join(", ")}
|
|
6745
6788
|
|
|
6746
6789
|
Use these as DOMAIN values when delegating to @sme.`}});init_zod();init_config();init_constants();init_branch();import*as fs155 from"node:fs";import*as path268 from"node:path";init_branch();init_logger();var MAX_LOG_COMMITS=1e4,SWARM_TASK_SUBJECT_RE=/^swarm\(task ([^)]+)\):/;function buildIsUpstreamCommitted(directory,options){return buildIsUpstreamCommittedWithStatus(directory,options).predicate}function buildIsUpstreamCommittedWithStatus(directory,options){let max=options?.maxCommits??MAX_LOG_COMMITS,subjects;try{subjects=_internals209.readGitLogSubjects(directory,max)}catch(err){let msg=err instanceof Error?err.message:String(err);return criticalWarn(`[epic:upstream-commits] git log scan failed (degrading to permissive predicate, the activation gate may flip fail-closed): ${msg}`),{predicate:()=>!0,gitFailed:!0}}let committed=new Set;for(let line of subjects.split(`
|
|
6747
6790
|
`)){let trimmed=line.trim();if(!trimmed)continue;let match=SWARM_TASK_SUBJECT_RE.exec(trimmed);if(match)committed.add(match[1])}return{predicate:(taskId)=>committed.has(taskId),gitFailed:!1}}var _internals209={readGitLogSubjects:(cwd,max)=>{return _internals27.gitExec(["log","--no-merges",`--max-count=${max}`,"--pretty=%s"],cwd)}};init_logger();init_conflicts();function planEpicWaves(directory,phaseNumber,plan,config3,scopes,isUpstreamCommitted){let phase=plan.phases.find((p)=>p.id===phaseNumber);if(!phase)return createEmptyPlan2(phaseNumber,"");let pendingTasks=(phase.tasks??[]).filter((t)=>t.status!=="completed");if(pendingTasks.length===0)return createEmptyPlan2(phaseNumber,"");let{sortedTasks,taskMap,tasksInCycle}=runPartitionPreflight(directory,pendingTasks,config3,scopes),waves=[],serializedTasks=[],degradedTasks=[],assignedTasks=new Set,maxConcurrentPerWave=config3.max_parallel_coders;for(let taskId of tasksInCycle)serializedTasks.push(taskId),assignedTasks.add(taskId);let isSatisfied=makeDependencySatisfactionChecker(taskMap,assignedTasks,isUpstreamCommitted),waveCounter=1;while(!0){let readyTasks=getReadyTasks(sortedTasks,assignedTasks,isSatisfied);if(readyTasks.length===0)break;let waveTaskIds=[],waveFiles=[],claimedInWave=new Set;for(let classified of readyTasks){if(assignedTasks.has(classified.task.id))continue;if(classified.category==="global"){degradedTasks.push({taskId:classified.task.id,reason:"global file conflict",files:classified.files,requiredMode:"balanced"}),assignedTasks.add(classified.task.id);continue}if(classified.category==="protected"){if(config3.degrade_on_risk)degradedTasks.push({taskId:classified.task.id,reason:"protected path",files:classified.files,requiredMode:"balanced"});else serializedTasks.push(classified.task.id);assignedTasks.add(classified.task.id);continue}if(classified.category==="no-scope"||classified.category==="invalid-scope"){serializedTasks.push(classified.task.id),assignedTasks.add(classified.task.id);continue}if(classified.files.some((file3)=>Array.from(claimedInWave).some((claimed)=>pathsConflict(file3,claimed))))continue;if(waveTaskIds.length>=maxConcurrentPerWave)continue;waveTaskIds.push(classified.task.id);for(let file3 of classified.files)claimedInWave.add(file3),waveFiles.push(file3)}for(let taskId of waveTaskIds)assignedTasks.add(taskId);if(waveTaskIds.length>0)waves.push({waveId:waveCounter,taskIds:waveTaskIds,files:waveFiles}),waveCounter+=1;else{let drained=[];for(let classified of readyTasks){if(assignedTasks.has(classified.task.id))continue;serializedTasks.push(classified.task.id),assignedTasks.add(classified.task.id),drained.push(classified.task.id)}if(drained.length>0)criticalWarn(`[wave-planner] no-progress drain on phase ${phaseNumber}: ${drained.length} ready task(s) serialized because max_parallel_coders=${maxConcurrentPerWave}. Task ids: ${drained.join(", ")}.`)}}if(isUpstreamCommitted){let taskIsInWave=new Set;for(let w of waves)for(let id of w.taskIds)taskIsInWave.add(id);for(let classified of sortedTasks){if(assignedTasks.has(classified.task.id))continue;let deps=classified.task.depends??[],uncommittedCrossBatch=[],unassignedInBatch=[];for(let dep of deps)if(taskMap.has(dep)){if(!taskIsInWave.has(dep))unassignedInBatch.push(dep)}else if(!isUpstreamCommitted(dep))uncommittedCrossBatch.push(dep);let reason;if(uncommittedCrossBatch.length>0){let sample=uncommittedCrossBatch.slice(0,3).join(", "),more=uncommittedCrossBatch.length>3?`, +${uncommittedCrossBatch.length-3} more`:"";reason=`cross-batch upstream not committed (greenfield-smart Rule 3): ${sample}${more}`}else if(unassignedInBatch.length>0){let sample=unassignedInBatch.slice(0,3).join(", "),more=unassignedInBatch.length>3?`, +${unassignedInBatch.length-3} more`:"";reason=`unresolved in-batch dependency: ${sample}${more}`}else reason="planning leftover (no identifiable blocker)";degradedTasks.push({taskId:classified.task.id,reason,files:classified.files,requiredMode:"balanced"}),assignedTasks.add(classified.task.id)}}let degradationSummary;if(waves.length===0&°radedTasks.length+serializedTasks.length===pendingTasks.length){if(degradedTasks.length>0){let reasons=Array.from(new Set(degradedTasks.map((t)=>t.reason))),rule3Count=degradedTasks.filter((t)=>t.reason.includes("greenfield-smart Rule 3")).length;if(rule3Count>0&&rule3Count>=degradedTasks.length/2)degradationSummary=`All ${pendingTasks.length} tasks degraded. ${rule3Count} blocked by greenfield-smart Rule 3 — cross-batch upstream(s) not in git history. Remediation: verify Epic Mode commit-on-completion is succeeding for upstream phases, or commit those tasks manually before re-running.`;else degradationSummary=`All ${pendingTasks.length} tasks degraded. Reasons: ${reasons.join(", ")}. Consider running in standard (serial) mode.`}else if(serializedTasks.length===pendingTasks.length&&maxConcurrentPerWave<=0)degradationSummary=`All ${pendingTasks.length} tasks serialized because max_parallel_coders=${maxConcurrentPerWave}. Raise it to ≥1 (or use the standard serial flow) to dispatch.`;else if(serializedTasks.length===pendingTasks.length)degradationSummary=`All ${pendingTasks.length} tasks serialized (no parallel waves emitted). Likely cause: missing/empty scopes or a dependency cycle. Check declared scopes and the dependency graph.`}let totalConcurrentTasks=waves.reduce((sum,w)=>sum+w.taskIds.length,0),planId=`epic-waves-${phaseNumber}-${Date.now()}`;return{phase:phaseNumber,planId,waves,serializedTasks,degradedTasks,degradationSummary,totalPendingTasks:pendingTasks.length,totalConcurrentTasks}}function createEmptyPlan2(phaseNumber,planId){return{phase:phaseNumber,planId,waves:[],serializedTasks:[],degradedTasks:[],totalPendingTasks:0,totalConcurrentTasks:0}}init_conflicts();init_logger();init_create_tool();function readPlanJson(directory){let planPath=path268.join(directory,".swarm","plan.json");if(!fs155.existsSync(planPath))return null;try{return JSON.parse(fs155.readFileSync(planPath,"utf-8"))}catch{return null}}async function executeEpicPlanWaves(args2){let{directory,phase,scopes}=args2,plan=_internals210.readPlanJson(directory);if(!plan)return{success:!1,reason:"no-plan",errors:["plan.json not found or unparseable in .swarm directory. Run `/swarm specify` to bootstrap a plan, then retry."]};if(!Array.isArray(plan.phases))return{success:!1,reason:"no-plan",errors:["plan.json `phases` is not an array. The plan file may be corrupt or hand-edited; restore from a known-good version or re-run `/swarm specify`."]};let phaseObj=plan.phases.find((p)=>p.id===phase);if(!phaseObj){let availablePhases=plan.phases.map((p)=>p.id).join(", ");return{success:!1,reason:"no-phase",errors:[`Phase ${phase} not found in plan.json. Available phases: ${availablePhases||"(none)"}. Re-invoke \`epic_plan_waves\` with a valid phase number.`]}}let tasksArray=Array.isArray(phaseObj.tasks)?phaseObj.tasks:[];if(tasksArray.length===0)return{success:!1,reason:"phase-empty",errors:[`Phase ${phase} exists in plan.json but has zero tasks defined. Either populate this phase with tasks (declared scopes, depends, acceptance) and re-invoke, or remove the empty phase from plan.json and advance.`]};let pendingTasks=tasksArray.filter((t)=>t.status!=="completed");if(pendingTasks.length===0)return{success:!1,reason:"phase-already-complete",errors:[`Phase ${phase} has no pending tasks — every task is already completed. `+'Advance to the next phase, or set tasks back to "pending" if you intend to re-run.']};try{let tasksMissingScope=[];for(let task2 of pendingTasks){let declaredScope=_internals210.readTaskScopes(directory,task2.id),filesTouched=task2.files_touched??[],providedScope=scopes&&task2.id in scopes?scopes[task2.id]:null;if((declaredScope===null||declaredScope.length===0)&&filesTouched.length===0&&(providedScope===null||providedScope.length===0))tasksMissingScope.push(task2.id)}if(tasksMissingScope.length>0){let list=tasksMissingScope.join(", ");return{success:!1,reason:"scopes-missing",missingScopes:tasksMissingScope,errors:[`Cannot plan waves for phase ${phase}: ${tasksMissingScope.length} pending task(s) have no declared scope and no files_touched in plan.json. The wave planner needs scope data to compute disjoint concurrent groups; without it the dispatch is silently serial and Epic Mode's parallelization is lost.
|