opencode-swarm 7.193.0 → 7.194.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/README.md +1 -1
- package/binaries/win32-arm64/swarm-sandbox-runner.exe +0 -0
- package/binaries/win32-x64/swarm-sandbox-runner.exe +0 -0
- package/dist/background/pending-delegations.d.ts +8 -0
- package/dist/cli/{auto-checkpoint-taay16xe.js → auto-checkpoint-67dk8rjz.js} +5 -5
- package/dist/cli/{checkpoint-6229g3jq.js → checkpoint-jbqqyp5e.js} +9 -9
- package/dist/cli/{coder-settlement-hexmmefv.js → coder-settlement-a09t7mvx.js} +4 -4
- package/dist/cli/{config-doctor-3ghvthh5.js → config-doctor-dkp263xx.js} +8 -8
- package/dist/cli/{core-0k7t9fw0.js → core-stnmz1rg.js} +2 -2
- package/dist/cli/{curator-drift-a5142x0d.js → curator-drift-d1wedyed.js} +6 -6
- package/dist/cli/{curator-llm-factory-8gt3mvg9.js → curator-llm-factory-97dpqjz4.js} +26 -26
- package/dist/cli/{curator-kwwnkyr7.js → curator-mc0wcpvw.js} +26 -26
- package/dist/cli/{doctor-knowledge-receipt-phase-id-11nsf9tz.js → doctor-knowledge-receipt-phase-id-dfwx5jha.js} +5 -5
- package/dist/cli/{evidence-summary-service-y2ykc6ta.js → evidence-summary-service-k1shqefr.js} +10 -10
- package/dist/cli/{gate-evidence-cd5299js.js → gate-evidence-vw9y4gs6.js} +3 -3
- package/dist/cli/{guardrail-explain-hpgecr7x.js → guardrail-explain-24g3bsqw.js} +27 -27
- package/dist/cli/{guardrail-log-g6krx0s2.js → guardrail-log-vbeyx6nq.js} +4 -4
- package/dist/cli/{guardrail-reset-a3xv675m.js → guardrail-reset-jwtt15e3.js} +26 -26
- package/dist/cli/{hive-promoter-90svfzvs.js → hive-promoter-p9ad63mx.js} +26 -26
- package/dist/cli/{index-ngk8hpc3.js → index-0xe19j9g.js} +1 -1
- package/dist/cli/{index-py8wpe81.js → index-1jt12p3y.js} +1 -1
- package/dist/cli/{index-jxs9qnad.js → index-3dpb3kps.js} +1 -1
- package/dist/cli/{index-cs0p582p.js → index-43v5axvm.js} +2 -2
- package/dist/cli/{index-ma71x1aa.js → index-48h1yn6c.js} +1 -1
- package/dist/cli/{index-1dx5zyss.js → index-4ftg3p9n.js} +2 -2
- package/dist/cli/{index-bkpyff61.js → index-51dxek4p.js} +2 -2
- package/dist/cli/{index-bgtfvst1.js → index-6xppb1er.js} +1 -1
- package/dist/cli/{index-vbp35frb.js → index-7bfshvq1.js} +3 -3
- package/dist/cli/{index-r3mffz78.js → index-9bzgea2y.js} +3 -3
- package/dist/cli/{index-cpt38e0e.js → index-9kbnxb7v.js} +2 -2
- package/dist/cli/{index-he2nyr7x.js → index-9v43y7y6.js} +5 -5
- package/dist/cli/{index-tr47q89d.js → index-ajkdt5b8.js} +2 -2
- package/dist/cli/{index-5ev6f1gj.js → index-at34nry4.js} +2 -2
- package/dist/cli/{index-bg19b84s.js → index-cwr69qw7.js} +4 -4
- package/dist/cli/{index-x2phyvcv.js → index-d7pznffh.js} +2 -2
- package/dist/cli/{index-6dn16dre.js → index-dy7nztyp.js} +2 -2
- package/dist/cli/{index-4mq8r4be.js → index-ehab3z5y.js} +4 -4
- package/dist/cli/{index-4gacy6y6.js → index-f3ttgqak.js} +1 -1
- package/dist/cli/{index-rd9th57y.js → index-h14wpwpa.js} +4 -4
- package/dist/cli/{index-nz6ehpjn.js → index-jrs2qh6j.js} +1 -1
- package/dist/cli/{index-3xj89bf0.js → index-kp5qw5p4.js} +28 -28
- package/dist/cli/{index-ymnathfr.js → index-n5xwza76.js} +3 -3
- package/dist/cli/{index-1p24bfn2.js → index-r8mavcg6.js} +1 -1
- package/dist/cli/{index-5n760fzn.js → index-rpnkp79f.js} +6 -6
- package/dist/cli/{index-ntmnse4d.js → index-t6aae9wq.js} +1 -1
- package/dist/cli/{index-prvancd0.js → index-vfdkvvkf.js} +1 -1
- package/dist/cli/{index-jx80ed6g.js → index-vjytfp05.js} +90 -66
- package/dist/cli/{index-db786kn6.js → index-x7qeaa9y.js} +26 -26
- package/dist/cli/{index-d2emv8ap.js → index-y3n9ry9q.js} +1 -1
- package/dist/cli/{index-nktwf2xm.js → index-yfbk69b1.js} +3 -3
- package/dist/cli/index.js +27 -27
- package/dist/cli/{knowledge-escalator-2d7g3hs0.js → knowledge-escalator-g6dctrae.js} +8 -8
- package/dist/cli/{knowledge-events-hjeaevc9.js → knowledge-events-acdz0x2g.js} +6 -6
- package/dist/cli/{knowledge-store-g9cb2m0v.js → knowledge-store-vxtj4m59.js} +1 -1
- package/dist/cli/{knowledge-validator-dghf9pcj.js → knowledge-validator-b545vc9t.js} +2 -2
- package/dist/cli/{mcp-f5myvd7r.js → mcp-c3t18313.js} +1 -1
- package/dist/cli/{model-preflight-4w4wd6dj.js → model-preflight-r99c08re.js} +26 -26
- package/dist/cli/{pending-delegations-adm6gf3n.js → pending-delegations-57f3049j.js} +4 -2
- package/dist/cli/{pr-subscriptions-n1hks854.js → pr-subscriptions-5jb793xe.js} +1 -1
- package/dist/cli/{pr-workflow-gate-59cr6gve.js → pr-workflow-gate-n3x25ddw.js} +28 -26
- package/dist/cli/{scan-cursor-t26xmfhd.js → scan-cursor-s9mazw82.js} +2 -2
- package/dist/cli/{schema-cr120ar5.js → schema-7czxpvwm.js} +2 -2
- package/dist/cli/{scope-persistence-mrnz8j43.js → scope-persistence-y0ebqyjm.js} +6 -6
- package/dist/cli/{server-mwk6zn83.js → server-m10e78ey.js} +26 -26
- package/dist/cli/{skill-generator-svs4k0g8.js → skill-generator-kzw1dcba.js} +9 -9
- package/dist/cli/{snapshot-coordination-init-xzrahhsb.js → snapshot-coordination-init-z1aqsvn4.js} +26 -26
- package/dist/cli/{speckit-checkoff-g2qrb1tn.js → speckit-checkoff-1g3vzywn.js} +4 -4
- package/dist/cli/{worktree-collision-ownership-d145wmpg.js → worktree-collision-ownership-d0etv08a.js} +2 -2
- package/dist/cli/{worktree-isolation-pt1rws6p.js → worktree-isolation-dj2qw13p.js} +26 -26
- package/dist/commands/registry.d.ts +1 -1
- package/dist/epic/start.d.ts +8 -5
- package/dist/hooks/pr-workflow-gate.d.ts +37 -0
- package/dist/host/v2/session-client.d.ts +77 -0
- package/dist/host/v2/types.d.ts +7 -5
- package/dist/index.js +13 -11
- package/dist/tools/pr-workflow-status.d.ts +24 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{createRequire}from"node:module";var __create=Object.create;var{getPrototypeOf:__getProtoOf,defineProperty:__defProp,getOwnPropertyNames:__getOwnPropNames,getOwnPropertyDescriptor:__getOwnPropDesc}=Object,__hasOwnProp=Object.prototype.hasOwnProperty;function __accessProp(key){return this[key]}var __toESMCache_node,__toESMCache_esm,__toESM=(mod,isNodeMode,target)=>{var canCache=mod!=null&&typeof mod==="object";if(canCache){var cache=isNodeMode?__toESMCache_node??=new WeakMap:__toESMCache_esm??=new WeakMap,cached=cache.get(mod);if(cached)return cached}target=mod!=null?__create(__getProtoOf(mod)):{};let to=isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target;for(let key of __getOwnPropNames(mod))if(!__hasOwnProp.call(to,key))__defProp(to,key,{get:__accessProp.bind(mod,key),enumerable:!0});if(canCache)cache.set(mod,to);return to},__toCommonJS=(from)=>{var entry=(__moduleCache??=new WeakMap).get(from),desc;if(entry)return entry;if(entry=__defProp({},"__esModule",{value:!0}),from&&typeof from==="object"||typeof from==="function"){for(var key of __getOwnPropNames(from))if(!__hasOwnProp.call(entry,key))__defProp(entry,key,{get:__accessProp.bind(from,key),enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return __moduleCache.set(from,entry),entry},__moduleCache,__commonJS=(cb,mod)=>()=>(mod||cb((mod={exports:{}}).exports,mod),mod.exports);var __returnValue=(v)=>v;function __exportSetter(name,newValue){this[name]=__returnValue.bind(null,newValue)}var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0,configurable:!0,set:__exportSetter.bind(all,name)})};var __esm=(fn2,res)=>()=>(fn2&&(res=fn2(fn2=0)),res);var __require=createRequire(import.meta.url);var package_default;var init_package=__esm(()=>{package_default={name:"opencode-swarm",version:"7.193.0",description:"Architect-centric agentic swarm plugin for OpenCode - hub-and-spoke orchestration with SME consultation, code generation, and QA review",main:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",default:"./dist/index.js"},"./package.json":"./package.json"},bin:{"opencode-swarm":"./dist/cli/index.js"},type:"module",engines:{bun:">=1.3.13",node:">=22.13"},license:"MIT",repository:{type:"git",url:"https://github.com/ZaxbyHub/opencode-swarm.git"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},keywords:["opencode","opencode-plugin","ai","agents","orchestration","swarm","multi-agent","llm"],files:["dist","dist/lang/grammars","binaries","evaluation-fixtures",".opencode/skills/brainstorm",".opencode/skills/specify",".opencode/skills/clarify-spec",".opencode/skills/swarm-resume",".opencode/skills/clarify",".opencode/skills/discover",".opencode/skills/consult",".opencode/skills/pre-phase-briefing",".opencode/skills/council",".opencode/skills/deep-dive",".opencode/skills/deep-research",".opencode/skills/codebase-review-swarm",".opencode/skills/swarm-implement",".opencode/skills/design-docs",".opencode/skills/swarm-pr-review",".opencode/skills/swarm",".opencode/skills/swarm-pr-feedback",".opencode/skills/swarm-pr-subscribe",".opencode/skills/swarm-ci-monitor",".opencode/skills/issue-ingest",".opencode/skills/swarm-plan",".opencode/skills/critic-gate",".opencode/skills/execute",".opencode/skills/phase-wrap",".opencode/skills/loop",".opencode/skills/writing-tests",".opencode/skills/running-tests",".opencode/skills/engineering-conventions",".opencode/skills/commit-pr",".opencode/skills/ci-failure-batching",".opencode/skills/gate-attribution",".opencode/skills/merge-queue-readiness",".opencode/skills/skill-edit-validation",".opencode/skills/worktree-retry-cleanup",".opencode/skills/test-file-split",".opencode/skills/fork-pr-operations",".opencode/skills/parallel-work-check",".opencode/skills/ci-fix-monitor",".opencode/skills/issue-tracer",".opencode/skills/orchestrating-subagents",".opencode/skills/durable-session-state","tests/fixtures/memory-recall","tests/fixtures/memory-recall-heldout","opencode-swarm.schema.json","README.md","LICENSE"],scripts:{clean:`bun -e "require('fs').rmSync('dist',{recursive:true,force:true})"`,build:"bun run clean && bun run scripts/generate-config-schema.ts && bun run scripts/copy-grammars.ts && bun build src/index.ts --outdir dist --target node --format esm --external web-tree-sitter --minify-whitespace --minify-syntax && bun build src/cli/index.ts --outdir dist/cli --target bun --format esm --external bash-parser --splitting && bun run scripts/copy-grammars.ts --to-dist && tsc --emitDeclarationOnly",typecheck:"tsc --noEmit",test:"bun test",lint:"biome lint .","lint:ci":"biome ci .","test:unit:ci":"bun scripts/ci/run-unit-tests-local.ts","validate:repo":"bun scripts/ci/repository-validation.ts","drift:check":"bun run scripts/drift-check.ts","check:pre-push":"bun run scripts/drift-check.ts --enforce --no-report && bun run check:registry-citations","schema:generate":"bun run scripts/generate-config-schema.ts","generate:commands-docs":"bun run scripts/generate-commands-docs.ts","check:runtime-src-refs":"bun run scripts/check-runtime-src-refs.ts","drift:fix":"bun run scripts/drift-check.ts --fix --confirm","skills:sync":"bun run scripts/sync-qa-gate-skills.ts",format:"biome format . --write",check:"biome check --write .",dev:"bun run build && opencode","package:smoke":"node scripts/package-smoke.mjs",prepare:"bun run build","repro:704":"node scripts/repro-704.mjs","repro:2669":"node scripts/repro-2669.mjs","repro:2670":"node scripts/repro-2670.mjs","repro:1144":"bun scripts/repro-1144.mjs","repro:1873":"bun build scripts/repro-1873-entry.ts --outdir dist-build-test/repro-1873 --target node --format esm && node scripts/repro-1873.mjs","repro:2487":"bun build scripts/repro-2487-parity-entry.ts --outdir dist-build-test/repro-2487 --target node --format esm && node scripts/repro-2487-parity.mjs","check:events":"bun run scripts/check-event-contract.ts","check:retention":"bun run scripts/check-retention-registry.ts","check:core-events":"bun run scripts/check-core-events-usage.ts","check:shell-audit":"bun run scripts/check-shell-audit-usage.ts","check:trajectory-store":"bun run scripts/check-trajectory-store-usage.ts","check:mock-cleanup":"bun run scripts/check-mock-cleanup.ts","check:invariants":"bun run scripts/check-invariants.ts","check:token-formula":"bun run scripts/check-token-formula.ts","check:cross-contamination":"bun run scripts/check-cross-contamination.ts","check:test-clock":"bun run scripts/check-test-clock.ts","check:test-file-cap":"bun run scripts/check-test-file-cap.ts","check:test-tmpdir":"bun run scripts/check-test-tmpdir.ts","check:bash-portability":"bun run scripts/check-bash-portability.ts","check:pending-fragment":"bun run scripts/check-pending-fragment.ts","check:gate-portability":"bun run scripts/check-gate-portability.ts","check:bare-spawn":"bun run scripts/check-bare-executable-spawn.ts","check:error-channel-discard":"bun run scripts/check-error-channel-discard.ts","check:path-identity":"bun run scripts/check-path-identity.ts","check:registry-citations":"bun run scripts/check-registry-citations.ts","check:memory-recall":"bun run scripts/memory-recall-regression.ts","check:retrieval-quality":"bun run scripts/retrieval-quality-regression.ts"},dependencies:{"@modelcontextprotocol/sdk":"^1.30.0","@opencode-ai/plugin":"^1.18.3","@opencode-ai/sdk":"^1.18.3","@vscode/tree-sitter-wasm":"^0.3.0","bash-parser":"^0.5.0","p-limit":"^7.3.0",picomatch:"^4.0.4","proper-lockfile":"^4.1.2","quick-lru":"^7.3.0","web-tree-sitter":"^0.25.0",zod:"4.3.6"},devDependencies:{"@biomejs/biome":"2.3.14","@types/picomatch":"^4.0.3","bun-types":"1.3.8","js-yaml":"^4.1.1",typescript:"^5.7.3"},peerDependencies:{"@xenova/transformers":"^2.17.2"},peerDependenciesMeta:{"@xenova/transformers":{optional:!0}}}});var QA_AGENTS,PIPELINE_AGENTS,ORCHESTRATOR_NAME="architect",ALL_SUBAGENT_NAMES,ALL_AGENT_NAMES;var init_agent_names=__esm(()=>{QA_AGENTS=["reviewer","critic","critic_oversight","critic_finding_validator"],PIPELINE_AGENTS=["explorer","coder","test_engineer"],ALL_SUBAGENT_NAMES=["sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","curator_postmortem","curator_consolidation","council_generalist","council_skeptic","council_domain_expert","skill_improver","spec_writer",...QA_AGENTS,...PIPELINE_AGENTS],ALL_AGENT_NAMES=["architect",...ALL_SUBAGENT_NAMES]});function getPrWorkflowToolCapability(toolName,mode){let metadata=TOOL_METADATA[toolName];if(!metadata?.prWorkflow?.modes.includes(mode))return null;return metadata.prWorkflow.capability}var TOOL_METADATA,TOOL_NAMES,TOOL_NAME_SET,TOOL_DESCRIPTIONS,AGENT_TOOL_MAP;var init_tool_metadata=__esm(()=>{init_agent_names();TOOL_METADATA={diff:{description:"structured git diff with contract change detection",agents:["architect","reviewer","critic_finding_validator","critic_oversight","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},diff_summary:{description:"filter classified AST changes by category, risk level, or file for reviewer drill-down",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},syntax_check:{description:"check syntax of source files using tree-sitter parsers across multiple languages, returning per-file errors",agents:["architect","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},placeholder_scan:{description:"todo and FIXME comment detection",agents:["architect","reviewer","critic_finding_validator"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},imports:{description:"find all consumers that import from a given file — use before refactoring shared modules to avoid breaking unseen dependents",agents:["architect","sme","researcher","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},lint:{description:"run project linter in check or fix mode; supports biome, eslint, ruff, clippy, and more, returns structured results",agents:["architect","reviewer","critic_finding_validator","coder"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},secretscan:{description:"scan for secrets (API keys, tokens, passwords) via regex and entropy; returns redacted previews, excludes common dirs",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},sast_scan:{description:"static analysis security scan",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},build_check:{description:"discover and run build, typecheck, and test commands for various project ecosystems in the working directory",agents:["architect","coder","test_engineer"]},pre_check_batch:{description:"parallel verification: lint:check + secretscan + sast_scan + quality_budget",agents:["architect","reviewer","critic_finding_validator"]},quality_budget:{description:"code quality budget check",agents:["architect"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},symbols:{description:"extract exported symbols (functions, classes, interfaces, types) from source files; supports TypeScript, JavaScript, Python, Rust, Go, Dart, Ruby, PHP, and Java",agents:["architect","sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},complexity_hotspots:{description:"git churn × complexity risk map",agents:["architect","sme","researcher","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","critic_oversight","explorer","test_engineer"]},schema_drift:{description:"OpenAPI spec vs route drift",agents:["architect","sme","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},todo_extract:{description:"structured TODO/FIXME extraction; with task_id, records the high-priority count as todo_scan gate evidence",agents:["architect","researcher","docs","explorer","coder"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},evidence_check:{description:"verify task evidence completeness",agents:["architect","critic_oversight"]},check_gate_status:{description:"check the gate status of a specific task",agents:["architect","critic_oversight"]},completion_verify:{description:"verify completed tasks have required evidence",agents:["architect","critic_oversight"]},complete_pr_workflow:{description:"validate terminal PR workflow evidence and clear its durable session gate",agents:["architect"]},abort_pr_workflow:{description:"abort an unrecoverable PR_REVIEW/PR_FEEDBACK mechanical gate and clear its durable session state",agents:["architect"]},authorize_pr_review_reentry:{description:"issue a one-use, identity-bound reviewer/test_engineer re-entry authorization for the active PR_REVIEW workflow (issue #2383)",agents:["architect"]},submit_pr_review_result:{description:"submit one child-bound typed result for an active PR-review base or micro discovery lane",agents:[],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},approve_plan_critic:{description:"record a MANUAL plan_critic_gate approval snapshot to unblock the ratchet-tighter critic_pre_plan execution gate when the critic already returned APPROVED but the mechanical recorder failed to persist it (issue #2012), or as the sanctioned recovery for a bookkeeping-grade hashed-field repair under the critic-gate PLAN FREEZE rule (the reason must state which case applies)",agents:["architect"]},approve_retry_sounding_board:{description:"record a MANUAL critic_sounding_board gate entry to unblock the coder retry circuit-breaker gate when the sounding board returned APPROVED but the mechanical recorder missed it (issue #2703)",agents:["architect"]},recover_rework_task:{description:"recover a task wedged at rework_required when the reviewer/test_engineer verdict did not require a code change: write a supervised stage_a_passed so those gates can be re-dispatched without re-running the coder (issue #2755)",agents:["architect"]},recover_stage_a_task:{description:"recover a task wedged in the settlement-backed Stage A deadlock — workflow at idle/blocked while a COMMITTED accepted coder settlement and green post-settlement pre-check proof justify Stage A: write a settlement-backed stage_a_passed so reviewer/test_engineer can be dispatched, without re-running the coder (issue #2828)",agents:["architect"]},prepare_pr_workflow_checkout:{description:"prepare an auditable PR workflow checkout or restore its exact original branch/HEAD and preserved stash after terminal cleanup",agents:["architect"]},invalidate_pr_feedback_publication:{description:"invalidate the armed PR_FEEDBACK publication generation so approved content can change, superseding every content-dependent approval and reopening the exact scoped rework + fresh-review path (issue #2108)",agents:["architect"]},record_implementation_review:{description:"record fresh-context reviewer + critic APPROVE verdicts for the implementation diff so the /swarm issue --trace workflow can satisfy its review gate before commit-pr handoff",agents:["architect"]},record_issue_publication:{description:"record a publication receipt so the /swarm issue --trace workflow reaches its terminal published state after the PR is created/updated",agents:["architect"]},record_issue_reproduction:{description:"record the reproduction outcome for the current traced issue so the /swarm issue --trace workflow can satisfy its reproduction gate and transition to PLAN",agents:["architect"]},record_recurrence_sweep:{description:"record the recurrence sweep (defect class, predicates, hit dispositions, guardrail proof, related-problems results) so the /swarm issue --trace workflow can satisfy its recurrence gate before commit-pr handoff",agents:["architect"]},record_branch_freshness:{description:"record the Phase 0 branch-freshness outcome (synced / behind:<n> / fetch-failed:<reason> plus optional user override) so the /swarm issue --trace workflow can pass its freshness gate before transitioning to PLAN (issue #2564)",agents:["architect"]},record_trace_validation:{description:"record one per-phase trace-check.sh validator outcome (phase, pass/fail, reviewedCommit, treeId) so the /swarm issue --trace workflow can satisfy its validator-receipt gate before commit-pr handoff (issue #2564)",agents:["architect"]},record_merge_approval:{description:"record the human merge approval bound to the exact PR head SHA so the /swarm issue --trace workflow reaches its terminal merge_approval_recorded state — recorded for audit only, never certified or driven by the plugin (issue #2564)",agents:["architect"]},rebind_pr_feedback_head:{description:"rebind a PR_FEEDBACK workflow to a new verified remote PR head after merge/rebase/conflict repair, invalidating ancestry-bound receipts so the mechanical ladder re-runs",agents:["architect"]},run_pr_feedback_stage_a:{description:"execute and persist mandatory PR-feedback Stage A checks on a content-bound revision",agents:["architect"]},submit_council_verdicts:{description:"submit pre-collected council member verdicts for synthesis (architect MUST dispatch critic/reviewer/sme/test_engineer/explorer as Agent tasks first; this tool synthesizes only, it does not contact members)",agents:[]},submit_phase_council_verdicts:{description:"submit pre-collected phase-level council member verdicts for holistic phase synthesis (architect MUST dispatch all 5 council members with phase-scoped context first; this tool synthesizes only, it does not contact members)",agents:[]},declare_council_criteria:{description:"pre-declare acceptance criteria for a task before the coder starts work; criteria are read back during council evaluation",agents:[]},sbom_generate:{description:"SBOM generation for dependency inventory",agents:["architect"]},checkpoint:{description:"create named git checkpoints for save, restore, and delete — use before risky operations to enable rollback; a destructive restore previews first and requires the confirm_token issued in the preview (#2946)",agents:["architect"]},pkg_audit:{description:"dependency vulnerability scan — npm/pip/cargo",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},parse_lane_candidates:{description:"Parse [CANDIDATE] rows from a dispatch_lanes or collect_lane_results artifact (by output_ref), produce structured records with provenance, optionally persist to a per-batch sidecar JSONL. Pure-parser variant exists as internal module.",agents:["architect"]},plan_conflict_check:{description:"read-only advisory check (#1656): compute a pairwise file-conflict matrix for N proposed parallel task groups using declared scopes and optional git co-change; returns a verdict (all_disjoint / conflicts_present / unknown_scopes), per-pair evidence, and a suggested serialization order. Writes nothing — the execution gate independently recomputes the verdict inline at dispatch time via the same helper. Call BEFORE attempting parallel dispatch to confirm disjointness.",agents:["architect"]},write_pr_review_trigger_eval:{description:"persist the complete PR-review trigger evaluation with exact-set validation, dispatch provenance, and live merge-base verification",agents:["architect"]},write_pr_review_artifact:{description:"persist schema-validated PR-review findings checkpoints and exact actionable feedback handoffs under the active run",agents:["architect"]},pr_review_submission:{description:"submit a settled, head-bound PR review to GitHub through the gh PR Review API after the PR_REVIEW gate clears; architect-only, refuses while a gate is active or the run was aborted after settlement",agents:["architect"]},export_pr_review_partial_results:{description:"export the validated partial results of an ABORTED PR_REVIEW run as a partial, non-authoritative artifact bound per-item to receipt-authenticated findings; architect-only, requires the gate cleared and an abort event binding session and head, never implies completion or feedback consent",agents:["architect"]},prepare_pr_feedback_scope:{description:"prepare an exact file scope for one PR-feedback coder Task after immutable feedback verification settles",agents:["architect"]},test_runner:{description:"auto-detect and run tests",agents:["architect","reviewer","critic_finding_validator","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},test_impact:{description:"identify test files impacted by changed source files via import analysis",agents:["architect","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},mutation_test:{description:"executes pre-generated mutation patches against tests, evaluates kill rate against quality gate thresholds; test selection comes from explicit files (override) or source_files derived via the impact analyzer with a typed bounded fallback",agents:["architect","test_engineer"]},generate_mutants:{description:"generate LLM-based mutation testing patches for source files; returns MutationPatch[] for direct consumption by the mutation_test tool",agents:["architect"]},detect_domains:{description:"detect which SME domains are relevant for a given text",agents:["architect","sme","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic","critic_oversight","explorer"]},git_blame:{description:"per-line git blame metadata: sha, author, date, summary for each line in a file",agents:["reviewer","critic_finding_validator","explorer","architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},gitingest:{description:"fetch a GitHub repository full content via gitingest.com",agents:["architect","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_summary:{description:"retrieve the full content of a stored tool output summary",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_lane_output:{description:"retrieve paged full dispatch lane output by output_ref; use before consuming truncated lane previews or routing candidates from lane results",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},extract_code_blocks:{description:"extract code blocks from text content and save them to files",agents:["docs","docs_design","designer","spec_writer","coder","test_engineer"]},phase_complete:{description:"preflight every applicable phase gate, report all blockers, and atomically commit a current passing snapshot",agents:["architect"]},run_phase_review:{description:"run the bounded phase-final review engine and persist complete content-addressed review evidence",agents:["architect"]},repair_gate_evidence:{description:"quarantine recoverable exact-task gate evidence, rebuild from durable requirements, recover receipt-backed legacy marker wedges or the exact sentinel-only historical reset, and refuse every other receipt-less reconstruction",agents:["architect"]},repair_knowledge_receipt_ledger:{description:"validate or repair authoritative knowledge receipts, preserve corrupt authority in bounded quarantine, require scoped re-evaluation, and backfill stable phase ids across the whole ledger (operation backfill_phase_id; phase/session_id do not scope the backfill)",agents:["architect"]},record_directive_override:{description:"record an audited architect override for identified critical-directive violations without bypassing unreadable authority",agents:["architect"]},save_plan:{description:"save a structured implementation plan",agents:["architect"]},update_task_status:{description:"mark tasks complete, track phase progress",agents:["architect"]},lint_spec:{description:"validate .swarm/spec.md format and required fields",agents:["architect","spec_writer"]},write_retro:{description:"document phase retrospectives via phase_complete workflow, capture lessons learned",agents:["architect"]},write_drift_evidence:{description:"write drift verification evidence for a completed phase",agents:["architect"]},write_hallucination_evidence:{description:"write hallucination verification evidence for a completed phase",agents:["architect"]},write_mutation_evidence:{description:"write mutation gate evidence for a completed phase; normalizes PASS/WARN/FAIL/SKIP verdicts and writes .swarm/evidence/{phase}/mutation-gate.json",agents:["architect"]},declare_scope:{description:"declare file scope for next coder delegation",agents:["architect"]},scope_validate:{description:"validate shell writes against an inline file scope",agents:["architect"]},knowledge_query:{description:"query swarm or hive knowledge with optional filters",agents:["architect","skill_improver","spec_writer"]},doc_scan:{description:"scan project documentation files and build an index manifest",agents:["architect","docs_design","skill_improver","spec_writer","explorer"]},doc_extract:{description:"extract actionable constraints from project documentation",agents:["architect","docs_design","skill_improver","spec_writer"]},curator_analyze:{description:"run curator phase analysis and optionally apply knowledge recommendations",agents:["architect"]},consensus_mine:{description:"mine cross-run consensus from existing .swarm evidence into an immutable proposals-only report; also deletes its own reports past consensus.report_retention, appends to the shared recommendation dedup ledger (in the shared cohort root, outside this project, when a knowledge link is active), and mirrors proposals into pending swarm-memory proposals when memory is enabled",agents:["architect","curator_phase","curator_postmortem"]},knowledge_add:{description:"store a new lesson in the knowledge base",agents:["architect","coder"]},knowledge_recall:{description:"search the knowledge base for relevant past decisions",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"]},knowledge_remove:{description:"delete an outdated swarm knowledge entry by ID (swarm tier only)",agents:["architect"]},co_change_analyzer:{description:"detect hidden couplings by analyzing git history",agents:["architect"]},context_status:{description:"report current context-window headroom for the active session — returns tokens-used, usageSource (provider|estimated), model-limit with provenance (modelLimitSource: host|override|provider_cap|native|fallback; modelLimitResolution: user_provider_model|user_model|user_default|live_model_limit|static_provider_cap|static_native|static_default; fallbackActive: true when the denominator came from a static table or the flat 128k default — treat headroom as uncertain), usage-percent, threshold-state (none/warn/critical), model name, and provider. Pure read-only: no state mutation, no warning injection. Works whether context_budget.enabled is true or false.",agents:["architect"]},search:{description:"Workspace-scoped ripgrep-style text search with structured JSON output. Supports literal and regex modes, glob filtering, and result limits. NOTE: This is text search, not structural AST search — use symbols and imports tools for structural queries.",agents:["architect","sme","docs","docs_design","designer","critic_hallucination_verifier","skill_improver","spec_writer","reviewer","critic_finding_validator","critic_oversight","explorer","coder","test_engineer","researcher"]},ast_grep:{description:"Read-only structural AST search using ast-grep patterns with optional language and glob filters. Use for syntax-aware code pattern searches; does not rewrite files.",agents:["architect","sme","docs","docs_design","critic_hallucination_verifier","spec_writer","explorer","coder","test_engineer","researcher"]},actionlint_scan:{description:"Run actionlint against GitHub Actions workflow YAML files with structured findings. Resolves actionlint lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},osv_scan:{description:"Run OSV-Scanner against a workspace path and return structured dependency vulnerability findings. Resolves osv-scanner lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},gh_evidence:{description:"Fetch bounded GitHub pull request or issue metadata through gh for review and CI evidence. Resolves gh lazily and is read-only.",agents:["architect","researcher"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},pr_workflow_status:{description:"Read-only architect observation of local git state (HEAD, branch, clean/dirty with a bounded changed-file list, remotes) plus a session-pinned PR workflow gate summary and the PR_FEEDBACK publication-generation section (state, attempts, invalidation reason, recovery guidance). Use to observe state under the fail-closed PR_REVIEW/PR_FEEDBACK gate. Never executes PR-controlled scripts and never reads another session gate.",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},batch_symbols:{description:"Batched symbol extraction across multiple files. Returns per-file symbol summaries with isolated error handling.",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","explorer"]},suggest_patch:{description:"Reviewer-safe structured patch suggestion tool. Produces context-anchored patch artifacts without file modification. Returns structured diagnostics on context mismatch.",agents:["architect","reviewer","critic_finding_validator"]},req_coverage:{description:"query requirement coverage status for tracked functional requirements",agents:["critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","critic","critic_oversight"]},get_approved_plan:{description:"retrieve the last critic-approved immutable plan snapshot for baseline drift comparison",agents:["critic_drift_verifier","critic","critic_oversight"]},repo_map:{description:"query the repo code graph: importers, dependencies, blast radius, localization, ontology facts, package boundaries, and heuristic preflight packets before refactoring; ontology findings are advisory, not formal proofs",agents:["architect","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},get_qa_gate_profile:{description:"retrieve the QA gate profile for the current or exact future plan identity: gates (reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council), lock state, profile hash, the calling session’s ratchet-tighter overrides, and the EFFECTIVE gates (profile merged with those overrides; durable across restart). Read-only and never creates state.",agents:["architect"]},set_qa_gates:{description:"configure the QA gate profile for the current plan or bootstrap an exact future plan with swarm_id and plan_title. Architect-only. The initial selection may set explicit true/false values over defaults; later changes are ratchet-tighter and rejected once locked after critic approval. Supports: reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council, plus adopt_legacy_binding_only for exact-binding recovery without mutating gates.",agents:["architect"]},web_search:{description:"External web search (Tavily or Brave) for architect-driven council research, SME domain research, researcher auto-research, and skill-improver research. Returns titled results with snippets, URLs, normalized query metadata, temporal intent, freshness, and removed stale years. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides. Requires a search API key. Used by the architect in MODE: COUNCIL to gather a RESEARCH CONTEXT before dispatching council agents, by SME for opt-in external skill/source evaluation, and by the researcher agent for multi-source auto-research.",agents:["sme","researcher","skill_improver"]},web_fetch:{description:"Fetch the readable text of a single http(s) URL (architect-only). Returns decoded page text, document title, final URL after redirects, and an evidence reference. Reads primary sources that web_search only surfaces as snippets. Config-gated on council.general.enabled. Blocks private/loopback/link-local/metadata addresses (re-validated and re-pinned across redirects); enforces timeout and body size cap.",agents:[]},convene_general_council:{description:"Synthesize responses from a multi-model General Council. Accepts parallel member responses (Round 1, optionally Round 2), detects disagreements, and returns consensus points, persisting disagreements, and a structured synthesis. Architect-only. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides.",agents:[]},write_final_council_evidence:{description:"Persist project-scoped final council evidence to .swarm/evidence/final-council.json. PREREQUISITE: dispatch critic, reviewer, sme, test_engineer, and explorer as project-scoped Agent tasks and collect their CouncilMemberVerdict JSON — this tool synthesizes only. Rejects on insufficient quorum or CONCERNS with unresolved requiredFixes; normalizes verdicts to approved/concerns/rejected. Architect-only.",agents:[]},skill_generate:{description:"compile knowledge entries into a structured SKILL.md draft",agents:["skill_improver"]},skill_list:{description:"list generated skill files and their status",agents:["skill_improver"]},skill_apply:{description:"activate a draft skill proposal",agents:[]},skill_inspect:{description:"inspect the content and source entries of a skill file",agents:["skill_improver"]},run_stale_reconciliation:{description:"reconcile skills against the knowledge store: mark skills stale when source knowledge is archived or deleted, or clear stale markers",agents:["architect"]},skill_regenerate:{description:"regenerate an active skill by re-clustering its source knowledge entries and updating the SKILL.md in place",agents:[]},skill_retire:{description:"retire a generated skill by adding a retired.marker file; retired skills are excluded from scoring and injection",agents:[]},skill_improve:{description:"run the skill_improver agent to review and refine skills",agents:["skill_improver"]},spec_write:{description:"author or update .swarm/spec.md for the current project",agents:["spec_writer"]},knowledge_receipt:{description:"file a receipt for retrieved knowledge (applied/ignored/contradicted + new lessons), recorded as immutable knowledge events",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},knowledge_receipt_status:{description:"receipt status",agents:["architect"]},knowledge_archive:{description:"archive (default), quarantine, or purge a swarm or hive knowledge entry by ID with an immutable audit tombstone; purge requires an admin flag",agents:["architect"]},swarm_memory_recall:{description:"recall scoped Swarm memory for the current repository as untrusted background",agents:[]},swarm_memory_propose:{description:"create a pending Swarm memory proposal; does not write durable memory directly",agents:[]},swarm_memory_outcome:{description:"record useful, dead-end, or corrected outcomes and, when enabled, synchronously refresh deterministic memory lessons",agents:[]},swarm_command:{description:"run supported /swarm commands through the canonical command registry",agents:["architect","sme","researcher","docs","docs_design","designer","reviewer","critic_finding_validator","critic","explorer","coder","test_engineer"]},dispatch_lanes:{description:"dispatch read-only exploration/review lanes concurrently and BLOCK until all finish; prefer dispatch_lanes_async for non-blocking dispatch, use this only when promptAsync is unavailable",agents:["architect"]},dispatch_lanes_async:{description:"launch read-only advisory lanes non-blockingly and return a batch id plus lane session handles immediately; each lane agent must be a registered generated agent name (unregistered bare roles are refused on multi-swarm hosts); launch_timeout_ms is only a promptAsync acceptance budget, not a lane runtime timeout; poll incrementally with collect_lane_results (wait omitted), or join with wait: true for all results",agents:["architect"]},collect_lane_results:{description:"collect/poll a dispatch_lanes_async batch — OBSERVATION ONLY; it can never cancel or abort a lane. A presumed-stale sweep runs on every call, settling lanes past the horizon: idle host to stale, unobservable host to a typed liveness error. The wait budget (timeout_ms) bounds this observer call only — its expiry, a missing messages client, or a degraded liveness probe never kills a lane, never proves it died, and never settles anything. If a collection returns pending lanes, poll again first; busy/retry host status is live evidence, not failure. Cancellation is a distinct, explicit, authorized, potentially destructive action: use cancel_lane_batch (confirm: true + reason), never this tool. An explicit operator cancellation settles as the distinct operator_cancelled class — not liveness. Unsettled lanes are reported in pending_lanes (batch_id, lane_id, status, output_ref) regardless of include_pending. Does not advance workflow gates. Settled-lane inline output is delivered once: later polls set output_omitted_repeat: true and omit output but keep output_ref for retrieval via retrieve_lane_output.",agents:["architect"]},cancel_lane_batch:{description:"cancel ACTIVE lanes of a dispatch_lanes_async batch — the only cancellation surface (collect_lane_results cannot cancel). Destructive and authorization-gated: requires confirm: true + a bounded reason, recorded on cancelled terminals as the distinct operator_cancelled class (never liveness; not auto-retryable, never consumes retry budget — re-dispatch explicitly). Race-safe per lane: busy/retry refused (live work is never destroyed — human force path: /swarm abort-pr-workflow); degraded/absent status probe refuses the whole batch fail-closed; idle or host-unknown sessions may be cancelled; a child completing in the race window is preserved; an abort timeout never claims cancellation.",agents:["architect"]},summarize_work:{description:"emit a short structured summary of completed work (key decisions, assumptions, risks, constraints) at task completion; rolls up per phase for architecture-supervisor review. Advisory, never blocks.",agents:["architect","sme","researcher","docs","docs_design","designer","explorer","coder","test_engineer"]},write_architecture_supervisor_evidence:{description:"persist the architecture supervisor verdict for a phase (architect MUST dispatch critic_architecture_supervisor first and collect its JSON verdict; this tool persists only, it does not contact the supervisor)",agents:["architect"]},lean_turbo_plan_lanes:{description:"partition phase tasks into parallel lanes based on file-scope conflicts for Lean Turbo execution",agents:[]},lean_turbo_acquire_locks:{description:"acquire file locks for all files in a lane (all-or-nothing) before lane execution",agents:[]},lean_turbo_runner_status:{description:"read Lean Turbo run state from .swarm/turbo-state.json",agents:[]},lean_turbo_critic:{description:"dispatch a read-only critic agent to evaluate boundary conditions for a completed Lean Turbo phase (satisfies the turbo.lean.phase_critic gate)",agents:[]},lean_turbo_review:{description:"dispatch a read-only reviewer agent to evaluate a completed Lean Turbo phase",agents:[]},lean_turbo_run_phase:{description:"Execute a phase using Lean Turbo parallel lane execution. Plans lanes, acquires file locks, and dispatches coder agents concurrently. Use when Lean Turbo is active and you want to execute all tasks in a phase in parallel lanes.",agents:[]},lean_turbo_status:{description:"returns Lean Turbo configuration and active status for the current session",agents:[]},swarm_apply_patch:{description:"Apply a unified diff patch to workspace files with exact context matching, atomic writes, and path validation. Use standard unified diff format only — does NOT support *** Begin Patch / *** Update File payloads (use native apply_patch for those).",agents:["coder","test_engineer"]},external_skill_discover:{description:"Discover external skill candidates from configured sources. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_list:{description:"List external skill candidates in the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_inspect:{description:"Inspect a specific external skill candidate by ID. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_promote:{description:"Promote a validated external skill candidate to an active generated skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_reject:{description:"Reject an external skill candidate after evaluation. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_delete:{description:"Delete an external skill candidate from the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_revoke:{description:"Revoke a previously promoted external skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},epic_next_wave:{description:"Epic Mode: the single, idempotent way forward while an epic is open. Closes the active wave once every task is resolved (recording per-task outcomes and declared-vs-actual divergence, which Epic learning uses to plan later waves), keeps phases in order, and issues the next wave of disjoint tasks with dispatch instructions. Returns a status: dispatch | declare-scopes | in-progress | blocked | phase-ready-for-review | epic-complete | refused. Requires `epic.mode.enabled: true` and an epic opened by `/swarm epic start`.",agents:[]},epic_phase_review:{description:"Epic Mode phase readiness: dispatch a read-only phase reviewer, then (only if it APPROVES) a read-only phase critic over the completed phase; parse both verdicts from the agents and record them to .swarm/evidence/{phase}/epic-phase-review.json. Required by phase_complete while an epic is open for the current plan; re-run after any fix (evidence is bound to the plan and phase task evidence).",agents:[]}},TOOL_NAMES=Object.keys(TOOL_METADATA),TOOL_NAME_SET=new Set(TOOL_NAMES);TOOL_DESCRIPTIONS=Object.fromEntries(Object.entries(TOOL_METADATA).map(([name,meta])=>[name,meta.description])),AGENT_TOOL_MAP=(()=>{let map=Object.fromEntries(ALL_AGENT_NAMES.map((agent)=>[agent,[]]));for(let[name,meta]of Object.entries(TOOL_METADATA))for(let agent of meta.agents)map[agent].push(name);return map})()});function scanOverrideForDangerousKeys(value,path,depth){if(depth>=10)return;if(Array.isArray(value)){for(let i=0;i<value.length;i++)scanOverrideForDangerousKeys(value[i],`${path}[${i}]`,depth+1);return}if(typeof value!=="object"||value===null)return;for(let key of Object.keys(value)){if(DANGEROUS_MERGE_KEYS.has(key))throw new DangerousMergeKeyError(key,path);scanOverrideForDangerousKeys(value[key],`${path}.${key}`,depth+1)}}function deepMergeInternal(base,override,depth,path){if(depth>=10)throw Error("deepMerge exceeded maximum depth of 10");let result={...base};for(let key of Object.keys(override)){let baseVal=base[key],overrideVal=override[key];if(typeof baseVal==="object"&&baseVal!==null&&typeof overrideVal==="object"&&overrideVal!==null&&!Array.isArray(baseVal)&&!Array.isArray(overrideVal))result[key]=deepMergeInternal(baseVal,overrideVal,depth+1,`${path}.${key}`);else result[key]=overrideVal}return result}function deepMerge(base,override){if(!base)return override;if(!override)return base;return scanOverrideForDangerousKeys(override,"$",0),deepMergeInternal(base,override,0,"$")}var MAX_MERGE_DEPTH=10,DANGEROUS_MERGE_KEYS,DangerousMergeKeyError;var init_merge=__esm(()=>{DANGEROUS_MERGE_KEYS=new Set(["__proto__","constructor","prototype"]);DangerousMergeKeyError=class DangerousMergeKeyError extends Error{key;path;constructor(key,path){super(`deepMerge refused dangerous key "${key}" at "${path}": prototype-pollution carriers (__proto__/constructor/prototype) are never merged`);this.key=key;this.path=path;this.name="DangerousMergeKeyError"}}});function freezeSet(items,name="CLAUDE_CODE_NATIVE_COMMANDS"){let set=new Set(items),proxy=new Proxy(set,{get(target,prop){if(prop==="add"||prop==="delete"||prop==="clear")return()=>{throw TypeError(`${name} is readonly`)};if(prop==="forEach")return(callback,thisArg)=>{let wrapped=(v,k)=>callback.call(thisArg??void 0,v,k,proxy);return set.forEach(wrapped)};let value=Reflect.get(target,prop);return typeof value==="function"?value.bind(target):value},set(){throw TypeError(`${name} is readonly`)},deleteProperty(){throw TypeError(`${name} is readonly`)},defineProperty(){throw TypeError(`${name} is readonly`)},setPrototypeOf(){throw TypeError(`${name} is readonly`)}});return proxy}function isQAAgent(name){return QA_AGENTS.includes(name)}function isSubagent(name){return ALL_SUBAGENT_NAMES.includes(name)}function isLowCapabilityModel(modelId){let lower=(modelId||"").toLowerCase();return LOW_CAPABILITY_MODELS.some((substr)=>lower.includes(substr))}var OPENCODE_NATIVE_AGENTS,CLAUDE_CODE_NATIVE_COMMANDS,OPENCODE_NATIVE_COMMANDS,MEMORY_AGENT_TOOL_MAP,EXTERNAL_SKILL_TOOL_NAMES,EXTERNAL_SKILL_AGENT_TOOL_MAP,COUNCIL_TOOL_NAMES,COUNCIL_AGENT_TOOL_MAP,GENERAL_COUNCIL_TOOL_NAMES,GENERAL_COUNCIL_AGENT_TOOL_MAP,TURBO_TOOL_NAMES,TURBO_AGENT_TOOL_MAP,EPIC_TOOL_NAMES,EPIC_AGENT_TOOL_MAP,SKILL_TOOL_NAMES,SKILL_AGENT_TOOL_MAP,PR_REVIEW_CHILD_TOOL_NAMES,PR_REVIEW_CHILD_AGENT_TOOL_MAP,WRITE_TOOL_NAMES,SUMMARIZER_EXEMPT_TOOL_NAMES,DEFAULT_MODELS,DEFAULT_AGENT_CONFIGS,DEFAULT_SCORING_CONFIG,LOW_CAPABILITY_MODELS,TURBO_MODE_BANNER=`## \uD83D\uDE80 TURBO MODE ACTIVE
|
|
1
|
+
import{createRequire}from"node:module";var __create=Object.create;var{getPrototypeOf:__getProtoOf,defineProperty:__defProp,getOwnPropertyNames:__getOwnPropNames,getOwnPropertyDescriptor:__getOwnPropDesc}=Object,__hasOwnProp=Object.prototype.hasOwnProperty;function __accessProp(key){return this[key]}var __toESMCache_node,__toESMCache_esm,__toESM=(mod,isNodeMode,target)=>{var canCache=mod!=null&&typeof mod==="object";if(canCache){var cache=isNodeMode?__toESMCache_node??=new WeakMap:__toESMCache_esm??=new WeakMap,cached=cache.get(mod);if(cached)return cached}target=mod!=null?__create(__getProtoOf(mod)):{};let to=isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target;for(let key of __getOwnPropNames(mod))if(!__hasOwnProp.call(to,key))__defProp(to,key,{get:__accessProp.bind(mod,key),enumerable:!0});if(canCache)cache.set(mod,to);return to},__toCommonJS=(from)=>{var entry=(__moduleCache??=new WeakMap).get(from),desc;if(entry)return entry;if(entry=__defProp({},"__esModule",{value:!0}),from&&typeof from==="object"||typeof from==="function"){for(var key of __getOwnPropNames(from))if(!__hasOwnProp.call(entry,key))__defProp(entry,key,{get:__accessProp.bind(from,key),enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return __moduleCache.set(from,entry),entry},__moduleCache,__commonJS=(cb,mod)=>()=>(mod||cb((mod={exports:{}}).exports,mod),mod.exports);var __returnValue=(v)=>v;function __exportSetter(name,newValue){this[name]=__returnValue.bind(null,newValue)}var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0,configurable:!0,set:__exportSetter.bind(all,name)})};var __esm=(fn2,res)=>()=>(fn2&&(res=fn2(fn2=0)),res);var __require=createRequire(import.meta.url);var package_default;var init_package=__esm(()=>{package_default={name:"opencode-swarm",version:"7.194.0",description:"Architect-centric agentic swarm plugin for OpenCode - hub-and-spoke orchestration with SME consultation, code generation, and QA review",main:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",default:"./dist/index.js"},"./package.json":"./package.json"},bin:{"opencode-swarm":"./dist/cli/index.js"},type:"module",engines:{bun:">=1.3.13",node:">=22.13"},license:"MIT",repository:{type:"git",url:"https://github.com/ZaxbyHub/opencode-swarm.git"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},keywords:["opencode","opencode-plugin","ai","agents","orchestration","swarm","multi-agent","llm"],files:["dist","dist/lang/grammars","binaries","evaluation-fixtures",".opencode/skills/brainstorm",".opencode/skills/specify",".opencode/skills/clarify-spec",".opencode/skills/swarm-resume",".opencode/skills/clarify",".opencode/skills/discover",".opencode/skills/consult",".opencode/skills/pre-phase-briefing",".opencode/skills/council",".opencode/skills/deep-dive",".opencode/skills/deep-research",".opencode/skills/codebase-review-swarm",".opencode/skills/swarm-implement",".opencode/skills/design-docs",".opencode/skills/swarm-pr-review",".opencode/skills/swarm",".opencode/skills/swarm-pr-feedback",".opencode/skills/swarm-pr-subscribe",".opencode/skills/swarm-ci-monitor",".opencode/skills/issue-ingest",".opencode/skills/swarm-plan",".opencode/skills/critic-gate",".opencode/skills/execute",".opencode/skills/phase-wrap",".opencode/skills/loop",".opencode/skills/writing-tests",".opencode/skills/running-tests",".opencode/skills/engineering-conventions",".opencode/skills/commit-pr",".opencode/skills/ci-failure-batching",".opencode/skills/gate-attribution",".opencode/skills/merge-queue-readiness",".opencode/skills/skill-edit-validation",".opencode/skills/worktree-retry-cleanup",".opencode/skills/test-file-split",".opencode/skills/fork-pr-operations",".opencode/skills/parallel-work-check",".opencode/skills/ci-fix-monitor",".opencode/skills/issue-tracer",".opencode/skills/orchestrating-subagents",".opencode/skills/durable-session-state","tests/fixtures/memory-recall","tests/fixtures/memory-recall-heldout","opencode-swarm.schema.json","README.md","LICENSE"],scripts:{clean:`bun -e "require('fs').rmSync('dist',{recursive:true,force:true})"`,build:"bun run clean && bun run scripts/generate-config-schema.ts && bun run scripts/copy-grammars.ts && bun build src/index.ts --outdir dist --target node --format esm --external web-tree-sitter --minify-whitespace --minify-syntax && bun build src/cli/index.ts --outdir dist/cli --target bun --format esm --external bash-parser --splitting && bun run scripts/copy-grammars.ts --to-dist && tsc --emitDeclarationOnly",typecheck:"tsc --noEmit",test:"bun test",lint:"biome lint .","lint:ci":"biome ci .","test:unit:ci":"bun scripts/ci/run-unit-tests-local.ts","validate:repo":"bun scripts/ci/repository-validation.ts","drift:check":"bun run scripts/drift-check.ts","check:pre-push":"bun run scripts/drift-check.ts --enforce --no-report && bun run check:registry-citations","schema:generate":"bun run scripts/generate-config-schema.ts","generate:commands-docs":"bun run scripts/generate-commands-docs.ts","check:runtime-src-refs":"bun run scripts/check-runtime-src-refs.ts","drift:fix":"bun run scripts/drift-check.ts --fix --confirm","skills:sync":"bun run scripts/sync-qa-gate-skills.ts",format:"biome format . --write",check:"biome check --write .",dev:"bun run build && opencode","package:smoke":"node scripts/package-smoke.mjs",prepare:"bun run build","repro:704":"node scripts/repro-704.mjs","repro:2669":"node scripts/repro-2669.mjs","repro:2670":"node scripts/repro-2670.mjs","repro:1144":"bun scripts/repro-1144.mjs","repro:1873":"bun build scripts/repro-1873-entry.ts --outdir dist-build-test/repro-1873 --target node --format esm && node scripts/repro-1873.mjs","repro:2487":"bun build scripts/repro-2487-parity-entry.ts --outdir dist-build-test/repro-2487 --target node --format esm && node scripts/repro-2487-parity.mjs","check:events":"bun run scripts/check-event-contract.ts","check:retention":"bun run scripts/check-retention-registry.ts","check:core-events":"bun run scripts/check-core-events-usage.ts","check:shell-audit":"bun run scripts/check-shell-audit-usage.ts","check:trajectory-store":"bun run scripts/check-trajectory-store-usage.ts","check:mock-cleanup":"bun run scripts/check-mock-cleanup.ts","check:invariants":"bun run scripts/check-invariants.ts","check:token-formula":"bun run scripts/check-token-formula.ts","check:cross-contamination":"bun run scripts/check-cross-contamination.ts","check:test-clock":"bun run scripts/check-test-clock.ts","check:test-file-cap":"bun run scripts/check-test-file-cap.ts","check:test-tmpdir":"bun run scripts/check-test-tmpdir.ts","check:bash-portability":"bun run scripts/check-bash-portability.ts","check:pending-fragment":"bun run scripts/check-pending-fragment.ts","check:gate-portability":"bun run scripts/check-gate-portability.ts","check:bare-spawn":"bun run scripts/check-bare-executable-spawn.ts","check:error-channel-discard":"bun run scripts/check-error-channel-discard.ts","check:path-identity":"bun run scripts/check-path-identity.ts","check:registry-citations":"bun run scripts/check-registry-citations.ts","check:memory-recall":"bun run scripts/memory-recall-regression.ts","check:retrieval-quality":"bun run scripts/retrieval-quality-regression.ts"},dependencies:{"@modelcontextprotocol/sdk":"^1.30.0","@opencode-ai/plugin":"^1.18.3","@opencode-ai/sdk":"^1.18.3","@vscode/tree-sitter-wasm":"^0.3.0","bash-parser":"^0.5.0","p-limit":"^7.3.0",picomatch:"^4.0.4","proper-lockfile":"^4.1.2","quick-lru":"^7.3.0","web-tree-sitter":"^0.25.0",zod:"4.3.6"},devDependencies:{"@biomejs/biome":"2.3.14","@types/picomatch":"^4.0.3","bun-types":"1.3.8","js-yaml":"^4.1.1",typescript:"^5.7.3"},peerDependencies:{"@xenova/transformers":"^2.17.2"},peerDependenciesMeta:{"@xenova/transformers":{optional:!0}}}});var QA_AGENTS,PIPELINE_AGENTS,ORCHESTRATOR_NAME="architect",ALL_SUBAGENT_NAMES,ALL_AGENT_NAMES;var init_agent_names=__esm(()=>{QA_AGENTS=["reviewer","critic","critic_oversight","critic_finding_validator"],PIPELINE_AGENTS=["explorer","coder","test_engineer"],ALL_SUBAGENT_NAMES=["sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","curator_postmortem","curator_consolidation","council_generalist","council_skeptic","council_domain_expert","skill_improver","spec_writer",...QA_AGENTS,...PIPELINE_AGENTS],ALL_AGENT_NAMES=["architect",...ALL_SUBAGENT_NAMES]});function getPrWorkflowToolCapability(toolName,mode){let metadata=TOOL_METADATA[toolName];if(!metadata?.prWorkflow?.modes.includes(mode))return null;return metadata.prWorkflow.capability}var TOOL_METADATA,TOOL_NAMES,TOOL_NAME_SET,TOOL_DESCRIPTIONS,AGENT_TOOL_MAP;var init_tool_metadata=__esm(()=>{init_agent_names();TOOL_METADATA={diff:{description:"structured git diff with contract change detection",agents:["architect","reviewer","critic_finding_validator","critic_oversight","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},diff_summary:{description:"filter classified AST changes by category, risk level, or file for reviewer drill-down",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},syntax_check:{description:"check syntax of source files using tree-sitter parsers across multiple languages, returning per-file errors",agents:["architect","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},placeholder_scan:{description:"todo and FIXME comment detection",agents:["architect","reviewer","critic_finding_validator"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},imports:{description:"find all consumers that import from a given file — use before refactoring shared modules to avoid breaking unseen dependents",agents:["architect","sme","researcher","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},lint:{description:"run project linter in check or fix mode; supports biome, eslint, ruff, clippy, and more, returns structured results",agents:["architect","reviewer","critic_finding_validator","coder"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},secretscan:{description:"scan for secrets (API keys, tokens, passwords) via regex and entropy; returns redacted previews, excludes common dirs",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},sast_scan:{description:"static analysis security scan",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},build_check:{description:"discover and run build, typecheck, and test commands for various project ecosystems in the working directory",agents:["architect","coder","test_engineer"]},pre_check_batch:{description:"parallel verification: lint:check + secretscan + sast_scan + quality_budget",agents:["architect","reviewer","critic_finding_validator"]},quality_budget:{description:"code quality budget check",agents:["architect"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},symbols:{description:"extract exported symbols (functions, classes, interfaces, types) from source files; supports TypeScript, JavaScript, Python, Rust, Go, Dart, Ruby, PHP, and Java",agents:["architect","sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},complexity_hotspots:{description:"git churn × complexity risk map",agents:["architect","sme","researcher","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","critic_oversight","explorer","test_engineer"]},schema_drift:{description:"OpenAPI spec vs route drift",agents:["architect","sme","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},todo_extract:{description:"structured TODO/FIXME extraction; with task_id, records the high-priority count as todo_scan gate evidence",agents:["architect","researcher","docs","explorer","coder"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},evidence_check:{description:"verify task evidence completeness",agents:["architect","critic_oversight"]},check_gate_status:{description:"check the gate status of a specific task",agents:["architect","critic_oversight"]},completion_verify:{description:"verify completed tasks have required evidence",agents:["architect","critic_oversight"]},complete_pr_workflow:{description:"validate terminal PR workflow evidence and clear its durable session gate",agents:["architect"]},abort_pr_workflow:{description:"abort an unrecoverable PR_REVIEW/PR_FEEDBACK mechanical gate and clear its durable session state",agents:["architect"]},authorize_pr_review_reentry:{description:"issue a one-use, identity-bound reviewer/test_engineer re-entry authorization for the active PR_REVIEW workflow (issue #2383)",agents:["architect"]},submit_pr_review_result:{description:"submit one child-bound typed result for an active PR-review base or micro discovery lane",agents:[],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},approve_plan_critic:{description:"record a MANUAL plan_critic_gate approval snapshot to unblock the ratchet-tighter critic_pre_plan execution gate when the critic already returned APPROVED but the mechanical recorder failed to persist it (issue #2012), or as the sanctioned recovery for a bookkeeping-grade hashed-field repair under the critic-gate PLAN FREEZE rule (the reason must state which case applies)",agents:["architect"]},approve_retry_sounding_board:{description:"record a MANUAL critic_sounding_board gate entry to unblock the coder retry circuit-breaker gate when the sounding board returned APPROVED but the mechanical recorder missed it (issue #2703)",agents:["architect"]},recover_rework_task:{description:"recover a task wedged at rework_required when the reviewer/test_engineer verdict did not require a code change: write a supervised stage_a_passed so those gates can be re-dispatched without re-running the coder (issue #2755)",agents:["architect"]},recover_stage_a_task:{description:"recover a task wedged in the settlement-backed Stage A deadlock — workflow at idle/blocked while a COMMITTED accepted coder settlement and green post-settlement pre-check proof justify Stage A: write a settlement-backed stage_a_passed so reviewer/test_engineer can be dispatched, without re-running the coder (issue #2828)",agents:["architect"]},prepare_pr_workflow_checkout:{description:"prepare an auditable PR workflow checkout or restore its exact original branch/HEAD and preserved stash after terminal cleanup",agents:["architect"]},invalidate_pr_feedback_publication:{description:"invalidate the armed PR_FEEDBACK publication generation so approved content can change, superseding every content-dependent approval and reopening the exact scoped rework + fresh-review path (issue #2108)",agents:["architect"]},record_implementation_review:{description:"record fresh-context reviewer + critic APPROVE verdicts for the implementation diff so the /swarm issue --trace workflow can satisfy its review gate before commit-pr handoff",agents:["architect"]},record_issue_publication:{description:"record a publication receipt so the /swarm issue --trace workflow reaches its terminal published state after the PR is created/updated",agents:["architect"]},record_issue_reproduction:{description:"record the reproduction outcome for the current traced issue so the /swarm issue --trace workflow can satisfy its reproduction gate and transition to PLAN",agents:["architect"]},record_recurrence_sweep:{description:"record the recurrence sweep (defect class, predicates, hit dispositions, guardrail proof, related-problems results) so the /swarm issue --trace workflow can satisfy its recurrence gate before commit-pr handoff",agents:["architect"]},record_branch_freshness:{description:"record the Phase 0 branch-freshness outcome (synced / behind:<n> / fetch-failed:<reason> plus optional user override) so the /swarm issue --trace workflow can pass its freshness gate before transitioning to PLAN (issue #2564)",agents:["architect"]},record_trace_validation:{description:"record one per-phase trace-check.sh validator outcome (phase, pass/fail, reviewedCommit, treeId) so the /swarm issue --trace workflow can satisfy its validator-receipt gate before commit-pr handoff (issue #2564)",agents:["architect"]},record_merge_approval:{description:"record the human merge approval bound to the exact PR head SHA so the /swarm issue --trace workflow reaches its terminal merge_approval_recorded state — recorded for audit only, never certified or driven by the plugin (issue #2564)",agents:["architect"]},rebind_pr_feedback_head:{description:"rebind a PR_FEEDBACK workflow to a new verified remote PR head after merge/rebase/conflict repair, invalidating ancestry-bound receipts so the mechanical ladder re-runs",agents:["architect"]},run_pr_feedback_stage_a:{description:"execute and persist mandatory PR-feedback Stage A checks on a content-bound revision",agents:["architect"]},submit_council_verdicts:{description:"submit pre-collected council member verdicts for synthesis (architect MUST dispatch critic/reviewer/sme/test_engineer/explorer as Agent tasks first; this tool synthesizes only, it does not contact members)",agents:[]},submit_phase_council_verdicts:{description:"submit pre-collected phase-level council member verdicts for holistic phase synthesis (architect MUST dispatch all 5 council members with phase-scoped context first; this tool synthesizes only, it does not contact members)",agents:[]},declare_council_criteria:{description:"pre-declare acceptance criteria for a task before the coder starts work; criteria are read back during council evaluation",agents:[]},sbom_generate:{description:"SBOM generation for dependency inventory",agents:["architect"]},checkpoint:{description:"create named git checkpoints for save, restore, and delete — use before risky operations to enable rollback; a destructive restore previews first and requires the confirm_token issued in the preview (#2946)",agents:["architect"]},pkg_audit:{description:"dependency vulnerability scan — npm/pip/cargo",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},parse_lane_candidates:{description:"Parse [CANDIDATE] rows from a dispatch_lanes or collect_lane_results artifact (by output_ref), produce structured records with provenance, optionally persist to a per-batch sidecar JSONL. Pure-parser variant exists as internal module.",agents:["architect"]},plan_conflict_check:{description:"read-only advisory check (#1656): compute a pairwise file-conflict matrix for N proposed parallel task groups using declared scopes and optional git co-change; returns a verdict (all_disjoint / conflicts_present / unknown_scopes), per-pair evidence, and a suggested serialization order. Writes nothing — the execution gate independently recomputes the verdict inline at dispatch time via the same helper. Call BEFORE attempting parallel dispatch to confirm disjointness.",agents:["architect"]},write_pr_review_trigger_eval:{description:"persist the complete PR-review trigger evaluation with exact-set validation, dispatch provenance, and live merge-base verification",agents:["architect"]},write_pr_review_artifact:{description:"persist schema-validated PR-review findings checkpoints and exact actionable feedback handoffs under the active run",agents:["architect"]},pr_review_submission:{description:"submit a settled, head-bound PR review to GitHub through the gh PR Review API after the PR_REVIEW gate clears; architect-only, refuses while a gate is active or the run was aborted after settlement",agents:["architect"]},export_pr_review_partial_results:{description:"export the validated partial results of an ABORTED PR_REVIEW run as a partial, non-authoritative artifact bound per-item to receipt-authenticated findings; architect-only, requires the gate cleared and an abort event binding session and head, never implies completion or feedback consent",agents:["architect"]},prepare_pr_feedback_scope:{description:"prepare an exact file scope for one PR-feedback coder Task after immutable feedback verification settles",agents:["architect"]},test_runner:{description:"auto-detect and run tests",agents:["architect","reviewer","critic_finding_validator","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},test_impact:{description:"identify test files impacted by changed source files via import analysis",agents:["architect","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},mutation_test:{description:"executes pre-generated mutation patches against tests, evaluates kill rate against quality gate thresholds; test selection comes from explicit files (override) or source_files derived via the impact analyzer with a typed bounded fallback",agents:["architect","test_engineer"]},generate_mutants:{description:"generate LLM-based mutation testing patches for source files; returns MutationPatch[] for direct consumption by the mutation_test tool",agents:["architect"]},detect_domains:{description:"detect which SME domains are relevant for a given text",agents:["architect","sme","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic","critic_oversight","explorer"]},git_blame:{description:"per-line git blame metadata: sha, author, date, summary for each line in a file",agents:["reviewer","critic_finding_validator","explorer","architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},gitingest:{description:"fetch a GitHub repository full content via gitingest.com",agents:["architect","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_summary:{description:"retrieve the full content of a stored tool output summary",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_lane_output:{description:"retrieve paged full dispatch lane output by output_ref; use before consuming truncated lane previews or routing candidates from lane results",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},extract_code_blocks:{description:"extract code blocks from text content and save them to files",agents:["docs","docs_design","designer","spec_writer","coder","test_engineer"]},phase_complete:{description:"preflight every applicable phase gate, report all blockers, and atomically commit a current passing snapshot",agents:["architect"]},run_phase_review:{description:"run the bounded phase-final review engine and persist complete content-addressed review evidence",agents:["architect"]},repair_gate_evidence:{description:"quarantine recoverable exact-task gate evidence, rebuild from durable requirements, recover receipt-backed legacy marker wedges or the exact sentinel-only historical reset, and refuse every other receipt-less reconstruction",agents:["architect"]},repair_knowledge_receipt_ledger:{description:"validate or repair authoritative knowledge receipts, preserve corrupt authority in bounded quarantine, require scoped re-evaluation, and backfill stable phase ids across the whole ledger (operation backfill_phase_id; phase/session_id do not scope the backfill)",agents:["architect"]},record_directive_override:{description:"record an audited architect override for identified critical-directive violations without bypassing unreadable authority",agents:["architect"]},save_plan:{description:"save a structured implementation plan",agents:["architect"]},update_task_status:{description:"mark tasks complete, track phase progress",agents:["architect"]},lint_spec:{description:"validate .swarm/spec.md format and required fields",agents:["architect","spec_writer"]},write_retro:{description:"document phase retrospectives via phase_complete workflow, capture lessons learned",agents:["architect"]},write_drift_evidence:{description:"write drift verification evidence for a completed phase",agents:["architect"]},write_hallucination_evidence:{description:"write hallucination verification evidence for a completed phase",agents:["architect"]},write_mutation_evidence:{description:"write mutation gate evidence for a completed phase; normalizes PASS/WARN/FAIL/SKIP verdicts and writes .swarm/evidence/{phase}/mutation-gate.json",agents:["architect"]},declare_scope:{description:"declare file scope for next coder delegation",agents:["architect"]},scope_validate:{description:"validate shell writes against an inline file scope",agents:["architect"]},knowledge_query:{description:"query swarm or hive knowledge with optional filters",agents:["architect","skill_improver","spec_writer"]},doc_scan:{description:"scan project documentation files and build an index manifest",agents:["architect","docs_design","skill_improver","spec_writer","explorer"]},doc_extract:{description:"extract actionable constraints from project documentation",agents:["architect","docs_design","skill_improver","spec_writer"]},curator_analyze:{description:"run curator phase analysis and optionally apply knowledge recommendations",agents:["architect"]},consensus_mine:{description:"mine cross-run consensus from existing .swarm evidence into an immutable proposals-only report; also deletes its own reports past consensus.report_retention, appends to the shared recommendation dedup ledger (in the shared cohort root, outside this project, when a knowledge link is active), and mirrors proposals into pending swarm-memory proposals when memory is enabled",agents:["architect","curator_phase","curator_postmortem"]},knowledge_add:{description:"store a new lesson in the knowledge base",agents:["architect","coder"]},knowledge_recall:{description:"search the knowledge base for relevant past decisions",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"]},knowledge_remove:{description:"delete an outdated swarm knowledge entry by ID (swarm tier only)",agents:["architect"]},co_change_analyzer:{description:"detect hidden couplings by analyzing git history",agents:["architect"]},context_status:{description:"report current context-window headroom for the active session — returns tokens-used, usageSource (provider|estimated), model-limit with provenance (modelLimitSource: host|override|provider_cap|native|fallback; modelLimitResolution: user_provider_model|user_model|user_default|live_model_limit|static_provider_cap|static_native|static_default; fallbackActive: true when the denominator came from a static table or the flat 128k default — treat headroom as uncertain), usage-percent, threshold-state (none/warn/critical), model name, and provider. Pure read-only: no state mutation, no warning injection. Works whether context_budget.enabled is true or false.",agents:["architect"]},search:{description:"Workspace-scoped ripgrep-style text search with structured JSON output. Supports literal and regex modes, glob filtering, and result limits. NOTE: This is text search, not structural AST search — use symbols and imports tools for structural queries.",agents:["architect","sme","docs","docs_design","designer","critic_hallucination_verifier","skill_improver","spec_writer","reviewer","critic_finding_validator","critic_oversight","explorer","coder","test_engineer","researcher"]},ast_grep:{description:"Read-only structural AST search using ast-grep patterns with optional language and glob filters. Use for syntax-aware code pattern searches; does not rewrite files.",agents:["architect","sme","docs","docs_design","critic_hallucination_verifier","spec_writer","explorer","coder","test_engineer","researcher"]},actionlint_scan:{description:"Run actionlint against GitHub Actions workflow YAML files with structured findings. Resolves actionlint lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},osv_scan:{description:"Run OSV-Scanner against a workspace path and return structured dependency vulnerability findings. Resolves osv-scanner lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},gh_evidence:{description:"Fetch bounded GitHub pull request or issue metadata through gh for review and CI evidence. Resolves gh lazily and is read-only.",agents:["architect","researcher"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},pr_workflow_status:{description:"Read-only architect observation of local git state (HEAD, branch, clean/dirty with a bounded changed-file list, remotes) plus a session-pinned PR workflow gate summary and the PR_FEEDBACK publication-generation section (state, attempts, invalidation reason, recovery guidance). For an active PR_REVIEW gate it also projects that derived state read-only: per-boundary settlement (post_explorer / post_reviewer / post_critic), per-lane coverage (accepted, rejected, one-line latest finding), and the bounded candidate inventory, each degrading to a typed unavailable state rather than an absence claim. Use to observe state under the fail-closed PR_REVIEW/PR_FEEDBACK gate. Never executes PR-controlled scripts and never reads another session gate.",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},batch_symbols:{description:"Batched symbol extraction across multiple files. Returns per-file symbol summaries with isolated error handling.",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","explorer"]},suggest_patch:{description:"Reviewer-safe structured patch suggestion tool. Produces context-anchored patch artifacts without file modification. Returns structured diagnostics on context mismatch.",agents:["architect","reviewer","critic_finding_validator"]},req_coverage:{description:"query requirement coverage status for tracked functional requirements",agents:["critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","critic","critic_oversight"]},get_approved_plan:{description:"retrieve the last critic-approved immutable plan snapshot for baseline drift comparison",agents:["critic_drift_verifier","critic","critic_oversight"]},repo_map:{description:"query the repo code graph: importers, dependencies, blast radius, localization, ontology facts, package boundaries, and heuristic preflight packets before refactoring; ontology findings are advisory, not formal proofs",agents:["architect","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},get_qa_gate_profile:{description:"retrieve the QA gate profile for the current or exact future plan identity: gates (reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council), lock state, profile hash, the calling session’s ratchet-tighter overrides, and the EFFECTIVE gates (profile merged with those overrides; durable across restart). Read-only and never creates state.",agents:["architect"]},set_qa_gates:{description:"configure the QA gate profile for the current plan or bootstrap an exact future plan with swarm_id and plan_title. Architect-only. The initial selection may set explicit true/false values over defaults; later changes are ratchet-tighter and rejected once locked after critic approval. Supports: reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council, plus adopt_legacy_binding_only for exact-binding recovery without mutating gates.",agents:["architect"]},web_search:{description:"External web search (Tavily or Brave) for architect-driven council research, SME domain research, researcher auto-research, and skill-improver research. Returns titled results with snippets, URLs, normalized query metadata, temporal intent, freshness, and removed stale years. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides. Requires a search API key. Used by the architect in MODE: COUNCIL to gather a RESEARCH CONTEXT before dispatching council agents, by SME for opt-in external skill/source evaluation, and by the researcher agent for multi-source auto-research.",agents:["sme","researcher","skill_improver"]},web_fetch:{description:"Fetch the readable text of a single http(s) URL (architect-only). Returns decoded page text, document title, final URL after redirects, and an evidence reference. Reads primary sources that web_search only surfaces as snippets. Config-gated on council.general.enabled. Blocks private/loopback/link-local/metadata addresses (re-validated and re-pinned across redirects); enforces timeout and body size cap.",agents:[]},convene_general_council:{description:"Synthesize responses from a multi-model General Council. Accepts parallel member responses (Round 1, optionally Round 2), detects disagreements, and returns consensus points, persisting disagreements, and a structured synthesis. Architect-only. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides.",agents:[]},write_final_council_evidence:{description:"Persist project-scoped final council evidence to .swarm/evidence/final-council.json. PREREQUISITE: dispatch critic, reviewer, sme, test_engineer, and explorer as project-scoped Agent tasks and collect their CouncilMemberVerdict JSON — this tool synthesizes only. Rejects on insufficient quorum or CONCERNS with unresolved requiredFixes; normalizes verdicts to approved/concerns/rejected. Architect-only.",agents:[]},skill_generate:{description:"compile knowledge entries into a structured SKILL.md draft",agents:["skill_improver"]},skill_list:{description:"list generated skill files and their status",agents:["skill_improver"]},skill_apply:{description:"activate a draft skill proposal",agents:[]},skill_inspect:{description:"inspect the content and source entries of a skill file",agents:["skill_improver"]},run_stale_reconciliation:{description:"reconcile skills against the knowledge store: mark skills stale when source knowledge is archived or deleted, or clear stale markers",agents:["architect"]},skill_regenerate:{description:"regenerate an active skill by re-clustering its source knowledge entries and updating the SKILL.md in place",agents:[]},skill_retire:{description:"retire a generated skill by adding a retired.marker file; retired skills are excluded from scoring and injection",agents:[]},skill_improve:{description:"run the skill_improver agent to review and refine skills",agents:["skill_improver"]},spec_write:{description:"author or update .swarm/spec.md for the current project",agents:["spec_writer"]},knowledge_receipt:{description:"file a receipt for retrieved knowledge (applied/ignored/contradicted + new lessons), recorded as immutable knowledge events",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},knowledge_receipt_status:{description:"receipt status",agents:["architect"]},knowledge_archive:{description:"archive (default), quarantine, or purge a swarm or hive knowledge entry by ID with an immutable audit tombstone; purge requires an admin flag",agents:["architect"]},swarm_memory_recall:{description:"recall scoped Swarm memory for the current repository as untrusted background",agents:[]},swarm_memory_propose:{description:"create a pending Swarm memory proposal; does not write durable memory directly",agents:[]},swarm_memory_outcome:{description:"record useful, dead-end, or corrected outcomes and, when enabled, synchronously refresh deterministic memory lessons",agents:[]},swarm_command:{description:"run supported /swarm commands through the canonical command registry",agents:["architect","sme","researcher","docs","docs_design","designer","reviewer","critic_finding_validator","critic","explorer","coder","test_engineer"]},dispatch_lanes:{description:"dispatch read-only exploration/review lanes concurrently and BLOCK until all finish; prefer dispatch_lanes_async for non-blocking dispatch, use this only when promptAsync is unavailable",agents:["architect"]},dispatch_lanes_async:{description:"launch read-only advisory lanes non-blockingly and return a batch id plus lane session handles immediately; each lane agent must be a registered generated agent name (unregistered bare roles are refused on multi-swarm hosts); launch_timeout_ms is only a promptAsync acceptance budget, not a lane runtime timeout; poll incrementally with collect_lane_results (wait omitted), or join with wait: true for all results",agents:["architect"]},collect_lane_results:{description:"collect/poll a dispatch_lanes_async batch — OBSERVATION ONLY; it can never cancel or abort a lane. A presumed-stale sweep runs on every call, settling lanes past the horizon: idle host to stale, unobservable host to a typed liveness error. The wait budget (timeout_ms) bounds this observer call only — its expiry, a missing messages client, or a degraded liveness probe never kills a lane, never proves it died, and never settles anything. If a collection returns pending lanes, poll again first; busy/retry host status is live evidence, not failure. Cancellation is a distinct, explicit, authorized, potentially destructive action: use cancel_lane_batch (confirm: true + reason), never this tool. An explicit operator cancellation settles as the distinct operator_cancelled class — not liveness. Unsettled lanes are reported in pending_lanes (batch_id, lane_id, status, output_ref) regardless of include_pending. Does not advance workflow gates. Settled-lane inline output is delivered once: later polls set output_omitted_repeat: true and omit output but keep output_ref for retrieval via retrieve_lane_output.",agents:["architect"]},cancel_lane_batch:{description:"cancel ACTIVE lanes of a dispatch_lanes_async batch — the only cancellation surface (collect_lane_results cannot cancel). Destructive and authorization-gated: requires confirm: true + a bounded reason, recorded on cancelled terminals as the distinct operator_cancelled class (never liveness; not auto-retryable, never consumes retry budget — re-dispatch explicitly). Race-safe per lane: busy/retry refused (live work is never destroyed — human force path: /swarm abort-pr-workflow); degraded/absent status probe refuses the whole batch fail-closed; idle or host-unknown sessions may be cancelled; a child completing in the race window is preserved; an abort timeout never claims cancellation.",agents:["architect"]},summarize_work:{description:"emit a short structured summary of completed work (key decisions, assumptions, risks, constraints) at task completion; rolls up per phase for architecture-supervisor review. Advisory, never blocks.",agents:["architect","sme","researcher","docs","docs_design","designer","explorer","coder","test_engineer"]},write_architecture_supervisor_evidence:{description:"persist the architecture supervisor verdict for a phase (architect MUST dispatch critic_architecture_supervisor first and collect its JSON verdict; this tool persists only, it does not contact the supervisor)",agents:["architect"]},lean_turbo_plan_lanes:{description:"partition phase tasks into parallel lanes based on file-scope conflicts for Lean Turbo execution",agents:[]},lean_turbo_acquire_locks:{description:"acquire file locks for all files in a lane (all-or-nothing) before lane execution",agents:[]},lean_turbo_runner_status:{description:"read Lean Turbo run state from .swarm/turbo-state.json",agents:[]},lean_turbo_critic:{description:"dispatch a read-only critic agent to evaluate boundary conditions for a completed Lean Turbo phase (satisfies the turbo.lean.phase_critic gate)",agents:[]},lean_turbo_review:{description:"dispatch a read-only reviewer agent to evaluate a completed Lean Turbo phase",agents:[]},lean_turbo_run_phase:{description:"Execute a phase using Lean Turbo parallel lane execution. Plans lanes, acquires file locks, and dispatches coder agents concurrently. Use when Lean Turbo is active and you want to execute all tasks in a phase in parallel lanes.",agents:[]},lean_turbo_status:{description:"returns Lean Turbo configuration and active status for the current session",agents:[]},swarm_apply_patch:{description:"Apply a unified diff patch to workspace files with exact context matching, atomic writes, and path validation. Use standard unified diff format only — does NOT support *** Begin Patch / *** Update File payloads (use native apply_patch for those).",agents:["coder","test_engineer"]},external_skill_discover:{description:"Discover external skill candidates from configured sources. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_list:{description:"List external skill candidates in the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_inspect:{description:"Inspect a specific external skill candidate by ID. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_promote:{description:"Promote a validated external skill candidate to an active generated skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_reject:{description:"Reject an external skill candidate after evaluation. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_delete:{description:"Delete an external skill candidate from the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_revoke:{description:"Revoke a previously promoted external skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},epic_next_wave:{description:"Epic Mode: the single, idempotent way forward while an epic is open. Closes the active wave once every task is resolved (recording per-task outcomes and declared-vs-actual divergence, which Epic learning uses to plan later waves), keeps phases in order, and issues the next wave of disjoint tasks with dispatch instructions. Returns a status: dispatch | declare-scopes | in-progress | blocked | phase-ready-for-review | epic-complete | refused. Requires `epic.mode.enabled: true` and an epic opened by `/swarm epic start`.",agents:[]},epic_phase_review:{description:"Epic Mode phase readiness: dispatch a read-only phase reviewer, then (only if it APPROVES) a read-only phase critic over the completed phase; parse both verdicts from the agents and record them to .swarm/evidence/{phase}/epic-phase-review.json. Required by phase_complete while an epic is open for the current plan; re-run after any fix (evidence is bound to the plan and phase task evidence).",agents:[]}},TOOL_NAMES=Object.keys(TOOL_METADATA),TOOL_NAME_SET=new Set(TOOL_NAMES);TOOL_DESCRIPTIONS=Object.fromEntries(Object.entries(TOOL_METADATA).map(([name,meta])=>[name,meta.description])),AGENT_TOOL_MAP=(()=>{let map=Object.fromEntries(ALL_AGENT_NAMES.map((agent)=>[agent,[]]));for(let[name,meta]of Object.entries(TOOL_METADATA))for(let agent of meta.agents)map[agent].push(name);return map})()});function scanOverrideForDangerousKeys(value,path,depth){if(depth>=10)return;if(Array.isArray(value)){for(let i=0;i<value.length;i++)scanOverrideForDangerousKeys(value[i],`${path}[${i}]`,depth+1);return}if(typeof value!=="object"||value===null)return;for(let key of Object.keys(value)){if(DANGEROUS_MERGE_KEYS.has(key))throw new DangerousMergeKeyError(key,path);scanOverrideForDangerousKeys(value[key],`${path}.${key}`,depth+1)}}function deepMergeInternal(base,override,depth,path){if(depth>=10)throw Error("deepMerge exceeded maximum depth of 10");let result={...base};for(let key of Object.keys(override)){let baseVal=base[key],overrideVal=override[key];if(typeof baseVal==="object"&&baseVal!==null&&typeof overrideVal==="object"&&overrideVal!==null&&!Array.isArray(baseVal)&&!Array.isArray(overrideVal))result[key]=deepMergeInternal(baseVal,overrideVal,depth+1,`${path}.${key}`);else result[key]=overrideVal}return result}function deepMerge(base,override){if(!base)return override;if(!override)return base;return scanOverrideForDangerousKeys(override,"$",0),deepMergeInternal(base,override,0,"$")}var MAX_MERGE_DEPTH=10,DANGEROUS_MERGE_KEYS,DangerousMergeKeyError;var init_merge=__esm(()=>{DANGEROUS_MERGE_KEYS=new Set(["__proto__","constructor","prototype"]);DangerousMergeKeyError=class DangerousMergeKeyError extends Error{key;path;constructor(key,path){super(`deepMerge refused dangerous key "${key}" at "${path}": prototype-pollution carriers (__proto__/constructor/prototype) are never merged`);this.key=key;this.path=path;this.name="DangerousMergeKeyError"}}});function freezeSet(items,name="CLAUDE_CODE_NATIVE_COMMANDS"){let set=new Set(items),proxy=new Proxy(set,{get(target,prop){if(prop==="add"||prop==="delete"||prop==="clear")return()=>{throw TypeError(`${name} is readonly`)};if(prop==="forEach")return(callback,thisArg)=>{let wrapped=(v,k)=>callback.call(thisArg??void 0,v,k,proxy);return set.forEach(wrapped)};let value=Reflect.get(target,prop);return typeof value==="function"?value.bind(target):value},set(){throw TypeError(`${name} is readonly`)},deleteProperty(){throw TypeError(`${name} is readonly`)},defineProperty(){throw TypeError(`${name} is readonly`)},setPrototypeOf(){throw TypeError(`${name} is readonly`)}});return proxy}function isQAAgent(name){return QA_AGENTS.includes(name)}function isSubagent(name){return ALL_SUBAGENT_NAMES.includes(name)}function isLowCapabilityModel(modelId){let lower=(modelId||"").toLowerCase();return LOW_CAPABILITY_MODELS.some((substr)=>lower.includes(substr))}var OPENCODE_NATIVE_AGENTS,CLAUDE_CODE_NATIVE_COMMANDS,OPENCODE_NATIVE_COMMANDS,MEMORY_AGENT_TOOL_MAP,EXTERNAL_SKILL_TOOL_NAMES,EXTERNAL_SKILL_AGENT_TOOL_MAP,COUNCIL_TOOL_NAMES,COUNCIL_AGENT_TOOL_MAP,GENERAL_COUNCIL_TOOL_NAMES,GENERAL_COUNCIL_AGENT_TOOL_MAP,TURBO_TOOL_NAMES,TURBO_AGENT_TOOL_MAP,EPIC_TOOL_NAMES,EPIC_AGENT_TOOL_MAP,SKILL_TOOL_NAMES,SKILL_AGENT_TOOL_MAP,PR_REVIEW_CHILD_TOOL_NAMES,PR_REVIEW_CHILD_AGENT_TOOL_MAP,WRITE_TOOL_NAMES,SUMMARIZER_EXEMPT_TOOL_NAMES,DEFAULT_MODELS,DEFAULT_AGENT_CONFIGS,DEFAULT_SCORING_CONFIG,LOW_CAPABILITY_MODELS,TURBO_MODE_BANNER=`## \uD83D\uDE80 TURBO MODE ACTIVE
|
|
2
2
|
|
|
3
3
|
**Speed optimization enabled for this session.**
|
|
4
4
|
|
|
@@ -1259,7 +1259,7 @@ ${warnings.map((w)=>`Detected signal: ${w}`).join(`
|
|
|
1259
1259
|
`:"");writeLegacyStoreFile(legacyPath,legacyPayload),fs64.writeFileSync(projectionMarkerPath(legacyPath),"","utf-8"),legacyStat=fs64.statSync(legacyPath)}checkpoint2.migration.sourceBytes=legacyStat.size,checkpoint2.migration.scannedBytes=legacyStat.size,checkpoint2.migration.sourceMtimeMs=legacyStat.mtimeMs}catch{}}flushAuditEvents(directory,events,checkpoint2.sequence,checkpoint2.maintenance);let archiveEvent=maybeArchiveLegacy(directory,checkpoint2);if(archiveEvent)events.push(archiveEvent),checkpoint2.sequence+=1,_internals95.writeCheckpointFile(directory,checkpoint2),flushAuditEvents(directory,[archiveEvent],checkpoint2.sequence,checkpoint2.maintenance);cleanupStaleLegacyArchive(directory);let coordinationView=readCoordinationSubscriptions(directory);if(coordinationView!==null&&!isDeepStrictEqualByJson(coordinationView,loaded.view))persistCoordinationSubscriptions(directory,{...loaded.view});for(let kind of["compact","migrate-complete","archive","foreign-rebind","corrupt-quarantine"])if(events.some((event)=>event.kind===kind))emitHealthTelemetry(directory,kind,checkpoint2)}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_AGENT,STORE_LOCK_TASK,async()=>{if(canUseCoordinationWritePath(directory)){let view=readCoordinationSubscriptions(directory)??{},match2=Object.values(view).find((r)=>r.correlationId===correlationId&&r.status==="active");if(match2)return onSubscriptionCreated?.(directory,match2),match2;if(input.maxSubscriptions===void 0||input.maxSubscriptions>0){let limit=input.maxSubscriptions!==void 0?input.maxSubscriptions:PR_SUBSCRIPTION_LIMITS.defaultMaxActiveSubscriptions,activeCount=Object.values(view).filter((r)=>r.status==="active").length;if(activeCount>=limit)throw Error(`PR subscription limit reached: ${activeCount}/${limit}`)}let record4={correlationId,sessionID:input.sessionID,prNumber:input.prNumber,repoFullName:input.repoFullName,prUrl:input.prUrl,...input.forge?{forge:input.forge}:{},lastCheckedAt:now,isWatching:!0,hasUnaddressedEvents:!1,status:"active",createdAt:now,updatedAt:now,errorCount:0};return validateRecord3(record4),view[correlationId]=record4,persistCoordinationSubscriptions(directory,view,!0,[{kind:"subscribe",correlationId}]),onSubscriptionCreated?.(directory,record4),record4}let loaded=loadViewForWrite(directory),match=Object.values(loaded.view).find((r)=>r.correlationId===correlationId&&r.status==="active");if(match)return onSubscriptionCreated?.(directory,match),finalizeWrite(directory,loaded,[]),match;if(input.maxSubscriptions===void 0||input.maxSubscriptions>0){let limit=input.maxSubscriptions!==void 0?input.maxSubscriptions:PR_SUBSCRIPTION_LIMITS.defaultMaxActiveSubscriptions,activeCount=Object.values(loaded.view).filter((r)=>r.status==="active").length;if(activeCount>=limit)throw Error(`PR subscription limit reached: ${activeCount}/${limit}`)}let record3={correlationId,sessionID:input.sessionID,prNumber:input.prNumber,repoFullName:input.repoFullName,prUrl:input.prUrl,...input.forge?{forge:input.forge}:{},lastCheckedAt:now,isWatching:!0,hasUnaddressedEvents:!1,status:"active",createdAt:now,updatedAt:now,errorCount:0};return validateRecord3(record3),loaded.view[correlationId]=record3,loaded.dirty=!0,finalizeWrite(directory,loaded,[{kind:"subscribe",correlationId}]),onSubscriptionCreated?.(directory,record3),record3})}async function unsubscribe(directory,correlationId){if(!correlationId)return null;return withEvidenceLock(directory,PR_SUBSCRIPTIONS_FILE,STORE_LOCK_AGENT,STORE_LOCK_TASK,async()=>{if(canUseCoordinationWritePath(directory)){let view=readCoordinationSubscriptions(directory)??{},match2=Object.values(view).find((r)=>r.correlationId===correlationId&&r.status==="active");if(!match2)return null;let removed2={...match2,status:"removed",isWatching:!1,updatedAt:Date.now()};return view[correlationId]=removed2,persistCoordinationSubscriptions(directory,view,!0,[{kind:"unsubscribe",correlationId}]),removed2}let loaded=loadViewForWrite(directory),match=Object.values(loaded.view).find((r)=>r.correlationId===correlationId&&r.status==="active");if(!match)return finalizeWrite(directory,loaded,[]),null;let now=Date.now(),removed={...match,status:"removed",isWatching:!1,updatedAt:now};return loaded.view[correlationId]=removed,loaded.dirty=!0,finalizeWrite(directory,loaded,[{kind:"unsubscribe",correlationId}]),removed})}async function listActive(directory){let{view}=await loadViewForRead(directory);return Object.values(view).filter((r)=>r.status==="active")}async function lookupByPr(directory,repoFullName,prNumber){let{view}=await loadViewForRead(directory);for(let record3 of Object.values(view))if(record3.status==="active"&&record3.repoFullName===repoFullName&&record3.prNumber===prNumber)return record3;return null}async function findSubscriptionRecordForPrUrl(directory,key2){if(key2.repoFullName!==void 0&&key2.prNumber!==void 0){let record3=await lookupByPr(directory,key2.repoFullName,key2.prNumber);if(record3&&(!key2.sessionID||record3.sessionID===key2.sessionID)&&(key2.prUrl===void 0||record3.prUrl===key2.prUrl||subscriptionPrUrlMatches(record3,key2.prUrl)))return record3;if(!key2.sessionID)return null}if(key2.prUrl===void 0&&key2.repoFullName===void 0)return null;if(key2.prUrl===void 0){let active2=await listActive(directory);for(let record3 of active2){if(key2.sessionID&&record3.sessionID!==key2.sessionID)continue;if(record3.repoFullName===key2.repoFullName&&record3.prNumber===key2.prNumber)return record3}return null}let active=await listActive(directory);for(let record3 of active){if(key2.sessionID&&record3.sessionID!==key2.sessionID)continue;if(record3.prUrl===key2.prUrl||subscriptionPrUrlMatches(record3,key2.prUrl))return record3}return null}function subscriptionPrUrlMatches(record3,prUrl){let left=canonicalForgePrUrl(record3.prUrl,record3.forge),right=canonicalForgePrUrl(prUrl,record3.forge);return left!==null&&left===right}async function updateSnapshot(directory,correlationId,updates){if(!correlationId)return null;return withEvidenceLock(directory,PR_SUBSCRIPTIONS_FILE,STORE_LOCK_AGENT,STORE_LOCK_TASK,async()=>{let existingCoordination=readCoordinationSubscriptions(directory);if(existingCoordination!==null&&!fileExistsStrict(storePath3(directory))&&!hasLegacyReconciliationArtifacts(directory)){let match2=Object.values(existingCoordination).find((r)=>r.correlationId===correlationId&&r.status==="active");if(!match2)return null;if(!snapshotUpdateHasChanges(match2,updates))return match2;let updated2={...match2,...updates,correlationId,sessionID:match2.sessionID,repoFullName:match2.repoFullName,prNumber:match2.prNumber,prUrl:match2.prUrl,createdAt:match2.createdAt,updatedAt:Date.now()};return validateRecord3(updated2),existingCoordination[correlationId]=updated2,persistCoordinationSubscriptions(directory,existingCoordination),updated2}if(canUseCoordinationWritePath(directory)){let view=readCoordinationSubscriptions(directory)??{},match2=Object.values(view).find((r)=>r.correlationId===correlationId&&r.status==="active");if(!match2)return null;if(!snapshotUpdateHasChanges(match2,updates))return match2;let updated2={...match2,...updates,correlationId,sessionID:match2.sessionID,repoFullName:match2.repoFullName,prNumber:match2.prNumber,prUrl:match2.prUrl,createdAt:match2.createdAt,updatedAt:Date.now()};return validateRecord3(updated2),view[correlationId]=updated2,persistCoordinationSubscriptions(directory,view),updated2}let loaded=loadViewForWrite(directory),match=Object.values(loaded.view).find((r)=>r.correlationId===correlationId&&r.status==="active");if(!match)return finalizeWrite(directory,loaded,[]),null;if(!snapshotUpdateHasChanges(match,updates))return finalizeWrite(directory,loaded,[]),match;let updated={...match,...updates,correlationId,sessionID:match.sessionID,repoFullName:match.repoFullName,prNumber:match.prNumber,prUrl:match.prUrl,createdAt:match.createdAt,updatedAt:Date.now()};return validateRecord3(updated),loaded.view[correlationId]=updated,loaded.dirty=!0,finalizeWrite(directory,loaded,[]),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_AGENT,STORE_LOCK_TASK,async()=>{if(canUseCoordinationWritePath(directory)){let view=readCoordinationSubscriptions(directory)??{},swept2=0,expiredCorrelationIds=[],now2=Date.now();for(let record3 of Object.values(view)){if(record3.status!=="active")continue;let prKey=`${record3.repoFullName}::${record3.prNumber}`,isMerged=mergedPrs?.has(prKey)??!1,isStale=now2-record3.updatedAt>ttlMs;if(isMerged||isStale&&!record3.hasUnaddressedEvents)view[record3.correlationId]={...record3,status:"expired",isWatching:!1,updatedAt:now2},expiredCorrelationIds.push(record3.correlationId),swept2+=1}if(swept2>0)persistCoordinationSubscriptions(directory,view,!0,expiredCorrelationIds.map((correlationId)=>({kind:"expired",correlationId})));return swept2}let loaded=loadViewForWrite(directory),opAudit=[],swept=0;for(let record3 of Object.values(loaded.view)){if(record3.status!=="active")continue;let prKey=`${record3.repoFullName}::${record3.prNumber}`,isMerged=mergedPrs?.has(prKey)??!1,isStale=now-record3.updatedAt>ttlMs;if(isMerged){loaded.view[record3.correlationId]={...record3,status:"expired",isWatching:!1,updatedAt:now},swept+=1,opAudit.push({kind:"expired",correlationId:record3.correlationId}),loaded.dirty=!0,log(`[pr-monitor] Swept subscription: merged/closed: ${prKey}`);continue}if(isStale&&!record3.hasUnaddressedEvents)loaded.view[record3.correlationId]={...record3,status:"expired",isWatching:!1,updatedAt:now},swept+=1,opAudit.push({kind:"expired",correlationId:record3.correlationId}),loaded.dirty=!0,log(`[pr-monitor] Swept subscription: stale (TTL ${ttlDays}d): ${prKey}`)}return finalizeWrite(directory,loaded,opAudit),swept})}catch(err){return log(`[pr-monitor] sweepStale failed: ${err instanceof Error?err.message:String(err)}`),0}}async function getPrSubscriptionHealth(directory){try{let coordinationView=readCoordinationSubscriptions(directory),read=readCheckpoint(directory),migrationPending=read.kind==="ok"&&sameProjectRoot(read.value.rootPath,directory)&&read.value.migration?.done===!1;if(coordinationView!==null&&Object.keys(coordinationView).length>0&&!migrationPending){let audit2=auditStats(directory),archiveBytes2=fileSizeOrNull(legacyArchivePath(directory))??0,checkpointBytes2=fileSizeOrNull(checkpointPath(directory))??0,health2=healthFromView(coordinationView,buildCoordinationProjectionCheckpoint(directory,coordinationView));return health2.recoverySource="checkpoint",applyFileStats(health2,checkpointBytes2,audit2,archiveBytes2),health2}let audit=auditStats(directory),archiveBytes=fileSizeOrNull(legacyArchivePath(directory))??0,checkpointBytes=fileSizeOrNull(checkpointPath(directory))??0,legacySize=fileSizeOrNull(storePath3(directory)),legacyOverLimit=legacySize!==null&&legacySize>PR_SUBSCRIPTION_LIMITS.legacySourceMaxBytes,health;if(read.kind==="ok"&&!sameProjectRoot(read.value.rootPath,directory))health=emptyHealth2(),health.recoverySource="foreign";else if(read.kind==="invalid"){if(legacySize!==null&&!legacyOverLimit){let fold=foldLegacyRegion(storePath3(directory),0,Number.MAX_SAFE_INTEGER),view={};if(!fold.ioError)mergeFoldedRecords(view,fold.folded);health=healthFromView(view,freshCheckpoint(directory)),health.corruptLegacyRecords=fold.corruptLines}else health=emptyHealth2();health.recoverySource="corrupt-recovered"}else if(read.kind==="absent"){if(legacySize===null||legacyOverLimit)health=emptyHealth2();else{let fold=foldLegacyRegion(storePath3(directory),0,Number.MAX_SAFE_INTEGER),view={};if(!fold.ioError)mergeFoldedRecords(view,fold.folded);health=healthFromView(view,freshCheckpoint(directory)),health.corruptLegacyRecords=fold.corruptLines}health.recoverySource=legacySize===null?"empty":"legacy-log"}else{let pendingCheckpoint=migrationPending&&coordinationView!==null?(()=>{let merged=cloneCheckpoint(read.value);return merged.records={...merged.records,...coordinationView},merged})():read.value,overlaid=overlayLegacy(directory,pendingCheckpoint);health=healthFromView(overlaid.view,read.value),health.recoverySource=overlaid.usedLegacy?"checkpoint+legacy":"checkpoint"}return health.legacyOverLimit=legacyOverLimit,applyFileStats(health,checkpointBytes,audit,archiveBytes),health}catch(err){return log(`[pr-monitor] getPrSubscriptionHealth failed: ${storageErrorCode(err)}`),emptyHealth2()}}function applyFileStats(health,checkpointBytes,audit,archiveBytes){health.checkpointBytes=checkpointBytes,health.pressurePct=checkpointBytes===0?0:Math.round(checkpointBytes/health.checkpointLimitBytes*1000)/10,health.auditLines=audit.lines,health.auditBytes=audit.bytes,health.legacyArchiveBytes=archiveBytes}function emptyHealth2(){return{schemaVersion:1,sequence:0,checkpointAgeMs:null,checkpointBytes:0,checkpointLimitBytes:PR_SUBSCRIPTION_LIMITS.maxCheckpointBytes,pressurePct:0,activeCount:0,removedCount:0,expiredCount:0,terminalSummary:{removed:0,expired:0,lastTerminalAt:null},auditLines:0,auditBytes:0,auditLimitBytes:PR_SUBSCRIPTION_LIMITS.auditMaxBytesHigh,compactions:0,corruptLegacyRecords:0,droppedAuditTransitions:0,resets:0,recoverySource:"empty",migration:null,legacyArchiveBytes:0,legacyOverLimit:!1}}function healthFromView(view,checkpoint2){let records=Object.values(view),health=emptyHealth2();return health.sequence=checkpoint2.sequence,health.checkpointAgeMs=checkpoint2.sequence>0?Date.now()-checkpoint2.updatedAt:null,health.activeCount=records.filter((r)=>r.status==="active").length,health.removedCount=records.filter((r)=>r.status==="removed").length,health.expiredCount=records.filter((r)=>r.status==="expired").length,health.terminalSummary={...checkpoint2.terminalSummary},health.compactions=checkpoint2.maintenance.compactions,health.corruptLegacyRecords=checkpoint2.maintenance.corruptLegacyRecords,health.droppedAuditTransitions=checkpoint2.maintenance.droppedAuditTransitions,health.resets=checkpoint2.maintenance.resets,health.migration=checkpoint2.migration?{done:checkpoint2.migration.done,scannedBytes:checkpoint2.migration.scannedBytes,sourceBytes:checkpoint2.migration.sourceBytes}:null,health}var PR_SUBSCRIPTIONS_FILE="pr-monitor/subscriptions.jsonl",PR_SUBSCRIPTIONS_CHECKPOINT_FILE="pr-monitor/subscriptions.checkpoint.json",PR_SUBSCRIPTIONS_AUDIT_FILE="pr-monitor/subscriptions.audit.jsonl",LEGACY_ARCHIVE_FILE="pr-monitor/subscriptions.legacy.jsonl",FOREIGN_CHECKPOINT_FILE="pr-monitor/subscriptions.checkpoint.foreign.json",CORRUPT_CHECKPOINT_FILE="pr-monitor/subscriptions.checkpoint.corrupt.json",FOREIGN_LEGACY_FILE="pr-monitor/subscriptions.legacy.foreign.jsonl",PR_SUBSCRIPTION_COORDINATION_NAMESPACE="background.pr-subscription",STORE_LOCK_AGENT="pr-monitor",STORE_LOCK_TASK="pr-subscriptions",PR_SUBSCRIPTION_LIMITS,onSubscriptionCreated=null,prMonitorWorkerHandlers,MAX_PR_MONITOR_WORKER_HANDLERS=64,RecordSchema,TerminalSummarySchema,MigrationSchema,MaintenanceSchema,CheckpointSchema,PrSubscriptionCapacityError,legacyOverLimitWarned,migrationCapacityWarned,bootstrapAttempted,_internals95;var init_pr_subscriptions=__esm(()=>{init_zod();init_db();init_lock();init_learning_health();init_utils2();init_forge_provider();init_telemetry();init_utils();init_atomic_write();init_canonical_root();PR_SUBSCRIPTION_LIMITS={readChunkBytes:65536,maxRecordBytes:65536,migrationChunkBytes:1048576,migrationMaxBytesPerOperation:8388608,legacySourceMaxBytes:67108864,defaultMaxActiveSubscriptions:20,maxCheckpointRecords:512,maxCheckpointBytes:262144,checkpointHardReadBytes:1048576,terminalRecordsHigh:60,terminalRecordsLow:30,terminalMaxAgeMs:2592000000,auditMaxLinesHigh:500,auditMaxLinesLow:250,auditMaxBytesHigh:131072,auditMaxBytesLow:65536,legacyArchiveTtlMs:604800000,bootstrapLockTimeoutMs:5000};prMonitorWorkerHandlers=new Map;RecordSchema=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(/^[^/\s]+(?:\/[^/\s]+)+$/,"Must be owner/repo format (GitLab nested namespaces allowed)"),prUrl:exports_external.string().min(1),forge:exports_external.object({provider:exports_external.literal("gitlab"),host:exports_external.string().min(1)}).optional(),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().superRefine((record3,ctx)=>{if(isForgePrUrl(record3.prUrl))return;if(record3.forge&&isForgePrUrl(record3.prUrl,{provider:record3.forge.provider,host:record3.forge.host}))return;ctx.addIssue({code:exports_external.ZodIssueCode.custom,path:["prUrl"],message:"Must be a valid PR URL (GitHub /pull/N or GitLab /-/merge_requests/N)"})}),TerminalSummarySchema=exports_external.object({removed:exports_external.number().int().min(0),expired:exports_external.number().int().min(0),lastTerminalAt:exports_external.number().int().nullable()}).strict(),MigrationSchema=exports_external.object({scannedBytes:exports_external.number().int().nonnegative(),sourceBytes:exports_external.number().int().nonnegative(),sourceMtimeMs:exports_external.number().nonnegative(),corruptLines:exports_external.number().int().nonnegative(),discardingOversizeLine:exports_external.boolean().optional().default(!1),baselineRecords:exports_external.record(exports_external.string(),RecordSchema).optional().default({}),baselineTerminalSummary:TerminalSummarySchema.optional().default({removed:0,expired:0,lastTerminalAt:null}),done:exports_external.boolean(),archived:exports_external.boolean(),startedAt:exports_external.number().int().nonnegative()}).strict(),MaintenanceSchema=exports_external.object({compactions:exports_external.number().int().nonnegative(),droppedAuditTransitions:exports_external.number().int().nonnegative(),corruptLegacyRecords:exports_external.number().int().nonnegative(),lastCompactedAt:exports_external.number().int().nullable(),resets:exports_external.number().int().nonnegative()}).strict(),CheckpointSchema=exports_external.object({schemaVersion:exports_external.literal(1),sequence:exports_external.number().int().positive(),rootPath:exports_external.string().min(1).max(4096),updatedAt:exports_external.number().int().nonnegative(),records:exports_external.record(exports_external.string(),RecordSchema),terminalSummary:TerminalSummarySchema,migration:MigrationSchema.nullable(),maintenance:MaintenanceSchema}).strict();PrSubscriptionCapacityError=class PrSubscriptionCapacityError extends Error{constructor(message){super(message);this.name="PrSubscriptionCapacityError"}};legacyOverLimitWarned=new Map;migrationCapacityWarned=new Map;bootstrapAttempted=new Map;_internals95={afterCheckpointFstat:(_filePath)=>{},archiveStatSync:fs64.statSync,auditCompactionWrite:atomicWriteSwarmFileSync,beforeBootstrapLock:(_directory2)=>{},beforeArchiveLegacy:(_directory2)=>{},beforeArchiveRename:(_directory2)=>{},foldLegacyRegion,legacyCloseSync:fs64.closeSync,legacyFstatSync:fs64.fstatSync,mergeFoldedRecords,readSync:fs64.readSync,renameWithRetry:renameWithRetry5,sameProjectRoot,statSync:fs64.statSync,writeCheckpointFile}});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,setFinalPromptPressure:()=>setFinalPromptPressure,setFinalAccountingWarningBand:()=>setFinalAccountingWarningBand,setDispatchParent:()=>setDispatchParent,setCriticalShownIds:()=>setCriticalShownIds,reviewerScopeGenerationHasDeclaredOverlap:()=>reviewerScopeGenerationHasDeclaredOverlap,resolveSessionWorkspaceDirectory:()=>resolveSessionWorkspaceDirectory,resolveInitialTurboMode:()=>resolveInitialTurboMode,resolveDispatchParent:()=>resolveDispatchParent,resetSwarmStatePreservingSingletons:()=>resetSwarmStatePreservingSingletons,resetSwarmState:()=>resetSwarmState,resetModifiedFilesForTask:()=>resetModifiedFilesForTask,reserveStageBRouteEvidence:()=>reserveStageBRouteEvidence,rehydrateSessionFromDisk:()=>rehydrateSessionFromDisk,rehydratePrSubscriptions:()=>rehydratePrSubscriptions,recordStageBRouteEvidence:()=>recordStageBRouteEvidence,recordStageBCompletion:()=>recordStageBCompletion,recordSessionWorkspaceRoot:()=>recordSessionWorkspaceRoot,recordReviewerScopeGenerationFileFingerprint:()=>recordReviewerScopeGenerationFileFingerprint,recordReviewerScopeGenerationFile:()=>recordReviewerScopeGenerationFile,recordReviewerScopeGenerationCaptureFailure:()=>recordReviewerScopeGenerationCaptureFailure,recordPhaseAgentDispatch:()=>recordPhaseAgentDispatch,recordPendingDispatchAuthorization:()=>recordPendingDispatchAuthorization,recordModifiedFilesForTask:()=>recordModifiedFilesForTask,recordModifiedFileForTask:()=>recordModifiedFileForTask,pruneOldWindows:()=>pruneOldWindows,peekReviewerScopeGenerationClaim:()=>peekReviewerScopeGenerationClaim,peekReviewerScopeGenerationByStatus:()=>peekReviewerScopeGenerationByStatus,peekReadyReviewerScopeGeneration:()=>peekReadyReviewerScopeGeneration,maybeSweepStaleSessions:()=>maybeSweepStaleSessions,markStageBRouteRequired:()=>markStageBRouteRequired,markReviewerScopeGenerationReady:()=>markReviewerScopeGenerationReady,markReviewerScopeGenerationNoChange:()=>markReviewerScopeGenerationNoChange,markReviewerScopeGenerationMergebackPending:()=>markReviewerScopeGenerationMergebackPending,isStageBRouteRequired:()=>isStageBRouteRequired,isReviewerScopeGenerationCurrent:()=>isReviewerScopeGenerationCurrent,isCouncilGateActive:()=>isCouncilGateActive,incrementGateDenialCount:()=>incrementGateDenialCount,hasModifiedFilesForTask:()=>hasModifiedFilesForTask,hasBothStageBCompletions:()=>hasBothStageBCompletions,hasActiveTurboMode:()=>hasActiveTurboMode,hasActiveLeanTurbo:()=>hasActiveLeanTurbo,hasActiveFullAuto:()=>hasActiveFullAuto,getTaskState:()=>getTaskState,getStageBRouteEvidence:()=>getStageBRouteEvidence,getSessionEnvironment:()=>getSessionEnvironment,getSessionBudgetTokens:()=>getSessionBudgetTokens,getSessionBudgetPct:()=>getSessionBudgetPct,getRunContext:()=>getRunContext,getReviewerScopeOwnershipHistory:()=>getReviewerScopeOwnershipHistory,getReviewerScopeGenerationForCoderCall:()=>getReviewerScopeGenerationForCoderCall,getResolvedAutoProceed:()=>getResolvedAutoProceed,getRehydrationCache:()=>getRehydrationCache,getModifiedFilesForTask:()=>getModifiedFilesForTask,getLiveContextWindow:()=>getLiveContextWindow,getLiveContextModelIdentity:()=>getLiveContextModelIdentity,getFinalPromptPressure:()=>getFinalPromptPressure,getFinalAccountingWarningBand:()=>getFinalAccountingWarningBand,getDisplayFinalPromptPressure:()=>getDisplayFinalPromptPressure,getDisplayBudget:()=>getDisplayBudget,getAgentSession:()=>getAgentSession,getActiveWindow:()=>getActiveWindow,getActiveFullAutoSessionID:()=>getActiveFullAutoSessionID,ensureSessionEnvironment:()=>ensureSessionEnvironment,ensureAgentSession:()=>ensureAgentSession,endAgentSession:()=>endAgentSession,discardReviewerScopeGenerationForCoderCall:()=>discardReviewerScopeGenerationForCoderCall,discardReviewerScopeGenerationClaim:()=>discardReviewerScopeGenerationClaim,defaultRunContext:()=>defaultRunContext,completeModifiedFilesForTask:()=>completeModifiedFilesForTask,clearStageBRouteRequired:()=>clearStageBRouteRequired,clearStageBRouteEvidence:()=>clearStageBRouteEvidence,clearGateDenialCount:()=>clearGateDenialCount,clearFinalAccountingWarningBands:()=>clearFinalAccountingWarningBands,clearDispatchLineageForSession:()=>clearDispatchLineageForSession,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:()=>_internals96,REVIEWER_SCOPE_GENERATION_TTL_MS:()=>REVIEWER_SCOPE_GENERATION_TTL_MS,PENDING_DISPATCH_AUTHORIZATION_TTL_MS:()=>PENDING_DISPATCH_AUTHORIZATION_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_DISPATCH_PARENTS:()=>MAX_TRACKED_DISPATCH_PARENTS,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 fs65 from"node:fs/promises";import*as path105 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.finalPromptPressureBySession.clear(),clearAllTurnLedgers(),swarmState.finalAccountingWarningBandsBySession.clear(),swarmState.liveContextWindows.clear(),swarmState.agentSessions.clear(),clearSnapshotSessionOwnerships(),_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=[],swarmState.dispatchParentByChildSession.clear(),swarmState.pendingDispatchAuthorizations=[],clearHydrationOwnershipState(),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 pruneExpiredPendingDispatchAuthorizations(now){let pendings=swarmState.pendingDispatchAuthorizations;if(pendings.length===0)return;let alive=pendings.filter((pending)=>now-pending.recordedAt<=PENDING_DISPATCH_AUTHORIZATION_TTL_MS);if(alive.length!==pendings.length)swarmState.pendingDispatchAuthorizations=alive}function recordPendingDispatchAuthorization(parentSessionId,agentName){if(!parentSessionId||!agentName)return;let now=Date.now();if(pruneExpiredPendingDispatchAuthorizations(now),swarmState.pendingDispatchAuthorizations.push({parentSessionId,agentName:stripKnownSwarmPrefix(agentName).toLowerCase(),recordedAt:now}),swarmState.pendingDispatchAuthorizations.length>MAX_TRACKED_DISPATCH_PARENTS)swarmState.pendingDispatchAuthorizations.splice(0,swarmState.pendingDispatchAuthorizations.length-MAX_TRACKED_DISPATCH_PARENTS)}function setDispatchParentEntry(childSessionId,parentSessionId){if(!childSessionId||!parentSessionId)return;if(swarmState.dispatchParentByChildSession.delete(childSessionId),swarmState.dispatchParentByChildSession.set(childSessionId,parentSessionId),swarmState.dispatchParentByChildSession.size>MAX_TRACKED_DISPATCH_PARENTS){let oldestKey=swarmState.dispatchParentByChildSession.keys().next().value;if(oldestKey!==void 0)swarmState.dispatchParentByChildSession.delete(oldestKey)}}function setDispatchParent(childSessionId,parentSessionId){if(!childSessionId||!parentSessionId)return;setDispatchParentEntry(childSessionId,parentSessionId);let now=Date.now();pruneExpiredPendingDispatchAuthorizations(now);let normalizedParent=parentSessionId,pendings=swarmState.pendingDispatchAuthorizations,matchIndex=pendings.findIndex((pending)=>pending.parentSessionId===normalizedParent);if(matchIndex>=0)pendings.splice(matchIndex,1)}function resolveDispatchParent(childSessionId){return swarmState.dispatchParentByChildSession.get(childSessionId)}function adoptPendingDispatchAuthorization(newSessionId,agentName){if(swarmState.dispatchParentByChildSession.has(newSessionId))return;let normalizedRole=stripKnownSwarmPrefix(agentName).toLowerCase();if(!normalizedRole)return;let now=Date.now();pruneExpiredPendingDispatchAuthorizations(now);let pendings=swarmState.pendingDispatchAuthorizations,matchIndex=pendings.findIndex((pending)=>pending.agentName===normalizedRole);if(matchIndex<0)return;let[adopted]=pendings.splice(matchIndex,1);if(!adopted)return;setDispatchParentEntry(newSessionId,adopted.parentSessionId)}function clearDispatchLineageForSession(sessionId){swarmState.dispatchParentByChildSession.delete(sessionId);for(let[child,parent]of swarmState.dispatchParentByChildSession)if(parent===sessionId)swarmState.dispatchParentByChildSession.delete(child);swarmState.pendingDispatchAuthorizations=swarmState.pendingDispatchAuthorizations.filter((pending)=>pending.parentSessionId!==sessionId)}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[key2,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(key2)}}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[key3,entry]of generations)if(entry.taskId===input.taskId&&entry.status!=="claimed")generations.delete(key3);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 key2=reviewerScopeGenerationKey(generation.taskId,generation.coderCallID,generation.generation);return generations.set(key2,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 key2=reviewerScopeGenerationKey(generation.taskId,generation.coderCallID,generation.generation);return generations.delete(key2),!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((file3)=>generation.modifiedFileFingerprints.some((entry)=>entry.file===file3))))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[key2,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(key2),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((file3)=>declared.has(file3)))}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(),directory){let staleIds=[];for(let[id,session]of swarmState.agentSessions)if(now-session.lastToolCallTime>staleDurationMs){if(directory&&isSnapshotSessionOwnedLocally(id)&&!isSnapshotSessionAuthoritativelyStale(directory,id,staleDurationMs,now))continue;staleIds.push(id)}for(let id of staleIds){if(directory&&isSnapshotSessionOwnedLocally(id)){try{deleteSnapshotSessionRows(directory,id,"stale")}catch(error93){warn("[state] durable stale-session teardown failed:",error93 instanceof Error?error93.message:String(error93))}try{clearOverrideForSession(directory,id)}catch(error93){warn("[state] durable stale-session override teardown failed:",error93 instanceof Error?error93.message:String(error93))}}releaseSnapshotSessionOwnership(id),swarmState.agentSessions.delete(id),swarmState.delegationChains.delete(id),clearDispatchLineageForSession(id),swarmState.activeAgent.delete(id)}return staleIds}function maybeSweepStaleSessions(staleDurationMs=STALE_SESSION_TTL_MS,now=Date.now(),directory){if(now-_lastIdleSweepAtMs<IDLE_SWEEP_COOLDOWN_MS)return[];return _lastIdleSweepAtMs=now,sweepStaleSessions(staleDurationMs,now,directory)}function resolveInitialTurboMode(directory){if(!directory)return!1;try{return _internals96.loadPluginConfigWithMeta(directory).config.turbo_mode===!0&&!(epicSentinelExists(directory)&&isEpicOpenForProject(directory))}catch{return!1}}function startAgentSession(sessionId,agentName,staleDurationMs=STALE_SESSION_TTL_MS,directory){let now=Date.now();if(claimSnapshotSessionOwnership(sessionId,!0),typeof directory==="string"&&directory.trim()==="")directory=void 0;let owningProjectKey=directory?hydrationProjectKey(directory):void 0,hydrationAuthority=owningProjectKey?captureCurrentHydrationAuthority(owningProjectKey):void 0,hydrationStamp=owningProjectKey?nextSessionHydrationStamp(owningProjectKey):void 0,hydrationAuthorityEpoch2=hydrationAuthority?.authorityEpoch;sweepStaleSessions(staleDurationMs,now,directory);let initialTurboMode=resolveInitialTurboMode(directory),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,stageBRouteEvidence:new Map,stageBRouteRequiredTasks:new Set,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:initialTurboMode,turboStrategy:void 0,leanTurboActive:!1,leanTurboCurrentPhase:void 0,maxConcurrencyOverride:void 0,qaGateSessionOverrides:{},fullAutoMode:!1,fullAutoInteractionCount:0,fullAutoDeadlockCount:0,fullAutoLastQuestionHash:null,model_fallback_index:0,modelFallbackExhausted:!1,coderRevisions:0,revisionLimitHit:!1,loopDetectionWindow:[],pendingAdvisoryMessages:[],sessionRehydratedAt:0,owningProjectKey,hydrationStamp,hydrationAuthorityEpoch:hydrationAuthorityEpoch2,prmPatternCounts:new Map,prmEscalationLevel:0,prmLastPatternDetected:null,prmTrajectoryStep:0,prmHardStopPending:!1,prmHardStopInjectPending:!1,prmInjectedAdvisoryKeys:new Set,prmStruckEpisodes:new Map,prmLadderCounts:new Map,prmEpisodes:new Map,prmEpisodeGeneration:0,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),_internals96.applyRehydrationCache(sessionState),directory){let liveSession=sessionState,shouldCommitRehydration=()=>hydrationAuthority!==void 0&&isHydrationAuthorityCurrent(hydrationAuthority)&&swarmState.agentSessions.get(sessionId)===liveSession,rehydrationPromise;rehydrationPromise=_internals96.rehydrateSessionFromDisk(directory,sessionState,shouldCommitRehydration).then(async()=>{if(!shouldCommitRehydration())return;try{let subscriptions=await _internals96.rehydratePrSubscriptions(sessionId,directory);if(!shouldCommitRehydration())return;sessionState.prSubscriptions=subscriptions}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,directory){if(directory){try{deleteSnapshotSessionRows(directory,sessionId)}catch(error93){warn("[state] durable snapshot session teardown failed:",error93 instanceof Error?error93.message:String(error93))}try{clearOverrideForSession(directory,sessionId)}catch(error93){warn("[state] durable session override teardown failed:",error93 instanceof Error?error93.message:String(error93))}}releaseSnapshotSessionOwnership(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),clearDispatchLineageForSession(sessionId),clearRealtimeLearningNudgeSession(sessionId),resetSessionQueue(sessionId),resetPrmPatternSupport(sessionId)}function getAgentSession(sessionId){return swarmState.agentSessions.get(sessionId)}function ensureAgentSession(sessionId,agentName,directory){let now=Date.now();claimSnapshotSessionOwnership(sessionId,!0);let 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.stageBRouteEvidence)session.stageBRouteEvidence=new Map;if(!session.stageBRouteRequiredTasks)session.stageBRouteRequiredTasks=new Set;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.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(STALE_SESSION_TTL_MS,now,directory),session}if(_internals96.startAgentSession(sessionId,agentName??"unknown",7200000,directory),session=swarmState.agentSessions.get(sessionId),!session)throw Error(`Failed to create guardrail session for ${sessionId}`);if(agentName&&agentName!=="unknown")adoptPendingDispatchAuthorization(sessionId,agentName);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,"invocation");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},key2=`${stripped}:${newId}`;return session.windows[key2]=window2,pruneOldWindows(sessionId,86400000,50),window2}function getActiveWindow(sessionId){let session=swarmState.agentSessions.get(sessionId);if(!session||!session.windows)return;let key2=`${stripKnownSwarmPrefix(session.agentName)}:${session.activeInvocationId}`;return session.windows[key2]}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,workspaceDirectory){if(!ensureModifiedFileTaskSlot(session,taskId))return!1;let normalized=[...new Set(files.map((file3)=>canonicalAttributionPath(file3,workspaceDirectory)).filter((file3)=>file3!==null))];if(session.modifiedFilesByTask.set(taskId,normalized),session.currentTaskId===taskId)projectModifiedFilesForActiveTask(session);return!0}function recordModifiedFileForTask(session,taskId,file3,workspaceDirectory){if(typeof file3!=="string"||file3.trim().length===0)return!1;if(!ensureModifiedFileTaskSlot(session,taskId))return!1;let canonical=canonicalAttributionPath(file3,workspaceDirectory);if(canonical===null)return!0;let entries=ensureModifiedFilesByTask(session),current=entries.get(taskId)??[];if(current.includes(canonical))return!0;if(entries.set(taskId,[...current,canonical]),session.currentTaskId===taskId)projectModifiedFilesForActiveTask(session);return!0}function hasModifiedFilesForTask(session,taskId){if(!session)return!1;if(!isValidTaskId2(taskId))return!1;if(!(session.modifiedFilesByTask instanceof Map))return!1;return session.modifiedFilesByTask.has(taskId)}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){let projectRoot=session.owningProjectKey;if(projectRoot===void 0||!isEpicOpenForProject(projectRoot))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,overrides2){let cache2=ensureTaskWorkflowCache(session),existing=cache2.get(taskId);cache2.set(taskId,{generation:overrides2.generation??existing?.generation??0,retryCount:overrides2.retryCount??existing?.retryCount??0,lastOutcome:overrides2.lastOutcome??existing?.lastOutcome??"none",lastTransitionId:overrides2.lastTransitionId??existing?.lastTransitionId??null,updatedAt:overrides2.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),clearStageBRouteEvidence(session,taskId),clearStageBRouteRequired(session,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,_directory2,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 reserveStageBRouteEvidence(session,taskId,evidence){if(!isValidTaskId2(taskId))return null;if(!session.stageBRouteEvidence)session.stageBRouteEvidence=new Map;let entries=session.stageBRouteEvidence.get(taskId)??[],dispatchIdentity=(entry)=>{if(!entry.callId||!entry.childSessionId||typeof entry.generation!=="number")return null;return[entry.role,entry.sessionId??"",entry.taskId??"",entry.callId,entry.childSessionId,String(entry.generation)].join("\x00")},incomingDispatchIdentity=dispatchIdentity(evidence),existingIndex=entries.findIndex((entry)=>entry.role===evidence.role&&(incomingDispatchIdentity!==null&&dispatchIdentity(entry)===incomingDispatchIdentity||incomingDispatchIdentity===null&&dispatchIdentity(entry)===null&&entry.identity===evidence.identity));if(existingIndex>=0){let previousEntry=entries[existingIndex],reservedEntry2={...evidence};return entries[existingIndex]=reservedEntry2,session.stageBRouteEvidence.set(taskId,entries),()=>{if(session.stageBRouteEvidence?.get(taskId)!==entries)return;let reservedIndex=entries.indexOf(reservedEntry2);if(reservedIndex<0)return;entries[reservedIndex]=previousEntry}}if(entries.length>=32)return null;let reservedEntry={...evidence};return entries.push(reservedEntry),session.stageBRouteEvidence.set(taskId,entries),()=>{if(session.stageBRouteEvidence?.get(taskId)!==entries)return;let reservedIndex=entries.indexOf(reservedEntry);if(reservedIndex<0)return;if(entries.splice(reservedIndex,1),entries.length===0)session.stageBRouteEvidence?.delete(taskId)}}function recordStageBRouteEvidence(session,taskId,evidence){return reserveStageBRouteEvidence(session,taskId,evidence)!==null}function getStageBRouteEvidence(session,taskId){return(session.stageBRouteEvidence?.get(taskId)??[]).map((entry)=>({...entry}))}function clearStageBRouteEvidence(session,taskId){session.stageBRouteEvidence?.delete(taskId)}function markStageBRouteRequired(session,taskId){if(!session.stageBRouteRequiredTasks)session.stageBRouteRequiredTasks=new Set;session.stageBRouteRequiredTasks.add(taskId)}function isStageBRouteRequired(session,taskId){return session.stageBRouteRequiredTasks?.has(taskId)===!0}function clearStageBRouteRequired(session,taskId){session.stageBRouteRequiredTasks?.delete(taskId)}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(evidence){let snapshot=getTaskWorkflowSnapshot(evidence);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=path105.join(directory,".swarm","plan.json"),content=await fs65.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=path105.join(directory,".swarm","evidence"),entries=await fs65.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=path105.join(evidenceDir,entry.name),content=await fs65.readFile(filePath,"utf-8"),parsed=parseTaskEvidence(content,taskId);evidenceMap.set(taskId,parsed)}catch{}}}catch{}return evidenceMap}async function buildRehydrationCache(directory,options){let projectKey=hydrationProjectKey(directory),buildAuthority=captureCurrentHydrationAuthority(projectKey),planTaskStates=new Map,plan=options&&Object.hasOwn(options,"planOverride")?options.planOverride:await readPlanFromDisk(directory),cachePlan=plan??null;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}if(options?.shouldCommit&&!options.shouldCommit()||!isHydrationAuthorityCurrent(buildAuthority))return{committed:!1,reason:"superseded"};return setRehydrationCache(projectKey,{planTaskStates,evidenceMap,taskIdentityContext:{plan:cachePlan,councilConfig}},buildAuthority)?{committed:!0}:{committed:!1,reason:"superseded"}}function applyRehydrationCache(session,projectKey){let resolvedKey=projectKey??session.owningProjectKey;if(!resolvedKey)return;let cache2=getRehydrationCache(resolvedKey);if(!cache2)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}=cache2;for(let[taskId,planState]of planTaskStates){let existingState=session.taskWorkflowStates.get(taskId),existingCache=ensureTaskWorkflowCache(session).get(taskId),evidence=evidenceMap.get(taskId);if(evidence){let derivedWorkflow=evidenceToWorkflowState(evidence);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,evidence]of evidenceMap){let council=evidence.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(evidence);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,shouldCommit){let cacheBuild=shouldCommit?await _internals96.buildRehydrationCache(directory,{shouldCommit}):await _internals96.buildRehydrationCache(directory);if(cacheBuild&&!cacheBuild.committed)return;if(shouldCommit&&!shouldCommit())return;_internals96.applyRehydrationCache(session,hydrationProjectKey(directory))}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 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 map3=swarmState.liveContextWindows,modelID=trimLiveContextIdentity(identity?.modelID),providerID=trimLiveContextIdentity(identity?.providerID),hasIdentity=Boolean(modelID||providerID),existing=map3.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(map3.has(sessionID))map3.delete(sessionID);map3.set(sessionID,{modelID,providerID}),evictOldestLiveContextWindow(map3,sessionID);return}if(!hasIdentity&&existing&&(existing.modelID||existing.providerID))return;if(map3.has(sessionID))map3.delete(sessionID);map3.set(sessionID,{tokens:Math.floor(tokens),modelID,providerID}),evictOldestLiveContextWindow(map3,sessionID)}function getLiveContextWindow(sessionID,identity){if(!sessionID)return;let cached3=swarmState.liveContextWindows.get(sessionID);if(!cached3)return;if(identity&&!liveContextIdentityMatches(cached3,identity))return;return cached3.tokens}function getLiveContextModelIdentity(sessionID){if(!sessionID)return;let cached3=swarmState.liveContextWindows.get(sessionID);if(!cached3)return;return{modelID:cached3.modelID,providerID:cached3.providerID}}function evictOldestLiveContextWindow(map3,sessionID){if(map3.size<=MAX_TRACKED_CONTEXT_WINDOWS)return;let oldest=map3.keys().next().value;if(oldest!==void 0&&oldest!==sessionID)map3.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 map3=swarmState.lastBudgetBySession;if(map3.has(sessionID))map3.delete(sessionID);if(map3.set(sessionID,{pct,tokens}),map3.size>MAX_TRACKED_BUDGET_SESSIONS){let oldest=map3.keys().next().value;if(oldest!==void 0&&oldest!==sessionID)map3.delete(oldest)}}function setFinalPromptPressure(sessionID,snapshot){let map3=swarmState.finalPromptPressureBySession;if(map3.has(sessionID))map3.delete(sessionID);if(map3.set(sessionID,snapshot),map3.size>MAX_TRACKED_BUDGET_SESSIONS){let oldest=map3.keys().next().value;if(oldest!==void 0&&oldest!==sessionID)map3.delete(oldest)}}function getFinalPromptPressure(sessionID){if(!sessionID)return;return swarmState.finalPromptPressureBySession.get(sessionID)}function setFinalAccountingWarningBand(sessionID,band){let map3=swarmState.finalAccountingWarningBandsBySession,entry=map3.get(sessionID)??{warn:!1,critical:!1};if(map3.has(sessionID))map3.delete(sessionID);if(band==="critical")entry.critical=!0;else entry.warn=!0;if(map3.set(sessionID,entry),map3.size>MAX_TRACKED_BUDGET_SESSIONS){let oldest=map3.keys().next().value;if(oldest!==void 0&&oldest!==sessionID)map3.delete(oldest)}}function getFinalAccountingWarningBand(sessionID,band){if(!sessionID)return!1;let entry=swarmState.finalAccountingWarningBandsBySession.get(sessionID);if(!entry)return!1;return band==="critical"?entry.critical:entry.warn}function clearFinalAccountingWarningBands(){swarmState.finalAccountingWarningBandsBySession.clear()}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 getDisplayFinalPromptPressure(){let best=null;for(let entry of swarmState.finalPromptPressureBySession.values())if(entry.pct>0&&(best===null||entry.pct>best.pct))best=entry;return best}function setCriticalShownIds(sessionID,value){let map3=swarmState.currentCriticalShownIds;if(map3.has(sessionID))map3.delete(sessionID);if(map3.set(sessionID,value),map3.size>MAX_TRACKED_CRITICAL_SHOWN){let oldest=map3.keys().next().value;if(oldest!==void 0&&oldest!==sessionID)map3.delete(oldest)}}function clearCriticalShownIds(sessionID){return swarmState.currentCriticalShownIds.delete(sessionID)}function buildGateDenialDirectiveKey(ids){return[...ids].sort().join(",")}function incrementGateDenialCount(sessionID,directiveKey){let map3=swarmState.gateDenialCounts,existing=map3.get(sessionID),count2=existing&&existing.directiveKey===directiveKey?existing.count+1:1;if(map3.has(sessionID))map3.delete(sessionID);if(map3.set(sessionID,{count:count2,directiveKey}),map3.size>MAX_TRACKED_GATE_DENIALS){let oldest=map3.keys().next().value;if(oldest!==void 0&&oldest!==sessionID)map3.delete(oldest)}return count2}function clearGateDenialCount(sessionID){swarmState.gateDenialCounts.delete(sessionID)}function addKnowledgeAckDedup(key2){let set3=swarmState.knowledgeAckDedup;if(set3.has(key2))return;if(set3.add(key2),set3.size>MAX_TRACKED_KNOWLEDGE_ACKS){let oldest=set3.values().next().value;if(oldest!==void 0)set3.delete(oldest)}}async function rehydratePrSubscriptions(sessionID,directory){let map3=new Map;try{let{listActive:listActive2}=await Promise.resolve().then(() => (init_pr_subscriptions(),exports_pr_subscriptions)),records=await listActive2(directory);for(let record3 of records){if(record3.sessionID!==sessionID)continue;let key2=`${record3.repoFullName}::${record3.prNumber}`;map3.set(key2,{prNumber:record3.prNumber,repoFullName:record3.repoFullName,prUrl:record3.prUrl,lastKnownStatus:record3.mergeableState??"unknown",lastPollTime:record3.lastCheckedAt,errorCount:record3.errorCount,isWatching:record3.isWatching})}}catch(err){warn(`[state] rehydratePrSubscriptions failed for session ${sessionID}: ${err instanceof Error?err.message:String(err)}`)}return map3}var _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,MAX_TRACKED_DISPATCH_PARENTS=200,PENDING_DISPATCH_AUTHORIZATION_TTL_MS=600000,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,_internals96;var init_state=__esm(()=>{init_constants();init_loader();init_plan_schema();init_schema();init_council_review_identity();init_qa_gate_profile();init_qa_gate_session_override();init_lifecycle();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_injection_budget();init_hydration_ownership();init_session_start_store();init_snapshot_store();init_worktree_link_suggestion();init_telemetry();init_logger();init_path();_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,finalPromptPressureBySession:new Map,finalAccountingWarningBandsBySession:new Map,liveContextWindows:new Map,dispatchParentByChildSession:new Map,pendingDispatchAuthorizations:[],agentSessions:defaultRunContext.agentSessions,pendingRehydrations:new Set,fullAutoEnabledInConfig:!1,environmentProfiles:defaultRunContext.environmentProfiles};REVIEWER_SCOPE_GENERATION_TTL_MS=STALE_SESSION_TTL_MS;_internals96={swarmState,resetSwarmState,ensureAgentSession,startAgentSession,loadPluginConfigWithMeta,resolveInitialTurboMode,getAgentSession,beginInvocation,getActiveWindow,advanceTaskState,getTaskState,hasActiveFullAuto,hasActiveTurboMode,hasActiveLeanTurbo,buildRehydrationCache,applyRehydrationCache,rehydrateSessionFromDisk,rehydratePrSubscriptions,isCouncilGateActive,defaultRunContext}});async function boundedSessionCall(call,timeoutMs,timeoutLabel,failureLabel,sessionId){let timer;try{await Promise.race([call(),new Promise((_resolve,reject2)=>{timer=setTimeout(()=>reject2(Error(`${timeoutLabel} after ${timeoutMs}ms`)),Math.max(1,timeoutMs))})])}catch(error93){_internals97.log(`${failureLabel} for ephemeral session`,{sessionId,error:error93 instanceof Error?error93.message:String(error93)})}finally{if(timer)clearTimeout(timer)}}async function boundedAbortEphemeralSession(session,sessionId,timeoutMs=DEFAULT_EPHEMERAL_ABORT_TIMEOUT_MS){if(typeof session.abort!=="function")return;await _internals97.boundedSessionCall(()=>session.abort({path:{id:sessionId}}),timeoutMs,"ephemeral session abort timed out","ephemeral session abort failed",sessionId)}async function boundedDeleteEphemeralSession(session,sessionId,timeoutMs=DEFAULT_EPHEMERAL_TEARDOWN_DELETE_TIMEOUT_MS){await _internals97.boundedSessionCall(()=>session.delete({path:{id:sessionId}}),timeoutMs,"ephemeral session delete timed out","ephemeral session delete failed",sessionId)}async function teardownEphemeralSession(session,sessionId,options={}){let abortTimeoutMs=options.abortTimeoutMs??DEFAULT_EPHEMERAL_ABORT_TIMEOUT_MS,deleteTimeoutMs=options.deleteTimeoutMs??DEFAULT_EPHEMERAL_TEARDOWN_DELETE_TIMEOUT_MS;if(!(options.skipAbort??!1))await _internals97.boundedAbort(session,sessionId,abortTimeoutMs);await _internals97.boundedDelete(session,sessionId,deleteTimeoutMs)}async function sessionExists(session,sessionId,verifyTimeoutMs){if(typeof session.get!=="function")return!0;try{let body=(await withTimeout(session.get({path:{id:sessionId}}),verifyTimeoutMs,Error(`ephemeral session verify timed out after ${verifyTimeoutMs}ms`)))?.data;if(body===void 0||body===null)return!1;return!0}catch{return!1}}async function teardownEphemeralSessionVerified(session,sessionId,options={}){let verifyTimeoutMs=options.verifyTimeoutMs??DEFAULT_EPHEMERAL_VERIFY_TIMEOUT_MS,attempts=Math.min(6,Math.max(2,options.maxDeleteAttempts??DEFAULT_EPHEMERAL_MAX_DELETE_ATTEMPTS));if(typeof session.get!=="function")return await teardownEphemeralSession(session,sessionId,options),{ok:!1,sessionId,attempts:1,kind:"ephemeral-session-teardown-unverified",reason:"get-unavailable"};let deleteAttempts=0;for(;;){if(await teardownEphemeralSession(session,sessionId,{...options,skipAbort:deleteAttempts>0?!0:options.skipAbort}),deleteAttempts+=1,!await _internals97.sessionExists(session,sessionId,verifyTimeoutMs))return{ok:!0,sessionId,attempts:deleteAttempts};if(deleteAttempts>=attempts)return{ok:!1,sessionId,attempts:deleteAttempts,kind:"ephemeral-session-teardown-unverified",reason:"session-survived-bounded-retries"}}}var DEFAULT_EPHEMERAL_ABORT_TIMEOUT_MS=5000,DEFAULT_EPHEMERAL_TEARDOWN_DELETE_TIMEOUT_MS=2000,DEFAULT_EPHEMERAL_VERIFY_TIMEOUT_MS=2000,DEFAULT_EPHEMERAL_MAX_DELETE_ATTEMPTS=3,_internals97;var init_ephemeral_session_teardown=__esm(()=>{init_logger();init_timeout();_internals97={boundedSessionCall,boundedAbort:boundedAbortEphemeralSession,boundedDelete:boundedDeleteEphemeralSession,sessionExists,log}});var init_worktree=__esm(()=>{init_core3();init_merge2()});function verifyReviewerScopeGenerationMergeBack(input){try{let generation=getReviewerScopeGenerationForCoderCall({parentSessionID:input.parentSessionID,taskId:input.taskId,coderCallID:input.coderCallID,now:input.now});if(!generation||generation.modifiedFiles.length===0)return;if(generation.status!=="collecting"&&generation.status!=="mergeback_pending")return;if(generation.status==="collecting"){if(!markReviewerScopeGenerationMergebackPending({parentSessionID:input.parentSessionID,taskId:input.taskId,coderCallID:input.coderCallID,at:input.now}))return}let session=ensureAgentSession(input.parentSessionID),deadlineAt=(input.now??Date.now())+REVIEWER_SCOPE_CAPTURE_BATCH_DEADLINE_MS;for(let file3 of generation.modifiedFiles){let stored=generation.modifiedFileFingerprints.find((entry)=>entry.file===file3);if(!stored){settleReviewerScopeMergeback({parentSessionID:input.parentSessionID,taskId:input.taskId,coderCallID:input.coderCallID,outcome:{verified:!1,reason:`incomplete fingerprints: ${file3} has no stored capture`,at:input.now}}),pushAdvisory(session,`REVIEWER_SCOPE_MERGEBACK_MISMATCH: task ${input.taskId}: merge-back verification found no stored fingerprint for ${file3}. ACTION[architect]: re-dispatch the coder for this task`);return}let captured=captureReviewerScopeFileFingerprint(input.primaryDirectory,file3,{deadlineAt});if(captured.kind==="capture_failed"){settleReviewerScopeMergeback({parentSessionID:input.parentSessionID,taskId:input.taskId,coderCallID:input.coderCallID,outcome:{verified:!1,reason:`capture ${captured.code} on ${captured.file}`,at:input.now}}),pushAdvisory(session,`REVIEWER_SCOPE_MERGEBACK_MISMATCH: task ${input.taskId}: primary-checkout capture failed for ${captured.file} (${captured.code}). ACTION[architect]: verify the primary checkout, then re-dispatch the reviewer`);return}let capturedFingerprint=reviewerScopeCaptureToFingerprint(captured);if(!capturedFingerprint||!reviewerScopeFileFingerprintsEqual(stored,capturedFingerprint)){settleReviewerScopeMergeback({parentSessionID:input.parentSessionID,taskId:input.taskId,coderCallID:input.coderCallID,outcome:{verified:!1,reason:`primary bytes differ from lane manifest on ${file3}`,at:input.now}}),pushAdvisory(session,`REVIEWER_SCOPE_MERGEBACK_MISMATCH: task ${input.taskId}: primary-checkout bytes differ from the lane manifest on ${file3}; lane evidence retained. ACTION[architect]: resolve the merge conflict or re-dispatch the coder`);return}}let primaryIdentity=canonicalWorkspaceIdentity(input.primaryDirectory);settleReviewerScopeMergeback({parentSessionID:input.parentSessionID,taskId:input.taskId,coderCallID:input.coderCallID,outcome:{verified:!0,primaryWorkspaceIdentity:primaryIdentity??input.primaryDirectory,primaryDirectory:input.primaryDirectory,at:input.now}}),pushAdvisory(session,`REVIEWER_SCOPE_MERGEBACK_VERIFIED: task ${input.taskId}: primary checkout matches the lane manifest exactly; reviewer dispatch is enabled`)}catch(error93){try{let session=ensureAgentSession(input.parentSessionID);pushAdvisory(session,`REVIEWER_SCOPE_MERGEBACK_MISMATCH: task ${input.taskId}: merge-back verification errored (${String(error93).slice(0,200)}). ACTION[architect]: re-dispatch the reviewer to retry verification`),settleReviewerScopeMergeback({parentSessionID:input.parentSessionID,taskId:input.taskId,coderCallID:input.coderCallID,outcome:{verified:!1,reason:"verification error",at:input.now}})}catch{}}}var init_reviewer_scope_mergeback=__esm(()=>{init_scope_binding();init_state();init_reviewer_scope_file_fingerprint()});import{createHash as createHash47,randomBytes as randomBytes7}from"node:crypto";import*as fs66 from"node:fs";import*as path106 from"node:path";function nowMs2(input){return input??Date.now()}function sha2566(input){return createHash47("sha256").update(input).digest("hex")}function storePath4(directory){return path106.join(directory,STORE_RELATIVE_PATH)}function journalPath2(directory){return path106.join(directory,JOURNAL_RELATIVE_PATH)}function credentialPath(directory,authorityDigest){return path106.join(directory,CREDENTIAL_DIRECTORY,`${authorityDigest}.json`)}function readAuthorityLockRecord(lockPath){try{let parsed=JSON.parse(fs66.readFileSync(lockPath,"utf8"));if(typeof parsed?.nonce==="string"&&typeof parsed?.acquiredAt==="number"&&Number.isFinite(parsed.acquiredAt)&&typeof parsed?.pid==="number"&&Number.isInteger(parsed.pid))return{nonce:parsed.nonce,acquiredAt:parsed.acquiredAt,pid:parsed.pid}}catch{}return}function writeAuthorityLockRecord(lockPath,record3){try{return fs66.writeFileSync(lockPath,JSON.stringify(record3,null,2),{flag:"wx"}),!0}catch{return!1}}function isProcessAlive2(pid){if(!Number.isSafeInteger(pid)||pid<=0)return!1;try{return process.kill(pid,0),!0}catch{return!1}}function acquireAuthorityLock(directory){let lockPath=path106.join(directory,AUTHORITY_LOCK_RELATIVE_PATH);fs66.mkdirSync(path106.dirname(lockPath),{recursive:!0});let nonce=randomBytes7(16).toString("hex"),acquiredAt=Date.now(),attempt=()=>writeAuthorityLockRecord(lockPath,{nonce,acquiredAt,pid:process.pid});if(!attempt())try{let observed=readAuthorityLockRecord(lockPath);if(!observed)return;if(Date.now()-fs66.statSync(lockPath).mtimeMs>AUTHORITY_LOCK_STALE_MS){if(isProcessAlive2(observed.pid))return;let reread=readAuthorityLockRecord(lockPath);if(reread&&reread.nonce===observed.nonce&&reread.acquiredAt===observed.acquiredAt&&reread.pid===observed.pid){if(fs66.unlinkSync(lockPath),!attempt())return}}}catch{return}let acquired=readAuthorityLockRecord(lockPath);if(!acquired||acquired.nonce!==nonce)return;let released=!1;return()=>{if(released)return;released=!0;try{if(readAuthorityLockRecord(lockPath)?.nonce===nonce)fs66.unlinkSync(lockPath)}catch{}}}function taskKey(parentSessionId,taskId){return`${parentSessionId}::${taskId}`}function stableStringify(value){if(Array.isArray(value))return`[${value.map((item)=>stableStringify(item)).join(",")}]`;if(value&&typeof value==="object")return`{${Object.entries(value).sort(([left],[right])=>left.localeCompare(right)).map(([key2,item])=>`${JSON.stringify(key2)}:${stableStringify(item)}`).join(",")}}`;return JSON.stringify(value)}function digestAuthorityIdentity(input){return sha2566(stableStringify({originalCallID:input.originalCallID,parentSessionId:input.parentSessionId,taskId:input.taskId,reservationId:input.reservationId,generation:input.generation,canonicalBranch:input.canonicalBranch,canonicalPath:input.canonicalPath,laneBranch:input.laneBranch,lanePath:input.lanePath,expectedPrimaryHead:input.expectedPrimaryHead,sourceBaseOid:input.sourceBaseOid,sourceHeadOid:input.sourceHeadOid,targetHeadOid:input.targetHeadOid,strategy:input.strategy,declaredConflictFiles:input.declaredConflictFiles??[]}))}function nonEmpty(value){return typeof value==="string"&&value.length>0&&value.length<=4096}function isHex40(value){return typeof value==="string"&&HEX_40_RE.test(value)}function isOidArray(value){return Array.isArray(value)&&value.length<=4096&&value.every(isHex40)}function isSettlementEvidence(value){if(!value||typeof value!=="object"||Array.isArray(value))return!1;let candidate=value;return isOidArray(candidate.sourceCommitOrder)&&isOidArray(candidate.rewrittenCommitOrder)&&candidate.sourceCommitOrder.length===candidate.rewrittenCommitOrder.length}function isStrategy(value){return value==="merge"||value==="rebase"||value==="cherry-pick"}function isImmutableIdentity(value){if(!value||typeof value!=="object"||Array.isArray(value))return!1;let candidate=value;return nonEmpty(candidate.originalCallID)&&nonEmpty(candidate.parentSessionId)&&nonEmpty(candidate.taskId)&&nonEmpty(candidate.reservationId)&&typeof candidate.generation==="number"&&Number.isInteger(candidate.generation)&&candidate.generation>0&&nonEmpty(candidate.canonicalBranch)&&nonEmpty(candidate.canonicalPath)&&nonEmpty(candidate.laneBranch)&&nonEmpty(candidate.lanePath)&&isHex40(candidate.expectedPrimaryHead)&&isHex40(candidate.sourceBaseOid)&&isHex40(candidate.sourceHeadOid)&&isHex40(candidate.targetHeadOid)&&isStrategy(candidate.strategy)&&(candidate.declaredConflictFiles===void 0||Array.isArray(candidate.declaredConflictFiles)&&candidate.declaredConflictFiles.every((item)=>nonEmpty(item)))&&typeof candidate.createdAt==="number"&&Number.isFinite(candidate.createdAt)&&candidate.createdAt>=0}function isClaimState(value){if(!value||typeof value!=="object"||Array.isArray(value))return!1;let candidate=value;return nonEmpty(candidate.claimantCallID)&&nonEmpty(candidate.claimantSessionId)&&nonEmpty(candidate.childSessionId)&&typeof candidate.claimRevision==="number"&&Number.isInteger(candidate.claimRevision)&&candidate.claimRevision>0&&typeof candidate.attempt==="number"&&Number.isInteger(candidate.attempt)&&candidate.attempt>0&&typeof candidate.leaseExpiresAt==="number"&&Number.isFinite(candidate.leaseExpiresAt)&&candidate.leaseExpiresAt>=0&&nonEmpty(candidate.claimTokenDigest)&&typeof candidate.claimedAt==="number"&&Number.isFinite(candidate.claimedAt)&&candidate.claimedAt>=0}function isAuthority(value){if(!value||typeof value!=="object"||Array.isArray(value))return!1;let candidate=value,claimCursor=candidate.claimCursor&&typeof candidate.claimCursor==="object"?candidate.claimCursor:void 0,validStatus=candidate.status==="preserved"||candidate.status==="claimed"||candidate.status==="released"||candidate.status==="finalized";return candidate.schemaVersion===2&&nonEmpty(candidate.authorityDigest)&&isImmutableIdentity(candidate.immutable)&&validStatus&&(candidate.claim===void 0||isClaimState(candidate.claim))&&(claimCursor===void 0||typeof claimCursor.lastClaimRevision==="number"&&Number.isInteger(claimCursor.lastClaimRevision)&&claimCursor.lastClaimRevision>0&&typeof claimCursor.lastAttempt==="number"&&Number.isInteger(claimCursor.lastAttempt)&&claimCursor.lastAttempt>0)&&(candidate.status!=="claimed"||candidate.claim!==void 0)&&(candidate.finalizedAt===void 0||typeof candidate.finalizedAt==="number"&&Number.isFinite(candidate.finalizedAt)&&candidate.finalizedAt>=0)&&(candidate.settlement===void 0||isSettlementEvidence(candidate.settlement))}function isJournalEntry(value){if(!value||typeof value!=="object"||Array.isArray(value))return!1;let candidate=value,validState=candidate.state==="PREPARED"||candidate.state==="COMMITTED"||candidate.state==="CLAIM_RENEWED"||candidate.state==="ABORTED"||candidate.state==="RELEASED"||candidate.state==="FINALIZED";return candidate.schemaVersion===1&&nonEmpty(candidate.authorityDigest)&&validState&&nonEmpty(candidate.claimantCallID)&&nonEmpty(candidate.claimantSessionId)&&(candidate.childSessionId===void 0||nonEmpty(candidate.childSessionId))&&typeof candidate.claimRevision==="number"&&Number.isInteger(candidate.claimRevision)&&candidate.claimRevision>0&&typeof candidate.attempt==="number"&&Number.isInteger(candidate.attempt)&&candidate.attempt>0&&typeof candidate.leaseExpiresAt==="number"&&Number.isFinite(candidate.leaseExpiresAt)&&candidate.leaseExpiresAt>=0&&nonEmpty(candidate.claimTokenDigest)&&typeof candidate.preparedAt==="number"&&Number.isFinite(candidate.preparedAt)&&candidate.preparedAt>=0&&(candidate.credentialInstalledAt===void 0||typeof candidate.credentialInstalledAt==="number"&&Number.isFinite(candidate.credentialInstalledAt)&&candidate.credentialInstalledAt>=0)&&(candidate.committedAt===void 0||typeof candidate.committedAt==="number"&&Number.isFinite(candidate.committedAt)&&candidate.committedAt>=0)&&(candidate.abortedAt===void 0||typeof candidate.abortedAt==="number"&&Number.isFinite(candidate.abortedAt)&&candidate.abortedAt>=0)&&(candidate.reason===void 0||nonEmpty(candidate.reason))}function isCredential(value){if(!value||typeof value!=="object"||Array.isArray(value))return!1;let candidate=value;return candidate.schemaVersion===1&&nonEmpty(candidate.authorityDigest)&&nonEmpty(candidate.claimantCallID)&&nonEmpty(candidate.claimantSessionId)&&nonEmpty(candidate.childSessionId)&&typeof candidate.claimRevision==="number"&&Number.isInteger(candidate.claimRevision)&&candidate.claimRevision>0&&nonEmpty(candidate.rawToken)&&typeof candidate.leaseExpiresAt==="number"&&Number.isFinite(candidate.leaseExpiresAt)&&candidate.leaseExpiresAt>=0&&typeof candidate.createdAt==="number"&&Number.isFinite(candidate.createdAt)&&candidate.createdAt>=0}function rebuildIndex(authorities){let bySessionTask={};for(let authority of[...authorities].sort((left,right)=>right.immutable.generation-left.immutable.generation||right.immutable.createdAt-left.immutable.createdAt)){let key2=taskKey(authority.immutable.parentSessionId,authority.immutable.taskId),digests=bySessionTask[key2]??[];digests.push(authority.authorityDigest),bySessionTask[key2]=digests}return{bySessionTask}}function emptyJournal(){return{schemaVersion:1,entries:[]}}function readBoundedJsonFile2(filePath,maxBytes){try{if(fs66.statSync(filePath).size>maxBytes)return{ok:!1,reason:`${path106.basename(filePath)} exceeds the ${maxBytes}-byte safety bound`};let raw=fs66.readFileSync(filePath,"utf8");if(Buffer.byteLength(raw,"utf8")>maxBytes)return{ok:!1,reason:`${path106.basename(filePath)} changed beyond the ${maxBytes}-byte safety bound`};return{ok:!0,value:JSON.parse(raw)}}catch(error93){if(error93.code==="ENOENT")return{ok:!0,value:void 0};return{ok:!1,reason:`${path106.basename(filePath)} is unreadable or malformed: ${error93 instanceof Error?error93.message:String(error93)}`}}}function loadStoreStrict(directory){let loaded=readBoundedJsonFile2(storePath4(directory),MAX_STORE_BYTES);if(!loaded.ok)return{status:"uncertain",reason:loaded.reason};if(loaded.value===void 0)return{status:"ok",authorities:[]};let parsed=loaded.value;if(parsed.schemaVersion===1)return{status:"unsupported-legacy",reason:"worktree recovery v1 records are unsupported for claim mutation"};if(parsed.schemaVersion!==2)return{status:"uncertain",reason:`unknown worktree recovery schema version: ${String(parsed.schemaVersion)}`};if(!Array.isArray(parsed.authorities))return{status:"uncertain",reason:"worktree recovery store does not contain an authorities array"};if(parsed.authorities.length>MAX_STORE_AUTHORITIES)return{status:"uncertain",reason:`worktree recovery authority count exceeds the ${MAX_STORE_AUTHORITIES}-record safety bound`};for(let authority of parsed.authorities)if(!isAuthority(authority))return{status:"uncertain",reason:"worktree recovery store contains an invalid authority record"};return{status:"ok",authorities:[...parsed.authorities]}}function loadStoreWritable(directory){let scanned=loadStoreStrict(directory);if(scanned.status==="unsupported-legacy")return{ok:!1,code:"unsupported_legacy",reason:scanned.reason};if(scanned.status==="uncertain")return{ok:!1,code:"uncertain_store",reason:scanned.reason};return{schemaVersion:2,authorities:scanned.authorities,index:rebuildIndex(scanned.authorities)}}function loadJournal(directory){let loaded=readBoundedJsonFile2(journalPath2(directory),MAX_JOURNAL_BYTES2);if(!loaded.ok||loaded.value===void 0)return emptyJournal();let parsed=loaded.value;if(parsed.schemaVersion!==1||!Array.isArray(parsed.entries))return emptyJournal();let entries=[];for(let entry of parsed.entries)if(isJournalEntry(entry))entries.push(entry);return{schemaVersion:1,entries:entries.slice(-MAX_JOURNAL_ENTRIES)}}function updateStore(store,authorities){return store.authorities=authorities,store.index=rebuildIndex(authorities),store}function currentClaimMatches(authority,request){if(!authority.claim)return!1;return authority.claim.claimantCallID===request.claimantCallID&&authority.claim.claimRevision===request.claimRevision&&authority.claim.claimTokenDigest===sha2566(request.rawToken)}function latestJournalEntriesByAuthority(journal){let latest=new Map;for(let entry of journal.entries)latest.set(entry.authorityDigest,entry);return[...latest.values()]}function recordJournalEntry(directory,entry){let journal=loadJournal(directory);if(journal.entries.push(entry),journal.entries.length>MAX_JOURNAL_ENTRIES)journal.entries=journal.entries.slice(-MAX_JOURNAL_ENTRIES);return _internals98.writeClaimJournal(journalPath2(directory),journal),journal}function writeCredential(directory,credential){let targetPath=credentialPath(directory,credential.authorityDigest);_internals98.writeCredentialFile(targetPath,credential);try{fs66.chmodSync(targetPath,384)}catch{}return targetPath}function readCredential(directory,authorityDigest){let loaded=readBoundedJsonFile2(credentialPath(directory,authorityDigest),MAX_CREDENTIAL_BYTES);if(!loaded.ok||loaded.value===void 0)return;return isCredential(loaded.value)?loaded.value:void 0}function removeCredentialIfMatch(directory,entry){let credential=readCredential(directory,entry.authorityDigest);if(credential&&credential.claimRevision===entry.claimRevision&&credential.claimantCallID===entry.claimantCallID)try{fs66.unlinkSync(credentialPath(directory,entry.authorityDigest))}catch{}}function baseMutationFailure(code,reason){return{ok:!1,code,reason}}function publishWorktreeRecoveryAuthorityUnlocked(directory,input){let store=loadStoreWritable(directory);if("ok"in store)return store;let immutable={...input,createdAt:nowMs2()};if(!isImmutableIdentity(immutable))return baseMutationFailure("uncertain_store","invalid immutable recovery authority input");let authorityDigest=digestAuthorityIdentity(input),existing=store.authorities.find((authority2)=>authority2.authorityDigest===authorityDigest);if(existing)return{ok:!0,authority:existing};let authority={schemaVersion:2,authorityDigest,immutable,status:"preserved"},nextAuthorities=[...store.authorities,authority];if(nextAuthorities.length>MAX_STORE_AUTHORITIES)return baseMutationFailure("uncertain_store",`worktree recovery authority count exceeds the ${MAX_STORE_AUTHORITIES}-record safety bound`);return _internals98.writeRecoveryStore(storePath4(directory),updateStore(store,nextAuthorities),"publish"),{ok:!0,authority}}function publishWorktreeRecoveryAuthority(directory,input){let release=acquireAuthorityLock(directory);if(!release)return baseMutationFailure("busy","worktree recovery authority store is locked");try{return publishWorktreeRecoveryAuthorityUnlocked(directory,input)}finally{release()}}function scanWorktreeRecoveryAuthoritiesForRecovery(directory){return loadStoreStrict(directory)}function lookupWorktreeRecoveryAuthoritiesByTask(directory,query){let scanned=loadStoreStrict(directory);if(scanned.status!=="ok")return scanned;return{status:"ok",authorities:scanned.authorities.filter((authority)=>authority.immutable.parentSessionId===query.parentSessionId&&authority.immutable.taskId===query.taskId).sort((left,right)=>right.immutable.generation-left.immutable.generation||right.immutable.createdAt-left.immutable.createdAt)}}async function claimWorktreeRecoveryAuthorityUnlocked(directory,request){let store=loadStoreWritable(directory);if("ok"in store)return store;let authorityIndex=store.authorities.findIndex((authority2)=>authority2.authorityDigest===request.authorityDigest);if(authorityIndex===-1)return baseMutationFailure("not_found","worktree recovery authority not found");let authority=store.authorities[authorityIndex];if(authority.status==="finalized")return baseMutationFailure("finalized","finalized worktree recovery authority cannot be claimed again");let currentTime=nowMs2(request.now),previousClaim=authority.claim;if(previousClaim&&previousClaim.leaseExpiresAt>currentTime)return baseMutationFailure("busy","worktree recovery authority is already claimed");if(previousClaim&&previousClaim.leaseExpiresAt<=currentTime){if(!request.revalidateExpiredClaim)return baseMutationFailure("revalidation_required","expired worktree recovery claims require full revalidation before transfer");let verdict=await request.revalidateExpiredClaim({authority,previousClaim});if(!verdict.ok)return baseMutationFailure("revalidation_failed",verdict.reason)}let nextAttempt=(previousClaim?.attempt??authority.claimCursor?.lastAttempt??0)+1,maxAttempts=request.maxAttempts??DEFAULT_MAX_ATTEMPTS;if(nextAttempt>maxAttempts)return baseMutationFailure("retry_cap_exceeded",`worktree recovery claim attempt ${nextAttempt} exceeds the ${maxAttempts}-attempt safety cap`);let nextRevision=(previousClaim?.claimRevision??authority.claimCursor?.lastClaimRevision??0)+1,rawToken=_internals98.generateRawToken(),claimTokenDigest=sha2566(rawToken);recordJournalEntry(directory,{schemaVersion:1,authorityDigest:authority.authorityDigest,state:"PREPARED",claimantCallID:request.claimantCallID,claimantSessionId:request.claimantSessionId,claimRevision:nextRevision,attempt:nextAttempt,leaseExpiresAt:currentTime+request.leaseMs,claimTokenDigest,preparedAt:currentTime});let childSessionId=await request.createChildSession(),refreshedStore=loadStoreWritable(directory);if("ok"in refreshedStore)throw Error(`worktree recovery authority could not be revalidated: ${refreshedStore.reason}`);let refreshedAuthority=refreshedStore.authorities.find((candidate)=>candidate.authorityDigest===request.authorityDigest);if(!refreshedAuthority||stableStringify({status:refreshedAuthority.status,claim:refreshedAuthority.claim,claimCursor:refreshedAuthority.claimCursor,immutable:refreshedAuthority.immutable})!==stableStringify({status:authority.status,claim:authority.claim,claimCursor:authority.claimCursor,immutable:authority.immutable}))throw recordJournalEntry(directory,{schemaVersion:1,authorityDigest:authority.authorityDigest,state:"ABORTED",claimantCallID:request.claimantCallID,claimantSessionId:request.claimantSessionId,childSessionId,claimRevision:nextRevision,attempt:nextAttempt,leaseExpiresAt:currentTime+request.leaseMs,claimTokenDigest,preparedAt:currentTime,abortedAt:nowMs2(),reason:"authority changed while child session was being created"}),Error("worktree recovery authority changed while child session was being created");recordJournalEntry(directory,{schemaVersion:1,authorityDigest:authority.authorityDigest,state:"PREPARED",claimantCallID:request.claimantCallID,claimantSessionId:request.claimantSessionId,childSessionId,claimRevision:nextRevision,attempt:nextAttempt,leaseExpiresAt:currentTime+request.leaseMs,claimTokenDigest,preparedAt:currentTime});let credential={schemaVersion:1,authorityDigest:authority.authorityDigest,claimantCallID:request.claimantCallID,claimantSessionId:request.claimantSessionId,childSessionId,claimRevision:nextRevision,rawToken,leaseExpiresAt:currentTime+request.leaseMs,createdAt:currentTime},writtenCredentialPath=writeCredential(directory,credential);recordJournalEntry(directory,{schemaVersion:1,authorityDigest:authority.authorityDigest,state:"PREPARED",claimantCallID:request.claimantCallID,claimantSessionId:request.claimantSessionId,childSessionId,claimRevision:nextRevision,attempt:nextAttempt,leaseExpiresAt:currentTime+request.leaseMs,claimTokenDigest,preparedAt:currentTime,credentialInstalledAt:currentTime});let claimedAuthority={...authority,status:"claimed",claim:{claimantCallID:request.claimantCallID,claimantSessionId:request.claimantSessionId,childSessionId,claimRevision:nextRevision,attempt:nextAttempt,leaseExpiresAt:currentTime+request.leaseMs,claimTokenDigest,claimedAt:currentTime},claimCursor:{lastClaimRevision:nextRevision,lastAttempt:nextAttempt}},nextAuthorities=[...store.authorities];return nextAuthorities[authorityIndex]=claimedAuthority,_internals98.writeRecoveryStore(storePath4(directory),updateStore(store,nextAuthorities),"claim-commit"),recordJournalEntry(directory,{schemaVersion:1,authorityDigest:authority.authorityDigest,state:"COMMITTED",claimantCallID:request.claimantCallID,claimantSessionId:request.claimantSessionId,childSessionId,claimRevision:nextRevision,attempt:nextAttempt,leaseExpiresAt:currentTime+request.leaseMs,claimTokenDigest,preparedAt:currentTime,credentialInstalledAt:currentTime,committedAt:currentTime}),{ok:!0,authority:claimedAuthority,rawToken,credentialPath:writtenCredentialPath}}async function claimWorktreeRecoveryAuthority(directory,request){let release=acquireAuthorityLock(directory);if(!release)return baseMutationFailure("busy","worktree recovery authority store is locked");try{return await claimWorktreeRecoveryAuthorityUnlocked(directory,request)}finally{release()}}function renewWorktreeRecoveryClaimUnlocked(directory,request){let store=loadStoreWritable(directory);if("ok"in store)return store;let index=store.authorities.findIndex((authority2)=>authority2.authorityDigest===request.authorityDigest);if(index===-1)return baseMutationFailure("not_found","worktree recovery authority not found");let authority=store.authorities[index];if(!currentClaimMatches(authority,request))return baseMutationFailure("stale_claim","worktree recovery claim is stale or does not match the current claimant");let renewed={...authority,claim:{...authority.claim,leaseExpiresAt:nowMs2(request.now)+request.leaseMs}},nextAuthorities=[...store.authorities];return nextAuthorities[index]=renewed,_internals98.writeRecoveryStore(storePath4(directory),updateStore(store,nextAuthorities),"claim-renew"),writeCredential(directory,{schemaVersion:1,authorityDigest:renewed.authorityDigest,claimantCallID:renewed.claim.claimantCallID,claimantSessionId:renewed.claim.claimantSessionId,childSessionId:renewed.claim.childSessionId,claimRevision:renewed.claim.claimRevision,rawToken:request.rawToken,leaseExpiresAt:renewed.claim.leaseExpiresAt,createdAt:renewed.claim.claimedAt}),recordJournalEntry(directory,{schemaVersion:1,authorityDigest:renewed.authorityDigest,state:"CLAIM_RENEWED",claimantCallID:renewed.claim.claimantCallID,claimantSessionId:renewed.claim.claimantSessionId,childSessionId:renewed.claim.childSessionId,claimRevision:renewed.claim.claimRevision,attempt:renewed.claim.attempt,leaseExpiresAt:renewed.claim.leaseExpiresAt,claimTokenDigest:renewed.claim.claimTokenDigest,preparedAt:renewed.claim.claimedAt,committedAt:nowMs2(request.now),reason:"claim lease renewed"}),{ok:!0,authority:renewed}}function renewWorktreeRecoveryClaim(directory,request){let release=acquireAuthorityLock(directory);if(!release)return baseMutationFailure("busy","worktree recovery authority store is locked");try{return renewWorktreeRecoveryClaimUnlocked(directory,request)}finally{release()}}function releaseWorktreeRecoveryClaimUnlocked(directory,request){let store=loadStoreWritable(directory);if("ok"in store)return store;let index=store.authorities.findIndex((authority2)=>authority2.authorityDigest===request.authorityDigest);if(index===-1)return baseMutationFailure("not_found","worktree recovery authority not found");let authority=store.authorities[index];if(!currentClaimMatches(authority,request))return baseMutationFailure("stale_claim","worktree recovery claim is stale or does not match the current claimant");let released={...authority,status:"preserved",claim:void 0,claimCursor:authority.claim?{lastClaimRevision:authority.claim.claimRevision,lastAttempt:authority.claim.attempt}:authority.claimCursor},nextAuthorities=[...store.authorities];return nextAuthorities[index]=released,_internals98.writeRecoveryStore(storePath4(directory),updateStore(store,nextAuthorities),"claim-release"),recordJournalEntry(directory,{schemaVersion:1,authorityDigest:authority.authorityDigest,state:"RELEASED",claimantCallID:authority.claim.claimantCallID,claimantSessionId:authority.claim.claimantSessionId,childSessionId:authority.claim.childSessionId,claimRevision:authority.claim.claimRevision,attempt:authority.claim.attempt,leaseExpiresAt:authority.claim.leaseExpiresAt,claimTokenDigest:authority.claim.claimTokenDigest,preparedAt:authority.claim.claimedAt,committedAt:nowMs2(request.now),reason:"claim released after preserved settlement"}),removeCredentialIfMatch(directory,request),{ok:!0,authority:released}}function releaseWorktreeRecoveryClaim(directory,request){let release=acquireAuthorityLock(directory);if(!release)return baseMutationFailure("busy","worktree recovery authority store is locked");try{return releaseWorktreeRecoveryClaimUnlocked(directory,request)}finally{release()}}function finalizeWorktreeRecoveryAuthorityUnlocked(directory,request){let store=loadStoreWritable(directory);if("ok"in store)return store;let index=store.authorities.findIndex((authority2)=>authority2.authorityDigest===request.authorityDigest);if(index===-1)return baseMutationFailure("not_found","worktree recovery authority not found");let authority=store.authorities[index];if(!currentClaimMatches(authority,request))return baseMutationFailure("stale_claim","worktree recovery claim is stale or does not match the current claimant");let finalized={...authority,status:"finalized",claim:void 0,claimCursor:authority.claim?{lastClaimRevision:authority.claim.claimRevision,lastAttempt:authority.claim.attempt}:authority.claimCursor,finalizedAt:nowMs2(request.now),settlement:request.settlement},nextAuthorities=[...store.authorities];return nextAuthorities[index]=finalized,_internals98.writeRecoveryStore(storePath4(directory),updateStore(store,nextAuthorities),"claim-finalize"),recordJournalEntry(directory,{schemaVersion:1,authorityDigest:authority.authorityDigest,state:"FINALIZED",claimantCallID:authority.claim.claimantCallID,claimantSessionId:authority.claim.claimantSessionId,childSessionId:authority.claim.childSessionId,claimRevision:authority.claim.claimRevision,attempt:authority.claim.attempt,leaseExpiresAt:authority.claim.leaseExpiresAt,claimTokenDigest:authority.claim.claimTokenDigest,preparedAt:authority.claim.claimedAt,committedAt:nowMs2(request.now),reason:"claim finalized after landed settlement"}),removeCredentialIfMatch(directory,request),{ok:!0,authority:finalized}}function finalizeWorktreeRecoveryAuthority(directory,request){let release=acquireAuthorityLock(directory);if(!release)return baseMutationFailure("busy","worktree recovery authority store is locked");try{return finalizeWorktreeRecoveryAuthorityUnlocked(directory,request)}finally{release()}}function replayWorktreeRecoveryClaimJournalUnlocked(directory,options){let outcomes=[],storeScan=loadStoreStrict(directory),authorities=new Map((storeScan.status==="ok"?storeScan.authorities:[]).map((authority)=>[authority.authorityDigest,authority]));for(let entry of latestJournalEntriesByAuthority(loadJournal(directory))){if(entry.state==="ABORTED"||entry.state==="CLAIM_RENEWED"||entry.state==="RELEASED"||entry.state==="FINALIZED"){outcomes.push({authorityDigest:entry.authorityDigest,outcome:"noop"});continue}if(entry.state==="COMMITTED"){let current2=authorities.get(entry.authorityDigest);if(current2&&!current2.claim&¤t2.claimCursor?.lastClaimRevision===entry.claimRevision&&(current2.status==="preserved"||current2.status==="finalized")){recordJournalEntry(directory,{...entry,state:current2.status==="finalized"?"FINALIZED":"RELEASED",reason:"repaired terminal claim journal after interrupted settlement"}),removeCredentialIfMatch(directory,entry),outcomes.push({authorityDigest:entry.authorityDigest,outcome:"repaired_terminal_claim"});continue}if(current2?.claim&¤t2.claim.claimRevision===entry.claimRevision&¤t2.claim.claimTokenDigest===entry.claimTokenDigest){let credential2=readCredential(directory,entry.authorityDigest),released=credential2?releaseWorktreeRecoveryClaimUnlocked(directory,{authorityDigest:entry.authorityDigest,claimantCallID:entry.claimantCallID,claimRevision:entry.claimRevision,rawToken:credential2.rawToken}):void 0;outcomes.push({authorityDigest:entry.authorityDigest,outcome:released?.ok?"released_orphaned_committed_claim":"uncertain_committed_without_authority"})}else outcomes.push({authorityDigest:entry.authorityDigest,outcome:"uncertain_committed_without_authority"});continue}let current=authorities.get(entry.authorityDigest);if(current?.claim&¤t.claim.claimRevision===entry.claimRevision&¤t.claim.claimTokenDigest===entry.claimTokenDigest){recordJournalEntry(directory,{...entry,state:"COMMITTED",committedAt:nowMs2()}),outcomes.push({authorityDigest:entry.authorityDigest,outcome:"committed_claim_stable"});continue}let credential=readCredential(directory,entry.authorityDigest);if(credential&&credential.claimRevision===entry.claimRevision&&credential.claimantCallID===entry.claimantCallID){removeCredentialIfMatch(directory,entry),recordJournalEntry(directory,{...entry,state:"ABORTED",abortedAt:nowMs2(),reason:"removed uncommitted credential during replay"}),options?.onAbortPreparedClaim?.(entry),outcomes.push({authorityDigest:entry.authorityDigest,outcome:"removed_uncommitted_credential"});continue}recordJournalEntry(directory,{...entry,state:"ABORTED",abortedAt:nowMs2(),reason:"prepared claim never reached credential install or commit"}),options?.onAbortPreparedClaim?.(entry),outcomes.push({authorityDigest:entry.authorityDigest,outcome:"aborted_prepared_claim"})}return outcomes}function replayWorktreeRecoveryClaimJournal(directory,options){let release=acquireAuthorityLock(directory);if(!release)throw Error("worktree recovery authority store is locked");try{return replayWorktreeRecoveryClaimJournalUnlocked(directory,options)}finally{release()}}var STORE_RELATIVE_PATH,JOURNAL_RELATIVE_PATH,CREDENTIAL_DIRECTORY,AUTHORITY_LOCK_RELATIVE_PATH,AUTHORITY_LOCK_STALE_MS=600000,MAX_STORE_BYTES=2097152,MAX_STORE_AUTHORITIES=512,MAX_JOURNAL_BYTES2=2097152,MAX_JOURNAL_ENTRIES=512,MAX_CREDENTIAL_BYTES=16384,DEFAULT_MAX_ATTEMPTS=8,HEX_40_RE,_internals98;var init_worktree_recovery_authority=__esm(()=>{init_atomic_write();STORE_RELATIVE_PATH=path106.join(".swarm","worktree-merge-recovery-v2.json"),JOURNAL_RELATIVE_PATH=path106.join(".swarm","worktree-merge-recovery-v2-journal.json"),CREDENTIAL_DIRECTORY=path106.join(".swarm","worktree-recovery-claims"),AUTHORITY_LOCK_RELATIVE_PATH=path106.join(".swarm","locks","worktree-recovery-authority.lock"),HEX_40_RE=/^[0-9a-f]{40}$/i;_internals98={generateRawToken:()=>randomBytes7(32).toString("hex"),writeRecoveryStore:(targetPath,store,_phase)=>{atomicWriteSwarmFileSync(targetPath,JSON.stringify(store,null,2))},writeClaimJournal:(targetPath,journal)=>{atomicWriteSwarmFileSync(targetPath,JSON.stringify(journal,null,2))},writeCredentialFile:(targetPath,credential)=>{atomicWriteSwarmFileSync(targetPath,JSON.stringify(credential,null,2),{mode:384})},getRecoveryStorePath:storePath4,getClaimJournalPath:journalPath2,getCredentialPath:credentialPath,acquireAuthorityLock,readClaimJournal(directory){return loadJournal(directory)},resetForTest(){}}});import*as fs67 from"node:fs";import*as path107 from"node:path";function decodeTagPart(value){if(!value||!/^[A-Za-z0-9_-]+$/.test(value))return null;let decoded=Buffer.from(value,"base64url").toString("utf8");return decoded&&Buffer.from(decoded,"utf8").toString("base64url")===value?decoded:null}async function scanBackgroundWorktreeOwnershipTagsForRecovery(directory){try{fs67.statSync(path107.join(directory,".git"))}catch(error93){if(error93.code==="ENOENT")return{status:"ok",owners:[]};return{status:"uncertain",reason:`Git metadata could not be inspected: ${error93 instanceof Error?error93.message:String(error93)}`}}let proc;try{proc=bunSpawn([resolveGitExecutable(),"-C",directory,"for-each-ref",`--count=${MAX_OWNERSHIP_TAGS+1}`,"--format=%(refname:strip=2)%00%(objectname)","refs/tags/swarm-preserved-owner/"],{stdin:"ignore",stdout:"pipe",stderr:"ignore",timeout:OWNERSHIP_TAG_SCAN_TIMEOUT_MS});let exitCode=await proc.exited;if(exitCode!==0)return{status:"uncertain",reason:`ownership tag scan exited ${exitCode}`};let lines=(await proc.stdout.text()).split(/\r?\n/).map((line)=>line.trim()).filter(Boolean);if(lines.length>MAX_OWNERSHIP_TAGS)return{status:"uncertain",reason:`ownership tag scan exceeded the ${MAX_OWNERSHIP_TAGS}-tag safety bound`};let owners=[];for(let line of lines){let[tag,ref,...extra]=line.split("\x00"),segments=tag?.split("/")??[],sessionId=decodeTagPart(segments[1]??""),laneId=decodeTagPart(segments[2]??""),callDigest=segments[3];if(extra.length>0||segments.length!==4||segments[0]!=="swarm-preserved-owner"||!sessionId||!laneId||!callDigest||!/^[0-9a-f]{12}$/.test(callDigest)||!ref||!/^[0-9a-f]{40,64}$/i.test(ref))return{status:"uncertain",reason:`malformed background ownership tag entry "${tag??""}"`};owners.push({sessionId,laneId,callDigest,ref})}return{status:"ok",owners}}catch(error93){return{status:"uncertain",reason:`ownership tag scan failed: ${error93 instanceof Error?error93.message:String(error93)}`}}finally{try{proc?.kill()}catch{}}}var OWNERSHIP_TAG_SCAN_TIMEOUT_MS=2000,MAX_OWNERSHIP_TAGS=512;var init_worktree_ownership_tag=__esm(()=>{init_bun_compat();init_git_executable()});var exports_worktree_collision_ownership={};__export(exports_worktree_collision_ownership,{inspectStandardWorktreeCollisionOwnership:()=>inspectStandardWorktreeCollisionOwnership,_internals:()=>_internals99});import*as fs68 from"node:fs";function descriptorCoordinateMatch(descriptor,identity){let branchMatches=descriptor.branchName===identity.branchName,pathMatches2=canonicalRootKeyFresh(descriptor.worktreePath)===canonicalRootKeyFresh(identity.worktreePath);if(!branchMatches&&!pathMatches2)return"none";if(!branchMatches||!pathMatches2||descriptor.parentSessionId!==identity.parentSessionId||descriptor.taskId!==identity.taskId)return"uncertain";return"exact"}function isProvenSettled(record3){let settlement=record3.coderSettlement;return settlement?.state==="settled"&&settlement.outcome?.kind==="standard-worktree"&&(settlement.outcome.result==="merged"||settlement.outcome.result==="unchanged")}function classifyRecord(record3,identity,ownerKind){if(!record3.worktree)return null;let coordinates=descriptorCoordinateMatch(record3.worktree,identity);if(coordinates==="none")return null;if(coordinates==="uncertain")return{status:"uncertain",reason:`${ownerKind} background owner has conflicting identity for branch "${identity.branchName}"`};if(isProvenSettled(record3))return null;let lifecycle=record3.coderSettlement?.state==="preserved"?"preserved":"active";return{status:"protected",ownerKind,lifecycle,reason:`${ownerKind} background owner ${record3.correlationId} is ${record3.status}`+(record3.coderSettlement?` with coder settlement ${record3.coderSettlement.state}`:" without a settled workspace outcome")}}async function inspectStandardWorktreeCollisionOwnership(identity){let provisioning=scanWorktreeProvisioningOwnersForRecovery(identity.directory);if(provisioning.status==="uncertain")return provisioning;let now=Date.now();for(let owner of provisioning.owners){if(!(owner.parentSessionId===identity.parentSessionId||owner.worktreeSessionId===identity.parentSessionId))continue;if(owner.schemaVersion===1||owner.taskId===identity.taskId){let leaseIsLive=now-owner.createdAt<=WORKTREE_PROVISIONING_OWNER_LEASE_MS;if(!leaseIsLive)try{_internals99.statSync(identity.worktreePath)}catch(error93){let code=error93.code;if(code!=="ENOENT"&&code!=="ENOTDIR")return{status:"uncertain",reason:`expired provisioning owner ${owner.callID} lane liveness is unreadable: ${error93 instanceof Error?error93.message:String(error93)}`};if(!_internals99.removeWorktreeProvisioningOwner(identity.directory,owner.callID,owner.schemaVersion===3?{reservationId:owner.reservationId,generation:owner.generation,branchName:owner.branchName}:void 0))return{status:"uncertain",reason:`expired provisioning owner ${owner.callID} could not be removed`};continue}return{status:"protected",ownerKind:"provisioning",lifecycle:"active",reason:!leaseIsLive?`provisioning owner ${owner.callID} lease expired, but its exact lane path still exists`:owner.schemaVersion===1?`legacy provisioning owner ${owner.callID} cannot disprove ownership of this same-session lane`:`provisioning owner ${owner.callID} is active for task ${identity.taskId}`}}}let fallback=await scanDelegationFallbacksForRecovery(identity.directory);if(fallback.status==="uncertain")return fallback;for(let artifact of fallback.owners){let classified=classifyRecord(artifact.record,identity,"fallback");if(classified)return classified}let primary=scanDelegationsForRecovery(identity.directory);if(primary.status==="uncertain")return primary;for(let record3 of primary.owners){let classified=classifyRecord(record3,identity,"primary");if(classified)return classified}let tags=await scanBackgroundWorktreeOwnershipTagsForRecovery(identity.directory);if(tags.status==="uncertain")return tags;for(let owner of tags.owners)if(owner.sessionId===identity.parentSessionId&&owner.laneId===identity.taskId)return{status:"protected",ownerKind:"ownership-tag",lifecycle:"preserved",reason:`durable ownership tag ${owner.callDigest} preserves this same-session lane`};let mergeStatus=scanWorktreeMergeFailuresForRecovery(identity.directory);if(mergeStatus.status==="uncertain")return mergeStatus;for(let[,failure]of mergeStatus.failures){let branchMatches=failure.branch===identity.branchName,pathMatches2=typeof failure.worktreePath==="string"&&canonicalRootKeyFresh(failure.worktreePath)===canonicalRootKeyFresh(identity.worktreePath);if(!branchMatches&&!pathMatches2)continue;if(!branchMatches||!pathMatches2)return{status:"uncertain",reason:`merge-status owner has conflicting identity for branch "${identity.branchName}"`};return{status:"protected",ownerKind:"merge-status",lifecycle:"preserved",reason:`merge-status records ${failure.outcome} at stage ${failure.stage}`}}return{status:"unowned"}}var _internals99;var init_worktree_collision_ownership=__esm(()=>{init_pending_delegations();init_canonical_root();init_worktree_merge_status();init_worktree_ownership_tag();init_worktree_provisioning_owner();_internals99={statSync:fs68.statSync,removeWorktreeProvisioningOwner}});var exports_worktree_isolation={};__export(exports_worktree_isolation,{standardWorktreeSerializationSessions:()=>standardWorktreeSerializationSessions,standardWorktreeByCallID:()=>standardWorktreeByCallID,sanitizeWorktreeTaskId:()=>sanitizeWorktreeTaskId,runSerializedWithMergeBacks:()=>runSerializedWithMergeBacks,resolveWorktreeIsolationConfig:()=>resolveWorktreeIsolationConfig,resetStandardWorktreeIsolationState:()=>resetStandardWorktreeIsolationState,recordLaneChildSession:()=>recordLaneChildSession,readLaneEnvFileFromDisk:()=>readLaneEnvFileFromDisk,preserveDirtyWorktreeForCallId:()=>preserveDirtyWorktreeForCallId,preserveDirtyWorktreeAtPath:()=>preserveDirtyWorktreeAtPath,preserveBackgroundWorktreeOwnershipForCallId:()=>preserveBackgroundWorktreeOwnershipForCallId,precreateStandardWorktreeSession:()=>precreateStandardWorktreeSession,preProvisionCollisionCheck:()=>preProvisionCollisionCheck,parseLeanLaneIndex:()=>parseLeanLaneIndex,laneChildSessionAgents:()=>laneChildSessionAgents,isLaneOwnedByCurrentSession:()=>isLaneOwnedByCurrentSession,getStandardWorktreeDegradationReason:()=>getStandardWorktreeDegradationReason,finishStandardWorktreeDispatch:()=>finishStandardWorktreeDispatch,computeLaneRuntimeProfile:()=>computeLaneRuntimeProfile,cleanupStandardWorktreeForCallId:()=>cleanupStandardWorktreeForCallId,checkStandardWorktreeSerializationRelease:()=>checkStandardWorktreeSerializationRelease,awaitingMergeByCallID:()=>awaitingMergeByCallID,assertTaskIdNotForeignLaneSession:()=>assertTaskIdNotForeignLaneSession,abortStandardWorktreeDispatch:()=>abortStandardWorktreeDispatch,_internals:()=>_internals93,MAX_TRACKED_STANDARD_WORKTREE_CALLS:()=>MAX_TRACKED_STANDARD_WORKTREE_CALLS});import{createHash as createHash48}from"node:crypto";import*as fs69 from"node:fs/promises";import*as path108 from"node:path";function parseLeanLaneIndex(laneId){let match=/^lane-(\d+)$/.exec(laneId);if(match){let n=parseInt(match[1],10);return Number.isNaN(n)?0:n-1}return 0}function computeLaneRuntimeProfile(runtime,laneIndex,worktreePath){if(!runtime?.enabled)return;let portStride=runtime.port_stride??1,envOverrides={};if(runtime.port_base!==void 0){let portBase=runtime.port_base,port=Math.min(portBase+laneIndex*portStride,65535);envOverrides.PORT=String(port)}if(runtime.env_overrides)Object.assign(envOverrides,runtime.env_overrides);if(runtime.cache_redirects)for(let[envName,basePath]of Object.entries(runtime.cache_redirects)){let laneSuffix=path108.join(basePath,`lane-${laneIndex}`);envOverrides[envName]=laneSuffix}return{laneIndex,worktreePath,envOverrides}}function allocateStandardLaneIndex(parentSessionID){let current=standardWorktreeLaneIndexBySession.get(parentSessionID)??0;return standardWorktreeLaneIndexBySession.set(parentSessionID,current+1),current}function recordLaneChildSession(sessionId,agent){laneChildSessionAgents.delete(sessionId),laneChildSessionAgents.set(sessionId,agent);while(laneChildSessionAgents.size>LANE_CHILD_SESSION_LIMIT){let oldest=laneChildSessionAgents.keys().next().value;if(oldest===void 0)break;laneChildSessionAgents.delete(oldest)}}function assertTaskIdNotForeignLaneSession(args2){if(!args2)return;let taskId=typeof args2.task_id==="string"?args2.task_id.trim():"";if(!taskId)return;let owner=laneChildSessionAgents.get(taskId);if(owner===void 0)return;let requested=typeof args2.subagent_type==="string"?stripKnownSwarmPrefix(args2.subagent_type).toLowerCase():"";if(requested===owner)return;throw Error(`TASK_SESSION_RESUME_MISMATCH: task_id "${taskId}" is the session this plugin created for an isolated ${owner} lane; passing it would resume that ${owner} session as ${requested||"another agent"} (its lane, history and scope). `+'Set task_id to the plan task id (e.g. "1.1") or omit it; never pass a `ses_…` id returned in a Task result '+`for a different agent. Omitting it starts a fresh ${requested||"agent"} session.`)}async function createSessionWithinBudget(promise3,label,onLateResolve,timeoutMs=_internals93.worktreeSessionCreateTimeoutMs){let settled=new Promise((resolveState)=>{promise3.then((result)=>resolveState({status:"fulfilled",result}),()=>resolveState({status:"rejected"}))});try{return await withTimeout(promise3,timeoutMs,Error(`${label} deadline expired after ${timeoutMs}ms (worktree.session_create_timeout_ms)`))}catch(error93){let teardown=settled.then(async(state2)=>{if(state2.status==="fulfilled")await onLateResolve?.(state2.result)},()=>{}).catch((teardownError)=>{log(`[worktree-isolation] ${label} late-settle teardown failed: ${teardownError instanceof Error?teardownError.message:String(teardownError)}`)});throw await withTimeout(teardown,_internals93.worktreeSessionCreateSettleGraceMs,Error(`${label} settle grace expired`)).catch(()=>{}),error93}}function resolveSessionCreateTimeoutMs(args2){return args2.config?.worktree?.session_create_timeout_ms??_internals93.worktreeSessionCreateTimeoutMs}async function handleStrandedLane(lane){recordDeadLaneReclaim(lane.directory,{lanePath:lane.lanePath,branchName:lane.branchName,parentSessionId:lane.parentSessionID,taskId:lane.taskId,reason:lane.reason});let session=ensureAgentSession(lane.parentSessionID);pushAdvisory(session,`WORKTREE_LANE_STRANDED: lane ${lane.lanePath} could not be removed (${lane.reason}). A child session or system process may hold .swarm/swarm.db (WAL); its DB handle was released via closeProjectDb before this attempt. reclaim scheduled at next start.`)}function rememberStandardWorktreeDispatch(dispatch){standardWorktreeByCallID.set(dispatch.callID,dispatch)}function resolveRecoveryTaskId(input){return input.planTaskId??input.taskId}function toRecoveryStrategy(strategy){return strategy}function hasStandardWorktreeDispatchCapacity(){return standardWorktreeByCallID.size<MAX_TRACKED_STANDARD_WORKTREE_CALLS}function hasInFlightStandardWorktreeDispatch(parentSessionID){for(let dispatch of standardWorktreeByCallID.values())if(dispatch.parentSessionID===parentSessionID)return!0;for(let record3 of awaitingMergeByCallID.values())if(record3.parentSessionID===parentSessionID)return!0;return!1}function handleStandardWorktreeFailure(parentSessionID,policy,message){if(policy==="required")throw new StandardWorktreeLifecycleError(message);if(hasInFlightStandardWorktreeDispatch(parentSessionID))throw new StandardWorktreeLifecycleError(`STANDARD_WORKTREE_ISOLATION_UNSAFE: ${message} Sibling coder task(s) are isolated in worktrees for this session, so dispatching this coder un-isolated in the main tree would risk a merge-back collision. Wait for in-flight coder task(s) to be reviewed and merged, then retry.`);serializeStandardWorktreeDispatches(parentSessionID,message)}function resolveWorktreeLifecycleLockWaitMs(sessionCreateTimeoutMs){let createMs=Math.max(0,sessionCreateTimeoutMs),coverHolder=createMs+WORKTREE_LIFECYCLE_LOCK_WAIT_MARGIN_MS,roomInHook=WORKTREE_DISPATCH_HOOK_BUDGET_MS-createMs-WORKTREE_SESSION_CREATE_SETTLE_GRACE_MS-WORKTREE_PROVISION_ALLOWANCE_MS;return Math.max(WORKTREE_LIFECYCLE_LOCK_WAIT_MIN_MS,Math.min(coverHolder,roomInHook))}async function acquireWorktreeLifecycleLockWithin(directory,taskId,waitMs){let deadline=_internals93.now()+Math.max(0,waitMs);for(;;){let attempt=await _internals93.tryAcquireWorktreeLifecycleLock(directory,WORKTREE_LIFECYCLE_LOCK_FILE,"worktree-provisioning",taskId);if(attempt.acquired)return attempt;let remaining=deadline-_internals93.now();if(remaining<=0)return attempt;await _internals93.sleep(Math.min(remaining,50+Math.floor(Math.random()*200)))}}function hardStopStandardWorktreeLifecycle(parentSessionID,message){let session=ensureAgentSession(parentSessionID);throw pushAdvisory(session,message),new StandardWorktreeLifecycleError(message)}function serializeStandardWorktreeDispatches(sessionID,message){if(!rememberStandardWorktreeSerializationSession(sessionID)){let session2=ensureAgentSession(sessionID);pushAdvisory(session2,`${message} Serialization tracking is at capacity (256 sessions active); continuing in normal parallel mode.`);return}standardWorktreeDegradationReasonBySession.set(sessionID,{reason:message,at:Date.now()});let session=ensureAgentSession(sessionID);session.maxConcurrencyOverride=1,pushAdvisory(session,`${message} Serializing standard coder dispatches for this session.`)}function getStandardWorktreeDegradationReason(sessionID){return standardWorktreeDegradationReasonBySession.get(sessionID)}function resetStandardWorktreeIsolationState(){standardWorktreeByCallID.clear(),standardWorktreeSerializationSessions.clear(),laneChildSessionAgents.clear(),serializationStateBySessionID.clear(),standardWorktreeDegradationReasonBySession.clear(),awaitingMergeByCallID.clear(),standardWorktreeMergeQueue=Promise.resolve(),standardWorktreeLaneIndexBySession.clear()}function releaseStandardWorktreeSerialization(sessionID){if(!standardWorktreeSerializationSessions.has(sessionID))return!1;standardWorktreeSerializationSessions.delete(sessionID),serializationStateBySessionID.delete(sessionID),standardWorktreeDegradationReasonBySession.delete(sessionID);let session=ensureAgentSession(sessionID);return session.maxConcurrencyOverride=void 0,pushAdvisory(session,`WORKTREE_SERIALIZATION_RELEASED: ${sessionID} regains parallel dispatch eligibility (release-after-dispatches or TTL).`),!0}function checkStandardWorktreeSerializationRelease(sessionID,config3){let state2=serializationStateBySessionID.get(sessionID);if(!state2)return;let count2=config3.serialization_release_after_dispatches??5,ttl=config3.serialization_release_after_ms??60000;if(state2.successfulDispatchesSince>=count2){releaseStandardWorktreeSerialization(sessionID);return}if(Date.now()-state2.serializedAt>=ttl)releaseStandardWorktreeSerialization(sessionID)}function rememberStandardWorktreeSerializationSession(sessionID){if(standardWorktreeSerializationSessions.size>=MAX_TRACKED_STANDARD_WORKTREE_CALLS){let evicted=!1;for(let key2 of serializationStateBySessionID.keys())if(!hasInFlightStandardWorktreeDispatch(key2)){standardWorktreeSerializationSessions.delete(key2),serializationStateBySessionID.delete(key2),standardWorktreeDegradationReasonBySession.delete(key2),evicted=!0;break}if(!evicted)return log(`[worktree-isolation] serialization set at cap with all sessions active; refusing eviction for ${sessionID}`),!1}if(standardWorktreeSerializationSessions.add(sessionID),!serializationStateBySessionID.has(sessionID))serializationStateBySessionID.set(sessionID,{sessionID,serializedAt:Date.now(),successfulDispatchesSince:0});return!0}function sanitizeWorktreeTaskId(raw){return raw.replace(/[^A-Za-z0-9._-]/g,"-").slice(0,64)||"task"}async function preProvisionCollisionCheck(taskId,directory,_sessionId){let proc;try{proc=_internals93.bunSpawn([_internals93.resolveGitExecutable(),"-C",directory,"worktree","list","--porcelain"],{stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:WORKTREE_LIST_TIMEOUT_MS})}catch(error93){let detail=`git worktree list could not start in ${directory}: ${error93 instanceof Error?error93.message:String(error93)}`;return log(`[swarm] preProvisionCollisionCheck: ${detail}`),{collision:!1,uncertainty:detail}}let stdout="",stderr="";try{let exitCode=await proc.exited;if(stdout=await proc.stdout.text(),stderr=await proc.stderr.text(),exitCode!==0){if(stderr.toLowerCase().includes("not a git repository"))return{collision:!1};return log(`[swarm] preProvisionCollisionCheck: git worktree list failed (exit ${exitCode}): ${stderr}`),{collision:!1,uncertainty:stderr.trim()||`git worktree list exited ${exitCode}`}}}finally{try{proc.kill()}catch{}}let entries=[],current={path:"",branch:void 0,prunable:!1};for(let rawLine of stdout.split(`
|
|
1260
1260
|
`)){let line=rawLine.trim();if(line.startsWith("worktree ")){if(current.path)entries.push(current);current={path:line.slice(9),branch:void 0,prunable:!1}}else if(line.startsWith("branch "))current.branch=line.slice(7);else if(line==="prunable"||line.startsWith("prunable "))current.prunable=!0}if(current.path)entries.push(current);for(let entry of entries){if(!entry.branch)continue;if(entry.prunable)continue;let branchName=entry.branch.startsWith("refs/heads/")?entry.branch.slice(11):entry.branch,segments=branchName.split("/");if(segments.length>=4&&segments[0]==="swarm"&&segments[1]==="lane"){if(segments[3]===taskId){let ownerSessionId=segments[2];return{collision:!0,existingBranch:branchName,ownerSessionId,worktreePath:entry.path}}}if(segments.length>=3&&segments[0]==="swarm-lane"){if(segments[2]===taskId){let ownerSessionId=segments[1];return{collision:!0,existingBranch:branchName,ownerSessionId,worktreePath:entry.path}}}}return{collision:!1}}function isLaneOwnedByCurrentSession(branchName,expectedSessionId){return _internals35.extractSessionId(branchName)===expectedSessionId}async function inspectStandardWorktreeCollisionOwnership2(identity){return(await Promise.resolve().then(() => (init_worktree_collision_ownership(),exports_worktree_collision_ownership))).inspectStandardWorktreeCollisionOwnership(identity)}async function runRecoveryGit(directory,args2,timeoutMs=15000){let proc;try{proc=_internals93.bunSpawn([_internals93.resolveGitExecutable(),"-C",directory,...args2],{stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:timeoutMs,env:{...process.env,LC_ALL:"C"}});let exitCode=await proc.exited,stdout=await proc.stdout.text(),stderr=await proc.stderr.text();return{exitCode,stdout,stderr}}catch(error93){return{exitCode:1,stdout:"",stderr:error93 instanceof Error?error93.message:String(error93)}}finally{try{proc?.kill()}catch{}}}async function pathExists3(targetPath){try{return await fs69.stat(targetPath),!0}catch{return!1}}async function buildWorktreeRecoveryPublishIdentity(input){let mergeBase=await runRecoveryGit(input.directory,["merge-base",input.provenance.targetHeadBefore,input.provenance.sourceHead]),mergeBaseOid=mergeBase.stdout.trim();if(mergeBase.exitCode!==0||!/^[0-9a-f]{40}$|^[0-9a-f]{64}$/.test(mergeBaseOid))return;let targetHead=await runRecoveryGit(input.directory,["rev-parse","HEAD"]),targetHeadOid=targetHead.stdout.trim();if(targetHead.exitCode!==0||!/^[0-9a-f]{40}$|^[0-9a-f]{64}$/.test(targetHeadOid))return;return{originalCallID:input.dispatch.callID,parentSessionId:input.dispatch.parentSessionID,taskId:input.taskId,reservationId:input.dispatch.reservationId??`worktree:${input.dispatch.parentSessionID}:${input.taskId}`,generation:input.dispatch.generation??1,canonicalBranch:input.dispatch.canonicalBranch??input.dispatch.handle.branchName,canonicalPath:input.dispatch.canonicalPath??input.dispatch.handle.worktreePath,laneBranch:input.dispatch.handle.branchName,lanePath:input.dispatch.handle.worktreePath,expectedPrimaryHead:input.provenance.targetHeadBefore,sourceBaseOid:mergeBaseOid,sourceHeadOid:input.provenance.sourceHead,targetHeadOid,strategy:toRecoveryStrategy(input.provenance.strategy),...input.conflictFiles&&input.conflictFiles.length>0?{declaredConflictFiles:input.conflictFiles}:{}}}async function publishRecoveryAuthorityForSettlement(input){if(input.dispatch.recoveryClaim||!input.provenance)return{ok:!0};let identity=await _internals93.buildWorktreeRecoveryPublishIdentity({directory:input.directory,dispatch:input.dispatch,taskId:input.taskId,provenance:input.provenance,conflictFiles:input.conflictFiles});if(!identity)return{ok:!1,code:"identity_unavailable",reason:"worktree recovery publish identity could not be derived from the merge provenance"};let published=_internals93.publishWorktreeRecoveryAuthority(input.directory,identity);return published.ok?{ok:!0}:{ok:!1,code:published.code,reason:published.reason}}function isExactRecoveryClaimantStillActive(authority){let claim=authority.claim;if(!claim)return!1;if(standardWorktreeByCallID.has(claim.claimantCallID)||awaitingMergeByCallID.has(claim.claimantCallID))return!0;let childSession=swarmState.agentSessions.get(claim.childSessionId);if(!childSession?.workspaceDirectory?.trim())return!1;return sameProjectRoot(childSession.workspaceDirectory,authority.immutable.lanePath)}function describeRecoveryMutationFailure(input){return`recovery claim ${input.action} failed (${input.code}): ${input.reason}`}function maybeSelectRecoverableAuthority(lookup,collision){if(lookup.status!=="ok")return{status:"uncertain",reason:lookup.reason};let authority=lookup.authorities.find((candidate)=>candidate.status!=="finalized"&&candidate.immutable.laneBranch===collision.existingBranch&&candidate.immutable.lanePath===collision.worktreePath);return authority?{status:"match",authority}:{status:"none"}}async function precreateStandardWorktreeSession(args2){let configuredWorktree=resolveWorktreeIsolationConfig(args2.config),worktreeConfig=args2.isolationRequired&&configuredWorktree.policy==="auto"?{...configuredWorktree,policy:"required"}:configuredWorktree;if(worktreeConfig.policy==="disabled")return;if(standardWorktreeSerializationSessions.has(args2.parentSessionID)){if(checkStandardWorktreeSerializationRelease(args2.parentSessionID,worktreeConfig),!standardWorktreeSerializationSessions.has(args2.parentSessionID))return}if(!hasStandardWorktreeDispatchCapacity()){if(worktreeConfig.policy==="required")throw Error("STANDARD_WORKTREE_TRACKING_CAP_EXCEEDED: too many standard worktree coder dispatches are already awaiting merge-back.");serializeStandardWorktreeDispatches(args2.parentSessionID,"STANDARD_WORKTREE_TRACKING_CAP_EXCEEDED: too many standard worktree coder dispatches are already awaiting merge-back.");return}let client=swarmState.opencodeClient;if(!client){handleStandardWorktreeFailure(args2.parentSessionID,worktreeConfig.policy,"STANDARD_WORKTREE_ISOLATION_UNAVAILABLE: OpenCode SDK client is unavailable; standard parallel coder work cannot be isolated.");return}let laneIndex=allocateStandardLaneIndex(args2.parentSessionID),provisioningOwnerIdentity={reservationId:args2.reservationId??`foreground:${args2.parentSessionID}:${resolveRecoveryTaskId(args2)}:${args2.callID}`,generation:Math.max(1,args2.generation??1),branchName:makeWorktreeBranchName(args2.parentSessionID,args2.taskId,{purpose:"lane"})},recoveryLaunch,lifecycleLockWaitMs=resolveWorktreeLifecycleLockWaitMs(resolveSessionCreateTimeoutMs(args2)),lifecycleLock=await acquireWorktreeLifecycleLockWithin(args2.directory,args2.taskId,lifecycleLockWaitMs);if(!lifecycleLock.acquired)hardStopStandardWorktreeLifecycle(args2.parentSessionID,`STANDARD_WORKTREE_LIFECYCLE_BUSY: the worktree lifecycle lock stayed busy for ${Math.round(lifecycleLockWaitMs/1000)}s (another lane is provisioning or init orphan recovery is running); retry this coder dispatch. `+"The wait follows worktree.session_create_timeout_ms: that budget plus 5s, at least 10s, and — up to the default 30s budget — short enough that this dispatch (its own session create and worktree provisioning included) still fits the 60s host hook budget.");try{let collision=await _internals93.preProvisionCollisionCheck(args2.taskId,args2.directory,args2.parentSessionID);if(collision.uncertainty)hardStopStandardWorktreeLifecycle(args2.parentSessionID,`STANDARD_WORKTREE_COLLISION_SCAN_UNCERTAIN: ${collision.uncertainty}. Destructive cleanup and provisioning were blocked.`);if(collision.collision){if(!collision.existingBranch||!collision.worktreePath||!isLaneOwnedByCurrentSession(collision.existingBranch,args2.parentSessionID)){let ownerInfo=collision.ownerSessionId?` owned by session ${collision.ownerSessionId}`:" with uncertain ownership";hardStopStandardWorktreeLifecycle(args2.parentSessionID,`PREPROVISION_COLLISION: task ${args2.taskId} already has a lane on branch ${collision.existingBranch??"unknown"}${ownerInfo}; cleanup and provisioning were blocked.`)}for(let dispatch of _internals93.standardWorktreeByCallID.values())if(dispatch.handle.branchName===collision.existingBranch)hardStopStandardWorktreeLifecycle(args2.parentSessionID,`PREPROVISION_COLLISION_ACTIVE: branch ${collision.existingBranch} is still tracked by an active standard-worktree dispatch.`);for(let record3 of _internals93.awaitingMergeByCallID.values())if(record3.branch===collision.existingBranch)hardStopStandardWorktreeLifecycle(args2.parentSessionID,`PREPROVISION_COLLISION_AWAITING_MERGE: branch ${collision.existingBranch} is still awaiting merge-back.`);let recoveryCandidate=maybeSelectRecoverableAuthority(_internals93.lookupWorktreeRecoveryAuthoritiesByTask(args2.directory,{parentSessionId:args2.parentSessionID,taskId:resolveRecoveryTaskId(args2)}),collision);if(recoveryCandidate.status==="uncertain")hardStopStandardWorktreeLifecycle(args2.parentSessionID,`STANDARD_WORKTREE_RECOVERY_AUTHORITY_UNCERTAIN: ${recoveryCandidate.reason}. Recovery re-dispatch was blocked.`);if(recoveryCandidate.status==="match"){let recoveredChildSessionId="",claimed;try{claimed=await _internals93.claimWorktreeRecoveryAuthority(args2.directory,{authorityDigest:recoveryCandidate.authority.authorityDigest,claimantCallID:args2.callID,claimantSessionId:args2.parentSessionID,leaseMs:WORKTREE_RECOVERY_CLAIM_LEASE_MS,createChildSession:async()=>{let createResult=await createSessionWithinBudget(client.session.create({body:{parentID:args2.parentSessionID,title:`${args2.description??args2.taskId} (worktree recovery lane)`},query:{directory:collision.worktreePath}}),"STANDARD_WORKTREE_RECOVERY_SESSION_CREATE",async(result)=>{let lateChildSessionId=result.data?.id;if(lateChildSessionId){let verification=await teardownEphemeralSessionVerified(client.session,lateChildSessionId);if(!verification.ok)pushAdvisory(ensureAgentSession(args2.parentSessionID),`WORKTREE_RECOVERY_CHILD_SESSION_LEAKED: recovery child session ${lateChildSessionId} survived verified teardown (${verification.reason}); it holds the lane swarm.db at ${collision.worktreePath}. Retry the dispatch or restart the host to release it.`)}},resolveSessionCreateTimeoutMs(args2));if(recoveredChildSessionId=createResult.data?.id??"",!recoveredChildSessionId){let createError=createResult.error;throw Error(typeof createError==="string"?createError:JSON.stringify(createError??"missing session id"))}return recoveredChildSessionId},revalidateExpiredClaim:async({authority})=>{if(isExactRecoveryClaimantStillActive(authority))return{ok:!1,reason:"expired recovery claim still belongs to a live claimant session or dispatch"};if(authority.immutable.laneBranch!==collision.existingBranch||authority.immutable.lanePath!==collision.worktreePath)return{ok:!1,reason:"preserved lane coordinates drifted before claim transfer"};try{await fs69.stat(authority.immutable.lanePath)}catch{return{ok:!1,reason:"preserved lane path is no longer live"}}let laneHead=await runRecoveryGit(args2.directory,["rev-parse",`${authority.immutable.laneBranch}^{commit}`]);if(laneHead.exitCode!==0||laneHead.stdout.trim()!==authority.immutable.sourceHeadOid)return{ok:!1,reason:"preserved lane head changed since authority publication"};return{ok:!0}}})}catch(error93){if(_internals93.replayWorktreeRecoveryClaimJournal(args2.directory),recoveredChildSessionId){let verification=await teardownEphemeralSessionVerified(client.session,recoveredChildSessionId);if(!verification.ok)pushAdvisory(ensureAgentSession(args2.parentSessionID),`WORKTREE_RECOVERY_CHILD_SESSION_LEAKED: recovery child session ${recoveredChildSessionId} survived verified teardown (${verification.reason}); it holds the lane swarm.db at ${collision.worktreePath}. Retry the dispatch or restart the host to release it.`)}hardStopStandardWorktreeLifecycle(args2.parentSessionID,`STANDARD_WORKTREE_RECOVERY_SESSION_CREATE_FAILED: ${error93 instanceof Error?error93.message:String(error93)}. The PREPARED claim was rolled back and recovery re-dispatch was blocked.`)}if(!claimed.ok)hardStopStandardWorktreeLifecycle(args2.parentSessionID,`STANDARD_WORKTREE_RECOVERY_CLAIM_FAILED: ${claimed.reason}. The recovery child session ${recoveredChildSessionId} was created but the preserved lane was not reassigned.`);recoveryLaunch={childSessionId:recoveredChildSessionId,worktreePath:collision.worktreePath,branchName:collision.existingBranch,strategy:recoveryCandidate.authority.immutable.strategy,reservationId:recoveryCandidate.authority.immutable.reservationId,generation:recoveryCandidate.authority.immutable.generation,provisioningOwner:{reservationId:recoveryCandidate.authority.immutable.reservationId,generation:recoveryCandidate.authority.immutable.generation,branchName:collision.existingBranch},canonicalBranch:recoveryCandidate.authority.immutable.canonicalBranch,canonicalPath:recoveryCandidate.authority.immutable.canonicalPath,recoveryClaim:{authorityDigest:recoveryCandidate.authority.authorityDigest,claimRevision:claimed.authority.claim?.claimRevision??recoveryCandidate.authority.claimCursor?.lastClaimRevision??1,rawToken:claimed.rawToken,coordinates:{sourceBaseOid:recoveryCandidate.authority.immutable.sourceBaseOid,sourceHeadOid:recoveryCandidate.authority.immutable.sourceHeadOid,targetHeadOid:recoveryCandidate.authority.immutable.targetHeadOid,strategy:recoveryCandidate.authority.immutable.strategy}}}}if(!recoveryLaunch){let ownership=await _internals93.inspectStandardWorktreeCollisionOwnership({directory:args2.directory,parentSessionId:args2.parentSessionID,taskId:args2.taskId,branchName:collision.existingBranch,worktreePath:collision.worktreePath});if(ownership.status==="uncertain")hardStopStandardWorktreeLifecycle(args2.parentSessionID,`STANDARD_WORKTREE_OWNERSHIP_UNCERTAIN: ${ownership.reason}. Destructive cleanup and provisioning were blocked.`);if(ownership.status==="protected")hardStopStandardWorktreeLifecycle(args2.parentSessionID,`STANDARD_WORKTREE_OWNER_PROTECTED: ${ownership.ownerKind} owner is ${ownership.lifecycle}; ${ownership.reason}. Destructive cleanup and provisioning were blocked.`);let collisionPathExists=!0;try{await fs69.stat(collision.worktreePath)}catch(error93){let code=error93.code;if(code==="ENOENT"||code==="ENOTDIR")collisionPathExists=!1;else hardStopStandardWorktreeLifecycle(args2.parentSessionID,`STANDARD_WORKTREE_COLLISION_PATH_STAT_FAILED: ${error93 instanceof Error?error93.message:String(error93)}. Destructive cleanup and provisioning were blocked.`)}if(collisionPathExists){let preserveResult=await _internals93.preserveDirtyWorktreeAtPath(collision.worktreePath,collision.existingBranch,"denied",args2.directory,worktreeConfig.worktree_dir);if(preserveResult.outcome==="preserve-failed")hardStopStandardWorktreeLifecycle(args2.parentSessionID,`STANDARD_WORKTREE_PRESERVATION_FAILED_ABORT_CLEANUP: pre-provision collision for task ${args2.taskId} could not be preserved (${preserveResult.error}). Cleanup and provisioning were blocked.`);closeProjectDb(collision.worktreePath);let removeResult=await _internals93.removeWorktree(collision.worktreePath,args2.directory,{force:!0,worktreeDir:worktreeConfig.worktree_dir});if("error"in removeResult)hardStopStandardWorktreeLifecycle(args2.parentSessionID,`STANDARD_WORKTREE_COLLISION_REMOVE_FAILED: ${removeResult.error}. Provisioning was blocked.`);let cleanupResult=await _internals93.postMergeCleanup(args2.directory,collision.existingBranch);if("error"in cleanupResult)hardStopStandardWorktreeLifecycle(args2.parentSessionID,`STANDARD_WORKTREE_COLLISION_BRANCH_CLEANUP_FAILED: ${cleanupResult.error}. Provisioning was blocked.`)}else{let pruneResult=await _internals93.pruneStaleWorktreeMetadata(args2.directory);if("error"in pruneResult)hardStopStandardWorktreeLifecycle(args2.parentSessionID,`STANDARD_WORKTREE_COLLISION_PRUNE_FAILED: ${pruneResult.error}. Provisioning was blocked without deleting the lane branch.`)}let verification=await _internals93.preProvisionCollisionCheck(args2.taskId,args2.directory,args2.parentSessionID);if(verification.uncertainty||verification.collision)hardStopStandardWorktreeLifecycle(args2.parentSessionID,`STANDARD_WORKTREE_COLLISION_CLEANUP_UNVERIFIED: ${verification.uncertainty??"git still reports the colliding lane after cleanup"}. Provisioning was blocked.`)}}_internals93.recordWorktreeProvisioningOwner(args2.directory,{callID:args2.callID,parentSessionId:args2.parentSessionID,worktreeSessionId:args2.parentSessionID,taskId:args2.taskId,...provisioningOwnerIdentity})}catch(error93){if(error93 instanceof StandardWorktreeLifecycleError)throw error93;hardStopStandardWorktreeLifecycle(args2.parentSessionID,`STANDARD_WORKTREE_OWNER_PERSIST_FAILED: ${error93 instanceof Error?error93.message:String(error93)}.`)}finally{try{await lifecycleLock.lock._release?.()}catch{}}let childSessionId="",handle,mergeStrategy,reservationId,generation,canonicalBranch,canonicalPath,recoveryClaim;if(recoveryLaunch)childSessionId=recoveryLaunch.childSessionId,handle={worktreePath:recoveryLaunch.worktreePath,branchName:recoveryLaunch.branchName,purpose:"lane",id:sanitizeWorktreeTaskId(args2.taskId),sessionId:args2.parentSessionID},mergeStrategy=recoveryLaunch.strategy,reservationId=recoveryLaunch.reservationId,generation=recoveryLaunch.generation,provisioningOwnerIdentity=recoveryLaunch.provisioningOwner,canonicalBranch=recoveryLaunch.canonicalBranch,canonicalPath=recoveryLaunch.canonicalPath,recoveryClaim=recoveryLaunch.recoveryClaim;else{reservationId=args2.reservationId??`foreground:${args2.parentSessionID}:${resolveRecoveryTaskId(args2)}:${args2.callID}`,generation=provisioningOwnerIdentity.generation,canonicalPath=args2.directory;let provisionResult;try{provisionResult=await _internals93.provisionWorktree(args2.directory,args2.taskId,args2.parentSessionID,{purpose:"lane",worktreeDir:worktreeConfig.worktree_dir,mergeStrategy:worktreeConfig.merge_strategy,depsStrategy:worktreeConfig.deps_strategy,scope:args2.scope})}catch(error93){throw _internals93.removeWorktreeProvisioningOwner(args2.directory,args2.callID,provisioningOwnerIdentity),error93}if("error"in provisionResult){_internals93.removeWorktreeProvisioningOwner(args2.directory,args2.callID,provisioningOwnerIdentity);let message=`STANDARD_WORKTREE_PROVISION_FAILED: ${provisionResult.error}.`;handleStandardWorktreeFailure(args2.parentSessionID,worktreeConfig.policy,message);return}handle=provisionResult,mergeStrategy=worktreeConfig.merge_strategy,recordLiveLaneOwner(args2.directory,{lanePath:handle.worktreePath,branchName:handle.branchName,sessionId:args2.parentSessionID,taskId:args2.taskId})}let originalPrompt=typeof args2.outputArgs.prompt==="string"?args2.outputArgs.prompt:"";args2.outputArgs.prompt=["<worktree_lane_context>",`authoritative_lane_root: ${JSON.stringify(handle.worktreePath)}`,"All FILE declarations and scope-bound edit/write paths must be workspace-relative to authoritative_lane_root.","Remain in authoritative_lane_root: do not change directory into, or edit/write through, the primary checkout or any other worktree.","Example: FILE: src/example.ts means <authoritative_lane_root>/src/example.ts, never <primary-checkout>/src/example.ts.","Do not declare project-root absolute paths; resolve and operate inside this lane root.","</worktree_lane_context>","",originalPrompt].join(`
|
|
1261
1261
|
`);let laneProfile=computeLaneRuntimeProfile(worktreeConfig.runtime_isolation,laneIndex,handle.worktreePath);if(laneProfile)try{let{writeLaneProfileToDiskReal:writeLaneProfileToDiskReal2}=await Promise.resolve().then(() => (init_core3(),exports_core3));await writeLaneProfileToDiskReal2(handle.worktreePath,laneProfile.laneIndex,laneProfile.envOverrides)}catch{}if((worktreeConfig.deps_strategy??"skip")==="skip"){let desc=(args2.description??args2.taskId??"").toLowerCase();if(/\btests?\b/.test(desc)||/\bbuild(ing|s)?\b/.test(desc)||/\blint(ing|er)?\b/.test(desc)||/\bchecks?\b/.test(desc)){let session=ensureAgentSession(args2.parentSessionID);pushAdvisory(session,`WORKTREE_DEPS_SKIP: task ${args2.taskId} was provisioned with deps_strategy: 'skip' (default). This task's gates appear to include test/build commands; the lane may lack node_modules. Set worktree.deps_strategy to 'copy' or 'link' (or use a non-worktree lane) if the task requires host dependencies.`)}}if(!recoveryLaunch){let createResult;try{createResult=await createSessionWithinBudget(client.session.create({body:{parentID:args2.parentSessionID,title:`${args2.description??args2.taskId} (worktree lane)`},query:{directory:handle.worktreePath}}),"STANDARD_WORKTREE_SESSION_CREATE",async(result)=>{let lateChildSessionId=result.data?.id;if(lateChildSessionId){let verification=await teardownEphemeralSessionVerified(client.session,lateChildSessionId);if(!verification.ok)await handleStrandedLane({directory:args2.directory,parentSessionID:args2.parentSessionID,lanePath:handle.worktreePath,branchName:handle.branchName,taskId:args2.taskId,reason:`late child session ${lateChildSessionId} survived verified teardown (${verification.reason})`})}},resolveSessionCreateTimeoutMs(args2))}catch(error93){closeProjectDb(handle.worktreePath);let removal=await _internals93.removeWorktree(handle.worktreePath,args2.directory,{force:!0,worktreeDir:worktreeConfig.worktree_dir}).catch((cleanupError)=>({error:cleanupError instanceof Error?cleanupError.message:String(cleanupError)})),removalError=typeof removal==="object"&&removal!==null&&"error"in removal&&typeof removal.error==="string"?removal.error:void 0;if(removalError)log(`[worktree-isolation] session-create failure cleanup could not remove lane ${handle.worktreePath}: ${removalError}`),await handleStrandedLane({directory:args2.directory,parentSessionID:args2.parentSessionID,lanePath:handle.worktreePath,branchName:handle.branchName,taskId:args2.taskId,reason:removalError});_internals93.removeWorktreeProvisioningOwner(args2.directory,args2.callID,provisioningOwnerIdentity);let message=`STANDARD_WORKTREE_SESSION_CREATE_FAILED: ${error93 instanceof Error?error93.message:String(error93)}.`;handleStandardWorktreeFailure(args2.parentSessionID,worktreeConfig.policy,message);return}if(!createResult?.data?.id){closeProjectDb(handle.worktreePath);let removal=await _internals93.removeWorktree(handle.worktreePath,args2.directory,{force:!0,worktreeDir:worktreeConfig.worktree_dir}).catch((cleanupError)=>({error:cleanupError instanceof Error?cleanupError.message:String(cleanupError)})),removalError=typeof removal==="object"&&removal!==null&&"error"in removal&&typeof removal.error==="string"?removal.error:void 0;if(removalError)log(`[worktree-isolation] session-create failure cleanup could not remove lane ${handle.worktreePath}: ${removalError}`),await handleStrandedLane({directory:args2.directory,parentSessionID:args2.parentSessionID,lanePath:handle.worktreePath,branchName:handle.branchName,taskId:args2.taskId,reason:removalError});_internals93.removeWorktreeProvisioningOwner(args2.directory,args2.callID,provisioningOwnerIdentity);let createError=createResult.error,message=`STANDARD_WORKTREE_SESSION_CREATE_FAILED: ${typeof createError==="string"?createError:JSON.stringify(createError??"missing session id")}.`;handleStandardWorktreeFailure(args2.parentSessionID,worktreeConfig.policy,message);return}childSessionId=createResult.data.id}if(!childSessionId)throw Error("STANDARD_WORKTREE_SESSION_CREATE_FAILED: missing child session id.");args2.outputArgs.task_id=childSessionId,recordLaneChildSession(childSessionId,"coder"),ensureAgentSession(childSessionId,"coder",handle.worktreePath),recordSessionWorkspaceRoot(childSessionId,handle.worktreePath),rememberStandardWorktreeDispatch({callID:args2.callID,parentSessionID:args2.parentSessionID,taskId:args2.taskId,planTaskId:args2.planTaskId,reservationId,generation,provisioningOwner:provisioningOwnerIdentity,canonicalBranch,canonicalPath,handle,mergeStrategy,recoveryClaim,laneIndex,worktree_dir:worktreeConfig.worktree_dir})}async function preserveBackgroundWorktreeOwnershipForCallId(callID){let dispatch=standardWorktreeByCallID.get(callID);if(!dispatch)return{outcome:"not-found"};let refProc;try{refProc=_internals93.bunSpawn([_internals93.resolveGitExecutable(),"-C",dispatch.handle.worktreePath,"rev-parse","HEAD"],{stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:PRESERVE_COMMIT_TIMEOUT_MS})}catch(error93){return{outcome:"preserve-failed",error:`git rev-parse could not start: ${error93 instanceof Error?error93.message:String(error93)}`}}let ref="";try{let exitCode=await refProc.exited;if(exitCode!==0)return{outcome:"preserve-failed",error:await refProc.stderr.text()||`git rev-parse exited ${exitCode}`};ref=(await refProc.stdout.text()).trim()}finally{try{refProc.kill()}catch{}}if(!ref)return{outcome:"preserve-failed",error:"git rev-parse returned empty"};let session=Buffer.from(dispatch.handle.sessionId,"utf8").toString("base64url"),lane=Buffer.from(dispatch.handle.id,"utf8").toString("base64url"),callDigest=createHash48("sha256").update(callID).digest("hex").slice(0,12),tag=`swarm-preserved-owner/${session}/${lane}/${callDigest}`,tagProc;try{tagProc=_internals93.bunSpawn([_internals93.resolveGitExecutable(),"-C",dispatch.handle.worktreePath,"tag",tag,ref],{stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:PRESERVE_COMMIT_TIMEOUT_MS})}catch(error93){return{outcome:"preserve-failed",error:`git tag could not start: ${error93 instanceof Error?error93.message:String(error93)}`}}try{let exitCode=await tagProc.exited;if(exitCode!==0)return{outcome:"preserve-failed",error:await tagProc.stderr.text()||`git tag exited ${exitCode}`}}finally{try{tagProc.kill()}catch{}}return{outcome:"preserved",tag,ref}}async function preserveDirtyWorktreeForCallId(callID,reason,_directory2,_worktree_dir){let dispatch=standardWorktreeByCallID.get(callID),worktreePath,parentSessionID;if(dispatch)worktreePath=dispatch.handle.worktreePath,parentSessionID=dispatch.parentSessionID;else{let awaiting=awaitingMergeByCallID.get(callID);if(!awaiting)return{outcome:"clean",preserved:!1};worktreePath=awaiting.worktreePath,parentSessionID=awaiting.parentSessionID}let statusProc;try{statusProc=_internals93.bunSpawn([_internals93.resolveGitExecutable(),"-C",worktreePath,"status","--porcelain"],{stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:PRESERVE_COMMIT_TIMEOUT_MS})}catch(error93){return{outcome:"preserve-failed",preserved:!1,error:`git status could not start: ${error93 instanceof Error?error93.message:String(error93)}`}}let statusStdout="",statusStderr="";try{let exitCode=await statusProc.exited;if(statusStdout=await statusProc.stdout.text(),statusStderr=await statusProc.stderr.text(),exitCode!==0)return log(`[swarm] preserveDirtyWorktreeForCallId: git status failed for ${callID}: ${statusStderr}`),{outcome:"preserve-failed",preserved:!1,error:`git status failed: ${statusStderr||`exit ${exitCode}`}`}}finally{try{statusProc.kill()}catch{}}if(statusStdout.trim()==="")return{outcome:"clean",preserved:!1};let addProc;try{addProc=_internals93.bunSpawn([_internals93.resolveGitExecutable(),"-C",worktreePath,"add","-A"],{stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:PRESERVE_COMMIT_TIMEOUT_MS})}catch(error93){return{outcome:"preserve-failed",preserved:!1,error:`git add could not start: ${error93 instanceof Error?error93.message:String(error93)}`}}try{let addExit=await addProc.exited;if(addExit!==0){let addErr=await addProc.stderr.text();return log(`[swarm] preserveDirtyWorktreeForCallId: git add failed for ${callID}: ${addErr}`),{outcome:"preserve-failed",preserved:!1,error:`git add failed: ${addErr||`exit ${addExit}`}`}}}finally{try{addProc.kill()}catch{}}let isoDate=new Date().toISOString(),sanitizedCallID=callID.replace(/[^A-Za-z0-9._-]/g,"-").slice(0,64),commitMessage=`swarm-preserved: ${reason} for callID ${sanitizedCallID} at ${isoDate}`,commitProc;try{commitProc=_internals93.bunSpawn([_internals93.resolveGitExecutable(),"-C",worktreePath,"commit","-m",commitMessage],{stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:PRESERVE_COMMIT_TIMEOUT_MS})}catch(error93){return{outcome:"preserve-failed",preserved:!1,error:`git commit could not start: ${error93 instanceof Error?error93.message:String(error93)}`}}let commitHash="";try{let commitExit=await commitProc.exited;if(commitExit!==0){let commitErr=await commitProc.stderr.text();return log(`[swarm] preserveDirtyWorktreeForCallId: git commit failed for ${callID}: ${commitErr}`),{outcome:"preserve-failed",preserved:!1,error:`git commit failed: ${commitErr||`exit ${commitExit}`}`}}}finally{try{commitProc.kill()}catch{}}let hashProc;try{hashProc=_internals93.bunSpawn([_internals93.resolveGitExecutable(),"-C",worktreePath,"rev-parse","HEAD"],{stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:PRESERVE_COMMIT_TIMEOUT_MS})}catch(error93){return{outcome:"preserve-failed",preserved:!1,error:`git rev-parse could not start: ${error93 instanceof Error?error93.message:String(error93)}`}}try{let hashExit=await hashProc.exited;if(hashExit!==0){let hashErr=await hashProc.stderr.text();return log(`[swarm] preserveDirtyWorktreeForCallId: git rev-parse failed for ${callID}: ${hashErr}`),{outcome:"preserve-failed",preserved:!1,error:`git rev-parse failed: ${hashErr||`exit ${hashExit}`}`}}commitHash=(await hashProc.stdout.text()).trim()}finally{try{hashProc.kill()}catch{}}if(!commitHash)return{outcome:"preserve-failed",preserved:!1,error:"git rev-parse returned empty hash"};let shortHash=commitHash.slice(0,8),tagName=`swarm-preserved-${sanitizedCallID}-${shortHash}`,tagProc;try{tagProc=_internals93.bunSpawn([_internals93.resolveGitExecutable(),"-C",worktreePath,"tag",tagName],{stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:PRESERVE_COMMIT_TIMEOUT_MS})}catch(error93){return{outcome:"preserve-failed",preserved:!1,error:`git tag could not start: ${error93 instanceof Error?error93.message:String(error93)}`}}try{let tagExit=await tagProc.exited;if(tagExit!==0){let tagErr=await tagProc.stderr.text();return log(`[swarm] preserveDirtyWorktreeForCallId: git tag failed for ${callID}: ${tagErr}`),{outcome:"preserve-failed",preserved:!1,error:`git tag failed: ${tagErr||`exit ${tagExit}`}`}}}finally{try{tagProc.kill()}catch{}}let session=ensureAgentSession(parentSessionID);return pushAdvisory(session,`STANDARD_WORKTREE_PRESERVED: dispatch ${callID} dirty work preserved as commit ${commitHash} (tag: ${tagName}; reason: ${reason}); worktree will be cleaned.`),{outcome:"preserved",preserved:!0,ref:commitHash}}async function preserveDirtyWorktreeAtPath(worktreePath,branchName,reason,_directory2,_worktree_dir){let statusProc;try{statusProc=_internals93.bunSpawn([_internals93.resolveGitExecutable(),"-C",worktreePath,"status","--porcelain"],{stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:PRESERVE_COMMIT_TIMEOUT_MS})}catch(error93){return{outcome:"preserve-failed",preserved:!1,error:`git status could not start: ${error93 instanceof Error?error93.message:String(error93)}`}}let statusStdout="",statusStderr="";try{let exitCode=await statusProc.exited;if(statusStdout=await statusProc.stdout.text(),statusStderr=await statusProc.stderr.text(),exitCode!==0)return log(`[swarm] preserveDirtyWorktreeAtPath: git status failed for ${worktreePath}: ${statusStderr}`),{outcome:"preserve-failed",preserved:!1,error:`git status failed: ${statusStderr||`exit ${exitCode}`}`}}finally{try{statusProc.kill()}catch{}}if(statusStdout.trim()==="")return{outcome:"clean",preserved:!1};let addProc;try{addProc=_internals93.bunSpawn([_internals93.resolveGitExecutable(),"-C",worktreePath,"add","-A"],{stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:PRESERVE_COMMIT_TIMEOUT_MS})}catch(error93){return{outcome:"preserve-failed",preserved:!1,error:`git add could not start: ${error93 instanceof Error?error93.message:String(error93)}`}}try{let addExit=await addProc.exited;if(addExit!==0){let addErr=await addProc.stderr.text();return log(`[swarm] preserveDirtyWorktreeAtPath: git add failed for ${worktreePath}: ${addErr}`),{outcome:"preserve-failed",preserved:!1,error:`git add failed: ${addErr||`exit ${addExit}`}`}}}finally{try{addProc.kill()}catch{}}let isoDate=new Date().toISOString(),sanitizedPath=worktreePath.replace(/[^A-Za-z0-9._-]/g,"-").slice(0,64),sanitizedBranch=branchName.replace(/[^A-Za-z0-9._-]/g,"-").slice(0,64),commitMessage=`swarm-preserved: ${reason} for worktree ${sanitizedPath} at ${isoDate}`,commitProc;try{commitProc=_internals93.bunSpawn([_internals93.resolveGitExecutable(),"-C",worktreePath,"commit","-m",commitMessage],{stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:PRESERVE_COMMIT_TIMEOUT_MS})}catch(error93){return{outcome:"preserve-failed",preserved:!1,error:`git commit could not start: ${error93 instanceof Error?error93.message:String(error93)}`}}let commitHash="";try{let commitExit=await commitProc.exited;if(commitExit!==0){let commitErr=await commitProc.stderr.text();return log(`[swarm] preserveDirtyWorktreeAtPath: git commit failed for ${worktreePath}: ${commitErr}`),{outcome:"preserve-failed",preserved:!1,error:`git commit failed: ${commitErr||`exit ${commitExit}`}`}}}finally{try{commitProc.kill()}catch{}}let hashProc;try{hashProc=_internals93.bunSpawn([_internals93.resolveGitExecutable(),"-C",worktreePath,"rev-parse","HEAD"],{stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:PRESERVE_COMMIT_TIMEOUT_MS})}catch(error93){return{outcome:"preserve-failed",preserved:!1,error:`git rev-parse could not start: ${error93 instanceof Error?error93.message:String(error93)}`}}try{let hashExit=await hashProc.exited;if(hashExit!==0){let hashErr=await hashProc.stderr.text();return log(`[swarm] preserveDirtyWorktreeAtPath: git rev-parse failed for ${worktreePath}: ${hashErr}`),{outcome:"preserve-failed",preserved:!1,error:`git rev-parse failed: ${hashErr||`exit ${hashExit}`}`}}commitHash=(await hashProc.stdout.text()).trim()}finally{try{hashProc.kill()}catch{}}if(!commitHash)return{outcome:"preserve-failed",preserved:!1,error:"git rev-parse returned empty hash"};let shortHash=commitHash.slice(0,8),tagName=`swarm-preserved-worktree-${sanitizedBranch}-${shortHash}`,tagProc;try{tagProc=_internals93.bunSpawn([_internals93.resolveGitExecutable(),"-C",worktreePath,"tag",tagName],{stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:PRESERVE_COMMIT_TIMEOUT_MS})}catch(error93){return{outcome:"preserve-failed",preserved:!1,error:`git tag could not start: ${error93 instanceof Error?error93.message:String(error93)}`}}try{let tagExit=await tagProc.exited;if(tagExit!==0){let tagErr=await tagProc.stderr.text();return log(`[swarm] preserveDirtyWorktreeAtPath: git tag failed for ${worktreePath}: ${tagErr}`),{outcome:"preserve-failed",preserved:!1,error:`git tag failed: ${tagErr||`exit ${tagExit}`}`}}}finally{try{tagProc.kill()}catch{}}return{outcome:"preserved",preserved:!0,ref:commitHash}}async function cleanupStandardWorktreeForCallId(callID,reason,directory,worktree_dir,options){let dispatch=standardWorktreeByCallID.get(callID),worktreePath,branchName,parentSessionID;if(dispatch)worktreePath=dispatch.handle.worktreePath,branchName=dispatch.handle.branchName,parentSessionID=dispatch.parentSessionID;else{let awaiting=awaitingMergeByCallID.get(callID);if(!awaiting)return{removedWorktree:!1,cleanedBranch:!1,preservedRecoveryLane:!1};worktreePath=awaiting.worktreePath,branchName=awaiting.branch,parentSessionID=awaiting.parentSessionID}if(dispatch?.recoveryClaim&&(reason==="denied"||reason==="cancelled")){let renewResult=_internals93.renewWorktreeRecoveryClaim(directory,{authorityDigest:dispatch.recoveryClaim.authorityDigest,claimantCallID:callID,claimRevision:dispatch.recoveryClaim.claimRevision,rawToken:dispatch.recoveryClaim.rawToken,leaseMs:WORKTREE_RECOVERY_CLAIM_LEASE_MS});if(!renewResult.ok){let message=`STANDARD_WORKTREE_RECOVERY_ABORT_RELEASE_FAILED: dispatch ${callID} preserved lane ${worktreePath} (${branchName}) after ${reason}, but ${describeRecoveryMutationFailure({action:"renew",code:renewResult.code,reason:renewResult.reason})}. No tracking teardown was performed.`,session3=ensureAgentSession(parentSessionID);throw pushAdvisory(session3,message),Error(message)}let releaseResult=_internals93.releaseWorktreeRecoveryClaim(directory,{authorityDigest:dispatch.recoveryClaim.authorityDigest,claimantCallID:callID,claimRevision:dispatch.recoveryClaim.claimRevision,rawToken:dispatch.recoveryClaim.rawToken});if(!releaseResult.ok){let message=`STANDARD_WORKTREE_RECOVERY_ABORT_RELEASE_FAILED: dispatch ${callID} preserved lane ${worktreePath} (${branchName}) after ${reason}, but ${describeRecoveryMutationFailure({action:"release",code:releaseResult.code,reason:releaseResult.reason})}. No tracking teardown was performed.`,session3=ensureAgentSession(parentSessionID);throw pushAdvisory(session3,message),Error(message)}standardWorktreeByCallID.delete(callID),awaitingMergeByCallID.delete(callID);let session2=ensureAgentSession(parentSessionID);return pushAdvisory(session2,`STANDARD_WORKTREE_RECOVERY_ABORT_PRESERVED: dispatch ${callID} released its recovery claim and preserved lane ${worktreePath} (${branchName}) after ${reason}.`),{removedWorktree:!1,cleanedBranch:!1,preservedRecoveryLane:!0}}let preserveResult;if(reason==="denied"||reason==="cancelled"){try{preserveResult=await _internals93.preserveDirtyWorktreeForCallId(callID,reason,directory,worktree_dir)}catch(err){log(`[swarm] cleanupStandardWorktreeForCallId: preserveDirtyWorktreeForCallId threw for ${callID}: ${err}`),preserveResult={outcome:"preserve-failed",preserved:!1,error:String(err)}}if(preserveResult.outcome==="clean")try{preserveResult=await _internals93.preserveDirtyWorktreeForCallId(callID,reason,directory,worktree_dir)}catch(err){log(`[swarm] cleanupStandardWorktreeForCallId: final preservation check threw for ${callID}: ${err}`),preserveResult={outcome:"preserve-failed",preserved:!1,error:String(err)}}}if(preserveResult&&preserveResult.outcome==="preserve-failed"){standardWorktreeByCallID.delete(callID),awaitingMergeByCallID.delete(callID);let session2=ensureAgentSession(parentSessionID);return pushAdvisory(session2,`STANDARD_WORKTREE_PRESERVATION_FAILED_ABORT_CLEANUP: dispatch ${callID} has dirty uncommitted work but preservation failed (${preserveResult.error}). Cleanup aborted to protect uncommitted work. Investigate and resolve manually. Worktree=${worktreePath}; branch=${branchName}.`),{removedWorktree:!1,cleanedBranch:!1,preservedRecoveryLane:!1}}let removedWorktree=!1;try{closeProjectDb(worktreePath);let result=await _internals93.removeWorktree(worktreePath,directory,{force:!0,worktreeDir:worktree_dir});if(!("error"in result))removedWorktree=!0;else if(result.error.includes("is not a working tree")&&await pathExists3(worktreePath)&&isPathUnderSwarmWorktreeBase(worktreePath,directory,worktree_dir?[worktree_dir]:[]))try{await fs69.rm(worktreePath,{recursive:!0,force:!0}),removedWorktree=!await pathExists3(worktreePath)}catch(err){log(`[swarm] cleanupStandardWorktreeForCallId: residual directory cleanup failed for ${callID}: ${err}`)}}catch(err){log(`[swarm] cleanupStandardWorktreeForCallId: removeWorktree failed for ${callID}: ${err}`)}let cleanedBranch=!1;if(options?.retainBranch){let retainedSession=ensureAgentSession(parentSessionID);pushAdvisory(retainedSession,`STANDARD_WORKTREE_BRANCH_RETAINED: dispatch ${callID} removed worktree ${worktreePath} but retained branch ${branchName} (unstaged landing); the branch is the recovery backup until the landed changes are committed.`)}else try{cleanedBranch=!("error"in await _internals93.postMergeCleanup(directory,branchName))}catch(err){log(`[swarm] cleanupStandardWorktreeForCallId: postMergeCleanup failed for ${callID}: ${err}`)}standardWorktreeByCallID.delete(callID),awaitingMergeByCallID.delete(callID);let session=ensureAgentSession(parentSessionID);return pushAdvisory(session,`STANDARD_WORKTREE_CLEANUP: dispatch ${callID} cleaned up (reason: ${reason}); worktree=${worktreePath}; branch=${branchName}.`),{removedWorktree,cleanedBranch,preservedRecoveryLane:!1}}async function abortStandardWorktreeDispatch(callID,reason,directory){let dispatch=standardWorktreeByCallID.get(callID);if(!dispatch){let session=ensureAgentSession("unknown");pushAdvisory(session,`STANDARD_WORKTREE_ABORT_NOOP: dispatch ${callID} has no tracked worktree to abort (reason: ${reason}).`);return}await cleanupStandardWorktreeForCallId(callID,reason,directory,dispatch.worktree_dir)}function runSerializedWithMergeBacks(task){let queued=standardWorktreeMergeQueue.then(task,task);return standardWorktreeMergeQueue=queued,queued}async function finishStandardWorktreeDispatch(directory,dispatch,config3,callID,settlement={}){let wtConfig=config3?resolveWorktreeIsolationConfig(config3):DEFAULT_WORKTREE_ISOLATION_CONFIG,resolvedCallID=callID??dispatch.callID,run=async()=>{let statusKey=dispatch.planTaskId??dispatch.taskId,failRecoverySettlement=(stage,message,provenance)=>{recordWorktreeMergeFailure(statusKey,{outcome:"failed",stage,message,worktreePath:dispatch.handle.worktreePath,branch:dispatch.handle.branchName,completedAt:Date.now()});let session=ensureAgentSession(dispatch.parentSessionID);return pushAdvisory(session,`STANDARD_WORKTREE_RECOVERY_MUTATION_FAILED: task ${dispatch.taskId} preserved at ${dispatch.handle.worktreePath}; ${message}.`),{outcome:"failed",stage,message,provenance}},renewRecoveryClaimLease=(phase,provenance)=>{if(!dispatch.recoveryClaim)return;let renewed=_internals93.renewWorktreeRecoveryClaim(directory,{authorityDigest:dispatch.recoveryClaim.authorityDigest,claimantCallID:resolvedCallID,claimRevision:dispatch.recoveryClaim.claimRevision,rawToken:dispatch.recoveryClaim.rawToken,leaseMs:WORKTREE_RECOVERY_CLAIM_LEASE_MS});if(renewed.ok)return;return failRecoverySettlement("recovery-claim-renew",`The live recovery lane could not extend its lease ${phase}; ${describeRecoveryMutationFailure({action:"renew",code:renewed.code,reason:renewed.reason})}`,provenance)},releaseRecoveryClaim=(provenance)=>{if(!dispatch.recoveryClaim)return;let released=_internals93.releaseWorktreeRecoveryClaim(directory,{authorityDigest:dispatch.recoveryClaim.authorityDigest,claimantCallID:resolvedCallID,claimRevision:dispatch.recoveryClaim.claimRevision,rawToken:dispatch.recoveryClaim.rawToken});if(released.ok)return;return failRecoverySettlement("recovery-claim-release",`The preserved recovery lane could not release its exact claim after settlement; ${describeRecoveryMutationFailure({action:"release",code:released.code,reason:released.reason})}`,provenance)},publishRecoveryAuthority=async(provenance,conflictFiles)=>{let published=await publishRecoveryAuthorityForSettlement({directory,dispatch,taskId:statusKey,provenance,conflictFiles});if(published.ok)return;return failRecoverySettlement("recovery-authority-publish",`The preserved original lane could not publish recoverable authority; ${describeRecoveryMutationFailure({action:"publish",code:published.code,reason:published.reason})}`,provenance)},preMergeRenewFailure=renewRecoveryClaimLease("before merge-back");if(preMergeRenewFailure)return preMergeRenewFailure;let mergeResult=await(async()=>{if(!dispatch.recoveryClaim){let epicLanding=settlement.commitLanding===void 0?_internals93.epicCommitLandingFor(directory,dispatch.planTaskId):void 0;if(epicLanding&&"refused"in epicLanding)return{failed:!0,stage:epicLanding.stage,message:epicLanding.message};return _internals93.attemptMergeBackFromDirty(dispatch.handle.worktreePath,dispatch.handle.branchName,directory,getMergeStrategy({merge_strategy:dispatch.mergeStrategy}),{operationId:settlement.operationId,resume:settlement.resume,onBeforeMerge:settlement.onBeforeMerge,commitLanding:settlement.commitLanding??epicLanding?.commitLanding,...epicLanding?{landingCommitMessage:epicLanding.landingCommitMessage}:{}})}let coordinates=dispatch.recoveryClaim.coordinates;if(!coordinates)return{failed:!0,stage:"recovery-coordinates",message:"Claimed recovery lane is missing immutable Git coordinates"};let provenance={operationId:settlement.operationId??`recovery:${dispatch.recoveryClaim.authorityDigest}`,sourceHead:coordinates.sourceHeadOid,targetHeadBefore:coordinates.targetHeadOid,branchName:dispatch.handle.branchName,strategy:coordinates.strategy};if(settlement.onBeforeMerge)await settlement.onBeforeMerge(provenance);let recovered=await _internals93.recoverMergeBackFromImmutableCoordinates(directory,coordinates);if("merged"in recovered&&recovered.merged){if(recovered.sourceCommitOrder&&recovered.rewrittenCommitOrder)dispatch.recoveryClaim.settlement={sourceCommitOrder:recovered.sourceCommitOrder,rewrittenCommitOrder:recovered.rewrittenCommitOrder};return{merged:!0,strategy:recovered.strategy,autoCommitted:!1,cleaned:!0,reconciled:!1,provenance}}if("conflict"in recovered&&recovered.conflict)return{partial:!0,stage:"conflict",autoCommitted:!1,cleaned:!0,message:recovered.message,conflictFiles:recovered.files,provenance};return{failed:!0,stage:"recovery",message:"error"in recovered?recovered.error:"Immutable recovery returned an unexpected result",provenance}})();if("merged"in mergeResult&&mergeResult.merged){let mergedSettlement={outcome:"merged",strategy:mergeResult.strategy,autoCommitted:mergeResult.autoCommitted??!1,cleaned:mergeResult.cleaned??!1,reconciled:mergeResult.reconciled??!1,provenance:mergeResult.provenance};if(settlement.onMerged)try{await settlement.onMerged(mergedSettlement)}catch(error93){let failedSettlement={outcome:"failed",stage:"settlement-persist",message:`Git merge-back succeeded but settlement persistence failed: ${String(error93)}`,provenance:mergeResult.provenance},publishFailure=await publishRecoveryAuthority(mergeResult.provenance);if(publishFailure)failedSettlement.message=`${failedSettlement.message} ${publishFailure.message}`;let releaseFailure=releaseRecoveryClaim(mergeResult.provenance);if(releaseFailure)failedSettlement.message=`${failedSettlement.message} ${releaseFailure.message}`;recordWorktreeMergeFailure(statusKey,{outcome:"failed",stage:failedSettlement.stage,message:failedSettlement.message,worktreePath:dispatch.handle.worktreePath,branch:dispatch.handle.branchName,completedAt:Date.now()});let session=ensureAgentSession(dispatch.parentSessionID);return pushAdvisory(session,`STANDARD_WORKTREE_SETTLEMENT_PERSIST_FAILED: task ${dispatch.taskId} landed in ${directory}, but settlement persistence failed; worktree and branch preserved at ${dispatch.handle.worktreePath} (${dispatch.handle.branchName}).`),failedSettlement}let preCleanupRenewFailure=renewRecoveryClaimLease("before cleanup/finalization",mergeResult.provenance);if(preCleanupRenewFailure)return preCleanupRenewFailure;let cleanupResult=await cleanupStandardWorktreeForCallId(resolvedCallID,"success",directory,dispatch.worktree_dir,{retainBranch:mergeResult.strategy==="squash-unstaged"});if(dispatch.recoveryClaim){let request={authorityDigest:dispatch.recoveryClaim.authorityDigest,claimantCallID:resolvedCallID,claimRevision:dispatch.recoveryClaim.claimRevision,rawToken:dispatch.recoveryClaim.rawToken,settlement:dispatch.recoveryClaim.settlement};if(cleanupResult.removedWorktree&&cleanupResult.cleanedBranch){let finalized=_internals93.finalizeWorktreeRecoveryAuthority(directory,request);if(!finalized.ok)return failRecoverySettlement("recovery-claim-finalize",`The merged recovery lane was cleaned up but could not finalize its exact claim; ${describeRecoveryMutationFailure({action:"finalize",code:finalized.code,reason:finalized.reason})}`,mergeResult.provenance)}else{let releaseFailure=releaseRecoveryClaim(mergeResult.provenance);if(releaseFailure)return releaseFailure}}clearWorktreeMergeStatus(statusKey);try{let{removeLaneProfileFromDiskReal:removeLaneProfileFromDiskReal2}=await Promise.resolve().then(() => (init_core3(),exports_core3));await removeLaneProfileFromDiskReal2(dispatch.handle.worktreePath,dispatch.laneIndex)}catch{}let state2=serializationStateBySessionID.get(dispatch.parentSessionID);if(state2)state2.successfulDispatchesSince++,checkStandardWorktreeSerializationRelease(dispatch.parentSessionID,wtConfig);try{verifyReviewerScopeGenerationMergeBack({parentSessionID:dispatch.parentSessionID,taskId:statusKey,coderCallID:resolvedCallID,primaryDirectory:directory})}catch{}return mergedSettlement}if("partial"in mergeResult){let publishFailure=await publishRecoveryAuthority(mergeResult.provenance,mergeResult.conflictFiles);if(publishFailure)return publishFailure;let releaseFailure=releaseRecoveryClaim(mergeResult.provenance);if(releaseFailure)return releaseFailure;recordWorktreeMergeFailure(statusKey,{outcome:"partial",stage:mergeResult.stage,message:mergeResult.message,worktreePath:dispatch.handle.worktreePath,branch:dispatch.handle.branchName,completedAt:Date.now()});let session=ensureAgentSession(dispatch.parentSessionID);pushAdvisory(session,`STANDARD_WORKTREE_MERGE_PARTIAL: task ${dispatch.taskId} preserved at ${dispatch.handle.worktreePath}; stage: ${mergeResult.stage}; ${mergeResult.message}`+(mergeResult.code?` (code: ${mergeResult.code})`:"")+(mergeResult.recoveryHint?` ${mergeResult.recoveryHint}`:""));try{markReviewerScopeGenerationMergebackPending({parentSessionID:dispatch.parentSessionID,taskId:statusKey,coderCallID:resolvedCallID})}catch{}return{outcome:"partial",stage:mergeResult.stage,message:mergeResult.message,autoCommitted:mergeResult.autoCommitted,cleaned:mergeResult.cleaned,conflictFiles:mergeResult.conflictFiles,code:mergeResult.code,recoveryHint:mergeResult.recoveryHint,provenance:mergeResult.provenance}}if("failed"in mergeResult){let publishFailure=await publishRecoveryAuthority(mergeResult.provenance);if(publishFailure)return publishFailure;let releaseFailure=releaseRecoveryClaim(mergeResult.provenance);if(releaseFailure)return releaseFailure;recordWorktreeMergeFailure(statusKey,{outcome:"failed",stage:mergeResult.stage,message:mergeResult.message,worktreePath:dispatch.handle.worktreePath,branch:dispatch.handle.branchName,completedAt:Date.now()});let session=ensureAgentSession(dispatch.parentSessionID),location=mergeResult.stage===SOURCE_WORKTREE_GONE_STAGE||mergeResult.stage===SOURCE_WORKTREE_UNCERTAIN_STAGE?`lane worktree ${dispatch.handle.worktreePath} no longer exists`:`preserved at ${dispatch.handle.worktreePath}`;pushAdvisory(session,`STANDARD_WORKTREE_MERGE_FAILED: task ${dispatch.taskId} ${location}; stage: ${mergeResult.stage}; ${mergeResult.message}.`);try{markReviewerScopeGenerationMergebackPending({parentSessionID:dispatch.parentSessionID,taskId:statusKey,coderCallID:resolvedCallID})}catch{}return{outcome:"failed",stage:mergeResult.stage,message:mergeResult.message,provenance:mergeResult.provenance}}return{outcome:"failed",stage:"merge",message:"Merge-back returned an unexpected result"}},queuedRun=standardWorktreeMergeQueue.then(run,run);standardWorktreeMergeQueue=queuedRun;let result;try{result=await queuedRun}catch(error93){if(standardWorktreeByCallID.delete(resolvedCallID),awaitingMergeByCallID.delete(resolvedCallID),dispatch.recoveryClaim)try{_internals93.releaseWorktreeRecoveryClaim(directory,{authorityDigest:dispatch.recoveryClaim.authorityDigest,claimantCallID:resolvedCallID,claimRevision:dispatch.recoveryClaim.claimRevision,rawToken:dispatch.recoveryClaim.rawToken})}catch{}let message=`Unexpected worktree settlement failure: ${error93 instanceof Error?error93.message:String(error93)}`;recordWorktreeMergeFailure(dispatch.planTaskId??dispatch.taskId,{outcome:"failed",stage:"merge",message,worktreePath:dispatch.handle.worktreePath,branch:dispatch.handle.branchName,completedAt:Date.now()});let session=ensureAgentSession(dispatch.parentSessionID);return pushAdvisory(session,`STANDARD_WORKTREE_SETTLEMENT_FAILED: task ${dispatch.taskId} preserved at ${dispatch.handle.worktreePath}; ${message}.`),{outcome:"failed",stage:"merge",message}}if(resolvedCallID)awaitingMergeByCallID.delete(resolvedCallID);return result}async function readLaneEnvFileFromDisk(worktreePath,laneIndex){let envPath=path108.join(worktreePath,".swarm","lanes",`${laneIndex}.env`),content;try{content=await fs69.readFile(envPath,"utf-8")}catch(err){if(err.code==="ENOENT")return{};return log(`[worktree-isolation] failed to read lane env file ${envPath}: ${err.message}`),{}}let result={};for(let rawLine of content.split(`
|
|
1262
|
-
`)){let line=rawLine.trim();if(!line||line.startsWith("#"))continue;let eqIdx=line.indexOf("=");if(eqIdx<0)continue;let k=line.slice(0,eqIdx),v=line.slice(eqIdx+1);if(!isValidEnvKey(k))continue;if(isUntrustedEnvKey(k))continue;result[k]=v}return result}var MAX_TRACKED_STANDARD_WORKTREE_CALLS=256,awaitingMergeByCallID,standardWorktreeByCallID,standardWorktreeSerializationSessions,LANE_CHILD_SESSION_LIMIT=512,laneChildSessionAgents,standardWorktreeMergeQueue,standardWorktreeLaneIndexBySession,serializationStateBySessionID,WORKTREE_RECOVERY_CLAIM_LEASE_MS=300000,WORKTREE_SESSION_CREATE_TIMEOUT_MS=30000,WORKTREE_SESSION_CREATE_SETTLE_GRACE_MS=5000,StandardWorktreeLifecycleError,WORKTREE_LIFECYCLE_LOCK_WAIT_MARGIN_MS=5000,WORKTREE_LIFECYCLE_LOCK_WAIT_MIN_MS=1e4,WORKTREE_DISPATCH_HOOK_BUDGET_MS=60000,WORKTREE_PROVISION_ALLOWANCE_MS=15000,standardWorktreeDegradationReasonBySession,WORKTREE_LIST_TIMEOUT_MS=15000,PRESERVE_COMMIT_TIMEOUT_MS=30000,_internals93;var init_worktree_isolation=__esm(()=>{init_constants();init_schema();init_project_db();init_task_landing();init_file_locks();init_lane_owners();init_executor();init_state();init_bun_compat();init_canonical_root();init_ephemeral_session_teardown();init_git_executable();init_logger();init_timeout();init_worktree();init_merge2();init_reviewer_scope_mergeback();init_dead_lane_reclaim();init_worktree_merge_status();init_worktree_provisioning_owner();init_worktree_recovery_authority();init_worktree_isolation_config();awaitingMergeByCallID=new Map,standardWorktreeByCallID=new Map,standardWorktreeSerializationSessions=new Set,laneChildSessionAgents=new Map;standardWorktreeMergeQueue=Promise.resolve(),standardWorktreeLaneIndexBySession=new Map,serializationStateBySessionID=new Map;StandardWorktreeLifecycleError=class StandardWorktreeLifecycleError extends Error{kind="standard-worktree-lifecycle";constructor(message){super(message);this.name="StandardWorktreeLifecycleError"}};standardWorktreeDegradationReasonBySession=new Map;_internals93={epicCommitLandingFor,provisionWorktree,removeWorktree,attemptMergeBackFromDirty,recoverMergeBackFromImmutableCoordinates,postMergeCleanup,pruneStaleWorktreeMetadata,readLaneEnvFileFromDisk,serializationStateBySessionID,rememberStandardWorktreeSerializationSession,awaitingMergeByCallID,startupOrphanRecovery,cleanupOrphanedBranches,cleanupStandardWorktreeForCallId,preserveDirtyWorktreeForCallId,preserveBackgroundWorktreeOwnershipForCallId,tryAcquireWorktreeLifecycleLock:tryAcquireLock,acquireWorktreeLifecycleLockWithin,resolveWorktreeLifecycleLockWaitMs,now:()=>Date.now(),sleep:(ms)=>new Promise((resolve53)=>setTimeout(resolve53,ms)),recordWorktreeProvisioningOwner,removeWorktreeProvisioningOwner,lookupWorktreeRecoveryAuthoritiesByTask,claimWorktreeRecoveryAuthority,renewWorktreeRecoveryClaim,releaseWorktreeRecoveryClaim,finalizeWorktreeRecoveryAuthority,publishWorktreeRecoveryAuthority,replayWorktreeRecoveryClaimJournal,buildWorktreeRecoveryPublishIdentity,preserveDirtyWorktreeAtPath,worktreeSessionCreateTimeoutMs:WORKTREE_SESSION_CREATE_TIMEOUT_MS,worktreeSessionCreateSettleGraceMs:WORKTREE_SESSION_CREATE_SETTLE_GRACE_MS,createSessionWithinBudget,abortStandardWorktreeDispatch,standardWorktreeByCallID,preProvisionCollisionCheck,inspectStandardWorktreeCollisionOwnership:inspectStandardWorktreeCollisionOwnership2,isLaneOwnedByCurrentSession,bunSpawn,resolveGitExecutable}});var exports_coder_settlement={};__export(exports_coder_settlement,{transferCoderSettlementToBackground:()=>transferCoderSettlementToBackground,settleCoderDispatch:()=>settleCoderDispatch,releaseCoderDispatchOwnership:()=>releaseCoderDispatchOwnership,recoverStaleCoderSettlements:()=>recoverStaleCoderSettlements,recoverCoderSettlement:()=>recoverCoderSettlement,recordCoderMergeProvenance:()=>recordCoderMergeProvenance,listCoderSettlementWalStates:()=>listCoderSettlementWalStates,hasUnattributedEmptyScopeMutation:()=>hasUnattributedEmptyScopeMutation,completeCoderSettlementCleanup:()=>completeCoderSettlementCleanup,beginCoderSettlement:()=>beginCoderSettlement,assertNoUnsettledCoderDispatch:()=>assertNoUnsettledCoderDispatch,abortCoderSettlementIfDoomed:()=>abortCoderSettlementIfDoomed,abortCoderSettlement:()=>abortCoderSettlement,_internals:()=>_internals100});import{spawnSync as spawnSync13}from"node:child_process";import{randomUUID as randomUUID14}from"node:crypto";import{existsSync as existsSync54}from"node:fs";import{readdir as readdir6}from"node:fs/promises";function dispatchKey(directory,taskId,transitionId){return`${canonicalRootKeyFresh(directory)}\x00${taskId}\x00${transitionId}`}function walPath(directory,taskId){return validateSwarmPath(directory,`coder-settlements/${taskId}.json`)}async function readWal2(filePath,taskId){return readWorkflowWalFile("coder-settlement",filePath,taskId)}async function withSettlementLock(directory,taskId,actor,operation){let target=`coder-settlements/${taskId}.json`,lock=await tryAcquireLock(directory,target,actor,`coder-settlement-${taskId}-${Date.now()}`);if(!lock.acquired)throw Error(`CODER_SETTLEMENT_LOCKED: task ${taskId}`);try{return await operation()}finally{await lock.lock._release?.().catch(()=>{return})}}async function writeWal3(filePath,wal){await writeWorkflowWalFile("coder-settlement",filePath,wal)}async function appendSettlementEvent(directory,action,wal,extra){try{appendCoreEventSync(directory,{type:"coder_settlement",action,timestamp:new Date().toISOString(),taskId:wal.taskId,transitionId:wal.transitionId,actor:wal.actor,...extra??{}})}catch(error93){criticalWarn(`[coder-settlement] lifecycle event write failed (${action} ${wal.taskId}): ${error93 instanceof Error?error93.message:String(error93)}`)}}function baselineAttributionDoomed(baseline){if(baseline.gitHead===null)return!0;return Array.isArray(baseline.changedFiles)&&baseline.changedFiles.length>0}function hasUnattributedEmptyScopeMutation(declaredFiles,rawObservedFiles){return Array.isArray(declaredFiles)&&declaredFiles.length===0&&Array.isArray(rawObservedFiles)&&rawObservedFiles.length>0}function doomedReason(baseline){if(baseline.gitHead===null)return"launch workspace has no git baseline (not a git repository, or git unavailable at dispatch)";return`launch baseline was dirty with ${String(baseline.changedFiles?.length??0)} pre-existing uncommitted/untracked change(s)`}function isProcessAlive3(processId){if(processId===process.pid)return!0;try{return process.kill(processId,0),!0}catch(error93){return error93.code==="EPERM"}}async function scopedObservedFiles(directory,context){let baseline={...context.baseline,directory},observed=await changedFilesSinceSnapshotAsync(directory,baseline);if(!observed||!context.declaredFiles)return null;if(hasUnattributedEmptyScopeMutation(context.declaredFiles,observed))return observed;return observed.filter((filePath)=>isPathWithinDeclaredScope(filePath,context.declaredFiles??[],directory))}function settlementTransitionEvent(wal){return wal.accepted?{type:"accepted_mutation",agentType:"coder",context:{testEngineerExempt:wal.testEngineerExempt===!0,settlementFailed:wal.settlementFailed===!0},expectedGeneration:wal.expectedGeneration,transitionId:wal.transitionId}:{type:"dispatch_no_mutation",agentType:"coder",context:{declaredFiles:wal.context.declaredFiles,settlementTransitionId:wal.transitionId},expectedGeneration:wal.expectedGeneration,transitionId:wal.transitionId}}function withLandedUnstaged(worktree,landedUnstaged){if(worktree===void 0||landedUnstaged===void 0)return worktree;return{...worktree,landedUnstaged}}async function commitPrepared(directory,wal,options){return withTaskEvidenceTransaction(directory,wal.taskId,wal.actor,async(transaction)=>{let lockedWal=await readWal2(walPath(directory,wal.taskId),wal.taskId);if(lockedWal===null)throw Error("CODER_SETTLEMENT_WAL_MISSING");if(lockedWal.transitionId!==wal.transitionId)throw Error("CODER_SETTLEMENT_WAL_REPLACED");let transitionEvent=settlementTransitionEvent(lockedWal),snapshot=getTaskWorkflowSnapshot(transaction.read());if(lockedWal.accepted===!0?snapshot.authoritative&&snapshot.state===(lockedWal.settlementFailed===!0?"rework_required":"coder_delegated")&&snapshot.generation===lockedWal.expectedGeneration+1&&snapshot.lastOutcome===(lockedWal.settlementFailed===!0?"accepted_mutation_failed":"accepted_mutation")&&snapshot.lastTransitionId===lockedWal.transitionId:snapshot.authoritative&&snapshot.generation===lockedWal.expectedGeneration&&(lockedWal.context.declaredFiles?.length===0?snapshot.noMutationSettlement?.transitionId===lockedWal.transitionId:snapshot.lastOutcome==="dispatch_no_mutation"&&snapshot.lastTransitionId===lockedWal.transitionId)){let evidence2=transaction.read();if(lockedWal.accepted===!0)await ensureTaskGateRequirementsReceiptForSettledTransition(directory,lockedWal.taskId,evidence2,transitionEvent);if(lockedWal.state!=="COMMITTED")lockedWal={...lockedWal,state:"COMMITTED",cleanupComplete:lockedWal.worktree===void 0,worktree:withLandedUnstaged(lockedWal.worktree,options?.landedUnstaged)},await writeWal3(walPath(directory,wal.taskId),lockedWal),await appendSettlementEvent(directory,"settled",lockedWal,{resumed:!0});return{evidence:evidence2,accepted:lockedWal.accepted===!0,alreadyApplied:!0}}if(lockedWal.state!=="PREPARED"&&!(lockedWal.state==="COMMITTED"&&lockedWal.accepted!==!0&&snapshot.state==="idle"))throw Error("CODER_SETTLEMENT_NOT_PREPARED");let evidence=await transaction.transition(transitionEvent);return lockedWal={...lockedWal,state:"COMMITTED",cleanupComplete:lockedWal.worktree===void 0,worktree:withLandedUnstaged(lockedWal.worktree,options?.landedUnstaged)},await writeWal3(walPath(directory,wal.taskId),lockedWal),await appendSettlementEvent(directory,"settled",lockedWal),{evidence,accepted:lockedWal.accepted===!0,alreadyApplied:!1}})}async function beginCoderSettlement(options){if(options.context.baseline.gitHead===null){if((await captureWorkspaceSnapshotAsync(options.directory)).gitHead!==null)throw Error(`CODER_SETTLEMENT_BASELINE_UNAVAILABLE: the launch baseline for task ${options.taskId} has no git HEAD — the observation directory (${options.context.baseline.directory}) is not a git repository or git is unavailable there. An unregistered worktree lane (a lane directory that git worktree list does not know) produces exactly this. The task was not dispatched and no settlement state was created; retry the dispatch, or set worktree.policy "disabled" to run coders in the primary tree.`)}let filePath=walPath(options.directory,options.taskId),ownsActiveDispatch=!1;if(await withSettlementLock(options.directory,options.taskId,options.actor,()=>withTaskEvidenceTransaction(options.directory,options.taskId,options.actor,async(transaction)=>{let snapshot=getTaskWorkflowSnapshot(transaction.read());if(snapshot.generation!==options.expectedGeneration)throw Error(`TASK_WORKFLOW_GENERATION_MISMATCH: expected ${options.expectedGeneration}, found ${snapshot.generation}`);let existing=await readWal2(filePath,options.taskId);if(existing!==null){if((existing.state==="DISPATCHED"||existing.state==="PREPARED")&&existing.transitionId!==options.transitionId)throw Error(`CODER_SETTLEMENT_IN_PROGRESS: transition ${existing.transitionId} owns task ${options.taskId}, so transition ${options.transitionId} cannot dispatch it (${filePath}, state ${existing.state}). Wait for the owning transition to settle or run /swarm recover ${options.taskId} (or /swarm reset-session), then retry; do not remove the WAL by hand.`);if(existing.transitionId===options.transitionId){if(!(existing.actor===options.actor&&existing.expectedGeneration===options.expectedGeneration&&JSON.stringify(existing.context)===JSON.stringify(options.context)&&JSON.stringify(existing.worktree)===JSON.stringify(options.worktree)))throw Error("CODER_SETTLEMENT_IDEMPOTENCY_CONFLICT");if(existing.state==="ABORTED")throw Error("CODER_SETTLEMENT_IDEMPOTENCY_CONFLICT");ownsActiveDispatch=existing.state==="DISPATCHED"&&existing.runtimeId===runtimeId;return}}await transaction.transition({type:"dispatch_attempted",agentType:"coder",expectedGeneration:options.expectedGeneration,transitionId:options.transitionId}),await writeWal3(filePath,{version:1,state:"DISPATCHED",taskId:options.taskId,transitionId:options.transitionId,actor:options.actor,processId:process.pid,runtimeId,expectedGeneration:options.expectedGeneration,context:options.context,...options.worktree?{worktree:options.worktree}:{},recordedAt:new Date().toISOString()}),ownsActiveDispatch=!0,await appendSettlementEvent(options.directory,"dispatched",{taskId:options.taskId,transitionId:options.transitionId,actor:options.actor})})),ownsActiveDispatch){let key2=dispatchKey(options.directory,options.taskId,options.transitionId);if(!liveDispatches.has(key2)&&liveDispatches.size>=MAX_LIVE_DISPATCHES)throw Error("CODER_SETTLEMENT_CAPACITY_EXCEEDED");liveDispatches.add(key2)}}async function settleCoderDispatch(options){return withSettlementLock(options.directory,options.taskId,"coder-settlement",async()=>{let filePath=walPath(options.directory,options.taskId),wal=await readWal2(filePath,options.taskId);if(wal===null)throw Error("CODER_SETTLEMENT_WAL_MISSING");if(wal.transitionId!==options.transitionId)throw Error("CODER_SETTLEMENT_WAL_REPLACED");let unattributedEmptyScopeMutation=hasUnattributedEmptyScopeMutation(wal.context.declaredFiles,options.observedFiles),accepted=options.accepted||unattributedEmptyScopeMutation,settlementFailed=options.settlementFailed===!0||unattributedEmptyScopeMutation;if(wal.state==="COMMITTED"){if(wal.accepted!==accepted||wal.testEngineerExempt!==options.testEngineerExempt||wal.settlementFailed!==settlementFailed)throw Error("CODER_SETTLEMENT_IDEMPOTENCY_CONFLICT");return commitPrepared(options.directory,wal,{landedUnstaged:options.landedUnstaged})}if(wal.state==="ABORTED")throw Error("CODER_SETTLEMENT_IDEMPOTENCY_CONFLICT");if(wal.state==="PREPARED"&&(wal.accepted!==accepted||wal.testEngineerExempt!==options.testEngineerExempt||wal.settlementFailed!==settlementFailed))throw Error("CODER_SETTLEMENT_IDEMPOTENCY_CONFLICT");let prepared={...wal,state:"PREPARED",accepted,testEngineerExempt:options.testEngineerExempt,settlementFailed};if(wal.state!=="PREPARED")await writeWal3(filePath,prepared);liveDispatches.delete(dispatchKey(options.directory,options.taskId,options.transitionId));try{return await commitPrepared(options.directory,prepared,{landedUnstaged:options.landedUnstaged})}finally{let finalWal=await readWal2(filePath,options.taskId);if(finalWal!==null&&finalWal.state==="COMMITTED")liveDispatches.delete(dispatchKey(options.directory,options.taskId,options.transitionId))}})}async function abortCoderSettlement(options){let{outcome,worktree}=await withSettlementLock(options.directory,options.taskId,"coder-abort",async()=>abortDispatchedWalUnderLock(options.directory,options.taskId,options.transitionId,options.reason));if(worktree&&outcome!=="not-dispatched")try{await completeCoderSettlementCleanup(options.directory,options.taskId,options.transitionId)}catch(error93){criticalWarn(`[coder-settlement] aborted settlement worktree cleanup failed for task ${options.taskId}: ${error93 instanceof Error?error93.message:String(error93)}`)}return outcome}async function transferCoderSettlementToBackground(options){return withSettlementLock(options.directory,options.taskId,"coder-background-transfer",async()=>{let filePath=walPath(options.directory,options.taskId),wal=await readWal2(filePath,options.taskId);if(wal===null)return"missing";if(wal.taskId!==options.taskId||wal.transitionId!==options.transitionId)throw Error("CODER_SETTLEMENT_WAL_REPLACED");if(wal.state==="PREPARED")throw Error("CODER_SETTLEMENT_IN_PROGRESS");if(wal.state!=="DISPATCHED")return liveDispatches.delete(dispatchKey(options.directory,options.taskId,options.transitionId)),"already-terminal";let reason="ownership transferred to durable background completion";return await writeWal3(filePath,{...wal,state:"ABORTED",abortReason:reason,cleanupComplete:!0}),liveDispatches.delete(dispatchKey(options.directory,options.taskId,options.transitionId)),await appendSettlementEvent(options.directory,"aborted",wal,{reason,ownership:"background-delegation"}),"transferred"})}async function abortDispatchedWalUnderLock(directory,taskId,transitionId,reason){let filePath=walPath(directory,taskId),wal=await readWal2(filePath,taskId);if(wal===null)throw Error("CODER_SETTLEMENT_WAL_MISSING");if(wal.transitionId!==transitionId)throw Error("CODER_SETTLEMENT_WAL_REPLACED");if(wal.state==="ABORTED")return{outcome:"already-aborted",worktree:wal.worktree!==void 0};if(wal.state!=="DISPATCHED")return{outcome:"not-dispatched",worktree:!1};return await writeWal3(filePath,{...wal,state:"ABORTED",abortReason:reason}),liveDispatches.delete(dispatchKey(directory,taskId,transitionId)),await appendSettlementEvent(directory,"aborted",wal,{reason}),{outcome:"aborted",worktree:wal.worktree!==void 0}}async function abortCoderSettlementIfDoomed(options){let filePath=walPath(options.directory,options.taskId),wal;try{wal=await readWal2(filePath,options.taskId)}catch{return"not-doomed"}if(wal===null)return"not-doomed";if(wal.state==="ABORTED")return"already-aborted";if(wal.transitionId!==options.transitionId||wal.state!=="DISPATCHED")return"not-doomed";if(!baselineAttributionDoomed(wal.context.baseline))return"not-doomed";let outcome=await abortCoderSettlement({directory:options.directory,taskId:options.taskId,transitionId:options.transitionId,reason:doomedReason(wal.context.baseline)});return outcome==="aborted"||outcome==="already-aborted"?outcome:"not-doomed"}async function recordCoderMergeProvenance(options){await withSettlementLock(options.directory,options.taskId,"coder-merge-provenance",async()=>{let filePath=walPath(options.directory,options.taskId),wal=await readWal2(filePath,options.taskId);if(wal===null)throw Error("CODER_SETTLEMENT_WAL_MISSING");if(wal.taskId!==options.taskId||wal.transitionId!==options.transitionId)throw Error("CODER_SETTLEMENT_WAL_REPLACED");if(wal.state!=="DISPATCHED"){if(!(JSON.stringify(wal.mergeProvenance)===JSON.stringify(options.provenance)&&JSON.stringify(wal.observedFiles)===JSON.stringify(options.observedFiles)))throw Error("CODER_SETTLEMENT_IDEMPOTENCY_CONFLICT");return}await writeWal3(filePath,{...wal,mergeProvenance:options.provenance,observedFiles:[...options.observedFiles]})})}function probeBranchExists(directory,branchName){let result=spawnSync13(resolveGitExecutable(),["-C",directory,"show-ref","--verify","--quiet",`refs/heads/${branchName}`],{cwd:directory,stdio:["ignore","ignore","ignore"],timeout:5000,windowsHide:!0});if(result.error)throw result.error;if(result.status===0)return!0;if(result.status===1)return!1;throw Error(`CODER_SETTLEMENT_CLEANUP_UNCERTAIN: git show-ref exited with status ${String(result.status)}`)}async function cleanupRecoveredWorktree(directory,descriptor,options){let retainBranch=options?.retainBranch??descriptor.landedUnstaged===!0,branchExists=()=>_internals100.branchExists(directory,descriptor.branchName),hasResidue=existsSync54(descriptor.worktreePath)||branchExists(),{awaitingMergeByCallID:awaitingMergeByCallID2,cleanupStandardWorktreeForCallId:cleanupStandardWorktreeForCallId2,standardWorktreeByCallID:standardWorktreeByCallID2}=await Promise.resolve().then(() => (init_worktree_isolation(),exports_worktree_isolation));if(standardWorktreeByCallID2.delete(descriptor.callID),hasResidue)awaitingMergeByCallID2.set(descriptor.callID,{callID:descriptor.callID,parentSessionID:descriptor.parentSessionId,taskId:descriptor.taskId,...descriptor.planTaskId?{planTaskId:descriptor.planTaskId}:{},branch:descriptor.branchName,worktreePath:descriptor.worktreePath,mergeStrategy:descriptor.mergeStrategy,queuedAt:Date.now()});if(hasResidue)await cleanupStandardWorktreeForCallId2(descriptor.callID,"success",directory,descriptor.worktreeDir??void 0,retainBranch?{retainBranch:!0}:void 0);if(existsSync54(descriptor.worktreePath)||branchExists()&&!retainBranch)throw Error("CODER_SETTLEMENT_WORKTREE_CLEANUP_UNVERIFIED");let provisioningOwner=descriptor.provisioningOwner??(descriptor.reservationId!==void 0&&descriptor.generation!==void 0?{reservationId:descriptor.reservationId,generation:descriptor.generation,branchName:descriptor.branchName}:void 0);if(!_internals100.removeWorktreeProvisioningOwner(directory,descriptor.callID,provisioningOwner))throw Error("CODER_SETTLEMENT_OWNER_CLEANUP_FAILED")}async function completeCoderSettlementCleanup(directory,taskId,transitionId){await withSettlementLock(directory,taskId,"coder-cleanup",async()=>{let filePath=walPath(directory,taskId),wal=await readWal2(filePath,taskId);if(wal===null)throw Error("CODER_SETTLEMENT_WAL_MISSING");if(wal.taskId!==taskId||wal.transitionId!==transitionId)throw Error("CODER_SETTLEMENT_WAL_REPLACED");if(wal.state!=="COMMITTED"&&wal.state!=="ABORTED")throw Error("CODER_SETTLEMENT_NOT_COMMITTED");if(!wal.worktree||wal.cleanupComplete===!0)return;await cleanupRecoveredWorktree(directory,wal.worktree),await writeWal3(filePath,{...wal,cleanupComplete:!0})})}async function selfHealMissingLaneWorktree(directory,filePath,taskId,transitionId,descriptor,detail){if(existsSync54(descriptor.worktreePath))return!1;if(_internals100.branchExists(directory,descriptor.branchName))return!1;let reason=`CODER_SETTLEMENT_SELF_HEALED_MISSING_WORKTREE: ${detail}`;if((await abortDispatchedWalUnderLock(directory,taskId,transitionId,reason)).outcome==="not-dispatched")return!1;try{await cleanupRecoveredWorktree(directory,descriptor);let healedWal=await readWal2(filePath,taskId);if(healedWal!==null)await writeWal3(filePath,{...healedWal,cleanupComplete:!0})}catch(error93){criticalWarn(`[coder-settlement] self-healed task ${taskId} but residual cleanup failed: ${error93 instanceof Error?error93.message:String(error93)}`)}let message=`STALE_CODER_SETTLEMENT_SELF_HEALED: task ${taskId} was blocked by a coder settlement whose lane worktree "${descriptor.worktreePath}" and lane branch "${descriptor.branchName}" no longer exist. Nothing was recoverable, so the write-ahead log at "${filePath}" was marked terminal (ABORTED) and the task was unblocked. Re-dispatch the task if its work still needs doing.`;return criticalWarn(message),advisoryWarn(message),!0}async function recoverCoderSettlement(directory,taskId){return withSettlementLock(directory,taskId,"coder-recovery",async()=>{let filePath=walPath(directory,taskId),existingWal=await readWal2(filePath,taskId);if(existingWal===null)return null;let wal=existingWal;if(wal.state==="ABORTED")return null;if(wal.state==="COMMITTED"){if(wal.worktree&&wal.cleanupComplete!==!0)await cleanupRecoveredWorktree(directory,wal.worktree),await writeWal3(filePath,{...wal,cleanupComplete:!0});return null}let key2=dispatchKey(directory,taskId,wal.transitionId);if(liveDispatches.has(key2)||wal.processId!==process.pid&&isProcessAlive3(wal.processId))throw Error(`CODER_DISPATCH_IN_PROGRESS: transition ${wal.transitionId} still owns task ${taskId} (${filePath}, state ${wal.state}, pid ${wal.processId}). Wait for that dispatch to settle or run /swarm recover ${taskId} (or /swarm reset-session) to unwedge it; do not remove the WAL by hand.`);if(wal.state==="DISPATCHED"){if(wal.worktree){let worktree=wal.worktree,observed2=wal.observedFiles??await scopedObservedFiles(worktree.worktreePath,wal.context);if(observed2===null)throw Error(`CODER_SETTLEMENT_RECOVERY_UNCERTAIN: transition ${wal.transitionId} for isolated task ${taskId} could not attribute worktree changes to the declared scope (${filePath}, state ${wal.state}). Run /swarm recover ${taskId} (or /swarm reset-session), then retry; do not remove the WAL by hand.`);let unattributedEmptyScopeMutation2=hasUnattributedEmptyScopeMutation(wal.context.declaredFiles,observed2),accepted=observed2.length>0||unattributedEmptyScopeMutation2,settlementFailed=wal.settlementFailed===!0||unattributedEmptyScopeMutation2;if(wal.mergeProvenance){let landed=await reconcileLandedMerge(directory,wal.mergeProvenance);if(landed.landed){let landedUnstaged=landed.method==="worktree-match";wal={...wal,state:"PREPARED",observedFiles:observed2,accepted,settlementFailed,testEngineerExempt:isMarkdownOnlyTaskChange(wal.context.declaredFiles,observed2)},await writeWal3(filePath,wal);let committed2=await commitPrepared(directory,wal,{landedUnstaged});await cleanupRecoveredWorktree(directory,worktree,{retainBranch:landedUnstaged});let reconciledWal=await readWal2(filePath,taskId);if(reconciledWal===null)throw Error("CODER_SETTLEMENT_WAL_MISSING");return await writeWal3(filePath,{...reconciledWal,cleanupComplete:!0}),committed2}if(landed.error)throw Error(`CODER_SETTLEMENT_RECOVERY_UNCERTAIN: transition ${wal.transitionId} for task ${taskId} could not reconcile the landed merge (${filePath}, state ${wal.state}): ${landed.error}. Run /swarm recover ${taskId} (or /swarm reset-session), then retry; do not remove the WAL by hand.`)}let{awaitingMergeByCallID:awaitingMergeByCallID2,finishStandardWorktreeDispatch:finishStandardWorktreeDispatch2,standardWorktreeByCallID:standardWorktreeByCallID2}=await Promise.resolve().then(() => (init_worktree_isolation(),exports_worktree_isolation)),descriptor=wal.worktree,reconstructedDispatch={callID:descriptor.callID,parentSessionID:descriptor.parentSessionId,taskId:descriptor.taskId,...descriptor.planTaskId?{planTaskId:descriptor.planTaskId}:{},handle:{worktreePath:descriptor.worktreePath,branchName:descriptor.branchName,purpose:"lane",id:descriptor.worktreeId,sessionId:descriptor.worktreeSessionId},mergeStrategy:descriptor.mergeStrategy,laneIndex:descriptor.laneIndex,...descriptor.worktreeDir?{worktree_dir:descriptor.worktreeDir}:{}};standardWorktreeByCallID2.delete(descriptor.callID),awaitingMergeByCallID2.set(descriptor.callID,{callID:descriptor.callID,parentSessionID:descriptor.parentSessionId,taskId:descriptor.taskId,...descriptor.planTaskId?{planTaskId:descriptor.planTaskId}:{},branch:descriptor.branchName,worktreePath:descriptor.worktreePath,mergeStrategy:descriptor.mergeStrategy,queuedAt:Date.now()});let recovered=null,mergeResult=await finishStandardWorktreeDispatch2(directory,reconstructedDispatch,void 0,descriptor.callID,{operationId:wal.transitionId,...wal.mergeProvenance?{resume:wal.mergeProvenance}:{},onBeforeMerge:async(provenance)=>{wal={...wal,mergeProvenance:provenance,observedFiles:observed2},await writeWal3(filePath,wal)},onMerged:async(mergedResult)=>{wal={...wal,state:"PREPARED",accepted,settlementFailed,testEngineerExempt:isMarkdownOnlyTaskChange(wal.context.declaredFiles,observed2)},await writeWal3(filePath,wal),recovered=await commitPrepared(directory,wal,{landedUnstaged:mergedResult.strategy==="squash-unstaged"})}});if(mergeResult.outcome!=="merged"||recovered===null){if(mergeResult.outcome==="failed"&&mergeResult.stage===SOURCE_WORKTREE_GONE_STAGE&&await selfHealMissingLaneWorktree(directory,filePath,taskId,wal.transitionId,descriptor,mergeResult.message))return null;throw Error(`CODER_SETTLEMENT_MERGE_RECOVERY_REQUIRED: transition ${wal.transitionId} for task ${taskId} worktree merge-back did not reach merged (${filePath}, state ${wal.state}, outcome ${mergeResult.outcome}${mergeResult.outcome==="failed"&&mergeResult.message?`: ${mergeResult.message}`:""}). Run /swarm recover ${taskId} (or /swarm reset-session), then retry; do not remove the WAL by hand.`)}await cleanupRecoveredWorktree(directory,descriptor,{retainBranch:mergeResult.strategy==="squash-unstaged"});let committedWal=await readWal2(filePath,taskId);if(committedWal===null)throw Error("CODER_SETTLEMENT_WAL_MISSING");return await writeWal3(filePath,{...committedWal,cleanupComplete:!0}),recovered}let rawObserved=await changedFilesSinceSnapshotAsync(directory,wal.context.baseline),unattributedEmptyScopeMutation=hasUnattributedEmptyScopeMutation(wal.context.declaredFiles,rawObserved),observed;if(rawObserved===null){if(baselineAttributionDoomed(wal.context.baseline)){let aborted3=await abortDispatchedWalUnderLock(directory,taskId,wal.transitionId,doomedReason(wal.context.baseline));if(aborted3.outcome==="aborted"||aborted3.outcome==="already-aborted")return null}observed=null}else if(wal.context.declaredFiles===null)observed=[];else observed=unattributedEmptyScopeMutation?rawObserved:rawObserved.filter((filePath2)=>isPathWithinDeclaredScope(filePath2,wal.context.declaredFiles??[],directory));if(observed===null)throw Error(`CODER_SETTLEMENT_RECOVERY_UNCERTAIN: transition ${wal.transitionId} for task ${taskId} workspace changes could not be attributed to the declared scope (${filePath}, state ${wal.state}). Run /swarm recover ${taskId} (or /swarm reset-session), then retry; do not remove the WAL by hand.`);wal={...wal,state:"PREPARED",accepted:observed.length>0,settlementFailed:wal.settlementFailed===!0||unattributedEmptyScopeMutation,testEngineerExempt:isMarkdownOnlyTaskChange(wal.context.declaredFiles,observed)},await writeWal3(filePath,wal)}let committed=await commitPrepared(directory,wal);if(wal.worktree){await cleanupRecoveredWorktree(directory,wal.worktree);let committedWal=await readWal2(filePath,taskId);if(committedWal===null)throw Error("CODER_SETTLEMENT_WAL_MISSING");await writeWal3(filePath,{...committedWal,cleanupComplete:!0})}return committed})}function releaseCoderDispatchOwnership(directory,taskId,transitionId){liveDispatches.delete(dispatchKey(directory,taskId,transitionId))}async function assertNoUnsettledCoderDispatch(directory,taskId){let filePath=walPath(directory,taskId),wal=await readWal2(filePath,taskId);if(wal===null)return;if(wal.state==="DISPATCHED"||wal.state==="PREPARED")throw Error(`CODER_SETTLEMENT_RECOVERY_REQUIRED: transition ${wal.transitionId} must settle before task ${taskId} can change plan status (${filePath}, state ${wal.state}). Run /swarm recover ${taskId} (or /swarm reset-session), then retry.`)}async function listCoderSettlementWalStates(directory){let entries;try{let dirPath=validateSwarmPath(directory,"coder-settlements");entries=await readdir6(dirPath)}catch{return{states:[],truncated:!1}}let matching=entries.filter((entry)=>SETTLEMENT_WAL_FILE_PATTERN.test(entry)),states=[];for(let entry of matching.sort().slice(0,MAX_SETTLEMENT_WAL_SCAN)){let taskId=entry.slice(0,-5);try{let wal=await readWal2(walPath(directory,taskId),taskId);if(wal===null)continue;states.push({taskId,state:wal.state,transitionId:wal.transitionId,processId:wal.processId,recordedAt:wal.recordedAt,accepted:wal.accepted===!0?!0:void 0,declaredFiles:wal.context?.declaredFiles??null,expectedGeneration:wal.expectedGeneration,ownedInProcess:liveDispatches.has(dispatchKey(directory,taskId,wal.transitionId)),ownedByLiveForeignPid:wal.processId!==process.pid&&isProcessAlive3(wal.processId)})}catch{states.push({taskId,state:"unreadable",ownedInProcess:!1,ownedByLiveForeignPid:!1})}}return{states,truncated:matching.length>MAX_SETTLEMENT_WAL_SCAN}}async function recoverStaleCoderSettlements(directory,options){let{states:listed,truncated}=await listCoderSettlementWalStates(directory),filter=options?.taskIds?new Set(options.taskIds):void 0,results=[];for(let entry of listed){if(filter&&!filter.has(entry.taskId))continue;if(entry.state==="unreadable"){results.push({taskId:entry.taskId,outcome:"unreadable_wal"});continue}if(entry.state==="ABORTED"||entry.state==="COMMITTED"){try{await _internals100.recoverCoderSettlement(directory,entry.taskId),results.push({taskId:entry.taskId,outcome:"already_terminal",state:entry.state})}catch(error93){results.push({taskId:entry.taskId,outcome:"error",message:error93 instanceof Error?error93.message:String(error93)})}continue}if(entry.ownedInProcess&&options?.force!==!0){results.push({taskId:entry.taskId,outcome:"owned_in_process",transitionId:entry.transitionId??""});continue}if(entry.ownedByLiveForeignPid){results.push({taskId:entry.taskId,outcome:"owned_by_live_foreign_pid",processId:entry.processId??-1});continue}let forced=entry.ownedInProcess&&options?.force===!0;if(forced&&entry.transitionId)releaseCoderDispatchOwnership(directory,entry.taskId,entry.transitionId),await appendSettlementEvent(directory,"recovered",{taskId:entry.taskId,transitionId:entry.transitionId,actor:"swarm-recovery"},{forced:!0,stage:"ownership-release"});try{let recovered=await _internals100.recoverCoderSettlement(directory,entry.taskId);if(recovered===null){let current=null;try{current=await readWal2(walPath(directory,entry.taskId),entry.taskId)}catch{current=null}if(current&&(current.state==="COMMITTED"||current.state==="ABORTED")){results.push({taskId:entry.taskId,outcome:"already_terminal",state:current.state});continue}results.push({taskId:entry.taskId,outcome:"error",message:"settlement WAL disappeared during recovery"});continue}await appendSettlementEvent(directory,"recovered",{taskId:entry.taskId,transitionId:entry.transitionId??"",actor:"swarm-recovery"},{forced,accepted:recovered.accepted,previousTransitionId:entry.transitionId??"",previousState:entry.state,...typeof entry.expectedGeneration==="number"?{expectedGeneration:entry.expectedGeneration}:{}}),results.push({taskId:entry.taskId,outcome:"recovered",accepted:recovered.accepted,forced})}catch(error93){let message=error93 instanceof Error?error93.message:String(error93);await appendSettlementEvent(directory,"recovery-failed",{taskId:entry.taskId,transitionId:entry.transitionId??"",actor:"swarm-recovery"},{forced,error:message}),results.push({taskId:entry.taskId,outcome:"error",message})}}return{results,truncated}}var LIVE_DISPATCHES_SYMBOL,globalRegistry3,liveDispatches,runtimeId,MAX_LIVE_DISPATCHES=512,MAX_SETTLEMENT_WAL_SCAN=200,SETTLEMENT_WAL_FILE_PATTERN,_internals100;var init_coder_settlement=__esm(()=>{init_workspace_snapshot();init_core_events();init_gate_evidence();init_gate_evidence_classification();init_worktree_provisioning_owner();init_utils2();init_file_locks();init_path_identity();init_warning_buffer();init_canonical_root();init_git_executable();init_logger();init_merge2();init_workflow_wal_file();LIVE_DISPATCHES_SYMBOL=Symbol.for("opencode-swarm.workflow.coder-settlement.live-dispatches"),globalRegistry3=globalThis;if(!globalRegistry3[LIVE_DISPATCHES_SYMBOL])globalRegistry3[LIVE_DISPATCHES_SYMBOL]=new Set;liveDispatches=globalRegistry3[LIVE_DISPATCHES_SYMBOL],runtimeId=randomUUID14();SETTLEMENT_WAL_FILE_PATTERN=/^[\w.\-:]+\.json$/;_internals100={liveDispatches,removeWorktreeProvisioningOwner,branchExists:probeBranchExists,recoverCoderSettlement}});var exports_pending_delegations={};__export(exports_pending_delegations,{writeDelegationFallback:()=>writeDelegationFallback,updateCoderSettlement:()=>updateCoderSettlement,sweepStaleDelegations:()=>sweepStaleDelegations,scanDelegationsForRecovery:()=>scanDelegationsForRecovery,scanDelegationFallbacksForRecovery:()=>scanDelegationFallbacksForRecovery,scanBackgroundCoderReservationsForAdmission:()=>scanBackgroundCoderReservationsForAdmission,reserveBackgroundCoderSlot:()=>reserveBackgroundCoderSlot,replacePendingBackgroundAdvisory:()=>replacePendingBackgroundAdvisory,removeDelegationFallback:()=>removeDelegationFallback,releasePreparedBackgroundAdvisories:()=>releasePreparedBackgroundAdvisories,releaseBackgroundCoderReservation:()=>releaseBackgroundCoderReservation,registerStaleSweepObserver:()=>registerStaleSweepObserver,registerLegacyCoderSettlementReconciler:()=>registerLegacyCoderSettlementReconciler,recordPendingDelegationDetailed:()=>recordPendingDelegationDetailed,recordPendingDelegation:()=>recordPendingDelegation,recordDelegationIngestionResult:()=>recordDelegationIngestionResult,readDelegationsDetailed:()=>readDelegationsDetailed,readDelegations:()=>readDelegations,readDelegationFallback:()=>readDelegationFallback,putPendingBackgroundAdvisory:()=>putPendingBackgroundAdvisory,publishPrReviewResultReceipt:()=>publishPrReviewResultReceipt,promoteDelegationFallback:()=>promoteDelegationFallback,preparePendingBackgroundAdvisories:()=>preparePendingBackgroundAdvisories,normalizeBackgroundObservedFiles:()=>normalizeBackgroundObservedFiles,markLegacyCoderSettlementTransferPending:()=>markLegacyCoderSettlementTransferPending,maintainBackgroundDelegations:()=>maintainBackgroundDelegations,listDelegationFallbacks:()=>listDelegationFallbacks,isUnsettledWorktreeOwner:()=>isUnsettledWorktreeOwner,isTerminalDelegationStatus:()=>isTerminalDelegationStatus,findOpenAsyncLaneBatches:()=>findOpenAsyncLaneBatches,findDelegationForCompletion:()=>findDelegationForCompletion,findByCorrelationIdDetailed:()=>findByCorrelationIdDetailed,findByCorrelationId:()=>findByCorrelationId,findByBatchIdDetailed:()=>findByBatchIdDetailed,findByBatchId:()=>findByBatchId,compactBackgroundDelegations:()=>compactBackgroundDelegations,clearLegacyCoderSettlementTransferPending:()=>clearLegacyCoderSettlementTransferPending,claimTerminalResult:()=>claimTerminalResult,claimDelegationIngestion:()=>claimDelegationIngestion,claimCoderSettlement:()=>claimCoderSettlement,buildTypedDelegationTerminal:()=>buildTypedDelegationTerminal,buildPromptSnapshot:()=>buildPromptSnapshot,buildBackgroundCompletionEventId:()=>buildBackgroundCompletionEventId,buildBackgroundCoderReservationId:()=>buildBackgroundCoderReservationId,bindBackgroundCoderReservation:()=>bindBackgroundCoderReservation,appendDelegationTransition:()=>appendDelegationTransition,acknowledgeObservedBackgroundAdvisories:()=>acknowledgeObservedBackgroundAdvisories,_internals:()=>_internals101,_checkpointInternals:()=>_checkpointInternals,TOMBSTONE_MIN_AGE_MS:()=>TOMBSTONE_MIN_AGE_MS,MAX_RECOVERY_LEDGER_BYTES:()=>MAX_RECOVERY_LEDGER_BYTES,MAX_LIVE_BACKGROUND_FALLBACKS:()=>MAX_LIVE_BACKGROUND_FALLBACKS,MAX_LIVE_BACKGROUND_CODER_RESERVATIONS:()=>MAX_LIVE_BACKGROUND_CODER_RESERVATIONS,MAX_CHECKPOINT_RECORDS:()=>MAX_CHECKPOINT_RECORDS,MAX_CHECKPOINT_BYTES:()=>MAX_CHECKPOINT_BYTES,MAX_BACKGROUND_OBSERVED_FILES:()=>MAX_BACKGROUND_OBSERVED_FILES,MAX_BACKGROUND_ADVISORY_CHARS:()=>MAX_BACKGROUND_ADVISORY_CHARS,LEGACY_CODER_SETTLEMENT_PENDING_ADVISORY_MARKER:()=>LEGACY_CODER_SETTLEMENT_PENDING_ADVISORY_MARKER,DELEGATION_READ_RETRY_DELAY_MS:()=>DELEGATION_READ_RETRY_DELAY_MS,DELEGATION_COMPACTION_LOW_WATER_BYTES:()=>DELEGATION_COMPACTION_LOW_WATER_BYTES,DELEGATION_COMPACTION_HIGH_WATER_BYTES:()=>DELEGATION_COMPACTION_HIGH_WATER_BYTES,DEFAULT_SWEEPABLE_DELEGATION_STATUSES:()=>DEFAULT_SWEEPABLE_DELEGATION_STATUSES,DEFAULT_STALE_DELEGATION_TIMEOUT_MS:()=>DEFAULT_STALE_DELEGATION_TIMEOUT_MS,BACKGROUND_INGESTION_LEASE_MS:()=>BACKGROUND_INGESTION_LEASE_MS,BACKGROUND_DELEGATION_FALLBACK_DIR:()=>BACKGROUND_DELEGATION_FALLBACK_DIR,BACKGROUND_DELEGATIONS_MANIFEST_FILE:()=>BACKGROUND_DELEGATIONS_MANIFEST_FILE,BACKGROUND_DELEGATIONS_FILE:()=>BACKGROUND_DELEGATIONS_FILE,BACKGROUND_DELEGATIONS_CHECKPOINT_FILE:()=>BACKGROUND_DELEGATIONS_CHECKPOINT_FILE,BACKGROUND_CODER_RESERVATION_LEASE_MS:()=>BACKGROUND_CODER_RESERVATION_LEASE_MS,BACKGROUND_CODER_RESERVATION_LEASE_MIN_MS:()=>BACKGROUND_CODER_RESERVATION_LEASE_MIN_MS,BACKGROUND_CODER_RESERVATION_LEASE_MAX_MS:()=>BACKGROUND_CODER_RESERVATION_LEASE_MAX_MS,BACKGROUND_CODER_RESERVATIONS_FILE:()=>BACKGROUND_CODER_RESERVATIONS_FILE});import{createHash as createHash49}from"node:crypto";import*as fs70 from"node:fs";import*as path109 from"node:path";import{isDeepStrictEqual}from"node:util";function clampReservationLeaseMs(leaseMs){if(leaseMs===void 0)return BACKGROUND_CODER_RESERVATION_LEASE_MS;if(!Number.isFinite(leaseMs))return BACKGROUND_CODER_RESERVATION_LEASE_MS;return Math.min(Math.max(Math.round(leaseMs),BACKGROUND_CODER_RESERVATION_LEASE_MIN_MS),BACKGROUND_CODER_RESERVATION_LEASE_MAX_MS)}function isValidReservationGeneration(generation){return generation===void 0||Number.isInteger(generation)&&generation>=1&&generation<=MAX_BACKGROUND_DELEGATION_GENERATION}function storePath5(directory){return validateSwarmPath(directory,BACKGROUND_DELEGATIONS_FILE)}function checkpointPath2(directory){return validateSwarmPath(directory,BACKGROUND_DELEGATIONS_CHECKPOINT_FILE)}function manifestPath(directory){return validateSwarmPath(directory,BACKGROUND_DELEGATIONS_MANIFEST_FILE)}function importedShadowPath2(filePath){return`${filePath}.imported`}function projectionMarkerPath2(filePath){return`${filePath}.sqlite-projection`}function coordinationReservationLeaseKey(reservation){return{namespace:RESERVATION_LEASE_NAMESPACE,entityKey:reservation.reservationId,generation:reservation.generation??1,ownerToken:reservation.reservationId}}function releaseReservationLeaseIfPresent(directory,reservation){let leaseKey=coordinationReservationLeaseKey(reservation),existing=getCoordinationLease(directory,leaseKey.namespace,leaseKey.entityKey);if(!existing)return;if(existing.generation!==leaseKey.generation||existing.ownerToken!==leaseKey.ownerToken||!releaseCoordinationLease(directory,leaseKey.namespace,leaseKey.entityKey,leaseKey.generation,leaseKey.ownerToken))throw Error(`reservation lease authority mismatch for ${reservation.reservationId}`)}function coordinationRowsToDelegations(directory){if(!projectDbExists(directory))return null;try{let rows=listCoordinationStates(directory,DELEGATION_COORDINATION_NAMESPACE,MAX_COORDINATION_STATE_LIST_ROWS);if(rows.length>=MAX_COORDINATION_STATE_LIST_ROWS)throw Error(`delegation coordination read reached its ${MAX_COORDINATION_STATE_LIST_ROWS}-row safety bound`);return rows.map((row)=>{let parsed=RecordSchema2.safeParse(JSON.parse(row.payload));if(!parsed.success)throw Error(`delegation coordination row failed schema validation for ${row.entityKey}`);if(parsed.data.correlationId!==row.entityKey)throw Error(`delegation coordination row authority binding mismatch: payload correlationId does not equal entity key ${row.entityKey}`);if(Math.max(parsed.data.generation??1,1)!==row.generation)throw Error(`delegation coordination row authority binding mismatch: payload generation does not equal row generation for ${row.entityKey}`);if(parsed.data.status!==row.status)throw Error(`delegation coordination row authority binding mismatch: payload status does not equal row status for ${row.entityKey}`);return parsed.data}).sort((left,right)=>left.createdAt===right.createdAt?left.correlationId.localeCompare(right.correlationId):left.createdAt-right.createdAt)}catch(error93){return recordLedgerUncertainty(directory,error93 instanceof Error?error93.message:String(error93),"coordination-read"),null}}function archiveShadowFileBestEffort2(filePath){if(!fs70.existsSync(filePath))return;let importedPath=importedShadowPath2(filePath);try{if(fs70.existsSync(importedPath))return;fs70.renameSync(filePath,importedPath)}catch(error93){warn(`[background] shadow archive failed for ${path109.basename(filePath)}: ${error93 instanceof Error?error93.message:String(error93)}`)}}function writeDelegationShadowProjection(directory,records){ensureSwarmDir3(directory);let payload=records.map((record3)=>JSON.stringify(record3)).join(`
|
|
1262
|
+
`)){let line=rawLine.trim();if(!line||line.startsWith("#"))continue;let eqIdx=line.indexOf("=");if(eqIdx<0)continue;let k=line.slice(0,eqIdx),v=line.slice(eqIdx+1);if(!isValidEnvKey(k))continue;if(isUntrustedEnvKey(k))continue;result[k]=v}return result}var MAX_TRACKED_STANDARD_WORKTREE_CALLS=256,awaitingMergeByCallID,standardWorktreeByCallID,standardWorktreeSerializationSessions,LANE_CHILD_SESSION_LIMIT=512,laneChildSessionAgents,standardWorktreeMergeQueue,standardWorktreeLaneIndexBySession,serializationStateBySessionID,WORKTREE_RECOVERY_CLAIM_LEASE_MS=300000,WORKTREE_SESSION_CREATE_TIMEOUT_MS=30000,WORKTREE_SESSION_CREATE_SETTLE_GRACE_MS=5000,StandardWorktreeLifecycleError,WORKTREE_LIFECYCLE_LOCK_WAIT_MARGIN_MS=5000,WORKTREE_LIFECYCLE_LOCK_WAIT_MIN_MS=1e4,WORKTREE_DISPATCH_HOOK_BUDGET_MS=60000,WORKTREE_PROVISION_ALLOWANCE_MS=15000,standardWorktreeDegradationReasonBySession,WORKTREE_LIST_TIMEOUT_MS=15000,PRESERVE_COMMIT_TIMEOUT_MS=30000,_internals93;var init_worktree_isolation=__esm(()=>{init_constants();init_schema();init_project_db();init_task_landing();init_file_locks();init_lane_owners();init_executor();init_state();init_bun_compat();init_canonical_root();init_ephemeral_session_teardown();init_git_executable();init_logger();init_timeout();init_worktree();init_merge2();init_reviewer_scope_mergeback();init_dead_lane_reclaim();init_worktree_merge_status();init_worktree_provisioning_owner();init_worktree_recovery_authority();init_worktree_isolation_config();awaitingMergeByCallID=new Map,standardWorktreeByCallID=new Map,standardWorktreeSerializationSessions=new Set,laneChildSessionAgents=new Map;standardWorktreeMergeQueue=Promise.resolve(),standardWorktreeLaneIndexBySession=new Map,serializationStateBySessionID=new Map;StandardWorktreeLifecycleError=class StandardWorktreeLifecycleError extends Error{kind="standard-worktree-lifecycle";constructor(message){super(message);this.name="StandardWorktreeLifecycleError"}};standardWorktreeDegradationReasonBySession=new Map;_internals93={epicCommitLandingFor,provisionWorktree,removeWorktree,attemptMergeBackFromDirty,recoverMergeBackFromImmutableCoordinates,postMergeCleanup,pruneStaleWorktreeMetadata,readLaneEnvFileFromDisk,serializationStateBySessionID,rememberStandardWorktreeSerializationSession,awaitingMergeByCallID,startupOrphanRecovery,cleanupOrphanedBranches,cleanupStandardWorktreeForCallId,preserveDirtyWorktreeForCallId,preserveBackgroundWorktreeOwnershipForCallId,tryAcquireWorktreeLifecycleLock:tryAcquireLock,acquireWorktreeLifecycleLockWithin,resolveWorktreeLifecycleLockWaitMs,now:()=>Date.now(),sleep:(ms)=>new Promise((resolve53)=>setTimeout(resolve53,ms)),recordWorktreeProvisioningOwner,removeWorktreeProvisioningOwner,lookupWorktreeRecoveryAuthoritiesByTask,claimWorktreeRecoveryAuthority,renewWorktreeRecoveryClaim,releaseWorktreeRecoveryClaim,finalizeWorktreeRecoveryAuthority,publishWorktreeRecoveryAuthority,replayWorktreeRecoveryClaimJournal,buildWorktreeRecoveryPublishIdentity,preserveDirtyWorktreeAtPath,worktreeSessionCreateTimeoutMs:WORKTREE_SESSION_CREATE_TIMEOUT_MS,worktreeSessionCreateSettleGraceMs:WORKTREE_SESSION_CREATE_SETTLE_GRACE_MS,createSessionWithinBudget,abortStandardWorktreeDispatch,standardWorktreeByCallID,preProvisionCollisionCheck,inspectStandardWorktreeCollisionOwnership:inspectStandardWorktreeCollisionOwnership2,isLaneOwnedByCurrentSession,bunSpawn,resolveGitExecutable}});var exports_coder_settlement={};__export(exports_coder_settlement,{transferCoderSettlementToBackground:()=>transferCoderSettlementToBackground,settleCoderDispatch:()=>settleCoderDispatch,releaseCoderDispatchOwnership:()=>releaseCoderDispatchOwnership,recoverStaleCoderSettlements:()=>recoverStaleCoderSettlements,recoverCoderSettlement:()=>recoverCoderSettlement,recordCoderMergeProvenance:()=>recordCoderMergeProvenance,listCoderSettlementWalStates:()=>listCoderSettlementWalStates,hasUnattributedEmptyScopeMutation:()=>hasUnattributedEmptyScopeMutation,completeCoderSettlementCleanup:()=>completeCoderSettlementCleanup,beginCoderSettlement:()=>beginCoderSettlement,assertNoUnsettledCoderDispatch:()=>assertNoUnsettledCoderDispatch,abortCoderSettlementIfDoomed:()=>abortCoderSettlementIfDoomed,abortCoderSettlement:()=>abortCoderSettlement,_internals:()=>_internals100});import{spawnSync as spawnSync13}from"node:child_process";import{randomUUID as randomUUID14}from"node:crypto";import{existsSync as existsSync54}from"node:fs";import{readdir as readdir6}from"node:fs/promises";function dispatchKey(directory,taskId,transitionId){return`${canonicalRootKeyFresh(directory)}\x00${taskId}\x00${transitionId}`}function walPath(directory,taskId){return validateSwarmPath(directory,`coder-settlements/${taskId}.json`)}async function readWal2(filePath,taskId){return readWorkflowWalFile("coder-settlement",filePath,taskId)}async function withSettlementLock(directory,taskId,actor,operation){let target=`coder-settlements/${taskId}.json`,lock=await tryAcquireLock(directory,target,actor,`coder-settlement-${taskId}-${Date.now()}`);if(!lock.acquired)throw Error(`CODER_SETTLEMENT_LOCKED: task ${taskId}`);try{return await operation()}finally{await lock.lock._release?.().catch(()=>{return})}}async function writeWal3(filePath,wal){await writeWorkflowWalFile("coder-settlement",filePath,wal)}async function appendSettlementEvent(directory,action,wal,extra){try{appendCoreEventSync(directory,{type:"coder_settlement",action,timestamp:new Date().toISOString(),taskId:wal.taskId,transitionId:wal.transitionId,actor:wal.actor,...extra??{}})}catch(error93){criticalWarn(`[coder-settlement] lifecycle event write failed (${action} ${wal.taskId}): ${error93 instanceof Error?error93.message:String(error93)}`)}}function baselineAttributionDoomed(baseline){if(baseline.gitHead===null)return!0;return Array.isArray(baseline.changedFiles)&&baseline.changedFiles.length>0}function hasUnattributedEmptyScopeMutation(declaredFiles,rawObservedFiles){return Array.isArray(declaredFiles)&&declaredFiles.length===0&&Array.isArray(rawObservedFiles)&&rawObservedFiles.length>0}function doomedReason(baseline){if(baseline.gitHead===null)return"launch workspace has no git baseline (not a git repository, or git unavailable at dispatch)";return`launch baseline was dirty with ${String(baseline.changedFiles?.length??0)} pre-existing uncommitted/untracked change(s)`}function isProcessAlive3(processId){if(processId===process.pid)return!0;try{return process.kill(processId,0),!0}catch(error93){return error93.code==="EPERM"}}async function scopedObservedFiles(directory,context){let baseline={...context.baseline,directory},observed=await changedFilesSinceSnapshotAsync(directory,baseline);if(!observed||!context.declaredFiles)return null;if(hasUnattributedEmptyScopeMutation(context.declaredFiles,observed))return observed;return observed.filter((filePath)=>isPathWithinDeclaredScope(filePath,context.declaredFiles??[],directory))}function settlementTransitionEvent(wal){return wal.accepted?{type:"accepted_mutation",agentType:"coder",context:{testEngineerExempt:wal.testEngineerExempt===!0,settlementFailed:wal.settlementFailed===!0},expectedGeneration:wal.expectedGeneration,transitionId:wal.transitionId}:{type:"dispatch_no_mutation",agentType:"coder",context:{declaredFiles:wal.context.declaredFiles,settlementTransitionId:wal.transitionId},expectedGeneration:wal.expectedGeneration,transitionId:wal.transitionId}}function withLandedUnstaged(worktree,landedUnstaged){if(worktree===void 0||landedUnstaged===void 0)return worktree;return{...worktree,landedUnstaged}}async function commitPrepared(directory,wal,options){return withTaskEvidenceTransaction(directory,wal.taskId,wal.actor,async(transaction)=>{let lockedWal=await readWal2(walPath(directory,wal.taskId),wal.taskId);if(lockedWal===null)throw Error("CODER_SETTLEMENT_WAL_MISSING");if(lockedWal.transitionId!==wal.transitionId)throw Error("CODER_SETTLEMENT_WAL_REPLACED");let transitionEvent=settlementTransitionEvent(lockedWal),snapshot=getTaskWorkflowSnapshot(transaction.read());if(lockedWal.accepted===!0?snapshot.authoritative&&snapshot.state===(lockedWal.settlementFailed===!0?"rework_required":"coder_delegated")&&snapshot.generation===lockedWal.expectedGeneration+1&&snapshot.lastOutcome===(lockedWal.settlementFailed===!0?"accepted_mutation_failed":"accepted_mutation")&&snapshot.lastTransitionId===lockedWal.transitionId:snapshot.authoritative&&snapshot.generation===lockedWal.expectedGeneration&&(lockedWal.context.declaredFiles?.length===0?snapshot.noMutationSettlement?.transitionId===lockedWal.transitionId:snapshot.lastOutcome==="dispatch_no_mutation"&&snapshot.lastTransitionId===lockedWal.transitionId)){let evidence2=transaction.read();if(lockedWal.accepted===!0)await ensureTaskGateRequirementsReceiptForSettledTransition(directory,lockedWal.taskId,evidence2,transitionEvent);if(lockedWal.state!=="COMMITTED")lockedWal={...lockedWal,state:"COMMITTED",cleanupComplete:lockedWal.worktree===void 0,worktree:withLandedUnstaged(lockedWal.worktree,options?.landedUnstaged)},await writeWal3(walPath(directory,wal.taskId),lockedWal),await appendSettlementEvent(directory,"settled",lockedWal,{resumed:!0});return{evidence:evidence2,accepted:lockedWal.accepted===!0,alreadyApplied:!0}}if(lockedWal.state!=="PREPARED"&&!(lockedWal.state==="COMMITTED"&&lockedWal.accepted!==!0&&snapshot.state==="idle"))throw Error("CODER_SETTLEMENT_NOT_PREPARED");let evidence=await transaction.transition(transitionEvent);return lockedWal={...lockedWal,state:"COMMITTED",cleanupComplete:lockedWal.worktree===void 0,worktree:withLandedUnstaged(lockedWal.worktree,options?.landedUnstaged)},await writeWal3(walPath(directory,wal.taskId),lockedWal),await appendSettlementEvent(directory,"settled",lockedWal),{evidence,accepted:lockedWal.accepted===!0,alreadyApplied:!1}})}async function beginCoderSettlement(options){if(options.context.baseline.gitHead===null){if((await captureWorkspaceSnapshotAsync(options.directory)).gitHead!==null)throw Error(`CODER_SETTLEMENT_BASELINE_UNAVAILABLE: the launch baseline for task ${options.taskId} has no git HEAD — the observation directory (${options.context.baseline.directory}) is not a git repository or git is unavailable there. An unregistered worktree lane (a lane directory that git worktree list does not know) produces exactly this. The task was not dispatched and no settlement state was created; retry the dispatch, or set worktree.policy "disabled" to run coders in the primary tree.`)}let filePath=walPath(options.directory,options.taskId),ownsActiveDispatch=!1;if(await withSettlementLock(options.directory,options.taskId,options.actor,()=>withTaskEvidenceTransaction(options.directory,options.taskId,options.actor,async(transaction)=>{let snapshot=getTaskWorkflowSnapshot(transaction.read());if(snapshot.generation!==options.expectedGeneration)throw Error(`TASK_WORKFLOW_GENERATION_MISMATCH: expected ${options.expectedGeneration}, found ${snapshot.generation}`);let existing=await readWal2(filePath,options.taskId);if(existing!==null){if((existing.state==="DISPATCHED"||existing.state==="PREPARED")&&existing.transitionId!==options.transitionId)throw Error(`CODER_SETTLEMENT_IN_PROGRESS: transition ${existing.transitionId} owns task ${options.taskId}, so transition ${options.transitionId} cannot dispatch it (${filePath}, state ${existing.state}). Wait for the owning transition to settle or run /swarm recover ${options.taskId} (or /swarm reset-session), then retry; do not remove the WAL by hand.`);if(existing.transitionId===options.transitionId){if(!(existing.actor===options.actor&&existing.expectedGeneration===options.expectedGeneration&&JSON.stringify(existing.context)===JSON.stringify(options.context)&&JSON.stringify(existing.worktree)===JSON.stringify(options.worktree)))throw Error("CODER_SETTLEMENT_IDEMPOTENCY_CONFLICT");if(existing.state==="ABORTED")throw Error("CODER_SETTLEMENT_IDEMPOTENCY_CONFLICT");ownsActiveDispatch=existing.state==="DISPATCHED"&&existing.runtimeId===runtimeId;return}}await transaction.transition({type:"dispatch_attempted",agentType:"coder",expectedGeneration:options.expectedGeneration,transitionId:options.transitionId}),await writeWal3(filePath,{version:1,state:"DISPATCHED",taskId:options.taskId,transitionId:options.transitionId,actor:options.actor,processId:process.pid,runtimeId,expectedGeneration:options.expectedGeneration,context:options.context,...options.worktree?{worktree:options.worktree}:{},recordedAt:new Date().toISOString()}),ownsActiveDispatch=!0,await appendSettlementEvent(options.directory,"dispatched",{taskId:options.taskId,transitionId:options.transitionId,actor:options.actor})})),ownsActiveDispatch){let key2=dispatchKey(options.directory,options.taskId,options.transitionId);if(!liveDispatches.has(key2)&&liveDispatches.size>=MAX_LIVE_DISPATCHES)throw Error("CODER_SETTLEMENT_CAPACITY_EXCEEDED");liveDispatches.add(key2)}}async function settleCoderDispatch(options){return withSettlementLock(options.directory,options.taskId,"coder-settlement",async()=>{let filePath=walPath(options.directory,options.taskId),wal=await readWal2(filePath,options.taskId);if(wal===null)throw Error("CODER_SETTLEMENT_WAL_MISSING");if(wal.transitionId!==options.transitionId)throw Error("CODER_SETTLEMENT_WAL_REPLACED");let unattributedEmptyScopeMutation=hasUnattributedEmptyScopeMutation(wal.context.declaredFiles,options.observedFiles),accepted=options.accepted||unattributedEmptyScopeMutation,settlementFailed=options.settlementFailed===!0||unattributedEmptyScopeMutation;if(wal.state==="COMMITTED"){if(wal.accepted!==accepted||wal.testEngineerExempt!==options.testEngineerExempt||wal.settlementFailed!==settlementFailed)throw Error("CODER_SETTLEMENT_IDEMPOTENCY_CONFLICT");return commitPrepared(options.directory,wal,{landedUnstaged:options.landedUnstaged})}if(wal.state==="ABORTED")throw Error("CODER_SETTLEMENT_IDEMPOTENCY_CONFLICT");if(wal.state==="PREPARED"&&(wal.accepted!==accepted||wal.testEngineerExempt!==options.testEngineerExempt||wal.settlementFailed!==settlementFailed))throw Error("CODER_SETTLEMENT_IDEMPOTENCY_CONFLICT");let prepared={...wal,state:"PREPARED",accepted,testEngineerExempt:options.testEngineerExempt,settlementFailed};if(wal.state!=="PREPARED")await writeWal3(filePath,prepared);liveDispatches.delete(dispatchKey(options.directory,options.taskId,options.transitionId));try{return await commitPrepared(options.directory,prepared,{landedUnstaged:options.landedUnstaged})}finally{let finalWal=await readWal2(filePath,options.taskId);if(finalWal!==null&&finalWal.state==="COMMITTED")liveDispatches.delete(dispatchKey(options.directory,options.taskId,options.transitionId))}})}async function abortCoderSettlement(options){let{outcome,worktree}=await withSettlementLock(options.directory,options.taskId,"coder-abort",async()=>abortDispatchedWalUnderLock(options.directory,options.taskId,options.transitionId,options.reason));if(worktree&&outcome!=="not-dispatched")try{await completeCoderSettlementCleanup(options.directory,options.taskId,options.transitionId)}catch(error93){criticalWarn(`[coder-settlement] aborted settlement worktree cleanup failed for task ${options.taskId}: ${error93 instanceof Error?error93.message:String(error93)}`)}return outcome}async function transferCoderSettlementToBackground(options){return withSettlementLock(options.directory,options.taskId,"coder-background-transfer",async()=>{let filePath=walPath(options.directory,options.taskId),wal=await readWal2(filePath,options.taskId);if(wal===null)return"missing";if(wal.taskId!==options.taskId||wal.transitionId!==options.transitionId)throw Error("CODER_SETTLEMENT_WAL_REPLACED");if(wal.state==="PREPARED")throw Error("CODER_SETTLEMENT_IN_PROGRESS");if(wal.state!=="DISPATCHED")return liveDispatches.delete(dispatchKey(options.directory,options.taskId,options.transitionId)),"already-terminal";let reason="ownership transferred to durable background completion";return await writeWal3(filePath,{...wal,state:"ABORTED",abortReason:reason,cleanupComplete:!0}),liveDispatches.delete(dispatchKey(options.directory,options.taskId,options.transitionId)),await appendSettlementEvent(options.directory,"aborted",wal,{reason,ownership:"background-delegation"}),"transferred"})}async function abortDispatchedWalUnderLock(directory,taskId,transitionId,reason){let filePath=walPath(directory,taskId),wal=await readWal2(filePath,taskId);if(wal===null)throw Error("CODER_SETTLEMENT_WAL_MISSING");if(wal.transitionId!==transitionId)throw Error("CODER_SETTLEMENT_WAL_REPLACED");if(wal.state==="ABORTED")return{outcome:"already-aborted",worktree:wal.worktree!==void 0};if(wal.state!=="DISPATCHED")return{outcome:"not-dispatched",worktree:!1};return await writeWal3(filePath,{...wal,state:"ABORTED",abortReason:reason}),liveDispatches.delete(dispatchKey(directory,taskId,transitionId)),await appendSettlementEvent(directory,"aborted",wal,{reason}),{outcome:"aborted",worktree:wal.worktree!==void 0}}async function abortCoderSettlementIfDoomed(options){let filePath=walPath(options.directory,options.taskId),wal;try{wal=await readWal2(filePath,options.taskId)}catch{return"not-doomed"}if(wal===null)return"not-doomed";if(wal.state==="ABORTED")return"already-aborted";if(wal.transitionId!==options.transitionId||wal.state!=="DISPATCHED")return"not-doomed";if(!baselineAttributionDoomed(wal.context.baseline))return"not-doomed";let outcome=await abortCoderSettlement({directory:options.directory,taskId:options.taskId,transitionId:options.transitionId,reason:doomedReason(wal.context.baseline)});return outcome==="aborted"||outcome==="already-aborted"?outcome:"not-doomed"}async function recordCoderMergeProvenance(options){await withSettlementLock(options.directory,options.taskId,"coder-merge-provenance",async()=>{let filePath=walPath(options.directory,options.taskId),wal=await readWal2(filePath,options.taskId);if(wal===null)throw Error("CODER_SETTLEMENT_WAL_MISSING");if(wal.taskId!==options.taskId||wal.transitionId!==options.transitionId)throw Error("CODER_SETTLEMENT_WAL_REPLACED");if(wal.state!=="DISPATCHED"){if(!(JSON.stringify(wal.mergeProvenance)===JSON.stringify(options.provenance)&&JSON.stringify(wal.observedFiles)===JSON.stringify(options.observedFiles)))throw Error("CODER_SETTLEMENT_IDEMPOTENCY_CONFLICT");return}await writeWal3(filePath,{...wal,mergeProvenance:options.provenance,observedFiles:[...options.observedFiles]})})}function probeBranchExists(directory,branchName){let result=spawnSync13(resolveGitExecutable(),["-C",directory,"show-ref","--verify","--quiet",`refs/heads/${branchName}`],{cwd:directory,stdio:["ignore","ignore","ignore"],timeout:5000,windowsHide:!0});if(result.error)throw result.error;if(result.status===0)return!0;if(result.status===1)return!1;throw Error(`CODER_SETTLEMENT_CLEANUP_UNCERTAIN: git show-ref exited with status ${String(result.status)}`)}async function cleanupRecoveredWorktree(directory,descriptor,options){let retainBranch=options?.retainBranch??descriptor.landedUnstaged===!0,branchExists=()=>_internals100.branchExists(directory,descriptor.branchName),hasResidue=existsSync54(descriptor.worktreePath)||branchExists(),{awaitingMergeByCallID:awaitingMergeByCallID2,cleanupStandardWorktreeForCallId:cleanupStandardWorktreeForCallId2,standardWorktreeByCallID:standardWorktreeByCallID2}=await Promise.resolve().then(() => (init_worktree_isolation(),exports_worktree_isolation));if(standardWorktreeByCallID2.delete(descriptor.callID),hasResidue)awaitingMergeByCallID2.set(descriptor.callID,{callID:descriptor.callID,parentSessionID:descriptor.parentSessionId,taskId:descriptor.taskId,...descriptor.planTaskId?{planTaskId:descriptor.planTaskId}:{},branch:descriptor.branchName,worktreePath:descriptor.worktreePath,mergeStrategy:descriptor.mergeStrategy,queuedAt:Date.now()});if(hasResidue)await cleanupStandardWorktreeForCallId2(descriptor.callID,"success",directory,descriptor.worktreeDir??void 0,retainBranch?{retainBranch:!0}:void 0);if(existsSync54(descriptor.worktreePath)||branchExists()&&!retainBranch)throw Error("CODER_SETTLEMENT_WORKTREE_CLEANUP_UNVERIFIED");let provisioningOwner=descriptor.provisioningOwner??(descriptor.reservationId!==void 0&&descriptor.generation!==void 0?{reservationId:descriptor.reservationId,generation:descriptor.generation,branchName:descriptor.branchName}:void 0);if(!_internals100.removeWorktreeProvisioningOwner(directory,descriptor.callID,provisioningOwner))throw Error("CODER_SETTLEMENT_OWNER_CLEANUP_FAILED")}async function completeCoderSettlementCleanup(directory,taskId,transitionId){await withSettlementLock(directory,taskId,"coder-cleanup",async()=>{let filePath=walPath(directory,taskId),wal=await readWal2(filePath,taskId);if(wal===null)throw Error("CODER_SETTLEMENT_WAL_MISSING");if(wal.taskId!==taskId||wal.transitionId!==transitionId)throw Error("CODER_SETTLEMENT_WAL_REPLACED");if(wal.state!=="COMMITTED"&&wal.state!=="ABORTED")throw Error("CODER_SETTLEMENT_NOT_COMMITTED");if(!wal.worktree||wal.cleanupComplete===!0)return;await cleanupRecoveredWorktree(directory,wal.worktree),await writeWal3(filePath,{...wal,cleanupComplete:!0})})}async function selfHealMissingLaneWorktree(directory,filePath,taskId,transitionId,descriptor,detail){if(existsSync54(descriptor.worktreePath))return!1;if(_internals100.branchExists(directory,descriptor.branchName))return!1;let reason=`CODER_SETTLEMENT_SELF_HEALED_MISSING_WORKTREE: ${detail}`;if((await abortDispatchedWalUnderLock(directory,taskId,transitionId,reason)).outcome==="not-dispatched")return!1;try{await cleanupRecoveredWorktree(directory,descriptor);let healedWal=await readWal2(filePath,taskId);if(healedWal!==null)await writeWal3(filePath,{...healedWal,cleanupComplete:!0})}catch(error93){criticalWarn(`[coder-settlement] self-healed task ${taskId} but residual cleanup failed: ${error93 instanceof Error?error93.message:String(error93)}`)}let message=`STALE_CODER_SETTLEMENT_SELF_HEALED: task ${taskId} was blocked by a coder settlement whose lane worktree "${descriptor.worktreePath}" and lane branch "${descriptor.branchName}" no longer exist. Nothing was recoverable, so the write-ahead log at "${filePath}" was marked terminal (ABORTED) and the task was unblocked. Re-dispatch the task if its work still needs doing.`;return criticalWarn(message),advisoryWarn(message),!0}async function recoverCoderSettlement(directory,taskId){return withSettlementLock(directory,taskId,"coder-recovery",async()=>{let filePath=walPath(directory,taskId),existingWal=await readWal2(filePath,taskId);if(existingWal===null)return null;let wal=existingWal;if(wal.state==="ABORTED")return null;if(wal.state==="COMMITTED"){if(wal.worktree&&wal.cleanupComplete!==!0)await cleanupRecoveredWorktree(directory,wal.worktree),await writeWal3(filePath,{...wal,cleanupComplete:!0});return null}let key2=dispatchKey(directory,taskId,wal.transitionId);if(liveDispatches.has(key2)||wal.processId!==process.pid&&isProcessAlive3(wal.processId))throw Error(`CODER_DISPATCH_IN_PROGRESS: transition ${wal.transitionId} still owns task ${taskId} (${filePath}, state ${wal.state}, pid ${wal.processId}). Wait for that dispatch to settle or run /swarm recover ${taskId} (or /swarm reset-session) to unwedge it; do not remove the WAL by hand.`);if(wal.state==="DISPATCHED"){if(wal.worktree){let worktree=wal.worktree,observed2=wal.observedFiles??await scopedObservedFiles(worktree.worktreePath,wal.context);if(observed2===null)throw Error(`CODER_SETTLEMENT_RECOVERY_UNCERTAIN: transition ${wal.transitionId} for isolated task ${taskId} could not attribute worktree changes to the declared scope (${filePath}, state ${wal.state}). Run /swarm recover ${taskId} (or /swarm reset-session), then retry; do not remove the WAL by hand.`);let unattributedEmptyScopeMutation2=hasUnattributedEmptyScopeMutation(wal.context.declaredFiles,observed2),accepted=observed2.length>0||unattributedEmptyScopeMutation2,settlementFailed=wal.settlementFailed===!0||unattributedEmptyScopeMutation2;if(wal.mergeProvenance){let landed=await reconcileLandedMerge(directory,wal.mergeProvenance);if(landed.landed){let landedUnstaged=landed.method==="worktree-match";wal={...wal,state:"PREPARED",observedFiles:observed2,accepted,settlementFailed,testEngineerExempt:isMarkdownOnlyTaskChange(wal.context.declaredFiles,observed2)},await writeWal3(filePath,wal);let committed2=await commitPrepared(directory,wal,{landedUnstaged});await cleanupRecoveredWorktree(directory,worktree,{retainBranch:landedUnstaged});let reconciledWal=await readWal2(filePath,taskId);if(reconciledWal===null)throw Error("CODER_SETTLEMENT_WAL_MISSING");return await writeWal3(filePath,{...reconciledWal,cleanupComplete:!0}),committed2}if(landed.error)throw Error(`CODER_SETTLEMENT_RECOVERY_UNCERTAIN: transition ${wal.transitionId} for task ${taskId} could not reconcile the landed merge (${filePath}, state ${wal.state}): ${landed.error}. Run /swarm recover ${taskId} (or /swarm reset-session), then retry; do not remove the WAL by hand.`)}let{awaitingMergeByCallID:awaitingMergeByCallID2,finishStandardWorktreeDispatch:finishStandardWorktreeDispatch2,standardWorktreeByCallID:standardWorktreeByCallID2}=await Promise.resolve().then(() => (init_worktree_isolation(),exports_worktree_isolation)),descriptor=wal.worktree,reconstructedDispatch={callID:descriptor.callID,parentSessionID:descriptor.parentSessionId,taskId:descriptor.taskId,...descriptor.planTaskId?{planTaskId:descriptor.planTaskId}:{},handle:{worktreePath:descriptor.worktreePath,branchName:descriptor.branchName,purpose:"lane",id:descriptor.worktreeId,sessionId:descriptor.worktreeSessionId},mergeStrategy:descriptor.mergeStrategy,laneIndex:descriptor.laneIndex,...descriptor.worktreeDir?{worktree_dir:descriptor.worktreeDir}:{}};standardWorktreeByCallID2.delete(descriptor.callID),awaitingMergeByCallID2.set(descriptor.callID,{callID:descriptor.callID,parentSessionID:descriptor.parentSessionId,taskId:descriptor.taskId,...descriptor.planTaskId?{planTaskId:descriptor.planTaskId}:{},branch:descriptor.branchName,worktreePath:descriptor.worktreePath,mergeStrategy:descriptor.mergeStrategy,queuedAt:Date.now()});let recovered=null,mergeResult=await finishStandardWorktreeDispatch2(directory,reconstructedDispatch,void 0,descriptor.callID,{operationId:wal.transitionId,...wal.mergeProvenance?{resume:wal.mergeProvenance}:{},onBeforeMerge:async(provenance)=>{wal={...wal,mergeProvenance:provenance,observedFiles:observed2},await writeWal3(filePath,wal)},onMerged:async(mergedResult)=>{wal={...wal,state:"PREPARED",accepted,settlementFailed,testEngineerExempt:isMarkdownOnlyTaskChange(wal.context.declaredFiles,observed2)},await writeWal3(filePath,wal),recovered=await commitPrepared(directory,wal,{landedUnstaged:mergedResult.strategy==="squash-unstaged"})}});if(mergeResult.outcome!=="merged"||recovered===null){if(mergeResult.outcome==="failed"&&mergeResult.stage===SOURCE_WORKTREE_GONE_STAGE&&await selfHealMissingLaneWorktree(directory,filePath,taskId,wal.transitionId,descriptor,mergeResult.message))return null;throw Error(`CODER_SETTLEMENT_MERGE_RECOVERY_REQUIRED: transition ${wal.transitionId} for task ${taskId} worktree merge-back did not reach merged (${filePath}, state ${wal.state}, outcome ${mergeResult.outcome}${mergeResult.outcome==="failed"&&mergeResult.message?`: ${mergeResult.message}`:""}). Run /swarm recover ${taskId} (or /swarm reset-session), then retry; do not remove the WAL by hand.`)}await cleanupRecoveredWorktree(directory,descriptor,{retainBranch:mergeResult.strategy==="squash-unstaged"});let committedWal=await readWal2(filePath,taskId);if(committedWal===null)throw Error("CODER_SETTLEMENT_WAL_MISSING");return await writeWal3(filePath,{...committedWal,cleanupComplete:!0}),recovered}let rawObserved=await changedFilesSinceSnapshotAsync(directory,wal.context.baseline),unattributedEmptyScopeMutation=hasUnattributedEmptyScopeMutation(wal.context.declaredFiles,rawObserved),observed;if(rawObserved===null){if(baselineAttributionDoomed(wal.context.baseline)){let aborted3=await abortDispatchedWalUnderLock(directory,taskId,wal.transitionId,doomedReason(wal.context.baseline));if(aborted3.outcome==="aborted"||aborted3.outcome==="already-aborted")return null}observed=null}else if(wal.context.declaredFiles===null)observed=[];else observed=unattributedEmptyScopeMutation?rawObserved:rawObserved.filter((filePath2)=>isPathWithinDeclaredScope(filePath2,wal.context.declaredFiles??[],directory));if(observed===null)throw Error(`CODER_SETTLEMENT_RECOVERY_UNCERTAIN: transition ${wal.transitionId} for task ${taskId} workspace changes could not be attributed to the declared scope (${filePath}, state ${wal.state}). Run /swarm recover ${taskId} (or /swarm reset-session), then retry; do not remove the WAL by hand.`);wal={...wal,state:"PREPARED",accepted:observed.length>0,settlementFailed:wal.settlementFailed===!0||unattributedEmptyScopeMutation,testEngineerExempt:isMarkdownOnlyTaskChange(wal.context.declaredFiles,observed)},await writeWal3(filePath,wal)}let committed=await commitPrepared(directory,wal);if(wal.worktree){await cleanupRecoveredWorktree(directory,wal.worktree);let committedWal=await readWal2(filePath,taskId);if(committedWal===null)throw Error("CODER_SETTLEMENT_WAL_MISSING");await writeWal3(filePath,{...committedWal,cleanupComplete:!0})}return committed})}function releaseCoderDispatchOwnership(directory,taskId,transitionId){liveDispatches.delete(dispatchKey(directory,taskId,transitionId))}async function assertNoUnsettledCoderDispatch(directory,taskId){let filePath=walPath(directory,taskId),wal=await readWal2(filePath,taskId);if(wal===null)return;if(wal.state==="DISPATCHED"||wal.state==="PREPARED")throw Error(`CODER_SETTLEMENT_RECOVERY_REQUIRED: transition ${wal.transitionId} must settle before task ${taskId} can change plan status (${filePath}, state ${wal.state}). Run /swarm recover ${taskId} (or /swarm reset-session), then retry.`)}async function listCoderSettlementWalStates(directory){let entries;try{let dirPath=validateSwarmPath(directory,"coder-settlements");entries=await readdir6(dirPath)}catch{return{states:[],truncated:!1}}let matching=entries.filter((entry)=>SETTLEMENT_WAL_FILE_PATTERN.test(entry)),states=[];for(let entry of matching.sort().slice(0,MAX_SETTLEMENT_WAL_SCAN)){let taskId=entry.slice(0,-5);try{let wal=await readWal2(walPath(directory,taskId),taskId);if(wal===null)continue;states.push({taskId,state:wal.state,transitionId:wal.transitionId,processId:wal.processId,recordedAt:wal.recordedAt,accepted:wal.accepted===!0?!0:void 0,declaredFiles:wal.context?.declaredFiles??null,expectedGeneration:wal.expectedGeneration,ownedInProcess:liveDispatches.has(dispatchKey(directory,taskId,wal.transitionId)),ownedByLiveForeignPid:wal.processId!==process.pid&&isProcessAlive3(wal.processId)})}catch{states.push({taskId,state:"unreadable",ownedInProcess:!1,ownedByLiveForeignPid:!1})}}return{states,truncated:matching.length>MAX_SETTLEMENT_WAL_SCAN}}async function recoverStaleCoderSettlements(directory,options){let{states:listed,truncated}=await listCoderSettlementWalStates(directory),filter=options?.taskIds?new Set(options.taskIds):void 0,results=[];for(let entry of listed){if(filter&&!filter.has(entry.taskId))continue;if(entry.state==="unreadable"){results.push({taskId:entry.taskId,outcome:"unreadable_wal"});continue}if(entry.state==="ABORTED"||entry.state==="COMMITTED"){try{await _internals100.recoverCoderSettlement(directory,entry.taskId),results.push({taskId:entry.taskId,outcome:"already_terminal",state:entry.state})}catch(error93){results.push({taskId:entry.taskId,outcome:"error",message:error93 instanceof Error?error93.message:String(error93)})}continue}if(entry.ownedInProcess&&options?.force!==!0){results.push({taskId:entry.taskId,outcome:"owned_in_process",transitionId:entry.transitionId??""});continue}if(entry.ownedByLiveForeignPid){results.push({taskId:entry.taskId,outcome:"owned_by_live_foreign_pid",processId:entry.processId??-1});continue}let forced=entry.ownedInProcess&&options?.force===!0;if(forced&&entry.transitionId)releaseCoderDispatchOwnership(directory,entry.taskId,entry.transitionId),await appendSettlementEvent(directory,"recovered",{taskId:entry.taskId,transitionId:entry.transitionId,actor:"swarm-recovery"},{forced:!0,stage:"ownership-release"});try{let recovered=await _internals100.recoverCoderSettlement(directory,entry.taskId);if(recovered===null){let current=null;try{current=await readWal2(walPath(directory,entry.taskId),entry.taskId)}catch{current=null}if(current&&(current.state==="COMMITTED"||current.state==="ABORTED")){results.push({taskId:entry.taskId,outcome:"already_terminal",state:current.state});continue}results.push({taskId:entry.taskId,outcome:"error",message:"settlement WAL disappeared during recovery"});continue}await appendSettlementEvent(directory,"recovered",{taskId:entry.taskId,transitionId:entry.transitionId??"",actor:"swarm-recovery"},{forced,accepted:recovered.accepted,previousTransitionId:entry.transitionId??"",previousState:entry.state,...typeof entry.expectedGeneration==="number"?{expectedGeneration:entry.expectedGeneration}:{}}),results.push({taskId:entry.taskId,outcome:"recovered",accepted:recovered.accepted,forced})}catch(error93){let message=error93 instanceof Error?error93.message:String(error93);await appendSettlementEvent(directory,"recovery-failed",{taskId:entry.taskId,transitionId:entry.transitionId??"",actor:"swarm-recovery"},{forced,error:message}),results.push({taskId:entry.taskId,outcome:"error",message})}}return{results,truncated}}var LIVE_DISPATCHES_SYMBOL,globalRegistry3,liveDispatches,runtimeId,MAX_LIVE_DISPATCHES=512,MAX_SETTLEMENT_WAL_SCAN=200,SETTLEMENT_WAL_FILE_PATTERN,_internals100;var init_coder_settlement=__esm(()=>{init_workspace_snapshot();init_core_events();init_gate_evidence();init_gate_evidence_classification();init_worktree_provisioning_owner();init_utils2();init_file_locks();init_path_identity();init_warning_buffer();init_canonical_root();init_git_executable();init_logger();init_merge2();init_workflow_wal_file();LIVE_DISPATCHES_SYMBOL=Symbol.for("opencode-swarm.workflow.coder-settlement.live-dispatches"),globalRegistry3=globalThis;if(!globalRegistry3[LIVE_DISPATCHES_SYMBOL])globalRegistry3[LIVE_DISPATCHES_SYMBOL]=new Set;liveDispatches=globalRegistry3[LIVE_DISPATCHES_SYMBOL],runtimeId=randomUUID14();SETTLEMENT_WAL_FILE_PATTERN=/^[\w.\-:]+\.json$/;_internals100={liveDispatches,removeWorktreeProvisioningOwner,branchExists:probeBranchExists,recoverCoderSettlement}});var exports_pending_delegations={};__export(exports_pending_delegations,{writeDelegationFallback:()=>writeDelegationFallback,updateCoderSettlement:()=>updateCoderSettlement,sweepStaleDelegations:()=>sweepStaleDelegations,scanDelegationsForRecovery:()=>scanDelegationsForRecovery,scanDelegationFallbacksForRecovery:()=>scanDelegationFallbacksForRecovery,scanBackgroundCoderReservationsForAdmission:()=>scanBackgroundCoderReservationsForAdmission,reserveBackgroundCoderSlot:()=>reserveBackgroundCoderSlot,replacePendingBackgroundAdvisory:()=>replacePendingBackgroundAdvisory,removeDelegationFallback:()=>removeDelegationFallback,releasePreparedBackgroundAdvisories:()=>releasePreparedBackgroundAdvisories,releaseBackgroundCoderReservation:()=>releaseBackgroundCoderReservation,registerStaleSweepObserver:()=>registerStaleSweepObserver,registerLegacyCoderSettlementReconciler:()=>registerLegacyCoderSettlementReconciler,recordedPrReviewResultReceipt:()=>recordedPrReviewResultReceipt,recordPendingDelegationDetailed:()=>recordPendingDelegationDetailed,recordPendingDelegation:()=>recordPendingDelegation,recordDelegationIngestionResult:()=>recordDelegationIngestionResult,readDelegationsDetailed:()=>readDelegationsDetailed,readDelegations:()=>readDelegations,readDelegationFallback:()=>readDelegationFallback,putPendingBackgroundAdvisory:()=>putPendingBackgroundAdvisory,publishPrReviewResultReceipt:()=>publishPrReviewResultReceipt,promoteDelegationFallback:()=>promoteDelegationFallback,preparePendingBackgroundAdvisories:()=>preparePendingBackgroundAdvisories,normalizeBackgroundObservedFiles:()=>normalizeBackgroundObservedFiles,markLegacyCoderSettlementTransferPending:()=>markLegacyCoderSettlementTransferPending,maintainBackgroundDelegations:()=>maintainBackgroundDelegations,listDelegationFallbacks:()=>listDelegationFallbacks,isUnsettledWorktreeOwner:()=>isUnsettledWorktreeOwner,isTerminalDelegationStatus:()=>isTerminalDelegationStatus,findOpenAsyncLaneBatches:()=>findOpenAsyncLaneBatches,findDelegationForCompletion:()=>findDelegationForCompletion,findByCorrelationIdDetailed:()=>findByCorrelationIdDetailed,findByCorrelationId:()=>findByCorrelationId,findByBatchIdDetailed:()=>findByBatchIdDetailed,findByBatchId:()=>findByBatchId,compactBackgroundDelegations:()=>compactBackgroundDelegations,clearLegacyCoderSettlementTransferPending:()=>clearLegacyCoderSettlementTransferPending,claimTerminalResult:()=>claimTerminalResult,claimDelegationIngestion:()=>claimDelegationIngestion,claimCoderSettlement:()=>claimCoderSettlement,buildTypedDelegationTerminal:()=>buildTypedDelegationTerminal,buildPromptSnapshot:()=>buildPromptSnapshot,buildBackgroundCompletionEventId:()=>buildBackgroundCompletionEventId,buildBackgroundCoderReservationId:()=>buildBackgroundCoderReservationId,bindBackgroundCoderReservation:()=>bindBackgroundCoderReservation,appendDelegationTransition:()=>appendDelegationTransition,acknowledgeObservedBackgroundAdvisories:()=>acknowledgeObservedBackgroundAdvisories,_internals:()=>_internals101,_checkpointInternals:()=>_checkpointInternals,TOMBSTONE_MIN_AGE_MS:()=>TOMBSTONE_MIN_AGE_MS,MAX_RECOVERY_LEDGER_BYTES:()=>MAX_RECOVERY_LEDGER_BYTES,MAX_LIVE_BACKGROUND_FALLBACKS:()=>MAX_LIVE_BACKGROUND_FALLBACKS,MAX_LIVE_BACKGROUND_CODER_RESERVATIONS:()=>MAX_LIVE_BACKGROUND_CODER_RESERVATIONS,MAX_CHECKPOINT_RECORDS:()=>MAX_CHECKPOINT_RECORDS,MAX_CHECKPOINT_BYTES:()=>MAX_CHECKPOINT_BYTES,MAX_BACKGROUND_OBSERVED_FILES:()=>MAX_BACKGROUND_OBSERVED_FILES,MAX_BACKGROUND_ADVISORY_CHARS:()=>MAX_BACKGROUND_ADVISORY_CHARS,LEGACY_CODER_SETTLEMENT_PENDING_ADVISORY_MARKER:()=>LEGACY_CODER_SETTLEMENT_PENDING_ADVISORY_MARKER,DELEGATION_READ_RETRY_DELAY_MS:()=>DELEGATION_READ_RETRY_DELAY_MS,DELEGATION_COMPACTION_LOW_WATER_BYTES:()=>DELEGATION_COMPACTION_LOW_WATER_BYTES,DELEGATION_COMPACTION_HIGH_WATER_BYTES:()=>DELEGATION_COMPACTION_HIGH_WATER_BYTES,DEFAULT_SWEEPABLE_DELEGATION_STATUSES:()=>DEFAULT_SWEEPABLE_DELEGATION_STATUSES,DEFAULT_STALE_DELEGATION_TIMEOUT_MS:()=>DEFAULT_STALE_DELEGATION_TIMEOUT_MS,BACKGROUND_INGESTION_LEASE_MS:()=>BACKGROUND_INGESTION_LEASE_MS,BACKGROUND_DELEGATION_FALLBACK_DIR:()=>BACKGROUND_DELEGATION_FALLBACK_DIR,BACKGROUND_DELEGATIONS_MANIFEST_FILE:()=>BACKGROUND_DELEGATIONS_MANIFEST_FILE,BACKGROUND_DELEGATIONS_FILE:()=>BACKGROUND_DELEGATIONS_FILE,BACKGROUND_DELEGATIONS_CHECKPOINT_FILE:()=>BACKGROUND_DELEGATIONS_CHECKPOINT_FILE,BACKGROUND_CODER_RESERVATION_LEASE_MS:()=>BACKGROUND_CODER_RESERVATION_LEASE_MS,BACKGROUND_CODER_RESERVATION_LEASE_MIN_MS:()=>BACKGROUND_CODER_RESERVATION_LEASE_MIN_MS,BACKGROUND_CODER_RESERVATION_LEASE_MAX_MS:()=>BACKGROUND_CODER_RESERVATION_LEASE_MAX_MS,BACKGROUND_CODER_RESERVATIONS_FILE:()=>BACKGROUND_CODER_RESERVATIONS_FILE});import{createHash as createHash49}from"node:crypto";import*as fs70 from"node:fs";import*as path109 from"node:path";import{isDeepStrictEqual}from"node:util";function clampReservationLeaseMs(leaseMs){if(leaseMs===void 0)return BACKGROUND_CODER_RESERVATION_LEASE_MS;if(!Number.isFinite(leaseMs))return BACKGROUND_CODER_RESERVATION_LEASE_MS;return Math.min(Math.max(Math.round(leaseMs),BACKGROUND_CODER_RESERVATION_LEASE_MIN_MS),BACKGROUND_CODER_RESERVATION_LEASE_MAX_MS)}function isValidReservationGeneration(generation){return generation===void 0||Number.isInteger(generation)&&generation>=1&&generation<=MAX_BACKGROUND_DELEGATION_GENERATION}function storePath5(directory){return validateSwarmPath(directory,BACKGROUND_DELEGATIONS_FILE)}function checkpointPath2(directory){return validateSwarmPath(directory,BACKGROUND_DELEGATIONS_CHECKPOINT_FILE)}function manifestPath(directory){return validateSwarmPath(directory,BACKGROUND_DELEGATIONS_MANIFEST_FILE)}function importedShadowPath2(filePath){return`${filePath}.imported`}function projectionMarkerPath2(filePath){return`${filePath}.sqlite-projection`}function coordinationReservationLeaseKey(reservation){return{namespace:RESERVATION_LEASE_NAMESPACE,entityKey:reservation.reservationId,generation:reservation.generation??1,ownerToken:reservation.reservationId}}function releaseReservationLeaseIfPresent(directory,reservation){let leaseKey=coordinationReservationLeaseKey(reservation),existing=getCoordinationLease(directory,leaseKey.namespace,leaseKey.entityKey);if(!existing)return;if(existing.generation!==leaseKey.generation||existing.ownerToken!==leaseKey.ownerToken||!releaseCoordinationLease(directory,leaseKey.namespace,leaseKey.entityKey,leaseKey.generation,leaseKey.ownerToken))throw Error(`reservation lease authority mismatch for ${reservation.reservationId}`)}function coordinationRowsToDelegations(directory){if(!projectDbExists(directory))return null;try{let rows=listCoordinationStates(directory,DELEGATION_COORDINATION_NAMESPACE,MAX_COORDINATION_STATE_LIST_ROWS);if(rows.length>=MAX_COORDINATION_STATE_LIST_ROWS)throw Error(`delegation coordination read reached its ${MAX_COORDINATION_STATE_LIST_ROWS}-row safety bound`);return rows.map((row)=>{let parsed=RecordSchema2.safeParse(JSON.parse(row.payload));if(!parsed.success)throw Error(`delegation coordination row failed schema validation for ${row.entityKey}`);if(parsed.data.correlationId!==row.entityKey)throw Error(`delegation coordination row authority binding mismatch: payload correlationId does not equal entity key ${row.entityKey}`);if(Math.max(parsed.data.generation??1,1)!==row.generation)throw Error(`delegation coordination row authority binding mismatch: payload generation does not equal row generation for ${row.entityKey}`);if(parsed.data.status!==row.status)throw Error(`delegation coordination row authority binding mismatch: payload status does not equal row status for ${row.entityKey}`);return parsed.data}).sort((left,right)=>left.createdAt===right.createdAt?left.correlationId.localeCompare(right.correlationId):left.createdAt-right.createdAt)}catch(error93){return recordLedgerUncertainty(directory,error93 instanceof Error?error93.message:String(error93),"coordination-read"),null}}function archiveShadowFileBestEffort2(filePath){if(!fs70.existsSync(filePath))return;let importedPath=importedShadowPath2(filePath);try{if(fs70.existsSync(importedPath))return;fs70.renameSync(filePath,importedPath)}catch(error93){warn(`[background] shadow archive failed for ${path109.basename(filePath)}: ${error93 instanceof Error?error93.message:String(error93)}`)}}function writeDelegationShadowProjection(directory,records){ensureSwarmDir3(directory);let payload=records.map((record3)=>JSON.stringify(record3)).join(`
|
|
1263
1263
|
`)+(records.length>0?`
|
|
1264
1264
|
`:"");fs70.writeFileSync(storePath5(directory),payload,"utf-8"),fs70.writeFileSync(projectionMarkerPath2(storePath5(directory)),"","utf-8")}function loadLegacyDelegationsStrict(directory){let load=loadFoldedState(directory,{strict:!0});if(load.status==="uncertain")return recordLedgerUncertainty(directory,load.reason,"legacy-import",load.repairHint),null;return[...load.records.values()]}function delegationShadowMatches(directory,records){let load=loadFoldedState(directory,{strict:!1});if(load.status==="uncertain")return!1;return isDeepStrictEqual([...load.records.values()].sort((left,right)=>left.correlationId.localeCompare(right.correlationId)),[...records].sort((left,right)=>left.correlationId.localeCompare(right.correlationId)))}function delegationShadowDigest(directory,records){let hash4=createHash49("sha256");hash4.update(JSON.stringify(records));for(let filePath of[storePath5(directory),checkpointPath2(directory),manifestPath(directory)]){if(!fs70.existsSync(filePath))continue;hash4.update(path109.basename(filePath)),hash4.update(fs70.readFileSync(filePath))}return hash4.digest("hex")}function ensureDelegationCoordinationImported(directory,createIfNeeded){let dbExists=projectDbExists(directory);if(!createIfNeeded&&!dbExists)return"absent";let existing=dbExists?coordinationRowsToDelegations(directory):null;if(dbExists&&existing===null)return"uncertain";if(existing&&existing.length>0){if(createIfNeeded)return"ready";if(!(fs70.existsSync(projectionMarkerPath2(storePath5(directory)))&&delegationShadowMatches(directory,existing))){for(let filePath of[storePath5(directory),checkpointPath2(directory),manifestPath(directory)])archiveShadowFileBestEffort2(filePath);writeDelegationShadowProjection(directory,existing)}return"ready"}let legacyRecords=loadLegacyDelegationsStrict(directory);if(legacyRecords===null)return"uncertain";if(legacyRecords.length===0&&!fs70.existsSync(storePath5(directory))&&!fs70.existsSync(checkpointPath2(directory))&&!fs70.existsSync(manifestPath(directory))){if(!createIfNeeded)return"absent";return withCoordinationTransaction(directory,()=>{return}),"ready"}if(importCoordinationOnce(directory,{source:BACKGROUND_DELEGATIONS_FILE,sourceDigest:delegationShadowDigest(directory,legacyRecords),rowCount:legacyRecords.length,emptyNamespace:DELEGATION_COORDINATION_NAMESPACE},()=>{for(let record3 of legacyRecords){let result=transitionCoordinationState(directory,{namespace:DELEGATION_COORDINATION_NAMESPACE,entityKey:record3.correlationId,expectedRevision:null,generation:Math.max(record3.generation??1,1),status:record3.status,payload:JSON.stringify(record3)});if(result.outcome!=="applied")throw Error(`delegation import failed for ${record3.correlationId}: ${result.outcome}`)}})==="imported")archiveShadowFileBestEffort2(storePath5(directory)),archiveShadowFileBestEffort2(checkpointPath2(directory)),archiveShadowFileBestEffort2(manifestPath(directory)),writeDelegationShadowProjection(directory,legacyRecords);return"ready"}function pruneCoordinationDelegationRows(directory){let terminals=listCoordinationStates(directory,DELEGATION_COORDINATION_NAMESPACE,MAX_COORDINATION_STATE_LIST_ROWS).filter((row)=>!isCheckpointLiveRecord(JSON.parse(row.payload))).sort((left,right)=>left.updatedAt.localeCompare(right.updatedAt)),excessTerminals=Math.max(0,terminals.length-MAX_COORDINATION_TERMINAL_ROWS);for(let row of terminals.slice(0,excessTerminals))deleteCoordinationState(directory,DELEGATION_COORDINATION_NAMESPACE,row.entityKey,row.revision);if(listCoordinationStates(directory,DELEGATION_COORDINATION_NAMESPACE,MAX_COORDINATION_STATE_LIST_ROWS).length>=MAX_COORDINATION_DELEGATION_ROWS)throw Error(`delegation coordination state reached its ${MAX_COORDINATION_DELEGATION_ROWS}-row safety bound`)}function portableSyncSleep(ms){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,ms)}catch{let start=Date.now();while(Date.now()-start<ms);}}function writeDurableFileSync(target,contents){let tmp=`${target}.tmp-${process.pid}-${Math.random().toString(36).slice(2,10)}`;try{let fd=fs70.openSync(tmp,"w");try{if(typeof contents==="string")fs70.writeSync(fd,contents);else fs70.writeSync(fd,contents,0,contents.length);fs70.fsyncSync(fd)}finally{fs70.closeSync(fd)}_checkpointInternals.renameWithRetry(tmp,target)}catch(err){try{fs70.rmSync(tmp,{force:!0})}catch{}throw err}try{let dfd=fs70.openSync(path109.dirname(target),"r");try{fs70.fsyncSync(dfd)}finally{fs70.closeSync(dfd)}}catch{}}function readJsonFileWithRetry(target){let raw;try{raw=fs70.readFileSync(target,"utf-8")}catch(err){let code=err.code;if(code==="ENOENT")return{status:"absent"};return{status:"invalid",reason:`unreadable (${code??"unknown error"})`}}try{return{status:"ok",value:JSON.parse(raw)}}catch(err){return{status:"invalid",reason:`malformed JSON (${err instanceof Error?err.message:String(err)})`}}}function readDelegationManifest(directory){let read=readJsonFileWithRetry(manifestPath(directory));if(read.status==="absent")return{kind:"absent"};if(read.status==="invalid")return{kind:"invalid",reason:read.reason};let parsed=ManifestSchema.safeParse(read.value);if(!parsed.success)return{kind:"invalid",reason:"manifest fails schema validation"};return{kind:"ok",manifest:parsed.data}}function readDelegationCheckpoint(directory){let bytes=0;try{bytes=fs70.statSync(checkpointPath2(directory)).size}catch{}if(bytes>MAX_CHECKPOINT_BYTES)return{kind:"invalid",reason:`checkpoint exceeds the ${MAX_CHECKPOINT_BYTES}-byte bound`};let read=readJsonFileWithRetry(checkpointPath2(directory));if(read.status==="absent")return{kind:"absent"};if(read.status==="invalid")return{kind:"invalid",reason:read.reason};let parsed=CheckpointSchema2.safeParse(read.value);if(!parsed.success)return{kind:"invalid",reason:"checkpoint fails schema validation"};return{kind:"ok",checkpoint:parsed.data,bytes}}function sha256Hex(data){return createHash49("sha256").update(data).digest("hex")}function checkpointPayloadChecksum(checkpoint2){return sha256Hex(JSON.stringify([checkpoint2.schemaVersion,checkpoint2.sequence,checkpoint2.writerId,checkpoint2.rootPath,checkpoint2.createdAt,checkpoint2.cutLedgerBytes,checkpoint2.cutLedgerDigest,checkpoint2.records,checkpoint2.closed,checkpoint2.audit]))}function loadFoldedState(directory,options){let manifestRead=readDelegationManifest(directory);if(manifestRead.kind==="invalid")return{status:"uncertain",reason:`background delegation manifest is invalid: ${manifestRead.reason}`,repairHint:CHECKPOINT_RESET_HINT};if(manifestRead.kind==="absent")return loadLegacyLedger(directory,options.strict);let manifest=manifestRead.manifest;if(!sameProjectRoot(manifest.rootPath,directory))return{status:"uncertain",reason:"background delegation checkpoint is bound to a different project root",repairHint:CHECKPOINT_REBIND_HINT};let checkpointRead=readDelegationCheckpoint(directory);if(checkpointRead.kind==="invalid"||checkpointRead.kind==="absent")return{status:"uncertain",reason:`background delegation checkpoint is invalid${checkpointRead.kind==="invalid"?`: ${checkpointRead.reason}`:" (file missing)"} while a manifest is published`,repairHint:CHECKPOINT_RESET_HINT};let checkpoint2=checkpointRead.checkpoint;if(checkpoint2.sequence!==manifest.sequence&&checkpoint2.sequence!==manifest.sequence+1)return{status:"uncertain",reason:`background delegation checkpoint/manifest sequence mismatch (checkpoint ${checkpoint2.sequence}, manifest ${manifest.sequence})`,repairHint:CHECKPOINT_RESET_HINT};if(checkpoint2.sequence===manifest.sequence&&manifest.checkpointChecksum!==checkpoint2.payloadChecksum)return{status:"uncertain",reason:"background delegation manifest checksum does not match its checkpoint",repairHint:CHECKPOINT_RESET_HINT};if(checkpointPayloadChecksum(checkpoint2)!==checkpoint2.payloadChecksum)return{status:"uncertain",reason:"background delegation checkpoint payload checksum mismatch",repairHint:CHECKPOINT_RESET_HINT};let stat10;try{stat10=fs70.statSync(storePath5(directory))}catch(error93){return{status:"uncertain",reason:`background delegation ledger metadata is unreadable: ${error93 instanceof Error?error93.message:String(error93)}`}}let tail,mode;if(stat10.size>=checkpoint2.cutLedgerBytes&&checkpoint2.cutLedgerBytes>0){let prefix=readLedgerRegion(directory,0,checkpoint2.cutLedgerBytes);if(sha256Hex(prefix)===checkpoint2.cutLedgerDigest){let suffixBytes=stat10.size-checkpoint2.cutLedgerBytes;if(suffixBytes>MAX_RECOVERY_LEDGER_BYTES)return{status:"uncertain",reason:`background delegation ledger changed beyond the ${MAX_RECOVERY_LEDGER_BYTES}-byte recovery bound`};tail=suffixBytes===0?Buffer.alloc(0):readLedgerRegion(directory,checkpoint2.cutLedgerBytes,suffixBytes),mode="checkpoint+ledger-suffix"}else tail=readBoundedRecentLedgerWindow(directory,stat10.size),mode="checkpoint+tail"}else tail=readBoundedRecentLedgerWindow(directory,stat10.size),mode="checkpoint+tail";let records=new Map;for(let record3 of checkpoint2.records)records.set(record3.correlationId,record3);for(let summary of checkpoint2.closed)records.set(summary.correlationId,summary);let lenientSkips=emptyLenientLedgerSkipCounts(),foldError=foldLedgerTail(records,tail,options.strict,checkpoint2,lenientSkips);if(foldError)return{status:"uncertain",reason:foldError};if(!options.strict)recordLenientLedgerSkips(directory,mode,lenientSkips);return{status:"ok",mode,records,manifest,checkpoint:checkpoint2}}function readLedgerRegion(directory,offset,length){let fd=fs70.openSync(storePath5(directory),"r");try{let buffer=Buffer.alloc(length),read=0;while(read<length){let n=fs70.readSync(fd,buffer,read,length-read,offset+read);if(n<=0)break;read+=n}return read===length?buffer:buffer.subarray(0,read)}finally{fs70.closeSync(fd)}}function readBoundedRecentLedgerWindow(directory,size){if(size===0)return Buffer.alloc(0);if(size<=MAX_RECOVERY_LEDGER_BYTES)return readLedgerRegion(directory,0,size);let window2=readLedgerRegion(directory,size-MAX_RECOVERY_LEDGER_BYTES,MAX_RECOVERY_LEDGER_BYTES),firstNewline=window2.indexOf(10);return firstNewline===-1?Buffer.alloc(0):window2.subarray(firstNewline+1)}function foldLedgerTail(records,tail,strict,checkpoint2,lenientSkips){let lineNumber=0;for(let line of tail.toString("utf-8").split(`
|
|
1265
1265
|
`)){lineNumber+=1;let trimmed=line.trim();if(!trimmed)continue;let parsedJson;try{parsedJson=JSON.parse(trimmed)}catch{if(strict)return`background delegation ledger has malformed JSON at line ${lineNumber}`;if(lenientSkips)lenientSkips.malformedJson+=1;continue}let parsed=RecordSchema2.safeParse(parsedJson);if(!parsed.success){if(strict)return`background delegation ledger has an invalid record at line ${lineNumber}`;if(lenientSkips)lenientSkips.invalidRecord+=1;continue}let existing=checkpoint2?records.get(parsed.data.correlationId):void 0;if(checkpoint2&&existing&&!(parsed.data.updatedAt>existing.updatedAt)&&!(parsed.data.updatedAt===existing.updatedAt&&parsed.data.updatedAt>checkpoint2.createdAt))continue;records.set(parsed.data.correlationId,parsed.data)}return null}function loadLegacyLedger(directory,strict){if(!strict){let raw2;try{raw2=fs70.readFileSync(storePath5(directory),"utf-8")}catch(err){if(err.code!=="ENOENT")warn(`[background] readDelegations failed: ${err instanceof Error?err.message:String(err)}`);return{status:"ok",mode:"legacy",records:new Map,manifest:null,checkpoint:null}}let records2=new Map,lenientSkips=emptyLenientLedgerSkipCounts(),foldError2=foldLedgerTail(records2,Buffer.from(raw2,"utf-8"),!1,void 0,lenientSkips);return recordLenientLedgerSkips(directory,"legacy-ledger",lenientSkips),{status:"ok",mode:"legacy",records:records2,manifest:null,checkpoint:null}}let absolutePath;try{if(absolutePath=storePath5(directory),fs70.statSync(absolutePath).size>MAX_RECOVERY_LEDGER_BYTES)return{status:"uncertain",reason:`background delegation ledger exceeds the ${MAX_RECOVERY_LEDGER_BYTES}-byte recovery bound`}}catch(error93){if(error93.code==="ENOENT")return{status:"ok",mode:"legacy",records:new Map,manifest:null,checkpoint:null};return{status:"uncertain",reason:`background delegation ledger metadata is unreadable: ${error93 instanceof Error?error93.message:String(error93)}`}}let raw;try{raw=fs70.readFileSync(absolutePath,"utf-8")}catch(error93){return{status:"uncertain",reason:`background delegation ledger is unreadable: ${error93 instanceof Error?error93.message:String(error93)}`}}if(Buffer.byteLength(raw,"utf8")>MAX_RECOVERY_LEDGER_BYTES)return{status:"uncertain",reason:`background delegation ledger changed beyond the ${MAX_RECOVERY_LEDGER_BYTES}-byte recovery bound`};let records=new Map,foldError=foldLedgerTail(records,Buffer.from(raw,"utf-8"),!0);if(foldError)return{status:"uncertain",reason:foldError};return{status:"ok",mode:"legacy",records,manifest:null,checkpoint:null}}function loadRecordsForWrite(directory){let importState=ensureDelegationCoordinationImported(directory,!0);if(importState==="uncertain")return null;if(importState==="ready"){let coordination=coordinationRowsToDelegations(directory);if(coordination!==null)return coordination;return null}let load=loadFoldedState(directory,{strict:!1});if(load.status==="uncertain")return recordLedgerUncertainty(directory,load.reason,"mutation",load.repairHint),null;return[...load.records.values()]}function findRecordForWrite(records,correlationId){if(!records)return null;for(let record3 of records)if(record3.correlationId===correlationId)return record3;return null}function recordLedgerUncertainty(directory,reason,source,repairHint){try{writeDelegationHealthArtifact(directory,{uncertainty:{reason,at:Date.now(),source,...repairHint?{repairHint}:{}}})}catch{}}function emptyLenientLedgerSkipCounts(){return{malformedJson:0,invalidRecord:0}}function shouldEmitLenientLedgerSignal(directory,signature){let key2=canonicalRootKeyFresh(directory),existing=lenientLedgerSignalByRoot.get(key2);if(existing===signature)return!1;if(!existing){if(lenientLedgerSignalOrder.length>=MAX_TRACKED_LENIENT_LEDGER_SIGNALS){let evicted=lenientLedgerSignalOrder.shift();if(evicted)lenientLedgerSignalByRoot.delete(evicted)}lenientLedgerSignalOrder.push(key2)}return lenientLedgerSignalByRoot.set(key2,signature),!0}function recordLenientLedgerSkips(directory,source,counts){let skipped=counts.malformedJson+counts.invalidRecord;if(skipped<=0)return;let reason=`background delegation ledger skipped ${skipped} malformed/invalid row${skipped===1?"":"s"} during lenient ${source} read (${counts.malformedJson} malformed JSON, ${counts.invalidRecord} invalid records)`,signature=`${source}:${counts.malformedJson}:${counts.invalidRecord}`;if(shouldEmitLenientLedgerSignal(directory,signature))criticalWarn(`[background] ${reason}`);try{let current=readDelegationHealthArtifact(directory);if(current?.lastUncertainty&¤t.lastUncertainty.source!==LENIENT_LEDGER_SIGNAL_SOURCE)return;writeDelegationHealthArtifact(directory,{lastUncertainty:{reason,at:Date.now(),source:LENIENT_LEDGER_SIGNAL_SOURCE}})}catch{}}function isUnsettledWorktreeOwner(record3){return Boolean(record3.worktree)&&!(record3.coderSettlement?.state==="settled"&&record3.coderSettlement.outcome?.kind==="standard-worktree"&&(record3.coderSettlement.outcome.result==="merged"||record3.coderSettlement.outcome.result==="unchanged"))}function isCheckpointLiveRecord(record3){if(!isTerminal(record3.status))return!0;if(record3.advisoryInbox?.state==="pending")return!0;if(record3.legacyCoderSettlementTransfer)return!0;let settlement=record3.coderSettlement;if(settlement&&settlement.state!=="settled")return!0;if(settlement?.state==="settled"&&isUnsettledWorktreeOwner(record3))return!0;if(isActiveCoderOwner(record3))return!0;return!1}function buildClosedSummary(record3){let summary={...record3};if(delete summary.prompt,delete summary.taskChangeContext,summary.result)summary.result=stripResultBody(record3,summary.result);if(summary.terminalResult)summary.terminalResult={...summary.terminalResult,result:dropTerminalResultBody(summary.terminalResult.result)};let parsed=RecordSchema2.safeParse(summary);return parsed.success?parsed.data:null}function stripResultBody(record3,result){let{text:_text,error:_error,...rest}=result,receipt=parsePrReviewCollectionReceiptFooter(record3,result),shedMarker=receipt?null:parsePrReviewCollectionReceiptShedMarker(record3,result),receiptText=receipt?`${PR_REVIEW_COLLECTION_RECEIPT_PREFIX}${JSON.stringify(receipt)}`:shedMarker?`${PR_REVIEW_COLLECTION_RECEIPT_SHED_PREFIX}${JSON.stringify(shedMarker)}`:void 0;return receiptText?{...rest,text:receiptText,outputPreviewChars:receiptText.length}:rest}function dropResultBody(result){let{text:_text,error:_error,outputPreviewChars:_preview,...rest}=result;return rest}function dropTerminalResultBody(result){let{prReviewResultReceipt:_receipt,...rest}=dropResultBody(result);return rest}function dropRetainedPrReviewReceipt(record3){let compact=(result)=>{let payload=parsePrReviewCollectionReceiptFooter(record3,result);if(!payload){let marker2=parsePrReviewCollectionReceiptShedMarker(record3,result);if(!marker2)return dropResultBody(result);let markerText=`${PR_REVIEW_COLLECTION_RECEIPT_SHED_PREFIX}${JSON.stringify(marker2)}`,{text:_text2,error:_error2,...rest2}=result;return{...rest2,text:markerText,outputPreviewChars:markerText.length}}let marker=encodePrReviewCollectionReceiptShedMarker(payload),{text:_text,error:_error,...rest}=result;return{...rest,text:marker,outputPreviewChars:marker.length}};return{...record3,...record3.result?{result:compact(record3.result)}:{},...record3.terminalResult?{terminalResult:{...record3.terminalResult,result:dropTerminalResultBody(record3.terminalResult.result)}}:{}}}function emptyAudit(){return{dispatchCount:0,terminalsByStatus:{completed:0,error:0,cancelled:0,stale:0},settledCount:0,preservedCount:0,lateTerminalCount:0,compactedTransitionCount:0,compactedRecordCount:0,firstDispatchAt:null,lastTerminalAt:null,lastCompactionAt:0}}function terminalEventStatusOf(record3){if(record3.terminalResult)return record3.terminalResult.status;if(record3.status==="completed"||record3.status==="error"||record3.status==="cancelled"||record3.status==="rejected"||record3.status==="stale")return record3.status;return null}function mergeCheckpointAudit(previous,previousCheckpoint,folded,healthLateTerminals,retiredLineCount,newlySummarizedCount,now){let prev=previous??emptyAudit(),prevById=new Map;if(previousCheckpoint){for(let record3 of previousCheckpoint.records)prevById.set(record3.correlationId,record3);for(let summary of previousCheckpoint.closed)prevById.set(summary.correlationId,summary)}let audit={dispatchCount:prev.dispatchCount,terminalsByStatus:{...prev.terminalsByStatus},settledCount:prev.settledCount,preservedCount:prev.preservedCount,lateTerminalCount:Math.max(prev.lateTerminalCount,healthLateTerminals),compactedTransitionCount:capCounter(prev.compactedTransitionCount,retiredLineCount),compactedRecordCount:capCounter(prev.compactedRecordCount,newlySummarizedCount),firstDispatchAt:prev.firstDispatchAt,lastTerminalAt:prev.lastTerminalAt,lastCompactionAt:now},minCreated=Number.POSITIVE_INFINITY,maxTerminal=0;for(let record3 of folded){let prevRecord=prevById.get(record3.correlationId);if(!prevRecord)audit.dispatchCount+=1;let terminalStatus=terminalEventStatusOf(record3);if(terminalStatus){if((prevRecord?terminalEventStatusOf(prevRecord):null)!==terminalStatus){if(terminalStatus!=="rejected")audit.terminalsByStatus[terminalStatus]+=1}maxTerminal=Math.max(maxTerminal,record3.terminalResult?.recordedAt??record3.completedAt??0)}if(record3.coderSettlement?.state==="settled"&&prevRecord?.coderSettlement?.state!=="settled")audit.settledCount+=1;if(record3.coderSettlement?.state==="preserved"&&prevRecord?.coderSettlement?.state!=="preserved")audit.preservedCount+=1;minCreated=Math.min(minCreated,record3.createdAt)}return audit.firstDispatchAt=Number.isFinite(minCreated)?Math.min(prev.firstDispatchAt??Number.POSITIVE_INFINITY,minCreated):prev.firstDispatchAt,audit.lastTerminalAt=Math.max(prev.lastTerminalAt??0,maxTerminal)||null,audit}function capCounter(previous,delta){return Number.isSafeInteger(previous+delta)?previous+delta:Number.MAX_SAFE_INTEGER}function synchronizeCoordinationAfterCompaction(directory,retained){if(!projectDbExists(directory))return;let retainedById=new Map(retained.map((record3)=>[record3.correlationId,record3]));withCoordinationTransaction(directory,()=>{let rows=listCoordinationStates(directory,DELEGATION_COORDINATION_NAMESPACE,MAX_COORDINATION_STATE_LIST_ROWS);if(rows.length>=MAX_COORDINATION_STATE_LIST_ROWS)throw Error(`delegation coordination read reached its ${MAX_COORDINATION_STATE_LIST_ROWS}-row safety bound`);for(let row of rows){let record3=retainedById.get(row.entityKey);if(!record3){if(!deleteCoordinationStateWithinTransaction(directory,DELEGATION_COORDINATION_NAMESPACE,row.entityKey,row.revision))throw Error(`coordination compaction delete lost a concurrent update for ${row.entityKey}`);continue}let current=RecordSchema2.safeParse(JSON.parse(row.payload));if(!current.success)throw Error(`delegation coordination row failed schema validation for ${row.entityKey}`);if(isDeepStrictEqual(current.data,record3))continue;if(getProjectDb(directory).run(`UPDATE coordination_state
|
|
@@ -1285,14 +1285,14 @@ ${warnings.map((w)=>`Detected signal: ${w}`).join(`
|
|
|
1285
1285
|
`))return{frontmatter:"",body:content};let end=content.indexOf(`
|
|
1286
1286
|
---
|
|
1287
1287
|
`,4);if(end===-1)return{frontmatter:"",body:content};return{frontmatter:content.slice(0,end+5),body:content.slice(end+5)}}function skillContractDigest(body){let normalized=body.replace(/\r\n/g,`
|
|
1288
|
-
`);return createHash58("sha256").update(normalized,"utf8").digest("hex").slice(0,12)}var init_skill_contract_digest=()=>{};import*as fs75 from"node:fs";import*as os16 from"node:os";import*as path118 from"node:path";import{fileURLToPath as fileURLToPath4}from"node:url";function nearestPackageRootFrom(startDir){let current=startDir;for(let depth=0;depth<8;depth+=1){if(fs75.existsSync(path118.join(current,"package.json")))return current;let parent=path118.dirname(current);if(parent===current)return;current=parent}return}function readBodyDigestOrNull(file3){let content;try{content=fs75.readFileSync(file3,"utf8")}catch{return}return skillContractDigest(splitSkillFrontmatter(content).body)}async function ensurePrWorkflowSkillContractsFresh(directory,mode,options={}){let advisories=[],emit2=(message)=>{advisories.push(message),advisoryWarn(message)};try{let slug=PR_WORKFLOW_MODE_SKILL[mode],packageRoot=_internals110.resolvePackageRoot(),canonicalPath=path118.join(packageRoot,".opencode","skills",slug,"SKILL.md"),canonicalDigest=readBodyDigestOrNull(canonicalPath);if(!canonicalDigest)return advisories;let installedPath=path118.join(directory,".swarm","bundled-skills",slug,"SKILL.md"),installedExisted=fs75.existsSync(installedPath),installedBefore=readBodyDigestOrNull(installedPath);if(!installedExisted){let materialized=!1;try{await withTimeout(_internals110.syncBundled(directory,packageRoot,!0),options.budgetMs??SKILL_CONTRACT_ACTIVATION_BUDGET_MS,Error(`skill-contract materialization exceeded its budget for ${slug}`))}catch{}if(materialized=readBodyDigestOrNull(installedPath)===canonicalDigest,!materialized)emit2(`bundled skill '${slug}' is missing and could not be materialized: ${installedPath} was not found; the bounded re-sync from the shipped canonical ${canonicalPath} did not restore it — re-run the /swarm pr-review or /swarm pr-feedback command, or restart the host`)}else if(installedBefore!==canonicalDigest){let healed=!1;try{await withTimeout(_internals110.syncBundled(directory,packageRoot,!0),options.budgetMs??SKILL_CONTRACT_ACTIVATION_BUDGET_MS,Error(`skill-contract re-sync exceeded its budget for ${slug}`))}catch{}healed=readBodyDigestOrNull(installedPath)===canonicalDigest,emit2(`stale skill contract detected at ${mode} activation for '${slug}': the installed copy ${installedPath} (digest ${installedBefore??"<missing>"}) does not match the shipped canonical ${canonicalPath} (digest ${canonicalDigest}) — `+(healed?"refreshed from the canonical source":"still stale after the bounded re-sync; repair by re-running the /swarm pr-review or /swarm pr-feedback command, or delete the stale .swarm/bundled-skills directory"))}let home=_internals110.resolveUserGlobalHome();for(let relativePath of[path118.join(".opencode","skills",slug,"SKILL.md"),path118.join(".claude","skills",slug,"SKILL.md")]){let userPath=path118.join(home,relativePath),userDigest=readBodyDigestOrNull(userPath);if(userDigest===void 0||userDigest===canonicalDigest)continue;emit2(`stale user-global copy of '${slug}' shadows the canonical skill: ${userPath} (digest ${userDigest}) differs from the repository copy ${canonicalPath} (digest ${canonicalDigest}) — delete the stale user-global copy`)}return advisories.slice(0,MAX_ADVISORIES)}catch(error93){let message=`skill-contract verification failed (fail-open): ${error93 instanceof Error?error93.message:String(error93)}`;return advisoryWarn(message),[message]}}var PR_WORKFLOW_MODE_SKILL,SKILL_CONTRACT_ACTIVATION_BUDGET_MS=2000,SKILL_CONTRACT_WAKE_BUDGET_MS=750,MAX_SKILL_CONTRACT_ADVISORIES=8,MAX_ADVISORIES,_internals110;var init_pr_workflow_skill_contract=__esm(()=>{init_bundled_skills();init_skill_contract_digest();init_timeout();init_warning_buffer();PR_WORKFLOW_MODE_SKILL={PR_REVIEW:"swarm-pr-review",PR_FEEDBACK:"swarm-pr-feedback"},MAX_ADVISORIES=MAX_SKILL_CONTRACT_ADVISORIES;_internals110={resolvePackageRoot:()=>{let moduleDir=path118.dirname(fileURLToPath4(import.meta.url));return nearestPackageRootFrom(moduleDir)??path118.resolve(moduleDir,"..","..")},resolveUserGlobalHome:()=>{if(process.platform==="win32"){let userProfile=process.env.USERPROFILE?.trim();if(userProfile)return userProfile}else{let home=process.env.HOME?.trim();if(home)return home}return os16.homedir()},syncBundled:(projectDirectory,packageRoot,quiet)=>syncBundledProjectSkillsIfMissingAsync(projectDirectory,packageRoot,quiet)}});function classifyLaneLivenessCondition(input){if(input.recordStatus==="error")return"completed_failure";let sessionLiveOrUnknown=input.sessionStatusType===void 0||input.sessionStatusType==="busy"||input.sessionStatusType==="retry";if(input.waitBudgetExpired&&sessionLiveOrUnknown)return"observer_deadline";if(input.sessionStatusType==="retry")return"provider_retry_in_flight";if(input.exceededEffectiveHorizon)return"execution_deadline";return"idle_failed_child"}function resolveEffectivePrLaneHorizonMs(watchdog,backgroundPendingTimeoutMs){let watchdogOwnsHorizon=watchdog?.enabled===!0&&(watchdog.timeout_ms??0)>0,horizonMs=watchdogOwnsHorizon?watchdog?.timeout_ms:DEFAULT_STALE_DELEGATION_TIMEOUT_MS;return{horizonMs,source:watchdogOwnsHorizon?"watchdog-timeout":"reachability-floor",conflictDisclosed:backgroundPendingTimeoutMs!==void 0&&backgroundPendingTimeoutMs>0&&backgroundPendingTimeoutMs!==horizonMs}}function laneLivenessWatchdogFeatures(watchdog){let enabled=watchdog?.enabled===!0;return{deadlineActive:enabled&&(watchdog?.timeout_ms??0)>0,stallActive:enabled&&(watchdog?.stall_threshold_ms??0)>0&&(watchdog?.stall_min_steps??0)>0&&(watchdog?.stall_token_threshold??0)>0}}var LANE_LIVENESS_WATCHDOG_DEFAULTS,MAX_LANE_LIVENESS_DISCLOSED_IDS=10,ZERO_LANE_ACTIVITY,defaultReadLaneActivity=()=>ZERO_LANE_ACTIVITY;var init_lane_liveness_watchdog=__esm(()=>{init_pending_delegations();init_schema();LANE_LIVENESS_WATCHDOG_DEFAULTS=LaneLivenessWatchdogConfigSchema.parse({});ZERO_LANE_ACTIVITY={stepsObserved:0,estimatedTokens:0}});var exports_pr_workflow_gate={};__export(exports_pr_workflow_gate,{writePrWorkflowAtomicJson:()=>writePrWorkflowAtomicJson,withPrWorkflowCheckoutPreparationLock:()=>withPrWorkflowCheckoutPreparationLock,withPrWorkflowCheckoutMutationLock:()=>withPrWorkflowCheckoutMutationLock,withInactivePrWorkflowCheckoutRestoreLock:()=>withInactivePrWorkflowCheckoutRestoreLock,validatePrWorkflowTransportRecovery:()=>validatePrWorkflowTransportRecovery,validatePrReviewDiscoveryLaneCompletion:()=>validatePrReviewDiscoveryLaneCompletion2,validatePrFeedbackScopeBinding:()=>validatePrFeedbackScopeBinding,validateExactStructuredReceiptCoverage:()=>validateExactStructuredReceiptCoverage2,transitionPrReviewToFeedback:()=>transitionPrReviewToFeedback,terminalizePrWorkflowGateForSession:()=>terminalizePrWorkflowGateForSession2,submitPrReviewResult:()=>submitPrReviewResult,settlePresumedStalePrWorkflowLanes:()=>settlePresumedStalePrWorkflowLanes,rollbackPrReviewPartialBaseCoverageAdmission:()=>rollbackPrReviewPartialBaseCoverageAdmission,rollbackPrReviewBaseAdmissionIfUnlaunched:()=>rollbackPrReviewBaseAdmissionIfUnlaunched,resolvePrReviewWriterRunId:()=>resolvePrReviewWriterRunId,resolvePrFeedbackScopeDeclaration:()=>resolvePrFeedbackScopeDeclaration,reserveActivePrReviewReentryAuthorization:()=>reserveActivePrReviewReentryAuthorization,recoverArmedPrWorkflow:()=>recoverArmedPrWorkflow,recordPrReviewValidationBatch:()=>recordPrReviewValidationBatch,recordPrReviewSubmitRejection:()=>recordPrReviewSubmitRejection,recordPrReviewMicroFamilyDispatch:()=>recordPrReviewMicroFamilyDispatch,recordPrFeedbackStageA:()=>recordPrFeedbackStageA,recordPrFeedbackPushAttemptResult:()=>recordPrFeedbackPushAttemptResult,recordPrFeedbackGateBatch:()=>recordPrFeedbackGateBatch,rebindPrFeedbackHead:()=>rebindPrFeedbackHead,readPrWorkflowGateStateForRecovery:()=>readPrWorkflowGateStateForRecovery,readPrWorkflowGateState:()=>readPrWorkflowGateState,readPrReviewVerdictSettlementReceiptItems:()=>readPrReviewVerdictSettlementReceiptItems,readPrReviewVerdictSettlementEffectiveIds:()=>readPrReviewVerdictSettlementEffectiveIds,readPrReviewTerminalCoverageForReport:()=>readPrReviewTerminalCoverageForReport,readPrReviewReentryBindingContext:()=>readPrReviewReentryBindingContext,readPrReviewFinalFindingPolicyForReport:()=>readPrReviewFinalFindingPolicyForReport,readAuthoritativePrReviewCriticVerdicts:()=>readAuthoritativePrReviewCriticVerdicts,readAuthoritativePrReviewCriticSettlements:()=>readAuthoritativePrReviewCriticSettlements,prWorkflowSessionFileStem:()=>prWorkflowSessionFileStem,prReviewDiscoveryArtifactCoversLane:()=>prReviewDiscoveryArtifactCoversLane,normalizePrWorkflowShellCommand:()=>normalizePrWorkflowShellCommand,normalizePrReviewPartialBaseCoverageRecord:()=>normalizePrReviewPartialBaseCoverageRecord,markPrReviewTriggerEvaluationComplete:()=>markPrReviewTriggerEvaluationComplete,markPrReviewHandoffComplete:()=>markPrReviewHandoffComplete,markPrReviewArtifactBoundary:()=>markPrReviewArtifactBoundary,latestPrReviewSubmitRejectionMessage:()=>latestPrReviewSubmitRejectionMessage,invalidatePrFeedbackPublication:()=>invalidatePrFeedbackPublication,hasActivePrReviewReentryAuthorization:()=>hasActivePrReviewReentryAuthorization,formatPrReviewLaneValidationFailure:()=>formatPrReviewLaneValidationFailure,findDanglingLivePublicationGeneration:()=>findDanglingLivePublicationGeneration,ensurePrWorkflowSafeParentDirectory:()=>ensurePrWorkflowSafeParentDirectory,enforcePrWorkflowToolBefore:()=>enforcePrWorkflowToolBefore,enforcePrWorkflowDispatchLanesAsync:()=>enforcePrWorkflowDispatchLanesAsync,enforcePrReviewBaseDimensions:()=>enforcePrReviewBaseDimensions,enforcePrFeedbackVerificationOwnership:()=>enforcePrFeedbackVerificationOwnership,describePrWorkflowRevisionDigestFailure:()=>describePrWorkflowRevisionDigestFailure,describePrWorkflowPublicationSection:()=>describePrWorkflowPublicationSection,declarePrFeedbackScope:()=>declarePrFeedbackScope,declarePrFeedbackInventory:()=>declarePrFeedbackInventory,consumePrFeedbackScopeDeclaration:()=>consumePrFeedbackScopeDeclaration,computePrReviewDepthTier:()=>computePrReviewDepthTier,completePrWorkflow:()=>completePrWorkflow,collectPrWorkflowPendingLaneLiveness:()=>collectPrWorkflowPendingLaneLiveness,clearPrWorkflowGateState:()=>clearPrWorkflowGateState,cancelPrFeedbackPublication:()=>cancelPrFeedbackPublication,bindPrWorkflowHead:()=>bindPrWorkflowHead,bindPrReviewTriggerLedger:()=>bindPrReviewTriggerLedger,bindPrReviewBase:()=>bindPrReviewBase,assertPrReviewValidationSettled:()=>assertPrReviewValidationSettled,assertPrReviewCleanCheckout:()=>assertPrReviewCleanCheckout,assertPrReviewBaseCoverageSettled:()=>assertPrReviewBaseCoverageSettled2,assertPrReviewArtifactRecordsMatchAuthoritativeVerdicts:()=>assertPrReviewArtifactRecordsMatchAuthoritativeVerdicts,assertPrReviewArtifactBoundary:()=>assertPrReviewArtifactBoundary,assertPrFeedbackVerificationSettled:()=>assertPrFeedbackVerificationSettled,assertPrFeedbackReadyToPublish:()=>assertPrFeedbackReadyToPublish,assertPrFeedbackGatePhaseSettled:()=>assertPrFeedbackGatePhaseSettled,assertCurrentCheckoutHead:()=>assertCurrentCheckoutHead,appendPrWorkflowSkillContractAdvisories:()=>appendPrWorkflowSkillContractAdvisories,allowedPrReviewReportVerdicts:()=>allowedPrReviewReportVerdicts,admitPrReviewPartialBaseCoverage:()=>admitPrReviewPartialBaseCoverage2,activatePrWorkflow:()=>activatePrWorkflow,abortPrWorkflow:()=>abortPrWorkflow,_test_exports:()=>_test_exports2,PrWorkflowCheckoutMutationTimeoutError:()=>PrWorkflowCheckoutMutationTimeoutError,PrReviewResilienceRetryExhaustedError:()=>PrReviewResilienceRetryExhaustedError,PrReviewResilienceCircuitOpenError:()=>PrReviewResilienceCircuitOpenError,PR_WORKFLOW_PROBE_SKIPPED_NO_BUDGET_REASON:()=>PR_WORKFLOW_PROBE_SKIPPED_NO_BUDGET_REASON,PR_REVIEW_TIER_L_CONSOLIDATED_LANE_FLOOR:()=>PR_REVIEW_TIER_L_CONSOLIDATED_LANE_FLOOR,PR_REVIEW_REQUIRED_MICRO_LANE_IDS:()=>PR_REVIEW_REQUIRED_MICRO_LANE_IDS,PR_REVIEW_REPORT_VERDICTS:()=>PR_REVIEW_REPORT_VERDICTS,PR_REVIEW_MICRO_LANE_FLOORS:()=>PR_REVIEW_MICRO_LANE_FLOORS,PR_REVIEW_DEPTH_TIER_THRESHOLDS:()=>PR_REVIEW_DEPTH_TIER_THRESHOLDS,PR_REVIEW_BASE_LANE_FLOORS:()=>PR_REVIEW_BASE_LANE_FLOORS,PR_REVIEW_BASE_DIMENSION_IDS:()=>PR_REVIEW_BASE_DIMENSION_IDS,MAX_SALVAGED_SCHEMA_ERROR_CHARS:()=>MAX_SALVAGED_SCHEMA_ERROR_CHARS,MAX_PR_REVIEW_SUBMIT_REJECTIONS:()=>MAX_PR_REVIEW_SUBMIT_REJECTIONS,MAX_PR_FEEDBACK_INVENTORY_AMENDMENTS:()=>MAX_PR_FEEDBACK_INVENTORY_AMENDMENTS});import{createHash as createHash59,randomUUID as randomUUID17}from"node:crypto";import*as fsp8 from"node:fs/promises";import*as path119 from"node:path";function readPrWorkflowGateStateFromDisk3(directory,sessionID){return readPrWorkflowGateStateFromDisk(directory,sessionID)}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(state2){let evidence2=JSON.stringify({operations:state2.evidence.operations,unmerged_codes:state2.evidence.unmergedCodes,paths:state2.evidence.paths,paths_truncated:state2.evidence.pathsTruncated});return`BLOCKED: PR workflow checkout requires manual Git recovery before activation. code=${state2.code} retryable=false required_action=${state2.requiredAction} evidence=${evidence2}`}function checkoutRecoveryRecord(state2){if(state2.kind!=="recovery-required"&&state2.kind!=="indeterminate")throw Error("PR workflow checkout recovery requires a terminal Git state");return{code:state2.code,retryable:!1,requiredAction:state2.requiredAction,evidence:state2.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 readPrWorkflowGateStateFromDisk3(directory,normalizedSessionID);if(existing?.mode===mode){if(mode==="PR_FEEDBACK"&&options.prUrl){let requestedTarget=canonicalGitHubPrUrl(options.prUrl,options.forge);if(!requestedTarget)throw Error("BLOCKED: PR_FEEDBACK target must be a canonical GitHub PR URL");let existingTarget=existing.prFeedbackTargetUrl?canonicalGitHubPrUrl(existing.prFeedbackTargetUrl,options.forge):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:[path119.join(".swarm",workflowCheckoutMutationLockRelativePath()),path119.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,skillContractAdvisories=await ensurePrWorkflowSkillContractsFresh(directory,mode),ghReadinessAdvisory=collectPrWorkflowGhReadinessAdvisory(_test_exports2.resolveGhBinary),activationAdvisories=ghReadinessAdvisory?[ghReadinessAdvisory,...skillContractAdvisories]:skillContractAdvisories,timestamp=isoNow(),feedbackTargetUrl=mode==="PR_FEEDBACK"&&options.prUrl?canonicalGitHubPrUrl(options.prUrl,options.forge)?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:randomUUID17(),sessionID:normalizedSessionID,mode,activatedAt:timestamp,updatedAt:timestamp,...activationAdvisories.length>0?{skillContractAdvisories:activationAdvisories}:{},...initialHead?{prHeadSha:initialHead}:{},...feedbackTargetUrl?{prFeedbackTargetUrl:feedbackTargetUrl}:{}};return writeStateWhileLocked(directory,nextState)}))}async function appendPrWorkflowSkillContractAdvisories(directory,sessionID,advisories){if(advisories.length===0)return;let normalizedSessionID=normalizeSessionID(sessionID);if(!normalizedSessionID)return;await withSessionStateMutation(directory,normalizedSessionID,async()=>{try{let existing=await readPrWorkflowGateStateFromDisk3(directory,normalizedSessionID);if(!existing)return;let current=existing.skillContractAdvisories??[],merged=[...current];for(let advisory of advisories){if(merged.length>=MAX_SKILL_CONTRACT_ADVISORIES)break;if(!merged.includes(advisory))merged.push(advisory)}if(merged.length===current.length)return;await writeStateWhileLocked(directory,{...existing,skillContractAdvisories:merged,updatedAt:isoNow()})}catch{}})}async function readPrWorkflowGateState(directory,sessionID){let normalizedSessionID=normalizeSessionID(sessionID),state2=await readPrWorkflowGateStateFromDisk3(directory,normalizedSessionID);if(state2)rememberState(directory,state2);else forgetTrackedPrWorkflowState(directory,normalizedSessionID);return state2}function isLivenessTerminalLaneRecord2(record3){if(record3.status!=="cancelled"&&record3.status!=="stale"&&record3.status!=="error")return!1;return record3.terminalResult?.result.workflowLaneFailureClass==="liveness"||record3.result?.workflowLaneFailureClass==="liveness"}async function recordPrReviewSubmitRejection(directory,childSessionId,message){try{let child=childSessionId.trim();if(!child)return;let childRead=readDelegationsDetailed(directory);if(childRead.status==="uncertain")return;let record3=childRead.records.find((candidate)=>candidate.subagentSessionId===child&&(candidate.mode==="swarm-pr-review:base"||candidate.mode==="swarm-pr-review:micro")),parentSessionId=record3?.parentSessionId?.trim();if(!parentSessionId)return;let existing=await readPrWorkflowGateStateFromDisk3(directory,parentSessionId);if(!existing||existing.mode!=="PR_REVIEW")return;let laneId=record3?.laneId?.trim(),bounded=redactSecrets(message.replace(PUBLICATION_URL_CREDENTIALS_PATTERN,"$1[REDACTED:url_credentials]@")).slice(0,300);await withSessionStateMutation(directory,parentSessionId,async()=>{let locked=await readPrWorkflowGateStateFromDisk3(directory,parentSessionId);if(!locked||locked.mode!=="PR_REVIEW")return;let prior=locked.prReviewSubmitRejections??[];if(prior.filter((entry)=>entry.childSessionId===child).at(-1)?.message===bounded)return;let journal=[...prior,{childSessionId:child,...laneId?{laneId}:{},at:Date.now(),message:bounded}].slice(-MAX_PR_REVIEW_SUBMIT_REJECTIONS);await writeStateWhileLocked(directory,{...locked,prReviewSubmitRejections:journal,updatedAt:isoNow()})})}catch{}}function latestPrReviewSubmitRejectionMessage(state2,childSessionId){let journal=state2.prReviewSubmitRejections;if(!journal?.length)return;for(let index=journal.length-1;index>=0;index--)if(journal[index]?.childSessionId===childSessionId)return journal[index]?.message;return}async function submitPrReviewResultCore(directory,childSessionId,input){let child=childSessionId.trim(),parsedResult=PrReviewLaneResultEnvelopeSchema.safeParse(input.result);if(!child||!parsedResult.success)return{status:"rejected",reason:"invalid child session or result envelope"};let childRead=readDelegationsDetailed(directory);if(childRead.status==="uncertain")return{status:"rejected",reason:`delegation store unreadable after ${childRead.attempts} attempts; child lookup uncertain (${childRead.reason})`};let preliminary=childRead.records.filter((record4)=>record4.subagentSessionId===child&&record4.correlationId===child&&(record4.mode==="swarm-pr-review:base"||record4.mode==="swarm-pr-review:micro")),repairRecord=null;if(preliminary.length!==1){let repairCandidates=childRead.records.filter((candidate)=>candidate.parentSessionId===child&&(candidate.mode==="swarm-pr-review:base"||candidate.mode==="swarm-pr-review:micro")&&(input.batchId===void 0||input.batchId===candidate.batchId)&&(input.laneId===void 0||input.laneId===candidate.laneId)&&isLivenessTerminalLaneRecord2(candidate));if(repairCandidates.length!==1)return{status:"rejected",reason:`expected one exact child delegation, found ${preliminary.length}`};if(repairRecord=repairCandidates[0],parsedResult.data.outcome!=="INCOMPLETE")return{status:"rejected",reason:"architect-parent repair may only record an unresolved-terminal (INCOMPLETE) outcome"}}let parentSessionId=(repairRecord??preliminary[0]).parentSessionId,record3=repairRecord??preliminary[0],childOfRecord=record3.subagentSessionId;if(!record3.batchId||!record3.laneId)return{status:"rejected",reason:"delegation batch/lane provenance is missing"};if(input.batchId!==void 0&&input.batchId!==record3.batchId||input.laneId!==void 0&&input.laneId!==record3.laneId)return{status:"rejected",reason:"delegation batch/lane identity mismatch"};let{batchId,laneId}=record3;return withSessionStateMutation(directory,parentSessionId,async()=>{let state2=await readPrWorkflowGateStateFromDisk3(directory,parentSessionId);if(!state2||state2.mode!=="PR_REVIEW"||!state2.workflowInstanceId||!state2.prHeadSha||!state2.prReviewBaseSha)return{status:"rejected",reason:"no active bound PR_REVIEW workflow"};if((await createPrReviewGateContext2(directory,state2)).revisionDigest!==input.revisionDigest)return{status:"rejected",reason:"stale dispatch revision digest"};let dispatchWorkflowInstanceId=decodePrReviewWorkflowBinding(record3.jobId),dispatchWorkflowRevision=record3.workflowGeneration;if(!dispatchWorkflowInstanceId||dispatchWorkflowRevision===void 0)return{status:"rejected",reason:"delegation workflow binding provenance is missing"};if(dispatchWorkflowInstanceId!==state2.workflowInstanceId)return{status:"rejected",reason:"stale workflow instance binding"};if(repairRecord&&dispatchWorkflowRevision!==state2.revision)return{status:"rejected",reason:`superseded workflow generation binding (delegation generation ${dispatchWorkflowRevision}, active generation ${state2.revision})`};if(record3.mode!=="swarm-pr-review:base"&&record3.mode!=="swarm-pr-review:micro"||!sameProjectRoot(record3.workspace?.directory??"",directory))return{status:"rejected",reason:"delegation mode or workspace mismatch"};let ownedWorkflowLanes=record3.ownedWorkflowLanes?.length?record3.ownedWorkflowLanes:record3.workflowLane?[record3.workflowLane]:[];if(!record3.workflowLane||ownedWorkflowLanes.length===0)return{status:"rejected",reason:"delegation ownership is missing"};let semanticEnvelopeDigest=prReviewLaneResultEnvelopeDigest(parsedResult.data),existingReceiptDigest=record3.result?.prReviewResultReceipt?.semanticEnvelopeDigest,submission=reducePrReviewEvent(state2,{type:"lane_structured_result_submitted",batchId,laneId,generation:state2.revision,semanticEnvelopeDigest,outcome:parsedResult.data.outcome,...existingReceiptDigest!==void 0?{existingReceiptDigest}:{},...repairRecord?{submittedBy:"workflow_parent"}:{}});if(submission.status==="rejected")return{status:"rejected",reason:submission.rejection.code==="duplicate_conflicting_result"?"a different bound receipt is already recorded":`structured result submission rejected: ${submission.rejection.code}`};let published=await publishPrReviewResultReceipt(directory,{parentSessionId,childSessionId:childOfRecord,batchId,laneId,expectedWorkflowInstanceId:state2.workflowInstanceId,expectedWorkflowRevision:dispatchWorkflowRevision,expectedBaseSha:state2.prReviewBaseSha,...repairRecord?{parentRepair:!0}:{},receipt:{schemaVersion:1,mode:record3.mode,workflowInstanceId:dispatchWorkflowInstanceId,workflowRevision:dispatchWorkflowRevision,batchId,laneId,workflowLane:record3.workflowLane,ownedWorkflowLanes,baseSha:state2.prReviewBaseSha,headSha:state2.prHeadSha,dispatchRevisionDigest:input.revisionDigest,childSessionId:childOfRecord,generation:record3.generation??1,semanticEnvelopeDigest,envelope:parsedResult.data,...repairRecord?{submittedBy:"workflow_parent",submittedByParentSessionId:parentSessionId,laneTerminalStateAtSubmission:record3.status}:{}}});if(published.status==="recorded"||published.status==="duplicate")return{status:published.status,receiptDigest:semanticEnvelopeDigest};return{status:"rejected",reason:published.reason}})}async function submitPrReviewResult(directory,childSessionId,input){let outcome=await submitPrReviewResultCore(directory,childSessionId,input);if(outcome.status==="rejected")await recordPrReviewSubmitRejection(directory,childSessionId,outcome.reason);return outcome}async function withPrWorkflowCheckoutPreparationLock(directory,sessionID,action2){let normalizedSessionID=normalizeSessionID(sessionID);return withPrWorkflowCheckoutMutationLock(directory,async()=>withSessionStateMutation(directory,normalizedSessionID,async()=>{let state2=await readPrWorkflowGateStateFromDisk3(directory,normalizedSessionID);if(!state2)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(state2.prHeadSha)throw Error(`BLOCKED: ${state2.mode} checkout preparation is allowed only before the PR head is bound`);return action2(state2,{markRecoveryRequired:async(gitState)=>{let nextState={...state2,updatedAt:isoNow(),checkoutRecovery:checkoutRecoveryRecord(gitState)},persisted=await writeStateWhileLocked(directory,nextState);return Object.assign(state2,persisted),persisted}})}))}async function withInactivePrWorkflowCheckoutRestoreLock(directory,sessionID,action2){let normalizedSessionID=normalizeSessionID(sessionID);return withPrWorkflowCheckoutMutationLock(directory,async()=>withSessionStateMutation(directory,normalizedSessionID,async()=>{if(await readPrWorkflowGateStateFromDisk3(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),action2()}))}async function assertNoActivePrWorkflowGateForCheckoutRestore(directory){let gateDirectory=validateSwarmPath(directory,WORKFLOW_GATE_DIR),handle;try{handle=await fsp8.opendir(gateDirectory)}catch(error93){if(error93.code==="ENOENT")return;throw error93}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 statePath2=validateSwarmPath(directory,path119.join(WORKFLOW_GATE_DIR,entry.name)),state2=await readPrWorkflowGateStateFileFromDisk(statePath2,entry.name);if(!state2)continue;let expectedName=path119.basename(workflowGateStateRelativePath(state2.sessionID));if(entry.name!==expectedName)throw Error("BLOCKED: PR workflow gate inventory contains an ambiguous state filename; checkout restoration cannot prove project inactivity");let boundedEntryName=entry.name.length<=MAX_PR_WORKFLOW_GATE_ENTRY_NAME_CHARS?entry.name:`${entry.name.slice(0,MAX_PR_WORKFLOW_GATE_ENTRY_NAME_CHARS-1)}…`;throw Error(`BLOCKED: checkout restoration cannot mutate this project while session "${state2.sessionID}" has an active ${state2.mode} workflow (state entry "${boundedEntryName}"). For the owning session, run \`/swarm abort-pr-workflow ${state2.mode} <reason...>\` to recover the stuck gate.`)}}catch(error93){scanError=error93}finally{try{await handle.close()}catch(error93){if(error93.code!=="ERR_DIR_CLOSED")closeError=error93}}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 readPrWorkflowGateStateFromDisk3(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")}await deleteStateWhileLocked(directory,normalizedSessionID,{expectedStateRevision:expectedRevision,allowSalvagedRead:options.allowSalvagedRead})})}async function terminalizePrWorkflowGateForSession2(directory,sessionID){return terminalizePrWorkflowGateForSession(directory,sessionID)}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(error93){return{statuses:new Map,degradedReason:error93===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 record3 of records){let subagentSessionId=record3.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=(record3,reason)=>({laneId:record3.laneId??record3.correlationId,pendingMs:Math.max(0,now-record3.updatedAt),hostStatus:"unknown",stalledSuspect:!0,degradedReason:reason});try{now=_test_exports2.nowMs();let threshold=_test_exports2.pendingLaneLivenessThresholdMs;if(pastThreshold=records.filter((record3)=>(record3.status==="pending"||record3.status==="running"||record3.status==="ingesting")&&now-record3.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((record3)=>degraded(record3,PR_WORKFLOW_PROBE_SKIPPED_NO_BUDGET_REASON));let probe2=await probePrWorkflowLaneSessionStatusTypes(directory,pastThreshold,budgetMs),advisories=[];for(let record3 of pastThreshold){let pendingMs=now-record3.updatedAt,laneId=record3.laneId??record3.correlationId;if(probe2.degradedReason){advisories.push({laneId,pendingMs,hostStatus:"unknown",stalledSuspect:!0,degradedReason:probe2.degradedReason});continue}let subagentSessionId=record3.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((record3)=>degraded(record3,"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(record3){return record3.laneId??record3.subagentSessionId??"unknown"}function isOpenPrWorkflowLane(record3,sessionID){return record3.parentSessionId===sessionID&&record3.mode?.startsWith("swarm-pr-")===!0&&(record3.status==="pending"||record3.status==="running")}async function abortLaneSessionForWatchdog(record3){let session=_test_exports2.getSessionOps(),abortOp=session?.abort;if(!session||typeof abortOp!=="function"||!record3.subagentSessionId)return!1;try{return await withTimeout(abortOp.call(session,{path:{id:record3.subagentSessionId}}),_test_exports2.laneLivenessProbeTimeoutMs,Error("lane-liveness watchdog abort exceeded its deadline")),!0}catch{return!1}}function lastWatchdogEscalationsByLaneLabel(directory,sessionID){let escalations=new Map,activityObservations=new Map,deadlineLabels=new Set,text="";try{text=readCoreEvents(directory).text}catch{return{escalations,activityObservations,deadlineLabels}}for(let line of text.split(`
|
|
1288
|
+
`);return createHash58("sha256").update(normalized,"utf8").digest("hex").slice(0,12)}var init_skill_contract_digest=()=>{};import*as fs75 from"node:fs";import*as os16 from"node:os";import*as path118 from"node:path";import{fileURLToPath as fileURLToPath4}from"node:url";function nearestPackageRootFrom(startDir){let current=startDir;for(let depth=0;depth<8;depth+=1){if(fs75.existsSync(path118.join(current,"package.json")))return current;let parent=path118.dirname(current);if(parent===current)return;current=parent}return}function readBodyDigestOrNull(file3){let content;try{content=fs75.readFileSync(file3,"utf8")}catch{return}return skillContractDigest(splitSkillFrontmatter(content).body)}async function ensurePrWorkflowSkillContractsFresh(directory,mode,options={}){let advisories=[],emit2=(message)=>{advisories.push(message),advisoryWarn(message)};try{let slug=PR_WORKFLOW_MODE_SKILL[mode],packageRoot=_internals110.resolvePackageRoot(),canonicalPath=path118.join(packageRoot,".opencode","skills",slug,"SKILL.md"),canonicalDigest=readBodyDigestOrNull(canonicalPath);if(!canonicalDigest)return advisories;let installedPath=path118.join(directory,".swarm","bundled-skills",slug,"SKILL.md"),installedExisted=fs75.existsSync(installedPath),installedBefore=readBodyDigestOrNull(installedPath);if(!installedExisted){let materialized=!1;try{await withTimeout(_internals110.syncBundled(directory,packageRoot,!0),options.budgetMs??SKILL_CONTRACT_ACTIVATION_BUDGET_MS,Error(`skill-contract materialization exceeded its budget for ${slug}`))}catch{}if(materialized=readBodyDigestOrNull(installedPath)===canonicalDigest,!materialized)emit2(`bundled skill '${slug}' is missing and could not be materialized: ${installedPath} was not found; the bounded re-sync from the shipped canonical ${canonicalPath} did not restore it — re-run the /swarm pr-review or /swarm pr-feedback command, or restart the host`)}else if(installedBefore!==canonicalDigest){let healed=!1;try{await withTimeout(_internals110.syncBundled(directory,packageRoot,!0),options.budgetMs??SKILL_CONTRACT_ACTIVATION_BUDGET_MS,Error(`skill-contract re-sync exceeded its budget for ${slug}`))}catch{}healed=readBodyDigestOrNull(installedPath)===canonicalDigest,emit2(`stale skill contract detected at ${mode} activation for '${slug}': the installed copy ${installedPath} (digest ${installedBefore??"<missing>"}) does not match the shipped canonical ${canonicalPath} (digest ${canonicalDigest}) — `+(healed?"refreshed from the canonical source":"still stale after the bounded re-sync; repair by re-running the /swarm pr-review or /swarm pr-feedback command, or delete the stale .swarm/bundled-skills directory"))}let home=_internals110.resolveUserGlobalHome();for(let relativePath of[path118.join(".opencode","skills",slug,"SKILL.md"),path118.join(".claude","skills",slug,"SKILL.md")]){let userPath=path118.join(home,relativePath),userDigest=readBodyDigestOrNull(userPath);if(userDigest===void 0||userDigest===canonicalDigest)continue;emit2(`stale user-global copy of '${slug}' shadows the canonical skill: ${userPath} (digest ${userDigest}) differs from the repository copy ${canonicalPath} (digest ${canonicalDigest}) — delete the stale user-global copy`)}return advisories.slice(0,MAX_ADVISORIES)}catch(error93){let message=`skill-contract verification failed (fail-open): ${error93 instanceof Error?error93.message:String(error93)}`;return advisoryWarn(message),[message]}}var PR_WORKFLOW_MODE_SKILL,SKILL_CONTRACT_ACTIVATION_BUDGET_MS=2000,SKILL_CONTRACT_WAKE_BUDGET_MS=750,MAX_SKILL_CONTRACT_ADVISORIES=8,MAX_ADVISORIES,_internals110;var init_pr_workflow_skill_contract=__esm(()=>{init_bundled_skills();init_skill_contract_digest();init_timeout();init_warning_buffer();PR_WORKFLOW_MODE_SKILL={PR_REVIEW:"swarm-pr-review",PR_FEEDBACK:"swarm-pr-feedback"},MAX_ADVISORIES=MAX_SKILL_CONTRACT_ADVISORIES;_internals110={resolvePackageRoot:()=>{let moduleDir=path118.dirname(fileURLToPath4(import.meta.url));return nearestPackageRootFrom(moduleDir)??path118.resolve(moduleDir,"..","..")},resolveUserGlobalHome:()=>{if(process.platform==="win32"){let userProfile=process.env.USERPROFILE?.trim();if(userProfile)return userProfile}else{let home=process.env.HOME?.trim();if(home)return home}return os16.homedir()},syncBundled:(projectDirectory,packageRoot,quiet)=>syncBundledProjectSkillsIfMissingAsync(projectDirectory,packageRoot,quiet)}});function classifyLaneLivenessCondition(input){if(input.recordStatus==="error")return"completed_failure";let sessionLiveOrUnknown=input.sessionStatusType===void 0||input.sessionStatusType==="busy"||input.sessionStatusType==="retry";if(input.waitBudgetExpired&&sessionLiveOrUnknown)return"observer_deadline";if(input.sessionStatusType==="retry")return"provider_retry_in_flight";if(input.exceededEffectiveHorizon)return"execution_deadline";return"idle_failed_child"}function resolveEffectivePrLaneHorizonMs(watchdog,backgroundPendingTimeoutMs){let watchdogOwnsHorizon=watchdog?.enabled===!0&&(watchdog.timeout_ms??0)>0,horizonMs=watchdogOwnsHorizon?watchdog?.timeout_ms:DEFAULT_STALE_DELEGATION_TIMEOUT_MS;return{horizonMs,source:watchdogOwnsHorizon?"watchdog-timeout":"reachability-floor",conflictDisclosed:backgroundPendingTimeoutMs!==void 0&&backgroundPendingTimeoutMs>0&&backgroundPendingTimeoutMs!==horizonMs}}function laneLivenessWatchdogFeatures(watchdog){let enabled=watchdog?.enabled===!0;return{deadlineActive:enabled&&(watchdog?.timeout_ms??0)>0,stallActive:enabled&&(watchdog?.stall_threshold_ms??0)>0&&(watchdog?.stall_min_steps??0)>0&&(watchdog?.stall_token_threshold??0)>0}}var LANE_LIVENESS_WATCHDOG_DEFAULTS,MAX_LANE_LIVENESS_DISCLOSED_IDS=10,ZERO_LANE_ACTIVITY,defaultReadLaneActivity=()=>ZERO_LANE_ACTIVITY;var init_lane_liveness_watchdog=__esm(()=>{init_pending_delegations();init_schema();LANE_LIVENESS_WATCHDOG_DEFAULTS=LaneLivenessWatchdogConfigSchema.parse({});ZERO_LANE_ACTIVITY={stepsObserved:0,estimatedTokens:0}});var exports_pr_workflow_gate={};__export(exports_pr_workflow_gate,{writePrWorkflowAtomicJson:()=>writePrWorkflowAtomicJson,withPrWorkflowCheckoutPreparationLock:()=>withPrWorkflowCheckoutPreparationLock,withPrWorkflowCheckoutMutationLock:()=>withPrWorkflowCheckoutMutationLock,withInactivePrWorkflowCheckoutRestoreLock:()=>withInactivePrWorkflowCheckoutRestoreLock,validatePrWorkflowTransportRecovery:()=>validatePrWorkflowTransportRecovery,validatePrReviewDiscoveryLaneCompletion:()=>validatePrReviewDiscoveryLaneCompletion2,validatePrFeedbackScopeBinding:()=>validatePrFeedbackScopeBinding,validateExactStructuredReceiptCoverage:()=>validateExactStructuredReceiptCoverage2,transitionPrReviewToFeedback:()=>transitionPrReviewToFeedback,terminalizePrWorkflowGateForSession:()=>terminalizePrWorkflowGateForSession2,submitPrReviewResult:()=>submitPrReviewResult,settlePresumedStalePrWorkflowLanes:()=>settlePresumedStalePrWorkflowLanes,rollbackPrReviewPartialBaseCoverageAdmission:()=>rollbackPrReviewPartialBaseCoverageAdmission,rollbackPrReviewBaseAdmissionIfUnlaunched:()=>rollbackPrReviewBaseAdmissionIfUnlaunched,resolvePrReviewWriterRunId:()=>resolvePrReviewWriterRunId,resolvePrFeedbackScopeDeclaration:()=>resolvePrFeedbackScopeDeclaration,reserveActivePrReviewReentryAuthorization:()=>reserveActivePrReviewReentryAuthorization,recoverArmedPrWorkflow:()=>recoverArmedPrWorkflow,recordPrReviewValidationBatch:()=>recordPrReviewValidationBatch,recordPrReviewSubmitRejection:()=>recordPrReviewSubmitRejection,recordPrReviewMicroFamilyDispatch:()=>recordPrReviewMicroFamilyDispatch,recordPrFeedbackStageA:()=>recordPrFeedbackStageA,recordPrFeedbackPushAttemptResult:()=>recordPrFeedbackPushAttemptResult,recordPrFeedbackGateBatch:()=>recordPrFeedbackGateBatch,rebindPrFeedbackHead:()=>rebindPrFeedbackHead,readPrWorkflowGateStateForRecovery:()=>readPrWorkflowGateStateForRecovery,readPrWorkflowGateState:()=>readPrWorkflowGateState,readPrReviewVerdictSettlementReceiptItems:()=>readPrReviewVerdictSettlementReceiptItems,readPrReviewVerdictSettlementEffectiveIds:()=>readPrReviewVerdictSettlementEffectiveIds,readPrReviewTerminalCoverageForReport:()=>readPrReviewTerminalCoverageForReport,readPrReviewReentryBindingContext:()=>readPrReviewReentryBindingContext,readPrReviewFinalFindingPolicyForReport:()=>readPrReviewFinalFindingPolicyForReport,readAuthoritativePrReviewCriticVerdicts:()=>readAuthoritativePrReviewCriticVerdicts,readAuthoritativePrReviewCriticSettlements:()=>readAuthoritativePrReviewCriticSettlements,prWorkflowSessionFileStem:()=>prWorkflowSessionFileStem,prReviewDiscoveryArtifactCoversLane:()=>prReviewDiscoveryArtifactCoversLane,normalizePrWorkflowShellCommand:()=>normalizePrWorkflowShellCommand,normalizePrReviewPartialBaseCoverageRecord:()=>normalizePrReviewPartialBaseCoverageRecord,markPrReviewTriggerEvaluationComplete:()=>markPrReviewTriggerEvaluationComplete,markPrReviewHandoffComplete:()=>markPrReviewHandoffComplete,markPrReviewArtifactBoundary:()=>markPrReviewArtifactBoundary,latestPrReviewSubmitRejectionMessage:()=>latestPrReviewSubmitRejectionMessage,invalidatePrFeedbackPublication:()=>invalidatePrFeedbackPublication,hasActivePrReviewReentryAuthorization:()=>hasActivePrReviewReentryAuthorization,formatPrReviewLaneValidationFailure:()=>formatPrReviewLaneValidationFailure,findDanglingLivePublicationGeneration:()=>findDanglingLivePublicationGeneration,ensurePrWorkflowSafeParentDirectory:()=>ensurePrWorkflowSafeParentDirectory,enforcePrWorkflowToolBefore:()=>enforcePrWorkflowToolBefore,enforcePrWorkflowDispatchLanesAsync:()=>enforcePrWorkflowDispatchLanesAsync,enforcePrReviewBaseDimensions:()=>enforcePrReviewBaseDimensions,enforcePrFeedbackVerificationOwnership:()=>enforcePrFeedbackVerificationOwnership,describePrWorkflowRevisionDigestFailure:()=>describePrWorkflowRevisionDigestFailure,describePrWorkflowPublicationSection:()=>describePrWorkflowPublicationSection,derivePrReviewCandidateInventoryForStatus:()=>derivePrReviewCandidateInventoryForStatus,declarePrFeedbackScope:()=>declarePrFeedbackScope,declarePrFeedbackInventory:()=>declarePrFeedbackInventory,consumePrFeedbackScopeDeclaration:()=>consumePrFeedbackScopeDeclaration,computePrReviewDepthTier:()=>computePrReviewDepthTier,completePrWorkflow:()=>completePrWorkflow,collectPrWorkflowPendingLaneLiveness:()=>collectPrWorkflowPendingLaneLiveness,clearPrWorkflowGateState:()=>clearPrWorkflowGateState,cancelPrFeedbackPublication:()=>cancelPrFeedbackPublication,bindPrWorkflowHead:()=>bindPrWorkflowHead,bindPrReviewTriggerLedger:()=>bindPrReviewTriggerLedger,bindPrReviewBase:()=>bindPrReviewBase,assertPrReviewValidationSettled:()=>assertPrReviewValidationSettled,assertPrReviewCleanCheckout:()=>assertPrReviewCleanCheckout,assertPrReviewBaseCoverageSettled:()=>assertPrReviewBaseCoverageSettled2,assertPrReviewArtifactRecordsMatchAuthoritativeVerdicts:()=>assertPrReviewArtifactRecordsMatchAuthoritativeVerdicts,assertPrReviewArtifactBoundary:()=>assertPrReviewArtifactBoundary,assertPrFeedbackVerificationSettled:()=>assertPrFeedbackVerificationSettled,assertPrFeedbackReadyToPublish:()=>assertPrFeedbackReadyToPublish,assertPrFeedbackGatePhaseSettled:()=>assertPrFeedbackGatePhaseSettled,assertCurrentCheckoutHead:()=>assertCurrentCheckoutHead,appendPrWorkflowSkillContractAdvisories:()=>appendPrWorkflowSkillContractAdvisories,allowedPrReviewReportVerdicts:()=>allowedPrReviewReportVerdicts,admitPrReviewPartialBaseCoverage:()=>admitPrReviewPartialBaseCoverage2,activatePrWorkflow:()=>activatePrWorkflow,abortPrWorkflow:()=>abortPrWorkflow,_test_exports:()=>_test_exports2,PrWorkflowCheckoutMutationTimeoutError:()=>PrWorkflowCheckoutMutationTimeoutError,PrReviewResilienceRetryExhaustedError:()=>PrReviewResilienceRetryExhaustedError,PrReviewResilienceCircuitOpenError:()=>PrReviewResilienceCircuitOpenError,PR_WORKFLOW_PROBE_SKIPPED_NO_BUDGET_REASON:()=>PR_WORKFLOW_PROBE_SKIPPED_NO_BUDGET_REASON,PR_REVIEW_TIER_L_CONSOLIDATED_LANE_FLOOR:()=>PR_REVIEW_TIER_L_CONSOLIDATED_LANE_FLOOR,PR_REVIEW_REQUIRED_MICRO_LANE_IDS:()=>PR_REVIEW_REQUIRED_MICRO_LANE_IDS,PR_REVIEW_REPORT_VERDICTS:()=>PR_REVIEW_REPORT_VERDICTS,PR_REVIEW_MICRO_LANE_FLOORS:()=>PR_REVIEW_MICRO_LANE_FLOORS,PR_REVIEW_DEPTH_TIER_THRESHOLDS:()=>PR_REVIEW_DEPTH_TIER_THRESHOLDS,PR_REVIEW_BASE_LANE_FLOORS:()=>PR_REVIEW_BASE_LANE_FLOORS,PR_REVIEW_BASE_DIMENSION_IDS:()=>PR_REVIEW_BASE_DIMENSION_IDS,MAX_SALVAGED_SCHEMA_ERROR_CHARS:()=>MAX_SALVAGED_SCHEMA_ERROR_CHARS,MAX_PR_REVIEW_SUBMIT_REJECTIONS:()=>MAX_PR_REVIEW_SUBMIT_REJECTIONS,MAX_PR_FEEDBACK_INVENTORY_AMENDMENTS:()=>MAX_PR_FEEDBACK_INVENTORY_AMENDMENTS});import{createHash as createHash59,randomUUID as randomUUID17}from"node:crypto";import*as fsp8 from"node:fs/promises";import*as path119 from"node:path";function readPrWorkflowGateStateFromDisk3(directory,sessionID){return readPrWorkflowGateStateFromDisk(directory,sessionID)}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(state2){let evidence2=JSON.stringify({operations:state2.evidence.operations,unmerged_codes:state2.evidence.unmergedCodes,paths:state2.evidence.paths,paths_truncated:state2.evidence.pathsTruncated});return`BLOCKED: PR workflow checkout requires manual Git recovery before activation. code=${state2.code} retryable=false required_action=${state2.requiredAction} evidence=${evidence2}`}function checkoutRecoveryRecord(state2){if(state2.kind!=="recovery-required"&&state2.kind!=="indeterminate")throw Error("PR workflow checkout recovery requires a terminal Git state");return{code:state2.code,retryable:!1,requiredAction:state2.requiredAction,evidence:state2.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 readPrWorkflowGateStateFromDisk3(directory,normalizedSessionID);if(existing?.mode===mode){if(mode==="PR_FEEDBACK"&&options.prUrl){let requestedTarget=canonicalGitHubPrUrl(options.prUrl,options.forge);if(!requestedTarget)throw Error("BLOCKED: PR_FEEDBACK target must be a canonical GitHub PR URL");let existingTarget=existing.prFeedbackTargetUrl?canonicalGitHubPrUrl(existing.prFeedbackTargetUrl,options.forge):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:[path119.join(".swarm",workflowCheckoutMutationLockRelativePath()),path119.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,skillContractAdvisories=await ensurePrWorkflowSkillContractsFresh(directory,mode),ghReadinessAdvisory=collectPrWorkflowGhReadinessAdvisory(_test_exports2.resolveGhBinary),activationAdvisories=ghReadinessAdvisory?[ghReadinessAdvisory,...skillContractAdvisories]:skillContractAdvisories,timestamp=isoNow(),feedbackTargetUrl=mode==="PR_FEEDBACK"&&options.prUrl?canonicalGitHubPrUrl(options.prUrl,options.forge)?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:randomUUID17(),sessionID:normalizedSessionID,mode,activatedAt:timestamp,updatedAt:timestamp,...activationAdvisories.length>0?{skillContractAdvisories:activationAdvisories}:{},...initialHead?{prHeadSha:initialHead}:{},...feedbackTargetUrl?{prFeedbackTargetUrl:feedbackTargetUrl}:{}};return writeStateWhileLocked(directory,nextState)}))}async function appendPrWorkflowSkillContractAdvisories(directory,sessionID,advisories){if(advisories.length===0)return;let normalizedSessionID=normalizeSessionID(sessionID);if(!normalizedSessionID)return;await withSessionStateMutation(directory,normalizedSessionID,async()=>{try{let existing=await readPrWorkflowGateStateFromDisk3(directory,normalizedSessionID);if(!existing)return;let current=existing.skillContractAdvisories??[],merged=[...current];for(let advisory of advisories){if(merged.length>=MAX_SKILL_CONTRACT_ADVISORIES)break;if(!merged.includes(advisory))merged.push(advisory)}if(merged.length===current.length)return;await writeStateWhileLocked(directory,{...existing,skillContractAdvisories:merged,updatedAt:isoNow()})}catch{}})}async function readPrWorkflowGateState(directory,sessionID){let normalizedSessionID=normalizeSessionID(sessionID),state2=await readPrWorkflowGateStateFromDisk3(directory,normalizedSessionID);if(state2)rememberState(directory,state2);else forgetTrackedPrWorkflowState(directory,normalizedSessionID);return state2}function isLivenessTerminalLaneRecord2(record3){if(record3.status!=="cancelled"&&record3.status!=="stale"&&record3.status!=="error")return!1;return record3.terminalResult?.result.workflowLaneFailureClass==="liveness"||record3.result?.workflowLaneFailureClass==="liveness"}async function recordPrReviewSubmitRejection(directory,childSessionId,message){try{let child=childSessionId.trim();if(!child)return;let childRead=readDelegationsDetailed(directory);if(childRead.status==="uncertain")return;let record3=childRead.records.find((candidate)=>candidate.subagentSessionId===child&&(candidate.mode==="swarm-pr-review:base"||candidate.mode==="swarm-pr-review:micro")),parentSessionId=record3?.parentSessionId?.trim();if(!parentSessionId)return;let existing=await readPrWorkflowGateStateFromDisk3(directory,parentSessionId);if(!existing||existing.mode!=="PR_REVIEW")return;let laneId=record3?.laneId?.trim(),bounded=redactSecrets(message.replace(PUBLICATION_URL_CREDENTIALS_PATTERN,"$1[REDACTED:url_credentials]@")).slice(0,300);await withSessionStateMutation(directory,parentSessionId,async()=>{let locked=await readPrWorkflowGateStateFromDisk3(directory,parentSessionId);if(!locked||locked.mode!=="PR_REVIEW")return;let prior=locked.prReviewSubmitRejections??[];if(prior.filter((entry)=>entry.childSessionId===child).at(-1)?.message===bounded)return;let journal=[...prior,{childSessionId:child,...laneId?{laneId}:{},at:Date.now(),message:bounded}].slice(-MAX_PR_REVIEW_SUBMIT_REJECTIONS);await writeStateWhileLocked(directory,{...locked,prReviewSubmitRejections:journal,updatedAt:isoNow()})})}catch{}}function latestPrReviewSubmitRejectionMessage(state2,childSessionId){let journal=state2.prReviewSubmitRejections;if(!journal?.length)return;for(let index=journal.length-1;index>=0;index--)if(journal[index]?.childSessionId===childSessionId)return journal[index]?.message;return}async function submitPrReviewResultCore(directory,childSessionId,input){let child=childSessionId.trim(),parsedResult=PrReviewLaneResultEnvelopeSchema.safeParse(input.result);if(!child||!parsedResult.success)return{status:"rejected",reason:"invalid child session or result envelope"};let childRead=readDelegationsDetailed(directory);if(childRead.status==="uncertain")return{status:"rejected",reason:`delegation store unreadable after ${childRead.attempts} attempts; child lookup uncertain (${childRead.reason})`};let preliminary=childRead.records.filter((record4)=>record4.subagentSessionId===child&&record4.correlationId===child&&(record4.mode==="swarm-pr-review:base"||record4.mode==="swarm-pr-review:micro")),repairRecord=null;if(preliminary.length!==1){let repairCandidates=childRead.records.filter((candidate)=>candidate.parentSessionId===child&&(candidate.mode==="swarm-pr-review:base"||candidate.mode==="swarm-pr-review:micro")&&(input.batchId===void 0||input.batchId===candidate.batchId)&&(input.laneId===void 0||input.laneId===candidate.laneId)&&isLivenessTerminalLaneRecord2(candidate));if(repairCandidates.length!==1)return{status:"rejected",reason:`expected one exact child delegation, found ${preliminary.length}`};if(repairRecord=repairCandidates[0],parsedResult.data.outcome!=="INCOMPLETE")return{status:"rejected",reason:"architect-parent repair may only record an unresolved-terminal (INCOMPLETE) outcome"}}let parentSessionId=(repairRecord??preliminary[0]).parentSessionId,record3=repairRecord??preliminary[0],childOfRecord=record3.subagentSessionId;if(!record3.batchId||!record3.laneId)return{status:"rejected",reason:"delegation batch/lane provenance is missing"};if(input.batchId!==void 0&&input.batchId!==record3.batchId||input.laneId!==void 0&&input.laneId!==record3.laneId)return{status:"rejected",reason:"delegation batch/lane identity mismatch"};let{batchId,laneId}=record3;return withSessionStateMutation(directory,parentSessionId,async()=>{let state2=await readPrWorkflowGateStateFromDisk3(directory,parentSessionId);if(!state2||state2.mode!=="PR_REVIEW"||!state2.workflowInstanceId||!state2.prHeadSha||!state2.prReviewBaseSha)return{status:"rejected",reason:"no active bound PR_REVIEW workflow"};if((await createPrReviewGateContext2(directory,state2)).revisionDigest!==input.revisionDigest)return{status:"rejected",reason:"stale dispatch revision digest"};let dispatchWorkflowInstanceId=decodePrReviewWorkflowBinding(record3.jobId),dispatchWorkflowRevision=record3.workflowGeneration;if(!dispatchWorkflowInstanceId||dispatchWorkflowRevision===void 0)return{status:"rejected",reason:"delegation workflow binding provenance is missing"};if(dispatchWorkflowInstanceId!==state2.workflowInstanceId)return{status:"rejected",reason:"stale workflow instance binding"};if(repairRecord&&dispatchWorkflowRevision!==state2.revision)return{status:"rejected",reason:`superseded workflow generation binding (delegation generation ${dispatchWorkflowRevision}, active generation ${state2.revision})`};if(record3.mode!=="swarm-pr-review:base"&&record3.mode!=="swarm-pr-review:micro"||!sameProjectRoot(record3.workspace?.directory??"",directory))return{status:"rejected",reason:"delegation mode or workspace mismatch"};let ownedWorkflowLanes=record3.ownedWorkflowLanes?.length?record3.ownedWorkflowLanes:record3.workflowLane?[record3.workflowLane]:[];if(!record3.workflowLane||ownedWorkflowLanes.length===0)return{status:"rejected",reason:"delegation ownership is missing"};let semanticEnvelopeDigest=prReviewLaneResultEnvelopeDigest(parsedResult.data),existingReceiptDigest=record3.result?.prReviewResultReceipt?.semanticEnvelopeDigest,submission=reducePrReviewEvent(state2,{type:"lane_structured_result_submitted",batchId,laneId,generation:state2.revision,semanticEnvelopeDigest,outcome:parsedResult.data.outcome,...existingReceiptDigest!==void 0?{existingReceiptDigest}:{},...repairRecord?{submittedBy:"workflow_parent"}:{}});if(submission.status==="rejected")return{status:"rejected",reason:submission.rejection.code==="duplicate_conflicting_result"?"a different bound receipt is already recorded":`structured result submission rejected: ${submission.rejection.code}`};let published=await publishPrReviewResultReceipt(directory,{parentSessionId,childSessionId:childOfRecord,batchId,laneId,expectedWorkflowInstanceId:state2.workflowInstanceId,expectedWorkflowRevision:dispatchWorkflowRevision,expectedBaseSha:state2.prReviewBaseSha,...repairRecord?{parentRepair:!0}:{},receipt:{schemaVersion:1,mode:record3.mode,workflowInstanceId:dispatchWorkflowInstanceId,workflowRevision:dispatchWorkflowRevision,batchId,laneId,workflowLane:record3.workflowLane,ownedWorkflowLanes,baseSha:state2.prReviewBaseSha,headSha:state2.prHeadSha,dispatchRevisionDigest:input.revisionDigest,childSessionId:childOfRecord,generation:record3.generation??1,semanticEnvelopeDigest,envelope:parsedResult.data,...repairRecord?{submittedBy:"workflow_parent",submittedByParentSessionId:parentSessionId,laneTerminalStateAtSubmission:record3.status}:{}}});if(published.status==="recorded"||published.status==="duplicate")return{status:published.status,receiptDigest:semanticEnvelopeDigest};return{status:"rejected",reason:published.reason}})}async function submitPrReviewResult(directory,childSessionId,input){let outcome=await submitPrReviewResultCore(directory,childSessionId,input);if(outcome.status==="rejected")await recordPrReviewSubmitRejection(directory,childSessionId,outcome.reason);return outcome}async function withPrWorkflowCheckoutPreparationLock(directory,sessionID,action2){let normalizedSessionID=normalizeSessionID(sessionID);return withPrWorkflowCheckoutMutationLock(directory,async()=>withSessionStateMutation(directory,normalizedSessionID,async()=>{let state2=await readPrWorkflowGateStateFromDisk3(directory,normalizedSessionID);if(!state2)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(state2.prHeadSha)throw Error(`BLOCKED: ${state2.mode} checkout preparation is allowed only before the PR head is bound`);return action2(state2,{markRecoveryRequired:async(gitState)=>{let nextState={...state2,updatedAt:isoNow(),checkoutRecovery:checkoutRecoveryRecord(gitState)},persisted=await writeStateWhileLocked(directory,nextState);return Object.assign(state2,persisted),persisted}})}))}async function withInactivePrWorkflowCheckoutRestoreLock(directory,sessionID,action2){let normalizedSessionID=normalizeSessionID(sessionID);return withPrWorkflowCheckoutMutationLock(directory,async()=>withSessionStateMutation(directory,normalizedSessionID,async()=>{if(await readPrWorkflowGateStateFromDisk3(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),action2()}))}async function assertNoActivePrWorkflowGateForCheckoutRestore(directory){let gateDirectory=validateSwarmPath(directory,WORKFLOW_GATE_DIR),handle;try{handle=await fsp8.opendir(gateDirectory)}catch(error93){if(error93.code==="ENOENT")return;throw error93}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 statePath2=validateSwarmPath(directory,path119.join(WORKFLOW_GATE_DIR,entry.name)),state2=await readPrWorkflowGateStateFileFromDisk(statePath2,entry.name);if(!state2)continue;let expectedName=path119.basename(workflowGateStateRelativePath(state2.sessionID));if(entry.name!==expectedName)throw Error("BLOCKED: PR workflow gate inventory contains an ambiguous state filename; checkout restoration cannot prove project inactivity");let boundedEntryName=entry.name.length<=MAX_PR_WORKFLOW_GATE_ENTRY_NAME_CHARS?entry.name:`${entry.name.slice(0,MAX_PR_WORKFLOW_GATE_ENTRY_NAME_CHARS-1)}…`;throw Error(`BLOCKED: checkout restoration cannot mutate this project while session "${state2.sessionID}" has an active ${state2.mode} workflow (state entry "${boundedEntryName}"). For the owning session, run \`/swarm abort-pr-workflow ${state2.mode} <reason...>\` to recover the stuck gate.`)}}catch(error93){scanError=error93}finally{try{await handle.close()}catch(error93){if(error93.code!=="ERR_DIR_CLOSED")closeError=error93}}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 readPrWorkflowGateStateFromDisk3(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")}await deleteStateWhileLocked(directory,normalizedSessionID,{expectedStateRevision:expectedRevision,allowSalvagedRead:options.allowSalvagedRead})})}async function terminalizePrWorkflowGateForSession2(directory,sessionID){return terminalizePrWorkflowGateForSession(directory,sessionID)}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(error93){return{statuses:new Map,degradedReason:error93===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 record3 of records){let subagentSessionId=record3.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=(record3,reason)=>({laneId:record3.laneId??record3.correlationId,pendingMs:Math.max(0,now-record3.updatedAt),hostStatus:"unknown",stalledSuspect:!0,degradedReason:reason});try{now=_test_exports2.nowMs();let threshold=_test_exports2.pendingLaneLivenessThresholdMs;if(pastThreshold=records.filter((record3)=>(record3.status==="pending"||record3.status==="running"||record3.status==="ingesting")&&now-record3.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((record3)=>degraded(record3,PR_WORKFLOW_PROBE_SKIPPED_NO_BUDGET_REASON));let probe2=await probePrWorkflowLaneSessionStatusTypes(directory,pastThreshold,budgetMs),advisories=[];for(let record3 of pastThreshold){let pendingMs=now-record3.updatedAt,laneId=record3.laneId??record3.correlationId;if(probe2.degradedReason){advisories.push({laneId,pendingMs,hostStatus:"unknown",stalledSuspect:!0,degradedReason:probe2.degradedReason});continue}let subagentSessionId=record3.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((record3)=>degraded(record3,"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(record3){return record3.laneId??record3.subagentSessionId??"unknown"}function isOpenPrWorkflowLane(record3,sessionID){return record3.parentSessionId===sessionID&&record3.mode?.startsWith("swarm-pr-")===!0&&(record3.status==="pending"||record3.status==="running")}async function abortLaneSessionForWatchdog(record3){let session=_test_exports2.getSessionOps(),abortOp=session?.abort;if(!session||typeof abortOp!=="function"||!record3.subagentSessionId)return!1;try{return await withTimeout(abortOp.call(session,{path:{id:record3.subagentSessionId}}),_test_exports2.laneLivenessProbeTimeoutMs,Error("lane-liveness watchdog abort exceeded its deadline")),!0}catch{return!1}}function lastWatchdogEscalationsByLaneLabel(directory,sessionID){let escalations=new Map,activityObservations=new Map,deadlineLabels=new Set,text="";try{text=readCoreEvents(directory).text}catch{return{escalations,activityObservations,deadlineLabels}}for(let line of text.split(`
|
|
1289
1289
|
`)){let trimmed=line.trim();if(!trimmed||!trimmed.includes("pr_workflow_lane_watchdog"))continue;let event;try{event=JSON.parse(trimmed)}catch{continue}if(event.type!=="pr_workflow_lane_watchdog")continue;if(sessionID!==void 0&&event.sessionID!==sessionID)continue;let isEscalation=event.escalated===!0,isActivityObservation=!isEscalation&&event.activityObserved===!0,isDeadlineEvent=!isEscalation&&!isActivityObservation&&event.condition==="execution_deadline";if(!isEscalation&&!isActivityObservation&&!isDeadlineEvent)continue;let timestamp=Date.parse(`${event.timestamp}`);if(!Number.isFinite(timestamp))continue;let laneIds=event.laneIds;if(!Array.isArray(laneIds))continue;let target=isEscalation?escalations:activityObservations;for(let label of laneIds){if(typeof label!=="string")continue;if(isDeadlineEvent){deadlineLabels.add(label);continue}let prior=target.get(label);if(prior===void 0||timestamp>prior)target.set(label,timestamp)}}return{escalations,activityObservations,deadlineLabels}}function appendWatchdogActivityObservation(directory,sessionID,labels,horizon,condition){try{appendCoreEventSync(directory,{type:"pr_workflow_lane_watchdog",timestamp:isoNow(),sessionID,condition,laneIds:labels.slice(0,MAX_LANE_LIVENESS_DISCLOSED_IDS),effectiveHorizonMs:horizon.horizonMs,horizonSource:horizon.source,escalated:!1,activityObserved:!0,disclosure:`${labels.length} lane(s) progressed (activity observed since the last escalation); stall escalation baseline reset`})}catch{}}async function evaluateLaneLivenessWatchdogEscalation(args2){let{directory,sessionID,lanes,sessionTypes,watchdog,horizon}=args2,candidates=lanes.filter((record3)=>{if(!record3.subagentSessionId)return!1;let type=sessionTypes.get(record3.subagentSessionId);return type==="busy"||type==="retry"});if(candidates.length===0)return;let lastEscalations=lastWatchdogEscalationsByLaneLabel(directory,sessionID),escalated=[],progressed=[],firstEscalatedSteps=0,firstEscalatedTokens=0;for(let record3 of candidates){let activity=null;try{activity=await laneLivenessWatchdogSurface.readLaneActivity(directory,record3.subagentSessionId)}catch{activity=null}let steps=activity?.stepsObserved??0,tokens2=activity?.estimatedTokens??0;if(steps>=watchdog.stall_min_steps||tokens2>=watchdog.stall_token_threshold){progressed.push(record3);continue}let label=prWorkflowLaneLabel(record3),lastEscalation=lastEscalations.escalations.get(label);if(lastEscalation!==void 0){let lastActivity=activity?.lastActivityAtMs;if(!(lastActivity!==void 0&&lastActivity>=lastEscalation||(lastEscalations.activityObservations.get(label)??-1/0)>=lastEscalation))continue}if(escalated.length===0)firstEscalatedSteps=steps,firstEscalatedTokens=tokens2;escalated.push(record3)}if(progressed.length>0){let firstProgressed=progressed[0],firstProgressedType=firstProgressed.subagentSessionId?sessionTypes.get(firstProgressed.subagentSessionId):void 0;appendWatchdogActivityObservation(directory,sessionID,progressed.map(prWorkflowLaneLabel),horizon,firstProgressedType==="retry"?"provider_retry_in_flight":"idle_failed_child")}if(escalated.length===0)return;let first=escalated[0],condition=classifyLaneLivenessCondition({sessionStatusType:first.subagentSessionId?sessionTypes.get(first.subagentSessionId):void 0,recordStatus:first.status,waitBudgetExpired:!1,exceededEffectiveHorizon:Date.now()-first.updatedAt>horizon.horizonMs}),laneLabels=escalated.map(prWorkflowLaneLabel),disclosure=`${laneLabels.length} lane(s) stalled (fewer than ${watchdog.stall_min_steps} steps and fewer than ~${watchdog.stall_token_threshold} estimated tokens in the last ${watchdog.stall_threshold_ms}ms): inspect the lane transcript or abort via /swarm abort-pr-workflow (force): ${laneLabels.slice(0,MAX_LANE_LIVENESS_DISCLOSED_IDS).join(", ")}`;try{appendCoreEventSync(directory,{type:"pr_workflow_lane_watchdog",timestamp:isoNow(),sessionID,condition,laneIds:laneLabels.slice(0,MAX_LANE_LIVENESS_DISCLOSED_IDS),effectiveHorizonMs:horizon.horizonMs,horizonSource:horizon.source,escalated:!0,stall:{stepsObserved:firstEscalatedSteps,estimatedTokens:firstEscalatedTokens,stallThresholdMs:watchdog.stall_threshold_ms,stallMinSteps:watchdog.stall_min_steps,stallTokenThreshold:watchdog.stall_token_threshold},disclosure})}catch{}}async function settlePresumedStalePrWorkflowLanes(directory,sessionID,options){let watchdog=options?.laneLivenessWatchdog,{deadlineActive,stallActive}=laneLivenessWatchdogFeatures(watchdog),watchdogWork=deadlineActive||stallActive,horizon=resolveEffectivePrLaneHorizonMs(watchdog,options?.backgroundPendingTimeoutMs),horizonConflictNote=horizon.conflictDisclosed?horizon.source==="watchdog-timeout"?`lane_liveness_watchdog.timeout_ms (${horizon.horizonMs}ms) governs the PR-lane settlement horizon; hooks.background_pending_timeout_minutes was also set and disagrees — it was not applied (one effective horizon)`:`PR-lane settlement uses the ${Math.round(horizon.horizonMs/60000)}min reachability floor; hooks.background_pending_timeout_minutes disagrees with it and does not change this horizon`:void 0,now=Date.now(),open7=[],presumedStale=[],laneRead=readDelegationsDetailed(directory);if(laneRead.status==="uncertain")return{openLaneIds:[],openLanes:0,freshOpenLanes:0,presumedStaleLaneIds:[],...horizonConflictNote?{horizonConflictNote}:{},uncertainty:{reason:laneRead.reason,attempts:laneRead.attempts}};for(let record3 of laneRead.records){if(!isOpenPrWorkflowLane(record3,sessionID))continue;if(now-record3.updatedAt>horizon.horizonMs)presumedStale.push(record3);else open7.push(record3)}if(watchdogWork&&(open7.length>0||presumedStale.length>0))laneLivenessWatchdogSurface.evaluations+=1;if(presumedStale.length===0){if(watchdogWork&&stallActive&&open7.length>0){let statuses=new Map;try{let probe3=await _test_exports2.probeLaneSessionStatusTypesAsync(directory,open7);if(statuses=probe3.statuses,!probe3.degradedReason)laneLivenessWatchdogSurface.hostStatusCalls+=1}catch{}if(statuses.size>0)await evaluateLaneLivenessWatchdogEscalation({directory,sessionID,lanes:open7,sessionTypes:statuses,watchdog,horizon})}return{openLaneIds:open7.map(prWorkflowLaneLabel),openLanes:open7.length,freshOpenLanes:open7.length,presumedStaleLaneIds:[],...horizonConflictNote?{horizonConflictNote}:{}}}let probe2,sessionTypes=new Map;if(watchdogWork)try{let typesProbe=await _test_exports2.probeLaneSessionStatusTypesAsync(directory,stallActive?[...presumedStale,...open7]:presumedStale);if(sessionTypes=typesProbe.statuses,!typesProbe.degradedReason)laneLivenessWatchdogSurface.hostStatusCalls+=1;let alive=new Set;for(let[sessionId,type]of typesProbe.statuses)if(isLiveSessionStatusType(type))alive.add(sessionId);probe2=typesProbe.degradedReason?{alive:new Set,degradedReason:typesProbe.degradedReason}:{alive}}catch{probe2={alive:new Set,degradedReason:"probe-error"}}else try{probe2=await _test_exports2.probeLaneLivenessAsync(directory,presumedStale)}catch{probe2={alive:new Set,degradedReason:"probe-error"}}let probeRetained=[],settled=[],deadlineLanes=[];for(let record3 of presumedStale){let type=record3.subagentSessionId?sessionTypes.get(record3.subagentSessionId):void 0;if(deadlineActive&&type!=="retry")deadlineLanes.push(record3),settled.push(record3);else if(record3.subagentSessionId&&probe2.alive.has(record3.subagentSessionId))probeRetained.push(record3);else if(deadlineActive)deadlineLanes.push(record3),settled.push(record3);else settled.push(record3)}let probedAliveLaneIds=probeRetained.map(prWorkflowLaneLabel),openLaneIds=[...open7.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((record3)=>record3.correlationId)}:{},...probe2.degradedReason?{probeDegradedReason:probe2.degradedReason}:{}};if(settled.length===0){if(watchdogWork&&stallActive&&probeRetained.length>0)await evaluateLaneLivenessWatchdogEscalation({directory,sessionID,lanes:probeRetained,sessionTypes,watchdog,horizon});return{openLaneIds,openLanes:openLaneIds.length,freshOpenLanes:open7.length,presumedStaleLaneIds:[],...horizonConflictNote?{horizonConflictNote}:{},...retentionFields,disclosure:retentionDisclosure}}if(deadlineActive){let priorDeadlineLabels=lastWatchdogEscalationsByLaneLabel(directory,sessionID).deadlineLabels,abortAttempted=!1;for(let record3 of deadlineLanes){if((record3.subagentSessionId?sessionTypes.get(record3.subagentSessionId):void 0)!=="busy"||!record3.subagentSessionId)continue;if(priorDeadlineLabels.has(prWorkflowLaneLabel(record3)))continue;if(abortAttempted=!0,await abortLaneSessionForWatchdog(record3))laneLivenessWatchdogSurface.hostAbortCalls+=1}if(deadlineLanes.length>0)try{appendCoreEventSync(directory,{type:"pr_workflow_lane_watchdog",timestamp:isoNow(),sessionID,condition:"execution_deadline",laneIds:deadlineLanes.map(prWorkflowLaneLabel).slice(0,MAX_LANE_LIVENESS_DISCLOSED_IDS),effectiveHorizonMs:horizon.horizonMs,horizonSource:horizon.source,escalated:!1,disclosure:`${deadlineLanes.length} lane(s) exceeded the ${horizon.horizonMs}ms execution deadline (${horizon.source}); `+(abortAttempted?"sessions aborted best-effort and settled ":"no session abort was attempted (the liveness probe could not confirm these sessions were running); lanes settled ")+"through the shared path with the real outcome: no output observed (no transcript activity recorded for these lanes)"})}catch{}}let presumedStaleLaneIds=settled.map(prWorkflowLaneLabel),disclosure=`${presumedStaleLaneIds.length} lane(s) stale >${Math.round(horizon.horizonMs/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,horizon.horizonMs,{statuses:PR_WORKFLOW_SWEEPABLE_LANE_STATUSES,excludeCorrelationIds:new Set(probeRetained.map((record3)=>record3.correlationId))})}catch{}try{appendCoreEventSync(directory,{type:"pr_workflow_lanes_presumed_stale",timestamp:isoNow(),sessionID,presumedStaleLanes:presumedStaleLaneIds.slice(0,MAX_DISCLOSED_LANE_IDS),staleTimeoutMs:horizon.horizonMs,probeStatus:probe2.degradedReason??"ok",probedAliveLanes:probedAliveLaneIds.slice(0,MAX_DISCLOSED_LANE_IDS),disclosure})}catch{}if(watchdogWork&&stallActive&&!(deadlineActive&&deadlineLanes.length>0)){let stallCandidates=[...open7,...probeRetained];if(stallCandidates.length>0&&sessionTypes.size>0)await evaluateLaneLivenessWatchdogEscalation({directory,sessionID,lanes:stallCandidates,sessionTypes,watchdog,horizon});else if(stallCandidates.length>0);}return{openLaneIds,openLanes:openLaneIds.length,freshOpenLanes:open7.length,presumedStaleLaneIds,...horizonConflictNote?{horizonConflictNote}:{},...retentionFields,disclosure}}async function finalizeOverriddenProbeRetainedLanes(directory,sessionID,correlationIds,horizonMs=PR_WORKFLOW_STALE_LANE_TIMEOUT_MS,reason="/swarm abort-pr-workflow force override"){try{await _test_exports2.sweepStaleDelegationsAsync(directory,horizonMs,{statuses:PR_WORKFLOW_SWEEPABLE_LANE_STATUSES,includeCorrelationIds:new Set(correlationIds),failureClass:"operator_cancelled",reasonPrefix:`lane finalized by operator force abort: ${reason}`})}catch{}let targeted=new Set(correlationIds),outcome={sessionOpenLaneIds:[],finalizedLaneIds:[],sparedLaneDescriptions:[]},finalizeRead=readDelegationsDetailed(directory);if(finalizeRead.status==="uncertain")return{...outcome,delegationReadUncertain:`${finalizeRead.reason} (after ${finalizeRead.attempts} attempts)`};for(let record3 of finalizeRead.records){if(isOpenPrWorkflowLane(record3,sessionID))outcome.sessionOpenLaneIds.push(record3.correlationId);if(!targeted.has(record3.correlationId))continue;if(record3.status==="stale")outcome.finalizedLaneIds.push(record3.correlationId);else if(record3.status!=="pending"&&record3.status!=="running")outcome.sparedLaneDescriptions.push(`${record3.correlationId} (${record3.status})`)}return outcome}async function abortPrWorkflow(directory,sessionID,options={kind:"recovery",reason:""}){let recovery=await readPrWorkflowGateStateForRecovery(directory,sessionID);if(!recovery){if(options.cancelPublication){if(!options.reason.trim())throw Error("BLOCKED: cancel_publication requires a non-empty reason; the cancellation reason is part of the durable audit trail");let dangling=findDanglingLivePublicationGeneration(directory,sessionID);if(!dangling)throw noActiveGateError(sessionID);return appendPublicationEvent(directory,{type:"pr_feedback_publication_cancelled",sessionID:normalizeSessionID(sessionID),generation:dangling.generation,reason:options.reason.trim(),stateFileAbsent:!0,observedRemoteHead:null}),{mode:"PR_FEEDBACK",observedRemoteHead:null,openLanes:0,stateSalvaged:!1,stateSalvageDisclosure:"The gate state file was already absent; the live publication generation in the audit trail was recorded as cancelled_without_publication (event-only terminal)."}}throw noActiveGateError(sessionID)}let state2=recovery.state,cancelRevision=null,cancellationObservedRemoteHead;if(options.expectedMode&&state2.mode!==options.expectedMode)throw wrongModeError(state2,options.expectedMode);if(options.cancelPublication){if(options.kind==="force")throw Error('BLOCKED: cancel_publication cannot be combined with kind "force"; use kind "cancel-publication" with a reason');if(options.kind!=="cancel-publication")throw Error('BLOCKED: cancel_publication requires kind "cancel-publication"; do not combine it with kind "recovery" or "force"');if(!options.reason.trim())throw Error("BLOCKED: cancel_publication requires a non-empty reason; the cancellation reason is part of the durable audit trail");let activeState=state2.prFeedbackPublication?.active?.state;if(activeState==="published")throw Error("BLOCKED: PR_FEEDBACK publication is already marked published; use complete_pr_workflow so the actual remote branch is re-verified before the gate clears");if(state2.mode!=="PR_FEEDBACK"||!state2.prFeedbackReadyToPublish&&!recovery.armedShapeUnreadable&&activeState!=="armed"&&activeState!=="push_in_flight"&&activeState!=="invalidated"&&activeState!=="cancelled_without_publication")throw Error("BLOCKED: cancel_publication applies only to a PR_FEEDBACK workflow with a publication generation (armed, push_in_flight, or invalidated)");let cancellation=await cancelPrFeedbackPublication(directory,sessionID,options.reason.trim());cancelRevision=cancellation.revision,cancellationObservedRemoteHead=cancellation.observedRemoteHead}if(state2.prFeedbackPublication?.active?.state==="published")throw Error("BLOCKED: PR_FEEDBACK publication is already marked published; use complete_pr_workflow so the actual remote branch is re-verified before the gate clears");if((state2.prFeedbackReadyToPublish||recovery.armedShapeUnreadable)&&!options.cancelPublication)throw Error(`BLOCKED: ${state2.mode} is armed for publication; abort is blocked. Complete the workflow with complete_pr_workflow (or push the bound commit first) before aborting, or use the audited cancellation (abort_pr_workflow with cancel_publication and a reason).`+(recovery.armedShapeUnreadable?" The publication-arming record is itself unreadable, so it is treated as armed (fail-closed).":""));let laneSettlement=await settlePresumedStalePrWorkflowLanes(directory,state2.sessionID,options.laneLiveness),probeRetainedLanes=laneSettlement.probedAliveLaneIds??[],overridesProbeRetention=options.kind==="force"&&laneSettlement.freshOpenLanes===0&&probeRetainedLanes.length>0;if(laneSettlement.uncertainty)throw Error(`BLOCKED: ${state2.mode} abort refused while the delegation store is unreadable after ${laneSettlement.uncertainty.attempts} attempts (${laneSettlement.uncertainty.reason}); open lanes are UNKNOWN, not absent. Restore the store (see the settlement disclosure) or retry once it is readable before aborting.`);if(laneSettlement.openLanes>0&&!overridesProbeRetention){let laneIds=laneSettlement.openLaneIds.filter(Boolean).slice(0,MAX_DISCLOSED_LANE_IDS).join(", ");throw Error(`BLOCKED: ${state2.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: ${state2.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:state2.sessionID,mode:state2.mode,kind:options.kind,...state2.prHeadSha?{prHeadSha:state2.prHeadSha}:{},...state2.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{appendCoreEventSync(directory,abortEvent)}catch{}let casEscape=recovery.salvaged&&!recovery.revisionSalvageable;await _test_exports2.beforeAbortClear?.();try{await clearPrWorkflowGateState(directory,sessionID,casEscape?void 0:cancelRevision??state2.revision,{allowSalvagedRead:recovery.salvaged})}catch(error93){try{appendCoreEventSync(directory,{type:"pr_workflow_abort_not_completed",timestamp:isoNow(),sessionID:state2.sessionID,mode:state2.mode,...state2.prHeadSha?{prHeadSha:state2.prHeadSha}:{},reason:sanitizedReason,...overridesProbeRetention?{probeRetentionOverrideLanes:overrideTargetedLaneIds.slice(0,MAX_DISCLOSED_LANE_IDS),probeRetentionOverrideFinalized:!1}:{},failure:(error93 instanceof Error?error93.message:String(error93)).slice(0,MAX_BASE_COVERAGE_DIAGNOSTIC_CHARS2),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.":"")})}catch{}throw error93}let overrideOutcome=overridesProbeRetention?await finalizeOverriddenProbeRetainedLanes(directory,state2.sessionID,overrideTargetedLaneIds,resolveEffectivePrLaneHorizonMs(options.laneLiveness?.laneLivenessWatchdog,options.laneLiveness?.backgroundPendingTimeoutMs).horizonMs,options.reason??"/swarm abort-pr-workflow force override"):{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.delegationReadUncertain!==void 0?` WARNING: the post-abort delegation-store re-read was unreadable (${overrideOutcome.delegationReadUncertain}); whether any PR workflow delegation record(s) for this session remain open is UNKNOWN — revalidate with pr_workflow_status before assuming a new PR workflow can start.`: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:state2.mode,...state2.prHeadSha?{prHeadSha:state2.prHeadSha}:{},...cancellationObservedRemoteHead!==void 0?{observedRemoteHead:cancellationObservedRemoteHead}:{},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 recoverArmedPrWorkflow(directory,sessionID,request){let sanitizedReason=typeof request.reason==="string"&&request.reason.trim().length>0?request.reason.trim().slice(0,500):void 0;if(sanitizedReason===void 0)throw Error("BLOCKED: armed recovery requires a non-empty reason (recorded to the audit trail).");return withSessionStateMutation(directory,normalizeSessionID(sessionID),async()=>{let state2=await readPrWorkflowGateStateFromDisk3(directory,normalizeSessionID(sessionID));if(!state2)throw noActiveGateError(sessionID);if(request.expectedMode&&state2.mode!==request.expectedMode)throw wrongModeError(state2,request.expectedMode);let armed=state2.prFeedbackReadyToPublish;if(!armed)throw Error(`BLOCKED: ${state2.mode} is not armed for publication; armed recovery applies only to an active staged publication authorization (complete or abort normally instead).`);if(request.prHeadSha!==state2.prHeadSha)throw Error(`BLOCKED: armed recovery head mismatch: workflow is bound to "${state2.prHeadSha??"(none)"}", request declared "${request.prHeadSha}".`);if(state2.prReviewBaseSha===void 0!==(request.baseSha===void 0))throw Error(`BLOCKED: armed recovery base mismatch: ${state2.prReviewBaseSha===void 0?"the active workflow has no merge-base binding but the request declared one":"the active workflow is merge-base bound but the request omitted base_sha"}; fail closed.`);if(request.baseSha!==void 0&&state2.prReviewBaseSha!==void 0&&request.baseSha!==state2.prReviewBaseSha)throw Error(`BLOCKED: armed recovery base mismatch: workflow is merge-base bound to "${state2.prReviewBaseSha}", request declared "${request.baseSha}".`);if(request.revisionDigest!==armed.revisionDigest)throw Error("BLOCKED: armed recovery revision digest does not match the staged publication authorization; fail closed.");if(request.generation!==state2.revision)throw Error(`BLOCKED: armed recovery generation mismatch: current gate generation is ${state2.revision}, request declared ${request.generation}. Stale requests fail closed; re-read the workflow state and retry.`);if(request.workflowInstanceId===void 0!==(state2.workflowInstanceId===void 0))throw Error("BLOCKED: armed recovery workflow identity mismatch: request and active state disagree on workflowInstanceId presence; fail closed.");if(request.workflowInstanceId!==void 0&&state2.workflowInstanceId!==void 0&&request.workflowInstanceId!==state2.workflowInstanceId)throw Error(`BLOCKED: armed recovery workflow identity mismatch: active workflow is "${state2.workflowInstanceId}", request declared "${request.workflowInstanceId}".`);let laneSettlement=await settlePresumedStalePrWorkflowLanes(directory,state2.sessionID,request.laneLiveness);if(laneSettlement.uncertainty)throw Error(`BLOCKED: armed recovery refused while the delegation store is unreadable after ${laneSettlement.uncertainty.attempts} attempts (${laneSettlement.uncertainty.reason}); open lanes are UNKNOWN, not absent. Restore the store before recovering.`);if(laneSettlement.openLanes>0){let laneIds=laneSettlement.openLaneIds.filter(Boolean).slice(0,MAX_DISCLOSED_LANE_IDS).join(", ");throw Error(`BLOCKED: armed recovery refused while ${laneSettlement.openLanes} PR workflow lane(s) are still in flight (lane ids: ${laneIds}). Collect their results or let them settle before recovering.`+describePrWorkflowLaneProbe(laneSettlement))}let cancelledDimensions=[],cancellations=state2.prReviewDimensionCancellations,recoveredAt=isoNow();if(state2.mode==="PR_REVIEW"&&state2.prHeadSha){let ctx=await createPrReviewGateContext2(directory,state2),settlement=derivePrReviewDimensionSettlement(directory,state2,ctx.revisionDigest);for(let entry of settlement.unresolvedDimensions){if(entry.terminalState!=="NOT_LAUNCHED")continue;cancelledDimensions.push(entry.dimension)}if(cancelledDimensions.length>0){let recoveryOutcome=reducePrReviewEvent(state2,{type:"armed_recovery_requested",binding:{sessionID:state2.sessionID,...state2.workflowInstanceId?{workflowInstanceId:state2.workflowInstanceId}:{},prHeadSha:state2.prHeadSha,revisionDigest:armed.revisionDigest,generation:state2.revision},dimensionsToCancel:cancelledDimensions,nowIso:recoveredAt,reason:sanitizedReason});if(recoveryOutcome.status==="rejected")throw Error(`BLOCKED: armed recovery rejected (${recoveryOutcome.rejection.code}): ${recoveryOutcome.rejection.detail}`);cancellations=recoveryOutcome.state.prReviewDimensionCancellations??cancellations}}try{appendCoreEventSync(directory,{type:"pr_workflow_armed_recovery",timestamp:recoveredAt,sessionID:state2.sessionID,mode:state2.mode,prHeadSha:state2.prHeadSha,revisionDigest:armed.revisionDigest,generation:state2.revision,settledLanes:laneSettlement.presumedStaleLaneIds?.length??0,cancelledDimensions,reason:sanitizedReason})}catch{}return await writeStateWhileLocked(directory,{...state2,updatedAt:recoveredAt,prFeedbackReadyToPublish:void 0,prFeedbackArmedRecovery:{recoveredAt,prHeadSha:state2.prHeadSha,revisionDigest:armed.revisionDigest,generation:state2.revision,reason:sanitizedReason},...cancellations?{prReviewDimensionCancellations:cancellations}:{}}),{mode:state2.mode,prHeadSha:state2.prHeadSha,openLanes:laneSettlement.openLanes,settledLanes:laneSettlement.presumedStaleLaneIds?.length??0,cancelledDimensions,recoveredAt}})}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),state2=await readPrWorkflowGateStateFromDisk3(directory,normalizedSessionID);if(!state2)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,state2.mode),state2.prHeadSha&&state2.prHeadSha!==normalizedHead)throw Error(`BLOCKED: active ${state2.mode} workflow is bound to PR head "${state2.prHeadSha}"; received "${normalizedHead}"`);if(!state2.prHeadSha)await assertPrReviewCleanCheckout(directory,state2.mode);if(!state2.prHeadSha&&state2.mode==="PR_FEEDBACK")await assertPrFeedbackTrackingCheckout(directory,normalizedHead);if(state2.prHeadSha===normalizedHead){if(state2.mode==="PR_FEEDBACK")await assertPrFeedbackTrackingCheckout(directory,normalizedHead);return state2}let nextState={...state2,prHeadSha:normalizedHead,checkoutRecovery:void 0,updatedAt:isoNow()};await _test_exports2.beforePrFeedbackTrackingPersist?.();try{return await writeStateWhileLocked(directory,nextState)}catch(error93){if(!state2.prHeadSha)try{let candidates=await resolvePrFeedbackTrackingCandidatesAsync(directory,normalizedHead);if(candidates?.local.length===1)await switchPrFeedbackTrackingCandidateAsync(directory,candidates.local[0]);else if(candidates?.remote.length===1)await switchPrFeedbackTrackingCandidateAsync(directory,candidates.remote[0]);await assertPrFeedbackTrackingCheckout(directory,normalizedHead)}catch{}throw error93}}async function rebindPrFeedbackHead(directory,sessionID,prHeadSha){let state2=await requireBoundState2(directory,sessionID,"PR_FEEDBACK"),normalizedHead=normalizePrHeadSha(prHeadSha);if(state2.prFeedbackReadyToPublish)throw Error("BLOCKED: PR_FEEDBACK rebind is refused while publication is armed; complete the workflow (or push the bound commit) before rebinding.");let rebindRead=readDelegationsDetailed(directory);if(rebindRead.status==="uncertain")throw Error(`BLOCKED: PR_FEEDBACK rebind refused while the delegation store is unreadable after ${rebindRead.attempts} attempts (${rebindRead.reason}); in-flight lanes are UNKNOWN. Restore the store before rebinding.`);let openLanes=rebindRead.records.filter((record3)=>record3.parentSessionId===state2.sessionID&&record3.mode?.startsWith("swarm-pr-")&&(record3.status==="pending"||record3.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===state2.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,state2.mode),await assertPrFeedbackTrackingCheckout(directory,normalizedHead);let nextState={...state2,prHeadSha:normalizedHead,prFeedbackStageA:void 0,prFeedbackVerifications:void 0,prFeedbackGateBatches:void 0,prFeedbackRebindCount:(state2.prFeedbackRebindCount??0)+1,updatedAt:isoNow()};try{appendCoreEventSync(directory,{type:"pr_feedback_rebound",timestamp:isoNow(),sessionID:state2.sessionID,previousPrHeadSha:state2.prHeadSha,prHeadSha:normalizedHead,rebindCount:nextState.prFeedbackRebindCount})}catch{}return withSessionStateMutation(directory,state2.sessionID,async()=>writeStateWhileLocked(directory,nextState))}async function bindPrReviewBase(directory,sessionID,options){let state2=await bindPrWorkflowHead(directory,sessionID,options.prHeadSha);if(state2.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(state2.prReviewBaseRef&&state2.prReviewBaseRef!==baseRef||state2.prReviewBaseSha&&state2.prReviewBaseSha!==baseSha)throw Error(`BLOCKED: active PR_REVIEW is bound to merge-base scope "${state2.prReviewBaseRef??"(unbound)"}" at "${state2.prReviewBaseSha??"(unbound)"}"; received "${baseRef}" at "${baseSha}"`);if(state2.prReviewBaseRef===baseRef&&state2.prReviewBaseSha===baseSha)return state2;let prHeadSha=normalizePrHeadSha(options.prHeadSha).toLowerCase(),diffStats=await _test_exports2.resolvePrReviewDiffStatsAsync(directory,baseSha,prHeadSha);return state2={...state2,prReviewBaseRef:baseRef,prReviewBaseSha:baseSha,prReviewDepthTier:computePrReviewDepthTier(diffStats),...diffStats?{prReviewDiffStats:diffStats}:{},updatedAt:isoNow()},await persistState2(directory,state2),state2}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 state2=await readPrWorkflowGateState(directory,sessionID);if(!state2)return null;if(toolName===DISPATCH_TOOL_NAME)return state2;if(toolName===BLOCKING_DISPATCH_TOOL_NAME)throw Error(`BLOCKED: active ${state2.mode} workflow for session "${state2.sessionID}" requires ${DISPATCH_TOOL_NAME}; ${BLOCKING_DISPATCH_TOOL_NAME} is not allowed`);return state2}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 warnDelegationReadUncertainOnce(scope,uncertain){let key2=`${scope}\x00${uncertain.reason}`;if(delegationReadUncertainLogged.has(key2))return;if(delegationReadUncertainLogged.size>=DELEGATION_READ_UNCERTAIN_LOG_LIMIT){let oldest=delegationReadUncertainLogged.values().next().value;if(oldest!==void 0)delegationReadUncertainLogged.delete(oldest)}delegationReadUncertainLogged.add(key2),warn(`PR workflow gate: delegation store unreadable after ${uncertain.attempts} attempts (${uncertain.reason}); ${scope} is UNKNOWN, not absent`)}function batchLaneRecords(directory,state2,batchId,laneId){let outcome=findByBatchIdDetailed(directory,batchId,{parentSessionId:state2.sessionID});if(outcome.status==="uncertain")return warnDelegationReadUncertainOnce("batch lane records",outcome),[];return outcome.value.filter((record3)=>record3.laneId===laneId)}function batchIsTerminal(directory,state2,batchId){let outcome=findByBatchIdDetailed(directory,batchId,{parentSessionId:state2.sessionID});if(outcome.status==="uncertain")return warnDelegationReadUncertainOnce("batch terminality",outcome),!1;return outcome.value.length>0&&outcome.value.every((record3)=>TERMINAL_FAILED_DELEGATION_STATUSES2.has(record3.status)||record3.status==="consumed")}function effectivePrReviewResiliencePolicy(state2,requestedPolicy){return state2.prReviewResilience?.policy??snapshotPrReviewResiliencePolicy(requestedPolicy)}function reportCircuitAdoptionDiagnostic(diagnostic){if(diagnostic.code==="migrated_legacy_circuit"){log("PR review resilience circuit: migrated unversioned legacy circuit record to v2 CLOSED (nonblocking, evidence waterlined)",{legacyContributors:diagnostic.legacySignatureCount});return}if(malformedCircuitDiagnosticsSeen.has(diagnostic.bodyHash8))return;if(malformedCircuitDiagnosticsSeen.size>=MALFORMED_CIRCUIT_DIAGNOSTIC_LIMIT){let oldest=malformedCircuitDiagnosticsSeen.values().next().value;if(oldest!==void 0)malformedCircuitDiagnosticsSeen.delete(oldest)}malformedCircuitDiagnosticsSeen.add(diagnostic.bodyHash8),log("PR review resilience circuit: malformed circuit record dropped (fail-open)",{bodyHash8:diagnostic.bodyHash8,byteLength:diagnostic.byteLength})}function circuitOpenDurationMs(policy){return policy.circuitOpenDurationMs??DEFAULT_PR_REVIEW_RESILIENCE_CONFIG.circuit_open_duration_ms}function laneSignalsForCircuitReview(directory,state2){let signals=[];for(let batch of state2.prReviewBaseDispatches??[])for(let lane of batch.lanes){let latest=latestDelegationRecord(batchLaneRecords(directory,state2,batch.batchId,lane.laneId));if(!latest)continue;let signal=classifyPrReviewCircuitSignal(latest);if(signal)signals.push(signal)}return signals}function probeObservationForCircuit(directory,state2,circuit){if(circuit.state!=="HALF_OPEN"||!circuit.probe)return;let latest=latestDelegationRecord(batchLaneRecords(directory,state2,circuit.probe.batchId,circuit.probe.laneId));if(!latest)return;if(!TERMINAL_FAILED_DELEGATION_STATUSES2.has(latest.status))return;return{terminalStatus:latest.status,signal:classifyPrReviewCircuitSignal(latest),terminalAtMs:latest.terminalResult?.recordedAt??latest.completedAt??latest.updatedAt??latest.createdAt??0}}function formatPrReviewResilienceCircuitOpenMessage(circuit,nowMs3=Date.now()){if(!circuit)return"BLOCKED: PR_REVIEW resilience retry circuit is open; collect, diagnose, cancel, abort, gap reporting, and config disable remain available";if("version"in circuit){let openUntilMs=circuit.openUntil?Date.parse(circuit.openUntil):0,remainingMs=Math.max(0,openUntilMs-nowMs3),retryNote=remainingMs>0?`the recovery canary probe is admitted in about ${Math.ceil(remainingMs/1000)}s`:"the next staged dispatch is admitted as the recovery canary probe";return`BLOCKED: PR_REVIEW resilience retry circuit is ${circuit.state} after ${circuit.contributors.length} distinct terminal provider failures (${circuit.providerClass??"provider"}); ${retryNote}; collect, diagnose, cancel, abort, gap reporting, and config disable remain available`}return`BLOCKED: PR_REVIEW base dispatch circuit is open after ${circuit.count} correlated terminal failures (${circuit.signature}); collect every launched lane, then settle coverage truthfully (COMPLETE/PARTIAL/NO_COVERAGE) via complete_pr_workflow`}async function advanceResilienceCircuitWhileLocked(args2){let{directory}=args2,state2=args2.state,snapshot=args2.snapshot,nowMs3=_test_exports2.nowMs(),adoption=adoptPrReviewCircuit(snapshot.circuit,nowMs3),circuit=null;if(adoption.kind==="v2")circuit=adoption.record;else if(adoption.kind==="migrated")circuit=adoption.record,snapshot={...snapshot,circuit:adoption.record},state2=await writeStateWhileLocked(directory,{...state2,updatedAt:isoNow(),prReviewResilience:snapshot}),reportCircuitAdoptionDiagnostic(adoption.diagnostic);else if(adoption.kind==="malformed"){let withoutCircuit={...snapshot};withoutCircuit.circuit=void 0,snapshot=withoutCircuit,reportCircuitAdoptionDiagnostic(adoption.diagnostic)}let advanceOutcome=reducePrReviewEvent(state2,{type:"circuit_advance_requested",nowMs:nowMs3,laneSignals:laneSignalsForCircuitReview(directory,state2),probeObservation:circuit?.state==="HALF_OPEN"?probeObservationForCircuit(directory,state2,circuit):void 0,admission:args2.admission,policy:snapshot.policy});if(advanceOutcome.status==="rejected")return{state:state2,snapshot};let nextState=advanceOutcome.state,blockedReason=advanceOutcome.effects.find((effect)=>effect.kind==="block_dispatch")?.reason;if(advanceOutcome.effects.some((effect)=>effect.kind==="persist_state"))snapshot={...snapshot,circuit:nextState.prReviewResilience?.circuit},state2=await writeStateWhileLocked(directory,{...nextState,updatedAt:isoNow(),prReviewResilience:snapshot});else state2=nextState;if(blockedReason!==void 0)return{state:state2,snapshot,blocked:{reason:blockedReason}};let pendingProbe=nextState.prReviewResilience?.circuit;if(pendingProbe&&"version"in pendingProbe&&pendingProbe.state==="HALF_OPEN"&&pendingProbe.probe)return{state:state2,snapshot,pendingProbeCircuit:pendingProbe};return{state:state2,snapshot}}async function preflightPrReviewResilienceCircuitBeforePrune(directory,state2,previous,policy,liveResilienceEnabled){let nextState=state2,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(!liveResilienceEnabled)return{state:nextState,previous:nextPrevious};let outcome=await advanceResilienceCircuitWhileLocked({directory,state:nextState,snapshot});if(outcome.blocked)throw new PrReviewResilienceCircuitOpenError(formatPrReviewResilienceCircuitOpenMessage(outcome.snapshot.circuit));return{state:outcome.state,previous:outcome.state.prReviewBaseDispatches??nextPrevious}}async function probeResilienceCanaryLiveness(directory,records,timeoutMs){let session=_test_exports2.getSessionOps(),status2=session?.status;if(!session||typeof status2!=="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()=>status2.call(session,{query:{directory}}))(),timeoutMs,timeoutError)}catch(error93){return{live:!1,reason:error93===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 record3 of records){let type=response.data[record3.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,state2,attempt,revisionDigest,policy){let attempts=summarizePrReviewBaseDimensionAttempts(directory,state2,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,state2,attempt.fanoutBatchId):!1};let canaryRecords=batchLaneRecords(directory,state2,attempt.canaryBatchId,attempt.canaryLaneId);if(canaryRecords.length>0&&canaryRecords.every((record3)=>TERMINAL_FAILED_DELEGATION_STATUSES2.has(record3.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 state2=await bindPrWorkflowHeadWhileLocked(directory,normalizedSessionID,options.prHeadSha);if(state2.mode!=="PR_REVIEW")throw wrongModeError(state2,"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((state2.prReviewDepthTier??"L")==="L"&&normalizedLanes.some((lane)=>(lane.ownedWorkflowLanes?.length??1)!==1)){let rejection=await tierLConsolidationRejection(directory,state2,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=state2.prReviewBaseDispatches??[];if(previous.some((record4)=>record4.batchId===batchId))throw Error(`BLOCKED: PR_REVIEW base batch id "${batchId}" is already recorded`);let depthTier=state2.prReviewDepthTier??"L",requestedContractRetry=options.prReviewContractRetry===!0,requestedWaveStage=options.prReviewWaveStage,requestedWaveAttempt=options.prReviewWaveAttempt;if(requestedContractRetry&&(requestedWaveStage!==void 0||requestedWaveAttempt!==void 0))throw Error("BLOCKED: PR_REVIEW contract retry is mutually exclusive with pr_review_wave_stage and pr_review_wave_attempt");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(state2,options.prReviewResiliencePolicy),liveResilienceEnabled=options.prReviewResiliencePolicy?.enabled??DEFAULT_PR_REVIEW_RESILIENCE_CONFIG.enabled;if(previous.length>=MAX_WORKFLOW_BATCHES&&requestedWaveStage!==void 0&&requestedWaveAttempt!==void 0&&depthTier!=="S"&&liveResilienceEnabled)({state:state2,previous}=await preflightPrReviewResilienceCircuitBeforePrune(directory,state2,previous,resiliencePolicy,liveResilienceEnabled));if(previous.length>=MAX_WORKFLOW_BATCHES){if(state2=await prunePrWorkflowBatchesForCapacity(directory,state2,options.revisionDigest),previous=state2.prReviewBaseDispatches??[],previous.length>=MAX_WORKFLOW_BATCHES)throw Error("BLOCKED: PR_REVIEW base batch limit reached")}let nextResilience=state2.prReviewResilience;if(!nextResilience){if(nextResilience={policy:resiliencePolicy,attempts:[]},previous.length>0)state2=await writeStateWhileLocked(directory,{...state2,updatedAt:isoNow(),prReviewResilience:nextResilience}),previous=state2.prReviewBaseDispatches??[]}if(nextResilience&&(!liveResilienceEnabled||nextResilience.policy.enabled===!1)){let configEvent={type:"resilience_config_changed",enabled:liveResilienceEnabled,policy:liveResilienceEnabled?options.prReviewResiliencePolicy:void 0,nowMs:_test_exports2.nowMs()},outcome=reducePrReviewEvent(state2,configEvent);if(outcome.status==="applied"&&outcome.effects.some((effect)=>effect.kind==="persist_state"))state2=await writeStateWhileLocked(directory,{...outcome.state,updatedAt:isoNow()}),previous=state2.prReviewBaseDispatches??[],nextResilience=state2.prReviewResilience??nextResilience}if(liveResilienceEnabled&&depthTier!=="S"&&requestedWaveStage===void 0&&!requestedContractRetry)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"||!liveResilienceEnabled)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 createPrReviewGateContext2(directory,state2)).revisionDigest;let snapshot=nextResilience??{policy:resiliencePolicy,attempts:[]},pendingProbeCircuit;if(liveResilienceEnabled){let outcome=await advanceResilienceCircuitWhileLocked({directory,state:state2,snapshot,admission:{batchId,laneId:normalizedLanes[0]?.laneId??""}});if(state2=outcome.state,snapshot=outcome.snapshot,nextResilience=outcome.snapshot,pendingProbeCircuit=outcome.pendingProbeCircuit,outcome.blocked)throw new PrReviewResilienceCircuitOpenError(formatPrReviewResilienceCircuitOpenMessage(outcome.snapshot.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,state2,revisionDigest);globalInFlight=PR_REVIEW_BASE_DIMENSION_IDS.filter((dimension)=>globalAttempts.inFlight.has(dimension));let globalTarget=unresolvedPrReviewBaseDimensions(globalAttempts),evaluated=await evaluatePrReviewResilienceAttempt(directory,state2,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,state2,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,state2,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()}],...pendingProbeCircuit??snapshot.circuit?{circuit:pendingProbeCircuit??snapshot.circuit}:{}}}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,state2,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}]}}}if(requestedContractRetry){let revisionDigest=options.revisionDigest??(await createPrReviewGateContext2(directory,state2)).revisionDigest,attempts=summarizePrReviewBaseDimensionAttempts(directory,state2,revisionDigest);if(normalizedLanes.length!==1||(normalizedLanes[0]?.ownedWorkflowLanes?.length??1)!==1)throw Error("BLOCKED: PR_REVIEW contract retry requires exactly one singleton lane");let contractedDimension=declaredBaseDimensions(normalizedLanes)[0]??normalizedLanes[0].workflowLane;if(attempts.successful.has(contractedDimension))throw Error(`BLOCKED: PR_REVIEW contract retry cannot target already-successful dimension "${contractedDimension}"`);if(attempts.inFlight.has(contractedDimension))throw Error(`BLOCKED: PR_REVIEW contract retry cannot target in-flight dimension "${contractedDimension}"`);if(!attempts.contractFailed.has(contractedDimension))throw Error(`BLOCKED: PR_REVIEW contract retry requires a recorded terminal contract failure for dimension "${contractedDimension}"`);if(attempts.contractRetried.has(contractedDimension))throw Error(`BLOCKED: PR_REVIEW contract retry for dimension "${contractedDimension}" was already admitted`)}let record3={batchId,lanes:normalizedLanes.map((lane)=>({laneId:lane.laneId,workflowLane:lane.workflowLane,...lane.ownedWorkflowLanes?{ownedWorkflowLanes:lane.ownedWorkflowLanes}:{}})),validatedAt:isoNow()},admissionOutcome=reducePrReviewEvent(state2,{type:"base_admission_requested",batchId,lanes:record3.lanes,maxBatches:MAX_WORKFLOW_BATCHES,validatedAt:record3.validatedAt});if(admissionOutcome.status==="rejected")throw Error("BLOCKED: PR_REVIEW base batch limit reached");let nextState={...admissionOutcome.state,updatedAt:isoNow(),...requestedContractRetry?{prReviewContractRetryDimensions:[...state2.prReviewContractRetryDimensions??[],declaredBaseDimensions(normalizedLanes)[0]]}:{},...nextResilience?{prReviewResilience:nextResilience}:{}};return writeStateWhileLocked(directory,nextState)}async function rollbackPrReviewBaseAdmissionIfUnlaunched(directory,sessionID,batchId,contractRetry=!1){let normalizedSessionID=normalizeSessionID(sessionID),normalizedBatchId=normalizeBatchId(batchId);return withPrWorkflowCheckoutMutationLock(directory,async()=>withSessionStateMutation(directory,normalizedSessionID,async()=>{let state2=await readPrWorkflowGateState(directory,normalizedSessionID);if(!state2||state2.mode!=="PR_REVIEW")return!1;let batchRead=findByBatchIdDetailed(directory,normalizedBatchId,{parentSessionId:normalizedSessionID});if(batchRead.status==="uncertain")return warnDelegationReadUncertainOnce("base admission rollback existence guard",batchRead),!1;let batchRecords=batchRead.value,rollbackOutcome=reducePrReviewEvent(state2,{type:"base_admission_rolled_back",batchId:normalizedBatchId,batchDelegationRecordsExist:batchRecords.length>0});if(rollbackOutcome.status==="rejected")return!1;let rollbackState=rollbackOutcome.state,currentBaseDispatches=state2.prReviewBaseDispatches??[],nextBaseDispatches=rollbackState.prReviewBaseDispatches??[],rolledBackDimensions=new Set(currentBaseDispatches.at(-1)?.lanes.flatMap((lane)=>lane.ownedWorkflowLanes?.length?lane.ownedWorkflowLanes:[lane.workflowLane])??[]),nextContractRetryDimensions=contractRetry?(state2.prReviewContractRetryDimensions??[]).filter((dimension)=>!rolledBackDimensions.has(dimension)):state2.prReviewContractRetryDimensions,lastAttempt=state2.prReviewResilience?.attempts.at(-1),nextResilience=rollbackState.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 rolledBackCircuit=nextResilience?.circuit;if(rolledBackCircuit&&"version"in rolledBackCircuit&&rolledBackCircuit.state==="HALF_OPEN"&&rolledBackCircuit.probe?.batchId===normalizedBatchId){let probeOutcome=reducePrReviewEvent({...rollbackState,prReviewResilience:nextResilience},{type:"circuit_probe_settled",outcome:{result:"rolled_back_admission"},nowMs:_test_exports2.nowMs(),policy:{...nextResilience?.policy??snapshotPrReviewResiliencePolicy(),circuitOpenDurationMs:circuitOpenDurationMs(nextResilience?.policy??snapshotPrReviewResiliencePolicy())}});if(probeOutcome.status==="applied")nextResilience=probeOutcome.state.prReviewResilience??nextResilience}let shouldKeepResilience=nextBaseDispatches.length>0&&Boolean(nextResilience?.policy)||Boolean(nextResilience?.circuit)||(nextResilience?.attempts.length??0)>0;return await writeStateWhileLocked(directory,{...state2,updatedAt:isoNow(),prReviewBaseDispatches:nextBaseDispatches,...nextBaseDispatches.length>0?{prReviewBaseDispatch:nextBaseDispatches.at(-1)}:{prReviewBaseDispatch:void 0},...shouldKeepResilience?{prReviewResilience:nextResilience}:{prReviewResilience:void 0},...nextContractRetryDimensions?.length?{prReviewContractRetryDimensions:nextContractRetryDimensions}:{prReviewContractRetryDimensions:void 0}}),!0}))}function encodeConsolidatedLaneKey(owned){return[...new Set(owned)].sort().join("|")}function decodeConsolidatedLaneKey(key2){return key2.split("|").filter((dimension)=>dimension.length>0)}function minimumConsolidatedLaneCover(sets){let bitOf=new Map;for(let set3 of sets)for(let dimension of set3)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 set3 of sets){let mask=0,size=0;for(let dimension of set3){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(state2,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 state2.prReviewBaseDispatches??[])for(let lane of batch.lanes)considerLane(lane,!0);for(let key2 of state2.prReviewRetiredConsolidatedLanes??[])consider(decodeConsolidatedLaneKey(key2),!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,state2,normalizedLanes,revisionDigest){if((state2.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 digest3=revisionDigest;if(!digest3)digest3=(await createPrReviewGateContext2(directory,state2)).revisionDigest;let attempts=summarizePrReviewBaseDimensionAttempts(directory,state2,digest3),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(state2,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,state2,revisionDigest){try{let digest3=revisionDigest??(await createPrReviewGateContext2(directory,state2)).revisionDigest,before={candidate:derivePrReviewCandidateInventory2(directory,state2,{revisionDigest:digest3}),critic:derivePrReviewCriticInventory2(directory,state2,{revisionDigest:digest3})},pruned=pruneWorkflowBatches(directory,state2,digest3);if(!pruned)return state2;let after={candidate:derivePrReviewCandidateInventory2(directory,pruned,{revisionDigest:digest3}),critic:derivePrReviewCriticInventory2(directory,pruned,{revisionDigest:digest3})};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"),state2;let survivingBaseIds=new Set((pruned.prReviewBaseDispatches??[]).map((batch)=>batch.batchId));if(state2.prReviewBaseDispatch&&!survivingBaseIds.has(state2.prReviewBaseDispatch.batchId))return warn("PR_REVIEW batch GC aborted: the latest base dispatch pointer would have been orphaned"),state2;return pruned}catch(error93){return warn(`PR_REVIEW batch GC aborted: ${error93 instanceof Error?error93.message:String(error93)}`),state2}}function pruneWorkflowBatches(directory,state2,revisionDigest){let baseBatches=state2.prReviewBaseDispatches??[],validationBatches=state2.prReviewValidationBatches??[],ctx={revisionDigest},contributingBaseBatchIds=new Set;for(let batch of baseBatches){let successful2=successfulObligationsFromExactBatch2(directory,state2,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,state2,"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(state2.prReviewRetiredReviewerSessionIds??[]);for(let batch of validationBatches){if(batch.phase!=="reviewer")continue;if(survivingValidationIds.has(batch.batchId))continue;let batchRead=findByBatchIdDetailed(directory,batch.batchId,{parentSessionId:state2.sessionID});if(batchRead.status==="uncertain")return warnDelegationReadUncertainOnce("retired-reviewer session collection",batchRead),null;for(let record3 of batchRead.value){let subagentSessionId=record3.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(state2.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(state2.prReviewBatchCoherence??{}).filter(([batchId])=>survivingBatchIds.has(batchId)));return{...state2,...state2.prReviewBaseDispatches?{prReviewBaseDispatches:survivingBase}:{},...state2.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 admitPrReviewPartialBaseCoverage2(directory,sessionID,runId,unresolvedDimensions){return await admitPrReviewPartialBaseCoverage(directory,sessionID,runId,unresolvedDimensions)}async function assertPrReviewBaseCoverageSettled2(directory,sessionID,gateContext){let settled=await assertPrReviewBaseCoverageSettled(directory,sessionID,gateContext);return{state:settled.state,settlement:settled.settlement}}async function recordPrReviewMicroFamilyDispatch(directory,sessionID,lanes,options){let state2=await bindPrWorkflowHead(directory,sessionID,options.prHeadSha);if(state2.mode!=="PR_REVIEW")throw wrongModeError(state2,"PR_REVIEW");let batchId=normalizeBatchId(options.batchId),previous=state2.prReviewMicroFamilyDispatches??[];if(previous.some((record4)=>record4.batchId===batchId))return state2;if(previous.length>=MAX_WORKFLOW_BATCHES)throw Error(`BLOCKED: PR_REVIEW micro-family dispatch ledger limit reached (${MAX_WORKFLOW_BATCHES} recorded acknowledgments). Nothing was appended and no lane was launched, so re-issuing this dispatch call is safe once the ledger has room. A healthy run records at most ~33 acknowledgments (11 families x initial dispatch + 2 retries), so reaching the cap indicates a dispatch loop. Recovery: let the active workflow settle or restart with abort_pr_workflow (kind "recovery").`);let record3={batchId,prHeadSha:options.prHeadSha,lanes:normalizeWorkflowLanes(lanes).map((lane)=>({laneId:lane.laneId,workflowLane:lane.workflowLane,...lane.ownedWorkflowLanes?.length?{ownedWorkflowLanes:lane.ownedWorkflowLanes}:{}})),admittedAt:isoNow()},nextState={...state2,updatedAt:isoNow(),prReviewMicroFamilyDispatches:[...previous,record3]};return await persistState2(directory,nextState),nextState}async function recordPrReviewValidationBatch(directory,sessionID,phase,lanes,options){let state2=await bindPrWorkflowHead(directory,sessionID,options.prHeadSha);if(state2.mode!=="PR_REVIEW")throw wrongModeError(state2,"PR_REVIEW");if(!state2.prReviewTriggerEvalPath)throw Error("BLOCKED: PR_REVIEW validation dispatch requires a completed trigger evaluation");let ctx=await createPrReviewGateContext2(directory,state2);if(phase==="reviewer"&&(state2.prReviewValidationBatches??[]).some((batch)=>batch.phase==="council"))state2=await assertPrReviewValidationSettled(directory,sessionID,"council",ctx);else if(phase==="critic")state2=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"?derivePrReviewCandidateInventory2(directory,state2,ctx):derivePrReviewCriticInventory2(directory,state2,ctx),assertStringSetSubset(assigned,validatedInventory,`PR_REVIEW ${phase} ownership`)}let batchId=normalizeBatchId(options.batchId),previous=state2.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(state2=await prunePrWorkflowBatchesForCapacity(directory,state2,ctx.revisionDigest),previous=state2.prReviewValidationBatches??[],previous.length>=MAX_WORKFLOW_BATCHES)throw Error("BLOCKED: PR_REVIEW validation batch limit reached")}let record3={batchId,phase,lanes:normalizedLanes,validatedAt:isoNow()},reviewerItemBindings=phase==="critic"?criticReviewerItemBindings(directory,state2,normalizedLanes,ctx):void 0,retained=phase==="reviewer"?previous.filter((batch)=>batch.phase!=="critic"||Boolean(state2.prReviewBatchCoherence?.[batch.batchId]?.reviewerItemBindings)):previous,retainedIds=new Set(retained.map((batch)=>batch.batchId)),coherence=Object.fromEntries(Object.entries(state2.prReviewBatchCoherence??{}).filter(([id])=>retainedIds.has(id)));if(validatedInventory)coherence[batchId]={validatedInventory,...reviewerItemBindings?{reviewerItemBindings,reviewerItemBindingKeyEncoding:"prefixed-v1"}:{}};let nextState={...state2,updatedAt:isoNow(),prReviewValidationBatches:[...retained,record3],prReviewBatchCoherence:Object.keys(coherence).length>0?coherence:void 0};return await persistState2(directory,nextState),nextState}async function assertPrReviewValidationSettled(directory,sessionID,phase,gateContext){let state2=await requireBoundState2(directory,sessionID,"PR_REVIEW"),stateOut=state2,ctx=gateContext??await createPrReviewGateContext2(directory,state2),declaredPhases=new Set((state2.prReviewValidationBatches??[]).map((batch)=>batch.phase)),phases=phase?[phase]:["council","reviewer","critic"].filter((candidate)=>declaredPhases.has(candidate));for(let requiredPhase of phases){let validationBatches=state2.prReviewValidationBatches??[],batches=requiredPhase==="council"?validationBatches.filter((batch)=>batch.phase==="council"):prReviewPhaseWindow2(state2,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 successfulObligationsFromExactBatch2(directory,state2,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,state2,requiredPhase,ctx);if(composed.unclaimed.length>0){let boundPrHeadSha=state2.prHeadSha;if(!boundPrHeadSha)throw Error("BLOCKED: PR_REVIEW settlement requires a bound PR head SHA");let admission=deriveVerdictSettlementAdmission({directory,prHeadSha:boundPrHeadSha,phase:requiredPhase,window:prReviewPhaseWindow2(state2,requiredPhase),unclaimed:composed.unclaimed,parentSessionId:state2.sessionID});if(!admission.admitted){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(" | ")}`:"")+`; N-of-M settlement not admissible (${admission.reason}); re-dispatch the unclaimed items to exhaust the retry budget with controller-observed liveness evidence, or complete downgrade-only once admissible`)}let runId=state2.prReviewArtifactRunId??state2.prReviewReservedRunId;if(!runId)throw Error(`BLOCKED: PR_REVIEW ${requiredPhase} N-of-M settlement requires a reserved pr-review run id to persist its disclosure receipt`);let receipt=buildVerdictSettlementReceipt({runId,prHeadSha:boundPrHeadSha,revisionDigest:ctx.revisionDigest,phase:requiredPhase,items:admission.items});await persistVerdictSettlementReceipt(directory,receipt);let persistedRead=readVerdictSettlementReceipt(directory,runId,requiredPhase);if(persistedRead.status!=="ok")throw Error(`BLOCKED: PR_REVIEW ${requiredPhase} verdict-settlement receipt failed to persist as a readable bounded file (${persistedRead.status})`);if(stateOut.prReviewVerdictSettlementDigests?.[requiredPhase]!==persistedRead.rawSha256){let settledState={...stateOut,updatedAt:isoNow(),prReviewVerdictSettlementDigests:{...stateOut.prReviewVerdictSettlementDigests??{},[requiredPhase]:persistedRead.rawSha256}};await persistState2(directory,settledState),stateOut=settledState}warn(`PR_REVIEW ${requiredPhase} settled N-of-M over ${composed.claims.size} claimed item(s); ${admission.items.length} liveness-dead item(s) disclosed in the verdict-settlement receipt`)}if(assertSettledPhaseHasAuthoritativeVerdicts(requiredPhase,composed,requiredPhase==="reviewer"?deriveLatestPrReviewReviewerVerdicts(directory,state2,ctx):deriveLatestPrReviewCriticVerdicts(directory,state2,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 stateOut}async function declarePrFeedbackInventory(directory,sessionID,inventoryIds,options){let state2=await bindPrWorkflowHead(directory,sessionID,options.prHeadSha);if(state2.mode!=="PR_FEEDBACK")throw wrongModeError(state2,"PR_FEEDBACK");let normalizedInventory=normalizeInventoryIds(inventoryIds),requiredHandoffIds=state2.prFeedbackReviewHandoff?.findingIds??[],inventorySet=new Set(normalizedInventory),missingHandoffIds=requiredHandoffIds.filter((findingId2)=>!inventorySet.has(findingId2));if(missingHandoffIds.length>0)throw Error(`BLOCKED: PR_FEEDBACK inventory must include every continued review finding: ${missingHandoffIds.join(", ")}`);if(state2.prFeedbackInventory){let existing=state2.prFeedbackInventory;if(sameStringArray(existing,normalizedInventory))return state2;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=state2.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={...state2,updatedAt:amendedAt,prFeedbackInventory:normalizedInventory,prFeedbackInventoryAmendments:[...previousAmendments,...appendedIds.map((entry)=>({entry,amendedAt,batch}))],prFeedbackReadyToPublish:void 0},superseded=supersedeLivePublicationInPendingState(amendedState,"inventory-amended");if(await persistState2(directory,superseded.state),superseded.invalidationEvent)appendPublicationEvent(directory,superseded.invalidationEvent);return superseded.state}let nextState={...state2,updatedAt:isoNow(),prFeedbackInventory:normalizedInventory,prFeedbackVerifications:[]};return await persistState2(directory,nextState),nextState}async function prunePrFeedbackVerificationsForCapacity(directory,state2){try{let digest3=await currentPrFeedbackRevisionDigest(directory,state2),batches=state2.prFeedbackVerifications??[],before=prFeedbackCoveredItems(directory,state2,digest3),newestBatchId=batches.at(-1)?.batchId,surviving=batches.filter((batch)=>batch.batchId===newestBatchId||prFeedbackBatchCoveredItems(directory,state2,batch,digest3).size>0);if(surviving.length===batches.length)return state2;let retiredItemOwnership={...state2.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"),state2;let pruned={...state2,prFeedbackVerifications:surviving,prFeedbackRetiredItemOwnership:Object.keys(retiredItemOwnership).length>0?retiredItemOwnership:void 0},after=prFeedbackCoveredItems(directory,pruned,digest3);if(!sameStringSet([...before],[...after]))return warn("PR_FEEDBACK verification GC aborted: pruning would have changed the covered inventory; every batch was kept"),state2;if(state2.prFeedbackVerification&&!survivingIds.has(state2.prFeedbackVerification.batchId))return warn("PR_FEEDBACK verification GC aborted: the latest verification pointer would have been orphaned"),state2;return pruned}catch(error93){return warn(`PR_FEEDBACK verification GC aborted: ${error93 instanceof Error?error93.message:String(error93)}`),state2}}async function enforcePrFeedbackVerificationOwnership(directory,sessionID,ownership,options){let state2=await bindPrWorkflowHead(directory,sessionID,options.prHeadSha);if(state2.mode!=="PR_FEEDBACK")throw wrongModeError(state2,"PR_FEEDBACK");let inventory=state2.prFeedbackInventory;if(!inventory||inventory.length===0)throw Error(`BLOCKED: PR_FEEDBACK verification for session "${state2.sessionID}" requires a declared feedback inventory before dispatch`);let normalizedOwnership=normalizeOwnership(ownership),inventorySet=new Set(inventory),claimedByItemId=new Map,previous=state2.prFeedbackVerifications??[],batchId=normalizeBatchId(options.batchId);if(previous.some((record4)=>record4.batchId===batchId))throw Error(`BLOCKED: PR_FEEDBACK verification batch id "${batchId}" is already recorded`);if(previous.length>=MAX_WORKFLOW_BATCHES){if(state2=await prunePrFeedbackVerificationsForCapacity(directory,state2),previous=state2.prFeedbackVerifications??[],previous.length>=MAX_WORKFLOW_BATCHES)throw Error("BLOCKED: PR_FEEDBACK verification batch limit reached")}for(let[itemId,laneId]of Object.entries(state2.prFeedbackRetiredItemOwnership??{}))claimedByItemId.set(itemId,laneId);for(let record4 of previous)for(let lane of record4.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 record3={batchId,ownership:normalizedOwnership,validatedAt:isoNow()},nextState={...state2,updatedAt:isoNow(),prFeedbackVerifications:[...previous,record3],prFeedbackVerification:record3};return await persistState2(directory,nextState),nextState}function prFeedbackBatchCoveredItems(directory,state2,batch,currentDigest){let covered=new Set,successfulLaneIds=successfulObligationsFromExactBatch2(directory,state2,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(!legacyFeedbackArtifactCoversItems(directory,state2,batch.batchId,lane.laneId,lane.ownedItemIds))continue;for(let itemId of lane.ownedItemIds)covered.add(itemId)}return covered}function prFeedbackCoveredItems(directory,state2,currentDigest){let covered=new Set;for(let batch of state2.prFeedbackVerifications??[])for(let itemId of prFeedbackBatchCoveredItems(directory,state2,batch,currentDigest))covered.add(itemId);return covered}async function assertPrFeedbackVerificationSettledState(directory,state2){if(state2.mode!=="PR_FEEDBACK")throw wrongModeError(state2,"PR_FEEDBACK");let currentDigest=await currentPrFeedbackRevisionDigest(directory,state2),inventory=state2.prFeedbackInventory,batches=state2.prFeedbackVerifications??[];if(!inventory||batches.length===0)throw Error("BLOCKED: PR_FEEDBACK requires an immutable inventory and verification batches");let covered=prFeedbackCoveredItems(directory,state2,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 currentDigest}async function assertPrFeedbackVerificationSettled(directory,sessionID){let state2=await requireBoundState2(directory,sessionID,"PR_FEEDBACK");return await assertPrFeedbackVerificationSettledState(directory,state2),state2}async function recordPrFeedbackStageA(directory,sessionID,revisionDigest,checks5,options={}){let state2=await assertPrFeedbackVerificationSettled(directory,sessionID),currentDigest=await currentPrFeedbackRevisionDigest(directory,state2);if(revisionDigest!==currentDigest)throw Error("BLOCKED: PR_FEEDBACK Stage A receipt is stale because the working-tree revision changed during validation");if(checks5.length<2||checks5.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)=>checks5.some((check3)=>check3.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 required3=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 check3 of checks5){if(["diff-check","reproduction"].includes(check3.category)&&singletonSeen.has(check3.category))throw Error(`BLOCKED: PR_FEEDBACK Stage A contains duplicate category "${check3.category}"`);if(singletonSeen.add(check3.category),required3.delete(check3.category),check3.obligationId){let obligation=applicableObligations.find((candidate)=>candidate.id===check3.obligationId);if(!obligation||obligation.category!==check3.category||obligation.workingDirectory!==(check3.workingDirectory??".")||!requiredObligationIds.delete(check3.obligationId))throw Error(`BLOCKED: PR_FEEDBACK Stage A receipt does not match one exact applicable obligation: ${check3.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&&(check3.validatorContract?.path!==requiredContract.path||check3.validatorContract.id!==requiredContract.id))throw Error(`BLOCKED: PR_FEEDBACK Stage A obligation ${obligation.id} requires exact validator contract provenance`)}let commandDigest=createHash59("sha256").update(`${check3.obligationId??check3.category}\x00${check3.workingDirectory??"."}\x00${check3.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),check3.category==="diff-check"&&!sameStringArray(check3.command,["git","diff","--check"]))throw Error("BLOCKED: PR_FEEDBACK Stage A diff-check receipt is not the exact git diff --check command");if(check3.category==="reproduction"&&(!check3.targets?.length||!check3.feedbackTargets?.length||check3.targets.some((target)=>!check3.command.join(" ").includes(target))))throw Error("BLOCKED: PR_FEEDBACK Stage A reproduction receipt requires exact selected targets");if(check3.category==="reproduction"){if(reproductionFeedbackItemIds=check3.feedbackTargets.map((mapping)=>mapping.feedbackItemId),assertNoDuplicates(reproductionFeedbackItemIds,"PR_FEEDBACK Stage A reproduction feedback item mappings"),check3.feedbackTargets.some((mapping)=>!check3.targets.includes(mapping.target)))throw Error("BLOCKED: PR_FEEDBACK Stage A feedback mappings must reference exact executed reproduction targets")}}if(required3.size>0)throw Error(`BLOCKED: PR_FEEDBACK Stage A is missing required checks: ${[...required3].join(", ")}`);if(requiredObligationIds.size>0)throw Error(`BLOCKED: PR_FEEDBACK Stage A is missing applicable workspace obligations: ${[...requiredObligationIds].join(", ")}`);if(!sameStringArray(reproductionFeedbackItemIds,state2.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(state2.prFeedbackStageA,{revisionDigest:currentDigest,applicableCategories:normalizedCategories,applicableObligations}),nextState={...state2,updatedAt:isoNow(),prFeedbackStageA:{revisionDigest:currentDigest,checks:[...checks5],feedbackItemIds:reproductionFeedbackItemIds,applicableCategories:normalizedCategories,applicableObligations,validatedAt:isoNow()},prFeedbackGateBatches:retainsGateBatches?[...state2.prFeedbackGateBatches??[]]:[],prFeedbackReadyToPublish:void 0},superseded=supersedeLivePublicationInPendingState(nextState,"stage-a-rerun");if(await persistState2(directory,superseded.state),superseded.invalidationEvent)appendPublicationEvent(directory,superseded.invalidationEvent);return superseded.state}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 state2=await bindPrWorkflowHead(directory,sessionID,options.prHeadSha);if(state2.mode!=="PR_FEEDBACK")throw wrongModeError(state2,"PR_FEEDBACK");let inventory=state2.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)state2=await assertPrFeedbackGatePhaseSettled(directory,sessionID,prerequisite);let{prFeedbackStageA:stageA,prFeedbackInventory:refreshedInventory}=state2,currentDigest=await currentPrFeedbackRevisionDigest(directory,state2);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=state2.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),record3={batchId,phase,laneId:normalized.laneId,itemIds:normalized.ownedItemIds,revisionDigest:currentDigest,validatedAt:isoNow()},nextState={...state2,updatedAt:isoNow(),prFeedbackGateBatches:[...retained,record3]};return await persistState2(directory,nextState),nextState}async function assertPrFeedbackGatePhaseSettled(directory,sessionID,phase){let state2=await requireBoundState2(directory,sessionID,"PR_FEEDBACK"),currentDigest=await currentPrFeedbackRevisionDigest(directory,state2);if(state2.prFeedbackStageA?.revisionDigest!==currentDigest)throw Error(`BLOCKED: PR_FEEDBACK ${phase} cannot use stale Stage A evidence`);if(!sameStringArray(state2.prFeedbackStageA?.feedbackItemIds??[],state2.prFeedbackInventory??[]))throw Error(`BLOCKED: PR_FEEDBACK ${phase} Stage A reproduction is not bound to the exact immutable feedback inventory`);let batch=[...state2.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,state2.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(!successfulObligationsFromExactBatch2(directory,state2,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`);let batchRead=findByBatchIdDetailed(directory,batch.batchId,{parentSessionId:state2.sessionID});if(batchRead.status==="uncertain")throw Error(`BLOCKED: PR_FEEDBACK ${phase} gate cannot be validated: the delegation store is unreadable after ${batchRead.attempts} attempts (${batchRead.reason}); the batch's durable child record is UNKNOWN, not absent. Restore the store and re-validate.`);if(batchRead.value.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,state2,phase),state2}function assertIndependentFeedbackGateSessions(directory,state2,throughPhase){let throughIndex=PR_FEEDBACK_PHASE_ORDER.indexOf(throughPhase),batches=(state2.prFeedbackGateBatches??[]).filter((batch)=>PR_FEEDBACK_PHASE_ORDER.indexOf(batch.phase)<=throughIndex),seenSessions=new Set;for(let batch of batches){let batchRead=findByBatchIdDetailed(directory,batch.batchId,{parentSessionId:state2.sessionID});if(batchRead.status==="uncertain")throw Error(`BLOCKED: PR_FEEDBACK ${batch.phase} cannot be validated: the delegation store is unreadable after ${batchRead.attempts} attempts (${batchRead.reason}); the batch's durable child session is UNKNOWN, not absent. Restore the store and re-validate.`);let matching=batchRead.value.filter((record4)=>record4.laneId===batch.laneId);if(matching.length!==1)throw Error(`BLOCKED: PR_FEEDBACK ${batch.phase} must resolve from exactly one durable child session`);let record3=matching[0],expectedRole=PR_FEEDBACK_PHASE_ROLE[batch.phase];if(!(record3.normalizedAgent===expectedRole||expectedRole==="critic"&&record3.normalizedAgent.startsWith("critic_")))throw Error(`BLOCKED: PR_FEEDBACK ${batch.phase} requires role ${expectedRole}, received ${record3.normalizedAgent||"(unknown)"}`);if(seenSessions.has(record3.subagentSessionId))throw Error(`BLOCKED: PR_FEEDBACK independent phases reused child session "${record3.subagentSessionId}"`);seenSessions.add(record3.subagentSessionId)}}async function assertPrFeedbackReadyToPublish(directory,sessionID){let state2=await assertPrFeedbackVerificationSettled(directory,sessionID);for(let phase of PR_FEEDBACK_PHASE_ORDER)state2=await assertPrFeedbackGatePhaseSettled(directory,sessionID,phase);return state2}function deriveReadyToPublishMirror(active){if(!active||active.state!=="armed"&&active.state!=="push_in_flight")return;return{revisionDigest:active.revisionDigest,localHead:active.localHead,remoteName:active.remoteName,remoteBranchRef:active.remoteBranchRef,remoteRef:active.remoteRef,validatedAt:active.armedAt??active.createdAt}}async function verifyPublicationIdentityComponent(directory,state2,active,component){switch(component){case"digest":try{let digest3=await currentPrFeedbackRevisionDigest(directory,state2);return digest3===active.revisionDigest?{kind:"intact"}:{kind:"drift",component,detail:`approved revision digest ${active.revisionDigest} vs current ${digest3}`}}catch(error93){return{kind:"unresolvable",component,detail:String(error93?.message??error93)}}case"head":{let head=(await _test_exports2.resolveCurrentGitHeadAsync(directory))?.trim();if(!head)return{kind:"unresolvable",component,detail:"HEAD resolution returned empty"};return head===active.localHead?{kind:"intact"}:{kind:"drift",component,detail:`approved head ${active.localHead} vs current ${head}`}}case"worktree":{let clean=await _test_exports2.resolveIsWorkingTreeCleanAsync(directory);if(clean!==!0&&clean!==!1)return{kind:"unresolvable",component,detail:"clean-status resolution failed"};return clean===!0?{kind:"intact"}:{kind:"drift",component,detail:"working tree or index is dirty"}}case"upstream":{let target=await _test_exports2.resolveCurrentUpstreamPushTargetAsync(directory);if(!target)return{kind:"unresolvable",component,detail:"upstream target resolution returned empty"};return target.remoteName===active.remoteName&&target.remoteBranchRef===active.remoteBranchRef&&target.remoteTrackingRef===active.remoteRef?{kind:"intact"}:{kind:"drift",component,detail:`approved target ${active.remoteName}/${active.remoteBranchRef}/${active.remoteRef} vs current ${target.remoteName}/${target.remoteBranchRef}/${target.remoteTrackingRef}`}}case"remote-url":{if(!active.remoteUrlIdentity)return{kind:"unresolvable",component,detail:"armed generation carries no remote URL identity"};let url3=await _test_exports2.resolveRemoteUrlIdentityAsync(directory,active.remoteName);if(!url3)return{kind:"unresolvable",component,detail:`remote "${active.remoteName}" URL could not be resolved`};return url3===active.remoteUrlIdentity?{kind:"intact"}:{kind:"drift",component,detail:`approved remote URL identity ${active.remoteUrlIdentity} vs current ${url3}`}}case"workspace-identity":{let identity=canonicalWorkspaceIdentity(directory);if(!identity)return{kind:"unresolvable",component,detail:"canonical workspace identity could not be resolved"};return identity===active.workspaceIdentity?{kind:"intact"}:{kind:"drift",component,detail:"generation is bound to a different workspace"}}case"evidence-join":return publicationEvidenceJoinIntact(state2,active)?{kind:"intact"}:{kind:"drift",component,detail:"the receipt set recorded at arming is no longer the active one"};default:return{kind:"unresolvable",component,detail:"unknown component"}}}async function checkPublicationIdentity(directory,state2,active){for(let component of PUBLICATION_IDENTITY_COMPONENTS){let check3=await verifyPublicationIdentityComponent(directory,state2,active,component);if(check3.kind!=="intact")return check3}if(!publicationEvidenceJoinIntact(state2,active))return{kind:"drift",component:"evidence-join",detail:"the receipt set recorded at arming is no longer the active one"};return{kind:"intact"}}function publicationEvidenceJoinIntact(state2,active){if(state2.prFeedbackStageA?.validatedAt!==active.evidence.stageAValidatedAt)return!1;for(let join92 of active.evidence.batches){let batch=[...state2.prFeedbackGateBatches??[]].reverse().find((candidate)=>candidate.phase===join92.phase);if(!batch||batch.batchId!==join92.batchId||batch.laneId!==join92.laneId)return!1}return!0}function buildPublicationEvidenceJoin(state2,currentDigest){let stageA=state2.prFeedbackStageA;if(!stageA||stageA.revisionDigest!==currentDigest||!stageA.validatedAt)return null;let batches=[];for(let phase of PR_FEEDBACK_PHASE_ORDER){let batch=[...state2.prFeedbackGateBatches??[]].reverse().find((candidate)=>candidate.phase===phase&&candidate.revisionDigest===currentDigest);if(!batch)return null;batches.push({phase,batchId:batch.batchId,laneId:batch.laneId})}return{stageAValidatedAt:stageA.validatedAt,batches}}function appendPublicationEvent(directory,event){try{appendCoreEventSync(directory,{...event,timestamp:isoNow()})}catch{}}function boundPublicationDiagnostic(text){let redacted=redactSecrets(text).replace(PUBLICATION_URL_CREDENTIALS_PATTERN,"$1[REDACTED:url_credentials]@");return redacted.length>MAX_PUSH_ATTEMPT_DIAGNOSTIC_CHARS?`${redacted.slice(0,MAX_PUSH_ATTEMPT_DIAGNOSTIC_CHARS-3)}...`:redacted}function nextPublicationContainer(previous,active,historyAppends=[],attempts=[]){let history=[...previous?.history??[],...historyAppends].slice(-MAX_PUBLICATION_HISTORY_GENERATIONS);return{schemaVersion:PUBLICATION_SCHEMA_VERSION,active,history,attempts:attempts.slice(-MAX_PUBLICATION_ATTEMPTS)}}async function invalidatePublicationGeneration(directory,sessionID,reason,options={}){let normalizedSessionID=normalizeSessionID(sessionID);return withSessionStateMutation(directory,normalizedSessionID,async()=>{let state2=await readPrWorkflowGateStateFromDisk3(directory,normalizedSessionID);if(!state2||state2.mode!=="PR_FEEDBACK")throw Error("BLOCKED: PR_FEEDBACK publication invalidation requires an active PR_FEEDBACK gate");return applyPublicationInvalidationWhileLocked(directory,state2,reason,options)})}async function applyPublicationInvalidationWhileLocked(directory,state2,reason,options={}){{let active=state2.prFeedbackPublication?.active,legacyRecord=active?void 0:state2.prFeedbackReadyToPublish;if(!active&&!legacyRecord)throw Error("BLOCKED: no armed publication generation to invalidate");if(active&&active.state!=="armed"&&active.state!=="push_in_flight")throw Error(`BLOCKED: publication generation ${active.generation} is already ${active.state}`);if(options.driftReverification&&options.drift&&active){let recheck=await verifyPublicationIdentityComponent(directory,state2,active,options.drift.component);if(recheck.kind!=="drift")throw Error(`BLOCKED: PR_FEEDBACK publication drift on ${options.drift.component} did not re-confirm under the state lock (${recheck.kind}); no invalidation was recorded — retry from current state`);options.drift={component:recheck.component,detail:recheck.detail}}let now=isoNow(),attempts=(state2.prFeedbackPublication?.attempts??[]).map((attempt)=>attempt.result?attempt:{...attempt,result:{outcome:options.finalizeInFlightAs??"uncertain",exitStatus:"not-observed",diagnostic:`finalized by publication invalidation (${reason})`,postPush:{localHead:null,observedRemoteHead:null},completedAt:now}}),invalidated;if(active)invalidated={...active,state:"invalidated",invalidatedAt:now,invalidationReason:reason};else if(legacyRecord)invalidated={schemaVersion:PUBLICATION_SCHEMA_VERSION,generation:1,state:"invalidated",workspaceIdentity:canonicalWorkspaceIdentity(directory)??"unresolvable",sessionID:state2.sessionID,intakeHeadSha:state2.prHeadSha??"unknown",localHeadRef:"unknown",localHead:legacyRecord.localHead,remoteName:legacyRecord.remoteName,remoteUrlIdentity:void 0,remoteBranchRef:legacyRecord.remoteBranchRef,remoteRef:legacyRecord.remoteRef,revisionDigest:legacyRecord.revisionDigest,evidence:{stageAValidatedAt:state2.prFeedbackStageA?.validatedAt??"unknown",batches:(state2.prFeedbackGateBatches??[]).map((batch)=>({phase:batch.phase,batchId:batch.batchId,laneId:batch.laneId}))},invalidationReason:reason,createdAt:legacyRecord.validatedAt,armedAt:legacyRecord.validatedAt,invalidatedAt:now};else throw Error("BLOCKED: no armed publication generation to invalidate");if(!active)attempts=[];let nextState={...state2,updatedAt:now,prFeedbackStageA:void 0,prFeedbackVerifications:void 0,prFeedbackGateBatches:void 0,prFeedbackScopes:void 0,prFeedbackReadyToPublish:void 0,prFeedbackPublication:nextPublicationContainer(state2.prFeedbackPublication,invalidated,[],attempts)};return await writeStateWhileLocked(directory,nextState),appendPublicationEvent(directory,{type:"pr_feedback_publication_invalidated",sessionID:state2.sessionID,generation:invalidated.generation,reason,previousState:active?.state??"armed",drift:options.drift??null,revisionDigest:invalidated.revisionDigest,localHead:invalidated.localHead,remoteName:invalidated.remoteName,remoteBranchRef:invalidated.remoteBranchRef,supersededBatchIds:invalidated.evidence.batches.map((b)=>b.batchId)}),{generation:invalidated,state:nextState}}}async function ensurePublicationGenerationCurrent(directory,sessionID){let normalizedSessionID=normalizeSessionID(sessionID),state2=await readPrWorkflowGateState(directory,normalizedSessionID);if(!state2||state2.mode!=="PR_FEEDBACK")return state2;if(state2.prFeedbackPublication||!state2.prFeedbackReadyToPublish)return state2;let legacy=state2.prFeedbackReadyToPublish;return withSessionStateMutation(directory,normalizedSessionID,async()=>{let locked=await readPrWorkflowGateStateFromDisk3(directory,normalizedSessionID);if(!locked||locked.mode!=="PR_FEEDBACK")return locked??state2;if(locked.prFeedbackPublication||!locked.prFeedbackReadyToPublish)return locked;let now=isoNow(),base={schemaVersion:PUBLICATION_SCHEMA_VERSION,generation:1,sessionID:locked.sessionID,prTargetUrl:locked.prFeedbackTargetUrl,intakeHeadSha:locked.prHeadSha??"unknown",revisionDigest:legacy.revisionDigest,evidence:buildPublicationEvidenceJoin(locked,legacy.revisionDigest)??{stageAValidatedAt:"unknown",batches:[]},createdAt:legacy.validatedAt,armedAt:legacy.validatedAt},mismatch=async(reason)=>{let invalidated={...base,evidence:base.evidence.batches.length>0?base.evidence:{stageAValidatedAt:locked.prFeedbackStageA?.validatedAt??"unknown",batches:(locked.prFeedbackGateBatches??[]).map((batch)=>({phase:batch.phase,batchId:batch.batchId,laneId:batch.laneId}))},state:"invalidated",workspaceIdentity:canonicalWorkspaceIdentity(directory)??"unresolvable",localHeadRef:"unknown",localHead:legacy.localHead,remoteName:legacy.remoteName,remoteUrlIdentity:void 0,remoteBranchRef:legacy.remoteBranchRef,remoteRef:legacy.remoteRef,invalidationReason:reason,invalidatedAt:now},nextState2={...locked,updatedAt:now,prFeedbackStageA:void 0,prFeedbackVerifications:void 0,prFeedbackGateBatches:void 0,prFeedbackScopes:void 0,prFeedbackReadyToPublish:void 0,prFeedbackPublication:nextPublicationContainer(locked.prFeedbackPublication,invalidated)};return await writeStateWhileLocked(directory,nextState2),appendPublicationEvent(directory,{type:"pr_feedback_publication_migrated",sessionID:locked.sessionID,generation:1,outcome:"invalidated",reason}),nextState2};if(locked.prFeedbackStageA?.revisionDigest!==legacy.revisionDigest||!(locked.prFeedbackGateBatches??[]).some((batch)=>batch.revisionDigest===legacy.revisionDigest))return mismatch("legacy-migration-receipt-mismatch");let workspaceIdentity=canonicalWorkspaceIdentity(directory);if(!workspaceIdentity)return mismatch("legacy-migration-unresolvable");let digest3;try{digest3=await currentPrFeedbackRevisionDigest(directory,locked)}catch{return mismatch("legacy-migration-unresolvable")}let head=(await _test_exports2.resolveCurrentGitHeadAsync(directory))?.trim(),target=await _test_exports2.resolveCurrentUpstreamPushTargetAsync(directory),localHeadRef=await resolveCurrentLocalHeadRefAsync(directory),remoteUrlIdentity=await _test_exports2.resolveRemoteUrlIdentityAsync(directory,legacy.remoteName);if(digest3!==legacy.revisionDigest||head!==legacy.localHead||!target||target.remoteName!==legacy.remoteName||target.remoteBranchRef!==legacy.remoteBranchRef||target.remoteTrackingRef!==legacy.remoteRef||!localHeadRef||!remoteUrlIdentity)return mismatch("legacy-migration-identity-mismatch");let evidenceJoin=buildPublicationEvidenceJoin(locked,legacy.revisionDigest);if(!evidenceJoin)return mismatch("legacy-migration-receipt-mismatch");let upgraded={...base,evidence:evidenceJoin,state:"armed",workspaceIdentity,localHeadRef,localHead:legacy.localHead,remoteName:legacy.remoteName,remoteUrlIdentity,remoteBranchRef:legacy.remoteBranchRef,remoteRef:legacy.remoteRef},nextState={...locked,updatedAt:now,prFeedbackPublication:nextPublicationContainer(locked.prFeedbackPublication,upgraded)};return await writeStateWhileLocked(directory,nextState),appendPublicationEvent(directory,{type:"pr_feedback_publication_migrated",sessionID:locked.sessionID,generation:1,outcome:"armed",reason:"legacy-record-proven-equivalent"}),nextState})}async function reconcileForeignInFlightAttempt(directory,sessionID,currentCallId){let normalizedSessionID=normalizeSessionID(sessionID);return withSessionStateMutation(directory,normalizedSessionID,async()=>{let state2=await readPrWorkflowGateStateFromDisk3(directory,normalizedSessionID),publication=state2?.prFeedbackPublication,active=publication?.active;if(!state2||!publication||!active||active.state!=="push_in_flight"||!publication.attempts.some((attempt)=>!attempt.result))return state2;let now=isoNow(),localHead=(await _test_exports2.resolveCurrentGitHeadAsync(directory))?.trim(),observedRemoteHead=await _test_exports2.resolveExactRemoteBranchHeadAsync(directory,active.remoteName,active.remoteBranchRef),attempts=publication.attempts.map((attempt)=>attempt.result?attempt:{...attempt,result:{outcome:"uncertain",exitStatus:"not-observed",diagnostic:boundPublicationDiagnostic(`recovered without an observed result${currentCallId&&attempt.callID===currentCallId?" (same call)":""}`),postPush:{localHead:localHead??null,observedRemoteHead},completedAt:now}}),nextState={...state2,updatedAt:now,prFeedbackPublication:nextPublicationContainer(publication,{...active,state:"armed"},[],attempts)};return await writeStateWhileLocked(directory,nextState),appendPublicationEvent(directory,{type:"pr_feedback_push_attempt_result",sessionID:state2.sessionID,generation:active.generation,outcome:"uncertain",by:"reaper",observedRemoteHead}),nextState})}async function invalidatePrFeedbackPublication(directory,sessionID,reason){let trimmed=reason.trim();if(!trimmed)throw Error("BLOCKED: invalidate_pr_feedback_publication requires a non-empty reason; the reason is part of the durable audit trail");return await ensurePublicationGenerationCurrent(directory,sessionID),await reconcileForeignInFlightAttempt(directory,sessionID),(await invalidatePublicationGeneration(directory,sessionID,`controller-rework:${trimmed}`)).generation}function describePrWorkflowPublicationSection(state2){let active=state2.prFeedbackPublication?.active,history=state2.prFeedbackPublication?.history??[],attempts=state2.prFeedbackPublication?.attempts??[];if(!active&&!state2.prFeedbackReadyToPublish&&history.length===0)return null;let lines=[];if(state2.prFeedbackReadyToPublish&&!active)lines.push("publication: legacy armed record awaiting generation migration (fail-closed until the next gated interaction migrates it)");if(active){if(lines.push(`publication: generation ${active.generation} state=${active.state}`),lines.push(` approved: ${active.localHead} -> ${active.remoteName} ${active.remoteBranchRef} (digest ${active.revisionDigest.slice(0,12)}…)`),active.remoteUrlIdentity)lines.push(` remote url identity: ${active.remoteUrlIdentity}`);if(active.state==="invalidated"&&active.invalidationReason)lines.push(` invalidated because: ${active.invalidationReason}`);if(active.supersededByGeneration)lines.push(` superseded by generation ${active.supersededByGeneration}`);let generationAttempts=attempts.filter((attempt)=>attempt.generation===active.generation);if(generationAttempts.length>0){let outcomes=generationAttempts.map((attempt)=>attempt.result?.outcome??"in-flight");lines.push(` push attempts: ${generationAttempts.length} (${outcomes.join(", ")})`)}switch(active.state){case"armed":lines.push(" next: run the exact approved push, then complete_pr_workflow");break;case"push_in_flight":lines.push(" next: a push attempt is in flight; the next gated interaction reconciles it (uncertain) and re-verifies the remote before any retry");break;case"invalidated":lines.push(" next: rerun Stage A and every independent gate on the corrected content, then arm a fresh generation with complete_pr_workflow; the exact scoped rework path reopens via prepare_pr_feedback_scope");break;case"published":lines.push(" terminal: published (verified remote head)");break;case"cancelled_without_publication":lines.push(" terminal: cancelled without publication");break;default:lines.push(" next: continue the ordered gates")}}if(history.length>0){let summary=history.map((generation)=>`gen ${generation.generation}: ${generation.state}${generation.supersededByGeneration?` -> ${generation.supersededByGeneration}`:""}`).join("; ");lines.push(` superseded generations: ${summary}`)}return lines.push(" audit: full publication trail in the .swarm events store (pr_feedback_publication_*, pr_feedback_push_attempt_*, pr_feedback_published)"),lines.join(`
|
|
1290
1290
|
`)}function findDanglingLivePublicationGeneration(directory,sessionID){let text;try{text=readCoreEvents(directory).text}catch{return null}if(!text.trim())return null;let dangling=null;for(let line of text.split(`
|
|
1291
1291
|
`)){if(!line.trim())continue;let event;try{event=JSON.parse(line)}catch{continue}if(typeof event.type!=="string"||!PUBLICATION_EVENT_TYPES.has(event.type)||event.sessionID!==sessionID)continue;let generation=typeof event.generation==="number"?event.generation:null;switch(event.type){case"pr_feedback_publication_armed":case"pr_feedback_push_attempt_started":dangling=generation?{generation}:dangling;break;case"pr_feedback_publication_migrated":if(event.outcome==="armed")dangling=generation?{generation}:dangling;else dangling=null;break;default:dangling=null;break}}return dangling}function supersedeLivePublicationInPendingState(pending,reason){let publication=pending.prFeedbackPublication,active=publication?.active;if(!(pending.prFeedbackReadyToPublish!=null||active?.state==="armed"||active?.state==="push_in_flight"))return{state:pending,invalidationEvent:null};let now=isoNow(),attempts=(publication?.attempts??[]).map((attempt)=>attempt.result?attempt:{...attempt,result:{outcome:"uncertain",exitStatus:"not-observed",diagnostic:`finalized by publication invalidation (${reason})`,postPush:{localHead:null,observedRemoteHead:null},completedAt:now}}),invalidatedActive=active?{...active,state:"invalidated",invalidatedAt:now,invalidationReason:reason}:void 0,nextState={...pending,updatedAt:now,prFeedbackReadyToPublish:void 0,prFeedbackVerifications:void 0,prFeedbackGateBatches:void 0,prFeedbackScopes:void 0,prFeedbackPublication:active?nextPublicationContainer(publication,invalidatedActive,[],attempts):pending.prFeedbackPublication},invalidationEvent=active?{type:"pr_feedback_publication_invalidated",sessionID:pending.sessionID,generation:active.generation,reason,previousState:active.state,drift:null,revisionDigest:active.revisionDigest,localHead:active.localHead,remoteName:active.remoteName,remoteBranchRef:active.remoteBranchRef,supersededBatchIds:active.evidence.batches.map((b)=>b.batchId)}:null;return{state:nextState,invalidationEvent}}function parseExactBoundPushIntent(command,armed){if(hasUnsafeShellControlSyntax(command))return{ok:!1,reason:"shell-syntax"};if(!armed.remoteBranchRef.startsWith("refs/heads/"))return{ok:!1,reason:"unbound-target"};let tokens2=command.trim().split(/\s+/);if(tokens2.length!==4||tokens2[0].toLowerCase()!=="git"||tokens2[1].toLowerCase()!=="push"||tokens2.some((token)=>/["'\\]/.test(token)))return{ok:!1,reason:"token-shape"};let[remoteToken,refspecToken]=[tokens2[2],tokens2[3]];if(remoteToken.startsWith("-")||refspecToken.startsWith("-"))return{ok:!1,reason:"flag-or-option"};if(/[:@]/.test(remoteToken)||remoteToken.includes("://"))return{ok:!1,reason:"credential-bearing-remote"};let refspecParts=refspecToken.split(":");if(refspecParts.length!==2)return{ok:!1,reason:refspecParts.length>2?"token-shape":"invalid-dest-ref"};let[sourceToken,destToken]=refspecParts;if(!destToken.startsWith("refs/heads/")||destToken==="refs/heads/")return{ok:!1,reason:"invalid-dest-ref"};if(sourceToken==="")return{ok:!1,reason:"delete-refspec"};if(sourceToken.includes("*")||destToken.includes("*"))return{ok:!1,reason:"wildcard-refspec"};if(remoteToken!==armed.remoteName)return{ok:!1,reason:"remote-mismatch"};if(sourceToken!==armed.localHead)return{ok:!1,reason:"source-mismatch"};if(destToken!==armed.remoteBranchRef)return{ok:!1,reason:"branch-mismatch"};let intent={remote:remoteToken,sourceSha:sourceToken,destRef:destToken};return{ok:!0,intent,digest:createHash59("sha256").update(JSON.stringify(intent),"utf8").digest("hex")}}async function admitPrFeedbackPushAttempt(directory,sessionID,callID,intent,intentDigest){let normalizedSessionID=normalizeSessionID(sessionID);await withSessionStateMutation(directory,normalizedSessionID,async()=>{let state2=await readPrWorkflowGateStateFromDisk3(directory,normalizedSessionID),active=state2?.prFeedbackPublication?.active;if(!state2||state2.mode!=="PR_FEEDBACK"||!active)throw Error("BLOCKED: PR_FEEDBACK push admission requires an armed publication generation");if(active.state!=="armed")throw Error(`BLOCKED: PR_FEEDBACK push admission requires the armed state, not ${active.state}`);let check3=await checkPublicationIdentity(directory,state2,active);if(check3.kind==="unresolvable")throw Error(`BLOCKED: PR_FEEDBACK could not verify the armed publication identity component "${check3.component}" (${check3.detail}); the push was not admitted`);if(check3.kind==="drift"){let invalidation=await applyPublicationInvalidationWhileLocked(directory,state2,`drift:${check3.component}`,{drift:check3});throw Error(`BLOCKED: PR_FEEDBACK publication generation ${invalidation.generation.generation} was INVALIDATED because approved content identity drifted (${check3.component}: ${check3.detail}). Rerun Stage A and every independent gate, then arm a fresh generation with complete_pr_workflow.`)}let now=isoNow();if(intent.remote!==active.remoteName||intent.sourceSha!==active.localHead||intent.destRef!==active.remoteBranchRef)throw Error("BLOCKED: PR_FEEDBACK push intent does not match the armed publication generation under the state lock; the push was not admitted");let observedRemoteHead=await _test_exports2.resolveExactRemoteBranchHeadAsync(directory,active.remoteName,active.remoteBranchRef),localHead=(await _test_exports2.resolveCurrentGitHeadAsync(directory))?.trim(),worktreeClean=await _test_exports2.resolveIsWorkingTreeCleanAsync(directory),baseAttempt={attemptId:randomUUID17(),generation:active.generation,sessionID:state2.sessionID,callID,intentDigest,intent:{remote:intent.remote,sourceSha:intent.sourceSha,destRef:intent.destRef},prePush:{localHead:active.localHead,worktreeClean:worktreeClean===!0,remoteName:active.remoteName,remoteBranchRef:active.remoteBranchRef,observedRemoteHead},startedAt:now};if(observedRemoteHead?.toLowerCase()===active.localHead.toLowerCase()){let attempt={...baseAttempt,result:{outcome:"completed",exitStatus:"not-observed",diagnostic:"remote branch already observed at the approved head (no-op push)",postPush:{localHead:localHead??null,observedRemoteHead:observedRemoteHead??null},completedAt:now}},nextState2={...state2,updatedAt:now,prFeedbackPublication:nextPublicationContainer(state2.prFeedbackPublication,active,[],[...state2.prFeedbackPublication?.attempts??[],attempt])};await writeStateWhileLocked(directory,nextState2),appendPublicationEvent(directory,{type:"pr_feedback_push_attempt_result",sessionID:state2.sessionID,generation:active.generation,outcome:"completed",by:"no-op-observation",observedRemoteHead});return}let nextState={...state2,updatedAt:now,prFeedbackPublication:nextPublicationContainer(state2.prFeedbackPublication,{...active,state:"push_in_flight"},[],[...state2.prFeedbackPublication?.attempts??[],baseAttempt])};await writeStateWhileLocked(directory,nextState),appendPublicationEvent(directory,{type:"pr_feedback_push_attempt_started",sessionID:state2.sessionID,generation:active.generation,intentDigest,intent,observedRemoteHead})});let attempts=(await readPrWorkflowGateState(directory,normalizedSessionID))?.prFeedbackPublication?.attempts??[];return attempts[attempts.length-1]?.result?.outcome==="completed"?{kind:"already-published-remotely"}:{kind:"started"}}function describeToolOutputText(output){if(typeof output==="string")return output;if(output&&typeof output==="object"&&"output"in output&&typeof output.output==="string")return output.output;try{return JSON.stringify(output)??""}catch{return""}}async function recordPrFeedbackPushAttemptResult(directory,input,command,output){let normalizedTool=(normalizeToolName(input.tool)??input.tool).toLowerCase();if(normalizedTool!=="bash"&&normalizedTool!=="shell")return;if(!/^\s*git\s+push/i.test(command))return;let normalizedSessionID=normalizeSessionID(input.sessionID);await withSessionStateMutation(directory,normalizedSessionID,async()=>{let state2=await readPrWorkflowGateStateFromDisk3(directory,normalizedSessionID),publication=state2?.prFeedbackPublication,active=publication?.active;if(!state2||!publication||!active||active.state!=="push_in_flight"||!input.callID)return;let attemptIndex=publication.attempts.findIndex((attempt)=>!attempt.result&&attempt.callID===input.callID);if(attemptIndex<0)return;let now=isoNow(),localHead=(await _test_exports2.resolveCurrentGitHeadAsync(directory))?.trim(),observedRemoteHead=await _test_exports2.resolveExactRemoteBranchHeadAsync(directory,active.remoteName,active.remoteBranchRef),remoteVerifiedAtApprovedHead=observedRemoteHead?.toLowerCase()===active.localHead.toLowerCase(),metadataExit=output?.metadata?.exitCode,exitStatus=typeof metadataExit==="number"&&Number.isInteger(metadataExit)?metadataExit:"not-observed",outcome;if(remoteVerifiedAtApprovedHead)outcome="completed";else if(exitStatus!=="not-observed"&&exitStatus!==0)outcome="rejected";else outcome="uncertain";let diagnostic=boundPublicationDiagnostic(remoteVerifiedAtApprovedHead?`push result observed; remote branch verified at the approved head${exitStatus!=="not-observed"&&exitStatus!==0?` (shell reported nonzero exit ${exitStatus}; the verified remote head is the publication truth)`:""}`:`push result observed without remote verification at the approved head; exit status ${exitStatus==="not-observed"?"not observed":exitStatus}; output: ${describeToolOutputText(output)}`),attempts=publication.attempts.map((attempt,index)=>index===attemptIndex?{...attempt,result:{outcome,exitStatus,diagnostic,postPush:{localHead:localHead??null,observedRemoteHead:observedRemoteHead??null},completedAt:now}}:attempt),nextState={...state2,updatedAt:now,prFeedbackPublication:nextPublicationContainer(publication,{...active,state:"armed"},[],attempts)};await writeStateWhileLocked(directory,nextState),appendPublicationEvent(directory,{type:"pr_feedback_push_attempt_result",sessionID:state2.sessionID,generation:active.generation,outcome,exitStatus,by:"tool-after",observedRemoteHead})})}async function cancelPrFeedbackPublication(directory,sessionID,reason){let normalizedSessionID=normalizeSessionID(sessionID),nextRevision=null,observedRemoteHead=null,cancelledGeneration=null,cancelledAttemptsFinalized=0;try{await withSessionStateMutation(directory,normalizedSessionID,async()=>{let state2=await readPrWorkflowGateStateFromDisk3(directory,normalizedSessionID),publication=state2?.prFeedbackPublication,active=publication?.active;if(!state2||!publication||!active)return;if(active.state==="cancelled_without_publication"){nextRevision=state2.revision;return}if(active.state!=="armed"&&active.state!=="push_in_flight"&&active.state!=="invalidated")throw Error(`BLOCKED: PR_FEEDBACK publication generation ${active.generation} is ${active.state}; only armed, push_in_flight, or invalidated generations may be cancelled`);let now=isoNow();observedRemoteHead=await _test_exports2.resolveExactRemoteBranchHeadAsync(directory,active.remoteName,active.remoteBranchRef);let attempts=publication.attempts.map((attempt)=>attempt.result?attempt:{...attempt,result:{outcome:"cancelled",exitStatus:"not-observed",diagnostic:"finalized by publication cancellation",postPush:{localHead:null,observedRemoteHead},completedAt:now}}),cancelled={...active,state:"cancelled_without_publication",cancelledAt:now,invalidationReason:active.invalidationReason??`cancelled:${reason}`},nextState={...state2,updatedAt:now,prFeedbackReadyToPublish:void 0,prFeedbackPublication:nextPublicationContainer(publication,cancelled,[],attempts)};nextRevision=(await writeStateWhileLocked(directory,nextState)).revision,cancelledGeneration=active.generation,cancelledAttemptsFinalized=attempts.filter((attempt)=>attempt.result?.outcome==="cancelled").length})}catch(error93){if(error93 instanceof Error&&error93.message.startsWith("BLOCKED: PR_FEEDBACK publication generation"))throw error93}return appendPublicationEvent(directory,{type:"pr_feedback_publication_cancelled",sessionID:normalizedSessionID,...cancelledGeneration!==null?{generation:cancelledGeneration}:{},reason,...cancelledAttemptsFinalized>0?{attemptsFinalized:cancelledAttemptsFinalized}:{},observedRemoteHead}),{revision:nextRevision,observedRemoteHead}}async function assertPrFeedbackPublicationArmed(directory,sessionID,options={}){let state2=await ensurePublicationGenerationCurrent(directory,sessionID)??await requireBoundState2(directory,sessionID,"PR_FEEDBACK");state2=await reconcileForeignInFlightAttempt(directory,sessionID,options.currentCallId)??state2??await requireBoundState2(directory,sessionID,"PR_FEEDBACK");let active=state2.prFeedbackPublication?.active;if(!active||active.state!=="armed"&&active.state!=="push_in_flight"){if(active?.state==="invalidated")throw Error(`BLOCKED: PR_FEEDBACK publication generation ${active.generation} was invalidated${active.invalidationReason?` (${active.invalidationReason})`:""}; rerun Stage A and every independent gate, then arm a fresh generation with complete_pr_workflow`);throw Error("BLOCKED: PR_FEEDBACK publication is not armed; call complete_pr_workflow once after every ordered gate passes")}let check3=await checkPublicationIdentity(directory,state2,active);if(check3.kind==="unresolvable")throw Error(`BLOCKED: PR_FEEDBACK could not verify the armed publication identity component "${check3.component}" (${check3.detail}); the armed window is unchanged and fails closed. Resolve the verification failure and retry.`);if(check3.kind==="drift"){let invalidation=await invalidatePublicationGeneration(directory,sessionID,`drift:${check3.component}`,{drift:check3,driftReverification:!0});throw Error(`BLOCKED: PR_FEEDBACK publication generation ${invalidation.generation.generation} was INVALIDATED because approved content identity drifted (${check3.component}: ${check3.detail}). Every approval of that generation is now superseded. Rerun Stage A and every independent gate, then arm a fresh generation with complete_pr_workflow.`)}return state2}async function resolvePrReviewWriterRunId(directory,sessionID,requestedRunId){let normalizedSessionID=normalizeSessionID(sessionID);return withPrWorkflowCheckoutMutationLock(directory,()=>withSessionStateMutation(directory,normalizedSessionID,async()=>{let state2=await requireBoundState2(directory,normalizedSessionID,"PR_REVIEW"),workflowInstanceId=workflowIdentity(state2),normalizedRequested=requestedRunId?.trim()||void 0,stateBoundValues=[state2.prReviewReservedRunId,state2.prReviewTriggerEvalRunId,state2.prReviewArtifactRunId].filter((value)=>Boolean(value?.trim())),stateDistinct=[...new Set(stateBoundValues)];if(normalizedRequested&&stateDistinct.some((value)=>value!==normalizedRequested)){if(stateDistinct.length===1)throw Error(`BLOCKED: field run_id expected "${stateDistinct[0]}", got "${normalizedRequested}"`);throw Error(`BLOCKED: field run_id expected one unambiguous active value, got "${normalizedRequested}" while active bindings are ${stateDistinct.join(", ")}`)}let recoveredReservations=normalizedRequested?[]:await findOwnedPrReviewRunReservations(directory,normalizedSessionID,workflowInstanceId),distinct=[...new Set([...stateBoundValues,...recoveredReservations])];if(!normalizedRequested&&distinct.length>1)throw Error(`BLOCKED: field run_id expected one unambiguous active value, got (omitted) while active bindings are ${distinct.join(", ")}`);let reserve=async(runId)=>{return await tryCreatePrReviewRunReservation(directory,normalizedSessionID,workflowInstanceId,runId)==="occupied"?null:runId},resolvedRunId=normalizedRequested??distinct[0];if(!resolvedRunId){let base=generatePrReviewRunId();for(let suffix=0;suffix<MAX_PR_REVIEW_RUN_ID_SUFFIX_ATTEMPTS&&!resolvedRunId;suffix+=1){let candidate=suffix===0?base:`${base}-${suffix}`,reserved=await reserve(candidate);if(reserved)resolvedRunId=reserved}if(!resolvedRunId)throw Error(`BLOCKED: PR_REVIEW run_id generation exhausted ${MAX_PR_REVIEW_RUN_ID_SUFFIX_ATTEMPTS} reservation attempts for base "${base}"`)}else if(await reserve(resolvedRunId)===null)throw Error(`BLOCKED: field run_id expected an unused active reservation, got "${resolvedRunId}" which is already occupied by another workflow`);if(state2.prReviewReservedRunId===resolvedRunId)return resolvedRunId;let nextState={...state2,updatedAt:isoNow(),prReviewReservedRunId:resolvedRunId};return(await writeStateWhileLocked(directory,nextState,{replaceWorkflowInstanceId:state2.workflowInstanceId})).prReviewReservedRunId??resolvedRunId}))}async function markPrReviewTriggerEvaluationComplete(directory,sessionID,runId,artifactPath){let state2=(await assertPrReviewBaseCoverageSettled2(directory,sessionID)).state,normalizedRunId=runId.trim();if(!normalizedRunId)throw Error("BLOCKED: PR_REVIEW trigger artifact run_id is required");let normalizedPath=artifactPath.trim();if(!normalizedPath)throw Error("BLOCKED: PR_REVIEW trigger artifact path is required");if(state2.prReviewTriggerEvalRunId&&state2.prReviewTriggerEvalRunId!==normalizedRunId)throw Error(`BLOCKED: PR_REVIEW trigger evaluation is already bound to run "${state2.prReviewTriggerEvalRunId}"`);if(state2.prReviewArtifactRunId&&state2.prReviewArtifactRunId!==normalizedRunId)throw Error(`BLOCKED: PR_REVIEW trigger evaluation run_id must match the findings artifact run "${state2.prReviewArtifactRunId}"`);let nextState={...state2,updatedAt:isoNow(),prReviewTriggerEvalPath:normalizedPath,prReviewTriggerEvalRunId:normalizedRunId};return await persistState2(directory,nextState),nextState}async function bindPrReviewTriggerLedger(directory,sessionID,input){let ledger;try{ledger=validatePrReviewInlineTriggerLedger(input)}catch(error93){throw Error(`BLOCKED: invalid PR_REVIEW trigger_evaluation: ${error93 instanceof Error?error93.message:String(error93)}`)}let state2=(await assertPrReviewBaseCoverageSettled2(directory,sessionID)).state;if(state2.prReviewTriggerLedger){let frozen;try{frozen=validatePrReviewInlineTriggerLedger(state2.prReviewTriggerLedger)}catch(error93){throw Error(`BLOCKED: persisted PR_REVIEW trigger ledger is invalid: ${error93 instanceof Error?error93.message:String(error93)}`)}if(prReviewTriggerLedgerDigest(frozen.rows)!==prReviewTriggerLedgerDigest(ledger.rows))throw Error("BLOCKED: PR_REVIEW trigger_evaluation must remain exactly identical across every micro dispatch");return state2}let nextState={...state2,updatedAt:isoNow(),prReviewTriggerLedger:ledger.rows};return await persistState2(directory,nextState),nextState}async function assertPrReviewArtifactBoundary(directory,sessionID,runId,boundary,findingIds,options={}){let state2=await requireBoundState2(directory,sessionID,"PR_REVIEW"),baseOnlyExplorerCheckpoint=boundary==="post_explorer"&&!state2.prReviewTriggerEvalPath;if(!state2.prReviewTriggerEvalPath&&!baseOnlyExplorerCheckpoint)throw Error("BLOCKED: PR_REVIEW findings persistence requires the trigger evaluation artifact (write_pr_review_trigger_eval must complete first)");if(baseOnlyExplorerCheckpoint&&!options.skipBaseCoverage)state2=(await assertPrReviewBaseCoverageSettled2(directory,sessionID)).state;let persistedBoundaries=state2.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 createPrReviewGateContext2(directory,state2);if(boundary==="post_reviewer")state2=await assertPrReviewValidationSettled(directory,sessionID,"reviewer",ctx);else if(boundary==="post_critic"){if(await assertPrReviewValidationSettled(directory,sessionID,"reviewer",ctx),derivePrReviewCriticInventoryForCoverageGate(directory,state2,ctx,"assertPrReviewArtifactBoundary(post_critic)").length>0)state2=await assertPrReviewValidationSettled(directory,sessionID,"critic",ctx)}if(state2.prReviewArtifactRunId&&state2.prReviewArtifactRunId!==runId)throw Error(`BLOCKED: PR_REVIEW artifacts are already bound to run "${state2.prReviewArtifactRunId}"`);if(state2.prReviewTriggerEvalRunId&&state2.prReviewTriggerEvalRunId!==runId)throw Error(`BLOCKED: PR_REVIEW findings must use the same run as the trigger evaluation "${state2.prReviewTriggerEvalRunId}"`);let expectedFindingIds=derivePrReviewCandidateInventory2(directory,state2,ctx),reviewerDeadForCover=verdictSettlementEffectiveIdsForGate(directory,state2,"reviewer",ctx),coverableExpected=expectedFindingIds.filter((id)=>!reviewerDeadForCover.has(id)),nonDeadFindingIds=findingIds.filter((id)=>!reviewerDeadForCover.has(id)),normalizedFindingIds=[...new Set(nonDeadFindingIds)].sort();if(normalizedFindingIds.length!==nonDeadFindingIds.length||JSON.stringify(normalizedFindingIds)!==JSON.stringify([...coverableExpected].sort())){let actualSet=new Set(normalizedFindingIds),expectedSet=new Set(coverableExpected),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 state2}async function assertPrReviewArtifactRecordsMatchAuthoritativeVerdicts(directory,sessionID,boundary,records){let state2=await requireBoundState2(directory,sessionID,"PR_REVIEW"),violations=[],report=(findingId2,field,expected,actual)=>{violations.push({findingId:findingId2,detail:`${field} expected ${expected}, got ${actual}`})},reportSeverity=(record3,expected)=>{if(record3.severity===expected)return;let raw=record3.severity,actual=raw===void 0?"(omitted)":raw===null?"(null)":raw===""?"(empty)":`"${raw}"`;report(record3.finding_id,"severity",`"${expected}"`,actual)},reportRiskMetadata=(record3,reviewer)=>{if(record3.status!=="CONFIRMED")return;let expectedImpact=reviewer.riskImpact??"UNKNOWN",expectedTags=reviewer.riskTags??[],actualImpact=record3.risk_impact??"UNKNOWN",actualTags=record3.risk_tags??[];if(actualImpact!==expectedImpact)report(record3.finding_id,"risk_impact",`"${expectedImpact}"`,record3.risk_impact===void 0?"(omitted)":`"${actualImpact}"`);if(actualTags.join(",")!==expectedTags.join(","))report(record3.finding_id,"risk_tags",JSON.stringify(expectedTags),record3.risk_tags===void 0?"(omitted)":JSON.stringify(actualTags))};if(boundary==="post_explorer"){let candidateSeverities=derivePrReviewCandidateSeverities(directory,state2,await createPrReviewGateContext2(directory,state2));for(let record3 of records){if(record3.status!=="PENDING")report(record3.finding_id,"status",'"PENDING"',`"${record3.status}"`);if(record3.next_action!=="route_to_reviewer")report(record3.finding_id,"next_action",'"route_to_reviewer"',`"${record3.next_action}"`);let candidateSeverity=candidateSeverities.get(record3.finding_id);if(candidateSeverity){reportSeverity(record3,candidateSeverity);continue}if(record3.finding_id===PR_REVIEW_CLEAN_SENTINEL_ID){reportSeverity(record3,"NONE");continue}violations.push({findingId:record3.finding_id,detail:"no authoritative candidate severity (absent from the derived candidate inventory)"})}}else{let ctx=await createPrReviewGateContext2(directory,state2),reviewerVerdicts=authoritativeReviewerVerdictsForGate(directory,state2,ctx,`assertPrReviewArtifactRecordsMatchAuthoritativeVerdicts(${boundary})`),criticVerdicts=boundary==="post_critic"?authoritativeCriticVerdictsForGate(directory,state2,ctx,`assertPrReviewArtifactRecordsMatchAuthoritativeVerdicts(${boundary})`):void 0,reviewerDeadForMatch=verdictSettlementEffectiveIdsForGate(directory,state2,"reviewer",ctx),criticDeadForMatch=boundary==="post_critic"?verdictSettlementEffectiveIdsForGate(directory,state2,"critic",ctx):new Set;for(let record3 of records){if(reviewerDeadForMatch.has(record3.finding_id)){violations.push({findingId:record3.finding_id,detail:"disclosed-dead items carry no verdict-bearing record; they live only in the verdict-settlement receipt"});continue}let reviewer=reviewerVerdicts.get(record3.finding_id);if(!reviewer){violations.push({findingId:record3.finding_id,detail:"no authoritative reviewer verdict (absent from the settled reviewer map)"});continue}let requiresCritic=prReviewFindingRequiresCritic({classification:reviewer.classification,severity:reviewer.severity,risk_impact:reviewer.riskImpact,risk_tags:reviewer.riskTags}),expectedStatus=reviewer.classification==="UNVERIFIED"?"PENDING":reviewer.classification;if(boundary==="post_critic"&&criticDeadForMatch.has(record3.finding_id)){if(record3.critic_status!==void 0)report(record3.finding_id,"critic_status","(absent — the model never authors a critic status on a disclosed-dead critic item)",`"${record3.critic_status}"`);if(record3.status!==expectedStatus)report(record3.finding_id,"status",`"${expectedStatus}"`,`"${record3.status}"`);reportSeverity(record3,reviewer.severity),reportRiskMetadata(record3,reviewer);continue}if(boundary==="post_reviewer"){if(record3.status!==expectedStatus)report(record3.finding_id,"status",`"${expectedStatus}"`,`"${record3.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(record3.next_action!==expectedAction)report(record3.finding_id,"next_action",`"${expectedAction}"`,`"${record3.next_action}"`);reportSeverity(record3,reviewer.severity),reportRiskMetadata(record3,reviewer);continue}if(!requiresCritic){let expectedAction=reviewer.classification==="CONFIRMED"||reviewer.classification==="PRE_EXISTING"?"report":reviewer.classification==="DISPROVED"?"suppress_with_reason":"route_to_reviewer";if(record3.status!==expectedStatus)report(record3.finding_id,"status",`"${expectedStatus}"`,`"${record3.status}"`);if(record3.next_action!==expectedAction)report(record3.finding_id,"next_action",`"${expectedAction}"`,`"${record3.next_action}"`);reportSeverity(record3,reviewer.severity),reportRiskMetadata(record3,reviewer);continue}let critic=criticVerdicts?.get(record3.finding_id);if(!critic){reportSeverity(record3,reviewer.severity),reportRiskMetadata(record3,reviewer),violations.push({findingId:record3.finding_id,detail:"no authoritative critic verdict (absent from the settled critic map)"});continue}if(critic.status==="DISPROVED"){if(record3.status!=="DISPROVED")report(record3.finding_id,"status",'"DISPROVED"',`"${record3.status}"`);if(record3.next_action!=="suppress_with_reason")report(record3.finding_id,"next_action",'"suppress_with_reason"',`"${record3.next_action}"`)}else{if(record3.status!=="CONFIRMED")report(record3.finding_id,"status",'"CONFIRMED"',`"${record3.status}"`);if(!["report","handoff_to_feedback"].includes(record3.next_action))report(record3.finding_id,"next_action",'"report" or "handoff_to_feedback"',`"${record3.next_action}"`)}reportSeverity(record3,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):
|
|
1292
1292
|
${lines.join(`
|
|
1293
1293
|
`)}`)}}async function markPrReviewArtifactBoundary(directory,sessionID,runId,boundary,artifactPath,findingIds,handoffRequired){let state2=await assertPrReviewArtifactBoundary(directory,sessionID,runId,boundary,findingIds),boundaries=new Set(state2.prReviewArtifactBoundaries??[]);boundaries.add(boundary);let nextState={...state2,updatedAt:isoNow(),prReviewArtifactRunId:runId,prReviewFindingsPath:artifactPath,prReviewArtifactBoundaries:[...boundaries],prReviewHandoffRequired:handoffRequired};return await persistState2(directory,nextState),nextState}async function markPrReviewHandoffComplete(directory,sessionID,runId,artifactPath){let normalizedSessionID=normalizeSessionID(sessionID);return withPrWorkflowCheckoutMutationLock(directory,()=>withSessionStateMutation(directory,normalizedSessionID,async()=>{let state2=await requireBoundState2(directory,normalizedSessionID,"PR_REVIEW");if(state2.prReviewArtifactRunId!==runId||!(state2.prReviewArtifactBoundaries??[]).includes("post_critic"))throw Error("BLOCKED: PR_REVIEW handoff requires the final findings boundary for the same run");let read=await readPrReviewFeedbackHandoffArtifact(directory,artifactPath),command=`/swarm pr-feedback ${read.artifact.pr_url} continue from .swarm/${artifactPath}`,consentInput={sessionID:normalizedSessionID,runId,handoffPath:artifactPath,handoffDigest:read.digest,prUrl:read.artifact.pr_url,prHeadSha:read.artifact.pr_head_sha,findingIdsDigest:hashPrReviewFindingIds(read.artifact.finding_ids),sourceWorkflowInstanceId:workflowIdentity(state2)},existing=await readPrReviewFeedbackConsent(directory,runId),alreadyOffered=existing!==null;if(existing)assertMatchingPrReviewFeedbackConsent(existing,consentInput);else await writePrReviewFeedbackConsent(directory,{schema_version:1,state:"offered",session_id:normalizedSessionID,source_workflow_instance_id:workflowIdentity(state2),run_id:runId,handoff_path:artifactPath,handoff_digest:read.digest,pr_url:read.artifact.pr_url,pr_head_sha:read.artifact.pr_head_sha.toLowerCase(),finding_ids_digest:consentInput.findingIdsDigest,confirmation_command:command,offered_at:isoNow()});if(alreadyOffered&&state2.prReviewHandoffPath===artifactPath)return{state:state2,alreadyOffered:!0};let nextState={...state2,updatedAt:isoNow(),prReviewHandoffPath:artifactPath};return{state:await writeStateWhileLocked(directory,nextState),alreadyOffered}}))}function normalizePrReviewFeedbackHandoffPath(handoffPath){let normalized=handoffPath.trim().replace(/\\/g,"/"),relative32=normalized.startsWith(".swarm/")?normalized.slice(7):normalized,matched=relative32.match(PR_REVIEW_HANDOFF_RELATIVE_PATH_PATTERN);if(!matched)return null;return{runId:matched[1],relativePath:relative32}}function buildAcceptedPrFeedbackContinuationCommands(confirmationCommand,relativeHandoffPath,requestedPrUrl){let commands=new Set([confirmationCommand]);if(!requestedPrUrl)commands.add(`/swarm pr-feedback continue from .swarm/${relativeHandoffPath}`);return commands}async function readBoundedSwarmRegularFile2(directory,relativePath,maxBytes,label){let absPath=validateSwarmPath(directory,relativePath),swarmRoot=path119.resolve(directory,".swarm"),rootStat,artifactStat;try{rootStat=await fsp8.lstat(swarmRoot,{bigint:!0}),artifactStat=await fsp8.lstat(absPath,{bigint:!0})}catch(error93){if(error93.code==="ENOENT")throw Error(`BLOCKED: ${label} "${relativePath}" does not exist`);throw error93}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([fsp8.realpath(swarmRoot),fsp8.realpath(absPath)]),relativeRealPath=path119.relative(realRoot,realArtifact);if(relativeRealPath===""||relativeRealPath===".."||relativeRealPath.startsWith(`..${path119.sep}`)||path119.isAbsolute(relativeRealPath))throw Error(`BLOCKED: ${label} escapes the project .swarm directory`);await _test_exports2.beforeBoundedSwarmFileOpen?.();let handle=await fsp8.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([fsp8.lstat(swarmRoot,{bigint:!0}),fsp8.lstat(absPath,{bigint:!0}),fsp8.realpath(swarmRoot),fsp8.realpath(absPath)]),postRelativeRealPath=path119.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(`..${path119.sep}`)||path119.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 prReviewRunReservationRelativePath(runId){return`pr-review/${runId}/run-reservation.json`}function prReviewFeedbackConsentRelativePath(runId){return`pr-review/${runId}/feedback-consent.json`}async function findOwnedPrReviewRunReservations(directory,sessionID,workflowInstanceId){let reviewRoot=validateSwarmPath(directory,"pr-review"),entries;try{entries=await fsp8.readdir(reviewRoot,{withFileTypes:!0})}catch(error93){if(error93.code==="ENOENT")return[];throw error93}if(entries.length>MAX_PR_REVIEW_RESERVATION_SCAN_ENTRIES)throw Error(`BLOCKED: PR_REVIEW reservation recovery expected at most ${MAX_PR_REVIEW_RESERVATION_SCAN_ENTRIES} run entries, got ${entries.length}`);let owned=[];for(let entry of entries){if(!entry.isDirectory()||!PrReviewRunIdSchema.safeParse(entry.name).success)continue;let reservation;try{reservation=await readPrReviewRunReservation(directory,entry.name)}catch{continue}if(reservation?.session_id===sessionID&&reservation.workflow_instance_id===workflowInstanceId&&reservation.run_id===entry.name)owned.push(entry.name)}return owned.sort()}function hashPrReviewFindingIds(ids){return createHash59("sha256").update([...new Set(ids)].sort().join("\x00"),"utf8").digest("hex")}async function readPrReviewRunReservation(directory,runId){try{let raw=await readBoundedSwarmRegularFile2(directory,prReviewRunReservationRelativePath(runId),PR_REVIEW_RUN_RESERVATION_MAX_BYTES,"PR_REVIEW run reservation"),parsed=PrReviewRunReservationSchema.safeParse(JSON.parse(raw));if(!parsed.success)throw Error("BLOCKED: PR_REVIEW run reservation is invalid");return parsed.data}catch(error93){if((error93 instanceof Error?error93.message:String(error93)).includes("does not exist"))return null;throw error93}}async function tryCreatePrReviewRunReservation(directory,sessionID,workflowInstanceId,runId){let relativePath=prReviewRunReservationRelativePath(runId),absolutePath=validateSwarmPath(directory,relativePath),runDirectory=path119.dirname(absolutePath),payload=`${JSON.stringify({schema_version:1,session_id:sessionID,workflow_instance_id:workflowInstanceId,run_id:runId,reserved_at:isoNow()},null,2)}
|
|
1294
1294
|
`;await fsp8.mkdir(runDirectory,{recursive:!0});try{return await fsp8.writeFile(absolutePath,payload,{encoding:"utf8",flag:"wx"}),"created"}catch(error93){if(error93.code!=="EEXIST")throw error93}let existing=await readPrReviewRunReservation(directory,runId);if(existing?.session_id===sessionID&&existing.workflow_instance_id===workflowInstanceId&&existing.run_id===runId)return"owned";let occupiedNames=new Set(["trigger-eval.json","findings.jsonl","feedback-handoff.json","feedback-consent.json"]);try{if((await fsp8.readdir(runDirectory)).some((entry)=>occupiedNames.has(entry)))return"occupied"}catch(error93){if(error93.code!=="ENOENT")throw error93}return"occupied"}async function readPrReviewFeedbackConsent(directory,runId){try{let raw=await readBoundedSwarmRegularFile2(directory,prReviewFeedbackConsentRelativePath(runId),PR_REVIEW_FEEDBACK_CONSENT_MAX_BYTES,"PR_REVIEW feedback consent artifact"),parsed=PrReviewFeedbackConsentSchema.safeParse(JSON.parse(raw));if(!parsed.success)throw Error("BLOCKED: PR_REVIEW feedback consent artifact is invalid");return parsed.data}catch(error93){if((error93 instanceof Error?error93.message:String(error93)).includes("does not exist"))return null;throw error93}}async function writePrReviewFeedbackConsent(directory,record3){let relativePath=prReviewFeedbackConsentRelativePath(record3.run_id),absolutePath=validateSwarmPath(directory,relativePath);if(record3.state==="confirmed"){await writeAtomicJson2(directory,absolutePath,record3);return}let parent=path119.dirname(absolutePath),tempPath=path119.join(parent,`.feedback-consent.${randomUUID17()}.tmp`);await fsp8.mkdir(parent,{recursive:!0});try{await fsp8.writeFile(tempPath,`${JSON.stringify(record3,null,2)}
|
|
1295
|
-
`,{encoding:"utf8",flag:"wx"}),await fsp8.link(tempPath,absolutePath)}finally{await fsp8.rm(tempPath,{force:!0}).catch(()=>{return})}}async function readPrReviewFeedbackHandoffArtifact(directory,relativePath){let raw=await readBoundedSwarmRegularFile2(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:createHash59("sha256").update(raw,"utf8").digest("hex")}}async function readActionableReviewFindingIds(directory,state2,runId){let expectedPath=`pr-review/${runId}/findings.jsonl`;if(state2.prReviewFindingsPath!==expectedPath)throw Error(`BLOCKED: PR_REVIEW transition requires the exact final findings artifact "${expectedPath}"`);let raw=await readBoundedSwarmRegularFile2(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 deriveFeedbackHandoffFindingIds([...latest.values()])}async function readAuthoritativeFindingPolicy(directory,state2){let runId=state2.prReviewArtifactRunId;if(!runId||!state2.prReviewFindingsPath||!state2.prHeadSha)throw Error("BLOCKED: PR_REVIEW terminal finding policy evidence is not bound to the active run");let outcome=await readReviewOutcome({projectRoot:directory,sessionId:state2.sessionID,taskId:runId}).catch((error93)=>{throw Error(`BLOCKED: PR_REVIEW finding-policy evidence is missing or invalid: ${error93 instanceof Error?error93.message:String(error93)}`)}),routeReceipt=outcome.evidence.routeReceipt;if(!routeReceipt||typeof routeReceipt!=="object")throw Error("BLOCKED: PR_REVIEW finding-policy evidence has no route receipt");let receipt=routeReceipt,expectedPath=`pr-review/${runId}/findings.jsonl`,raw=await readBoundedSwarmRegularFile2(directory,state2.prReviewFindingsPath,PR_REVIEW_FINDINGS_MAX_BYTES,"PR_REVIEW final findings artifact"),findingsDigest=createHash59("sha256").update(raw,"utf8").digest("hex");if(receipt.version!==FINDING_POLICY_VERSION)throw Error(`BLOCKED: PR_REVIEW finding-policy route receipt version ${String(receipt.version)} does not match the current finding-policy version ${FINDING_POLICY_VERSION}; the sidecar was written by a different plugin version and cannot be trusted at this one`);if(receipt.kind!=="pr_review_finding_policy"||receipt.sessionId!==state2.sessionID||receipt.taskId!==runId||receipt.boundary!=="post_critic"||receipt.prHeadSha!==state2.prHeadSha||receipt.findingsPath!==expectedPath||receipt.findingsDigest!==findingsDigest)throw Error("BLOCKED: PR_REVIEW finding-policy route receipt is stale or does not bind the final findings artifact");let synthesis=PrReviewFindingPolicySynthesisSchema.safeParse(outcome.evidence.synthesis);if(!synthesis.success)throw Error("BLOCKED: PR_REVIEW finding-policy synthesis is invalid or incomplete");return{policyFindings:synthesis.data.findings,criticSettlements:synthesis.data.criticSettlements??[]}}async function readPrReviewFinalFindingPolicyForReport(directory,sessionID){let state2=await readPrWorkflowGateStateFromDisk3(directory,normalizeSessionID(sessionID));if(!state2||state2.mode!=="PR_REVIEW"||!state2.prHeadSha)return null;let ctx=await createPrReviewGateContext2(directory,state2),settlement=derivePrReviewDimensionSettlement(directory,state2,ctx.revisionDigest),findings=(await readAuthoritativeFindingPolicy(directory,state2)).policyFindings,disclosedDegradation=prReviewReceiptHasCoverageDegradations(directory,state2.prReviewTriggerEvalPath)||await verdictSettlementDegradesReport(directory,state2,ctx),permittedVerdicts=allowedPrReviewReportVerdicts(settlement.kind,findings,{disclosedCoverageDegradation:disclosedDegradation}),policyProjection=evaluateFinalFindingPolicy({policyVersion:FINDING_POLICY_VERSION,finalStatus:"COMPLETE",coverage:settlement.kind==="COMPLETE"?{kind:"base",quality:"complete",provenance:"valid"}:settlement.kind==="PARTIAL"?{kind:"base",quality:"partial",provenance:"valid"}:{kind:"base",quality:"none",provenance:"valid"},findings}),sourceIdsByPolicyFindingId=new Map(findings.map((finding)=>[finding.id,Array.isArray(finding.sourceFindingIds)?finding.sourceFindingIds.filter((value)=>typeof value==="string"):[]])),blockingFindingIds=policyProjection.blockingFindingIds.flatMap((id)=>sourceIdsByPolicyFindingId.get(id)??[id]).sort();return{policyVersion:1,permittedVerdicts,blockingFindingIds}}function canonicalGitHubPrUrl(value,configured){return canonicalForgePrUrl(value,configured)}function assertMatchingPrReviewFeedbackConsent(record3,input){if(record3.session_id!==input.sessionID||record3.run_id!==input.runId||record3.handoff_path!==input.handoffPath||record3.handoff_digest!==input.handoffDigest||canonicalGitHubPrUrl(record3.pr_url)!==canonicalGitHubPrUrl(input.prUrl)||record3.pr_head_sha.toLowerCase()!==input.prHeadSha.toLowerCase()||record3.finding_ids_digest!==input.findingIdsDigest||record3.source_workflow_instance_id!==input.sourceWorkflowInstanceId)throw Error("BLOCKED: PR_REVIEW feedback consent artifact does not match the requested handoff; remove the stale sidecar or repeat the exact continuation offer")}function workflowIdentity(state2){return state2.workflowInstanceId??`legacy-${createHash59("sha256").update(`${state2.sessionID}\x00${state2.mode}\x00${state2.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(state2,relativePath,read,requestedPrUrl){let existing=state2.prFeedbackReviewHandoff;if(!existing)throw Error(`BLOCKED: session "${state2.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 "${state2.sessionID}" is already active in PR_FEEDBACK for a different handoff or PR`)}async function assertPrReviewTerminalReady(directory,sessionID,laneLiveness){let state2=await requireBoundState2(directory,sessionID,"PR_REVIEW");await assertPrReviewCleanCheckout(directory,"PR_REVIEW");let laneSettlement=await settlePresumedStalePrWorkflowLanes(directory,state2.sessionID,laneLiveness);if(laneSettlement.uncertainty)throw Error(`BLOCKED: PR_REVIEW transition refused while the delegation store is unreadable after ${laneSettlement.uncertainty.attempts} attempts (${laneSettlement.uncertainty.reason}); open lanes are UNKNOWN, not absent. Restore the store before transitioning.`);if(laneSettlement.openLanes>0)throw Error(`BLOCKED: PR_REVIEW transition has ${laneSettlement.openLanes} unsettled PR workflow lane(s)`+describePrWorkflowLaneProbe(laneSettlement));let ctx=await createPrReviewGateContext2(directory,state2),{settlement}=await assertPrReviewBaseCoverageSettled2(directory,sessionID,ctx);if(!state2.prReviewTriggerEvalPath)throw Error("BLOCKED: PR_REVIEW transition requires a persisted trigger evaluation artifact");if((state2.prReviewValidationBatches??[]).some((batch)=>batch.phase==="council"))await assertPrReviewValidationSettled(directory,sessionID,"council",ctx);await assertPrReviewValidationSettled(directory,sessionID,"reviewer",ctx);let criticInventory=derivePrReviewCriticInventoryForCoverageGate(directory,state2,ctx,"completePrWorkflow critic-coverage gate"),authoritativeCriticSettlements=[];if(criticInventory.length>0){if(!(state2.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),authoritativeCriticSettlements=deriveAuthoritativeCriticSettlements(directory,state2,ctx,criticInventory);let criticVerdicts=deriveLatestPrReviewCriticVerdicts(directory,state2,ctx),reviewerClaims=authoritativeReviewerClaims2(directory,state2,ctx),settledReceipts=[];for(let[itemId,verdict]of criticVerdicts){if(verdict.status!=="UPHELD"&&verdict.status!=="DOWNGRADED"&&verdict.status!=="DISPROVED")continue;let reviewerRowDigest=reviewerClaims.get(itemId)?.rowDigest;if(!reviewerRowDigest)continue;settledReceipts.push({findingId:itemId,status:verdict.status,reviewerRowDigest})}let criticSettlementEffective=verdictSettlementEffectiveIdsForGate(directory,state2,"critic",ctx);if(reducePrReviewEvent(state2,{type:"critic_result_recorded",criticRequiredFindingIds:criticInventory.filter((itemId)=>!criticSettlementEffective.has(itemId)),criticSettledReceipts:settledReceipts}).status==="rejected"){let settledIds=new Set(settledReceipts.map((r)=>r.findingId)),unfulfilled=criticInventory.filter((id)=>!settledIds.has(id));throw Error(`BLOCKED: PR_REVIEW reviewer verdicts require critic coverage for: ${unfulfilled.join(", ")}`)}}let requiredBoundaries=["post_explorer","post_reviewer","post_critic"],persistedBoundaries=new Set(state2.prReviewArtifactBoundaries??[]),missing=requiredBoundaries.filter((boundary)=>!persistedBoundaries.has(boundary));if(!state2.prReviewFindingsPath||missing.length>0)throw Error(`BLOCKED: PR_REVIEW transition requires durable findings checkpoints; missing: ${missing.join(", ")||"findings path"}`);if(state2.prReviewHandoffRequired&&!state2.prReviewHandoffPath)throw Error("BLOCKED: PR_REVIEW actionable findings require a persisted feedback handoff artifact");let criticSettlementIncomplete=authoritativeCriticSettlements.some((settlement2)=>!settlement2.terminal),findingPolicyAuthority=criticSettlementIncomplete?null:await readAuthoritativeFindingPolicy(directory,state2);if(!criticSettlementIncomplete&&criticInventory.length>0){let persistedSettlements=findingPolicyAuthority?.criticSettlements??[],actualById=new Map(authoritativeCriticSettlements.map((settlement2)=>[settlement2.findingId,settlement2]));if(persistedSettlements.length!==authoritativeCriticSettlements.length||persistedSettlements.some((settlement2)=>{let actual=actualById.get(settlement2.findingId);return!actual||actual.terminal!==settlement2.terminal||actual.status!==settlement2.status}))throw Error("BLOCKED: PR_REVIEW finding-policy critic settlements are stale or do not match the authenticated critic verdict map")}let reviewerReceipts=(state2.prReviewValidationBatches??[]).filter((batch)=>batch.phase==="reviewer").map((batch)=>({id:batch.batchId,valid:!0})),councilEnabled=(state2.prReviewValidationBatches??[]).some((batch)=>batch.phase==="council"),criticEnabled=criticInventory.length>0,policyReadiness=assessTerminalReadiness({baseReceipt:{id:"base-coverage-settlement",valid:Boolean((state2.prReviewBaseDispatches??[]).length>0||state2.prReviewBaseDispatch)},reviewerReceipts,criticReceipt:{id:"critic-coverage-settlement",valid:!criticEnabled||!criticSettlementIncomplete&&(state2.prReviewValidationBatches??[]).some((batch)=>batch.phase==="critic")},coverage:{kind:"base",quality:settlement.kind==="COMPLETE"?"complete":"partial",provenance:"valid"},council:{enabled:councilEnabled,receipt:councilEnabled?{id:"council-settlement",valid:!0}:null},criticSettlements:criticEnabled?authoritativeCriticSettlements:void 0});if(!policyReadiness.ready)throw Error(`BLOCKED: PR_REVIEW terminal finding readiness is incomplete: ${policyReadiness.blockers.join(", ")}`);return{state:state2,settlement}}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,expectedConsentSourceIdentity,sourceRevision=0,provenance;if(preliminary){if(preliminary.mode!=="PR_REVIEW")throw wrongModeError(preliminary,"PR_REVIEW");let ready=(await assertPrReviewTerminalReady(directory,normalizedSessionID,request.laneLiveness)).state;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),expectedConsentSourceIdentity=sourceIdentity,sourceRevision=ready.revision,provenance="active-review-v1"}else{let reservation=await readPrReviewRunReservation(directory,request.runId);if(!reservation||reservation.session_id!==normalizedSessionID||reservation.run_id!==request.runId)throw Error("BLOCKED: completed PR_REVIEW continuation requires the matching durable run reservation for this session");expectedConsentSourceIdentity=reservation.workflow_instance_id,sourceIdentity=expectedConsentSourceIdentity,provenance="external-v1"}let consent=await readPrReviewFeedbackConsent(directory,request.runId);if(!consent)throw Error("BLOCKED: PR_FEEDBACK continuation requires explicit confirmation; repeat the exact continuation command first");assertMatchingPrReviewFeedbackConsent(consent,{sessionID:normalizedSessionID,runId:request.runId,handoffPath:normalizedHandoff.relativePath,handoffDigest:preliminaryRead.digest,prUrl:artifact.pr_url,prHeadSha:artifact.pr_head_sha,findingIdsDigest:hashPrReviewFindingIds(artifact.finding_ids),sourceWorkflowInstanceId:expectedConsentSourceIdentity});let exactCommand=request.exactCommand?.trim(),acceptedContinuationCommands=buildAcceptedPrFeedbackContinuationCommands(consent.confirmation_command,normalizedHandoff.relativePath,request.prUrl);if(request.confirmedByUser!==!0||!exactCommand||!acceptedContinuationCommands.has(exactCommand))throw Error(`BLOCKED: PR_FEEDBACK continuation requires explicit confirmation with the offered command: ${consent.confirmation_command}`);return await _test_exports2.beforePrFeedbackTransitionLock?.(),withPrWorkflowCheckoutMutationLock(directory,()=>withSessionStateMutation(directory,normalizedSessionID,async()=>{let current=await readPrWorkflowGateStateFromDisk3(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");if(provenance==="external-v1"){let lockedReservation=await readPrReviewRunReservation(directory,request.runId);if(!lockedReservation||lockedReservation.session_id!==normalizedSessionID||lockedReservation.workflow_instance_id!==expectedConsentSourceIdentity)throw Error("BLOCKED: PR_REVIEW run reservation changed during external feedback transition")}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 lockedConsent=await readPrReviewFeedbackConsent(directory,request.runId);if(!lockedConsent)throw Error("BLOCKED: PR_REVIEW feedback consent artifact disappeared during transition");if(assertMatchingPrReviewFeedbackConsent(lockedConsent,{sessionID:normalizedSessionID,runId:request.runId,handoffPath:normalizedHandoff.relativePath,handoffDigest:lockedRead.digest,prUrl:lockedRead.artifact.pr_url,prHeadSha:lockedRead.artifact.pr_head_sha,findingIdsDigest:hashPrReviewFindingIds(lockedRead.artifact.finding_ids),sourceWorkflowInstanceId:expectedConsentSourceIdentity}),!buildAcceptedPrFeedbackContinuationCommands(lockedConsent.confirmation_command,normalizedHandoff.relativePath,request.prUrl).has(exactCommand))throw Error("BLOCKED: PR_FEEDBACK continuation command changed during transition");if(lockedConsent.state==="offered")await writePrReviewFeedbackConsent(directory,{...lockedConsent,state:"confirmed",confirmed_at:isoNow()});let timestamp=isoNow(),nextState={schemaVersion:GATE_SCHEMA_VERSION,revision:sourceRevision,workflowInstanceId:randomUUID17(),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 state2=await assertPrFeedbackVerificationSettled(directory,sessionID),revisionDigest=await currentPrFeedbackRevisionDigest(directory,state2),previous=state2.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 record3={taskId,files,revisionDigest,declaredAt:isoNow()},nextState={...state2,updatedAt:isoNow(),prFeedbackScopes:[...previous.filter((entry)=>entry.taskId!==taskId),record3]};return await persistState2(directory,nextState),nextState}async function resolvePrFeedbackScopeDeclaration(directory,sessionID,taskId){let state2=await readPrWorkflowGateState(directory,sessionID);if(state2?.mode!=="PR_FEEDBACK")return null;let declaration=(state2.prFeedbackScopes??[]).find((entry)=>entry.taskId===taskId);if(!declaration)return null;return await assertPrFeedbackVerificationSettled(directory,sessionID),await currentPrFeedbackRevisionDigest(directory,state2)===declaration.revisionDigest?declaration:null}async function consumePrFeedbackScopeDeclaration(directory,sessionID,taskId,callID,expected){let normalizedSessionID=normalizeSessionID(sessionID);return withSessionStateMutation(directory,normalizedSessionID,async()=>{let state2=await readPrWorkflowGateStateFromDisk3(directory,normalizedSessionID);if(!state2||state2.mode!=="PR_FEEDBACK")return null;let declaration=(state2.prFeedbackScopes??[]).find((entry)=>entry.taskId===taskId);if(!declaration)return null;if(declaration.declaredAt!==expected.declaredAt||declaration.revisionDigest!==expected.revisionDigest||JSON.stringify(declaration.files)!==JSON.stringify(expected.files))return null;if(await assertPrFeedbackVerificationSettledState(directory,state2)!==declaration.revisionDigest)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 consumed={...declaration,consumedByCallId:callID};return await writeStateWhileLocked(directory,{...state2,updatedAt:isoNow(),prFeedbackScopes:(state2.prFeedbackScopes??[]).map((entry)=>entry.taskId===taskId?consumed:entry)}),consumed})}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=[],callID){let state2=await readPrWorkflowGateState(directory,sessionID);if(!state2){let normalizedEarlyTool=toolName.toLowerCase();if(normalizedEarlyTool==="bash"||normalizedEarlyTool==="shell"){let earlyCommand=typeof args2?.command==="string"?args2.command.trim():"";if(/\bgit\b/.test(earlyCommand)&&(/\bpush\b/.test(earlyCommand)||/\bsend-pack\b/.test(earlyCommand))||/\bgh\s+api\b/i.test(earlyCommand)&&/refs\/heads\//.test(earlyCommand)){let dangling=findDanglingLivePublicationGeneration(directory,sessionID);if(dangling)throw Error(`BLOCKED: PR_FEEDBACK publication generation ${dangling.generation} for this session is live in the audit trail but its gate state is missing (deleted or moved by hand). Publication commands fail closed until the window is resolved: use abort_pr_workflow with kind "cancel-publication", cancel_publication: true, and a reason to record the audited no-publish terminal, or restore the gate state from backup.`)}}return}if(state2.mode==="PR_FEEDBACK"&&state2.prFeedbackReadyToPublish&&!state2.prFeedbackPublication)state2=await ensurePublicationGenerationCurrent(directory,sessionID)??state2;let normalizedTool=toolName.toLowerCase(),isDirectAgentTask=normalizedTool==="task"||normalizedTool==="run_agent",requestedAgentFields=["subagent_type","agent"].filter((field)=>Object.hasOwn(args2??{},field)),requestedRoles=requestedAgentFields.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(state2.mode,normalizedTool),isShellTool3=normalizedTool==="bash"||normalizedTool==="shell",isReadOnlyShell=!1,shellPermissionEnvelope=null;if(isShellTool3&&command.length>0){let trackingFetchTarget=state2.prHeadSha?await _test_exports2.resolveCurrentUpstreamPushTargetAsync(directory):null;shellPermissionEnvelope={allowCheckout:!state2.prHeadSha,allowFetch:!state2.prHeadSha,allowTrackingFetch:Boolean(state2.prHeadSha),trackingFetchTarget},isReadOnlyShell=isAllowedPrWorkflowReadOnlyShell(command,shellPermissionEnvelope)}let trustedCapability=getPrWorkflowToolCapability(normalizedTool,state2.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(state2.checkoutRecovery){if(isRecoverySafeEvidenceTool||isReadOnlyShell||normalizedTool==="abort_pr_workflow"||normalizedTool==="pr_workflow_status"||normalizedTool==="prepare_pr_workflow_checkout")return;throw Error(`BLOCKED: ${state2.mode} requires manual Git recovery before controller work can continue. code=${state2.checkoutRecovery.code} retryable=false required_action=${state2.checkoutRecovery.requiredAction}`)}if(state2.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 ${state2.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(state2.mode==="PR_REVIEW"){let hasAuthorizedDirectReentry=!1;if(isDirectAgentTask&&requestedAgentFields.length===1&&requestedAgentFields[0]==="subagent_type"&&requestedRoles.length===1&&(requestedRoles[0]==="reviewer"||requestedRoles[0]==="test_engineer")&&callID)hasAuthorizedDirectReentry=await hasActivePrReviewReentryAuthorization(directory,sessionID,{role:requestedRoles[0]});if(!(isInternalWorkflowTool||hasAuthorizedDirectReentry||isNamedReadOnlyTool||isReadOnlyShell&&(!isShellCheckout||isCanonicalReviewCheckout))||Boolean(state2.prHeadSha)&&(isRemoteCheckoutTool||isShellCheckout)){if(!state2.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(state2.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(state2.mode));if(state2.prHeadSha&&(isShellCheckout||isRemoteCheckoutTool))throw Error("BLOCKED: PR_FEEDBACK checkout is immutable after exact PR head binding");if(containsGitCommitShell&&state2.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(state2.prFeedbackReadyToPublish){if(normalizedTool==="complete_pr_workflow")return;if(normalizedTool==="invalidate_pr_feedback_publication")return;if(normalizedTool==="abort_pr_workflow"&&args2?.cancel_publication===!0)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,{currentCallId:callID})).prFeedbackReadyToPublish,intent=parseExactBoundPushIntent(command,armed);if(intent.ok&&intent.intent&&intent.digest){await admitPrFeedbackPushAttempt(directory,sessionID,callID,intent.intent,intent.digest);return}throw Error(`BLOCKED: PR_FEEDBACK is armed for publication; only the exact approved push is allowed: ${expectedBoundPushCommand(armed)}${intent.reason?` (rejected form: ${intent.reason})`:""}`)}throw Error("BLOCKED: PR_FEEDBACK is armed for publication; only read-only inspection, the exact approved push, and complete_pr_workflow are allowed. To change approved content, use invalidate_pr_feedback_publication (audited invalidation; the full ladder re-runs) or abort_pr_workflow with cancel_publication for a terminal no-publish cancellation")}if(!state2.prHeadSha&&normalizedTool==="prepare_pr_workflow_checkout")return;if(!state2.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(!state2.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(!state2.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 readPrReviewReentryBindingContext(directory,sessionID){let state2=await readPrWorkflowGateStateFromDisk3(directory,normalizeSessionID(sessionID));return state2?prReviewReentryBindingFromState(directory,state2):null}async function prReviewReentryBindingFromState(directory,state2){if(state2.mode!=="PR_REVIEW"||!state2.prHeadSha)return null;let ctx=await createPrReviewGateContext2(directory,state2);return{prHeadSha:state2.prHeadSha,revisionDigest:ctx.revisionDigest,generation:state2.revision,...state2.workflowInstanceId?{workflowInstanceId:state2.workflowInstanceId}:{},...state2.prReviewArtifactRunId??state2.prReviewReservedRunId?{runId:state2.prReviewArtifactRunId??state2.prReviewReservedRunId??void 0}:{}}}async function hasActivePrReviewReentryAuthorization(directory,sessionID,request){let normalizedSessionID=normalizeSessionID(sessionID);return withSessionStateMutation(directory,normalizedSessionID,async()=>{let state2=await readPrWorkflowGateStateFromDisk3(directory,normalizedSessionID);if(!state2)return!1;let binding=await prReviewReentryBindingFromState(directory,state2);if(!binding)return!1;return hasPrReviewReentryAuthorizationAgainstBinding(directory,normalizedSessionID,request,binding)})}async function reserveActivePrReviewReentryAuthorization(directory,sessionID,request){let normalizedSessionID=normalizeSessionID(sessionID);return withSessionStateMutation(directory,normalizedSessionID,async()=>{let state2=await readPrWorkflowGateStateFromDisk3(directory,normalizedSessionID);if(!state2)return null;let binding=await prReviewReentryBindingFromState(directory,state2);if(!binding)return null;return await _test_exports2.beforePrReviewReentryReservation?.(),reservePrReviewReentryAuthorizationAgainstBinding(directory,normalizedSessionID,request,binding)})}async function completePrWorkflow(directory,sessionID,expectedMode,prHeadSha,options){let state2=await requireBoundState2(directory,sessionID,expectedMode),normalizedHead=normalizePrHeadSha(prHeadSha);if(state2.prHeadSha!==normalizedHead)throw Error(`BLOCKED: cannot complete ${expectedMode} at PR head "${normalizedHead}"; workflow is bound to "${state2.prHeadSha}"`);let laneSettlement=await settlePresumedStalePrWorkflowLanes(directory,state2.sessionID,options?.laneLiveness);if(laneSettlement.uncertainty)throw Error(`BLOCKED: ${expectedMode} completion refused while the delegation store is unreadable after ${laneSettlement.uncertainty.attempts} attempts (${laneSettlement.uncertainty.reason}); open lanes are UNKNOWN, not absent. Restore the store and re-run completion (a healthy empty store still completes through its valid INCOMPLETE route).`);if(laneSettlement.openLanes>0)throw Error(`BLOCKED: ${expectedMode} completion has ${laneSettlement.openLanes} unsettled PR workflow lane(s)`+describePrWorkflowLaneProbe(laneSettlement));let terminalClearRevision;if(expectedMode==="PR_REVIEW"){let verdict=options?.reportVerdict;if(verdict===void 0)throw Error("BLOCKED: PR_REVIEW completion requires a terminal report_verdict (APPROVE, REQUEST_CHANGES, or INCOMPLETE)");let ctx=await createPrReviewGateContext2(directory,state2),settlement=derivePrReviewDimensionSettlement(directory,state2,ctx.revisionDigest),disclosedDegradation=settlement.kind==="COMPLETE"&&(prReviewReceiptHasCoverageDegradations(directory,state2.prReviewTriggerEvalPath)||await verdictSettlementDegradesReport(directory,state2,ctx)),dispatchCoverageFinalization=(finalizationSettlement)=>{let outcome=reducePrReviewEvent(state2,{type:"coverage_finalization_requested",settlement:{kind:finalizationSettlement.kind,coveredDimensions:finalizationSettlement.coveredDimensions,unresolvedDimensions:finalizationSettlement.unresolvedDimensions,liveDimensions:finalizationSettlement.liveDimensions},requestedVerdict:verdict,disclosedDegradation});if(outcome.status==="applied")return;let{code}=outcome.rejection;if(code==="live_lane_blocks_coverage"){if(finalizationSettlement.kind==="NO_COVERAGE")throw Error(`BLOCKED: PR_REVIEW completion has zero covered dimensions and still-live lanes for: ${finalizationSettlement.liveDimensions.join(", ")}. Collect or settle them, then complete with report_verdict INCOMPLETE.`);throw Error(`BLOCKED: PR_REVIEW base coverage is incomplete and still has live lanes for: ${finalizationSettlement.liveDimensions.join(", ")}. Completion is allowed only once every launched lane is terminal or explicitly cancelled.`)}if(code==="no_coverage_requires_incomplete")throw Error(`BLOCKED: PR_REVIEW NO_COVERAGE completion must report verdict INCOMPLETE; got "${verdict}". A zero-coverage report never approves and never claims a code-quality review.`);if(code==="degraded_disclosure_cannot_approve")throw Error(`BLOCKED: PR_REVIEW ${finalizationSettlement.kind} completion discloses a coverage degradation (dead family or dead verdict lane) and cannot report verdict APPROVE; got "${verdict}". Report REQUEST_CHANGES with the disclosed degradation surfaced in the report, or INCOMPLETE.`);let allowedList=allowedPrReviewReportVerdicts(finalizationSettlement.kind,[],{disclosedCoverageDegradation:disclosedDegradation}).join(" | ");throw Error(`BLOCKED: PR_REVIEW ${finalizationSettlement.kind} completion allows report_verdict ${allowedList}; got "${verdict}". Partial coverage never approves and never claims a full review.`)};if(settlement.kind==="PARTIAL"||settlement.kind==="NO_COVERAGE"){let stagedPolicyEnabled=state2.prReviewResilience?.policy?.enabled===!0,consumedLegacyContractRetry=new Set(state2.prReviewContractRetryDimensions??[]),attemptsUsed=state2.prReviewResilience?.attempts?.length??0,maxAttempts=1+(state2.prReviewResilience?.policy?.maxRetryAttemptsAfterInitial??0),retryableRemainder=settlement.unresolvedDimensions.filter((entry)=>{if(entry.failureClass==="operator_cancelled")return!1;if(stagedPolicyEnabled)return entry.failureClass==="contract"||entry.failureClass==="resource";return entry.failureClass==="contract"&&!consumedLegacyContractRetry.has(entry.dimension)});if(retryableRemainder.length>0&&attemptsUsed<maxAttempts){try{appendCoreEventSync(directory,{type:"pr_review_completion_retryable_remainder",timestamp:isoNow(),sessionID:state2.sessionID,prHeadSha:state2.prHeadSha,coverageKind:settlement.kind,remainingDimensions:retryableRemainder.map((entry)=>`${entry.dimension}:${entry.terminalState}:${entry.failureClass??"none"}`),attemptsUsed,maxAttempts,stagedPolicyEnabled})}catch{}throw Error(`BLOCKED: PR_REVIEW ${settlement.kind} completion refused while eligible retryable work remains and retry budget is available. Remaining dimensions: ${retryableRemainder.map((entry)=>`${entry.dimension} (${entry.failureClass})`).join(", ")}. Retry budget: ${attemptsUsed}/${maxAttempts} attempts used${stagedPolicyEnabled?" (staged policy)":" (legacy single contract retry)"} — re-dispatch the dimension(s) via dispatch_lanes_async to consume the retry budget, or end the workflow through the human force path (/swarm abort-pr-workflow). If lanes are still live at an earlier stage, settle them explicitly first — cancel_lane_batch (confirm: true + reason) refuses busy/retry lanes, so live work is never destroyed on the model path.`)}}if(dispatchCoverageFinalization(settlement),settlement.kind==="NO_COVERAGE"){let noCoverageRunId=state2.prReviewArtifactRunId??state2.prReviewReservedRunId??generatePrReviewRunId();terminalClearRevision=(await admitPrReviewPartialBaseCoverage2(directory,sessionID,noCoverageRunId,settlement.unresolvedDimensions.map((entry)=>entry.dimension))).revision;try{appendCoreEventSync(directory,{type:"pr_review_no_coverage_terminal",timestamp:isoNow(),sessionID:state2.sessionID,prHeadSha:state2.prHeadSha,revisionDigest:ctx.revisionDigest,coveredDimensions:settlement.coveredDimensions.length,unresolvedDimensions:settlement.unresolvedDimensions.map((entry)=>`${entry.dimension}:${entry.terminalState}`),disclosureRunId:noCoverageRunId,reportVerdict:verdict})}catch{}}else{let preAllowed=allowedPrReviewReportVerdicts(settlement.kind,[],{disclosedCoverageDegradation:disclosedDegradation});if(!preAllowed.includes(verdict))throw Error(`BLOCKED: PR_REVIEW ${settlement.kind} completion allows report_verdict ${preAllowed.join(" | ")}; got "${verdict}". Partial coverage never approves and never claims a full review.`);let ready=await assertPrReviewTerminalReady(directory,sessionID,options?.laneLiveness),readyState=ready.state;if(workflowIdentity(readyState)!==workflowIdentity(state2)||readyState.revision!==state2.revision)throw Error("BLOCKED: PR_REVIEW state changed while checking terminal readiness; retry from current state");if(ready.settlement.kind==="COMPLETE")disclosedDegradation=prReviewReceiptHasCoverageDegradations(directory,readyState.prReviewTriggerEvalPath)||await verdictSettlementDegradesReport(directory,readyState);dispatchCoverageFinalization(ready.settlement);let finalFindingAuthority=await readAuthoritativeFindingPolicy(directory,readyState),policyAllowed=allowedPrReviewReportVerdicts(ready.settlement.kind,finalFindingAuthority.policyFindings,{disclosedCoverageDegradation:disclosedDegradation});if(!policyAllowed.includes(verdict))throw Error(`BLOCKED: PR_REVIEW ${ready.settlement.kind} completion allows report_verdict ${policyAllowed.join(" | ")}; got "${verdict}". Final finding policy and coverage do not permit this report.`)}}else{await ensurePublicationGenerationCurrent(directory,sessionID);let readyState=await assertPrFeedbackReadyToPublish(directory,sessionID);readyState=await reconcileForeignInFlightAttempt(directory,sessionID)??readyState;let currentDigest=await currentPrFeedbackRevisionDigest(directory,readyState),armed=readyState.prFeedbackReadyToPublish;if(!armed){let previousActive=readyState.prFeedbackPublication?.active;if(previousActive?.state==="published"){if((await _test_exports2.resolveExactRemoteBranchHeadAsync(directory,previousActive.remoteName,previousActive.remoteBranchRef))?.toLowerCase()!==previousActive.localHead.toLowerCase())throw Error(`BLOCKED: PR_FEEDBACK generation ${previousActive.generation} is marked published but the remote verification no longer holds; inspect pr_workflow_status`);return await _test_exports2.beforeTerminalClear?.(),await clearPrWorkflowGateState(directory,sessionID,readyState.revision),"completed"}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,state2.prHeadSha,localHead);if(commitCount===0){if(localHead!==state2.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=readLegacySettledFeedbackClassifications(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{appendCoreEventSync(directory,{type:"pr_feedback_verified_no_change",timestamp:isoNow(),sessionID:state2.sessionID,prHeadSha:state2.prHeadSha,items:inventory.length})}catch{}if(previousActive&&previousActive.state==="invalidated")appendPublicationEvent(directory,{type:"pr_feedback_publication_cancelled",sessionID:state2.sessionID,generation:previousActive.generation,reason:"verified-no-change-terminal"});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,state2.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");if(previousActive&&previousActive.state!=="invalidated")throw Error(`BLOCKED: PR_FEEDBACK cannot arm a new publication generation while generation ${previousActive.generation} is ${previousActive.state}`);let workspaceIdentity=canonicalWorkspaceIdentity(directory);if(!workspaceIdentity)throw Error("BLOCKED: PR_FEEDBACK cannot arm publication without a canonical workspace identity");let localHeadRef=await _test_exports2.resolveCurrentLocalHeadRefAsync(directory);if(!localHeadRef)throw Error("BLOCKED: PR_FEEDBACK cannot arm publication without the current branch ref (HEAD appears detached)");let remoteUrlIdentity=await _test_exports2.resolveRemoteUrlIdentityAsync(directory,upstreamTarget.remoteName);if(!remoteUrlIdentity)throw Error(`BLOCKED: PR_FEEDBACK cannot arm publication without a credential-redacted remote URL identity for "${upstreamTarget.remoteName}"`);let evidenceJoin=buildPublicationEvidenceJoin(readyState,currentDigest);if(!evidenceJoin)throw Error("BLOCKED: PR_FEEDBACK cannot arm publication without the exact settled receipt set (Stage A plus one batch per ordered phase)");let armedAt=isoNow(),generation={schemaVersion:PUBLICATION_SCHEMA_VERSION,generation:(previousActive?.generation??0)+1,state:"armed",workspaceIdentity,sessionID:readyState.sessionID,prTargetUrl:readyState.prFeedbackTargetUrl,intakeHeadSha:readyState.prHeadSha??"unknown",localHeadRef,localHead,remoteName:upstreamTarget.remoteName,remoteUrlIdentity,remoteBranchRef:upstreamTarget.remoteBranchRef,remoteRef:upstreamTarget.remoteTrackingRef,revisionDigest:currentDigest,evidence:evidenceJoin,createdAt:armedAt,armedAt};return await persistState2(directory,{...readyState,updatedAt:armedAt,prFeedbackReadyToPublish:deriveReadyToPublishMirror(generation),prFeedbackPublication:nextPublicationContainer(readyState.prFeedbackPublication,generation,previousActive?[{...previousActive,supersededByGeneration:generation.generation}]:[],[])}),appendPublicationEvent(directory,{type:"pr_feedback_publication_armed",sessionID:readyState.sessionID,generation:generation.generation,supersedes:previousActive?.generation??null,revisionDigest:currentDigest,localHead,remoteName:upstreamTarget.remoteName,remoteUrlIdentity,remoteBranchRef:upstreamTarget.remoteBranchRef}),"ready-to-publish"}let armedState=await assertPrFeedbackPublicationArmed(directory,sessionID),active=armedState.prFeedbackPublication?.active;if(!active)throw Error("BLOCKED: PR_FEEDBACK publication is not armed; call complete_pr_workflow once after every ordered gate passes");let attemptsForGeneration=(armedState.prFeedbackPublication?.attempts??[]).filter((attempt)=>attempt.generation===active.generation);if(!attemptsForGeneration.some((attempt)=>attempt.result))throw Error(`BLOCKED: PR_FEEDBACK completion requires the exact approved push to have been admitted and observed for generation ${active.generation}; run the exact push first: ${expectedBoundPushCommand(armed)}`);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`);let publishedAt=isoNow(),published={...active,state:"published",publishedAt},publishState={...armedState,updatedAt:publishedAt,prFeedbackReadyToPublish:void 0,prFeedbackPublication:nextPublicationContainer(armedState.prFeedbackPublication,published)};return await persistState2(directory,publishState),appendPublicationEvent(directory,{type:"pr_feedback_published",sessionID:armedState.sessionID,generation:published.generation,localHead:published.localHead,remoteName:published.remoteName,remoteBranchRef:published.remoteBranchRef,remoteUrlIdentity:published.remoteUrlIdentity??null,revisionDigest:published.revisionDigest,attempts:attemptsForGeneration.length}),await _test_exports2.beforeTerminalClear?.(),await clearPrWorkflowGateState(directory,sessionID,publishState.revision),"completed"}return await _test_exports2.beforeTerminalClear?.(),await clearPrWorkflowGateState(directory,sessionID,terminalClearRevision??state2.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 state2=await readPrWorkflowGateState(directory,sessionID);if(!state2)throw noActiveGateError(sessionID);return state2}async function requireBoundState2(directory,sessionID,expectedMode){let state2=await requireAnyActiveState(directory,sessionID);if(state2.mode!==expectedMode)throw wrongModeError(state2,expectedMode);if(!state2.prHeadSha)throw Error(`BLOCKED: active ${expectedMode} workflow is not bound to a PR head`);if(expectedMode==="PR_REVIEW")await assertCurrentCheckoutHead(directory,state2.prHeadSha,"PR_REVIEW"),await assertPrReviewCleanCheckout(directory);return state2}function wrongModeError(state2,expectedMode){return Error(`BLOCKED: session "${state2.sessionID}" is active in ${state2.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 tokens2=toolName.split(/[._:/-]+/).filter(Boolean);if(tokens2.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 tokens2.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(path120,constraint,value){return{safe:!1,path:path120||"(root)",constraint,value}}function readOnlyArgumentPath(parent,key2){return parent?`${parent}.${key2}`:key2}function isDeclaredReadOnlyMethod(toolName,value){if(!PR_REVIEW_TOOLS_WITH_ENUMERATED_READ_METHODS.has(toolName))return!1;return PR_REVIEW_ENUMERATED_READ_METHODS.has(value.trim().toLowerCase())}function classifyReadOnlyToolArguments(toolName,value,key2="",path120="",depth=0){if(depth>8)return unsafeReadOnlyArgument(path120,"argument nesting exceeds the read-only depth limit of 8",value);let keyTokens=key2.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(path120,"argument name is mutation-bearing and is not allowed for read-only tools",value);if(keyTokens.some((token)=>/^(?:method|verb)$/i.test(token))){if(typeof value!=="string")return unsafeReadOnlyArgument(path120,"HTTP method/verb must be GET or HEAD for a read-only tool",value);if(/^(?:GET|HEAD)$/i.test(value.trim()))return{safe:!0};if(isDeclaredReadOnlyMethod(toolName,value))return{safe:!0};return unsafeReadOnlyArgument(path120,"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(path120,"action/operation must name a recognized observation operation",value);if(/^mode$/i.test(key2)&&typeof value==="string")return(toolName==="search"?/^(?:r|rb|read|literal|regex)$/i:/^(?:r|rb|read)$/i).test(value.trim())?{safe:!0}:unsafeReadOnlyArgument(path120,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(path120,"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(path120,"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],key2,`${path120}[${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(path120,childKey),depth+1);if(!result.safe)return result}return{safe:!0}}return unsafeReadOnlyArgument(path120,"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 tokens2=[],current="",quoted2=!1,quote=null,pipeIsDoubleQuoted=!0,flush=()=>{if(current.length>0||quoted2)tokens2.push({value:current,quoted:quoted2,pipeIsDoubleQuoted});current="",quoted2=!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==='"'){quoted2=!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=tokens2.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],gitGrepPattern=resolveGitGrepRegexPatternOperand(tokens2);if(gitGrepPattern!==null&&gitGrepPattern===quotedPipeToken&"edPipeToken.pipeIsDoubleQuoted)return{unsafe:!1,reason:null};if(!/^gh\s+api(?:\s|$)/i.test(compact))return{unsafe:!0,reason:"gh-api-jq-pipe"};for(let index=0;index<tokens2.length;index+=1)if(tokens2[index].value==="--jq"&&tokens2[index+1]===quotedPipeToken)return{unsafe:!1,reason:null};return{unsafe:!0,reason:"gh-api-jq-pipe"}}function resolveGitGrepRegexPatternOperand(tokens2){if(tokens2.length===0||tokens2[0].value!=="git")return null;let index=1;while(index<tokens2.length){let value=tokens2[index].value;if(/^--[\w-]+=/.test(value)){index+=1;continue}if(value==="-C"){index+=2;continue}if(value.startsWith("-C=")||value.startsWith("-C")&&value.length>2){index+=1;continue}if(value==="-c"){index+=2;continue}if(value.startsWith("-C")&&value.length>2){index+=1;continue}if(value==="--"){index+=1;break}if(value.startsWith("-")){index+=1;continue}break}if(tokens2[index]?.value!=="grep")return null;index+=1;let extendedRegexp=!1,operand=null;for(;index<tokens2.length;index+=1){let token=tokens2[index],value=token.value;if(value==="--extended-regexp"){extendedRegexp=!0;continue}if(value.startsWith("--"))continue;if(value.startsWith("-")&&/^-\w+$/.test(value)){if(/[Ee]/.test(value.slice(1)))extendedRegexp=!0;continue}operand=token;break}if(!extendedRegexp)return null;return operand}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 or a double-quoted `git grep -E` pattern operand; 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 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 tokens2=gitArgs.trim().split(/\s+/);if(tokens2.length!==3||tokens2[0].toLowerCase()!=="fetch")return!1;let[,remote,remoteBranch]=tokens2,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 tokens2=gitArgs.trim().split(/\s+/);if(tokens2.length===5){let[verb,createFlag,localBranch,trackFlag,upstream]=tokens2;return(verb==="checkout"||verb==="switch")&&(createFlag==="-b"||createFlag==="-c")&&trackFlag==="--track"&&isSafeGitRefToken(localBranch)&&isSafeGitRefToken(upstream)&&upstream.includes("/")}if(tokens2.length===3&&tokens2[0]==="branch"){let upstream=tokens2[1].match(/^--set-upstream-to=(.+)$/)?.[1];return Boolean(upstream&&isSafeGitRefToken(upstream)&&upstream.includes("/")&&isSafeGitRefToken(tokens2[2]))}return!1}function isAllowedReadOnlyGitBranchListing(gitArgs){let tokens2=gitArgs.trim().split(/\s+/);if(tokens2.length===0||tokens2[0].toLowerCase()!=="branch")return!1;let listingSelectorInEffect=!1;for(let index=1;index<tokens2.length;index+=1){let token=tokens2[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 tokens2=gitArgs.trim().split(/\s+/);if(tokens2.length<2||tokens2[0].toLowerCase()!=="stash")return!1;if(tokens2[1].toLowerCase()!=="list")return!1;for(let index=2;index<tokens2.length;index+=1){let token=tokens2[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 tokens2=gitArgs.trim().split(/\s+/);if(tokens2.length<2||tokens2[0].toLowerCase()!=="worktree")return!1;if(tokens2[1].toLowerCase()!=="list")return!1;for(let index=2;index<tokens2.length;index+=1){let token=tokens2[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 tokens2=command.trim().split(/\s+/);if(tokens2.length<4||tokens2[0]!=="gh"||tokens2[1]!=="pr"||tokens2[2]!=="checkout")return!1;let target=tokens2[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<tokens2.length;index+=1){let token=tokens2[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=tokens2[++index];if(!repo||!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repo))return!1;continue}if(token==="--branch"||token==="-b"){let branch=tokens2[++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,state2){if(!state2.prHeadSha)throw Error("BLOCKED: PR_FEEDBACK revision binding requires pr_head_sha");let resolved=await resolvePrWorkflowRevisionDigestForGate(directory,state2.prHeadSha);if(!resolved.ok)throw Error(`BLOCKED: PR_FEEDBACK could not compute a bounded current-revision digest for pr_head_sha "${state2.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 digest3=_test_exports2.resolvePrWorkflowRevisionDigest(directory,baseHeadSha);return digest3?{ok:!0,digest:digest3}:{ok:!1,reason:"seam-unavailable"}}return resolvePrWorkflowRevisionDigestDetailedAsync(directory,baseHeadSha)}async function createPrReviewGateContext2(directory,state2){if(!state2.prHeadSha)throw Error("BLOCKED: PR_REVIEW revision binding requires pr_head_sha");let resolved=await resolvePrWorkflowRevisionDigestForGate(directory,state2.prHeadSha);if(!resolved.ok)throw Error(`BLOCKED: PR_REVIEW could not compute a bounded current-revision digest for pr_head_sha "${state2.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 derivePrReviewCandidateInventory2(directory,state2,ctx){if(ctx.candidateInventory)return ctx.candidateInventory;let sources=[],baseDimensionSources=new Map,baseSourceCreditedDimensions=new Map,baseSourceFullOwnershipCount=new Map,reversedBaseBatches=[...state2.prReviewBaseDispatches??[]].reverse(),successfulByBaseBatchId=new Map;for(let batch of reversedBaseBatches)successfulByBaseBatchId.set(batch.batchId,successfulObligationsFromExactBatch2(directory,state2,batch.batchId,batch.lanes,"swarm-pr-review:base",batch.validatedAt,!0,new Set,ctx.revisionDigest));let laneClassPasses=(state2.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;let creditedDimensions=ownedDimensions.filter((dimension)=>successful2.has(dimension));if(creditedDimensions.length===0)continue;let key2=`${batch.batchId}\x00${lane.laneId}`;baseSourceFullOwnershipCount.set(key2,ownedDimensions.length);for(let dimension of creditedDimensions)if(!baseDimensionSources.has(dimension)){baseDimensionSources.set(dimension,{batchId:batch.batchId,laneId:lane.laneId});let credited=baseSourceCreditedDimensions.get(key2);if(credited)credited.push(dimension);else baseSourceCreditedDimensions.set(key2,[dimension])}}}let seenBaseSourceKeys=new Set;for(let{batchId,laneId}of baseDimensionSources.values()){let key2=`${batchId}\x00${laneId}`;if(seenBaseSourceKeys.has(key2))continue;seenBaseSourceKeys.add(key2);let credited=baseSourceCreditedDimensions.get(key2),fullOwnershipCount=baseSourceFullOwnershipCount.get(key2)??0;sources.push({batchId,laneId,mode:"swarm-pr-review:base",creditedLanes:credited&&credited.length<fullOwnershipCount?credited:void 0})}let selectedCouncilLanes=new Set;if(state2.prReviewTriggerEvalPath)for(let batch of[...state2.prReviewValidationBatches??[]].reverse()){if(batch.phase!=="council")continue;let successful2=successfulObligationsFromExactBatch2(directory,state2,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(state2.prReviewTriggerEvalPath){let receiptRead=readPrReviewTriggerReceiptForGate(directory,state2.prReviewTriggerEvalPath),receipt="noReceipt"in receiptRead?null:receiptRead.receipt;if(!receipt)throw Error("BLOCKED: PR_REVIEW trigger evaluation artifact is missing or invalid");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,sourceRead=findByBatchIdDetailed(directory,source.batchId,{parentSessionId:state2.sessionID});if(sourceRead.status==="uncertain")throw Error(`BLOCKED: PR_REVIEW discovery provenance cannot be read for ${source.workflowLane??source.laneId}: the delegation store is unreadable after ${sourceRead.attempts} attempts (${sourceRead.reason}); the lane's records are UNKNOWN, not absent. Restore the store and re-run discovery.`);for(let record3 of sourceRead.value){if(record3.laneId!==source.laneId||record3.mode!==source.mode||record3.workspace?.prHeadSha!==state2.prHeadSha||record3.workspace?.gitHead!==state2.prHeadSha)continue;let structured=record3.result?.prReviewResultReceipt;if(structured){let credited=source.creditedLanes?.length?structured.envelope.creditedLanes.filter((lane)=>source.creditedLanes?.includes(lane)):structured.envelope.creditedLanes;if(source.workflowLane&&!credited.includes(source.workflowLane))continue;resolvedArtifact=!0;let laneKey2=`${source.batchId}\x00${source.laneId}`;if(!extractedLaneKeys.has(laneKey2)){extractedLaneKeys.add(laneKey2);for(let finding of structured.envelope.findings){if(!credited.includes(finding.workflowLane))continue;if(candidateIds.push(finding.id),!candidateSeverities.has(finding.id))candidateSeverities.set(finding.id,finding.severity)}}continue}let ref=record3.result?.outputRef?.trim(),artifact=ref?readLaneOutput(directory,ref)?.artifact:void 0,recordOwnedLanes=record3.ownedWorkflowLanes?.length?record3.ownedWorkflowLanes:record3.workflowLane?[record3.workflowLane]:void 0;if(!artifact||!workflowArtifactHasContractMarker(directory,state2,record3,source.mode,record3.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_CHARS2));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 normalizeCandidateArtifactCached(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 issue3 of analysis.issues)appendBoundedCandidateIssue(issues,`row ${index+1} field ${issue3.field}: ${issue3.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,state2,ctx){if(!ctx.candidateSeverities)derivePrReviewCandidateInventory2(directory,state2,ctx);if(!ctx.candidateSeverities)throw Error("BLOCKED: PR_REVIEW candidate severity authority is unavailable for this gate context");return ctx.candidateSeverities}function prReviewPhaseWindow2(state2,phase){let all=state2.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 reviewerSubagentSessionIds2(directory,state2){let forbidden=new Set(state2.prReviewRetiredReviewerSessionIds??[]);for(let reviewerBatch of(state2.prReviewValidationBatches??[]).filter((batch)=>batch.phase==="reviewer")){let batchRead=findByBatchIdDetailed(directory,reviewerBatch.batchId,{parentSessionId:state2.sessionID});if(batchRead.status==="uncertain")throw Error(`BLOCKED: PR_REVIEW critic reuse ban cannot be derived: the delegation store is unreadable after ${batchRead.attempts} attempts (${batchRead.reason}); reviewer batch ${reviewerBatch.batchId}'s child sessions are UNKNOWN, not absent. Restore the store and re-derive.`);for(let record3 of batchRead.value){let subagentSessionId=record3.subagentSessionId?.trim();if(subagentSessionId)forbidden.add(subagentSessionId)}}return forbidden}function batchMayContributeClaims2(directory,state2,batch,phase,requiredInventory,forbiddenSubagentSessionIds,reviewerClaims,ctx){let coherence=state2.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=successfulObligationsFromExactBatch2(directory,state2,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 admittedVerdictSettlementReceipt(directory,state2,phase,expectedRevisionDigest){let runId=state2.prReviewArtifactRunId??state2.prReviewReservedRunId;if(!runId)return;let read=readVerdictSettlementReceipt(directory,runId,phase);if(read.status!=="ok")return;if(read.receipt.runId!==runId||read.receipt.phase!==phase)return;if(read.receipt.prHeadSha!==state2.prHeadSha)return;if(read.receipt.revisionDigest!==expectedRevisionDigest)return;let anchoredDigest=state2.prReviewVerdictSettlementDigests?.[phase];if(!anchoredDigest||anchoredDigest!==read.rawSha256)return;return read.receipt}function settlementCoveringAllUnclaimed(directory,state2,phase,unclaimed,expectedRevisionDigest){if(unclaimed.length===0)return;let receipt=admittedVerdictSettlementReceipt(directory,state2,phase,expectedRevisionDigest);if(!receipt)return;return effectiveVerdictSettlementItems(receipt,unclaimed).length===unclaimed.length?receipt:void 0}function verdictSettlementEffectiveIdsForGate(directory,state2,phase,ctx){let composed=composePrReviewPhaseVerdicts(directory,state2,phase,ctx),receipt=settlementCoveringAllUnclaimed(directory,state2,phase,composed.unclaimed,ctx.revisionDigest);if(!receipt)return new Set;return new Set(effectiveVerdictSettlementItems(receipt,composed.unclaimed).map((item)=>item.itemId))}async function verdictSettlementDegradesReport(directory,state2,ctx){let gateCtx=ctx??await createPrReviewGateContext2(directory,state2);return verdictSettlementDegradationActive({directory,runId:state2.prReviewArtifactRunId??state2.prReviewReservedRunId,prHeadSha:state2.prHeadSha,revisionDigest:gateCtx.revisionDigest,reviewerUnclaimed:composePrReviewPhaseVerdicts(directory,state2,"reviewer",gateCtx).unclaimed,criticUnclaimed:composePrReviewPhaseVerdicts(directory,state2,"critic",gateCtx).unclaimed})}function authoritativeReviewerClaims2(directory,state2,ctx){let composed=composePrReviewPhaseVerdicts(directory,state2,"reviewer",ctx);if(composed.unclaimed.length===0)return composed.claims;return settlementCoveringAllUnclaimed(directory,state2,"reviewer",composed.unclaimed,ctx.revisionDigest)?composed.claims:new Map}function criticReviewerItemBindings(directory,state2,lanes,ctx){let reviewerClaims=authoritativeReviewerClaims2(directory,state2,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 derivePrReviewCriticInventory2(directory,state2,ctx){return[...authoritativeReviewerVerdictsForGate(directory,state2,ctx,"derivePrReviewCriticInventory").entries()].filter(([,verdict])=>prReviewFindingRequiresCritic({classification:verdict.classification,severity:verdict.severity,risk_impact:verdict.riskImpact,risk_tags:verdict.riskTags})).map(([itemId])=>itemId).sort()}function deriveLatestPrReviewCriticVerdicts(directory,state2,ctx){let composed=composePrReviewPhaseVerdicts(directory,state2,"critic",ctx);if(composed.unclaimed.length>0&&!settlementCoveringAllUnclaimed(directory,state2,"critic",composed.unclaimed,ctx.revisionDigest))return new Map;return new Map([...composed.claims].map(([itemId,claim])=>[itemId,{status:claim.classification,severity:claim.severity}]))}function deriveAuthoritativeCriticSettlements(directory,state2,ctx,criticInventory){let verdicts=deriveLatestPrReviewCriticVerdicts(directory,state2,ctx),unavailableIds=verdictSettlementEffectiveIdsForGate(directory,state2,"critic",ctx);return criticInventory.map((findingId2)=>{let verdict=verdicts.get(findingId2);if(unavailableIds.has(findingId2)&&(!verdict||verdict.status==="NEEDS_MORE_EVIDENCE"))return{findingId:findingId2,terminal:!0,status:"CRITIC_UNAVAILABLE"};if(!verdict||verdict.status==="NEEDS_MORE_EVIDENCE")return{findingId:findingId2,terminal:!1,status:"NEEDS_MORE_EVIDENCE"};if(verdict.status==="UPHELD"||verdict.status==="DOWNGRADED"||verdict.status==="DISPROVED")return{findingId:findingId2,terminal:!0,status:verdict.status};return{findingId:findingId2,terminal:!1,status:"NEEDS_MORE_EVIDENCE"}})}async function readPrReviewVerdictSettlementReceiptItems(directory,sessionID){let state2=await requireBoundState2(directory,sessionID,"PR_REVIEW"),ctx=await createPrReviewGateContext2(directory,state2),rows=[];for(let phase of["reviewer","critic"]){let composed=composePrReviewPhaseVerdicts(directory,state2,phase,ctx),receipt=settlementCoveringAllUnclaimed(directory,state2,phase,composed.unclaimed,ctx.revisionDigest);if(!receipt)continue;for(let item of effectiveVerdictSettlementItems(receipt,composed.unclaimed))rows.push({...item})}return rows}async function readPrReviewVerdictSettlementEffectiveIds(directory,sessionID,phase){let state2=await requireBoundState2(directory,sessionID,"PR_REVIEW"),ctx=await createPrReviewGateContext2(directory,state2),composed=composePrReviewPhaseVerdicts(directory,state2,phase,ctx),receipt=settlementCoveringAllUnclaimed(directory,state2,phase,composed.unclaimed,ctx.revisionDigest);if(!receipt)return new Set;return new Set(effectiveVerdictSettlementItems(receipt,composed.unclaimed).map((item)=>item.itemId))}async function readAuthoritativePrReviewCriticSettlements(directory,sessionID){let state2=await requireBoundState2(directory,sessionID,"PR_REVIEW"),ctx=await createPrReviewGateContext2(directory,state2),inventory=derivePrReviewCriticInventoryForCoverageGate(directory,state2,ctx,"readAuthoritativePrReviewCriticSettlements");return deriveAuthoritativeCriticSettlements(directory,state2,ctx,inventory)}function deriveLatestPrReviewReviewerVerdicts(directory,state2,ctx){return new Map([...authoritativeReviewerClaims2(directory,state2,ctx)].map(([itemId,claim])=>[itemId,{classification:claim.classification,severity:claim.severity,riskImpact:claim.riskImpact,riskTags:claim.riskTags}]))}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,state2,ctx,origin){let verdicts=deriveLatestPrReviewReviewerVerdicts(directory,state2,ctx);return assertSettledPhaseHasAuthoritativeVerdicts("reviewer",composePrReviewPhaseVerdicts(directory,state2,"reviewer",ctx),verdicts,origin),verdicts}function authoritativeCriticVerdictsForGate(directory,state2,ctx,origin){let verdicts=deriveLatestPrReviewCriticVerdicts(directory,state2,ctx);return assertSettledPhaseHasAuthoritativeVerdicts("critic",composePrReviewPhaseVerdicts(directory,state2,"critic",ctx),verdicts,origin),verdicts}async function readAuthoritativePrReviewCriticVerdicts(directory,sessionID){let state2=await requireBoundState2(directory,sessionID,"PR_REVIEW"),ctx=await createPrReviewGateContext2(directory,state2);return authoritativeCriticVerdictsForGate(directory,state2,ctx,"write_pr_review_artifact critic settlement")}function derivePrReviewCriticInventoryForCoverageGate(directory,state2,ctx,origin){let reviewer=composePrReviewPhaseVerdicts(directory,state2,"reviewer",ctx);if(reviewer.unclaimed.length>0){if(!settlementCoveringAllUnclaimed(directory,state2,"reviewer",reviewer.unclaimed,ctx.revisionDigest)){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 derivePrReviewCriticInventory2(directory,state2,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_CHARS2)}function analyzeLaneRecordResultIntegrity(args2){let{record:record3,result,expected}=args2;if(expected.checkWorkflowLane&&record3.workflowLane!==expected.workflowLane)return failedLaneValidation("record.workflow_lane",expected.workflowLane,record3.workflowLane??"(missing)");if(expected.checkWorkflowLane&&!ownedLaneSetsEqual(record3.ownedWorkflowLanes,expected.ownedWorkflowLanes))return failedLaneValidation("record.owned_workflow_lanes",expected.ownedWorkflowLanes,record3.ownedWorkflowLanes??(record3.workflowLane?[record3.workflowLane]:[]));if(record3.mode!==expected.mode)return failedLaneValidation("record.mode",expected.mode,record3.mode??"(missing)");if(record3.workspace?.prHeadSha!==expected.prHeadSha)return failedLaneValidation("record.pr_head_sha",expected.prHeadSha,record3.workspace?.prHeadSha??"(missing)");if(record3.workspace?.gitHead!==expected.gitHead)return failedLaneValidation("record.git_head",expected.gitHead,record3.workspace?.gitHead??"(missing)");if(args2.requireCompleted&&record3.status!=="completed")return failedLaneValidation("record.status","completed",record3.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((record3)=>record3.laneId&&expectedByLaneId.has(record3.laneId)),recordsByLaneId=new Map,recordCountBySubagentSessionId=new Map;for(let record3 of relevantRecords){let laneRecords=recordsByLaneId.get(record3.laneId)??[];laneRecords.push(record3),recordsByLaneId.set(record3.laneId,laneRecords);let sessionId=record3.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 record3=laneRecords[0],subagentSessionId=record3.subagentSessionId?.trim();if(!subagentSessionId)return failed(failedLaneValidation("record.subagent_session_id","non-empty child session id",record3.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(record3.createdAt<validatedAtMs)return failed(failedLaneValidation("record.created_at",`at or after ${args2.validatedAt}`,new Date(record3.createdAt).toISOString()).failure);let recordIntegrity=analyzeLaneRecordResultIntegrity({record:record3,result:record3.result,expected:{mode:args2.expectedMode,workflowLane:expectedWorkflowLane,ownedWorkflowLanes:expectedOwnedLanes,prHeadSha:args2.expectedPrHeadSha??record3.workspace?.prHeadSha??"",gitHead:args2.expectedPrHeadSha??record3.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:record3,expectedLane,expectedWorkflowLane,expectedOwnedLanes}})}function recordsPassingBatchIntegrity3(directory,state2,batchId,expectedLanes,expectedMode,validatedAt,checkWorkflowLane=!0,forbiddenSubagentSessionIds=new Set,diagnostics){let batchRead=findByBatchIdDetailed(directory,batchId,{parentSessionId:state2.sessionID});if(batchRead.status==="uncertain")throw Error(`BLOCKED: PR_REVIEW batch integrity cannot be analyzed for ${batchId}: the delegation store is unreadable after ${batchRead.attempts} attempts (${batchRead.reason}); the batch's records are UNKNOWN, not absent. Restore the store and re-validate.`);let records=batchRead.value,analyses=analyzePrReviewBatchRecordIntegrity({batchId,expectedLanes,expectedMode,validatedAt,checkWorkflowLane,forbiddenSubagentSessionIds,records,expectedPrHeadSha:state2.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_CHARS2));return analyses.filter((analysis)=>analysis.ok)}function successfulObligationsFromExactBatch2(directory,state2,batchId,expectedLanes,expectedMode,validatedAt,checkWorkflowLane=!0,forbiddenSubagentSessionIds=new Set,expectedRevisionDigest,diagnostics,reviewerClaims){let successful2=new Set;for(let qualified of recordsPassingBatchIntegrity3(directory,state2,batchId,expectedLanes,expectedMode,validatedAt,checkWorkflowLane,forbiddenSubagentSessionIds,diagnostics)){let structuredCoverage=validateExactStructuredReceiptCoverage2({record:qualified.record,result:qualified.record.result,artifact:null,expected:{mode:expectedMode==="swarm-pr-review:base"||expectedMode==="swarm-pr-review:micro"?expectedMode:"swarm-pr-review:base",workflowLane:qualified.expectedWorkflowLane,ownedWorkflowLanes:qualified.expectedOwnedLanes,prHeadSha:state2.prHeadSha??"",gitHead:state2.prHeadSha??"",revisionDigest:expectedRevisionDigest??"",workflowInstanceId:state2.workflowInstanceId,workflowRevision:qualified.record.workflowGeneration,baseSha:state2.prReviewBaseSha,reviewScope:state2.mode==="PR_REVIEW"&&state2.prReviewBaseSha&&state2.prHeadSha?`complete PR diff ${state2.prReviewBaseSha}...${state2.prHeadSha}`:void 0}});if(structuredCoverage.status==="accepted"){for(let obligation of structuredCoverage.creditedWorkflowLanes)successful2.add(obligation);continue}if(structuredCoverage.status==="rejected"){if(diagnostics&&diagnostics.length<MAX_BASE_COVERAGE_DIAGNOSTICS)diagnostics.push(`batch=${batchId} lane=${qualified.expectedLane.laneId} workflow_lane=${qualified.expectedWorkflowLane}: ${formatPrReviewLaneValidationFailure(structuredCoverage.failure)}`.slice(0,MAX_BASE_COVERAGE_DIAGNOSTIC_CHARS2));continue}if(workflowArtifactHasContractMarker(directory,state2,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 validateExactStructuredReceiptCoverage2(input){if(input.expected.mode!=="swarm-pr-review:base"&&input.expected.mode!=="swarm-pr-review:micro")return{status:"absent"};let rawReceipt=input.result.prReviewResultReceipt;if(!rawReceipt)return{status:"absent"};let parsedReceipt2=PrReviewResultReceiptSchema.safeParse(rawReceipt);if(!parsedReceipt2.success)return{status:"rejected",failure:failedLaneValidation("discovery.coverage","schema-valid exact child/workflow/revision-bound structured receipt","invalid structured receipt").failure};if(input.expected.workflowInstanceId===void 0||input.expected.workflowRevision===void 0||input.expected.baseSha===void 0)return{status:"rejected",failure:failedLaneValidation("discovery.coverage","live workflow instance/revision/base identity","missing live workflow instance/revision/base identity").failure};let receipt=parsedReceipt2.data,recordWorkflowInstanceId=decodePrReviewWorkflowBinding(input.record.jobId),recordWorkflowRevision=input.record.workflowGeneration,ownedWorkflowLanes=input.expected.ownedWorkflowLanes?.length?[...input.expected.ownedWorkflowLanes]:[input.expected.workflowLane];if(!recordWorkflowInstanceId||recordWorkflowRevision===void 0||recordWorkflowInstanceId!==input.expected.workflowInstanceId||recordWorkflowRevision!==input.expected.workflowRevision||receipt.mode!==input.expected.mode||receipt.workflowInstanceId!==recordWorkflowInstanceId||receipt.workflowRevision!==recordWorkflowRevision||receipt.baseSha!==input.expected.baseSha||receipt.batchId!==input.record.batchId||receipt.laneId!==input.record.laneId||receipt.childSessionId!==input.record.subagentSessionId||receipt.workflowLane!==input.expected.workflowLane||!ownedLaneSetsEqual(receipt.ownedWorkflowLanes,ownedWorkflowLanes)||receipt.headSha!==input.expected.prHeadSha||receipt.dispatchRevisionDigest!==input.expected.revisionDigest)return{status:"rejected",failure:failedLaneValidation("discovery.coverage","exact child/workflow/revision-bound structured receipt","mismatched structured receipt").failure};return{status:"accepted",creditedWorkflowLanes:receipt.envelope.creditedLanes.filter((lane)=>ownedWorkflowLanes.includes(lane)),receipt}}function analyzeLaneArtifactIntegrity(args2){let{record:record3,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!==record3.batchId)return failedLaneValidation("artifact.batch_id",record3.batchId??"(missing)",artifact.batchId);if(artifact.laneId!==record3.laneId)return failedLaneValidation("artifact.lane_id",record3.laneId??"(missing)",artifact.laneId);if(artifact.mode!==expected.mode)return failedLaneValidation("artifact.mode",expected.mode,artifact.mode??"(missing)");if(artifact.sessionId!==record3.subagentSessionId)return failedLaneValidation("artifact.session_id",record3.subagentSessionId,artifact.sessionId??"(missing)");if(artifact.parentSessionId!==record3.parentSessionId)return failedLaneValidation("artifact.parent_session_id",record3.parentSessionId,artifact.parentSessionId??"(missing)");if(artifact.agent!==record3.swarmPrefixedAgent)return failedLaneValidation("artifact.agent",record3.swarmPrefixedAgent,artifact.agent);if(artifact.role!==record3.normalizedAgent)return failedLaneValidation("artifact.role",record3.normalizedAgent,artifact.role);if(artifact.source!=="collect_lane_results")return failedLaneValidation("artifact.source","collect_lane_results",artifact.source);if(artifact.workflowLane!==record3.workflowLane)return failedLaneValidation("artifact.workflow_lane_record",record3.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&&record3.workspace?.scope!==expected.reviewScope)return failedLaneValidation("record.scope",expected.reviewScope,record3.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 loadArtifactPassingLaneIntegrity2(directory,state2,record3,expectedMode,expectedWorkflowLane,expectedRevisionDigest,diagnostics){let ref=record3.result?.outputRef?.trim();if(!ref)return null;let artifact=readLaneOutput(directory,ref)?.artifact??null,expectedReviewScope=state2.mode==="PR_REVIEW"&&state2.prReviewBaseSha&&state2.prHeadSha?`complete PR diff ${state2.prReviewBaseSha}...${state2.prHeadSha}`:void 0,integrity=analyzeLaneArtifactIntegrity({record:record3,result:record3.result,artifact,expected:{mode:expectedMode,workflowLane:expectedWorkflowLane,prHeadSha:record3.workspace?.prHeadSha??"",gitHead:record3.workspace?.gitHead??"",revisionDigest:expectedRevisionDigest,reviewScope:expectedReviewScope}});if(!integrity.ok){if(diagnostics&&diagnostics.length<MAX_BASE_COVERAGE_DIAGNOSTICS)diagnostics.push(`batch=${record3.batchId??"(missing)"} lane=${record3.laneId??"(missing)"} workflow_lane=${expectedWorkflowLane} output_ref=${ref}: ${formatPrReviewLaneValidationFailure(integrity.failure)}`.slice(0,MAX_BASE_COVERAGE_DIAGNOSTIC_CHARS2));return null}return artifact}function workflowArtifactHasContractMarker(directory,state2,record3,expectedMode,expectedWorkflowLane,reviewItemIds,expectedRevisionDigest,ownedWorkflowLanes,diagnostics,reviewerClaims){let ref=record3.result?.outputRef?.trim(),artifact=expectedRevisionDigest?loadArtifactPassingLaneIntegrity2(directory,state2,record3,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 analyzeLegacyVerdictRowContract(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)=>legacyArtifactHasExactPositiveVerdictRow(artifact.text,feedbackVerdict[0],itemId,feedbackVerdict[1])));if(expectedMode==="swarm-pr-review:base"||expectedMode==="swarm-pr-review:micro"){let reviewScope=state2.mode==="PR_REVIEW"&&state2.prReviewBaseSha&&state2.prHeadSha?`complete PR diff ${state2.prReviewBaseSha}...${state2.prHeadSha}`:void 0,lastSubmitRejection=latestPrReviewSubmitRejectionMessage(state2,record3.subagentSessionId),validation=validatePrReviewDiscoveryLaneCompletion2({record:record3,result:record3.result,artifact,expected:{mode:expectedMode,workflowLane:expectedWorkflowLane,ownedWorkflowLanes,prHeadSha:state2.prHeadSha??"",gitHead:state2.prHeadSha??"",revisionDigest:expectedRevisionDigest??"",workflowInstanceId:state2.workflowInstanceId,workflowRevision:record3.workflowGeneration,baseSha:state2.prReviewBaseSha,reviewScope},...lastSubmitRejection?{lastSubmitRejection}:{}});if(!validation.ok){if(diagnostics&&diagnostics.length<MAX_BASE_COVERAGE_DIAGNOSTICS)diagnostics.push(`batch=${record3.batchId??"(missing)"} lane=${record3.laneId??"(missing)"} workflow_lane=${expectedWorkflowLane} output_ref=${ref}: ${formatPrReviewLaneValidationFailure(validation.failure)}`.slice(0,MAX_BASE_COVERAGE_DIAGNOSTIC_CHARS2));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=${record3.batchId??"(missing)"} lane=${record3.laneId??"(missing)"} workflow_lane=${coveredLane} output_ref=${ref} digest=${record3.result?.digest??"(missing)"}: ${analysis.issues.join("; ")}`;diagnostics.push(diagnostic.slice(0,MAX_BASE_COVERAGE_DIAGNOSTIC_CHARS2))}}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,acceptPartial=!1){let fallbackFamily=resolvePrReviewRowFamily(expectedWorkflowLane,mode),issues=[],normalized=normalizeCandidateArtifactCached(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:acceptPartial,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 validatePrReviewDiscoveryLaneCompletion2(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 structuredCoverage=validateExactStructuredReceiptCoverage2(input);if(structuredCoverage.status==="accepted")return{ok:!0};if(structuredCoverage.status==="rejected")return{ok:!1,failure:structuredCoverage.failure};if((input.expected.mode==="swarm-pr-review:base"||input.expected.mode==="swarm-pr-review:micro")&&!prReviewLegacyTranscriptCompatibilityEnabled(input.record.prReviewLegacyTranscriptCompatibility))return failedLaneValidation("discovery.coverage","child-bound structured receipt",`missing structured receipt (legacy transcript adapter disabled)${input.lastSubmitRejection?`; last rejected submit_pr_review_result: ${input.lastSubmitRejection.slice(0,300)}`:""}`);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,input.result.transcriptIncomplete===!0)})),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 state2=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?(state2.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(state2.mode!==expectedMode)return{ok:!1,reason:`active workflow mode mismatch; expected ${expectedMode}, got ${state2.mode}`,...rejectedReceipt?{receipt:rejectedReceipt}:{}};let artifactText=input.artifact?.text??"",prReviewGateContext=state2.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=(state2.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"?authoritativeReviewerClaims2(input.directory,state2,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=analyzeLegacyVerdictRowContract(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:[]},recoveries=[...(analysis.recoveries??[]).map(({recovery,itemId})=>({workflowLane,kind:"legacy-verdict-row-recovery",reason:recovery==="legacy-fidelity-safe"?`legacy verdict row ${itemId} used trailing-field pipe recovery with full field fidelity`:`legacy verdict row ${itemId} used trailing-field pipe recovery with lossy prose normalization`})),...input.result.truncated===!0?[{workflowLane,kind:"truncated-preview-durable-artifact",reason:"inline preview truncated; durable artifact retained exact coverage"}]:[]];return recoveries.length>0?{ok:!0,receipt,recoveries}:{ok:!0,receipt}}else if(mode==="swarm-pr-feedback:verification"){let lane=(state2.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||!legacyFeedbackArtifactTextCoversItems(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=(state2.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)=>legacyArtifactHasExactPositiveVerdictRow(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}async function persistState2(directory,state2){let validated=PrWorkflowGateStateSchema.parse(state2);await withSessionStateMutation(directory,validated.sessionID,async()=>{let nextState=await writeStateWhileLocked(directory,validated);Object.assign(state2,nextState)})}function boundSalvagedSchemaError(message){return message.length<=MAX_SALVAGED_SCHEMA_ERROR_CHARS?message:`${message.slice(0,MAX_SALVAGED_SCHEMA_ERROR_CHARS-1)}…`}function boundSalvageDisclosure(sessionID,schemaErrors,coordinationNotice,revisionSalvageable=!0,armedShapeUnreadable=!1,publicationShapeUnreadable=!1){let disclosure=`DEGRADED: PR workflow gate state for session "${sessionID}" `+(coordinationNotice?`${coordinationNotice} and was SALVAGED for recovery only (abort/status; write and completion paths still refuse it). `:"failed schema validation and was SALVAGED for recovery only (abort/status; write and completion paths still refuse it). ")+`Schema errors: ${schemaErrors.join("; ")}.`+(revisionSalvageable?"":" state revision unsalvageable.")+(armedShapeUnreadable?" prFeedbackReadyToPublish is present but unreadable; treated as ARMED (fail-closed).":"")+(publicationShapeUnreadable?" prFeedbackPublication is present but unreadable; treated as ARMED (fail-closed).":""),maxDisclosureChars=MAX_SALVAGED_SCHEMA_ERROR_CHARS*12;return disclosure.length<=maxDisclosureChars?disclosure:`${disclosure.slice(0,maxDisclosureChars-1)}…`}async function readPrWorkflowGateStateForRecovery(directory,sessionID){let normalizedSessionID=normalizeSessionID(sessionID),coordination=readPrWorkflowGateStateCoordinationForRecovery(directory,normalizedSessionID);if(coordination.kind==="invalid")throw Error(`BLOCKED: PR workflow gate state for session "${normalizedSessionID}" is invalid (${coordination.reason})`);if(coordination.kind==="valid")return{state:coordination.state,salvaged:!1,schemaErrors:[],revisionSalvageable:!0,armedShapeUnreadable:!1};let coordinationCorrupt=coordination.kind==="corrupt",coordinationGeneration=coordinationCorrupt?coordination.generation:void 0,coordinationReason=coordinationCorrupt?coordination.reason:void 0,filePath=workflowGateStatePath(directory,normalizedSessionID),raw;try{raw=await fsp8.readFile(filePath,"utf-8")}catch(error93){if(error93.code==="ENOENT")return null;throw error93}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){if(parsed.data.sessionID!==normalizedSessionID||coordinationGeneration!==void 0&&parsed.data.revision!==coordinationGeneration)throw Error(`BLOCKED: PR workflow gate state for session "${normalizedSessionID}" is invalid`);if(!coordinationCorrupt)return{state:parsed.data,salvaged:!1,schemaErrors:[],revisionSalvageable:!0,armedShapeUnreadable:!1};let coordinationSchemaError=boundSalvagedSchemaError(`coordination_state.payload: ${coordinationReason}`);return{state:parsed.data,salvaged:!0,schemaErrors:[coordinationSchemaError],disclosure:boundSalvageDisclosure(normalizedSessionID,[coordinationSchemaError],"coordination authority was corrupt and the valid shadow projection was used"),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||salvagedSessionID.data!==normalizedSessionID)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);if(coordinationGeneration!==void 0&&(!salvagedRevision.success||salvagedRevision.data!==coordinationGeneration))throw invalidError;let armedKeyPresent=rawRecord.prFeedbackReadyToPublish!==void 0,salvagedArmed=PrFeedbackReadyToPublishRecordSchema.safeParse(rawRecord.prFeedbackReadyToPublish),publicationKeyPresent=rawRecord.prFeedbackPublication!==void 0,salvagedPublication=PrFeedbackPublicationStateSchema.safeParse(rawRecord.prFeedbackPublication),publicationShapeUnreadable=publicationKeyPresent&&!salvagedPublication.success,salvagedCheckoutRecovery=PrWorkflowCheckoutRecoveryRecordSchema.safeParse(rawRecord.checkoutRecovery),armedShapeUnreadable=armedKeyPresent&&!salvagedArmed.success||publicationShapeUnreadable,shadowSchemaErrors=parsed.error.issues.slice(0,MAX_SALVAGED_SCHEMA_ERRORS).map((issue3)=>boundSalvagedSchemaError(`${issue3.path.join(".")||"(root)"}: ${issue3.message}`)),schemaErrors=[...coordinationCorrupt?[boundSalvagedSchemaError(`coordination_state.payload: ${coordinationReason}`)]:[],...shadowSchemaErrors].slice(0,MAX_SALVAGED_SCHEMA_ERRORS),disclosure=boundSalvageDisclosure(normalizedSessionID,schemaErrors,coordinationCorrupt?`coordination authority was corrupt (${coordinationReason}) and the shadow projection was used`:void 0,salvagedRevision.success,armedShapeUnreadable,publicationShapeUnreadable);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}:{},...salvagedPublication.success?{prFeedbackPublication:salvagedPublication.data}:{},...salvagedCheckoutRecovery.success?{checkoutRecovery:salvagedCheckoutRecovery.data}:{}},salvaged:!0,schemaErrors,disclosure,revisionSalvageable:salvagedRevision.success,armedShapeUnreadable}}var 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,MAX_PUBLICATION_HISTORY_GENERATIONS=4,MAX_PUBLICATION_ATTEMPTS=8,MAX_PUSH_ATTEMPT_DIAGNOSTIC_CHARS=500,PUBLICATION_SCHEMA_VERSION=1,PUBLICATION_URL_CREDENTIALS_PATTERN,MAX_PR_REVIEW_SUBMIT_REJECTIONS=24,GATE_SCHEMA_VERSION=1,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,MAX_PR_WORKFLOW_GATE_DIRECTORY_ENTRIES,MAX_PR_WORKFLOW_GATE_ENTRY_NAME_CHARS=240,MAX_CANDIDATE_ISSUES_PER_ARTIFACT=8,MAX_BASE_COVERAGE_DIAGNOSTICS=8,MAX_BASE_COVERAGE_DIAGNOSTIC_CHARS2=1000,MAX_LANE_VALIDATION_VALUE_CHARS=240,DISPATCH_TOOL_NAME="dispatch_lanes_async",BLOCKING_DISPATCH_TOOL_NAME="dispatch_lanes",PrReviewBaseDimensionIdSchema,PrReviewBaseDispatchRecordSchema,PrReviewResiliencePolicyRecordSchema,PrReviewResilienceAttemptRecordSchema,PrReviewResilienceStateRecordSchema,PrFeedbackLaneOwnershipSchema,PrFeedbackVerificationRecordSchema,PrFeedbackStageACheckReceiptSchema,PrFeedbackStageARecordSchema,PrFeedbackGateBatchRecordSchema,PrFeedbackReadyToPublishRecordSchema,PrFeedbackPublicationEvidenceJoinSchema,PrFeedbackPublicationGenerationSchema,PrFeedbackPushAttemptSchema,PrFeedbackPublicationStateSchema,PrFeedbackInventoryAmendmentRecordSchema,PrReviewValidationBatchRecordSchema,PrReviewMicroFamilyDispatchRecordSchema,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,LIVE_SESSION_STATUS_TYPES,defaultGetSessionOps=()=>swarmState.opencodeClient?.session??null,PR_WORKFLOW_PROBE_SKIPPED_NO_BUDGET_REASON="probe-skipped-no-budget",laneLivenessWatchdogSurface,PrReviewResilienceCircuitOpenError,PrReviewResilienceRetryExhaustedError,snapshotPrReviewResiliencePolicy,DELEGATION_READ_UNCERTAIN_LOG_LIMIT=64,delegationReadUncertainLogged,MALFORMED_CIRCUIT_DIAGNOSTIC_LIMIT=64,malformedCircuitDiagnosticsSeen,TERMINAL_FAILED_DELEGATION_STATUSES2,MAX_COVER_UNIVERSE_BITS=12,PR_FEEDBACK_PHASE_ORDER,PR_FEEDBACK_PHASE_ROLE,PUBLICATION_IDENTITY_COMPONENTS,PUBLICATION_EVENT_TYPES,PR_REVIEW_HANDOFF_RELATIVE_PATH_PATTERN,PR_REVIEW_FEEDBACK_CONSENT_MAX_BYTES=65536,PR_REVIEW_RUN_RESERVATION_MAX_BYTES=16384,PrReviewFeedbackHandoffArtifactSchema,PrReviewRunReservationSchema,PrReviewFeedbackConsentSchema,MAX_PR_REVIEW_RESERVATION_SCAN_ENTRIES=1024,MAX_PR_REVIEW_RUN_ID_SUFFIX_ATTEMPTS=64,PrReviewFindingProjectionSchema,PrReviewFindingPolicySynthesisFindingSchema,PrReviewCriticSettlementEvidenceSchema,PrReviewFindingPolicySynthesisSchema,_test_exports2,PR_WORKFLOW_SHARED_CONTROLLER_TOOLS,PR_REVIEW_CONTROLLER_TOOLS,PR_FEEDBACK_CONTROLLER_TOOLS,PR_REVIEW_READ_ONLY_TOOL_NAMES,PR_REVIEW_ENUMERATED_READ_METHODS,PR_REVIEW_TOOLS_WITH_ENUMERATED_READ_METHODS,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_UNCLAIMED_ITEMS_IN_MESSAGE=50,FEEDBACK_NO_CHANGE_CLASSIFICATIONS,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_contract();init_pr_review_trigger_contract();init_pr_review_trigger_receipt_reader();init_workspace_snapshot();init_constants();init_schema();init_project_db();init_core_events();init_pr_workflow_state();init_redaction();init_authorization();init_circuit();init_completion();init_finding_policy();init_legacy_transcript_adapter();init_persistence();init_reducer();init_verdict_settlement();init_forge_provider();init_scope_binding();init_pr_workflow_gh_readiness();init_pr_workflow_skill_contract();init_state();init_gh_evidence();init_tool_metadata();init_canonical_root();init_logger();init_timeout();init_lane_liveness_watchdog();init_normalize_tool_name();init_utils2();init_completion();init_persistence();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};PUBLICATION_URL_CREDENTIALS_PATTERN=/\b([a-zA-Z][a-zA-Z0-9+.-]*:\/\/)[^\s/@:]+:[^\s/@]+@/g,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_SESSIONS2*2+1,PrReviewBaseDimensionIdSchema=exports_external.enum(PR_REVIEW_BASE_DIMENSION_IDS),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),circuitOpenDurationMs:exports_external.number().int().min(1000).max(1800000).optional()}).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(),PrReviewResilienceStateRecordSchema=exports_external.object({policy:PrReviewResiliencePolicyRecordSchema,attempts:exports_external.array(PrReviewResilienceAttemptRecordSchema).max(3),circuit:PrReviewCircuitRecordSchema.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(),PrFeedbackPublicationEvidenceJoinSchema=exports_external.object({stageAValidatedAt:exports_external.string().min(1),batches:exports_external.array(exports_external.object({phase:exports_external.enum(["stage-b-reviewer","stage-b-test","closeout-reviewer","closeout-critic"]),batchId:exports_external.string().min(1),laneId:exports_external.string().min(1)}).strict())}).strict(),PrFeedbackPublicationGenerationSchema=exports_external.object({schemaVersion:exports_external.literal(PUBLICATION_SCHEMA_VERSION),generation:exports_external.number().int().positive(),state:exports_external.enum(["reviewing","armed","invalidated","push_in_flight","published","cancelled_without_publication"]),workspaceIdentity:exports_external.string().min(1),sessionID:exports_external.string().min(1),prTargetUrl:exports_external.string().min(1).optional(),intakeHeadSha:exports_external.string().min(1),localHeadRef:exports_external.string().min(1),localHead:exports_external.string().min(1),remoteName:exports_external.string().min(1),remoteUrlIdentity:exports_external.string().min(1).optional(),remoteBranchRef:exports_external.string().startsWith("refs/heads/"),remoteRef:exports_external.string().startsWith("refs/remotes/"),revisionDigest:exports_external.string().min(1),evidence:PrFeedbackPublicationEvidenceJoinSchema,invalidationReason:exports_external.string().min(1).optional(),supersededByGeneration:exports_external.number().int().positive().optional(),createdAt:exports_external.string().min(1),armedAt:exports_external.string().min(1).optional(),invalidatedAt:exports_external.string().min(1).optional(),publishedAt:exports_external.string().min(1).optional(),cancelledAt:exports_external.string().min(1).optional()}).strict(),PrFeedbackPushAttemptSchema=exports_external.object({attemptId:exports_external.string().min(1),generation:exports_external.number().int().positive(),sessionID:exports_external.string().min(1),callID:exports_external.string().min(1).optional(),intentDigest:exports_external.string().regex(/^[0-9a-f]{64}$/),intent:exports_external.object({remote:exports_external.string().min(1),sourceSha:exports_external.string().min(1),destRef:exports_external.string().startsWith("refs/heads/")}).strict(),prePush:exports_external.object({localHead:exports_external.string().min(1),worktreeClean:exports_external.boolean(),remoteName:exports_external.string().min(1),remoteBranchRef:exports_external.string().startsWith("refs/heads/"),observedRemoteHead:exports_external.string().min(1).nullable()}).strict(),startedAt:exports_external.string().min(1),result:exports_external.object({outcome:exports_external.enum(["completed","rejected","uncertain","cancelled"]),exitStatus:exports_external.union([exports_external.number().int(),exports_external.literal("not-observed")]),diagnostic:exports_external.string().max(MAX_PUSH_ATTEMPT_DIAGNOSTIC_CHARS),postPush:exports_external.object({localHead:exports_external.string().min(1).nullable(),observedRemoteHead:exports_external.string().min(1).nullable()}).strict(),completedAt:exports_external.string().min(1)}).strict().optional()}).strict(),PrFeedbackPublicationStateSchema=exports_external.object({schemaVersion:exports_external.literal(PUBLICATION_SCHEMA_VERSION),active:PrFeedbackPublicationGenerationSchema.optional(),history:exports_external.array(PrFeedbackPublicationGenerationSchema).max(MAX_PUBLICATION_HISTORY_GENERATIONS),attempts:exports_external.array(PrFeedbackPushAttemptSchema).max(MAX_PUBLICATION_ATTEMPTS)}).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(),PrReviewMicroFamilyDispatchRecordSchema=exports_external.object({batchId:exports_external.string().min(1),prHeadSha:exports_external.string().min(1),lanes:exports_external.array(exports_external.object({laneId:exports_external.string().min(1),workflowLane:exports_external.string().min(1),ownedWorkflowLanes:exports_external.array(exports_external.string().min(1)).min(1).optional()}).strict()).min(1),admittedAt: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),skillContractAdvisories:exports_external.array(exports_external.string().min(1)).max(MAX_SKILL_CONTRACT_ADVISORIES).optional(),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(),prReviewContractRetryDimensions:exports_external.array(PrReviewBaseDimensionIdSchema).max(PR_REVIEW_BASE_DIMENSION_IDS.length).optional(),prReviewTriggerLedger:exports_external.array(PrReviewInlineTriggerRowSchema).length(PR_REVIEW_REQUIRED_TRIGGER_IDS.length).optional(),prReviewMicroFamilyDispatches:exports_external.array(PrReviewMicroFamilyDispatchRecordSchema).max(MAX_WORKFLOW_BATCHES).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(),prReviewReservedRunId:exports_external.string().min(1).optional(),prReviewArtifactRunId:exports_external.string().min(1).optional(),prReviewFindingsPath:exports_external.string().min(1).optional(),prReviewPartialBaseCoverage:PrReviewPartialBaseCoverageRecordSchema.optional(),prReviewCoverageDisclosurePath:exports_external.string().min(1).max(512).optional(),prReviewCoverageDisclosureDigest:exports_external.string().regex(/^[0-9a-f]{64}$/).optional(),prReviewDimensionCancellations:exports_external.record(exports_external.enum(PR_REVIEW_BASE_DIMENSION_IDS),PrReviewDimensionCancellationRecordSchema).optional(),prReviewSubmitRejections:exports_external.array(exports_external.object({childSessionId:exports_external.string().min(1).max(200),laneId:exports_external.string().min(1).max(200).optional(),at:exports_external.number(),message:exports_external.string().min(1).max(300)}).strict()).max(MAX_PR_REVIEW_SUBMIT_REJECTIONS).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(),prFeedbackPublication:PrFeedbackPublicationStateSchema.optional(),prFeedbackArmedRecovery:exports_external.object({recoveredAt:exports_external.string().datetime(),prHeadSha:exports_external.string().regex(/^[0-9a-f]{6,64}$/i),revisionDigest:exports_external.string().min(1).max(256),generation:exports_external.number().int().nonnegative(),reason:exports_external.string().min(1).max(500)}).strict().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"]);laneLivenessWatchdogSurface={resolveEffectivePrLaneHorizonMs,classifyLaneLivenessCondition,evaluateLaneLivenessWatchdog:evaluateLaneLivenessWatchdogEscalation,readLaneActivity:defaultReadLaneActivity,hostStatusCalls:0,hostAbortCalls:0,evaluations:0};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"}};snapshotPrReviewResiliencePolicy=resolvePrReviewResiliencePolicy;delegationReadUncertainLogged=new Set;malformedCircuitDiagnosticsSeen=new Set;TERMINAL_FAILED_DELEGATION_STATUSES2=CIRCUIT_TERMINAL_DELEGATION_STATUSES;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"};PUBLICATION_IDENTITY_COMPONENTS=["digest","head","worktree","upstream","remote-url","workspace-identity"];PUBLICATION_EVENT_TYPES=new Set(["pr_feedback_publication_armed","pr_feedback_publication_migrated","pr_feedback_push_attempt_started","pr_feedback_publication_invalidated","pr_feedback_published","pr_feedback_publication_cancelled"]);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(),PrReviewRunReservationSchema=exports_external.object({schema_version:exports_external.literal(1),session_id:exports_external.string().min(1),workflow_instance_id:exports_external.string().min(1),run_id:exports_external.string().min(1).max(128),reserved_at:exports_external.string().datetime()}).strict(),PrReviewFeedbackConsentSchema=exports_external.object({schema_version:exports_external.literal(1),state:exports_external.enum(["offered","confirmed"]),session_id:exports_external.string().min(1),source_workflow_instance_id:exports_external.string().min(1),run_id:exports_external.string().min(1).max(128),handoff_path:exports_external.string().min(1).max(512),handoff_digest:exports_external.string().regex(/^[a-f0-9]{64}$/),pr_url:exports_external.string().url().max(2000),pr_head_sha:exports_external.string().regex(/^[0-9a-f]{6,64}$/i),finding_ids_digest:exports_external.string().regex(/^[a-f0-9]{64}$/),confirmation_command:exports_external.string().min(1).max(4000),offered_at:exports_external.string().datetime(),confirmed_at:exports_external.string().datetime().optional()}).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(),PrReviewFindingPolicySynthesisFindingSchema=exports_external.object({id:exports_external.string().min(1).max(128),status:exports_external.string().min(1),severity:exports_external.string().min(1),action:exports_external.string().min(1)}).passthrough(),PrReviewCriticSettlementEvidenceSchema=exports_external.object({findingId:exports_external.string().min(1).max(128),terminal:exports_external.boolean(),status:exports_external.enum(["UPHELD","DOWNGRADED","DISPROVED","NEEDS_MORE_EVIDENCE","CRITIC_UNAVAILABLE"])}).passthrough(),PrReviewFindingPolicySynthesisSchema=exports_external.object({findings:exports_external.array(PrReviewFindingPolicySynthesisFindingSchema),criticSettlements:exports_external.array(PrReviewCriticSettlementEvidenceSchema).optional()});bindPrReviewReentryBindingReader(readPrReviewReentryBindingContext);_test_exports2={resolveGhBinary,parseGateState:(data)=>PrWorkflowGateStateSchema.safeParse(data),classifyPrReviewCircuitSignal,minimumConsolidatedLaneCover,analyzePrReviewBatchRecordIntegrity,workflowArtifactHasContractMarker,MAX_COVER_UNIVERSE_BITS,extractCandidateIds,parseCanonicalCandidateRows,resolvePrReviewRowFamily,boundPublicationDiagnostic,workflowGateStateRelativePath,workflowGateStateLockRelativePath,workflowCheckoutMutationLockRelativePath,withPrWorkflowCheckoutMutationLock,resetTrackedStateCache:()=>{resetPrReviewPersistenceCaches(),malformedCircuitDiagnosticsSeen.clear(),delegationReadUncertainLogged.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.beforePrReviewReentryReservation=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=defaultPersistenceHooks.openCheckoutLock,_test_exports2.removeCheckoutLock=defaultPersistenceHooks.removeCheckoutLock,_test_exports2.checkoutMutationActionTimeoutMs=CHECKOUT_MUTATION_ACTION_TIMEOUT_MS,_test_exports2.classifyPrWorkflowGitStateAsync=classifyPrWorkflowGitState,_test_exports2.sweepStaleDelegationsAsync=sweepStaleDelegations,_test_exports2.probeLaneLivenessAsync=probeAlivePrWorkflowLaneSessions,_test_exports2.probeLaneSessionStatusTypesAsync=probePrWorkflowLaneSessionStatusTypes,laneLivenessWatchdogSurface.hostStatusCalls=0,laneLivenessWatchdogSurface.hostAbortCalls=0,laneLivenessWatchdogSurface.evaluations=0,laneLivenessWatchdogSurface.readLaneActivity=defaultReadLaneActivity,_test_exports2.getSessionOps=defaultGetSessionOps,_test_exports2.laneLivenessProbeTimeoutMs=PR_WORKFLOW_LANE_LIVENESS_PROBE_TIMEOUT_MS,_test_exports2.pendingLaneLivenessThresholdMs=PR_WORKFLOW_PENDING_LIVENESS_THRESHOLD_MS,closeAllProjectDbs()},beforeTerminalClear:void 0,beforeAbortClear:void 0,beforePrFeedbackTransitionLock:void 0,beforePrFeedbackTrackingSwitch:void 0,afterPrFeedbackTrackingSwitch:void 0,beforePrFeedbackTrackingPersist:void 0,beforePrReviewReentryReservation:void 0,beforeBoundedSwarmFileOpen:void 0,beforeSessionStateLockWrite:void 0,beforeCheckoutLockWrite:void 0,beforeSafeDirectoryCreate:void 0,beforeAtomicTempWrite:void 0,beforeAtomicRename:void 0,openCheckoutLock:defaultPersistenceHooks.openCheckoutLock,removeCheckoutLock:defaultPersistenceHooks.removeCheckoutLock,checkoutMutationActionTimeoutMs:CHECKOUT_MUTATION_ACTION_TIMEOUT_MS,classifyPrWorkflowGitStateAsync:classifyPrWorkflowGitState,sweepStaleDelegationsAsync:sweepStaleDelegations,probeLaneLivenessAsync:probeAlivePrWorkflowLaneSessions,probeLaneSessionStatusTypesAsync:probePrWorkflowLaneSessionStatusTypes,laneLivenessWatchdog:laneLivenessWatchdogSurface,getSessionOps:defaultGetSessionOps,laneLivenessProbeTimeoutMs:PR_WORKFLOW_LANE_LIVENESS_PROBE_TIMEOUT_MS,pendingLaneLivenessThresholdMs:PR_WORKFLOW_PENDING_LIVENESS_THRESHOLD_MS,effectivePrReviewResiliencePolicy,snapshotPrReviewResiliencePolicy,resolveCurrentGitHead,resolveCurrentGitHeadAsync,resolveCurrentUpstreamPushTarget,resolveCurrentUpstreamPushTargetAsync,resolveCurrentUpstreamRemoteRef,resolveCurrentLocalHeadRefAsync,resolveRemoteUrlIdentity,resolveRemoteUrlIdentityAsync,parseExactBoundPushIntent,admitPrFeedbackPushAttempt,recordPrFeedbackPushAttemptResult,reconcileForeignInFlightAttempt,ensurePublicationGenerationCurrent,invalidatePublicationGeneration,invalidatePrFeedbackPublication,cancelPrFeedbackPublication,buildPublicationEvidenceJoin,nextPublicationContainer,supersedeLivePublicationInPendingState,describePrWorkflowPublicationSection,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,composePrReviewPhaseVerdicts:async(directory,sessionID,phase)=>{let state2=await requireBoundState2(directory,sessionID,"PR_REVIEW"),ctx=await createPrReviewGateContext2(directory,state2);return composePrReviewPhaseVerdicts(directory,state2,phase,ctx)},assertSettledPhaseHasAuthoritativeVerdicts,derivePrReviewCriticInventoryForCoverageGate:async(directory,sessionID,origin="_test_exports")=>{let state2=await requireBoundState2(directory,sessionID,"PR_REVIEW"),ctx=await createPrReviewGateContext2(directory,state2);return derivePrReviewCriticInventoryForCoverageGate(directory,state2,ctx,origin)},derivePrReviewCandidateInventory:async(directory,sessionID)=>{let state2=await requireBoundState2(directory,sessionID,"PR_REVIEW"),ctx=await createPrReviewGateContext2(directory,state2);return derivePrReviewCandidateInventory2(directory,state2,ctx)},isProcessAlive:defaultPersistenceHooks.isProcessAlive,isSafeStandaloneGitCommit,rename:fsp8.rename,nowMs:()=>Date.now()};Object.assign(_test_exports2,legacyTranscriptAdapterTestSurface);bindPrReviewPersistenceHooks(_test_exports2);bindPrReviewStateCodec({safeParse:(data)=>PrWorkflowGateStateSchema.safeParse(data),parse:(data)=>PrWorkflowGateStateSchema.parse(data)});bindPrReviewCompletionHelpers({createPrReviewGateContext:createPrReviewGateContext2,requireBoundState:requireBoundState2,readPrWorkflowGateStateFromDisk:readPrWorkflowGateStateFromDisk3,readBoundedSwarmRegularFile:readBoundedSwarmRegularFile2,successfulObligationsFromExactBatch:successfulObligationsFromExactBatch2,recordsPassingBatchIntegrity:recordsPassingBatchIntegrity3,validatePrReviewDiscoveryLaneCompletion:validatePrReviewDiscoveryLaneCompletion2,validateExactStructuredReceiptCoverage:validateExactStructuredReceiptCoverage2});bindPrReviewTranscriptAdapterHelpers({derivePrReviewCandidateInventory:derivePrReviewCandidateInventory2,derivePrReviewCriticInventory:derivePrReviewCriticInventory2,authoritativeReviewerClaims:authoritativeReviewerClaims2,reviewerSubagentSessionIds:reviewerSubagentSessionIds2,prReviewPhaseWindow:prReviewPhaseWindow2,batchMayContributeClaims:batchMayContributeClaims2,recordsPassingBatchIntegrity:recordsPassingBatchIntegrity3,loadArtifactPassingLaneIntegrity:loadArtifactPassingLaneIntegrity2});PR_WORKFLOW_SHARED_CONTROLLER_TOOLS=new Set(["abort_pr_workflow","cancel_lane_batch","collect_lane_results","complete_pr_workflow","dispatch_lanes_async","prepare_pr_workflow_checkout"]),PR_REVIEW_CONTROLLER_TOOLS=new Set(["authorize_pr_review_reentry","parse_lane_candidates","write_pr_review_artifact","write_pr_review_trigger_eval"]),PR_FEEDBACK_CONTROLLER_TOOLS=new Set(["invalidate_pr_feedback_publication","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_REVIEW_ENUMERATED_READ_METHODS=new Set(["get","get_diff","get_status","get_files","get_commits","get_review_comments","get_reviews","get_comments","get_check_runs"]),PR_REVIEW_TOOLS_WITH_ENUMERATED_READ_METHODS=new Set(["github_pull_request_read","mcp__github__pull_request_read"]);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 /;FEEDBACK_NO_CHANGE_CLASSIFICATIONS=new Set(["DISPROVED","PRE_EXISTING","NEEDS_MORE_EVIDENCE","NEEDS_USER_DECISION"])});import*as child_process5 from"node:child_process";function sanitizeUrl(raw){let urlStr=raw.trim();urlStr=urlStr.replace(/^([A-Za-z][A-Za-z0-9+.-]*:\/\/)\/?[^@/]+@/,"$1"),urlStr=urlStr.replace(/\[\s*MODE\s*:[^\]]*\]/gi,""),urlStr=urlStr.replace(/^([A-Za-z][A-Za-z0-9+.-]*:\/\/)\/?[^@/]+@/,"$1");let fragmentIdx=urlStr.indexOf("#");if(fragmentIdx!==-1)urlStr=urlStr.slice(0,fragmentIdx);let queryIdx=urlStr.indexOf("?");if(queryIdx!==-1)urlStr=urlStr.slice(0,queryIdx);if(urlStr.length>MAX_URL_LEN)urlStr=urlStr.slice(0,MAX_URL_LEN);return urlStr.trim()}function sanitizeErrorEcho(raw,maxLength=80){let stripped="";for(let ch of raw){let cp2=ch.codePointAt(0);if(cp2!==void 0&&(cp2<=31||cp2===127)){stripped+=" ";continue}stripped+=ch}let collapsed=stripped.replace(/\s+/g," ").trim();if(collapsed.length<=maxLength)return collapsed;return`${collapsed.slice(0,maxLength)}…`}function validateAndSanitizeGithubUrl(rawUrl,resource,configured){let sanitized=sanitizeUrl(rawUrl);if(!sanitized)return{error:"Empty URL"};if(!sanitized.startsWith("https://"))return{error:"URL must use HTTPS scheme"};try{let url3=new URL(sanitized);if(hasNonAsciiHostname(url3.hostname))return{error:"Non-ASCII hostnames are not allowed"};if(isPrivateHost(url3))return{error:"Private or localhost URLs are not allowed"};if(!matchForgeResourceUrl(sanitized,resource,configured))return{error:resource==="issues"?"URL must be a GitHub issue URL (https://github.com/owner/repo/issues/N) or a GitLab issue URL (https://<gitlab-host>/owner/repo/-/issues/N)":"URL must be a GitHub pull request URL (https://github.com/owner/repo/pull/N) or a GitLab merge request URL (https://<gitlab-host>/owner/repo/-/merge_requests/N)"};return{sanitized}}catch{return{error:"Invalid URL format"}}}function detectGitRemote(cwd,laneEnv){try{let result=_internals111.spawnSync(resolveGitExecutable(),["remote","get-url","origin"],{encoding:"utf-8",stdio:["ignore","pipe","pipe"],timeout:5000,...cwd?{cwd}:{},envOverrides:laneEnv});if(result.status!==0||result.error)return null;return(result.stdout??"").trim()||null}catch{return null}}function parseGitRemoteUrl(remoteUrl){let httpsMatch=remoteUrl.match(/^https:\/\/github\.com\/([^/]+)\/([^/]+?)(?:\.git)?\/?$/i);if(httpsMatch){let owner=httpsMatch[1],repo=httpsMatch[2].replace(/\.git$/,"");if(containsControlCharacters(owner)||containsControlCharacters(repo))return null;return{owner,repo}}let sshMatch=remoteUrl.match(/^git@github\.com:([^/]+)\/([^/]+?)(?:\.git)?$/i);if(sshMatch){let owner=sshMatch[1],repo=sshMatch[2].replace(/\.git$/,"");if(containsControlCharacters(owner)||containsControlCharacters(repo))return null;return{owner,repo}}let pathMatch=remoteUrl.match(/\/([^/]+)\/([^/]+?)(?:\.git)?\/?$/);if(pathMatch){let owner=pathMatch[1],repo=pathMatch[2].replace(/\.git$/,"");if(containsControlCharacters(owner)||containsControlCharacters(repo))return null;return{owner,repo}}return null}var MAX_URL_LEN=2048,_internals111;var init_url_security=__esm(()=>{init_forge_provider();init_host_guards();init_bun_compat();init_git_executable();_internals111={spawnSync:(cmd,args2,options)=>{let mergedEnv=mergeEnvForChild(options?.env,options?.envOverrides);return child_process5.spawnSync(cmd,args2,{...options,env:mergedEnv})}}});async function handleAbortPrWorkflowCommand(directory,args2,sessionID){let tokens2=(args2??[]).filter((token)=>token.trim().length>0),modeToken=tokens2[0]?.toUpperCase(),knownMode=modeToken&&KNOWN_MODES.has(modeToken)?modeToken:void 0,cancellationRequested=tokens2.includes(CANCEL_PUBLICATION_FLAG),reasonStartIndex=knownMode?1:0;if(modeToken&&!knownMode)return`Error: Unknown mode "${modeToken}". Expected PR_REVIEW or PR_FEEDBACK.
|
|
1295
|
+
`,{encoding:"utf8",flag:"wx"}),await fsp8.link(tempPath,absolutePath)}finally{await fsp8.rm(tempPath,{force:!0}).catch(()=>{return})}}async function readPrReviewFeedbackHandoffArtifact(directory,relativePath){let raw=await readBoundedSwarmRegularFile2(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:createHash59("sha256").update(raw,"utf8").digest("hex")}}async function readActionableReviewFindingIds(directory,state2,runId){let expectedPath=`pr-review/${runId}/findings.jsonl`;if(state2.prReviewFindingsPath!==expectedPath)throw Error(`BLOCKED: PR_REVIEW transition requires the exact final findings artifact "${expectedPath}"`);let raw=await readBoundedSwarmRegularFile2(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 deriveFeedbackHandoffFindingIds([...latest.values()])}async function readAuthoritativeFindingPolicy(directory,state2){let runId=state2.prReviewArtifactRunId;if(!runId||!state2.prReviewFindingsPath||!state2.prHeadSha)throw Error("BLOCKED: PR_REVIEW terminal finding policy evidence is not bound to the active run");let outcome=await readReviewOutcome({projectRoot:directory,sessionId:state2.sessionID,taskId:runId}).catch((error93)=>{throw Error(`BLOCKED: PR_REVIEW finding-policy evidence is missing or invalid: ${error93 instanceof Error?error93.message:String(error93)}`)}),routeReceipt=outcome.evidence.routeReceipt;if(!routeReceipt||typeof routeReceipt!=="object")throw Error("BLOCKED: PR_REVIEW finding-policy evidence has no route receipt");let receipt=routeReceipt,expectedPath=`pr-review/${runId}/findings.jsonl`,raw=await readBoundedSwarmRegularFile2(directory,state2.prReviewFindingsPath,PR_REVIEW_FINDINGS_MAX_BYTES,"PR_REVIEW final findings artifact"),findingsDigest=createHash59("sha256").update(raw,"utf8").digest("hex");if(receipt.version!==FINDING_POLICY_VERSION)throw Error(`BLOCKED: PR_REVIEW finding-policy route receipt version ${String(receipt.version)} does not match the current finding-policy version ${FINDING_POLICY_VERSION}; the sidecar was written by a different plugin version and cannot be trusted at this one`);if(receipt.kind!=="pr_review_finding_policy"||receipt.sessionId!==state2.sessionID||receipt.taskId!==runId||receipt.boundary!=="post_critic"||receipt.prHeadSha!==state2.prHeadSha||receipt.findingsPath!==expectedPath||receipt.findingsDigest!==findingsDigest)throw Error("BLOCKED: PR_REVIEW finding-policy route receipt is stale or does not bind the final findings artifact");let synthesis=PrReviewFindingPolicySynthesisSchema.safeParse(outcome.evidence.synthesis);if(!synthesis.success)throw Error("BLOCKED: PR_REVIEW finding-policy synthesis is invalid or incomplete");return{policyFindings:synthesis.data.findings,criticSettlements:synthesis.data.criticSettlements??[]}}async function readPrReviewFinalFindingPolicyForReport(directory,sessionID){let state2=await readPrWorkflowGateStateFromDisk3(directory,normalizeSessionID(sessionID));if(!state2||state2.mode!=="PR_REVIEW"||!state2.prHeadSha)return null;let ctx=await createPrReviewGateContext2(directory,state2),settlement=derivePrReviewDimensionSettlement(directory,state2,ctx.revisionDigest),findings=(await readAuthoritativeFindingPolicy(directory,state2)).policyFindings,disclosedDegradation=prReviewReceiptHasCoverageDegradations(directory,state2.prReviewTriggerEvalPath)||await verdictSettlementDegradesReport(directory,state2,ctx),permittedVerdicts=allowedPrReviewReportVerdicts(settlement.kind,findings,{disclosedCoverageDegradation:disclosedDegradation}),policyProjection=evaluateFinalFindingPolicy({policyVersion:FINDING_POLICY_VERSION,finalStatus:"COMPLETE",coverage:settlement.kind==="COMPLETE"?{kind:"base",quality:"complete",provenance:"valid"}:settlement.kind==="PARTIAL"?{kind:"base",quality:"partial",provenance:"valid"}:{kind:"base",quality:"none",provenance:"valid"},findings}),sourceIdsByPolicyFindingId=new Map(findings.map((finding)=>[finding.id,Array.isArray(finding.sourceFindingIds)?finding.sourceFindingIds.filter((value)=>typeof value==="string"):[]])),blockingFindingIds=policyProjection.blockingFindingIds.flatMap((id)=>sourceIdsByPolicyFindingId.get(id)??[id]).sort();return{policyVersion:1,permittedVerdicts,blockingFindingIds}}function canonicalGitHubPrUrl(value,configured){return canonicalForgePrUrl(value,configured)}function assertMatchingPrReviewFeedbackConsent(record3,input){if(record3.session_id!==input.sessionID||record3.run_id!==input.runId||record3.handoff_path!==input.handoffPath||record3.handoff_digest!==input.handoffDigest||canonicalGitHubPrUrl(record3.pr_url)!==canonicalGitHubPrUrl(input.prUrl)||record3.pr_head_sha.toLowerCase()!==input.prHeadSha.toLowerCase()||record3.finding_ids_digest!==input.findingIdsDigest||record3.source_workflow_instance_id!==input.sourceWorkflowInstanceId)throw Error("BLOCKED: PR_REVIEW feedback consent artifact does not match the requested handoff; remove the stale sidecar or repeat the exact continuation offer")}function workflowIdentity(state2){return state2.workflowInstanceId??`legacy-${createHash59("sha256").update(`${state2.sessionID}\x00${state2.mode}\x00${state2.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(state2,relativePath,read,requestedPrUrl){let existing=state2.prFeedbackReviewHandoff;if(!existing)throw Error(`BLOCKED: session "${state2.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 "${state2.sessionID}" is already active in PR_FEEDBACK for a different handoff or PR`)}async function assertPrReviewTerminalReady(directory,sessionID,laneLiveness){let state2=await requireBoundState2(directory,sessionID,"PR_REVIEW");await assertPrReviewCleanCheckout(directory,"PR_REVIEW");let laneSettlement=await settlePresumedStalePrWorkflowLanes(directory,state2.sessionID,laneLiveness);if(laneSettlement.uncertainty)throw Error(`BLOCKED: PR_REVIEW transition refused while the delegation store is unreadable after ${laneSettlement.uncertainty.attempts} attempts (${laneSettlement.uncertainty.reason}); open lanes are UNKNOWN, not absent. Restore the store before transitioning.`);if(laneSettlement.openLanes>0)throw Error(`BLOCKED: PR_REVIEW transition has ${laneSettlement.openLanes} unsettled PR workflow lane(s)`+describePrWorkflowLaneProbe(laneSettlement));let ctx=await createPrReviewGateContext2(directory,state2),{settlement}=await assertPrReviewBaseCoverageSettled2(directory,sessionID,ctx);if(!state2.prReviewTriggerEvalPath)throw Error("BLOCKED: PR_REVIEW transition requires a persisted trigger evaluation artifact");if((state2.prReviewValidationBatches??[]).some((batch)=>batch.phase==="council"))await assertPrReviewValidationSettled(directory,sessionID,"council",ctx);await assertPrReviewValidationSettled(directory,sessionID,"reviewer",ctx);let criticInventory=derivePrReviewCriticInventoryForCoverageGate(directory,state2,ctx,"completePrWorkflow critic-coverage gate"),authoritativeCriticSettlements=[];if(criticInventory.length>0){if(!(state2.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),authoritativeCriticSettlements=deriveAuthoritativeCriticSettlements(directory,state2,ctx,criticInventory);let criticVerdicts=deriveLatestPrReviewCriticVerdicts(directory,state2,ctx),reviewerClaims=authoritativeReviewerClaims2(directory,state2,ctx),settledReceipts=[];for(let[itemId,verdict]of criticVerdicts){if(verdict.status!=="UPHELD"&&verdict.status!=="DOWNGRADED"&&verdict.status!=="DISPROVED")continue;let reviewerRowDigest=reviewerClaims.get(itemId)?.rowDigest;if(!reviewerRowDigest)continue;settledReceipts.push({findingId:itemId,status:verdict.status,reviewerRowDigest})}let criticSettlementEffective=verdictSettlementEffectiveIdsForGate(directory,state2,"critic",ctx);if(reducePrReviewEvent(state2,{type:"critic_result_recorded",criticRequiredFindingIds:criticInventory.filter((itemId)=>!criticSettlementEffective.has(itemId)),criticSettledReceipts:settledReceipts}).status==="rejected"){let settledIds=new Set(settledReceipts.map((r)=>r.findingId)),unfulfilled=criticInventory.filter((id)=>!settledIds.has(id));throw Error(`BLOCKED: PR_REVIEW reviewer verdicts require critic coverage for: ${unfulfilled.join(", ")}`)}}let requiredBoundaries=["post_explorer","post_reviewer","post_critic"],persistedBoundaries=new Set(state2.prReviewArtifactBoundaries??[]),missing=requiredBoundaries.filter((boundary)=>!persistedBoundaries.has(boundary));if(!state2.prReviewFindingsPath||missing.length>0)throw Error(`BLOCKED: PR_REVIEW transition requires durable findings checkpoints; missing: ${missing.join(", ")||"findings path"}`);if(state2.prReviewHandoffRequired&&!state2.prReviewHandoffPath)throw Error("BLOCKED: PR_REVIEW actionable findings require a persisted feedback handoff artifact");let criticSettlementIncomplete=authoritativeCriticSettlements.some((settlement2)=>!settlement2.terminal),findingPolicyAuthority=criticSettlementIncomplete?null:await readAuthoritativeFindingPolicy(directory,state2);if(!criticSettlementIncomplete&&criticInventory.length>0){let persistedSettlements=findingPolicyAuthority?.criticSettlements??[],actualById=new Map(authoritativeCriticSettlements.map((settlement2)=>[settlement2.findingId,settlement2]));if(persistedSettlements.length!==authoritativeCriticSettlements.length||persistedSettlements.some((settlement2)=>{let actual=actualById.get(settlement2.findingId);return!actual||actual.terminal!==settlement2.terminal||actual.status!==settlement2.status}))throw Error("BLOCKED: PR_REVIEW finding-policy critic settlements are stale or do not match the authenticated critic verdict map")}let reviewerReceipts=(state2.prReviewValidationBatches??[]).filter((batch)=>batch.phase==="reviewer").map((batch)=>({id:batch.batchId,valid:!0})),councilEnabled=(state2.prReviewValidationBatches??[]).some((batch)=>batch.phase==="council"),criticEnabled=criticInventory.length>0,policyReadiness=assessTerminalReadiness({baseReceipt:{id:"base-coverage-settlement",valid:Boolean((state2.prReviewBaseDispatches??[]).length>0||state2.prReviewBaseDispatch)},reviewerReceipts,criticReceipt:{id:"critic-coverage-settlement",valid:!criticEnabled||!criticSettlementIncomplete&&(state2.prReviewValidationBatches??[]).some((batch)=>batch.phase==="critic")},coverage:{kind:"base",quality:settlement.kind==="COMPLETE"?"complete":"partial",provenance:"valid"},council:{enabled:councilEnabled,receipt:councilEnabled?{id:"council-settlement",valid:!0}:null},criticSettlements:criticEnabled?authoritativeCriticSettlements:void 0});if(!policyReadiness.ready)throw Error(`BLOCKED: PR_REVIEW terminal finding readiness is incomplete: ${policyReadiness.blockers.join(", ")}`);return{state:state2,settlement}}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,expectedConsentSourceIdentity,sourceRevision=0,provenance;if(preliminary){if(preliminary.mode!=="PR_REVIEW")throw wrongModeError(preliminary,"PR_REVIEW");let ready=(await assertPrReviewTerminalReady(directory,normalizedSessionID,request.laneLiveness)).state;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),expectedConsentSourceIdentity=sourceIdentity,sourceRevision=ready.revision,provenance="active-review-v1"}else{let reservation=await readPrReviewRunReservation(directory,request.runId);if(!reservation||reservation.session_id!==normalizedSessionID||reservation.run_id!==request.runId)throw Error("BLOCKED: completed PR_REVIEW continuation requires the matching durable run reservation for this session");expectedConsentSourceIdentity=reservation.workflow_instance_id,sourceIdentity=expectedConsentSourceIdentity,provenance="external-v1"}let consent=await readPrReviewFeedbackConsent(directory,request.runId);if(!consent)throw Error("BLOCKED: PR_FEEDBACK continuation requires explicit confirmation; repeat the exact continuation command first");assertMatchingPrReviewFeedbackConsent(consent,{sessionID:normalizedSessionID,runId:request.runId,handoffPath:normalizedHandoff.relativePath,handoffDigest:preliminaryRead.digest,prUrl:artifact.pr_url,prHeadSha:artifact.pr_head_sha,findingIdsDigest:hashPrReviewFindingIds(artifact.finding_ids),sourceWorkflowInstanceId:expectedConsentSourceIdentity});let exactCommand=request.exactCommand?.trim(),acceptedContinuationCommands=buildAcceptedPrFeedbackContinuationCommands(consent.confirmation_command,normalizedHandoff.relativePath,request.prUrl);if(request.confirmedByUser!==!0||!exactCommand||!acceptedContinuationCommands.has(exactCommand))throw Error(`BLOCKED: PR_FEEDBACK continuation requires explicit confirmation with the offered command: ${consent.confirmation_command}`);return await _test_exports2.beforePrFeedbackTransitionLock?.(),withPrWorkflowCheckoutMutationLock(directory,()=>withSessionStateMutation(directory,normalizedSessionID,async()=>{let current=await readPrWorkflowGateStateFromDisk3(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");if(provenance==="external-v1"){let lockedReservation=await readPrReviewRunReservation(directory,request.runId);if(!lockedReservation||lockedReservation.session_id!==normalizedSessionID||lockedReservation.workflow_instance_id!==expectedConsentSourceIdentity)throw Error("BLOCKED: PR_REVIEW run reservation changed during external feedback transition")}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 lockedConsent=await readPrReviewFeedbackConsent(directory,request.runId);if(!lockedConsent)throw Error("BLOCKED: PR_REVIEW feedback consent artifact disappeared during transition");if(assertMatchingPrReviewFeedbackConsent(lockedConsent,{sessionID:normalizedSessionID,runId:request.runId,handoffPath:normalizedHandoff.relativePath,handoffDigest:lockedRead.digest,prUrl:lockedRead.artifact.pr_url,prHeadSha:lockedRead.artifact.pr_head_sha,findingIdsDigest:hashPrReviewFindingIds(lockedRead.artifact.finding_ids),sourceWorkflowInstanceId:expectedConsentSourceIdentity}),!buildAcceptedPrFeedbackContinuationCommands(lockedConsent.confirmation_command,normalizedHandoff.relativePath,request.prUrl).has(exactCommand))throw Error("BLOCKED: PR_FEEDBACK continuation command changed during transition");if(lockedConsent.state==="offered")await writePrReviewFeedbackConsent(directory,{...lockedConsent,state:"confirmed",confirmed_at:isoNow()});let timestamp=isoNow(),nextState={schemaVersion:GATE_SCHEMA_VERSION,revision:sourceRevision,workflowInstanceId:randomUUID17(),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 state2=await assertPrFeedbackVerificationSettled(directory,sessionID),revisionDigest=await currentPrFeedbackRevisionDigest(directory,state2),previous=state2.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 record3={taskId,files,revisionDigest,declaredAt:isoNow()},nextState={...state2,updatedAt:isoNow(),prFeedbackScopes:[...previous.filter((entry)=>entry.taskId!==taskId),record3]};return await persistState2(directory,nextState),nextState}async function resolvePrFeedbackScopeDeclaration(directory,sessionID,taskId){let state2=await readPrWorkflowGateState(directory,sessionID);if(state2?.mode!=="PR_FEEDBACK")return null;let declaration=(state2.prFeedbackScopes??[]).find((entry)=>entry.taskId===taskId);if(!declaration)return null;return await assertPrFeedbackVerificationSettled(directory,sessionID),await currentPrFeedbackRevisionDigest(directory,state2)===declaration.revisionDigest?declaration:null}async function consumePrFeedbackScopeDeclaration(directory,sessionID,taskId,callID,expected){let normalizedSessionID=normalizeSessionID(sessionID);return withSessionStateMutation(directory,normalizedSessionID,async()=>{let state2=await readPrWorkflowGateStateFromDisk3(directory,normalizedSessionID);if(!state2||state2.mode!=="PR_FEEDBACK")return null;let declaration=(state2.prFeedbackScopes??[]).find((entry)=>entry.taskId===taskId);if(!declaration)return null;if(declaration.declaredAt!==expected.declaredAt||declaration.revisionDigest!==expected.revisionDigest||JSON.stringify(declaration.files)!==JSON.stringify(expected.files))return null;if(await assertPrFeedbackVerificationSettledState(directory,state2)!==declaration.revisionDigest)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 consumed={...declaration,consumedByCallId:callID};return await writeStateWhileLocked(directory,{...state2,updatedAt:isoNow(),prFeedbackScopes:(state2.prFeedbackScopes??[]).map((entry)=>entry.taskId===taskId?consumed:entry)}),consumed})}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=[],callID){let state2=await readPrWorkflowGateState(directory,sessionID);if(!state2){let normalizedEarlyTool=toolName.toLowerCase();if(normalizedEarlyTool==="bash"||normalizedEarlyTool==="shell"){let earlyCommand=typeof args2?.command==="string"?args2.command.trim():"";if(/\bgit\b/.test(earlyCommand)&&(/\bpush\b/.test(earlyCommand)||/\bsend-pack\b/.test(earlyCommand))||/\bgh\s+api\b/i.test(earlyCommand)&&/refs\/heads\//.test(earlyCommand)){let dangling=findDanglingLivePublicationGeneration(directory,sessionID);if(dangling)throw Error(`BLOCKED: PR_FEEDBACK publication generation ${dangling.generation} for this session is live in the audit trail but its gate state is missing (deleted or moved by hand). Publication commands fail closed until the window is resolved: use abort_pr_workflow with kind "cancel-publication", cancel_publication: true, and a reason to record the audited no-publish terminal, or restore the gate state from backup.`)}}return}if(state2.mode==="PR_FEEDBACK"&&state2.prFeedbackReadyToPublish&&!state2.prFeedbackPublication)state2=await ensurePublicationGenerationCurrent(directory,sessionID)??state2;let normalizedTool=toolName.toLowerCase(),isDirectAgentTask=normalizedTool==="task"||normalizedTool==="run_agent",requestedAgentFields=["subagent_type","agent"].filter((field)=>Object.hasOwn(args2??{},field)),requestedRoles=requestedAgentFields.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(state2.mode,normalizedTool),isShellTool3=normalizedTool==="bash"||normalizedTool==="shell",isReadOnlyShell=!1,shellPermissionEnvelope=null;if(isShellTool3&&command.length>0){let trackingFetchTarget=state2.prHeadSha?await _test_exports2.resolveCurrentUpstreamPushTargetAsync(directory):null;shellPermissionEnvelope={allowCheckout:!state2.prHeadSha,allowFetch:!state2.prHeadSha,allowTrackingFetch:Boolean(state2.prHeadSha),trackingFetchTarget},isReadOnlyShell=isAllowedPrWorkflowReadOnlyShell(command,shellPermissionEnvelope)}let trustedCapability=getPrWorkflowToolCapability(normalizedTool,state2.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(state2.checkoutRecovery){if(isRecoverySafeEvidenceTool||isReadOnlyShell||normalizedTool==="abort_pr_workflow"||normalizedTool==="pr_workflow_status"||normalizedTool==="prepare_pr_workflow_checkout")return;throw Error(`BLOCKED: ${state2.mode} requires manual Git recovery before controller work can continue. code=${state2.checkoutRecovery.code} retryable=false required_action=${state2.checkoutRecovery.requiredAction}`)}if(state2.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 ${state2.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(state2.mode==="PR_REVIEW"){let hasAuthorizedDirectReentry=!1;if(isDirectAgentTask&&requestedAgentFields.length===1&&requestedAgentFields[0]==="subagent_type"&&requestedRoles.length===1&&(requestedRoles[0]==="reviewer"||requestedRoles[0]==="test_engineer")&&callID)hasAuthorizedDirectReentry=await hasActivePrReviewReentryAuthorization(directory,sessionID,{role:requestedRoles[0]});if(!(isInternalWorkflowTool||hasAuthorizedDirectReentry||isNamedReadOnlyTool||isReadOnlyShell&&(!isShellCheckout||isCanonicalReviewCheckout))||Boolean(state2.prHeadSha)&&(isRemoteCheckoutTool||isShellCheckout)){if(!state2.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(state2.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(state2.mode));if(state2.prHeadSha&&(isShellCheckout||isRemoteCheckoutTool))throw Error("BLOCKED: PR_FEEDBACK checkout is immutable after exact PR head binding");if(containsGitCommitShell&&state2.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(state2.prFeedbackReadyToPublish){if(normalizedTool==="complete_pr_workflow")return;if(normalizedTool==="invalidate_pr_feedback_publication")return;if(normalizedTool==="abort_pr_workflow"&&args2?.cancel_publication===!0)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,{currentCallId:callID})).prFeedbackReadyToPublish,intent=parseExactBoundPushIntent(command,armed);if(intent.ok&&intent.intent&&intent.digest){await admitPrFeedbackPushAttempt(directory,sessionID,callID,intent.intent,intent.digest);return}throw Error(`BLOCKED: PR_FEEDBACK is armed for publication; only the exact approved push is allowed: ${expectedBoundPushCommand(armed)}${intent.reason?` (rejected form: ${intent.reason})`:""}`)}throw Error("BLOCKED: PR_FEEDBACK is armed for publication; only read-only inspection, the exact approved push, and complete_pr_workflow are allowed. To change approved content, use invalidate_pr_feedback_publication (audited invalidation; the full ladder re-runs) or abort_pr_workflow with cancel_publication for a terminal no-publish cancellation")}if(!state2.prHeadSha&&normalizedTool==="prepare_pr_workflow_checkout")return;if(!state2.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(!state2.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(!state2.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 readPrReviewReentryBindingContext(directory,sessionID){let state2=await readPrWorkflowGateStateFromDisk3(directory,normalizeSessionID(sessionID));return state2?prReviewReentryBindingFromState(directory,state2):null}async function prReviewReentryBindingFromState(directory,state2){if(state2.mode!=="PR_REVIEW"||!state2.prHeadSha)return null;let ctx=await createPrReviewGateContext2(directory,state2);return{prHeadSha:state2.prHeadSha,revisionDigest:ctx.revisionDigest,generation:state2.revision,...state2.workflowInstanceId?{workflowInstanceId:state2.workflowInstanceId}:{},...state2.prReviewArtifactRunId??state2.prReviewReservedRunId?{runId:state2.prReviewArtifactRunId??state2.prReviewReservedRunId??void 0}:{}}}async function hasActivePrReviewReentryAuthorization(directory,sessionID,request){let normalizedSessionID=normalizeSessionID(sessionID);return withSessionStateMutation(directory,normalizedSessionID,async()=>{let state2=await readPrWorkflowGateStateFromDisk3(directory,normalizedSessionID);if(!state2)return!1;let binding=await prReviewReentryBindingFromState(directory,state2);if(!binding)return!1;return hasPrReviewReentryAuthorizationAgainstBinding(directory,normalizedSessionID,request,binding)})}async function reserveActivePrReviewReentryAuthorization(directory,sessionID,request){let normalizedSessionID=normalizeSessionID(sessionID);return withSessionStateMutation(directory,normalizedSessionID,async()=>{let state2=await readPrWorkflowGateStateFromDisk3(directory,normalizedSessionID);if(!state2)return null;let binding=await prReviewReentryBindingFromState(directory,state2);if(!binding)return null;return await _test_exports2.beforePrReviewReentryReservation?.(),reservePrReviewReentryAuthorizationAgainstBinding(directory,normalizedSessionID,request,binding)})}async function completePrWorkflow(directory,sessionID,expectedMode,prHeadSha,options){let state2=await requireBoundState2(directory,sessionID,expectedMode),normalizedHead=normalizePrHeadSha(prHeadSha);if(state2.prHeadSha!==normalizedHead)throw Error(`BLOCKED: cannot complete ${expectedMode} at PR head "${normalizedHead}"; workflow is bound to "${state2.prHeadSha}"`);let laneSettlement=await settlePresumedStalePrWorkflowLanes(directory,state2.sessionID,options?.laneLiveness);if(laneSettlement.uncertainty)throw Error(`BLOCKED: ${expectedMode} completion refused while the delegation store is unreadable after ${laneSettlement.uncertainty.attempts} attempts (${laneSettlement.uncertainty.reason}); open lanes are UNKNOWN, not absent. Restore the store and re-run completion (a healthy empty store still completes through its valid INCOMPLETE route).`);if(laneSettlement.openLanes>0)throw Error(`BLOCKED: ${expectedMode} completion has ${laneSettlement.openLanes} unsettled PR workflow lane(s)`+describePrWorkflowLaneProbe(laneSettlement));let terminalClearRevision;if(expectedMode==="PR_REVIEW"){let verdict=options?.reportVerdict;if(verdict===void 0)throw Error("BLOCKED: PR_REVIEW completion requires a terminal report_verdict (APPROVE, REQUEST_CHANGES, or INCOMPLETE)");let ctx=await createPrReviewGateContext2(directory,state2),settlement=derivePrReviewDimensionSettlement(directory,state2,ctx.revisionDigest),disclosedDegradation=settlement.kind==="COMPLETE"&&(prReviewReceiptHasCoverageDegradations(directory,state2.prReviewTriggerEvalPath)||await verdictSettlementDegradesReport(directory,state2,ctx)),dispatchCoverageFinalization=(finalizationSettlement)=>{let outcome=reducePrReviewEvent(state2,{type:"coverage_finalization_requested",settlement:{kind:finalizationSettlement.kind,coveredDimensions:finalizationSettlement.coveredDimensions,unresolvedDimensions:finalizationSettlement.unresolvedDimensions,liveDimensions:finalizationSettlement.liveDimensions},requestedVerdict:verdict,disclosedDegradation});if(outcome.status==="applied")return;let{code}=outcome.rejection;if(code==="live_lane_blocks_coverage"){if(finalizationSettlement.kind==="NO_COVERAGE")throw Error(`BLOCKED: PR_REVIEW completion has zero covered dimensions and still-live lanes for: ${finalizationSettlement.liveDimensions.join(", ")}. Collect or settle them, then complete with report_verdict INCOMPLETE.`);throw Error(`BLOCKED: PR_REVIEW base coverage is incomplete and still has live lanes for: ${finalizationSettlement.liveDimensions.join(", ")}. Completion is allowed only once every launched lane is terminal or explicitly cancelled.`)}if(code==="no_coverage_requires_incomplete")throw Error(`BLOCKED: PR_REVIEW NO_COVERAGE completion must report verdict INCOMPLETE; got "${verdict}". A zero-coverage report never approves and never claims a code-quality review.`);if(code==="degraded_disclosure_cannot_approve")throw Error(`BLOCKED: PR_REVIEW ${finalizationSettlement.kind} completion discloses a coverage degradation (dead family or dead verdict lane) and cannot report verdict APPROVE; got "${verdict}". Report REQUEST_CHANGES with the disclosed degradation surfaced in the report, or INCOMPLETE.`);let allowedList=allowedPrReviewReportVerdicts(finalizationSettlement.kind,[],{disclosedCoverageDegradation:disclosedDegradation}).join(" | ");throw Error(`BLOCKED: PR_REVIEW ${finalizationSettlement.kind} completion allows report_verdict ${allowedList}; got "${verdict}". Partial coverage never approves and never claims a full review.`)};if(settlement.kind==="PARTIAL"||settlement.kind==="NO_COVERAGE"){let stagedPolicyEnabled=state2.prReviewResilience?.policy?.enabled===!0,consumedLegacyContractRetry=new Set(state2.prReviewContractRetryDimensions??[]),attemptsUsed=state2.prReviewResilience?.attempts?.length??0,maxAttempts=1+(state2.prReviewResilience?.policy?.maxRetryAttemptsAfterInitial??0),retryableRemainder=settlement.unresolvedDimensions.filter((entry)=>{if(entry.failureClass==="operator_cancelled")return!1;if(stagedPolicyEnabled)return entry.failureClass==="contract"||entry.failureClass==="resource";return entry.failureClass==="contract"&&!consumedLegacyContractRetry.has(entry.dimension)});if(retryableRemainder.length>0&&attemptsUsed<maxAttempts){try{appendCoreEventSync(directory,{type:"pr_review_completion_retryable_remainder",timestamp:isoNow(),sessionID:state2.sessionID,prHeadSha:state2.prHeadSha,coverageKind:settlement.kind,remainingDimensions:retryableRemainder.map((entry)=>`${entry.dimension}:${entry.terminalState}:${entry.failureClass??"none"}`),attemptsUsed,maxAttempts,stagedPolicyEnabled})}catch{}throw Error(`BLOCKED: PR_REVIEW ${settlement.kind} completion refused while eligible retryable work remains and retry budget is available. Remaining dimensions: ${retryableRemainder.map((entry)=>`${entry.dimension} (${entry.failureClass})`).join(", ")}. Retry budget: ${attemptsUsed}/${maxAttempts} attempts used${stagedPolicyEnabled?" (staged policy)":" (legacy single contract retry)"} — re-dispatch the dimension(s) via dispatch_lanes_async to consume the retry budget, or end the workflow through the human force path (/swarm abort-pr-workflow). If lanes are still live at an earlier stage, settle them explicitly first — cancel_lane_batch (confirm: true + reason) refuses busy/retry lanes, so live work is never destroyed on the model path.`)}}if(dispatchCoverageFinalization(settlement),settlement.kind==="NO_COVERAGE"){let noCoverageRunId=state2.prReviewArtifactRunId??state2.prReviewReservedRunId??generatePrReviewRunId();terminalClearRevision=(await admitPrReviewPartialBaseCoverage2(directory,sessionID,noCoverageRunId,settlement.unresolvedDimensions.map((entry)=>entry.dimension))).revision;try{appendCoreEventSync(directory,{type:"pr_review_no_coverage_terminal",timestamp:isoNow(),sessionID:state2.sessionID,prHeadSha:state2.prHeadSha,revisionDigest:ctx.revisionDigest,coveredDimensions:settlement.coveredDimensions.length,unresolvedDimensions:settlement.unresolvedDimensions.map((entry)=>`${entry.dimension}:${entry.terminalState}`),disclosureRunId:noCoverageRunId,reportVerdict:verdict})}catch{}}else{let preAllowed=allowedPrReviewReportVerdicts(settlement.kind,[],{disclosedCoverageDegradation:disclosedDegradation});if(!preAllowed.includes(verdict))throw Error(`BLOCKED: PR_REVIEW ${settlement.kind} completion allows report_verdict ${preAllowed.join(" | ")}; got "${verdict}". Partial coverage never approves and never claims a full review.`);let ready=await assertPrReviewTerminalReady(directory,sessionID,options?.laneLiveness),readyState=ready.state;if(workflowIdentity(readyState)!==workflowIdentity(state2)||readyState.revision!==state2.revision)throw Error("BLOCKED: PR_REVIEW state changed while checking terminal readiness; retry from current state");if(ready.settlement.kind==="COMPLETE")disclosedDegradation=prReviewReceiptHasCoverageDegradations(directory,readyState.prReviewTriggerEvalPath)||await verdictSettlementDegradesReport(directory,readyState);dispatchCoverageFinalization(ready.settlement);let finalFindingAuthority=await readAuthoritativeFindingPolicy(directory,readyState),policyAllowed=allowedPrReviewReportVerdicts(ready.settlement.kind,finalFindingAuthority.policyFindings,{disclosedCoverageDegradation:disclosedDegradation});if(!policyAllowed.includes(verdict))throw Error(`BLOCKED: PR_REVIEW ${ready.settlement.kind} completion allows report_verdict ${policyAllowed.join(" | ")}; got "${verdict}". Final finding policy and coverage do not permit this report.`)}}else{await ensurePublicationGenerationCurrent(directory,sessionID);let readyState=await assertPrFeedbackReadyToPublish(directory,sessionID);readyState=await reconcileForeignInFlightAttempt(directory,sessionID)??readyState;let currentDigest=await currentPrFeedbackRevisionDigest(directory,readyState),armed=readyState.prFeedbackReadyToPublish;if(!armed){let previousActive=readyState.prFeedbackPublication?.active;if(previousActive?.state==="published"){if((await _test_exports2.resolveExactRemoteBranchHeadAsync(directory,previousActive.remoteName,previousActive.remoteBranchRef))?.toLowerCase()!==previousActive.localHead.toLowerCase())throw Error(`BLOCKED: PR_FEEDBACK generation ${previousActive.generation} is marked published but the remote verification no longer holds; inspect pr_workflow_status`);return await _test_exports2.beforeTerminalClear?.(),await clearPrWorkflowGateState(directory,sessionID,readyState.revision),"completed"}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,state2.prHeadSha,localHead);if(commitCount===0){if(localHead!==state2.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=readLegacySettledFeedbackClassifications(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{appendCoreEventSync(directory,{type:"pr_feedback_verified_no_change",timestamp:isoNow(),sessionID:state2.sessionID,prHeadSha:state2.prHeadSha,items:inventory.length})}catch{}if(previousActive&&previousActive.state==="invalidated")appendPublicationEvent(directory,{type:"pr_feedback_publication_cancelled",sessionID:state2.sessionID,generation:previousActive.generation,reason:"verified-no-change-terminal"});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,state2.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");if(previousActive&&previousActive.state!=="invalidated")throw Error(`BLOCKED: PR_FEEDBACK cannot arm a new publication generation while generation ${previousActive.generation} is ${previousActive.state}`);let workspaceIdentity=canonicalWorkspaceIdentity(directory);if(!workspaceIdentity)throw Error("BLOCKED: PR_FEEDBACK cannot arm publication without a canonical workspace identity");let localHeadRef=await _test_exports2.resolveCurrentLocalHeadRefAsync(directory);if(!localHeadRef)throw Error("BLOCKED: PR_FEEDBACK cannot arm publication without the current branch ref (HEAD appears detached)");let remoteUrlIdentity=await _test_exports2.resolveRemoteUrlIdentityAsync(directory,upstreamTarget.remoteName);if(!remoteUrlIdentity)throw Error(`BLOCKED: PR_FEEDBACK cannot arm publication without a credential-redacted remote URL identity for "${upstreamTarget.remoteName}"`);let evidenceJoin=buildPublicationEvidenceJoin(readyState,currentDigest);if(!evidenceJoin)throw Error("BLOCKED: PR_FEEDBACK cannot arm publication without the exact settled receipt set (Stage A plus one batch per ordered phase)");let armedAt=isoNow(),generation={schemaVersion:PUBLICATION_SCHEMA_VERSION,generation:(previousActive?.generation??0)+1,state:"armed",workspaceIdentity,sessionID:readyState.sessionID,prTargetUrl:readyState.prFeedbackTargetUrl,intakeHeadSha:readyState.prHeadSha??"unknown",localHeadRef,localHead,remoteName:upstreamTarget.remoteName,remoteUrlIdentity,remoteBranchRef:upstreamTarget.remoteBranchRef,remoteRef:upstreamTarget.remoteTrackingRef,revisionDigest:currentDigest,evidence:evidenceJoin,createdAt:armedAt,armedAt};return await persistState2(directory,{...readyState,updatedAt:armedAt,prFeedbackReadyToPublish:deriveReadyToPublishMirror(generation),prFeedbackPublication:nextPublicationContainer(readyState.prFeedbackPublication,generation,previousActive?[{...previousActive,supersededByGeneration:generation.generation}]:[],[])}),appendPublicationEvent(directory,{type:"pr_feedback_publication_armed",sessionID:readyState.sessionID,generation:generation.generation,supersedes:previousActive?.generation??null,revisionDigest:currentDigest,localHead,remoteName:upstreamTarget.remoteName,remoteUrlIdentity,remoteBranchRef:upstreamTarget.remoteBranchRef}),"ready-to-publish"}let armedState=await assertPrFeedbackPublicationArmed(directory,sessionID),active=armedState.prFeedbackPublication?.active;if(!active)throw Error("BLOCKED: PR_FEEDBACK publication is not armed; call complete_pr_workflow once after every ordered gate passes");let attemptsForGeneration=(armedState.prFeedbackPublication?.attempts??[]).filter((attempt)=>attempt.generation===active.generation);if(!attemptsForGeneration.some((attempt)=>attempt.result))throw Error(`BLOCKED: PR_FEEDBACK completion requires the exact approved push to have been admitted and observed for generation ${active.generation}; run the exact push first: ${expectedBoundPushCommand(armed)}`);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`);let publishedAt=isoNow(),published={...active,state:"published",publishedAt},publishState={...armedState,updatedAt:publishedAt,prFeedbackReadyToPublish:void 0,prFeedbackPublication:nextPublicationContainer(armedState.prFeedbackPublication,published)};return await persistState2(directory,publishState),appendPublicationEvent(directory,{type:"pr_feedback_published",sessionID:armedState.sessionID,generation:published.generation,localHead:published.localHead,remoteName:published.remoteName,remoteBranchRef:published.remoteBranchRef,remoteUrlIdentity:published.remoteUrlIdentity??null,revisionDigest:published.revisionDigest,attempts:attemptsForGeneration.length}),await _test_exports2.beforeTerminalClear?.(),await clearPrWorkflowGateState(directory,sessionID,publishState.revision),"completed"}return await _test_exports2.beforeTerminalClear?.(),await clearPrWorkflowGateState(directory,sessionID,terminalClearRevision??state2.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 state2=await readPrWorkflowGateState(directory,sessionID);if(!state2)throw noActiveGateError(sessionID);return state2}async function requireBoundState2(directory,sessionID,expectedMode){let state2=await requireAnyActiveState(directory,sessionID);if(state2.mode!==expectedMode)throw wrongModeError(state2,expectedMode);if(!state2.prHeadSha)throw Error(`BLOCKED: active ${expectedMode} workflow is not bound to a PR head`);if(expectedMode==="PR_REVIEW")await assertCurrentCheckoutHead(directory,state2.prHeadSha,"PR_REVIEW"),await assertPrReviewCleanCheckout(directory);return state2}function wrongModeError(state2,expectedMode){return Error(`BLOCKED: session "${state2.sessionID}" is active in ${state2.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 tokens2=toolName.split(/[._:/-]+/).filter(Boolean);if(tokens2.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 tokens2.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(path120,constraint,value){return{safe:!1,path:path120||"(root)",constraint,value}}function readOnlyArgumentPath(parent,key2){return parent?`${parent}.${key2}`:key2}function isDeclaredReadOnlyMethod(toolName,value){if(!PR_REVIEW_TOOLS_WITH_ENUMERATED_READ_METHODS.has(toolName))return!1;return PR_REVIEW_ENUMERATED_READ_METHODS.has(value.trim().toLowerCase())}function classifyReadOnlyToolArguments(toolName,value,key2="",path120="",depth=0){if(depth>8)return unsafeReadOnlyArgument(path120,"argument nesting exceeds the read-only depth limit of 8",value);let keyTokens=key2.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(path120,"argument name is mutation-bearing and is not allowed for read-only tools",value);if(keyTokens.some((token)=>/^(?:method|verb)$/i.test(token))){if(typeof value!=="string")return unsafeReadOnlyArgument(path120,"HTTP method/verb must be GET or HEAD for a read-only tool",value);if(/^(?:GET|HEAD)$/i.test(value.trim()))return{safe:!0};if(isDeclaredReadOnlyMethod(toolName,value))return{safe:!0};return unsafeReadOnlyArgument(path120,"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(path120,"action/operation must name a recognized observation operation",value);if(/^mode$/i.test(key2)&&typeof value==="string")return(toolName==="search"?/^(?:r|rb|read|literal|regex)$/i:/^(?:r|rb|read)$/i).test(value.trim())?{safe:!0}:unsafeReadOnlyArgument(path120,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(path120,"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(path120,"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],key2,`${path120}[${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(path120,childKey),depth+1);if(!result.safe)return result}return{safe:!0}}return unsafeReadOnlyArgument(path120,"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 tokens2=[],current="",quoted2=!1,quote=null,pipeIsDoubleQuoted=!0,flush=()=>{if(current.length>0||quoted2)tokens2.push({value:current,quoted:quoted2,pipeIsDoubleQuoted});current="",quoted2=!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==='"'){quoted2=!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=tokens2.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],gitGrepPattern=resolveGitGrepRegexPatternOperand(tokens2);if(gitGrepPattern!==null&&gitGrepPattern===quotedPipeToken&"edPipeToken.pipeIsDoubleQuoted)return{unsafe:!1,reason:null};if(!/^gh\s+api(?:\s|$)/i.test(compact))return{unsafe:!0,reason:"gh-api-jq-pipe"};for(let index=0;index<tokens2.length;index+=1)if(tokens2[index].value==="--jq"&&tokens2[index+1]===quotedPipeToken)return{unsafe:!1,reason:null};return{unsafe:!0,reason:"gh-api-jq-pipe"}}function resolveGitGrepRegexPatternOperand(tokens2){if(tokens2.length===0||tokens2[0].value!=="git")return null;let index=1;while(index<tokens2.length){let value=tokens2[index].value;if(/^--[\w-]+=/.test(value)){index+=1;continue}if(value==="-C"){index+=2;continue}if(value.startsWith("-C=")||value.startsWith("-C")&&value.length>2){index+=1;continue}if(value==="-c"){index+=2;continue}if(value.startsWith("-C")&&value.length>2){index+=1;continue}if(value==="--"){index+=1;break}if(value.startsWith("-")){index+=1;continue}break}if(tokens2[index]?.value!=="grep")return null;index+=1;let extendedRegexp=!1,operand=null;for(;index<tokens2.length;index+=1){let token=tokens2[index],value=token.value;if(value==="--extended-regexp"){extendedRegexp=!0;continue}if(value.startsWith("--"))continue;if(value.startsWith("-")&&/^-\w+$/.test(value)){if(/[Ee]/.test(value.slice(1)))extendedRegexp=!0;continue}operand=token;break}if(!extendedRegexp)return null;return operand}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 or a double-quoted `git grep -E` pattern operand; 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 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 tokens2=gitArgs.trim().split(/\s+/);if(tokens2.length!==3||tokens2[0].toLowerCase()!=="fetch")return!1;let[,remote,remoteBranch]=tokens2,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 tokens2=gitArgs.trim().split(/\s+/);if(tokens2.length===5){let[verb,createFlag,localBranch,trackFlag,upstream]=tokens2;return(verb==="checkout"||verb==="switch")&&(createFlag==="-b"||createFlag==="-c")&&trackFlag==="--track"&&isSafeGitRefToken(localBranch)&&isSafeGitRefToken(upstream)&&upstream.includes("/")}if(tokens2.length===3&&tokens2[0]==="branch"){let upstream=tokens2[1].match(/^--set-upstream-to=(.+)$/)?.[1];return Boolean(upstream&&isSafeGitRefToken(upstream)&&upstream.includes("/")&&isSafeGitRefToken(tokens2[2]))}return!1}function isAllowedReadOnlyGitBranchListing(gitArgs){let tokens2=gitArgs.trim().split(/\s+/);if(tokens2.length===0||tokens2[0].toLowerCase()!=="branch")return!1;let listingSelectorInEffect=!1;for(let index=1;index<tokens2.length;index+=1){let token=tokens2[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 tokens2=gitArgs.trim().split(/\s+/);if(tokens2.length<2||tokens2[0].toLowerCase()!=="stash")return!1;if(tokens2[1].toLowerCase()!=="list")return!1;for(let index=2;index<tokens2.length;index+=1){let token=tokens2[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 tokens2=gitArgs.trim().split(/\s+/);if(tokens2.length<2||tokens2[0].toLowerCase()!=="worktree")return!1;if(tokens2[1].toLowerCase()!=="list")return!1;for(let index=2;index<tokens2.length;index+=1){let token=tokens2[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 tokens2=command.trim().split(/\s+/);if(tokens2.length<4||tokens2[0]!=="gh"||tokens2[1]!=="pr"||tokens2[2]!=="checkout")return!1;let target=tokens2[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<tokens2.length;index+=1){let token=tokens2[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=tokens2[++index];if(!repo||!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repo))return!1;continue}if(token==="--branch"||token==="-b"){let branch=tokens2[++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,state2){if(!state2.prHeadSha)throw Error("BLOCKED: PR_FEEDBACK revision binding requires pr_head_sha");let resolved=await resolvePrWorkflowRevisionDigestForGate(directory,state2.prHeadSha);if(!resolved.ok)throw Error(`BLOCKED: PR_FEEDBACK could not compute a bounded current-revision digest for pr_head_sha "${state2.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 digest3=_test_exports2.resolvePrWorkflowRevisionDigest(directory,baseHeadSha);return digest3?{ok:!0,digest:digest3}:{ok:!1,reason:"seam-unavailable"}}return resolvePrWorkflowRevisionDigestDetailedAsync(directory,baseHeadSha)}async function createPrReviewGateContext2(directory,state2){if(!state2.prHeadSha)throw Error("BLOCKED: PR_REVIEW revision binding requires pr_head_sha");let resolved=await resolvePrWorkflowRevisionDigestForGate(directory,state2.prHeadSha);if(!resolved.ok)throw Error(`BLOCKED: PR_REVIEW could not compute a bounded current-revision digest for pr_head_sha "${state2.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 derivePrReviewCandidateInventory2(directory,state2,ctx){if(ctx.candidateInventory)return ctx.candidateInventory;let sources=[],baseDimensionSources=new Map,baseSourceCreditedDimensions=new Map,baseSourceFullOwnershipCount=new Map,reversedBaseBatches=[...state2.prReviewBaseDispatches??[]].reverse(),successfulByBaseBatchId=new Map;for(let batch of reversedBaseBatches)successfulByBaseBatchId.set(batch.batchId,successfulObligationsFromExactBatch2(directory,state2,batch.batchId,batch.lanes,"swarm-pr-review:base",batch.validatedAt,!0,new Set,ctx.revisionDigest));let laneClassPasses=(state2.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;let creditedDimensions=ownedDimensions.filter((dimension)=>successful2.has(dimension));if(creditedDimensions.length===0)continue;let key2=`${batch.batchId}\x00${lane.laneId}`;baseSourceFullOwnershipCount.set(key2,ownedDimensions.length);for(let dimension of creditedDimensions)if(!baseDimensionSources.has(dimension)){baseDimensionSources.set(dimension,{batchId:batch.batchId,laneId:lane.laneId});let credited=baseSourceCreditedDimensions.get(key2);if(credited)credited.push(dimension);else baseSourceCreditedDimensions.set(key2,[dimension])}}}let seenBaseSourceKeys=new Set;for(let{batchId,laneId}of baseDimensionSources.values()){let key2=`${batchId}\x00${laneId}`;if(seenBaseSourceKeys.has(key2))continue;seenBaseSourceKeys.add(key2);let credited=baseSourceCreditedDimensions.get(key2),fullOwnershipCount=baseSourceFullOwnershipCount.get(key2)??0;sources.push({batchId,laneId,mode:"swarm-pr-review:base",creditedLanes:credited&&credited.length<fullOwnershipCount?credited:void 0})}let selectedCouncilLanes=new Set;if(state2.prReviewTriggerEvalPath)for(let batch of[...state2.prReviewValidationBatches??[]].reverse()){if(batch.phase!=="council")continue;let successful2=successfulObligationsFromExactBatch2(directory,state2,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(state2.prReviewTriggerEvalPath){let receiptRead=readPrReviewTriggerReceiptForGate(directory,state2.prReviewTriggerEvalPath),receipt="noReceipt"in receiptRead?null:receiptRead.receipt;if(!receipt)throw Error("BLOCKED: PR_REVIEW trigger evaluation artifact is missing or invalid");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,sourceRead=findByBatchIdDetailed(directory,source.batchId,{parentSessionId:state2.sessionID});if(sourceRead.status==="uncertain")throw Error(`BLOCKED: PR_REVIEW discovery provenance cannot be read for ${source.workflowLane??source.laneId}: the delegation store is unreadable after ${sourceRead.attempts} attempts (${sourceRead.reason}); the lane's records are UNKNOWN, not absent. Restore the store and re-run discovery.`);for(let record3 of sourceRead.value){if(record3.laneId!==source.laneId||record3.mode!==source.mode||record3.workspace?.prHeadSha!==state2.prHeadSha||record3.workspace?.gitHead!==state2.prHeadSha)continue;let structured=record3.result?.prReviewResultReceipt;if(structured){let credited=source.creditedLanes?.length?structured.envelope.creditedLanes.filter((lane)=>source.creditedLanes?.includes(lane)):structured.envelope.creditedLanes;if(source.workflowLane&&!credited.includes(source.workflowLane))continue;resolvedArtifact=!0;let laneKey2=`${source.batchId}\x00${source.laneId}`;if(!extractedLaneKeys.has(laneKey2)){extractedLaneKeys.add(laneKey2);for(let finding of structured.envelope.findings){if(!credited.includes(finding.workflowLane))continue;if(candidateIds.push(finding.id),!candidateSeverities.has(finding.id))candidateSeverities.set(finding.id,finding.severity)}}continue}let ref=record3.result?.outputRef?.trim(),artifact=ref?readLaneOutput(directory,ref)?.artifact:void 0,recordOwnedLanes=record3.ownedWorkflowLanes?.length?record3.ownedWorkflowLanes:record3.workflowLane?[record3.workflowLane]:void 0;if(!artifact||!workflowArtifactHasContractMarker(directory,state2,record3,source.mode,record3.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 boundPrReviewStatusReason(error93){let cleaned=(error93 instanceof Error?error93.message:String(error93??"unknown error")).replace(/[\p{Cc}]/gu," ").replace(/[`<>]/g," ").replace(/\s+/g," ").trim();return cleaned.length>PR_REVIEW_STATUS_REASON_MAX_CHARS?`${cleaned.slice(0,PR_REVIEW_STATUS_REASON_MAX_CHARS)}…`:cleaned}async function derivePrReviewCandidateInventoryForStatus(directory,state2){if(!state2.prHeadSha)return{state:"unavailable",reason:"active PR_REVIEW workflow is not bound to a PR head"};try{let ctx=await createPrReviewGateContext2(directory,state2);return{state:"available",inventory:derivePrReviewCandidateInventory2(directory,state2,ctx)}}catch(error93){return{state:"unavailable",reason:boundPrReviewStatusReason(error93)}}}function appendBoundedCandidateIssue(issues,message){if(issues.length<MAX_CANDIDATE_ISSUES_PER_ARTIFACT-1){issues.push(message.slice(0,MAX_BASE_COVERAGE_DIAGNOSTIC_CHARS2));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 normalizeCandidateArtifactCached(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 issue3 of analysis.issues)appendBoundedCandidateIssue(issues,`row ${index+1} field ${issue3.field}: ${issue3.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,state2,ctx){if(!ctx.candidateSeverities)derivePrReviewCandidateInventory2(directory,state2,ctx);if(!ctx.candidateSeverities)throw Error("BLOCKED: PR_REVIEW candidate severity authority is unavailable for this gate context");return ctx.candidateSeverities}function prReviewPhaseWindow2(state2,phase){let all=state2.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 reviewerSubagentSessionIds2(directory,state2){let forbidden=new Set(state2.prReviewRetiredReviewerSessionIds??[]);for(let reviewerBatch of(state2.prReviewValidationBatches??[]).filter((batch)=>batch.phase==="reviewer")){let batchRead=findByBatchIdDetailed(directory,reviewerBatch.batchId,{parentSessionId:state2.sessionID});if(batchRead.status==="uncertain")throw Error(`BLOCKED: PR_REVIEW critic reuse ban cannot be derived: the delegation store is unreadable after ${batchRead.attempts} attempts (${batchRead.reason}); reviewer batch ${reviewerBatch.batchId}'s child sessions are UNKNOWN, not absent. Restore the store and re-derive.`);for(let record3 of batchRead.value){let subagentSessionId=record3.subagentSessionId?.trim();if(subagentSessionId)forbidden.add(subagentSessionId)}}return forbidden}function batchMayContributeClaims2(directory,state2,batch,phase,requiredInventory,forbiddenSubagentSessionIds,reviewerClaims,ctx){let coherence=state2.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=successfulObligationsFromExactBatch2(directory,state2,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 admittedVerdictSettlementReceipt(directory,state2,phase,expectedRevisionDigest){let runId=state2.prReviewArtifactRunId??state2.prReviewReservedRunId;if(!runId)return;let read=readVerdictSettlementReceipt(directory,runId,phase);if(read.status!=="ok")return;if(read.receipt.runId!==runId||read.receipt.phase!==phase)return;if(read.receipt.prHeadSha!==state2.prHeadSha)return;if(read.receipt.revisionDigest!==expectedRevisionDigest)return;let anchoredDigest=state2.prReviewVerdictSettlementDigests?.[phase];if(!anchoredDigest||anchoredDigest!==read.rawSha256)return;return read.receipt}function settlementCoveringAllUnclaimed(directory,state2,phase,unclaimed,expectedRevisionDigest){if(unclaimed.length===0)return;let receipt=admittedVerdictSettlementReceipt(directory,state2,phase,expectedRevisionDigest);if(!receipt)return;return effectiveVerdictSettlementItems(receipt,unclaimed).length===unclaimed.length?receipt:void 0}function verdictSettlementEffectiveIdsForGate(directory,state2,phase,ctx){let composed=composePrReviewPhaseVerdicts(directory,state2,phase,ctx),receipt=settlementCoveringAllUnclaimed(directory,state2,phase,composed.unclaimed,ctx.revisionDigest);if(!receipt)return new Set;return new Set(effectiveVerdictSettlementItems(receipt,composed.unclaimed).map((item)=>item.itemId))}async function verdictSettlementDegradesReport(directory,state2,ctx){let gateCtx=ctx??await createPrReviewGateContext2(directory,state2);return verdictSettlementDegradationActive({directory,runId:state2.prReviewArtifactRunId??state2.prReviewReservedRunId,prHeadSha:state2.prHeadSha,revisionDigest:gateCtx.revisionDigest,reviewerUnclaimed:composePrReviewPhaseVerdicts(directory,state2,"reviewer",gateCtx).unclaimed,criticUnclaimed:composePrReviewPhaseVerdicts(directory,state2,"critic",gateCtx).unclaimed})}function authoritativeReviewerClaims2(directory,state2,ctx){let composed=composePrReviewPhaseVerdicts(directory,state2,"reviewer",ctx);if(composed.unclaimed.length===0)return composed.claims;return settlementCoveringAllUnclaimed(directory,state2,"reviewer",composed.unclaimed,ctx.revisionDigest)?composed.claims:new Map}function criticReviewerItemBindings(directory,state2,lanes,ctx){let reviewerClaims=authoritativeReviewerClaims2(directory,state2,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 derivePrReviewCriticInventory2(directory,state2,ctx){return[...authoritativeReviewerVerdictsForGate(directory,state2,ctx,"derivePrReviewCriticInventory").entries()].filter(([,verdict])=>prReviewFindingRequiresCritic({classification:verdict.classification,severity:verdict.severity,risk_impact:verdict.riskImpact,risk_tags:verdict.riskTags})).map(([itemId])=>itemId).sort()}function deriveLatestPrReviewCriticVerdicts(directory,state2,ctx){let composed=composePrReviewPhaseVerdicts(directory,state2,"critic",ctx);if(composed.unclaimed.length>0&&!settlementCoveringAllUnclaimed(directory,state2,"critic",composed.unclaimed,ctx.revisionDigest))return new Map;return new Map([...composed.claims].map(([itemId,claim])=>[itemId,{status:claim.classification,severity:claim.severity}]))}function deriveAuthoritativeCriticSettlements(directory,state2,ctx,criticInventory){let verdicts=deriveLatestPrReviewCriticVerdicts(directory,state2,ctx),unavailableIds=verdictSettlementEffectiveIdsForGate(directory,state2,"critic",ctx);return criticInventory.map((findingId2)=>{let verdict=verdicts.get(findingId2);if(unavailableIds.has(findingId2)&&(!verdict||verdict.status==="NEEDS_MORE_EVIDENCE"))return{findingId:findingId2,terminal:!0,status:"CRITIC_UNAVAILABLE"};if(!verdict||verdict.status==="NEEDS_MORE_EVIDENCE")return{findingId:findingId2,terminal:!1,status:"NEEDS_MORE_EVIDENCE"};if(verdict.status==="UPHELD"||verdict.status==="DOWNGRADED"||verdict.status==="DISPROVED")return{findingId:findingId2,terminal:!0,status:verdict.status};return{findingId:findingId2,terminal:!1,status:"NEEDS_MORE_EVIDENCE"}})}async function readPrReviewVerdictSettlementReceiptItems(directory,sessionID){let state2=await requireBoundState2(directory,sessionID,"PR_REVIEW"),ctx=await createPrReviewGateContext2(directory,state2),rows=[];for(let phase of["reviewer","critic"]){let composed=composePrReviewPhaseVerdicts(directory,state2,phase,ctx),receipt=settlementCoveringAllUnclaimed(directory,state2,phase,composed.unclaimed,ctx.revisionDigest);if(!receipt)continue;for(let item of effectiveVerdictSettlementItems(receipt,composed.unclaimed))rows.push({...item})}return rows}async function readPrReviewVerdictSettlementEffectiveIds(directory,sessionID,phase){let state2=await requireBoundState2(directory,sessionID,"PR_REVIEW"),ctx=await createPrReviewGateContext2(directory,state2),composed=composePrReviewPhaseVerdicts(directory,state2,phase,ctx),receipt=settlementCoveringAllUnclaimed(directory,state2,phase,composed.unclaimed,ctx.revisionDigest);if(!receipt)return new Set;return new Set(effectiveVerdictSettlementItems(receipt,composed.unclaimed).map((item)=>item.itemId))}async function readAuthoritativePrReviewCriticSettlements(directory,sessionID){let state2=await requireBoundState2(directory,sessionID,"PR_REVIEW"),ctx=await createPrReviewGateContext2(directory,state2),inventory=derivePrReviewCriticInventoryForCoverageGate(directory,state2,ctx,"readAuthoritativePrReviewCriticSettlements");return deriveAuthoritativeCriticSettlements(directory,state2,ctx,inventory)}function deriveLatestPrReviewReviewerVerdicts(directory,state2,ctx){return new Map([...authoritativeReviewerClaims2(directory,state2,ctx)].map(([itemId,claim])=>[itemId,{classification:claim.classification,severity:claim.severity,riskImpact:claim.riskImpact,riskTags:claim.riskTags}]))}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,state2,ctx,origin){let verdicts=deriveLatestPrReviewReviewerVerdicts(directory,state2,ctx);return assertSettledPhaseHasAuthoritativeVerdicts("reviewer",composePrReviewPhaseVerdicts(directory,state2,"reviewer",ctx),verdicts,origin),verdicts}function authoritativeCriticVerdictsForGate(directory,state2,ctx,origin){let verdicts=deriveLatestPrReviewCriticVerdicts(directory,state2,ctx);return assertSettledPhaseHasAuthoritativeVerdicts("critic",composePrReviewPhaseVerdicts(directory,state2,"critic",ctx),verdicts,origin),verdicts}async function readAuthoritativePrReviewCriticVerdicts(directory,sessionID){let state2=await requireBoundState2(directory,sessionID,"PR_REVIEW"),ctx=await createPrReviewGateContext2(directory,state2);return authoritativeCriticVerdictsForGate(directory,state2,ctx,"write_pr_review_artifact critic settlement")}function derivePrReviewCriticInventoryForCoverageGate(directory,state2,ctx,origin){let reviewer=composePrReviewPhaseVerdicts(directory,state2,"reviewer",ctx);if(reviewer.unclaimed.length>0){if(!settlementCoveringAllUnclaimed(directory,state2,"reviewer",reviewer.unclaimed,ctx.revisionDigest)){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 derivePrReviewCriticInventory2(directory,state2,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_CHARS2)}function analyzeLaneRecordResultIntegrity(args2){let{record:record3,result,expected}=args2;if(expected.checkWorkflowLane&&record3.workflowLane!==expected.workflowLane)return failedLaneValidation("record.workflow_lane",expected.workflowLane,record3.workflowLane??"(missing)");if(expected.checkWorkflowLane&&!ownedLaneSetsEqual(record3.ownedWorkflowLanes,expected.ownedWorkflowLanes))return failedLaneValidation("record.owned_workflow_lanes",expected.ownedWorkflowLanes,record3.ownedWorkflowLanes??(record3.workflowLane?[record3.workflowLane]:[]));if(record3.mode!==expected.mode)return failedLaneValidation("record.mode",expected.mode,record3.mode??"(missing)");if(record3.workspace?.prHeadSha!==expected.prHeadSha)return failedLaneValidation("record.pr_head_sha",expected.prHeadSha,record3.workspace?.prHeadSha??"(missing)");if(record3.workspace?.gitHead!==expected.gitHead)return failedLaneValidation("record.git_head",expected.gitHead,record3.workspace?.gitHead??"(missing)");if(args2.requireCompleted&&record3.status!=="completed")return failedLaneValidation("record.status","completed",record3.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((record3)=>record3.laneId&&expectedByLaneId.has(record3.laneId)),recordsByLaneId=new Map,recordCountBySubagentSessionId=new Map;for(let record3 of relevantRecords){let laneRecords=recordsByLaneId.get(record3.laneId)??[];laneRecords.push(record3),recordsByLaneId.set(record3.laneId,laneRecords);let sessionId=record3.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 record3=laneRecords[0],subagentSessionId=record3.subagentSessionId?.trim();if(!subagentSessionId)return failed(failedLaneValidation("record.subagent_session_id","non-empty child session id",record3.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(record3.createdAt<validatedAtMs)return failed(failedLaneValidation("record.created_at",`at or after ${args2.validatedAt}`,new Date(record3.createdAt).toISOString()).failure);let recordIntegrity=analyzeLaneRecordResultIntegrity({record:record3,result:record3.result,expected:{mode:args2.expectedMode,workflowLane:expectedWorkflowLane,ownedWorkflowLanes:expectedOwnedLanes,prHeadSha:args2.expectedPrHeadSha??record3.workspace?.prHeadSha??"",gitHead:args2.expectedPrHeadSha??record3.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:record3,expectedLane,expectedWorkflowLane,expectedOwnedLanes}})}function recordsPassingBatchIntegrity3(directory,state2,batchId,expectedLanes,expectedMode,validatedAt,checkWorkflowLane=!0,forbiddenSubagentSessionIds=new Set,diagnostics){let batchRead=findByBatchIdDetailed(directory,batchId,{parentSessionId:state2.sessionID});if(batchRead.status==="uncertain")throw Error(`BLOCKED: PR_REVIEW batch integrity cannot be analyzed for ${batchId}: the delegation store is unreadable after ${batchRead.attempts} attempts (${batchRead.reason}); the batch's records are UNKNOWN, not absent. Restore the store and re-validate.`);let records=batchRead.value,analyses=analyzePrReviewBatchRecordIntegrity({batchId,expectedLanes,expectedMode,validatedAt,checkWorkflowLane,forbiddenSubagentSessionIds,records,expectedPrHeadSha:state2.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_CHARS2));return analyses.filter((analysis)=>analysis.ok)}function successfulObligationsFromExactBatch2(directory,state2,batchId,expectedLanes,expectedMode,validatedAt,checkWorkflowLane=!0,forbiddenSubagentSessionIds=new Set,expectedRevisionDigest,diagnostics,reviewerClaims){let successful2=new Set;for(let qualified of recordsPassingBatchIntegrity3(directory,state2,batchId,expectedLanes,expectedMode,validatedAt,checkWorkflowLane,forbiddenSubagentSessionIds,diagnostics)){let structuredCoverage=validateExactStructuredReceiptCoverage2({record:qualified.record,result:qualified.record.result,artifact:null,expected:{mode:expectedMode==="swarm-pr-review:base"||expectedMode==="swarm-pr-review:micro"?expectedMode:"swarm-pr-review:base",workflowLane:qualified.expectedWorkflowLane,ownedWorkflowLanes:qualified.expectedOwnedLanes,prHeadSha:state2.prHeadSha??"",gitHead:state2.prHeadSha??"",revisionDigest:expectedRevisionDigest??"",workflowInstanceId:state2.workflowInstanceId,workflowRevision:qualified.record.workflowGeneration,baseSha:state2.prReviewBaseSha,reviewScope:state2.mode==="PR_REVIEW"&&state2.prReviewBaseSha&&state2.prHeadSha?`complete PR diff ${state2.prReviewBaseSha}...${state2.prHeadSha}`:void 0}});if(structuredCoverage.status==="accepted"){for(let obligation of structuredCoverage.creditedWorkflowLanes)successful2.add(obligation);continue}if(structuredCoverage.status==="rejected"){if(diagnostics&&diagnostics.length<MAX_BASE_COVERAGE_DIAGNOSTICS)diagnostics.push(`batch=${batchId} lane=${qualified.expectedLane.laneId} workflow_lane=${qualified.expectedWorkflowLane}: ${formatPrReviewLaneValidationFailure(structuredCoverage.failure)}`.slice(0,MAX_BASE_COVERAGE_DIAGNOSTIC_CHARS2));continue}if(workflowArtifactHasContractMarker(directory,state2,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 validateExactStructuredReceiptCoverage2(input){if(input.expected.mode!=="swarm-pr-review:base"&&input.expected.mode!=="swarm-pr-review:micro")return{status:"absent"};let rawReceipt=input.result.prReviewResultReceipt;if(!rawReceipt)return{status:"absent"};let parsedReceipt2=PrReviewResultReceiptSchema.safeParse(rawReceipt);if(!parsedReceipt2.success)return{status:"rejected",failure:failedLaneValidation("discovery.coverage","schema-valid exact child/workflow/revision-bound structured receipt","invalid structured receipt").failure};if(input.expected.workflowInstanceId===void 0||input.expected.workflowRevision===void 0||input.expected.baseSha===void 0)return{status:"rejected",failure:failedLaneValidation("discovery.coverage","live workflow instance/revision/base identity","missing live workflow instance/revision/base identity").failure};let receipt=parsedReceipt2.data,recordWorkflowInstanceId=decodePrReviewWorkflowBinding(input.record.jobId),recordWorkflowRevision=input.record.workflowGeneration,ownedWorkflowLanes=input.expected.ownedWorkflowLanes?.length?[...input.expected.ownedWorkflowLanes]:[input.expected.workflowLane];if(!recordWorkflowInstanceId||recordWorkflowRevision===void 0||recordWorkflowInstanceId!==input.expected.workflowInstanceId||recordWorkflowRevision!==input.expected.workflowRevision||receipt.mode!==input.expected.mode||receipt.workflowInstanceId!==recordWorkflowInstanceId||receipt.workflowRevision!==recordWorkflowRevision||receipt.baseSha!==input.expected.baseSha||receipt.batchId!==input.record.batchId||receipt.laneId!==input.record.laneId||receipt.childSessionId!==input.record.subagentSessionId||receipt.workflowLane!==input.expected.workflowLane||!ownedLaneSetsEqual(receipt.ownedWorkflowLanes,ownedWorkflowLanes)||receipt.headSha!==input.expected.prHeadSha||receipt.dispatchRevisionDigest!==input.expected.revisionDigest)return{status:"rejected",failure:failedLaneValidation("discovery.coverage","exact child/workflow/revision-bound structured receipt","mismatched structured receipt").failure};return{status:"accepted",creditedWorkflowLanes:receipt.envelope.creditedLanes.filter((lane)=>ownedWorkflowLanes.includes(lane)),receipt}}function analyzeLaneArtifactIntegrity(args2){let{record:record3,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!==record3.batchId)return failedLaneValidation("artifact.batch_id",record3.batchId??"(missing)",artifact.batchId);if(artifact.laneId!==record3.laneId)return failedLaneValidation("artifact.lane_id",record3.laneId??"(missing)",artifact.laneId);if(artifact.mode!==expected.mode)return failedLaneValidation("artifact.mode",expected.mode,artifact.mode??"(missing)");if(artifact.sessionId!==record3.subagentSessionId)return failedLaneValidation("artifact.session_id",record3.subagentSessionId,artifact.sessionId??"(missing)");if(artifact.parentSessionId!==record3.parentSessionId)return failedLaneValidation("artifact.parent_session_id",record3.parentSessionId,artifact.parentSessionId??"(missing)");if(artifact.agent!==record3.swarmPrefixedAgent)return failedLaneValidation("artifact.agent",record3.swarmPrefixedAgent,artifact.agent);if(artifact.role!==record3.normalizedAgent)return failedLaneValidation("artifact.role",record3.normalizedAgent,artifact.role);if(artifact.source!=="collect_lane_results")return failedLaneValidation("artifact.source","collect_lane_results",artifact.source);if(artifact.workflowLane!==record3.workflowLane)return failedLaneValidation("artifact.workflow_lane_record",record3.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&&record3.workspace?.scope!==expected.reviewScope)return failedLaneValidation("record.scope",expected.reviewScope,record3.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 loadArtifactPassingLaneIntegrity2(directory,state2,record3,expectedMode,expectedWorkflowLane,expectedRevisionDigest,diagnostics){let ref=record3.result?.outputRef?.trim();if(!ref)return null;let artifact=readLaneOutput(directory,ref)?.artifact??null,expectedReviewScope=state2.mode==="PR_REVIEW"&&state2.prReviewBaseSha&&state2.prHeadSha?`complete PR diff ${state2.prReviewBaseSha}...${state2.prHeadSha}`:void 0,integrity=analyzeLaneArtifactIntegrity({record:record3,result:record3.result,artifact,expected:{mode:expectedMode,workflowLane:expectedWorkflowLane,prHeadSha:record3.workspace?.prHeadSha??"",gitHead:record3.workspace?.gitHead??"",revisionDigest:expectedRevisionDigest,reviewScope:expectedReviewScope}});if(!integrity.ok){if(diagnostics&&diagnostics.length<MAX_BASE_COVERAGE_DIAGNOSTICS)diagnostics.push(`batch=${record3.batchId??"(missing)"} lane=${record3.laneId??"(missing)"} workflow_lane=${expectedWorkflowLane} output_ref=${ref}: ${formatPrReviewLaneValidationFailure(integrity.failure)}`.slice(0,MAX_BASE_COVERAGE_DIAGNOSTIC_CHARS2));return null}return artifact}function workflowArtifactHasContractMarker(directory,state2,record3,expectedMode,expectedWorkflowLane,reviewItemIds,expectedRevisionDigest,ownedWorkflowLanes,diagnostics,reviewerClaims){let ref=record3.result?.outputRef?.trim(),artifact=expectedRevisionDigest?loadArtifactPassingLaneIntegrity2(directory,state2,record3,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 analyzeLegacyVerdictRowContract(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)=>legacyArtifactHasExactPositiveVerdictRow(artifact.text,feedbackVerdict[0],itemId,feedbackVerdict[1])));if(expectedMode==="swarm-pr-review:base"||expectedMode==="swarm-pr-review:micro"){let reviewScope=state2.mode==="PR_REVIEW"&&state2.prReviewBaseSha&&state2.prHeadSha?`complete PR diff ${state2.prReviewBaseSha}...${state2.prHeadSha}`:void 0,lastSubmitRejection=latestPrReviewSubmitRejectionMessage(state2,record3.subagentSessionId),validation=validatePrReviewDiscoveryLaneCompletion2({record:record3,result:record3.result,artifact,expected:{mode:expectedMode,workflowLane:expectedWorkflowLane,ownedWorkflowLanes,prHeadSha:state2.prHeadSha??"",gitHead:state2.prHeadSha??"",revisionDigest:expectedRevisionDigest??"",workflowInstanceId:state2.workflowInstanceId,workflowRevision:record3.workflowGeneration,baseSha:state2.prReviewBaseSha,reviewScope},...lastSubmitRejection?{lastSubmitRejection}:{}});if(!validation.ok){if(diagnostics&&diagnostics.length<MAX_BASE_COVERAGE_DIAGNOSTICS)diagnostics.push(`batch=${record3.batchId??"(missing)"} lane=${record3.laneId??"(missing)"} workflow_lane=${expectedWorkflowLane} output_ref=${ref}: ${formatPrReviewLaneValidationFailure(validation.failure)}`.slice(0,MAX_BASE_COVERAGE_DIAGNOSTIC_CHARS2));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=${record3.batchId??"(missing)"} lane=${record3.laneId??"(missing)"} workflow_lane=${coveredLane} output_ref=${ref} digest=${record3.result?.digest??"(missing)"}: ${analysis.issues.join("; ")}`;diagnostics.push(diagnostic.slice(0,MAX_BASE_COVERAGE_DIAGNOSTIC_CHARS2))}}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,acceptPartial=!1){let fallbackFamily=resolvePrReviewRowFamily(expectedWorkflowLane,mode),issues=[],normalized=normalizeCandidateArtifactCached(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:acceptPartial,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 validatePrReviewDiscoveryLaneCompletion2(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 structuredCoverage=validateExactStructuredReceiptCoverage2(input);if(structuredCoverage.status==="accepted")return{ok:!0};if(structuredCoverage.status==="rejected")return{ok:!1,failure:structuredCoverage.failure};if((input.expected.mode==="swarm-pr-review:base"||input.expected.mode==="swarm-pr-review:micro")&&!prReviewLegacyTranscriptCompatibilityEnabled(input.record.prReviewLegacyTranscriptCompatibility))return failedLaneValidation("discovery.coverage","child-bound structured receipt",`missing structured receipt (legacy transcript adapter disabled)${input.lastSubmitRejection?`; last rejected submit_pr_review_result: ${input.lastSubmitRejection.slice(0,300)}`:""}`);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,input.result.transcriptIncomplete===!0)})),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 state2=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?(state2.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(state2.mode!==expectedMode)return{ok:!1,reason:`active workflow mode mismatch; expected ${expectedMode}, got ${state2.mode}`,...rejectedReceipt?{receipt:rejectedReceipt}:{}};let artifactText=input.artifact?.text??"",prReviewGateContext=state2.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=(state2.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"?authoritativeReviewerClaims2(input.directory,state2,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=analyzeLegacyVerdictRowContract(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:[]},recoveries=[...(analysis.recoveries??[]).map(({recovery,itemId})=>({workflowLane,kind:"legacy-verdict-row-recovery",reason:recovery==="legacy-fidelity-safe"?`legacy verdict row ${itemId} used trailing-field pipe recovery with full field fidelity`:`legacy verdict row ${itemId} used trailing-field pipe recovery with lossy prose normalization`})),...input.result.truncated===!0?[{workflowLane,kind:"truncated-preview-durable-artifact",reason:"inline preview truncated; durable artifact retained exact coverage"}]:[]];return recoveries.length>0?{ok:!0,receipt,recoveries}:{ok:!0,receipt}}else if(mode==="swarm-pr-feedback:verification"){let lane=(state2.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||!legacyFeedbackArtifactTextCoversItems(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=(state2.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)=>legacyArtifactHasExactPositiveVerdictRow(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}async function persistState2(directory,state2){let validated=PrWorkflowGateStateSchema.parse(state2);await withSessionStateMutation(directory,validated.sessionID,async()=>{let nextState=await writeStateWhileLocked(directory,validated);Object.assign(state2,nextState)})}function boundSalvagedSchemaError(message){return message.length<=MAX_SALVAGED_SCHEMA_ERROR_CHARS?message:`${message.slice(0,MAX_SALVAGED_SCHEMA_ERROR_CHARS-1)}…`}function boundSalvageDisclosure(sessionID,schemaErrors,coordinationNotice,revisionSalvageable=!0,armedShapeUnreadable=!1,publicationShapeUnreadable=!1){let disclosure=`DEGRADED: PR workflow gate state for session "${sessionID}" `+(coordinationNotice?`${coordinationNotice} and was SALVAGED for recovery only (abort/status; write and completion paths still refuse it). `:"failed schema validation and was SALVAGED for recovery only (abort/status; write and completion paths still refuse it). ")+`Schema errors: ${schemaErrors.join("; ")}.`+(revisionSalvageable?"":" state revision unsalvageable.")+(armedShapeUnreadable?" prFeedbackReadyToPublish is present but unreadable; treated as ARMED (fail-closed).":"")+(publicationShapeUnreadable?" prFeedbackPublication is present but unreadable; treated as ARMED (fail-closed).":""),maxDisclosureChars=MAX_SALVAGED_SCHEMA_ERROR_CHARS*12;return disclosure.length<=maxDisclosureChars?disclosure:`${disclosure.slice(0,maxDisclosureChars-1)}…`}async function readPrWorkflowGateStateForRecovery(directory,sessionID){let normalizedSessionID=normalizeSessionID(sessionID),coordination=readPrWorkflowGateStateCoordinationForRecovery(directory,normalizedSessionID);if(coordination.kind==="invalid")throw Error(`BLOCKED: PR workflow gate state for session "${normalizedSessionID}" is invalid (${coordination.reason})`);if(coordination.kind==="valid")return{state:coordination.state,salvaged:!1,schemaErrors:[],revisionSalvageable:!0,armedShapeUnreadable:!1};let coordinationCorrupt=coordination.kind==="corrupt",coordinationGeneration=coordinationCorrupt?coordination.generation:void 0,coordinationReason=coordinationCorrupt?coordination.reason:void 0,filePath=workflowGateStatePath(directory,normalizedSessionID),raw;try{raw=await fsp8.readFile(filePath,"utf-8")}catch(error93){if(error93.code==="ENOENT")return null;throw error93}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){if(parsed.data.sessionID!==normalizedSessionID||coordinationGeneration!==void 0&&parsed.data.revision!==coordinationGeneration)throw Error(`BLOCKED: PR workflow gate state for session "${normalizedSessionID}" is invalid`);if(!coordinationCorrupt)return{state:parsed.data,salvaged:!1,schemaErrors:[],revisionSalvageable:!0,armedShapeUnreadable:!1};let coordinationSchemaError=boundSalvagedSchemaError(`coordination_state.payload: ${coordinationReason}`);return{state:parsed.data,salvaged:!0,schemaErrors:[coordinationSchemaError],disclosure:boundSalvageDisclosure(normalizedSessionID,[coordinationSchemaError],"coordination authority was corrupt and the valid shadow projection was used"),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||salvagedSessionID.data!==normalizedSessionID)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);if(coordinationGeneration!==void 0&&(!salvagedRevision.success||salvagedRevision.data!==coordinationGeneration))throw invalidError;let armedKeyPresent=rawRecord.prFeedbackReadyToPublish!==void 0,salvagedArmed=PrFeedbackReadyToPublishRecordSchema.safeParse(rawRecord.prFeedbackReadyToPublish),publicationKeyPresent=rawRecord.prFeedbackPublication!==void 0,salvagedPublication=PrFeedbackPublicationStateSchema.safeParse(rawRecord.prFeedbackPublication),publicationShapeUnreadable=publicationKeyPresent&&!salvagedPublication.success,salvagedCheckoutRecovery=PrWorkflowCheckoutRecoveryRecordSchema.safeParse(rawRecord.checkoutRecovery),armedShapeUnreadable=armedKeyPresent&&!salvagedArmed.success||publicationShapeUnreadable,shadowSchemaErrors=parsed.error.issues.slice(0,MAX_SALVAGED_SCHEMA_ERRORS).map((issue3)=>boundSalvagedSchemaError(`${issue3.path.join(".")||"(root)"}: ${issue3.message}`)),schemaErrors=[...coordinationCorrupt?[boundSalvagedSchemaError(`coordination_state.payload: ${coordinationReason}`)]:[],...shadowSchemaErrors].slice(0,MAX_SALVAGED_SCHEMA_ERRORS),disclosure=boundSalvageDisclosure(normalizedSessionID,schemaErrors,coordinationCorrupt?`coordination authority was corrupt (${coordinationReason}) and the shadow projection was used`:void 0,salvagedRevision.success,armedShapeUnreadable,publicationShapeUnreadable);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}:{},...salvagedPublication.success?{prFeedbackPublication:salvagedPublication.data}:{},...salvagedCheckoutRecovery.success?{checkoutRecovery:salvagedCheckoutRecovery.data}:{}},salvaged:!0,schemaErrors,disclosure,revisionSalvageable:salvagedRevision.success,armedShapeUnreadable,prReviewProjectionDropped:!0}}var 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,MAX_PUBLICATION_HISTORY_GENERATIONS=4,MAX_PUBLICATION_ATTEMPTS=8,MAX_PUSH_ATTEMPT_DIAGNOSTIC_CHARS=500,PUBLICATION_SCHEMA_VERSION=1,PUBLICATION_URL_CREDENTIALS_PATTERN,MAX_PR_REVIEW_SUBMIT_REJECTIONS=24,GATE_SCHEMA_VERSION=1,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,MAX_PR_WORKFLOW_GATE_DIRECTORY_ENTRIES,MAX_PR_WORKFLOW_GATE_ENTRY_NAME_CHARS=240,MAX_CANDIDATE_ISSUES_PER_ARTIFACT=8,MAX_BASE_COVERAGE_DIAGNOSTICS=8,MAX_BASE_COVERAGE_DIAGNOSTIC_CHARS2=1000,MAX_LANE_VALIDATION_VALUE_CHARS=240,DISPATCH_TOOL_NAME="dispatch_lanes_async",BLOCKING_DISPATCH_TOOL_NAME="dispatch_lanes",PrReviewBaseDimensionIdSchema,PrReviewBaseDispatchRecordSchema,PrReviewResiliencePolicyRecordSchema,PrReviewResilienceAttemptRecordSchema,PrReviewResilienceStateRecordSchema,PrFeedbackLaneOwnershipSchema,PrFeedbackVerificationRecordSchema,PrFeedbackStageACheckReceiptSchema,PrFeedbackStageARecordSchema,PrFeedbackGateBatchRecordSchema,PrFeedbackReadyToPublishRecordSchema,PrFeedbackPublicationEvidenceJoinSchema,PrFeedbackPublicationGenerationSchema,PrFeedbackPushAttemptSchema,PrFeedbackPublicationStateSchema,PrFeedbackInventoryAmendmentRecordSchema,PrReviewValidationBatchRecordSchema,PrReviewMicroFamilyDispatchRecordSchema,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,LIVE_SESSION_STATUS_TYPES,defaultGetSessionOps=()=>swarmState.opencodeClient?.session??null,PR_WORKFLOW_PROBE_SKIPPED_NO_BUDGET_REASON="probe-skipped-no-budget",laneLivenessWatchdogSurface,PrReviewResilienceCircuitOpenError,PrReviewResilienceRetryExhaustedError,snapshotPrReviewResiliencePolicy,DELEGATION_READ_UNCERTAIN_LOG_LIMIT=64,delegationReadUncertainLogged,MALFORMED_CIRCUIT_DIAGNOSTIC_LIMIT=64,malformedCircuitDiagnosticsSeen,TERMINAL_FAILED_DELEGATION_STATUSES2,MAX_COVER_UNIVERSE_BITS=12,PR_FEEDBACK_PHASE_ORDER,PR_FEEDBACK_PHASE_ROLE,PUBLICATION_IDENTITY_COMPONENTS,PUBLICATION_EVENT_TYPES,PR_REVIEW_HANDOFF_RELATIVE_PATH_PATTERN,PR_REVIEW_FEEDBACK_CONSENT_MAX_BYTES=65536,PR_REVIEW_RUN_RESERVATION_MAX_BYTES=16384,PrReviewFeedbackHandoffArtifactSchema,PrReviewRunReservationSchema,PrReviewFeedbackConsentSchema,MAX_PR_REVIEW_RESERVATION_SCAN_ENTRIES=1024,MAX_PR_REVIEW_RUN_ID_SUFFIX_ATTEMPTS=64,PrReviewFindingProjectionSchema,PrReviewFindingPolicySynthesisFindingSchema,PrReviewCriticSettlementEvidenceSchema,PrReviewFindingPolicySynthesisSchema,_test_exports2,PR_WORKFLOW_SHARED_CONTROLLER_TOOLS,PR_REVIEW_CONTROLLER_TOOLS,PR_FEEDBACK_CONTROLLER_TOOLS,PR_REVIEW_READ_ONLY_TOOL_NAMES,PR_REVIEW_ENUMERATED_READ_METHODS,PR_REVIEW_TOOLS_WITH_ENUMERATED_READ_METHODS,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",PR_REVIEW_STATUS_REASON_MAX_CHARS=240,MAX_UNCLAIMED_ITEMS_IN_MESSAGE=50,FEEDBACK_NO_CHANGE_CLASSIFICATIONS,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_contract();init_pr_review_trigger_contract();init_pr_review_trigger_receipt_reader();init_workspace_snapshot();init_constants();init_schema();init_project_db();init_core_events();init_pr_workflow_state();init_redaction();init_authorization();init_circuit();init_completion();init_finding_policy();init_legacy_transcript_adapter();init_persistence();init_reducer();init_verdict_settlement();init_forge_provider();init_scope_binding();init_pr_workflow_gh_readiness();init_pr_workflow_skill_contract();init_state();init_gh_evidence();init_tool_metadata();init_canonical_root();init_logger();init_timeout();init_lane_liveness_watchdog();init_normalize_tool_name();init_utils2();init_completion();init_persistence();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};PUBLICATION_URL_CREDENTIALS_PATTERN=/\b([a-zA-Z][a-zA-Z0-9+.-]*:\/\/)[^\s/@:]+:[^\s/@]+@/g,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_SESSIONS2*2+1,PrReviewBaseDimensionIdSchema=exports_external.enum(PR_REVIEW_BASE_DIMENSION_IDS),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),circuitOpenDurationMs:exports_external.number().int().min(1000).max(1800000).optional()}).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(),PrReviewResilienceStateRecordSchema=exports_external.object({policy:PrReviewResiliencePolicyRecordSchema,attempts:exports_external.array(PrReviewResilienceAttemptRecordSchema).max(3),circuit:PrReviewCircuitRecordSchema.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(),PrFeedbackPublicationEvidenceJoinSchema=exports_external.object({stageAValidatedAt:exports_external.string().min(1),batches:exports_external.array(exports_external.object({phase:exports_external.enum(["stage-b-reviewer","stage-b-test","closeout-reviewer","closeout-critic"]),batchId:exports_external.string().min(1),laneId:exports_external.string().min(1)}).strict())}).strict(),PrFeedbackPublicationGenerationSchema=exports_external.object({schemaVersion:exports_external.literal(PUBLICATION_SCHEMA_VERSION),generation:exports_external.number().int().positive(),state:exports_external.enum(["reviewing","armed","invalidated","push_in_flight","published","cancelled_without_publication"]),workspaceIdentity:exports_external.string().min(1),sessionID:exports_external.string().min(1),prTargetUrl:exports_external.string().min(1).optional(),intakeHeadSha:exports_external.string().min(1),localHeadRef:exports_external.string().min(1),localHead:exports_external.string().min(1),remoteName:exports_external.string().min(1),remoteUrlIdentity:exports_external.string().min(1).optional(),remoteBranchRef:exports_external.string().startsWith("refs/heads/"),remoteRef:exports_external.string().startsWith("refs/remotes/"),revisionDigest:exports_external.string().min(1),evidence:PrFeedbackPublicationEvidenceJoinSchema,invalidationReason:exports_external.string().min(1).optional(),supersededByGeneration:exports_external.number().int().positive().optional(),createdAt:exports_external.string().min(1),armedAt:exports_external.string().min(1).optional(),invalidatedAt:exports_external.string().min(1).optional(),publishedAt:exports_external.string().min(1).optional(),cancelledAt:exports_external.string().min(1).optional()}).strict(),PrFeedbackPushAttemptSchema=exports_external.object({attemptId:exports_external.string().min(1),generation:exports_external.number().int().positive(),sessionID:exports_external.string().min(1),callID:exports_external.string().min(1).optional(),intentDigest:exports_external.string().regex(/^[0-9a-f]{64}$/),intent:exports_external.object({remote:exports_external.string().min(1),sourceSha:exports_external.string().min(1),destRef:exports_external.string().startsWith("refs/heads/")}).strict(),prePush:exports_external.object({localHead:exports_external.string().min(1),worktreeClean:exports_external.boolean(),remoteName:exports_external.string().min(1),remoteBranchRef:exports_external.string().startsWith("refs/heads/"),observedRemoteHead:exports_external.string().min(1).nullable()}).strict(),startedAt:exports_external.string().min(1),result:exports_external.object({outcome:exports_external.enum(["completed","rejected","uncertain","cancelled"]),exitStatus:exports_external.union([exports_external.number().int(),exports_external.literal("not-observed")]),diagnostic:exports_external.string().max(MAX_PUSH_ATTEMPT_DIAGNOSTIC_CHARS),postPush:exports_external.object({localHead:exports_external.string().min(1).nullable(),observedRemoteHead:exports_external.string().min(1).nullable()}).strict(),completedAt:exports_external.string().min(1)}).strict().optional()}).strict(),PrFeedbackPublicationStateSchema=exports_external.object({schemaVersion:exports_external.literal(PUBLICATION_SCHEMA_VERSION),active:PrFeedbackPublicationGenerationSchema.optional(),history:exports_external.array(PrFeedbackPublicationGenerationSchema).max(MAX_PUBLICATION_HISTORY_GENERATIONS),attempts:exports_external.array(PrFeedbackPushAttemptSchema).max(MAX_PUBLICATION_ATTEMPTS)}).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(),PrReviewMicroFamilyDispatchRecordSchema=exports_external.object({batchId:exports_external.string().min(1),prHeadSha:exports_external.string().min(1),lanes:exports_external.array(exports_external.object({laneId:exports_external.string().min(1),workflowLane:exports_external.string().min(1),ownedWorkflowLanes:exports_external.array(exports_external.string().min(1)).min(1).optional()}).strict()).min(1),admittedAt: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),skillContractAdvisories:exports_external.array(exports_external.string().min(1)).max(MAX_SKILL_CONTRACT_ADVISORIES).optional(),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(),prReviewContractRetryDimensions:exports_external.array(PrReviewBaseDimensionIdSchema).max(PR_REVIEW_BASE_DIMENSION_IDS.length).optional(),prReviewTriggerLedger:exports_external.array(PrReviewInlineTriggerRowSchema).length(PR_REVIEW_REQUIRED_TRIGGER_IDS.length).optional(),prReviewMicroFamilyDispatches:exports_external.array(PrReviewMicroFamilyDispatchRecordSchema).max(MAX_WORKFLOW_BATCHES).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(),prReviewReservedRunId:exports_external.string().min(1).optional(),prReviewArtifactRunId:exports_external.string().min(1).optional(),prReviewFindingsPath:exports_external.string().min(1).optional(),prReviewPartialBaseCoverage:PrReviewPartialBaseCoverageRecordSchema.optional(),prReviewCoverageDisclosurePath:exports_external.string().min(1).max(512).optional(),prReviewCoverageDisclosureDigest:exports_external.string().regex(/^[0-9a-f]{64}$/).optional(),prReviewDimensionCancellations:exports_external.record(exports_external.enum(PR_REVIEW_BASE_DIMENSION_IDS),PrReviewDimensionCancellationRecordSchema).optional(),prReviewSubmitRejections:exports_external.array(exports_external.object({childSessionId:exports_external.string().min(1).max(200),laneId:exports_external.string().min(1).max(200).optional(),at:exports_external.number(),message:exports_external.string().min(1).max(300)}).strict()).max(MAX_PR_REVIEW_SUBMIT_REJECTIONS).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(),prFeedbackPublication:PrFeedbackPublicationStateSchema.optional(),prFeedbackArmedRecovery:exports_external.object({recoveredAt:exports_external.string().datetime(),prHeadSha:exports_external.string().regex(/^[0-9a-f]{6,64}$/i),revisionDigest:exports_external.string().min(1).max(256),generation:exports_external.number().int().nonnegative(),reason:exports_external.string().min(1).max(500)}).strict().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"]);laneLivenessWatchdogSurface={resolveEffectivePrLaneHorizonMs,classifyLaneLivenessCondition,evaluateLaneLivenessWatchdog:evaluateLaneLivenessWatchdogEscalation,readLaneActivity:defaultReadLaneActivity,hostStatusCalls:0,hostAbortCalls:0,evaluations:0};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"}};snapshotPrReviewResiliencePolicy=resolvePrReviewResiliencePolicy;delegationReadUncertainLogged=new Set;malformedCircuitDiagnosticsSeen=new Set;TERMINAL_FAILED_DELEGATION_STATUSES2=CIRCUIT_TERMINAL_DELEGATION_STATUSES;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"};PUBLICATION_IDENTITY_COMPONENTS=["digest","head","worktree","upstream","remote-url","workspace-identity"];PUBLICATION_EVENT_TYPES=new Set(["pr_feedback_publication_armed","pr_feedback_publication_migrated","pr_feedback_push_attempt_started","pr_feedback_publication_invalidated","pr_feedback_published","pr_feedback_publication_cancelled"]);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(),PrReviewRunReservationSchema=exports_external.object({schema_version:exports_external.literal(1),session_id:exports_external.string().min(1),workflow_instance_id:exports_external.string().min(1),run_id:exports_external.string().min(1).max(128),reserved_at:exports_external.string().datetime()}).strict(),PrReviewFeedbackConsentSchema=exports_external.object({schema_version:exports_external.literal(1),state:exports_external.enum(["offered","confirmed"]),session_id:exports_external.string().min(1),source_workflow_instance_id:exports_external.string().min(1),run_id:exports_external.string().min(1).max(128),handoff_path:exports_external.string().min(1).max(512),handoff_digest:exports_external.string().regex(/^[a-f0-9]{64}$/),pr_url:exports_external.string().url().max(2000),pr_head_sha:exports_external.string().regex(/^[0-9a-f]{6,64}$/i),finding_ids_digest:exports_external.string().regex(/^[a-f0-9]{64}$/),confirmation_command:exports_external.string().min(1).max(4000),offered_at:exports_external.string().datetime(),confirmed_at:exports_external.string().datetime().optional()}).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(),PrReviewFindingPolicySynthesisFindingSchema=exports_external.object({id:exports_external.string().min(1).max(128),status:exports_external.string().min(1),severity:exports_external.string().min(1),action:exports_external.string().min(1)}).passthrough(),PrReviewCriticSettlementEvidenceSchema=exports_external.object({findingId:exports_external.string().min(1).max(128),terminal:exports_external.boolean(),status:exports_external.enum(["UPHELD","DOWNGRADED","DISPROVED","NEEDS_MORE_EVIDENCE","CRITIC_UNAVAILABLE"])}).passthrough(),PrReviewFindingPolicySynthesisSchema=exports_external.object({findings:exports_external.array(PrReviewFindingPolicySynthesisFindingSchema),criticSettlements:exports_external.array(PrReviewCriticSettlementEvidenceSchema).optional()});bindPrReviewReentryBindingReader(readPrReviewReentryBindingContext);_test_exports2={resolveGhBinary,parseGateState:(data)=>PrWorkflowGateStateSchema.safeParse(data),classifyPrReviewCircuitSignal,minimumConsolidatedLaneCover,analyzePrReviewBatchRecordIntegrity,workflowArtifactHasContractMarker,MAX_COVER_UNIVERSE_BITS,extractCandidateIds,parseCanonicalCandidateRows,resolvePrReviewRowFamily,boundPublicationDiagnostic,workflowGateStateRelativePath,workflowGateStateLockRelativePath,workflowCheckoutMutationLockRelativePath,withPrWorkflowCheckoutMutationLock,resetTrackedStateCache:()=>{resetPrReviewPersistenceCaches(),malformedCircuitDiagnosticsSeen.clear(),delegationReadUncertainLogged.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.beforePrReviewReentryReservation=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=defaultPersistenceHooks.openCheckoutLock,_test_exports2.removeCheckoutLock=defaultPersistenceHooks.removeCheckoutLock,_test_exports2.checkoutMutationActionTimeoutMs=CHECKOUT_MUTATION_ACTION_TIMEOUT_MS,_test_exports2.classifyPrWorkflowGitStateAsync=classifyPrWorkflowGitState,_test_exports2.sweepStaleDelegationsAsync=sweepStaleDelegations,_test_exports2.probeLaneLivenessAsync=probeAlivePrWorkflowLaneSessions,_test_exports2.probeLaneSessionStatusTypesAsync=probePrWorkflowLaneSessionStatusTypes,laneLivenessWatchdogSurface.hostStatusCalls=0,laneLivenessWatchdogSurface.hostAbortCalls=0,laneLivenessWatchdogSurface.evaluations=0,laneLivenessWatchdogSurface.readLaneActivity=defaultReadLaneActivity,_test_exports2.getSessionOps=defaultGetSessionOps,_test_exports2.laneLivenessProbeTimeoutMs=PR_WORKFLOW_LANE_LIVENESS_PROBE_TIMEOUT_MS,_test_exports2.pendingLaneLivenessThresholdMs=PR_WORKFLOW_PENDING_LIVENESS_THRESHOLD_MS,closeAllProjectDbs()},beforeTerminalClear:void 0,beforeAbortClear:void 0,beforePrFeedbackTransitionLock:void 0,beforePrFeedbackTrackingSwitch:void 0,afterPrFeedbackTrackingSwitch:void 0,beforePrFeedbackTrackingPersist:void 0,beforePrReviewReentryReservation:void 0,beforeBoundedSwarmFileOpen:void 0,beforeSessionStateLockWrite:void 0,beforeCheckoutLockWrite:void 0,beforeSafeDirectoryCreate:void 0,beforeAtomicTempWrite:void 0,beforeAtomicRename:void 0,openCheckoutLock:defaultPersistenceHooks.openCheckoutLock,removeCheckoutLock:defaultPersistenceHooks.removeCheckoutLock,checkoutMutationActionTimeoutMs:CHECKOUT_MUTATION_ACTION_TIMEOUT_MS,classifyPrWorkflowGitStateAsync:classifyPrWorkflowGitState,sweepStaleDelegationsAsync:sweepStaleDelegations,probeLaneLivenessAsync:probeAlivePrWorkflowLaneSessions,probeLaneSessionStatusTypesAsync:probePrWorkflowLaneSessionStatusTypes,laneLivenessWatchdog:laneLivenessWatchdogSurface,getSessionOps:defaultGetSessionOps,laneLivenessProbeTimeoutMs:PR_WORKFLOW_LANE_LIVENESS_PROBE_TIMEOUT_MS,pendingLaneLivenessThresholdMs:PR_WORKFLOW_PENDING_LIVENESS_THRESHOLD_MS,effectivePrReviewResiliencePolicy,snapshotPrReviewResiliencePolicy,resolveCurrentGitHead,resolveCurrentGitHeadAsync,resolveCurrentUpstreamPushTarget,resolveCurrentUpstreamPushTargetAsync,resolveCurrentUpstreamRemoteRef,resolveCurrentLocalHeadRefAsync,resolveRemoteUrlIdentity,resolveRemoteUrlIdentityAsync,parseExactBoundPushIntent,admitPrFeedbackPushAttempt,recordPrFeedbackPushAttemptResult,reconcileForeignInFlightAttempt,ensurePublicationGenerationCurrent,invalidatePublicationGeneration,invalidatePrFeedbackPublication,cancelPrFeedbackPublication,buildPublicationEvidenceJoin,nextPublicationContainer,supersedeLivePublicationInPendingState,describePrWorkflowPublicationSection,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,composePrReviewPhaseVerdicts:async(directory,sessionID,phase)=>{let state2=await requireBoundState2(directory,sessionID,"PR_REVIEW"),ctx=await createPrReviewGateContext2(directory,state2);return composePrReviewPhaseVerdicts(directory,state2,phase,ctx)},assertSettledPhaseHasAuthoritativeVerdicts,derivePrReviewCriticInventoryForCoverageGate:async(directory,sessionID,origin="_test_exports")=>{let state2=await requireBoundState2(directory,sessionID,"PR_REVIEW"),ctx=await createPrReviewGateContext2(directory,state2);return derivePrReviewCriticInventoryForCoverageGate(directory,state2,ctx,origin)},derivePrReviewCandidateInventory:async(directory,sessionID)=>{let state2=await requireBoundState2(directory,sessionID,"PR_REVIEW"),ctx=await createPrReviewGateContext2(directory,state2);return derivePrReviewCandidateInventory2(directory,state2,ctx)},isProcessAlive:defaultPersistenceHooks.isProcessAlive,isSafeStandaloneGitCommit,rename:fsp8.rename,nowMs:()=>Date.now()};Object.assign(_test_exports2,legacyTranscriptAdapterTestSurface);bindPrReviewPersistenceHooks(_test_exports2);bindPrReviewStateCodec({safeParse:(data)=>PrWorkflowGateStateSchema.safeParse(data),parse:(data)=>PrWorkflowGateStateSchema.parse(data)});bindPrReviewCompletionHelpers({createPrReviewGateContext:createPrReviewGateContext2,requireBoundState:requireBoundState2,readPrWorkflowGateStateFromDisk:readPrWorkflowGateStateFromDisk3,readBoundedSwarmRegularFile:readBoundedSwarmRegularFile2,successfulObligationsFromExactBatch:successfulObligationsFromExactBatch2,recordsPassingBatchIntegrity:recordsPassingBatchIntegrity3,validatePrReviewDiscoveryLaneCompletion:validatePrReviewDiscoveryLaneCompletion2,validateExactStructuredReceiptCoverage:validateExactStructuredReceiptCoverage2});bindPrReviewTranscriptAdapterHelpers({derivePrReviewCandidateInventory:derivePrReviewCandidateInventory2,derivePrReviewCriticInventory:derivePrReviewCriticInventory2,authoritativeReviewerClaims:authoritativeReviewerClaims2,reviewerSubagentSessionIds:reviewerSubagentSessionIds2,prReviewPhaseWindow:prReviewPhaseWindow2,batchMayContributeClaims:batchMayContributeClaims2,recordsPassingBatchIntegrity:recordsPassingBatchIntegrity3,loadArtifactPassingLaneIntegrity:loadArtifactPassingLaneIntegrity2});PR_WORKFLOW_SHARED_CONTROLLER_TOOLS=new Set(["abort_pr_workflow","cancel_lane_batch","collect_lane_results","complete_pr_workflow","dispatch_lanes_async","prepare_pr_workflow_checkout"]),PR_REVIEW_CONTROLLER_TOOLS=new Set(["authorize_pr_review_reentry","parse_lane_candidates","write_pr_review_artifact","write_pr_review_trigger_eval"]),PR_FEEDBACK_CONTROLLER_TOOLS=new Set(["invalidate_pr_feedback_publication","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_REVIEW_ENUMERATED_READ_METHODS=new Set(["get","get_diff","get_status","get_files","get_commits","get_review_comments","get_reviews","get_comments","get_check_runs"]),PR_REVIEW_TOOLS_WITH_ENUMERATED_READ_METHODS=new Set(["github_pull_request_read","mcp__github__pull_request_read"]);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 /;FEEDBACK_NO_CHANGE_CLASSIFICATIONS=new Set(["DISPROVED","PRE_EXISTING","NEEDS_MORE_EVIDENCE","NEEDS_USER_DECISION"])});import*as child_process5 from"node:child_process";function sanitizeUrl(raw){let urlStr=raw.trim();urlStr=urlStr.replace(/^([A-Za-z][A-Za-z0-9+.-]*:\/\/)\/?[^@/]+@/,"$1"),urlStr=urlStr.replace(/\[\s*MODE\s*:[^\]]*\]/gi,""),urlStr=urlStr.replace(/^([A-Za-z][A-Za-z0-9+.-]*:\/\/)\/?[^@/]+@/,"$1");let fragmentIdx=urlStr.indexOf("#");if(fragmentIdx!==-1)urlStr=urlStr.slice(0,fragmentIdx);let queryIdx=urlStr.indexOf("?");if(queryIdx!==-1)urlStr=urlStr.slice(0,queryIdx);if(urlStr.length>MAX_URL_LEN)urlStr=urlStr.slice(0,MAX_URL_LEN);return urlStr.trim()}function sanitizeErrorEcho(raw,maxLength=80){let stripped="";for(let ch of raw){let cp2=ch.codePointAt(0);if(cp2!==void 0&&(cp2<=31||cp2===127)){stripped+=" ";continue}stripped+=ch}let collapsed=stripped.replace(/\s+/g," ").trim();if(collapsed.length<=maxLength)return collapsed;return`${collapsed.slice(0,maxLength)}…`}function validateAndSanitizeGithubUrl(rawUrl,resource,configured){let sanitized=sanitizeUrl(rawUrl);if(!sanitized)return{error:"Empty URL"};if(!sanitized.startsWith("https://"))return{error:"URL must use HTTPS scheme"};try{let url3=new URL(sanitized);if(hasNonAsciiHostname(url3.hostname))return{error:"Non-ASCII hostnames are not allowed"};if(isPrivateHost(url3))return{error:"Private or localhost URLs are not allowed"};if(!matchForgeResourceUrl(sanitized,resource,configured))return{error:resource==="issues"?"URL must be a GitHub issue URL (https://github.com/owner/repo/issues/N) or a GitLab issue URL (https://<gitlab-host>/owner/repo/-/issues/N)":"URL must be a GitHub pull request URL (https://github.com/owner/repo/pull/N) or a GitLab merge request URL (https://<gitlab-host>/owner/repo/-/merge_requests/N)"};return{sanitized}}catch{return{error:"Invalid URL format"}}}function detectGitRemote(cwd,laneEnv){try{let result=_internals111.spawnSync(resolveGitExecutable(),["remote","get-url","origin"],{encoding:"utf-8",stdio:["ignore","pipe","pipe"],timeout:5000,...cwd?{cwd}:{},envOverrides:laneEnv});if(result.status!==0||result.error)return null;return(result.stdout??"").trim()||null}catch{return null}}function parseGitRemoteUrl(remoteUrl){let httpsMatch=remoteUrl.match(/^https:\/\/github\.com\/([^/]+)\/([^/]+?)(?:\.git)?\/?$/i);if(httpsMatch){let owner=httpsMatch[1],repo=httpsMatch[2].replace(/\.git$/,"");if(containsControlCharacters(owner)||containsControlCharacters(repo))return null;return{owner,repo}}let sshMatch=remoteUrl.match(/^git@github\.com:([^/]+)\/([^/]+?)(?:\.git)?$/i);if(sshMatch){let owner=sshMatch[1],repo=sshMatch[2].replace(/\.git$/,"");if(containsControlCharacters(owner)||containsControlCharacters(repo))return null;return{owner,repo}}let pathMatch=remoteUrl.match(/\/([^/]+)\/([^/]+?)(?:\.git)?\/?$/);if(pathMatch){let owner=pathMatch[1],repo=pathMatch[2].replace(/\.git$/,"");if(containsControlCharacters(owner)||containsControlCharacters(repo))return null;return{owner,repo}}return null}var MAX_URL_LEN=2048,_internals111;var init_url_security=__esm(()=>{init_forge_provider();init_host_guards();init_bun_compat();init_git_executable();_internals111={spawnSync:(cmd,args2,options)=>{let mergedEnv=mergeEnvForChild(options?.env,options?.envOverrides);return child_process5.spawnSync(cmd,args2,{...options,env:mergedEnv})}}});async function handleAbortPrWorkflowCommand(directory,args2,sessionID){let tokens2=(args2??[]).filter((token)=>token.trim().length>0),modeToken=tokens2[0]?.toUpperCase(),knownMode=modeToken&&KNOWN_MODES.has(modeToken)?modeToken:void 0,cancellationRequested=tokens2.includes(CANCEL_PUBLICATION_FLAG),reasonStartIndex=knownMode?1:0;if(modeToken&&!knownMode)return`Error: Unknown mode "${modeToken}". Expected PR_REVIEW or PR_FEEDBACK.
|
|
1296
1296
|
|
|
1297
1297
|
${USAGE2}`;if(cancellationRequested&&(knownMode!=="PR_FEEDBACK"||tokens2[1]!==CANCEL_PUBLICATION_FLAG))return`Error: ${CANCEL_PUBLICATION_FLAG} requires the exact form PR_FEEDBACK ${CANCEL_PUBLICATION_FLAG} <reason...>. It is not valid for PR_REVIEW or an unqualified force abort.
|
|
1298
1298
|
|
|
@@ -2715,7 +2715,7 @@ Preserved in place (${result2.preserved.length}):
|
|
|
2715
2715
|
|
|
2716
2716
|
`,output+=`${formatResidueInventoryLines(inventory).join(`
|
|
2717
2717
|
`)}
|
|
2718
|
-
`,output+="\nPreview only. Run `/swarm config doctor --quarantine-residue` to quarantine eligible items (recoverable), or `--rollback-residue-quarantine` to restore a batch.\n"}catch{}return output}async function handleDoctorToolsCommand(directory,_args){let result=runToolDoctor(directory);return formatToolDoctorMarkdown(result)}var init_doctor=__esm(()=>{init_loader();init_config_doctor();init_swarm_residue();init_tool_doctor();init_state()});import*as fs107 from"node:fs";import*as path194 from"node:path";function archiveWithoutOverwrite(filePath){let canonical=`${filePath}.imported`;if(!fs107.existsSync(canonical))return fs107.renameSync(filePath,canonical),canonical;for(let suffix=1;suffix<=MAX_ARCHIVE_SUFFIX;suffix+=1){let candidate=`${canonical}.${suffix}`;if(fs107.existsSync(candidate))continue;return fs107.renameSync(filePath,candidate),candidate}throw Error("legacy Epic state archive collision limit exceeded")}function countActiveInLegacyFile(filePath){let stat17=fs107.statSync(filePath);if(!stat17.isFile()||stat17.size>MAX_LEGACY_FILE_BYTES)return 0;let parsed=JSON.parse(fs107.readFileSync(filePath,"utf-8"));return Object.values(parsed.sessions??{}).filter((session)=>session?.active===!0).length}function retireLegacyEpicSessionState(directory){let result={rowsRemoved:0,activeSessions:0,fileArchivedTo:null,errors:[]},activeIds=new Set;if(projectDbExists(directory))try{let rows=listCoordinationStates(directory,LEGACY_EPIC_SESSION_NAMESPACE);for(let row of rows){if(row.status==="active")activeIds.add(row.entityKey);if(deleteCoordinationState(directory,LEGACY_EPIC_SESSION_NAMESPACE,row.entityKey,row.revision))result.rowsRemoved+=1}}catch(error93){result.errors.push(`legacy Epic session rows: ${error93 instanceof Error?error93.message:String(error93)}`)}let filePath=path194.join(directory,".swarm",LEGACY_STATE_FILE);if(fs107.existsSync(filePath)){let fileActive=0;try{fileActive=countActiveInLegacyFile(filePath)}catch{fileActive=0}try{result.fileArchivedTo=path194.relative(directory,archiveWithoutOverwrite(filePath))}catch(error93){result.errors.push(`.swarm/${LEGACY_STATE_FILE}: ${error93 instanceof Error?error93.message:String(error93)}`)}result.activeSessions=Math.max(activeIds.size,fileActive)}else result.activeSessions=activeIds.size;return result}function describeLegacyEpicMigration(result){if(result.rowsRemoved===0&&result.fileArchivedTo===null&&result.errors.length===0)return[];let lines=["","### Legacy Epic v1 state"];if(result.rowsRemoved>0||result.fileArchivedTo!==null)lines.push(`Retired Epic v1 per-session state (${result.rowsRemoved} row(s)${result.fileArchivedTo?`; projection archived to \`${result.fileArchivedTo}\``:""}). Epic v1 \`/swarm epic on|off\` no longer exists — epics are plan-scoped.`);if(result.activeSessions>0)lines.push(`${result.activeSessions} session(s) had Epic v1 switched on. Nothing was opened automatically: run \`/swarm epic start\` to open an epic for the current plan.`);for(let error93 of result.errors)lines.push(`⚠️ Could not retire ${error93}`);return lines}var LEGACY_EPIC_SESSION_NAMESPACE="turbo.epic.session",LEGACY_STATE_FILE="epic-state.json",MAX_LEGACY_FILE_BYTES=4194304,MAX_ARCHIVE_SUFFIX=1000;var init_legacy_migration=__esm(()=>{init_coordination_store();init_project_db()});import*as fs108 from"node:fs";import*as path195 from"node:path";function listEpicPriorReports(directory){let dir=path195.join(directory,EPIC_PRIOR_REPORTS_RELATIVE_DIR),names;try{names=fs108.readdirSync(dir).filter((name)=>EPIC_REPORT_NAME_RE.test(name))}catch{return[]}return names.map((name)=>{try{return{name,mtime:fs108.statSync(path195.join(dir,name)).mtimeMs}}catch{return{name,mtime:0}}}).sort((a,b)=>b.mtime-a.mtime||b.name.localeCompare(a.name)).map((entry)=>entry.name)}function scorecardFromReport(raw){if(typeof raw!=="object"||raw===null||Array.isArray(raw))return{error:"not a JSON object"};let schema=raw.schema;if(schema!==EPIC_REPORT_SCHEMA)return{error:`unknown report schema ${JSON.stringify(schema)}`};let card=raw.scorecard,parsed=EpicScorecardSchema.safeParse(card);if(!parsed.success){let issue3=parsed.error.issues[0];return{error:`invalid ${["scorecard",...(issue3?.path??[]).map(String)].join(".")}: ${issue3?.message??"malformed scorecard"}`}}return{scorecard:card}}function readReport(directory,name){let file3=path195.join(directory,EPIC_PRIOR_REPORTS_RELATIVE_DIR,name),reportKey=name.replace(/\.json$/,""),raw;try{if(fs108.statSync(file3).size>MAX_EPIC_REPORT_BYTES)return{status:"error",message:`Report \`${reportKey}\` is larger than ${MAX_EPIC_REPORT_BYTES} bytes and was not read.`};raw=JSON.parse(fs108.readFileSync(file3,"utf-8"))}catch(error93){return{status:"error",message:`Report \`${reportKey}\` could not be read (${error93 instanceof Error?error93.message:String(error93)}).`}}let scored=scorecardFromReport(raw);if("error"in scored)return{status:"error",message:`Report \`${reportKey}\` is unreadable: ${scored.error}.`};return{status:"ok",source:"report",reportKey,scorecard:scored.scorecard}}async function liveEpicScorecard(directory,epic,learning){let plan=null;try{plan=await _internals162.loadPlanJsonOnly(directory)}catch{plan=null}let adoptedAtStart;if(plan)try{adoptedAtStart=(await _internals162.completedBeforeEpic(directory,epic,plan)).size}catch{adoptedAtStart=void 0}let view=_internals162.loadEpicLearningView(directory,epic,learning,_internals162.now());return computeEpicScorecard({record:epic,outcome:"open",closedAt:null,planTaskTotal:plan?summarizePlanTasks(plan).total:null,adoptedAtStart,hotFiles:epicHotFiles(view.stats,learning.hotExcess)})}async function selectEpicReport(directory,selector,learning){if(selector===null){let live=await liveSelection(directory,learning);if(live)return live}let names=listEpicPriorReports(directory);if(selector===null||selector.toLowerCase()==="last"){if(names.length===0)return{status:"none",message:selector===null?"No epic is open and no past epic report exists (`.swarm/epic-prior/reports/` is empty).":"No past epic report exists (`.swarm/epic-prior/reports/` is empty)."};return readReport(directory,names[0])}if(!SELECTOR_RE.test(selector))return{status:"error",message:`\`${selector}\` is not a report or epic key (letters, digits, \`-\` and \`_\` only).`};let exact=names.find((name)=>name===`${selector}.json`),byEpic=names.find((name)=>name.startsWith(`${selector}-`)&&EPIC_REPORT_NAME_RE.test(name)&&/^\d{8}T\d{6}Z\.json$/.test(name.slice(selector.length+1))),chosen=exact??byEpic;if(!chosen){let stillOpen=safeOpenKey(directory)===selector?` — epic \`${selector}\` is still open; run \`/swarm epic report\` for its live scorecard`:"";return{status:"none",message:`No report for \`${selector}\` in \`.swarm/epic-prior/reports/\`${stillOpen}.`}}return readReport(directory,chosen)}async function liveSelection(directory,learning){if(!_internals162.epicSentinelExists(directory))return null;let inspection;try{inspection=_internals162.inspectEpic(directory)}catch(error93){inspection={unreadable:error93 instanceof Error?error93.message:String(error93)}}if(inspection.unreadable)return{status:"error",message:`The epic's lifecycle state is unreadable (${inspection.unreadable}); run \`/swarm epic status\`.`};let record3=inspection.record;if(!record3)return null;let notes=[];if(inspection.orphanReason)notes.push(`The epic no longer matches the current plan (${inspection.orphanReason}); close it with \`/swarm epic close --abandon\`.`);if(!inspection.configEnabled)notes.push("Epic Mode is disabled by config (`epic.mode.enabled`), so no Epic behaviour runs for this epic until it is re-enabled or closed.");return{status:"ok",source:"live",reportKey:null,scorecard:await liveEpicScorecard(directory,record3,learning),notes}}function safeOpenKey(directory){if(!_internals162.epicSentinelExists(directory))return null;try{return _internals162.inspectEpic(directory).record?.epicKey??null}catch{return null}}var MAX_EPIC_REPORT_BYTES=4194304,SELECTOR_RE,_internals162,num,count3,rate2,EpicScorecardSchema;var init_report3=__esm(()=>{init_zod();init_manager();init_close();init_learning();init_learning_store();init_lifecycle();init_next_wave();init_scorecard();SELECTOR_RE=/^[A-Za-z0-9_-]{1,200}$/,_internals162={epicSentinelExists,inspectEpic,loadPlanJsonOnly,completedBeforeEpic,loadEpicLearningView,now:()=>Date.now()};num=exports_external.number().finite(),count3=num.min(0),rate2=exports_external.object({passed:count3,of:count3,rate:num.min(0).max(1).nullable()}),EpicScorecardSchema=exports_external.object({schema:exports_external.literal(EPIC_SCORECARD_SCHEMA),epicKey:exports_external.string().min(1),planId:exports_external.string(),outcome:exports_external.enum(["open","completed","abandoned","abandoned-by-swarm-close"]),startedAt:exports_external.string(),closedAt:exports_external.string().nullable(),forced:exports_external.boolean(),sizingAtStart:exports_external.object({epicSized:exports_external.boolean(),reasons:exports_external.array(exports_external.string()),pendingTasks:count3,scopedTasks:count3,scopeCoverage:num,serialSteps:count3,concurrency:num,effectiveSpeedup:num}),tasks:exports_external.object({total:count3.nullable(),completedInEpic:count3,adoptedAtStart:count3.optional(),exclusive:count3,serialComponent:count3}),waves:exports_external.object({count:count3,parallel:count3,meanWidth:count3,maxWidth:count3}),time:exports_external.object({method:exports_external.literal("wave-span-v1"),label:exports_external.string(),spanMs:count3,workMs:count3,concurrencyFactor:count3.nullable(),interWaveIdleMs:count3}),conflicts:exports_external.object({mergeFailures:count3,undeclaredWriteTasks:count3,undeclaredFiles:exports_external.array(exports_external.string()),undeclaredFilesTotal:count3}),rework:exports_external.object({tasksWithRework:count3,extraGenerations:count3,reopened:count3}),gates:exports_external.object({stageAFirstPass:rate2,stageBFirstPass:rate2,phaseReviewFirstPass:rate2,boundedHistory:exports_external.literal(!0)}),learning:exports_external.object({priorDigest:exports_external.string().nullable(),topHotFiles:exports_external.array(exports_external.string())})})});import{randomUUID as randomUUID30}from"node:crypto";import*as fs109 from"node:fs";import*as path196 from"node:path";function refused2(reason,details,sizing){return{status:"refused",reason,details,sizing}}function errorText7(error93){return error93 instanceof Error?error93.message:String(error93)}function findRunningLeanRun(directory){if(projectDbExists(directory)){let rows=listCoordinationStates(directory,LEAN_SESSION_NAMESPACE),running=rows.find((row)=>row.status==="running");if(running)return`durable Lean Turbo run for session ${running.entityKey}`;if(rows.length>0)return null}let legacyPath=path196.join(directory,".swarm",LEGACY_LEAN_STATE_FILE);try{let stat17=fs109.statSync(legacyPath);if(!stat17.isFile()||stat17.size>MAX_LEGACY_LEAN_STATE_BYTES)return null;let parsed=JSON.parse(fs109.readFileSync(legacyPath,"utf-8"));for(let[sessionID,state2]of Object.entries(parsed.sessions??{}))if(state2?.status==="running")return`durable Lean Turbo run for session ${sessionID} (.swarm/${LEGACY_LEAN_STATE_FILE})`}catch{}return null}function findTurboActivity(directory,config3){let reasons=[];if(config3.turbo_mode===!0)reasons.push("config `turbo_mode: true` seeds Turbo into every new session — set it to false");if(_internals163.hasActiveTurboMode())reasons.push("a session in this process has Turbo on — run `/swarm turbo off` in it");let lean=_internals163.findRunningLeanRun(directory);if(lean)reasons.push(`${lean} — finish it or run \`/swarm turbo off\``);return reasons}function findDirtyBaseline(directory){return listDirtyPathsOutsideSwarm(directory,_internals163.gitExec)}async function findInFlightCoderWork(directory){let found=[],dispatches=_internals163.countTrackedWorktreeDispatches();if(dispatches>0)found.push(`${dispatches} worktree-isolated coder dispatch(es) running or awaiting merge-back — let them finish (\`/swarm lanes\` shows them)`);if(projectDbExists(directory)){let open7=listCoordinationStates(directory,BACKGROUND_DELEGATION_NAMESPACE).filter((row)=>!isTerminalDelegationStatus(row.status));if(open7.length>0)found.push(`${open7.length} non-terminal background delegation(s) — let them finish`)}else{let outcome=_internals163.readDelegationsDetailed(directory);if(outcome.status!=="ok")found.push("background delegation state is uncertain — cannot prove no coder is running");else{let open7=outcome.records.filter((record3)=>!isTerminalDelegationStatus(record3.status));if(open7.length>0)found.push(`${open7.length} non-terminal background delegation(s) — let them finish`)}}let wal=await _internals163.listCoderSettlementWalStates(directory),unsettled=wal.states.filter((state2)=>UNSETTLED_WAL_STATES2.has(state2.state)),live=unsettled.filter((state2)=>state2.state!=="unreadable"&&(state2.ownedInProcess||state2.ownedByLiveForeignPid)),stale=unsettled.filter((state2)=>!live.includes(state2)),describe3=(states)=>states.slice(0,5).map((state2)=>`${state2.taskId} (${state2.state})`).join(", ");if(live.length>0)found.push(`${live.length} coder settlement(s) still owned by a running dispatch: ${describe3(live)} — let them finish`);if(stale.length>0)found.push(`${stale.length} stale or unreadable coder settlement(s): ${describe3(stale)} — run \`/swarm recover <taskId>\` for each (it settles WALs whose owner process is gone)`);if(wal.truncated)found.push("coder settlement directory exceeds the scan bound — cannot prove every settlement is final; run `/swarm recover` to settle stale WALs");let recovery=_internals163.listRecoveryRecords(directory);if(recovery.length>0)found.push(`${recovery.length} preserved Lean recovery lane(s) in .swarm/recovery/ — finish them with Lean Turbo (\`/swarm turbo lean on\`, then \`/swarm turbo off\`) or discard those lanes`);else if(_internals163.recoveryReadErrored(directory))found.push("Lean recovery records in .swarm/recovery/ are unreadable — inspect and repair or remove them");let authorities=_internals163.scanWorktreeRecoveryAuthoritiesForRecovery(directory);if(authorities.status==="ok"){let liveLanes=authorities.authorities.filter((authority)=>authority.status==="preserved"||authority.status==="claimed");if(liveLanes.length>0)found.push(`${liveLanes.length} preserved/claimed worktree recovery lane(s) — inspect with \`/swarm lanes\`; merge or discard them (\`/swarm reset-session\` can purge dirty lanes)`)}else found.push(`worktree recovery state is ${authorities.status} — inspect .swarm/worktree-merge-recovery-v2.json`);let owners=_internals163.scanWorktreeProvisioningOwnersForRecovery(directory);if(owners.status==="ok"){if(owners.owners.length>0)found.push(`${owners.owners.length} worktree lane(s) being provisioned — let the dispatch finish (\`/swarm lanes\`)`)}else found.push(`worktree provisioning state is uncertain (${owners.reason})`);return found}function isPending(status2){return isEpicPendingStatus(status2)}function sizeStartPlan(directory,plan,config3,maxParallel,signals){let estimate=estimatePlanScopes(directory,plan),context=epicSizingContextFor(directory,config3,maxParallel,signals);return{plan:sizeEpicPlan(context,plan.phases,estimate,MAX_START_SIZING_WORK),estimate,context}}function estimatePlanScopes(directory,plan){let pendingIds=[];for(let phase of plan.phases)for(let task of phase.tasks??[])if(isPending(task.status))pendingIds.push(task.id);return estimateEpicScopes(plan.phases,_internals163.resolveEpicDeclaredScopes(directory,plan,pendingIds))}function shapeRefusedPlan(directory,plan,sizing){try{return _internals163.shapeEpicPlan({...sizing.context,phases:plan.phases,declared:Object.fromEntries(sizing.estimate.pendingIds.map((id)=>[id,sizing.estimate.scopes[id]])),baseline:sizing.plan,isDirectory:(entry)=>isDirectoryOnDisk(directory,entry)})}catch(error93){warn(`[epic/start] plan shaping failed (the refusal carries no suggestions): ${errorText7(error93)}`);return}}function initialEpicPhases(plan){let phases={};for(let phase of plan.phases){let tasks=phase.tasks??[];if(phase.status==="closed"||tasks.length>0&&tasks.every((task)=>!isPending(task.status)))phases[String(phase.id)]={status:"complete",completeAtStart:!0,reviewRuns:0,verdicts:[]}}return phases}function readGitFacts(directory){if(!_internals163.getGitRepositoryStatus(directory).isRepo)return{isRepo:!1,baseCommit:null,originalBranch:null,epicBranch:null};let baseCommit=null,originalBranch=null;try{baseCommit=_internals163.gitExec(["rev-parse","HEAD"],directory).trim()}catch{baseCommit=null}try{originalBranch=_internals163.gitExec(["rev-parse","--abbrev-ref","HEAD"],directory).trim()}catch{originalBranch=null}if(originalBranch==="HEAD"||originalBranch==="")originalBranch=null;return{isRepo:!0,baseCommit,originalBranch,epicBranch:null}}async function startEpic(options){let{directory,sessionID,force}=options,config3;try{config3=_internals163.loadPluginConfigWithMeta(directory).config}catch{return refused2("epic-disabled-by-config",[EPIC_MODE_CONFIG_DISABLED_MESSAGE])}if(!isEpicModeConfigEnabled(config3))return refused2("epic-disabled-by-config",[EPIC_MODE_CONFIG_DISABLED_MESSAGE]);if(!_internals163.hostProvidesClient())return refused2("host-unsupported",[EPIC_HOST_UNSUPPORTED_MESSAGE]);let plan;try{plan=await _internals163.loadPlanJsonOnly(directory)}catch(error93){return refused2("no-plan",[`plan could not be loaded: ${errorText7(error93)}`])}if(!plan)return refused2("no-plan",["No plan found at `.swarm/plan.json` — create and approve a plan first."]);let planEpoch,planIdentityHashFromLedger;try{let identity2=await withTimeout(_internals163.readPlanEpochIdentity(directory,plan),PLAN_SCOPE_RESOLVE_TIMEOUT_MS,Error(`plan ledger read timed out after ${PLAN_SCOPE_RESOLVE_TIMEOUT_MS}ms`));planEpoch=identity2?.planEpoch??null,planIdentityHashFromLedger=identity2?.planIdentityHash??null}catch(error93){return refused2("plan-ledger-unreadable",[errorText7(error93)])}let ledgerRootDigest=readLedgerRootDigest(directory);if(planEpoch===null||ledgerRootDigest===null||ledgerRootDigest==="unreadable")return refused2("plan-ledger-unreadable",[ledgerRootDigest==="unreadable"?"The plan ledger (.swarm/plan-ledger.jsonl) could not be read.":"The plan has no plan ledger with a plan epoch yet.","Save the plan first (save_plan) so the plan ledger exists, then retry `/swarm epic start`."]);let identity=planIdentityOf(plan),planKey=computePlanKey(planIdentityHashFromLedger??identity.planIdentityHash,planEpoch),epicKey=computeEpicKey(identity.planId,planKey),inspection=_internals163.inspectEpic(directory,plan);if(inspection.unreadable)return refused2("epic-state-unreadable",[inspection.unreadable,"Run `/swarm epic status` to diagnose or `/swarm epic close --abandon` to repair."]);if(inspection.record){let existing=inspection.record;if(existing.epicKey===epicKey&&existing.status==="open"&&inspection.orphanReason===null)return{status:"already-open",record:existing};return refused2("epic-open-for-other-plan",[`Epic ${existing.epicKey} (plan ${existing.planId}) is ${existing.status}${inspection.orphanReason?` and orphaned (${inspection.orphanReason})`:""}.`,"Close it first: `/swarm epic close` (or `/swarm epic close --abandon`)."])}let turbo;try{turbo=findTurboActivity(directory,config3)}catch(error93){turbo=[`Turbo state could not be verified: ${errorText7(error93)}`]}if(turbo.length>0)return refused2("turbo-active",turbo);let git=readGitFacts(directory),commitPolicy=git.isRepo?resolveEpicCommitPolicy(config3):"current-branch",epicBranch=null;if(git.isRepo){let dirty;try{dirty=findDirtyBaseline(directory)}catch(error93){return refused2("dirty-baseline",[`git status failed: ${errorText7(error93)}`])}if(dirty.length>0)return refused2("dirty-baseline",[`${dirty.length} uncommitted change(s) outside .swarm/: ${dirty.slice(0,10).join(", ")}${dirty.length>10?", …":""}`,"Commit or stash them, then retry."]);if(commitPolicy==="epic-branch"){if(git.originalBranch===null||git.baseCommit===null)return refused2("detached-head",[git.baseCommit===null?"The current branch has no commit yet, so there is nothing to branch the epic from.":"HEAD is detached, so there is no branch to land the epic back onto at close.",'Check out (or create) a branch with at least one commit, then retry — or set `epic.commit_policy: "current-branch"`.']);epicBranch=epicBranchName(epicKey);let exists;try{exists=_internals163.localBranchExists(directory,epicBranch)}catch(error93){return refused2("branch-create-failed",[`git could not check for the epic branch \`${epicBranch}\`: ${errorText7(error93)}`])}if(exists)return refused2("epic-branch-exists",[`The epic branch \`${epicBranch}\` already exists (left by an earlier epic of this plan that was abandoned or not landed).`,`Land or inspect what you need from it, delete it with \`git branch -D ${epicBranch}\`, then retry.`])}}let inFlight;try{inFlight=await findInFlightCoderWork(directory)}catch(error93){inFlight=[`in-flight coder state could not be verified: ${errorText7(error93)}`]}if(inFlight.length>0)return refused2("in-flight-coders",inFlight);let maxParallel=epicWaveWidth(config3,git.isRepo),learningSettings=resolveEpicLearningSettings(config3),imported=null,priorSnapshot={status:"absent",digest:null};if(learningSettings.enabled){let migration=_internals163.importLegacyEpicCalibrationOnce(directory,_internals163.now());if(migration.status==="imported")imported={calibrationHotModules:migration.calibrationHotModules,divergenceRecords:migration.divergenceRecords};else if(migration.status==="failed")warn(`[epic/start] Epic v1 calibration import failed (retried at the next start): ${migration.detail}`);priorSnapshot=_internals163.readEpicPrior(directory)}let signals=await loadEpicPlanningSignals(directory,config3,{loadLearningView:_internals163.loadEpicLearningView,getCoChangeData:_internals163.getCoChangeData,now:_internals163.now},null),startSizing=sizeStartPlan(directory,plan,config3,maxParallel,signals),sizing=startSizing.plan.verdict;if(sizing.pendingTasks===0)return refused2("not-epic-sized",["Every task is already completed or closed — there is nothing to run."],sizing);if(!sizing.epicSized&&!force)return{...refused2("not-epic-sized",startSizing.plan.aborted?[SIZING_ABORTED_DETAIL]:[],sizing),shaping:shapeRefusedPlan(directory,plan,startSizing)};let record3={schema:"epic-record-v1",epicKey,token:_internals163.newToken(),planId:identity.planId,planIdentityHash:identity.planIdentityHash,planEpoch,planKey,ledgerRootDigest,status:"open",startedAt:new Date(_internals163.now()).toISOString(),startedBySession:sessionID,forced:!sizing.epicSized,structureHashAtStart:computePlanStructureHash(plan),config:{commitPolicy,isolation:git.isRepo?"worktree":"main-tree-nogit",maxParallel},git,sizing,priorDigest:priorSnapshot.digest,waves:[],activeWaveSeq:null,tasks:{},phases:initialEpicPhases(plan),closing:null},created=_internals163.createEpicRecord(directory,record3);if(created.outcome!=="created"){let winner=_internals163.inspectEpic(directory,plan).record;if(winner&&winner.epicKey===epicKey&&winner.status==="open")return{status:"already-open",record:winner};return refused2("epic-open-for-other-plan",[`Another epic was opened concurrently (${created.existingKeys.join(", ")}).`])}let result=epicBranch===null||git.originalBranch===null?{status:"started",record:created.record}:switchToEpicBranch(directory,created.record,git.originalBranch,epicBranch);if(result.status!=="started")return result;if(writeBaseRef(directory,result.record),learningSettings.enabled)try{_internals163.initEpicPosterior(directory,result.record,priorSnapshot)}catch(error93){warn(`[epic/start] learning posterior for ${result.record.epicKey} not written yet: ${errorText7(error93)}`)}return{...result,learning:describeStartLearning(learningSettings,priorSnapshot,imported)}}function describeStartLearning(settings,snapshot,imported){let enabled=settings.enabled;if(!enabled||snapshot.status!=="ok")return{enabled,prior:snapshot.status,files:0,coWrites:0,hotFiles:0,imported};let summary=summarizeEpicLearning(snapshot.prior.stats,settings.hotExcess,0);return{enabled,prior:"ok",files:summary.files,coWrites:summary.edges,hotFiles:summary.hotFiles.length,imported}}function writeBaseRef(directory,record3){if(!record3.git.isRepo||!isFullSha(record3.git.baseCommit))return;try{_internals163.syncEpicRefs(directory,record3)}catch(error93){warn(`[epic/start] base ref for ${record3.epicKey} not written yet: ${errorText7(error93)}`)}}function switchToEpicBranch(directory,record3,originalBranch,epicBranch){let baseCommit=record3.git.baseCommit??"",rollbackState=()=>{try{return _internals163.deleteEpicState(directory,record3.epicKey,record3.token),[]}catch(error93){return[`rolling back the epic record failed: ${errorText7(error93)} — run \`/swarm epic close --abandon\``]}},checkoutError=null;try{_internals163.checkoutNewEpicBranch(directory,epicBranch)}catch(error93){checkoutError=errorText7(error93)}if(checkoutError!==null){let current=null;try{current=_internals163.readCurrentBranch(directory)}catch{current=null}if(current!==epicBranch)return refused2("branch-create-failed",[`git checkout -b ${epicBranch} failed: ${checkoutError}`,..._internals163.undoEpicBranchCreate(directory,originalBranch,epicBranch,baseCommit),...rollbackState(),"The epic was not opened; fix the git problem and retry."])}let updated=null,updateError=null;try{updated=_internals163.recordEpicBranch(directory,record3.epicKey,record3.token,epicBranch)}catch(error93){updateError=errorText7(error93)}if(updated)return{status:"started",record:updated};return refused2("branch-create-failed",[`the epic branch \`${epicBranch}\` was created but could not be recorded${updateError?`: ${updateError}`:" (the epic row vanished)"}`,..._internals163.undoEpicBranchCreate(directory,originalBranch,epicBranch,baseCommit),...rollbackState(),"The epic was not opened; retry `/swarm epic start`."])}var LEAN_SESSION_NAMESPACE="turbo.lean.session",BACKGROUND_DELEGATION_NAMESPACE="background.pending-delegation",LEGACY_LEAN_STATE_FILE="turbo-state.json",MAX_LEGACY_LEAN_STATE_BYTES=4194304,UNSETTLED_WAL_STATES2,EPIC_HOST_UNSUPPORTED_MESSAGE="This OpenCode host gives the plugin no SDK client (OpenCode 2 does not yet, see docs/host/v2-hook-inventory.md). Epic needs it for worktree-isolated coders and for the epic_phase_review reviewer/critic, so an epic here could neither run its coders nor complete a phase. Run the plan in Balanced, or use an OpenCode 1.x host (1.18.29+).",SIZING_ABORTED_DETAIL="The plan is too large or densely coupled to size exactly within the sizing work budget: the tasks left unplanned were counted as serial steps. Run it in Balanced, or open it anyway with `/swarm epic start --force`.",_internals163;var init_start=__esm(()=>{init_pending_delegations();init_config2();init_coordination_store();init_project_db();init_branch();init_worktree_isolation();init_worktree_provisioning_owner();init_worktree_recovery_authority();init_ledger();init_manager();init_state();init_recovery();init_logger();init_timeout();init_coder_settlement();init_cochange_source();init_config_gate();init_declared_scopes();init_epic_branch();init_learning();init_learning_store();init_lifecycle();init_markers();init_plan_key();init_planning_signals();init_shaping();init_shaping_sizing();UNSETTLED_WAL_STATES2=new Set(["DISPATCHED","PREPARED","unreadable"]);_internals163={loadPluginConfigWithMeta,loadPlanJsonOnly,readPlanEpochIdentity,inspectEpic,createEpicRecord,deleteEpicState,recordEpicBranch,localBranchExists,checkoutNewEpicBranch,readCurrentBranch,undoEpicBranchCreate,resolveEpicDeclaredScopes,loadEpicLearningView,readEpicPrior,importLegacyEpicCalibrationOnce,initEpicPosterior,getCoChangeData,shapeEpicPlan,hasActiveTurboMode:()=>hasActiveTurboMode(),hostProvidesClient:()=>swarmState.opencodeClient!==void 0,findRunningLeanRun,gitExec:(args2,cwd)=>_internals44.gitExec(args2,cwd),getGitRepositoryStatus:(cwd)=>_internals44.getGitRepositoryStatus(cwd),countTrackedWorktreeDispatches:()=>standardWorktreeByCallID.size+awaitingMergeByCallID.size,readDelegationsDetailed,listCoderSettlementWalStates,listRecoveryRecords,recoveryReadErrored,scanWorktreeRecoveryAuthoritiesForRecovery,scanWorktreeProvisioningOwnersForRecovery,syncEpicRefs,now:()=>Date.now(),newToken:()=>randomUUID30()}});import*as path197 from"node:path";function parseConfirm(args2){let token=null;for(let i=0;i<args2.length;i+=1){let arg=args2[i];if(arg.toLowerCase().startsWith("--confirm="))token=arg.slice(10).trim();else if(arg.toLowerCase()==="--confirm")token=(args2[i+1]??"").trim(),i+=1;else return{error:`Unknown option(s) for \`/swarm epic prior reset\`: ${arg}.`};if(!token)return{error:"`--confirm` takes the token the preview printed: run `/swarm epic prior reset` first, then `/swarm epic prior reset --confirm=<token>`."}}return{token}}function fmt(value){return(Math.round(value*100)/100).toString()}function statsLines(stats2,settings){let summary=summarizeEpicLearning(stats2,settings.hotExcess,SHOWN),lines=[`- ${summary.files} file statistic(s), ${summary.edges} learned co-write(s).`,"","### Hot files (a task declaring one runs alone)"];if(summary.hotFiles.length===0)lines.push("_None._ A file becomes hot only on excess evidence: at least one full incident (undeclared write, merge conflict, or accumulated Stage B failures / rework / reopens) and an incident rate above the prior mean by more than `hot_excess`. Undeclared writes its strongest learned co-writer explains are discounted (that co-write already keeps the writer apart from the file).");else{for(let file3 of summary.hotFiles.slice(0,SHOWN)){let e=epicHotEvidence(stats2,file3),discount=e.countedAlpha<e.alpha?` (${fmt(e.countedAlpha)} counted after its strongest co-writer)`:"";lines.push(`- \`${file3}\` — incidents ${fmt(e.alpha)}${discount}, exposures ${fmt(e.beta)}, rate ${fmt(e.rate)}`)}if(summary.hotFiles.length>SHOWN)lines.push(`- … +${summary.hotFiles.length-SHOWN} more`)}if(lines.push("","### Learned co-writes (scope expansion — planner analysis only, never write authorization)"),summary.topCoWrites.length===0)lines.push("_None._ Tasks have not written files outside their declared scope.");else{for(let edge of summary.topCoWrites)lines.push(`- \`${edge.from}\` → \`${edge.to}\` (weight ${fmt(edge.weight)}${edge.weight>=1?"":", below 1 — expands only together with other declared files"})`);if(summary.edges>summary.topCoWrites.length)lines.push(`- … +${summary.edges-summary.topCoWrites.length} more`)}return lines}function renderEpicLearning(directory,settings){let lines=["## Epic Mode — Learning",""];if(lines.push(`Settings: ${settings.enabled?"enabled":"**disabled**"}; decay_per_epic ${settings.decayPerEpic}; half_life_days ${settings.halfLifeDays}; hot_excess ${settings.hotExcess} (\`epic.learning.*\`).`),!settings.enabled)return lines.push("","Learning is disabled: epics plan without learned signals and nothing is learned or written."),lines.join(`
|
|
2718
|
+
`,output+="\nPreview only. Run `/swarm config doctor --quarantine-residue` to quarantine eligible items (recoverable), or `--rollback-residue-quarantine` to restore a batch.\n"}catch{}return output}async function handleDoctorToolsCommand(directory,_args){let result=runToolDoctor(directory);return formatToolDoctorMarkdown(result)}var init_doctor=__esm(()=>{init_loader();init_config_doctor();init_swarm_residue();init_tool_doctor();init_state()});import*as fs107 from"node:fs";import*as path194 from"node:path";function archiveWithoutOverwrite(filePath){let canonical=`${filePath}.imported`;if(!fs107.existsSync(canonical))return fs107.renameSync(filePath,canonical),canonical;for(let suffix=1;suffix<=MAX_ARCHIVE_SUFFIX;suffix+=1){let candidate=`${canonical}.${suffix}`;if(fs107.existsSync(candidate))continue;return fs107.renameSync(filePath,candidate),candidate}throw Error("legacy Epic state archive collision limit exceeded")}function countActiveInLegacyFile(filePath){let stat17=fs107.statSync(filePath);if(!stat17.isFile()||stat17.size>MAX_LEGACY_FILE_BYTES)return 0;let parsed=JSON.parse(fs107.readFileSync(filePath,"utf-8"));return Object.values(parsed.sessions??{}).filter((session)=>session?.active===!0).length}function retireLegacyEpicSessionState(directory){let result={rowsRemoved:0,activeSessions:0,fileArchivedTo:null,errors:[]},activeIds=new Set;if(projectDbExists(directory))try{let rows=listCoordinationStates(directory,LEGACY_EPIC_SESSION_NAMESPACE);for(let row of rows){if(row.status==="active")activeIds.add(row.entityKey);if(deleteCoordinationState(directory,LEGACY_EPIC_SESSION_NAMESPACE,row.entityKey,row.revision))result.rowsRemoved+=1}}catch(error93){result.errors.push(`legacy Epic session rows: ${error93 instanceof Error?error93.message:String(error93)}`)}let filePath=path194.join(directory,".swarm",LEGACY_STATE_FILE);if(fs107.existsSync(filePath)){let fileActive=0;try{fileActive=countActiveInLegacyFile(filePath)}catch{fileActive=0}try{result.fileArchivedTo=path194.relative(directory,archiveWithoutOverwrite(filePath))}catch(error93){result.errors.push(`.swarm/${LEGACY_STATE_FILE}: ${error93 instanceof Error?error93.message:String(error93)}`)}result.activeSessions=Math.max(activeIds.size,fileActive)}else result.activeSessions=activeIds.size;return result}function describeLegacyEpicMigration(result){if(result.rowsRemoved===0&&result.fileArchivedTo===null&&result.errors.length===0)return[];let lines=["","### Legacy Epic v1 state"];if(result.rowsRemoved>0||result.fileArchivedTo!==null)lines.push(`Retired Epic v1 per-session state (${result.rowsRemoved} row(s)${result.fileArchivedTo?`; projection archived to \`${result.fileArchivedTo}\``:""}). Epic v1 \`/swarm epic on|off\` no longer exists — epics are plan-scoped.`);if(result.activeSessions>0)lines.push(`${result.activeSessions} session(s) had Epic v1 switched on. Nothing was opened automatically: run \`/swarm epic start\` to open an epic for the current plan.`);for(let error93 of result.errors)lines.push(`⚠️ Could not retire ${error93}`);return lines}var LEGACY_EPIC_SESSION_NAMESPACE="turbo.epic.session",LEGACY_STATE_FILE="epic-state.json",MAX_LEGACY_FILE_BYTES=4194304,MAX_ARCHIVE_SUFFIX=1000;var init_legacy_migration=__esm(()=>{init_coordination_store();init_project_db()});import*as fs108 from"node:fs";import*as path195 from"node:path";function listEpicPriorReports(directory){let dir=path195.join(directory,EPIC_PRIOR_REPORTS_RELATIVE_DIR),names;try{names=fs108.readdirSync(dir).filter((name)=>EPIC_REPORT_NAME_RE.test(name))}catch{return[]}return names.map((name)=>{try{return{name,mtime:fs108.statSync(path195.join(dir,name)).mtimeMs}}catch{return{name,mtime:0}}}).sort((a,b)=>b.mtime-a.mtime||b.name.localeCompare(a.name)).map((entry)=>entry.name)}function scorecardFromReport(raw){if(typeof raw!=="object"||raw===null||Array.isArray(raw))return{error:"not a JSON object"};let schema=raw.schema;if(schema!==EPIC_REPORT_SCHEMA)return{error:`unknown report schema ${JSON.stringify(schema)}`};let card=raw.scorecard,parsed=EpicScorecardSchema.safeParse(card);if(!parsed.success){let issue3=parsed.error.issues[0];return{error:`invalid ${["scorecard",...(issue3?.path??[]).map(String)].join(".")}: ${issue3?.message??"malformed scorecard"}`}}return{scorecard:card}}function readReport(directory,name){let file3=path195.join(directory,EPIC_PRIOR_REPORTS_RELATIVE_DIR,name),reportKey=name.replace(/\.json$/,""),raw;try{if(fs108.statSync(file3).size>MAX_EPIC_REPORT_BYTES)return{status:"error",message:`Report \`${reportKey}\` is larger than ${MAX_EPIC_REPORT_BYTES} bytes and was not read.`};raw=JSON.parse(fs108.readFileSync(file3,"utf-8"))}catch(error93){return{status:"error",message:`Report \`${reportKey}\` could not be read (${error93 instanceof Error?error93.message:String(error93)}).`}}let scored=scorecardFromReport(raw);if("error"in scored)return{status:"error",message:`Report \`${reportKey}\` is unreadable: ${scored.error}.`};return{status:"ok",source:"report",reportKey,scorecard:scored.scorecard}}async function liveEpicScorecard(directory,epic,learning){let plan=null;try{plan=await _internals162.loadPlanJsonOnly(directory)}catch{plan=null}let adoptedAtStart;if(plan)try{adoptedAtStart=(await _internals162.completedBeforeEpic(directory,epic,plan)).size}catch{adoptedAtStart=void 0}let view=_internals162.loadEpicLearningView(directory,epic,learning,_internals162.now());return computeEpicScorecard({record:epic,outcome:"open",closedAt:null,planTaskTotal:plan?summarizePlanTasks(plan).total:null,adoptedAtStart,hotFiles:epicHotFiles(view.stats,learning.hotExcess)})}async function selectEpicReport(directory,selector,learning){if(selector===null){let live=await liveSelection(directory,learning);if(live)return live}let names=listEpicPriorReports(directory);if(selector===null||selector.toLowerCase()==="last"){if(names.length===0)return{status:"none",message:selector===null?"No epic is open and no past epic report exists (`.swarm/epic-prior/reports/` is empty).":"No past epic report exists (`.swarm/epic-prior/reports/` is empty)."};return readReport(directory,names[0])}if(!SELECTOR_RE.test(selector))return{status:"error",message:`\`${selector}\` is not a report or epic key (letters, digits, \`-\` and \`_\` only).`};let exact=names.find((name)=>name===`${selector}.json`),byEpic=names.find((name)=>name.startsWith(`${selector}-`)&&EPIC_REPORT_NAME_RE.test(name)&&/^\d{8}T\d{6}Z\.json$/.test(name.slice(selector.length+1))),chosen=exact??byEpic;if(!chosen){let stillOpen=safeOpenKey(directory)===selector?` — epic \`${selector}\` is still open; run \`/swarm epic report\` for its live scorecard`:"";return{status:"none",message:`No report for \`${selector}\` in \`.swarm/epic-prior/reports/\`${stillOpen}.`}}return readReport(directory,chosen)}async function liveSelection(directory,learning){if(!_internals162.epicSentinelExists(directory))return null;let inspection;try{inspection=_internals162.inspectEpic(directory)}catch(error93){inspection={unreadable:error93 instanceof Error?error93.message:String(error93)}}if(inspection.unreadable)return{status:"error",message:`The epic's lifecycle state is unreadable (${inspection.unreadable}); run \`/swarm epic status\`.`};let record3=inspection.record;if(!record3)return null;let notes=[];if(inspection.orphanReason)notes.push(`The epic no longer matches the current plan (${inspection.orphanReason}); close it with \`/swarm epic close --abandon\`.`);if(!inspection.configEnabled)notes.push("Epic Mode is disabled by config (`epic.mode.enabled`), so no Epic behaviour runs for this epic until it is re-enabled or closed.");return{status:"ok",source:"live",reportKey:null,scorecard:await liveEpicScorecard(directory,record3,learning),notes}}function safeOpenKey(directory){if(!_internals162.epicSentinelExists(directory))return null;try{return _internals162.inspectEpic(directory).record?.epicKey??null}catch{return null}}var MAX_EPIC_REPORT_BYTES=4194304,SELECTOR_RE,_internals162,num,count3,rate2,EpicScorecardSchema;var init_report3=__esm(()=>{init_zod();init_manager();init_close();init_learning();init_learning_store();init_lifecycle();init_next_wave();init_scorecard();SELECTOR_RE=/^[A-Za-z0-9_-]{1,200}$/,_internals162={epicSentinelExists,inspectEpic,loadPlanJsonOnly,completedBeforeEpic,loadEpicLearningView,now:()=>Date.now()};num=exports_external.number().finite(),count3=num.min(0),rate2=exports_external.object({passed:count3,of:count3,rate:num.min(0).max(1).nullable()}),EpicScorecardSchema=exports_external.object({schema:exports_external.literal(EPIC_SCORECARD_SCHEMA),epicKey:exports_external.string().min(1),planId:exports_external.string(),outcome:exports_external.enum(["open","completed","abandoned","abandoned-by-swarm-close"]),startedAt:exports_external.string(),closedAt:exports_external.string().nullable(),forced:exports_external.boolean(),sizingAtStart:exports_external.object({epicSized:exports_external.boolean(),reasons:exports_external.array(exports_external.string()),pendingTasks:count3,scopedTasks:count3,scopeCoverage:num,serialSteps:count3,concurrency:num,effectiveSpeedup:num}),tasks:exports_external.object({total:count3.nullable(),completedInEpic:count3,adoptedAtStart:count3.optional(),exclusive:count3,serialComponent:count3}),waves:exports_external.object({count:count3,parallel:count3,meanWidth:count3,maxWidth:count3}),time:exports_external.object({method:exports_external.literal("wave-span-v1"),label:exports_external.string(),spanMs:count3,workMs:count3,concurrencyFactor:count3.nullable(),interWaveIdleMs:count3}),conflicts:exports_external.object({mergeFailures:count3,undeclaredWriteTasks:count3,undeclaredFiles:exports_external.array(exports_external.string()),undeclaredFilesTotal:count3}),rework:exports_external.object({tasksWithRework:count3,extraGenerations:count3,reopened:count3}),gates:exports_external.object({stageAFirstPass:rate2,stageBFirstPass:rate2,phaseReviewFirstPass:rate2,boundedHistory:exports_external.literal(!0)}),learning:exports_external.object({priorDigest:exports_external.string().nullable(),topHotFiles:exports_external.array(exports_external.string())})})});import{randomUUID as randomUUID30}from"node:crypto";import*as fs109 from"node:fs";import*as path196 from"node:path";function refused2(reason,details,sizing){return{status:"refused",reason,details,sizing}}function errorText7(error93){return error93 instanceof Error?error93.message:String(error93)}function findRunningLeanRun(directory){if(projectDbExists(directory)){let rows=listCoordinationStates(directory,LEAN_SESSION_NAMESPACE),running=rows.find((row)=>row.status==="running");if(running)return`durable Lean Turbo run for session ${running.entityKey}`;if(rows.length>0)return null}let legacyPath=path196.join(directory,".swarm",LEGACY_LEAN_STATE_FILE);try{let stat17=fs109.statSync(legacyPath);if(!stat17.isFile()||stat17.size>MAX_LEGACY_LEAN_STATE_BYTES)return null;let parsed=JSON.parse(fs109.readFileSync(legacyPath,"utf-8"));for(let[sessionID,state2]of Object.entries(parsed.sessions??{}))if(state2?.status==="running")return`durable Lean Turbo run for session ${sessionID} (.swarm/${LEGACY_LEAN_STATE_FILE})`}catch{}return null}function findTurboActivity(directory,config3){let reasons=[];if(config3.turbo_mode===!0)reasons.push("config `turbo_mode: true` seeds Turbo into every new session — set it to false");if(_internals163.hasActiveTurboMode())reasons.push("a session in this process has Turbo on — run `/swarm turbo off` in it");let lean=_internals163.findRunningLeanRun(directory);if(lean)reasons.push(`${lean} — finish it or run \`/swarm turbo off\``);return reasons}function findDirtyBaseline(directory){return listDirtyPathsOutsideSwarm(directory,_internals163.gitExec)}async function findInFlightCoderWork(directory){let found=[],dispatches=_internals163.countTrackedWorktreeDispatches();if(dispatches>0)found.push(`${dispatches} worktree-isolated coder dispatch(es) running or awaiting merge-back — let them finish (\`/swarm lanes\` shows them)`);if(projectDbExists(directory)){let open7=listCoordinationStates(directory,BACKGROUND_DELEGATION_NAMESPACE).filter((row)=>!isTerminalDelegationStatus(row.status));if(open7.length>0)found.push(`${open7.length} non-terminal background delegation(s) — let them finish`)}else{let outcome=_internals163.readDelegationsDetailed(directory);if(outcome.status!=="ok")found.push("background delegation state is uncertain — cannot prove no coder is running");else{let open7=outcome.records.filter((record3)=>!isTerminalDelegationStatus(record3.status));if(open7.length>0)found.push(`${open7.length} non-terminal background delegation(s) — let them finish`)}}let wal=await _internals163.listCoderSettlementWalStates(directory),unsettled=wal.states.filter((state2)=>UNSETTLED_WAL_STATES2.has(state2.state)),live=unsettled.filter((state2)=>state2.state!=="unreadable"&&(state2.ownedInProcess||state2.ownedByLiveForeignPid)),stale=unsettled.filter((state2)=>!live.includes(state2)),describe3=(states)=>states.slice(0,5).map((state2)=>`${state2.taskId} (${state2.state})`).join(", ");if(live.length>0)found.push(`${live.length} coder settlement(s) still owned by a running dispatch: ${describe3(live)} — let them finish`);if(stale.length>0)found.push(`${stale.length} stale or unreadable coder settlement(s): ${describe3(stale)} — run \`/swarm recover <taskId>\` for each (it settles WALs whose owner process is gone)`);if(wal.truncated)found.push("coder settlement directory exceeds the scan bound — cannot prove every settlement is final; run `/swarm recover` to settle stale WALs");let recovery=_internals163.listRecoveryRecords(directory);if(recovery.length>0)found.push(`${recovery.length} preserved Lean recovery lane(s) in .swarm/recovery/ — finish them with Lean Turbo (\`/swarm turbo lean on\`, then \`/swarm turbo off\`) or discard those lanes`);else if(_internals163.recoveryReadErrored(directory))found.push("Lean recovery records in .swarm/recovery/ are unreadable — inspect and repair or remove them");let authorities=_internals163.scanWorktreeRecoveryAuthoritiesForRecovery(directory);if(authorities.status==="ok"){let liveLanes=authorities.authorities.filter((authority)=>authority.status==="preserved"||authority.status==="claimed");if(liveLanes.length>0)found.push(`${liveLanes.length} preserved/claimed worktree recovery lane(s) — inspect with \`/swarm lanes\`; merge or discard them (\`/swarm reset-session\` can purge dirty lanes)`)}else found.push(`worktree recovery state is ${authorities.status} — inspect .swarm/worktree-merge-recovery-v2.json`);let owners=_internals163.scanWorktreeProvisioningOwnersForRecovery(directory);if(owners.status==="ok"){if(owners.owners.length>0)found.push(`${owners.owners.length} worktree lane(s) being provisioned — let the dispatch finish (\`/swarm lanes\`)`)}else found.push(`worktree provisioning state is uncertain (${owners.reason})`);return found}function isPending(status2){return isEpicPendingStatus(status2)}function sizeStartPlan(directory,plan,config3,maxParallel,signals){let estimate=estimatePlanScopes(directory,plan),context=epicSizingContextFor(directory,config3,maxParallel,signals);return{plan:sizeEpicPlan(context,plan.phases,estimate,MAX_START_SIZING_WORK),estimate,context}}function estimatePlanScopes(directory,plan){let pendingIds=[];for(let phase of plan.phases)for(let task of phase.tasks??[])if(isPending(task.status))pendingIds.push(task.id);return estimateEpicScopes(plan.phases,_internals163.resolveEpicDeclaredScopes(directory,plan,pendingIds))}function shapeRefusedPlan(directory,plan,sizing){try{return _internals163.shapeEpicPlan({...sizing.context,phases:plan.phases,declared:Object.fromEntries(sizing.estimate.pendingIds.map((id)=>[id,sizing.estimate.scopes[id]])),baseline:sizing.plan,isDirectory:(entry)=>isDirectoryOnDisk(directory,entry)})}catch(error93){warn(`[epic/start] plan shaping failed (the refusal carries no suggestions): ${errorText7(error93)}`);return}}function initialEpicPhases(plan){let phases={};for(let phase of plan.phases){let tasks=phase.tasks??[];if(phase.status==="closed"||tasks.length>0&&tasks.every((task)=>!isPending(task.status)))phases[String(phase.id)]={status:"complete",completeAtStart:!0,reviewRuns:0,verdicts:[]}}return phases}function readGitFacts(directory){if(!_internals163.getGitRepositoryStatus(directory).isRepo)return{isRepo:!1,baseCommit:null,originalBranch:null,epicBranch:null};let baseCommit=null,originalBranch=null;try{baseCommit=_internals163.gitExec(["rev-parse","HEAD"],directory).trim()}catch{baseCommit=null}try{originalBranch=_internals163.gitExec(["rev-parse","--abbrev-ref","HEAD"],directory).trim()}catch{originalBranch=null}if(originalBranch==="HEAD"||originalBranch==="")originalBranch=null;return{isRepo:!0,baseCommit,originalBranch,epicBranch:null}}async function startEpic(options){let{directory,sessionID,force}=options,config3;try{config3=_internals163.loadPluginConfigWithMeta(directory).config}catch{return refused2("epic-disabled-by-config",[EPIC_MODE_CONFIG_DISABLED_MESSAGE])}if(!isEpicModeConfigEnabled(config3))return refused2("epic-disabled-by-config",[EPIC_MODE_CONFIG_DISABLED_MESSAGE]);if(!_internals163.hostProvidesClient())return refused2("host-unsupported",[EPIC_HOST_UNSUPPORTED_MESSAGE]);let plan;try{plan=await _internals163.loadPlanJsonOnly(directory)}catch(error93){return refused2("no-plan",[`plan could not be loaded: ${errorText7(error93)}`])}if(!plan)return refused2("no-plan",["No plan found at `.swarm/plan.json` — create and approve a plan first."]);let planEpoch,planIdentityHashFromLedger;try{let identity2=await withTimeout(_internals163.readPlanEpochIdentity(directory,plan),PLAN_SCOPE_RESOLVE_TIMEOUT_MS,Error(`plan ledger read timed out after ${PLAN_SCOPE_RESOLVE_TIMEOUT_MS}ms`));planEpoch=identity2?.planEpoch??null,planIdentityHashFromLedger=identity2?.planIdentityHash??null}catch(error93){return refused2("plan-ledger-unreadable",[errorText7(error93)])}let ledgerRootDigest=readLedgerRootDigest(directory);if(planEpoch===null||ledgerRootDigest===null||ledgerRootDigest==="unreadable")return refused2("plan-ledger-unreadable",[ledgerRootDigest==="unreadable"?"The plan ledger (.swarm/plan-ledger.jsonl) could not be read.":"The plan has no plan ledger with a plan epoch yet.","Save the plan first (save_plan) so the plan ledger exists, then retry `/swarm epic start`."]);let identity=planIdentityOf(plan),planKey=computePlanKey(planIdentityHashFromLedger??identity.planIdentityHash,planEpoch),epicKey=computeEpicKey(identity.planId,planKey),inspection=_internals163.inspectEpic(directory,plan);if(inspection.unreadable)return refused2("epic-state-unreadable",[inspection.unreadable,"Run `/swarm epic status` to diagnose or `/swarm epic close --abandon` to repair."]);if(inspection.record){let existing=inspection.record;if(existing.epicKey===epicKey&&existing.status==="open"&&inspection.orphanReason===null)return{status:"already-open",record:existing};return refused2("epic-open-for-other-plan",[`Epic ${existing.epicKey} (plan ${existing.planId}) is ${existing.status}${inspection.orphanReason?` and orphaned (${inspection.orphanReason})`:""}.`,"Close it first: `/swarm epic close` (or `/swarm epic close --abandon`)."])}let turbo;try{turbo=findTurboActivity(directory,config3)}catch(error93){turbo=[`Turbo state could not be verified: ${errorText7(error93)}`]}if(turbo.length>0)return refused2("turbo-active",turbo);let git=readGitFacts(directory),commitPolicy=git.isRepo?resolveEpicCommitPolicy(config3):"current-branch",epicBranch=null;if(git.isRepo){let dirty;try{dirty=findDirtyBaseline(directory)}catch(error93){return refused2("dirty-baseline",[`git status failed: ${errorText7(error93)}`])}if(dirty.length>0)return refused2("dirty-baseline",[`${dirty.length} uncommitted change(s) outside .swarm/: ${dirty.slice(0,10).join(", ")}${dirty.length>10?", …":""}`,"Commit or stash them, then retry."]);if(commitPolicy==="epic-branch"){if(git.originalBranch===null||git.baseCommit===null)return refused2("detached-head",[git.baseCommit===null?"The current branch has no commit yet, so there is nothing to branch the epic from.":"HEAD is detached, so there is no branch to land the epic back onto at close.",'Check out (or create) a branch with at least one commit, then retry — or set `epic.commit_policy: "current-branch"`.']);epicBranch=epicBranchName(epicKey);let exists;try{exists=_internals163.localBranchExists(directory,epicBranch)}catch(error93){return refused2("branch-create-failed",[`git could not check for the epic branch \`${epicBranch}\`: ${errorText7(error93)}`])}if(exists)return refused2("epic-branch-exists",[`The epic branch \`${epicBranch}\` already exists (left by an earlier epic of this plan that was abandoned or not landed).`,`Land or inspect what you need from it, delete it with \`git branch -D ${epicBranch}\`, then retry.`])}}let inFlight;try{inFlight=await findInFlightCoderWork(directory)}catch(error93){inFlight=[`in-flight coder state could not be verified: ${errorText7(error93)}`]}if(inFlight.length>0)return refused2("in-flight-coders",inFlight);let maxParallel=epicWaveWidth(config3,git.isRepo),learningSettings=resolveEpicLearningSettings(config3),imported=null,priorSnapshot={status:"absent",digest:null};if(learningSettings.enabled){let migration=_internals163.importLegacyEpicCalibrationOnce(directory,_internals163.now());if(migration.status==="imported")imported={calibrationHotModules:migration.calibrationHotModules,divergenceRecords:migration.divergenceRecords};else if(migration.status==="failed")warn(`[epic/start] Epic v1 calibration import failed (retried at the next start): ${migration.detail}`);priorSnapshot=_internals163.readEpicPrior(directory)}let signals=await loadEpicPlanningSignals(directory,config3,{loadLearningView:_internals163.loadEpicLearningView,getCoChangeData:_internals163.getCoChangeData,now:_internals163.now},null),startSizing=sizeStartPlan(directory,plan,config3,maxParallel,signals),sizing=startSizing.plan.verdict;if(sizing.pendingTasks===0)return refused2("not-epic-sized",["Every task is already completed or closed — there is nothing to run."],sizing);if(!sizing.epicSized&&!force)return{...refused2("not-epic-sized",startSizing.plan.aborted?[SIZING_ABORTED_DETAIL]:[],sizing),shaping:shapeRefusedPlan(directory,plan,startSizing)};let record3={schema:"epic-record-v1",epicKey,token:_internals163.newToken(),planId:identity.planId,planIdentityHash:identity.planIdentityHash,planEpoch,planKey,ledgerRootDigest,status:"open",startedAt:new Date(_internals163.now()).toISOString(),startedBySession:sessionID,forced:!sizing.epicSized,structureHashAtStart:computePlanStructureHash(plan),config:{commitPolicy,isolation:git.isRepo?"worktree":"main-tree-nogit",maxParallel},git,sizing,priorDigest:priorSnapshot.digest,waves:[],activeWaveSeq:null,tasks:{},phases:initialEpicPhases(plan),closing:null},created=_internals163.createEpicRecord(directory,record3);if(created.outcome!=="created"){let winner=_internals163.inspectEpic(directory,plan).record;if(winner&&winner.epicKey===epicKey&&winner.status==="open")return{status:"already-open",record:winner};return refused2("epic-open-for-other-plan",[`Another epic was opened concurrently (${created.existingKeys.join(", ")}).`])}let result=epicBranch===null||git.originalBranch===null?{status:"started",record:created.record}:switchToEpicBranch(directory,created.record,git.originalBranch,epicBranch);if(result.status!=="started")return result;if(writeBaseRef(directory,result.record),learningSettings.enabled)try{_internals163.initEpicPosterior(directory,result.record,priorSnapshot)}catch(error93){warn(`[epic/start] learning posterior for ${result.record.epicKey} not written yet: ${errorText7(error93)}`)}return{...result,learning:describeStartLearning(learningSettings,priorSnapshot,imported)}}function describeStartLearning(settings,snapshot,imported){let enabled=settings.enabled;if(!enabled||snapshot.status!=="ok")return{enabled,prior:snapshot.status,files:0,coWrites:0,hotFiles:0,imported};let summary=summarizeEpicLearning(snapshot.prior.stats,settings.hotExcess,0);return{enabled,prior:"ok",files:summary.files,coWrites:summary.edges,hotFiles:summary.hotFiles.length,imported}}function writeBaseRef(directory,record3){if(!record3.git.isRepo||!isFullSha(record3.git.baseCommit))return;try{_internals163.syncEpicRefs(directory,record3)}catch(error93){warn(`[epic/start] base ref for ${record3.epicKey} not written yet: ${errorText7(error93)}`)}}function switchToEpicBranch(directory,record3,originalBranch,epicBranch){let baseCommit=record3.git.baseCommit??"",rollbackState=()=>{try{return _internals163.deleteEpicState(directory,record3.epicKey,record3.token),[]}catch(error93){return[`rolling back the epic record failed: ${errorText7(error93)} — run \`/swarm epic close --abandon\``]}},checkoutError=null;try{_internals163.checkoutNewEpicBranch(directory,epicBranch)}catch(error93){checkoutError=errorText7(error93)}if(checkoutError!==null){let current=null;try{current=_internals163.readCurrentBranch(directory)}catch{current=null}if(current!==epicBranch)return refused2("branch-create-failed",[`git checkout -b ${epicBranch} failed: ${checkoutError}`,..._internals163.undoEpicBranchCreate(directory,originalBranch,epicBranch,baseCommit),...rollbackState(),"The epic was not opened; fix the git problem and retry."])}let updated=null,updateError=null;try{updated=_internals163.recordEpicBranch(directory,record3.epicKey,record3.token,epicBranch)}catch(error93){updateError=errorText7(error93)}if(updated)return{status:"started",record:updated};return refused2("branch-create-failed",[`the epic branch \`${epicBranch}\` was created but could not be recorded${updateError?`: ${updateError}`:" (the epic row vanished)"}`,..._internals163.undoEpicBranchCreate(directory,originalBranch,epicBranch,baseCommit),...rollbackState(),"The epic was not opened; retry `/swarm epic start`."])}var LEAN_SESSION_NAMESPACE="turbo.lean.session",BACKGROUND_DELEGATION_NAMESPACE="background.pending-delegation",LEGACY_LEAN_STATE_FILE="turbo-state.json",MAX_LEGACY_LEAN_STATE_BYTES=4194304,UNSETTLED_WAL_STATES2,EPIC_HOST_UNSUPPORTED_MESSAGE="This OpenCode host gives the plugin no SDK client. Epic needs it for worktree-isolated coders and for the epic_phase_review reviewer/critic, so an epic here could neither run its coders nor complete a phase. Run the plan in Balanced, or use an OpenCode 1.x host (1.18.29+). (On OpenCode 2 the v2 adapter now ships a session-capable client, so this refusal no longer fires there — Epic on v2 is held by the #3169 child-session placement work instead.)",SIZING_ABORTED_DETAIL="The plan is too large or densely coupled to size exactly within the sizing work budget: the tasks left unplanned were counted as serial steps. Run it in Balanced, or open it anyway with `/swarm epic start --force`.",_internals163;var init_start=__esm(()=>{init_pending_delegations();init_config2();init_coordination_store();init_project_db();init_branch();init_worktree_isolation();init_worktree_provisioning_owner();init_worktree_recovery_authority();init_ledger();init_manager();init_state();init_recovery();init_logger();init_timeout();init_coder_settlement();init_cochange_source();init_config_gate();init_declared_scopes();init_epic_branch();init_learning();init_learning_store();init_lifecycle();init_markers();init_plan_key();init_planning_signals();init_shaping();init_shaping_sizing();UNSETTLED_WAL_STATES2=new Set(["DISPATCHED","PREPARED","unreadable"]);_internals163={loadPluginConfigWithMeta,loadPlanJsonOnly,readPlanEpochIdentity,inspectEpic,createEpicRecord,deleteEpicState,recordEpicBranch,localBranchExists,checkoutNewEpicBranch,readCurrentBranch,undoEpicBranchCreate,resolveEpicDeclaredScopes,loadEpicLearningView,readEpicPrior,importLegacyEpicCalibrationOnce,initEpicPosterior,getCoChangeData,shapeEpicPlan,hasActiveTurboMode:()=>hasActiveTurboMode(),hostProvidesClient:()=>swarmState.opencodeClient!==void 0,findRunningLeanRun,gitExec:(args2,cwd)=>_internals44.gitExec(args2,cwd),getGitRepositoryStatus:(cwd)=>_internals44.getGitRepositoryStatus(cwd),countTrackedWorktreeDispatches:()=>standardWorktreeByCallID.size+awaitingMergeByCallID.size,readDelegationsDetailed,listCoderSettlementWalStates,listRecoveryRecords,recoveryReadErrored,scanWorktreeRecoveryAuthoritiesForRecovery,scanWorktreeProvisioningOwnersForRecovery,syncEpicRefs,now:()=>Date.now(),newToken:()=>randomUUID30()}});import*as path197 from"node:path";function parseConfirm(args2){let token=null;for(let i=0;i<args2.length;i+=1){let arg=args2[i];if(arg.toLowerCase().startsWith("--confirm="))token=arg.slice(10).trim();else if(arg.toLowerCase()==="--confirm")token=(args2[i+1]??"").trim(),i+=1;else return{error:`Unknown option(s) for \`/swarm epic prior reset\`: ${arg}.`};if(!token)return{error:"`--confirm` takes the token the preview printed: run `/swarm epic prior reset` first, then `/swarm epic prior reset --confirm=<token>`."}}return{token}}function fmt(value){return(Math.round(value*100)/100).toString()}function statsLines(stats2,settings){let summary=summarizeEpicLearning(stats2,settings.hotExcess,SHOWN),lines=[`- ${summary.files} file statistic(s), ${summary.edges} learned co-write(s).`,"","### Hot files (a task declaring one runs alone)"];if(summary.hotFiles.length===0)lines.push("_None._ A file becomes hot only on excess evidence: at least one full incident (undeclared write, merge conflict, or accumulated Stage B failures / rework / reopens) and an incident rate above the prior mean by more than `hot_excess`. Undeclared writes its strongest learned co-writer explains are discounted (that co-write already keeps the writer apart from the file).");else{for(let file3 of summary.hotFiles.slice(0,SHOWN)){let e=epicHotEvidence(stats2,file3),discount=e.countedAlpha<e.alpha?` (${fmt(e.countedAlpha)} counted after its strongest co-writer)`:"";lines.push(`- \`${file3}\` — incidents ${fmt(e.alpha)}${discount}, exposures ${fmt(e.beta)}, rate ${fmt(e.rate)}`)}if(summary.hotFiles.length>SHOWN)lines.push(`- … +${summary.hotFiles.length-SHOWN} more`)}if(lines.push("","### Learned co-writes (scope expansion — planner analysis only, never write authorization)"),summary.topCoWrites.length===0)lines.push("_None._ Tasks have not written files outside their declared scope.");else{for(let edge of summary.topCoWrites)lines.push(`- \`${edge.from}\` → \`${edge.to}\` (weight ${fmt(edge.weight)}${edge.weight>=1?"":", below 1 — expands only together with other declared files"})`);if(summary.edges>summary.topCoWrites.length)lines.push(`- … +${summary.edges-summary.topCoWrites.length} more`)}return lines}function renderEpicLearning(directory,settings){let lines=["## Epic Mode — Learning",""];if(lines.push(`Settings: ${settings.enabled?"enabled":"**disabled**"}; decay_per_epic ${settings.decayPerEpic}; half_life_days ${settings.halfLifeDays}; hot_excess ${settings.hotExcess} (\`epic.learning.*\`).`),!settings.enabled)return lines.push("","Learning is disabled: epics plan without learned signals and nothing is learned or written."),lines.join(`
|
|
2719
2719
|
`);let epic=null;try{let record3=_internals164.getOpenEpic(directory);epic=record3?{epicKey:record3.epicKey,token:record3.token}:null}catch{epic=null}let view=_internals164.loadEpicLearningView(directory,epic,settings,_internals164.now());return lines.push(`Source: ${SOURCE_TEXT[view.source]}.`,""),lines.push(...statsLines(view.stats,settings)),lines.push("","Learned from the task outcomes `epic_next_wave` records at each wave close; merged into the project prior at `/swarm epic close`; decayed per epic and by age. See `/swarm epic prior`."),lines.join(`
|
|
2720
2720
|
`)}function renderEpicPrior(directory,args2,settings){let sub=(args2[0]??"show").toLowerCase(),flags=args2.slice(1).map((arg)=>arg.toLowerCase());if(sub==="show"){if(flags.length>0)return`Unknown option(s) for \`/swarm epic prior show\`: ${flags.join(", ")}.
|
|
2721
2721
|
|
|
@@ -4358,7 +4358,7 @@ Showing full help:
|
|
|
4358
4358
|
|
|
4359
4359
|
Showing full help:
|
|
4360
4360
|
|
|
4361
|
-
`+fullHelp()}function isCommandFailure(value){return typeof value==="object"&&value!==null&&value.ok===!1}async function handleModeCommandWithBundledSkills(ctx,handler,mechanicalMode){if(ctx.packageRoot)await syncBundledProjectSkillsIfMissingAsync(ctx.directory,ctx.packageRoot,!0);let result=await Promise.resolve(handler(ctx.directory,ctx.args));if(typeof result==="string"&&/^\s*\[MODE:\s*[A-Z][A-Z0-9_-]*\b/.test(result)){if(mechanicalMode)await activatePrWorkflow(ctx.directory,ctx.sessionID,mechanicalMode,{requireCheckoutPreflight:!0})}return result}function resolveCommandForgeContext(directory,prUrl){if(detectForgeFromUrl(prUrl))return;try{let config3=loadPluginConfig(directory),remote=detectGitRemote(directory,void 0);return resolveForgeContextFromPluginConfig(config3,remote?[remote]:[])??void 0}catch{return}}async function handlePrFeedbackCommandWithTransition(ctx){if(ctx.packageRoot)await syncBundledProjectSkillsIfMissingAsync(ctx.directory,ctx.packageRoot,!0);let parsed=parsePrFeedbackCommandInput(ctx.directory,ctx.args);if(parsed.error)return handlePrFeedbackCommand(ctx.directory,ctx.args);if(parsed.continuation){let exactCommand=parsed.prUrl?`/swarm pr-feedback ${parsed.prUrl} continue from ${parsed.continuation.handoffPath}`:`/swarm pr-feedback continue from ${parsed.continuation.handoffPath}`,laneLiveness;try{let config3=loadPluginConfig(ctx.directory),hooks2=config3.hooks;laneLiveness={laneLivenessWatchdog:config3.lane_liveness_watchdog,backgroundPendingTimeoutMs:hooks2?.background_pending_timeout_minutes!==void 0?hooks2.background_pending_timeout_minutes*60000:void 0}}catch{}await transitionPrReviewToFeedback(ctx.directory,ctx.sessionID,{runId:parsed.continuation.runId,handoffPath:parsed.continuation.handoffPath,prUrl:parsed.prUrl,exactCommand,confirmedByUser:!0,...laneLiveness?{laneLiveness}:{}})}else await activatePrWorkflow(ctx.directory,ctx.sessionID,"PR_FEEDBACK",{requireCheckoutPreflight:!0,...parsed.prUrl?{prUrl:parsed.prUrl}:{},...parsed.prUrl?{forge:resolveCommandForgeContext(ctx.directory,parsed.prUrl)}:{}});return handlePrFeedbackCommand(ctx.directory,ctx.args)}function validateAliases(){let errors5=[],warnings=[];for(let[name,entry]of Object.entries(COMMAND_REGISTRY)){let cmdEntry=entry;if(!cmdEntry.handler&&!cmdEntry.aliasOf){errors5.push(`Command '${name}' has no handler and no aliasOf — pure aliases must dereference to a canonical entry`);continue}if(cmdEntry.aliasOf){let target=cmdEntry.aliasOf;if(!Object.hasOwn(COMMAND_REGISTRY,target)){errors5.push(`Alias '${name}' points to non-existent command '${target}'`);continue}let visited=new Set,path287=[],current=target;while(current){let currentEntry=COMMAND_REGISTRY[current];if(!currentEntry)break;if(visited.has(current)){let cycleStart=path287.indexOf(current),fullChain=[name,...path287.slice(0,cycleStart>0?cycleStart:path287.length),current].join(" → ");errors5.push(`Circular alias detected: ${fullChain}`);break}visited.add(current),path287.push(current),current=currentEntry.aliasOf||""}}}return{valid:errors5.length===0,errors:errors5,warnings}}function validateToolPolicy(){let warnings=[];for(let[name,entry]of Object.entries(COMMAND_REGISTRY)){let cmdEntry=entry;if(cmdEntry.aliasOf||cmdEntry.subcommandOf)continue;if(cmdEntry.toolPolicy===void 0)warnings.push(`Command '${name}' has no toolPolicy field — it will not be available through the swarm_command tool. Add toolPolicy: 'agent' | 'human-only' | 'restricted' | 'none'.`)}return{valid:warnings.length===0,warnings}}function resolveCommand(tokens2){if(tokens2.length===0)return null;if(tokens2.length>=3){let compound=`${tokens2[0]} ${tokens2[1]} ${tokens2[2]}`;if(Object.hasOwn(COMMAND_REGISTRY,compound))return{...resolveRegistryEntry(compound),remainingArgs:tokens2.slice(3)}}if(tokens2.length>=2){let compound=`${tokens2[0]} ${tokens2[1]}`;if(Object.hasOwn(COMMAND_REGISTRY,compound))return{...resolveRegistryEntry(compound),remainingArgs:tokens2.slice(2)}}let key2=tokens2[0];if(Object.hasOwn(COMMAND_REGISTRY,key2))return{...resolveRegistryEntry(key2),remainingArgs:tokens2.slice(1)};return null}function resolveRegistryEntry(key2){let entry=COMMAND_REGISTRY[key2],warning=entry.deprecated?`⚠️ "/swarm ${key2}" is deprecated. Use "/swarm ${entry.aliasOf}" instead.`:void 0;while(!entry.handler&&entry.aliasOf){let target=COMMAND_REGISTRY[entry.aliasOf];if(!target)break;entry=target}if(!entry.handler)throw Error(`Command '${key2}' resolves to no handler`);return{entry,key:key2,warning}}var COMMAND_REGISTRY,VALID_COMMANDS,_internals86,validation;var init_registry2=__esm(()=>{init_bundled_skills();init_loader();init_pr_workflow_gate();init_forge_provider();init_logger();init_url_security();init_abort_pr_workflow();init_acknowledge_spec_drift();init_agents();init_approve_plan_critic();init_approve_write();init_archive();init_auto_proceed();init_benchmark();init_checkpoint2();init_ci2();init_ci_monitor();init_ci_simulate();init_close2();init_codebase_review();init_concurrency();init_config4();init_consolidate();init_context_map_stats();init_costs();init_council();init_coupling();init_curate();init_dark_matter();init_dashboard2();init_dataset();init_deep_dive();init_deep_research();init_design_docs();init_diagnose();init_doctor();init_epic();init_evidence();init_export();init_full_auto();init_gate_audit2();init_gate_stats2();init_handoff();init_harness();init_harness_opt();init_history();init_hive_quarantine2();init_issue();init_knowledge();init_lanes();init_learning2();init_link();init_loop();init_memory2();init_memory_link2();init_plan();init_post_mortem();init_pr_feedback();init_pr_feedback_loop2();init_pr_monitor_status();init_pr_review();init_pr_subscribe();init_pr_unsubscribe();init_preflight();init_promote();init_qa_gates();init_recover();init_report();init_reset();init_reset_session();init_retrieve();init_review();init_rollback();init_sdd();init_simulate();init_skill_opt();init_status();init_sync_plan();init_turbo();init_unlink();init_write_retro2();COMMAND_REGISTRY={"blueprint validate":{handler:(ctx)=>handleBlueprintValidateCommand(ctx.directory,ctx.args,{config:ctx.config}),description:"Validate a declarative harness blueprint or atomic blueprint patch",args:"<project-relative-json>",category:"utility",toolPolicy:"none"},"blueprint current":{handler:(ctx)=>handleBlueprintCurrentCommand(ctx.directory,ctx.agents,{config:ctx.config}),description:"Show the ledger-derived current harness blueprint projection",args:"",category:"utility",toolPolicy:"none"},"blueprint history":{handler:(ctx)=>handleBlueprintHistoryCommand(ctx.directory,ctx.args,{config:ctx.config}),description:"Show bounded hash-verified harness version history",args:"[--limit <1..100>]",category:"utility",toolPolicy:"none"},"blueprint diff":{handler:(ctx)=>handleBlueprintDiffCommand(ctx.directory,ctx.args,{config:ctx.config}),description:"Compare two stored harness blueprint versions",args:"<from-version> <to-version>",category:"utility",toolPolicy:"none"},"blueprint export":{handler:(ctx)=>handleBlueprintExportCommand(ctx.directory,ctx.args,{config:ctx.config}),description:"Export a canonical stored harness blueprint",args:"[version]",category:"utility",toolPolicy:"none"},"harness candidate validate":{handler:(ctx)=>handleHarnessCandidateValidateCommand(ctx.directory,ctx.args,{config:ctx.config}),description:"Validate an inert harness candidate manifest",args:"<project-relative-json>",category:"utility",toolPolicy:"none"},"harness candidate show":{handler:(ctx)=>handleHarnessCandidateShowCommand(ctx.directory,ctx.args,{config:ctx.config}),description:"Show bounded harness candidate metadata without raw patch content",args:"<candidate-id>",category:"utility",toolPolicy:"none"},"harness candidate diff":{handler:(ctx)=>handleHarnessCandidateDiffCommand(ctx.directory,ctx.args,{config:ctx.config}),description:"Show candidate file and blueprint-change metadata without raw patch content",args:"<candidate-id>",category:"utility",toolPolicy:"none"},"blueprint-validate":{description:"TUI shortcut alias for blueprint validate",category:"utility",aliasOf:"blueprint validate",deprecated:!0},"blueprint-current":{description:"TUI shortcut alias for blueprint current",category:"utility",aliasOf:"blueprint current",deprecated:!0},"blueprint-history":{description:"TUI shortcut alias for blueprint history",category:"utility",aliasOf:"blueprint history",deprecated:!0},"blueprint-diff":{description:"TUI shortcut alias for blueprint diff",category:"utility",aliasOf:"blueprint diff",deprecated:!0},"blueprint-export":{description:"TUI shortcut alias for blueprint export",category:"utility",aliasOf:"blueprint export",deprecated:!0},"harness-candidate-validate":{description:"TUI shortcut alias for harness candidate validate",category:"utility",aliasOf:"harness candidate validate",deprecated:!0},"harness-candidate-show":{description:"TUI shortcut alias for harness candidate show",category:"utility",aliasOf:"harness candidate show",deprecated:!0},"harness-candidate-diff":{description:"TUI shortcut alias for harness candidate diff",category:"utility",aliasOf:"harness candidate diff",deprecated:!0},"acknowledge-spec-drift":{handler:(ctx)=>handleAcknowledgeSpecDriftCommand(ctx.directory,ctx.args,ctx.source==="cli"?"cli":ctx.source==="chat"?"user":"unknown"),description:"Acknowledge that the spec has drifted from the plan and suppress further warnings",args:"",category:"diagnostics",toolPolicy:"restricted"},"approve-write":{handler:(ctx)=>handleApproveWriteCommand(ctx.directory,ctx.args,ctx.sessionID),description:"Issue a one-shot session/action/candidate/hash-bound write approval",args:"<target-session-id> skill_improve <candidate-id> <candidate-content-hash> [--generation <n>] [--allowed-path-digest <sha256>]",category:"utility",toolPolicy:"human-only"},status:{handler:async(ctx)=>handleStatusCommand(ctx.directory,ctx.agents,ctx.sessionID),description:"Show current swarm state (plus background-work health when hooks.background_subagents is enabled)",category:"core",clashesWithNativeCcCommand:"/status",toolPolicy:"agent",toolNoArgs:!0},"context-map stats":{handler:async(ctx)=>handleContextMapStatsCommand(ctx.directory),description:"Show aggregated context-capsule telemetry stats",category:"diagnostics",toolPolicy:"agent",toolNoArgs:!0},"context-map-stats":{description:"Show aggregated context-capsule telemetry stats",category:"diagnostics",aliasOf:"context-map stats",deprecated:!0},"show-plan":{handler:(ctx)=>handlePlanCommand(ctx.directory,ctx.args),description:"Show current plan (optionally filter by phase number)",category:"core",args:"[phase-number]",toolPolicy:"agent"},plan:{description:"Show current plan (deprecated alias for /swarm show-plan)",category:"core",clashesWithNativeCcCommand:"/plan",aliasOf:"show-plan",deprecated:!0},agents:{handler:(ctx)=>Promise.resolve(handleAgentsCommand(ctx.agents,void 0)),description:"List registered agents",category:"core",clashesWithNativeCcCommand:"/agents",toolPolicy:"agent",toolNoArgs:!0},help:{handler:(ctx)=>_internals86.handleHelpCommand(ctx),description:"Show help for swarm commands",category:"core",args:"[command]",details:"Without argument, shows full command listing. With argument, shows detailed help for a specific command.",toolPolicy:"agent"},history:{handler:(ctx)=>handleHistoryCommand(ctx.directory,ctx.args),description:"Show completed phases summary",category:"utility",clashesWithNativeCcCommand:"/history",toolPolicy:"agent",toolNoArgs:!0},config:{handler:(ctx)=>handleConfigCommand(ctx.directory,ctx.args),description:"Show current resolved configuration",category:"config",clashesWithNativeCcCommand:"/config",toolPolicy:"agent",toolNoArgs:!0},"config doctor":{handler:(ctx)=>handleDoctorCommand(ctx.directory,ctx.args),description:"Run config doctor checks",subcommandOf:"config",category:"diagnostics",toolPolicy:"agent",toolNoArgs:!0},"config-doctor":{description:"Run config doctor checks",subcommandOf:"config",category:"diagnostics",aliasOf:"config doctor",deprecated:!0},"doctor tools":{handler:(ctx)=>handleDoctorToolsCommand(ctx.directory,ctx.args),description:"Run tool registration coherence check",category:"diagnostics",toolPolicy:"agent",toolNoArgs:!0},"doctor-tools":{description:"Run tool registration coherence check",category:"diagnostics",aliasOf:"doctor tools",deprecated:!0},diagnose:{handler:(ctx)=>handleDiagnoseCommand(ctx.directory,ctx.args,ctx.sessionID),description:"Run health check on swarm state",category:"diagnostics",toolPolicy:"agent",toolNoArgs:!0},diagnosis:{description:"Run health check on swarm state",category:"diagnostics",aliasOf:"diagnose",deprecated:!0},"guardrail explain":{handler:async(ctx)=>{let{handleGuardrailExplain:handleGuardrailExplain2}=await Promise.resolve().then(() => (init_guardrail_explain(),exports_guardrail_explain));return handleGuardrailExplain2(ctx.directory,ctx.args)},description:"Dry-run: show what the guardrails would do to a command or write target (executes nothing)",category:"diagnostics",toolPolicy:"agent",toolNoArgs:!1},"guardrail reset":{handler:async(ctx)=>{let{handleGuardrailReset:handleGuardrailReset2}=await Promise.resolve().then(() => (init_guardrail_reset(),exports_guardrail_reset));return handleGuardrailReset2(ctx.args,ctx.sessionID)},description:"Reset one exact active invocation/action circuit after repair",category:"diagnostics",toolPolicy:"agent"},"guardrail-explain":{description:"Dry-run: show what the guardrails would do to a command or write target (executes nothing)",category:"diagnostics",aliasOf:"guardrail explain",deprecated:!0},"guardrail-reset":{description:"Reset one exact active invocation/action circuit after repair",category:"diagnostics",aliasOf:"guardrail reset",deprecated:!0},"guardrail-log":{handler:async(ctx)=>{let{handleGuardrailLog:handleGuardrailLog2}=await Promise.resolve().then(() => (init_guardrail_log(),exports_guardrail_log));return handleGuardrailLog2(ctx.directory,ctx.args)},description:"Read the guardrail decision log (use --blocks-only for blocks)",category:"diagnostics",toolPolicy:"agent",toolNoArgs:!1},preflight:{handler:(ctx)=>handlePreflightCommand(ctx.directory,ctx.args),description:"Run preflight automation checks",category:"diagnostics",toolPolicy:"agent",toolNoArgs:!0},lanes:{handler:(ctx)=>Promise.resolve(handleLanesCommand(ctx.directory,ctx.args)),description:"List active, awaiting-merge, and conflicted worktree lanes",category:"diagnostics",toolPolicy:"agent",toolNoArgs:!0},"sync-plan":{handler:(ctx)=>handleSyncPlanCommand(ctx.directory,ctx.args),description:"Ensure plan.json and plan.md are synced",args:"",category:"config",toolPolicy:"agent",toolNoArgs:!0},benchmark:{handler:(ctx)=>handleBenchmarkCommand(ctx.directory,ctx.args),description:"Show performance metrics [--cumulative] [--ci-gate] [--max-cost-usd <n>] [--gate-audit-run <id>]",args:"--cumulative, --ci-gate, --max-cost-usd <n>, --gate-audit-run <id>",details:"Exit codes (#2493 review F-14): with --ci-gate, the process exits 0 only when every quality check passes and 1 on any failure, budget breach, or missing evidence — CI-safe by construction. Without --ci-gate the command is informational and always exits 0.",category:"diagnostics",toolPolicy:"agent"},"gate-audit":{handler:(ctx)=>handleGateAuditCommand(ctx.directory,ctx.args,{packageRoot:ctx.packageRoot,dispatcher:ctx.evaluationModelDispatcher,parentSessionId:ctx.sessionID}),description:"Run the bounded Tier-1 reviewer/test/SAST/mutation/quality gate matrix",args:"--model <id>, --swarm <id>, --gates <csv>, --tasks <csv>, --runs <n>, --max-concurrency <n>, --max-retries <n>, --max-time-ms <n>, --max-cost-usd <n>, --seed <value>, --run-id <id>, --json",details:"Runs immutable curated defects only in disposable copies, records unavailable data honestly, and writes versioned results below .swarm/evidence/gate-audit/. Container tasks are unsupported until a safe array-form runner exists.",category:"diagnostics",toolPolicy:"agent"},"gate-stats":{handler:(ctx)=>handleGateStatsCommand(ctx.directory,ctx.args),description:"Show offline per-model gate catch, false-reject, retry, cost, and reviewer fallback statistics",args:"--json, --min-samples <n>",category:"diagnostics",toolPolicy:"agent"},"skill-opt":{handler:(ctx)=>handleSkillOptPlan(ctx.directory,ctx.args,{config:ctx.config?.skill_opt,dispatcher:ctx.evaluationModelDispatcher,parentSessionId:ctx.sessionID}),description:"Governed single-skill optimizer (issue #1822). Proposes, validates, and activates one allowlisted SKILL.md candidate at a time with durable lifecycle, serial control, and manual approval.",args:"plan|run|status|diff|approve|reject|rollback|history <slug> [candidateId] [--json] [--confirm] [--expected-content-hash <hash>] [--models <csv>] [--dry-run]",details:"Disabled/proposal-only by default. `run` requires skill_opt.enabled=true AND --confirm (consumes a held-out test set). approve/activate/reject/rollback are human-only and require --expected-content-hash to refuse a stale base. Stores append-only lifecycle under .swarm/evolution/skills/<slug>/<candidateId>/.",category:"utility",toolPolicy:"agent"},"skill-opt plan":{handler:(ctx)=>handleSkillOptPlan(ctx.directory,ctx.args,{config:ctx.config?.skill_opt,dispatcher:ctx.evaluationModelDispatcher,parentSessionId:ctx.sessionID}),description:"Propose an optimization round (dry-run; no mutation, no validation)",subcommandOf:"skill-opt",args:"<slug> [--json] [--models <csv>]",category:"utility",toolPolicy:"agent"},"skill-opt run":{handler:(ctx)=>handleSkillOptRun(ctx.directory,ctx.args,{config:ctx.config?.skill_opt,dispatcher:ctx.evaluationModelDispatcher,parentSessionId:ctx.sessionID}),description:"Execute the optimization loop (draft→smoke→validate; held-out set is single-use so at most one validation per run). Requires skill_opt.enabled=true and --confirm.",subcommandOf:"skill-opt",args:"<slug> --confirm [--json] [--models <csv>]",category:"utility",toolPolicy:"human-only"},"skill-opt status":{handler:(ctx)=>handleSkillOptStatus(ctx.directory,ctx.args),description:"Show the current candidate lifecycle state",subcommandOf:"skill-opt",args:"<slug> <candidateId> [--json]",category:"utility",toolPolicy:"agent"},"skill-opt diff":{handler:(ctx)=>handleSkillOptDiff(ctx.directory,ctx.args),description:"Show baseline-vs-candidate diff summary for a candidate",subcommandOf:"skill-opt",args:"<slug> <candidateId> [--json]",category:"utility",toolPolicy:"agent"},"skill-opt approve":{handler:(ctx)=>handleSkillOptApprove(ctx.directory,ctx.args),description:"Activate a pending candidate (human-only; requires --expected-content-hash)",subcommandOf:"skill-opt",args:"<slug> <candidateId> --expected-content-hash <hash> [--json]",category:"utility",toolPolicy:"human-only"},"skill-opt reject":{handler:(ctx)=>handleSkillOptReject(ctx.directory,ctx.args),description:"Record a rejection for a candidate (no active-skill mutation)",subcommandOf:"skill-opt",args:"<slug> <candidateId> [--json]",category:"utility",toolPolicy:"human-only"},"skill-opt rollback":{handler:(ctx)=>handleSkillOptRollback(ctx.directory,ctx.args),description:"Restore the pre-activation snapshot (appends a rolled_back event)",subcommandOf:"skill-opt",args:"<slug> <candidateId> [--json]",category:"utility",toolPolicy:"human-only"},"skill-opt history":{handler:(ctx)=>handleSkillOptHistory(ctx.directory,ctx.args),description:"Show the append-only lifecycle event log for a candidate",subcommandOf:"skill-opt",args:"<slug> <candidateId> [--json]",category:"utility",toolPolicy:"agent"},"harness-opt":{handler:(ctx)=>handleHarnessOptPlan(ctx.directory,ctx.args,{parentSessionId:ctx.sessionID}),description:"Governed HarnessOpt capstone (issue #2503). Freezes the comparative task set and drives isolated, approved, reversible optimization rounds through the evaluation substrate.",args:"plan|run|status|stop|history [--tasks <json>] [--split train|validation|test] [--seed <s>] [--confirm] [--json] [--reason <text>]",details:"Disabled by default. `run` requires harness_opt.enabled=true AND --confirm, executes one governed round in a disposable worktree (a test split consumes the held-out set exactly once, substrate-enforced), and records durable lineage with task-cost accounting (unknown-not-zero). Activation/rollback stay on /swarm approve-write + the harness store; the controller never mutates the live harness.",category:"utility",toolPolicy:"agent"},"harness-opt plan":{handler:(ctx)=>handleHarnessOptPlan(ctx.directory,ctx.args,{parentSessionId:ctx.sessionID}),description:"Freeze the comparative task set and report loop status (dry-run)",subcommandOf:"harness-opt",args:"--tasks <json> [--split train|validation|test] [--seed <s>] [--json]",category:"utility",toolPolicy:"agent"},"harness-opt run":{handler:(ctx)=>handleHarnessOptRun(ctx.directory,ctx.args,{config:ctx.config?.harness_opt,dispatcher:ctx.evaluationModelDispatcher,parentSessionId:ctx.sessionID}),description:"Execute ONE governed optimization round in a disposable worktree. Requires harness_opt.enabled=true and --confirm; a test split consumes the held-out set exactly once.",subcommandOf:"harness-opt",args:"--tasks <json> --confirm [--split train|validation|test] [--seed <s>] [--json]",category:"utility",toolPolicy:"human-only"},"harness-opt status":{handler:(ctx)=>handleHarnessOptStatus(ctx.directory,ctx.args),description:"Show loop status and the latest round lineage summary",subcommandOf:"harness-opt",args:"[--json]",category:"utility",toolPolicy:"agent"},"harness-opt stop":{handler:(ctx)=>handleHarnessOptStop(ctx.directory,ctx.args),description:"Human-only operator stop: halt governed rounds with a recorded reason",subcommandOf:"harness-opt",args:"[--reason <text>] [--json]",category:"utility",toolPolicy:"human-only"},"harness-opt compare":{handler:(ctx)=>handleHarnessOptCompare(ctx.directory,ctx.args,{config:ctx.config?.harness_opt,dispatcher:ctx.evaluationModelDispatcher,parentSessionId:ctx.sessionID}),description:"Separately executable comparative evaluation (issue #2503): baseline, ablation, and simple-agent arms on one frozen task population with an independently validated manifest, the independent oracle verdict, and a retained pilot-graduation record.",subcommandOf:"harness-opt",args:"--tasks <json> --confirm [--manifest <json>] [--seed <s>] [--lower-ci <n>] [--json]",category:"utility",toolPolicy:"human-only"},"harness-opt history":{handler:(ctx)=>handleHarnessOptHistory(ctx.directory,ctx.args),description:"List durable round lineage records (bounded to the last 20)",subcommandOf:"harness-opt",args:"[--json]",category:"utility",toolPolicy:"agent"},review:{handler:handleReviewCommand,description:"Run the independent review model against a selected Git diff",args:"--base <ref>, --range <from..to|from...to>, --working-tree, --json",details:"Collects one bounded canonical diff, dispatches the configured reviewer in a fresh read-only session, optionally validates eligible HIGH/CRITICAL findings when configured or required by gate mode, and persists the receipt and evidence. With no selector, reviews the default merge-base plus working-tree scope.",category:"diagnostics",toolPolicy:"human-only"},costs:{handler:(ctx)=>handleCostsCommand(ctx.directory,ctx.args),description:"Show per-agent and per-task token/cost telemetry [--json]",args:"--json",category:"diagnostics",toolPolicy:"agent"},report:{handler:(ctx)=>handleReportCommand(ctx.directory,ctx.args),description:"Report swarm observability events from the SQLite query authority [--task <id>] [--session <id>] [--trace <id>] [--run <batchId>] [--since <ISO-8601>] [--json]",args:"--task <id>, --session <id>, --trace <id>, --run <batchId>, --since <ISO-8601>, --json",details:"Bounded, deterministic query over the observability events store in .swarm/swarm.db (the first run performs a bounded, idempotent legacy-import into the local sink). --run filters the lane/dispatch batch axis (workflow.batchId). Unmatched delegation begins are disclosed, never fabricated into ends. Includes a Task attempts (cohort) section (issue #2676): execution-attempt records folded through a snapshot-qualified cohort with per-class counts, known/unavailable cost split, uncertainty, and an explicit causal-rate qualification line. --json emits a schemaVersion-tagged block (schema v2 adds the taskAttempts cohort field).",category:"diagnostics",toolPolicy:"agent"},dashboard:{handler:(ctx)=>handleDashboardCommand(ctx.directory,ctx.args),description:"Show the opt-in local mission-control dashboard URL and status (issue #2509)",details:"Read-only status for the opt-in loopback dashboard over durable swarm state (gates & circuits, delegation age bands, lane liveness, task board, activity timeline). Disabled by default; enable with dashboard.port > 0 in opencode-swarm.json. Never starts or stops the listener — lifecycle belongs to plugin init; the dashboard itself performs no mutations.",category:"diagnostics",toolPolicy:"agent"},learning:{handler:(ctx)=>handleLearningCommand(ctx.directory,ctx.args),description:"Show learning metrics and violation trends",args:"--json, --phase <N>",details:"Computes aggregate learning metrics from knowledge events: violation-rate trends, directive application rates, escalation frequency, per-entry ROI, and never-applied entries. Surfaces a learning summary for the curator digest.",category:"diagnostics",toolPolicy:"agent"},export:{handler:(ctx)=>handleExportCommand(ctx.directory,ctx.args),description:"Export plan and context as JSON",args:"",details:"Exports the current plan and context as JSON to stdout. Useful for piping to external tools or debugging swarm state.",category:"utility",clashesWithNativeCcCommand:"/export",toolPolicy:"agent",toolNoArgs:!0},"dataset consent":{handler:(ctx)=>handleDatasetConsentCommand(ctx.directory,ctx.args),description:"Human-only grant/revoke of the training-content consent record (two-step confirm token)",args:"[--confirm=<token>] [--revoke] [--max-bytes N] [--max-records N] [--retention-days N]",details:"Issue #2486 (D7). Training-content capture is OFF by default and cannot be enabled by config, env, agents, or tools — only by this durable, project-bound consent record under .swarm/training/v1/consent.json. Bare invocation prints the consent terms (purpose, content classes, redaction, hard quota ceilings) and issues a 15-minute confirmation token; --confirm=<token> writes the grant (quotas clamp to the ceilings, never above); --revoke stops capture immediately (physical deletion is /swarm dataset withdraw).",category:"utility",toolPolicy:"human-only"},"dataset withdraw":{handler:(ctx)=>handleDatasetWithdrawCommand(ctx.directory,ctx.args),description:"Human-only destructive withdrawal: purge vault content, tombstone, revoke exports",args:"[--confirm=<token>]",details:"Issue #2486 (D7). Preview-first: the bare command shows exactly what would be deleted (records, bytes, exports to revoke) and issues a 15-minute confirmation token. --confirm=<token> physically empties the vault records file, appends a durable withdrawal tombstone (never deleted by any later operation), writes REVOKED.json revocation manifests into every export still under plugin control, and marks the consent withdrawn.",category:"utility",toolPolicy:"human-only"},"dataset export":{handler:(ctx)=>handleDatasetExportCommand(ctx.directory,ctx.args),description:"Human-only governed dataset export (deterministic bundle + manifest, two-step confirm token)",args:"[--kind <k>[,<k>]] [--session <id>] [--task <id>] [--since <ISO>] [--validation-ratio <0..0.5>] [--confirm=<token>]",details:"Issue #2486 (D7). Side-effect-free preview by default: export id, record counts (train/validation split, quarantined excluded), estimated size, destination, and a 15-minute confirmation token. --confirm=<token> writes the deterministic bundle (records.jsonl, train.jsonl, validation.jsonl, manifest.json with sha256 checksums, schema version, echoed filters, and a session-coherent split) under .swarm/training/v1/exports/<export-id>/; identical re-exports are idempotent. The existing /swarm export (plan+context JSON) is unchanged.",category:"utility",toolPolicy:"human-only"},"dataset-consent":{description:"Human-only grant/revoke of the training-content consent record (two-step confirm token)",aliasOf:"dataset consent",deprecated:!0},"dataset-withdraw":{description:"Human-only destructive withdrawal: purge vault content, tombstone, revoke exports",aliasOf:"dataset withdraw",deprecated:!0},"dataset-export":{description:"Human-only governed dataset export (deterministic bundle + manifest, two-step confirm token)",aliasOf:"dataset export",deprecated:!0},evidence:{handler:(ctx)=>handleEvidenceCommand(ctx.directory,ctx.args),description:"Show evidence bundles [taskId]",args:"<taskId>",details:'Displays review results, test verdicts, and other evidence bundles for the given task ID (e.g., "2.1").',category:"utility",toolPolicy:"agent"},"evidence summary":{handler:(ctx)=>handleEvidenceSummaryCommand(ctx.directory),description:"Generate evidence summary with completion ratio and blockers",subcommandOf:"evidence",args:"",details:"Generates a summary showing completion ratio across all tasks, lists blockers, and identifies missing evidence.",category:"utility",toolPolicy:"agent",toolNoArgs:!0},"evidence-summary":{description:"Generate evidence summary with completion ratio and blockers",subcommandOf:"evidence",args:"",details:"Generates a summary showing completion ratio across all tasks, lists blockers, and identifies missing evidence.",category:"utility",aliasOf:"evidence summary",deprecated:!0},doctor:{description:"Run config doctor checks",category:"diagnostics",aliasOf:"config doctor",deprecated:!0,clashesWithNativeCcCommand:"/doctor"},info:{description:"Show current swarm state (plus background-work health when hooks.background_subagents is enabled)",category:"core",aliasOf:"status",deprecated:!0},"list-agents":{description:"List registered agents",category:"core",aliasOf:"agents",deprecated:!0},health:{description:"Run health check on swarm state",category:"diagnostics",aliasOf:"diagnose",deprecated:!0},check:{description:"Run preflight automation checks",category:"diagnostics",aliasOf:"preflight",deprecated:!0},clear:{description:"Clear session state while preserving plan, evidence, and knowledge",category:"utility",aliasOf:"reset-session",deprecated:!0},archive:{handler:(ctx)=>handleArchiveCommand(ctx.directory,ctx.args),description:"Archive old evidence bundles [--dry-run]",details:"Archives evidence bundles older than max_age_days (config, default 90) or beyond max_bundles cap (config, default 1000). --dry-run previews which bundles would be archived without deleting them. Applies two-tier retention: age-based first, then count-based on oldest remaining.",args:"--dry-run",category:"utility",toolPolicy:"none"},curate:{handler:(ctx)=>handleCurateCommand(ctx.directory,ctx.args,{sessionID:ctx.sessionID}),description:"Run knowledge curation and hive promotion review",args:"",category:"utility",toolPolicy:"none"},consolidate:{handler:(ctx)=>handleConsolidateCommand(ctx.directory,ctx.args,{sessionID:ctx.sessionID}),description:"Run quota-bounded skill-improver consolidation and stage skill proposals",details:"Runs the same consolidation pass used by scheduled skill_improver trigger points: queue hardening, skill-improver proposal writing, and optional draft-skill generation. It never auto-activates skills. Use --respect-interval to obey the configured cadence instead of forcing a run.",args:"--force, --respect-interval, --evaluate",category:"utility",toolPolicy:"restricted"},coupling:{handler:(ctx)=>handleCouplingCommand(ctx.directory,ctx.args),description:"Measure plan coupling (p) and rank modules driving conflicts (Epic mode preview)",details:"Computes the coupling coefficient p = (conflicting task pairs) / (total task pairs) over the current plan, using Epic mode's combined path + co-change conflict signal. Surfaces per-module contention and a ranked decoupling roadmap. Declared scopes come from live `declare_scope` bindings (falling back to plan `files_touched`). Read-only and usable without Epic Mode on, but the co-change signal is included only when `epic.cochange.enabled` is true — otherwise p reflects path conflicts only and the report says the signal is disabled by config. `--suggest` adds Epic plan shaping for the whole plan (the advisory save_plan returns as `epic_shaping` when Epic is on): the plan's epic sizing and up to 5 suggestions — scope advice (declare-scope, narrow-scope) first, then by their effective-speedup gain: extract-prerequisite, isolate-hot-file, split-task, merge-tasks, each with a concrete save_plan patch. Read-only; bounded by a work budget (skipped-budget beyond it).",args:"--phase <n>, --threshold <-1..1>, --min-co-changes <n>, --format markdown|json, --persist, --suggest",category:"diagnostics",toolPolicy:"none"},epic:{handler:(ctx)=>handleEpicCommand(ctx.directory,ctx.args,ctx.sessionID),description:"Open, inspect, and close a plan-scoped epic (coupling-aware parallel execution of the current plan)",details:"An epic is bound to ONE plan: `start` opens it for the current plan, `close` ends it. Requires `epic.mode.enabled: true` in config (top-level `epic` block; no `turbo` block needed — the legacy `turbo.epic` path is still accepted and migrated). `start [--force]` refuses, in order: epic-disabled-by-config, host-unsupported (the host gives the plugin no OpenCode SDK client — OpenCode 2 does not yet — so worktree-isolated coders and the phase review cannot run), no-plan / plan-ledger-unreadable, epic-already-open (idempotent for the same plan) / epic-open-for-other-plan, turbo-active (config turbo_mode, a session with Turbo on, or a running Lean run — Epic enables neither Lean nor Turbo and never waives per-task QA), dirty-baseline (git: uncommitted changes outside .swarm/), detached-head / epic-branch-exists (epic-branch policy), in-flight-coders (any coder dispatch, background delegation, unsettled settlement, or preserved/recovery lane), not-epic-sized (too few pending tasks, insufficient scope coverage, or insufficient effective speedup — run it in Balanced, or reshape it with the plan-shaping suggestions shown; `--force` overrides and is recorded). Non-git projects run an epic serially (one task per wave). Git epics default to `epic.commit_policy: \"epic-branch\"`: start checks out `swarm/epic/<epicKey>` and every Epic commit goes there (epic_next_wave blocks with epic-branch-mismatch, and no landing or residue is committed, while HEAD is elsewhere); `current-branch` keeps commits on the starting branch. In a git epic every coder runs in an isolated worktree (refused EPIC_ISOLATION_DEGRADED when isolation is unavailable) and lands as a `swarm(task <id>): …` merge commit; main-tree files a non-coder writer (test_engineer, docs) wrote for a task are committed as residue of that task; update_task_status writes nothing to git; wave close records the commit of each task as `refs/swarm/epics/<epicKey>/tasks/<id>` (deleted at close unless `epic.retain_refs`; never pushed by default). While open, the architect calls epic_next_wave and does what its status says: it issues one wave at a time (tasks with non-conflicting declared scopes — exclusive tasks alone, at most one task per densely coupled component; phases strictly in order), the architect dispatches one Task per taskId in ONE message and runs per-task QA (pre_check_batch → reviewer + test_engineer → update_task_status(completed)), and the next epic_next_wave closes the wave (recording outcomes and declared-vs-actual divergence) and issues the next; when a phase is done it returns phase-ready-for-review → epic_phase_review → phase_complete. `close [--abandon] [--land squash|merge|none]` refuses while tasks are pending (or the epic is orphaned / unreadable) unless `--abandon`, refuses a dirty tree before landing, writes a close report (epic-report-v2, embedding the epic scorecard) to .swarm/epic/reports/ and .swarm/epic-prior/reports/ (newest 50 kept), and lands the epic branch onto the original branch: squash (default — staged, uncommitted changes for you to review and commit), merge (a --no-ff merge commit), or none (switch back only). The epic branch is kept (remove it with `git branch -D` once committed). A landing conflict is rolled back (the attempted squash or merge is undone) and the epic stays closing — rerun close to resume. `--abandon` never lands; it switches back to the original branch when the tree is clean. `status [--repair-refs]` (also bare /swarm epic) shows the epic, its waves, phases, the task components recorded with the latest wave and recorded divergence, orphan detection (plan renamed or replaced), sentinel/row repair, recorded worktree merge failures, and retires legacy Epic v1 session state once; `--repair-refs` re-adopts task commits a rebase or amend made unreachable from HEAD. `report [<key>|last] [--format json]` shows the epic scorecard: live for the open epic (bare `report`), else from the close report of a past epic in .swarm/epic-prior/reports/ (`last` = newest; `<key>` = a report or epic key) — tasks completed in the epic, waves (count, width), time over closed waves (wave span, task issue→resolve time, and their ratio, a concurrency factor that is NOT a speedup: it includes queueing behind serialized QA), conflicts (merge-back failures, undeclared writes), rework (extra generations, reopens), first-pass gate rates (upper bounds: the failure history is bounded), forced/sizing at start and learned hot files. Epics learn from their outcomes: undeclared writes teach learned co-writes (a task declaring D that also wrote f makes later tasks declaring D conflict with tasks on f — planner analysis only, never write authorization) and incidents (undeclared writes, merge conflicts, Stage B failures, rework, reopens) in excess of clean exposures make a file hot (a task declaring it runs alone) — undeclared writes its strongest learned co-writer explains are discounted (expansion already separates them), so one declarer writing a file is not heat; an empty history learns nothing (neutral start). Each wave close updates the posterior of the epic; close merges it into the project prior .swarm/epic-prior/learning.json (decayed per epic and by age; kept across /swarm close; `epic.learning.*`). `learning` shows what the planner learned and uses now; `prior [show]` shows the project prior; `prior reset` previews and prints a single-use confirm token (15 minutes); `prior reset --confirm=<token>` clears it. Also: clear-merge-failure <taskId> [--confirm]. The former `on` / `off` toggles, the `decide` / `last` subcommands and `calibration` (renamed `learning`) were removed.",args:"start [--force] | close [--abandon] [--land squash|merge|none] | status [--repair-refs] | report [<key>|last] [--format json] | learning | prior [show|reset [--confirm=<token>]] | clear-merge-failure <taskId> [--confirm]",category:"diagnostics",toolPolicy:"human-only"},"dark-matter":{handler:(ctx)=>handleDarkMatterCommand(ctx.directory,ctx.args),description:"Detect hidden file couplings via co-change NPMI analysis",args:"--threshold <number>, --min-commits <number>",category:"diagnostics",toolPolicy:"none"},finalize:{handler:(ctx)=>handleCloseCommand(ctx.directory,ctx.args,{sessionID:ctx.sessionID}),description:"Use /swarm finalize to finalize the swarm project and archive evidence",details:"Idempotent 4-stage terminal finalization: (1) finalize writes retrospectives for in-progress phases, (2) archive creates timestamped bundle of swarm artifacts and evidence, (3) clean removes active-state files for a clean slate, (4) align performs aggressive git reset --hard to the default remote branch, discarding uncommitted changes and gitignored build artifacts (user-created untracked files are preserved); falls back to a cautious reset that preserves uncommitted changes when the aggressive path cannot proceed. Alignment re-verifies the tracked tree immediately before its destructive reset and aborts fail-closed (leaving alignment undone) when tracked files changed after the close gate was verified or the status cannot be re-read (#2953). WARNING: alignment discards local changes and gitignored files. Resets agent sessions, delegation chains, and active-agent mappings. Reads .swarm/close-lessons.md for explicit lessons and runs curation. Cleanup: knowledge.jsonl is preserved; plan.json, plan.md, events.jsonl, handoff.*, run-memory.jsonl, and summaries/ are removed. An open epic (Epic Mode) is first closed as abandoned-by-swarm-close (it never lands; its close report is archived); .swarm/epic/ is cleaned, while .swarm/epic-prior/ (learning prior and past epic reports) is preserved. Use --skill-review to run the quota-bounded skill_improver in proposal mode. Use --dry-run to preview what finalize would archive, clean, and align without taking the lock or changing anything.",args:"--prune-branches, --skill-review, --dry-run",category:"core",toolPolicy:"none"},close:{description:"Use /swarm close (deprecated alias) to finalize and archive swarm state",details:"Deprecated alias for /swarm finalize. Preserved for backward compatibility. Supports the same flags, including --dry-run.",args:"--prune-branches, --skill-review, --dry-run",category:"core",aliasOf:"finalize",deprecated:!0},"post-mortem":{handler:(ctx)=>handlePostMortemCommand(ctx.directory,ctx.args,{sessionID:ctx.sessionID}),description:"Run the post-mortem agent: project-end synthesis, queue triage, and final curation pass",details:"Reads .swarm/ evidence (knowledge entries, events, curator digests, proposals, retrospectives, drift reports) and produces a post-mortem report at .swarm/post-mortem-{planId}.md. Idempotent: re-runs skip if report exists unless --force is passed. Use --scope session to limit knowledge event aggregation to the current session; project scope is the default.",args:"--force, --scope session|project",category:"core",toolPolicy:"agent"},concurrency:{handler:(ctx)=>handleConcurrencyCommand(ctx.directory,ctx.args,ctx.sessionID),description:"Manage runtime concurrency override for plan execution [set|status|reset]",args:"set <N|preset>, status, reset",details:`Sets, queries, or clears a session-scoped concurrency override for max_concurrent_tasks during plan execution.
|
|
4361
|
+
`+fullHelp()}function isCommandFailure(value){return typeof value==="object"&&value!==null&&value.ok===!1}async function handleModeCommandWithBundledSkills(ctx,handler,mechanicalMode){if(ctx.packageRoot)await syncBundledProjectSkillsIfMissingAsync(ctx.directory,ctx.packageRoot,!0);let result=await Promise.resolve(handler(ctx.directory,ctx.args));if(typeof result==="string"&&/^\s*\[MODE:\s*[A-Z][A-Z0-9_-]*\b/.test(result)){if(mechanicalMode)await activatePrWorkflow(ctx.directory,ctx.sessionID,mechanicalMode,{requireCheckoutPreflight:!0})}return result}function resolveCommandForgeContext(directory,prUrl){if(detectForgeFromUrl(prUrl))return;try{let config3=loadPluginConfig(directory),remote=detectGitRemote(directory,void 0);return resolveForgeContextFromPluginConfig(config3,remote?[remote]:[])??void 0}catch{return}}async function handlePrFeedbackCommandWithTransition(ctx){if(ctx.packageRoot)await syncBundledProjectSkillsIfMissingAsync(ctx.directory,ctx.packageRoot,!0);let parsed=parsePrFeedbackCommandInput(ctx.directory,ctx.args);if(parsed.error)return handlePrFeedbackCommand(ctx.directory,ctx.args);if(parsed.continuation){let exactCommand=parsed.prUrl?`/swarm pr-feedback ${parsed.prUrl} continue from ${parsed.continuation.handoffPath}`:`/swarm pr-feedback continue from ${parsed.continuation.handoffPath}`,laneLiveness;try{let config3=loadPluginConfig(ctx.directory),hooks2=config3.hooks;laneLiveness={laneLivenessWatchdog:config3.lane_liveness_watchdog,backgroundPendingTimeoutMs:hooks2?.background_pending_timeout_minutes!==void 0?hooks2.background_pending_timeout_minutes*60000:void 0}}catch{}await transitionPrReviewToFeedback(ctx.directory,ctx.sessionID,{runId:parsed.continuation.runId,handoffPath:parsed.continuation.handoffPath,prUrl:parsed.prUrl,exactCommand,confirmedByUser:!0,...laneLiveness?{laneLiveness}:{}})}else await activatePrWorkflow(ctx.directory,ctx.sessionID,"PR_FEEDBACK",{requireCheckoutPreflight:!0,...parsed.prUrl?{prUrl:parsed.prUrl}:{},...parsed.prUrl?{forge:resolveCommandForgeContext(ctx.directory,parsed.prUrl)}:{}});return handlePrFeedbackCommand(ctx.directory,ctx.args)}function validateAliases(){let errors5=[],warnings=[];for(let[name,entry]of Object.entries(COMMAND_REGISTRY)){let cmdEntry=entry;if(!cmdEntry.handler&&!cmdEntry.aliasOf){errors5.push(`Command '${name}' has no handler and no aliasOf — pure aliases must dereference to a canonical entry`);continue}if(cmdEntry.aliasOf){let target=cmdEntry.aliasOf;if(!Object.hasOwn(COMMAND_REGISTRY,target)){errors5.push(`Alias '${name}' points to non-existent command '${target}'`);continue}let visited=new Set,path287=[],current=target;while(current){let currentEntry=COMMAND_REGISTRY[current];if(!currentEntry)break;if(visited.has(current)){let cycleStart=path287.indexOf(current),fullChain=[name,...path287.slice(0,cycleStart>0?cycleStart:path287.length),current].join(" → ");errors5.push(`Circular alias detected: ${fullChain}`);break}visited.add(current),path287.push(current),current=currentEntry.aliasOf||""}}}return{valid:errors5.length===0,errors:errors5,warnings}}function validateToolPolicy(){let warnings=[];for(let[name,entry]of Object.entries(COMMAND_REGISTRY)){let cmdEntry=entry;if(cmdEntry.aliasOf||cmdEntry.subcommandOf)continue;if(cmdEntry.toolPolicy===void 0)warnings.push(`Command '${name}' has no toolPolicy field — it will not be available through the swarm_command tool. Add toolPolicy: 'agent' | 'human-only' | 'restricted' | 'none'.`)}return{valid:warnings.length===0,warnings}}function resolveCommand(tokens2){if(tokens2.length===0)return null;if(tokens2.length>=3){let compound=`${tokens2[0]} ${tokens2[1]} ${tokens2[2]}`;if(Object.hasOwn(COMMAND_REGISTRY,compound))return{...resolveRegistryEntry(compound),remainingArgs:tokens2.slice(3)}}if(tokens2.length>=2){let compound=`${tokens2[0]} ${tokens2[1]}`;if(Object.hasOwn(COMMAND_REGISTRY,compound))return{...resolveRegistryEntry(compound),remainingArgs:tokens2.slice(2)}}let key2=tokens2[0];if(Object.hasOwn(COMMAND_REGISTRY,key2))return{...resolveRegistryEntry(key2),remainingArgs:tokens2.slice(1)};return null}function resolveRegistryEntry(key2){let entry=COMMAND_REGISTRY[key2],warning=entry.deprecated?`⚠️ "/swarm ${key2}" is deprecated. Use "/swarm ${entry.aliasOf}" instead.`:void 0;while(!entry.handler&&entry.aliasOf){let target=COMMAND_REGISTRY[entry.aliasOf];if(!target)break;entry=target}if(!entry.handler)throw Error(`Command '${key2}' resolves to no handler`);return{entry,key:key2,warning}}var COMMAND_REGISTRY,VALID_COMMANDS,_internals86,validation;var init_registry2=__esm(()=>{init_bundled_skills();init_loader();init_pr_workflow_gate();init_forge_provider();init_logger();init_url_security();init_abort_pr_workflow();init_acknowledge_spec_drift();init_agents();init_approve_plan_critic();init_approve_write();init_archive();init_auto_proceed();init_benchmark();init_checkpoint2();init_ci2();init_ci_monitor();init_ci_simulate();init_close2();init_codebase_review();init_concurrency();init_config4();init_consolidate();init_context_map_stats();init_costs();init_council();init_coupling();init_curate();init_dark_matter();init_dashboard2();init_dataset();init_deep_dive();init_deep_research();init_design_docs();init_diagnose();init_doctor();init_epic();init_evidence();init_export();init_full_auto();init_gate_audit2();init_gate_stats2();init_handoff();init_harness();init_harness_opt();init_history();init_hive_quarantine2();init_issue();init_knowledge();init_lanes();init_learning2();init_link();init_loop();init_memory2();init_memory_link2();init_plan();init_post_mortem();init_pr_feedback();init_pr_feedback_loop2();init_pr_monitor_status();init_pr_review();init_pr_subscribe();init_pr_unsubscribe();init_preflight();init_promote();init_qa_gates();init_recover();init_report();init_reset();init_reset_session();init_retrieve();init_review();init_rollback();init_sdd();init_simulate();init_skill_opt();init_status();init_sync_plan();init_turbo();init_unlink();init_write_retro2();COMMAND_REGISTRY={"blueprint validate":{handler:(ctx)=>handleBlueprintValidateCommand(ctx.directory,ctx.args,{config:ctx.config}),description:"Validate a declarative harness blueprint or atomic blueprint patch",args:"<project-relative-json>",category:"utility",toolPolicy:"none"},"blueprint current":{handler:(ctx)=>handleBlueprintCurrentCommand(ctx.directory,ctx.agents,{config:ctx.config}),description:"Show the ledger-derived current harness blueprint projection",args:"",category:"utility",toolPolicy:"none"},"blueprint history":{handler:(ctx)=>handleBlueprintHistoryCommand(ctx.directory,ctx.args,{config:ctx.config}),description:"Show bounded hash-verified harness version history",args:"[--limit <1..100>]",category:"utility",toolPolicy:"none"},"blueprint diff":{handler:(ctx)=>handleBlueprintDiffCommand(ctx.directory,ctx.args,{config:ctx.config}),description:"Compare two stored harness blueprint versions",args:"<from-version> <to-version>",category:"utility",toolPolicy:"none"},"blueprint export":{handler:(ctx)=>handleBlueprintExportCommand(ctx.directory,ctx.args,{config:ctx.config}),description:"Export a canonical stored harness blueprint",args:"[version]",category:"utility",toolPolicy:"none"},"harness candidate validate":{handler:(ctx)=>handleHarnessCandidateValidateCommand(ctx.directory,ctx.args,{config:ctx.config}),description:"Validate an inert harness candidate manifest",args:"<project-relative-json>",category:"utility",toolPolicy:"none"},"harness candidate show":{handler:(ctx)=>handleHarnessCandidateShowCommand(ctx.directory,ctx.args,{config:ctx.config}),description:"Show bounded harness candidate metadata without raw patch content",args:"<candidate-id>",category:"utility",toolPolicy:"none"},"harness candidate diff":{handler:(ctx)=>handleHarnessCandidateDiffCommand(ctx.directory,ctx.args,{config:ctx.config}),description:"Show candidate file and blueprint-change metadata without raw patch content",args:"<candidate-id>",category:"utility",toolPolicy:"none"},"blueprint-validate":{description:"TUI shortcut alias for blueprint validate",category:"utility",aliasOf:"blueprint validate",deprecated:!0},"blueprint-current":{description:"TUI shortcut alias for blueprint current",category:"utility",aliasOf:"blueprint current",deprecated:!0},"blueprint-history":{description:"TUI shortcut alias for blueprint history",category:"utility",aliasOf:"blueprint history",deprecated:!0},"blueprint-diff":{description:"TUI shortcut alias for blueprint diff",category:"utility",aliasOf:"blueprint diff",deprecated:!0},"blueprint-export":{description:"TUI shortcut alias for blueprint export",category:"utility",aliasOf:"blueprint export",deprecated:!0},"harness-candidate-validate":{description:"TUI shortcut alias for harness candidate validate",category:"utility",aliasOf:"harness candidate validate",deprecated:!0},"harness-candidate-show":{description:"TUI shortcut alias for harness candidate show",category:"utility",aliasOf:"harness candidate show",deprecated:!0},"harness-candidate-diff":{description:"TUI shortcut alias for harness candidate diff",category:"utility",aliasOf:"harness candidate diff",deprecated:!0},"acknowledge-spec-drift":{handler:(ctx)=>handleAcknowledgeSpecDriftCommand(ctx.directory,ctx.args,ctx.source==="cli"?"cli":ctx.source==="chat"?"user":"unknown"),description:"Acknowledge that the spec has drifted from the plan and suppress further warnings",args:"",category:"diagnostics",toolPolicy:"restricted"},"approve-write":{handler:(ctx)=>handleApproveWriteCommand(ctx.directory,ctx.args,ctx.sessionID),description:"Issue a one-shot session/action/candidate/hash-bound write approval",args:"<target-session-id> skill_improve <candidate-id> <candidate-content-hash> [--generation <n>] [--allowed-path-digest <sha256>]",category:"utility",toolPolicy:"human-only"},status:{handler:async(ctx)=>handleStatusCommand(ctx.directory,ctx.agents,ctx.sessionID),description:"Show current swarm state (plus background-work health when hooks.background_subagents is enabled)",category:"core",clashesWithNativeCcCommand:"/status",toolPolicy:"agent",toolNoArgs:!0},"context-map stats":{handler:async(ctx)=>handleContextMapStatsCommand(ctx.directory),description:"Show aggregated context-capsule telemetry stats",category:"diagnostics",toolPolicy:"agent",toolNoArgs:!0},"context-map-stats":{description:"Show aggregated context-capsule telemetry stats",category:"diagnostics",aliasOf:"context-map stats",deprecated:!0},"show-plan":{handler:(ctx)=>handlePlanCommand(ctx.directory,ctx.args),description:"Show current plan (optionally filter by phase number)",category:"core",args:"[phase-number]",toolPolicy:"agent"},plan:{description:"Show current plan (deprecated alias for /swarm show-plan)",category:"core",clashesWithNativeCcCommand:"/plan",aliasOf:"show-plan",deprecated:!0},agents:{handler:(ctx)=>Promise.resolve(handleAgentsCommand(ctx.agents,void 0)),description:"List registered agents",category:"core",clashesWithNativeCcCommand:"/agents",toolPolicy:"agent",toolNoArgs:!0},help:{handler:(ctx)=>_internals86.handleHelpCommand(ctx),description:"Show help for swarm commands",category:"core",args:"[command]",details:"Without argument, shows full command listing. With argument, shows detailed help for a specific command.",toolPolicy:"agent"},history:{handler:(ctx)=>handleHistoryCommand(ctx.directory,ctx.args),description:"Show completed phases summary",category:"utility",clashesWithNativeCcCommand:"/history",toolPolicy:"agent",toolNoArgs:!0},config:{handler:(ctx)=>handleConfigCommand(ctx.directory,ctx.args),description:"Show current resolved configuration",category:"config",clashesWithNativeCcCommand:"/config",toolPolicy:"agent",toolNoArgs:!0},"config doctor":{handler:(ctx)=>handleDoctorCommand(ctx.directory,ctx.args),description:"Run config doctor checks",subcommandOf:"config",category:"diagnostics",toolPolicy:"agent",toolNoArgs:!0},"config-doctor":{description:"Run config doctor checks",subcommandOf:"config",category:"diagnostics",aliasOf:"config doctor",deprecated:!0},"doctor tools":{handler:(ctx)=>handleDoctorToolsCommand(ctx.directory,ctx.args),description:"Run tool registration coherence check",category:"diagnostics",toolPolicy:"agent",toolNoArgs:!0},"doctor-tools":{description:"Run tool registration coherence check",category:"diagnostics",aliasOf:"doctor tools",deprecated:!0},diagnose:{handler:(ctx)=>handleDiagnoseCommand(ctx.directory,ctx.args,ctx.sessionID),description:"Run health check on swarm state",category:"diagnostics",toolPolicy:"agent",toolNoArgs:!0},diagnosis:{description:"Run health check on swarm state",category:"diagnostics",aliasOf:"diagnose",deprecated:!0},"guardrail explain":{handler:async(ctx)=>{let{handleGuardrailExplain:handleGuardrailExplain2}=await Promise.resolve().then(() => (init_guardrail_explain(),exports_guardrail_explain));return handleGuardrailExplain2(ctx.directory,ctx.args)},description:"Dry-run: show what the guardrails would do to a command or write target (executes nothing)",category:"diagnostics",toolPolicy:"agent",toolNoArgs:!1},"guardrail reset":{handler:async(ctx)=>{let{handleGuardrailReset:handleGuardrailReset2}=await Promise.resolve().then(() => (init_guardrail_reset(),exports_guardrail_reset));return handleGuardrailReset2(ctx.args,ctx.sessionID)},description:"Reset one exact active invocation/action circuit after repair",category:"diagnostics",toolPolicy:"agent"},"guardrail-explain":{description:"Dry-run: show what the guardrails would do to a command or write target (executes nothing)",category:"diagnostics",aliasOf:"guardrail explain",deprecated:!0},"guardrail-reset":{description:"Reset one exact active invocation/action circuit after repair",category:"diagnostics",aliasOf:"guardrail reset",deprecated:!0},"guardrail-log":{handler:async(ctx)=>{let{handleGuardrailLog:handleGuardrailLog2}=await Promise.resolve().then(() => (init_guardrail_log(),exports_guardrail_log));return handleGuardrailLog2(ctx.directory,ctx.args)},description:"Read the guardrail decision log (use --blocks-only for blocks)",category:"diagnostics",toolPolicy:"agent",toolNoArgs:!1},preflight:{handler:(ctx)=>handlePreflightCommand(ctx.directory,ctx.args),description:"Run preflight automation checks",category:"diagnostics",toolPolicy:"agent",toolNoArgs:!0},lanes:{handler:(ctx)=>Promise.resolve(handleLanesCommand(ctx.directory,ctx.args)),description:"List active, awaiting-merge, and conflicted worktree lanes",category:"diagnostics",toolPolicy:"agent",toolNoArgs:!0},"sync-plan":{handler:(ctx)=>handleSyncPlanCommand(ctx.directory,ctx.args),description:"Ensure plan.json and plan.md are synced",args:"",category:"config",toolPolicy:"agent",toolNoArgs:!0},benchmark:{handler:(ctx)=>handleBenchmarkCommand(ctx.directory,ctx.args),description:"Show performance metrics [--cumulative] [--ci-gate] [--max-cost-usd <n>] [--gate-audit-run <id>]",args:"--cumulative, --ci-gate, --max-cost-usd <n>, --gate-audit-run <id>",details:"Exit codes (#2493 review F-14): with --ci-gate, the process exits 0 only when every quality check passes and 1 on any failure, budget breach, or missing evidence — CI-safe by construction. Without --ci-gate the command is informational and always exits 0.",category:"diagnostics",toolPolicy:"agent"},"gate-audit":{handler:(ctx)=>handleGateAuditCommand(ctx.directory,ctx.args,{packageRoot:ctx.packageRoot,dispatcher:ctx.evaluationModelDispatcher,parentSessionId:ctx.sessionID}),description:"Run the bounded Tier-1 reviewer/test/SAST/mutation/quality gate matrix",args:"--model <id>, --swarm <id>, --gates <csv>, --tasks <csv>, --runs <n>, --max-concurrency <n>, --max-retries <n>, --max-time-ms <n>, --max-cost-usd <n>, --seed <value>, --run-id <id>, --json",details:"Runs immutable curated defects only in disposable copies, records unavailable data honestly, and writes versioned results below .swarm/evidence/gate-audit/. Container tasks are unsupported until a safe array-form runner exists.",category:"diagnostics",toolPolicy:"agent"},"gate-stats":{handler:(ctx)=>handleGateStatsCommand(ctx.directory,ctx.args),description:"Show offline per-model gate catch, false-reject, retry, cost, and reviewer fallback statistics",args:"--json, --min-samples <n>",category:"diagnostics",toolPolicy:"agent"},"skill-opt":{handler:(ctx)=>handleSkillOptPlan(ctx.directory,ctx.args,{config:ctx.config?.skill_opt,dispatcher:ctx.evaluationModelDispatcher,parentSessionId:ctx.sessionID}),description:"Governed single-skill optimizer (issue #1822). Proposes, validates, and activates one allowlisted SKILL.md candidate at a time with durable lifecycle, serial control, and manual approval.",args:"plan|run|status|diff|approve|reject|rollback|history <slug> [candidateId] [--json] [--confirm] [--expected-content-hash <hash>] [--models <csv>] [--dry-run]",details:"Disabled/proposal-only by default. `run` requires skill_opt.enabled=true AND --confirm (consumes a held-out test set). approve/activate/reject/rollback are human-only and require --expected-content-hash to refuse a stale base. Stores append-only lifecycle under .swarm/evolution/skills/<slug>/<candidateId>/.",category:"utility",toolPolicy:"agent"},"skill-opt plan":{handler:(ctx)=>handleSkillOptPlan(ctx.directory,ctx.args,{config:ctx.config?.skill_opt,dispatcher:ctx.evaluationModelDispatcher,parentSessionId:ctx.sessionID}),description:"Propose an optimization round (dry-run; no mutation, no validation)",subcommandOf:"skill-opt",args:"<slug> [--json] [--models <csv>]",category:"utility",toolPolicy:"agent"},"skill-opt run":{handler:(ctx)=>handleSkillOptRun(ctx.directory,ctx.args,{config:ctx.config?.skill_opt,dispatcher:ctx.evaluationModelDispatcher,parentSessionId:ctx.sessionID}),description:"Execute the optimization loop (draft→smoke→validate; held-out set is single-use so at most one validation per run). Requires skill_opt.enabled=true and --confirm.",subcommandOf:"skill-opt",args:"<slug> --confirm [--json] [--models <csv>]",category:"utility",toolPolicy:"human-only"},"skill-opt status":{handler:(ctx)=>handleSkillOptStatus(ctx.directory,ctx.args),description:"Show the current candidate lifecycle state",subcommandOf:"skill-opt",args:"<slug> <candidateId> [--json]",category:"utility",toolPolicy:"agent"},"skill-opt diff":{handler:(ctx)=>handleSkillOptDiff(ctx.directory,ctx.args),description:"Show baseline-vs-candidate diff summary for a candidate",subcommandOf:"skill-opt",args:"<slug> <candidateId> [--json]",category:"utility",toolPolicy:"agent"},"skill-opt approve":{handler:(ctx)=>handleSkillOptApprove(ctx.directory,ctx.args),description:"Activate a pending candidate (human-only; requires --expected-content-hash)",subcommandOf:"skill-opt",args:"<slug> <candidateId> --expected-content-hash <hash> [--json]",category:"utility",toolPolicy:"human-only"},"skill-opt reject":{handler:(ctx)=>handleSkillOptReject(ctx.directory,ctx.args),description:"Record a rejection for a candidate (no active-skill mutation)",subcommandOf:"skill-opt",args:"<slug> <candidateId> [--json]",category:"utility",toolPolicy:"human-only"},"skill-opt rollback":{handler:(ctx)=>handleSkillOptRollback(ctx.directory,ctx.args),description:"Restore the pre-activation snapshot (appends a rolled_back event)",subcommandOf:"skill-opt",args:"<slug> <candidateId> [--json]",category:"utility",toolPolicy:"human-only"},"skill-opt history":{handler:(ctx)=>handleSkillOptHistory(ctx.directory,ctx.args),description:"Show the append-only lifecycle event log for a candidate",subcommandOf:"skill-opt",args:"<slug> <candidateId> [--json]",category:"utility",toolPolicy:"agent"},"harness-opt":{handler:(ctx)=>handleHarnessOptPlan(ctx.directory,ctx.args,{parentSessionId:ctx.sessionID}),description:"Governed HarnessOpt capstone (issue #2503). Freezes the comparative task set and drives isolated, approved, reversible optimization rounds through the evaluation substrate.",args:"plan|run|status|stop|history [--tasks <json>] [--split train|validation|test] [--seed <s>] [--confirm] [--json] [--reason <text>]",details:"Disabled by default. `run` requires harness_opt.enabled=true AND --confirm, executes one governed round in a disposable worktree (a test split consumes the held-out set exactly once, substrate-enforced), and records durable lineage with task-cost accounting (unknown-not-zero). Activation/rollback stay on /swarm approve-write + the harness store; the controller never mutates the live harness.",category:"utility",toolPolicy:"agent"},"harness-opt plan":{handler:(ctx)=>handleHarnessOptPlan(ctx.directory,ctx.args,{parentSessionId:ctx.sessionID}),description:"Freeze the comparative task set and report loop status (dry-run)",subcommandOf:"harness-opt",args:"--tasks <json> [--split train|validation|test] [--seed <s>] [--json]",category:"utility",toolPolicy:"agent"},"harness-opt run":{handler:(ctx)=>handleHarnessOptRun(ctx.directory,ctx.args,{config:ctx.config?.harness_opt,dispatcher:ctx.evaluationModelDispatcher,parentSessionId:ctx.sessionID}),description:"Execute ONE governed optimization round in a disposable worktree. Requires harness_opt.enabled=true and --confirm; a test split consumes the held-out set exactly once.",subcommandOf:"harness-opt",args:"--tasks <json> --confirm [--split train|validation|test] [--seed <s>] [--json]",category:"utility",toolPolicy:"human-only"},"harness-opt status":{handler:(ctx)=>handleHarnessOptStatus(ctx.directory,ctx.args),description:"Show loop status and the latest round lineage summary",subcommandOf:"harness-opt",args:"[--json]",category:"utility",toolPolicy:"agent"},"harness-opt stop":{handler:(ctx)=>handleHarnessOptStop(ctx.directory,ctx.args),description:"Human-only operator stop: halt governed rounds with a recorded reason",subcommandOf:"harness-opt",args:"[--reason <text>] [--json]",category:"utility",toolPolicy:"human-only"},"harness-opt compare":{handler:(ctx)=>handleHarnessOptCompare(ctx.directory,ctx.args,{config:ctx.config?.harness_opt,dispatcher:ctx.evaluationModelDispatcher,parentSessionId:ctx.sessionID}),description:"Separately executable comparative evaluation (issue #2503): baseline, ablation, and simple-agent arms on one frozen task population with an independently validated manifest, the independent oracle verdict, and a retained pilot-graduation record.",subcommandOf:"harness-opt",args:"--tasks <json> --confirm [--manifest <json>] [--seed <s>] [--lower-ci <n>] [--json]",category:"utility",toolPolicy:"human-only"},"harness-opt history":{handler:(ctx)=>handleHarnessOptHistory(ctx.directory,ctx.args),description:"List durable round lineage records (bounded to the last 20)",subcommandOf:"harness-opt",args:"[--json]",category:"utility",toolPolicy:"agent"},review:{handler:handleReviewCommand,description:"Run the independent review model against a selected Git diff",args:"--base <ref>, --range <from..to|from...to>, --working-tree, --json",details:"Collects one bounded canonical diff, dispatches the configured reviewer in a fresh read-only session, optionally validates eligible HIGH/CRITICAL findings when configured or required by gate mode, and persists the receipt and evidence. With no selector, reviews the default merge-base plus working-tree scope.",category:"diagnostics",toolPolicy:"human-only"},costs:{handler:(ctx)=>handleCostsCommand(ctx.directory,ctx.args),description:"Show per-agent and per-task token/cost telemetry [--json]",args:"--json",category:"diagnostics",toolPolicy:"agent"},report:{handler:(ctx)=>handleReportCommand(ctx.directory,ctx.args),description:"Report swarm observability events from the SQLite query authority [--task <id>] [--session <id>] [--trace <id>] [--run <batchId>] [--since <ISO-8601>] [--json]",args:"--task <id>, --session <id>, --trace <id>, --run <batchId>, --since <ISO-8601>, --json",details:"Bounded, deterministic query over the observability events store in .swarm/swarm.db (the first run performs a bounded, idempotent legacy-import into the local sink). --run filters the lane/dispatch batch axis (workflow.batchId). Unmatched delegation begins are disclosed, never fabricated into ends. Includes a Task attempts (cohort) section (issue #2676): execution-attempt records folded through a snapshot-qualified cohort with per-class counts, known/unavailable cost split, uncertainty, and an explicit causal-rate qualification line. --json emits a schemaVersion-tagged block (schema v2 adds the taskAttempts cohort field).",category:"diagnostics",toolPolicy:"agent"},dashboard:{handler:(ctx)=>handleDashboardCommand(ctx.directory,ctx.args),description:"Show the opt-in local mission-control dashboard URL and status (issue #2509)",details:"Read-only status for the opt-in loopback dashboard over durable swarm state (gates & circuits, delegation age bands, lane liveness, task board, activity timeline). Disabled by default; enable with dashboard.port > 0 in opencode-swarm.json. Never starts or stops the listener — lifecycle belongs to plugin init; the dashboard itself performs no mutations.",category:"diagnostics",toolPolicy:"agent"},learning:{handler:(ctx)=>handleLearningCommand(ctx.directory,ctx.args),description:"Show learning metrics and violation trends",args:"--json, --phase <N>",details:"Computes aggregate learning metrics from knowledge events: violation-rate trends, directive application rates, escalation frequency, per-entry ROI, and never-applied entries. Surfaces a learning summary for the curator digest.",category:"diagnostics",toolPolicy:"agent"},export:{handler:(ctx)=>handleExportCommand(ctx.directory,ctx.args),description:"Export plan and context as JSON",args:"",details:"Exports the current plan and context as JSON to stdout. Useful for piping to external tools or debugging swarm state.",category:"utility",clashesWithNativeCcCommand:"/export",toolPolicy:"agent",toolNoArgs:!0},"dataset consent":{handler:(ctx)=>handleDatasetConsentCommand(ctx.directory,ctx.args),description:"Human-only grant/revoke of the training-content consent record (two-step confirm token)",args:"[--confirm=<token>] [--revoke] [--max-bytes N] [--max-records N] [--retention-days N]",details:"Issue #2486 (D7). Training-content capture is OFF by default and cannot be enabled by config, env, agents, or tools — only by this durable, project-bound consent record under .swarm/training/v1/consent.json. Bare invocation prints the consent terms (purpose, content classes, redaction, hard quota ceilings) and issues a 15-minute confirmation token; --confirm=<token> writes the grant (quotas clamp to the ceilings, never above); --revoke stops capture immediately (physical deletion is /swarm dataset withdraw).",category:"utility",toolPolicy:"human-only"},"dataset withdraw":{handler:(ctx)=>handleDatasetWithdrawCommand(ctx.directory,ctx.args),description:"Human-only destructive withdrawal: purge vault content, tombstone, revoke exports",args:"[--confirm=<token>]",details:"Issue #2486 (D7). Preview-first: the bare command shows exactly what would be deleted (records, bytes, exports to revoke) and issues a 15-minute confirmation token. --confirm=<token> physically empties the vault records file, appends a durable withdrawal tombstone (never deleted by any later operation), writes REVOKED.json revocation manifests into every export still under plugin control, and marks the consent withdrawn.",category:"utility",toolPolicy:"human-only"},"dataset export":{handler:(ctx)=>handleDatasetExportCommand(ctx.directory,ctx.args),description:"Human-only governed dataset export (deterministic bundle + manifest, two-step confirm token)",args:"[--kind <k>[,<k>]] [--session <id>] [--task <id>] [--since <ISO>] [--validation-ratio <0..0.5>] [--confirm=<token>]",details:"Issue #2486 (D7). Side-effect-free preview by default: export id, record counts (train/validation split, quarantined excluded), estimated size, destination, and a 15-minute confirmation token. --confirm=<token> writes the deterministic bundle (records.jsonl, train.jsonl, validation.jsonl, manifest.json with sha256 checksums, schema version, echoed filters, and a session-coherent split) under .swarm/training/v1/exports/<export-id>/; identical re-exports are idempotent. The existing /swarm export (plan+context JSON) is unchanged.",category:"utility",toolPolicy:"human-only"},"dataset-consent":{description:"Human-only grant/revoke of the training-content consent record (two-step confirm token)",aliasOf:"dataset consent",deprecated:!0},"dataset-withdraw":{description:"Human-only destructive withdrawal: purge vault content, tombstone, revoke exports",aliasOf:"dataset withdraw",deprecated:!0},"dataset-export":{description:"Human-only governed dataset export (deterministic bundle + manifest, two-step confirm token)",aliasOf:"dataset export",deprecated:!0},evidence:{handler:(ctx)=>handleEvidenceCommand(ctx.directory,ctx.args),description:"Show evidence bundles [taskId]",args:"<taskId>",details:'Displays review results, test verdicts, and other evidence bundles for the given task ID (e.g., "2.1").',category:"utility",toolPolicy:"agent"},"evidence summary":{handler:(ctx)=>handleEvidenceSummaryCommand(ctx.directory),description:"Generate evidence summary with completion ratio and blockers",subcommandOf:"evidence",args:"",details:"Generates a summary showing completion ratio across all tasks, lists blockers, and identifies missing evidence.",category:"utility",toolPolicy:"agent",toolNoArgs:!0},"evidence-summary":{description:"Generate evidence summary with completion ratio and blockers",subcommandOf:"evidence",args:"",details:"Generates a summary showing completion ratio across all tasks, lists blockers, and identifies missing evidence.",category:"utility",aliasOf:"evidence summary",deprecated:!0},doctor:{description:"Run config doctor checks",category:"diagnostics",aliasOf:"config doctor",deprecated:!0,clashesWithNativeCcCommand:"/doctor"},info:{description:"Show current swarm state (plus background-work health when hooks.background_subagents is enabled)",category:"core",aliasOf:"status",deprecated:!0},"list-agents":{description:"List registered agents",category:"core",aliasOf:"agents",deprecated:!0},health:{description:"Run health check on swarm state",category:"diagnostics",aliasOf:"diagnose",deprecated:!0},check:{description:"Run preflight automation checks",category:"diagnostics",aliasOf:"preflight",deprecated:!0},clear:{description:"Clear session state while preserving plan, evidence, and knowledge",category:"utility",aliasOf:"reset-session",deprecated:!0},archive:{handler:(ctx)=>handleArchiveCommand(ctx.directory,ctx.args),description:"Archive old evidence bundles [--dry-run]",details:"Archives evidence bundles older than max_age_days (config, default 90) or beyond max_bundles cap (config, default 1000). --dry-run previews which bundles would be archived without deleting them. Applies two-tier retention: age-based first, then count-based on oldest remaining.",args:"--dry-run",category:"utility",toolPolicy:"none"},curate:{handler:(ctx)=>handleCurateCommand(ctx.directory,ctx.args,{sessionID:ctx.sessionID}),description:"Run knowledge curation and hive promotion review",args:"",category:"utility",toolPolicy:"none"},consolidate:{handler:(ctx)=>handleConsolidateCommand(ctx.directory,ctx.args,{sessionID:ctx.sessionID}),description:"Run quota-bounded skill-improver consolidation and stage skill proposals",details:"Runs the same consolidation pass used by scheduled skill_improver trigger points: queue hardening, skill-improver proposal writing, and optional draft-skill generation. It never auto-activates skills. Use --respect-interval to obey the configured cadence instead of forcing a run.",args:"--force, --respect-interval, --evaluate",category:"utility",toolPolicy:"restricted"},coupling:{handler:(ctx)=>handleCouplingCommand(ctx.directory,ctx.args),description:"Measure plan coupling (p) and rank modules driving conflicts (Epic mode preview)",details:"Computes the coupling coefficient p = (conflicting task pairs) / (total task pairs) over the current plan, using Epic mode's combined path + co-change conflict signal. Surfaces per-module contention and a ranked decoupling roadmap. Declared scopes come from live `declare_scope` bindings (falling back to plan `files_touched`). Read-only and usable without Epic Mode on, but the co-change signal is included only when `epic.cochange.enabled` is true — otherwise p reflects path conflicts only and the report says the signal is disabled by config. `--suggest` adds Epic plan shaping for the whole plan (the advisory save_plan returns as `epic_shaping` when Epic is on): the plan's epic sizing and up to 5 suggestions — scope advice (declare-scope, narrow-scope) first, then by their effective-speedup gain: extract-prerequisite, isolate-hot-file, split-task, merge-tasks, each with a concrete save_plan patch. Read-only; bounded by a work budget (skipped-budget beyond it).",args:"--phase <n>, --threshold <-1..1>, --min-co-changes <n>, --format markdown|json, --persist, --suggest",category:"diagnostics",toolPolicy:"none"},epic:{handler:(ctx)=>handleEpicCommand(ctx.directory,ctx.args,ctx.sessionID),description:"Open, inspect, and close a plan-scoped epic (coupling-aware parallel execution of the current plan)",details:"An epic is bound to ONE plan: `start` opens it for the current plan, `close` ends it. Requires `epic.mode.enabled: true` in config (top-level `epic` block; no `turbo` block needed — the legacy `turbo.epic` path is still accepted and migrated). `start [--force]` refuses, in order: epic-disabled-by-config, host-unsupported (the host gives the plugin no OpenCode SDK client; on OpenCode 2 the v2 adapter now ships one, so this refusal no longer fires there — v2 is held by the child-session placement work instead), no-plan / plan-ledger-unreadable, epic-already-open (idempotent for the same plan) / epic-open-for-other-plan, turbo-active (config turbo_mode, a session with Turbo on, or a running Lean run — Epic enables neither Lean nor Turbo and never waives per-task QA), dirty-baseline (git: uncommitted changes outside .swarm/), detached-head / epic-branch-exists (epic-branch policy), in-flight-coders (any coder dispatch, background delegation, unsettled settlement, or preserved/recovery lane), not-epic-sized (too few pending tasks, insufficient scope coverage, or insufficient effective speedup — run it in Balanced, or reshape it with the plan-shaping suggestions shown; `--force` overrides and is recorded). Non-git projects run an epic serially (one task per wave). Git epics default to `epic.commit_policy: \"epic-branch\"`: start checks out `swarm/epic/<epicKey>` and every Epic commit goes there (epic_next_wave blocks with epic-branch-mismatch, and no landing or residue is committed, while HEAD is elsewhere); `current-branch` keeps commits on the starting branch. In a git epic every coder runs in an isolated worktree (refused EPIC_ISOLATION_DEGRADED when isolation is unavailable) and lands as a `swarm(task <id>): …` merge commit; main-tree files a non-coder writer (test_engineer, docs) wrote for a task are committed as residue of that task; update_task_status writes nothing to git; wave close records the commit of each task as `refs/swarm/epics/<epicKey>/tasks/<id>` (deleted at close unless `epic.retain_refs`; never pushed by default). While open, the architect calls epic_next_wave and does what its status says: it issues one wave at a time (tasks with non-conflicting declared scopes — exclusive tasks alone, at most one task per densely coupled component; phases strictly in order), the architect dispatches one Task per taskId in ONE message and runs per-task QA (pre_check_batch → reviewer + test_engineer → update_task_status(completed)), and the next epic_next_wave closes the wave (recording outcomes and declared-vs-actual divergence) and issues the next; when a phase is done it returns phase-ready-for-review → epic_phase_review → phase_complete. `close [--abandon] [--land squash|merge|none]` refuses while tasks are pending (or the epic is orphaned / unreadable) unless `--abandon`, refuses a dirty tree before landing, writes a close report (epic-report-v2, embedding the epic scorecard) to .swarm/epic/reports/ and .swarm/epic-prior/reports/ (newest 50 kept), and lands the epic branch onto the original branch: squash (default — staged, uncommitted changes for you to review and commit), merge (a --no-ff merge commit), or none (switch back only). The epic branch is kept (remove it with `git branch -D` once committed). A landing conflict is rolled back (the attempted squash or merge is undone) and the epic stays closing — rerun close to resume. `--abandon` never lands; it switches back to the original branch when the tree is clean. `status [--repair-refs]` (also bare /swarm epic) shows the epic, its waves, phases, the task components recorded with the latest wave and recorded divergence, orphan detection (plan renamed or replaced), sentinel/row repair, recorded worktree merge failures, and retires legacy Epic v1 session state once; `--repair-refs` re-adopts task commits a rebase or amend made unreachable from HEAD. `report [<key>|last] [--format json]` shows the epic scorecard: live for the open epic (bare `report`), else from the close report of a past epic in .swarm/epic-prior/reports/ (`last` = newest; `<key>` = a report or epic key) — tasks completed in the epic, waves (count, width), time over closed waves (wave span, task issue→resolve time, and their ratio, a concurrency factor that is NOT a speedup: it includes queueing behind serialized QA), conflicts (merge-back failures, undeclared writes), rework (extra generations, reopens), first-pass gate rates (upper bounds: the failure history is bounded), forced/sizing at start and learned hot files. Epics learn from their outcomes: undeclared writes teach learned co-writes (a task declaring D that also wrote f makes later tasks declaring D conflict with tasks on f — planner analysis only, never write authorization) and incidents (undeclared writes, merge conflicts, Stage B failures, rework, reopens) in excess of clean exposures make a file hot (a task declaring it runs alone) — undeclared writes its strongest learned co-writer explains are discounted (expansion already separates them), so one declarer writing a file is not heat; an empty history learns nothing (neutral start). Each wave close updates the posterior of the epic; close merges it into the project prior .swarm/epic-prior/learning.json (decayed per epic and by age; kept across /swarm close; `epic.learning.*`). `learning` shows what the planner learned and uses now; `prior [show]` shows the project prior; `prior reset` previews and prints a single-use confirm token (15 minutes); `prior reset --confirm=<token>` clears it. Also: clear-merge-failure <taskId> [--confirm]. The former `on` / `off` toggles, the `decide` / `last` subcommands and `calibration` (renamed `learning`) were removed.",args:"start [--force] | close [--abandon] [--land squash|merge|none] | status [--repair-refs] | report [<key>|last] [--format json] | learning | prior [show|reset [--confirm=<token>]] | clear-merge-failure <taskId> [--confirm]",category:"diagnostics",toolPolicy:"human-only"},"dark-matter":{handler:(ctx)=>handleDarkMatterCommand(ctx.directory,ctx.args),description:"Detect hidden file couplings via co-change NPMI analysis",args:"--threshold <number>, --min-commits <number>",category:"diagnostics",toolPolicy:"none"},finalize:{handler:(ctx)=>handleCloseCommand(ctx.directory,ctx.args,{sessionID:ctx.sessionID}),description:"Use /swarm finalize to finalize the swarm project and archive evidence",details:"Idempotent 4-stage terminal finalization: (1) finalize writes retrospectives for in-progress phases, (2) archive creates timestamped bundle of swarm artifacts and evidence, (3) clean removes active-state files for a clean slate, (4) align performs aggressive git reset --hard to the default remote branch, discarding uncommitted changes and gitignored build artifacts (user-created untracked files are preserved); falls back to a cautious reset that preserves uncommitted changes when the aggressive path cannot proceed. Alignment re-verifies the tracked tree immediately before its destructive reset and aborts fail-closed (leaving alignment undone) when tracked files changed after the close gate was verified or the status cannot be re-read (#2953). WARNING: alignment discards local changes and gitignored files. Resets agent sessions, delegation chains, and active-agent mappings. Reads .swarm/close-lessons.md for explicit lessons and runs curation. Cleanup: knowledge.jsonl is preserved; plan.json, plan.md, events.jsonl, handoff.*, run-memory.jsonl, and summaries/ are removed. An open epic (Epic Mode) is first closed as abandoned-by-swarm-close (it never lands; its close report is archived); .swarm/epic/ is cleaned, while .swarm/epic-prior/ (learning prior and past epic reports) is preserved. Use --skill-review to run the quota-bounded skill_improver in proposal mode. Use --dry-run to preview what finalize would archive, clean, and align without taking the lock or changing anything.",args:"--prune-branches, --skill-review, --dry-run",category:"core",toolPolicy:"none"},close:{description:"Use /swarm close (deprecated alias) to finalize and archive swarm state",details:"Deprecated alias for /swarm finalize. Preserved for backward compatibility. Supports the same flags, including --dry-run.",args:"--prune-branches, --skill-review, --dry-run",category:"core",aliasOf:"finalize",deprecated:!0},"post-mortem":{handler:(ctx)=>handlePostMortemCommand(ctx.directory,ctx.args,{sessionID:ctx.sessionID}),description:"Run the post-mortem agent: project-end synthesis, queue triage, and final curation pass",details:"Reads .swarm/ evidence (knowledge entries, events, curator digests, proposals, retrospectives, drift reports) and produces a post-mortem report at .swarm/post-mortem-{planId}.md. Idempotent: re-runs skip if report exists unless --force is passed. Use --scope session to limit knowledge event aggregation to the current session; project scope is the default.",args:"--force, --scope session|project",category:"core",toolPolicy:"agent"},concurrency:{handler:(ctx)=>handleConcurrencyCommand(ctx.directory,ctx.args,ctx.sessionID),description:"Manage runtime concurrency override for plan execution [set|status|reset]",args:"set <N|preset>, status, reset",details:`Sets, queries, or clears a session-scoped concurrency override for max_concurrent_tasks during plan execution.
|
|
4362
4362
|
When set, the override takes precedence over the plan's locked execution_profile.max_concurrent_tasks.
|
|
4363
4363
|
`+`The override is session-scoped — it does not modify the plan and is cleared on session reset.
|
|
4364
4364
|
`+`While an epic is open (Epic Mode), the override is not consulted: the epic wave width (turbo.lean.max_parallel_coders, default 4) governs.
|
|
@@ -7182,7 +7182,7 @@ ${modeSignal}`:message,usePromptDelivery=config3.event_delivery==="prompt"&&_int
|
|
|
7182
7182
|
`);return[header,"- Test execution policy: Always execute tests via the swarm test runner tool.",policy.avoidPosixExamples?" Do not describe POSIX shell setup commands unless the profile indicates Docker, WSL, or POSIX shell.":" Use POSIX semantics for test commands.","","ENVIRONMENT-SPECIFIC TEST EXECUTION RULES",profile.isWindowsNative?"- Native Windows + PowerShell: Assume PowerShell semantics for paths and env vars. Prefer Pester for PowerShell modules where appropriate.":profile.isWindowsDocker?"- Windows + Docker: Host paths are Windows-style; in-container operations use POSIX semantics.":"- Linux/macOS: Use POSIX semantics for all shell-related reasoning.","- In all modes: prefer the swarm test runner over ad hoc shell commands.","- When tests are skipped due to environment issues, explicitly mention the environment profile assumptions in your verdict."].join(`
|
|
7183
7183
|
`)}var init_prompt_renderer=()=>{};function reject2(reason,detail,rejected_items){return{ok:!1,rejected:!0,reason,detail,rejected_items}}async function validateReceipt(ctx){let{items,no_relevant_knowledge:noRelevant}=ctx;if(items.length===0&&!noRelevant)return reject2("empty_receipt","no items and no_relevant_knowledge is false");if(noRelevant&&items.length>0)return reject2("invalid_outcome","no_relevant_knowledge cannot be combined with items");for(let item of items)if(!VALID_OUTCOMES.has(item.outcome))return reject2("invalid_outcome",`item ${item.id}: outcome ${item.outcome}`);let traceId=ctx.trace_id||NO_TRACE_SENTINEL;if(traceId===NO_TRACE_SENTINEL){if(items.length>0)return reject2("trace_not_found","items filed against the none sentinel trace");let empty=await commitEmptyRetrieval(ctx.directory,{trace_id:traceId,session_id:ctx.session_id,phase:ctx.phase,task_id:ctx.task_id,agent:ctx.agent,grace_days:ctx.grace_days});if(!empty.ok)return reject2(empty.code,empty.detail);return{ok:!0,accepted:[],idempotent_skips:[],trace:null,closes_no_relevant:!0,authoritative_event_ids:{},no_relevant_event_id:empty.terminal_event_id}}let committed=await validateAndCommitTerminalBatch(ctx.directory,{trace_id:traceId,session_id:ctx.session_id,phase:ctx.phase,task_id:ctx.task_id,agent:ctx.agent,cohort_id:ctx.cohort_id,source_link_id:ctx.source_link_id,grace_days:ctx.grace_days,authorized_filing_sessions:ctx.authorized_filing_sessions,items:items.map((item)=>({entry_id:item.id,outcome:item.outcome,reason:item.reason,source:ctx.source.trim()||"unknown"})),no_relevant_knowledge:noRelevant});if(!committed.ok)return reject2(committed.code,committed.detail);let remainingItems=[...items],takeItem=(id,outcome)=>{let index=remainingItems.findIndex((item)=>item.id===id&&(outcome===void 0||item.outcome===outcome));if(index<0)return;return remainingItems.splice(index,1)[0]},accepted=committed.accepted.map((item)=>takeItem(item.entry_id,item.outcome)).filter((item)=>item!==void 0),idempotent_skips=committed.idempotent.map((id)=>takeItem(id)).filter((item)=>item!==void 0),wrongSessionStamps=committed.wrong_session_membership_sessions??{},wrongSessionDetail=(id)=>{let stamp=wrongSessionStamps[id];if(!stamp)return;return`wrong_session for id ${sanitizeDiagnosticText(id,64)}: knowledge captured in session ${sanitizeDiagnosticText(stamp,64)} but filed from ${sanitizeDiagnosticText(ctx.session_id,64)}; file from the capturing session or its dispatched child (after a reset-session, a re-dispatched child is authorized), or surface fresh knowledge via knowledge_recall`},rejected_items=committed.rejected.map((item)=>({item:takeItem(item.entry_id)??{id:item.entry_id,outcome:"ignored"},reason:item.reason}));if(rejected_items.length&&accepted.length===0&&idempotent_skips.length===0){let first=rejected_items[0];return reject2(first.reason,wrongSessionDetail(first.item.id)??`${first.reason} for id ${first.item.id}`,rejected_items.map((entry)=>entry.reason==="wrong_session"?{...entry,detail:wrongSessionDetail(entry.item.id)}:entry))}let queried=await queryLiveMemberships(ctx.directory,{session_id:ctx.session_id,include_terminal:!0,grace_days:ctx.grace_days}),memberships=queried.ok?queried.memberships.filter((membership)=>membership.trace_id===traceId):[],trace=memberships.length?{type:"retrieved",event_id:memberships[0].membership_event_id,trace_id:traceId,timestamp:memberships[0].committed_at,session_id:ctx.session_id,phase:memberships[0].phase,task_id:memberships[0].task_id,agent:memberships[0].agent??ctx.agent,query:"",retrieval_mode:"manual",result_ids:memberships.map((membership)=>membership.entry_id),ranks:Object.fromEntries(memberships.map((membership,index)=>[membership.entry_id,membership.rank??index+1])),scores:Object.fromEntries(memberships.map((membership)=>[membership.entry_id,membership.score??0]))}:null;return{ok:!0,accepted,idempotent_skips,trace,closes_no_relevant:committed.closes_no_relevant,authoritative_event_ids:Object.fromEntries(committed.accepted.map((item)=>[item.entry_id,item.event_id])),...committed.terminal_event_id?{no_relevant_event_id:committed.terminal_event_id}:{},...rejected_items.length?{rejected_items:rejected_items.map((entry)=>entry.reason==="wrong_session"?{...entry,detail:wrongSessionDetail(entry.item.id)}:entry)}:{}}}var NO_TRACE_SENTINEL="none",VALID_OUTCOMES;var init_knowledge_receipt_validator=__esm(()=>{init_path_identity();init_knowledge_receipt_ledger();VALID_OUTCOMES=RECEIPT_TERMINAL_OUTCOMES});function isTaskTool3(tool3){return tool3==="Task"||tool3==="task"}function resolveDelegateAckTaskId(args2,knownPlanTaskIds,planContextOverLimit=!1){let resolved=resolveDelegateAckTaskIdResult(args2,knownPlanTaskIds,planContextOverLimit);return resolved.status==="resolved"?resolved.taskId:void 0}function resolveDelegateAckTaskIdResult(args2,knownPlanTaskIds,planContextOverLimit=!1){return resolveTaskId(args2,{policy:"attribution",knownPlanTaskIds,planContextOverLimit})}async function appendUnacknowledgedCritical(directory,record3){let filePath=validateSwarmPath(directory,"unacknowledged-criticals.jsonl");await appendCappedJsonl(filePath,JSON.stringify(record3),{maxEntries:resolveRetentionCap("MAX_UNACKNOWLEDGED_CRITICALS",MAX_UNACKNOWLEDGED_CRITICALS),onPrune:(dropped)=>{warn(`unacknowledged-criticals audit at cap: dropped ${dropped} oldest ${dropped===1?"entry":"entries"} (FIFO bound MAX_UNACKNOWLEDGED_CRITICALS)`)}})}async function reconcileShownDirectives(params){let result={emitted:[],unacknowledgedCriticals:[],unacknowledgedNonCritical:[]};try{let shown=params.shown;if(shown.length===0)return result;let shownById=new Map(shown.map((d)=>[d.id,d])),criticalIds=shown.filter((d)=>d.priority==="critical").map((d)=>d.id),acks=parseAcknowledgments(params.transcript),ackedIds=new Set,violatedIds=new Set,sessionId=params.sessionId,taskId=params.taskId,traceId=params.traceId??"legacy-unverifiable",isLegacyPrompt=params.traceId===void 0,cohortId,linkId;try{cohortId=await ensureCohortIdCached(params.directory,sessionId),linkId=readLinkPointer(params.directory)?.linkId}catch{}let ackItems=[],ackByItemId=new Map;for(let ack of acks){if(!shownById.has(ack.id))continue;if(ackedIds.add(ack.id),!isLegacyPrompt&&ack.trace_id!==traceId)continue;if(ack.result==="applied"||ack.result==="ignored"||ack.result==="violated"||ack.result==="n_a"||ack.result==="contradicted")ackItems.push({id:ack.id,outcome:ack.result,reason:ack.reason}),ackByItemId.set(ack.id,ack)}let eventIdByKnowledgeId=new Map;if(isLegacyPrompt)for(let ack of acks){if(!shownById.has(ack.id))continue;if(!ackByItemId.has(ack.id))continue;ackedIds.add(ack.id)}else{let validation2=await validateReceipt({directory:params.directory,trace_id:traceId,session_id:sessionId,task_id:taskId,agent:params.agent,source:"delegate",cohort_id:cohortId,source_link_id:linkId,items:ackItems,no_relevant_knowledge:!1});if(validation2.ok){for(let item of validation2.accepted){let ack=ackByItemId.get(item.id);if(!ack)continue;ackedIds.add(item.id),await recordKnowledgeEvent(params.directory,{type:item.outcome,trace_id:traceId,knowledge_id:item.id,session_id:sessionId,task_id:taskId,agent:params.agent,source:"delegate",reason:ack.reason});let authoritativeEventId=validation2.authoritative_event_ids[item.id];if(authoritativeEventId)eventIdByKnowledgeId.set(item.id,authoritativeEventId);if(item.outcome==="violated")violatedIds.add(item.id);result.emitted.push({id:item.id,type:item.outcome})}for(let item of validation2.idempotent_skips)ackedIds.add(item.id);for(let rejected2 of validation2.rejected_items??[])ackedIds.add(rejected2.item.id)}if(!validation2.ok)for(let id of ackByItemId.keys())ackedIds.add(id)}try{let now2=new Date().toISOString(),evidenceRecords=[];for(let[kid,eid]of eventIdByKnowledgeId){let ack=ackByItemId.get(kid);if(!ack||!cohortId)continue;let outcome=ack.result;if(outcome!=="applied"&&outcome!=="violated"&&outcome!=="contradicted")continue;evidenceRecords.push({cohort_id:cohortId,source_link_id:linkId,entry_id:kid,retrieval_trace_id:traceId,receipt_outcome:outcome,receipt_source:"delegate",receipt_event_id:eid,phase:void 0,timestamp:now2})}await appendPromotionEvidence(params.directory,evidenceRecords)}catch{}let missingCriticalIds=criticalIds.filter((id)=>!ackedIds.has(id)),committedMissingCriticalIds=new Set;if(!isLegacyPrompt&&missingCriticalIds.length>0){let committed=await validateAndCommitTerminalBatch(params.directory,{trace_id:traceId,session_id:sessionId,task_id:taskId,agent:params.agent,cohort_id:cohortId,source_link_id:linkId,items:missingCriticalIds.map((entry_id)=>({entry_id,outcome:"violated",source:"delegate",reason:"unacknowledged"}))});if(committed.ok)committedMissingCriticalIds=new Set(committed.committed.map((item)=>item.entry_id))}for(let id of missingCriticalIds){if(!committedMissingCriticalIds.has(id))continue;result.unacknowledgedCriticals.push(id),await recordKnowledgeEvent(params.directory,{type:"violated",trace_id:traceId,knowledge_id:id,session_id:sessionId,task_id:taskId,agent:params.agent,source:"delegate",reason:"unacknowledged"}),violatedIds.add(id),result.emitted.push({id,type:"violated"});try{await appendUnacknowledgedCritical(params.directory,{timestamp:new Date().toISOString(),knowledge_id:id,agent:params.agent,session_id:sessionId,task_id:taskId,reason:"unacknowledged"})}catch{}}let silentEvents=[];for(let[id,directive]of shownById){if(directive.priority==="critical")continue;if(ackedIds.has(id))continue;if(params.replay===!0)continue;result.unacknowledgedNonCritical.push(id),silentEvents.push({type:"unacknowledged",trace_id:traceId,knowledge_id:id,session_id:sessionId,task_id:taskId,agent:params.agent,source:"delegate",reason:"no_ack_marker"}),result.emitted.push({id,type:"unacknowledged"})}if(silentEvents.length>0)await recordKnowledgeEventsBatch(params.directory,silentEvents);if(violatedIds.size>0)await escalateViolatedEntries(params.directory,[...violatedIds])}catch{}return result}async function collectDelegateAcks(params){let shown=parseDelegateDirectiveBlock(params.prompt);if(shown.length===0)return{emitted:[],unacknowledgedCriticals:[],unacknowledgedNonCritical:[]};let sessionId=params.sessionId;if(!sessionId)return{emitted:[],unacknowledgedCriticals:[],unacknowledgedNonCritical:[],unverifiable:{code:"missing_session_id",detail:"Delegate acknowledgments require a real host session id"}};let traceId=parseDelegateDirectiveTraceId(params.prompt)??void 0,taskId=params.taskIdResolution?params.taskIdResolution.status==="resolved"?params.taskIdResolution.taskId:void 0:params.taskId??resolveDelegateAckTaskId({prompt:params.prompt});return reconcileShownDirectives({directory:params.directory,shown,traceId,transcript:params.transcript,agent:params.agent,sessionId,taskId})}async function collectLaneDelegateAcks(params){let empty={emitted:[],unacknowledgedCriticals:[],unacknowledgedNonCritical:[],phases:[]};try{let memberships=await queryLiveMemberships(params.directory,{session_id:params.sessionId,exposure_kind:"delegate_directive",include_terminal:!0});if(!memberships.ok)return empty;let byTrace=new Map,phases=new Set;for(let membership of memberships.memberships){let group=byTrace.get(membership.trace_id)??[];if(group.push(membership),byTrace.set(membership.trace_id,group),membership.phase)phases.add(membership.phase)}let combined={emitted:[],unacknowledgedCriticals:[],unacknowledgedNonCritical:[]};for(let[traceId,group]of byTrace){let taskId=group.find((m)=>m.task_id)?.task_id,outcome=await reconcileShownDirectives({directory:params.directory,shown:group.map((m)=>({id:m.entry_id,priority:m.critical?"critical":"medium"})),traceId,transcript:params.transcript,agent:params.agent,sessionId:params.sessionId,taskId,replay:params.replay});if(combined.emitted.push(...outcome.emitted),combined.unacknowledgedCriticals.push(...outcome.unacknowledgedCriticals),combined.unacknowledgedNonCritical.push(...outcome.unacknowledgedNonCritical),outcome.unverifiable)combined.unverifiable=outcome.unverifiable}return{...combined,phases:[...phases]}}catch{return empty}}async function collectDelegateAcksAfter(directory,input,output){if(!isTaskTool3(input.tool))return;let argsRecord=input.args&&typeof input.args==="object"?input.args:null,prompt=argsRecord&&typeof argsRecord.prompt==="string"?argsRecord.prompt:"";if(!prompt)return;let transcript=typeof output.output==="string"?output.output:"";if(!transcript)return;let agent=parseDelegationArgs(input.args)?.targetAgent??"unknown",sessionId=typeof input.sessionID==="string"?input.sessionID:void 0,planTaskIdOptions=toTaskIdPlanContextOptions(await loadPlanTaskIdContext(directory)),taskIdResolution=resolveDelegateAckTaskIdResult(argsRecord??{prompt},planTaskIdOptions.knownPlanTaskIds,planTaskIdOptions.planContextOverLimit);await collectDelegateAcks({directory,prompt,transcript,agent,sessionId,taskIdResolution})}var MAX_UNACKNOWLEDGED_CRITICALS=500;var init_delegate_ack_collector=__esm(()=>{init_caps();init_jsonl_cap();init_logger();init_cohort_cache();init_knowledge_application();init_knowledge_escalator();init_knowledge_events();init_knowledge_injector();init_knowledge_link();init_knowledge_receipt_ledger();init_knowledge_receipt_validator();init_plan_task_id_context();init_promotion_evidence_store();init_skill_propagation_gate();init_task_id_resolver();init_utils2()});import{existsSync as existsSync158,readdirSync as readdirSync49,readFileSync as readFileSync132,statSync as statSync100}from"node:fs";import*as path312 from"node:path";function validateRepoRelativeGlob(directory,value){let v=value.trim();if(!v)return null;if(v.includes("\x00"))return null;if(v.startsWith("/")||/^[A-Za-z]:[\\/]/.test(v)||v.startsWith("\\"))return null;if(v.split(/[/\\]/).some((s)=>s===".."))return null;let globStart=v.search(/[*?{[]/),concrete=globStart===-1?v:v.slice(0,globStart);if(concrete){let baseDir=path312.resolve(directory),resolved=path312.resolve(baseDir,concrete),rel3=path312.relative(baseDir,resolved);if(rel3.startsWith("..")||path312.isAbsolute(rel3))return null}return v}function findBinaryInPath(binary){let candidates=process.platform==="win32"?[`${binary}.exe`,`${binary}.cmd`,`${binary}.bat`,binary]:[binary];for(let dir of(process.env.PATH??"").split(path312.delimiter)){if(!dir)continue;for(let name of candidates){let candidate2=path312.join(dir,name);if(existsSync158(candidate2))return candidate2}}return null}function safeChildEnv(){let env={};if(process.env.PATH)env.PATH=process.env.PATH;if(process.env.HOME)env.HOME=process.env.HOME;if(process.env.SystemRoot)env.SystemRoot=process.env.SystemRoot;if(process.env.TEMP)env.TEMP=process.env.TEMP;if(process.env.TMP)env.TMP=process.env.TMP;return env}async function runArgv(argv,cwd){let proc=bunSpawn(argv,{stdin:"ignore",stdout:"pipe",stderr:"pipe",cwd,env:safeChildEnv()}),finished=!1;try{let timeout=new Promise((resolve119)=>setTimeout(()=>resolve119("timeout"),PREDICATE_TIMEOUT_MS));if(await Promise.race([proc.exited,timeout])==="timeout")return{exitCode:null,stdout:"",stderr:"",timedOut:!0};let[stdout,stderr]=await Promise.all([proc.stdout.text().catch(()=>""),proc.stderr.text().catch(()=>"")]);return finished=!0,{exitCode:proc.exitCode,stdout,stderr,timedOut:!1}}finally{if(!finished)try{proc.kill()}catch{}}}async function runGrepPredicate(rest,directory){let lastColon=rest.lastIndexOf(":");if(lastColon<=0||lastColon===rest.length-1)return{result:"error",detail:"grep: expected <regex>:<path-glob>"};let regex=rest.slice(0,lastColon),rawGlob=rest.slice(lastColon+1),glob=validateRepoRelativeGlob(directory,rawGlob);if(glob===null)return{result:"error",detail:`grep: unsafe or empty path-glob "${rawGlob}"`};let pattern;try{pattern=new RegExp(regex,"m")}catch(err){return{result:"error",detail:`grep: invalid regex ${err instanceof Error?err.message:String(err)}`}}let matcher=import_picomatch2.default(glob,{dot:!0}),visited=0,matches=0,walk=(dir)=>{if(visited>=GREP_MAX_FILES)return;let entries2;try{entries2=readdirSync49(dir,{withFileTypes:!0})}catch{return}for(let entry of entries2){if(visited>=GREP_MAX_FILES)return;let fullPath=path312.join(dir,entry.name),relPath=path312.relative(directory,fullPath).replace(/\\/g,"/");if(entry.isDirectory()){if(!GREP_SKIP_DIRECTORIES.has(entry.name))walk(fullPath);continue}if(!entry.isFile())continue;if(visited++,!matcher(relPath))continue;try{if(statSync100(fullPath).size>GREP_MAX_BYTES_PER_FILE)continue;let found=readFileSync132(fullPath,"utf-8").match(pattern);if(found)matches+=found.length}catch{}}};if(walk(directory),visited>=GREP_MAX_FILES)return{result:"error",detail:`grep: file scan exceeded ${GREP_MAX_FILES} files`};if(matches===0)return{result:"pass",detail:"grep: zero matches"};return{result:"fail",detail:`grep: ${matches} match(es) found`}}async function runToolPredicate(rest,directory){let raw=rest.trim();if(!raw)return{result:"error",detail:"tool: empty command"};if(raw.includes("\x00"))return{result:"error",detail:"tool: null byte in command"};let argvParts=raw.split(/\s+/).filter((p)=>p.length>0);if(argvParts.length===0)return{result:"error",detail:"tool: empty command"};let binary=argvParts[0];if(binary.includes("/")||binary.includes("\\"))return{result:"error",detail:`tool: path-qualified binary "${binary}" is not allowed`};if(!TOOL_BINARY_ALLOWLIST.has(binary))return{result:"error",detail:`tool: binary "${binary}" is not on the allowlist`};let resolved=findBinaryInPath(binary);if(!resolved)return{result:"error",detail:`tool: binary "${binary}" not found`};let res=await runArgv([resolved,...argvParts.slice(1)],directory);if(res.timedOut)return{result:"error",detail:"tool: timed out"};if(res.exitCode===0)return{result:"pass",detail:"tool: exit 0"};return{result:"fail",detail:`tool: exit ${res.exitCode} ${res.stderr.slice(0,200)}`}}async function changedPaths(directory){let git2=findBinaryInPath("git");if(!git2)return null;let res=await runArgv([git2,"status","--porcelain","-z"],directory);if(res.timedOut||res.exitCode!==0)return null;let out=new Set;for(let entry of res.stdout.split("\x00")){if(entry.length<=3)continue;let p=entry.slice(3);if(p)out.add(path312.normalize(p))}return out}async function runFileModifiedPredicate(rest,directory,expectModified){let label=expectModified?"file_modified":"file_not_modified",safe2=validateRepoRelativeGlob(directory,rest);if(safe2===null)return{result:"error",detail:`${label}: unsafe or empty path "${rest}"`};let changed2=await changedPaths(directory);if(changed2===null)return{result:"error",detail:`${label}: git unavailable or failed`};let target=path312.normalize(safe2),isChanged=changed2.has(target);return{result:(expectModified?isChanged:!isChanged)?"pass":"fail",detail:`${label}: ${target} ${isChanged?"changed":"unchanged"}`}}async function runDirectivePredicate(predicate,directory){try{if(typeof predicate!=="string"||!predicate.trim())return{result:"error",detail:"predicate: empty"};let trimmed=predicate.trim(),firstColon=trimmed.indexOf(":");if(firstColon<=0)return{result:"error",detail:"predicate: missing handler prefix (expected <handler>:...)"};let handler=trimmed.slice(0,firstColon),rest=trimmed.slice(firstColon+1);switch(handler){case"grep":return await runGrepPredicate(rest,directory);case"tool":return await runToolPredicate(rest,directory);case"file_not_modified":return await runFileModifiedPredicate(rest,directory,!1);case"file_modified":return await runFileModifiedPredicate(rest,directory,!0);default:return{result:"error",detail:`predicate: unknown handler "${handler}"`}}}catch(err){return warn(`[directive-predicate-runner] unexpected error: ${err instanceof Error?err.message:String(err)}`),{result:"error",detail:"predicate: unexpected error (fail-closed)"}}}var import_picomatch2,PREDICATE_TIMEOUT_MS=15000,GREP_MAX_FILES=1e4,GREP_MAX_BYTES_PER_FILE=1e6,GREP_SKIP_DIRECTORIES,TOOL_BINARY_ALLOWLIST;var init_directive_predicate_runner=__esm(()=>{init_bun_compat();init_logger();import_picomatch2=__toESM(require_picomatch2(),1),GREP_SKIP_DIRECTORIES=new Set([".git",".swarm","node_modules","dist","coverage"]),TOOL_BINARY_ALLOWLIST=new Set(["rg","grep","git","biome","eslint","tsc","ruff"])});function parseReviewerDirectiveCompliance(text){if(!text||typeof text!=="string")return[];let out=[];for(let m of text.matchAll(VERDICT_PATTERN)){let verb=m[1].toUpperCase(),traceId=decodeDirectiveCorrelationId(m[2]),entryId=decodeDirectiveCorrelationId(m[3]);if(!traceId||!entryId)continue;let evidence2=m[4]?.trim().slice(0,280),verdict=verb==="VERIFIED"?"verified":verb==="VIOLATED"?"violated":"n_a";out.push({trace_id:traceId,entry_id:entryId,verdict,evidence:evidence2})}return out}function verdictToEventType(v){return v==="verified"?"applied":v==="violated"?"violated":"n_a"}function pairKey2(traceId,entryId){return JSON.stringify([traceId,entryId])}async function reconcileReviewerVerdicts(params){let result={emitted:[],omittedCriticals:[],uncertainties:[]},verifyByPair=new Map(params.directivesToVerify.map((d)=>[pairKey2(d.trace_id,d.entry_id),d]));if(verifyByPair.size===0)return result;let verdictsByPair=new Map;for(let verdict of parseReviewerDirectiveCompliance(params.transcript)){let key2=pairKey2(verdict.trace_id,verdict.entry_id);if(!verifyByPair.has(key2))continue;let existing=verdictsByPair.get(key2)??[];existing.push(verdict),verdictsByPair.set(key2,existing)}let pending=[];for(let[key2,directive]of verifyByPair){let matching=verdictsByPair.get(key2)??[];if(matching.length>1){result.uncertainties.push({trace_id:directive.trace_id,entry_id:directive.entry_id,code:"duplicate_verdict",uncertainty:"Reviewer emitted more than one verdict for the exact pair"});continue}if(matching.length===0){if(directive.priority!=="critical")continue;result.omittedCriticals.push({trace_id:directive.trace_id,entry_id:directive.entry_id}),pending.push({directive,type:"violated",reason:"reviewer_omitted"});continue}let verdict=matching[0];if(verdict.verdict==="verified"&&!verdict.evidence?.trim()){if(result.uncertainties.push({trace_id:directive.trace_id,entry_id:directive.entry_id,code:"reviewer_missing_evidence",uncertainty:"VERIFIED requires nonempty evidence"}),directive.priority==="critical")result.omittedCriticals.push({trace_id:directive.trace_id,entry_id:directive.entry_id}),pending.push({directive,type:"violated",reason:"reviewer_missing_evidence"});continue}let item={directive,type:verdictToEventType(verdict.verdict),reason:verdict.evidence};if(verdict.verdict==="violated"&&directive.verification_predicate)try{let outcome=await _internals265.runDirectivePredicate(directive.verification_predicate,params.directory);item.predicate_check={predicate:directive.verification_predicate,result:outcome.result,detail:outcome.detail}}catch(error93){item.predicate_check={predicate:directive.verification_predicate,result:"error",detail:error93 instanceof Error?error93.message:String(error93)}}pending.push(item)}let groups=new Map;for(let item of pending){let groupKey=JSON.stringify([item.directive.trace_id,item.directive.session_id,item.directive.cohort_id,item.directive.source_link_id,item.directive.prior_terminal_outcome,item.directive.prior_terminal_event_id]),group=groups.get(groupKey)??[];group.push(item),groups.set(groupKey,group)}let violatedIds=new Set,agent=params.agent??"reviewer";for(let group of groups.values()){let first=group[0].directive,remediationAuthorization=(first.prior_terminal_outcome==="violated"||first.prior_terminal_outcome==="contradicted")&&first.prior_terminal_event_id&&group.some((item)=>item.type!=="violated")?{actor:"reviewer-remediation",reason:"reviewer_verified_remediation",expected_event_id:first.prior_terminal_event_id,expected_outcome:first.prior_terminal_outcome}:void 0,committedEntries;try{let committed=await _internals265.validateAndCommitTerminalBatch(params.directory,{trace_id:first.trace_id,session_id:first.session_id,cohort_id:first.cohort_id,source_link_id:first.source_link_id,authorization:remediationAuthorization,items:group.map((item)=>({entry_id:item.directive.entry_id,outcome:item.type,source:"reviewer",reason:item.reason}))});if(!committed.ok){for(let item of group)result.uncertainties.push({trace_id:item.directive.trace_id,entry_id:item.directive.entry_id,code:committed.code,uncertainty:committed.detail});continue}committedEntries=new Set(committed.accepted.map((terminal)=>terminal.entry_id));for(let rejected2 of committed.rejected)result.uncertainties.push({trace_id:first.trace_id,entry_id:rejected2.entry_id||void 0,code:rejected2.reason,uncertainty:"Authoritative ledger rejected reviewer terminal"})}catch(error93){for(let item of group)result.uncertainties.push({trace_id:item.directive.trace_id,entry_id:item.directive.entry_id,code:"ledger_exception",uncertainty:error93 instanceof Error?error93.message:String(error93)});continue}for(let item of group){if(!committedEntries.has(item.directive.entry_id))continue;try{if(await _internals265.recordKnowledgeEvent(params.directory,{type:item.type,trace_id:item.directive.trace_id,knowledge_id:item.directive.entry_id,session_id:item.directive.session_id,task_id:params.taskId,phase:params.phase,agent,source:"reviewer",reason:item.reason,predicate_check:item.predicate_check}),result.emitted.push({trace_id:item.directive.trace_id,entry_id:item.directive.entry_id,id:item.directive.entry_id,type:item.type,source:"reviewer"}),item.type==="violated")violatedIds.add(item.directive.entry_id)}catch(error93){result.uncertainties.push({trace_id:item.directive.trace_id,entry_id:item.directive.entry_id,code:"diagnostic_event_failed",uncertainty:error93 instanceof Error?error93.message:String(error93)})}}}if(violatedIds.size>0)try{await _internals265.escalateViolatedEntries(params.directory,[...violatedIds])}catch(error93){result.uncertainties.push({trace_id:"",code:"escalation_failed",uncertainty:error93 instanceof Error?error93.message:String(error93)})}return result}function isTaskTool7(tool3){return tool3==="Task"||tool3==="task"}async function collectReviewerVerdictsAfter(directory,input,output){if(!isTaskTool7(input.tool))return;let parsedArgs=parseDelegationArgs(input.args);if(!parsedArgs)return;if(stripKnownSwarmPrefix(parsedArgs.targetAgent).toLowerCase()!=="reviewer")return;let argsRecord=input.args&&typeof input.args==="object"?input.args:null,prompt=argsRecord&&typeof argsRecord.prompt==="string"?argsRecord.prompt:"";if(!prompt)return;let transcript=typeof output.output==="string"?output.output:"";if(!transcript)return;let directivesToVerify=parseDirectivesToVerifyBlock(prompt);if(directivesToVerify.length===0)return;let sessionId=typeof input.sessionID==="string"?input.sessionID:void 0;await reconcileReviewerVerdicts({directory,transcript,directivesToVerify,sessionId,agent:"reviewer"})}var _internals265,VERDICT_PATTERN;var init_reviewer_verdict_parser=__esm(()=>{init_reviewer_directive_compliance();init_schema();init_directive_predicate_runner();init_knowledge_escalator();init_knowledge_events();init_knowledge_receipt_ledger();init_skill_propagation_gate();_internals265={validateAndCommitTerminalBatch,recordKnowledgeEvent,runDirectivePredicate,escalateViolatedEntries},VERDICT_PATTERN=/\b(VERIFIED|VIOLATED|N\/A)\s*:\s*([^:\s]{1,512})\s*:\s*([^:\s]{1,512})(?:\s+(?:evidence|reason)\s*=\s*([^\n\r]+?))?(?=$|[\n\r]|\s+(?:VERIFIED|VIOLATED|N\/A)\b)/gi});import{createHash as createHash106}from"node:crypto";function delegationCostRecordMaterial(record3){if(!record3.laneId)return`${record3.parentSessionId}\x00${record3.callID}`;return`${record3.parentSessionId}\x00${record3.callID}\x00lane:${record3.laneId}`}function buildDelegationTerminalIdentityFields(input){let material=delegationCostRecordMaterial(input.record);return{record_id:createHash106("sha256").update(`delegation-cost-id-v1\x00${material}`).digest("hex").slice(0,32),identity_fingerprint:createHash106("sha256").update(`delegation-cost-identity-v1\x00${material}\x00${input.record.swarmPrefixedAgent}\x00${input.model??""}`).digest("hex").slice(0,32),version:1,parent_session_digest:createHash106("sha256").update(`delegation-cost-parent-v1\x00${input.record.parentSessionId}`).digest("hex").slice(0,32),child_session_digest:createHash106("sha256").update(`delegation-cost-child-v1\x00${input.record.subagentSessionId}`).digest("hex").slice(0,32),...input.recovered?{recovered:!0}:{}}}var init_delegation_cost_identity=()=>{};var exports_delegation_lifecycle={};__export(exports_delegation_lifecycle,{settleDelegationTerminal:()=>settleDelegationTerminal,recoverTerminalLaneReceipts:()=>recoverTerminalLaneReceipts,isBenignSettleOutcome:()=>isBenignSettleOutcome,emitDelegationEventlessTerminalEnd:()=>emitDelegationEventlessTerminalEnd,emitDelegationBegin:()=>emitDelegationBegin,delegationCostRecordMaterial:()=>delegationCostRecordMaterial,buildDelegationTerminal:()=>buildDelegationTerminal,_internals:()=>_internals279,TERMINAL_LANE_RECEIPT_RECOVERY_DEADLINE_MS:()=>TERMINAL_LANE_RECEIPT_RECOVERY_DEADLINE_MS,MAX_TERMINAL_LANE_RECEIPT_RECOVERY:()=>MAX_TERMINAL_LANE_RECEIPT_RECOVERY});import*as fs188 from"node:fs";import*as path326 from"node:path";function isBenignSettleOutcome(kind){return kind==="duplicate"||kind==="conflict"||kind==="already_terminal_without_event"}function buildDelegationTerminal(record3,terminal,now2){return{eventId:buildBackgroundCompletionEventId({correlationId:record3.correlationId,jobId:record3.jobId,status:terminal.status,resultDigest:terminal.result.digest}),status:terminal.status,recordedAt:now2,result:terminal.result}}async function settleDelegationTerminal(directory,record3,terminal,observations={},now2=Date.now()){let claim=await _internals279.claimTerminalResult(directory,record3.correlationId,buildDelegationTerminal(record3,terminal,now2));if(claim){if(claim.disposition==="claimed")return await runDelegationTerminalObservations(directory,claim.record,terminal,observations,now2),{kind:"claimed",record:claim.record};if(claim.disposition==="duplicate"&&observations.transcript)await reconcileLaneKnowledgeReceipts(directory,claim.record,observations,!0);return{kind:"duplicate",record:claim.record}}let reread=_internals279.findByCorrelationIdDetailed(directory,record3.correlationId);if(reread.status==="uncertain")return{kind:"uncertain",reason:reread.reason};if(!reread.value)return{kind:"missing"};if(isTerminalDelegationStatus(reread.value.status)){if(reread.value.terminalResult)return{kind:"conflict",record:reread.value};return emitDelegationEventlessTerminalEnd(reread.value,reread.value.status),{kind:"already_terminal_without_event",record:reread.value}}return{kind:"not_open",record:reread.value}}function emitDelegationBegin(record3){try{_internals279.telemetry.delegationBegin(record3.parentSessionId,record3.swarmPrefixedAgent,record3.planTaskId??""),recordExecutionAttempt({sessionId:record3.parentSessionId,...record3.planTaskId?{taskId:record3.planTaskId}:{},attemptClass:"attempt",outcomeStatus:"unknown"})}catch{}}function terminalAttemptClass(status2){if(status2==="cancelled")return"cancelled";return"result"}function terminalAttemptOutcome(status2){if(status2==="completed")return"success";if(status2==="error"||status2==="failed")return"failure";return"unknown"}function emitDelegationCostObservation(record3,observations,terminalStatus,recovered=!1){try{let costFields=buildDelegationCostFields({raw:observations.costRaw,model:observations.model,pricing:observations.pricing});Object.assign(costFields,buildDelegationTerminalIdentityFields({record:record3,model:observations.model,recovered})),_internals279.telemetry.delegationEnd(record3.parentSessionId,record3.swarmPrefixedAgent,record3.planTaskId??"",terminalStatus,costFields);let usageAttested=costFields.cost_source==="reported";recordExecutionAttempt({sessionId:record3.parentSessionId,...record3.planTaskId?{taskId:record3.planTaskId}:{},...record3.callID?{callId:record3.callID}:{},...record3.laneId?{laneId:record3.laneId}:{},attemptClass:terminalAttemptClass(terminalStatus),outcomeStatus:terminalAttemptOutcome(terminalStatus),cost:{...observations.startedAt!==void 0?{latencyMs:Math.max(0,Date.now()-observations.startedAt)}:{},...usageAttested?{...typeof costFields.tokens_input==="number"?{inputTokens:costFields.tokens_input}:{},...typeof costFields.tokens_output==="number"?{outputTokens:costFields.tokens_output}:{},...typeof costFields.tokens_cache==="number"?{cacheReadTokens:costFields.tokens_cache}:{}}:{},...costFields.cost_source==="reported"&&costFields.cost_usd!==null?{billedCostUsd:costFields.cost_usd}:{},...costFields.cost_source==="estimated"&&costFields.cost_usd!==null?{estimatedCostUsd:costFields.cost_usd}:{}}})}catch(error93){log(`[delegation-lifecycle] cost observation skipped: ${error93 instanceof Error?error93.message:String(error93)}`)}}function emitDelegationEventlessTerminalEnd(record3,terminalStatus){emitDelegationCostObservation(record3,{},terminalStatus,!0)}async function appendDelegationTrajectoryObservation(directory,record3,terminalStatus,observations,now2){try{let lastStep=await getCurrentStep(record3.parentSessionId,directory);seedTrajectoryStepCounter(record3.parentSessionId,directory,lastStep);let entry={step:nextTrajectoryStep(record3.parentSessionId,directory),agent:record3.swarmPrefixedAgent,action:"delegate",target:record3.laneId??record3.correlationId,intent:`dispatch_lanes terminal ${terminalStatus}`,timestamp:new Date(now2).toISOString(),result:terminalStatus==="completed"?"success":"failure",tool:"dispatch_lanes",...observations.startedAt!==void 0?{elapsed_ms:Math.max(0,now2-observations.startedAt)}:{},...record3.batchId!==void 0?{batchId:record3.batchId}:{},laneId:record3.laneId??record3.correlationId,...record3.planTaskId?{taskId:record3.planTaskId}:{}};await appendTrajectoryEntry(record3.parentSessionId,entry,directory)}catch{}}async function reconcileLaneKnowledgeReceipts(directory,record3,observations,replay=!1){if(!observations.transcript)return;try{let ack=await collectLaneDelegateAcks({directory,sessionId:record3.subagentSessionId,agent:record3.swarmPrefixedAgent,transcript:observations.transcript,replay});if(record3.normalizedAgent!=="reviewer")return;let phase=ack.phases.find((value)=>Boolean(value));if(!phase)return;let directivesToVerify=await readPhaseDirectivesToVerify(directory,phase);if(directivesToVerify.length===0)return;await reconcileReviewerVerdicts({directory,transcript:observations.transcript,directivesToVerify,sessionId:record3.subagentSessionId,agent:"reviewer"})}catch{}}async function runDelegationTerminalObservations(directory,record3,terminal,observations,now2){emitDelegationCostObservation(record3,observations,terminal.status),await appendDelegationTrajectoryObservation(directory,record3,terminal.status,observations,now2),await reconcileLaneKnowledgeReceipts(directory,record3,observations)}function candidateAfter(record3,cursor){if(record3.updatedAt!==cursor.updatedAt)return record3.updatedAt>cursor.updatedAt;return record3.correlationId>cursor.correlationId}function readRecoveryCursor(directory){try{let filePath=path326.join(directory,".swarm",RECOVERY_CURSOR_FILE);if(!fs188.existsSync(filePath))return null;let parsed=JSON.parse(fs188.readFileSync(filePath,"utf-8"));if(typeof parsed.updatedAt==="number"&&Number.isFinite(parsed.updatedAt)&&typeof parsed.correlationId==="string"&&parsed.correlationId.length>0)return{updatedAt:parsed.updatedAt,correlationId:parsed.correlationId};return null}catch{return null}}function writeRecoveryCursor(directory,cursor){try{let swarmDir=path326.join(directory,".swarm");fs188.mkdirSync(swarmDir,{recursive:!0});let filePath=path326.join(swarmDir,RECOVERY_CURSOR_FILE);if(cursor===null)fs188.rmSync(filePath,{force:!0});else fs188.writeFileSync(filePath,JSON.stringify(cursor),"utf-8")}catch{}}function isRecoverableTerminalLaneRecord(record3){return Boolean(record3.laneId&&record3.terminalResult&&typeof record3.terminalResult.result.text==="string"&&record3.terminalResult.result.text.length>0)}async function recoverTerminalLaneReceipts(directory,records,options={}){let now2=options.now??Date.now,deadlineMs=options.deadlineMs??TERMINAL_LANE_RECEIPT_RECOVERY_DEADLINE_MS,deadline=now2()+deadlineMs;if(records!==void 0){let recovered2=0;for(let record3 of records){if(!isRecoverableTerminalLaneRecord(record3))continue;let transcript=record3.terminalResult?.result.text;if(!transcript)continue;if(now2()>=deadline)return{recovered:recovered2,exhaustedBudget:!0};try{await reconcileLaneKnowledgeReceipts(directory,record3,{transcript},!0),recovered2+=1}catch{}}return{recovered:recovered2,exhaustedBudget:!1}}let enumeration=readDelegationsDetailed(directory);if(enumeration.status==="uncertain")return warn(`[delegation-lifecycle] terminal-lane receipt recovery deferred: delegation store unreadable after ${enumeration.attempts} attempts (${enumeration.reason})`),{recovered:0,exhaustedBudget:!1};let candidates=enumeration.records.filter(isRecoverableTerminalLaneRecord).sort((left,right)=>{if(left.updatedAt!==right.updatedAt)return left.updatedAt-right.updatedAt;return left.correlationId<right.correlationId?-1:left.correlationId>right.correlationId?1:0});if(candidates.length===0)return{recovered:0,exhaustedBudget:!1};let cursor=readRecoveryCursor(directory),selected=cursor?candidates.filter((record3)=>candidateAfter(record3,cursor)):candidates,wrapped=!1;if(selected.length===0)selected=candidates,wrapped=!0;let recovered=0,lastProcessed=null;for(let record3 of selected){if(recovered>=MAX_TERMINAL_LANE_RECEIPT_RECOVERY)break;if(now2()>=deadline)break;let transcript=record3.terminalResult?.result.text;if(!transcript)continue;try{await reconcileLaneKnowledgeReceipts(directory,record3,{transcript},!0),recovered+=1,lastProcessed={updatedAt:record3.updatedAt,correlationId:record3.correlationId}}catch{lastProcessed={updatedAt:record3.updatedAt,correlationId:record3.correlationId}}}let lastCandidate=selected[selected.length-1],processedAll=selected.length>0&&lastProcessed!==null&&lastCandidate!==void 0&&lastProcessed.updatedAt===lastCandidate.updatedAt&&lastProcessed.correlationId===lastCandidate.correlationId,nextCursor=wrapped&&processedAll?null:lastProcessed??cursor??null;if(nextCursor?.correlationId!==cursor?.correlationId)writeRecoveryCursor(directory,nextCursor);return{recovered,exhaustedBudget:recovered<selected.length&&(now2()>=deadline||recovered>=MAX_TERMINAL_LANE_RECEIPT_RECOVERY)}}var MAX_TERMINAL_LANE_RECEIPT_RECOVERY=64,TERMINAL_LANE_RECEIPT_RECOVERY_DEADLINE_MS=5000,RECOVERY_CURSOR_FILE="lane-receipt-recovery-cursor.json",_internals279;var init_delegation_lifecycle=__esm(()=>{init_delegate_ack_collector();init_phase_directives();init_reviewer_verdict_parser();init_trajectory_step_state();init_trajectory_store();init_cost_accounting();init_execution_attempt();init_telemetry();init_logger();init_delegation_cost_identity();init_pending_delegations();init_delegation_cost_identity();registerStaleSweepObserver((record3)=>{emitDelegationEventlessTerminalEnd(record3,"stale")});_internals279={claimTerminalResult,findByCorrelationId,findByCorrelationIdDetailed,telemetry}});var exports_design_doc_drift={};__export(exports_design_doc_drift,{runDesignDocDriftCheck:()=>runDesignDocDriftCheck,_internals:()=>_internals306});import*as fs216 from"node:fs";import*as path357 from"node:path";function mtimeMsOrNull(absPath){try{return fs216.statSync(absPath).mtimeMs}catch{return null}}function resolveAnchorWithin(directory,anchor){if(!anchor||typeof anchor!=="string")return null;let root=path357.resolve(directory),resolved=path357.resolve(root,anchor),rel3=path357.relative(root,resolved);if(rel3.startsWith("..")||path357.isAbsolute(rel3))return null;return resolved}async function runDesignDocDriftCheck(directory,phase,outDir){try{let root=path357.resolve(directory),outAbs=path357.resolve(root,outDir),outRel=path357.relative(root,outAbs);if(outRel.startsWith("..")||path357.isAbsolute(outRel))return null;let docMtimes=new Map,checkedDocs=[],missingDocs=[];for(let[docName,relFile]of Object.entries(DESIGN_DOC_FILES)){let abs=path357.join(outAbs,relFile),mtime=mtimeMsOrNull(abs);if(docMtimes.set(docName,mtime),mtime===null)missingDocs.push(path357.join(outDir,relFile));else checkedDocs.push(path357.join(outDir,relFile))}let traceabilityAbs=path357.join(outAbs,TRACEABILITY_REL),registry4=null;try{if((await fs216.promises.stat(traceabilityAbs)).size<=MAX_TRACEABILITY_BYTES){let raw=await fs216.promises.readFile(traceabilityAbs,"utf-8"),parsed=JSON.parse(raw);registry4=parsed&&typeof parsed==="object"&&!Array.isArray(parsed)?parsed:null}}catch{registry4=null}let noDocs=checkedDocs.length===0||registry4===null,effectiveSpec=readEffectiveSpecSync(root),specMtime=effectiveSpec?.mtime?Date.parse(effectiveSpec.mtime):null,staleSections=[];if(!noDocs&&Array.isArray(registry4?.sections))for(let section2 of registry4.sections){if(!section2||typeof section2.section_id!=="string")continue;if(typeof section2.doc!=="string"||!docMtimes.has(section2.doc))continue;let docMtime=docMtimes.get(section2.doc)??null;if(docMtime===null){staleSections.push({section_id:section2.section_id,doc:section2.doc,reason:"owning design doc is missing"});continue}let flagged=!1;for(let anchor of section2.code_anchors??[]){let anchorAbs=resolveAnchorWithin(directory,anchor);if(anchorAbs===null)continue;let anchorMtime=mtimeMsOrNull(anchorAbs);if(anchorMtime!==null&&anchorMtime>docMtime){staleSections.push({section_id:section2.section_id,doc:section2.doc,reason:`code anchor ${anchor} changed after the doc`}),flagged=!0;break}}if(!flagged&&specMtime!==null&&specMtime>docMtime&&(section2.spec_frs?.length??0)>0)staleSections.push({section_id:section2.section_id,doc:section2.doc,reason:"effective spec changed after the doc"})}let verdict=noDocs?"NO_DOCS":staleSections.length>0?"DOC_STALE":"DOC_FRESH",report={schema_version:1,phase,timestamp:new Date().toISOString(),out_dir:outDir,verdict,stale_sections:staleSections,missing_docs:missingDocs,checked_docs:checkedDocs},locator=phaseReportLocator("design_doc_drift",phase);return await upsertPhaseReportDb(directory,"design_doc_drift",phase,JSON.stringify(report,null,2)),getGlobalEventBus().publish("curator.docdrift.completed",{phase,verdict,stale_count:staleSections.length,report_path:locator}),report}catch(err){try{getGlobalEventBus().publish("curator.error",{operation:"docdrift",phase,error:String(err)})}catch{}return warn(`[design-doc-drift] check failed for phase ${phase}: ${String(err)}`),null}}var MAX_TRACEABILITY_BYTES=1048576,DESIGN_DOC_FILES,TRACEABILITY_REL,_internals306;var init_design_doc_drift=__esm(()=>{init_event_bus();init_phase_report_store();init_effective_spec();init_logger();DESIGN_DOC_FILES={domain:"domain.md","technical-spec":"technical-spec.md","behavior-spec":"behavior-spec.md","reference-impl":path357.join("reference","reference-impl.md"),"idiom-notes":path357.join("reference","idiom-notes.md")},TRACEABILITY_REL=path357.join("reference","traceability.json");_internals306={mtimeMsOrNull,resolveAnchorWithin,DESIGN_DOC_FILES}});var exports_project_context={};__export(exports_project_context,{buildProjectContext:()=>buildProjectContext,_internals:()=>_internals341,LANG_BACKEND_DETECTION_TIMEOUT_MS:()=>LANG_BACKEND_DETECTION_TIMEOUT_MS});import*as fs246 from"node:fs";import*as path395 from"node:path";function detectFileExists2(directory,pattern){if(pattern.includes("*")||pattern.includes("?"))try{let files=fs246.readdirSync(directory),regex=new RegExp(`^${pattern.replace(/\./g,"\\.").replace(/\*/g,".*").replace(/\?/g,".")}$`);return files.some((f)=>regex.test(f))}catch{return!1}try{return fs246.accessSync(path395.join(directory,pattern)),!0}catch{return!1}}function selectTestCommandFromScriptsTest(backend,directory){let pkgRaw;try{pkgRaw=fs246.readFileSync(path395.join(directory,"package.json"),"utf-8")}catch{return null}let pkg;try{pkg=JSON.parse(pkgRaw)}catch{return null}let script=pkg.scripts?.test;if(!script)return null;let fwName=null;if(script.includes("vitest"))fwName="vitest";else if(script.includes("jest"))fwName="jest";else if(script.includes("mocha"))fwName="mocha";else if(script.includes("bun test"))fwName="bun:test";if(!fwName)return null;let fw=backend.test.frameworks.find((f)=>f.name===fwName);return fw?fw.cmd:null}function selectTestCommandFast(backend,directory){let fromScripts=selectTestCommandFromScriptsTest(backend,directory);if(fromScripts!==null)return fromScripts;let sorted2=[...backend.test.frameworks].sort((a,b)=>b.priority-a.priority);for(let fw of sorted2){if(!detectFileExists2(directory,fw.detect))continue;return fw.cmd}return null}function selectBuildCommandFast(backend,directory){let sorted2=[...backend.build.commands].sort((a,b)=>b.priority-a.priority);for(let cmd of sorted2){if(cmd.detectFile&&!detectFileExists2(directory,cmd.detectFile))continue;return cmd.cmd}return null}function selectLintCommand(backend,directory){let sorted2=[...backend.lint.linters].sort((a,b)=>b.priority-a.priority);for(let lint2 of sorted2){if(!detectFileExists2(directory,lint2.detect))continue;return lint2.cmd}return null}async function buildProjectContext(directory,signal2){let backend=await _internals341.pickBackend(directory,signal2);if(!backend)return null;let profiles=_internals341.pickedProfiles(directory),ctx=emptyProjectContext();ctx.PROJECT_LANGUAGE=backend.displayName;let buildCmd=selectBuildCommandFast(backend,directory);if(buildCmd)ctx.BUILD_CMD=buildCmd;let testCmd=selectTestCommandFast(backend,directory);if(testCmd)ctx.TEST_CMD=testCmd;let lintCmd=selectLintCommand(backend,directory);if(lintCmd)ctx.LINT_CMD=lintCmd;if(backend.id==="php"){let overlay=getLaravelCommandOverlay(directory);if(overlay){if(ctx.TEST_CMD=overlay.testCommand,overlay.lintCommand)ctx.LINT_CMD=overlay.lintCommand}}let[frameworkSel,entryPoints]=await Promise.all([backend.selectFramework?backend.selectFramework(directory).catch(()=>null):Promise.resolve(null),backend.selectEntryPoints?backend.selectEntryPoints(directory).catch(()=>[]):Promise.resolve([])]);if(frameworkSel)ctx.PROJECT_FRAMEWORK=frameworkSel.name;if(entryPoints.length>0)ctx.ENTRY_POINTS=entryPoints.join(", ");if(backend.prompts.coderConstraints.length>0)ctx.CODER_CONSTRAINTS=bulletList(backend.prompts.coderConstraints);if(backend.prompts.testConstraints&&backend.prompts.testConstraints.length>0)ctx.TEST_CONSTRAINTS=bulletList(backend.prompts.testConstraints);if(backend.prompts.reviewerChecklist.length>0)ctx.REVIEWER_CHECKLIST=bulletList(backend.prompts.reviewerChecklist);if(profiles.length>1)ctx.PROJECT_CONTEXT_SECONDARY_LANGUAGES=profiles.slice(1).map((p)=>p.id).join(", ");return ctx}var LANG_BACKEND_DETECTION_TIMEOUT_MS=300,_internals341;var init_project_context=__esm(()=>{init_dispatch();init_framework_detector();_internals341={pickBackend,pickedProfiles}});init_package();init_agents2();init_critic();import{createHash as createHash123}from"node:crypto";import{mkdirSync as mkdirSync103,writeFileSync as writeFileSync66}from"node:fs";import*as path396 from"node:path";import{performance as performance2}from"node:perf_hooks";import{fileURLToPath as fileURLToPath8}from"node:url";init_event_bus();init_evidence_summary_integration();init_manager4();init_manager();init_utils();import*as fs160 from"node:fs";import*as path289 from"node:path";class PlanSyncWorker{directory;debounceMs;pollIntervalMs;syncTimeoutMs;onSyncComplete;status="stopped";watcher=null;pollTimer=null;debounceTimer=null;syncing=!1;pendingSync=!1;lastStat=null;disposed=!1;constructor(options={}){this.directory=options.directory??"",this.debounceMs=options.debounceMs??500,this.pollIntervalMs=options.pollIntervalMs??2000,this.syncTimeoutMs=options.syncTimeoutMs??30000,this.onSyncComplete=options.onSyncComplete}getSwarmDir(){return path289.resolve(this.directory,".swarm")}getPlanJsonPath(){return path289.join(this.getSwarmDir(),"plan.json")}start(){if(this.disposed){log("[PlanSyncWorker] Cannot start - worker has been disposed");return}if(!this.directory){log("[PlanSyncWorker] Cannot start - no directory provided");return}if(this.status==="running"||this.status==="starting"){log("[PlanSyncWorker] Already running or starting");return}this.status="starting",log("[PlanSyncWorker] Starting..."),this.initializeStat(),this.setupPolling(),this.setupNativeWatcher(),this.status="running",log("[PlanSyncWorker] Started watching for plan.json changes")}stop(){if(this.status==="stopped"||this.status==="stopping")return;if(this.status="stopping",log("[PlanSyncWorker] Stopping..."),this.clearDebounce(),this.watcher)this.watcher.close(),this.watcher=null;if(this.pollTimer)clearInterval(this.pollTimer),this.pollTimer=null;this.status="stopped",log("[PlanSyncWorker] Stopped")}dispose(){this.stop(),this.disposed=!0,this.lastStat=null,log("[PlanSyncWorker] Disposed")}getStatus(){return this.status}isRunning(){return this.status==="running"}initializeStat(){try{let stats2=fs160.statSync(this.getPlanJsonPath());this.lastStat={mtimeMs:stats2.mtimeMs,size:stats2.size}}catch{this.lastStat=null}}setupNativeWatcher(){let swarmDir=this.getSwarmDir();try{if(!fs160.existsSync(swarmDir))return log("[PlanSyncWorker] Swarm directory does not exist yet"),!1;return this.watcher=fs160.watch(swarmDir,{persistent:!1},(_eventType,filename)=>{if(this.disposed||this.status!=="running")return;if(filename&&(filename.includes(".tmp.")||filename.endsWith(".rebuild")))return;if(filename==="plan.json"||filename===void 0)this.debouncedSync()}),this.watcher.on("error",(error93)=>{if(this.disposed||this.status!=="running")return;if(log("[PlanSyncWorker] Watcher error, falling back to polling",{error:error93.message}),this.watcher)this.watcher.close(),this.watcher=null;this.setupPolling()}),log("[PlanSyncWorker] Native fs.watch established"),!0}catch(error93){return log("[PlanSyncWorker] Failed to setup native watcher",{error:error93 instanceof Error?error93.message:String(error93)}),!1}}setupPolling(){if(this.pollTimer)clearInterval(this.pollTimer);if(this.pollTimer=setInterval(()=>{if(this.disposed||this.status!=="running")return;this.pollCheck()},this.pollIntervalMs),typeof this.pollTimer.unref==="function")this.pollTimer.unref();log("[PlanSyncWorker] Polling fallback established",{intervalMs:this.pollIntervalMs})}pollCheck(){try{let planPath=this.getPlanJsonPath();if(!fs160.existsSync(planPath)){if(this.lastStat!==null)this.lastStat=null,log("[PlanSyncWorker] plan.json deleted");return}let stats2=fs160.statSync(planPath),currentStat={mtimeMs:stats2.mtimeMs,size:stats2.size};if(this.lastStat===null||currentStat.mtimeMs!==this.lastStat.mtimeMs||currentStat.size!==this.lastStat.size)this.lastStat=currentStat,this.debouncedSync()}catch(error93){log("[PlanSyncWorker] Poll check error",{error:error93 instanceof Error?error93.message:String(error93)})}}debouncedSync(){if(this.disposed||this.status!=="running")return;if(this.debounceTimer)clearTimeout(this.debounceTimer);this.debounceTimer=setTimeout(()=>{if(this.disposed||this.status!=="running")return;this.debounceTimer=null,this.triggerSync()},this.debounceMs)}clearDebounce(){if(this.debounceTimer)clearTimeout(this.debounceTimer),this.debounceTimer=null}triggerSync(){if(this.syncing){this.pendingSync=!0,log("[PlanSyncWorker] Sync pending (in-flight)");return}this.executeSync()}async executeSync(){this.syncing=!0;try{log("[PlanSyncWorker] Syncing plan..."),this.checkForUnauthorizedWrite();let plan=await this.withTimeout(_internals66.loadPlanJsonOnly(this.directory),this.syncTimeoutMs,"Sync operation timed out");if(plan&&plan.phases.length>0)await _internals66.regeneratePlanMarkdown(this.directory,plan),log("[PlanSyncWorker] Sync complete",{title:plan.title,phase:plan.current_phase}),this.safeCallback(!0);else if(plan)log("[PlanSyncWorker] Plan has no phases, skipping markdown regeneration"),this.safeCallback(!0);else log("[PlanSyncWorker] No plan found to sync"),this.safeCallback(!0)}catch(error93){if(error93 instanceof Error&&error93.message.includes("timed out"))log("[PlanSyncWorker] Sync timed out after "+this.syncTimeoutMs+"ms, worker remains active");else log("[PlanSyncWorker] Sync failed",{error:error93 instanceof Error?error93.message:String(error93)});this.safeCallback(!1,error93 instanceof Error?error93:Error(String(error93)))}finally{if(this.syncing=!1,this.pendingSync&&!this.disposed&&this.status==="running")this.pendingSync=!1,log("[PlanSyncWorker] Executing pending sync"),this.executeSync()}}safeCallback(success3,error93){if(this.onSyncComplete)try{this.onSyncComplete(success3,error93)}catch(callbackError){log("[PlanSyncWorker] onSyncComplete callback threw error (ignored)",{callbackError:callbackError instanceof Error?callbackError.message:String(callbackError)})}}checkForUnauthorizedWrite(){try{let swarmDir=this.getSwarmDir(),planJsonPath=path289.join(swarmDir,"plan.json"),markerPath=path289.join(swarmDir,".plan-write-marker"),planStats=fs160.statSync(planJsonPath),planMtimeMs=Math.floor(planStats.mtimeMs),markerContent=fs160.readFileSync(markerPath,"utf8"),marker=JSON.parse(markerContent);if(marker.in_progress===!0){log("[PlanSyncWorker] Skipping unauthorized-write check - plan write in progress");return}let markerTimestampMs=new Date(marker.timestamp).getTime();if(planMtimeMs>markerTimestampMs+5000)log("[PlanSyncWorker] WARNING: plan.json may have been written outside save_plan/savePlan - unauthorized direct write suspected",{planMtimeMs,markerTimestampMs})}catch{}}withTimeout(promise3,ms2,timeoutMessage2){return new Promise((resolve111,reject2)=>{let timer=setTimeout(()=>{reject2(Error(`${timeoutMessage2} (${ms2}ms)`))},ms2);promise3.then((result)=>{clearTimeout(timer),resolve111(result)}).catch((error93)=>{clearTimeout(timer),reject2(error93)})})}}init_pr_event_subscribers();init_pr_feedback_loop_runtime();init_pr_monitor_worker();init_queue();init_status_artifact();init_trigger();init_worker();init_lifecycle();init_residue_commit();import{createHash as createHash101}from"node:crypto";init_zod();init_task_envelope();init_workspace_snapshot();init_plan_schema();init_schema();init_plan_task_id_context();init_task_id_resolver();init_task_result_classifier();init_utils2();init_ledger();init_manager();init_utils3();init_atomic_write();init_canonical_root();init_lock();init_task_file();import{createHash as createHash100}from"node:crypto";import*as fs162 from"node:fs";import*as path291 from"node:path";var PHASE_PARTICIPATION_FILE="evidence/phase-participation.json",PHASE_PARTICIPATION_QUARANTINE_DIR="evidence/phase-participation-quarantine",MAX_PHASE_PARTICIPATION_BYTES=262144,MAX_PHASE_PARTICIPATION_PENDING=128,MAX_PHASE_PARTICIPATION_RECEIPTS=128,MAX_PHASE_PARTICIPATION_QUARANTINE_FILES=16,MAX_PHASE_PARTICIPATION_QUARANTINE_BYTES=1048576,MAX_PHASE_PARTICIPATION_QUARANTINE_DIRECTORY_ENTRIES=64,MAX_PENDING_IN_MEMORY=128,MAX_ID_CHARS=256,WorkspaceSchema2=exports_external.object({directory:exports_external.string().max(4096),gitHead:exports_external.string().max(256).nullable(),prHeadSha:exports_external.string().max(256).nullable()}).strict(),BindingSchema=exports_external.object({role:exports_external.string().min(1).max(120),prefixedRole:exports_external.string().min(1).max(120),planId:exports_external.string().min(1).max(512),planIdentityHash:exports_external.string().length(64),planStructureHash:exports_external.string().length(64),phase:exports_external.number().int().nonnegative(),taskId:exports_external.string().min(1).max(120).nullable(),parentSessionId:exports_external.string().min(1).max(MAX_ID_CHARS),callId:exports_external.string().min(1).max(MAX_ID_CHARS),policyDigest:exports_external.string().length(64),workspace:WorkspaceSchema2,capturedAt:exports_external.number().int().nonnegative()}).strict(),PendingSchema=BindingSchema.extend({childSessionId:exports_external.string().min(1).max(MAX_ID_CHARS)}).strict(),ReceiptSchema=PendingSchema.extend({receiptId:exports_external.string().length(64),resultDigest:exports_external.string().length(64),completedAt:exports_external.number().int().nonnegative(),childIdentityAvailable:exports_external.boolean()}).strict(),StoreSchema=exports_external.object({schemaVersion:exports_external.literal(1),pending:exports_external.array(PendingSchema).max(MAX_PHASE_PARTICIPATION_PENDING),receipts:exports_external.array(ReceiptSchema).max(MAX_PHASE_PARTICIPATION_RECEIPTS)}).strict(),foregroundReservations=new Map;function emptyStore(){return{schemaVersion:1,pending:[],receipts:[]}}function correlationKey2(parentSessionId,callId){return`${parentSessionId}\x00${callId}`}function sha25611(value){return createHash100("sha256").update(value).digest("hex")}function policyDigest(policy){return sha25611(stableCanonicalStringify(policy??{}))}async function captureParticipationWorkspace(directory){let workspace=await captureWorkspaceSnapshotAsync(directory,{resolveCurrentPrHeadSha:!0});return{directory:workspace.directory,gitHead:workspace.gitHead,prHeadSha:workspace.prHeadSha}}function boundedPut(binding){let key2=correlationKey2(binding.parentSessionId,binding.callId);foregroundReservations.delete(key2),foregroundReservations.set(key2,binding);while(foregroundReservations.size>MAX_PENDING_IN_MEMORY){let oldest=foregroundReservations.keys().next().value;if(!oldest)break;foregroundReservations.delete(oldest)}}function takeBinding(parentSessionId,callId){let key2=correlationKey2(parentSessionId,callId),binding=foregroundReservations.get(key2)??null;return foregroundReservations.delete(key2),binding}async function persistWithBindingRecovery(directory,binding,operation){try{await withEvidenceLock(directory,PHASE_PARTICIPATION_FILE,"docs","phase-participation",operation)}catch(error93){throw boundedPut(binding),error93}}async function buildBinding(input){return{role:stripKnownSwarmPrefix(input.role),prefixedRole:input.role,planId:derivePlanId(input.plan),planIdentityHash:derivePlanIdentityHash(input.plan),planStructureHash:receiptStructureHash(input.plan),phase:input.phase,taskId:input.taskId,parentSessionId:input.parentSessionId,callId:input.callId,policyDigest:policyDigest(input.policy),workspace:await captureParticipationWorkspace(input.directory),capturedAt:Date.now()}}function extractPlanTaskId2(args2,plan){let context=collectPlanTaskIdContextFromPhases(plan.phases),result=resolveTaskId(args2,{policy:"plan",...toTaskIdPlanContextOptions(context)});if(result.status!=="resolved")return null;if(context.status==="over_limit"&&!plan.phases.some((phase)=>phase?.tasks?.some((task2)=>task2?.id===result.taskId)))return null;return result.taskId}function storePath6(directory){return validateSwarmPath(directory,PHASE_PARTICIPATION_FILE)}function readRawStore(directory){let filePath;try{filePath=storePath6(directory)}catch(error93){return{status:"unreadable",error:error93}}let descriptor,bytes;try{let pathStat=fs162.lstatSync(filePath);if(pathStat.isSymbolicLink()||!pathStat.isFile())return{status:"unreadable",error:Error("Participation projection is not a regular file")};if(pathStat.size>MAX_PHASE_PARTICIPATION_BYTES)return{status:"oversized",bytes:pathStat.size};descriptor=fs162.openSync(filePath,fs162.constants.O_RDONLY|(fs162.constants.O_NOFOLLOW??0));let openedStat=fs162.fstatSync(descriptor);if(!openedStat.isFile()||openedStat.dev!==pathStat.dev||openedStat.ino!==pathStat.ino)return{status:"unreadable",error:Error("Participation projection changed while it was being opened")};if(openedStat.size>MAX_PHASE_PARTICIPATION_BYTES)return{status:"oversized",bytes:openedStat.size};let bounded=Buffer.allocUnsafe(MAX_PHASE_PARTICIPATION_BYTES+1),offset=0;while(offset<bounded.byteLength){let read=fs162.readSync(descriptor,bounded,offset,bounded.byteLength-offset,null);if(read===0)break;offset+=read}if(offset>MAX_PHASE_PARTICIPATION_BYTES)return{status:"oversized",bytes:offset};bytes=bounded.subarray(0,offset)}catch(error93){if(error93.code==="ENOENT")return{status:"missing"};return{status:"unreadable",error:error93}}finally{if(descriptor!==void 0)try{fs162.closeSync(descriptor)}catch{}}try{return{status:"valid",store:StoreSchema.parse(JSON.parse(bytes.toString("utf8")))}}catch{return{status:"corrupt",bytes}}}async function atomicWriteBytes(filePath,bytes){await atomicWriteSwarmFile(filePath,bytes)}async function readBoundedRegularFile(filePath,maxBytes){let pathStat=await fs162.promises.lstat(filePath);if(pathStat.isSymbolicLink()||!pathStat.isFile()||pathStat.size>maxBytes)throw Error("bounded evidence artifact is not a permitted regular file");let handle=await fs162.promises.open(filePath,fs162.constants.O_RDONLY|(fs162.constants.O_NOFOLLOW??0));try{let openedStat=await handle.stat();if(!openedStat.isFile()||openedStat.dev!==pathStat.dev||openedStat.ino!==pathStat.ino||openedStat.size>maxBytes)throw Error("bounded evidence artifact changed while being opened");let bounded=Buffer.allocUnsafe(maxBytes+1),offset=0;while(offset<bounded.byteLength){let{bytesRead}=await handle.read(bounded,offset,bounded.byteLength-offset,null);if(bytesRead===0)break;offset+=bytesRead}if(offset>maxBytes)throw Error("bounded evidence artifact exceeds its byte limit");return bounded.subarray(0,offset)}finally{try{await handle.close()}catch{}}}function quarantineFullError(){return Error("PHASE_PARTICIPATION_QUARANTINE_FULL: preserved corrupt evidence reached its bounded retention limit; an operator must archive the quarantine before docs can be re-dispatched.")}async function quarantineCorruptBytes(directory,bytes){let digest4=sha25611(bytes),quarantineDir=validateSwarmPath(directory,PHASE_PARTICIPATION_QUARANTINE_DIR);await fs162.promises.mkdir(quarantineDir,{recursive:!0});let quarantineStat=await fs162.promises.lstat(quarantineDir);if(quarantineStat.isSymbolicLink()||!quarantineStat.isDirectory())throw Error("PHASE_PARTICIPATION_QUARANTINE_UNREADABLE: quarantine is not a regular directory.");let target=validateSwarmPath(directory,`${PHASE_PARTICIPATION_QUARANTINE_DIR}/${digest4}.bin`);try{if(!(await readBoundedRegularFile(target,MAX_PHASE_PARTICIPATION_BYTES)).equals(bytes))throw Error("hash-addressed quarantine content mismatch");return}catch(error93){if(error93.code!=="ENOENT")throw error93}let count4=0,totalBytes=0,scanned=0,handle=await fs162.promises.opendir(quarantineDir,{bufferSize:16});try{for await(let entry of handle){if(scanned+=1,scanned>MAX_PHASE_PARTICIPATION_QUARANTINE_DIRECTORY_ENTRIES)throw quarantineFullError();if(!entry.isFile()||!/^[a-f0-9]{64}\.bin$/.test(entry.name))continue;count4+=1;let candidate2=validateSwarmPath(directory,`${PHASE_PARTICIPATION_QUARANTINE_DIR}/${entry.name}`),candidateStat=await fs162.promises.lstat(candidate2);if(candidateStat.isSymbolicLink()||!candidateStat.isFile())throw Error("PHASE_PARTICIPATION_QUARANTINE_UNREADABLE: invalid quarantine artifact.");if(totalBytes+=candidateStat.size,count4>=MAX_PHASE_PARTICIPATION_QUARANTINE_FILES||totalBytes+bytes.byteLength>MAX_PHASE_PARTICIPATION_QUARANTINE_BYTES)throw quarantineFullError()}}finally{try{await handle.close()}catch{}}await atomicWriteBytes(target,bytes)}async function loadWritableStoreUnderLock(directory){let read=readRawStore(directory);if(read.status==="missing")return emptyStore();if(read.status==="valid")return read.store;if(read.status==="corrupt")return await quarantineCorruptBytes(directory,read.bytes),emptyStore();if(read.status==="oversized")throw Error(`PHASE_PARTICIPATION_OVERSIZED: ${read.bytes} bytes exceeds ${MAX_PHASE_PARTICIPATION_BYTES}; operator action is required before docs can be re-dispatched.`);throw Error("PHASE_PARTICIPATION_UNREADABLE: operator action is required before docs can be re-dispatched.")}async function writeStore3(directory,store){let validatedStore=StoreSchema.parse(store);validatedStore.pending.sort((left,right)=>left.capturedAt-right.capturedAt),validatedStore.receipts.sort((left,right)=>left.completedAt-right.completedAt);let serialized3=JSON.stringify(validatedStore,null,2);while(Buffer.byteLength(serialized3,"utf8")>MAX_PHASE_PARTICIPATION_BYTES){let pendingTime=validatedStore.pending[0]?.capturedAt??1/0,receiptTime=validatedStore.receipts[0]?.completedAt??1/0;if(pendingTime===1/0&&receiptTime===1/0)throw Error("PHASE_PARTICIPATION_WRITE_OVERSIZED: even an empty participation store exceeds its byte limit.");if(pendingTime<=receiptTime)validatedStore.pending.shift();else validatedStore.receipts.shift();validatedStore=StoreSchema.parse(validatedStore),serialized3=JSON.stringify(validatedStore,null,2)}await fs162.promises.mkdir(path291.dirname(storePath6(directory)),{recursive:!0}),await atomicWriteFile(storePath6(directory),serialized3)}function receiptStructureHash(plan){return computePlanStructureHash({...plan,current_phase:void 0})}function samePlanIdentity(binding,plan){return binding.planId===derivePlanId(plan)&&binding.planIdentityHash===derivePlanIdentityHash(plan)&&binding.planStructureHash===receiptStructureHash(plan)}function bindingMatchesPlan(binding,plan,phase){return samePlanIdentity(binding,plan)&&binding.phase===phase}function receiptCursorCoversPhase(receiptPhase,phase,plan){let cursorPhase=getCurrentPhase(plan);if(receiptPhase!==cursorPhase||cursorPhase===phase)return!1;if(cursorPhase<phase)return!0;return isPhaseInWrapWindow(plan,phase)}function workspaceIdentityIsFresh(expected,current){return sameProjectRoot(expected.directory,current.directory)&&expected.gitHead===current.gitHead&&expected.prHeadSha===current.prHeadSha}function resultText(output){if(!output||typeof output!=="object")return{text:"",childSessionId:null};let record3=output,rawOutput=typeof record3.output==="string"?record3.output:"",envelope=parseTaskEnvelope(rawOutput);if(envelope?.state==="completed")return{text:envelope.resultText??"",childSessionId:envelope.sessionId};return{text:rawOutput,childSessionId:null}}function envelopeFromOutput(output){if(typeof output==="string")return parseTaskEnvelope(output);if(!output||typeof output!=="object")return null;let rawOutput=output.output;return typeof rawOutput==="string"?parseTaskEnvelope(rawOutput):null}function validateMetadata(output,parentSessionId,childSessionId){if(!output||typeof output!=="object")return{valid:!0,childSessionId};let metadata=output.metadata;if(!metadata||typeof metadata!=="object")return{valid:!0,childSessionId};let meta3=metadata;if(typeof meta3.parentSessionId==="string"&&meta3.parentSessionId!==parentSessionId)return{valid:!1,childSessionId:null};let metadataChild=typeof meta3.sessionId==="string"&&meta3.sessionId.length>0?meta3.sessionId:null;if(childSessionId&&metadataChild&&childSessionId!==metadataChild)return{valid:!1,childSessionId:null};return{valid:!0,childSessionId:childSessionId??metadataChild}}function computeReceiptId(input){return sha25611(stableCanonicalStringify({parentSessionId:input.parentSessionId,callId:input.callId,childSessionId:input.childSessionId,planIdentityHash:input.planIdentityHash,planStructureHash:input.planStructureHash,phase:input.phase,role:input.role}))}function addReceipt(store,pending,text,childIdentityAvailable){let receiptId=computeReceiptId(pending),receipt={...pending,receiptId,resultDigest:sha25611(text),completedAt:Date.now(),childIdentityAvailable};store.receipts=store.receipts.filter((existing)=>existing.receiptId!==receiptId&&!(existing.planIdentityHash===receipt.planIdentityHash&&existing.planStructureHash===receipt.planStructureHash&&existing.phase===receipt.phase&&existing.role===receipt.role)),store.receipts.push(receipt),store.receipts=store.receipts.slice(-MAX_PHASE_PARTICIPATION_RECEIPTS)}async function reserveApprovedPhaseParticipation(input){if(input.tool.toLowerCase()!=="task")return;let rawRole=input.args.subagent_type;if(typeof rawRole!=="string"||stripKnownSwarmPrefix(rawRole)!=="docs")return;let plan=await loadPlan(input.directory);if(!plan)return;let binding=await buildBinding({plan,phase:getCurrentPhase(plan),role:rawRole,parentSessionId:input.parentSessionId,callId:input.callId,taskId:extractPlanTaskId2(input.args,plan),policy:input.policy,directory:input.directory});await withEvidenceLock(input.directory,PHASE_PARTICIPATION_FILE,"docs","phase-participation",async()=>{let store=await loadWritableStoreUnderLock(input.directory);await writeStore3(input.directory,store)}),boundedPut(binding)}async function observePhaseParticipationToolResult(input){if(input.tool.toLowerCase()!=="task")return;let binding=takeBinding(input.parentSessionId,input.callId);if(!binding)return;let envelope=envelopeFromOutput(input.output);if(envelope?.state==="running"){let{subagentSessionId}=extractDispatchIds(input.output);if(!subagentSessionId||subagentSessionId!==envelope.sessionId)return;let pending2={...binding,childSessionId:subagentSessionId};await persistWithBindingRecovery(input.directory,binding,async()=>{let store=await loadWritableStoreUnderLock(input.directory);store.pending=store.pending.filter((existing)=>existing.childSessionId!==pending2.childSessionId&&!(existing.parentSessionId===pending2.parentSessionId&&existing.callId===pending2.callId)),store.pending.push(pending2),store.pending=store.pending.slice(-MAX_PHASE_PARTICIPATION_PENDING),await writeStore3(input.directory,store)});return}if(envelope&&envelope.state!=="completed")return;if(classifyTaskResult(input.output)!=="success")return;let extracted=resultText(input.output),text=extracted.text.trim();if(!text)return;let metadata=validateMetadata(input.output,input.parentSessionId,extracted.childSessionId);if(!metadata.valid)return;let childSessionId=metadata.childSessionId,currentPlan=await loadPlan(input.directory);if(!currentPlan||!bindingMatchesPlan(binding,currentPlan,binding.phase))return;if(!workspaceIdentityIsFresh(binding.workspace,await captureParticipationWorkspace(input.directory)))return;let pending={...binding,childSessionId:childSessionId??`unavailable:${sha25611(correlationKey2(input.parentSessionId,input.callId))}`};await persistWithBindingRecovery(input.directory,binding,async()=>{let store=await loadWritableStoreUnderLock(input.directory);addReceipt(store,pending,text,childSessionId!==null),await writeStore3(input.directory,store)})}async function completeBackgroundPhaseParticipation(input){if(stripKnownSwarmPrefix(input.record.normalizedAgent)!=="docs")return!1;let text=input.resultText.trim();if(!text)return!1;return withEvidenceLock(input.directory,PHASE_PARTICIPATION_FILE,"docs","phase-participation",async()=>{let store=await loadWritableStoreUnderLock(input.directory),currentPlan=await loadPlan(input.directory),existingReceipt=store.receipts.find((receipt)=>receipt.childSessionId===input.record.subagentSessionId&&receipt.parentSessionId===input.record.parentSessionId&&receipt.callId===input.record.callID&&receipt.role===input.record.normalizedAgent&&receipt.prefixedRole===input.record.swarmPrefixedAgent&&receipt.taskId===input.record.planTaskId);if(existingReceipt&¤tPlan&&bindingMatchesPlan(existingReceipt,currentPlan,existingReceipt.phase))return!0;let pending=store.pending.find((candidate2)=>candidate2.childSessionId===input.record.subagentSessionId&&candidate2.parentSessionId===input.record.parentSessionId&&candidate2.callId===input.record.callID&&candidate2.role===input.record.normalizedAgent&&candidate2.prefixedRole===input.record.swarmPrefixedAgent&&candidate2.taskId===input.record.planTaskId);if(!pending)return!1;let plan=currentPlan;if(!plan||!bindingMatchesPlan(pending,plan,pending.phase))return!1;if(!workspaceIdentityIsFresh(pending.workspace,await captureParticipationWorkspace(input.directory)))return!1;if(pending.taskId!==null&&input.record.ingestion?.state!=="consumed")return!1;return addReceipt(store,pending,text,!0),store.pending=store.pending.filter((candidate2)=>candidate2.childSessionId!==pending.childSessionId),await writeStore3(input.directory,store),!0})}async function readPhaseParticipation(directory,plan,phase,role){let read=readRawStore(directory);if(read.status!=="valid")return{status:read.status,found:!1};let canonicalRole2=stripKnownSwarmPrefix(role),currentWorkspace=await captureParticipationWorkspace(directory);return{status:"valid",found:read.store.receipts.some((receipt)=>receipt.role===canonicalRole2&&samePlanIdentity(receipt,plan)&&workspaceIdentityIsFresh(receipt.workspace,currentWorkspace)&&(receipt.phase===phase||receiptCursorCoversPhase(receipt.phase,phase,plan)))}}async function rebindCursorTaggedReceipts(directory,plan,phase,role){let canonicalRole2=stripKnownSwarmPrefix(role),peek=readRawStore(directory);if(peek.status==="unreadable"||peek.status==="oversized")throw Error(peek.status==="oversized"?`the participation store is oversized (${peek.bytes} bytes)`:`the participation store could not be read (${peek.error instanceof Error?peek.error.message:String(peek.error)})`);if(!(peek.status==="valid"&&peek.store.receipts.some((receipt)=>receipt.role===canonicalRole2&&samePlanIdentity(receipt,plan)&&receiptCursorCoversPhase(receipt.phase,phase,plan))))return{rebound:0};return withEvidenceLock(directory,PHASE_PARTICIPATION_FILE,"docs","phase-participation",async()=>{let store=await loadWritableStoreUnderLock(directory),rebound=0;for(let receipt of store.receipts)if(receipt.role===canonicalRole2&&samePlanIdentity(receipt,plan)&&receiptCursorCoversPhase(receipt.phase,phase,plan))receipt.phase=phase,receipt.receiptId=computeReceiptId(receipt),rebound+=1;if(rebound>0){let newestByKey=new Map;for(let receipt of store.receipts.slice().sort((left,right)=>left.completedAt-right.completedAt))newestByKey.set(`${receipt.planIdentityHash}\x00${receipt.planStructureHash}\x00${receipt.phase}\x00${receipt.role}`,receipt);store.receipts=[...newestByKey.values()],await writeStore3(directory,store)}return{rebound}})}init_gate_evidence();init_worktree_isolation();init_helpers();init_state();init_canonical_root();init_logger();init_coder_settlement();init_merge2();init_pending_delegations();init_loader();init_task_gate_requirements();init_gate_evidence();init_gate_evidence_classification();init_review_receipt_collector();init_reviewer_scope_file_fingerprint();init_routing_enforcement();init_scope_binding();init_state();init_logger();init_workspace_snapshot();var GATE_EVIDENCE_ROLES=new Set(["reviewer","test_engineer","docs","designer","critic","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","explorer","sme"]);function structuredStageBVerdict(role,text,taskId){let escapedTaskId=taskId.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),match=(role==="reviewer"?new RegExp(`^\\[REVIEWED\\]\\s*\\|\\s*(?:task-)?${escapedTaskId}\\s*\\|\\s*(APPROVED|REJECTED|CONCERNS)\\s*\\|`,"im"):new RegExp(`^\\[TESTED\\]\\s*\\|\\s*(?:task-)?${escapedTaskId}\\s*\\|\\s*(PASS|FAIL|SKIPPED)\\s*\\|`,"im")).exec(text);if(!match)return null;if(match[1]==="APPROVED"||match[1]==="PASS")return"pass";if(match[1]==="SKIPPED")return"skip";return"fail"}function normalizeAttributionPath(file3){let normalized=file3.trim().replaceAll("\\","/").replace(/^\.\/+/,""),hasControlCharacter5=[...normalized].some((character)=>{let code=character.charCodeAt(0);return code<=31||code===127});if(!normalized||normalized.startsWith("/")||/^[A-Za-z]:\//.test(normalized)||normalized===".."||normalized.startsWith("../")||normalized.split("/").includes("..")||hasControlCharacter5)return null;return normalized}function normalizedPathSet(files){if(!files)return null;let normalized=new Set;for(let file3 of files){let candidate2=normalizeAttributionPath(file3);if(!candidate2)return null;normalized.add(candidate2)}return normalized}function pathSetsEqual(left,right){return left.size===right.size&&[...left].every((file3)=>right.has(file3))}function hasDistinctBackgroundOwner(input){if(!Number.isFinite(input.candidateCreatedAt)||!Number.isFinite(input.candidateCompletedAt)||input.candidateCreatedAt>input.candidateCompletedAt)return!1;let liveOwners=[...(swarmState.agentSessions.get(input.parentSessionID)?.reviewerScopeGenerations??new Map).values()].filter((generation)=>{if(generation.background!==!0||generation.taskId===input.taskId&&generation.coderCallID===input.coderCallID)return!1;let declared=normalizedPathSet(generation.declaredFiles),routed=normalizedPathSet(generation.modifiedFiles),fingerprints=generation.modifiedFileFingerprints.filter((entry)=>normalizeAttributionPath(entry.file)===input.file),ownerCompletedAt=generation.readyAt??input.candidateCompletedAt;return Number.isFinite(generation.createdAt)&&Number.isFinite(ownerCompletedAt)&&generation.createdAt<=input.candidateCompletedAt&&input.candidateCreatedAt<=ownerCompletedAt&&declared?.has(input.file)===!0&&routed?.has(input.file)===!0&&fingerprints.length===1&&reviewerScopeFileFingerprintsEqual(fingerprints[0],input.fingerprint)}),historicalOwners=getReviewerScopeOwnershipHistory({parentSessionID:input.parentSessionID}).filter((owner)=>{if(owner.taskId===input.taskId&&owner.coderCallID===input.coderCallID)return!1;let declared=normalizedPathSet(owner.declaredFiles),routed=normalizedPathSet(owner.modifiedFiles),fingerprints=owner.modifiedFileFingerprints.filter((entry)=>normalizeAttributionPath(entry.file)===input.file);return owner.parentSessionID===input.parentSessionID&&owner.background===!0&&Number.isFinite(owner.createdAt)&&Number.isFinite(owner.readyAt)&&owner.createdAt<=input.candidateCompletedAt&&input.candidateCreatedAt<=owner.readyAt&&declared?.has(input.file)===!0&&routed?.has(input.file)===!0&&fingerprints.length===1&&reviewerScopeFileFingerprintsEqual(fingerprints[0],input.fingerprint)});return liveOwners.length+historicalOwners.length===1}function isBackgroundGateBearingRecord(record3){return record3.batchId===void 0&&record3.evidenceTaskId!==null&&GATE_EVIDENCE_ROLES.has(record3.normalizedAgent)}function validateStageBWorkspace(directory,record3){let actualWorkspace=captureWorkspaceSnapshot(directory,{scope:record3.workspace?.scope??null,prHeadSha:record3.workspace?.prHeadSha??null,resolveCurrentPrHeadSha:record3.workspace?.prHeadSha!==null}),check3=compareStageBWorkspace(record3,actualWorkspace,directory);return{...check3,ok:!check3.stale}}var BARE_TASK_ID=/^\d+(?:\.\d+)*$/,SCOPE_CASE_FOLD=process.platform==="win32";function scopeMatchKey(normalized){return SCOPE_CASE_FOLD?normalized.toLowerCase():normalized}function deriveScopeFiles(scope){if(!scope)return null;let files=new Set;for(let fragment of scope.split(",")){let normalized=normalizeAttributionPath(fragment);if(normalized===null||BARE_TASK_ID.test(normalized))continue;files.add(scopeMatchKey(normalized))}return files.size>0?files:null}function scopeDirtySlice(files,scopeFiles){let slice=new Set;for(let file3 of files){let normalized=normalizeAttributionPath(file3);if(normalized!==null&&scopeFiles.has(scopeMatchKey(normalized)))slice.add(normalized)}return slice}function compareStageBWorkspace(record3,actualWorkspace,directory){let expectedWorkspace=record3.normalizedAgent==="docs"&&record3.workspace?{...record3.workspace,dirtyHash:null}:record3.workspace;if(!expectedWorkspace)return{stale:!1};if(record3.normalizedAgent==="docs")return compareWorkspaceSnapshots(expectedWorkspace,actualWorkspace);let scopeFiles=deriveScopeFiles(expectedWorkspace.scope),expectedHead=expectedWorkspace.gitHead,currentHead=actualWorkspace.gitHead,expectedChanged=expectedWorkspace.changedFiles,currentChanged=actualWorkspace.changedFiles;if(scopeFiles===null||expectedHead==null||currentHead==null||expectedChanged==null||currentChanged==null||directory===void 0)return compareWorkspaceSnapshots(expectedWorkspace,actualWorkspace);let identity=workspaceSnapshotMatches({...expectedWorkspace,gitHead:null,dirtyHash:null},{...actualWorkspace,gitHead:null,dirtyHash:null});if(!identity.ok)return{stale:!0,reason:identity.reason};let committed=committedFilesBetween(directory,expectedHead,currentHead);if(committed===null)return compareWorkspaceSnapshots(expectedWorkspace,actualWorkspace);let committedInScope=committed.filter((file3)=>scopeFiles.has(scopeMatchKey(normalizeAttributionPath(file3)??"")));if(committedInScope.length>0){let shown=committedInScope.slice(0,5).join(", "),extra=committedInScope.length>5?` (+${committedInScope.length-5} more)`:"";return{stale:!0,reason:`in-scope committed change: ${shown}${extra}`}}let dispatchDirty=scopeDirtySlice(expectedChanged,scopeFiles),currentDirty=scopeDirtySlice(currentChanged,scopeFiles),dirtied=[...currentDirty].filter((file3)=>!dispatchDirty.has(file3)),cleaned=[...dispatchDirty].filter((file3)=>!currentDirty.has(file3));if(dirtied.length>0||cleaned.length>0)return{stale:!0,reason:`in-scope dirty set changed: +[${dirtied.join(", ")}] -[${cleaned.join(", ")}]`};return{stale:!1}}async function ingestBackgroundStageBCompletion(args2){let taskId=args2.record.evidenceTaskId??args2.record.planTaskId;if(!taskId)return{ok:!0,consumed:!1};if(args2.record.normalizedAgent==="coder"){let taskChangeContext=args2.record.taskChangeContext,settledFiles=args2.record.coderSettlement?.state==="settled"?args2.record.coderSettlement.observedFiles:void 0,observedFiles=settledFiles!==void 0?settledFiles:taskChangeContext?changedFilesSinceSnapshot(taskChangeContext.baseline.directory,taskChangeContext.baseline):null;if(observedFiles===null)return{ok:!1,consumed:!1,stale:!0,reason:"background coder files could not be attributed to a clean immutable baseline"};try{let observedSet=normalizedPathSet(observedFiles),declaredSet=normalizedPathSet(taskChangeContext?.declaredFiles??null),completionTime=args2.record.completedAt??args2.record.updatedAt,attributedFiles=observedFiles??[];if(args2.reviewerReceiptOptions?.config?.enabled!==!0){if(observedSet&&declaredSet)attributedFiles=[...observedSet].filter((file3)=>declaredSet.has(file3))}if(args2.reviewerReceiptOptions?.config?.enabled===!0){if(!observedSet||!declaredSet)return{ok:!1,consumed:!1,reason:"background coder changed-file attribution could not be reconstructed exactly"};attributedFiles=[...observedSet].filter((file3)=>declaredSet.has(file3));let generation=getReviewerScopeGenerationForCoderCall({parentSessionID:args2.record.parentSessionId,taskId,coderCallID:args2.record.callID}),generationScope=normalizedPathSet(generation?.declaredFiles??null),routedFiles=normalizedPathSet(generation?.modifiedFiles??null),routedFingerprints=generation?.modifiedFileFingerprints??null;if(generation?.status==="collecting"&&generation.background===!0&&observedSet.size===0&&routedFiles?.size===0&&declaredSet){if(markReviewerScopeGenerationNoChange({parentSessionID:args2.record.parentSessionId,taskId,coderCallID:args2.record.callID}))return{ok:!0,consumed:!0}}let captureRoot=generation?.captureDirectory?.trim()||args2.directory,observedFingerprints=new Map;for(let file3 of observedSet){let captured=captureReviewerScopeFileFingerprint(captureRoot,file3);if(captured.kind==="capture_failed")return{ok:!1,consumed:!1,reason:`background coder post-write fingerprint could not be reconstructed exactly (${captured.code}${captured.retryable?" (retryable)":" (permanent)"} on ${captured.file})`};let fingerprint2=reviewerScopeCaptureToFingerprint(captured);if(!fingerprint2)return{ok:!1,consumed:!1,reason:"background coder post-write fingerprint returned an unusable result"};observedFingerprints.set(file3,fingerprint2)}let changedWithinDeclaredScope=new Set([...observedSet].filter((file3)=>declaredSet.has(file3)&&generationScope?.has(file3))),observedOutsideCurrentScope=[...observedSet].filter((file3)=>!generationScope?.has(file3));if(generation?.status!=="collecting"&&generation?.status!=="ready"||generation.background!==!0||!generationScope||!routedFiles||!routedFingerprints||routedFiles.size===0||!pathSetsEqual(declaredSet,generationScope)||!pathSetsEqual(routedFiles,changedWithinDeclaredScope)||reviewerScopeGenerationHasDeclaredOverlap({parentSessionID:args2.record.parentSessionId,taskId,coderCallID:args2.record.callID,declaredFiles:generation.declaredFiles})||observedOutsideCurrentScope.some((file3)=>!hasDistinctBackgroundOwner({parentSessionID:args2.record.parentSessionId,taskId,coderCallID:args2.record.callID,file:file3,fingerprint:observedFingerprints.get(file3),candidateCreatedAt:args2.record.createdAt,candidateCompletedAt:completionTime}))||[...routedFiles].some((file3)=>{let fingerprints=routedFingerprints.filter((entry)=>normalizeAttributionPath(entry.file)===file3),observedFingerprint=observedFingerprints.get(file3);return!observedSet.has(file3)||!declaredSet.has(file3)||!generationScope.has(file3)||fingerprints.length!==1||!observedFingerprint||!reviewerScopeFileFingerprintsEqual(fingerprints[0],observedFingerprint)}))return{ok:!1,consumed:!1,reason:"background coder scope handoff could not be reconstructed exactly"};attributedFiles=[...routedFiles];for(let file3 of routedFiles){let fingerprint2=observedFingerprints.get(file3);if(fingerprint2)recordReviewerScopeGenerationFileFingerprint({parentSessionID:args2.record.parentSessionId,taskId,coderCallID:args2.record.callID,fingerprint:fingerprint2})}}let parentSession=swarmState.agentSessions.get(args2.record.parentSessionId);if(parentSession){let state2=getTaskState(parentSession,taskId);if(state2!=="idle"&&state2!=="coder_delegated"&&state2!=="rework_required")return{ok:!1,consumed:!1,reason:`background coder completion is late for task ${taskId}: current state is ${state2}`}}let accepted=attributedFiles.length>0,expectedGeneration=args2.record.taskChangeContext?.workflowGeneration??0,transitionId=`background-coder:${args2.record.correlationId}`,existingEvidence=await readTaskEvidence(args2.directory,taskId),existingWorkflow=getTaskWorkflowSnapshot(existingEvidence),updated=existingWorkflow.authoritative&&existingWorkflow.lastTransitionId===transitionId&&existingWorkflow.lastOutcome===(accepted?"accepted_mutation":"dispatch_no_mutation")&&existingWorkflow.generation===expectedGeneration+(accepted?1:0)?existingEvidence:await transitionTaskWorkflowEvidence(args2.directory,taskId,accepted?{type:"accepted_mutation",agentType:"coder",context:{testEngineerExempt:isMarkdownOnlyTaskChange(taskChangeContext?.declaredFiles,attributedFiles)},expectedGeneration,transitionId}:{type:"dispatch_no_mutation",agentType:"coder",expectedGeneration,transitionId});if(accepted){let workflow=getTaskWorkflowSnapshot(updated),parentSession2=swarmState.agentSessions.get(args2.record.parentSessionId);if(parentSession2){if(!recordModifiedFilesForTask(parentSession2,taskId,attributedFiles,args2.directory))warn(`[background] durable coder mutation for ${taskId} exceeded session file-attribution capacity`);parentSession2.taskWorkflowStates.set(taskId,"coder_delegated"),parentSession2.stageBCompletion?.delete(taskId),parentSession2.taskCouncilApproved?.delete(taskId),parentSession2.taskCouncilWorkflowGeneration?.delete(taskId),updateTaskWorkflowCache(parentSession2,taskId,workflow)}}if(args2.reviewerReceiptOptions?.config?.enabled===!0){let laneGeneration=getReviewerScopeGenerationForCoderCall({parentSessionID:args2.record.parentSessionId,taskId,coderCallID:args2.record.callID});if(laneGeneration!==null&&laneGeneration.workspaceIdentity!==canonicalWorkspaceIdentity(args2.directory))return markReviewerScopeGenerationMergebackPending({parentSessionID:args2.record.parentSessionId,taskId,coderCallID:args2.record.callID}),{ok:!0,consumed:!0}}if(args2.reviewerReceiptOptions?.config?.enabled===!0&&!markReviewerScopeGenerationReady({parentSessionID:args2.record.parentSessionId,taskId,coderCallID:args2.record.callID,primaryWorkspaceIdentity:canonicalWorkspaceIdentity(args2.directory)??void 0}))return{ok:!1,consumed:!1,reason:"background coder scope handoff could not be marked ready after evidence persisted"};return{ok:!0,consumed:!0}}catch(err){return{ok:!1,consumed:!1,reason:`background coder evidence ingestion failed: ${err instanceof Error?err.message:String(err)}`}}}if(!isBackgroundGateBearingRecord(args2.record))return{ok:!0,consumed:!1};let workspaceCheck=validateStageBWorkspace(args2.directory,args2.record);if(workspaceCheck.stale)return{ok:!1,consumed:!1,stale:!0,reason:workspaceCheck.reason??"workspace changed while gate was running"};try{if(args2.record.workflowGeneration===void 0)return{ok:!1,consumed:!1,reason:`stage-b ingestion failed: TASK_WORKFLOW_GENERATION_REQUIRED for ${taskId}`};let existingEvidence=await readTaskEvidence(args2.directory,taskId),stageBRole=args2.record.normalizedAgent==="reviewer"||args2.record.normalizedAgent==="test_engineer"?args2.record.normalizedAgent:null,verdict=stageBRole?structuredStageBVerdict(stageBRole,args2.result.text??"",taskId):null;if(stageBRole&&verdict==="skip")return{ok:!1,consumed:!0,skipped:!0,reason:`background ${stageBRole} skipped task ${taskId} — tests not run; re-dispatch the test gate (task stays Stage B eligible; reviewer proof preserved)`};if(stageBRole&&verdict!=="pass"){let rejected2=await transitionTaskWorkflowEvidence(args2.directory,taskId,{type:"stage_b_failed",gate:stageBRole,expectedGeneration:args2.record.workflowGeneration,transitionId:`background-gate-failed:${args2.record.correlationId}`}),parentSession=swarmState.agentSessions.get(args2.record.parentSessionId);if(parentSession)parentSession.taskWorkflowStates.set(taskId,"rework_required"),parentSession.stageBCompletion?.delete(taskId),updateTaskWorkflowCache(parentSession,taskId,getTaskWorkflowSnapshot(rejected2));return{ok:!1,consumed:!0,reason:verdict==="fail"?`background ${stageBRole} rejected task ${taskId}`:`background ${stageBRole} returned no valid structured verdict for task ${taskId}`}}let preparedRoute,routeCompleteForPersistence;if(stageBRole){let parentSession=swarmState.agentSessions.get(args2.record.parentSessionId);if(parentSession){preparedRoute=resolveBackgroundStageBRoute({directory:args2.directory,taskId,parentSessionId:args2.record.parentSessionId,role:stageBRole,callId:args2.record.callID,childSessionId:args2.record.subagentSessionId,generation:args2.record.workflowGeneration,session:parentSession});let routeEnabled=(()=>{try{return loadPluginConfig(args2.directory).review_routing?.enforce_receipts??!0}catch{return!0}})(),routeDecision=enforcePersistedReviewRouteReceipt({projectRoot:args2.directory,sessionId:args2.record.parentSessionId,taskId,receipts:preparedRoute.prospective,enforcementEnabled:routeEnabled,legacyUnrouted:preparedRoute.legacyUnrouted,requireEvidenceBindings:!0,requireCompleteEvidence:!1,expectedDispatch:preparedRoute.binding?{role:preparedRoute.binding.role,identity:preparedRoute.binding.identity,callId:preparedRoute.binding.callId,childSessionId:preparedRoute.binding.childSessionId,generation:preparedRoute.binding.generation}:void 0});if(!routeDecision.canAdvance)return warn(`[background-stage-b] route receipt blocked before evidence publication for ${taskId}: ${routeDecision.reason??"unknown reason"}`),{ok:!1,consumed:!1,reason:`route receipt blocked before Stage-B evidence publication: ${routeDecision.reason??"unknown reason"}`};if(routeEnabled&&preparedRoute.route?.kind==="review_route_receipt")routeCompleteForPersistence=enforcePersistedReviewRouteReceipt({projectRoot:args2.directory,sessionId:args2.record.parentSessionId,taskId,receipts:preparedRoute.prospective,enforcementEnabled:!0,legacyUnrouted:preparedRoute.legacyUnrouted,requireEvidenceBindings:!0,requireCompleteEvidence:!0}).canAdvance}else{let route=readReviewRouteReceiptSync({projectRoot:args2.directory,sessionId:args2.record.parentSessionId,taskId});if(route?.kind!=="review_route_router_error"||route.sessionId!==args2.record.parentSessionId||route.taskId!==taskId)return{ok:!1,consumed:!1,reason:"route receipt blocked before Stage-B evidence publication: parent session is unavailable and recovery receipt is not identity-bound"}}}let routeEvidenceRollback=null;if(preparedRoute?.binding){let parentSession=swarmState.agentSessions.get(args2.record.parentSessionId);if(!parentSession)return warn(`[background-stage-b] route receipt blocked before evidence publication for ${taskId}: parent session unavailable`),{ok:!1,consumed:!1,reason:"route receipt blocked before Stage-B evidence publication: parent session unavailable"};if(routeEvidenceRollback=reserveStageBRouteEvidence(parentSession,taskId,preparedRoute.binding),!routeEvidenceRollback)return warn(`[background-stage-b] route receipt blocked before evidence publication for ${taskId}: bounded route evidence capacity exceeded`),{ok:!1,consumed:!1,reason:"route receipt blocked before Stage-B evidence publication: bounded route evidence capacity exceeded"}}try{await recordGateEvidence(args2.directory,taskId,args2.record.normalizedAgent,args2.record.subagentSessionId,hasActiveTurboMode(args2.record.parentSessionId),{expectedGeneration:args2.record.workflowGeneration,transitionId:`background-gate:${args2.record.correlationId}`,ensureDefaultStageB:existingEvidence?.test_engineer_exempt!==!0,routeBinding:preparedRoute?.binding,routeComplete:routeCompleteForPersistence})}catch(err){throw routeEvidenceRollback?.(),err}if(args2.record.normalizedAgent==="reviewer")await collectReviewerReceiptFromTranscript(args2.directory,{targetAgent:args2.record.swarmPrefixedAgent,prompt:args2.record.prompt?.text??"",transcript:args2.result.text??"",sessionID:args2.record.parentSessionId,taskId,reviewerCallID:args2.record.callID,consumeHandoff:!0},args2.reviewerReceiptOptions);if(args2.record.normalizedAgent==="reviewer"||args2.record.normalizedAgent==="test_engineer")applyStageBStateCompletion(taskId,args2.record.normalizedAgent,args2.record.parentSessionId,existingEvidence?.test_engineer_exempt===!0,args2.directory,args2.record.callID,args2.record.subagentSessionId,args2.record.workflowGeneration,preparedRoute);return{ok:!0,consumed:!0}}catch(err){let message=err instanceof Error?err.message:String(err);return warn(`[background-stage-b] ingestion failed: ${message}`),{ok:!1,consumed:!1,reason:`stage-b ingestion failed: ${message}`}}}function candidateSessions(parentSessionId){let parent=swarmState.agentSessions.get(parentSessionId);return parent?[parent]:[]}function routeDispatchKey(entry){if(!entry.callId||!entry.childSessionId||typeof entry.generation!=="number")return null;return[entry.role,entry.sessionId??"",entry.taskId??"",entry.callId,entry.childSessionId,String(entry.generation)].join("\x00")}function resolveBackgroundStageBRoute(input){let route=readReviewRouteReceiptSync({projectRoot:input.directory,sessionId:input.parentSessionId,taskId:input.taskId}),evidence2=getStageBRouteEvidence(input.session,input.taskId);if(evidence2.length===0)try{evidence2=routeEvidenceFromTaskGateRequirements(readTaskGateRequirementsReceiptsSync(input.directory,input.taskId))}catch{}let legacyUnrouted=route===null&&!isStageBRouteRequired(input.session,input.taskId)&&(()=>{try{let receipts=readTaskGateRequirementsReceiptsSync(input.directory,input.taskId);return receipts.length>0&&receipts.every((receipt)=>!receipt.routeBinding)}catch{return!1}})(),binding,prospective=evidence2;if(route?.kind==="review_route_receipt"){let identities=input.role==="reviewer"?route.identities.reviewers:route.identities.testEngineers,slots=input.role==="reviewer"?route.slots?.reviewers??identities:route.slots?.testEngineers??identities,dispatchKey2=[input.role,input.parentSessionId,input.taskId,input.callId,input.childSessionId,String(input.generation)].join("\x00"),retry=evidence2.find((entry)=>entry.role===input.role&&routeDispatchKey(entry)===dispatchKey2),usedSlots=new Set(evidence2.filter((entry)=>entry.role===input.role&&entry!==retry&&entry.slotId).map((entry)=>entry.slotId)),slotIndex=retry?slots.indexOf(retry.slotId??""):slots.findIndex((slot)=>!usedSlots.has(slot));if(slotIndex>=0&&slotIndex<identities.length){let slotId=slots[slotIndex],identity=identities[slotIndex];binding={role:input.role,identity,sessionId:input.parentSessionId,taskId:input.taskId,slotId,callId:input.callId,childSessionId:input.childSessionId,generation:input.generation},prospective=retry?evidence2.map((entry)=>entry===retry?binding:entry):[...evidence2,binding]}}return{route,binding,prospective,legacyUnrouted}}function applyStageBStateCompletion(taskId,agent,parentSessionId,testEngineerExempt,directory,callId,childSessionId,generation,preparedRoute){for(let session of candidateSessions(parentSessionId)){let resolvedRoute=preparedRoute??resolveBackgroundStageBRoute({directory,taskId,parentSessionId,role:agent,callId,childSessionId,generation:generation??-1,session}),{binding,prospective:routeEvidence,legacyUnrouted}=resolvedRoute,routeEnabled=(()=>{try{return loadPluginConfig(directory).review_routing?.enforce_receipts??!0}catch{return!0}})(),completionDecision=enforcePersistedReviewRouteReceipt({projectRoot:directory,sessionId:parentSessionId,taskId,receipts:routeEvidence,enforcementEnabled:routeEnabled,legacyUnrouted,requireEvidenceBindings:!0,requireCompleteEvidence:!1,expectedDispatch:binding?{role:binding.role,identity:binding.identity,callId:binding.callId,childSessionId:binding.childSessionId,generation:binding.generation}:void 0});if(!completionDecision.canAdvance){warn(`[background-stage-b] route receipt blocked ${taskId}: ${completionDecision.reason??"unknown reason"}`);continue}if(binding&&!recordStageBRouteEvidence(session,taskId,binding)){warn(`[background-stage-b] route receipt blocked before Stage-B evidence publication for ${taskId}: bounded route evidence capacity exceeded`);continue}recordStageBCompletion(session,taskId,agent);let state2=getTaskState(session,taskId);if(state2==="tests_run"||state2==="complete")continue;let routeComplete=enforcePersistedReviewRouteReceipt({projectRoot:directory,sessionId:parentSessionId,taskId,receipts:getStageBRouteEvidence(session,taskId),enforcementEnabled:routeEnabled,legacyUnrouted,requireEvidenceBindings:!0,requireCompleteEvidence:!0}).canAdvance;if(routeComplete&&(hasBothStageBCompletions(session,taskId)||testEngineerExempt&&agent==="reviewer")){try{if(state2==="coder_delegated"||state2==="pre_check_passed")advanceTaskState(session,taskId,"reviewer_run",{telemetrySessionId:parentSessionId});if(getTaskState(session,taskId)==="reviewer_run")advanceTaskState(session,taskId,"tests_run",{telemetrySessionId:parentSessionId})}catch(err){warn(`[background-stage-b] could not advance ${taskId} after ${agent}: ${err instanceof Error?err.message:String(err)}`)}continue}if(agent==="reviewer"&&(state2==="coder_delegated"||state2==="pre_check_passed"))try{advanceTaskState(session,taskId,"reviewer_run",{telemetrySessionId:parentSessionId})}catch(err){warn(`[background-stage-b] could not advance ${taskId} to reviewer_run: ${err instanceof Error?err.message:String(err)}`)}else if(routeComplete&&agent==="test_engineer"&&state2==="reviewer_run")try{advanceTaskState(session,taskId,"tests_run",{telemetrySessionId:parentSessionId})}catch(err){warn(`[background-stage-b] could not advance ${taskId} to tests_run: ${err instanceof Error?err.message:String(err)}`)}}}init_task_envelope();init_workspace_snapshot();var RETRYABLE_LEGACY_SETTLEMENT_TRANSFER_ERROR_CODES=new Set(["CODER_SETTLEMENT_LOCKED","EACCES","EBUSY","EIO","EPERM","ETIMEDOUT"]),observerInternals={epicSentinelExists,commitEpicResidueAfterDelegation,transferCoderSettlementToBackground,markLegacyCoderSettlementTransferPending,sleep:(milliseconds)=>new Promise((resolve111)=>setTimeout(resolve111,milliseconds))};function createBackgroundCompletionObserver(opts){let{config:config3,directory}=opts,replayInProgress=!1,notifyLegacyCoderSettlementAdvisoryReplaced=(record3,replacement)=>{let session=swarmState.agentSessions.get(record3.parentSessionId);if(!session)return;if(removeQueuedLegacyTransferAdvisory(session.pendingAdvisoryMessages,replacement.advisory.eventId),replacement.replacedMessage)removeQueuedAdvisoryMessage(session.pendingAdvisoryMessages,[replacement.replacedMessage]);pushAdvisory(session,replacement.advisory.message)},event=async(input)=>{if(!config3.enabled)return;try{let pending,result,terminal,record3,text,isDuplicate=!1;if(input.trustedTerminal)pending=input.trustedTerminal.record,result=input.trustedTerminal.result,terminal=input.trustedTerminal.terminal,text=result.error??result.text??"",record3=pending,isDuplicate=!0;else{let evt=input?.event;if(!evt||evt.type!=="message.part.updated")return;let part=evt.properties?.part;if(!part||part.type!=="text"||part.synthetic!==!0||typeof part.text!=="string")return;let envelope=parseTaskEnvelope(part.text);if(!envelope||envelope.state!=="completed"&&envelope.state!=="error"&&envelope.state!=="cancelled")return;let parentSessionId=typeof part.sessionID==="string"?part.sessionID:"",lookup=await findDelegationForCompletion(directory,envelope.sessionId);if(lookup?.source==="uncertain"){warn(`[background] deferring terminal ingestion: delegation store unreadable for ${envelope.sessionId} (${lookup.uncertain})`);return}if(!lookup){log(`[background] trusted completion for ${envelope.sessionId} has no durable primary or fallback owner; ignored`);return}if(!parentSessionId||lookup.record.parentSessionId!==parentSessionId||lookup.record.subagentSessionId!==envelope.sessionId){warn(`[background] trusted completion identity mismatch for ${envelope.sessionId}; ignored`);return}if(pending=lookup.record,lookup.source==="fallback"){let promoted=await promoteDelegationFallback(directory,envelope.sessionId);if(!promoted){warn(`[background] fallback promotion failed for ${envelope.sessionId}; terminal work remains preserved`);return}pending=promoted.record}text=envelope.state==="error"||envelope.state==="cancelled"?envelope.errorText??"":envelope.resultText??"",result={...envelope.state==="error"?{error:text}:{text},chars:envelope.resultChars??text.length,truncated:envelope.resultTruncated??!1,digest:digest4(text)},terminal={eventId:buildBackgroundCompletionEventId({correlationId:pending.correlationId,jobId:pending.jobId,status:envelope.state,resultDigest:result.digest}),status:envelope.state,recordedAt:pending.terminalResult?.recordedAt??Date.now(),result};let terminalClaim=await claimTerminalResult(directory,pending.correlationId,terminal);if(!terminalClaim){warn(`[background] terminal claim failed for ${pending.correlationId}; ignored`);return}isDuplicate=terminalClaim.disposition==="duplicate",record3=terminalClaim.record}if(opts.onTerminalClaimed?.(record3),!input.trustedTerminal?.skipMaintenance)try{await maintainBackgroundDelegations(directory,{lockTimeoutMs:1000,reason:"trusted-terminal",onLegacyCoderSettlementReconciled:reconcilePending,onLegacyCoderSettlementAdvisoryReplaced:notifyLegacyCoderSettlementAdvisoryReplaced})}catch{}let legacyTransferPending=!1,legacyTransferRequiresManualRecovery=!1;if(terminal.status!=="completed"){if(isDuplicate&&record3.normalizedAgent!=="coder")return;if(record3.normalizedAgent==="coder"){let legacyTransfer=await transferLegacyCoderSettlement(directory,record3);if(legacyTransfer.disposition==="retry_pending")legacyTransferPending=!0;else if(legacyTransfer.disposition==="manual_recovery")legacyTransferRequiresManualRecovery=!0;if(record3.planTaskId){let expectedGeneration=record3.taskChangeContext?.workflowGeneration;if(expectedGeneration===void 0)warn(`[background] failed coder ${record3.correlationId} has no launch generation for task ${record3.planTaskId}`);else try{await transitionTaskWorkflowEvidence(directory,record3.planTaskId,{type:"dispatch_no_mutation",agentType:"coder",expectedGeneration,transitionId:`background-coder-terminal:${terminal.eventId}`})}catch(error93){warn(`[background] failed coder retry accounting was fenced for ${record3.planTaskId}: ${error93 instanceof Error?error93.message:String(error93)}`)}}try{await releaseCoderReservation(directory,record3,"recovered")}catch(error93){warn(`[background] failed coder reservation cleanup will be retried by admission reconciliation: ${error93 instanceof Error?error93.message:String(error93)}`)}if(record3.worktree){let descriptor=record3.worktree;if(!standardWorktreeByCallID.has(record3.callID))standardWorktreeByCallID.set(record3.callID,{callID:descriptor.callID,parentSessionID:descriptor.parentSessionId,taskId:descriptor.taskId,...descriptor.planTaskId?{planTaskId:descriptor.planTaskId}:{},handle:{worktreePath:descriptor.worktreePath,branchName:descriptor.branchName,purpose:"lane",id:descriptor.worktreeId,sessionId:descriptor.worktreeSessionId},mergeStrategy:descriptor.mergeStrategy,laneIndex:descriptor.laneIndex,...descriptor.worktreeDir?{worktree_dir:descriptor.worktreeDir}:{}});try{await abortStandardWorktreeDispatch(record3.callID,"cancelled",directory)}catch(error93){warn(`[background] failed coder worktree cleanup preserved the lane for manual recovery: ${error93 instanceof Error?error93.message:String(error93)}`)}}}if(discardScopeForRecord(record3),await publishAdvisory(directory,record3,terminal.eventId,legacyTransferPending?`${terminal.status==="cancelled"?"cancelled":"failed"}; legacy coder settlement transfer is pending; durable reconciliation will retry`:legacyTransferRequiresManualRecovery?`${terminal.status==="cancelled"?"cancelled":"failed"}; legacy coder settlement requires manual recovery; run /swarm recover for this task (or /swarm reset-session)`:terminal.status==="cancelled"?"cancelled":"failed"),!legacyTransferPending)await clearLegacyCoderSettlementTransferPending(directory,record3.correlationId);return}if(record3.normalizedAgent==="coder"){let settled=await settleCoder(directory,record3,terminal.eventId);if(record3=settled.record,!settled.ok){await publishAdvisory(directory,record3,terminal.eventId,settled.outcome);return}let legacyTransfer=await transferLegacyCoderSettlement(directory,record3);if(legacyTransfer.disposition==="retry_pending")legacyTransferPending=!0;else if(legacyTransfer.disposition==="manual_recovery")legacyTransferRequiresManualRecovery=!0}else if(!isDuplicate&&isBackgroundGateBearingRecord(record3)){if(validateStageBWorkspace(directory,record3).stale){await appendDelegationTransition(directory,record3.correlationId,{status:"stale"}),discardScopeForRecord(record3),await publishAdvisory(directory,record3,terminal.eventId,"stale");return}}if(record3.normalizedAgent==="coder"||isBackgroundGateBearingRecord(record3)){let ingestion=await claimDelegationIngestion(directory,record3.correlationId,{claimantId:terminal.eventId});if(ingestion?.disposition==="claimed"||ingestion?.disposition==="retry"){let applied2=await ingestBackgroundStageBCompletion({directory,record:ingestion.record,result:ingestion.record.result??result,reviewerReceiptOptions:opts.reviewerReceiptOptions}),claimToken=ingestion.record.ingestion?.claimToken;if(!claimToken){await publishAdvisory(directory,record3,terminal.eventId,"ingestion claim token missing");return}let ingestionCommit=await(opts.recordIngestionResult??recordDelegationIngestionResult)(directory,record3.correlationId,claimToken,applied2.ok);if(!ingestionCommit){warn(`[background] ingestion claim for ${record3.correlationId} expired or was fenced before commit; retry remains pending`);return}if(applied2.ok&&(ingestionCommit.status!=="consumed"||ingestionCommit.ingestion?.state!=="consumed"||ingestionCommit.ingestion.claimToken!==claimToken)){warn(`[background] ingestion commit for ${record3.correlationId} did not confirm the exact consumed claim; retry remains pending`);return}if(record3=ingestionCommit,record3=(await findDelegationForCompletion(directory,record3.correlationId))?.record??record3,!applied2.ok){await publishAdvisory(directory,record3,terminal.eventId,applied2.skipped?"skipped (tests not run) — re-dispatch the test gate; reviewer proof preserved; task remains Stage B eligible":legacyTransferPending?"ingestion failed; legacy coder settlement transfer is pending; durable reconciliation will retry":legacyTransferRequiresManualRecovery?"ingestion failed; legacy coder settlement requires manual recovery; run /swarm recover for this task (or /swarm reset-session)":applied2.stale?"stale":"ingestion failed");try{await maintainBackgroundDelegations(directory,{lockTimeoutMs:1000,reason:"ingestion-rejection",skipLegacyCoderSettlementReconciliation:legacyTransferPending,onLegacyCoderSettlementAdvisoryReplaced:notifyLegacyCoderSettlementAdvisoryReplaced})}catch{}return}}else if(ingestion?.disposition==="busy")return;else if(ingestion?.disposition!=="consumed"){await publishAdvisory(directory,record3,terminal.eventId,"ingestion pending");return}}if(record3.normalizedAgent==="docs")try{if(!await completeBackgroundPhaseParticipation({directory,record:record3,resultText:text}))warn(`[background] docs completion ${record3.correlationId} did not satisfy its durable phase-participation binding`)}catch(error93){warn(`[background] docs completion ${record3.correlationId} could not persist phase participation: ${error93 instanceof Error?error93.message:String(error93)}`)}if(record3.normalizedAgent!=="coder"&&observerInternals.epicSentinelExists(directory))await observerInternals.commitEpicResidueAfterDelegation({directory,agent:record3.normalizedAgent,sessionID:record3.parentSessionId,resolveTaskIds:async()=>{let taskId=record3.planTaskId??record3.evidenceTaskId;return taskId?[taskId]:[]},childSessionIds:async()=>[record3.subagentSessionId]});if(record3.normalizedAgent==="reviewer")discardScopeForRecord(record3);if(record3.normalizedAgent==="coder"){if(await releaseCoderReservation(directory,record3,"consumed"),!legacyTransferPending)await clearLegacyCoderSettlementTransferPending(directory,record3.correlationId)}await publishAdvisory(directory,record3,terminal.eventId,record3.normalizedAgent==="coder"?legacyTransferPending?"completed and settled; legacy coder settlement transfer is pending; durable reconciliation will retry":legacyTransferRequiresManualRecovery?"completed and settled; legacy coder settlement requires manual recovery; run /swarm recover for this task (or /swarm reset-session)":"completed and settled":"completed"),log(`[background] trusted completion settled: agent=${record3.normalizedAgent} task=${taskLabel(record3)} parent=${record3.parentSessionId}`)}catch(err){warn(`[background] completion observer error: ${err instanceof Error?err.message:String(err)}`)}},reconcilePending=async(record3)=>{if(replayInProgress)return!1;let terminal=record3.terminalResult;if(!terminal)return!1;replayInProgress=!0;try{await event({event:void 0,trustedTerminal:{record:record3,terminal,result:terminal.result,skipMaintenance:!0}});let refreshed=await findDelegationForCompletion(directory,record3.subagentSessionId);return refreshed?.record?refreshed.record.status==="consumed":!1}finally{replayInProgress=!1}};if(config3.enabled)registerLegacyCoderSettlementReconciler(directory,reconcilePending);return{event,reconcilePending,notifyLegacyCoderSettlementAdvisoryReplaced,prepareAdvisories:async(parentSessionId)=>{if(!config3.enabled||!parentSessionId)return null;let preparationId=`bg-prepare:${cryptoRandomId()}`,entries2=await preparePendingBackgroundAdvisories(directory,parentSessionId,{preparationId});return entries2.length===0?null:{preparationId,eventIds:entries2.map((entry)=>entry.eventId),messages:entries2.map((entry)=>entry.message)}},ackObservedAdvisories:(parentSessionId,observedTexts)=>acknowledgeObservedBackgroundAdvisories(directory,parentSessionId,observedTexts),releaseAdvisories:(parentSessionId,prepared)=>releasePreparedBackgroundAdvisories(directory,parentSessionId,prepared.preparationId,prepared.eventIds)}}async function transferLegacyCoderSettlement(directory,record3){if(!record3.planTaskId)return{disposition:"ok",outcome:"no task-scoped legacy settlement"};let transfer={taskId:record3.planTaskId,transitionId:`coder:${record3.callID}`},detail="unknown transfer failure",lastErrorCode=null;for(let attempt=0;attempt<3;attempt+=1)try{return{disposition:"ok",outcome:await observerInternals.transferCoderSettlementToBackground({directory,taskId:transfer.taskId,transitionId:transfer.transitionId})}}catch(error93){if(lastErrorCode=errorCode2(error93),detail=error93 instanceof Error?error93.message:String(error93),attempt===2||!isRetryableLegacyTransferErrorCode(lastErrorCode))break;await observerInternals.sleep(50*(attempt+1))}if(warn(`[background] legacy coder settlement transfer failed for ${record3.planTaskId}: ${detail}`),!isRetryableLegacyTransferErrorCode(lastErrorCode))return{disposition:"manual_recovery",outcome:"legacy coder settlement requires manual recovery; run /swarm recover for this task (or /swarm reset-session)"};let pending=null;for(let markerAttempt=0;markerAttempt<3;markerAttempt+=1){try{pending=await observerInternals.markLegacyCoderSettlementTransferPending(directory,record3.correlationId,transfer)}catch{pending=null}if(hasExactPendingLegacyTransfer(pending,transfer))break;if(markerAttempt<2)await observerInternals.sleep(50*(markerAttempt+1))}if(hasExactPendingLegacyTransfer(pending,transfer))return{disposition:"retry_pending",outcome:"legacy coder settlement transfer is pending; retrying durable reconciliation"};return{disposition:"manual_recovery",outcome:"legacy coder settlement requires manual recovery; run /swarm recover for this task (or /swarm reset-session)"}}async function releaseCoderReservation(directory,record3,reason){if(!record3.coderReservationId)return;let bound=await bindBackgroundCoderReservation(directory,{reservationId:record3.coderReservationId,parentSessionId:record3.parentSessionId,planTaskId:record3.planTaskId,callID:record3.callID,correlationId:record3.correlationId});if(!bound){warn(`[background] coder reservation ${record3.coderReservationId} could not be bound for ${record3.correlationId}; admission remains fail-closed`);return}if(!await releaseBackgroundCoderReservation(directory,{...bound,generation:record3.generation??1,reason}))warn(`[background] coder reservation ${record3.coderReservationId} could not be released after ${reason}; the next admission will retry reconciliation`)}async function settleCoder(directory,record3,operationId){let context=record3.taskChangeContext;if(!context)return{ok:!1,record:record3,outcome:"stale: no coder baseline"};let claim=await claimCoderSettlement(directory,record3.correlationId,operationId);if(!claim)return{ok:!1,record:record3,outcome:"settlement claim failed"};if(claim.disposition==="settled")return{ok:!0,record:claim.record,outcome:"completed and settled"};if(claim.disposition==="preserved")return{ok:!1,record:claim.record,outcome:"settlement preserved"};if(record3=claim.record,!record3.worktree){let baseline=context.baseline,current=captureWorkspaceSnapshot(directory,{scope:baseline.scope,prHeadSha:baseline.prHeadSha,resolveCurrentPrHeadSha:baseline.prHeadSha!==null}),repositoryDelta=changedFilesSinceSnapshot(directory,baseline),declaredFiles=context.declaredFiles,observedFiles2=repositoryDelta&&declaredFiles&&declaredFiles.length>0?repositoryDelta.filter((file3)=>isInDeclaredScope(file3,declaredFiles,directory)):null,staleReason=!sameProjectRoot(baseline.directory,directory)?"shared-root directory identity changed":!baseline.gitHead||current.gitHead!==baseline.gitHead?"shared-root HEAD changed before coder completion":baseline.prHeadSha!==null&¤t.prHeadSha!==baseline.prHeadSha?"shared-root PR head changed before coder completion":observedFiles2===null?"shared-root coder files could not be attributed to a non-empty declared scope":null;if(staleReason||observedFiles2===null){let preserved2=await updateCoderSettlement(directory,record3.correlationId,{operationId,state:"preserved",observedFiles:null,outcome:{kind:"shared-root",result:"failed",reason:staleReason??"coder attribution failed"}});return await appendDelegationTransition(directory,record3.correlationId,{status:"stale"}),{ok:!1,record:preserved2??record3,outcome:`stale: ${staleReason??"coder attribution failed"}`}}let settled=await updateCoderSettlement(directory,record3.correlationId,{operationId,state:"settled",observedFiles:observedFiles2,outcome:{kind:"shared-root",result:"ready"}});return settled?{ok:!0,record:settled,outcome:"completed and settled"}:{ok:!1,record:record3,outcome:"settlement persistence failed"}}let descriptor=record3.worktree;if(descriptor.callID!==record3.callID||descriptor.parentSessionId!==record3.parentSessionId||descriptor.planTaskId!==record3.planTaskId||!sameProjectRoot(context.baseline.directory,descriptor.worktreePath))return{ok:!1,record:await updateCoderSettlement(directory,record3.correlationId,{operationId,state:"preserved",observedFiles:null,outcome:{kind:"standard-worktree",result:"failed",reason:"worktree recovery identity does not match the dispatch"}})??record3,outcome:"worktree settlement preserved: identity mismatch"};let observedFiles=changedFilesSinceSnapshot(descriptor.worktreePath,context.baseline);if(observedFiles===null)return{ok:!1,record:await updateCoderSettlement(directory,record3.correlationId,{operationId,state:"preserved",observedFiles:null,outcome:{kind:"standard-worktree",result:"failed",reason:"worktree files could not be attributed to the clean baseline"}})??record3,outcome:"worktree settlement preserved: attribution failed"};let dispatch=standardWorktreeByCallID.get(record3.callID)??{callID:descriptor.callID,parentSessionID:descriptor.parentSessionId,taskId:descriptor.taskId,...descriptor.planTaskId?{planTaskId:descriptor.planTaskId}:{},handle:{worktreePath:descriptor.worktreePath,branchName:descriptor.branchName,purpose:"lane",id:descriptor.worktreeId,sessionId:descriptor.worktreeSessionId},mergeStrategy:descriptor.mergeStrategy,laneIndex:descriptor.laneIndex,...descriptor.worktreeDir?{worktree_dir:descriptor.worktreeDir}:{}};standardWorktreeByCallID.delete(record3.callID),awaitingMergeByCallID.set(record3.callID,{callID:record3.callID,parentSessionID:descriptor.parentSessionId,taskId:descriptor.taskId,...descriptor.planTaskId?{planTaskId:descriptor.planTaskId}:{},branch:descriptor.branchName,worktreePath:descriptor.worktreePath,mergeStrategy:descriptor.mergeStrategy,queuedAt:Date.now()});let resume=settlementResume(record3),mergeResult=await finishStandardWorktreeDispatch(directory,dispatch,void 0,record3.callID,{operationId,...resume?{resume}:{},onBeforeMerge:async(provenance)=>{let persisted=await updateCoderSettlement(directory,record3.correlationId,{operationId,state:"settling",sourceHeadAfterCommit:provenance.sourceHead,targetHeadBeforeMerge:provenance.targetHeadBefore,observedFiles});if(!persisted)throw Error("could not persist pre-merge provenance");record3=persisted},onMerged:async(merged)=>{let provenance=merged.provenance??resume,persisted=await updateCoderSettlement(directory,record3.correlationId,{operationId,state:"settled",observedFiles,...provenance?{sourceHeadAfterCommit:provenance.sourceHead,targetHeadBeforeMerge:provenance.targetHeadBefore}:{},outcome:{kind:"standard-worktree",result:provenance&&provenance.sourceHead!==provenance.targetHeadBefore?"merged":"unchanged",sourceHeadAfterCommit:provenance?.sourceHead??null,targetHeadBeforeMerge:provenance?.targetHeadBefore??null,targetHeadAfterMerge:resolveCurrentGitHead(directory)}});if(!persisted)throw Error("could not persist merged settlement");record3=persisted}});if(mergeResult.outcome==="merged")return{ok:!0,record:(await findDelegationForCompletion(directory,record3.correlationId))?.record??record3,outcome:"completed and merged"};if(mergeResult.outcome==="failed"&&mergeResult.stage==="settlement-persist")return{ok:!1,record:record3,outcome:"worktree settlement persistence pending retry"};return{ok:!1,record:await updateCoderSettlement(directory,record3.correlationId,{operationId,state:"preserved",observedFiles,...mergeResult.provenance?{sourceHeadAfterCommit:mergeResult.provenance.sourceHead,targetHeadBeforeMerge:mergeResult.provenance.targetHeadBefore}:{},outcome:{kind:"standard-worktree",result:mergeResult.outcome,reason:mergeResult.message,sourceHeadAfterCommit:mergeResult.provenance?.sourceHead??null,targetHeadBeforeMerge:mergeResult.provenance?.targetHeadBefore??null}})??record3,outcome:`worktree settlement preserved: ${mergeResult.message}`}}function settlementResume(record3){let{coderSettlement:settlement,worktree}=record3;if(settlement?.state!=="settling"||!settlement.operationId||!settlement.sourceHeadAfterCommit||!settlement.targetHeadBeforeMerge||!GIT_OBJECT_ID_PATTERN.test(settlement.sourceHeadAfterCommit)||!GIT_OBJECT_ID_PATTERN.test(settlement.targetHeadBeforeMerge)||!worktree)return;return{operationId:settlement.operationId,sourceHead:settlement.sourceHeadAfterCommit,targetHeadBefore:settlement.targetHeadBeforeMerge,branchName:worktree.branchName,strategy:worktree.mergeStrategy}}async function publishAdvisory(directory,record3,eventId,outcome){let message=`[BACKGROUND COMPLETION ${eventId}] ${record3.normalizedAgent} task ${taskLabel(record3)} ${outcome}.`,input={eventId,parentSessionId:record3.parentSessionId,message},needsCorrection=!message.includes(LEGACY_CODER_SETTLEMENT_PENDING_ADVISORY_MARKER),replacement=(needsCorrection?await replacePendingBackgroundAdvisory(directory,record3.correlationId,input):null)??null,stored=replacement?.advisory??await putPendingBackgroundAdvisory(directory,record3.correlationId,input);if(!stored)return;let session=swarmState.agentSessions.get(record3.parentSessionId);if(session){if(needsCorrection){if(removeQueuedLegacyTransferAdvisory(session.pendingAdvisoryMessages,eventId),replacement?.replacedMessage)removeQueuedAdvisoryMessage(session.pendingAdvisoryMessages,[replacement.replacedMessage])}pushAdvisory(session,stored.message)}}function errorCode2(error93){if(error93&&typeof error93==="object"&&"code"in error93&&typeof error93.code==="string")return error93.code??null;let detail=error93 instanceof Error?error93.message:String(error93);return/^([A-Z][A-Z0-9_]*)(?::|$)/.exec(detail.trim())?.[1]??null}function hasExactPendingLegacyTransfer(record3,transfer){return record3?.legacyCoderSettlementTransfer?.taskId===transfer.taskId&&record3.legacyCoderSettlementTransfer.transitionId===transfer.transitionId}function isRetryableLegacyTransferErrorCode(code){return code!==null&&RETRYABLE_LEGACY_SETTLEMENT_TRANSFER_ERROR_CODES.has(code)}function removeQueuedAdvisoryMessage(queue,messagesToRemove){if(!queue||queue.length===0||messagesToRemove.length===0)return;let remove=new Set(messagesToRemove);for(let index=queue.length-1;index>=0;index-=1)if(remove.has(queue[index]))queue.splice(index,1)}function removeQueuedLegacyTransferAdvisory(queue,eventId){if(!queue||queue.length===0)return;let prefix=`[BACKGROUND COMPLETION ${eventId}]`;for(let index=queue.length-1;index>=0;index-=1){let message=queue[index];if(message?.startsWith(prefix)&&message.includes(LEGACY_CODER_SETTLEMENT_PENDING_ADVISORY_MARKER))queue.splice(index,1)}}function taskLabel(record3){return record3.evidenceTaskId??record3.planTaskId??"unknown"}function discardScopeForRecord(record3){let taskId=record3.evidenceTaskId??record3.planTaskId;if(!taskId)return;if(record3.normalizedAgent==="reviewer")discardReviewerScopeGenerationClaim({parentSessionID:record3.parentSessionId,taskId,reviewerCallID:record3.callID});else if(record3.normalizedAgent==="coder")discardReviewerScopeGenerationForCoderCall({parentSessionID:record3.parentSessionId,taskId,coderCallID:record3.callID})}function digest4(text){return createHash101("sha256").update(text).digest("hex")}function cryptoRandomId(){return createHash101("sha256").update(`${Date.now()}:${Math.random()}`).digest("hex").slice(0,24)}init_pr_subscriptions();init_commands();init_registry2();init_config2();init_agent_model();init_bundled_skills();init_constants();init_config2();init_package();init_constants();import*as fs163 from"node:fs";import*as path292 from"node:path";var CONFIG_SCHEMA_REF=`https://unpkg.com/opencode-swarm@${package_default.version}/opencode-swarm.schema.json`;function writeSwarmConfigExampleIfNew(projectDirectory){try{let swarmDir=path292.join(projectDirectory,".swarm"),dest=path292.join(swarmDir,"config.example.json");if(fs163.existsSync(dest))return;if(!fs163.existsSync(swarmDir))fs163.mkdirSync(swarmDir,{recursive:!0});let example={$schema:CONFIG_SCHEMA_REF,agents:Object.fromEntries(Object.entries(DEFAULT_MODELS).filter(([name])=>name!=="default").map(([name,model])=>[name,{model,fallback_models:DEFAULT_AGENT_CONFIGS.coder?.fallback_models??["opencode/big-pickle"]}])),max_iterations:5};fs163.writeFileSync(dest,`${JSON.stringify(example,null,2)}
|
|
7184
7184
|
`,"utf-8")}catch{}}init_schema();init_schema();init_core_events();init_delegation_gate();init_utils2();init_injection_budget();init_utils();var FOR_TAG_PATTERN=/^\[FOR:\s*([^\]]+)\]/i;function containsPlanContent(text){if(!text)return!1;let lowerText=text.toLowerCase();return lowerText.includes(".swarm/plan")||lowerText.includes(".swarm/context")||lowerText.includes("swarm/plan.md")||lowerText.includes("swarm/context.md")}function containsKnowledgeContent(text){if(!text)return!1;let lowerText=text.toLowerCase();return lowerText.includes("knowledge")||lowerText.includes("lesson")||lowerText.includes(".swarm/knowledge")||lowerText.includes("swarm knowledge")}function parseForTag(content){let match=content.trim().match(FOR_TAG_PATTERN);if(!match)return null;let tagContent=match[1].trim();if(tagContent.toLowerCase()==="all")return["all"];return tagContent.split(",").map((agent)=>agent.trim().toLowerCase()).filter(Boolean)}function isTargetRoleAllowed(targetRole,allowedAgents){if(allowedAgents.includes("all"))return!0;let normalizedTarget=stripKnownSwarmPrefix(targetRole).toLowerCase();return allowedAgents.some((agent)=>{let normalizedAgent=stripKnownSwarmPrefix(agent).toLowerCase();return normalizedTarget===normalizedAgent})}function shouldNeverFilter(entry){if(entry.role==="system")return!0;if(entry.role==="user"){if(parseDelegationEnvelope(entry.content))return!0}if(entry.role==="assistant"){if(containsPlanContent(entry.content)||containsKnowledgeContent(entry.content))return!0}return!1}function logFilteringMetrics(directory,targetRole,totalEntries,includedEntries){try{appendCoreEventSync(directory,{event:"context_filtered",timestamp:new Date().toISOString(),agentName:targetRole,totalEntries,includedEntries,filteredEntries:totalEntries-includedEntries,estimatedTokensSaved:(totalEntries-includedEntries)*100})}catch(error93){log("[RoleFilter] event append failed",{error:error93 instanceof Error?error93.message:String(error93)})}}function filterByRole(entries2,targetRole,directory,options={}){if(!entries2||entries2.length===0)return[];let filtered=[];for(let entry of entries2){let allowedAgents=parseForTag(entry.content),canFilterTaggedSystem=entry.role==="system"&&options.filterTaggedSystem===!0&&allowedAgents!==null&&allowedAgents.length>0;if(shouldNeverFilter(entry)&&!canFilterTaggedSystem){filtered.push(entry);continue}if(allowedAgents===null){filtered.push(entry);continue}if(isTargetRoleAllowed(targetRole,allowedAgents))filtered.push(entry)}if(directory)logFilteringMetrics(directory,targetRole,entries2.length,filtered.length);return filtered}function createRoleFilterSystemHook(getActiveAgentName){return{"experimental.chat.system.transform":async(input,output)=>{if(!input.sessionID||!Array.isArray(output.system))return;let targetRole=input.agent??getActiveAgentName(input.sessionID);if(!targetRole)return;let entries2=output.system.map((content)=>({role:"system",content})),kept=filterByRole(entries2,targetRole,void 0,{filterTaggedSystem:!0}).map(({content})=>content),keptRemaining=new Map;for(let content of kept)keptRemaining.set(content,(keptRemaining.get(content)??0)+1);let removedTokens=0;for(let{content}of entries2){let remaining=keptRemaining.get(content)??0;if(remaining>0)keptRemaining.set(content,remaining-1);else removedTokens+=estimateTokens(content)}if(removedTokens>0)deductProducerEmission(input.sessionID,"system-enhancer",removedTokens,{expectedGeneration:input.expectedGeneration});output.system.length=0;for(let content of kept)output.system.push(content)}}}import*as fs166 from"node:fs";import*as path295 from"node:path";import*as fs165 from"node:fs";import*as path294 from"node:path";import*as crypto13 from"node:crypto";import*as fs164 from"node:fs";import*as path293 from"node:path";var _internals242={readFileSync:fs164.readFileSync,writeFileSync:fs164.writeFileSync,mkdirSync:fs164.mkdirSync,renameSync:fs164.renameSync,existsSync:fs164.existsSync,statSync:fs164.statSync,createHash:crypto13.createHash.bind(crypto13)};function computeContentHash3(content){return _internals242.createHash("sha256").update(content,"utf-8").digest("hex")}function createEmptyContextMap(){return{schema_version:1,generated_at:new Date().toISOString(),repo_fingerprint:"",files:{},task_history:{},decisions:[]}}function loadContextMap(directory){let filePath=path293.join(directory,".swarm","context-map.json");try{if(!_internals242.existsSync(filePath))return null;let raw=_internals242.readFileSync(filePath,"utf-8"),parsed=JSON.parse(raw);if(typeof parsed!=="object"||parsed===null||parsed.schema_version!==1||!Array.isArray(parsed.decisions)||typeof parsed.files!=="object"||parsed.files===null||Array.isArray(parsed.files)||typeof parsed.task_history!=="object"||parsed.task_history===null||Array.isArray(parsed.task_history))return null;return parsed}catch{return null}}function saveContextMap(map3,directory){let swarmDir=path293.join(directory,".swarm"),tmpPath=path293.join(swarmDir,"context-map.tmp"),finalPath=path293.join(swarmDir,"context-map.json");_internals242.mkdirSync(swarmDir,{recursive:!0});let updated={...map3,generated_at:new Date().toISOString()},json3=JSON.stringify(updated,null,2);_internals242.writeFileSync(tmpPath,json3,"utf-8"),_internals242.renameSync(tmpPath,finalPath)}function appendTaskHistory(map3,summary){return{...map3,task_history:{...map3.task_history,[summary.task_id]:summary}}}function appendDecision(map3,decision){return{...map3,decisions:[...map3.decisions,decision]}}var EXTENSION_LANGUAGE_MAP={".ts":"typescript",".tsx":"typescript",".js":"javascript",".jsx":"javascript",".mjs":"javascript",".py":"python",".rs":"rust",".go":"go",".json":"json",".md":"markdown",".yaml":"yaml",".yml":"yaml",".css":"css",".scss":"scss",".html":"html",".sh":"shell",".bash":"shell",".ps1":"powershell"};function detectLanguage(filePath){let ext=path294.extname(filePath).toLowerCase();return EXTENSION_LANGUAGE_MAP[ext]}var RE_EXPORT_NAMED=/export\s+(?:function|class|interface|type|const|let|var|enum)\s+(\w+)/g,RE_EXPORT_BRACE=/export\s*\{\s*([\w,\s]+)\s*\}/g,RE_IMPORT_FROM=/import\s+.*?\s+from\s+['"](.+?)['"]/g,RE_IMPORT_REQUIRE=/require\(\s*['"](.+?)['"]\s*\)/g,RE_FIRST_COMMENT=/\/\*(.+?)\*\//s,MAX_KEY_SYMBOLS=10,MAX_PURPOSE_LENGTH=200;function extractFileSummary(filePath,content,absolutePath2,existingEntry){let contentHash=computeContentHash3(content),language=detectLanguage(filePath),exportsList=extractExports(content),importsList=extractImports6(content),purpose=extractPurpose(content),keySymbols=exportsList.slice(0,MAX_KEY_SYMBOLS),mtimeMs=0;if(absolutePath2)try{mtimeMs=fs165.statSync(absolutePath2).mtimeMs}catch{}let base={path:filePath,content_hash:contentHash,mtime_ms:mtimeMs,language,purpose,exports:exportsList.length>0?exportsList:void 0,imports:importsList.length>0?importsList:void 0,key_symbols:keySymbols.length>0?keySymbols:void 0,summary:purpose};if(existingEntry)return{...base,invariants:existingEntry.invariants,risks:existingEntry.risks,tests:existingEntry.tests,last_seen_task_ids:existingEntry.last_seen_task_ids};return base}function isFileStale(entry,currentContent){let currentHash=computeContentHash3(currentContent);return entry.content_hash!==currentHash}function extractExports(content){let symbols2=[],namedRe=new RegExp(RE_EXPORT_NAMED.source,"g"),match;match=namedRe.exec(content);while(match!==null)symbols2.push(match[1]),match=namedRe.exec(content);let braceRe=new RegExp(RE_EXPORT_BRACE.source,"g");match=braceRe.exec(content);while(match!==null){let list2=match[1];for(let name of list2.split(",")){let trimmed=name.trim();if(trimmed)symbols2.push(trimmed)}match=braceRe.exec(content)}return symbols2}function extractImports6(content){let specifiers=[],fromRe=new RegExp(RE_IMPORT_FROM.source,"g"),match;match=fromRe.exec(content);while(match!==null)specifiers.push(match[1]),match=fromRe.exec(content);let requireRe=new RegExp(RE_IMPORT_REQUIRE.source,"g");match=requireRe.exec(content);while(match!==null)specifiers.push(match[1]),match=requireRe.exec(content);return specifiers}function extractPurpose(content){let match=RE_FIRST_COMMENT.exec(content);if(!match)return"No summary available";let body=match[1].split(`
|
|
7185
|
-
`).map((line)=>line.replace(/^\s*\*\s?/,"").trim()).join(" ").replace(/\s+/g," ").trim();if(body.length>MAX_PURPOSE_LENGTH)body=`${body.substring(0,MAX_PURPOSE_LENGTH)}...`;return body||"No summary available"}var MAX_CONTEXT_MD_DECISIONS=50,MAX_CONTEXT_MD_CONTENT_CHARS=1e6;function allocateDecisionId(decisions){let max=0n;for(let entry of decisions){if(typeof entry?.id!=="string")continue;let match=/^A(\d+)$/.exec(entry.id);if(!match)continue;let value=BigInt(match[1]);if(value>max)max=value}return`A${(max+1n).toString()}`}function isArchitectRole(role){return role==="architect"||role.endsWith("_architect")}function extractContextDecisionsFromContextMd(directory,options){if(options?.agent_role!==void 0&&!isArchitectRole(options.agent_role))return[];try{let contextMdPath=path295.join(directory,".swarm","context.md");if(!_internals243.existsSync(contextMdPath))return[];let content=_internals243.readFileSync(contextMdPath,"utf-8"),bounded=content.length>MAX_CONTEXT_MD_CONTENT_CHARS?content.slice(content.length-MAX_CONTEXT_MD_CONTENT_CHARS):content,extracted=extractContextDecisions(bounded),decisions=[];for(let entry of extracted){let separatorIndex=entry.text.indexOf(": "),decision=separatorIndex===-1?entry.text:entry.text.slice(0,separatorIndex),rationale=separatorIndex===-1?"":entry.text.slice(separatorIndex+2);if(decision.trim()===""||/^[\s✅]*$/.test(decision))continue;decisions.push({decision:sanitizeContextText(decision),rationale:sanitizeContextText(rationale),...entry.phase===null?{}:{phase:entry.phase}})}if(decisions.length>MAX_CONTEXT_MD_DECISIONS)return decisions.slice(decisions.length-MAX_CONTEXT_MD_DECISIONS);return decisions}catch{return[]}}var MAX_PERSISTED_DECISIONS=200;function deriveFinalStatus(params){if(params.rejection_reasons&¶ms.rejection_reasons.length>0)return"rejected";switch(params.final_status){case"completed":return"approved";case"failed":return"rejected";case"blocked":return"blocked";case"cancelled":return"rejected"}}function readFileContent(absolutePath2){try{if(!_internals243.existsSync(absolutePath2))return null;return _internals243.readFileSync(absolutePath2,"utf-8")}catch{return null}}function refreshFileEntry(relativePath2,absolutePath2,existingEntry){let content=readFileContent(absolutePath2);if(content===null)return null;return _internals243.extractFileSummary(relativePath2,content,absolutePath2,existingEntry)}var _internals243={loadContextMap,saveContextMap,createEmptyContextMap,extractFileSummary,existsSync:fs166.existsSync,readFileSync:fs166.readFileSync,readdirSync:fs166.readdirSync,realpathSync:fs166.realpathSync,appendTaskHistory,appendDecision};function extractEvidenceFindings(taskId,directory){let result={rejection_reasons:[],review_findings:[]};try{let evidenceDir=path295.join(directory,".swarm","evidence",taskId);if(!_internals243.existsSync(evidenceDir))return result;let evidenceFiles=_internals243.readdirSync(evidenceDir),targetFiles=["evidence.json","reviewer.json","test-engineer.json","test_engineer.json"];for(let fileName of evidenceFiles){if(!targetFiles.includes(fileName))continue;let filePath=path295.join(evidenceDir,fileName),content=readFileContent(filePath);if(content===null)continue;try{let parsed=JSON.parse(content);if(typeof parsed!=="object"||parsed===null||Array.isArray(parsed))continue;let obj=parsed;if(Array.isArray(obj.entries))for(let entry of obj.entries){if(typeof entry!=="object"||entry===null||Array.isArray(entry))continue;let entryObj=entry,entryType=String(entryObj.type??"").toLowerCase(),isActionable=entryType==="review"||entryType==="test"||entryType==="reviewer"||entryType==="test_engineer"||entryType==="test-engineer";if(isActionable&&typeof entryObj.verdict==="string"){let normalizedVerdict=String(entryObj.verdict).toLowerCase();if(normalizedVerdict==="rejected"||normalizedVerdict==="fail"||normalizedVerdict==="concerns")result.rejection_reasons.push(`[${fileName.replace(".json","")}] ${entryObj.verdict}`)}if(isActionable){let entryIssues=entryObj.issues||entryObj.findings||[];if(Array.isArray(entryIssues))for(let issue3 of entryIssues){let issueText=typeof issue3==="object"&&issue3!==null?String(issue3.message||issue3.detail||issue3.description||""):String(issue3);if(issueText)result.review_findings.push(issueText)}let entryFailures=entryObj.failures;if(Array.isArray(entryFailures))for(let failure of entryFailures){let failureText=typeof failure==="object"&&failure!==null?String(failure.message||failure.detail||String(failure)):String(failure);if(failureText)result.review_findings.push(failureText)}}}else{if(typeof obj.verdict==="string"){let normalizedVerdict=String(obj.verdict).toLowerCase();if(normalizedVerdict==="rejected"||normalizedVerdict==="fail"||normalizedVerdict==="concerns")result.rejection_reasons.push(`[${fileName.replace(".json","")}] ${obj.verdict}`)}if(Array.isArray(obj.issues))for(let issue3 of obj.issues){let issueText=typeof issue3==="object"&&issue3!==null?String(issue3.message||issue3.detail||issue3.description||""):String(issue3);if(issueText)result.review_findings.push(issueText)}if(Array.isArray(obj.findings)){for(let finding of obj.findings)if(typeof finding==="object"&&finding!==null){let findingText=String(finding.message||finding.detail||finding.description||"");if(findingText)result.review_findings.push(findingText)}}}}catch{}}}catch{}return result}function updateContextMapAfterAgent(params){try{let map3=_internals243.loadContextMap(params.directory);if(map3===null)map3=_internals243.createEmptyContextMap();let root=path295.resolve(params.directory),updatedFiles={...map3.files},validFiles=[],realRoot=_internals243.realpathSync(root);for(let filePath of params.files_touched)try{let resolved=path295.resolve(root,filePath),realResolved=_internals243.realpathSync(resolved),relative73=path295.relative(realRoot,realResolved);if(relative73.startsWith("..")||path295.isAbsolute(relative73))continue;let normalizedRelative=relative73.replace(/\\/g,"/"),existingEntry=map3.files[normalizedRelative],refreshed=refreshFileEntry(normalizedRelative,resolved,existingEntry);if(refreshed!==null)updatedFiles[normalizedRelative]=refreshed;validFiles.push(normalizedRelative)}catch{}map3={...map3,files:updatedFiles};let evidenceFindings=extractEvidenceFindings(params.task_id,params.directory),rejectionReasons=params.rejection_reasons??[],reviewFindings=params.review_findings??[],mergedRejectionReasons=[...rejectionReasons,...evidenceFindings.rejection_reasons.filter((r)=>!rejectionReasons.includes(r))],mergedReviewFindings=[...reviewFindings,...evidenceFindings.review_findings.filter((f)=>!reviewFindings.includes(f))],reviewerFindings=[...mergedRejectionReasons.map((r)=>`[rejection] ${r}`),...mergedReviewFindings],taskSummary={task_id:params.task_id,goal:params.task_goal,files_touched:validFiles,implementation_summary:params.implementation_summary,reviewer_findings:reviewerFindings.length>0?reviewerFindings:void 0,final_status:mergedRejectionReasons.length>0?"rejected":deriveFinalStatus(params)};if(map3=_internals243.appendTaskHistory(map3,taskSummary),params.decisions&¶ms.decisions.length>0){let batch=params.decisions.filter((entry)=>(entry.decision??"").trim()!==""),existingTexts=new Set(map3.decisions.map((entry)=>String(entry?.decision??"").trim())),nextSuffix=BigInt(allocateDecisionId(map3.decisions).slice(1));for(let entry of batch){let text=String(entry.decision).trim();if(existingTexts.has(text))continue;existingTexts.add(text);let decision={id:`A${nextSuffix.toString()}`,decision:entry.decision,rationale:entry.rationale,timestamp:new Date().toISOString(),task_id:params.task_id,...entry.phase===void 0?{}:{phase:entry.phase}};map3=_internals243.appendDecision(map3,decision),nextSuffix+=1n}}if(map3.decisions.length>MAX_PERSISTED_DECISIONS)map3={...map3,decisions:map3.decisions.slice(map3.decisions.length-MAX_PERSISTED_DECISIONS)};return _internals243.saveContextMap(map3,params.directory),map3}catch{try{return _internals243.loadContextMap(params.directory)??_internals243.createEmptyContextMap()}catch{return _internals243.createEmptyContextMap()}}}init_dashboard();init_group_commit_writer();init_observability_event_store();init_project_db();init_spawn_circuit();init_coordination_store();init_logger();var TOKEN_BUCKET_NAMESPACE="dispatch.token-bucket",TOKEN_BUCKET_ENTITY_KEY="project",buckets=new Map;function refill(bucket,ratePerSecond,capacity,now2){if(now2<bucket.lastRefillMs)bucket.lastRefillMs=now2;let elapsedSeconds=(now2-bucket.lastRefillMs)/1000;if(elapsedSeconds>0&&ratePerSecond>0)bucket.level=Math.min(capacity,bucket.level+elapsedSeconds*ratePerSecond),bucket.lastRefillMs=now2}function persist(directory,bucket){try{let payload={level:bucket.level,lastRefillMs:bucket.lastRefillMs};transitionCoordinationState(directory,{namespace:TOKEN_BUCKET_NAMESPACE,entityKey:TOKEN_BUCKET_ENTITY_KEY,generation:1,status:"active",payload:JSON.stringify(payload)})}catch(err){_internals244.onPersistError(err)}}function hydrate(directory,capacity){let existing=buckets.get(directory);if(existing)return existing;let bucket={level:capacity,lastRefillMs:_internals244.now(),hydrated:!0};try{let row=_internals244.readState(directory);if(row){let parsed=JSON.parse(row.payload);if(typeof parsed.level==="number"&&Number.isFinite(parsed.level)){let nowMs3=_internals244.now();bucket={level:Math.min(capacity,Math.max(0,parsed.level)),lastRefillMs:typeof parsed.lastRefillMs==="number"&&Number.isFinite(parsed.lastRefillMs)?Math.min(parsed.lastRefillMs,nowMs3):nowMs3,hydrated:!0}}}}catch(err){_internals244.onPersistError(err)}return buckets.set(directory,bucket),bucket}async function acquireDispatchToken(input){let rate3=input.ratePerSecond;if(!(rate3>0))return;let capacity=Math.max(1,input.burstCapacity),bucket=hydrate(input.directory,capacity),waited=!1;for(;;){let now2=_internals244.now();if(refill(bucket,rate3,capacity,now2),bucket.level>=1){if(bucket.level-=1,waited)persist(input.directory,bucket);return}waited=!0;let waitMs=Math.max(1,(1-bucket.level)/rate3*1000);await _internals244.sleep(Math.min(waitMs,1000))}}var _internals244={now:()=>Date.now(),sleep:(ms2)=>new Promise((resolve112)=>setTimeout(resolve112,ms2)),readState:(directory)=>getCoordinationState(directory,TOKEN_BUCKET_NAMESPACE,TOKEN_BUCKET_ENTITY_KEY),onPersistError:(err)=>{if(process.env.DEBUG_SWARM)log("[dispatch.token-bucket] persist failed",err)}};init_model_dispatch_fallback();init_provider_error_classification();init_ephemeral_agent_dispatcher();function parseRequestedModel(modelId){if(modelId==="configured")return;let parsed=parseModelString2(modelId);if(!parsed)throw Error("explicit evaluation models must use provider/model syntax");return parsed}function resolveEvaluationAgentName(agents,logicalName,preferredSwarm){let names=agents.map((agent)=>agent.name);if(preferredSwarm){let preferred=`${preferredSwarm}_${logicalName}`;if(names.includes(preferred))return preferred;throw Error(`preferred swarm ${preferredSwarm} does not provide evaluation agent ${logicalName}`)}if(names.includes(logicalName))return logicalName;let prefixed=names.filter((name)=>name.endsWith(`_${logicalName}`)).sort((left,right)=>left.localeCompare(right));if(prefixed.length===1)return prefixed[0];if(prefixed.length>1)throw Error(`multiple swarms provide ${logicalName}; preferredSwarm is required`);throw Error(`evaluation agent ${logicalName} is not registered`)}var _internals245=Object.defineProperties({},{boundedAbort:{enumerable:!0,get:()=>_internals195.boundedAbort,set:(value)=>{_internals195.boundedAbort=value}},boundedDelete:{enumerable:!0,get:()=>_internals195.boundedDelete,set:(value)=>{_internals195.boundedDelete=value}},log:{enumerable:!0,get:()=>_internals195.log,set:(value)=>{_internals195.log=value}}});async function awaitWithAbort2(promise3,signal2){if(signal2.aborted)throw Error("evaluation dispatch aborted");return new Promise((resolve112,reject2)=>{let onAbort=()=>reject2(Error("evaluation dispatch aborted"));signal2.addEventListener("abort",onAbort,{once:!0}),promise3.then(resolve112,reject2).finally(()=>{signal2.removeEventListener("abort",onAbort)})})}function createEvaluationModelDispatcher(client,pricing){return async(request)=>{let startedAt=Date.now();if(request.abortSignal?.aborted)return{status:"cancelled",modelId:request.modelId,text:"",durationMs:0};let resolvedAgentName,controller=new AbortController,timedOut=!1,abortListener=()=>controller.abort();request.abortSignal?.addEventListener("abort",abortListener,{once:!0});let timeoutHandle=setTimeout(()=>{timedOut=!0,controller.abort()},request.timeoutMs);try{let requestedModel=parseRequestedModel(request.modelId),agentsResult=await awaitWithAbort2(client.app.agents({query:{directory:request.sessionDirectory},signal:controller.signal}),controller.signal);if(!agentsResult.data)throw Error(`Failed to list registered evaluation agents: ${JSON.stringify(agentsResult.error)}`);resolvedAgentName=resolveEvaluationAgentName(agentsResult.data,request.agentName,request.preferredSwarm);let result=(await dispatchWithModelFallback({dispatch:async(_model,context)=>{let result2=await dispatchEphemeralAgent({client,directory:request.sessionDirectory,parentSessionId:request.parentSessionId,agentName:resolvedAgentName,model:requestedModel,...request.system===void 0?{}:{system:request.system},prompt:request.prompt,readOnlyTools:DEFAULT_READ_ONLY_TOOLS,title:`evaluation gate (${resolvedAgentName})`,timeoutMs:context.remainingMs??request.timeoutMs,abortSignal:controller.signal,pricing});if(result2.status==="completed")return result2;if(result2.status==="timeout")timedOut=!0;throw Error(result2.error??`evaluation dispatch ${result2.status}`)},classify:(error93)=>{let message=error93 instanceof Error?error93.message:String(error93);return isTransientProviderError(message)?"transient":"permanent"},maxTransientRetriesPerModel:2,backoffMs:()=>0,maxAttempts:3,deadlineAtMs:startedAt+request.timeoutMs})).result;return{status:"completed",modelId:result.modelId??request.modelId,agentName:resolvedAgentName,text:result.text,durationMs:Date.now()-startedAt,promptBytes:result.promptBytes,responseBytes:result.responseBytes,costFields:result.costFields}}catch(error93){let cancelled=request.abortSignal?.aborted===!0,msg=error93 instanceof Error?error93.message:String(error93),quotaMessage=isQuotaError(msg)?`${msg} (model quota/usage limit; retried the same model 2 time(s) — not substituted, to preserve benchmark attribution)`:msg;return{status:cancelled?"cancelled":timedOut?"timeout":"error",modelId:request.modelId,agentName:resolvedAgentName,text:"",durationMs:Date.now()-startedAt,error:quotaMessage}}finally{clearTimeout(timeoutHandle),request.abortSignal?.removeEventListener("abort",abortListener),controller.abort()}}}init_action_circuit();init_action_identity();init_invocation_failure();init_constants();init_schema();init_logger();init_oversight();init_state2();function configCadence(config3){let oversight=config3.full_auto?.oversight;return{everyToolCalls:oversight?.every_tool_calls??25,everyArchitectTurns:oversight?.every_architect_turns??5,everyMinutes:oversight?.every_minutes??20}}function denialLimits(config3){return{maxConsecutive:config3.full_auto?.denials?.max_consecutive??3,maxTotal:config3.full_auto?.denials?.max_total??20}}function evaluateFullAutoCadence(state2,config3,now2=Date.now()){let triggers=[],cadence=configCadence(config3),denials=denialLimits(config3);if(cadence.everyToolCalls>0&&state2.counters.toolCalls>0&&state2.counters.toolCalls%cadence.everyToolCalls===0)triggers.push({kind:"tool_calls",threshold:cadence.everyToolCalls});if(cadence.everyArchitectTurns>0&&state2.counters.architectTurns>0&&state2.counters.architectTurns%cadence.everyArchitectTurns===0)triggers.push({kind:"architect_turns",threshold:cadence.everyArchitectTurns});if(cadence.everyMinutes>0&&state2.lastOversightAt){let lastTs=Date.parse(state2.lastOversightAt);if(Number.isFinite(lastTs)){let elapsedMinutes=(now2-lastTs)/60000;if(elapsedMinutes>=cadence.everyMinutes)triggers.push({kind:"minutes",threshold:cadence.everyMinutes,elapsedMinutes})}}if(state2.counters.consecutiveNoProgressTurns>=3)triggers.push({kind:"consecutive_no_progress",threshold:3});if(denials.maxConsecutive>1&&state2.denialCounters.consecutive>=denials.maxConsecutive-1&&state2.denialCounters.consecutive<denials.maxConsecutive)triggers.push({kind:"denials_near_limit",consecutive:state2.denialCounters.consecutive,max:denials.maxConsecutive});return{shouldEscalate:triggers.length>0,triggers}}function tickAndEvaluate(directory,sessionID,counter,config3){let before=loadFullAutoRunState(directory,sessionID);if(!before||before.status!=="running")return;let updated=incrementFullAutoCounter(directory,sessionID,counter);if(!updated)return;return evaluateFullAutoCadence(updated,config3)}var cadenceDispatchInFlight=new Set;function resolveOversightAgentName2(activeAgent){if(!activeAgent)return"critic_oversight";if(stripKnownSwarmPrefix(activeAgent)!==ORCHESTRATOR_NAME)return"critic_oversight";let lastIdx=activeAgent.toLowerCase().lastIndexOf("architect");if(lastIdx>0)return`${activeAgent.slice(0,lastIdx)}critic_oversight`;return"critic_oversight"}function tickAndMaybeDispatchCadence(directory,sessionID,counter,config3,options={}){let decision=tickAndEvaluate(directory,sessionID,counter,config3);if(!decision||!decision.shouldEscalate)return decision;if(cadenceDispatchInFlight.has(sessionID))return decision;let runState=loadFullAutoRunState(directory,sessionID);if(!runState||runState.status!=="running")return decision;let oversightAgentName=resolveOversightAgentName2(options.activeAgent),criticModel=config3.full_auto?.critic_model??config3.agents?.critic?.model??"opencode/big-pickle";return cadenceDispatchInFlight.add(sessionID),(options.dispatch??dispatchFullAutoOversight)({directory,sessionID,trigger:`cadence:${decision.triggers.map((t)=>t.kind).join(",")}`,triggerSource:"cadence",phase:runState.currentPhase,taskID:runState.currentTaskID??void 0,planID:runState.planID,actionContext:{counters:runState.counters,denialCounters:runState.denialCounters,triggers:decision.triggers},criticModel,oversightAgentName,fullAutoConfig:{fail_closed:config3.full_auto?.fail_closed!==!1,max_dispatch_retries:config3.full_auto?.oversight?.max_dispatch_retries??2,max_consecutive_dispatch_failures:config3.full_auto?.oversight?.max_consecutive_dispatch_failures??3,total_timeout_ms:config3.full_auto?.oversight?.total_timeout_ms??120000}}).catch((err)=>{error48(`[full-auto/cadence] dispatch threw past dispatcher's own fail-closed branches: ${err instanceof Error?err.message:String(err)}`)}).finally(()=>{cadenceDispatchInFlight.delete(sessionID)}),decision}init_recovery2();init_severe_result();init_state2();init_task_file();init_invocation_failure();init_state();init_utils();init_realtime_learning_nudge();init_utils2();import*as nodePath from"node:path";var MAX_TOOL_FAILURE_REASONS=5,MAX_TOOL_FAILURE_REASON_LENGTH=200;function extractFailureReason(error93){let raw;if(error93 instanceof Error)raw=error93.message;else if(typeof error93==="string")raw=error93;else if(error93&&typeof error93==="object"){let maybeMessage=error93.message;raw=typeof maybeMessage==="string"?maybeMessage:void 0}if(!raw)return;let trimmed=sanitizeFailureEvidenceDisplay(raw).trim();if(!trimmed)return;return trimmed.length>MAX_TOOL_FAILURE_REASON_LENGTH?`${trimmed.slice(0,MAX_TOOL_FAILURE_REASON_LENGTH)}...`:trimmed}function recordFailureReason(aggregate,reason){if(!aggregate.failureReasons)aggregate.failureReasons=[];if(aggregate.failureReasons.includes(reason))return;if(aggregate.failureReasons.length>=MAX_TOOL_FAILURE_REASONS)return;aggregate.failureReasons.push(reason)}function createAgentActivityHooks(config3,directory){if(config3.hooks?.agent_activity===!1)return{toolBefore:async()=>{},toolAfter:async()=>{}};return{toolBefore:async(input)=>{swarmState.activeToolCalls.set(input.callID,{tool:input.tool,sessionID:input.sessionID,callID:input.callID,startTime:Date.now()})},toolAfter:async(input,output)=>{let entry=swarmState.activeToolCalls.get(input.callID);if(!entry)return;swarmState.activeToolCalls.delete(input.callID);let duration5=Date.now()-entry.startTime,success3=!((typeof output.success==="boolean"?output.success:void 0)===!1||!!output.error),key2=entry.tool,existing=swarmState.toolAggregates.get(key2)??{tool:key2,count:0,successCount:0,failureCount:0,totalDuration:0};if(existing.count++,success3)existing.successCount++;else{existing.failureCount++;let reason=extractFailureReason(output.error);if(reason)recordFailureReason(existing,reason)}if(existing.totalDuration+=duration5,swarmState.toolAggregates.set(key2,existing),recordRealtimeLearningToolCall(entry.sessionID),swarmState.pendingEvents++,swarmState.pendingEvents>=20)flushActivityToFile(directory).catch((err)=>warn("Agent activity flush trigger failed:",err))}}}var flushPromise=null;async function flushActivityToFile(directory){if(flushPromise)return flushPromise=flushPromise.then(()=>doFlush(directory)).catch((err)=>{warn("Queued agent activity flush failed:",err)}),flushPromise;flushPromise=doFlush(directory);try{await flushPromise}finally{flushPromise=null}}async function doFlush(directory){try{let existing=await readSwarmFileAsync(directory,"context.md")??"",activitySection=renderActivitySection(),updated=replaceOrAppendSection(existing,"## Agent Activity",activitySection),flushedCount=swarmState.pendingEvents,path296=nodePath.join(directory,".swarm","context.md");await atomicWriteFile(path296,updated),swarmState.pendingEvents=Math.max(0,swarmState.pendingEvents-flushedCount)}catch(error93){warn("Agent activity flush failed:",error93)}}function renderActivitySection(){let lines=["## Agent Activity",""];if(swarmState.toolAggregates.size===0)return lines.push("No tool activity recorded yet."),lines.join(`
|
|
7185
|
+
`).map((line)=>line.replace(/^\s*\*\s?/,"").trim()).join(" ").replace(/\s+/g," ").trim();if(body.length>MAX_PURPOSE_LENGTH)body=`${body.substring(0,MAX_PURPOSE_LENGTH)}...`;return body||"No summary available"}var MAX_CONTEXT_MD_DECISIONS=50,MAX_CONTEXT_MD_CONTENT_CHARS=1e6;function allocateDecisionId(decisions){let max=0n;for(let entry of decisions){if(typeof entry?.id!=="string")continue;let match=/^A(\d+)$/.exec(entry.id);if(!match)continue;let value=BigInt(match[1]);if(value>max)max=value}return`A${(max+1n).toString()}`}function isArchitectRole(role){return role==="architect"||role.endsWith("_architect")}function extractContextDecisionsFromContextMd(directory,options){if(options?.agent_role!==void 0&&!isArchitectRole(options.agent_role))return[];try{let contextMdPath=path295.join(directory,".swarm","context.md");if(!_internals243.existsSync(contextMdPath))return[];let content=_internals243.readFileSync(contextMdPath,"utf-8"),bounded=content.length>MAX_CONTEXT_MD_CONTENT_CHARS?content.slice(content.length-MAX_CONTEXT_MD_CONTENT_CHARS):content,extracted=extractContextDecisions(bounded),decisions=[];for(let entry of extracted){let separatorIndex=entry.text.indexOf(": "),decision=separatorIndex===-1?entry.text:entry.text.slice(0,separatorIndex),rationale=separatorIndex===-1?"":entry.text.slice(separatorIndex+2);if(decision.trim()===""||/^[\s✅]*$/.test(decision))continue;decisions.push({decision:sanitizeContextText(decision),rationale:sanitizeContextText(rationale),...entry.phase===null?{}:{phase:entry.phase}})}if(decisions.length>MAX_CONTEXT_MD_DECISIONS)return decisions.slice(decisions.length-MAX_CONTEXT_MD_DECISIONS);return decisions}catch{return[]}}var MAX_PERSISTED_DECISIONS=200;function deriveFinalStatus(params){if(params.rejection_reasons&¶ms.rejection_reasons.length>0)return"rejected";switch(params.final_status){case"completed":return"approved";case"failed":return"rejected";case"blocked":return"blocked";case"cancelled":return"rejected"}}function readFileContent(absolutePath2){try{if(!_internals243.existsSync(absolutePath2))return null;return _internals243.readFileSync(absolutePath2,"utf-8")}catch{return null}}function refreshFileEntry(relativePath2,absolutePath2,existingEntry){let content=readFileContent(absolutePath2);if(content===null)return null;return _internals243.extractFileSummary(relativePath2,content,absolutePath2,existingEntry)}var _internals243={loadContextMap,saveContextMap,createEmptyContextMap,extractFileSummary,existsSync:fs166.existsSync,readFileSync:fs166.readFileSync,readdirSync:fs166.readdirSync,realpathSync:fs166.realpathSync,appendTaskHistory,appendDecision};function extractEvidenceFindings(taskId,directory){let result={rejection_reasons:[],review_findings:[]};try{let evidenceDir=path295.join(directory,".swarm","evidence",taskId);if(!_internals243.existsSync(evidenceDir))return result;let evidenceFiles=_internals243.readdirSync(evidenceDir),targetFiles=["evidence.json","reviewer.json","test-engineer.json","test_engineer.json"];for(let fileName of evidenceFiles){if(!targetFiles.includes(fileName))continue;let filePath=path295.join(evidenceDir,fileName),content=readFileContent(filePath);if(content===null)continue;try{let parsed=JSON.parse(content);if(typeof parsed!=="object"||parsed===null||Array.isArray(parsed))continue;let obj=parsed;if(Array.isArray(obj.entries))for(let entry of obj.entries){if(typeof entry!=="object"||entry===null||Array.isArray(entry))continue;let entryObj=entry,entryType=String(entryObj.type??"").toLowerCase(),isActionable=entryType==="review"||entryType==="test"||entryType==="reviewer"||entryType==="test_engineer"||entryType==="test-engineer";if(isActionable&&typeof entryObj.verdict==="string"){let normalizedVerdict=String(entryObj.verdict).toLowerCase();if(normalizedVerdict==="rejected"||normalizedVerdict==="fail"||normalizedVerdict==="concerns")result.rejection_reasons.push(`[${fileName.replace(".json","")}] ${entryObj.verdict}`)}if(isActionable){let entryIssues=entryObj.issues||entryObj.findings||[];if(Array.isArray(entryIssues))for(let issue3 of entryIssues){let issueText=typeof issue3==="object"&&issue3!==null?String(issue3.message||issue3.detail||issue3.description||""):String(issue3);if(issueText)result.review_findings.push(issueText)}let entryFailures=entryObj.failures;if(Array.isArray(entryFailures))for(let failure of entryFailures){let failureText=typeof failure==="object"&&failure!==null?String(failure.message||failure.detail||String(failure)):String(failure);if(failureText)result.review_findings.push(failureText)}}}else{if(typeof obj.verdict==="string"){let normalizedVerdict=String(obj.verdict).toLowerCase();if(normalizedVerdict==="rejected"||normalizedVerdict==="fail"||normalizedVerdict==="concerns")result.rejection_reasons.push(`[${fileName.replace(".json","")}] ${obj.verdict}`)}if(Array.isArray(obj.issues))for(let issue3 of obj.issues){let issueText=typeof issue3==="object"&&issue3!==null?String(issue3.message||issue3.detail||issue3.description||""):String(issue3);if(issueText)result.review_findings.push(issueText)}if(Array.isArray(obj.findings)){for(let finding of obj.findings)if(typeof finding==="object"&&finding!==null){let findingText=String(finding.message||finding.detail||finding.description||"");if(findingText)result.review_findings.push(findingText)}}}}catch{}}}catch{}return result}function updateContextMapAfterAgent(params){try{let map3=_internals243.loadContextMap(params.directory);if(map3===null)map3=_internals243.createEmptyContextMap();let root=path295.resolve(params.directory),updatedFiles={...map3.files},validFiles=[],realRoot=_internals243.realpathSync(root);for(let filePath of params.files_touched)try{let resolved=path295.resolve(root,filePath),realResolved=_internals243.realpathSync(resolved),relative73=path295.relative(realRoot,realResolved);if(relative73.startsWith("..")||path295.isAbsolute(relative73))continue;let normalizedRelative=relative73.replace(/\\/g,"/"),existingEntry=map3.files[normalizedRelative],refreshed=refreshFileEntry(normalizedRelative,resolved,existingEntry);if(refreshed!==null)updatedFiles[normalizedRelative]=refreshed;validFiles.push(normalizedRelative)}catch{}map3={...map3,files:updatedFiles};let evidenceFindings=extractEvidenceFindings(params.task_id,params.directory),rejectionReasons=params.rejection_reasons??[],reviewFindings=params.review_findings??[],mergedRejectionReasons=[...rejectionReasons,...evidenceFindings.rejection_reasons.filter((r)=>!rejectionReasons.includes(r))],mergedReviewFindings=[...reviewFindings,...evidenceFindings.review_findings.filter((f)=>!reviewFindings.includes(f))],reviewerFindings=[...mergedRejectionReasons.map((r)=>`[rejection] ${r}`),...mergedReviewFindings],taskSummary={task_id:params.task_id,goal:params.task_goal,files_touched:validFiles,implementation_summary:params.implementation_summary,reviewer_findings:reviewerFindings.length>0?reviewerFindings:void 0,final_status:mergedRejectionReasons.length>0?"rejected":deriveFinalStatus(params)};if(map3=_internals243.appendTaskHistory(map3,taskSummary),params.decisions&¶ms.decisions.length>0){let batch=params.decisions.filter((entry)=>(entry.decision??"").trim()!==""),existingTexts=new Set(map3.decisions.map((entry)=>String(entry?.decision??"").trim())),nextSuffix=BigInt(allocateDecisionId(map3.decisions).slice(1));for(let entry of batch){let text=String(entry.decision).trim();if(existingTexts.has(text))continue;existingTexts.add(text);let decision={id:`A${nextSuffix.toString()}`,decision:entry.decision,rationale:entry.rationale,timestamp:new Date().toISOString(),task_id:params.task_id,...entry.phase===void 0?{}:{phase:entry.phase}};map3=_internals243.appendDecision(map3,decision),nextSuffix+=1n}}if(map3.decisions.length>MAX_PERSISTED_DECISIONS)map3={...map3,decisions:map3.decisions.slice(map3.decisions.length-MAX_PERSISTED_DECISIONS)};return _internals243.saveContextMap(map3,params.directory),map3}catch{try{return _internals243.loadContextMap(params.directory)??_internals243.createEmptyContextMap()}catch{return _internals243.createEmptyContextMap()}}}init_dashboard();init_group_commit_writer();init_observability_event_store();init_project_db();init_spawn_circuit();init_coordination_store();init_logger();var TOKEN_BUCKET_NAMESPACE="dispatch.token-bucket",TOKEN_BUCKET_ENTITY_KEY="project",buckets=new Map;function refill(bucket,ratePerSecond,capacity,now2){if(now2<bucket.lastRefillMs)bucket.lastRefillMs=now2;let elapsedSeconds=(now2-bucket.lastRefillMs)/1000;if(elapsedSeconds>0&&ratePerSecond>0)bucket.level=Math.min(capacity,bucket.level+elapsedSeconds*ratePerSecond),bucket.lastRefillMs=now2}function persist(directory,bucket){try{let payload={level:bucket.level,lastRefillMs:bucket.lastRefillMs};transitionCoordinationState(directory,{namespace:TOKEN_BUCKET_NAMESPACE,entityKey:TOKEN_BUCKET_ENTITY_KEY,generation:1,status:"active",payload:JSON.stringify(payload)})}catch(err){_internals244.onPersistError(err)}}function hydrate(directory,capacity){let existing=buckets.get(directory);if(existing)return existing;let bucket={level:capacity,lastRefillMs:_internals244.now(),hydrated:!0};try{let row=_internals244.readState(directory);if(row){let parsed=JSON.parse(row.payload);if(typeof parsed.level==="number"&&Number.isFinite(parsed.level)){let nowMs3=_internals244.now();bucket={level:Math.min(capacity,Math.max(0,parsed.level)),lastRefillMs:typeof parsed.lastRefillMs==="number"&&Number.isFinite(parsed.lastRefillMs)?Math.min(parsed.lastRefillMs,nowMs3):nowMs3,hydrated:!0}}}}catch(err){_internals244.onPersistError(err)}return buckets.set(directory,bucket),bucket}async function acquireDispatchToken(input){let rate3=input.ratePerSecond;if(!(rate3>0))return;let capacity=Math.max(1,input.burstCapacity),bucket=hydrate(input.directory,capacity),waited=!1;for(;;){let now2=_internals244.now();if(refill(bucket,rate3,capacity,now2),bucket.level>=1){if(bucket.level-=1,waited)persist(input.directory,bucket);return}waited=!0;let waitMs=Math.max(1,(1-bucket.level)/rate3*1000);await _internals244.sleep(Math.min(waitMs,1000))}}var _internals244={now:()=>Date.now(),sleep:(ms2)=>new Promise((resolve112)=>setTimeout(resolve112,ms2)),readState:(directory)=>getCoordinationState(directory,TOKEN_BUCKET_NAMESPACE,TOKEN_BUCKET_ENTITY_KEY),onPersistError:(err)=>{if(process.env.DEBUG_SWARM)log("[dispatch.token-bucket] persist failed",err)}};init_model_dispatch_fallback();init_provider_error_classification();init_ephemeral_agent_dispatcher();function parseRequestedModel(modelId){if(modelId==="configured")return;let parsed=parseModelString2(modelId);if(!parsed)throw Error("explicit evaluation models must use provider/model syntax");return parsed}function resolveEvaluationAgentName(agents,logicalName,preferredSwarm){let names=agents.map((agent)=>agent.name);if(preferredSwarm){let preferred=`${preferredSwarm}_${logicalName}`;if(names.includes(preferred))return preferred;throw Error(`preferred swarm ${preferredSwarm} does not provide evaluation agent ${logicalName}`)}if(names.includes(logicalName))return logicalName;let prefixed=names.filter((name)=>name.endsWith(`_${logicalName}`)).sort((left,right)=>left.localeCompare(right));if(prefixed.length===1)return prefixed[0];if(prefixed.length>1)throw Error(`multiple swarms provide ${logicalName}; preferredSwarm is required`);throw Error(`evaluation agent ${logicalName} is not registered`)}var _internals245=Object.defineProperties({},{boundedAbort:{enumerable:!0,get:()=>_internals195.boundedAbort,set:(value)=>{_internals195.boundedAbort=value}},boundedDelete:{enumerable:!0,get:()=>_internals195.boundedDelete,set:(value)=>{_internals195.boundedDelete=value}},log:{enumerable:!0,get:()=>_internals195.log,set:(value)=>{_internals195.log=value}}});async function awaitWithAbort2(promise3,signal2){if(signal2.aborted)throw Error("evaluation dispatch aborted");return new Promise((resolve112,reject2)=>{let onAbort=()=>reject2(Error("evaluation dispatch aborted"));signal2.addEventListener("abort",onAbort,{once:!0}),promise3.then(resolve112,reject2).finally(()=>{signal2.removeEventListener("abort",onAbort)})})}function createEvaluationModelDispatcher(client,pricing){return async(request)=>{let startedAt=Date.now();if(request.abortSignal?.aborted)return{status:"cancelled",modelId:request.modelId,text:"",durationMs:0};let resolvedAgentName,controller=new AbortController,timedOut=!1,abortListener=()=>controller.abort();request.abortSignal?.addEventListener("abort",abortListener,{once:!0});let timeoutHandle=setTimeout(()=>{timedOut=!0,controller.abort()},request.timeoutMs);try{let requestedModel=parseRequestedModel(request.modelId);if(!client.app||typeof client.app.agents!=="function")throw Error("evaluation dispatch unavailable: host client carries no app.agents surface");let agentsResult=await awaitWithAbort2(client.app.agents({query:{directory:request.sessionDirectory},signal:controller.signal}),controller.signal);if(!agentsResult.data)throw Error(`Failed to list registered evaluation agents: ${JSON.stringify(agentsResult.error)}`);resolvedAgentName=resolveEvaluationAgentName(agentsResult.data,request.agentName,request.preferredSwarm);let result=(await dispatchWithModelFallback({dispatch:async(_model,context)=>{let result2=await dispatchEphemeralAgent({client,directory:request.sessionDirectory,parentSessionId:request.parentSessionId,agentName:resolvedAgentName,model:requestedModel,...request.system===void 0?{}:{system:request.system},prompt:request.prompt,readOnlyTools:DEFAULT_READ_ONLY_TOOLS,title:`evaluation gate (${resolvedAgentName})`,timeoutMs:context.remainingMs??request.timeoutMs,abortSignal:controller.signal,pricing});if(result2.status==="completed")return result2;if(result2.status==="timeout")timedOut=!0;throw Error(result2.error??`evaluation dispatch ${result2.status}`)},classify:(error93)=>{let message=error93 instanceof Error?error93.message:String(error93);return isTransientProviderError(message)?"transient":"permanent"},maxTransientRetriesPerModel:2,backoffMs:()=>0,maxAttempts:3,deadlineAtMs:startedAt+request.timeoutMs})).result;return{status:"completed",modelId:result.modelId??request.modelId,agentName:resolvedAgentName,text:result.text,durationMs:Date.now()-startedAt,promptBytes:result.promptBytes,responseBytes:result.responseBytes,costFields:result.costFields}}catch(error93){let cancelled=request.abortSignal?.aborted===!0,msg=error93 instanceof Error?error93.message:String(error93),quotaMessage=isQuotaError(msg)?`${msg} (model quota/usage limit; retried the same model 2 time(s) — not substituted, to preserve benchmark attribution)`:msg;return{status:cancelled?"cancelled":timedOut?"timeout":"error",modelId:request.modelId,agentName:resolvedAgentName,text:"",durationMs:Date.now()-startedAt,error:quotaMessage}}finally{clearTimeout(timeoutHandle),request.abortSignal?.removeEventListener("abort",abortListener),controller.abort()}}}init_action_circuit();init_action_identity();init_invocation_failure();init_constants();init_schema();init_logger();init_oversight();init_state2();function configCadence(config3){let oversight=config3.full_auto?.oversight;return{everyToolCalls:oversight?.every_tool_calls??25,everyArchitectTurns:oversight?.every_architect_turns??5,everyMinutes:oversight?.every_minutes??20}}function denialLimits(config3){return{maxConsecutive:config3.full_auto?.denials?.max_consecutive??3,maxTotal:config3.full_auto?.denials?.max_total??20}}function evaluateFullAutoCadence(state2,config3,now2=Date.now()){let triggers=[],cadence=configCadence(config3),denials=denialLimits(config3);if(cadence.everyToolCalls>0&&state2.counters.toolCalls>0&&state2.counters.toolCalls%cadence.everyToolCalls===0)triggers.push({kind:"tool_calls",threshold:cadence.everyToolCalls});if(cadence.everyArchitectTurns>0&&state2.counters.architectTurns>0&&state2.counters.architectTurns%cadence.everyArchitectTurns===0)triggers.push({kind:"architect_turns",threshold:cadence.everyArchitectTurns});if(cadence.everyMinutes>0&&state2.lastOversightAt){let lastTs=Date.parse(state2.lastOversightAt);if(Number.isFinite(lastTs)){let elapsedMinutes=(now2-lastTs)/60000;if(elapsedMinutes>=cadence.everyMinutes)triggers.push({kind:"minutes",threshold:cadence.everyMinutes,elapsedMinutes})}}if(state2.counters.consecutiveNoProgressTurns>=3)triggers.push({kind:"consecutive_no_progress",threshold:3});if(denials.maxConsecutive>1&&state2.denialCounters.consecutive>=denials.maxConsecutive-1&&state2.denialCounters.consecutive<denials.maxConsecutive)triggers.push({kind:"denials_near_limit",consecutive:state2.denialCounters.consecutive,max:denials.maxConsecutive});return{shouldEscalate:triggers.length>0,triggers}}function tickAndEvaluate(directory,sessionID,counter,config3){let before=loadFullAutoRunState(directory,sessionID);if(!before||before.status!=="running")return;let updated=incrementFullAutoCounter(directory,sessionID,counter);if(!updated)return;return evaluateFullAutoCadence(updated,config3)}var cadenceDispatchInFlight=new Set;function resolveOversightAgentName2(activeAgent){if(!activeAgent)return"critic_oversight";if(stripKnownSwarmPrefix(activeAgent)!==ORCHESTRATOR_NAME)return"critic_oversight";let lastIdx=activeAgent.toLowerCase().lastIndexOf("architect");if(lastIdx>0)return`${activeAgent.slice(0,lastIdx)}critic_oversight`;return"critic_oversight"}function tickAndMaybeDispatchCadence(directory,sessionID,counter,config3,options={}){let decision=tickAndEvaluate(directory,sessionID,counter,config3);if(!decision||!decision.shouldEscalate)return decision;if(cadenceDispatchInFlight.has(sessionID))return decision;let runState=loadFullAutoRunState(directory,sessionID);if(!runState||runState.status!=="running")return decision;let oversightAgentName=resolveOversightAgentName2(options.activeAgent),criticModel=config3.full_auto?.critic_model??config3.agents?.critic?.model??"opencode/big-pickle";return cadenceDispatchInFlight.add(sessionID),(options.dispatch??dispatchFullAutoOversight)({directory,sessionID,trigger:`cadence:${decision.triggers.map((t)=>t.kind).join(",")}`,triggerSource:"cadence",phase:runState.currentPhase,taskID:runState.currentTaskID??void 0,planID:runState.planID,actionContext:{counters:runState.counters,denialCounters:runState.denialCounters,triggers:decision.triggers},criticModel,oversightAgentName,fullAutoConfig:{fail_closed:config3.full_auto?.fail_closed!==!1,max_dispatch_retries:config3.full_auto?.oversight?.max_dispatch_retries??2,max_consecutive_dispatch_failures:config3.full_auto?.oversight?.max_consecutive_dispatch_failures??3,total_timeout_ms:config3.full_auto?.oversight?.total_timeout_ms??120000}}).catch((err)=>{error48(`[full-auto/cadence] dispatch threw past dispatcher's own fail-closed branches: ${err instanceof Error?err.message:String(err)}`)}).finally(()=>{cadenceDispatchInFlight.delete(sessionID)}),decision}init_recovery2();init_severe_result();init_state2();init_task_file();init_invocation_failure();init_state();init_utils();init_realtime_learning_nudge();init_utils2();import*as nodePath from"node:path";var MAX_TOOL_FAILURE_REASONS=5,MAX_TOOL_FAILURE_REASON_LENGTH=200;function extractFailureReason(error93){let raw;if(error93 instanceof Error)raw=error93.message;else if(typeof error93==="string")raw=error93;else if(error93&&typeof error93==="object"){let maybeMessage=error93.message;raw=typeof maybeMessage==="string"?maybeMessage:void 0}if(!raw)return;let trimmed=sanitizeFailureEvidenceDisplay(raw).trim();if(!trimmed)return;return trimmed.length>MAX_TOOL_FAILURE_REASON_LENGTH?`${trimmed.slice(0,MAX_TOOL_FAILURE_REASON_LENGTH)}...`:trimmed}function recordFailureReason(aggregate,reason){if(!aggregate.failureReasons)aggregate.failureReasons=[];if(aggregate.failureReasons.includes(reason))return;if(aggregate.failureReasons.length>=MAX_TOOL_FAILURE_REASONS)return;aggregate.failureReasons.push(reason)}function createAgentActivityHooks(config3,directory){if(config3.hooks?.agent_activity===!1)return{toolBefore:async()=>{},toolAfter:async()=>{}};return{toolBefore:async(input)=>{swarmState.activeToolCalls.set(input.callID,{tool:input.tool,sessionID:input.sessionID,callID:input.callID,startTime:Date.now()})},toolAfter:async(input,output)=>{let entry=swarmState.activeToolCalls.get(input.callID);if(!entry)return;swarmState.activeToolCalls.delete(input.callID);let duration5=Date.now()-entry.startTime,success3=!((typeof output.success==="boolean"?output.success:void 0)===!1||!!output.error),key2=entry.tool,existing=swarmState.toolAggregates.get(key2)??{tool:key2,count:0,successCount:0,failureCount:0,totalDuration:0};if(existing.count++,success3)existing.successCount++;else{existing.failureCount++;let reason=extractFailureReason(output.error);if(reason)recordFailureReason(existing,reason)}if(existing.totalDuration+=duration5,swarmState.toolAggregates.set(key2,existing),recordRealtimeLearningToolCall(entry.sessionID),swarmState.pendingEvents++,swarmState.pendingEvents>=20)flushActivityToFile(directory).catch((err)=>warn("Agent activity flush trigger failed:",err))}}}var flushPromise=null;async function flushActivityToFile(directory){if(flushPromise)return flushPromise=flushPromise.then(()=>doFlush(directory)).catch((err)=>{warn("Queued agent activity flush failed:",err)}),flushPromise;flushPromise=doFlush(directory);try{await flushPromise}finally{flushPromise=null}}async function doFlush(directory){try{let existing=await readSwarmFileAsync(directory,"context.md")??"",activitySection=renderActivitySection(),updated=replaceOrAppendSection(existing,"## Agent Activity",activitySection),flushedCount=swarmState.pendingEvents,path296=nodePath.join(directory,".swarm","context.md");await atomicWriteFile(path296,updated),swarmState.pendingEvents=Math.max(0,swarmState.pendingEvents-flushedCount)}catch(error93){warn("Agent activity flush failed:",error93)}}function renderActivitySection(){let lines=["## Agent Activity",""];if(swarmState.toolAggregates.size===0)return lines.push("No tool activity recorded yet."),lines.join(`
|
|
7186
7186
|
`);lines.push("| Tool | Calls | Success | Failed | Avg Duration |"),lines.push("|------|-------|---------|--------|--------------|");let sorted2=[...swarmState.toolAggregates.values()].sort((a,b)=>b.count-a.count);for(let agg of sorted2){let avgDuration=agg.count>0?Math.round(agg.totalDuration/agg.count):0;lines.push(`| ${agg.tool} | ${agg.count} | ${agg.successCount} | ${agg.failureCount} | ${avgDuration}ms |`)}return lines.join(`
|
|
7187
7187
|
`)}function replaceOrAppendSection(content,heading,newSection){let headingIndex=content.indexOf(heading);if(headingIndex===-1)return`${content.trimEnd()}
|
|
7188
7188
|
|
|
@@ -7422,9 +7422,11 @@ ${findingText}
|
|
|
7422
7422
|
Review before proceeding.`;injectSystemMessage(input.sessionID,message)}}}init_core_events();init_utils2();function createSteeringConsumedHook(directory){return safeHook(async()=>{try{let window2=readCoreEvents(directory);if(!window2.text.trim())return;let lines=window2.text.trim().split(`
|
|
7423
7423
|
`),directiveIds=new Set,consumedIds=new Set;for(let line of lines){if(!line.trim())continue;try{let parsed=JSON.parse(line);if(parsed.type==="steering-directive"&&parsed.directiveId)directiveIds.add(parsed.directiveId);else if(parsed.type==="steering-consumed"&&parsed.directiveId)consumedIds.add(parsed.directiveId)}catch{}}let unconsumed=[...directiveIds].filter((id)=>!consumedIds.has(id));if(unconsumed.length>0)appendCoreEventsSync(directory,unconsumed.map((directiveId)=>({type:"steering-consumed",directiveId,timestamp:new Date().toISOString()})),{ensureSwarmDir:!1})}catch{}})}init_system_guidance_carrier();init_logger();var CACHE_CAPABLE_PROVIDER_PREFIXES=["anthropic"],STRICT_FAMILY_PATTERN=/(?:^|[^a-z0-9])(?:qwen|gemma)/i;function readModelStringField(model,key2){if(typeof model!=="object"||model===null)return"";let value=model[key2];return typeof value==="string"?value:""}function resolveSystemRenderCapability(model){let providerID=readModelStringField(model,"providerID").toLowerCase();if(CACHE_CAPABLE_PROVIDER_PREFIXES.some((prefix)=>providerID.startsWith(prefix)))return"multi-system";let modelID=readModelStringField(model,"id");if(modelID.length>0&&STRICT_FAMILY_PATTERN.test(modelID))return"strict-single-system";return"multi-system"}function applySystemRenderBoundary(model,system){let capability=resolveSystemRenderCapability(model);if(!Array.isArray(system))return{capability,entriesBefore:-1,entriesAfter:-1,collapsed:!1};let entriesBefore=system.length;if(capability!=="strict-single-system"||entriesBefore<=1)return{capability,entriesBefore,entriesAfter:entriesBefore,collapsed:!1};let nonEmpty2=system.filter((entry)=>typeof entry==="string"&&entry.length>0);if(nonEmpty2.length===0)return{capability,entriesBefore,entriesAfter:entriesBefore,collapsed:!1};let joined=nonEmpty2.join(`
|
|
7424
7424
|
|
|
7425
|
-
`);return system.length=0,system.push(joined),{capability,entriesBefore,entriesAfter:1,collapsed:!0}}function createSystemRenderBoundaryHook(){return{"experimental.chat.system.transform":async(input,output)=>{try{let model=typeof input==="object"&&input!==null?input.model:void 0,system=typeof output==="object"&&output!==null?output.system:void 0;if(model===void 0||model===null){log("[system-render-boundary] no model on input; leaving system surface untouched (multi-system)");return}if(!Array.isArray(system))return;let result=applySystemRenderBoundary(model,system);if(result.collapsed)log(`[system-render-boundary] strict-single-system collapse: ${result.entriesBefore} -> 1 entry (${joinedByteLength(system)} bytes)`)}catch(error93){log(`[system-render-boundary] fail-open, system surface untouched: ${error93 instanceof Error?error93.message:String(error93)}`)}}}}function joinedByteLength(system){return system[0]?.length??0}init_trajectory_logger();init_utils2();init_utils();init_timeout();var V2_MODEL_APPLY_TIMEOUT_MS=1e4,registeredTransform,MAX_HELD_APPLY_REGISTRATIONS=128,registrationsByAgent=new Map;function registerV2AgentTransformSurface(ctx){let transform3=ctx?.agent&&typeof ctx.agent.transform==="function"?ctx.agent.transform.bind(ctx.agent):void 0;if(registeredTransform=transform3,transform3===void 0)log("v2 agent transform surface absent; runtime model apply disabled",{})}function clearV2AgentTransformSurface(){registeredTransform=void 0;let held=[...registrationsByAgent.values()];registrationsByAgent.clear();for(let reg of held)reg.dispose().catch((err)=>{log("v2 model-apply registration dispose failed (non-fatal)",{error:err instanceof Error?err.message:String(err)})})}async function applyV2AgentModelOverride(agentName,modelString){let transform3=registeredTransform;if(transform3===void 0)return!1;let separator=modelString.indexOf("/");if(typeof agentName!=="string"||agentName.length===0||separator<=0||separator===modelString.length-1)return log("v2 model apply rejected malformed input (non-fatal)",{agentName,modelString}),!1;let providerID=modelString.slice(0,separator),id=modelString.slice(separator+1);try{let applied2=await withTimeout(Promise.resolve(transform3((editor)=>{editor.update(agentName,(agent)=>{agent.model={providerID,id}})})),V2_MODEL_APPLY_TIMEOUT_MS,Error(`[opencode-swarm] v2: model apply for ${agentName} exceeded budget`)),previous=registrationsByAgent.get(agentName);registrationsByAgent.set(agentName,applied2);while(registrationsByAgent.size>MAX_HELD_APPLY_REGISTRATIONS){let oldest=registrationsByAgent.keys().next().value;if(typeof oldest!=="string")break;let evicted=registrationsByAgent.get(oldest);registrationsByAgent.delete(oldest),evicted?.dispose().catch((err)=>{log("v2 evicted model-apply registration dispose failed (non-fatal)",{agentName:oldest,error:err instanceof Error?err.message:String(err)})})}if(previous)previous.dispose().catch((err)=>{log("v2 previous model-apply registration dispose failed (non-fatal)",{agentName,error:err instanceof Error?err.message:String(err)})});return log("v2 agent model applied",{agentName,modelString}),!0}catch(err){return log("v2 agent model apply failed (non-fatal)",{agentName,modelString,error:err instanceof Error?err.message:String(err)}),!1}}init_zod();init_loader();init_model_preflight();init_warning_buffer();init_state();init_utils();init_project_boundary();init_timeout();init_utils();init_timeout();var V2_REGISTRATION_TIMEOUT_MS=60000;function mapV1AgentToV2(name,config3){let info={id:name,name,mode:config3.mode==="primary"||config3.mode==="subagent"||config3.mode==="all"?config3.mode:"subagent",hidden:!1,request:{settings:{},headers:{},body:{}}};if(typeof config3.prompt==="string"&&config3.prompt.length>0)info.system=config3.prompt;if(typeof config3.description==="string"&&config3.description.length>0)info.description=config3.description;if(typeof config3.model==="string"&&config3.model.includes("/")){let separator=config3.model.indexOf("/");info.model={providerID:config3.model.slice(0,separator),id:config3.model.slice(separator+1)}}let rules=[];if(Array.isArray(config3.tools)){for(let tool3 of config3.tools)if(typeof tool3==="string"&&tool3.length>0)rules.push({action:"tool",resource:tool3,effect:"allow"})}else if(config3.tools&&typeof config3.tools==="object")for(let[tool3,enabled]of Object.entries(config3.tools)){if(enabled===!1)continue;if(tool3.length>0)rules.push({action:"tool",resource:tool3,effect:"allow"})}if(rules.length>0)info.permissions=rules;return info}function expandV1Template(template,argumentsText){return template.replaceAll("$ARGUMENTS",argumentsText).trim()}async function registerV2AgentsAndCommands(ctx,hooks2,directory,registrations){if(typeof hooks2.config!=="function")return;let syntheticConfig={};await withTimeout(Promise.resolve(hooks2.config(syntheticConfig)),V2_REGISTRATION_TIMEOUT_MS,Error("[opencode-swarm] v2: synthetic config-hook run exceeded budget"));let agentTable=syntheticConfig.agent??{},commandTable=syntheticConfig.command??{},agentRegistration=await withTimeout(ctx.agent.transform((editor)=>{for(let[name,config3]of Object.entries(agentTable)){if(!config3||typeof config3!=="object")continue;if(config3.disable===!0){editor.remove(name);continue}let mapped=mapV1AgentToV2(name,config3);editor.update(name,(agent)=>{Object.assign(agent,mapped)})}}),V2_REGISTRATION_TIMEOUT_MS,Error("[opencode-swarm] v2: agent transform exceeded budget"));registrations.push(agentRegistration);let commandRegistration=await withTimeout(ctx.command.transform((editor)=>{for(let[key2,entry]of Object.entries(commandTable)){if(!entry||typeof entry!=="object")continue;let template=typeof entry.template==="string"?entry.template:void 0;if(template===void 0)continue;let definition={name:key2,description:typeof entry.description==="string"?entry.description:void 0,execute:async(invocation)=>{let text=expandV1Template(template,invocation?.prompt?.text??""),prompt=ctx.session?.prompt;if(typeof prompt!=="function"){log("v2 command executed without a session prompt surface",{name:key2});return}await withTimeout(Promise.resolve(prompt({sessionID:invocation.sessionID,text})),V2_REGISTRATION_TIMEOUT_MS,Error(`[opencode-swarm] v2: command ${key2} prompt exceeded budget`))}};editor.add(definition)}}),V2_REGISTRATION_TIMEOUT_MS,Error("[opencode-swarm] v2: command transform exceeded budget"));registrations.push(commandRegistration),log("v2 agents + commands registered",{directory,agents:Object.keys(agentTable).length,commands:Object.keys(commandTable).length})}init_task_model_routing();init_utils();init_timeout();var V2_EVENT_BATCH_TIMEOUT_MS=60000,UNMAPPED_LOG_LIMIT=20;function mapV2EventToV1(envelope){let type=typeof envelope?.type==="string"?envelope.type:void 0;if(type===void 0)return;let data=envelope.data??envelope.properties??{},sessionID=typeof data.sessionID==="string"?data.sessionID:void 0;switch(type){case"session.idle":case"session.status.updated":return{type:"session.idle",properties:{...sessionID?{sessionID}:{},...data}};case"session.status":return{type:"session.status",properties:{...sessionID?{sessionID}:{},...data}};case"session.error":case"session.execution.failed":return{type:"session.error",properties:{...sessionID?{sessionID}:{},...data}};case"session.deleted":return{type:"session.deleted",properties:{...sessionID?{sessionID}:{},...data}};case"session.created":return{type:"session.created",properties:{...sessionID?{sessionID}:{},...data}};case"session.text.delta":case"session.tool.called":case"session.tool.input.delta":return{type:"message.part.updated",properties:{...sessionID?{sessionID}:{},...data}};case"session.text.ended":case"session.tool.success":case"session.tool.failed":return{type:"message.updated",properties:{...sessionID?{sessionID}:{},...data}};default:return}}async function deferredDispatch(hooks2,mapped){let handler=hooks2.event;if(typeof handler!=="function")return;await withTimeout(Promise.resolve(handler({event:{type:mapped.type,properties:mapped.properties}})),V2_EVENT_BATCH_TIMEOUT_MS,Error("[opencode-swarm] v2: event dispatch exceeded budget")).catch((err)=>{log("v2 event dispatch failed (non-fatal)",{type:mapped.type,error:err instanceof Error?err.message:String(err)})})}function seedSessionIdentityFromEnvelope(envelope){let type=typeof envelope?.type==="string"?envelope.type:void 0;if(type!=="session.created"&&type!=="session.agent.selected")return;let payload=envelope.data??envelope.properties??{},sessionID=typeof payload.sessionID==="string"?payload.sessionID:void 0,agent=typeof payload.agent==="string"?payload.agent:void 0;if(sessionID&&agent)recordSessionChatAgent(sessionID,agent)}function startDeferredEventPump(ctx,hooks2){let stopped=!1,unmappedSeen=new Set;return(async()=>{try{let subscribe2=ctx?.event?.subscribe;if(typeof subscribe2!=="function"){log("v2 event subscribe surface absent; event pump idle (non-fatal)",{});return}let iterable=await withTimeout(Promise.resolve(subscribe2()),V2_EVENT_BATCH_TIMEOUT_MS,Error("[opencode-swarm] v2: event subscribe exceeded budget"));if(!iterable||typeof iterable[Symbol.asyncIterator]!=="function"){log("v2 event subscribe returned a non-iterable; event pump idle (non-fatal)",{});return}for await(let envelope of iterable){if(stopped)break;seedSessionIdentityFromEnvelope(envelope);let mapped=mapV2EventToV1(envelope);if(mapped===void 0){let t=typeof envelope?.type==="string"?envelope.type:"(no type)";if(!unmappedSeen.has(t)&&unmappedSeen.size<UNMAPPED_LOG_LIMIT)unmappedSeen.add(t),log("v2 event type not mapped (ignored)",{type:t});continue}await deferredDispatch(hooks2,mapped)}}catch(err){if(!stopped)log("v2 event pump stopped on error (non-fatal)",{error:err instanceof Error?err.message:String(err)})}})(),()=>{stopped=!0}}init_system_guidance_carrier();init_utils();init_timeout();var V2_GUIDANCE_CHAIN_TIMEOUT_MS=30000;function toV1MessageView(message,sessionID){let textParts=[];for(let part of message.content??[])if(part&&typeof part==="object"&&part.type==="text"&&typeof part.text==="string")textParts.push({type:"text",text:part.text});return{info:{id:typeof message.id==="string"?message.id:void 0,role:message.role,sessionID},parts:textParts}}function writeBackTextParts(message,parts){let kept=(message.content??[]).filter((part)=>!(part&&typeof part==="object"&&part.type==="text")),texts=parts.filter((p)=>p.type==="text"&&typeof p.text==="string").map((p)=>({type:"text",text:p.text}));message.content=[...kept,...texts]}function toV1ModelInput(model){if(model&&typeof model==="object")return{providerID:typeof model.providerID==="string"?model.providerID:"unknown",modelID:typeof model.id==="string"?model.id:"unknown"};return{providerID:"unknown",modelID:"unknown"}}async function onV2ContextEvent(event,hooks2,directory){let sessionID=event.sessionID;seedV1SessionState(sessionID,event.agent,directory);let messagesTransform=hooks2["experimental.chat.messages.transform"];if(typeof messagesTransform==="function"){let views=(event.messages??[]).map((m)=>toV1MessageView(m,sessionID)),originalMessages=[...event.messages??[]];await withTimeout(messagesTransform({},{messages:views}),V2_GUIDANCE_CHAIN_TIMEOUT_MS,Error("[opencode-swarm] v2: messages transform exceeded budget")).catch((err)=>{log("v2 messages transform failed (non-fatal; original messages retained)",{error:err instanceof Error?err.message:String(err)});for(let i=0;i<originalMessages.length;i+=1)views[i]=toV1MessageView(originalMessages[i],sessionID)});let originalById=new Map,originalsWithoutId=[];for(let message of originalMessages){let id=typeof message.id==="string"?message.id:void 0;if(id!==void 0&&id.length>0)originalById.set(id,message);else originalsWithoutId.push(message)}let usedIds=new Set,nextIdless=0,keptParts=[];event.system=event.system??[];for(let view of views){let id=view.info.id;if(typeof id==="string"&&id.startsWith(GUIDANCE_CARRIER_ID_PREFIX)){for(let part of view.parts)if(part.type==="text"&&typeof part.text==="string"&&part.text.length>0)event.system.push({type:"text",text:part.text});continue}let message;if(typeof id==="string"&&id.length>0&&originalById.has(id)&&!usedIds.has(id))message=originalById.get(id),usedIds.add(id);else if((id===void 0||id.length===0)&&nextIdless<originalsWithoutId.length)message=originalsWithoutId[nextIdless],nextIdless+=1;if(message)keptParts.push({message,parts:view.parts})}for(let{message,parts}of keptParts)writeBackTextParts(message,parts);event.messages.length=0,event.messages.push(...keptParts.map((k)=>k.message))}let systemTransform=hooks2["experimental.chat.system.transform"];if(typeof systemTransform==="function"){let output={system:[]};await withTimeout(systemTransform({sessionID,model:toV1ModelInput(event.model)},output),V2_GUIDANCE_CHAIN_TIMEOUT_MS,Error("[opencode-swarm] v2: system transform exceeded budget")).catch((err)=>{log("v2 system transform failed (non-fatal)",{error:err instanceof Error?err.message:String(err)})});for(let text of output.system)if(typeof text==="string"&&text.length>0)event.system.push({type:"text",text})}}async function registerV2ContextHook(ctx,hooks2,directory,registrations){let registration=await withTimeout(ctx.session.hook("context",async(event)=>{return onV2ContextEvent(event,hooks2,directory)}),V2_GUIDANCE_CHAIN_TIMEOUT_MS,Error("[opencode-swarm] v2: context hook registration exceeded budget"));registrations.push(registration)}init_normalize_tool_name();init_utils();init_timeout();var V2_HOOK_TIMEOUT_MS=60000;function isV2SubagentToolId(toolName){if(!toolName)return!1;if(toolName.includes("."))return/^tool\.[^.:]+\.subagent$/i.test(toolName);return normalizeToolNameLowerCase(toolName)==="subagent"}function isPlainObject9(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function mapV2SubagentArgsToV1(input){if(!isPlainObject9(input))return input;let mapped={};for(let[key2,value]of Object.entries(input))if(key2==="agent")mapped.subagent_type=value;else if(key2==="sessionID")mapped.task_id=value;else mapped[key2]=value;return mapped}function mapV1TaskArgsToV2(args2){if(!isPlainObject9(args2))return args2;let mapped={};for(let[key2,value]of Object.entries(args2))if(key2==="subagent_type")mapped.agent=value;else if(key2==="task_id")mapped.sessionID=value;else mapped[key2]=value;return mapped}var V2_SUBAGENT_WRAPPER_RE=/<subagent\s+sessionID="([^"]+)"\s+state="(running|completed|error|cancelled|canceled)"[^>]*>/,MAX_V2_WRAPPER_INNER_CHARS=20000;function parseV2SubagentWrapper(content){if(typeof content!=="string")return null;let match=content.match(V2_SUBAGENT_WRAPPER_RE);if(!match)return null;let sessionID=match[1];if(sessionID.includes("<")||sessionID.includes(">"))return null;let rawState=match[2],matchStart=match.index??0,inner=content.slice(matchStart+match[0].length).replace(/\s*<\/subagent>\s*$/,"");return{sessionID,state:rawState==="canceled"?"cancelled":rawState,inner}}var V2_WRAPPER_STRUCTURAL_TAG_RE=/<\/?(?:task_result|task_error|summary)>/g;function renderV1TaskEnvelopeFromV2(wrapper){let inner=wrapper.inner;if(inner.length>MAX_V2_WRAPPER_INNER_CHARS){let omitted=inner.length-MAX_V2_WRAPPER_INNER_CHARS;inner=`${inner.slice(0,MAX_V2_WRAPPER_INNER_CHARS)}
|
|
7425
|
+
`);return system.length=0,system.push(joined),{capability,entriesBefore,entriesAfter:1,collapsed:!0}}function createSystemRenderBoundaryHook(){return{"experimental.chat.system.transform":async(input,output)=>{try{let model=typeof input==="object"&&input!==null?input.model:void 0,system=typeof output==="object"&&output!==null?output.system:void 0;if(model===void 0||model===null){log("[system-render-boundary] no model on input; leaving system surface untouched (multi-system)");return}if(!Array.isArray(system))return;let result=applySystemRenderBoundary(model,system);if(result.collapsed)log(`[system-render-boundary] strict-single-system collapse: ${result.entriesBefore} -> 1 entry (${joinedByteLength(system)} bytes)`)}catch(error93){log(`[system-render-boundary] fail-open, system surface untouched: ${error93 instanceof Error?error93.message:String(error93)}`)}}}}function joinedByteLength(system){return system[0]?.length??0}init_trajectory_logger();init_utils2();init_utils();init_timeout();var V2_MODEL_APPLY_TIMEOUT_MS=1e4,registeredTransform,MAX_HELD_APPLY_REGISTRATIONS=128,registrationsByAgent=new Map;function registerV2AgentTransformSurface(ctx){let transform3=ctx?.agent&&typeof ctx.agent.transform==="function"?ctx.agent.transform.bind(ctx.agent):void 0;if(registeredTransform=transform3,transform3===void 0)log("v2 agent transform surface absent; runtime model apply disabled",{})}function clearV2AgentTransformSurface(){registeredTransform=void 0;let held=[...registrationsByAgent.values()];registrationsByAgent.clear();for(let reg of held)reg.dispose().catch((err)=>{log("v2 model-apply registration dispose failed (non-fatal)",{error:err instanceof Error?err.message:String(err)})})}async function applyV2AgentModelOverride(agentName,modelString){let transform3=registeredTransform;if(transform3===void 0)return!1;let separator=modelString.indexOf("/");if(typeof agentName!=="string"||agentName.length===0||separator<=0||separator===modelString.length-1)return log("v2 model apply rejected malformed input (non-fatal)",{agentName,modelString}),!1;let providerID=modelString.slice(0,separator),id=modelString.slice(separator+1);try{let applied2=await withTimeout(Promise.resolve(transform3((editor)=>{editor.update(agentName,(agent)=>{agent.model={providerID,id}})})),V2_MODEL_APPLY_TIMEOUT_MS,Error(`[opencode-swarm] v2: model apply for ${agentName} exceeded budget`)),previous=registrationsByAgent.get(agentName);registrationsByAgent.set(agentName,applied2);while(registrationsByAgent.size>MAX_HELD_APPLY_REGISTRATIONS){let oldest=registrationsByAgent.keys().next().value;if(typeof oldest!=="string")break;let evicted=registrationsByAgent.get(oldest);registrationsByAgent.delete(oldest),evicted?.dispose().catch((err)=>{log("v2 evicted model-apply registration dispose failed (non-fatal)",{agentName:oldest,error:err instanceof Error?err.message:String(err)})})}if(previous)previous.dispose().catch((err)=>{log("v2 previous model-apply registration dispose failed (non-fatal)",{agentName,error:err instanceof Error?err.message:String(err)})});return log("v2 agent model applied",{agentName,modelString}),!0}catch(err){return log("v2 agent model apply failed (non-fatal)",{agentName,modelString,error:err instanceof Error?err.message:String(err)}),!1}}init_zod();init_loader();init_model_preflight();init_warning_buffer();init_state();init_utils();init_project_boundary();init_timeout();init_utils();init_timeout();var V2_REGISTRATION_TIMEOUT_MS=60000;function mapV1AgentToV2(name,config3){let info={id:name,name,mode:config3.mode==="primary"||config3.mode==="subagent"||config3.mode==="all"?config3.mode:"subagent",hidden:!1,request:{settings:{},headers:{},body:{}}};if(typeof config3.prompt==="string"&&config3.prompt.length>0)info.system=config3.prompt;if(typeof config3.description==="string"&&config3.description.length>0)info.description=config3.description;if(typeof config3.model==="string"&&config3.model.includes("/")){let separator=config3.model.indexOf("/");info.model={providerID:config3.model.slice(0,separator),id:config3.model.slice(separator+1)}}let rules=[];if(Array.isArray(config3.tools)){for(let tool3 of config3.tools)if(typeof tool3==="string"&&tool3.length>0)rules.push({action:"tool",resource:tool3,effect:"allow"})}else if(config3.tools&&typeof config3.tools==="object")for(let[tool3,enabled]of Object.entries(config3.tools)){if(enabled===!1)continue;if(tool3.length>0)rules.push({action:"tool",resource:tool3,effect:"allow"})}if(rules.length>0)info.permissions=rules;return info}function expandV1Template(template,argumentsText){return template.replaceAll("$ARGUMENTS",argumentsText).trim()}async function registerV2AgentsAndCommands(ctx,hooks2,directory,registrations){if(typeof hooks2.config!=="function")return;let syntheticConfig={};await withTimeout(Promise.resolve(hooks2.config(syntheticConfig)),V2_REGISTRATION_TIMEOUT_MS,Error("[opencode-swarm] v2: synthetic config-hook run exceeded budget"));let agentTable=syntheticConfig.agent??{},commandTable=syntheticConfig.command??{},agentRegistration=await withTimeout(ctx.agent.transform((editor)=>{for(let[name,config3]of Object.entries(agentTable)){if(!config3||typeof config3!=="object")continue;if(config3.disable===!0){editor.remove(name);continue}let mapped=mapV1AgentToV2(name,config3);editor.update(name,(agent)=>{Object.assign(agent,mapped)})}}),V2_REGISTRATION_TIMEOUT_MS,Error("[opencode-swarm] v2: agent transform exceeded budget"));registrations.push(agentRegistration);let commandRegistration=await withTimeout(ctx.command.transform((editor)=>{for(let[key2,entry]of Object.entries(commandTable)){if(!entry||typeof entry!=="object")continue;let template=typeof entry.template==="string"?entry.template:void 0;if(template===void 0)continue;let definition={name:key2,description:typeof entry.description==="string"?entry.description:void 0,execute:async(invocation)=>{let text=expandV1Template(template,invocation?.prompt?.text??""),prompt=ctx.session?.prompt;if(typeof prompt!=="function"){log("v2 command executed without a session prompt surface",{name:key2});return}await withTimeout(Promise.resolve(prompt({sessionID:invocation.sessionID,text})),V2_REGISTRATION_TIMEOUT_MS,Error(`[opencode-swarm] v2: command ${key2} prompt exceeded budget`))}};editor.add(definition)}}),V2_REGISTRATION_TIMEOUT_MS,Error("[opencode-swarm] v2: command transform exceeded budget"));registrations.push(commandRegistration),log("v2 agents + commands registered",{directory,agents:Object.keys(agentTable).length,commands:Object.keys(commandTable).length})}init_task_model_routing();init_utils();init_timeout();init_canonical_root();init_logger();var SYSTEM_DIRECTIVE_FENCE_OPEN="<swarm_system_directive",MAX_PLACEHOLDER_SESSIONS=64,MAX_RECORDED_SESSION_ERRORS=128,ERROR_RECHECK_ATTEMPTS=3,ERROR_RECHECK_DELAY_MS=50,SIGNAL_LESS_WAIT_CAP_MS=600000,placeholderSessions=new Map,sessionErrors=new Map,placeholderCounter=0;function rememberPlaceholder(id,record3){placeholderSessions.set(id,record3);while(placeholderSessions.size>MAX_PLACEHOLDER_SESSIONS){let oldest=placeholderSessions.keys().next().value;if(oldest===void 0)break;placeholderSessions.delete(oldest)}}function rememberSessionError(sessionId,error93){sessionErrors.set(sessionId,error93);while(sessionErrors.size>MAX_RECORDED_SESSION_ERRORS){let oldest=sessionErrors.keys().next().value;if(oldest===void 0)break;sessionErrors.delete(oldest)}}function recordV2SessionErrorFromEnvelope(envelope){let type=typeof envelope?.type==="string"?envelope.type:void 0;if(type!=="session.error"&&type!=="session.execution.failed")return;let payload=envelope.data??envelope.properties??{},sessionID=typeof payload.sessionID==="string"?payload.sessionID:void 0,error93=payload.error;if(sessionID!==void 0&&error93!==void 0)rememberSessionError(sessionID,error93)}function clearV2SessionClientState(){placeholderSessions.clear(),sessionErrors.clear()}function readOnlyToolsToV2Permissions(tools){if(!tools||typeof tools!=="object")return[];let permissions=[];for(let resource of Object.keys(tools)){if(resource.length===0)continue;permissions.push({action:"tool",resource,effect:"deny"})}return permissions}function sameDirectoryLexical(a,b){return canonicalRootKeyLexical(a)===canonicalRootKeyLexical(b)}function isAssistantEntry(entry){if(!entry||typeof entry!=="object")return!1;let record3=entry;if(record3.role==="assistant")return!0;return typeof record3.type==="string"&&record3.type.includes("assistant")}function isUserEntry(entry){if(!entry||typeof entry!=="object")return!1;let record3=entry;if(record3.role==="user")return!0;return typeof record3.type==="string"&&record3.type.includes("user")}function entryText2(entry){if(!entry||typeof entry!=="object")return;let record3=entry;if(typeof record3.text==="string")return record3.text;let blocks=Array.isArray(record3.content)?record3.content:Array.isArray(record3.parts)?record3.parts:void 0;if(!blocks)return;let texts=[];for(let block of blocks)if(block&&typeof block==="object"&&block.type==="text"&&typeof block.text==="string")texts.push(block.text);return texts.length>0?texts.join(`
|
|
7426
|
+
`):void 0}function entryModelIds(entry){if(!entry||typeof entry!=="object")return{};let record3=entry,providerID=typeof record3.model?.providerID==="string"?record3.model.providerID:typeof record3.providerID==="string"?record3.providerID:void 0,modelID=typeof record3.model?.id==="string"?record3.model.id:typeof record3.modelID==="string"?record3.modelID:void 0;return{providerID,modelID}}function idleOutcome(entries2){for(let i=entries2.length-1;i>=0;i-=1){let entry=entries2[i];if(!entry||typeof entry!=="object")continue;let record3=entry;if(record3.type!=="idle")continue;return typeof record3.outcome==="string"?record3.outcome:void 0}return}function recordedErrorToInfoError(error93){if(error93&&typeof error93==="object"){let record3=error93,message=typeof record3.data?.message==="string"&&record3.data.message.length>0?record3.data.message:typeof record3.message==="string"&&record3.message.length>0?record3.message:"no message",statusCodeValue=typeof record3.data?.statusCode==="number"&&Number.isFinite(record3.data.statusCode)?record3.data.statusCode:typeof record3.statusCode==="number"&&Number.isFinite(record3.statusCode)?record3.statusCode:typeof record3.status==="number"&&Number.isFinite(record3.status)?record3.status:void 0;return{name:typeof record3.name==="string"&&record3.name.length>0?record3.name.slice(0,64):"ProviderError",data:{message,...statusCodeValue===void 0?{}:{statusCode:statusCodeValue}}}}return{name:"ProviderError",data:{message:"v2 session failed without recorded error detail"}}}function classifyContextEntries(entries2){let lastUserIndex=entries2.reduce((last,entry,index)=>isUserEntry(entry)?index:last,-1),assistantEntries=entries2.slice(lastUserIndex+1).filter(isAssistantEntry),texts=assistantEntries.map(entryText2).filter((text)=>typeof text==="string"),outcome=idleOutcome(entries2);return{outcome,texts,model:assistantEntries.reduce((acc,entry)=>{let ids=entryModelIds(entry);if(ids.providerID!==void 0&&ids.modelID!==void 0)return{providerID:ids.providerID,modelID:ids.modelID};return acc},{}),needsErrorLookup:outcome==="failed"||outcome===void 0&&texts.length===0}}function buildTranslatedPromptData(classification,recordedError){if(classification.needsErrorLookup||recordedError!==void 0)return{info:{error:recordedErrorToInfoError(recordedError)},parts:[]};return{info:classification.model,parts:classification.texts.map((text)=>({type:"text",text}))}}async function deferredV2SessionErrorRecheck(realId){for(let attempt=0;attempt<ERROR_RECHECK_ATTEMPTS;attempt+=1){if(sessionErrors.has(realId))return sessionErrors.get(realId);if(attempt<ERROR_RECHECK_ATTEMPTS-1)await new Promise((resolve121)=>setTimeout(resolve121,ERROR_RECHECK_DELAY_MS))}return}async function deferredV2SessionTranslate(entries2,sessionId){let classification=classifyContextEntries(entries2),recordedError=sessionErrors.get(sessionId);if(classification.needsErrorLookup&&recordedError===void 0)recordedError=await deferredV2SessionErrorRecheck(sessionId);return buildTranslatedPromptData(classification,recordedError)}async function deferredV2SessionGetParentDirectory(ctx,parentID){let info=await ctx.session.get({sessionID:parentID});if(!info||typeof info!=="object")return;let location=info.location;return typeof location?.directory==="string"?location.directory:void 0}async function deferredV2SessionWait(ctx,realId,signal2){if(signal2?.aborted)throw await ctx.session.interrupt({sessionID:realId}).catch(()=>{return}),Error("v2 session-client: prompt wait aborted");await new Promise((resolve121,reject3)=>{let settled=!1,timer=signal2===void 0?setTimeout(()=>{if(settled)return;settled=!0,ctx.session.interrupt({sessionID:realId}).catch(()=>{return}).finally(()=>{reject3(Error("v2 session-client: signal-less prompt wait exceeded cap"))})},SIGNAL_LESS_WAIT_CAP_MS):void 0,onAbort=()=>{if(settled)return;if(settled=!0,timer!==void 0)clearTimeout(timer);ctx.session.interrupt({sessionID:realId}).catch(()=>{return}).finally(()=>{reject3(Error("v2 session-client: prompt wait aborted"))})};signal2?.addEventListener("abort",onAbort,{once:!0}),Promise.resolve(ctx.session.wait({sessionID:realId})).then(()=>{if(settled)return;if(settled=!0,timer!==void 0)clearTimeout(timer);signal2?.removeEventListener("abort",onAbort),resolve121()}).catch((error93)=>{if(settled)return;if(settled=!0,timer!==void 0)clearTimeout(timer);signal2?.removeEventListener("abort",onAbort),reject3(error93 instanceof Error?error93:String(error93))})})}function makeV2SessionContextHandler(realId,system,tools){return(event)=>{let typed=event;if(!typed||typed.sessionID!==realId)return Promise.resolve();if(system!==void 0&&Array.isArray(typed.system)){let fenced=typed.system.filter((part)=>part&&typeof part.text==="string"&&part.text.includes(SYSTEM_DIRECTIVE_FENCE_OPEN));typed.system.length=0,typed.system.push(...fenced.map((part)=>({type:"text",text:part.text})),{type:"text",text:system})}if(tools&&typed.tools&&typeof typed.tools==="object"){let deleted=0;for(let name of Object.keys(tools))if(Object.hasOwn(typed.tools,name))delete typed.tools[name],deleted+=1;if(deleted>0)log("v2 session-client: denied tools via context hook",{count:deleted})}return Promise.resolve()}}function promptBodyText(parts){if(!Array.isArray(parts))return"";let texts=[];for(let part of parts)if(part&&typeof part==="object"&&part.type==="text"&&typeof part.text==="string")texts.push(part.text);return texts.join(`
|
|
7427
|
+
`)}async function deferredV2SessionPromptPlaceholder(ctx,_placeholderId,stash,body,text,signal2){if(stash.promptStarted=!0,signal2?.aborted)throw Error("v2 session-client: prompt wait aborted");let previousRealId=stash.realId;if(previousRealId!==void 0)stash.realId=void 0,stash.abortPending=!1,stash.deletePending=!1,await ctx.session.remove({sessionID:previousRealId}).catch(()=>{return});let agent=typeof body.agent==="string"?body.agent:void 0,model=body.model&&typeof body.model.providerID==="string"&&typeof body.model.modelID==="string"?{id:body.model.modelID,providerID:body.model.providerID}:void 0,system=typeof body.system==="string"?body.system:void 0,createdRecord=await ctx.session.create({...stash.parentID!==void 0?{parentID:stash.parentID}:{},...stash.title!==void 0?{title:stash.title}:{},...agent!==void 0?{agent}:{},...model!==void 0?{model}:{},location:{directory:stash.directory},permissions:readOnlyToolsToV2Permissions(body.tools)}),realId=typeof createdRecord?.id==="string"?createdRecord.id:void 0;if(realId===void 0)throw Error("v2 session-client: session create returned no id");let echoedDirectory=typeof createdRecord.location?.directory==="string"?createdRecord.location.directory:void 0;if(echoedDirectory!==void 0&&!sameDirectoryLexical(echoedDirectory,stash.directory))throw await ctx.session.remove({sessionID:realId}).catch(()=>{return}),Error(`v2 session-client: created session landed in ${echoedDirectory}, not the requested ${stash.directory} (#3169 Phase 0 C1)`);sessionErrors.delete(realId);let registration;try{if(system!==void 0||body.tools!==void 0)registration=await ctx.session.hook("context",makeV2SessionContextHandler(realId,system,body.tools));await ctx.session.prompt({sessionID:realId,text}),await deferredV2SessionWait(ctx,realId,signal2);let entries2=await ctx.session.context({sessionID:realId});return{data:await deferredV2SessionTranslate(Array.isArray(entries2)?entries2:[],realId)}}finally{if(stash.realId=realId,registration?.dispose)await registration.dispose().catch(()=>{return});if(stash.abortPending)await ctx.session.interrupt({sessionID:realId}).catch(()=>{return});if(stash.deletePending)sessionErrors.delete(realId),await ctx.session.remove({sessionID:realId}).catch(()=>{return})}}async function deferredV2SessionPromptReal(ctx,sessionId,body,text,signal2){if(typeof body.agent==="string"){let switchAgent=ctx.session.switchAgent;if(typeof switchAgent==="function")await switchAgent({sessionID:sessionId,agent:body.agent})}sessionErrors.delete(sessionId),await ctx.session.prompt({sessionID:sessionId,text}),await deferredV2SessionWait(ctx,sessionId,signal2);let entries2=await ctx.session.context({sessionID:sessionId});return{data:await deferredV2SessionTranslate(Array.isArray(entries2)?entries2:[],sessionId)}}function resolveSessionId(id){let stash=placeholderSessions.get(id);if(stash===void 0)return id;return stash.realId}function createV2SessionClient(ctx){let session=ctx?.session;if(!session||typeof session!=="object")return;for(let member of["create","get","remove","prompt","wait","context","interrupt","hook"])if(typeof session[member]!=="function")return;return{session:{create:(args2)=>deferredV2SessionCreate(ctx,args2),prompt:(args2)=>deferredV2SessionPrompt(ctx,args2),abort:(args2)=>{let id=args2?.path?.id,resolved=resolveSessionId(id);if(resolved!==void 0)return ctx.session.interrupt({sessionID:resolved}).catch(()=>{return});let stash=placeholderSessions.get(id);if(stash?.promptStarted)stash.abortPending=!0;return Promise.resolve(void 0)},delete:(args2)=>{let id=args2?.path?.id,resolved=resolveSessionId(id);if(resolved!==void 0)return sessionErrors.delete(resolved),ctx.session.remove({sessionID:resolved}).catch(()=>{return});let stash=placeholderSessions.get(id);if(stash?.promptStarted)stash.deletePending=!0;return Promise.resolve(void 0)},get:(args2)=>{let resolved=resolveSessionId(args2?.path?.id);if(resolved===void 0)return Promise.resolve({data:null});return ctx.session.get({sessionID:resolved}).then((info)=>({data:info})).catch((error93)=>({data:null,error:error93}))}}}}async function deferredV2SessionCreate(ctx,args2){let directory=args2?.query?.directory;if(typeof directory!=="string"||directory.length===0)return{data:null,error:{message:"v2 session-client: create requires query.directory (v1 contract)"}};let parentID=args2?.body?.parentID;if(parentID!==void 0){let parentDirectory=await deferredV2SessionGetParentDirectory(ctx,parentID).catch(()=>{return});if(parentDirectory===void 0)return{data:null,error:{message:"v2 session-client: parent session placement unverifiable (get returned no location.directory — live-verification item on #3169 Phase 2)"}};if(!sameDirectoryLexical(parentDirectory,directory))return{data:null,error:{message:`v2 session-client: child sessions inherit the parent directory (#3169 Phase 0 C1); requested ${directory} diverges from parent ${parentDirectory} — refusing to create`}}}placeholderCounter+=1;let placeholderId=`v2shim-${placeholderCounter}-${Math.random().toString(36).slice(2,10)}`;return rememberPlaceholder(placeholderId,{...parentID!==void 0?{parentID}:{},...args2?.body?.title!==void 0?{title:args2.body.title}:{},directory}),{data:{id:placeholderId}}}async function deferredV2SessionPrompt(ctx,args2){let id=args2?.path?.id;if(typeof id!=="string"||id.length===0)return{data:null,error:{message:"v2 session-client: prompt requires path.id"}};let body=args2?.body??{},text=promptBodyText(body.parts),stash=placeholderSessions.get(id);if(stash!==void 0)return deferredV2SessionPromptPlaceholder(ctx,id,stash,body,text,args2?.signal);return deferredV2SessionPromptReal(ctx,id,body,text,args2?.signal)}var V2_EVENT_BATCH_TIMEOUT_MS=60000,UNMAPPED_LOG_LIMIT=20;function mapV2EventToV1(envelope){let type=typeof envelope?.type==="string"?envelope.type:void 0;if(type===void 0)return;let data=envelope.data??envelope.properties??{},sessionID=typeof data.sessionID==="string"?data.sessionID:void 0;switch(type){case"session.idle":case"session.status.updated":return{type:"session.idle",properties:{...sessionID?{sessionID}:{},...data}};case"session.status":return{type:"session.status",properties:{...sessionID?{sessionID}:{},...data}};case"session.error":case"session.execution.failed":return{type:"session.error",properties:{...sessionID?{sessionID}:{},...data}};case"session.deleted":return{type:"session.deleted",properties:{...sessionID?{sessionID}:{},...data}};case"session.created":return{type:"session.created",properties:{...sessionID?{sessionID}:{},...data}};case"session.text.delta":case"session.tool.called":case"session.tool.input.delta":return{type:"message.part.updated",properties:{...sessionID?{sessionID}:{},...data}};case"session.text.ended":case"session.tool.success":case"session.tool.failed":return{type:"message.updated",properties:{...sessionID?{sessionID}:{},...data}};default:return}}async function deferredDispatch(hooks2,mapped){let handler=hooks2.event;if(typeof handler!=="function")return;await withTimeout(Promise.resolve(handler({event:{type:mapped.type,properties:mapped.properties}})),V2_EVENT_BATCH_TIMEOUT_MS,Error("[opencode-swarm] v2: event dispatch exceeded budget")).catch((err)=>{log("v2 event dispatch failed (non-fatal)",{type:mapped.type,error:err instanceof Error?err.message:String(err)})})}function seedSessionIdentityFromEnvelope(envelope){let type=typeof envelope?.type==="string"?envelope.type:void 0;if(type!=="session.created"&&type!=="session.agent.selected")return;let payload=envelope.data??envelope.properties??{},sessionID=typeof payload.sessionID==="string"?payload.sessionID:void 0,agent=typeof payload.agent==="string"?payload.agent:void 0;if(sessionID&&agent)recordSessionChatAgent(sessionID,agent)}function startDeferredEventPump(ctx,hooks2){let stopped=!1,unmappedSeen=new Set;return(async()=>{try{let subscribe2=ctx?.event?.subscribe;if(typeof subscribe2!=="function"){log("v2 event subscribe surface absent; event pump idle (non-fatal)",{});return}let iterable=await withTimeout(Promise.resolve(subscribe2()),V2_EVENT_BATCH_TIMEOUT_MS,Error("[opencode-swarm] v2: event subscribe exceeded budget"));if(!iterable||typeof iterable[Symbol.asyncIterator]!=="function"){log("v2 event subscribe returned a non-iterable; event pump idle (non-fatal)",{});return}for await(let envelope of iterable){if(stopped)break;seedSessionIdentityFromEnvelope(envelope),recordV2SessionErrorFromEnvelope(envelope);let mapped=mapV2EventToV1(envelope);if(mapped===void 0){let t=typeof envelope?.type==="string"?envelope.type:"(no type)";if(!unmappedSeen.has(t)&&unmappedSeen.size<UNMAPPED_LOG_LIMIT)unmappedSeen.add(t),log("v2 event type not mapped (ignored)",{type:t});continue}await deferredDispatch(hooks2,mapped)}}catch(err){if(!stopped)log("v2 event pump stopped on error (non-fatal)",{error:err instanceof Error?err.message:String(err)})}})(),()=>{stopped=!0}}init_system_guidance_carrier();init_utils();init_timeout();var V2_GUIDANCE_CHAIN_TIMEOUT_MS=30000;function toV1MessageView(message,sessionID){let textParts=[];for(let part of message.content??[])if(part&&typeof part==="object"&&part.type==="text"&&typeof part.text==="string")textParts.push({type:"text",text:part.text});return{info:{id:typeof message.id==="string"?message.id:void 0,role:message.role,sessionID},parts:textParts}}function writeBackTextParts(message,parts){let kept=(message.content??[]).filter((part)=>!(part&&typeof part==="object"&&part.type==="text")),texts=parts.filter((p)=>p.type==="text"&&typeof p.text==="string").map((p)=>({type:"text",text:p.text}));message.content=[...kept,...texts]}function toV1ModelInput(model){if(model&&typeof model==="object")return{providerID:typeof model.providerID==="string"?model.providerID:"unknown",modelID:typeof model.id==="string"?model.id:"unknown"};return{providerID:"unknown",modelID:"unknown"}}async function onV2ContextEvent(event,hooks2,directory){let sessionID=event.sessionID;seedV1SessionState(sessionID,event.agent,directory);let messagesTransform=hooks2["experimental.chat.messages.transform"];if(typeof messagesTransform==="function"){let views=(event.messages??[]).map((m)=>toV1MessageView(m,sessionID)),originalMessages=[...event.messages??[]];await withTimeout(messagesTransform({},{messages:views}),V2_GUIDANCE_CHAIN_TIMEOUT_MS,Error("[opencode-swarm] v2: messages transform exceeded budget")).catch((err)=>{log("v2 messages transform failed (non-fatal; original messages retained)",{error:err instanceof Error?err.message:String(err)});for(let i=0;i<originalMessages.length;i+=1)views[i]=toV1MessageView(originalMessages[i],sessionID)});let originalById=new Map,originalsWithoutId=[];for(let message of originalMessages){let id=typeof message.id==="string"?message.id:void 0;if(id!==void 0&&id.length>0)originalById.set(id,message);else originalsWithoutId.push(message)}let usedIds=new Set,nextIdless=0,keptParts=[];event.system=event.system??[];for(let view of views){let id=view.info.id;if(typeof id==="string"&&id.startsWith(GUIDANCE_CARRIER_ID_PREFIX)){for(let part of view.parts)if(part.type==="text"&&typeof part.text==="string"&&part.text.length>0)event.system.push({type:"text",text:part.text});continue}let message;if(typeof id==="string"&&id.length>0&&originalById.has(id)&&!usedIds.has(id))message=originalById.get(id),usedIds.add(id);else if((id===void 0||id.length===0)&&nextIdless<originalsWithoutId.length)message=originalsWithoutId[nextIdless],nextIdless+=1;if(message)keptParts.push({message,parts:view.parts})}for(let{message,parts}of keptParts)writeBackTextParts(message,parts);event.messages.length=0,event.messages.push(...keptParts.map((k)=>k.message))}let systemTransform=hooks2["experimental.chat.system.transform"];if(typeof systemTransform==="function"){let output={system:[]};await withTimeout(systemTransform({sessionID,model:toV1ModelInput(event.model)},output),V2_GUIDANCE_CHAIN_TIMEOUT_MS,Error("[opencode-swarm] v2: system transform exceeded budget")).catch((err)=>{log("v2 system transform failed (non-fatal)",{error:err instanceof Error?err.message:String(err)})});for(let text of output.system)if(typeof text==="string"&&text.length>0)event.system.push({type:"text",text})}}async function registerV2ContextHook(ctx,hooks2,directory,registrations){let registration=await withTimeout(ctx.session.hook("context",async(event)=>{return onV2ContextEvent(event,hooks2,directory)}),V2_GUIDANCE_CHAIN_TIMEOUT_MS,Error("[opencode-swarm] v2: context hook registration exceeded budget"));registrations.push(registration)}init_normalize_tool_name();init_utils();init_timeout();var V2_HOOK_TIMEOUT_MS=60000;function isV2SubagentToolId(toolName){if(!toolName)return!1;if(toolName.includes("."))return/^tool\.[^.:]+\.subagent$/i.test(toolName);return normalizeToolNameLowerCase(toolName)==="subagent"}function isPlainObject9(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function mapV2SubagentArgsToV1(input){if(!isPlainObject9(input))return input;let mapped={};for(let[key2,value]of Object.entries(input))if(key2==="agent")mapped.subagent_type=value;else if(key2==="sessionID")mapped.task_id=value;else mapped[key2]=value;return mapped}function mapV1TaskArgsToV2(args2){if(!isPlainObject9(args2))return args2;let mapped={};for(let[key2,value]of Object.entries(args2))if(key2==="subagent_type")mapped.agent=value;else if(key2==="task_id")mapped.sessionID=value;else mapped[key2]=value;return mapped}var V2_SUBAGENT_WRAPPER_RE=/<subagent\s+sessionID="([^"]+)"\s+state="(running|completed|error|cancelled|canceled)"[^>]*>/,MAX_V2_WRAPPER_INNER_CHARS=20000;function parseV2SubagentWrapper(content){if(typeof content!=="string")return null;let match=content.match(V2_SUBAGENT_WRAPPER_RE);if(!match)return null;let sessionID=match[1];if(sessionID.includes("<")||sessionID.includes(">"))return null;let rawState=match[2],matchStart=match.index??0,inner=content.slice(matchStart+match[0].length).replace(/\s*<\/subagent>\s*$/,"");return{sessionID,state:rawState==="canceled"?"cancelled":rawState,inner}}var V2_WRAPPER_STRUCTURAL_TAG_RE=/<\/?(?:task_result|task_error|summary)>/g;function renderV1TaskEnvelopeFromV2(wrapper){let inner=wrapper.inner;if(inner.length>MAX_V2_WRAPPER_INNER_CHARS){let omitted=inner.length-MAX_V2_WRAPPER_INNER_CHARS;inner=`${inner.slice(0,MAX_V2_WRAPPER_INNER_CHARS)}
|
|
7426
7428
|
[... ${omitted} chars truncated by v2 task translation ...]`}return inner=inner.replace(V2_WRAPPER_STRUCTURAL_TAG_RE,(tag)=>tag.replace("<","<\\")),`<task id="${wrapper.sessionID}" state="${wrapper.state}"><task_result>${inner}</task_result></task>`}async function onV2ToolBefore(event,hooks2,directory){let handler=hooks2["tool.execute.before"];if(typeof handler!=="function")return;seedV1SessionState(event.sessionID,event.agent,directory);let isSubagent2=isV2SubagentToolId(event.tool),output={args:isSubagent2?mapV2SubagentArgsToV1(event.input):event.input};if(await withTimeout(Promise.resolve(handler({tool:isSubagent2?"task":event.tool,sessionID:event.sessionID,callID:event.id,agent:normalizeV2AgentRef(event.agent),messageID:event.messageID},output)),V2_HOOK_TIMEOUT_MS,Error("[opencode-swarm] v2: tool.execute.before exceeded budget")),isSubagent2){let mapped=mapV1TaskArgsToV2(output.args);if(isPlainObject9(event.input)&&isPlainObject9(mapped)){for(let key2 of Object.keys(event.input))delete event.input[key2];Object.assign(event.input,mapped)}}else event.input=output.args}async function onV2ToolAfter(event,hooks2,directory){let handler=hooks2["tool.execute.after"];if(typeof handler!=="function")return;seedV1SessionState(event.sessionID,event.agent,directory);let isSubagent2=isV2SubagentToolId(event.tool),output=translateV2ResultToV1Output(event,isSubagent2);await withTimeout(Promise.resolve(handler({tool:isSubagent2?"task":event.tool,sessionID:event.sessionID,callID:event.id,agent:normalizeV2AgentRef(event.agent),messageID:event.messageID,...isSubagent2?{args:mapV2SubagentArgsToV1(event.input)}:{}},output)),V2_HOOK_TIMEOUT_MS,Error("[opencode-swarm] v2: tool.execute.after exceeded budget")).catch((err)=>{log("v2 tool.execute.after failed (non-fatal)",{tool:event.tool,error:err instanceof Error?err.message:String(err)})})}function translateV2ResultToV1Output(event,isSubagent2){if(event.status==="error")return{title:"error",state:"error",output:event.error&&typeof event.error.message==="string"?event.error.message:"tool error",metadata:{}};let result=event.result,content=typeof result?.content==="string"?result.content:Array.isArray(result?.content)?(result?.content).filter((p)=>p.type==="text"&&typeof p.text==="string").map((p)=>p.text).join(`
|
|
7427
|
-
`):"";if(isSubagent2){let wrapper=parseV2SubagentWrapper(content);if(wrapper)return{title:"",state:wrapper.state==="running"?"running":wrapper.state==="completed"?"completed":wrapper.state==="error"?"error":"cancelled",output:renderV1TaskEnvelopeFromV2(wrapper),metadata:result?.metadata??{}};if(content.includes("<subagent"))log("v2 subagent wrapper not recognized; passing result text through",{chars:content.length})}return{title:"",state:"completed",output:content,metadata:result?.metadata??{}}}async function onV2Compaction(event,hooks2,directory){let handler=hooks2["experimental.session.compacting"];if(typeof handler!=="function")return;seedV1SessionState(event.sessionID,event.agent,directory);let model=event.model,output={};await withTimeout(Promise.resolve(handler({sessionID:event.sessionID,providerID:typeof model?.providerID==="string"?model.providerID:"unknown",modelID:typeof model?.id==="string"?model.id:"unknown"},output)),V2_HOOK_TIMEOUT_MS,Error("[opencode-swarm] v2: compaction hook exceeded budget")).catch((err)=>{log("v2 compaction hook failed (non-fatal)",{error:err instanceof Error?err.message:String(err)})})}async function onV2Prompt(event,hooks2){let handler=hooks2["chat.message"];if(typeof handler!=="function")return;let text=event.prompt?.text??"",message={id:event.messageID,role:"user",sessionID:event.sessionID},parts=[{type:"text",text}],input={sessionID:event.sessionID,message:{...message},parts:[...parts]},output={message:{...message},parts:[...parts]};if(await withTimeout(Promise.resolve(handler(input,output)),V2_HOOK_TIMEOUT_MS,Error("[opencode-swarm] v2: prompt hook exceeded budget")).catch((err)=>{log("v2 prompt (chat.message) hook failed (non-fatal)",{error:err instanceof Error?err.message:String(err)})}),typeof event.prompt==="object"&&event.prompt!==null){let rewritten=output.parts.find((p)=>p.type==="text"&&typeof p.text==="string");if(rewritten&&typeof rewritten.text==="string"&&rewritten.text!==text)event.prompt.text=rewritten.text}}async function registerV2ToolHooks(ctx,hooks2,directory,registrations){let before=await withTimeout(ctx.tool.hook("execute.before",async(event)=>{return onV2ToolBefore(event,hooks2,directory)}),V2_HOOK_TIMEOUT_MS,Error("[opencode-swarm] v2: execute.before registration exceeded budget"));registrations.push(before);let after=await withTimeout(ctx.tool.hook("execute.after",async(event)=>{return onV2ToolAfter(event,hooks2,directory)}),V2_HOOK_TIMEOUT_MS,Error("[opencode-swarm] v2: execute.after registration exceeded budget"));registrations.push(after)}async function registerV2SessionHooks(ctx,hooks2,directory,registrations){let compaction=await withTimeout(ctx.session.hook("compaction",async(event)=>{return onV2Compaction(event,hooks2,directory)}),V2_HOOK_TIMEOUT_MS,Error("[opencode-swarm] v2: compaction registration exceeded budget"));registrations.push(compaction);let prompt=await withTimeout(ctx.session.hook("prompt",async(event)=>{return onV2Prompt(event,hooks2)}),V2_HOOK_TIMEOUT_MS,Error("[opencode-swarm] v2: prompt registration exceeded budget"));registrations.push(prompt)}init_utils();init_timeout();var V2_TOOL_EXECUTE_TIMEOUT_MS=600000;function synthesizeV1ToolContext(context,projectRoot,permissionBridge){let agentName=normalizeV2AgentRef(context.agent)??"architect";return{sessionID:context.sessionID,messageID:context.messageID,agent:agentName,directory:projectRoot,worktree:projectRoot,abort:context.signal,metadata:(input)=>{try{let progress=context.progress;if(typeof progress==="function")progress({...input.metadata??{},...input.title!==void 0?{title:input.title}:{}})}catch{}},ask:async(input)=>{if(permissionBridge){await withTimeout(Promise.resolve(permissionBridge(input)),V2_TOOL_EXECUTE_TIMEOUT_MS,Error("[opencode-swarm] v2: permission bridge exceeded budget"));return}throw Error("[opencode-swarm] v2: interactive tool permission request unavailable (no permission surface); denying by default.")}}}function mapV1ToolResult(result){if(typeof result==="string")return{content:result};if(result&&typeof result==="object"){let rec=result;return{...typeof rec.output==="string"?{content:rec.output}:{},...rec.metadata&&typeof rec.metadata==="object"?{metadata:rec.metadata}:{}}}return{content:String(result??"")}}async function registerV2Tools(ctx,hooks2,projectRoot,registrations){let toolMap=hooks2.tool??{},permissionBridge=buildPermissionBridge(ctx),registration=await withTimeout(ctx.tool.transform((editor)=>{for(let[name,definition]of Object.entries(toolMap)){let v1Execute=definition.execute;if(typeof v1Execute!=="function")continue;let info={name,description:definition.description??"",input:v2ToolInputSchema(definition.args),execute:async(input,context)=>{seedV1SessionState(context.sessionID,context.agent,projectRoot);let result=await withTimeout(Promise.resolve(v1Execute(input,synthesizeV1ToolContext(context,projectRoot,permissionBridge))),V2_TOOL_EXECUTE_TIMEOUT_MS,Error(`[opencode-swarm] v2: tool ${name} exceeded execution budget`));return mapV1ToolResult(result)}};editor.add(info)}}),V2_TOOL_EXECUTE_TIMEOUT_MS,Error("[opencode-swarm] v2: tool transform exceeded budget"));registrations.push(registration)}function buildPermissionBridge(ctx){let permission=ctx.permission;if(!permission||typeof permission.reply!=="function")return;return async(input)=>{let askInput=input;log("v2 permission bridge invoked (best-effort passthrough)",{permission:typeof askInput?.permission==="string"?askInput.permission:"unknown",patternCount:Array.isArray(askInput?.patterns)?askInput.patterns.length:0}),await withTimeout(Promise.resolve(permission.reply?.(input)),V2_TOOL_EXECUTE_TIMEOUT_MS,Error("[opencode-swarm] v2: permission reply exceeded budget"))}}async function deferredV2StartupModelPreflight(directory){try{let loaded=await withTimeout(Promise.resolve(loadPluginConfigWithMeta(directory)),2000,Error("[opencode-swarm] v2: startup preflight config read exceeded budget")),models=collectEnabledAgentModels(loaded?.config).map((entry)=>entry.model).filter((model)=>typeof model==="string"&&model.length>0),quiet=loaded?.config?.quiet===!0;for(let warning of collectModelRosterWarnings(models,VERIFIED_KEYLESS_MODEL_ROSTER))if(addDeferredWarning(warning),!quiet)console.warn(warning)}catch(err){log("v2 startup model preflight failed (non-fatal)",{error:err instanceof Error?err.message:String(err)})}}var V2_SETUP_TIMEOUT_MS=60000;function normalizeV2AgentRef(agent){if(typeof agent==="string")return agent;if(agent&&typeof agent==="object"){let rec=agent;if(typeof rec.id==="string"&&rec.id.length>0)return rec.id;if(typeof rec.name==="string"&&rec.name.length>0)return rec.name}return}async function openCodeSwarmV2Setup(ctx,deps){let rawDirectory=ctx?.location?.directory;if(typeof rawDirectory!=="string"||rawDirectory.length===0)throw Error("[opencode-swarm] v2 setup: host Context carried no location.directory; refusing to start (invariant 4).");let rootDecision=resolveProjectRootDecision(rawDirectory),directory=rootDecision.kind==="redirect"?rootDecision.owningRoot:rootDecision.kind==="root"?rootDecision.directory:rawDirectory,state2={registrations:[]},input={client:void 0,directory,worktree:directory},hooks2=await withTimeout(deps.runInit(input),V2_SETUP_TIMEOUT_MS,Error("[opencode-swarm] v2 setup: initialization exceeded budget"));await withTimeout(registerV2AgentsAndCommands(ctx,hooks2,directory,state2.registrations),V2_SETUP_TIMEOUT_MS,Error("[opencode-swarm] v2 setup: agent/command registration exceeded budget")).catch((err)=>{log("v2 agent/command registration failed (non-fatal)",{error:err instanceof Error?err.message:String(err)})}),await withTimeout(registerV2Tools(ctx,hooks2,directory,state2.registrations),V2_SETUP_TIMEOUT_MS,Error("[opencode-swarm] v2 setup: tool registration exceeded budget")).catch((err)=>{log("v2 tool registration failed (non-fatal)",{error:err instanceof Error?err.message:String(err)})}),await withTimeout(registerV2ContextHook(ctx,hooks2,directory,state2.registrations),V2_SETUP_TIMEOUT_MS,Error("[opencode-swarm] v2 setup: guidance registration exceeded budget")).catch((err)=>{log("v2 context-hook registration failed (non-fatal)",{error:err instanceof Error?err.message:String(err)})}),await withTimeout(registerV2ToolHooks(ctx,hooks2,directory,state2.registrations),V2_SETUP_TIMEOUT_MS,Error("[opencode-swarm] v2 setup: tool-hook registration exceeded budget")).catch((err)=>{log("v2 tool-hook registration failed (non-fatal)",{error:err instanceof Error?err.message:String(err)})}),await withTimeout(registerV2SessionHooks(ctx,hooks2,directory,state2.registrations),V2_SETUP_TIMEOUT_MS,Error("[opencode-swarm] v2 setup: prompt-hook registration exceeded budget")).catch((err)=>{log("v2 prompt-hook registration failed (non-fatal)",{error:err instanceof Error?err.message:String(err)})});let stopPump=startDeferredEventPump(ctx,hooks2);return state2.pumpStop=stopPump,registerV2AgentTransformSurface(ctx),await withTimeout(deferredV2StartupModelPreflight(directory),V2_SETUP_TIMEOUT_MS,Error("[opencode-swarm] v2: startup model preflight exceeded budget")),state2.disposeV1=typeof hooks2.dispose==="function"?hooks2.dispose:void 0,log("[opencode-swarm] v2 setup complete",{directory,tools:Object.keys(hooks2.tool??{}).length}),async function(){if(typeof state2.pumpStop==="function")state2.pumpStop();clearV2AgentTransformSurface();for(let registration of state2.registrations)try{await withTimeout(registration.dispose(),V2_SETUP_TIMEOUT_MS,Error("[opencode-swarm] v2 cleanup: registration dispose exceeded budget"))}catch(err){log("v2 registration dispose failed (non-fatal)",{error:err instanceof Error?err.message:String(err)})}if(state2.disposeV1)await withTimeout(state2.disposeV1(),V2_SETUP_TIMEOUT_MS,Error("[opencode-swarm] v2 cleanup: v1 dispose exceeded budget")).catch((err)=>{log("v1 dispose during v2 cleanup failed (non-fatal)",{error:err instanceof Error?err.message:String(err)})})}}function seedV1SessionState(sessionID,agentRef,directory){if(typeof sessionID!=="string"||sessionID.length===0)return;let agentName=normalizeV2AgentRef(agentRef);if(agentName===void 0)return sessionID;try{ensureAgentSession(sessionID,agentName,directory)}catch{}return swarmState.activeAgent.set(sessionID,agentName),sessionID}function v2ToolInputSchema(args2){try{if(args2&&typeof args2==="object")return exports_external.toJSONSchema(exports_external.object(args2))}catch{}return{type:"object"}}init_manifest_files();init_p_limit();init_knowledge_curator();init_knowledge_reinforcement();init_knowledge_store();init_knowledge_validator();init_micro_reflector();init_logger();init_timeout();init_candidate_queue();init_provenance();var SCREENING_TOKEN_ESTIMATE=400,SCREENING_PROMPT_CAP=1200;function unionSourceKnowledgeIds(entry,ids){let next=entry.source_knowledge_ids;for(let id of ids)next=unionInsightMarker(next,id);entry.source_knowledge_ids=next??[]}function findActiveEntryWithMarker(entries2,marker){return entries2.find((entry)=>isActiveSwarmKnowledgeEntry(entry)&&(entry.source_knowledge_ids??[]).includes(marker))}function buildScreeningPrompt(candidate2){return["A subagent proposed this durable procedural lesson for the shared knowledge store.","Answer with exactly one word: ADMIT or REJECT.","REJECT when the lesson is task-specific trivia, a transient environment failure, or not generalizable.","",`LESSON: ${candidate2.lesson}`,`CATEGORY: ${candidate2.category}`,`SCOPE: agents=${(candidate2.applies_to_agents??[]).join(",")} tools=${(candidate2.applies_to_tools??[]).join(",")}`].join(`
|
|
7429
|
+
`):"";if(isSubagent2){let wrapper=parseV2SubagentWrapper(content);if(wrapper)return{title:"",state:wrapper.state==="running"?"running":wrapper.state==="completed"?"completed":wrapper.state==="error"?"error":"cancelled",output:renderV1TaskEnvelopeFromV2(wrapper),metadata:result?.metadata??{}};if(content.includes("<subagent"))log("v2 subagent wrapper not recognized; passing result text through",{chars:content.length})}return{title:"",state:"completed",output:content,metadata:result?.metadata??{}}}async function onV2Compaction(event,hooks2,directory){let handler=hooks2["experimental.session.compacting"];if(typeof handler!=="function")return;seedV1SessionState(event.sessionID,event.agent,directory);let model=event.model,output={};await withTimeout(Promise.resolve(handler({sessionID:event.sessionID,providerID:typeof model?.providerID==="string"?model.providerID:"unknown",modelID:typeof model?.id==="string"?model.id:"unknown"},output)),V2_HOOK_TIMEOUT_MS,Error("[opencode-swarm] v2: compaction hook exceeded budget")).catch((err)=>{log("v2 compaction hook failed (non-fatal)",{error:err instanceof Error?err.message:String(err)})})}async function onV2Prompt(event,hooks2){let handler=hooks2["chat.message"];if(typeof handler!=="function")return;let text=event.prompt?.text??"",message={id:event.messageID,role:"user",sessionID:event.sessionID},parts=[{type:"text",text}],input={sessionID:event.sessionID,message:{...message},parts:[...parts]},output={message:{...message},parts:[...parts]};if(await withTimeout(Promise.resolve(handler(input,output)),V2_HOOK_TIMEOUT_MS,Error("[opencode-swarm] v2: prompt hook exceeded budget")).catch((err)=>{log("v2 prompt (chat.message) hook failed (non-fatal)",{error:err instanceof Error?err.message:String(err)})}),typeof event.prompt==="object"&&event.prompt!==null){let rewritten=output.parts.find((p)=>p.type==="text"&&typeof p.text==="string");if(rewritten&&typeof rewritten.text==="string"&&rewritten.text!==text)event.prompt.text=rewritten.text}}async function registerV2ToolHooks(ctx,hooks2,directory,registrations){let before=await withTimeout(ctx.tool.hook("execute.before",async(event)=>{return onV2ToolBefore(event,hooks2,directory)}),V2_HOOK_TIMEOUT_MS,Error("[opencode-swarm] v2: execute.before registration exceeded budget"));registrations.push(before);let after=await withTimeout(ctx.tool.hook("execute.after",async(event)=>{return onV2ToolAfter(event,hooks2,directory)}),V2_HOOK_TIMEOUT_MS,Error("[opencode-swarm] v2: execute.after registration exceeded budget"));registrations.push(after)}async function registerV2SessionHooks(ctx,hooks2,directory,registrations){let compaction=await withTimeout(ctx.session.hook("compaction",async(event)=>{return onV2Compaction(event,hooks2,directory)}),V2_HOOK_TIMEOUT_MS,Error("[opencode-swarm] v2: compaction registration exceeded budget"));registrations.push(compaction);let prompt=await withTimeout(ctx.session.hook("prompt",async(event)=>{return onV2Prompt(event,hooks2)}),V2_HOOK_TIMEOUT_MS,Error("[opencode-swarm] v2: prompt registration exceeded budget"));registrations.push(prompt)}init_utils();init_timeout();var V2_TOOL_EXECUTE_TIMEOUT_MS=600000;function synthesizeV1ToolContext(context,projectRoot,permissionBridge){let agentName=normalizeV2AgentRef(context.agent)??"architect";return{sessionID:context.sessionID,messageID:context.messageID,agent:agentName,directory:projectRoot,worktree:projectRoot,abort:context.signal,metadata:(input)=>{try{let progress=context.progress;if(typeof progress==="function")progress({...input.metadata??{},...input.title!==void 0?{title:input.title}:{}})}catch{}},ask:async(input)=>{if(permissionBridge){await withTimeout(Promise.resolve(permissionBridge(input)),V2_TOOL_EXECUTE_TIMEOUT_MS,Error("[opencode-swarm] v2: permission bridge exceeded budget"));return}throw Error("[opencode-swarm] v2: interactive tool permission request unavailable (no permission surface); denying by default.")}}}function mapV1ToolResult(result){if(typeof result==="string")return{content:result};if(result&&typeof result==="object"){let rec=result;return{...typeof rec.output==="string"?{content:rec.output}:{},...rec.metadata&&typeof rec.metadata==="object"?{metadata:rec.metadata}:{}}}return{content:String(result??"")}}async function registerV2Tools(ctx,hooks2,projectRoot,registrations){let toolMap=hooks2.tool??{},permissionBridge=buildPermissionBridge(ctx),registration=await withTimeout(ctx.tool.transform((editor)=>{for(let[name,definition]of Object.entries(toolMap)){let v1Execute=definition.execute;if(typeof v1Execute!=="function")continue;let info={name,description:definition.description??"",input:v2ToolInputSchema(definition.args),execute:async(input,context)=>{seedV1SessionState(context.sessionID,context.agent,projectRoot);let result=await withTimeout(Promise.resolve(v1Execute(input,synthesizeV1ToolContext(context,projectRoot,permissionBridge))),V2_TOOL_EXECUTE_TIMEOUT_MS,Error(`[opencode-swarm] v2: tool ${name} exceeded execution budget`));return mapV1ToolResult(result)}};editor.add(info)}}),V2_TOOL_EXECUTE_TIMEOUT_MS,Error("[opencode-swarm] v2: tool transform exceeded budget"));registrations.push(registration)}function buildPermissionBridge(ctx){let permission=ctx.permission;if(!permission||typeof permission.reply!=="function")return;return async(input)=>{let askInput=input;log("v2 permission bridge invoked (best-effort passthrough)",{permission:typeof askInput?.permission==="string"?askInput.permission:"unknown",patternCount:Array.isArray(askInput?.patterns)?askInput.patterns.length:0}),await withTimeout(Promise.resolve(permission.reply?.(input)),V2_TOOL_EXECUTE_TIMEOUT_MS,Error("[opencode-swarm] v2: permission reply exceeded budget"))}}async function deferredV2StartupModelPreflight(directory){try{let loaded=await withTimeout(Promise.resolve(loadPluginConfigWithMeta(directory)),2000,Error("[opencode-swarm] v2: startup preflight config read exceeded budget")),models=collectEnabledAgentModels(loaded?.config).map((entry)=>entry.model).filter((model)=>typeof model==="string"&&model.length>0),quiet=loaded?.config?.quiet===!0;for(let warning of collectModelRosterWarnings(models,VERIFIED_KEYLESS_MODEL_ROSTER))if(addDeferredWarning(warning),!quiet)console.warn(warning)}catch(err){log("v2 startup model preflight failed (non-fatal)",{error:err instanceof Error?err.message:String(err)})}}var V2_SETUP_TIMEOUT_MS=60000;function normalizeV2AgentRef(agent){if(typeof agent==="string")return agent;if(agent&&typeof agent==="object"){let rec=agent;if(typeof rec.id==="string"&&rec.id.length>0)return rec.id;if(typeof rec.name==="string"&&rec.name.length>0)return rec.name}return}async function openCodeSwarmV2Setup(ctx,deps){let rawDirectory=ctx?.location?.directory;if(typeof rawDirectory!=="string"||rawDirectory.length===0)throw Error("[opencode-swarm] v2 setup: host Context carried no location.directory; refusing to start (invariant 4).");let rootDecision=resolveProjectRootDecision(rawDirectory),directory=rootDecision.kind==="redirect"?rootDecision.owningRoot:rootDecision.kind==="root"?rootDecision.directory:rawDirectory,state2={registrations:[]},input={client:createV2SessionClient(ctx),directory,worktree:directory},hooks2=await withTimeout(deps.runInit(input),V2_SETUP_TIMEOUT_MS,Error("[opencode-swarm] v2 setup: initialization exceeded budget"));await withTimeout(registerV2AgentsAndCommands(ctx,hooks2,directory,state2.registrations),V2_SETUP_TIMEOUT_MS,Error("[opencode-swarm] v2 setup: agent/command registration exceeded budget")).catch((err)=>{log("v2 agent/command registration failed (non-fatal)",{error:err instanceof Error?err.message:String(err)})}),await withTimeout(registerV2Tools(ctx,hooks2,directory,state2.registrations),V2_SETUP_TIMEOUT_MS,Error("[opencode-swarm] v2 setup: tool registration exceeded budget")).catch((err)=>{log("v2 tool registration failed (non-fatal)",{error:err instanceof Error?err.message:String(err)})}),await withTimeout(registerV2ContextHook(ctx,hooks2,directory,state2.registrations),V2_SETUP_TIMEOUT_MS,Error("[opencode-swarm] v2 setup: guidance registration exceeded budget")).catch((err)=>{log("v2 context-hook registration failed (non-fatal)",{error:err instanceof Error?err.message:String(err)})}),await withTimeout(registerV2ToolHooks(ctx,hooks2,directory,state2.registrations),V2_SETUP_TIMEOUT_MS,Error("[opencode-swarm] v2 setup: tool-hook registration exceeded budget")).catch((err)=>{log("v2 tool-hook registration failed (non-fatal)",{error:err instanceof Error?err.message:String(err)})}),await withTimeout(registerV2SessionHooks(ctx,hooks2,directory,state2.registrations),V2_SETUP_TIMEOUT_MS,Error("[opencode-swarm] v2 setup: prompt-hook registration exceeded budget")).catch((err)=>{log("v2 prompt-hook registration failed (non-fatal)",{error:err instanceof Error?err.message:String(err)})});let stopPump=startDeferredEventPump(ctx,hooks2);return state2.pumpStop=stopPump,registerV2AgentTransformSurface(ctx),await withTimeout(deferredV2StartupModelPreflight(directory),V2_SETUP_TIMEOUT_MS,Error("[opencode-swarm] v2: startup model preflight exceeded budget")),state2.disposeV1=typeof hooks2.dispose==="function"?hooks2.dispose:void 0,log("[opencode-swarm] v2 setup complete",{directory,tools:Object.keys(hooks2.tool??{}).length}),async function(){if(typeof state2.pumpStop==="function")state2.pumpStop();clearV2SessionClientState(),clearV2AgentTransformSurface();for(let registration of state2.registrations)try{await withTimeout(registration.dispose(),V2_SETUP_TIMEOUT_MS,Error("[opencode-swarm] v2 cleanup: registration dispose exceeded budget"))}catch(err){log("v2 registration dispose failed (non-fatal)",{error:err instanceof Error?err.message:String(err)})}if(state2.disposeV1)await withTimeout(state2.disposeV1(),V2_SETUP_TIMEOUT_MS,Error("[opencode-swarm] v2 cleanup: v1 dispose exceeded budget")).catch((err)=>{log("v1 dispose during v2 cleanup failed (non-fatal)",{error:err instanceof Error?err.message:String(err)})})}}function seedV1SessionState(sessionID,agentRef,directory){if(typeof sessionID!=="string"||sessionID.length===0)return;let agentName=normalizeV2AgentRef(agentRef);if(agentName===void 0)return sessionID;try{ensureAgentSession(sessionID,agentName,directory)}catch{}return swarmState.activeAgent.set(sessionID,agentName),sessionID}function v2ToolInputSchema(args2){try{if(args2&&typeof args2==="object")return exports_external.toJSONSchema(exports_external.object(args2))}catch{}return{type:"object"}}init_manifest_files();init_p_limit();init_knowledge_curator();init_knowledge_reinforcement();init_knowledge_store();init_knowledge_validator();init_micro_reflector();init_logger();init_timeout();init_candidate_queue();init_provenance();var SCREENING_TOKEN_ESTIMATE=400,SCREENING_PROMPT_CAP=1200;function unionSourceKnowledgeIds(entry,ids){let next=entry.source_knowledge_ids;for(let id of ids)next=unionInsightMarker(next,id);entry.source_knowledge_ids=next??[]}function findActiveEntryWithMarker(entries2,marker){return entries2.find((entry)=>isActiveSwarmKnowledgeEntry(entry)&&(entry.source_knowledge_ids??[]).includes(marker))}function buildScreeningPrompt(candidate2){return["A subagent proposed this durable procedural lesson for the shared knowledge store.","Answer with exactly one word: ADMIT or REJECT.","REJECT when the lesson is task-specific trivia, a transient environment failure, or not generalizable.","",`LESSON: ${candidate2.lesson}`,`CATEGORY: ${candidate2.category}`,`SCOPE: agents=${(candidate2.applies_to_agents??[]).join(",")} tools=${(candidate2.applies_to_tools??[]).join(",")}`].join(`
|
|
7428
7430
|
`).slice(0,SCREENING_PROMPT_CAP)}async function screenCandidate(candidate2,deps){let perCandidateMs=deps.llmTimeoutMs??0;if(!deps.llmDelegate||perCandidateMs<=0||!deps.sessionID)return!0;let llmDelegate=deps.llmDelegate;if(!deps.llmBudget)return!0;let remainingMs2=deps.remainingBudgetMs?.()??Number.POSITIVE_INFINITY,timeoutMs=Math.min(perCandidateMs,Math.max(0,remainingMs2));if(timeoutMs<=0)return!0;if(!reserveLlmBudget(deps.sessionID,SCREENING_TOKEN_ESTIMATE,deps.llmBudget))return!0;return!/\bREJECT\b/i.test(await withTimeoutSignal((signal2)=>llmDelegate("",buildScreeningPrompt(candidate2),signal2),timeoutMs,Error(`Knowledge admission screening timed out after ${timeoutMs}ms`)))}async function admitCandidate(directory,candidate2,deps){let candidateId2=resolveInsightCandidateId(candidate2),marker=insightAdmissionMarker(candidateId2),now2=deps.now??(()=>Date.now());if(!validateActionableFields({applies_to_agents:candidate2.applies_to_agents,applies_to_tools:candidate2.applies_to_tools,required_actions:candidate2.required_actions,forbidden_actions:candidate2.forbidden_actions,verification_checks:candidate2.verification_checks,triggers:candidate2.triggers,directive_priority:candidate2.directive_priority}).valid)return{outcome:"rejected",reason:"invalid_shape",marker};let actionability=validateActionability({applies_to_agents:candidate2.applies_to_agents,applies_to_tools:candidate2.applies_to_tools,required_actions:candidate2.required_actions,forbidden_actions:candidate2.forbidden_actions,verification_checks:candidate2.verification_checks});if(!actionability.actionable)return{outcome:"rejected",reason:actionability.reason??"unactionable",marker};if(!await screenCandidate(candidate2,deps))return{outcome:"rejected",reason:"screened_out",marker};let provenance=stampLearningProvenance({mechanism:candidate2.source?.kind==="prm_pattern"?"prm_pattern":"micro_reflection",sourceKnowledgeIds:[marker],sourceTaskIds:candidate2.source?.task_id?[candidate2.source.task_id]:[],sourceEvidenceRefs:candidate2.source_refs??[]},{sessionId:deps.sessionID,agentRole:candidate2.source?.agent,producedAt:new Date(now2()).toISOString()}),knowledgePath=(deps.resolveKnowledgePath??resolveSwarmKnowledgePath)(directory),entry=insightCandidateToEntry(candidate2,deps.projectName,deps.phaseNumber,deps.knowledgeConfig);if(unionSourceKnowledgeIds(entry,provenance.sourceKnowledgeIds),provenance.sourceEvidenceRefs.length>0){let refs=new Set([...entry.source_refs??[],...provenance.sourceEvidenceRefs]);entry.source_refs=[...refs]}let outcome="rejected",reason="no_change",entryId;if(await transactKnowledge(knowledgePath,(current)=>{if(findActiveEntryWithMarker(current,marker))return outcome="rejected",reason="already_admitted",null;let duplicate=findActiveSwarmNearDuplicate(entry.lesson,current,deps.knowledgeConfig.dedup_threshold);if(duplicate){let result=reinforceSwarmKnowledgeEntry(duplicate,{phase_number:deps.phaseNumber,confirmed_at:new Date(now2()).toISOString(),project_name:deps.projectName});return unionSourceKnowledgeIds(duplicate,[marker]),outcome="reinforced",reason=result.reason,entryId=duplicate.id,current}return current.push(entry),outcome="admitted",reason=void 0,entryId=entry.id,current}),outcome!=="rejected")deps.onKnowledgeChanged?.();return{outcome,reason,entryId,marker,provenance}}async function realtimeAdmissionAfter(directory,input,config3,resolveDeps){if(!isTaskTool(input.tool))return;if(!config3?.enabled)return;let sessionID=typeof input.sessionID==="string"&&input.sessionID.length>0?input.sessionID:void 0;if(!sessionID)return;if(getQueueDepth(sessionID)===0)return;let deps=await resolveDeps();return drainSessionQueue(directory,sessionID,config3,deps)}function emptySummary(){return{attempted:0,admitted:0,reinforced:0,rejected:0,deferred:0,failed:0,retries:0}}async function drainSessionQueue(directory,sessionID,config3,deps){let summary=emptySummary();if(!config3.enabled)return summary;let now2=deps.now??(()=>Date.now()),stats2=getQueueStats(sessionID);if(stats2.depth===0)return summary;let velocity=computeArrivalVelocity(stats2,now2()),size=computeDrainSize(stats2.depth,velocity,{minDrain:config3.min_drain,maxDrain:config3.max_drain,drainDepthFactor:config3.drain_depth_factor,drainVelocityFactor:config3.drain_velocity_factor});if(size<=0)return summary;let batch=takeDrainBatch(sessionID,size);if(batch.length===0)return summary;summary.attempted=batch.length;let startedAt=now2(),wallTimeMs=Math.max(0,Number(config3.max_drain_wall_time_ms)||0),deadline=wallTimeMs>0?startedAt+wallTimeMs:Number.POSITIVE_INFINITY,budgetExhausted=()=>now2()>=deadline,maxRetries=Math.max(0,Math.floor(Number(config3.max_retries_per_candidate)||0)),limit=pLimit(Math.max(1,Math.floor(Number(config3.max_concurrent_admissions)||1))),admissionDeps={...deps,sessionID,llmTimeoutMs:config3.max_llm_calls_per_session>0?deps.llmTimeoutMs??config3.per_candidate_llm_timeout_ms:0,llmBudget:deps.llmBudget??{maxLlmCallsPerSession:config3.max_llm_calls_per_session,maxTokensPerSession:config3.max_tokens_per_session},remainingBudgetMs:()=>deadline-now2()},deferOrAbandon=(item)=>{if(item.attempts>=MAX_CANDIDATE_DRAIN_ATTEMPTS){summary.failed++,warn(`[learning-admission] candidate abandoned after ${item.attempts} drain attempt(s) without completing`);return}requeueCandidate(sessionID,item,{maxQueueSize:config3.max_queue_size}),summary.deferred++};return await Promise.all(batch.map((item)=>limit(async()=>{if(budgetExhausted()){deferOrAbandon(item);return}for(let attempt=0;;attempt++)try{let result=await admitCandidate(directory,item.candidate,admissionDeps);if(result.outcome==="admitted")summary.admitted++;else if(result.outcome==="reinforced")summary.reinforced++;else summary.rejected++;return}catch(err){if(attempt>=maxRetries){warn(`[learning-admission] candidate failed after ${attempt+1} attempt(s): ${isAbortError(err)?"cancelled":err instanceof Error?err.message:String(err)}`),deferOrAbandon(item);return}if(summary.retries++,recordRetry(sessionID),budgetExhausted()){deferOrAbandon(item);return}}}))),summary}init_memory();init_provider_pool();init_task_model_routing();init_observability();init_otlp_exporter();init_startup_contract();init_manager();init_prm();init_trajectory_store();init_sweep();init_ephemeral_agent_dispatcher();function createReviewModelDispatcher(client,pricing){return{dispatch:(request)=>dispatchEphemeralAgent({client,directory:request.directory,parentSessionId:request.parentSessionId,agentName:request.agentName,model:request.model,system:request.system,prompt:request.prompt,readOnlyTools:request.tools??DEFAULT_READ_ONLY_TOOLS,title:request.title,timeoutMs:request.timeoutMs&&request.timeoutMs>0?request.timeoutMs:DEFAULT_EPHEMERAL_TIMEOUT_MS,promptByteLimit:request.promptByteLimit,responseByteLimit:request.responseByteLimit,abortSignal:request.abortSignal,pricing})}}init_finding_validator();init_runtime3();init_compaction_service();init_config_doctor();init_cost_accounting();init_injection_budget();init_model_preflight();init_version_check();init_snapshot_coordination_init();init_snapshot_reader();init_snapshot_store();init_snapshot_writer();init_state();init_telemetry();init_startup_contract();init_zod();init_lifecycle();init_loader();init_ephemeral_agent_dispatcher();init_gate_evidence();init_utils2();init_ledger();init_manager();init_utils3();init_runtime3();init_atomic_write();init_logger();init_model_dispatch_fallback();init_provider_error_classification();init_swarm_artifact_cache();init_config();init_lifecycle();init_next_wave_format();import{createHash as createHash105}from"node:crypto";import*as fs181 from"node:fs";import*as path316 from"node:path";var EPIC_PHASE_REVIEW_FILENAME="epic-phase-review.json",EPIC_PHASE_REVIEW_TTL_MS=86400000,EPIC_PHASE_REVIEW_FORWARD_SKEW_MS=300000,EPIC_PHASE_REVIEW_DISPATCH_TIMEOUT_MS=300000;function resolveEpicPhaseReviewTimeoutMs(directory){try{let configured=resolveEpicConfig(loadPluginConfigWithMeta(directory).config)?.phase_review?.timeout_ms;return typeof configured==="number"?configured:EPIC_PHASE_REVIEW_DISPATCH_TIMEOUT_MS}catch{return EPIC_PHASE_REVIEW_DISPATCH_TIMEOUT_MS}}var EPIC_PHASE_REVIEW_TOOL="epic_phase_review",EPIC_PHASE_REVIEW_BASH_RETRY_NOTE="You have a `bash` tool for this review. Use it only to read and inspect (for example cat, ls, grep, git log, git diff, git show). Never run a command that creates, modifies or deletes files, changes git state (checkout, stash, reset, commit), installs packages, or runs tests.",EPIC_PHASE_REVIEW_BASH_RETRY_TOOLS=Object.freeze(Object.fromEntries(Object.entries(DEFAULT_READ_ONLY_TOOLS).filter(([name])=>name!=="bash"))),MAX_REASON_CHARS=2000;function sha25612(text){return createHash105("sha256").update(text,"utf8").digest("hex")}function taskEvidenceFingerprint(directory,taskId){if(!isValidTaskId(taskId))return"invalid-task-id";try{let bytes=fs181.readFileSync(path316.join(directory,".swarm","evidence",`${taskId}.json`));return createHash105("sha256").update(bytes).digest("hex")}catch(error93){let code=error93.code;return code==="ENOENT"||code==="ENAMETOOLONG"?"missing":"unreadable"}}function currentEpicKey(directory){try{return _internals267.getOpenEpic(directory)?.epicKey??null}catch{return null}}function computeEpicPhaseBinding(directory,plan,phase){let target=plan.phases.find((item)=>item.id===phase);if(!target)return{ok:!1,reason:`phase ${phase} is not in the current plan`};let tasks=[...target.tasks].sort((a,b)=>a.id<b.id?-1:a.id>b.id?1:0),taskIds=tasks.map((task2)=>task2.id);return{ok:!0,incompleteTaskIds:tasks.filter((task2)=>task2.status!=="completed"&&task2.status!=="closed").map((task2)=>task2.id),binding:{epic_key:currentEpicKey(directory),plan_id:derivePlanId(plan),plan_structure_hash:computePlanStructureHash(plan),phase_task_ids:taskIds,phase_tasks_digest:sha25612(JSON.stringify(tasks.map((task2)=>[task2.id,task2.status]))),task_evidence_digest:sha25612(JSON.stringify(taskIds.map((id)=>[id,_internals267.taskEvidenceFingerprint(directory,id)])))}}}function evidencePath(directory,phase){return validateSwarmPath(directory,path316.posix.join("evidence",String(phase),EPIC_PHASE_REVIEW_FILENAME))}var VERDICTS=new Set(["APPROVED","NEEDS_REVISION","REJECTED"]);function isRoleVerdict(value,role){if(!value||typeof value!=="object"||Array.isArray(value))return!1;let v=value;return v.role===role&&typeof v.agent==="string"&&v.agent.length>0&&typeof v.verdict==="string"&&VERDICTS.has(v.verdict)&&(v.reason===null||typeof v.reason==="string")&&(v.dispatch==="completed"||v.dispatch==="unparseable"||v.dispatch==="failed")&&(v.tool_profile===void 0||v.tool_profile==="read-only"||v.tool_profile==="read-only-with-bash")&&typeof v.dispatched_at==="string"}function isBinding(value){if(!value||typeof value!=="object"||Array.isArray(value))return!1;let v=value;return(v.epic_key===void 0||v.epic_key===null||typeof v.epic_key==="string")&&typeof v.plan_id==="string"&&typeof v.plan_structure_hash==="string"&&Array.isArray(v.phase_task_ids)&&v.phase_task_ids.every((id)=>typeof id==="string")&&typeof v.phase_tasks_digest==="string"&&typeof v.task_evidence_digest==="string"}function parseEpicPhaseReviewEvidence(raw){if(!raw||typeof raw!=="object"||Array.isArray(raw))return null;let v=raw;if(v.schema_version!==1||v.kind!=="epic_phase_review"||typeof v.phase!=="number"||!Number.isInteger(v.phase)||typeof v.reviewed_at!=="string"||typeof v.parent_session_id!=="string"||!isBinding(v.binding)||!isRoleVerdict(v.reviewer,"reviewer")||!(v.critic===null||isRoleVerdict(v.critic,"critic")))return null;return raw}function readEpicPhaseReviewEvidence(directory,phase){let text;try{text=fs181.readFileSync(evidencePath(directory,phase),"utf-8")}catch(error93){if(error93.code==="ENOENT")return{status:"missing"};return{status:"invalid",detail:error93 instanceof Error?error93.message:String(error93)}}let parsed;try{parsed=JSON.parse(text)}catch{return{status:"invalid",detail:"evidence is not valid JSON"}}let evidence2=parseEpicPhaseReviewEvidence(parsed);return evidence2?{status:"found",evidence:evidence2}:{status:"invalid",detail:"evidence does not match schema v1"}}function rerunHint(phase){return`Call ${EPIC_PHASE_REVIEW_TOOL}({ phase: ${phase} }) — it dispatches the phase reviewer and then the phase critic and records both verdicts — then retry phase_complete.`}function openEpicWavesForPhase(record3,phase){return record3.waves.filter((wave)=>wave.phase===phase&&wave.status==="issued").map((wave)=>wave.seq)}function describeOpenEpicWaves(directory,phase){let record3;try{record3=_internals267.getOpenEpic(directory)}catch(error93){return`the open epic's record is unreadable (${error93 instanceof Error?error93.message:String(error93)}), so its waves cannot be verified (fail closed). Ask the user to run \`/swarm epic status\`.`}if(!record3)return null;let open11=openEpicWavesForPhase(record3,phase);if(open11.length===0)return null;return`wave ${open11.join(", ")} of phase ${phase} is still open. Call epic_next_wave — it closes a wave once every task in it is resolved — until it returns phase-ready-for-review.`}async function verifyEpicPhaseReadiness(directory,phase,nowMs3){let openWaves=describeOpenEpicWaves(directory,phase);if(openWaves!==null)return{ok:!1,code:"EPIC_PHASE_WAVES_OPEN",reason:`Phase ${phase} cannot complete: ${openWaves}`};let read=_internals267.readEvidence(directory,phase),rel3=`.swarm/evidence/${phase}/${EPIC_PHASE_REVIEW_FILENAME}`;if(read.status==="missing")return{ok:!1,code:"EPIC_PHASE_REVIEW_MISSING",reason:`Epic Mode requires an APPROVED phase reviewer and phase critic before phase ${phase} can complete, but ${rel3} does not exist. ${rerunHint(phase)}`};if(read.status==="invalid")return{ok:!1,code:"EPIC_PHASE_REVIEW_INVALID",reason:`Epic phase review evidence ${rel3} is unreadable or malformed (${read.detail}). Do not edit it by hand. ${rerunHint(phase)}`};let evidence2=read.evidence;if(evidence2.phase!==phase)return{ok:!1,code:"EPIC_PHASE_REVIEW_INVALID",reason:`Epic phase review evidence at ${rel3} records phase ${evidence2.phase}, not phase ${phase}. ${rerunHint(phase)}`};if(evidence2.reviewer.verdict!=="APPROVED")return{ok:!1,code:"EPIC_PHASE_REVIEWER_NOT_APPROVED",reason:`Epic phase reviewer (${evidence2.reviewer.agent}) returned ${evidence2.reviewer.verdict} for phase ${phase}${evidence2.reviewer.reason?`: ${evidence2.reviewer.reason}`:""}. ${epicPhaseFixPath(phase)} Then retry phase_complete.`};if(!evidence2.critic)return{ok:!1,code:"EPIC_PHASE_CRITIC_MISSING",reason:`Epic phase critic verdict is missing for phase ${phase}. ${rerunHint(phase)}`};if(evidence2.critic.verdict!=="APPROVED")return{ok:!1,code:"EPIC_PHASE_CRITIC_NOT_APPROVED",reason:`Epic phase critic (${evidence2.critic.agent}) returned ${evidence2.critic.verdict} for phase ${phase}${evidence2.critic.reason?`: ${evidence2.critic.reason}`:""}. ${epicPhaseFixPath(phase)} Then retry phase_complete.`};let reviewedAtMs=Date.parse(evidence2.reviewed_at);if(!Number.isFinite(reviewedAtMs))return{ok:!1,code:"EPIC_PHASE_REVIEW_INVALID",reason:`Epic phase review evidence for phase ${phase} has an invalid reviewed_at timestamp. ${rerunHint(phase)}`};let age=nowMs3-reviewedAtMs;if(age<-EPIC_PHASE_REVIEW_FORWARD_SKEW_MS)return{ok:!1,code:"EPIC_PHASE_REVIEW_STALE",reason:`Epic phase review evidence for phase ${phase} is future-dated (${evidence2.reviewed_at}); rejected as forged or clock-skewed. ${rerunHint(phase)}`};if(age>EPIC_PHASE_REVIEW_TTL_MS)return{ok:!1,code:"EPIC_PHASE_REVIEW_STALE",reason:`Epic phase review evidence for phase ${phase} is older than 24h. ${rerunHint(phase)}`};let plan;try{plan=await _internals267.loadPlan(directory)}catch{plan=null}if(!plan)return{ok:!1,code:"EPIC_PHASE_PLAN_UNREADABLE",reason:`Cannot verify Epic phase review freshness for phase ${phase}: the plan could not be loaded.`};let current=computeEpicPhaseBinding(directory,plan,phase);if(!current.ok)return{ok:!1,code:"EPIC_PHASE_PLAN_UNREADABLE",reason:`Cannot verify Epic phase review freshness: ${current.reason}.`};let recorded=evidence2.binding,drift=[];if((recorded.epic_key??null)!==current.binding.epic_key)drift.push("epic instance");if(recorded.plan_id!==current.binding.plan_id)drift.push("plan identity");if(recorded.plan_structure_hash!==current.binding.plan_structure_hash)drift.push("plan structure");if(recorded.phase_tasks_digest!==current.binding.phase_tasks_digest)drift.push("phase task set/status");if(recorded.task_evidence_digest!==current.binding.task_evidence_digest)drift.push("task gate evidence (rework after review)");if(drift.length>0)return{ok:!1,code:"EPIC_PHASE_REVIEW_STALE",reason:`Epic phase review evidence for phase ${phase} is stale — ${drift.join(", ")} changed after the review. ${rerunHint(phase)}`};return{ok:!0,evidence:evidence2}}function parseEpicPhaseVerdict(text){let lines=text.split(/\r?\n/),found=[];for(let i=0;i<lines.length;i++){let match=/^\s*(?:\*\*)?VERDICT(?:\*\*)?\s*:\s*(?:\*\*)?\s*(APPROVED|NEEDS_REVISION|REJECTED)\s*(?:\*\*)?\s*$/i.exec(lines[i]);if(match)found.push({verdict:match[1].toUpperCase(),index:i})}if(found.length===0)return null;if(new Set(found.map((item)=>item.verdict)).size>1)return null;let last=found[found.length-1],reason=null;for(let i=last.index+1;i<Math.min(lines.length,last.index+4);i++){let reasonMatch=/^\s*(?:\*\*)?REASON(?:\*\*)?\s*:\s*(.+)$/i.exec(lines[i]);if(reasonMatch){reason=reasonMatch[1].trim().slice(0,MAX_REASON_CHARS);break}}return{verdict:last.verdict,reason}}function buildReviewPackage(directory,plan,phase){let target=plan.phases.find((item)=>item.id===phase),tasks=target?.tasks??[],outcomes={};try{outcomes=_internals267.getOpenEpic(directory)?.tasks??{}}catch(error93){warn(`[epic-phase-readiness] epic record unreadable; reviewing without divergence: ${error93 instanceof Error?error93.message:String(error93)}`)}let filesChanged=new Set,packaged=tasks.map((task2)=>{let outcome=Object.hasOwn(outcomes,task2.id)?outcomes[task2.id]:void 0,divergence=outcome&&outcome.resolution!=="removed"?outcome:void 0,attributed=divergence?.attribution==="session"||divergence?.attribution==="git-single-task";for(let file3 of divergence&&attributed?[...divergence.declared,...divergence.undeclared]:[...divergence?.declared??[],...task2.files_touched])filesChanged.add(file3);return{id:task2.id,status:task2.status,description:task2.description,...task2.acceptance?{acceptance:task2.acceptance}:{},files_touched:[...task2.files_touched],depends:[...task2.depends],...divergence?{divergence:{declared_scope:[...divergence.declared],undeclared:[...divergence.undeclared],attribution:divergence.attribution}}:{}}});return{phase,phase_name:target?.name??`Phase ${phase}`,tasks:packaged,files_changed:[...filesChanged].sort()}}var VERDICT_FOOTER=`Conclude with exactly ONE verdict line followed by a REASON line:
|
|
7429
7431
|
|
|
7430
7432
|
VERDICT: APPROVED
|
|
@@ -7787,9 +7789,9 @@ ${jsdocContent}`;else if(line.includes("*/"))break;else if(functionKeywords.test
|
|
|
7787
7789
|
`)){let trimmed=line.trim();if(trimmed==="")continue;let parsedEvent;try{parsedEvent=JSON.parse(trimmed)}catch{continue}let parsed=asRecord4(parsedEvent);if(parsed===null)continue;if(parsed.type!=="pr_workflow_aborted")continue;if(parsed.sessionID!==sessionID)continue;if(typeof parsed.mode==="string"&&parsed.mode!=="PR_REVIEW")continue;if(typeof parsed.prHeadSha!=="string"||parsed.prHeadSha.toLowerCase()!==headSha)continue;let timestamp=parsed.timestamp;if(typeof timestamp!=="string")continue;if(settledAt===""||timestamp>=settledAt)return"aborted"}return"clean"}function deriveCoverage(directory,runId,receipt){let disclosurePath=safePath(directory,path361.join("pr-review",runId,"coverage-disclosure.json"));if("refusal"in disclosurePath)return{refusal:disclosurePath.refusal};let rawDisclosure=readJsonFile2(disclosurePath.path);if(rawDisclosure===null)return{refusal:failure2("not-settled",`Invalid pr_review_submission state: coverage disclosure for run ${runId} is corrupt (.swarm/pr-review/${runId}/coverage-disclosure.json); refusing to claim coverage`,!0)};let disclosure=asRecord4(rawDisclosure),dimensionNames=[],unresolvedFromDisclosure=disclosure?.unresolvedDimensions;if(Array.isArray(unresolvedFromDisclosure))for(let entry of unresolvedFromDisclosure){let record3=asRecord4(entry),name=typeof record3?.dimension==="string"?record3.dimension:typeof entry==="string"?entry:null;if(typeof name==="string")dimensionNames.push(name)}let missingDimension=disclosure?.missingDimension;if(dimensionNames.length===0&&typeof missingDimension==="string"&&missingDimension!=="")dimensionNames.push(missingDimension);if(dimensionNames.length>0)return{coverage:{kind:"PARTIAL",unresolved_dimensions:dimensionNames}};let degradations=Array.isArray(receipt.coverage_degradations)?receipt.coverage_degradations:[],reasons=[];for(let entry of degradations){let record3=asRecord4(entry);if(typeof record3?.reason==="string")reasons.push(typeof record3.trigger_id==="string"?`${record3.trigger_id}: ${record3.reason}`:record3.reason)}if(reasons.length>0)return{coverage:{kind:"PARTIAL",unresolved_dimensions:reasons}};let settlementReasons=[];for(let phase of["reviewer","critic"]){let settlementRead=readVerdictSettlementReceipt(directory,runId,phase);if(settlementRead.status==="ok"&&settlementRead.receipt.runId===runId&&settlementRead.receipt.items.length>0)settlementReasons.push(`verdict-settlement (${phase}): ${settlementRead.receipt.items.length} liveness-dead item(s) disclosed by N-of-M settlement`)}if(settlementReasons.length>0)return{coverage:{kind:"PARTIAL",unresolved_dimensions:[...reasons,...settlementReasons]}};return{coverage:{kind:"FULL",unresolved_dimensions:[]}}}function reviewEventFor(records){return records.some((record3)=>{let severity2=typeof record3.severity==="string"?record3.severity.toUpperCase():"NONE";return BLOCKING_SEVERITIES.has(severity2)})?"REQUEST_CHANGES":"COMMENT"}async function fetchExistingCommentBodies(executable,directory,repoSlug,prNumber){let endpoints=[`repos/${repoSlug}/pulls/${prNumber}/comments?per_page=100`,`repos/${repoSlug}/pulls/${prNumber}/reviews?per_page=100`],bodies=[];for(let endpoint of endpoints){let run=await _internals309.runExternalTool({executable,args:["api",endpoint],cwd:directory,timeoutMs:GH_TIMEOUT_MS2,maxStdoutBytes:GH_MAX_STDOUT_BYTES2,maxStderrBytes:GH_MAX_STDERR_BYTES2});if(run.status==="timeout")return{refusal:failure2("transport-failed",`gh api ${endpoint} timed out after ${GH_TIMEOUT_MS2}ms; refusing to submit without dedupe context`,!0)};if(run.status!=="completed")return{refusal:failure2("transport-failed",`gh api ${endpoint} failed to start (${run.message??run.status}); refusing to submit without dedupe context`,!0)};if(run.exitCode!==0)return{refusal:failure2("transport-failed",`gh api ${endpoint} exited ${run.exitCode}: ${run.stderr.split(`
|
|
7788
7790
|
`)[0]??""}; refusing to submit without dedupe context`,!0)};if(run.stdoutTruncated)return{refusal:failure2("transport-failed",`gh api ${endpoint} stdout exceeded the ${GH_MAX_STDOUT_BYTES2}-byte read cap; dedupe context would be silently incomplete — refusing to submit`,!0)};let parsed;try{parsed=JSON.parse(run.stdout)}catch{continue}if(!Array.isArray(parsed))continue;for(let entry of parsed){let record3=asRecord4(entry);if(typeof record3?.body==="string"&&record3.body!=="")bodies.push(record3.body)}}return{bodies}}var _internals309={resolveGhBinary,runExternalTool};async function executePrReviewSubmission(args2,directory,context={}){let raw=asRecord4(args2);if(raw===null)return failure2("invalid-args","Invalid pr_review_submission args: expected an object with pr_number, repo, run_id, pr_head_sha");if(typeof raw.pr_number!=="number"||!Number.isInteger(raw.pr_number)||raw.pr_number<=0)return failure2("invalid-args",`Invalid pr_review_submission args: pr_number must be a positive integer (got ${JSON.stringify(raw.pr_number)??"null"})`);if(typeof raw.repo!=="string"||!REPO_SLUG_PATTERN.test(raw.repo.trim()))return failure2("invalid-args",`Invalid pr_review_submission args: repo must be an owner/name slug (got ${JSON.stringify(raw.repo)??"null"})`);if(typeof raw.run_id!=="string"||!RUN_ID_PATTERN2.test(raw.run_id.trim()))return failure2("invalid-args",`Invalid pr_review_submission args: run_id must match ${RUN_ID_PATTERN2.source} (got ${JSON.stringify(raw.run_id)??"null"})`);if(typeof raw.pr_head_sha!=="string"||!PR_HEAD_SHA_PATTERN2.test(raw.pr_head_sha.trim()))return failure2("invalid-args",`Invalid pr_review_submission args: pr_head_sha must be 6-64 hex characters (got ${JSON.stringify(raw.pr_head_sha)??"null"})`);let prNumber=raw.pr_number,repoSlug=raw.repo.trim(),runId=raw.run_id.trim(),headSha=raw.pr_head_sha.trim().toLowerCase(),sessionID=context.sessionID?.trim();if(!sessionID)return failure2("invalid-args","Invalid pr_review_submission args: a session ID is required (controller-only surface)",!0);let gateState;try{gateState=await readPrWorkflowGateState(directory,sessionID)}catch(error93){return failure2("gate-indeterminate",`BLOCKED: PR workflow gate state for this session could not be read safely (${error93 instanceof Error?error93.message:String(error93)}); repair or abort the gate before submitting`,!0)}if(gateState!==null)return failure2("gate-active",`BLOCKED: an active ${gateState.mode} gate exists for this session; the submission path opens only after complete_pr_workflow clears the gate`,!0);let receiptPath=safePath(directory,path361.join("pr-review",runId,"trigger-eval.json"));if("refusal"in receiptPath)return receiptPath.refusal;let receipt=asRecord4(readJsonFile2(receiptPath.path));if(receipt===null)return failure2("not-settled",`Invalid pr_review_submission state: trigger evaluation receipt for run ${runId} is missing or unreadable (.swarm/pr-review/${runId}/trigger-eval.json)`,!0);let recordPath3=safePath(directory,path361.join("pr-review",runId,"findings.jsonl"));if("refusal"in recordPath3)return recordPath3.refusal;let records=readFindingsRecords(recordPath3.path);if(!records)return failure2("not-settled",`Invalid pr_review_submission state: findings artifact for run ${runId} is missing or corrupt (.swarm/pr-review/${runId}/findings.jsonl)`,!0);let abortScan=hasAbortAfterSettlement(directory,sessionID,headSha,settlementTime(records,receipt));if(abortScan==="indeterminate")return failure2("aborted-indeterminate",`BLOCKED: the aborted-run scan for head ${headSha} could not be completed (events store unreadable or truncated); refusing to submit without a determinate authorization signal`,!0);if(abortScan==="aborted")return failure2("aborted",`BLOCKED: the PR workflow for head ${headSha} was aborted at/after this run's settlement; aborted runs are out of scope (#3097)`,!0);if(receipt.run_id!==runId)return failure2("head-mismatch",`Invalid pr_review_submission state: trigger evaluation receipt run_id ${JSON.stringify(receipt.run_id)??"null"} does not match the requested run ${runId}`,!0);let receiptHead=typeof receipt.pr_head_sha==="string"?receipt.pr_head_sha.trim().toLowerCase():"";if(receiptHead===""||receiptHead!==headSha)return failure2("head-mismatch",`Invalid pr_review_submission state: pr_head_sha mismatch — trigger evaluation receipt for run ${runId} is bound to ${JSON.stringify(receipt.pr_head_sha)??"null"}, not ${headSha}`,!0);if(!records.some((record3)=>record3.boundary==="post_critic"))return failure2("not-settled",`Invalid pr_review_submission state: run ${runId} has no post_critic boundary record in findings.jsonl (run not settled)`,!0);if(records.some((record3)=>{return(typeof record3.pr_head_sha==="string"?record3.pr_head_sha.trim().toLowerCase():"")!==headSha}))return failure2("head-mismatch",`Invalid pr_review_submission state: pr_head_sha mismatch — findings.jsonl for run ${runId} contains records bound to a different head`,!0);let settledRecords=records.filter((record3)=>record3.boundary==="post_critic"&&record3.status!=="DISPROVED"),derived=deriveCoverage(directory,runId,receipt);if("refusal"in derived)return derived.refusal;let coverage=derived.coverage,event=reviewEventFor(settledRecords),rendererInput={run_id:runId,pr_head_sha:headSha,verdict:event,base_verification:typeof receipt.base_verification==="string"?receipt.base_verification:void 0,coverage,findings:settledRecords.map((record3)=>({finding_id:typeof record3.finding_id==="string"?record3.finding_id:"",status:typeof record3.status==="string"?record3.status:"",file_line:typeof record3.file_line==="string"?record3.file_line:"",evidence:typeof record3.evidence==="string"?record3.evidence:"",next_action:typeof record3.next_action==="string"?record3.next_action:"",severity:typeof record3.severity==="string"?record3.severity:void 0}))},executable=_internals309.resolveGhBinary();if(!executable)return failure2("gh-not-found","gh was not found on PATH and no override is configured; a GitHub submission requires the gh CLI (there is no unauthenticated POST fallback)",!0);let existing=await fetchExistingCommentBodies(executable,directory,repoSlug,prNumber);if("refusal"in existing)return existing.refusal;rendererInput.existingComments=existing.bodies;let rendered=renderPrReviewSubmissionBody(rendererInput);if(rendered.inlineComments.length===0&&rendererInput.findings.length>0&&rendererInput.findings.every((finding)=>rendered.skippedAsPosted.includes(finding.finding_id)))return failure2("nothing-new","nothing new to submit — every finding for this run is already present on the PR (idempotent no-op)",!0);let payload={commit_id:headSha,body:rendered.body,event,comments:rendered.inlineComments.map((comment)=>({path:comment.path,line:comment.line,body:comment.body}))},payloadPath;try{payloadPath=payloadArtifactPath(directory,runId)}catch(error93){return failure2("invalid-args",`Invalid pr_review_submission args: artifact path rejected (${error93 instanceof Error?error93.message:String(error93)})`,!1)}try{fs220.mkdirSync(path361.dirname(payloadPath),{recursive:!0}),fs220.writeFileSync(payloadPath,`${JSON.stringify(payload,null,2)}
|
|
7789
7791
|
`,"utf-8")}catch(error93){return failure2("payload-write-failed",`failed to persist the submission payload copy (.swarm/pr-review/${runId}/submission-payload.json): ${error93 instanceof Error?error93.message:String(error93)}`)}let run=await _internals309.runExternalTool({executable,args:["api",`repos/${repoSlug}/pulls/${prNumber}/reviews`,"--method","POST","--input",payloadPath],cwd:directory,timeoutMs:GH_TIMEOUT_MS2,maxStdoutBytes:GH_MAX_STDOUT_BYTES2,maxStderrBytes:GH_MAX_STDERR_BYTES2});if(run.status==="timeout")return failure2("transport-failed",`gh api repos/${repoSlug}/pulls/${prNumber}/reviews timed out after ${GH_TIMEOUT_MS2}ms (the review may or may not have been created; dedupe on resubmit; payload preserved at .swarm/pr-review/${runId}/submission-payload.json)`,!0);if(run.status!=="completed")return failure2("transport-failed",`gh api repos/${repoSlug}/pulls/${prNumber}/reviews failed to start (${run.message??run.status})`,!0);if(run.exitCode!==0)return failure2("transport-failed",`gh api repos/${repoSlug}/pulls/${prNumber}/reviews exited ${run.exitCode}: ${run.stderr.split(`
|
|
7790
|
-
`)[0]??""}`,!0);let review={};try{review=JSON.parse(run.stdout)}catch{}return JSON.stringify({success:!0,run_id:runId,pr_head_sha:headSha,event,inline_comment_count:rendered.inlineComments.length,skipped_as_posted:rendered.skippedAsPosted.length,truncated_inline_comments:rendered.truncatedInlineComments,dismissed_findings:rendered.dismissedCount,body_truncated:rendered.bodyTruncated,coverage_kind:coverage.kind,posted_review_id:typeof review.id==="number"?review.id:null,review_url:typeof review.html_url==="string"?review.html_url:null,payload_path:`.swarm/pr-review/${runId}/submission-payload.json`},null,2)}var pr_review_submission=createSwarmTool({allowWorkingDirectoryOverride:!0,description:"submit a settled, head-bound PR review to GitHub through the gh PR Review API after the PR_REVIEW gate clears; architect-only, refuses while a gate is active or the run was aborted after settlement",args:{pr_number:exports_external.number().int().positive().describe("Pull request number to submit the review to"),repo:exports_external.string().trim().regex(REPO_SLUG_PATTERN).describe("owner/name repository slug"),run_id:exports_external.string().trim().regex(RUN_ID_PATTERN2).describe("settled PR-review run id under .swarm/pr-review/"),pr_head_sha:exports_external.string().trim().regex(PR_HEAD_SHA_PATTERN2).describe("exact PR head sha the run is bound to (commit_id pin)")},execute:executePrReviewSubmission});init_pending_delegations();init_workspace_snapshot();init_pr_workflow_state();init_pr_workflow_auto_wake();init_pr_workflow_gate();import*as fsp12 from"node:fs/promises";import*as path362 from"node:path";init_utils2();init_bun_compat();init_git_executable();init_create_tool();var GIT_TIMEOUT_MS11=5000,GIT_MAX_STDOUT_BYTES=524288,MAX_DIRTY_FILES=50,MAX_REMOTES=20,MAX_REMOTE_URL_LEN=200,MAX_FIELD_LEN=240,MAX_RECOVERY_REASON_CODE_LEN=120,RECEIPT_DIR2="pr-workflow-checkouts",utf8Encoder=new TextEncoder,utf8Decoder=new TextDecoder("utf-8",{fatal:!1});function truncateToByteBudget(value,maxBytes){let encoded=utf8Encoder.encode(value);if(encoded.length<=maxBytes)return value;return utf8Decoder.decode(encoded.subarray(0,maxBytes))}function boundUntrusted(value,maxLen){let cleaned=value.replace(/[\p{Cc}]/gu," ").replace(/[`<>]/g," ").replace(/\s+/g," ").trim();return cleaned.length>maxLen?`${cleaned.slice(0,maxLen)}…`:cleaned}async function runGitCapture2(directory,args2){let gitExecutable;try{gitExecutable=await resolveGitExecutableAsync()}catch{return null}let proc=bunSpawn([gitExecutable,...args2],{cwd:directory,stdin:"ignore",stdout:"pipe",stderr:"ignore",timeout:GIT_TIMEOUT_MS11});try{let[exitCode,stdout]=await Promise.all([proc.exited,proc.stdout.text()]);if(exitCode!==0)return null;return truncateToByteBudget(stdout,GIT_MAX_STDOUT_BYTES)}catch{return null}finally{try{proc.kill()}catch{}}}async function resolveBranch(directory){let raw=await _internals310.runGitCapture(directory,["rev-parse","--abbrev-ref","HEAD"]);if(raw===null)return{branch:null,detached:null};let value=raw.trim();if(!value||value==="HEAD")return{branch:null,detached:!0};return{branch:boundUntrusted(value,MAX_FIELD_LEN),detached:!1}}function parseDirtyFiles(porcelain){if(!porcelain)return{dirtyFiles:[],dirtyFileCount:0,dirtyFilesTruncated:!1};let lines=porcelain.split(`
|
|
7792
|
+
`)[0]??""}`,!0);let review={};try{review=JSON.parse(run.stdout)}catch{}return JSON.stringify({success:!0,run_id:runId,pr_head_sha:headSha,event,inline_comment_count:rendered.inlineComments.length,skipped_as_posted:rendered.skippedAsPosted.length,truncated_inline_comments:rendered.truncatedInlineComments,dismissed_findings:rendered.dismissedCount,body_truncated:rendered.bodyTruncated,coverage_kind:coverage.kind,posted_review_id:typeof review.id==="number"?review.id:null,review_url:typeof review.html_url==="string"?review.html_url:null,payload_path:`.swarm/pr-review/${runId}/submission-payload.json`},null,2)}var pr_review_submission=createSwarmTool({allowWorkingDirectoryOverride:!0,description:"submit a settled, head-bound PR review to GitHub through the gh PR Review API after the PR_REVIEW gate clears; architect-only, refuses while a gate is active or the run was aborted after settlement",args:{pr_number:exports_external.number().int().positive().describe("Pull request number to submit the review to"),repo:exports_external.string().trim().regex(REPO_SLUG_PATTERN).describe("owner/name repository slug"),run_id:exports_external.string().trim().regex(RUN_ID_PATTERN2).describe("settled PR-review run id under .swarm/pr-review/"),pr_head_sha:exports_external.string().trim().regex(PR_HEAD_SHA_PATTERN2).describe("exact PR head sha the run is bound to (commit_id pin)")},execute:executePrReviewSubmission});init_pending_delegations();init_workspace_snapshot();init_pr_workflow_state();init_pr_workflow_auto_wake();init_pr_workflow_gate();import*as fsp12 from"node:fs/promises";import*as path362 from"node:path";init_utils2();init_bun_compat();init_git_executable();init_create_tool();var GIT_TIMEOUT_MS11=5000,GIT_MAX_STDOUT_BYTES=524288,MAX_DIRTY_FILES=50,MAX_REMOTES=20,MAX_REMOTE_URL_LEN=200,MAX_FIELD_LEN=240,MAX_RECOVERY_REASON_CODE_LEN=120,PR_REVIEW_STATUS_LANE_ROWS_CAP=30,PR_REVIEW_STATUS_INVENTORY_CAP=40,PR_REVIEW_STATUS_FINDING_LINE_MAX=240,PR_REVIEW_STATUS_FINDINGS_PER_LANE=5,PR_REVIEW_STATUS_FINDING_ID_MAX=128,PR_REVIEW_STATUS_FINDING_SEVERITY_MAX=32,SALVAGED_PROJECTION_REASON="gate state was salvaged after schema validation failed; PR-review projection fields were dropped and their absence proves nothing",RECEIPT_DIR2="pr-workflow-checkouts",utf8Encoder=new TextEncoder,utf8Decoder=new TextDecoder("utf-8",{fatal:!1});function truncateToByteBudget(value,maxBytes){let encoded=utf8Encoder.encode(value);if(encoded.length<=maxBytes)return value;return utf8Decoder.decode(encoded.subarray(0,maxBytes))}var PR_REVIEW_BOUNDARY_ORDER=["post_explorer","post_reviewer","post_critic"],PR_REVIEW_BOUNDARY_SETTLEMENT_PHASE={post_reviewer:"reviewer",post_critic:"critic"};function boundUntrusted(value,maxLen){let cleaned=value.replace(/[\p{Cc}]/gu," ").replace(/[`<>]/g," ").replace(/\s+/g," ").trim();return cleaned.length>maxLen?`${cleaned.slice(0,maxLen)}…`:cleaned}async function runGitCapture2(directory,args2){let gitExecutable;try{gitExecutable=await resolveGitExecutableAsync()}catch{return null}let proc=bunSpawn([gitExecutable,...args2],{cwd:directory,stdin:"ignore",stdout:"pipe",stderr:"ignore",timeout:GIT_TIMEOUT_MS11});try{let[exitCode,stdout]=await Promise.all([proc.exited,proc.stdout.text()]);if(exitCode!==0)return null;return truncateToByteBudget(stdout,GIT_MAX_STDOUT_BYTES)}catch{return null}finally{try{proc.kill()}catch{}}}async function resolveBranch(directory){let raw=await _internals310.runGitCapture(directory,["rev-parse","--abbrev-ref","HEAD"]);if(raw===null)return{branch:null,detached:null};let value=raw.trim();if(!value||value==="HEAD")return{branch:null,detached:!0};return{branch:boundUntrusted(value,MAX_FIELD_LEN),detached:!1}}function parseDirtyFiles(porcelain){if(!porcelain)return{dirtyFiles:[],dirtyFileCount:0,dirtyFilesTruncated:!1};let lines=porcelain.split(`
|
|
7791
7793
|
`).filter((line)=>line.length>=4),dirtyFiles=[];for(let line of lines){if(dirtyFiles.length>=MAX_DIRTY_FILES)break;let status2=line.slice(0,2).trim()||"??",rawPath=line.slice(3);dirtyFiles.push({status:boundUntrusted(status2,4),path:boundUntrusted(rawPath,MAX_FIELD_LEN)})}return{dirtyFiles,dirtyFileCount:lines.length,dirtyFilesTruncated:lines.length>dirtyFiles.length}}function parseRemotes(remoteOutput){if(!remoteOutput)return{remotes:[],remotesTruncated:!1};let byName=new Map;for(let line of remoteOutput.split(`
|
|
7792
|
-
`)){let trimmed=line.trim();if(!trimmed)continue;let[name,rest]=trimmed.split(/\s+/,2);if(!name||!rest||byName.has(name))continue;let url3=rest.replace(/\s+\((?:fetch|push)\)\s*$/i,"");byName.set(boundUntrusted(name,64),boundUntrusted(url3,MAX_REMOTE_URL_LEN))}let entries2=[...byName.entries()],remotes=entries2.slice(0,MAX_REMOTES).map(([name,url3])=>({name,url:url3}));return{remotes,remotesTruncated:entries2.length>remotes.length}}async function countCheckoutReceiptFiles(directory,sessionID){try{let receiptDirectory=validateSwarmPath(directory,path362.join(RECEIPT_DIR2,prWorkflowSessionFileStem(sessionID)));return(await fsp12.readdir(receiptDirectory,{withFileTypes:!0})).filter((entry)=>entry.isFile()&&/^[0-9a-f]{40,64}\.json$/i.test(entry.name)).length}catch(error93){if(error93.code==="ENOENT")return 0;return null}}function describeDelegationRead(directory){try{let outcome=_internals310.readDelegationsDetailed(directory);if(outcome.status==="ok")return{state:"ok"};return{state:"uncertain",reasonCode:boundUntrusted(outcome.reason,MAX_RECOVERY_REASON_CODE_LEN)}}catch{return{state:"uncertain",reasonCode:"reader-threw"}}}function describeRecoveryNextStep(delegationReadState){if(delegationReadState==="uncertain")return"Delegation store read is uncertain: repair the store, then re-run pr_workflow_status; if abandoning the workflow, abort via abort_pr_workflow.";return"Re-run pr_workflow_status after any store repair; if abandoning the workflow, abort via abort_pr_workflow."}function describeNextStep(gate,git2,checkout){if(checkout.kind==="recovery-required"||checkout.kind==="indeterminate")return`Manual Git recovery required. code=${checkout.code} retryable=false required_action=${checkout.requiredAction}`;if(!gate.active){if(gate.reason==="delegation-chain-uncertain")return"PR workflow gate ownership could not be resolved from this session delegation chain (cycle, depth limit, or missing ancestor). Treat the workflow state as unknown and use read-only recovery inspection; do not perform PR-workflow writes.";return"No active PR workflow gate for this session. Activate with `/swarm pr-review <pr-ref>` or `/swarm pr-feedback <pr-ref>` before PR-workflow tool calls are admitted."}if(!gate.prHeadBound)return gate.mode==="PR_FEEDBACK"?"PR_FEEDBACK gate active; PR head not yet bound. If the working tree is dirty, preserve it with prepare_pr_workflow_checkout (omit paths to include tracked and untracked changes). Prefer the intended exact tracking checkout, then bind; if this workflow inherited an already-detached exact intake head, bind it directly and the controller will attach the unique exact local/remote tracking ref. Ambiguity or an existing mismatched upstream fails closed.":"PR_REVIEW gate active; PR head not yet bound. If the working tree is dirty, preserve it with prepare_pr_workflow_checkout (omit paths to include tracked and untracked changes), then bind the exact detached PR head.";if(git2.isClean===!1)return`${gate.mode} gate active and head bound, but the working tree is dirty. Read-only observation only; the gate keeps writes and non-tracking fetches fail-closed.`;if(git2.isClean===null)return`${gate.mode} gate active and head bound, but this session could not determine whether the working tree is clean (git status failed). Treat the tree state as unknown and verify manually before assuming it is clean; read-only observation only.`;return`${gate.mode} gate active and head bound. Continue read-only review using the admitted observe/validate tools (diff, gh_evidence, repo_map, lint check, etc.).`}function summarizeGate(state2,receiptFiles,salvage){if(!state2)return{active:!1,reason:"no-active-gate"};return{active:!0,...salvage?.salvaged?{stateSalvaged:!0,stateSalvageDisclosure:salvage.disclosure}:{},mode:state2.mode,prHeadBound:Boolean(state2.prHeadSha),prHeadSha:state2.prHeadSha??null,prFeedbackTargetUrl:state2.prFeedbackTargetUrl?boundUntrusted(state2.prFeedbackTargetUrl,MAX_FIELD_LEN):null,prReviewBaseRef:state2.prReviewBaseRef?boundUntrusted(state2.prReviewBaseRef,MAX_FIELD_LEN):null,prReviewBaseSha:state2.prReviewBaseSha??null,prReviewDepthTier:state2.prReviewDepthTier??null,baseDispatchBatches:state2.prReviewBaseDispatches?.length??0,validationBatches:state2.prReviewValidationBatches?.length??0,feedbackVerificationBatches:state2.prFeedbackVerifications?.length??0,...state2.prFeedbackInventoryAmendments?.length?{inventoryAmendments:state2.prFeedbackInventoryAmendments}:{},checkoutReceiptFiles:receiptFiles,activatedAt:state2.activatedAt,updatedAt:state2.updatedAt,revision:state2.revision}}async function resolveWorkflowGate(directory,sessionID){let outcome=await _internals310.resolvePrWorkflowControllerSession({directory,sessionID,readGate:(candidate2)=>_internals310.readPrWorkflowGateStateForRecovery(directory,candidate2)});if(outcome.kind==="gate-owner")return{sessionID:outcome.sessionID,recovery:outcome.gate};if(outcome.kind==="no-gate")return{sessionID:outcome.sessionID,recovery:null};return{sessionID:null,recovery:null}}async function resolveWorkflowGateSession(directory,sessionID){return(await resolveWorkflowGate(directory,sessionID)).sessionID}async function executePrWorkflowStatus(directory,rawSessionID){let sessionID=rawSessionID?.trim()?rawSessionID.trim():null,resolvedGate=sessionID?await resolveWorkflowGate(directory,sessionID):null,gateSessionID=resolvedGate?.sessionID??null,[head2,isClean,branchInfo,porcelain,remoteOutput,liveCheckout]=await Promise.all([_internals310.resolveCurrentGitHeadAsync(directory),_internals310.resolveIsWorkingTreeCleanAsync(directory),resolveBranch(directory),_internals310.runGitCapture(directory,["status","--porcelain=v1","--untracked-files=all"]),_internals310.runGitCapture(directory,["remote","-v"]),_internals310.classifyGitState(directory)]),dirty=parseDirtyFiles(porcelain),{remotes,remotesTruncated}=parseRemotes(remoteOutput),git2={head:head2,branch:branchInfo.branch,detached:branchInfo.detached,isClean,dirtyFileCount:dirty.dirtyFileCount,dirtyFiles:dirty.dirtyFiles,dirtyFilesTruncated:dirty.dirtyFilesTruncated,remotes,remotesTruncated},gate,activeState=null;if(!gateSessionID)gate={active:!1,reason:sessionID?"delegation-chain-uncertain":"no-session-context"};else{let recovery2=resolvedGate?.recovery??null;activeState=recovery2?.state??null;let receiptFiles=activeState?await countCheckoutReceiptFiles(directory,gateSessionID):null;gate=summarizeGate(activeState,receiptFiles,recovery2?{salvaged:recovery2.salvaged,disclosure:recovery2.disclosure}:void 0)}let recovery=activeState?.checkoutRecovery,checkout=recovery?{kind:recovery.code==="GIT_STATE_INDETERMINATE"?"indeterminate":"recovery-required",code:recovery.code,retryable:!1,requiredAction:recovery.requiredAction,evidence:recovery.evidence}:liveCheckout,delegationRead=describeDelegationRead(directory),recoverySection={controllerSessionID:gateSessionID,delegationRead,lastProgress:activeState?{revision:activeState.revision,updatedAt:activeState.updatedAt}:null,wakeSuspension:{suspended:sessionID?_internals310.isPrWorkflowAutoWakeSuppressed(directory,sessionID):!1},actionCircuits:{state:"unavailable"},nextStep:describeRecoveryNextStep(delegationRead.state)},result={success:!0,sessionID,git:git2,checkout,gate,publication:activeState?describePrWorkflowPublicationSection(activeState):null,nextStep:describeNextStep(gate,git2,checkout),recovery:recoverySection};return JSON.stringify(result,null,2)}var pr_workflow_status=createSwarmTool({description:"Read-only architect observation of local git state (HEAD, branch, clean/dirty with a bounded changed-file list, remotes) plus a session-pinned PR workflow gate summary (mode, bound PR head, base ref/sha, depth tier, dispatch/validation batch counts). Use to observe state under the fail-closed PR_REVIEW/PR_FEEDBACK gate. Never executes PR-controlled scripts and never reads another session gate.",args:{},execute:async(_args,directory,ctx)=>executePrWorkflowStatus(directory,ctx?.sessionID)}),_internals310={readPrWorkflowGateStateForRecovery,readDelegationsDetailed,isPrWorkflowAutoWakeSuppressed,resolvePrWorkflowControllerSession,resolveCurrentGitHeadAsync,resolveIsWorkingTreeCleanAsync,runGitCapture:runGitCapture2,classifyGitState:classifyPrWorkflowGitState,truncateToByteBudget,resolveWorkflowGateSession};init_p_limit();init_zod();init_config2();init_manager2();init_utils();init_external_tool_runner();init_filesystem_identity();init_git_executable();init_project_boundary();init_create_tool();init_lint();import*as path363 from"node:path";init_quality_budget();init_sast_scan();init_secretscan();var TOOL_TIMEOUT_MS=60000,MAX_COMBINED_BYTES=500000,MAX_COMPACT_ERROR_BYTES=4096,CANCELLATION_SETTLEMENT_GRACE_MS=1000,MAX_CONCURRENT=4,MAX_FILES=100,GIT_TIMEOUT_MS12=1e4,GIT_MAX_OUTPUT_BYTES2=2000000,ALL_LINES_CHANGED=-1,MAX_CHANGED_LINE_ENTRIES=200000,_internals311={qualityBudget,runLintWrapped,runSecretscanWrapped,runSastScanWrapped,runQualityBudgetWrapped,runWithTimeout:runWithTimeout2,getChangedLineRanges,getChangedLineAmbiguousFiles,saveEvidence,runExternalTool,detectResolvedLinter,runLintOnFiles,platform:()=>process.platform,serializePreCheckResult,resolveGatePreamble,runPreCheckBatch,loadGateOverrides,MAX_COMBINED_BYTES};function formatIncompletePaths(incompletePaths,maxEntries=3){let visible=incompletePaths.slice(0,maxEntries).map((entry)=>{return`${entry.path} (${entry.reason})`}),suffix=incompletePaths.length>maxEntries?` (+${incompletePaths.length-maxEntries} more)`:"";return`${visible.join("; ")}${suffix}`}function evaluateSecretscanGate(toolResult,requestedFiles,classification){if(toolResult.error)return{passed:!1,summary:`Secretscan wrapper error: ${toolResult.error}`,findingsCount:0};if(!toolResult.ran||!toolResult.result)return{passed:!1,summary:"Secretscan did not return a result",findingsCount:0};if("error"in toolResult.result)return{passed:!1,summary:`Secretscan error: ${toolResult.result.error}`,findingsCount:0};let result=toolResult.result;if(typeof result.incomplete_files!=="number"||!Array.isArray(result.incomplete_paths))return{passed:!1,summary:"Secretscan failed: scanner returned incomplete coverage metadata",result,findingsCount:Math.max(result.count,result.findings.length)};let findingsCount=Math.max(result.count,result.findings.length),failures=[],vacuousCoverage=result.files_scanned===0&&typeof result.policy_skipped_files==="number"&&typeof result.requested_files==="number"&&result.requested_files>0&&result.policy_skipped_files>=result.requested_files&&result.count===0&&result.findings.length===0&&result.incomplete_files===0&&result.incomplete_paths.length===0,newFindingsCount=classification?classification.newFindings.length:findingsCount;if(newFindingsCount>0)failures.push(`${newFindingsCount} new secret finding(s) on changed lines`);if(result.truncated===!0)failures.push(`results truncated at ${SECRETSCAN_MAX_FINDINGS} findings`);if(result.incomplete_files>0||result.incomplete_paths.length>0){let incompletePaths=result.incomplete_paths.length>0?`; incomplete paths: ${formatIncompletePaths(result.incomplete_paths)}`:"";failures.push(`${result.incomplete_files} incomplete file(s)${incompletePaths}`)}if(result.count!==result.findings.length)failures.push(`findings/count mismatch (reported ${result.count}, actual ${result.findings.length})`);if(requestedFiles>0&&result.files_scanned===0&&!vacuousCoverage)failures.push(typeof result.ignored_files==="number"&&result.ignored_files>0?`${result.ignored_files} requested file(s) suppressed by .secretscanignore; no file scanned`:"zero requested files scanned");let statistics=`Secretscan: ${findingsCount} finding(s), ${result.files_scanned} files scanned, ${result.skipped_files} skipped`;if(classification)statistics+=`, ${classification.newFindings.length} new secret finding(s) on changed lines (${classification.preexistingFindings.length} pre-existing)`;if(vacuousCoverage)statistics+=`, all ${result.requested_files} requested file(s) skipped by secretscan scan policy (vacuous coverage)`;let passedSummary=classification?.diffScoped?`${statistics}; secretscan green = zero new secrets on changed lines`:statistics;return{passed:failures.length===0,summary:failures.length>0?`${statistics}; failed: ${failures.join("; ")}`:passedSummary,result,findingsCount,...classification&&{newFindingsCount:classification.newFindings.length,preexistingFindingsCount:classification.preexistingFindings.length,diffScoped:classification.diffScoped}}}function truncateUtf8(value,maxBytes){if(Buffer.byteLength(value,"utf8")<=maxBytes)return value;let marker="... (truncated)",budget=Math.max(0,maxBytes-Buffer.byteLength(marker,"utf8")),result="",usedBytes=0;for(let character of value){let characterBytes=Buffer.byteLength(character,"utf8");if(usedBytes+characterBytes>budget)break;result+=character,usedBytes+=characterBytes}return`${result}${marker}`}function compactToolResult(toolResult){return{ran:toolResult.ran,duration_ms:toolResult.duration_ms,...toolResult.error!==void 0&&{error:truncateUtf8(toolResult.error,MAX_COMPACT_ERROR_BYTES)},...toolResult.error===void 0&&toolResult.result!==void 0&&{result_omitted:!0}}}function serializePreCheckResult(result){let serialized3=JSON.stringify(result,null,2);if(Buffer.byteLength(serialized3,"utf8")<=MAX_COMBINED_BYTES)return serialized3;let compact={batch_status:result.batch_status,gates_passed:result.gates_passed,...result.sast_degraded!==void 0&&{sast_degraded:result.sast_degraded},...result.sast_skipped!==void 0&&{sast_skipped:result.sast_skipped},lint:compactToolResult(result.lint),secretscan:compactToolResult(result.secretscan),sast_scan:compactToolResult(result.sast_scan),quality_budget:compactToolResult(result.quality_budget),total_duration_ms:result.total_duration_ms,output_truncated:!0};return JSON.stringify(compact,null,2)}function isWindowsAbsolutePath(inputPath){return/^[A-Za-z]:[/\\]/.test(inputPath)}function validatePath(inputPath,baseDir,workspaceDir){if(typeof inputPath!=="string")return"path must be a string";if(!inputPath||inputPath.trim().length===0)return"path is required";let resolved,isWinAbs=isWindowsAbsolutePath(inputPath);if(isWinAbs)resolved=path363.win32.resolve(inputPath);else if(path363.isAbsolute(inputPath))resolved=path363.resolve(inputPath);else resolved=path363.resolve(baseDir,inputPath);let workspaceResolved=isWindowsAbsolutePath(workspaceDir)?path363.win32.resolve(workspaceDir):path363.resolve(workspaceDir),relative97;if(isWinAbs)relative97=path363.win32.relative(workspaceResolved,resolved);else relative97=path363.relative(workspaceResolved,resolved);if(relative97.startsWith(".."))return"path traversal detected";return null}function isAcceptedProjectRootForPlatform(dir,workspaceDir,platform,hasExplicitBoundary,exactPhysicalRoot=!1){if(exactPhysicalRoot)return!0;let pathApi=platform==="win32"?path363.win32:path363,directoryKey=pathApi.resolve(dir).replace(/\\/g,"/"),workspaceKey=pathApi.resolve(workspaceDir).replace(/\\/g,"/"),normalizedDirectoryKey=platform==="win32"?directoryKey.toLowerCase():directoryKey,normalizedWorkspaceKey=platform==="win32"?workspaceKey.toLowerCase():workspaceKey;if(normalizedDirectoryKey===normalizedWorkspaceKey)return!0;let relative97=pathApi.relative(workspaceDir,dir);return relative97!==""&&relative97!==".."&&!relative97.startsWith(`..${pathApi.sep}`)&&!pathApi.isAbsolute(relative97)&&hasExplicitBoundary}function validateDirectory2(dir,workspaceDir){if(!dir||dir.length===0)return"directory is required";if(dir.length>500)return"directory path too long";let exactPhysicalRoot=sameExistingFilesystemPath(dir,workspaceDir);if(!exactPhysicalRoot){let traversalCheck=validatePath(dir,workspaceDir,workspaceDir);if(traversalCheck)return traversalCheck}let platform=_internals311.platform();if(!isAcceptedProjectRootForPlatform(dir,workspaceDir,platform,hasExplicitProjectBoundary(dir),exactPhysicalRoot))return"directory must resolve to the project root";return null}async function runWithTimeout2(operation,timeoutMs,parentSignal,waitForCancellationSettlement=!1){let controller=new AbortController,timeoutHandle,parentAbortListener;if(parentSignal?.aborted)throw Error("Tool execution cancelled");let parentAbortPromise=new Promise((_,reject3)=>{if(!parentSignal)return;if(parentAbortListener=()=>{reject3(Error("Tool execution cancelled")),controller.abort()},parentSignal.addEventListener("abort",parentAbortListener,{once:!0}),parentSignal.aborted)parentAbortListener()});if(controller.signal.aborted)return await parentAbortPromise;let operationPromise=operation(controller.signal);try{let timeoutPromise=new Promise((_,reject3)=>{timeoutHandle=setTimeout(()=>{reject3(Error(`Timeout after ${timeoutMs}ms`)),controller.abort()},timeoutMs)});return await Promise.race([operationPromise,timeoutPromise,parentAbortPromise])}catch(error93){if(controller.signal.aborted&&waitForCancellationSettlement){let settlementTimer;try{await Promise.race([operationPromise.then(()=>{return},()=>{return}),new Promise((resolve141)=>{settlementTimer=setTimeout(resolve141,CANCELLATION_SETTLEMENT_GRACE_MS)})])}finally{if(settlementTimer!==void 0)clearTimeout(settlementTimer)}}throw error93}finally{if(timeoutHandle!==void 0)clearTimeout(timeoutHandle);if(parentAbortListener&&parentSignal)parentSignal.removeEventListener("abort",parentAbortListener)}}async function runLintWrapped(files,directory,_gates,abortSignal){let start=process.hrtime.bigint();try{let resolvedLinter=await _internals311.detectResolvedLinter(directory,abortSignal);if(!resolvedLinter)return{ran:!1,error:"No linter found (biome or eslint)",duration_ms:Number(process.hrtime.bigint()-start)/1e6};if(files&&files.length>0)return{ran:!0,result:await _internals311.runLintOnFiles(resolvedLinter,files,directory,abortSignal),duration_ms:Number(process.hrtime.bigint()-start)/1e6};return{ran:!0,result:await _internals205.runResolvedLint(resolvedLinter,"check",directory,abortSignal),duration_ms:Number(process.hrtime.bigint()-start)/1e6}}catch(error93){return{ran:!0,error:error93 instanceof Error?error93.message:"Unknown error",duration_ms:Number(process.hrtime.bigint()-start)/1e6}}}async function runLintOnFiles(resolvedLinter,files,workspaceDir,abortSignal){if(resolvedLinter.source==="legacy-test-probe")return _internals205.runResolvedLint(resolvedLinter,"check",workspaceDir,abortSignal);let validatedFiles=[];for(let file3 of files){if(typeof file3!=="string")continue;let resolvedPath=path363.resolve(file3);if(validatePath(resolvedPath,workspaceDir,workspaceDir))continue;validatedFiles.push(resolvedPath)}if(validatedFiles.length===0)return{success:!1,mode:"check",linter:resolvedLinter.linter,command:[],error:"No valid files after security validation"};let args2;if(resolvedLinter.linter==="biome")args2=[...resolvedLinter.argsPrefix,"check",...validatedFiles];else args2=[...resolvedLinter.argsPrefix,...validatedFiles];let command=[...resolvedLinter.displayPrefix,...args2];try{let execution=await _internals311.runExternalTool({executable:resolvedLinter.executable,args:args2,cwd:workspaceDir,timeoutMs:TOOL_TIMEOUT_MS,maxStdoutBytes:512000,maxStderrBytes:512000,abortSignal});if(execution.status!=="completed")return{success:!1,mode:"check",linter:resolvedLinter.linter,command,error:execution.message??`Execution ${execution.status}`};let exitCode=execution.exitCode??1,output=execution.stdout;if(execution.stderr)output+=(output?`
|
|
7794
|
+
`)){let trimmed=line.trim();if(!trimmed)continue;let[name,rest]=trimmed.split(/\s+/,2);if(!name||!rest||byName.has(name))continue;let url3=rest.replace(/\s+\((?:fetch|push)\)\s*$/i,"");byName.set(boundUntrusted(name,64),boundUntrusted(url3,MAX_REMOTE_URL_LEN))}let entries2=[...byName.entries()],remotes=entries2.slice(0,MAX_REMOTES).map(([name,url3])=>({name,url:url3}));return{remotes,remotesTruncated:entries2.length>remotes.length}}async function countCheckoutReceiptFiles(directory,sessionID){try{let receiptDirectory=validateSwarmPath(directory,path362.join(RECEIPT_DIR2,prWorkflowSessionFileStem(sessionID)));return(await fsp12.readdir(receiptDirectory,{withFileTypes:!0})).filter((entry)=>entry.isFile()&&/^[0-9a-f]{40,64}\.json$/i.test(entry.name)).length}catch(error93){if(error93.code==="ENOENT")return 0;return null}}function describeDelegationRead(directory){try{let outcome=_internals310.readDelegationsDetailed(directory);if(outcome.status==="ok")return{state:"ok"};return{state:"uncertain",reasonCode:boundUntrusted(outcome.reason,MAX_RECOVERY_REASON_CODE_LEN)}}catch{return{state:"uncertain",reasonCode:"reader-threw"}}}function describeRecoveryNextStep(delegationReadState){if(delegationReadState==="uncertain")return"Delegation store read is uncertain: repair the store, then re-run pr_workflow_status; if abandoning the workflow, abort via abort_pr_workflow.";return"Re-run pr_workflow_status after any store repair; if abandoning the workflow, abort via abort_pr_workflow."}function describeNextStep(gate,git2,checkout){if(checkout.kind==="recovery-required"||checkout.kind==="indeterminate")return`Manual Git recovery required. code=${checkout.code} retryable=false required_action=${checkout.requiredAction}`;if(!gate.active){if(gate.reason==="delegation-chain-uncertain")return"PR workflow gate ownership could not be resolved from this session delegation chain (cycle, depth limit, or missing ancestor). Treat the workflow state as unknown and use read-only recovery inspection; do not perform PR-workflow writes.";return"No active PR workflow gate for this session. Activate with `/swarm pr-review <pr-ref>` or `/swarm pr-feedback <pr-ref>` before PR-workflow tool calls are admitted."}if(!gate.prHeadBound)return gate.mode==="PR_FEEDBACK"?"PR_FEEDBACK gate active; PR head not yet bound. If the working tree is dirty, preserve it with prepare_pr_workflow_checkout (omit paths to include tracked and untracked changes). Prefer the intended exact tracking checkout, then bind; if this workflow inherited an already-detached exact intake head, bind it directly and the controller will attach the unique exact local/remote tracking ref. Ambiguity or an existing mismatched upstream fails closed.":"PR_REVIEW gate active; PR head not yet bound. If the working tree is dirty, preserve it with prepare_pr_workflow_checkout (omit paths to include tracked and untracked changes), then bind the exact detached PR head.";if(git2.isClean===!1)return`${gate.mode} gate active and head bound, but the working tree is dirty. Read-only observation only; the gate keeps writes and non-tracking fetches fail-closed.`;if(git2.isClean===null)return`${gate.mode} gate active and head bound, but this session could not determine whether the working tree is clean (git status failed). Treat the tree state as unknown and verify manually before assuming it is clean; read-only observation only.`;return`${gate.mode} gate active and head bound. Continue read-only review using the admitted observe/validate tools (diff, gh_evidence, repo_map, lint check, etc.).`}function summarizeGate(state2,receiptFiles,salvage){if(!state2)return{active:!1,reason:"no-active-gate"};return{active:!0,...salvage?.salvaged?{stateSalvaged:!0,stateSalvageDisclosure:salvage.disclosure}:{},mode:state2.mode,prHeadBound:Boolean(state2.prHeadSha),prHeadSha:state2.prHeadSha??null,prFeedbackTargetUrl:state2.prFeedbackTargetUrl?boundUntrusted(state2.prFeedbackTargetUrl,MAX_FIELD_LEN):null,prReviewBaseRef:state2.prReviewBaseRef?boundUntrusted(state2.prReviewBaseRef,MAX_FIELD_LEN):null,prReviewBaseSha:state2.prReviewBaseSha??null,prReviewDepthTier:state2.prReviewDepthTier??null,baseDispatchBatches:state2.prReviewBaseDispatches?.length??0,validationBatches:state2.prReviewValidationBatches?.length??0,feedbackVerificationBatches:state2.prFeedbackVerifications?.length??0,...state2.prFeedbackInventoryAmendments?.length?{inventoryAmendments:state2.prFeedbackInventoryAmendments}:{},checkoutReceiptFiles:receiptFiles,activatedAt:state2.activatedAt,updatedAt:state2.updatedAt,revision:state2.revision}}function boundFindingLine(line){let cleaned=line.replace(/[\p{Cc}]/gu," ").replace(/[`<>]/g," ").replace(/\s+/g," ").trim(),chars=Array.from(cleaned);if(chars.length<=PR_REVIEW_STATUS_FINDING_LINE_MAX)return cleaned;return`${chars.slice(0,PR_REVIEW_STATUS_FINDING_LINE_MAX-1).join("")}…`}async function buildPrReviewProjection(directory,state2,projectionDropped){let settledPhases=new Set(state2.prReviewArtifactBoundaries??[]),runId=state2.prReviewArtifactRunId??null,findingsPath=state2.prReviewFindingsPath??null,digests=state2.prReviewVerdictSettlementDigests??{},boundaries=PR_REVIEW_BOUNDARY_ORDER.map((phase)=>{let settlementPhase=PR_REVIEW_BOUNDARY_SETTLEMENT_PHASE[phase],settled=settledPhases.has(phase);return{phase,status:settled?"settled":"pending",runId,findingsPath,settlementDigest:settled&&settlementPhase?digests[settlementPhase]??null:null}}),declaredLanes=[];for(let batch of state2.prReviewBaseDispatches??[])for(let lane of batch.lanes??[])declaredLanes.push({laneId:lane.laneId,workflowLane:lane.workflowLane,batchId:batch.batchId});let laneCoverageTruncated=declaredLanes.length>PR_REVIEW_STATUS_LANE_ROWS_CAP,emittedLanes=declaredLanes.slice(0,PR_REVIEW_STATUS_LANE_ROWS_CAP),rejectionCounts=new Map;for(let entry of state2.prReviewSubmitRejections??[]){if(!entry.laneId)continue;rejectionCounts.set(entry.laneId,(rejectionCounts.get(entry.laneId)??0)+1)}let receiptsByLane=new Map,uncertainBatches=new Set,headSha=state2.prHeadSha;for(let batchId of new Set(emittedLanes.map((lane)=>lane.batchId)))try{let outcome=_internals310.findByBatchIdDetailed(directory,batchId,{parentSessionId:state2.sessionID});if(outcome.status==="uncertain"){uncertainBatches.add(batchId);continue}for(let record3 of outcome.value){if(record3.laneId==null||record3.mode!=="swarm-pr-review:base")continue;if(record3.workspace?.prHeadSha!==headSha||record3.workspace?.gitHead!==headSha)continue;let receipt=recordedPrReviewResultReceipt(record3);if(!receipt)continue;let key2=`${batchId}\x00${record3.laneId}`;if(!receiptsByLane.has(key2))receiptsByLane.set(key2,receipt)}}catch{uncertainBatches.add(batchId)}let laneCoverage=emittedLanes.map((lane)=>{let uncertain=uncertainBatches.has(lane.batchId),receipt=uncertain?void 0:receiptsByLane.get(`${lane.batchId}\x00${lane.laneId}`),findings=receipt?.envelope.findings??[],lastFinding=findings[findings.length-1],latestFinding=uncertain?"receipt-uncertain":receipt?lastFinding?boundFindingLine(`${lastFinding.severity} ${lastFinding.id}: ${lastFinding.title}`):receipt.envelope.outcome==="CLEAN"?"clean":"incomplete":"no-receipt",findingsTruncated=findings.length>PR_REVIEW_STATUS_FINDINGS_PER_LANE,findingSummaries=findings.slice(0,PR_REVIEW_STATUS_FINDINGS_PER_LANE).map((finding)=>({id:boundUntrusted(finding.id,PR_REVIEW_STATUS_FINDING_ID_MAX),severity:boundUntrusted(finding.severity,PR_REVIEW_STATUS_FINDING_SEVERITY_MAX),title:boundUntrusted(finding.title,PR_REVIEW_STATUS_FINDING_LINE_MAX)}));return{laneId:lane.laneId,workflowLane:lane.workflowLane,batchId:lane.batchId,accepted:findings.length,rejected:rejectionCounts.get(lane.laneId)??0,latestFinding,findings:findingSummaries,findingsTruncated}}),inventory=projectionDropped?{state:"unavailable",reason:SALVAGED_PROJECTION_REASON}:await(async()=>{let derived=await derivePrReviewCandidateInventoryForStatus(directory,state2);if(derived.state==="unavailable")return{state:"unavailable",reason:boundUntrusted(derived.reason,PR_REVIEW_STATUS_FINDING_LINE_MAX)};return{state:"available",ids:derived.inventory.slice(0,PR_REVIEW_STATUS_INVENTORY_CAP).map((id)=>boundUntrusted(id,PR_REVIEW_STATUS_FINDING_ID_MAX)),truncated:derived.inventory.length>PR_REVIEW_STATUS_INVENTORY_CAP,total:derived.inventory.length,cap:PR_REVIEW_STATUS_INVENTORY_CAP}})(),salvagedSource=()=>projectionDropped?{state:"unavailable",reason:SALVAGED_PROJECTION_REASON}:{state:"ok"};return{boundaries,checkpointScope:"shared-last-write-wins",laneCoverage,laneCoverageTruncated,laneCoverageAdmission:"lane-record-only",inventory,sources:{boundaries:salvagedSource(),laneCoverage:salvagedSource()}}}async function resolveWorkflowGate(directory,sessionID){let outcome=await _internals310.resolvePrWorkflowControllerSession({directory,sessionID,readGate:(candidate2)=>_internals310.readPrWorkflowGateStateForRecovery(directory,candidate2)});if(outcome.kind==="gate-owner")return{sessionID:outcome.sessionID,recovery:outcome.gate};if(outcome.kind==="no-gate")return{sessionID:outcome.sessionID,recovery:null};return{sessionID:null,recovery:null}}async function resolveWorkflowGateSession(directory,sessionID){return(await resolveWorkflowGate(directory,sessionID)).sessionID}async function executePrWorkflowStatus(directory,rawSessionID){let sessionID=rawSessionID?.trim()?rawSessionID.trim():null,resolvedGate=sessionID?await resolveWorkflowGate(directory,sessionID):null,gateSessionID=resolvedGate?.sessionID??null,[head2,isClean,branchInfo,porcelain,remoteOutput,liveCheckout]=await Promise.all([_internals310.resolveCurrentGitHeadAsync(directory),_internals310.resolveIsWorkingTreeCleanAsync(directory),resolveBranch(directory),_internals310.runGitCapture(directory,["status","--porcelain=v1","--untracked-files=all"]),_internals310.runGitCapture(directory,["remote","-v"]),_internals310.classifyGitState(directory)]),dirty=parseDirtyFiles(porcelain),{remotes,remotesTruncated}=parseRemotes(remoteOutput),git2={head:head2,branch:branchInfo.branch,detached:branchInfo.detached,isClean,dirtyFileCount:dirty.dirtyFileCount,dirtyFiles:dirty.dirtyFiles,dirtyFilesTruncated:dirty.dirtyFilesTruncated,remotes,remotesTruncated},gate,activeState=null;if(!gateSessionID)gate={active:!1,reason:sessionID?"delegation-chain-uncertain":"no-session-context"};else{let recovery2=resolvedGate?.recovery??null;activeState=recovery2?.state??null;let receiptFiles=activeState?await countCheckoutReceiptFiles(directory,gateSessionID):null;if(gate=summarizeGate(activeState,receiptFiles,recovery2?{salvaged:recovery2.salvaged,disclosure:recovery2.disclosure}:void 0),activeState?.mode==="PR_REVIEW")gate.prReviewProjection=await buildPrReviewProjection(directory,activeState,recovery2?.prReviewProjectionDropped??!1)}let recovery=activeState?.checkoutRecovery,checkout=recovery?{kind:recovery.code==="GIT_STATE_INDETERMINATE"?"indeterminate":"recovery-required",code:recovery.code,retryable:!1,requiredAction:recovery.requiredAction,evidence:recovery.evidence}:liveCheckout,delegationRead=describeDelegationRead(directory),recoverySection={controllerSessionID:gateSessionID,delegationRead,lastProgress:activeState?{revision:activeState.revision,updatedAt:activeState.updatedAt}:null,wakeSuspension:{suspended:sessionID?_internals310.isPrWorkflowAutoWakeSuppressed(directory,sessionID):!1},actionCircuits:{state:"unavailable"},nextStep:describeRecoveryNextStep(delegationRead.state)},result={success:!0,sessionID,git:git2,checkout,gate,publication:activeState?describePrWorkflowPublicationSection(activeState):null,nextStep:describeNextStep(gate,git2,checkout),recovery:recoverySection};return JSON.stringify(result,null,2)}var pr_workflow_status=createSwarmTool({description:"Read-only architect observation of local git state (HEAD, branch, clean/dirty with a bounded changed-file list, remotes) plus a session-pinned PR workflow gate summary (mode, bound PR head, base ref/sha, depth tier, dispatch/validation batch counts) and, for an active PR_REVIEW gate, a bounded projection of boundary settlement, per-lane coverage, and the derived candidate inventory. Use to observe state under the fail-closed PR_REVIEW/PR_FEEDBACK gate. Never executes PR-controlled scripts and never reads another session gate.",args:{},execute:async(_args,directory,ctx)=>executePrWorkflowStatus(directory,ctx?.sessionID)}),_internals310={readPrWorkflowGateStateForRecovery,readDelegationsDetailed,isPrWorkflowAutoWakeSuppressed,resolvePrWorkflowControllerSession,resolveCurrentGitHeadAsync,resolveIsWorkingTreeCleanAsync,runGitCapture:runGitCapture2,classifyGitState:classifyPrWorkflowGitState,truncateToByteBudget,resolveWorkflowGateSession,findByBatchIdDetailed,boundUntrusted,boundFindingLine};init_p_limit();init_zod();init_config2();init_manager2();init_utils();init_external_tool_runner();init_filesystem_identity();init_git_executable();init_project_boundary();init_create_tool();init_lint();import*as path363 from"node:path";init_quality_budget();init_sast_scan();init_secretscan();var TOOL_TIMEOUT_MS=60000,MAX_COMBINED_BYTES=500000,MAX_COMPACT_ERROR_BYTES=4096,CANCELLATION_SETTLEMENT_GRACE_MS=1000,MAX_CONCURRENT=4,MAX_FILES=100,GIT_TIMEOUT_MS12=1e4,GIT_MAX_OUTPUT_BYTES2=2000000,ALL_LINES_CHANGED=-1,MAX_CHANGED_LINE_ENTRIES=200000,_internals311={qualityBudget,runLintWrapped,runSecretscanWrapped,runSastScanWrapped,runQualityBudgetWrapped,runWithTimeout:runWithTimeout2,getChangedLineRanges,getChangedLineAmbiguousFiles,saveEvidence,runExternalTool,detectResolvedLinter,runLintOnFiles,platform:()=>process.platform,serializePreCheckResult,resolveGatePreamble,runPreCheckBatch,loadGateOverrides,MAX_COMBINED_BYTES};function formatIncompletePaths(incompletePaths,maxEntries=3){let visible=incompletePaths.slice(0,maxEntries).map((entry)=>{return`${entry.path} (${entry.reason})`}),suffix=incompletePaths.length>maxEntries?` (+${incompletePaths.length-maxEntries} more)`:"";return`${visible.join("; ")}${suffix}`}function evaluateSecretscanGate(toolResult,requestedFiles,classification){if(toolResult.error)return{passed:!1,summary:`Secretscan wrapper error: ${toolResult.error}`,findingsCount:0};if(!toolResult.ran||!toolResult.result)return{passed:!1,summary:"Secretscan did not return a result",findingsCount:0};if("error"in toolResult.result)return{passed:!1,summary:`Secretscan error: ${toolResult.result.error}`,findingsCount:0};let result=toolResult.result;if(typeof result.incomplete_files!=="number"||!Array.isArray(result.incomplete_paths))return{passed:!1,summary:"Secretscan failed: scanner returned incomplete coverage metadata",result,findingsCount:Math.max(result.count,result.findings.length)};let findingsCount=Math.max(result.count,result.findings.length),failures=[],vacuousCoverage=result.files_scanned===0&&typeof result.policy_skipped_files==="number"&&typeof result.requested_files==="number"&&result.requested_files>0&&result.policy_skipped_files>=result.requested_files&&result.count===0&&result.findings.length===0&&result.incomplete_files===0&&result.incomplete_paths.length===0,newFindingsCount=classification?classification.newFindings.length:findingsCount;if(newFindingsCount>0)failures.push(`${newFindingsCount} new secret finding(s) on changed lines`);if(result.truncated===!0)failures.push(`results truncated at ${SECRETSCAN_MAX_FINDINGS} findings`);if(result.incomplete_files>0||result.incomplete_paths.length>0){let incompletePaths=result.incomplete_paths.length>0?`; incomplete paths: ${formatIncompletePaths(result.incomplete_paths)}`:"";failures.push(`${result.incomplete_files} incomplete file(s)${incompletePaths}`)}if(result.count!==result.findings.length)failures.push(`findings/count mismatch (reported ${result.count}, actual ${result.findings.length})`);if(requestedFiles>0&&result.files_scanned===0&&!vacuousCoverage)failures.push(typeof result.ignored_files==="number"&&result.ignored_files>0?`${result.ignored_files} requested file(s) suppressed by .secretscanignore; no file scanned`:"zero requested files scanned");let statistics=`Secretscan: ${findingsCount} finding(s), ${result.files_scanned} files scanned, ${result.skipped_files} skipped`;if(classification)statistics+=`, ${classification.newFindings.length} new secret finding(s) on changed lines (${classification.preexistingFindings.length} pre-existing)`;if(vacuousCoverage)statistics+=`, all ${result.requested_files} requested file(s) skipped by secretscan scan policy (vacuous coverage)`;let passedSummary=classification?.diffScoped?`${statistics}; secretscan green = zero new secrets on changed lines`:statistics;return{passed:failures.length===0,summary:failures.length>0?`${statistics}; failed: ${failures.join("; ")}`:passedSummary,result,findingsCount,...classification&&{newFindingsCount:classification.newFindings.length,preexistingFindingsCount:classification.preexistingFindings.length,diffScoped:classification.diffScoped}}}function truncateUtf8(value,maxBytes){if(Buffer.byteLength(value,"utf8")<=maxBytes)return value;let marker="... (truncated)",budget=Math.max(0,maxBytes-Buffer.byteLength(marker,"utf8")),result="",usedBytes=0;for(let character of value){let characterBytes=Buffer.byteLength(character,"utf8");if(usedBytes+characterBytes>budget)break;result+=character,usedBytes+=characterBytes}return`${result}${marker}`}function compactToolResult(toolResult){return{ran:toolResult.ran,duration_ms:toolResult.duration_ms,...toolResult.error!==void 0&&{error:truncateUtf8(toolResult.error,MAX_COMPACT_ERROR_BYTES)},...toolResult.error===void 0&&toolResult.result!==void 0&&{result_omitted:!0}}}function serializePreCheckResult(result){let serialized3=JSON.stringify(result,null,2);if(Buffer.byteLength(serialized3,"utf8")<=MAX_COMBINED_BYTES)return serialized3;let compact={batch_status:result.batch_status,gates_passed:result.gates_passed,...result.sast_degraded!==void 0&&{sast_degraded:result.sast_degraded},...result.sast_skipped!==void 0&&{sast_skipped:result.sast_skipped},lint:compactToolResult(result.lint),secretscan:compactToolResult(result.secretscan),sast_scan:compactToolResult(result.sast_scan),quality_budget:compactToolResult(result.quality_budget),total_duration_ms:result.total_duration_ms,output_truncated:!0};return JSON.stringify(compact,null,2)}function isWindowsAbsolutePath(inputPath){return/^[A-Za-z]:[/\\]/.test(inputPath)}function validatePath(inputPath,baseDir,workspaceDir){if(typeof inputPath!=="string")return"path must be a string";if(!inputPath||inputPath.trim().length===0)return"path is required";let resolved,isWinAbs=isWindowsAbsolutePath(inputPath);if(isWinAbs)resolved=path363.win32.resolve(inputPath);else if(path363.isAbsolute(inputPath))resolved=path363.resolve(inputPath);else resolved=path363.resolve(baseDir,inputPath);let workspaceResolved=isWindowsAbsolutePath(workspaceDir)?path363.win32.resolve(workspaceDir):path363.resolve(workspaceDir),relative97;if(isWinAbs)relative97=path363.win32.relative(workspaceResolved,resolved);else relative97=path363.relative(workspaceResolved,resolved);if(relative97.startsWith(".."))return"path traversal detected";return null}function isAcceptedProjectRootForPlatform(dir,workspaceDir,platform,hasExplicitBoundary,exactPhysicalRoot=!1){if(exactPhysicalRoot)return!0;let pathApi=platform==="win32"?path363.win32:path363,directoryKey=pathApi.resolve(dir).replace(/\\/g,"/"),workspaceKey=pathApi.resolve(workspaceDir).replace(/\\/g,"/"),normalizedDirectoryKey=platform==="win32"?directoryKey.toLowerCase():directoryKey,normalizedWorkspaceKey=platform==="win32"?workspaceKey.toLowerCase():workspaceKey;if(normalizedDirectoryKey===normalizedWorkspaceKey)return!0;let relative97=pathApi.relative(workspaceDir,dir);return relative97!==""&&relative97!==".."&&!relative97.startsWith(`..${pathApi.sep}`)&&!pathApi.isAbsolute(relative97)&&hasExplicitBoundary}function validateDirectory2(dir,workspaceDir){if(!dir||dir.length===0)return"directory is required";if(dir.length>500)return"directory path too long";let exactPhysicalRoot=sameExistingFilesystemPath(dir,workspaceDir);if(!exactPhysicalRoot){let traversalCheck=validatePath(dir,workspaceDir,workspaceDir);if(traversalCheck)return traversalCheck}let platform=_internals311.platform();if(!isAcceptedProjectRootForPlatform(dir,workspaceDir,platform,hasExplicitProjectBoundary(dir),exactPhysicalRoot))return"directory must resolve to the project root";return null}async function runWithTimeout2(operation,timeoutMs,parentSignal,waitForCancellationSettlement=!1){let controller=new AbortController,timeoutHandle,parentAbortListener;if(parentSignal?.aborted)throw Error("Tool execution cancelled");let parentAbortPromise=new Promise((_,reject3)=>{if(!parentSignal)return;if(parentAbortListener=()=>{reject3(Error("Tool execution cancelled")),controller.abort()},parentSignal.addEventListener("abort",parentAbortListener,{once:!0}),parentSignal.aborted)parentAbortListener()});if(controller.signal.aborted)return await parentAbortPromise;let operationPromise=operation(controller.signal);try{let timeoutPromise=new Promise((_,reject3)=>{timeoutHandle=setTimeout(()=>{reject3(Error(`Timeout after ${timeoutMs}ms`)),controller.abort()},timeoutMs)});return await Promise.race([operationPromise,timeoutPromise,parentAbortPromise])}catch(error93){if(controller.signal.aborted&&waitForCancellationSettlement){let settlementTimer;try{await Promise.race([operationPromise.then(()=>{return},()=>{return}),new Promise((resolve141)=>{settlementTimer=setTimeout(resolve141,CANCELLATION_SETTLEMENT_GRACE_MS)})])}finally{if(settlementTimer!==void 0)clearTimeout(settlementTimer)}}throw error93}finally{if(timeoutHandle!==void 0)clearTimeout(timeoutHandle);if(parentAbortListener&&parentSignal)parentSignal.removeEventListener("abort",parentAbortListener)}}async function runLintWrapped(files,directory,_gates,abortSignal){let start=process.hrtime.bigint();try{let resolvedLinter=await _internals311.detectResolvedLinter(directory,abortSignal);if(!resolvedLinter)return{ran:!1,error:"No linter found (biome or eslint)",duration_ms:Number(process.hrtime.bigint()-start)/1e6};if(files&&files.length>0)return{ran:!0,result:await _internals311.runLintOnFiles(resolvedLinter,files,directory,abortSignal),duration_ms:Number(process.hrtime.bigint()-start)/1e6};return{ran:!0,result:await _internals205.runResolvedLint(resolvedLinter,"check",directory,abortSignal),duration_ms:Number(process.hrtime.bigint()-start)/1e6}}catch(error93){return{ran:!0,error:error93 instanceof Error?error93.message:"Unknown error",duration_ms:Number(process.hrtime.bigint()-start)/1e6}}}async function runLintOnFiles(resolvedLinter,files,workspaceDir,abortSignal){if(resolvedLinter.source==="legacy-test-probe")return _internals205.runResolvedLint(resolvedLinter,"check",workspaceDir,abortSignal);let validatedFiles=[];for(let file3 of files){if(typeof file3!=="string")continue;let resolvedPath=path363.resolve(file3);if(validatePath(resolvedPath,workspaceDir,workspaceDir))continue;validatedFiles.push(resolvedPath)}if(validatedFiles.length===0)return{success:!1,mode:"check",linter:resolvedLinter.linter,command:[],error:"No valid files after security validation"};let args2;if(resolvedLinter.linter==="biome")args2=[...resolvedLinter.argsPrefix,"check",...validatedFiles];else args2=[...resolvedLinter.argsPrefix,...validatedFiles];let command=[...resolvedLinter.displayPrefix,...args2];try{let execution=await _internals311.runExternalTool({executable:resolvedLinter.executable,args:args2,cwd:workspaceDir,timeoutMs:TOOL_TIMEOUT_MS,maxStdoutBytes:512000,maxStderrBytes:512000,abortSignal});if(execution.status!=="completed")return{success:!1,mode:"check",linter:resolvedLinter.linter,command,error:execution.message??`Execution ${execution.status}`};let exitCode=execution.exitCode??1,output=execution.stdout;if(execution.stderr)output+=(output?`
|
|
7793
7795
|
`:"")+execution.stderr;if(execution.stdoutTruncated||execution.stderrTruncated)output+=`
|
|
7794
7796
|
... (output truncated)`;let result={success:!0,mode:"check",linter:resolvedLinter.linter,command,exitCode,output};if(exitCode===0)result.message=`${resolvedLinter.linter} check completed successfully with no issues`;else if(resolvedLinter.linter==="biome"&&output.includes("No files were processed"))result.message=`${resolvedLinter.linter} check processed no files (all specified paths ignored by biome configuration)`;else result.message=`${resolvedLinter.linter} check found issues (exit code ${exitCode}).`;return result}catch(error93){return{success:!1,mode:"check",linter:resolvedLinter.linter,command,error:error93 instanceof Error?`Execution failed: ${error93.message}`:"Execution failed: unknown error"}}}async function runSecretscanWrapped(files,directory,_gates,abortSignal,rawRequestedFiles){let start=process.hrtime.bigint();try{if(files&&files.length>0)return{ran:!0,result:await runWithTimeout2(()=>runSecretscanOnFiles(files,directory,rawRequestedFiles),TOOL_TIMEOUT_MS,abortSignal),duration_ms:Number(process.hrtime.bigint()-start)/1e6};return{ran:!0,result:await runWithTimeout2(()=>runSecretscan(directory),TOOL_TIMEOUT_MS,abortSignal,!0),duration_ms:Number(process.hrtime.bigint()-start)/1e6}}catch(error93){return{ran:!0,error:error93 instanceof Error?error93.message:"Unknown error",duration_ms:Number(process.hrtime.bigint()-start)/1e6}}}async function runSastScanWrapped(changedFiles,directory,severityThreshold,gates,phase,abortSignal){let start=process.hrtime.bigint();try{return{ran:!0,result:await runWithTimeout2((signal2)=>sastScan({changed_files:changedFiles,severity_threshold:severityThreshold,phase,abort_signal:signal2},directory,gates),TOOL_TIMEOUT_MS,abortSignal,!0),duration_ms:Number(process.hrtime.bigint()-start)/1e6}}catch(error93){return{ran:!0,error:error93 instanceof Error?error93.message:"Unknown error",duration_ms:Number(process.hrtime.bigint()-start)/1e6}}}async function runQualityBudgetWrapped(changedFiles,directory,gates,abortSignal){let start=process.hrtime.bigint();try{return{ran:!0,result:await runWithTimeout2((signal2)=>_internals311.qualityBudget({changed_files:changedFiles,config:gates?.quality_budget},directory,signal2),TOOL_TIMEOUT_MS,abortSignal,!0),duration_ms:Number(process.hrtime.bigint()-start)/1e6}}catch(error93){return{ran:!0,error:error93 instanceof Error?error93.message:"Unknown error",duration_ms:Number(process.hrtime.bigint()-start)/1e6}}}var GATE_SEVERITIES=new Set(["high","critical"]),SEVERITY_ORDER_PCB={low:0,medium:1,high:2,critical:3};function meetsThresholdForTriage(severity2,threshold){return(SEVERITY_ORDER_PCB[severity2]??0)>=(SEVERITY_ORDER_PCB[threshold]??1)}async function runGit8(args2,directory,abortSignal){let gitExecutable;try{gitExecutable=await resolveGitExecutableAsync()}catch{return null}let result=await _internals311.runExternalTool({executable:gitExecutable,args:args2,cwd:directory,timeoutMs:GIT_TIMEOUT_MS12,maxStdoutBytes:GIT_MAX_OUTPUT_BYTES2,maxStderrBytes:64000,abortSignal});if(result.status!=="completed"||result.exitCode!==0||result.stdoutTruncated)return null;return result.stdout}function decodeGitQuotedPath(value){if(!value.startsWith('"'))return value;if(!value.endsWith('"'))return null;let bytes=[],appendText=(text)=>{bytes.push(...Buffer.from(text,"utf8"))};for(let index=1;index<value.length-1;index++){let codePoint=value.codePointAt(index);if(codePoint===void 0)return null;let char=String.fromCodePoint(codePoint);if(char!=="\\"){if(appendText(char),char.length===2)index++;continue}if(index++,index>=value.length-1)return null;let escaped=value[index],simple={"\\":"\\",'"':'"',t:"\t",n:`
|
|
7795
7797
|
`,r:"\r",b:"\b",f:"\f",v:"\v"};if(simple[escaped]!==void 0){appendText(simple[escaped]);continue}if(/[0-7]/.test(escaped)){let octal=escaped;for(let count4=0;count4<2;count4++){let next=value[index+1];if(!next||!/[0-7]/.test(next))break;octal+=next,index++}bytes.push(Number.parseInt(octal,8));continue}return null}return Buffer.from(bytes).toString("utf8")}function normalizeRepoPathKey(repoPath){let normalized=repoPath.replace(/\\/g,"/");return _internals311.platform()==="win32"||_internals311.platform()==="darwin"?normalized.toLowerCase():normalized}function normalizeDiffPath(rawPath){let pathToken=rawPath.startsWith('"')?rawPath:rawPath.split("\t",1)[0],decoded=decodeGitQuotedPath(pathToken);if(decoded===null||decoded==="/dev/null"||decoded.trim().length===0)return null;return normalizeRepoPathKey(decoded)}function parseDiffLineRangesChecked(diffOutput,requireGitFileHeaders){let result=new Map,currentFile=null,inGitFile=!1,expectingDestination=!1,destinationSeen=!1,destinationNeedsHunk=!1,collectedLines=0;for(let rawLine of diffOutput.split(/\r?\n/)){let line=rawLine.endsWith("\r")?rawLine.slice(0,-1):rawLine;if(line.startsWith("diff --git ")){if(expectingDestination||destinationNeedsHunk)return null;inGitFile=!0,currentFile=null,expectingDestination=!1,destinationSeen=!1;continue}if(line.startsWith("--- ")&&(inGitFile||!requireGitFileHeaders)){if(expectingDestination||destinationNeedsHunk)return null;expectingDestination=!0;continue}if(line.startsWith("+++ ")){if(requireGitFileHeaders&&(!inGitFile||!expectingDestination))return null;let rawDestination=line.slice(4);if(currentFile=normalizeDiffPath(rawDestination),currentFile===null&&rawDestination.trim()!=="/dev/null")return null;if(expectingDestination=!1,destinationSeen=!0,destinationNeedsHunk=!0,!currentFile)continue;if(!result.has(currentFile))result.set(currentFile,new Set);continue}if(!line.startsWith("@@"))continue;if(expectingDestination||requireGitFileHeaders&&(!inGitFile||!destinationSeen))return null;let match=/^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/.exec(line);if(!match)return null;let start=Number.parseInt(match[1],10),count4=match[2]!==void 0?Number.parseInt(match[2],10):1;if(!Number.isSafeInteger(start)||!Number.isSafeInteger(count4)||count4<0||count4>0&&start<1||count4>MAX_CHANGED_LINE_ENTRIES||start+count4-1>Number.MAX_SAFE_INTEGER||collectedLines+count4>MAX_CHANGED_LINE_ENTRIES)return null;if(destinationNeedsHunk=!1,!currentFile)continue;let lines=result.get(currentFile);if(!lines)return null;for(let index=0;index<count4;index++)lines.add(start+index);collectedLines+=count4}if(expectingDestination||destinationNeedsHunk)return null;return result}function mergeChangedLines(target,source){for(let[file3,sourceLines]of source){let targetLines=target.get(file3)??new Set;for(let line of sourceLines)targetLines.add(line);target.set(file3,targetLines)}}function parseUntrackedStatus(output){if(output.length>0&&!output.endsWith("\x00"))return null;let untracked=[],records=output.split("\x00");for(let index=0;index<records.length-1;index++){let record3=records[index];if(!record3||record3.length<4||record3[2]!==" ")return null;let status2=record3.slice(0,2),filePath=record3.slice(3);if(!filePath||!isKnownPorcelainStatus(status2))return null;if(status2==="??"||status2==="!!")untracked.push(normalizeRepoPathKey(filePath));if(/[RC]/.test(status2)){let sourcePath=records[++index];if(!sourcePath||looksLikePorcelainStatusRecord(sourcePath))return null}}return untracked}function isKnownPorcelainStatus(status2){if(status2==="??"||status2==="!!")return!0;if(/U/.test(status2))return new Set(["DD","AU","UD","UA","DU","AA","UU"]).has(status2);return status2!==" "&&/^[ MTADRC]{2}$/.test(status2)}function looksLikePorcelainStatusRecord(value){return value.length>=4&&value[2]===" "&&isKnownPorcelainStatus(value.slice(0,2))}async function getChangedLineAmbiguousFiles(directory,abortSignal,requestedFiles=[]){let mergeBase=null;for(let baseBranch of["zaxbyhub/main","upstream/main","origin/main","main","origin/master","master"]){let candidate2=(await runGit8(["merge-base",baseBranch,"HEAD"],directory,abortSignal))?.trim();if(candidate2&&/^[0-9a-f]{40,64}$/i.test(candidate2)){mergeBase=candidate2;break}}if(!mergeBase)return null;let headSha=(await runGit8(["rev-parse","HEAD"],directory,abortSignal))?.trim();if(typeof headSha==="string"&&/^[0-9a-f]{40,64}$/i.test(headSha)&&headSha.toLowerCase()===mergeBase.toLowerCase())return null;let literalPathspecs=requestedFiles.map((file3)=>path363.relative(directory,file3).replace(/\\/g,"/")).filter((file3)=>file3.length>0&&file3!==".."&&!file3.startsWith("../")).map((file3)=>`:(literal)${file3}`),statusArgs=["-c","core.quotePath=false","status","--porcelain=v1","-z","--untracked-files=all",...literalPathspecs.length>0?["--",...literalPathspecs]:[]],[committedNames,status2]=await Promise.all([runGit8(["-c","core.quotePath=false","diff","--name-only","--no-ext-diff","--no-color","--no-prefix","-z",`${mergeBase}..HEAD`,"--",...literalPathspecs.length>0?literalPathspecs:[]],directory,abortSignal),runGit8(statusArgs,directory,abortSignal)]);if(committedNames===null||status2===null)return null;let committed=new Set(committedNames.split("\x00").filter(Boolean).map(normalizeRepoPathKey)),staged=new Set,unstaged=new Set;if(status2.length>0&&!status2.endsWith("\x00"))return null;let records=status2.split("\x00");for(let index=0;index<records.length-1;index++){let record3=records[index];if(!record3||record3.length<4||record3[2]!==" ")return null;let statusCode=record3.slice(0,2),filePath=record3.slice(3);if(!filePath||!isKnownPorcelainStatus(statusCode))return null;if(statusCode!=="??"&&statusCode!=="!!"){let key2=normalizeRepoPathKey(filePath);if(/[MADRCU]/.test(statusCode[0]))staged.add(key2);if(/[MADRCU]/.test(statusCode[1]))unstaged.add(key2)}if(/[RC]/.test(statusCode)){let sourcePath=records[++index];if(!sourcePath||looksLikePorcelainStatusRecord(sourcePath))return null}}let ambiguous=new Set;for(let key2 of committed)if(staged.has(key2)||unstaged.has(key2))ambiguous.add(key2);for(let key2 of staged)if(unstaged.has(key2))ambiguous.add(key2);return ambiguous}async function getChangedLineRanges(directory,abortSignal,requestedFiles=[]){let mergeBase=null;for(let baseBranch of["zaxbyhub/main","upstream/main","origin/main","main","origin/master","master"]){let candidate2=(await runGit8(["merge-base",baseBranch,"HEAD"],directory,abortSignal))?.trim();if(candidate2&&/^[0-9a-f]{40,64}$/i.test(candidate2)){mergeBase=candidate2;break}}if(!mergeBase)return null;let commonDiffArgs=["-c","core.quotePath=false","diff","--no-ext-diff","--no-color","--no-prefix","-U0"],requestedPathspecs=requestedFiles.map((file3)=>path363.relative(directory,file3).replace(/\\/g,"/")).filter((file3)=>file3.length>0&&file3!==".."&&!file3.startsWith("../")),statusArgs=["-c","core.quotePath=false","status","--porcelain=v1","-z","--untracked-files=all",...requestedPathspecs.length>0?["--ignored=matching"]:[],...requestedPathspecs.length>0?["--",...requestedPathspecs]:[]],[committed,staged,unstaged,status2]=await Promise.all([runGit8([...commonDiffArgs,`${mergeBase}..HEAD`,"--"],directory,abortSignal),runGit8([...commonDiffArgs,"--cached","HEAD","--"],directory,abortSignal),runGit8([...commonDiffArgs,"--"],directory,abortSignal),runGit8(statusArgs,directory,abortSignal)]);if(committed===null||staged===null||unstaged===null||status2===null)return null;let committedLines=parseDiffLineRangesChecked(committed,!0),stagedLines=parseDiffLineRangesChecked(staged,!0),unstagedLines=parseDiffLineRangesChecked(unstaged,!0);if(!committedLines||!stagedLines||!unstagedLines)return null;let result=new Map;mergeChangedLines(result,committedLines),mergeChangedLines(result,stagedLines),mergeChangedLines(result,unstagedLines);let untracked=parseUntrackedStatus(status2);if(untracked===null)return null;let requestedKeys=requestedPathspecs.map(normalizeRepoPathKey);for(let file3 of untracked)if(result.set(file3,new Set([ALL_LINES_CHANGED])),file3.endsWith("/")){for(let requestedFile of requestedKeys)if(requestedFile.startsWith(file3))result.set(requestedFile,new Set([ALL_LINES_CHANGED]))}return result}function classifySastFindings(findings,changedLineRanges,directory){if(!changedLineRanges)return{newFindings:findings,preexistingFindings:[]};let newFindings=[],preexistingFindings=[],pathApi=_internals311.platform()==="win32"?path363.win32:path363.posix,resolvedDirectory=pathApi.resolve(directory);for(let finding of findings){let filePath=finding.location.file,normalised;try{if(typeof filePath!=="string"||filePath.length===0||filePath.includes("\x00")){newFindings.push(finding);continue}let resolvedFinding=pathApi.isAbsolute(filePath)?pathApi.resolve(filePath):pathApi.resolve(resolvedDirectory,filePath),relative97=pathApi.relative(resolvedDirectory,resolvedFinding);if(pathApi.isAbsolute(relative97)||relative97===".."||relative97.startsWith(`..${pathApi.sep}`)){newFindings.push(finding);continue}normalised=normalizeRepoPathKey(relative97)}catch{newFindings.push(finding);continue}let changedLines=changedLineRanges.get(normalised);if(changedLines?.has(ALL_LINES_CHANGED)||changedLines?.has(finding.location.line))newFindings.push(finding);else preexistingFindings.push(finding)}return{newFindings,preexistingFindings}}function classifySecretFindings(findings,changedLineRanges,directory,ambiguousFiles){if(!changedLineRanges)return{newFindings:findings,preexistingFindings:[]};let newFindings=[],preexistingFindings=[],pathApi=_internals311.platform()==="win32"?path363.win32:path363.posix,resolvedDirectory=pathApi.resolve(directory);for(let finding of findings){let{path:filePath,line}=finding;if(typeof filePath!=="string"||filePath.length===0||filePath.includes("\x00")||typeof line!=="number"||!Number.isSafeInteger(line)||line<1){newFindings.push(finding);continue}let changedLines;try{let resolvedFinding=pathApi.isAbsolute(filePath)?pathApi.resolve(filePath):pathApi.resolve(resolvedDirectory,filePath),relative97=pathApi.relative(resolvedDirectory,resolvedFinding);if(pathApi.isAbsolute(relative97)||relative97===".."||relative97.startsWith(`..${pathApi.sep}`)){newFindings.push(finding);continue}let normalised=normalizeRepoPathKey(relative97);if(ambiguousFiles?.has(normalised)){newFindings.push(finding);continue}changedLines=changedLineRanges.get(normalised)}catch{newFindings.push(finding);continue}if(changedLines!==void 0&&changedLines.size>0&&!changedLines.has(ALL_LINES_CHANGED)&&!changedLines.has(line))preexistingFindings.push(finding);else newFindings.push(finding)}return{newFindings,preexistingFindings}}async function runPreCheckBatch(input,workspaceDir,contextDir,abortSignal){let effectiveWorkspaceDir=workspaceDir||input.directory||contextDir,{files,directory,sast_threshold="medium",gates:gatesOverrides,phase,sast_enabled=!0}=input,gates=gatesOverrides??(input.config?.gates?{sast_scan:input.config.gates.sast_scan,quality_budget:input.config.gates.quality_budget}:void 0),dirError=validateDirectory2(directory,effectiveWorkspaceDir);if(dirError)return warn(`pre_check_batch: Invalid directory: ${dirError}`),{batch_status:"invalid",gates_passed:!1,lint:{ran:!1,error:dirError,duration_ms:0},secretscan:{ran:!1,error:dirError,duration_ms:0},sast_scan:{ran:!1,error:dirError,duration_ms:0},quality_budget:{ran:!1,error:dirError,duration_ms:0},total_duration_ms:0};if(!files||files.length===0)return warn("pre_check_batch: No files provided, skipping all tools (fail-closed)"),{batch_status:"invalid",gates_passed:!1,lint:{ran:!1,error:"No files provided",duration_ms:0},secretscan:{ran:!1,error:"No files provided",duration_ms:0},sast_scan:{ran:!1,error:"No files provided",duration_ms:0},quality_budget:{ran:!1,error:"No files provided",duration_ms:0},total_duration_ms:0};let changedFiles=[],rawDeclaredCount=files.length;for(let file3 of files){if(typeof file3!=="string"){warn(`pre_check_batch: Non-string file entry rejected: ${String(file3)}`);continue}if(validatePath(file3,directory,effectiveWorkspaceDir)){warn(`pre_check_batch: Invalid file path: ${file3}`);continue}changedFiles.push(path363.resolve(directory,file3))}if(changedFiles.length===0)return warn("pre_check_batch: No valid files after validation, skipping all tools (fail-closed)"),{batch_status:"invalid",gates_passed:!1,lint:{ran:!1,error:"No files provided",duration_ms:0},secretscan:{ran:!1,error:"No files provided",duration_ms:0},sast_scan:{ran:!1,error:"No files provided",duration_ms:0},quality_budget:{ran:!1,error:"No files provided",duration_ms:0},total_duration_ms:0};try{assertProjectRoot(directory)}catch(error93){let rootError=error93 instanceof Error?error93.message:String(error93);return warn(`pre_check_batch: Project-root validation failed: ${rootError}`),{batch_status:"invalid",gates_passed:!1,lint:{ran:!1,error:rootError,duration_ms:0},secretscan:{ran:!1,error:rootError,duration_ms:0},sast_scan:{ran:!1,error:rootError,duration_ms:0},quality_budget:{ran:!1,error:rootError,duration_ms:0},total_duration_ms:0}}if(changedFiles.length>MAX_FILES)throw Error(`Input exceeds maximum file count: ${changedFiles.length} > ${MAX_FILES}`);let limit=pLimit(MAX_CONCURRENT),sastDisabledByConfig=gates?.sast_scan?.enabled===!1,[lintResult,secretscanResult,sastScanResult,qualityBudgetResult]=await Promise.all([limit(()=>_internals311.runLintWrapped(changedFiles,directory,gates,abortSignal)),limit(()=>_internals311.runSecretscanWrapped(changedFiles,directory,gates,abortSignal,rawDeclaredCount)),sast_enabled&&!sastDisabledByConfig?limit(()=>_internals311.runSastScanWrapped(changedFiles,directory,sast_threshold,gates,phase,abortSignal)):Promise.resolve({ran:!1,duration_ms:0}),limit(()=>_internals311.runQualityBudgetWrapped(changedFiles,directory,gates,abortSignal))]),totalDuration=lintResult.duration_ms+secretscanResult.duration_ms+sastScanResult.duration_ms+qualityBudgetResult.duration_ms,gatesPassed=!0;if(lintResult.ran&&lintResult.result){let lintRes=lintResult.result;if("success"in lintRes&&lintRes.success===!1)warn("pre_check_batch: Lint found issues (informational only)")}else if(lintResult.error)warn(`pre_check_batch: Lint error (informational only): ${lintResult.error}`);let changedLineRangesMemo,getChangedLineRangesMemoized=async()=>{if(changedLineRangesMemo===void 0)changedLineRangesMemo=await _internals311.getChangedLineRanges(directory,abortSignal,changedFiles);return changedLineRangesMemo},secretscanClassification,secretscanPreexistingFindings,secretscanScanFindings=secretscanResult.ran&&secretscanResult.result&&!("error"in secretscanResult.result)?secretscanResult.result.findings:[];if(secretscanScanFindings.length>0){let changedLineRanges=await getChangedLineRangesMemoized(),ambiguousFiles=await _internals311.getChangedLineAmbiguousFiles(directory,abortSignal,changedFiles);if(ambiguousFiles===null)secretscanClassification={newFindings:secretscanScanFindings,preexistingFindings:[],diffScoped:!1};else{let{newFindings,preexistingFindings}=classifySecretFindings(secretscanScanFindings,changedLineRanges,directory,ambiguousFiles);if(secretscanClassification={newFindings,preexistingFindings,diffScoped:changedLineRanges!==null},preexistingFindings.length>0)secretscanPreexistingFindings=preexistingFindings,warn(`pre_check_batch: Secretscan found ${preexistingFindings.length} pre-existing secret finding(s) on unchanged lines - visible, non-gating, passed to reviewer for triage`)}}let secretscanDecision=evaluateSecretscanGate(secretscanResult,rawDeclaredCount,secretscanClassification);if(!secretscanDecision.passed)gatesPassed=!1,warn(`pre_check_batch: ${secretscanDecision.summary} - GATE FAILED`);if(secretscanResult.ran||secretscanResult.error)try{let scanResult=secretscanDecision.result,secretscanEvidence={task_id:"secretscan",type:"secretscan",timestamp:new Date().toISOString(),agent:"pre_check_batch",verdict:secretscanDecision.passed?"pass":"fail",summary:secretscanDecision.summary,findings_count:secretscanDecision.findingsCount,scan_directory:scanResult?.scan_dir??directory,files_scanned:scanResult?.files_scanned??0,skipped_files:scanResult?.skipped_files??0,ignored_files:scanResult?.ignored_files??0,policy_skipped_files:scanResult?.policy_skipped_files??0,requested_files:scanResult?.requested_files??rawDeclaredCount,new_findings_count:secretscanDecision.newFindingsCount??0,preexisting_findings_count:secretscanDecision.preexistingFindingsCount??0,diff_scoped:secretscanDecision.diffScoped??!1,incomplete_files:scanResult?.incomplete_files??changedFiles.length,incomplete_paths:scanResult?.incomplete_paths??[{path:".",reason:"missing_coverage_metadata"}]};await _internals311.saveEvidence(directory,"secretscan",secretscanEvidence,abortSignal)}catch(e){let persistError=`Failed to persist secretscan evidence: ${e instanceof Error?e.message:String(e)}`;secretscanResult.error=persistError,gatesPassed=!1,warn(`pre_check_batch: ${persistError} - GATE FAILED`)}let sastPreexistingFindings,sastDegraded=!1;if(sastScanResult.ran&&sastScanResult.result){let sastResult=sastScanResult.result;if(sastResult.error)if(sastResult.failure_kind==="semgrep_process_exit"&&sastResult.findings.length===0)sastDegraded=!0,warn(`pre_check_batch: SAST coverage degraded (${sastResult.error}) - continuing without a gate failure`);else gatesPassed=!1,warn(`pre_check_batch: SAST scan error (${sastResult.error}) - GATE FAILED`);else if(sastResult.baseline_used){let sastCarryFindings=[...sastResult.pre_existing_findings??[],...sastResult.moved_findings??[]];if(sastCarryFindings.length>0){if(sastPreexistingFindings=sastCarryFindings.filter((f)=>meetsThresholdForTriage(f.severity,sast_threshold)),sastPreexistingFindings.length>0)warn(`pre_check_batch: SAST baseline diff found ${sastPreexistingFindings.length} pre-existing/moved finding(s) - passing to reviewer for triage`)}if(sastResult.verdict==="fail")gatesPassed=!1,warn("pre_check_batch: SAST scan found new findings above threshold - GATE FAILED")}else if(sastResult.verdict==="fail"){let gateFindings=sastResult.findings.filter((f)=>GATE_SEVERITIES.has(f.severity));if(gateFindings.length>0){let changedLineRanges=await getChangedLineRangesMemoized(),{newFindings,preexistingFindings}=classifySastFindings(gateFindings,changedLineRanges,directory);if(newFindings.length>0)gatesPassed=!1,warn(`pre_check_batch: SAST scan found ${newFindings.length} new HIGH/CRITICAL finding(s) on changed lines - GATE FAILED`);else if(preexistingFindings.length>0)sastPreexistingFindings=preexistingFindings,warn(`pre_check_batch: SAST scan found ${preexistingFindings.length} pre-existing HIGH/CRITICAL finding(s) on unchanged lines - passing to reviewer for triage`)}else gatesPassed=!1,warn("pre_check_batch: SAST scan found vulnerabilities - GATE FAILED")}}else if(sastScanResult.error)gatesPassed=!1,warn(`pre_check_batch: SAST scan error - GATE FAILED: ${sastScanResult.error}`);if(qualityBudgetResult.ran&&qualityBudgetResult.result){if(qualityBudgetResult.result.verdict==="fail")warn("pre_check_batch: Quality budget exceeded (informational only)")}else if(qualityBudgetResult.error)warn(`pre_check_batch: Quality budget error (informational only): ${qualityBudgetResult.error}`);return{batch_status:[lintResult,secretscanResult,sastScanResult,qualityBudgetResult].every((toolResult)=>toolResult.ran===!1)?"skipped":"completed",gates_passed:gatesPassed,lint:lintResult,secretscan:secretscanResult,sast_scan:sastScanResult,quality_budget:qualityBudgetResult,total_duration_ms:Math.round(totalDuration),...sastDegraded&&{sast_degraded:!0},...(!sast_enabled||sastDisabledByConfig)&&{sast_skipped:!0},...sastPreexistingFindings&&sastPreexistingFindings.length>0&&{sast_preexisting_findings:sastPreexistingFindings},...secretscanPreexistingFindings&&secretscanPreexistingFindings.length>0&&{secretscan_preexisting_findings:secretscanPreexistingFindings}}}var pre_check_batch=createSwarmTool({allowWorkingDirectoryOverride:!0,description:"Run multiple verification tools in parallel: lint, secretscan, SAST scan, and quality budget. Returns unified result with gates_passed status. Security findings and incomplete SAST runs are hard failures; a Semgrep nonzero process exit with zero findings is returned as explicit sast_degraded coverage and does not block.",args:{files:exports_external.array(exports_external.string()).optional().describe("Specific files to check (optional, scans directory if not provided)"),directory:exports_external.string().describe("Project root directory — ordinary workspace subdirectories are rejected; direct .git or .opencode project boundaries are accepted"),sast_threshold:exports_external.enum(["low","medium","high","critical"]).optional().describe("Minimum severity for SAST findings to cause failure (default: medium)"),phase:exports_external.number().int().min(1).optional().describe("Current phase number (positive integer >= 1). When provided, enables SAST baseline diffing: only findings absent from the phase-scoped baseline fail the gate.")},async execute(args2,directory,ctx){if(!args2||typeof args2!=="object")return serializePreCheckResult({batch_status:"invalid",gates_passed:!1,lint:{ran:!1,error:"Invalid arguments",duration_ms:0},secretscan:{ran:!1,error:"Invalid arguments",duration_ms:0},sast_scan:{ran:!1,error:"Invalid arguments",duration_ms:0},quality_budget:{ran:!1,error:"Invalid arguments",duration_ms:0},total_duration_ms:0});if(!directory||typeof directory!=="string"||directory.trim()==="")return serializePreCheckResult({batch_status:"invalid",gates_passed:!1,lint:{ran:!1,error:"project directory is required but was not provided",duration_ms:0},secretscan:{ran:!1,error:"project directory is required but was not provided",duration_ms:0},sast_scan:{ran:!1,error:"project directory is required but was not provided",duration_ms:0},quality_budget:{ran:!1,error:"project directory is required but was not provided",duration_ms:0},total_duration_ms:0});let typedArgs=args2;if(!typedArgs.directory)return serializePreCheckResult({batch_status:"invalid",gates_passed:!1,lint:{ran:!1,error:"directory is required",duration_ms:0},secretscan:{ran:!1,error:"directory is required",duration_ms:0},sast_scan:{ran:!1,error:"directory is required",duration_ms:0},quality_budget:{ran:!1,error:"directory is required",duration_ms:0},total_duration_ms:0});let resolvedDirectory=path363.resolve(typedArgs.directory),workspaceAnchor=path363.resolve(directory);if(isStrictPathDescendant(resolvedDirectory,workspaceAnchor)&&!hasExplicitProjectBoundary(resolvedDirectory)){let subDirError=`directory "${typedArgs.directory}" is a subdirectory of the project root — pre_check_batch requires the project root directory "${workspaceAnchor}"`;return serializePreCheckResult({batch_status:"invalid",gates_passed:!1,lint:{ran:!1,error:subDirError,duration_ms:0},secretscan:{ran:!1,error:subDirError,duration_ms:0},sast_scan:{ran:!1,error:subDirError,duration_ms:0},quality_budget:{ran:!1,error:subDirError,duration_ms:0},total_duration_ms:0})}let dirError=validateDirectory2(resolvedDirectory,workspaceAnchor);if(dirError)return serializePreCheckResult({batch_status:"invalid",gates_passed:!1,lint:{ran:!1,error:dirError,duration_ms:0},secretscan:{ran:!1,error:dirError,duration_ms:0},sast_scan:{ran:!1,error:dirError,duration_ms:0},quality_budget:{ran:!1,error:dirError,duration_ms:0},total_duration_ms:0});try{let sastEnabled=!0;try{let preamble=await _internals311.resolveGatePreamble(resolvedDirectory,ctx?.sessionID);if(preamble.resolved&&preamble.effectiveGates)sastEnabled=preamble.effectiveGates.sast_enabled}catch{warn("pre_check_batch: QA-gate profile resolution failed; keeping SAST enabled")}let rawPhase=typedArgs.phase,safePhase=typeof rawPhase==="number"&&Number.isInteger(rawPhase)&&rawPhase>=1?rawPhase:void 0,result=await _internals311.runPreCheckBatch({files:typedArgs.files,directory:resolvedDirectory,sast_threshold:typedArgs.sast_threshold,config:typedArgs.config,gates:_internals311.loadGateOverrides(resolvedDirectory),phase:safePhase,sast_enabled:sastEnabled},workspaceAnchor,directory,ctx?.abort);return serializePreCheckResult(result)}catch(error93){let errorMessage3=error93 instanceof Error?error93.message:"Unknown error";return serializePreCheckResult({batch_status:"invalid",gates_passed:!1,lint:{ran:!1,error:errorMessage3,duration_ms:0},secretscan:{ran:!1,error:errorMessage3,duration_ms:0},sast_scan:{ran:!1,error:errorMessage3,duration_ms:0},quality_budget:{ran:!1,error:errorMessage3,duration_ms:0},total_duration_ms:0})}}});init_zod();init_guardrails2();init_pr_workflow_gate();init_scope_binding();init_create_tool();var PreparePrFeedbackScopeArgsSchema=exports_external.object({task_id:exports_external.string().regex(/^\d+\.\d+(?:\.\d+)*$/,"task_id must use N.M notation"),files:exports_external.array(exports_external.string().min(1).max(4096)).min(1).max(1e4)}).strict();function failure3(message){return JSON.stringify({success:!1,message},null,2)}async function executePreparePrFeedbackScope(args2,directory,context={}){let parsed=PreparePrFeedbackScopeArgsSchema.safeParse(args2);if(!parsed.success)return failure3(`Invalid PR-feedback scope: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`);let sessionID=context.sessionID?.trim();if(!sessionID)return failure3("PR-feedback scope requires an active session");let files=normalizeScopeFiles(parsed.data.files);if(!files)return failure3("PR-feedback scope contains an unsafe file path");for(let file3 of files){let symlinkBlock=checkWriteTargetForSymlink(file3,directory);if(symlinkBlock)return failure3(symlinkBlock)}try{await declarePrFeedbackScope(directory,sessionID,parsed.data.task_id,files)}catch(error93){return failure3(error93 instanceof Error?error93.message:String(error93))}return JSON.stringify({success:!0,task_id:parsed.data.task_id,files,message:"Scope is bound to the verified PR-feedback revision and will authorize only the next matching coder Task."},null,2)}var prepare_pr_feedback_scope=createSwarmTool({description:"Prepare an exact file scope for one PR-feedback coder Task after immutable feedback verification settles.",args:{task_id:PreparePrFeedbackScopeArgsSchema.shape.task_id,files:PreparePrFeedbackScopeArgsSchema.shape.files},execute:executePreparePrFeedbackScope});init_quality_budget();init_zod();init_pr_workflow_gate();init_create_tool();var RebindPrFeedbackHeadArgsSchema=exports_external.object({pr_head_sha:exports_external.string().trim().regex(/^[0-9a-f]{40}$/i)}).strict();async function executeRebindPrFeedbackHead(args2,directory,context={}){let parsed=RebindPrFeedbackHeadArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,message:`Invalid PR feedback rebind: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`});if(!context.sessionID?.trim())return JSON.stringify({success:!1,message:"PR feedback rebind requires an active sessionID"});try{let state2=await rebindPrFeedbackHead(directory,context.sessionID,parsed.data.pr_head_sha);return JSON.stringify({success:!0,pr_head_sha:state2.prHeadSha,rebind_count:state2.prFeedbackRebindCount??1,message:"Rebound the PR_FEEDBACK intake head; every Stage A / verification / gate receipt is invalidated — re-run the full mechanical ladder on the new ancestry."})}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:String(error93)})}}var rebind_pr_feedback_head=createSwarmTool({description:"Rebind a PR_FEEDBACK workflow to a new verified remote PR head after merge/rebase/conflict repair (base-sync). Use ONLY when the history genuinely changed to repair base drift or conflicts: it refuses a no-op rebind to the current intake head, refuses while publication is armed (to change approved content after arming use invalidate_pr_feedback_publication), and refuses while lanes are in flight. It invalidates every ancestry-bound receipt (Stage A, verification, ordered gates) so the full mechanical ladder re-runs on the new ancestry. Requires the full 40-char new PR head SHA; the current checkout must equal it.",args:{pr_head_sha:RebindPrFeedbackHeadArgsSchema.shape.pr_head_sha},execute:executeRebindPrFeedbackHead});init_zod();init_utils2();init_atomic_write();init_create_tool();var FreshnessValueSchema=exports_external.string().trim().min(1).max(500).regex(/^(synced|behind:[1-9][0-9]*|fetch-failed:\S+)$/,"must be 'synced', 'behind:<n>', or 'fetch-failed:<reason>' (reason contains no whitespace)"),RecordBranchFreshnessArgsSchema=exports_external.object({issueNumber:exports_external.number().int().min(1),freshness:FreshnessValueSchema,override:exports_external.string().trim().min(1).max(4000).optional()}).strict();async function executeRecordBranchFreshness(args2,directory,context={}){let parsed=RecordBranchFreshnessArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,message:`Invalid branch-freshness receipt: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`});let data=parsed.data;if(data.freshness==="synced"&&data.override)return JSON.stringify({success:!1,message:"An override is only meaningful for a fetch-failed outcome; a synced base needs none."});let receipt={issueNumber:data.issueNumber,freshness:data.freshness,timestamp:new Date().toISOString()};if(data.override)receipt.override=data.override;if(context.sessionID?.trim())receipt.sessionId=context.sessionID.trim();let validatedPath;try{validatedPath=validateSwarmPath(directory,"branch-freshness.json")}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:"Failed to validate path"})}try{await atomicWriteSwarmFile(validatedPath,JSON.stringify(receipt,null,2));let permits=await branchFreshnessReceiptExists(directory,data.issueNumber);return JSON.stringify({success:!0,issueNumber:data.issueNumber,path:".swarm/branch-freshness.json",permits,message:permits?`Branch-freshness receipt recorded for issue #${data.issueNumber}; the trace's freshness gate is satisfied.`:`Branch-freshness receipt recorded for issue #${data.issueNumber}, but the outcome (${data.freshness}) does NOT permit the trace — ${data.freshness.startsWith("behind:")?"re-sync with the default branch and re-record as synced.":"a fetch-failed outcome without a recorded user override fails closed."}`})}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:String(error93)})}}var record_branch_freshness=createSwarmTool({description:`Record the Phase 0 branch-freshness outcome for the current traced issue (issue #2564): freshness is "synced", "behind:<n>", or "fetch-failed:<reason>" exactly as the fetch recorded it, plus an optional verbatim user override for a failed fetch. The /swarm issue --trace workflow will not transition to PLAN until the recorded outcome permits (synced, or fetch-failed with an override). The response's permits field mirrors the gate reader's verdict on the persisted receipt (advisory for the calling agent — the reducer always recomputes it independently).`,args:{issueNumber:RecordBranchFreshnessArgsSchema.shape.issueNumber,freshness:RecordBranchFreshnessArgsSchema.shape.freshness,override:RecordBranchFreshnessArgsSchema.shape.override},execute:executeRecordBranchFreshness});init_zod();init_plan_schema();init_schema();init_extractors();init_manager();init_create_tool();var recordDirectiveOverrideInternals={loadPlan,recordDirectiveOverrides};async function executeRecordDirectiveOverride(args2,directory,ctx){if(!ctx?.sessionID?.trim())return{success:!1,code:"DIRECTIVE_OVERRIDE_SESSION_REQUIRED",message:"An exact session identity is required to record an override."};if(stripKnownSwarmPrefix(ctx.agent??"").toLowerCase()!=="architect")return{success:!1,code:"DIRECTIVE_OVERRIDE_ARCHITECT_ONLY",message:"Only the architect may record a critical-directive override."};let plan=await recordDirectiveOverrideInternals.loadPlan(directory),requestedPhase=plan?.phases.find((candidate2)=>candidate2.id===args2.phase);if(!plan||!requestedPhase||getCurrentPhase(plan)!==args2.phase&&!isPhaseInWrapWindow(plan,args2.phase))return{success:!1,code:"DIRECTIVE_OVERRIDE_PHASE_MISMATCH",message:`Phase ${args2.phase} is neither the current plan phase nor the phase being wrapped.`};let phaseLabel=extractPhaseLabelFromPlan(plan,args2.phase)??`Phase ${args2.phase}`;return await recordDirectiveOverrideInternals.recordDirectiveOverrides(directory,[...new Set(args2.directive_ids)],args2.justification,ctx.sessionID,phaseLabel,args2.phase),{success:!0,code:"DIRECTIVE_OVERRIDE_RECORDED",phase:args2.phase,directive_ids:[...new Set(args2.directive_ids)],message:"Recorded the audited override. Retry phase_complete so every gate is re-evaluated from a fresh snapshot."}}var record_directive_override=createSwarmTool({description:"Architect-only audited override for identified critical-directive violations. Requires the current phase (or the phase being wrapped, whose last task already advanced the cursor), the session identity and substantive justification; it cannot repair or bypass unreadable authority.",args:{directive_ids:exports_external.array(exports_external.string().min(1).max(256)).min(1).max(64),justification:exports_external.string().trim().min(10).max(2000),phase:exports_external.number().int().min(1).max(9999)},execute:async(args2,directory,ctx)=>JSON.stringify(await executeRecordDirectiveOverride(args2,directory,ctx),null,2)});init_zod();init_utils2();init_atomic_write();init_create_tool();var RecordImplementationReviewArgsSchema=exports_external.object({issueNumber:exports_external.number().int().min(1),reviewerVerdict:exports_external.enum(["APPROVE","NEEDS_REVISION","BLOCKED"]),criticVerdict:exports_external.enum(["APPROVE","NEEDS_REVISION","BLOCKED"]),diffBase:exports_external.string().trim().regex(/^[0-9a-f]{7,40}$/i),diffHead:exports_external.string().trim().regex(/^[0-9a-f]{7,40}$/i),notes:exports_external.string().trim().min(8).max(4000)}).strict();async function executeRecordImplementationReview(args2,directory,context={}){let parsed=RecordImplementationReviewArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,message:`Invalid implementation review receipt: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`});let data=parsed.data;if(data.reviewerVerdict!=="APPROVE"||data.criticVerdict!=="APPROVE")return JSON.stringify({success:!1,message:"A satisfying implementation-review receipt requires BOTH the reviewer and the critic to have delivered APPROVE; record non-approving verdicts in the working notes and fix the findings instead."});let receipt={issueNumber:data.issueNumber,reviewerVerdict:data.reviewerVerdict,criticVerdict:data.criticVerdict,diffBase:data.diffBase,diffHead:data.diffHead,notes:data.notes,timestamp:new Date().toISOString()};if(context.sessionID?.trim())receipt.sessionId=context.sessionID.trim();let validatedPath;try{validatedPath=validateSwarmPath(directory,"implementation-review.json")}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:"Failed to validate path"})}try{return await atomicWriteSwarmFile(validatedPath,JSON.stringify(receipt,null,2)),JSON.stringify({success:!0,issueNumber:data.issueNumber,path:".swarm/implementation-review.json",message:`Implementation review recorded for issue #${data.issueNumber} (reviewer APPROVE + critic APPROVE); the trace may now satisfy its review gate.`})}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:String(error93)})}}var record_implementation_review=createSwarmTool({description:"Record the independent implementation review for the current traced issue (issue #2131 residual B): dispatch FRESH-context reviewer and critic passes over the implementation diff (separate contexts from the implementer), and once BOTH approve call this with the issue number, both APPROVE verdicts, the reviewed diff base/head SHAs, and notes. The /swarm issue --trace workflow will not hand off to commit-pr until this receipt exists. Non-approving verdicts cannot be recorded here — fix the findings and re-review.",args:{issueNumber:RecordImplementationReviewArgsSchema.shape.issueNumber,reviewerVerdict:RecordImplementationReviewArgsSchema.shape.reviewerVerdict,criticVerdict:RecordImplementationReviewArgsSchema.shape.criticVerdict,diffBase:RecordImplementationReviewArgsSchema.shape.diffBase,diffHead:RecordImplementationReviewArgsSchema.shape.diffHead,notes:RecordImplementationReviewArgsSchema.shape.notes},execute:executeRecordImplementationReview});init_zod();init_url_security();init_loader();init_utils2();init_forge_provider();init_atomic_write();init_create_tool();function loadConfiguredForgeContext4(directory){try{let config3=loadPluginConfig(directory),remote=detectGitRemote(directory,void 0);return resolveForgeContextFromPluginConfig(config3,remote?[remote]:[])??void 0}catch{return}}var RecordIssuePublicationArgsSchema=exports_external.object({issueNumber:exports_external.number().int().min(1),prNumber:exports_external.number().int().min(1),prUrl:exports_external.string().url(),headSha:exports_external.string().min(1).optional()}).strict();async function executeRecordIssuePublication(args2,directory){let parsed=RecordIssuePublicationArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,message:`Invalid publication receipt: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`});let{issueNumber,prNumber,prUrl,headSha}=parsed.data,sanitizedPrUrl=sanitizeUrl(prUrl);if(!isForgePrUrl(prUrl)){let configured=loadConfiguredForgeContext4(directory);if(!(configured&&isForgePrUrl(prUrl,configured)))return JSON.stringify({success:!1,message:"Invalid publication receipt: prUrl must be a canonical PR URL (GitHub https://github.com/<owner>/<repo>/pull/<number> or GitLab https://<gitlab-host>/<owner>/<repo>/-/merge_requests/<number>)"})}let receipt={published:!0,issueNumber,prNumber,prUrl:sanitizedPrUrl,publishedAt:new Date().toISOString()};if(headSha)receipt.headSha=headSha;let validatedPath;try{validatedPath=validateSwarmPath(directory,"issue-publication.json")}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:"Failed to validate path"})}try{return await atomicWriteSwarmFile(validatedPath,JSON.stringify(receipt,null,2)),JSON.stringify({success:!0,issueNumber,prNumber,prUrl,path:".swarm/issue-publication.json",message:`Publication receipt recorded for issue #${issueNumber} (PR #${prNumber}); the issue-trace workflow will transition to its terminal published state.`})}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:String(error93)})}}var record_issue_publication=createSwarmTool({description:'Record that the traced issue has been published (PR created/updated) so the /swarm issue --trace workflow can reach its terminal published state. The trace stops at publication_handoff (the commit-pr directive) until this receipt is observed — publication_handoff is NOT "issue resolved". commit-pr calls this after the PR is created/updated. Supply the traced issue number, the exact PR number, the canonical PR URL (GitHub or GitLab), and (optionally) the published HEAD sha. The receipt is issue-bound.',args:{issueNumber:RecordIssuePublicationArgsSchema.shape.issueNumber,prNumber:RecordIssuePublicationArgsSchema.shape.prNumber,prUrl:RecordIssuePublicationArgsSchema.shape.prUrl,headSha:RecordIssuePublicationArgsSchema.shape.headSha},execute:executeRecordIssuePublication});init_zod();init_utils2();init_atomic_write();init_create_tool();var RecordIssueReproductionArgsSchema=exports_external.object({issueNumber:exports_external.number().int().min(1),performed:exports_external.boolean(),commands:exports_external.array(exports_external.string().min(1)).min(1).optional(),output_summary:exports_external.string().min(1).optional()}).strict();async function executeRecordIssueReproduction(args2,directory,context={}){let parsed=RecordIssueReproductionArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,message:`Invalid reproduction receipt: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`});let{issueNumber,performed,commands,output_summary}=parsed.data;if(performed&&(!commands||commands.length===0||!output_summary))return JSON.stringify({success:!1,message:"A performed=true reproduction receipt requires non-empty commands and output_summary."});let receipt={performed,issueNumber,timestamp:new Date().toISOString()};if(commands)receipt.commands=commands;if(output_summary)receipt.output_summary=output_summary;if(context.sessionID?.trim())receipt.sessionId=context.sessionID.trim();let validatedPath;try{validatedPath=validateSwarmPath(directory,"reproduction.json")}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:"Failed to validate path"})}try{return await atomicWriteSwarmFile(validatedPath,JSON.stringify(receipt,null,2)),JSON.stringify({success:!0,issueNumber,performed,path:".swarm/reproduction.json",message:performed?`Reproduction receipt recorded for issue #${issueNumber}; the trace may now transition to PLAN.`:`Reproduction receipt recorded (performed=false) for issue #${issueNumber}; it does NOT satisfy the reproduction gate.`})}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:String(error93)})}}var record_issue_reproduction=createSwarmTool({description:"Record the reproduction outcome for the current traced issue. The /swarm issue --trace workflow requires reproduction evidence (or a typed --no-repro waiver) before it can leave localization and transition to PLAN. Call this with performed=true, the exact commands run, and a concrete output_summary after attempting a minimal reproduction; the receipt binds to issueNumber (and records the calling session) and is read by the issue-trace engine. A performed=true receipt MUST include commands and output_summary. A performed=false receipt is recorded but does NOT satisfy the gate.",args:{issueNumber:RecordIssueReproductionArgsSchema.shape.issueNumber,performed:RecordIssueReproductionArgsSchema.shape.performed,commands:RecordIssueReproductionArgsSchema.shape.commands,output_summary:RecordIssueReproductionArgsSchema.shape.output_summary},execute:executeRecordIssueReproduction});init_zod();init_utils2();init_atomic_write();init_create_tool();var HEX40=/^[0-9a-f]{40}$/,RecordMergeApprovalArgsSchema=exports_external.object({issueNumber:exports_external.number().int().min(1),prHeadSha:exports_external.string().regex(HEX40,"must be a 40-hex commit SHA"),finalCriticReviewedCommit:exports_external.string().regex(HEX40,"must be a 40-hex commit SHA"),userApprovalVerbatim:exports_external.string().trim().min(1).max(8000)}).strict();async function executeRecordMergeApproval(args2,directory,context={}){let parsed=RecordMergeApprovalArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,message:`Invalid merge-approval receipt: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`});let data=parsed.data;if(data.prHeadSha!==data.finalCriticReviewedCommit)return JSON.stringify({success:!1,message:"Merge-approval binding failed: prHeadSha must equal finalCriticReviewedCommit (the final critic approval must be bound to the exact PR head)."});let receipt={issueNumber:data.issueNumber,prHeadSha:data.prHeadSha,finalCriticReviewedCommit:data.finalCriticReviewedCommit,userApprovalVerbatim:data.userApprovalVerbatim,timestamp:new Date().toISOString()};if(context.sessionID?.trim())receipt.sessionId=context.sessionID.trim();let validatedPath;try{validatedPath=validateSwarmPath(directory,"merge-approval.json")}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:"Failed to validate path"})}try{return await atomicWriteSwarmFile(validatedPath,JSON.stringify(receipt,null,2)),JSON.stringify({success:!0,issueNumber:data.issueNumber,path:".swarm/merge-approval.json",message:`Merge approval recorded for issue #${data.issueNumber}, bound to PR head ${data.prHeadSha}. The approval is captured verbatim for audit; the merge itself is human-enforced and this plugin neither drives nor certifies it.`})}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:String(error93)})}}var record_merge_approval=createSwarmTool({description:"Record the human merge approval for the current traced issue (issue #2564): prHeadSha and finalCriticReviewedCommit must be the same 40-hex SHA (the final critic approval bound to the exact PR head), and userApprovalVerbatim is the user approval quoted verbatim. The receipt is recorded for audit only — the merge stays human-enforced and the plugin never certifies or drives it.",args:{issueNumber:RecordMergeApprovalArgsSchema.shape.issueNumber,prHeadSha:RecordMergeApprovalArgsSchema.shape.prHeadSha,finalCriticReviewedCommit:RecordMergeApprovalArgsSchema.shape.finalCriticReviewedCommit,userApprovalVerbatim:RecordMergeApprovalArgsSchema.shape.userApprovalVerbatim},execute:executeRecordMergeApproval});init_zod();init_utils2();init_atomic_write();init_create_tool();var DispositionSchema=exports_external.object({ref:exports_external.string().trim().min(1).max(500),disposition:exports_external.enum(["FIX","FALSE_POSITIVE","OUT_OF_CLASS","DEFERRED_WITH_USER_APPROVAL"]),note:exports_external.string().trim().max(1000).optional()}).strict(),GuardrailSchema=exports_external.object({kind:exports_external.enum(["lint-static-analysis","type-level","runtime-assertion","ci-check","documented-invariant-plus-regression-test"]),description:exports_external.string().trim().min(8).max(2000),proof:exports_external.string().trim().min(8).max(4000)}).strict(),RelatedProblemSchema=exports_external.object({ref:exports_external.string().trim().min(1).max(500),note:exports_external.string().trim().max(1000).optional()}).strict(),RecordRecurrenceSweepArgsSchema=exports_external.object({issueNumber:exports_external.number().int().min(1),defectClass:exports_external.string().trim().min(1).max(1000),justification:exports_external.string().trim().min(1).max(1000).optional(),predicates:exports_external.array(exports_external.string().trim().min(1).max(500)).min(1).max(32).optional(),dispositions:exports_external.array(DispositionSchema).min(1).max(200).optional(),guardrail:GuardrailSchema.optional(),relatedProblems:exports_external.array(RelatedProblemSchema).min(1).max(200)}).strict();async function executeRecordRecurrenceSweep(args2,directory,context={}){let parsed=RecordRecurrenceSweepArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,message:`Invalid recurrence sweep receipt: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`});let data=parsed.data,noDefectClass=data.defectClass==="no defect class";if(noDefectClass){if(!data.justification)return JSON.stringify({success:!1,message:'The "no defect class" fast path requires a one-line justification.'})}else if(!data.predicates||data.predicates.length===0||!data.dispositions||data.dispositions.length===0||!data.guardrail)return JSON.stringify({success:!1,message:"A defect-class sweep requires search predicates, a non-empty disposition for every hit (at least one — the original defect site itself, dispositioned FIX), and a guardrail with proof it catches the original defect. An empty dispositions array is indistinguishable from a sweep that never ran."});let receipt={issueNumber:data.issueNumber,defectClass:data.defectClass,timestamp:new Date().toISOString()};if(data.justification)receipt.justification=data.justification;if(data.predicates)receipt.predicates=data.predicates;if(data.dispositions)receipt.dispositions=data.dispositions;if(data.guardrail)receipt.guardrail=data.guardrail;if(receipt.relatedProblems=data.relatedProblems,context.sessionID?.trim())receipt.sessionId=context.sessionID.trim();let validatedPath;try{validatedPath=validateSwarmPath(directory,"recurrence-sweep.json")}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:"Failed to validate path"})}try{return await atomicWriteSwarmFile(validatedPath,JSON.stringify(receipt,null,2)),JSON.stringify({success:!0,issueNumber:data.issueNumber,path:".swarm/recurrence-sweep.json",message:noDefectClass?`Recurrence sweep recorded for issue #${data.issueNumber} (no defect class fast path).`:`Recurrence sweep recorded for issue #${data.issueNumber}; the trace may now satisfy its recurrence gate.`})}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:String(error93)})}}var record_recurrence_sweep=createSwarmTool({description:'Record the recurrence sweep for the current traced issue (issue #2131 residual B; widened in #2564 and #2600). The /swarm issue --trace workflow will not hand off to commit-pr until this receipt exists. Supply relatedProblems (the Phase 1 related-problems sweep results — at least one {ref, note?} entry) plus, for a real defect class: defectClass (one-sentence characterization), predicates (the exact search predicates), dispositions (non-empty — every hit as FIX / FALSE_POSITIVE / OUT_OF_CLASS / DEFERRED_WITH_USER_APPROVAL, including the original defect site), and a guardrail (kind + description + proof it catches the original defect). If the change corrects no incorrect behavior, use the literal defectClass "no defect class" with a one-line justification (relatedProblems still required).',args:{issueNumber:RecordRecurrenceSweepArgsSchema.shape.issueNumber,defectClass:RecordRecurrenceSweepArgsSchema.shape.defectClass,justification:RecordRecurrenceSweepArgsSchema.shape.justification,predicates:RecordRecurrenceSweepArgsSchema.shape.predicates,dispositions:RecordRecurrenceSweepArgsSchema.shape.dispositions,guardrail:RecordRecurrenceSweepArgsSchema.shape.guardrail,relatedProblems:RecordRecurrenceSweepArgsSchema.shape.relatedProblems},execute:executeRecordRecurrenceSweep});init_zod();import*as fs221 from"node:fs";init_utils2();init_file_locks();init_atomic_write();init_create_tool();var HEX402=/^[0-9a-f]{40}$/,TRACE_VALIDATION_PHASES2=["0","1","2","2.5","3","4","4.2","4.5","4.6","5"],ValidationEntrySchema=exports_external.object({phase:exports_external.enum(TRACE_VALIDATION_PHASES2),outcome:exports_external.enum(["pass","fail"]),reviewedCommit:exports_external.string().regex(HEX402,"must be a 40-hex commit SHA"),treeId:exports_external.string().regex(HEX402,"must be a 40-hex tree id")}).strict(),RecordTraceValidationArgsSchema=ValidationEntrySchema.extend({issueNumber:exports_external.number().int().min(1)}).strict();async function executeRecordTraceValidation(args2,directory,context={}){let parsed=RecordTraceValidationArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,message:`Invalid trace-validation receipt: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`});let data=parsed.data,validatedPath;try{validatedPath=validateSwarmPath(directory,"trace-validation.json")}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:"Failed to validate path"})}try{let lockResult=await tryAcquireLock(directory,"trace-validation.json","trace-validation","trace-validation");if(!lockResult.acquired)return JSON.stringify({success:!1,message:"The trace-validation receipt is locked by another concurrent writer; no write was attempted. Re-run record_trace_validation for this phase once the other writer finishes."});try{let validations=[];try{let raw=await fs221.promises.readFile(validatedPath,"utf-8"),existing=JSON.parse(raw);if(typeof existing==="object"&&existing!==null&&Array.isArray(existing.validations))validations=existing.validations.filter((v)=>typeof v==="object"&&v!==null&&typeof v.phase==="string")}catch{}let entry={phase:data.phase,outcome:data.outcome,reviewedCommit:data.reviewedCommit,treeId:data.treeId,timestamp:new Date().toISOString()},idx=validations.findIndex((v)=>v.phase===data.phase);if(idx===-1)validations.push(entry);else validations[idx]=entry;let receipt={issueNumber:data.issueNumber,timestamp:new Date().toISOString(),validations};if(context.sessionID?.trim())receipt.sessionId=context.sessionID.trim();await atomicWriteSwarmFile(validatedPath,JSON.stringify(receipt,null,2));let allGreen=await traceValidationReceiptExists(directory,data.issueNumber);return JSON.stringify({success:!0,issueNumber:data.issueNumber,path:".swarm/trace-validation.json",allGreen,message:allGreen?`Validator receipt recorded for issue #${data.issueNumber} phase ${data.phase} (${data.outcome}); every recorded phase is green.`:`Validator receipt recorded for issue #${data.issueNumber} phase ${data.phase} (${data.outcome}), but at least one recorded phase is failing — fix and re-record that phase as a pass before handoff.`})}finally{try{await lockResult.lock._release?.()}catch{}}}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:String(error93)})}}var record_trace_validation=createSwarmTool({description:"Record one per-phase trace-check.sh validator outcome for the current traced issue (issue #2564): the phase (v3 enum 0..5 incl. 2.5/4.2/4.5/4.6), the outcome (pass or fail), and the exact reviewedCommit and treeId the validator reported. Re-running a phase replaces its entry. The /swarm issue --trace workflow will not hand off to commit-pr while any recorded phase is failing or none is recorded. The receipt write is serialized by a per-file receipt lock, and the response's allGreen field mirrors the gate reader's verdict on the persisted receipt (advisory for the calling agent — the reducer always recomputes it independently).",args:{issueNumber:RecordTraceValidationArgsSchema.shape.issueNumber,phase:RecordTraceValidationArgsSchema.shape.phase,outcome:RecordTraceValidationArgsSchema.shape.outcome,reviewedCommit:RecordTraceValidationArgsSchema.shape.reviewedCommit,treeId:RecordTraceValidationArgsSchema.shape.treeId},execute:executeRecordTraceValidation});init_zod();init_schema();init_gate_evidence();init_manager();init_path_identity();init_state();init_stage_a_repair();import*as fs222 from"node:fs";import*as path364 from"node:path";async function forceRecoverReworkTask(directory,sessionID,options){let session=ensureAgentSession(sessionID,void 0,directory);if(!session||!session.agentName||stripKnownSwarmPrefix(session.agentName)!=="architect")throw Error("RECOVER_REWORK_ARCHITECT_REQUIRED: recover_rework_task requires an active architect session. The rework escape hatch is architect-only; a coder/reviewer/test_engineer cannot self-unblock a task.");let taskId=typeof options.taskId==="string"?options.taskId.trim():"";if(!taskId)throw Error('RECOVER_REWORK_UNKNOWN_TASK: recover_rework_task requires the exact plan task id (e.g. "1.1").');let plan=await loadPlanJsonOnly(directory);if(!plan){let planPath=path364.join(directory,".swarm","plan.json");if(fs222.existsSync(planPath))throw Error("PLAN_CORRUPT: .swarm/plan.json exists but could not be parsed (corrupt or schema-invalid). Repair or re-save the plan before recovering a rework_required task.");throw Error("PLAN_NOT_FOUND: no .swarm/plan.json — cannot recover a rework_required "+"task without a plan. Save a plan first.")}if(!new Set(plan.phases.flatMap((phase)=>phase.tasks.map((task2)=>task2.id))).has(taskId))throw Error(`RECOVER_REWORK_UNKNOWN_TASK: task ${taskId} is not in the current plan. Refusing to recover a foreign task id.`);let evidenceRead=await readTaskEvidenceState(directory,taskId);if(evidenceRead.kind==="unparseable")throw Error(`RECOVER_REWORK_EVIDENCE_CORRUPT: the workflow evidence file for task ${taskId} exists but could not be parsed (${evidenceRead.evidencePath}). Repair the evidence first (repair_gate_evidence or /swarm doctor); recovery cannot classify a corrupt evidence state.`);let evidence2=evidenceRead.kind==="ok"?evidenceRead.evidence:null,workflow=getTaskWorkflowSnapshot(evidence2);if(!evidence2||!workflow.authoritative)throw Error(`RECOVER_REWORK_NO_WORKFLOW: no durable task workflow evidence exists for task ${taskId} — there is no rework state to recover.`);if(workflow.state!=="rework_required")throw Error(`RECOVER_REWORK_STATE_REQUIRED: task ${taskId} is at ${workflow.state}, not rework_required. This recovery applies only to a task whose Stage B verdict moved it to rework_required without a code change. From coder_delegated, run pre_check_batch; for a genuine code defect, delegate the coder to repair it first.`);let wedgeMs=Date.parse(workflow.updatedAt);if(!Number.isFinite(wedgeMs))throw Error(`RECOVER_REWORK_GREEN_PRECHECK_REQUIRED: cannot prove pre-check recency (workflow updatedAt "${workflow.updatedAt}" is not a parseable timestamp — the evidence file for task ${taskId} is likely corrupt). Repair the evidence (repair_gate_evidence or /swarm doctor); re-running pre_check_batch cannot fix an unparseable timestamp.`);let greenness=await hasGreenPostSettlementPreCheck(directory,wedgeMs);if(!greenness.green){let sastHint=greenness.reason==="no_pre_check_bundles"?" Note: if gates.sast_scan.enabled is false, no sast_scan bundle is ever persisted and this recovery is unavailable by design — enable gates.sast_scan.enabled and run sast_scan, or use the coder repair loop.":"";throw Error(`RECOVER_REWORK_GREEN_PRECHECK_REQUIRED: refusing to mark Stage A passed without proof (${greenness.reason}). `+"The bar is a green secretscan AND sast_scan evidence pair newer than the failing verdict — normally provided by a fresh pre_check_batch run (bundle proof is global, not correlated to the task's changed files)."+sastHint)}let sanitizedReason=typeof options.reason==="string"&&options.reason.trim().length>0?sanitizeDiagnosticText(options.reason.trim(),500):void 0,recordedAt=new Date().toISOString(),transitionId=`rework-recovery:${taskId}:gen${workflow.generation}`,updated=await transitionTaskWorkflowEvidence(directory,taskId,{type:"stage_a_passed",supervisedRecovery:!0,expectedGeneration:workflow.generation,transitionId}),updatedWorkflow=getTaskWorkflowSnapshot(updated),auditEventRecorded=await appendStageARepairEvent(directory,{action:"rework_recovered",taskId,transitionId,generation:workflow.generation,sessionId:sessionID,...sanitizedReason?{reason:sanitizedReason}:{}});return{taskId,generation:updatedWorkflow.generation,state:updatedWorkflow.state,transitionId,recordedAt,auditEventRecorded}}init_create_tool();var RecoverReworkTaskArgsSchema=exports_external.object({task_id:exports_external.string().trim().min(1).max(64).describe('Exact plan task id of the rework_required task (e.g. "1.1"). Must exist in the current plan and have durable workflow evidence at state rework_required.'),reason:exports_external.string().trim().min(1).max(500).describe('Why the Stage B verdict did not require a code change (e.g. "test_engineer returned SKIPPED for a tool-argument error while pytest passes"). Audited to .swarm/events.jsonl.')}).strict();async function executeRecoverReworkTask(args2,directory,context={}){let parsed=RecoverReworkTaskArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,message:`Invalid recover_rework_task call: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`});if(!context.sessionID?.trim())return JSON.stringify({success:!1,message:"recover_rework_task requires an active sessionID"});try{let summary=await forceRecoverReworkTask(directory,context.sessionID,{taskId:parsed.data.task_id,reason:parsed.data.reason}),auditNote=summary.auditEventRecorded?"The recovery is audited to .swarm/events.jsonl (stage_a_repair action rework_recovered).":"WARNING: the audit event could NOT be appended to .swarm/events.jsonl (see the plugin log); the durable workflow evidence still records the supervised recovery via the rework-recovery: transition id.";return JSON.stringify({success:!0,task_id:summary.taskId,generation:summary.generation,state:summary.state,transition_id:summary.transitionId,recorded_at:summary.recordedAt,audit_event_recorded:summary.auditEventRecorded,method:"supervised_recovery",message:`Task ${summary.taskId} recovered from rework_required: a supervised stage_a_passed was written at generation ${summary.generation} (transition id `+summary.transitionId+"). Reviewer/test_engineer dispatch is permitted again — re-run the Stage B gates that the failed verdict cleared. "+auditNote+" Use it ONLY when the Stage B verdict did not require a code change; a genuine defect still needs the coder repair loop."})}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:String(error93)})}}var recover_rework_task=createSwarmTool({description:"Recover a task wedged at rework_required when the Stage B verdict did NOT require a code change (issue #2755): writes a supervised stage_a_passed for the current generation so reviewer/test_engineer can be re-dispatched, without re-running the coder. Requires the exact plan task id, an active architect session, durable workflow state exactly rework_required, and green pre-check proof: green secretscan AND sast_scan evidence bundles newer than the failing verdict (normally from a fresh pre_check_batch run; bundle recency is global, not file-correlated; projects with SAST disabled cannot use this path). Fail-closed otherwise; the mechanical stage_a_passed path still requires an accepted coder mutation. A reason is required and audited to .swarm/events.jsonl (stage_a_repair action rework_recovered). Prefer the coder repair loop when the code actually has a defect.",args:{task_id:RecoverReworkTaskArgsSchema.shape.task_id,reason:RecoverReworkTaskArgsSchema.shape.reason},execute:executeRecoverReworkTask});init_zod();init_schema();init_gate_evidence();init_path_identity();init_state();init_coder_settlement();init_session_view();init_stage_a_repair();async function recoverStageATaskSupervised(directory,sessionID,options){let session=ensureAgentSession(sessionID,void 0,directory);if(!session||!session.agentName||stripKnownSwarmPrefix(session.agentName)!=="architect")throw Error("RECOVER_STAGE_A_ARCHITECT_REQUIRED: recover_stage_a_task requires an active architect session. The settlement-backed Stage A escape hatch is architect-only; a coder/reviewer/test_engineer cannot self-unblock a task.");let taskId=typeof options.taskId==="string"?options.taskId.trim():"";if(!taskId)throw Error('RECOVER_STAGE_A_UNKNOWN_TASK: recover_stage_a_task requires the exact task id of the settlement-wedged task (e.g. "1.1").');let sanitizedReason=typeof options.reason==="string"&&options.reason.trim().length>0?sanitizeDiagnosticText(options.reason.trim(),500):void 0;if(!sanitizedReason)throw Error("RECOVER_STAGE_A_REASON_REQUIRED: recover_stage_a_task requires a reason describing why the settlement-backed recovery is justified; it is audited to .swarm/events.jsonl.");let evidenceRead=await readTaskEvidenceState(directory,taskId);if(evidenceRead.kind==="unparseable")throw Error(`RECOVER_STAGE_A_EVIDENCE_CORRUPT: the workflow evidence file for task ${taskId} exists but could not be parsed (${evidenceRead.evidencePath}). Repair the evidence first (repair_gate_evidence or /swarm doctor); recovery cannot classify a corrupt evidence state.`);let evidence2=evidenceRead.kind==="ok"?evidenceRead.evidence:null,workflow=getTaskWorkflowSnapshot(evidence2);if(!evidence2||!workflow.authoritative)throw Error(`RECOVER_STAGE_A_NO_WORKFLOW: no durable task workflow evidence exists for task ${taskId} — there is no settlement wedge to recover.`);if(workflow.state==="pre_check_passed"||workflow.state==="reviewer_run"||workflow.state==="tests_run"){if(isStageARecoveredState(workflow.state)&&shouldRefreshStageARecoveryView(session.taskWorkflowStates.get(taskId),workflow.state))applySessionWorkflowView(session,taskId,workflow);return{taskId,generation:workflow.generation,state:workflow.state,transitionId:`stage-a-supervised:${taskId}:noop`,recordedAt:new Date().toISOString(),alreadyRecovered:!0,auditEventRecorded:!1}}if(workflow.state!=="idle"&&workflow.state!=="blocked")throw Error(`RECOVER_STAGE_A_STATE_REQUIRED: task ${taskId} is at ${workflow.state}, not idle/blocked. This recovery applies only to the settlement-backed wedge (a COMMITTED accepted coder settlement while the workflow drifted to idle or blocked). From coder_delegated, run pre_check_batch or /swarm recover; from rework_required without a code change, use recover_rework_task.`);let{states:walStates}=await listCoderSettlementWalStates(directory),settledAfterMs=latestCommittedAcceptedSettlementMs(taskId,walStates);if(settledAfterMs===null)throw Error(`RECOVER_STAGE_A_SETTLEMENT_REQUIRED: refusing to recover task ${taskId} — no COMMITTED accepted coder settlement exists for it. `+"The settlement receipt is what distinguishes this wedge from a not-yet-started or deliberately stopped task; recovery without it would fabricate Stage A justification. Background-dispatched coder tasks never write a settlement WAL and cannot use this path.");let greenness=await hasGreenPostSettlementPreCheck(directory,settledAfterMs);if(!greenness.green){let sastHint=greenness.reason==="no_pre_check_bundles"?" Note: if gates.sast_scan.enabled is false, no sast_scan bundle is ever persisted and this recovery is unavailable by design — enable gates.sast_scan.enabled and run sast_scan, or use the coder repair loop.":"";throw Error(`RECOVER_STAGE_A_GREEN_PRECHECK_REQUIRED: refusing to mark Stage A passed without proof (${greenness.reason}). `+"The bar is a green secretscan AND sast_scan evidence pair newer than the settlement commit — normally provided by a fresh pre_check_batch run (bundle proof is global, not correlated to the task's changed files)."+sastHint)}let recordedAt=new Date().toISOString(),transitionId=`stage-a-supervised:${taskId}:${workflow.generation}`,updated=await transitionTaskWorkflowEvidence(directory,taskId,{type:"stage_a_passed",settlementRecovery:!0,expectedGeneration:workflow.generation,transitionId}),updatedWorkflow=getTaskWorkflowSnapshot(updated);if(isStageARecoveredState(updatedWorkflow.state)){if(shouldRefreshStageARecoveryView(session.taskWorkflowStates.get(taskId),updatedWorkflow.state))applySessionWorkflowView(session,taskId,updatedWorkflow)}let auditEventRecorded=await appendStageARepairEvent(directory,{action:"repaired",via:"recover_stage_a_task",taskId,transitionId,generation:workflow.generation,settlementRecovery:!0,predecessorTransitionId:workflow.lastTransitionId??null,sessionId:sessionID,reason:sanitizedReason});return{taskId,generation:updatedWorkflow.generation,state:updatedWorkflow.state,transitionId,recordedAt,alreadyRecovered:!1,auditEventRecorded}}init_create_tool();var RecoverStageATaskArgsSchema=exports_external.object({task_id:exports_external.string().trim().min(1).max(64).describe('Exact task id of the settlement-wedged task (e.g. "1.1"). Must have durable workflow evidence at state idle or blocked, a COMMITTED accepted coder settlement, and green post-settlement pre-check proof.'),reason:exports_external.string().trim().min(1).max(500).describe('Why the settlement-backed recovery is justified (e.g. "settlement COMMITTED and pre_check_batch green but stage_a_passed never fired; force-repair cleared the proofs"). Audited to .swarm/events.jsonl.')}).strict();async function executeRecoverStageATask(args2,directory,context={}){let parsed=RecoverStageATaskArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,message:`Invalid recover_stage_a_task call: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`});if(!context.sessionID?.trim())return JSON.stringify({success:!1,message:"recover_stage_a_task requires an active sessionID"});try{let summary=await recoverStageATaskSupervised(directory,context.sessionID,{taskId:parsed.data.task_id,reason:parsed.data.reason});if(summary.alreadyRecovered)return JSON.stringify({success:!0,task_id:summary.taskId,generation:summary.generation,state:summary.state,already_recovered:!0,message:`Task ${summary.taskId} already has Stage A recorded (state ${summary.state}, generation ${summary.generation}) — nothing to recover.`});let auditNote=summary.auditEventRecorded?"The recovery is audited to .swarm/events.jsonl (stage_a_repair action repaired, via recover_stage_a_task).":"WARNING: the audit event could NOT be appended to .swarm/events.jsonl (see the plugin log); the durable workflow evidence still records the settlement-backed recovery via the stage-a-supervised: transition id and the settlementRecovery marker.";return JSON.stringify({success:!0,task_id:summary.taskId,generation:summary.generation,state:summary.state,transition_id:summary.transitionId,recorded_at:summary.recordedAt,audit_event_recorded:summary.auditEventRecorded,method:"settlement_recovery",message:`Task ${summary.taskId} recovered from the settlement wedge: a settlement-backed stage_a_passed was written at generation ${summary.generation} (transition id `+summary.transitionId+"). Reviewer/test_engineer dispatch is permitted again — run the Stage B gates the task still needs. "+auditNote+" Use it ONLY when a COMMITTED accepted settlement and green post-settlement pre-check proof already justify Stage A; it never re-runs the coder and never edits gate evidence."})}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:String(error93)})}}var recover_stage_a_task=createSwarmTool({description:"Recover a task wedged in the settlement-backed Stage A deadlock (issue #2828): workflow at idle or blocked while a COMMITTED accepted coder settlement and green post-settlement pre-check proof (green secretscan AND sast_scan evidence newer than the settlement commit) still justify Stage A — the shape where stage_a_passed never fired, a force-repair cleared the proofs, and every other recovery path refuses. Writes a settlement-backed stage_a_passed for the current generation so reviewer/test_engineer can be dispatched, without re-running the coder and without editing gate evidence. Requires the exact task id (bound by its durable workflow evidence and settlement WAL — deliberately no plan-membership precondition, mirroring the /swarm recover scan), an active architect session, a reason (audited), and durable workflow evidence at exactly idle/blocked. Fail-closed otherwise (RECOVER_STAGE_A_* errors); the mechanical stage_a_passed path still requires an accepted coder mutation or the #2665 live_wedge scan.",args:{task_id:RecoverStageATaskArgsSchema.shape.task_id,reason:RecoverStageATaskArgsSchema.shape.reason},execute:executeRecoverStageATask});init_zod();init_schema();init_gate_evidence();init_utils2();init_manager();init_state();init_project_boundary();init_swarm_artifact_cache();init_task_id();init_task_file();init_task_gate_requirements();init_gate_evidence();import{createHash as createHash118,randomUUID as randomUUID48}from"node:crypto";import*as fs223 from"node:fs";import*as path365 from"node:path";var TASK_GATE_EVIDENCE_QUARANTINE_DIR=path365.join("evidence","task-gate-quarantine"),MAX_TASK_GATE_EVIDENCE_BYTES=262144,MAX_TASK_GATE_EVIDENCE_QUARANTINE_FILES=32,MAX_TASK_GATE_EVIDENCE_QUARANTINE_BYTES=12582912,MAX_TASK_GATE_EVIDENCE_QUARANTINE_DIRECTORY_ENTRIES=128,MAX_TASK_GATE_EVIDENCE_QUARANTINE_RECORD_BYTES=786432,TASK_GATE_EVIDENCE_QUARANTINE_SCHEMA_VERSION=1,GENERIC_REPAIR_REASONS=new Set(["fix","repair","test","debug","unknown","n/a","na","none"]);function isQuarantinableTaskEvidenceRead(read){return read.status==="corrupt"||read.status==="valid"}function sha25614(bytes){return createHash118("sha256").update(bytes).digest("hex")}function normalizeRepairReason(reason){let normalized=reason.trim().replace(/\s+/g," ");if(normalized.length<12)throw Error("TASK_GATE_EVIDENCE_REASON_REQUIRED: repair_gate_evidence requires a substantive reason of at least 12 characters.");if(GENERIC_REPAIR_REASONS.has(normalized.toLowerCase()))throw Error("TASK_GATE_EVIDENCE_REASON_REQUIRED: repair_gate_evidence requires a substantive reason, not a placeholder.");return normalized}function canonicalizeRepairRoot(directory){let requestedRoot=path365.resolve(directory),requestedStat=fs223.lstatSync(requestedRoot);if(requestedStat.isSymbolicLink()||!requestedStat.isDirectory())throw Error("TASK_GATE_EVIDENCE_ROOT_UNSAFE: repair_gate_evidence requires a canonical project root directory, not a symlink, junction, reparse point, or non-directory path.");let canonicalRoot2=fs223.realpathSync(requestedRoot);return assertProjectRoot(canonicalRoot2),canonicalRoot2}function assertExistingRegularPath(root,relativePath2){let segments=relativePath2.replace(/\\/g,"/").split("/").filter(Boolean),cursor=root;for(let segment of segments){if(cursor=path365.join(cursor,segment),!fs223.existsSync(cursor))return;if(fs223.lstatSync(cursor).isSymbolicLink())throw Error(`TASK_GATE_EVIDENCE_PATH_UNSAFE: ${relativePath2} contains a symlink, junction, or reparse point.`)}}function taskEvidenceFilePath(directory,taskId){let relativePath2=taskEvidenceRelPath(taskId);return assertExistingRegularPath(directory,".swarm"),assertExistingRegularPath(directory,path365.join(".swarm","evidence")),assertExistingRegularPath(directory,path365.join(".swarm",relativePath2)),validateSwarmPath(directory,relativePath2)}function readTaskEvidenceForRepair(directory,taskId){let filePath=taskEvidenceFilePath(directory,taskId),pathStat;try{pathStat=fs223.lstatSync(filePath)}catch(error93){if(error93.code==="ENOENT")return{status:"missing"};return{status:"unreadable",filePath,bytes:Buffer.alloc(0),sha256:sha25614(""),error:error93}}if(pathStat.isSymbolicLink()||!pathStat.isFile())return{status:"unreadable",filePath,bytes:Buffer.alloc(0),sha256:sha25614(""),error:Error("TASK_GATE_EVIDENCE_UNREADABLE: evidence path is not a regular file")};if(pathStat.size>MAX_TASK_GATE_EVIDENCE_BYTES)return{status:"oversized",filePath,bytes:Buffer.alloc(0),sha256:sha25614(""),error:Error(`TASK_GATE_EVIDENCE_OVERSIZED: ${pathStat.size} bytes exceeds ${MAX_TASK_GATE_EVIDENCE_BYTES}`)};let descriptor=fs223.openSync(filePath,fs223.constants.O_RDONLY|(fs223.constants.O_NOFOLLOW??0));try{let openedStat=fs223.fstatSync(descriptor);if(!openedStat.isFile()||openedStat.dev!==pathStat.dev||openedStat.ino!==pathStat.ino)return{status:"unreadable",filePath,bytes:Buffer.alloc(0),sha256:sha25614(""),error:Error("TASK_GATE_EVIDENCE_UNREADABLE: evidence changed while being opened")};let bytes=fs223.readFileSync(descriptor);if(bytes.byteLength>MAX_TASK_GATE_EVIDENCE_BYTES)return{status:"oversized",filePath,bytes:Buffer.alloc(0),sha256:sha25614(""),error:Error(`TASK_GATE_EVIDENCE_OVERSIZED: ${bytes.byteLength} bytes exceeds ${MAX_TASK_GATE_EVIDENCE_BYTES}`)};let digest5=sha25614(bytes);try{let evidence2=parseTaskEvidence(bytes.toString("utf8"),taskId);return{status:"valid",filePath,bytes,sha256:digest5,evidence:evidence2,generation:evidence2.workflow?.generation}}catch(error93){return{status:"corrupt",filePath,bytes,sha256:digest5,error:error93}}}finally{try{fs223.closeSync(descriptor)}catch{}}}function taskGateEvidenceQuarantinePath(directory,taskId,digest5){return validateSwarmPath(directory,path365.join(TASK_GATE_EVIDENCE_QUARANTINE_DIR,`${taskId}.${digest5}.v${TASK_GATE_EVIDENCE_QUARANTINE_SCHEMA_VERSION}.json`))}function parseErrorMetadata(error93){if(!error93)return null;return{name:error93.name||"Error",message:error93.message||String(error93),code:typeof error93.code==="string"?error93.code:null}}function parseQuarantineRecord(raw){try{let parsed=JSON.parse(raw);if(parsed?.schemaVersion!==TASK_GATE_EVIDENCE_QUARANTINE_SCHEMA_VERSION||typeof parsed.taskId!=="string"||typeof parsed.recordedAt!=="string"||typeof parsed.reason!=="string"||typeof parsed.original?.path!=="string"||typeof parsed.original?.sha256!=="string"||typeof parsed.content?.bytes!=="string"||parsed.content?.encoding!=="base64")return null;return parsed}catch{return null}}function buildQuarantineRecord(taskId,read,reason,context,receiptGeneration){let agentName=context?.sessionID!=null?swarmState.activeAgent.get(context.sessionID)??swarmState.agentSessions.get(context.sessionID)?.agentName??null:null;return{schemaVersion:TASK_GATE_EVIDENCE_QUARANTINE_SCHEMA_VERSION,taskId,recordedAt:new Date().toISOString(),reason,caller:{sessionId:context?.sessionID?.trim()||null,messageId:context?.messageID?.trim()||null,agentName},original:{path:read.filePath,sha256:read.sha256,sizeBytes:read.bytes.byteLength,status:read.status,observedGeneration:read.generation??null,receiptGeneration,requirementsState:read.evidence?.requirements_state??null},parseError:parseErrorMetadata(read.error),content:{encoding:"base64",bytes:read.bytes.toString("base64")}}}async function quarantineTaskEvidenceBytes(directory,taskId,read,reason,context,receiptGeneration){let digest5=read.sha256,quarantineDir=validateSwarmPath(directory,TASK_GATE_EVIDENCE_QUARANTINE_DIR);await fs223.promises.mkdir(quarantineDir,{recursive:!0});let dirStat=await fs223.promises.lstat(quarantineDir);if(dirStat.isSymbolicLink()||!dirStat.isDirectory())throw Error("TASK_GATE_EVIDENCE_QUARANTINE_UNREADABLE: quarantine is not a regular directory");let target=taskGateEvidenceQuarantinePath(directory,taskId,digest5),record3=buildQuarantineRecord(taskId,read,reason,context,receiptGeneration),serialized3=JSON.stringify(record3,null,2),serializedBytes=Buffer.byteLength(serialized3,"utf8");if(serializedBytes>MAX_TASK_GATE_EVIDENCE_QUARANTINE_RECORD_BYTES)throw Error("TASK_GATE_EVIDENCE_QUARANTINE_FULL: quarantine payload exceeds the bounded record size limit");let reconcileExisting=async()=>{let existingStat;try{existingStat=await fs223.promises.lstat(target)}catch(error93){if(error93.code==="ENOENT")return!1;throw error93}if(existingStat.isSymbolicLink()||!existingStat.isFile())throw Error("TASK_GATE_EVIDENCE_QUARANTINE_MISMATCH: existing quarantine path is not a regular immutable record");let existingRaw=await fs223.promises.readFile(target,"utf8"),existingRecord=parseQuarantineRecord(existingRaw);if(existingRecord&&existingRecord.taskId===taskId&&existingRecord.original.path===read.filePath&&existingRecord.original.sha256===read.sha256&&existingRecord.content.bytes===read.bytes.toString("base64"))return!0;throw Error("TASK_GATE_EVIDENCE_QUARANTINE_MISMATCH: existing quarantine record does not match the repaired evidence source")};if(await reconcileExisting())return{digest:digest5,filePath:target};let count4=0,totalBytes=0,scanned=0,handle=await fs223.promises.opendir(quarantineDir,{bufferSize:16});try{for await(let entry of handle){if(scanned+=1,scanned>MAX_TASK_GATE_EVIDENCE_QUARANTINE_DIRECTORY_ENTRIES)throw Error("TASK_GATE_EVIDENCE_QUARANTINE_FULL: too many quarantine entries");if(!entry.isFile()||!/^[0-9.]+\.[a-f0-9]{64}\.v1\.json$/.test(entry.name))continue;count4+=1;let candidate2=path365.join(quarantineDir,entry.name),candidateStat=await fs223.promises.lstat(candidate2);if(candidateStat.isSymbolicLink()||!candidateStat.isFile())throw Error("TASK_GATE_EVIDENCE_QUARANTINE_UNREADABLE: invalid quarantine artifact");if(totalBytes+=candidateStat.size,count4>=MAX_TASK_GATE_EVIDENCE_QUARANTINE_FILES||totalBytes+serializedBytes>MAX_TASK_GATE_EVIDENCE_QUARANTINE_BYTES)throw Error("TASK_GATE_EVIDENCE_QUARANTINE_FULL: quarantine retention limit reached")}}finally{try{await handle.close()}catch{}}let tempPath=path365.join(quarantineDir,`.pending.${process.pid}.${randomUUID48()}.json`),fileHandle;try{fileHandle=await fs223.promises.open(tempPath,"wx"),await fileHandle.writeFile(serialized3,"utf8"),await fileHandle.sync(),await fileHandle.close(),fileHandle=void 0,invalidateCachedArtifact(tempPath),await fs223.promises.link(tempPath,target),invalidateCachedArtifact(target)}catch(error93){if(error93.code!=="EEXIST")throw error93;if(await reconcileExisting())return{digest:digest5,filePath:target};throw error93}finally{await fileHandle?.close().catch(()=>{return}),await fs223.promises.unlink(tempPath).catch(()=>{return})}return{digest:digest5,filePath:target}}function buildRepairTransitionId(taskId,source){return`repair_gate_evidence:${taskId}:${source.slice(0,32)}`}function withoutLegacyReconstructionGate(gates){return[...new Set(gates.filter((gate)=>gate!==TASK_GATE_REQUIREMENTS_RECONSTRUCTION_SENTINEL))].sort()}function hasLegacyReconstructionGate(gates){return gates.includes(TASK_GATE_REQUIREMENTS_RECONSTRUCTION_SENTINEL)}function buildKnownRepairedEvidence(taskId,receipt,generation,source){let requiredGates=withoutLegacyReconstructionGate(receipt.requiredGates);if(requiredGates.length!==receipt.requiredGates.length)throw Error("TASK_GATE_REQUIREMENTS_RECEIPT_TAINTED: legacy reconstruction markers cannot seed known requirements.");return{taskId,required_gates:requiredGates,gates:{},requirements_state:"known",test_engineer_exempt:receipt.testEngineerExempt??void 0,workflow:{schema:TASK_WORKFLOW_SCHEMA_MARKER,generation,state:"idle",retryCount:0,retryHistory:[],retryEpoch:0,lastOutcome:"repair_idle",lastTransitionId:buildRepairTransitionId(taskId,receipt.chainHash),updatedAt:new Date().toISOString()},repair_provenance:{source_sha256:source.sha256,source_generation:source.generation,requirements_receipt_hash:receipt.chainHash}}}function buildUnknownRepairedEvidence(taskId,requiredGates,seedGeneration,source,receiptHash){return{taskId,required_gates:withoutLegacyReconstructionGate(requiredGates),gates:{},requirements_state:"unknown",workflow:{schema:TASK_WORKFLOW_SCHEMA_MARKER,generation:seedGeneration,state:"idle",retryCount:0,retryHistory:[],retryEpoch:0,lastOutcome:"repair_idle",lastTransitionId:buildRepairTransitionId(taskId,"unknown"),updatedAt:new Date().toISOString()},repair_provenance:{source_sha256:source.sha256,source_generation:source.generation,requirements_receipt_hash:receiptHash}}}function canonicalizeTaskEvidence(taskId,evidence2){let validated=parseTaskEvidence(JSON.stringify({...evidence2,taskId}),taskId);return JSON.stringify(validated,null,2)}function isRepairWorkflowReset(taskId,workflow){return workflow!=null&&workflow.state==="idle"&&workflow.retryCount===0&&workflow.retryEpoch===0&&workflow.retryHistory.length===0&&workflow.lastOutcome==="repair_idle"&&typeof workflow.lastTransitionId==="string"&&workflow.lastTransitionId.startsWith(`repair_gate_evidence:${taskId}:`)}function isReceiptlessLegacySentinelReset(taskId,evidence2){return evidence2!=null&&isRepairWorkflowReset(taskId,evidence2.workflow)&&evidence2.requirements_state==="unknown"&&evidence2.required_gates.length===1&&evidence2.required_gates[0]===TASK_GATE_REQUIREMENTS_RECONSTRUCTION_SENTINEL&&Object.keys(evidence2.gates).length===0&&evidence2.repair_provenance!=null&&typeof evidence2.repair_provenance.source_sha256==="string"&&(evidence2.repair_provenance.source_generation===null||evidence2.repair_provenance.source_generation<evidence2.workflow.generation)&&evidence2.repair_provenance.requirements_receipt_hash===null}function isAlreadyRepairedEvidence(taskId,evidence2,receipt){if(!evidence2||!isRepairWorkflowReset(taskId,evidence2.workflow))return!1;if(Object.keys(evidence2.gates).length!==0)return!1;if(hasLegacyReconstructionGate(evidence2.required_gates))return!1;let receiptIsTainted=receipt!=null&&hasLegacyReconstructionGate(receipt.requiredGates);if(receipt&&!receiptIsTainted)return evidence2.requirements_state==="known"&&JSON.stringify(evidence2.required_gates)===JSON.stringify(receipt.requiredGates)&&evidence2.workflow.generation>receipt.generation&&(evidence2.test_engineer_exempt??null)===(receipt.testEngineerExempt??null)&&evidence2.repair_provenance?.requirements_receipt_hash===receipt.chainHash;if(!receipt||!receiptIsTainted)return!1;return evidence2.requirements_state==="unknown"&&evidence2.workflow.generation>=1&&evidence2.repair_provenance!=null&&evidence2.repair_provenance.requirements_receipt_hash===receipt.chainHash&&withoutLegacyReconstructionGate(receipt.requiredGates).every((gate)=>evidence2.required_gates.includes(gate))}function repairedEvidenceMatchesCas(evidence2,args2){let provenance=evidence2.repair_provenance;if(!provenance)return args2.expected_sha256==null&&args2.expected_generation==null;return(args2.expected_sha256==null||provenance.source_sha256===args2.expected_sha256)&&(args2.expected_generation==null||provenance.source_generation===args2.expected_generation)}function buildRepairNextActions(taskId,evidence2){if(evidence2.requirements_state==="known")return[`Delegate coder on task ${taskId} to produce a fresh accepted_mutation for the repaired evidence generation ${evidence2.workflow?.generation}.`,`Rerun Stage A for task ${taskId} until pre_check passes for the new generation.`,`Rerun Stage B gates [${evidence2.required_gates.join(", ")}] for task ${taskId} before attempting completion again.`];return[`Delegate coder on task ${taskId} to produce a fresh accepted mutation and regenerate authoritative required gates for a new exact-task generation.`,`Rerun Stage A for task ${taskId} after the new mutation is recorded.`,`Rerun the exact Stage B gates for task ${taskId} only after authoritative required gates are re-recorded; the idle recovery generation cannot complete directly.`]}function invalidateTaskEvidenceSessionFallbacks(taskId){for(let session of swarmState.agentSessions.values()){if(session.currentTaskId===taskId)session.currentTaskId=null;if(session.lastCoderDelegationTaskId===taskId)session.lastCoderDelegationTaskId=null;if(session.taskWorkflowStates?.delete(taskId),session.taskWorkflowCache?.delete(taskId),session.stageBCompletion?.delete(taskId),session.taskCouncilApproved?.delete(taskId),session.taskCouncilWorkflowGeneration?.delete(taskId),session.gateLog?.delete(taskId),session.partialGateWarningsIssuedForTask?.delete(taskId),session.completionGateWarnedForTask?.delete(taskId),session.lastGateFailure?.taskId===taskId)session.lastGateFailure=null}}async function repairTaskGateEvidence(args2,directory,context){assertStrictTaskId(args2.task_id);let normalizedReason=normalizeRepairReason(args2.reason),canonicalDirectory=canonicalizeRepairRoot(directory);if(!(await loadPlan(canonicalDirectory))?.phases.flatMap((phase)=>phase.tasks).find((candidate2)=>candidate2.id===args2.task_id))return{success:!1,message:`TASK_GATE_EVIDENCE_TASK_MISSING: ${args2.task_id} is not present in the loaded plan`,errors:[`Task ${args2.task_id} is not present in .swarm/plan.json.`]};return withTaskEvidenceLock(canonicalDirectory,args2.task_id,"repair_gate_evidence",async()=>{let read=readTaskEvidenceForRepair(canonicalDirectory,args2.task_id),latestReceipt=(await readTaskGateRequirementsReceipts(canonicalDirectory,args2.task_id)).at(-1),evidenceHasLegacyMarker=read.status==="valid"&&read.evidence!=null&&hasLegacyReconstructionGate(read.evidence.required_gates),receiptHasLegacyMarker=latestReceipt!=null&&hasLegacyReconstructionGate(latestReceipt.requiredGates);if(read.status==="valid"&&isAlreadyRepairedEvidence(args2.task_id,read.evidence,latestReceipt)){if(!repairedEvidenceMatchesCas(read.evidence,args2))return{success:!1,message:"TASK_GATE_EVIDENCE_CAS_MISMATCH",errors:["TASK_GATE_EVIDENCE_CAS_MISMATCH: the existing repaired generation was created from a different source identity."]};let nextActions2=buildRepairNextActions(args2.task_id,read.evidence);return{success:!0,repaired:!1,task_id:args2.task_id,required_gates:[...read.evidence.required_gates],requirements_state:read.evidence.requirements_state,repaired_generation:read.evidence.workflow?.generation,next_actions:nextActions2,message:`Task gate evidence for ${args2.task_id} is already in repaired fail-closed state.`}}if(read.status==="valid"&&read.evidence?.workflow?.schema===TASK_WORKFLOW_SCHEMA_MARKER&&!evidenceHasLegacyMarker&&latestReceipt!=null&&!receiptHasLegacyMarker)return{success:!1,message:"TASK_GATE_EVIDENCE_REPAIR_NOT_REQUIRED",errors:[`TASK_GATE_EVIDENCE_REPAIR_NOT_REQUIRED: ${args2.task_id} has valid authoritative evidence. Use the normal workflow repair path; this tool only rebuilds corrupt or legacy evidence.`]};if(read.status==="valid"&&read.evidence?.requirements_state==="known"&&!evidenceHasLegacyMarker&&receiptHasLegacyMarker)return{success:!1,message:"TASK_GATE_REQUIREMENTS_RECEIPT_STALE",errors:[`TASK_GATE_REQUIREMENTS_RECEIPT_STALE: ${args2.task_id} has clean accepted-mutation evidence but its latest requirements receipt is legacy-tainted. Repair was refused without modifying evidence; replay the prepared coder settlement so it can publish the exact hash-linked receipt.`]};if(typeof args2.expected_sha256==="string"&&read.status!=="missing"&&read.sha256!==args2.expected_sha256)return{success:!1,message:"TASK_GATE_EVIDENCE_CAS_MISMATCH",errors:[`TASK_GATE_EVIDENCE_CAS_MISMATCH: expected sha256 ${args2.expected_sha256}, found ${read.sha256}.`]};if(typeof args2.expected_generation==="number"){let observedGeneration=read.status==="valid"?read.generation:latestReceipt?.generation;if(observedGeneration!==args2.expected_generation)return{success:!1,message:"TASK_GATE_EVIDENCE_CAS_MISMATCH",errors:[`TASK_GATE_EVIDENCE_CAS_MISMATCH: expected generation ${args2.expected_generation}, found ${observedGeneration??"unknown"}.`]}}if(read.status==="unreadable"||read.status==="oversized")return{success:!1,message:read.error?.message??"TASK_GATE_EVIDENCE_UNREADABLE: repair requires operator intervention before evidence can be rewritten.",errors:[read.error?.message??`TASK_GATE_EVIDENCE_UNREADABLE: ${args2.task_id} could not be read safely for repair.`]};if(evidenceHasLegacyMarker&&latestReceipt==null&&!isReceiptlessLegacySentinelReset(args2.task_id,read.evidence))return{success:!1,message:"TASK_GATE_REQUIREMENTS_RECEIPT_MISSING",errors:[`TASK_GATE_REQUIREMENTS_RECEIPT_MISSING: ${args2.task_id} is marker-bearing but does not match the exact receipt-less state emitted by the historical repair flow. Repair was refused without modifying evidence or session state.`]};let nextGeneration2=Math.max(read.status==="valid"?read.generation??-1:-1,latestReceipt?.generation??-1)+1,nextEvidence;if(evidenceHasLegacyMarker||receiptHasLegacyMarker){let preservedGates=withoutLegacyReconstructionGate([...read.status==="valid"?read.evidence?.required_gates??[]:[],...latestReceipt?.requiredGates??[]]);nextEvidence=buildUnknownRepairedEvidence(args2.task_id,preservedGates,Math.max(nextGeneration2,1),{sha256:read.status==="missing"?null:read.sha256,generation:read.status==="valid"?read.generation??null:latestReceipt?.generation??null},latestReceipt?.chainHash??null)}else if(latestReceipt)nextEvidence=buildKnownRepairedEvidence(args2.task_id,latestReceipt,nextGeneration2,{sha256:read.status==="missing"?null:read.sha256,generation:read.status==="valid"?read.generation??null:latestReceipt.generation??null});else if(read.status==="missing")return{success:!1,message:"TASK_GATE_EVIDENCE_ABSENT",errors:[`TASK_GATE_EVIDENCE_ABSENT: ${args2.task_id} has no evidence file and no authoritative requirements receipt to rebuild from.`]};else return{success:!1,message:"TASK_GATE_REQUIREMENTS_RECEIPT_MISSING",errors:[`TASK_GATE_REQUIREMENTS_RECEIPT_MISSING: ${args2.task_id} has no authoritative requirements receipt. Receipt-less repair was refused without modifying the original evidence because its required gates cannot be reconstructed safely.`]};let serialized3=canonicalizeTaskEvidence(args2.task_id,nextEvidence),quarantine;if(isQuarantinableTaskEvidenceRead(read))quarantine=await quarantineTaskEvidenceBytes(canonicalDirectory,args2.task_id,read,normalizedReason,context,latestReceipt?.generation??null);assertTaskEvidenceWriteAllowed(canonicalDirectory,args2.task_id),await atomicWriteFile(taskEvidenceFilePath(canonicalDirectory,args2.task_id),serialized3),invalidateTaskEvidenceSessionFallbacks(args2.task_id);let nextActions=buildRepairNextActions(args2.task_id,nextEvidence);return{success:!0,repaired:!0,task_id:args2.task_id,required_gates:[...nextEvidence.required_gates],requirements_state:nextEvidence.requirements_state,quarantine_digest:quarantine?.digest,quarantine_path:quarantine?.filePath,repaired_generation:nextEvidence.workflow?.generation,next_actions:nextActions,message:`Repaired task gate evidence for ${args2.task_id} into a fresh fail-closed generation ${nextEvidence.workflow?.generation}. Next actions: ${nextActions.join(" ")}`}})}init_create_tool();init_resolve_working_directory();async function executeRepairGateEvidence(args2,directory,_ctx){try{if(!_ctx||stripKnownSwarmPrefix(_ctx.agent??"").toLowerCase()!=="architect")return{success:!1,message:"Only the architect may repair task gate evidence.",errors:["TASK_GATE_EVIDENCE_ARCHITECT_ONLY"]};let resolved=resolveWorkingDirectory(args2.working_directory,directory);if(!resolved.success)return{success:!1,message:resolved.message,errors:[resolved.message]};return await repairTaskGateEvidence(args2,resolved.directory,{sessionID:_ctx?.sessionID,messageID:_ctx?.messageID})}catch(error93){return{success:!1,message:"repair_gate_evidence failed",errors:[error93 instanceof Error?error93.message:String(error93)]}}}var repair_gate_evidence=createSwarmTool({description:"Architect-only evidence repair for exact-task gate files. Rebuilds from a durable requirements receipt, recovers receipt-backed legacy marker wedges or the exact sentinel-only historical reset, and refuses every other receipt-less reconstruction.",args:{task_id:exports_external.string().min(1).regex(/^\d+\.\d+(\.\d+)*$/,"Task ID must be in N.M or N.M.P format"),reason:exports_external.string().min(1).max(2000),expected_sha256:exports_external.string().regex(/^[a-f0-9]{64}$/).optional(),expected_generation:exports_external.number().int().min(0).optional(),working_directory:exports_external.string().optional()},execute:async(args2,directory,ctx)=>JSON.stringify(await executeRepairGateEvidence(args2,directory,ctx),null,2)});init_zod();init_schema();init_knowledge_receipt_ledger();init_create_tool();init_resolve_working_directory();async function executeRepairKnowledgeReceiptLedger(args2,directory,_ctx){try{if(_ctx&&stripKnownSwarmPrefix(_ctx.agent??"").toLowerCase()!=="architect")return{success:!1,message:"Only the architect may repair the knowledge receipt ledger.",errors:["RECEIPT_REPAIR_ARCHITECT_ONLY"]};if(_ctx?.sessionID&&args2.session_id!==_ctx.sessionID)return{success:!1,message:"repair_knowledge_receipt_ledger session_id must match the invoking tool context.",errors:["RECEIPT_REPAIR_SESSION_MISMATCH"]};let resolved=resolveWorkingDirectory(args2.working_directory,directory);if(!resolved.success)return{success:!1,message:resolved.message,errors:[resolved.message]};if(args2.operation==="backfill_phase_id"){let backfill=await backfillMembershipPhaseIds(resolved.directory);if(!backfill.ok)return{success:!1,message:"repair_knowledge_receipt_ledger backfill_phase_id failed",errors:[backfill.detail],code:backfill.code};return{success:!0,message:`phase_id backfill complete: ${backfill.backfilled} membership(s) backfilled, ${backfill.skipped.length} skipped (unparsable label), ${backfill.journal_records} journal record(s) appended. Stored labels are never rewritten.`,backfilled:backfill.backfilled,skipped:backfill.skipped.slice(0,20),skipped_total:backfill.skipped.length,journal_records:backfill.journal_records}}let result=await repairKnowledgeReceiptLedger(resolved.directory,args2);if(!result.ok)return{success:!1,message:"repair_knowledge_receipt_ledger failed",errors:[result.detail],code:result.code};let reEvaluationArgs=JSON.stringify({repair_id:result.repair_id,phase:args2.phase,...args2.task_id?{task_id:args2.task_id}:{},scope_complete:!0});return{success:!0,message:result.status==="validated_projection"?"knowledge receipt projection validated":result.status==="pending_re_evaluation"?`knowledge receipt ledger still pending re-evaluation; as architect, run knowledge_recall with a comprehensive query and repair_re_evaluation ${reEvaluationArgs}`:`knowledge receipt ledger repaired and blocked pending re-evaluation; as architect, run knowledge_recall with a comprehensive query and repair_re_evaluation ${reEvaluationArgs}`,...result}}catch(error93){return{success:!1,message:"repair_knowledge_receipt_ledger failed",errors:[error93 instanceof Error?error93.message:String(error93)]}}}var repair_knowledge_receipt_ledger=createSwarmTool({description:"Architect-only repair and validation for the authoritative knowledge receipt ledger. Default operation repairs: rebuilds the derived projection when authority is readable, or quarantines a bounded corrupt authority, salvages only the validated prefix, and blocks the exact phase/session until a fresh re-evaluation is committed. operation backfill_phase_id durably stamps the stable numeric phase_id on live memberships that lack one across the WHOLE ledger (phase/session_id are not used to scope the backfill; labels never rewritten).",args:{phase:exports_external.string().min(1),session_id:exports_external.string().min(1),task_id:exports_external.string().min(1).optional(),reason:exports_external.string().min(1).max(2000),operation:exports_external.enum(["repair","backfill_phase_id"]).optional(),grace_days:exports_external.number().int().min(0).optional(),working_directory:exports_external.string().optional()},execute:async(args2,directory,ctx)=>JSON.stringify(await executeRepairKnowledgeReceiptLedger(args2,directory,ctx),null,2)});init_zod();init_loader();init_schema();init_profiles();init_telemetry();init_path_security();init_create_tool();import*as path367 from"node:path";init_zod();init_external_tool_runner();init_path_security();init_create_tool();import*as fs224 from"node:fs";import{createRequire as createRequire7}from"node:module";import*as path366 from"node:path";var require2=createRequire7(import.meta.url),DEFAULT_MAX_RESULTS4=100,DEFAULT_MAX_LINES=200,REGEX_TIMEOUT_MS=5000,MAX_FILE_SIZE_BYTES8=1048576,HARD_CAP_RESULTS4=1e4,HARD_CAP_LINES=1e4,MAX_QUERY_LENGTH=20000,MAX_INCLUDE_PATTERNS=100,MAX_RG_STDOUT_BYTES=8388608,MAX_RG_STDERR_BYTES=65536,FALLBACK_MAX_FILES=20000,FALLBACK_MAX_DIRS=5000,FALLBACK_MAX_DEPTH=40,FALLBACK_MAX_TOTAL_BYTES=67108864,DEFAULT_SKIP_DIRS=new Set([".git",".swarm","node_modules","dist","build","out","coverage",".next",".turbo",".cache"]);function globMatch(pattern,filePath){let normalizedPattern=pattern.replace(/\\/g,"/"),normalizedPath=filePath.replace(/\\/g,"/"),regexPattern=normalizedPattern.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"{{DOUBLESTAR}}").replace(/\*/g,"[^/]*").replace(/\?/g,".").replace(/\{\{DOUBLESTAR\}\}/g,".*");try{return new RegExp(`^${regexPattern}$`).test(normalizedPath)}catch{return!1}}function matchesGlobs(filePath,globs){if(globs.length===0)return!0;return globs.some((glob)=>globMatch(glob,filePath))}var WINDOWS_RESERVED_NAMES5=/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\.|:|$)/i;function containsWindowsAttacks4(str){if(/:[^\\/]/.test(str))return!0;let parts=str.split(/[/\\]/);for(let part of parts)if(WINDOWS_RESERVED_NAMES5.test(part))return!0;return!1}function resolveWithinWorkspace(filePath,workspace){try{let resolvedPath=path366.resolve(workspace,filePath),realWorkspace=fs224.realpathSync(workspace),realResolvedPath=fs224.realpathSync(resolvedPath),relativePath2=path366.relative(realWorkspace,realResolvedPath);if(relativePath2.startsWith("..")||path366.isAbsolute(relativePath2))return null;return relativePath2}catch{return null}}function isPathInWorkspace3(filePath,workspace){return resolveWithinWorkspace(filePath,workspace)!==null}function validatePathForRead2(filePath,workspace){return isPathInWorkspace3(filePath,workspace)}function splitGlobPatterns2(value){return value?value.split(",").map((p)=>p.trim()).filter(Boolean):[]}var GLOB_METACHARACTERS=/[*?[\]{}]/;function isExactPath(pattern){return!GLOB_METACHARACTERS.test(pattern)}function targetsDotDirectory(pattern){let firstSegment=pattern.split(/[\\/]/)[0];return!!firstSegment&&firstSegment.startsWith(".")&&firstSegment!=="."&&firstSegment!==".."}function hasGitSegment(resolvedRelativePath){return resolvedRelativePath.split(/[\\/]/).some((segment)=>segment.toLowerCase()===".git")}function toWorkspaceRelativePath2(filePath,workspace){try{let resolved=path366.resolve(workspace,filePath),realWorkspace=fs224.realpathSync(workspace),realResolved=fs224.realpathSync(resolved),relative98=path366.relative(realWorkspace,realResolved);if(!relative98||relative98.startsWith("..")||path366.isAbsolute(relative98))return null;return relative98.split(path366.sep).join("/")}catch{return null}}function truncateLine(line,maxLines){let trimmed=line.trimEnd();if(trimmed.length>maxLines)return`${trimmed.substring(0,maxLines)}...`;return trimmed}function resolvePackagedRipgrep(){try{let mod=require2("@vscode/ripgrep");return typeof mod.rgPath==="string"&&mod.rgPath?mod.rgPath:null}catch{return null}}function resolveRipgrepBinary(){return _internals312.resolvePackagedRipgrep()??_internals312.resolveExecutableFromPath(["rg"])}async function ripgrepSearch(opts){let rgPath=_internals312.resolveRipgrepBinary();if(!rgPath)return{error:!0,type:"rg-not-found",message:"ripgrep (rg) not found; using fallback search was not possible"};let args2=["--json","--no-config","-n"],includes=splitGlobPatterns2(opts.include),promotablePaths=[],globIncludes=[];for(let pattern of includes){let resolvedRelative=resolveWithinWorkspace(pattern,opts.workspace);if(isExactPath(pattern)&&targetsDotDirectory(pattern)&&pattern.split(/[\\/]/)[0]?.toLowerCase()!==".git"&&resolvedRelative!==null&&!hasGitSegment(resolvedRelative))promotablePaths.push(pattern);else globIncludes.push(pattern)}let pathOperands;if(promotablePaths.length>0&&globIncludes.length===0)pathOperands=promotablePaths;else{for(let pattern of[...globIncludes,...promotablePaths])args2.push("--glob",pattern);if(includes.some((p)=>targetsDotDirectory(p)&&p.split(/[\\/]/)[0]?.toLowerCase()!==".git"))args2.push("--hidden","--no-ignore"),args2.push("--glob","!.git");pathOperands=["."]}for(let pattern of splitGlobPatterns2(opts.exclude))args2.push("--glob",`!${pattern}`);if(opts.mode!=="regex")args2.push("--fixed-strings");args2.push("--",opts.query,...pathOperands);let run=await _internals312.runExternalTool({executable:rgPath,args:args2,cwd:opts.workspace,timeoutMs:REGEX_TIMEOUT_MS,maxStdoutBytes:MAX_RG_STDOUT_BYTES,maxStderrBytes:MAX_RG_STDERR_BYTES});try{if(run.status==="timeout")return{error:!0,type:"regex-timeout",message:`Search timed out after ${REGEX_TIMEOUT_MS}ms`};if(run.status==="spawn-error")return{error:!0,type:"unknown",message:run.message??"ripgrep failed to start"};if(run.exitCode!==0&&run.stderr){if(run.stderr.includes("Invalid regex")||run.stderr.includes("regex parse error")||run.stderr.includes("SyntaxError"))return{error:!0,type:"invalid-query",message:`Invalid query: ${run.stderr.split(`
|