opencode-swarm 7.135.3 → 7.135.5

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.
Files changed (42) hide show
  1. package/dist/agents/explorer.d.ts +1 -1
  2. package/dist/cli/{config-doctor-4nznqeca.js → config-doctor-exj26ryt.js} +2 -2
  3. package/dist/cli/{curation-policy-81m14519.js → curation-policy-mbv3b27c.js} +2 -2
  4. package/dist/cli/{curator-e0z5gcww.js → curator-7ycd6x29.js} +13 -13
  5. package/dist/cli/{curator-llm-factory-fem13y9n.js → curator-llm-factory-4d5pzh47.js} +13 -13
  6. package/dist/cli/{explorer-15gqzxh8.js → explorer-swjc297z.js} +1 -1
  7. package/dist/cli/{guardrail-explain-wgaj23hd.js → guardrail-explain-2jrqv2zf.js} +14 -14
  8. package/dist/cli/{guardrail-log-04p1z1vt.js → guardrail-log-c843gxnm.js} +3 -3
  9. package/dist/cli/{hive-promoter-k345z42k.js → hive-promoter-epnj14q8.js} +13 -13
  10. package/dist/cli/{index-30pg2rs3.js → index-09w3ezq2.js} +1 -1
  11. package/dist/cli/{index-36v55ryg.js → index-0csbx1wc.js} +1 -1
  12. package/dist/cli/{index-dg1njnms.js → index-6mjf4vr1.js} +1 -1
  13. package/dist/cli/{index-kb7qy7an.js → index-6yk6ezvj.js} +1 -1
  14. package/dist/cli/{index-yf30m841.js → index-8et4bx6j.js} +3 -3
  15. package/dist/cli/{index-dwargd10.js → index-9s5b8wrs.js} +54 -42
  16. package/dist/cli/{index-rv7s2k9y.js → index-bx10dq60.js} +21 -4
  17. package/dist/cli/{index-a01r818w.js → index-db52969t.js} +1 -1
  18. package/dist/cli/{index-5436jxnw.js → index-gvfw2y6v.js} +2 -2
  19. package/dist/cli/{index-p9ngg568.js → index-hw6yt4rs.js} +4 -4
  20. package/dist/cli/{index-168phrs7.js → index-jnemjn16.js} +2 -2
  21. package/dist/cli/{index-p5kr35wh.js → index-k8arazbb.js} +1 -1
  22. package/dist/cli/{index-wygxzvtf.js → index-kjg6vgqs.js} +1 -1
  23. package/dist/cli/{index-y47crdg9.js → index-kq9zb1cv.js} +15 -15
  24. package/dist/cli/{index-bcmrg4t4.js → index-qyn0b2jj.js} +1 -1
  25. package/dist/cli/{index-gxxxmajn.js → index-t1gszcwg.js} +2 -2
  26. package/dist/cli/{index-f52jt0am.js → index-ym516a9a.js} +5 -5
  27. package/dist/cli/index.js +13 -13
  28. package/dist/cli/{knowledge-escalator-42ecv7m3.js → knowledge-escalator-3tjhpwjf.js} +3 -3
  29. package/dist/cli/{knowledge-events-zhna7v3g.js → knowledge-events-0akk3p15.js} +5 -1
  30. package/dist/cli/{knowledge-store-56jcfc5k.js → knowledge-store-7nvfh2n3.js} +1 -1
  31. package/dist/cli/{knowledge-validator-8zk0pnb6.js → knowledge-validator-z618vhda.js} +4 -4
  32. package/dist/cli/{scan-cursor-h3ndxd41.js → scan-cursor-5zqr3afj.js} +2 -2
  33. package/dist/cli/{schema-r6wmd7zp.js → schema-n1cj94m0.js} +1 -1
  34. package/dist/cli/{skill-generator-12cftsx4.js → skill-generator-560ksca8.js} +5 -5
  35. package/dist/hooks/curator-postmortem.d.ts +8 -0
  36. package/dist/hooks/delegate-ack-collector.d.ts +21 -0
  37. package/dist/hooks/knowledge-events.d.ts +33 -1
  38. package/dist/hooks/pr-workflow-gate.d.ts +5 -5
  39. package/dist/hooks/pr-workflow-response-gate.d.ts +32 -1
  40. package/dist/index.js +24 -23
  41. package/dist/services/knowledge-diagnostics.d.ts +2 -0
  42. 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.135.3",description:"Architect-centric agentic swarm plugin for OpenCode - hub-and-spoke orchestration with SME consultation, code generation, and QA review",main:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",default:"./dist/index.js"},"./package.json":"./package.json"},bin:{"opencode-swarm":"./dist/cli/index.js"},type:"module",engines:{bun:">=1.3.13"},license:"MIT",repository:{type:"git",url:"https://github.com/ZaxbyHub/opencode-swarm.git"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},keywords:["opencode","opencode-plugin","ai","agents","orchestration","swarm","multi-agent","llm"],files:["dist","dist/lang/grammars","binaries","evaluation-fixtures",".opencode/skills/brainstorm",".opencode/skills/specify",".opencode/skills/clarify-spec",".opencode/skills/resume",".opencode/skills/clarify",".opencode/skills/discover",".opencode/skills/consult",".opencode/skills/pre-phase-briefing",".opencode/skills/council",".opencode/skills/deep-dive",".opencode/skills/deep-research",".opencode/skills/codebase-review-swarm",".opencode/skills/swarm-implement",".opencode/skills/design-docs",".opencode/skills/swarm-pr-review",".opencode/skills/swarm",".opencode/skills/swarm-pr-feedback",".opencode/skills/swarm-pr-subscribe",".opencode/skills/swarm-ci-monitor",".opencode/skills/issue-ingest",".opencode/skills/plan",".opencode/skills/critic-gate",".opencode/skills/execute",".opencode/skills/phase-wrap",".opencode/skills/loop",".opencode/skills/writing-tests",".opencode/skills/running-tests",".opencode/skills/engineering-conventions",".opencode/skills/commit-pr",".opencode/skills/ci-failure-batching",".opencode/skills/gate-attribution",".opencode/skills/merge-queue-readiness",".opencode/skills/skill-edit-validation",".opencode/skills/worktree-retry-cleanup",".opencode/skills/test-file-split",".opencode/skills/fork-pr-operations",".opencode/skills/parallel-work-check",".opencode/skills/ci-fix-monitor",".opencode/skills/issue-tracer","tests/fixtures/memory-recall","README.md","LICENSE"],scripts:{clean:`bun -e "require('fs').rmSync('dist',{recursive:true,force:true})"`,build:"bun run clean && bun run scripts/copy-grammars.ts && bun build src/index.ts --outdir dist --target node --format esm --external web-tree-sitter --minify-whitespace --minify-syntax && bun build src/cli/index.ts --outdir dist/cli --target bun --format esm --external bash-parser --splitting && bun run scripts/copy-grammars.ts --to-dist && tsc --emitDeclarationOnly",typecheck:"tsc --noEmit",test:"bun test",lint:"biome lint .","lint:ci":"biome ci .","test:unit:ci":"bun scripts/ci/run-unit-tests-local.ts","drift:check":"bun run scripts/drift-check.ts","drift:fix":"bun run scripts/drift-check.ts --fix --confirm","skills:sync":"bun run scripts/sync-qa-gate-skills.ts",format:"biome format . --write",check:"biome check --write .",dev:"bun run build && opencode","package:smoke":"node scripts/package-smoke.mjs",prepare:"bun run build","repro:704":"node scripts/repro-704.mjs","repro:1144":"bun scripts/repro-1144.mjs","repro:1873":"bun build scripts/repro-1873-entry.ts --outdir dist-build-test/repro-1873 --target node --format esm && node scripts/repro-1873.mjs"},dependencies:{"@opencode-ai/plugin":"^1.18.3","@opencode-ai/sdk":"^1.18.3","@vscode/tree-sitter-wasm":"^0.3.0","bash-parser":"^0.5.0","p-limit":"^7.3.0",picomatch:"^4.0.4","proper-lockfile":"^4.1.2","quick-lru":"^7.3.0","web-tree-sitter":"^0.25.0",zod:"^4.1.8"},devDependencies:{"@biomejs/biome":"2.3.14","@types/picomatch":"^4.0.3","bun-types":"1.3.8","js-yaml":"^4.1.1",typescript:"^5.7.3"}}});var QA_AGENTS,PIPELINE_AGENTS,ORCHESTRATOR_NAME="architect",ALL_SUBAGENT_NAMES,ALL_AGENT_NAMES;var init_agent_names=__esm(()=>{QA_AGENTS=["reviewer","critic","critic_oversight","critic_finding_validator"],PIPELINE_AGENTS=["explorer","coder","test_engineer"],ALL_SUBAGENT_NAMES=["sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","curator_postmortem","curator_consolidation","council_generalist","council_skeptic","council_domain_expert","skill_improver","spec_writer",...QA_AGENTS,...PIPELINE_AGENTS],ALL_AGENT_NAMES=["architect",...ALL_SUBAGENT_NAMES]});function getPrWorkflowToolCapability(toolName,mode){let metadata=TOOL_METADATA[toolName];if(!metadata?.prWorkflow?.modes.includes(mode))return null;return metadata.prWorkflow.capability}var TOOL_METADATA,TOOL_NAMES,TOOL_NAME_SET,TOOL_DESCRIPTIONS,AGENT_TOOL_MAP;var init_tool_metadata=__esm(()=>{init_agent_names();TOOL_METADATA={diff:{description:"structured git diff with contract change detection",agents:["architect","reviewer","critic_finding_validator","critic_oversight","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},diff_summary:{description:"filter classified AST changes by category, risk level, or file for reviewer drill-down",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},syntax_check:{description:"check syntax of source files using tree-sitter parsers across multiple languages, returning per-file errors",agents:["architect","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},placeholder_scan:{description:"todo and FIXME comment detection",agents:["architect","reviewer","critic_finding_validator"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},imports:{description:"find all consumers that import from a given file — use before refactoring shared modules to avoid breaking unseen dependents",agents:["architect","sme","researcher","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},lint:{description:"run project linter in check or fix mode; supports biome, eslint, ruff, clippy, and more, returns structured results",agents:["architect","reviewer","critic_finding_validator","coder"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},secretscan:{description:"scan for secrets (API keys, tokens, passwords) via regex and entropy; returns redacted previews, excludes common dirs",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},sast_scan:{description:"static analysis security scan",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},build_check:{description:"discover and run build, typecheck, and test commands for various project ecosystems in the working directory",agents:["architect","coder","test_engineer"]},pre_check_batch:{description:"parallel verification: lint:check + secretscan + sast_scan + quality_budget",agents:["architect","reviewer","critic_finding_validator"]},quality_budget:{description:"code quality budget check",agents:["architect"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},symbols:{description:"extract exported symbols (functions, classes, interfaces, types) from source files; supports TypeScript, JavaScript, and Python",agents:["architect","sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},complexity_hotspots:{description:"git churn × complexity risk map",agents:["architect","sme","researcher","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","critic_oversight","explorer","test_engineer"]},schema_drift:{description:"OpenAPI spec vs route drift",agents:["architect","sme","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},todo_extract:{description:"structured TODO/FIXME extraction",agents:["architect","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},evidence_check:{description:"verify task evidence completeness",agents:["architect","critic_oversight"]},check_gate_status:{description:"check the gate status of a specific task",agents:["architect","critic_oversight"]},completion_verify:{description:"verify completed tasks have required evidence",agents:["architect","critic_oversight"]},complete_pr_workflow:{description:"validate terminal PR workflow evidence and clear its durable session gate",agents:["architect"]},abort_pr_workflow:{description:"abort an unrecoverable PR_REVIEW/PR_FEEDBACK mechanical gate and clear its durable session state",agents:["architect"]},approve_plan_critic:{description:"record a MANUAL plan_critic_gate approval snapshot to unblock the ratchet-tighter critic_pre_plan execution gate when the critic already returned APPROVED but the mechanical recorder failed to persist it (issue #2012)",agents:["architect"]},prepare_pr_workflow_checkout:{description:"preserve explicit dirty tracked files before an unbound PR workflow checkout with an auditable recovery receipt",agents:["architect"]},run_pr_feedback_stage_a:{description:"execute and persist mandatory PR-feedback Stage A checks on a content-bound revision",agents:["architect"]},submit_council_verdicts:{description:"submit pre-collected council member verdicts for synthesis (architect MUST dispatch critic/reviewer/sme/test_engineer/explorer as Agent tasks first; this tool synthesizes only, it does not contact members)",agents:[]},submit_phase_council_verdicts:{description:"submit pre-collected phase-level council member verdicts for holistic phase synthesis (architect MUST dispatch all 5 council members with phase-scoped context first; this tool synthesizes only, it does not contact members)",agents:[]},declare_council_criteria:{description:"pre-declare acceptance criteria for a task before the coder starts work; criteria are read back during council evaluation",agents:[]},sbom_generate:{description:"SBOM generation for dependency inventory",agents:["architect"]},checkpoint:{description:"create named git checkpoints for save, restore, and delete — use before risky operations to enable rollback",agents:["architect"]},pkg_audit:{description:"dependency vulnerability scan — npm/pip/cargo",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},parse_lane_candidates:{description:"Parse [CANDIDATE] rows from a dispatch_lanes or collect_lane_results artifact (by output_ref), produce structured records with provenance, optionally persist to a per-batch sidecar JSONL. Pure-parser variant exists as internal module.",agents:["architect"]},plan_conflict_check:{description:"read-only advisory check (#1656): compute a pairwise file-conflict matrix for N proposed parallel task groups using declared scopes and optional git co-change; returns a verdict (all_disjoint / conflicts_present / unknown_scopes), per-pair evidence, and a suggested serialization order. Writes nothing — the execution gate independently recomputes the verdict inline at dispatch time via the same helper. Call BEFORE attempting parallel dispatch to confirm disjointness.",agents:["architect"]},write_pr_review_trigger_eval:{description:"persist the complete PR-review trigger evaluation with exact-set validation, dispatch provenance, and live merge-base verification",agents:["architect"]},write_pr_review_artifact:{description:"persist schema-validated PR-review findings checkpoints and exact actionable feedback handoffs under the active run",agents:["architect"]},prepare_pr_feedback_scope:{description:"prepare an exact file scope for one PR-feedback coder Task after immutable feedback verification settles",agents:["architect"]},test_runner:{description:"auto-detect and run tests",agents:["architect","reviewer","critic_finding_validator","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},test_impact:{description:"identify test files impacted by changed source files via import analysis",agents:["architect","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},mutation_test:{description:"executes pre-generated mutation patches against tests, evaluates kill rate against quality gate thresholds",agents:["architect","test_engineer"]},generate_mutants:{description:"generate LLM-based mutation testing patches for source files; returns MutationPatch[] for direct consumption by the mutation_test tool",agents:["architect"]},detect_domains:{description:"detect which SME domains are relevant for a given text",agents:["architect","sme","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic","critic_oversight","explorer"]},git_blame:{description:"per-line git blame metadata: sha, author, date, summary for each line in a file",agents:["reviewer","critic_finding_validator","explorer","architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},gitingest:{description:"fetch a GitHub repository full content via gitingest.com",agents:["architect","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_summary:{description:"retrieve the full content of a stored tool output summary",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_lane_output:{description:"retrieve paged full dispatch lane output by output_ref; use before consuming truncated lane previews or routing candidates from lane results",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},extract_code_blocks:{description:"extract code blocks from text content and save them to files",agents:["docs","docs_design","designer","spec_writer","coder","test_engineer"]},phase_complete:{description:"mark a phase as complete and track dispatched agents",agents:["architect"]},save_plan:{description:"save a structured implementation plan",agents:["architect"]},update_task_status:{description:"mark tasks complete, track phase progress",agents:["architect"]},lint_spec:{description:"validate .swarm/spec.md format and required fields",agents:["architect","spec_writer"]},write_retro:{description:"document phase retrospectives via phase_complete workflow, capture lessons learned",agents:["architect"]},write_drift_evidence:{description:"write drift verification evidence for a completed phase",agents:["architect"]},write_hallucination_evidence:{description:"write hallucination verification evidence for a completed phase",agents:["architect"]},write_mutation_evidence:{description:"write mutation gate evidence for a completed phase; normalizes PASS/WARN/FAIL/SKIP verdicts and writes .swarm/evidence/{phase}/mutation-gate.json",agents:["architect"]},declare_scope:{description:"declare file scope for next coder delegation",agents:["architect"]},knowledge_query:{description:"query swarm or hive knowledge with optional filters",agents:["architect","skill_improver","spec_writer"]},doc_scan:{description:"scan project documentation files and build an index manifest",agents:["architect","docs_design","skill_improver","spec_writer","explorer"]},doc_extract:{description:"extract actionable constraints from project documentation",agents:["architect","docs_design","skill_improver","spec_writer"]},curator_analyze:{description:"run curator phase analysis and optionally apply knowledge recommendations",agents:["architect"]},consensus_mine:{description:"mine cross-run consensus from existing .swarm evidence into an immutable proposals-only report; also deletes its own reports past consensus.report_retention, appends to the shared recommendation dedup ledger (in the shared cohort root, outside this project, when a knowledge link is active), and mirrors proposals into pending swarm-memory proposals when memory is enabled",agents:["architect","curator_phase","curator_postmortem"]},knowledge_add:{description:"store a new lesson in the knowledge base",agents:["architect","coder"]},knowledge_recall:{description:"search the knowledge base for relevant past decisions",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"]},knowledge_remove:{description:"delete an outdated swarm knowledge entry by ID (swarm tier only)",agents:["architect"]},co_change_analyzer:{description:"detect hidden couplings by analyzing git history",agents:["architect"]},context_status:{description:"report current context-window headroom for the active session — returns tokens-used, model-limit, usage-percent, threshold-state (none/warn/critical), model name, and provider. Pure read-only: no state mutation, no warning injection. Works whether context_budget.enabled is true or false.",agents:["architect"]},search:{description:"Workspace-scoped ripgrep-style text search with structured JSON output. Supports literal and regex modes, glob filtering, and result limits. NOTE: This is text search, not structural AST search — use symbols and imports tools for structural queries.",agents:["architect","sme","docs","docs_design","designer","critic_hallucination_verifier","skill_improver","spec_writer","reviewer","critic_finding_validator","critic_oversight","explorer","coder","test_engineer","researcher"]},ast_grep:{description:"Read-only structural AST search using ast-grep patterns with optional language and glob filters. Use for syntax-aware code pattern searches; does not rewrite files.",agents:["architect","sme","docs","docs_design","critic_hallucination_verifier","spec_writer","explorer","coder","test_engineer","researcher"]},actionlint_scan:{description:"Run actionlint against GitHub Actions workflow YAML files with structured findings. Resolves actionlint lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},osv_scan:{description:"Run OSV-Scanner against a workspace path and return structured dependency vulnerability findings. Resolves osv-scanner lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},gh_evidence:{description:"Fetch bounded GitHub pull request or issue metadata through gh for review and CI evidence. Resolves gh lazily and is read-only.",agents:["architect","researcher"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},pr_workflow_status:{description:"Read-only architect observation of local git state (HEAD, branch, clean/dirty with a bounded changed-file list, remotes) plus a session-pinned PR workflow gate summary. Use to observe state under the fail-closed PR_REVIEW/PR_FEEDBACK gate. Never executes PR-controlled scripts and never reads another session gate.",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},batch_symbols:{description:"Batched symbol extraction across multiple files. Returns per-file symbol summaries with isolated error handling.",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","explorer"]},suggest_patch:{description:"Reviewer-safe structured patch suggestion tool. Produces context-anchored patch artifacts without file modification. Returns structured diagnostics on context mismatch.",agents:["architect","reviewer","critic_finding_validator"]},req_coverage:{description:"query requirement coverage status for tracked functional requirements",agents:["critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","critic","critic_oversight"]},get_approved_plan:{description:"retrieve the last critic-approved immutable plan snapshot for baseline drift comparison",agents:["critic_drift_verifier","critic","critic_oversight"]},repo_map:{description:"query the repo code graph: importers, dependencies, blast radius, localization, ontology facts, package boundaries, and heuristic preflight packets before refactoring; ontology findings are advisory, not formal proofs",agents:["architect","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},get_qa_gate_profile:{description:"retrieve the QA gate profile for the current plan: gates (reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council), lock state, and profile hash. Read-only.",agents:["architect"]},set_qa_gates:{description:"configure the QA gate profile for the current plan. Architect-only. Ratchet-tighter only — rejected once the profile is locked after critic approval. Supports: reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council.",agents:["architect"]},web_search:{description:"External web search (Tavily or Brave) for architect-driven council research, SME domain research, researcher auto-research, and skill-improver research. Returns titled results with snippets, URLs, normalized query metadata, temporal intent, freshness, and removed stale years. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides. Requires a search API key. Used by the architect in MODE: COUNCIL to gather a RESEARCH CONTEXT before dispatching council agents, by SME for opt-in external skill/source evaluation, and by the researcher agent for multi-source auto-research.",agents:["sme","researcher","skill_improver"]},web_fetch:{description:"Fetch the readable text of a single http(s) URL (architect-only). Returns decoded page text, document title, final URL after redirects, and an evidence reference. Reads primary sources that web_search only surfaces as snippets. Config-gated on council.general.enabled. Blocks private/loopback/link-local/metadata addresses (re-validated and re-pinned across redirects); enforces timeout and body size cap.",agents:[]},convene_general_council:{description:"Synthesize responses from a multi-model General Council. Accepts parallel member responses (Round 1, optionally Round 2), detects disagreements, and returns consensus points, persisting disagreements, and a structured synthesis. Architect-only. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides.",agents:[]},write_final_council_evidence:{description:"Persist project-scoped final council evidence to .swarm/evidence/final-council.json. PREREQUISITE: dispatch critic, reviewer, sme, test_engineer, and explorer as project-scoped Agent tasks and collect their CouncilMemberVerdict JSON — this tool synthesizes only. Rejects on insufficient quorum or CONCERNS with unresolved requiredFixes; normalizes verdicts to approved/concerns/rejected. Architect-only.",agents:[]},skill_generate:{description:"compile knowledge entries into a structured SKILL.md draft",agents:["skill_improver"]},skill_list:{description:"list generated skill files and their status",agents:["skill_improver"]},skill_apply:{description:"activate a draft skill proposal",agents:[]},skill_inspect:{description:"inspect the content and source entries of a skill file",agents:["skill_improver"]},run_stale_reconciliation:{description:"reconcile skills against the knowledge store: mark skills stale when source knowledge is archived or deleted, or clear stale markers",agents:["architect"]},skill_regenerate:{description:"regenerate an active skill by re-clustering its source knowledge entries and updating the SKILL.md in place",agents:[]},skill_retire:{description:"retire a generated skill by adding a retired.marker file; retired skills are excluded from scoring and injection",agents:[]},skill_improve:{description:"run the skill_improver agent to review and refine skills",agents:["skill_improver"]},spec_write:{description:"author or update .swarm/spec.md for the current project",agents:["spec_writer"]},knowledge_receipt:{description:"file a receipt for retrieved knowledge (applied/ignored/contradicted + new lessons), recorded as immutable knowledge events",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},knowledge_archive:{description:"archive (default), quarantine, or purge a swarm or hive knowledge entry by ID with an immutable audit tombstone; purge requires an admin flag",agents:["architect"]},swarm_memory_recall:{description:"recall scoped Swarm memory for the current repository as untrusted background",agents:[]},swarm_memory_propose:{description:"create a pending Swarm memory proposal; does not write durable memory directly",agents:[]},swarm_command:{description:"run supported /swarm commands through the canonical command registry",agents:["architect","sme","researcher","docs","docs_design","designer","reviewer","critic_finding_validator","critic","explorer","coder","test_engineer"]},dispatch_lanes:{description:"dispatch read-only exploration/review lanes concurrently and BLOCK until all finish; prefer dispatch_lanes_async for non-blocking dispatch, use this only when promptAsync is unavailable",agents:["architect"]},dispatch_lanes_async:{description:"launch read-only advisory lanes non-blockingly and return a batch id plus lane session handles immediately so you can keep working; launch_timeout_ms is only a promptAsync acceptance budget, not a lane runtime timeout; poll incrementally with collect_lane_results (wait omitted or false) while doing independent investigation, or join with wait: true when you need all results",agents:["architect"]},collect_lane_results:{description:"collect or poll results for a dispatch_lanes_async batch; supports both non-blocking polling (wait omitted or false) and blocking join (wait: true). Non-blocking polls include pending lane identities by default and process settled lanes incrementally while continuing independent work; busy/retry lanes are not timed out just because they run for a long time. Does not advance workflow gates. Inline output for a settled lane is delivered only once: later polls of the same lane set output_omitted_repeat: true and omit output, but still include output_ref for recovery via retrieve_lane_output.",agents:["architect"]},summarize_work:{description:"emit a short structured summary of completed work (key decisions, assumptions, risks, constraints) at task completion; rolls up per phase for architecture-supervisor review. Advisory, never blocks.",agents:["architect","sme","researcher","docs","docs_design","designer","explorer","coder","test_engineer"]},write_architecture_supervisor_evidence:{description:"persist the architecture supervisor verdict for a phase (architect MUST dispatch critic_architecture_supervisor first and collect its JSON verdict; this tool persists only, it does not contact the supervisor)",agents:["architect"]},lean_turbo_plan_lanes:{description:"partition phase tasks into parallel lanes based on file-scope conflicts for Lean Turbo execution",agents:[]},lean_turbo_acquire_locks:{description:"acquire file locks for all files in a lane (all-or-nothing) before lane execution",agents:[]},lean_turbo_runner_status:{description:"read Lean Turbo run state from .swarm/turbo-state.json",agents:[]},lean_turbo_review:{description:"dispatch a read-only reviewer agent to evaluate a completed Lean Turbo phase",agents:[]},lean_turbo_run_phase:{description:"Execute a phase using Lean Turbo parallel lane execution. Plans lanes, acquires file locks, and dispatches coder agents concurrently. Use when Lean Turbo is active and you want to execute all tasks in a phase in parallel lanes.",agents:[]},lean_turbo_status:{description:"returns Lean Turbo configuration and active status for the current session",agents:[]},swarm_apply_patch:{description:"Apply a unified diff patch to workspace files with exact context matching, atomic writes, and path validation. Use standard unified diff format only — does NOT support *** Begin Patch / *** Update File payloads (use native apply_patch for those).",agents:["coder","test_engineer"]},external_skill_discover:{description:"Discover external skill candidates from configured sources. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_list:{description:"List external skill candidates in the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_inspect:{description:"Inspect a specific external skill candidate by ID. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_promote:{description:"Promote a validated external skill candidate to an active generated skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_reject:{description:"Reject an external skill candidate after evaluation. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_delete:{description:"Delete an external skill candidate from the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_revoke:{description:"Revoke a previously promoted external skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},epic_decide_phase:{description:"Compute the Epic Mode verdict for a phase WITHOUT dispatching coders. Runs preflight + calibration + the three gates (p-threshold, hot-module, greenfield), persists the decision, and returns the verdict so the architect can dispatch waves via the visible Task tool (promote) or fall back to per-task serial (demote). Pair with `epic_plan_waves` to get the wave plan when promoted. Use when /swarm epic is on for the session.",agents:["architect"]},epic_plan_waves:{description:"Partition a phase's pending tasks into ordered concurrent waves for Epic Mode dispatch. A wave is a set of tasks with mutually disjoint declared scopes and all dependencies satisfied by prior waves. Returns `{ waves: [{ waveId, taskIds, files }, ...], serializedTasks, degradedTasks }`. "+'For each wave in order, the architect dispatches one `Task(subagent_type="coder", ...)` per `taskId` — all in one assistant message — so the wave runs concurrently and each coder appears as a visible subagent. '+"Wait for the wave to finish before dispatching the next. Pair with `epic_decide_phase` (called first; this tool is only relevant on a `promote` verdict). "+"Preflight reject reasons: `no-plan`, `no-phase`, `phase-empty`, `phase-already-complete`, `scopes-missing` (call `declare_scope` for `missingScopes`), `git-failed` (transient — retry), `planner-error`.",agents:["architect"]},epic_record_divergence:{description:"After every `update_task_status(completed)`, record the task's declared-vs-actual divergence to .swarm/epic/divergence.jsonl. Feeds Epic Mode's self-calibration loop (Capability D). Best-effort: never blocks.",agents:["architect"]}},TOOL_NAMES=Object.keys(TOOL_METADATA),TOOL_NAME_SET=new Set(TOOL_NAMES);TOOL_DESCRIPTIONS=Object.fromEntries(Object.entries(TOOL_METADATA).map(([name,meta])=>[name,meta.description])),AGENT_TOOL_MAP=(()=>{let map=Object.fromEntries(ALL_AGENT_NAMES.map((agent)=>[agent,[]]));for(let[name,meta]of Object.entries(TOOL_METADATA))for(let agent of meta.agents)map[agent].push(name);return map})()});function deepMergeInternal(base,override,depth){if(depth>=10)throw Error("deepMerge exceeded maximum depth of 10");let result={...base};for(let key of Object.keys(override)){let baseVal=base[key],overrideVal=override[key];if(typeof baseVal==="object"&&baseVal!==null&&typeof overrideVal==="object"&&overrideVal!==null&&!Array.isArray(baseVal)&&!Array.isArray(overrideVal))result[key]=deepMergeInternal(baseVal,overrideVal,depth+1);else result[key]=overrideVal}return result}function deepMerge(base,override){if(!base)return override;if(!override)return base;return deepMergeInternal(base,override,0)}var MAX_MERGE_DEPTH=10;function freezeSet(items){let set=new Set(items),proxy=new Proxy(set,{get(target,prop){if(prop==="add"||prop==="delete"||prop==="clear")return()=>{throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")};if(prop==="forEach")return(callback,thisArg)=>{let wrapped=(v,k)=>callback.call(thisArg??void 0,v,k,proxy);return set.forEach(wrapped)};let value=Reflect.get(target,prop);return typeof value==="function"?value.bind(target):value},set(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},deleteProperty(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},defineProperty(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},setPrototypeOf(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")}});return proxy}function isQAAgent(name){return QA_AGENTS.includes(name)}function isSubagent(name){return ALL_SUBAGENT_NAMES.includes(name)}function isLowCapabilityModel(modelId){let lower=(modelId||"").toLowerCase();return LOW_CAPABILITY_MODELS.some((substr)=>lower.includes(substr))}var OPENCODE_NATIVE_AGENTS,CLAUDE_CODE_NATIVE_COMMANDS,MEMORY_AGENT_TOOL_MAP,EXTERNAL_SKILL_TOOL_NAMES,EXTERNAL_SKILL_AGENT_TOOL_MAP,COUNCIL_TOOL_NAMES,COUNCIL_AGENT_TOOL_MAP,GENERAL_COUNCIL_TOOL_NAMES,GENERAL_COUNCIL_AGENT_TOOL_MAP,TURBO_TOOL_NAMES,TURBO_AGENT_TOOL_MAP,SKILL_TOOL_NAMES,SKILL_AGENT_TOOL_MAP,WRITE_TOOL_NAMES,SUMMARIZER_EXEMPT_TOOL_NAMES,DEFAULT_MODELS,DEFAULT_AGENT_CONFIGS,DEFAULT_SCORING_CONFIG,LOW_CAPABILITY_MODELS,TURBO_MODE_BANNER=`## \uD83D\uDE80 TURBO MODE ACTIVE
1
+ import{createRequire}from"node:module";var __create=Object.create;var{getPrototypeOf:__getProtoOf,defineProperty:__defProp,getOwnPropertyNames:__getOwnPropNames,getOwnPropertyDescriptor:__getOwnPropDesc}=Object,__hasOwnProp=Object.prototype.hasOwnProperty;function __accessProp(key){return this[key]}var __toESMCache_node,__toESMCache_esm,__toESM=(mod,isNodeMode,target)=>{var canCache=mod!=null&&typeof mod==="object";if(canCache){var cache=isNodeMode?__toESMCache_node??=new WeakMap:__toESMCache_esm??=new WeakMap,cached=cache.get(mod);if(cached)return cached}target=mod!=null?__create(__getProtoOf(mod)):{};let to=isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target;for(let key of __getOwnPropNames(mod))if(!__hasOwnProp.call(to,key))__defProp(to,key,{get:__accessProp.bind(mod,key),enumerable:!0});if(canCache)cache.set(mod,to);return to},__toCommonJS=(from)=>{var entry=(__moduleCache??=new WeakMap).get(from),desc;if(entry)return entry;if(entry=__defProp({},"__esModule",{value:!0}),from&&typeof from==="object"||typeof from==="function"){for(var key of __getOwnPropNames(from))if(!__hasOwnProp.call(entry,key))__defProp(entry,key,{get:__accessProp.bind(from,key),enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return __moduleCache.set(from,entry),entry},__moduleCache,__commonJS=(cb,mod)=>()=>(mod||cb((mod={exports:{}}).exports,mod),mod.exports);var __returnValue=(v)=>v;function __exportSetter(name,newValue){this[name]=__returnValue.bind(null,newValue)}var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0,configurable:!0,set:__exportSetter.bind(all,name)})};var __esm=(fn2,res)=>()=>(fn2&&(res=fn2(fn2=0)),res);var __require=createRequire(import.meta.url);var package_default;var init_package=__esm(()=>{package_default={name:"opencode-swarm",version:"7.135.5",description:"Architect-centric agentic swarm plugin for OpenCode - hub-and-spoke orchestration with SME consultation, code generation, and QA review",main:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",default:"./dist/index.js"},"./package.json":"./package.json"},bin:{"opencode-swarm":"./dist/cli/index.js"},type:"module",engines:{bun:">=1.3.13"},license:"MIT",repository:{type:"git",url:"https://github.com/ZaxbyHub/opencode-swarm.git"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},keywords:["opencode","opencode-plugin","ai","agents","orchestration","swarm","multi-agent","llm"],files:["dist","dist/lang/grammars","binaries","evaluation-fixtures",".opencode/skills/brainstorm",".opencode/skills/specify",".opencode/skills/clarify-spec",".opencode/skills/resume",".opencode/skills/clarify",".opencode/skills/discover",".opencode/skills/consult",".opencode/skills/pre-phase-briefing",".opencode/skills/council",".opencode/skills/deep-dive",".opencode/skills/deep-research",".opencode/skills/codebase-review-swarm",".opencode/skills/swarm-implement",".opencode/skills/design-docs",".opencode/skills/swarm-pr-review",".opencode/skills/swarm",".opencode/skills/swarm-pr-feedback",".opencode/skills/swarm-pr-subscribe",".opencode/skills/swarm-ci-monitor",".opencode/skills/issue-ingest",".opencode/skills/plan",".opencode/skills/critic-gate",".opencode/skills/execute",".opencode/skills/phase-wrap",".opencode/skills/loop",".opencode/skills/writing-tests",".opencode/skills/running-tests",".opencode/skills/engineering-conventions",".opencode/skills/commit-pr",".opencode/skills/ci-failure-batching",".opencode/skills/gate-attribution",".opencode/skills/merge-queue-readiness",".opencode/skills/skill-edit-validation",".opencode/skills/worktree-retry-cleanup",".opencode/skills/test-file-split",".opencode/skills/fork-pr-operations",".opencode/skills/parallel-work-check",".opencode/skills/ci-fix-monitor",".opencode/skills/issue-tracer","tests/fixtures/memory-recall","README.md","LICENSE"],scripts:{clean:`bun -e "require('fs').rmSync('dist',{recursive:true,force:true})"`,build:"bun run clean && bun run scripts/copy-grammars.ts && bun build src/index.ts --outdir dist --target node --format esm --external web-tree-sitter --minify-whitespace --minify-syntax && bun build src/cli/index.ts --outdir dist/cli --target bun --format esm --external bash-parser --splitting && bun run scripts/copy-grammars.ts --to-dist && tsc --emitDeclarationOnly",typecheck:"tsc --noEmit",test:"bun test",lint:"biome lint .","lint:ci":"biome ci .","test:unit:ci":"bun scripts/ci/run-unit-tests-local.ts","drift:check":"bun run scripts/drift-check.ts","drift:fix":"bun run scripts/drift-check.ts --fix --confirm","skills:sync":"bun run scripts/sync-qa-gate-skills.ts",format:"biome format . --write",check:"biome check --write .",dev:"bun run build && opencode","package:smoke":"node scripts/package-smoke.mjs",prepare:"bun run build","repro:704":"node scripts/repro-704.mjs","repro:1144":"bun scripts/repro-1144.mjs","repro:1873":"bun build scripts/repro-1873-entry.ts --outdir dist-build-test/repro-1873 --target node --format esm && node scripts/repro-1873.mjs"},dependencies:{"@opencode-ai/plugin":"^1.18.3","@opencode-ai/sdk":"^1.18.3","@vscode/tree-sitter-wasm":"^0.3.0","bash-parser":"^0.5.0","p-limit":"^7.3.0",picomatch:"^4.0.4","proper-lockfile":"^4.1.2","quick-lru":"^7.3.0","web-tree-sitter":"^0.25.0",zod:"^4.1.8"},devDependencies:{"@biomejs/biome":"2.3.14","@types/picomatch":"^4.0.3","bun-types":"1.3.8","js-yaml":"^4.1.1",typescript:"^5.7.3"}}});var QA_AGENTS,PIPELINE_AGENTS,ORCHESTRATOR_NAME="architect",ALL_SUBAGENT_NAMES,ALL_AGENT_NAMES;var init_agent_names=__esm(()=>{QA_AGENTS=["reviewer","critic","critic_oversight","critic_finding_validator"],PIPELINE_AGENTS=["explorer","coder","test_engineer"],ALL_SUBAGENT_NAMES=["sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","curator_postmortem","curator_consolidation","council_generalist","council_skeptic","council_domain_expert","skill_improver","spec_writer",...QA_AGENTS,...PIPELINE_AGENTS],ALL_AGENT_NAMES=["architect",...ALL_SUBAGENT_NAMES]});function getPrWorkflowToolCapability(toolName,mode){let metadata=TOOL_METADATA[toolName];if(!metadata?.prWorkflow?.modes.includes(mode))return null;return metadata.prWorkflow.capability}var TOOL_METADATA,TOOL_NAMES,TOOL_NAME_SET,TOOL_DESCRIPTIONS,AGENT_TOOL_MAP;var init_tool_metadata=__esm(()=>{init_agent_names();TOOL_METADATA={diff:{description:"structured git diff with contract change detection",agents:["architect","reviewer","critic_finding_validator","critic_oversight","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},diff_summary:{description:"filter classified AST changes by category, risk level, or file for reviewer drill-down",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},syntax_check:{description:"check syntax of source files using tree-sitter parsers across multiple languages, returning per-file errors",agents:["architect","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},placeholder_scan:{description:"todo and FIXME comment detection",agents:["architect","reviewer","critic_finding_validator"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},imports:{description:"find all consumers that import from a given file — use before refactoring shared modules to avoid breaking unseen dependents",agents:["architect","sme","researcher","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},lint:{description:"run project linter in check or fix mode; supports biome, eslint, ruff, clippy, and more, returns structured results",agents:["architect","reviewer","critic_finding_validator","coder"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},secretscan:{description:"scan for secrets (API keys, tokens, passwords) via regex and entropy; returns redacted previews, excludes common dirs",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},sast_scan:{description:"static analysis security scan",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},build_check:{description:"discover and run build, typecheck, and test commands for various project ecosystems in the working directory",agents:["architect","coder","test_engineer"]},pre_check_batch:{description:"parallel verification: lint:check + secretscan + sast_scan + quality_budget",agents:["architect","reviewer","critic_finding_validator"]},quality_budget:{description:"code quality budget check",agents:["architect"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},symbols:{description:"extract exported symbols (functions, classes, interfaces, types) from source files; supports TypeScript, JavaScript, and Python",agents:["architect","sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},complexity_hotspots:{description:"git churn × complexity risk map",agents:["architect","sme","researcher","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","critic_oversight","explorer","test_engineer"]},schema_drift:{description:"OpenAPI spec vs route drift",agents:["architect","sme","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},todo_extract:{description:"structured TODO/FIXME extraction",agents:["architect","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},evidence_check:{description:"verify task evidence completeness",agents:["architect","critic_oversight"]},check_gate_status:{description:"check the gate status of a specific task",agents:["architect","critic_oversight"]},completion_verify:{description:"verify completed tasks have required evidence",agents:["architect","critic_oversight"]},complete_pr_workflow:{description:"validate terminal PR workflow evidence and clear its durable session gate",agents:["architect"]},abort_pr_workflow:{description:"abort an unrecoverable PR_REVIEW/PR_FEEDBACK mechanical gate and clear its durable session state",agents:["architect"]},approve_plan_critic:{description:"record a MANUAL plan_critic_gate approval snapshot to unblock the ratchet-tighter critic_pre_plan execution gate when the critic already returned APPROVED but the mechanical recorder failed to persist it (issue #2012)",agents:["architect"]},prepare_pr_workflow_checkout:{description:"preserve explicit dirty tracked files before an unbound PR workflow checkout with an auditable recovery receipt",agents:["architect"]},run_pr_feedback_stage_a:{description:"execute and persist mandatory PR-feedback Stage A checks on a content-bound revision",agents:["architect"]},submit_council_verdicts:{description:"submit pre-collected council member verdicts for synthesis (architect MUST dispatch critic/reviewer/sme/test_engineer/explorer as Agent tasks first; this tool synthesizes only, it does not contact members)",agents:[]},submit_phase_council_verdicts:{description:"submit pre-collected phase-level council member verdicts for holistic phase synthesis (architect MUST dispatch all 5 council members with phase-scoped context first; this tool synthesizes only, it does not contact members)",agents:[]},declare_council_criteria:{description:"pre-declare acceptance criteria for a task before the coder starts work; criteria are read back during council evaluation",agents:[]},sbom_generate:{description:"SBOM generation for dependency inventory",agents:["architect"]},checkpoint:{description:"create named git checkpoints for save, restore, and delete — use before risky operations to enable rollback",agents:["architect"]},pkg_audit:{description:"dependency vulnerability scan — npm/pip/cargo",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},parse_lane_candidates:{description:"Parse [CANDIDATE] rows from a dispatch_lanes or collect_lane_results artifact (by output_ref), produce structured records with provenance, optionally persist to a per-batch sidecar JSONL. Pure-parser variant exists as internal module.",agents:["architect"]},plan_conflict_check:{description:"read-only advisory check (#1656): compute a pairwise file-conflict matrix for N proposed parallel task groups using declared scopes and optional git co-change; returns a verdict (all_disjoint / conflicts_present / unknown_scopes), per-pair evidence, and a suggested serialization order. Writes nothing — the execution gate independently recomputes the verdict inline at dispatch time via the same helper. Call BEFORE attempting parallel dispatch to confirm disjointness.",agents:["architect"]},write_pr_review_trigger_eval:{description:"persist the complete PR-review trigger evaluation with exact-set validation, dispatch provenance, and live merge-base verification",agents:["architect"]},write_pr_review_artifact:{description:"persist schema-validated PR-review findings checkpoints and exact actionable feedback handoffs under the active run",agents:["architect"]},prepare_pr_feedback_scope:{description:"prepare an exact file scope for one PR-feedback coder Task after immutable feedback verification settles",agents:["architect"]},test_runner:{description:"auto-detect and run tests",agents:["architect","reviewer","critic_finding_validator","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},test_impact:{description:"identify test files impacted by changed source files via import analysis",agents:["architect","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},mutation_test:{description:"executes pre-generated mutation patches against tests, evaluates kill rate against quality gate thresholds",agents:["architect","test_engineer"]},generate_mutants:{description:"generate LLM-based mutation testing patches for source files; returns MutationPatch[] for direct consumption by the mutation_test tool",agents:["architect"]},detect_domains:{description:"detect which SME domains are relevant for a given text",agents:["architect","sme","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic","critic_oversight","explorer"]},git_blame:{description:"per-line git blame metadata: sha, author, date, summary for each line in a file",agents:["reviewer","critic_finding_validator","explorer","architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},gitingest:{description:"fetch a GitHub repository full content via gitingest.com",agents:["architect","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_summary:{description:"retrieve the full content of a stored tool output summary",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_lane_output:{description:"retrieve paged full dispatch lane output by output_ref; use before consuming truncated lane previews or routing candidates from lane results",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},extract_code_blocks:{description:"extract code blocks from text content and save them to files",agents:["docs","docs_design","designer","spec_writer","coder","test_engineer"]},phase_complete:{description:"mark a phase as complete and track dispatched agents",agents:["architect"]},save_plan:{description:"save a structured implementation plan",agents:["architect"]},update_task_status:{description:"mark tasks complete, track phase progress",agents:["architect"]},lint_spec:{description:"validate .swarm/spec.md format and required fields",agents:["architect","spec_writer"]},write_retro:{description:"document phase retrospectives via phase_complete workflow, capture lessons learned",agents:["architect"]},write_drift_evidence:{description:"write drift verification evidence for a completed phase",agents:["architect"]},write_hallucination_evidence:{description:"write hallucination verification evidence for a completed phase",agents:["architect"]},write_mutation_evidence:{description:"write mutation gate evidence for a completed phase; normalizes PASS/WARN/FAIL/SKIP verdicts and writes .swarm/evidence/{phase}/mutation-gate.json",agents:["architect"]},declare_scope:{description:"declare file scope for next coder delegation",agents:["architect"]},knowledge_query:{description:"query swarm or hive knowledge with optional filters",agents:["architect","skill_improver","spec_writer"]},doc_scan:{description:"scan project documentation files and build an index manifest",agents:["architect","docs_design","skill_improver","spec_writer","explorer"]},doc_extract:{description:"extract actionable constraints from project documentation",agents:["architect","docs_design","skill_improver","spec_writer"]},curator_analyze:{description:"run curator phase analysis and optionally apply knowledge recommendations",agents:["architect"]},consensus_mine:{description:"mine cross-run consensus from existing .swarm evidence into an immutable proposals-only report; also deletes its own reports past consensus.report_retention, appends to the shared recommendation dedup ledger (in the shared cohort root, outside this project, when a knowledge link is active), and mirrors proposals into pending swarm-memory proposals when memory is enabled",agents:["architect","curator_phase","curator_postmortem"]},knowledge_add:{description:"store a new lesson in the knowledge base",agents:["architect","coder"]},knowledge_recall:{description:"search the knowledge base for relevant past decisions",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"]},knowledge_remove:{description:"delete an outdated swarm knowledge entry by ID (swarm tier only)",agents:["architect"]},co_change_analyzer:{description:"detect hidden couplings by analyzing git history",agents:["architect"]},context_status:{description:"report current context-window headroom for the active session — returns tokens-used, model-limit, usage-percent, threshold-state (none/warn/critical), model name, and provider. Pure read-only: no state mutation, no warning injection. Works whether context_budget.enabled is true or false.",agents:["architect"]},search:{description:"Workspace-scoped ripgrep-style text search with structured JSON output. Supports literal and regex modes, glob filtering, and result limits. NOTE: This is text search, not structural AST search — use symbols and imports tools for structural queries.",agents:["architect","sme","docs","docs_design","designer","critic_hallucination_verifier","skill_improver","spec_writer","reviewer","critic_finding_validator","critic_oversight","explorer","coder","test_engineer","researcher"]},ast_grep:{description:"Read-only structural AST search using ast-grep patterns with optional language and glob filters. Use for syntax-aware code pattern searches; does not rewrite files.",agents:["architect","sme","docs","docs_design","critic_hallucination_verifier","spec_writer","explorer","coder","test_engineer","researcher"]},actionlint_scan:{description:"Run actionlint against GitHub Actions workflow YAML files with structured findings. Resolves actionlint lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},osv_scan:{description:"Run OSV-Scanner against a workspace path and return structured dependency vulnerability findings. Resolves osv-scanner lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},gh_evidence:{description:"Fetch bounded GitHub pull request or issue metadata through gh for review and CI evidence. Resolves gh lazily and is read-only.",agents:["architect","researcher"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},pr_workflow_status:{description:"Read-only architect observation of local git state (HEAD, branch, clean/dirty with a bounded changed-file list, remotes) plus a session-pinned PR workflow gate summary. Use to observe state under the fail-closed PR_REVIEW/PR_FEEDBACK gate. Never executes PR-controlled scripts and never reads another session gate.",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},batch_symbols:{description:"Batched symbol extraction across multiple files. Returns per-file symbol summaries with isolated error handling.",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","explorer"]},suggest_patch:{description:"Reviewer-safe structured patch suggestion tool. Produces context-anchored patch artifacts without file modification. Returns structured diagnostics on context mismatch.",agents:["architect","reviewer","critic_finding_validator"]},req_coverage:{description:"query requirement coverage status for tracked functional requirements",agents:["critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","critic","critic_oversight"]},get_approved_plan:{description:"retrieve the last critic-approved immutable plan snapshot for baseline drift comparison",agents:["critic_drift_verifier","critic","critic_oversight"]},repo_map:{description:"query the repo code graph: importers, dependencies, blast radius, localization, ontology facts, package boundaries, and heuristic preflight packets before refactoring; ontology findings are advisory, not formal proofs",agents:["architect","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},get_qa_gate_profile:{description:"retrieve the QA gate profile for the current plan: gates (reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council), lock state, and profile hash. Read-only.",agents:["architect"]},set_qa_gates:{description:"configure the QA gate profile for the current plan. Architect-only. Ratchet-tighter only — rejected once the profile is locked after critic approval. Supports: reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council.",agents:["architect"]},web_search:{description:"External web search (Tavily or Brave) for architect-driven council research, SME domain research, researcher auto-research, and skill-improver research. Returns titled results with snippets, URLs, normalized query metadata, temporal intent, freshness, and removed stale years. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides. Requires a search API key. Used by the architect in MODE: COUNCIL to gather a RESEARCH CONTEXT before dispatching council agents, by SME for opt-in external skill/source evaluation, and by the researcher agent for multi-source auto-research.",agents:["sme","researcher","skill_improver"]},web_fetch:{description:"Fetch the readable text of a single http(s) URL (architect-only). Returns decoded page text, document title, final URL after redirects, and an evidence reference. Reads primary sources that web_search only surfaces as snippets. Config-gated on council.general.enabled. Blocks private/loopback/link-local/metadata addresses (re-validated and re-pinned across redirects); enforces timeout and body size cap.",agents:[]},convene_general_council:{description:"Synthesize responses from a multi-model General Council. Accepts parallel member responses (Round 1, optionally Round 2), detects disagreements, and returns consensus points, persisting disagreements, and a structured synthesis. Architect-only. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides.",agents:[]},write_final_council_evidence:{description:"Persist project-scoped final council evidence to .swarm/evidence/final-council.json. PREREQUISITE: dispatch critic, reviewer, sme, test_engineer, and explorer as project-scoped Agent tasks and collect their CouncilMemberVerdict JSON — this tool synthesizes only. Rejects on insufficient quorum or CONCERNS with unresolved requiredFixes; normalizes verdicts to approved/concerns/rejected. Architect-only.",agents:[]},skill_generate:{description:"compile knowledge entries into a structured SKILL.md draft",agents:["skill_improver"]},skill_list:{description:"list generated skill files and their status",agents:["skill_improver"]},skill_apply:{description:"activate a draft skill proposal",agents:[]},skill_inspect:{description:"inspect the content and source entries of a skill file",agents:["skill_improver"]},run_stale_reconciliation:{description:"reconcile skills against the knowledge store: mark skills stale when source knowledge is archived or deleted, or clear stale markers",agents:["architect"]},skill_regenerate:{description:"regenerate an active skill by re-clustering its source knowledge entries and updating the SKILL.md in place",agents:[]},skill_retire:{description:"retire a generated skill by adding a retired.marker file; retired skills are excluded from scoring and injection",agents:[]},skill_improve:{description:"run the skill_improver agent to review and refine skills",agents:["skill_improver"]},spec_write:{description:"author or update .swarm/spec.md for the current project",agents:["spec_writer"]},knowledge_receipt:{description:"file a receipt for retrieved knowledge (applied/ignored/contradicted + new lessons), recorded as immutable knowledge events",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},knowledge_archive:{description:"archive (default), quarantine, or purge a swarm or hive knowledge entry by ID with an immutable audit tombstone; purge requires an admin flag",agents:["architect"]},swarm_memory_recall:{description:"recall scoped Swarm memory for the current repository as untrusted background",agents:[]},swarm_memory_propose:{description:"create a pending Swarm memory proposal; does not write durable memory directly",agents:[]},swarm_command:{description:"run supported /swarm commands through the canonical command registry",agents:["architect","sme","researcher","docs","docs_design","designer","reviewer","critic_finding_validator","critic","explorer","coder","test_engineer"]},dispatch_lanes:{description:"dispatch read-only exploration/review lanes concurrently and BLOCK until all finish; prefer dispatch_lanes_async for non-blocking dispatch, use this only when promptAsync is unavailable",agents:["architect"]},dispatch_lanes_async:{description:"launch read-only advisory lanes non-blockingly and return a batch id plus lane session handles immediately so you can keep working; launch_timeout_ms is only a promptAsync acceptance budget, not a lane runtime timeout; poll incrementally with collect_lane_results (wait omitted or false) while doing independent investigation, or join with wait: true when you need all results",agents:["architect"]},collect_lane_results:{description:"collect or poll results for a dispatch_lanes_async batch; supports both non-blocking polling (wait omitted or false) and blocking join (wait: true). Non-blocking polls include pending lane identities by default and process settled lanes incrementally while continuing independent work; busy/retry lanes are not timed out just because they run for a long time. Does not advance workflow gates. Inline output for a settled lane is delivered only once: later polls of the same lane set output_omitted_repeat: true and omit output, but still include output_ref for recovery via retrieve_lane_output.",agents:["architect"]},summarize_work:{description:"emit a short structured summary of completed work (key decisions, assumptions, risks, constraints) at task completion; rolls up per phase for architecture-supervisor review. Advisory, never blocks.",agents:["architect","sme","researcher","docs","docs_design","designer","explorer","coder","test_engineer"]},write_architecture_supervisor_evidence:{description:"persist the architecture supervisor verdict for a phase (architect MUST dispatch critic_architecture_supervisor first and collect its JSON verdict; this tool persists only, it does not contact the supervisor)",agents:["architect"]},lean_turbo_plan_lanes:{description:"partition phase tasks into parallel lanes based on file-scope conflicts for Lean Turbo execution",agents:[]},lean_turbo_acquire_locks:{description:"acquire file locks for all files in a lane (all-or-nothing) before lane execution",agents:[]},lean_turbo_runner_status:{description:"read Lean Turbo run state from .swarm/turbo-state.json",agents:[]},lean_turbo_review:{description:"dispatch a read-only reviewer agent to evaluate a completed Lean Turbo phase",agents:[]},lean_turbo_run_phase:{description:"Execute a phase using Lean Turbo parallel lane execution. Plans lanes, acquires file locks, and dispatches coder agents concurrently. Use when Lean Turbo is active and you want to execute all tasks in a phase in parallel lanes.",agents:[]},lean_turbo_status:{description:"returns Lean Turbo configuration and active status for the current session",agents:[]},swarm_apply_patch:{description:"Apply a unified diff patch to workspace files with exact context matching, atomic writes, and path validation. Use standard unified diff format only — does NOT support *** Begin Patch / *** Update File payloads (use native apply_patch for those).",agents:["coder","test_engineer"]},external_skill_discover:{description:"Discover external skill candidates from configured sources. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_list:{description:"List external skill candidates in the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_inspect:{description:"Inspect a specific external skill candidate by ID. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_promote:{description:"Promote a validated external skill candidate to an active generated skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_reject:{description:"Reject an external skill candidate after evaluation. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_delete:{description:"Delete an external skill candidate from the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_revoke:{description:"Revoke a previously promoted external skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},epic_decide_phase:{description:"Compute the Epic Mode verdict for a phase WITHOUT dispatching coders. Runs preflight + calibration + the three gates (p-threshold, hot-module, greenfield), persists the decision, and returns the verdict so the architect can dispatch waves via the visible Task tool (promote) or fall back to per-task serial (demote). Pair with `epic_plan_waves` to get the wave plan when promoted. Use when /swarm epic is on for the session.",agents:["architect"]},epic_plan_waves:{description:"Partition a phase's pending tasks into ordered concurrent waves for Epic Mode dispatch. A wave is a set of tasks with mutually disjoint declared scopes and all dependencies satisfied by prior waves. Returns `{ waves: [{ waveId, taskIds, files }, ...], serializedTasks, degradedTasks }`. "+'For each wave in order, the architect dispatches one `Task(subagent_type="coder", ...)` per `taskId` — all in one assistant message — so the wave runs concurrently and each coder appears as a visible subagent. '+"Wait for the wave to finish before dispatching the next. Pair with `epic_decide_phase` (called first; this tool is only relevant on a `promote` verdict). "+"Preflight reject reasons: `no-plan`, `no-phase`, `phase-empty`, `phase-already-complete`, `scopes-missing` (call `declare_scope` for `missingScopes`), `git-failed` (transient — retry), `planner-error`.",agents:["architect"]},epic_record_divergence:{description:"After every `update_task_status(completed)`, record the task's declared-vs-actual divergence to .swarm/epic/divergence.jsonl. Feeds Epic Mode's self-calibration loop (Capability D). Best-effort: never blocks.",agents:["architect"]}},TOOL_NAMES=Object.keys(TOOL_METADATA),TOOL_NAME_SET=new Set(TOOL_NAMES);TOOL_DESCRIPTIONS=Object.fromEntries(Object.entries(TOOL_METADATA).map(([name,meta])=>[name,meta.description])),AGENT_TOOL_MAP=(()=>{let map=Object.fromEntries(ALL_AGENT_NAMES.map((agent)=>[agent,[]]));for(let[name,meta]of Object.entries(TOOL_METADATA))for(let agent of meta.agents)map[agent].push(name);return map})()});function deepMergeInternal(base,override,depth){if(depth>=10)throw Error("deepMerge exceeded maximum depth of 10");let result={...base};for(let key of Object.keys(override)){let baseVal=base[key],overrideVal=override[key];if(typeof baseVal==="object"&&baseVal!==null&&typeof overrideVal==="object"&&overrideVal!==null&&!Array.isArray(baseVal)&&!Array.isArray(overrideVal))result[key]=deepMergeInternal(baseVal,overrideVal,depth+1);else result[key]=overrideVal}return result}function deepMerge(base,override){if(!base)return override;if(!override)return base;return deepMergeInternal(base,override,0)}var MAX_MERGE_DEPTH=10;function freezeSet(items){let set=new Set(items),proxy=new Proxy(set,{get(target,prop){if(prop==="add"||prop==="delete"||prop==="clear")return()=>{throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")};if(prop==="forEach")return(callback,thisArg)=>{let wrapped=(v,k)=>callback.call(thisArg??void 0,v,k,proxy);return set.forEach(wrapped)};let value=Reflect.get(target,prop);return typeof value==="function"?value.bind(target):value},set(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},deleteProperty(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},defineProperty(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},setPrototypeOf(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")}});return proxy}function isQAAgent(name){return QA_AGENTS.includes(name)}function isSubagent(name){return ALL_SUBAGENT_NAMES.includes(name)}function isLowCapabilityModel(modelId){let lower=(modelId||"").toLowerCase();return LOW_CAPABILITY_MODELS.some((substr)=>lower.includes(substr))}var OPENCODE_NATIVE_AGENTS,CLAUDE_CODE_NATIVE_COMMANDS,MEMORY_AGENT_TOOL_MAP,EXTERNAL_SKILL_TOOL_NAMES,EXTERNAL_SKILL_AGENT_TOOL_MAP,COUNCIL_TOOL_NAMES,COUNCIL_AGENT_TOOL_MAP,GENERAL_COUNCIL_TOOL_NAMES,GENERAL_COUNCIL_AGENT_TOOL_MAP,TURBO_TOOL_NAMES,TURBO_AGENT_TOOL_MAP,SKILL_TOOL_NAMES,SKILL_AGENT_TOOL_MAP,WRITE_TOOL_NAMES,SUMMARIZER_EXEMPT_TOOL_NAMES,DEFAULT_MODELS,DEFAULT_AGENT_CONFIGS,DEFAULT_SCORING_CONFIG,LOW_CAPABILITY_MODELS,TURBO_MODE_BANNER=`## \uD83D\uDE80 TURBO MODE ACTIVE
2
2
 
3
3
  **Speed optimization enabled for this session.**
4
4
 
@@ -182,7 +182,7 @@ ${trimmed}`}else malformedRows++;continue}let rowFields=fields.slice(0,CANDIDATE
182
182
  `)){let trimmed=line.trim();if(trimmed.length===0)continue;let fields=trimmed.split("\t");if(fields.length<3)return null;let added=fields[0]==="-"?0:Number.parseInt(fields[0],10),deleted=fields[1]==="-"?0:Number.parseInt(fields[1],10);if(Number.isNaN(added)||Number.isNaN(deleted))return null;changedFiles+=1,changedLines+=added+deleted}let rawOutput=await runGitAsync(directory,["diff","--raw",range]);if(rawOutput===null)return null;let hasSubmoduleChange=rawOutput.split(`
183
183
  `).some((line)=>GITLINK_MODE_PATTERN.test(line.trim()));return{changedLines,changedFiles,hasSubmoduleChange}}function isSafeGitRevisionToken(value){return/^(?!-)[A-Za-z0-9][A-Za-z0-9._/-]{0,255}$/.test(value)&&!value.includes("..")&&!value.includes("//")&&!value.includes("@{")}function resolveCurrentUpstreamRemoteRef(directory){let upstream=runGit(directory,["rev-parse","--symbolic-full-name","@{upstream}"]);if(!upstream?.startsWith("refs/remotes/")||upstream.endsWith("/HEAD"))return null;return upstream}function resolveCurrentUpstreamPushTarget(directory){let localBranchRef=runGit(directory,["symbolic-ref","--quiet","HEAD"]);if(!localBranchRef?.startsWith("refs/heads/"))return null;let encoded=runGit(directory,["for-each-ref","--format=%(upstream:remotename)%00%(upstream:remoteref)%00%(upstream)",localBranchRef]);if(!encoded)return null;let[remoteName,remoteBranchRef,remoteTrackingRef,...extras]=encoded.split("\x00");if(extras.length>0||!remoteName||remoteName.startsWith("-")||/[\s;&|<>`]/.test(remoteName)||!remoteBranchRef?.startsWith("refs/heads/")||remoteBranchRef==="refs/heads/"||/[\s;&|<>`]/.test(remoteBranchRef)||!remoteTrackingRef?.startsWith("refs/remotes/")||remoteTrackingRef.endsWith("/HEAD"))return null;return{remoteName,remoteBranchRef,remoteTrackingRef}}async function resolveCurrentUpstreamPushTargetAsync(directory){let localBranchRef=await runGitAsync(directory,["symbolic-ref","--quiet","HEAD"]);if(!localBranchRef?.startsWith("refs/heads/"))return null;let encoded=await runGitAsync(directory,["for-each-ref","--format=%(upstream:remotename)%00%(upstream:remoteref)%00%(upstream)",localBranchRef]);if(!encoded)return null;let[remoteName,remoteBranchRef,remoteTrackingRef,...extras]=encoded.split("\x00");if(extras.length>0||!remoteName||remoteName.startsWith("-")||/[\s;&|<>`]/.test(remoteName)||!remoteBranchRef?.startsWith("refs/heads/")||remoteBranchRef==="refs/heads/"||/[\s;&|<>`]/.test(remoteBranchRef)||!remoteTrackingRef?.startsWith("refs/remotes/")||remoteTrackingRef.endsWith("/HEAD"))return null;return{remoteName,remoteBranchRef,remoteTrackingRef}}function resolveExactRemoteBranchHead(directory,remoteName,remoteBranchRef){if(!remoteName||remoteName.startsWith("-")||/[\s;&|<>`]/.test(remoteName)||!remoteBranchRef.startsWith("refs/heads/")||remoteBranchRef==="refs/heads/"||/[\s;&|<>`]/.test(remoteBranchRef))return null;let output=runGit(directory,["ls-remote","--exit-code","--heads",remoteName,remoteBranchRef],20000);if(!output)return null;let rows=output.split(/\r?\n/).filter(Boolean);if(rows.length!==1)return null;let[objectName,refName,...extras]=rows[0].split(/\s+/);if(extras.length>0||refName!==remoteBranchRef||!objectName||!(/^[0-9a-f]{40}$/i.test(objectName)||/^[0-9a-f]{64}$/i.test(objectName)))return null;return objectName}async function resolveExactRemoteBranchHeadAsync(directory,remoteName,remoteBranchRef){if(!remoteName||remoteName.startsWith("-")||/[\s;&|<>`]/.test(remoteName)||!remoteBranchRef.startsWith("refs/heads/")||remoteBranchRef==="refs/heads/"||/[\s;&|<>`]/.test(remoteBranchRef))return null;let output=await runGitAsync(directory,["ls-remote","--exit-code","--heads",remoteName,remoteBranchRef],20000);if(!output)return null;let rows=output.split(/\r?\n/).filter(Boolean);if(rows.length!==1)return null;let[objectName,refName,...extras]=rows[0].split(/\s+/);if(extras.length>0||refName!==remoteBranchRef||!objectName||!(/^[0-9a-f]{40}$/i.test(objectName)||/^[0-9a-f]{64}$/i.test(objectName)))return null;return objectName}function resolveGitControlStateDigest(directory){let head=runGit(directory,["rev-parse","--verify","HEAD^{commit}"]),symbolicHead=runGit(directory,["symbolic-ref","--quiet","HEAD"]),upstream=resolveCurrentUpstreamPushTarget(directory),refs=runGit(directory,["for-each-ref","--format=%(refname)%00%(objectname)","refs/heads","refs/remotes","refs/tags"]),config2=runGit(directory,["config","--null","--show-origin","--show-scope","--list"]),index=runGit(directory,["ls-files","--stage","-z"]);if(head===null||symbolicHead===null||!upstream||refs===null||config2===null||index===null)return null;return digest(`head\x00${head}\x00symbolic\x00${symbolicHead}\x00upstream\x00${upstream.remoteName}\x00${upstream.remoteBranchRef}\x00${upstream.remoteTrackingRef}\x00refs\x00${refs}\x00config\x00${config2}\x00index\x00${index}`)}async function resolveGitControlStateDigestAsync(directory){let head=await runGitAsync(directory,["rev-parse","--verify","HEAD^{commit}"]),symbolicHead=await runGitAsync(directory,["symbolic-ref","--quiet","HEAD"]),upstream=await resolveCurrentUpstreamPushTargetAsync(directory),refs=await runGitAsync(directory,["for-each-ref","--format=%(refname)%00%(objectname)","refs/heads","refs/remotes","refs/tags"]),config2=await runGitAsync(directory,["config","--null","--show-origin","--show-scope","--list"]),index=await runGitAsync(directory,["ls-files","--stage","-z"]);if(head===null||symbolicHead===null||!upstream||refs===null||config2===null||index===null)return null;return digest(`head\x00${head}\x00symbolic\x00${symbolicHead}\x00upstream\x00${upstream.remoteName}\x00${upstream.remoteBranchRef}\x00${upstream.remoteTrackingRef}\x00refs\x00${refs}\x00config\x00${config2}\x00index\x00${index}`)}function resolveIsWorkingTreeClean(directory){let status=runGit(directory,["status","--porcelain=v1","--untracked-files=all"]);return status===null?null:status.length===0}async function resolveIsWorkingTreeCleanAsync(directory){let status=await runGitAsync(directory,["status","--porcelain=v1","--untracked-files=all"]);return status===null?null:status.length===0}function resolveCommitCountSince(directory,baseHeadSha,currentHeadSha){if(!isSafeGitRevisionToken(baseHeadSha)||!isSafeGitRevisionToken(currentHeadSha))return null;let output=runGit(directory,["rev-list","--count","--ancestry-path",`${baseHeadSha}..${currentHeadSha}`,"--"]);if(!output||!/^\d+$/.test(output))return null;let count=Number(output);return Number.isSafeInteger(count)?count:null}async function resolveCommitCountSinceAsync(directory,baseHeadSha,currentHeadSha){if(!isSafeGitRevisionToken(baseHeadSha)||!isSafeGitRevisionToken(currentHeadSha))return null;let output=await runGitAsync(directory,["rev-list","--count","--ancestry-path",`${baseHeadSha}..${currentHeadSha}`,"--"]);if(!output||!/^\d+$/.test(output))return null;let count=Number(output);return Number.isSafeInteger(count)?count:null}function resolveIsExactSingleChildCommit(directory,baseHeadSha,currentHeadSha){if(!isSafeGitRevisionToken(baseHeadSha)||!isSafeGitRevisionToken(currentHeadSha))return null;let base=runGit(directory,["rev-parse","--verify",`${baseHeadSha}^{commit}`,"--"]),current=runGit(directory,["rev-parse","--verify",`${currentHeadSha}^{commit}`,"--"]);if(!base||!current)return null;let commitAndParents=runGit(directory,["rev-list","--parents","-n","1",current]);if(commitAndParents===null)return null;let fields=commitAndParents.trim().split(/\s+/);return fields.length===2&&fields[0]?.toLowerCase()===current.toLowerCase()&&fields[1]?.toLowerCase()===base.toLowerCase()}async function resolveIsExactSingleChildCommitAsync(directory,baseHeadSha,currentHeadSha){if(!isSafeGitRevisionToken(baseHeadSha)||!isSafeGitRevisionToken(currentHeadSha))return null;let base=await runGitAsync(directory,["rev-parse","--verify",`${baseHeadSha}^{commit}`,"--"]),current=await runGitAsync(directory,["rev-parse","--verify",`${currentHeadSha}^{commit}`,"--"]);if(!base||!current)return null;let commitAndParents=await runGitAsync(directory,["rev-list","--parents","-n","1",current]);if(commitAndParents===null)return null;let fields=commitAndParents.trim().split(/\s+/);return fields.length===2&&fields[0]?.toLowerCase()===current.toLowerCase()&&fields[1]?.toLowerCase()===base.toLowerCase()}function resolveRemoteRefsContainingHead(directory,headSha){let output=runGit(directory,["for-each-ref","--format=%(refname)%09%(objectname)","refs/remotes"]);if(output===null)return null;return output.split(/\r?\n/).map((line)=>line.trim().split("\t")).filter(([ref,objectName])=>ref?.startsWith("refs/remotes/")&&!ref.endsWith("/HEAD")&&objectName?.toLowerCase()===headSha.toLowerCase()).map(([ref])=>ref)}async function resolveRemoteRefsContainingHeadAsync(directory,headSha){let output=await runGitAsync(directory,["for-each-ref","--format=%(refname)%09%(objectname)","refs/remotes"]);if(output===null)return null;return output.split(/\r?\n/).map((line)=>line.trim().split("\t")).filter(([ref,objectName])=>ref?.startsWith("refs/remotes/")&&!ref.endsWith("/HEAD")&&objectName?.toLowerCase()===headSha.toLowerCase()).map(([ref])=>ref)}async function resolvePrFeedbackTrackingCandidatesAsync(directory,headSha){let[localOutput,remoteRefs]=await Promise.all([runGitAsync(directory,["for-each-ref","--format=%(refname)%09%(objectname)%09%(upstream)","refs/heads"]),resolveRemoteRefsContainingHeadAsync(directory,headSha)]);if(localOutput===null||remoteRefs===null)return null;let exactRemoteRefs=new Set(remoteRefs);return{local:localOutput.split(/\r?\n/).map((line)=>line.trim().split("\t")).flatMap(([ref,objectName,upstream,...extras])=>{if(extras.length>0||!ref?.startsWith("refs/heads/")||objectName?.toLowerCase()!==headSha.toLowerCase()||!upstream?.startsWith("refs/remotes/")||!exactRemoteRefs.has(upstream))return[];return[{kind:"local",branchName:ref.slice(11),remoteTrackingRef:upstream}]}),remote:remoteRefs.map((remoteTrackingRef)=>({kind:"remote",remoteTrackingRef}))}}async function switchPrFeedbackTrackingCandidateAsync(directory,candidate){let args2=candidate.kind==="local"?["switch","--no-guess","--",candidate.branchName]:["switch","--track","--",candidate.remoteTrackingRef];return await runGitAsync(directory,args2)!==null}function resolvePrWorkflowRevisionDigest(directory,baseHeadSha){let projectRoot=path11.resolve(directory),baseHead=runGit(projectRoot,["rev-parse","--verify",`${baseHeadSha}^{commit}`]),diffNames=runGit(projectRoot,["diff","--no-ext-diff","--name-only","-z",baseHeadSha]),porcelain=runGit(projectRoot,["status","--porcelain=v1","-z","--untracked-files=all"]);if(!baseHead||diffNames===null||porcelain===null)return null;let porcelainPaths=parsePorcelainPaths(porcelain);if(!porcelainPaths)return null;let changedPaths=[...new Set([...parseNulPaths(diffNames),...porcelainPaths])].sort((left,right)=>left.localeCompare(right));if(changedPaths.length>REVISION_MAX_FILES)return null;let hash2=createHash6("sha256");hash2.update(`base\x00${baseHead}\x00`);let totalBytes=0;for(let relativePath of changedPaths){let resolvedPath=path11.resolve(projectRoot,relativePath),relativeToRoot=path11.relative(projectRoot,resolvedPath);if(!relativeToRoot||relativeToRoot.startsWith("..")||path11.isAbsolute(relativeToRoot))return null;hash2.update(`path\x00${relativePath}\x00`);let stats2;try{stats2=fs7.lstatSync(resolvedPath)}catch(error49){if(error49.code==="ENOENT"){hash2.update("deleted\x00");continue}return null}if(stats2.isSymbolicLink())try{hash2.update(`symlink\x00${fs7.readlinkSync(resolvedPath)}\x00`);continue}catch{return null}if(!stats2.isFile()){hash2.update(`node\x00${stats2.mode}\x00`);continue}if(totalBytes+=stats2.size,totalBytes>REVISION_MAX_TOTAL_BYTES)return null;try{hash2.update(`file\x00${stats2.mode}\x00`),hash2.update(fs7.readFileSync(resolvedPath)),hash2.update("\x00")}catch{return null}}return hash2.digest("hex")}async function resolvePrWorkflowRevisionDigestAsync(directory,baseHeadSha){let projectRoot=path11.resolve(directory),[baseHead,diffNames,porcelain]=await Promise.all([runGitAsync(projectRoot,["rev-parse","--verify",`${baseHeadSha}^{commit}`]),runGitAsync(projectRoot,["diff","--no-ext-diff","--name-only","-z",baseHeadSha]),runGitAsync(projectRoot,["status","--porcelain=v1","-z","--untracked-files=all"])]);if(!baseHead||diffNames===null||porcelain===null)return null;let porcelainPaths=parsePorcelainPaths(porcelain);if(!porcelainPaths)return null;let changedPaths=[...new Set([...parseNulPaths(diffNames),...porcelainPaths])].sort((left,right)=>left.localeCompare(right));if(changedPaths.length>REVISION_MAX_FILES)return null;let hash2=createHash6("sha256");hash2.update(`base\x00${baseHead}\x00`);let totalBytes=0,chunksSinceYield=0;for(let relativePath of changedPaths){let resolvedPath=path11.resolve(projectRoot,relativePath),relativeToRoot=path11.relative(projectRoot,resolvedPath);if(!relativeToRoot||relativeToRoot.startsWith("..")||path11.isAbsolute(relativeToRoot))return null;hash2.update(`path\x00${relativePath}\x00`);let stats2;try{stats2=await fs7.promises.lstat(resolvedPath)}catch(error49){if(error49.code==="ENOENT"){hash2.update("deleted\x00");continue}return null}if(stats2.isSymbolicLink())try{hash2.update(`symlink\x00${await fs7.promises.readlink(resolvedPath)}\x00`);continue}catch{return null}if(!stats2.isFile()){hash2.update(`node\x00${stats2.mode}\x00`);continue}if(totalBytes+=stats2.size,totalBytes>REVISION_MAX_TOTAL_BYTES)return null;hash2.update(`file\x00${stats2.mode}\x00`);let handle;try{handle=await fs7.promises.open(resolvedPath,"r");let buffer=Buffer.allocUnsafe(REVISION_READ_CHUNK_BYTES);for(let position=0;position<stats2.size;){let length=Math.min(REVISION_READ_CHUNK_BYTES,stats2.size-position),{bytesRead}=await handle.read(buffer,0,length,position);if(bytesRead<=0)return null;if(hash2.update(buffer.subarray(0,bytesRead)),position+=bytesRead,chunksSinceYield++,chunksSinceYield>=REVISION_YIELD_EVERY_CHUNKS)chunksSinceYield=0,await _internals6.yieldControl()}hash2.update("\x00")}catch{return null}finally{await handle?.close().catch(()=>{return})}}return hash2.digest("hex")}function parseNulPaths(output){return output.split("\x00").filter((entry)=>entry.length>0)}function parsePorcelainPaths(output){let entries=parseNulPaths(output),paths=[];for(let index=0;index<entries.length;index++){let entry=entries[index];if(entry.length<4||entry[2]!==" ")return null;let status=entry.slice(0,2),changedPath=entry.slice(3);if(!changedPath)return null;if(paths.push(changedPath),status.includes("R")||status.includes("C")){let originalPath=entries[++index];if(!originalPath)return null;paths.push(originalPath)}}return[...new Set(paths)]}function parsePorcelainV2Snapshot(output){let records=output.split("\x00"),headers=[];while(records[0]?.startsWith("# "))headers.push(records.shift());let oidMatch=headers.join(`
184
184
  `).match(/^# branch\.oid (.+)$/m);if(!oidMatch)return null;if(!/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/i.test(oidMatch[1])&&oidMatch[1]!=="(initial)")return null;let gitHead=oidMatch[1]==="(initial)"?null:oidMatch[1],dirtyTrackedPaths=[],untrackedPaths=[],unmergedPaths=[],unmergedCodes=[],dirtySubmodulePaths=[],renameOrCopy=!1;for(let index=0;index<records.length;index++){let record2=records[index];if(!record2)continue;if(record2.startsWith("? ")){untrackedPaths.push(record2.slice(2));continue}if(record2.startsWith("1 ")){let fields=record2.split(" "),changedPath=porcelainV2PathAfterFields(record2,8);if(!changedPath||!fields[2])return null;if(dirtyTrackedPaths.push(changedPath),fields[2]!=="N...")dirtySubmodulePaths.push(changedPath);continue}if(record2.startsWith("2 ")){let fields=record2.split(" "),changedPath=porcelainV2PathAfterFields(record2,9),originalPath=records[++index];if(!changedPath||!originalPath||!fields[2])return null;if(renameOrCopy=!0,dirtyTrackedPaths.push(changedPath,originalPath),fields[2]!=="N...")dirtySubmodulePaths.push(changedPath);continue}if(record2.startsWith("u ")){let fields=record2.split(" "),changedPath=porcelainV2PathAfterFields(record2,10),unmergedCode=fields[1];if(!changedPath||!fields[2]||!unmergedCode||!/^(?:DD|AU|UD|UA|DU|AA|UU)$/.test(unmergedCode))return null;if(unmergedPaths.push(changedPath),unmergedCodes.push(unmergedCode),dirtyTrackedPaths.push(changedPath),fields[2]!=="N...")dirtySubmodulePaths.push(changedPath);continue}return null}return{gitHead,dirtyTrackedPaths:[...new Set(dirtyTrackedPaths)],untrackedPaths:[...new Set(untrackedPaths)],renameOrCopy,unmergedPaths:[...new Set(unmergedPaths)],unmergedCodes:[...new Set(unmergedCodes)],dirtySubmodulePaths:[...new Set(dirtySubmodulePaths)]}}function porcelainV2PathAfterFields(record2,fields){let offset=0;for(let index=0;index<fields;index++){let delimiter=record2.indexOf(" ",offset);if(delimiter<0)return null;offset=delimiter+1}return record2.slice(offset)||null}function captureWorkspaceSnapshot(directory,optionsOrScope=null,prHeadShaArg=null){let scope=typeof optionsOrScope==="object"&&optionsOrScope!==null?optionsOrScope.scope??null:optionsOrScope,configuredPrHeadSha=(()=>{if(typeof optionsOrScope!=="object"||optionsOrScope===null)return prHeadShaArg;return optionsOrScope.prHeadSha??null})(),resolveCurrentPrHeadSha=typeof optionsOrScope==="object"&&optionsOrScope!==null&&optionsOrScope.resolveCurrentPrHeadSha===!0,upstreamBefore=resolveCurrentPrHeadSha?runGit(directory,["rev-parse","@{upstream}"]):null,porcelain=runGit(directory,["status","--porcelain=v2","--branch","-z","--untracked-files=all"]),snapshot=porcelain===null?null:parsePorcelainV2Snapshot(porcelain),upstreamAfter=resolveCurrentPrHeadSha?runGit(directory,["rev-parse","@{upstream}"]):null,prHeadSha=resolveCurrentPrHeadSha?upstreamBefore&&upstreamBefore===upstreamAfter?upstreamBefore:null:configuredPrHeadSha;return{directory:path11.resolve(directory),gitHead:snapshot?.gitHead??null,dirtyHash:porcelain===null?null:digest(porcelain),changedFiles:snapshot?[...new Set([...snapshot.dirtyTrackedPaths,...snapshot.untrackedPaths])]:null,prHeadSha,scope}}function changedFilesSinceSnapshot(directory,baseline){if(!baseline?.gitHead||baseline.changedFiles==null)return null;if(baseline.changedFiles.length>0)return null;let current=captureWorkspaceSnapshot(directory);if(!current.gitHead||current.changedFiles==null)return null;let changed=new Set(current.changedFiles);if(baseline.gitHead!==current.gitHead){let committed=runGit(directory,["diff","--name-only","-z",baseline.gitHead,current.gitHead]);if(committed===null)return null;for(let changedPath of parseNulPaths(committed))changed.add(changedPath)}return[...changed]}function workspaceSnapshotMatches(expected,current){if(!expected)return{ok:!0};if(path11.resolve(expected.directory)!==path11.resolve(current.directory))return{ok:!1,reason:`directory changed: expected ${expected.directory}, got ${current.directory}`};let checks3=["gitHead","dirtyHash","prHeadSha"];for(let key of checks3){let expectedValue=expected[key];if(expectedValue===null)continue;if(current[key]!==expectedValue)return{ok:!1,reason:`${key} changed: expected ${expectedValue}, got ${current[key]??"unknown"}`}}return{ok:!0}}function compareWorkspaceSnapshots(expected,current){let result=workspaceSnapshotMatches(expected,current);if(result.ok)return{stale:!1};return{stale:!0,reason:result.reason}}function digest(text){return createHash6("sha256").update(text).digest("hex")}var GIT_SNAPSHOT_TIMEOUT_MS=3000,GIT_SNAPSHOT_MAX_BUFFER=524288,REVISION_MAX_FILES=5000,REVISION_MAX_TOTAL_BYTES=67108864,REVISION_READ_CHUNK_BYTES=65536,REVISION_YIELD_EVERY_CHUNKS=16,GITLINK_MODE_PATTERN,compareWorkspaceSnapshot,_internals6;var init_workspace_snapshot=__esm(()=>{init_bun_compat();GITLINK_MODE_PATTERN=/^:\d{6} 160000 |^:160000 \d{6} /;compareWorkspaceSnapshot=workspaceSnapshotMatches;_internals6={spawnSync:child_process.spawnSync,bunSpawn,gitTimeoutMs:GIT_SNAPSHOT_TIMEOUT_MS,yieldControl:()=>new Promise((resolve7)=>setImmediate(resolve7)),parsePorcelainV2Snapshot}});import*as fs8 from"node:fs";import*as path12 from"node:path";function isExecutableFile(candidate){try{return fs8.statSync(candidate).isFile()}catch{return!1}}function resolveExecutableFromPath(names,envPath=process.env.PATH??"",platform=process.platform){let pathEntries=envPath.split(path12.delimiter).filter(Boolean),isWindows=platform==="win32";for(let rawName of names){if(!rawName)continue;if(path12.isAbsolute(rawName)&&isExecutableFile(rawName))return rawName;let extensions=isWindows&&path12.extname(rawName)===""?DEFAULT_WINDOWS_EXTENSIONS:[""];for(let dir of pathEntries)for(let ext of extensions){let candidate=path12.join(dir,`${rawName}${ext}`);if(isExecutableFile(candidate))return candidate}}return null}async function readBoundedStream(stream,maxBytes){let reader=stream.getReader(),lockReleased=!1,releaseLock=()=>{if(lockReleased)return;lockReleased=!0;try{reader.releaseLock()}catch{}},cancelAndRelease=async()=>{try{await reader.cancel()}catch{}finally{releaseLock()}};if(maxBytes<=0)return await cancelAndRelease(),{text:"",truncated:!0};let chunks=[],total=0,truncated=!1;try{for(;;){let{done,value}=await reader.read();if(done)break;if(!value)continue;let remaining=maxBytes-total;if(value.byteLength>remaining){if(remaining>0)chunks.push(value.slice(0,remaining)),total+=remaining;truncated=!0,await cancelAndRelease();break}chunks.push(value),total+=value.byteLength}}finally{releaseLock()}let out=new Uint8Array(total),offset=0;for(let chunk of chunks)out.set(chunk,offset),offset+=chunk.byteLength;return{text:new TextDecoder().decode(out),truncated}}function timeoutKillSignal(platform){return platform==="win32"?"SIGTERM":"SIGKILL"}function killProcess(proc){try{proc?.kill(timeoutKillSignal(_internals7.platform()))}catch{}}async function runExternalTool(options){if(!path12.isAbsolute(options.cwd))return{status:"spawn-error",exitCode:null,stdout:"",stderr:"",stdoutTruncated:!1,stderrTruncated:!1,message:"external tool cwd must be absolute"};if(options.abortSignal?.aborted)return{status:"cancelled",exitCode:null,stdout:"",stderr:"",stdoutTruncated:!1,stderrTruncated:!1,message:"external tool execution cancelled before spawn"};let proc,timeoutHandle,abortListener,exitSettled=!1,settledExitCode=null;try{proc=_internals7.bunSpawn([options.executable,...options.args],{cwd:options.cwd,env:options.env,stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:options.timeoutMs});let exitPromise=proc.exited.then((exitCode)=>{return exitSettled=!0,settledExitCode=exitCode,{kind:"exit",exitCode}}),timeout=new Promise((resolve7)=>{timeoutHandle=setTimeout(()=>{if(exitSettled){resolve7({kind:"exit",exitCode:settledExitCode??proc?.exitCode??0});return}killProcess(proc),resolve7({kind:"timeout"})},options.timeoutMs)}),cancelled=new Promise((resolve7)=>{if(!options.abortSignal)return;let handled=!1;if(abortListener=()=>{if(handled)return;handled=!0,killProcess(proc),resolve7({kind:"cancelled"})},options.abortSignal.addEventListener("abort",abortListener,{once:!0}),options.abortSignal.aborted)abortListener()}),stdoutPromise=readBoundedStream(proc.stdout,options.maxStdoutBytes),stderrPromise=readBoundedStream(proc.stderr,options.maxStderrBytes),exitResult=await Promise.race([exitPromise,timeout,cancelled]);if(exitResult.kind==="timeout")return{status:"timeout",exitCode:proc.exitCode,stdout:"",stderr:"",stdoutTruncated:!1,stderrTruncated:!1};if(exitResult.kind==="cancelled")return{status:"cancelled",exitCode:proc.exitCode,stdout:"",stderr:"",stdoutTruncated:!1,stderrTruncated:!1,message:"external tool execution cancelled"};let[stdout,stderr]=await Promise.all([stdoutPromise,stderrPromise]);return{status:"completed",exitCode:exitResult.exitCode,stdout:stdout.text,stderr:stderr.text,stdoutTruncated:stdout.truncated,stderrTruncated:stderr.truncated}}catch(err){return{status:"spawn-error",exitCode:proc?.exitCode??null,stdout:"",stderr:"",stdoutTruncated:!1,stderrTruncated:!1,message:err instanceof Error?err.message:String(err)}}finally{if(timeoutHandle!==void 0)clearTimeout(timeoutHandle);if(abortListener&&options.abortSignal)options.abortSignal.removeEventListener("abort",abortListener);if(proc)try{proc.kill()}catch{}}}var DEFAULT_WINDOWS_EXTENSIONS,_internals7;var init_external_tool_runner=__esm(()=>{init_bun_compat();DEFAULT_WINDOWS_EXTENSIONS=[".exe",".cmd",".bat"];_internals7={bunSpawn,platform:()=>process.platform}});import*as fsp2 from"node:fs/promises";import*as path13 from"node:path";function boundPath(value){let cleaned=value.replace(/[\p{Cc}]/gu," ").replace(/[`<>]/g," ").replace(/\s+/g," ").trim();return cleaned.length>MAX_EVIDENCE_PATH_LENGTH?`${cleaned.slice(0,MAX_EVIDENCE_PATH_LENGTH)}...`:cleaned}function evidence(parsed,worktreeRoot,gitDir,operations,detail){let allPaths=parsed?[...parsed.unmergedPaths,...parsed.dirtySubmodulePaths,...parsed.dirtyTrackedPaths,...parsed.untrackedPaths]:[],uniquePaths=[...new Set(allPaths)].map(boundPath);return{worktreeRoot:worktreeRoot?boundPath(worktreeRoot):null,gitDir:gitDir?boundPath(gitDir):null,operations,unmergedCodes:parsed?[...new Set(parsed.unmergedCodes)].sort():[],paths:uniquePaths.slice(0,MAX_EVIDENCE_PATHS),trackedCount:parsed?.dirtyTrackedPaths.length??0,untrackedCount:parsed?.untrackedPaths.length??0,pathsTruncated:uniquePaths.length>MAX_EVIDENCE_PATHS,...detail?{detail}:{}}}async function runGitCapture(directory,args2){let result=await runExternalTool({executable:"git",args:[...args2],cwd:path13.resolve(directory),timeoutMs:GIT_TIMEOUT_MS,maxStdoutBytes:MAX_GIT_OUTPUT_BYTES,maxStderrBytes:65536});return{ok:result.status==="completed"&&result.exitCode===0&&!result.stdoutTruncated&&!result.stderrTruncated,stdout:result.stdout}}async function activeOperations(gitDir){return(await Promise.all(OPERATION_MARKERS.map(async([name,marker])=>{try{return await fsp2.lstat(path13.join(gitDir,marker)),name}catch(error49){if(error49.code==="ENOENT")return null;throw error49}}))).filter((value)=>value!==null)}async function classifyPrWorkflowGitState(directory){let[statusResult,rootResult,gitDirResult]=await Promise.all([_internals8.runGitCapture(directory,["status","--porcelain=v2","--branch","-z","--untracked-files=all"]),_internals8.runGitCapture(directory,["rev-parse","--show-toplevel"]),_internals8.runGitCapture(directory,["rev-parse","--absolute-git-dir"])]);if(!statusResult.ok||!rootResult.ok||!gitDirResult.ok)return{kind:"indeterminate",code:"GIT_STATE_INDETERMINATE",retryable:!1,requiredAction:"Confirm this is a readable Git worktree and resolve filesystem or Git errors before starting the PR workflow.",evidence:evidence(null,null,null,[],"required Git inspection failed")};let worktreeRoot=rootResult.stdout.trim(),gitDir=gitDirResult.stdout.trim(),parsed=parsePorcelainV2Snapshot(statusResult.stdout);if(!worktreeRoot||!gitDir||!parsed)return{kind:"indeterminate",code:"GIT_STATE_INDETERMINATE",retryable:!1,requiredAction:"Resolve the malformed or incomplete Git status before starting the PR workflow.",evidence:evidence(parsed,worktreeRoot||null,gitDir||null,[],"Git returned an incomplete status snapshot")};let operations;try{operations=await _internals8.activeOperations(path13.resolve(gitDir))}catch{return{kind:"indeterminate",code:"GIT_STATE_INDETERMINATE",retryable:!1,requiredAction:"Resolve the unreadable Git operation state before starting the PR workflow.",evidence:evidence(parsed,worktreeRoot,gitDir,[],"Git operation markers could not be inspected")}}let stateEvidence=evidence(parsed,worktreeRoot,gitDir,operations);if(parsed.unmergedCodes.length>0)return{kind:"recovery-required",code:"UNMERGED_INDEX",retryable:!1,requiredAction:"Resolve or abort the current merge/rebase/cherry-pick/revert operation manually; conflicted index entries must never be stashed by PR workflow startup.",evidence:stateEvidence};if(operations.length>0)return{kind:"recovery-required",code:"GIT_OPERATION_IN_PROGRESS",retryable:!1,requiredAction:"Complete or abort the active Git operation manually before starting the PR workflow.",evidence:stateEvidence};if(parsed.dirtySubmodulePaths.length>0)return{kind:"recovery-required",code:"DIRTY_SUBMODULE",retryable:!1,requiredAction:"Resolve or preserve dirty submodule worktrees manually; the checkout-preparation stash cannot safely preserve them.",evidence:stateEvidence};if([...parsed.dirtyTrackedPaths,...parsed.untrackedPaths].find((candidate)=>candidate===".swarm"||candidate.startsWith(".swarm/")||candidate.startsWith(".swarm\\")))return{kind:"recovery-required",code:"SWARM_STATE_TRACKING_ERROR",retryable:!1,requiredAction:"Restore .swarm/ so it is git-excluded before starting the PR workflow; runtime state must not be treated as checkout dirt.",evidence:stateEvidence};if(parsed.dirtyTrackedPaths.length===0&&parsed.untrackedPaths.length===0)return{kind:"clean",code:"CLEAN",retryable:!0,requiredAction:"No checkout recovery is required.",evidence:stateEvidence};return{kind:"stashable",code:"STASHABLE_CHANGES",retryable:!0,requiredAction:"Run prepare_pr_workflow_checkout once to preserve the ordinary working-tree changes before checkout.",evidence:stateEvidence}}var GIT_TIMEOUT_MS=5000,MAX_GIT_OUTPUT_BYTES=524288,MAX_EVIDENCE_PATHS=20,MAX_EVIDENCE_PATH_LENGTH=240,OPERATION_MARKERS,_internals8;var init_pr_workflow_state=__esm(()=>{init_workspace_snapshot();init_external_tool_runner();OPERATION_MARKERS=[["merge","MERGE_HEAD"],["rebase-merge","rebase-merge"],["rebase-apply-or-am","rebase-apply"],["cherry-pick","CHERRY_PICK_HEAD"],["revert","REVERT_HEAD"],["bisect","BISECT_START"],["sequencer","sequencer"]];_internals8={runGitCapture,activeOperations,parsePorcelainV2:parsePorcelainV2Snapshot}});import{createHash as createHash7,randomUUID as randomUUID2}from"node:crypto";import{readFileSync as readFileSync6}from"node:fs";import*as fsp3 from"node:fs/promises";import*as path14 from"node:path";function computePrReviewDepthTier(stats2){if(!stats2)return"L";if(stats2.hasSubmoduleChange)return"L";if(stats2.changedLines<=PR_REVIEW_DEPTH_TIER_THRESHOLDS.smallMaxChangedLines&&stats2.changedFiles<=PR_REVIEW_DEPTH_TIER_THRESHOLDS.smallMaxChangedFiles)return"S";if(stats2.changedLines<=PR_REVIEW_DEPTH_TIER_THRESHOLDS.mediumMaxChangedLines&&stats2.changedFiles<=PR_REVIEW_DEPTH_TIER_THRESHOLDS.mediumMaxChangedFiles)return"M";return"L"}function formatCheckoutRecoveryBlock(state){let evidence2=JSON.stringify({operations:state.evidence.operations,unmerged_codes:state.evidence.unmergedCodes,paths:state.evidence.paths,paths_truncated:state.evidence.pathsTruncated});return`BLOCKED: PR workflow checkout requires manual Git recovery before activation. code=${state.code} retryable=false required_action=${state.requiredAction} evidence=${evidence2}`}function checkoutRecoveryRecord(state){if(state.kind!=="recovery-required"&&state.kind!=="indeterminate")throw Error("PR workflow checkout recovery requires a terminal Git state");return{code:state.code,retryable:!1,requiredAction:state.requiredAction,evidence:state.evidence,detectedAt:isoNow()}}async function activatePrWorkflow(directory,sessionID,mode,options={}){let normalizedSessionID=normalizeSessionID(sessionID),existing=await readPrWorkflowGateState(directory,normalizedSessionID);if(existing?.mode===mode){let activeState=existing;if(mode==="PR_FEEDBACK"&&options.prUrl){let requestedTarget=canonicalGitHubPrUrl(options.prUrl);if(!requestedTarget)throw Error("BLOCKED: PR_FEEDBACK target must be a canonical GitHub PR URL");let existingTarget=existing.prFeedbackTargetUrl?canonicalGitHubPrUrl(existing.prFeedbackTargetUrl):null;if(existingTarget&&requestedTarget!==existingTarget)throw Error("BLOCKED: active PR_FEEDBACK targets a different GitHub pull request");if(!existingTarget)activeState={...existing,prFeedbackTargetUrl:options.prUrl,updatedAt:isoNow()},await persistState(directory,activeState)}return options.prHeadSha?bindPrWorkflowHead(directory,normalizedSessionID,options.prHeadSha):activeState}if(existing)throw Error(`BLOCKED: session "${normalizedSessionID}" already has an active ${existing.mode} workflow; complete it before starting ${mode}`);if(options.requireCheckoutPreflight){let checkoutState=await classifyPrWorkflowGitState(directory);if(checkoutState.kind==="recovery-required"||checkoutState.kind==="indeterminate")throw Error(formatCheckoutRecoveryBlock(checkoutState))}let initialHead=options.prHeadSha?await assertCurrentCheckoutHead(directory,options.prHeadSha,mode):void 0,timestamp=isoNow(),feedbackTargetUrl=mode==="PR_FEEDBACK"&&options.prUrl?canonicalGitHubPrUrl(options.prUrl)?options.prUrl:null:void 0;if(feedbackTargetUrl===null)throw Error("BLOCKED: PR_FEEDBACK target must be a canonical GitHub PR URL");let nextState={schemaVersion:GATE_SCHEMA_VERSION,revision:0,workflowInstanceId:randomUUID2(),sessionID:normalizedSessionID,mode,activatedAt:timestamp,updatedAt:timestamp,...initialHead?{prHeadSha:initialHead}:{},...feedbackTargetUrl?{prFeedbackTargetUrl:feedbackTargetUrl}:{}};return await persistState(directory,nextState),nextState}async function readPrWorkflowGateState(directory,sessionID){let normalizedSessionID=normalizeSessionID(sessionID),state=await readPrWorkflowGateStateFromDisk(directory,normalizedSessionID);if(state)rememberState(directory,state);else trackedStatesByProjectSession.delete(stateCacheKey(directory,normalizedSessionID));return state}async function withPrWorkflowCheckoutPreparationLock(directory,sessionID,action){let normalizedSessionID=normalizeSessionID(sessionID);return withPrWorkflowCheckoutMutationLock(directory,async()=>withSessionStateMutation(directory,normalizedSessionID,async()=>{let state=await readPrWorkflowGateStateFromDisk(directory,normalizedSessionID);if(!state)throw Error(`BLOCKED: no active PR workflow gate for session "${normalizedSessionID}". The gate is activated by running \`/swarm pr-review <pr-ref>\` (which activates PR_REVIEW) or \`/swarm pr-feedback <pr-ref>\` (which activates PR_FEEDBACK), or by the first dispatch_lanes_async call with mode "swarm-pr-review:*" / "swarm-pr-feedback:*". Run the appropriate command first, then retry checkout preparation.`);if(state.prHeadSha)throw Error(`BLOCKED: ${state.mode} checkout preparation is allowed only before the PR head is bound`);return action(state,{markRecoveryRequired:async(gitState)=>{let nextState={...state,updatedAt:isoNow(),checkoutRecovery:checkoutRecoveryRecord(gitState)},persisted=await writeStateWhileLocked(directory,nextState);return Object.assign(state,persisted),persisted}})}))}async function clearPrWorkflowGateState(directory,sessionID,expectedRevision){let normalizedSessionID=normalizeSessionID(sessionID);await withSessionStateMutation(directory,normalizedSessionID,async()=>{if(expectedRevision!==void 0){let current=await readPrWorkflowGateStateFromDisk(directory,normalizedSessionID);if(!current||current.revision!==expectedRevision)throw Error("BLOCKED: PR workflow gate state changed during terminal completion; revalidate the current session state before retrying")}try{await fsp3.rm(workflowGateStatePath(directory,normalizedSessionID),{force:!0})}catch(error49){if(error49.code!=="ENOENT")throw error49}trackedStatesByProjectSession.delete(stateCacheKey(directory,normalizedSessionID))})}async function abortPrWorkflow(directory,sessionID,options={}){let state=await requireAnyActiveState(directory,sessionID);if(options.expectedMode&&state.mode!==options.expectedMode)throw wrongModeError(state,options.expectedMode);if(state.prFeedbackReadyToPublish)throw Error(`BLOCKED: ${state.mode} is armed for publication; abort is blocked. Complete the workflow with complete_pr_workflow (or push the bound commit first) before aborting.`);let openLanes=readDelegations(directory).filter((record2)=>record2.parentSessionId===state.sessionID&&record2.mode?.startsWith("swarm-pr-")&&(record2.status==="pending"||record2.status==="running"));if(openLanes.length>0){let laneIds=openLanes.map((record2)=>record2.laneId??record2.subagentSessionId??"unknown").filter(Boolean).slice(0,10).join(", ");throw Error(`BLOCKED: ${state.mode} abort refused while ${openLanes.length} PR workflow lane(s) are still in flight (lane ids: ${laneIds}). Collect their results or let them settle before aborting.`)}let sanitizedReason=typeof options.reason==="string"?options.reason.trim().slice(0,500):void 0,abortEvent={type:"pr_workflow_aborted",timestamp:isoNow(),sessionID:state.sessionID,mode:state.mode,...state.prHeadSha?{prHeadSha:state.prHeadSha}:{},openLanes:openLanes.length,...sanitizedReason?{reason:sanitizedReason}:{}};try{let eventsPath=validateSwarmPath(directory,"events.jsonl");await fsp3.appendFile(eventsPath,`${JSON.stringify(abortEvent)}
185
- `,"utf-8")}catch{}return await clearPrWorkflowGateState(directory,sessionID,state.revision),{mode:state.mode,...state.prHeadSha?{prHeadSha:state.prHeadSha}:{},openLanes:openLanes.length}}async function bindPrWorkflowHead(directory,sessionID,prHeadSha){let normalizedHead=normalizePrHeadSha(prHeadSha);return withPrWorkflowCheckoutMutationLock(directory,async()=>withSessionStateMutation(directory,normalizeSessionID(sessionID),async()=>{let state=await readPrWorkflowGateStateFromDisk(directory,normalizeSessionID(sessionID));if(!state)throw Error(`BLOCKED: no active PR workflow gate for session "${normalizeSessionID(sessionID)}". The gate must be activated before the PR head can be bound.`);if(await assertCurrentCheckoutHead(directory,normalizedHead,state.mode),state.prHeadSha&&state.prHeadSha!==normalizedHead)throw Error(`BLOCKED: active ${state.mode} workflow is bound to PR head "${state.prHeadSha}"; received "${normalizedHead}"`);if(!state.prHeadSha)await assertPrReviewCleanCheckout(directory,state.mode);if(!state.prHeadSha&&state.mode==="PR_FEEDBACK")await assertPrFeedbackTrackingCheckout(directory,normalizedHead);if(state.prHeadSha===normalizedHead){if(state.mode==="PR_FEEDBACK")await assertPrFeedbackTrackingCheckout(directory,normalizedHead);return state}let nextState={...state,prHeadSha:normalizedHead,updatedAt:isoNow()};return await _test_exports.beforePrFeedbackTrackingPersist?.(),writeStateWhileLocked(directory,nextState)}))}async function bindPrReviewBase(directory,sessionID,options){let state=await bindPrWorkflowHead(directory,sessionID,options.prHeadSha);if(state.mode!=="PR_REVIEW")throw Error("BLOCKED: only PR_REVIEW can bind a review merge base");let baseRef=options.baseRef.trim(),baseSha=normalizePrHeadSha(options.baseSha).toLowerCase();if(!baseRef)throw Error("BLOCKED: PR_REVIEW base_ref must not be empty");if(state.prReviewBaseRef&&state.prReviewBaseRef!==baseRef||state.prReviewBaseSha&&state.prReviewBaseSha!==baseSha)throw Error(`BLOCKED: active PR_REVIEW is bound to merge-base scope "${state.prReviewBaseRef??"(unbound)"}" at "${state.prReviewBaseSha??"(unbound)"}"; received "${baseRef}" at "${baseSha}"`);if(state.prReviewBaseRef===baseRef&&state.prReviewBaseSha===baseSha)return state;let prHeadSha=normalizePrHeadSha(options.prHeadSha).toLowerCase(),diffStats=await _test_exports.resolvePrReviewDiffStatsAsync(directory,baseSha,prHeadSha);return state={...state,prReviewBaseRef:baseRef,prReviewBaseSha:baseSha,prReviewDepthTier:computePrReviewDepthTier(diffStats),...diffStats?{prReviewDiffStats:diffStats}:{},updatedAt:isoNow()},await persistState(directory,state),state}async function assertCurrentCheckoutHead(directory,expectedHead,mode="PR_REVIEW"){let normalizedExpected=normalizePrHeadSha(expectedHead),currentHead=(await _test_exports.resolveCurrentGitHeadAsync(directory))?.trim();if(!currentHead)throw Error(`BLOCKED: cannot resolve the current Git HEAD in "${directory}" to verify against PR head "${normalizedExpected}". This means Git could not resolve HEAD (the working directory may not be a Git repository, HEAD may be unborn, the commit object may be missing in a shallow clone, the Git binary may not be on PATH, or the bounded Git invocation may have timed out). Verify with: git -C "${directory}" rev-parse --verify HEAD^{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 these bare, standalone commands from that directory: if the commit is not present locally, \`git fetch origin <pr-head-ref>\`; then \`git switch --detach ${normalizedExpected}\`. Do not prefix the switch with \`git -C\`; the read-only shell classifier refuses \`git -C ... switch\`.`;throw Error(`BLOCKED: current checkout HEAD "${currentHead}" does not match PR head "${normalizedExpected}" (working directory: "${directory}"). ${remediation}`)}return normalizedExpected}async function assertPrReviewCleanCheckout(directory,mode="PR_REVIEW"){if(await _test_exports.resolveIsWorkingTreeCleanAsync(directory)!==!0)throw Error(`BLOCKED: ${mode} requires a clean index and working tree at the exact PR head`)}async function assertPrFeedbackTrackingCheckout(directory,prHeadSha){let currentHead=(await _test_exports.resolveCurrentGitHeadAsync(directory))?.trim();if(!currentHead)throw Error("BLOCKED: PR_FEEDBACK requires a resolved exact Git HEAD before first head bind");if(currentHead.toLowerCase()!==prHeadSha.toLowerCase())throw Error(`BLOCKED: PR_FEEDBACK exact head changed before attach; expected ${prHeadSha}, received ${currentHead}`);let currentUpstream=await _test_exports.resolveCurrentUpstreamPushTargetAsync(directory),matchingRemoteRefs=await _test_exports.resolveRemoteRefsContainingHeadAsync(directory,prHeadSha);if(currentUpstream){if(matchingRemoteRefs===null)throw Error("BLOCKED: PR_FEEDBACK could not verify the current upstream against the exact intake PR head; the bounded Git query failed or timed out");if(matchingRemoteRefs.includes(currentUpstream.remoteTrackingRef))return;throw Error(`BLOCKED: PR_FEEDBACK current upstream "${currentUpstream.remoteTrackingRef}" must point to the exact intake PR head "${prHeadSha}"; refusing to replace an existing tracking relationship`)}let candidates=await resolvePrFeedbackTrackingCandidatesAsync(directory,prHeadSha);if(!candidates)throw Error(`BLOCKED: PR_FEEDBACK could not inspect tracked branches for exact PR head "${prHeadSha}"; the bounded Git query failed or timed out`);let{local:localCandidates,remote:remoteCandidates}=candidates;if(localCandidates.length===1){if(await _test_exports.beforePrFeedbackTrackingSwitch?.(),!await switchPrFeedbackTrackingCandidateAsync(directory,localCandidates[0]))throw Error(`BLOCKED: PR_FEEDBACK could not attach exact local tracked branch "${localCandidates[0].branchName}"; it may be checked out in another linked worktree or the bounded Git switch failed`)}else if(localCandidates.length>1)throw Error(`BLOCKED: PR_FEEDBACK exact head "${prHeadSha}" matches multiple local tracked branches: ${localCandidates.map((candidate)=>candidate.branchName).join(", ")}`);else if(remoteCandidates.length===1){if(await _test_exports.beforePrFeedbackTrackingSwitch?.(),!await switchPrFeedbackTrackingCandidateAsync(directory,remoteCandidates[0]))throw Error(`BLOCKED: PR_FEEDBACK could not attach exact remote-tracking branch "${remoteCandidates[0].remoteTrackingRef}"; the bounded Git switch failed or timed out`)}else if(remoteCandidates.length>1)throw Error(`BLOCKED: PR_FEEDBACK exact head "${prHeadSha}" matches multiple remote-tracking refs: ${remoteCandidates.map((candidate)=>candidate.remoteTrackingRef).join(", ")}`);else throw Error("BLOCKED: PR_FEEDBACK requires a current local branch or exact remote-tracking ref that points to the intake PR head before the first bind");await _test_exports.afterPrFeedbackTrackingSwitch?.();let attachedHead=(await _test_exports.resolveCurrentGitHeadAsync(directory))?.trim();if(attachedHead?.toLowerCase()!==prHeadSha.toLowerCase())throw Error(`BLOCKED: PR_FEEDBACK exact head changed after attach; expected ${prHeadSha}, received ${attachedHead??"(unresolved)"}`);if(await _test_exports.resolveIsWorkingTreeCleanAsync(directory)!==!0)throw Error("BLOCKED: PR_FEEDBACK requires a clean working tree after checkout attachment");let attachedUpstream=await _test_exports.resolveCurrentUpstreamPushTargetAsync(directory);if(!attachedUpstream)throw Error("BLOCKED: PR_FEEDBACK could not resolve the attached branch upstream after checkout promotion");if(!(await _test_exports.resolveRemoteRefsContainingHeadAsync(directory,prHeadSha))?.includes(attachedUpstream.remoteTrackingRef))throw Error(`BLOCKED: PR_FEEDBACK upstream "${attachedUpstream.remoteTrackingRef}" must point to the exact intake PR head "${prHeadSha}" before the first head bind`)}async function enforcePrWorkflowDispatchLanesAsync(directory,sessionID,toolName){let state=await readPrWorkflowGateState(directory,sessionID);if(!state)return null;if(toolName===DISPATCH_TOOL_NAME)return state;if(toolName===BLOCKING_DISPATCH_TOOL_NAME)throw Error(`BLOCKED: active ${state.mode} workflow for session "${state.sessionID}" requires ${DISPATCH_TOOL_NAME}; ${BLOCKING_DISPATCH_TOOL_NAME} is not allowed`);return state}async function enforcePrReviewBaseDimensions(directory,sessionID,lanes,options){let state=await bindPrWorkflowHead(directory,sessionID,options.prHeadSha);if(state.mode!=="PR_REVIEW")throw wrongModeError(state,"PR_REVIEW");let normalizedLanes=normalizeWorkflowLanes(lanes),claimedDimensionIds=normalizedLanes.flatMap((lane)=>lane.ownedWorkflowLanes??[lane.workflowLane]);if(claimedDimensionIds.filter((laneId)=>!PR_REVIEW_BASE_DIMENSION_IDS.includes(laneId)).length>0){let expected=PR_REVIEW_BASE_DIMENSION_IDS.join(", "),received=claimedDimensionIds.join(", ")||"(none)";throw Error(`BLOCKED: PR_REVIEW base dispatch lane ids must be drawn from: ${expected}. Received: ${received}`)}if((state.prReviewDepthTier??"L")==="L"&&normalizedLanes.some((lane)=>(lane.ownedWorkflowLanes?.length??1)!==1))throw Error("BLOCKED: PR_REVIEW base dispatch at depth tier L requires one dedicated lane per dimension; consolidated owned_workflow_lanes are allowed only at tiers S and M");let batchId=normalizeBatchId(options.batchId),previous=state.prReviewBaseDispatches??[];if(previous.some((record3)=>record3.batchId===batchId))throw Error(`BLOCKED: PR_REVIEW base batch id "${batchId}" is already recorded`);if(previous.length>=MAX_WORKFLOW_BATCHES)throw Error("BLOCKED: PR_REVIEW base batch limit reached");let record2={batchId,lanes:normalizedLanes.map((lane)=>({laneId:lane.laneId,workflowLane:lane.workflowLane,...lane.ownedWorkflowLanes?{ownedWorkflowLanes:lane.ownedWorkflowLanes}:{}})),validatedAt:isoNow()},nextState={...state,updatedAt:isoNow(),prReviewBaseDispatches:[...previous,record2],prReviewBaseDispatch:record2};return await persistState(directory,nextState),nextState}async function assertPrReviewBaseCoverageSettled(directory,sessionID){let state=await requireBoundState(directory,sessionID,"PR_REVIEW"),batches=state.prReviewBaseDispatches??[];if(batches.length===0)throw Error("BLOCKED: PR_REVIEW requires at least one base batch");let covered=new Set,malformedDiagnostics=[];for(let batch of batches){let successful=successfulObligationsFromExactBatch(directory,state,batch.batchId,batch.lanes,"swarm-pr-review:base",batch.validatedAt,!0,new Set,void 0,malformedDiagnostics);for(let obligation of successful)covered.add(obligation)}let missing=PR_REVIEW_BASE_DIMENSION_IDS.filter((dimension)=>!covered.has(dimension));if(missing.length>0||covered.size!==PR_REVIEW_BASE_DIMENSION_IDS.length)throw Error(`BLOCKED: PR_REVIEW base coverage is incomplete; missing dimensions: ${missing.join(", ")||"(none)"}${malformedDiagnostics.length>0?`; malformed candidate diagnostics: ${malformedDiagnostics.join(" | ")}`:""}`);return state}async function recordPrReviewValidationBatch(directory,sessionID,phase,lanes,options){let state=await bindPrWorkflowHead(directory,sessionID,options.prHeadSha);if(state.mode!=="PR_REVIEW")throw wrongModeError(state,"PR_REVIEW");if(!state.prReviewTriggerEvalPath)throw Error("BLOCKED: PR_REVIEW validation dispatch requires a completed trigger evaluation");if(phase==="reviewer"&&(state.prReviewValidationBatches??[]).some((batch)=>batch.phase==="council"))state=await assertPrReviewValidationSettled(directory,sessionID,"council");else if(phase==="critic")state=await assertPrReviewValidationSettled(directory,sessionID,"reviewer");let normalizedLanes=normalizeWorkflowLanes(lanes);if((phase==="reviewer"||phase==="critic")&&normalizedLanes.some((lane)=>!lane.reviewItemIds?.length))throw Error(`BLOCKED: PR_REVIEW ${phase} lanes require non-empty review_item_ids ownership`);if(phase==="reviewer"||phase==="critic"){assertNoDuplicates(normalizedLanes.flatMap((lane)=>lane.reviewItemIds??[]),`PR_REVIEW ${phase} review item ownership`);let assigned=normalizedLanes.flatMap((lane)=>lane.reviewItemIds??[]),required2=phase==="reviewer"?derivePrReviewCandidateInventory(directory,state):derivePrReviewCriticInventory(directory,state);assertExactStringSet(assigned,required2,`PR_REVIEW ${phase} ownership`)}let batchId=normalizeBatchId(options.batchId),previous=state.prReviewValidationBatches??[];if(previous.some((batch)=>batch.batchId===batchId))throw Error(`BLOCKED: PR_REVIEW validation batch id "${batchId}" is already recorded`);if(previous.length>=MAX_WORKFLOW_BATCHES)throw Error("BLOCKED: PR_REVIEW validation batch limit reached");let record2={batchId,phase,lanes:normalizedLanes,validatedAt:isoNow()},retained=phase==="reviewer"?previous.filter((batch)=>batch.phase!=="critic"):previous,nextState={...state,updatedAt:isoNow(),prReviewValidationBatches:[...retained,record2]};return await persistState(directory,nextState),nextState}async function assertPrReviewValidationSettled(directory,sessionID,phase){let state=await requireBoundState(directory,sessionID,"PR_REVIEW"),declaredPhases=new Set((state.prReviewValidationBatches??[]).map((batch)=>batch.phase)),phases=phase?[phase]:["council","reviewer","critic"].filter((candidate)=>declaredPhases.has(candidate));for(let requiredPhase of phases){let validationBatches=state.prReviewValidationBatches??[],forbiddenSubagentSessionIds=new Set;if(requiredPhase==="critic")for(let reviewerBatch of validationBatches.filter((batch)=>batch.phase==="reviewer"))for(let record2 of findByBatchId(directory,reviewerBatch.batchId,{parentSessionId:state.sessionID})){let subagentSessionId=record2.subagentSessionId?.trim();if(subagentSessionId)forbiddenSubagentSessionIds.add(subagentSessionId)}let batches=validationBatches.filter((batch)=>batch.phase===requiredPhase);if(requiredPhase==="reviewer"){let latestCouncilIndex=-1;for(let index=0;index<validationBatches.length;index++)if(validationBatches[index]?.phase==="council")latestCouncilIndex=index;if(latestCouncilIndex>=0)batches=validationBatches.slice(latestCouncilIndex+1).filter((batch)=>batch.phase==="reviewer")}if(batches.length===0)throw Error(requiredPhase==="reviewer"&&declaredPhases.has("council")?"BLOCKED: PR_REVIEW requires at least one reviewer batch after the latest council batch":`BLOCKED: PR_REVIEW requires at least one ${requiredPhase} batch`);let allObligations=new Set(batches.flatMap((batch)=>batch.lanes.map((lane)=>lane.workflowLane))),settled=new Set,hasFullySuccessfulExactBatch=!1;for(let batch of batches){let successful=successfulObligationsFromExactBatch(directory,state,batch.batchId,batch.lanes,`swarm-pr-review:${requiredPhase}`,batch.validatedAt,!0,forbiddenSubagentSessionIds);if(successful.size===batch.lanes.length&&batch.lanes.every((lane)=>successful.has(lane.workflowLane)))hasFullySuccessfulExactBatch=!0;for(let obligation of successful)settled.add(obligation)}if((requiredPhase==="reviewer"||requiredPhase==="critic")&&!hasFullySuccessfulExactBatch)throw Error(`BLOCKED: PR_REVIEW ${requiredPhase} requires one fully successful exact batch; complementary partial retries are not a coherent verdict set`);let missing=[...allObligations].filter((obligation)=>!settled.has(obligation));if(missing.length>0)throw Error(`BLOCKED: PR_REVIEW ${requiredPhase} obligations lack successful exact artifacts: ${missing.join(", ")}`)}return state}async function declarePrFeedbackInventory(directory,sessionID,inventoryIds,options){let state=await bindPrWorkflowHead(directory,sessionID,options.prHeadSha);if(state.mode!=="PR_FEEDBACK")throw wrongModeError(state,"PR_FEEDBACK");let normalizedInventory=normalizeInventoryIds(inventoryIds),requiredHandoffIds=state.prFeedbackReviewHandoff?.findingIds??[],inventorySet=new Set(normalizedInventory),missingHandoffIds=requiredHandoffIds.filter((findingId)=>!inventorySet.has(findingId));if(missingHandoffIds.length>0)throw Error(`BLOCKED: PR_FEEDBACK inventory must include every continued review finding: ${missingHandoffIds.join(", ")}`);if(state.prFeedbackInventory){if(!sameStringArray(state.prFeedbackInventory,normalizedInventory))throw Error("BLOCKED: PR_FEEDBACK inventory is immutable after declaration");return state}let nextState={...state,updatedAt:isoNow(),prFeedbackInventory:normalizedInventory,prFeedbackVerifications:[]};return await persistState(directory,nextState),nextState}async function enforcePrFeedbackVerificationOwnership(directory,sessionID,ownership,options){let state=await bindPrWorkflowHead(directory,sessionID,options.prHeadSha);if(state.mode!=="PR_FEEDBACK")throw wrongModeError(state,"PR_FEEDBACK");let inventory=state.prFeedbackInventory;if(!inventory||inventory.length===0)throw Error(`BLOCKED: PR_FEEDBACK verification for session "${state.sessionID}" requires a declared feedback inventory before dispatch`);let normalizedOwnership=normalizeOwnership(ownership),inventorySet=new Set(inventory),claimedByItemId=new Map,previous=state.prFeedbackVerifications??[],batchId=normalizeBatchId(options.batchId);if(previous.some((record3)=>record3.batchId===batchId))throw Error(`BLOCKED: PR_FEEDBACK verification batch id "${batchId}" is already recorded`);if(previous.length>=MAX_WORKFLOW_BATCHES)throw Error("BLOCKED: PR_FEEDBACK verification batch limit reached");for(let record3 of previous)for(let lane of record3.ownership)for(let itemId of lane.ownedItemIds)claimedByItemId.set(itemId,lane.laneId);for(let lane of normalizedOwnership)for(let itemId of lane.ownedItemIds){if(!inventorySet.has(itemId))throw Error(`BLOCKED: PR_FEEDBACK verification lane "${lane.laneId}" owns undeclared item "${itemId}"`);let previousLane=claimedByItemId.get(itemId);if(previousLane&&previousLane!==lane.laneId)throw Error(`BLOCKED: PR_FEEDBACK verification item "${itemId}" is owned by both "${previousLane}" and "${lane.laneId}"`);claimedByItemId.set(itemId,lane.laneId)}let record2={batchId,ownership:normalizedOwnership,validatedAt:isoNow()},nextState={...state,updatedAt:isoNow(),prFeedbackVerifications:[...previous,record2],prFeedbackVerification:record2};return await persistState(directory,nextState),nextState}async function assertPrFeedbackVerificationSettled(directory,sessionID){let state=await requireBoundState(directory,sessionID,"PR_FEEDBACK"),currentDigest=await currentPrFeedbackRevisionDigest(directory,state),inventory=state.prFeedbackInventory,batches=state.prFeedbackVerifications??[];if(!inventory||batches.length===0)throw Error("BLOCKED: PR_FEEDBACK requires an immutable inventory and verification batches");let covered=new Set;for(let batch of batches){let successfulLaneIds=successfulObligationsFromExactBatch(directory,state,batch.batchId,batch.ownership.map((lane)=>({laneId:lane.laneId,workflowLane:lane.laneId})),"swarm-pr-feedback:verification",batch.validatedAt,!1,new Set,currentDigest);for(let lane of batch.ownership){if(!successfulLaneIds.has(lane.laneId))continue;if(!feedbackArtifactCoversItems(directory,state,batch.batchId,lane.laneId,lane.ownedItemIds))continue;for(let itemId of lane.ownedItemIds)covered.add(itemId)}}let missing=inventory.filter((itemId)=>!covered.has(itemId));if(missing.length>0||covered.size!==inventory.length)throw Error(`BLOCKED: PR_FEEDBACK verification ownership is incomplete; missing inventory items: ${missing.join(", ")||"(none)"}`);return state}async function recordPrFeedbackStageA(directory,sessionID,revisionDigest,checks3,options={}){let state=await assertPrFeedbackVerificationSettled(directory,sessionID),currentDigest=await currentPrFeedbackRevisionDigest(directory,state);if(revisionDigest!==currentDigest)throw Error("BLOCKED: PR_FEEDBACK Stage A receipt is stale because the working-tree revision changed during validation");if(checks3.length<2||checks3.length>258)throw Error("BLOCKED: PR_FEEDBACK Stage A requires two to 258 controller-created check receipts");let optionalCategoryOrder=["build","typecheck","lint"],applicableCategories=options.applicableCategories??optionalCategoryOrder.filter((category)=>checks3.some((check2)=>check2.category===category));if(assertNoDuplicates(applicableCategories,"PR_FEEDBACK Stage A applicable categories"),applicableCategories.some((category)=>!optionalCategoryOrder.includes(category)))throw Error("BLOCKED: PR_FEEDBACK Stage A applicability may contain only build, typecheck, and lint");let required2=new Set(["diff-check","reproduction",...applicableCategories]),singletonSeen=new Set,applicableObligations=[...options.applicableObligations??[]];assertNoDuplicates(applicableObligations.map(({id})=>id),"PR_FEEDBACK Stage A applicable obligations");let requiredObligationIds=new Set(applicableObligations.map(({id})=>id)),commandDigests=new Set,reproductionFeedbackItemIds=[];for(let check2 of checks3){if(["diff-check","reproduction"].includes(check2.category)&&singletonSeen.has(check2.category))throw Error(`BLOCKED: PR_FEEDBACK Stage A contains duplicate category "${check2.category}"`);if(singletonSeen.add(check2.category),required2.delete(check2.category),check2.obligationId){let obligation=applicableObligations.find((candidate)=>candidate.id===check2.obligationId);if(!obligation||obligation.category!==check2.category||obligation.workingDirectory!==(check2.workingDirectory??".")||!requiredObligationIds.delete(check2.obligationId))throw Error(`BLOCKED: PR_FEEDBACK Stage A receipt does not match one exact applicable obligation: ${check2.obligationId}`);let sourceContract=obligation.source.includes(".pr-validation.json#")?{path:obligation.source.slice(0,obligation.source.lastIndexOf("#")),id:obligation.source.slice(obligation.source.lastIndexOf("#")+1)}:void 0,requiredContract=obligation.validatorContract??sourceContract;if(requiredContract&&(check2.validatorContract?.path!==requiredContract.path||check2.validatorContract.id!==requiredContract.id))throw Error(`BLOCKED: PR_FEEDBACK Stage A obligation ${obligation.id} requires exact validator contract provenance`)}let commandDigest=createHash7("sha256").update(`${check2.obligationId??check2.category}\x00${check2.workingDirectory??"."}\x00${check2.command.join("\x00")}`).digest("hex");if(commandDigests.has(commandDigest))throw Error("BLOCKED: PR_FEEDBACK Stage A cannot reuse one command as multiple check receipts");if(commandDigests.add(commandDigest),check2.category==="diff-check"&&!sameStringArray(check2.command,["git","diff","--check"]))throw Error("BLOCKED: PR_FEEDBACK Stage A diff-check receipt is not the exact git diff --check command");if(check2.category==="reproduction"&&(!check2.targets?.length||!check2.feedbackTargets?.length||check2.targets.some((target)=>!check2.command.join(" ").includes(target))))throw Error("BLOCKED: PR_FEEDBACK Stage A reproduction receipt requires exact selected targets");if(check2.category==="reproduction"){if(reproductionFeedbackItemIds=check2.feedbackTargets.map((mapping)=>mapping.feedbackItemId),assertNoDuplicates(reproductionFeedbackItemIds,"PR_FEEDBACK Stage A reproduction feedback item mappings"),check2.feedbackTargets.some((mapping)=>!check2.targets.includes(mapping.target)))throw Error("BLOCKED: PR_FEEDBACK Stage A feedback mappings must reference exact executed reproduction targets")}}if(required2.size>0)throw Error(`BLOCKED: PR_FEEDBACK Stage A is missing required checks: ${[...required2].join(", ")}`);if(requiredObligationIds.size>0)throw Error(`BLOCKED: PR_FEEDBACK Stage A is missing applicable workspace obligations: ${[...requiredObligationIds].join(", ")}`);if(!sameStringArray(reproductionFeedbackItemIds,state.prFeedbackInventory??[]))throw Error("BLOCKED: PR_FEEDBACK Stage A reproduction must map every immutable feedback item exactly once and in declared order");let nextState={...state,updatedAt:isoNow(),prFeedbackStageA:{revisionDigest:currentDigest,checks:[...checks3],feedbackItemIds:reproductionFeedbackItemIds,applicableCategories:optionalCategoryOrder.filter((category)=>applicableCategories.includes(category)),applicableObligations,validatedAt:isoNow()},prFeedbackGateBatches:[],prFeedbackReadyToPublish:void 0};return await persistState(directory,nextState),nextState}async function recordPrFeedbackGateBatch(directory,sessionID,phase,lane,options){let state=await bindPrWorkflowHead(directory,sessionID,options.prHeadSha);if(state.mode!=="PR_FEEDBACK")throw wrongModeError(state,"PR_FEEDBACK");let inventory=state.prFeedbackInventory;if(!inventory?.length)throw Error("BLOCKED: PR_FEEDBACK ordered gates require an immutable feedback inventory");let normalized=normalizeOwnership([lane])[0];if(!sameStringArray(normalized.ownedItemIds,inventory))throw Error(`BLOCKED: PR_FEEDBACK ${phase} must own every inventory item exactly once and in declared order`);let phaseIndex=PR_FEEDBACK_PHASE_ORDER.indexOf(phase),prerequisite=PR_FEEDBACK_PHASE_ORDER[phaseIndex-1];if(prerequisite)state=await assertPrFeedbackGatePhaseSettled(directory,sessionID,prerequisite);let{prFeedbackStageA:stageA,prFeedbackInventory:refreshedInventory}=state,currentDigest=await currentPrFeedbackRevisionDigest(directory,state);if(!stageA||!refreshedInventory||stageA.revisionDigest!==currentDigest||!sameStringArray(stageA.feedbackItemIds??[],refreshedInventory)||options.revisionDigest!==currentDigest)throw Error(`BLOCKED: PR_FEEDBACK ${phase} requires fresh Stage A checks on the current revision`);let batchId=normalizeBatchId(options.batchId),previous=state.prFeedbackGateBatches??[];if(previous.some((batch)=>batch.batchId===batchId))throw Error(`BLOCKED: PR_FEEDBACK gate batch id "${batchId}" is already recorded`);let retained=previous.filter((batch)=>PR_FEEDBACK_PHASE_ORDER.indexOf(batch.phase)<phaseIndex),record2={batchId,phase,laneId:normalized.laneId,itemIds:normalized.ownedItemIds,revisionDigest:currentDigest,validatedAt:isoNow()},nextState={...state,updatedAt:isoNow(),prFeedbackGateBatches:[...retained,record2]};return await persistState(directory,nextState),nextState}async function assertPrFeedbackGatePhaseSettled(directory,sessionID,phase){let state=await requireBoundState(directory,sessionID,"PR_FEEDBACK"),currentDigest=await currentPrFeedbackRevisionDigest(directory,state);if(state.prFeedbackStageA?.revisionDigest!==currentDigest)throw Error(`BLOCKED: PR_FEEDBACK ${phase} cannot use stale Stage A evidence`);if(!sameStringArray(state.prFeedbackStageA?.feedbackItemIds??[],state.prFeedbackInventory??[]))throw Error(`BLOCKED: PR_FEEDBACK ${phase} Stage A reproduction is not bound to the exact immutable feedback inventory`);let batch=[...state.prFeedbackGateBatches??[]].reverse().find((candidate)=>candidate.phase===phase);if(!batch||batch.revisionDigest!==currentDigest)throw Error(`BLOCKED: PR_FEEDBACK ${phase} has no validation batch on the current revision`);if(!successfulObligationsFromExactBatch(directory,state,batch.batchId,[{laneId:batch.laneId,workflowLane:phase,reviewItemIds:batch.itemIds}],`swarm-pr-feedback:${phase}`,batch.validatedAt,!0,new Set,currentDigest).has(phase))throw Error(`BLOCKED: PR_FEEDBACK ${phase} requires one complete, non-degraded positive verdict row per inventory item`);if(findByBatchId(directory,batch.batchId,{parentSessionId:state.sessionID}).find((candidate)=>candidate.laneId===batch.laneId)?.workspace?.dirtyHash!==currentDigest)throw Error(`BLOCKED: PR_FEEDBACK ${phase} artifact is not bound to the current revision digest`);return assertIndependentFeedbackGateSessions(directory,state,phase),state}function assertIndependentFeedbackGateSessions(directory,state,throughPhase){let throughIndex=PR_FEEDBACK_PHASE_ORDER.indexOf(throughPhase),batches=(state.prFeedbackGateBatches??[]).filter((batch)=>PR_FEEDBACK_PHASE_ORDER.indexOf(batch.phase)<=throughIndex),seenSessions=new Set;for(let batch of batches){let matching=findByBatchId(directory,batch.batchId,{parentSessionId:state.sessionID}).filter((record3)=>record3.laneId===batch.laneId);if(matching.length!==1)throw Error(`BLOCKED: PR_FEEDBACK ${batch.phase} must resolve from exactly one durable child session`);let record2=matching[0],expectedRole=PR_FEEDBACK_PHASE_ROLE[batch.phase];if(!(record2.normalizedAgent===expectedRole||expectedRole==="critic"&&record2.normalizedAgent.startsWith("critic_")))throw Error(`BLOCKED: PR_FEEDBACK ${batch.phase} requires role ${expectedRole}, received ${record2.normalizedAgent||"(unknown)"}`);if(seenSessions.has(record2.subagentSessionId))throw Error(`BLOCKED: PR_FEEDBACK independent phases reused child session "${record2.subagentSessionId}"`);seenSessions.add(record2.subagentSessionId)}}async function assertPrFeedbackReadyToPublish(directory,sessionID){let state=await assertPrFeedbackVerificationSettled(directory,sessionID);for(let phase of PR_FEEDBACK_PHASE_ORDER)state=await assertPrFeedbackGatePhaseSettled(directory,sessionID,phase);return state}async function assertPrFeedbackPublicationArmed(directory,sessionID){let state=await requireBoundState(directory,sessionID,"PR_FEEDBACK"),armed=state.prFeedbackReadyToPublish;if(!armed)throw Error("BLOCKED: PR_FEEDBACK publication is not armed; call complete_pr_workflow once after every ordered gate passes");let currentDigest=await currentPrFeedbackRevisionDigest(directory,state);if(armed.revisionDigest!==currentDigest)throw Error("BLOCKED: PR_FEEDBACK changed after publication was armed; rerun Stage A and every independent gate");if((await _test_exports.resolveCurrentGitHeadAsync(directory))?.trim()!==armed.localHead)throw Error("BLOCKED: PR_FEEDBACK current Git HEAD changed after publication was armed");if(await _test_exports.resolveIsWorkingTreeCleanAsync(directory)!==!0)throw Error("BLOCKED: PR_FEEDBACK working tree changed after publication was armed");let currentTarget=await _test_exports.resolveCurrentUpstreamPushTargetAsync(directory);if(!currentTarget||currentTarget.remoteName!==armed.remoteName||currentTarget.remoteBranchRef!==armed.remoteBranchRef||currentTarget.remoteTrackingRef!==armed.remoteRef)throw Error("BLOCKED: PR_FEEDBACK upstream publication target changed after publication was armed");return state}async function markPrReviewTriggerEvaluationComplete(directory,sessionID,artifactPath){let state=await assertPrReviewBaseCoverageSettled(directory,sessionID),normalizedPath=artifactPath.trim();if(!normalizedPath)throw Error("BLOCKED: PR_REVIEW trigger artifact path is required");let nextState={...state,updatedAt:isoNow(),prReviewTriggerEvalPath:normalizedPath};return await persistState(directory,nextState),nextState}async function bindPrReviewTriggerLedger(directory,sessionID,input){let ledger;try{ledger=validatePrReviewInlineTriggerLedger(input)}catch(error49){throw Error(`BLOCKED: invalid PR_REVIEW trigger_evaluation: ${error49 instanceof Error?error49.message:String(error49)}`)}let state=await assertPrReviewBaseCoverageSettled(directory,sessionID);if(state.prReviewTriggerLedger){let frozen;try{frozen=validatePrReviewInlineTriggerLedger(state.prReviewTriggerLedger)}catch(error49){throw Error(`BLOCKED: persisted PR_REVIEW trigger ledger is invalid: ${error49 instanceof Error?error49.message:String(error49)}`)}if(prReviewTriggerLedgerDigest(frozen.rows)!==prReviewTriggerLedgerDigest(ledger.rows))throw Error("BLOCKED: PR_REVIEW trigger_evaluation must remain exactly identical across every micro dispatch and the final receipt");return state}let nextState={...state,updatedAt:isoNow(),prReviewTriggerLedger:ledger.rows};return await persistState(directory,nextState),nextState}async function assertPrReviewArtifactBoundary(directory,sessionID,runId,boundary,findingIds){let state=await requireBoundState(directory,sessionID,"PR_REVIEW");if(!state.prReviewTriggerEvalPath)throw Error("BLOCKED: PR_REVIEW findings persistence requires the trigger evaluation artifact");let persistedBoundaries=state.prReviewArtifactBoundaries??[],boundaryOrder=["post_explorer","post_reviewer","post_critic"],boundaryIndex=boundaryOrder.indexOf(boundary),requiredPriorBoundary=boundaryOrder[boundaryIndex-1];if(requiredPriorBoundary&&!persistedBoundaries.includes(requiredPriorBoundary))throw Error(`BLOCKED: PR_REVIEW ${boundary} findings require the prior ${requiredPriorBoundary} checkpoint`);if(persistedBoundaries.some((persisted)=>boundaryOrder.indexOf(persisted)>boundaryIndex))throw Error(`BLOCKED: PR_REVIEW ${boundary} findings cannot be persisted after a later checkpoint`);if(boundary==="post_reviewer")state=await assertPrReviewValidationSettled(directory,sessionID,"reviewer");else if(boundary==="post_critic"){if(await assertPrReviewValidationSettled(directory,sessionID,"reviewer"),derivePrReviewCriticInventory(directory,state).length>0)state=await assertPrReviewValidationSettled(directory,sessionID,"critic")}if(state.prReviewArtifactRunId&&state.prReviewArtifactRunId!==runId)throw Error(`BLOCKED: PR_REVIEW artifacts are already bound to run "${state.prReviewArtifactRunId}"`);let expectedFindingIds=derivePrReviewCandidateInventory(directory,state),normalizedFindingIds=[...new Set(findingIds)].sort();if(normalizedFindingIds.length!==findingIds.length||JSON.stringify(normalizedFindingIds)!==JSON.stringify([...expectedFindingIds].sort()))throw Error(`BLOCKED: PR_REVIEW ${boundary} findings must exactly cover the discovered candidate inventory`);return state}async function assertPrReviewArtifactRecordsMatchAuthoritativeVerdicts(directory,sessionID,boundary,records){let state=await requireBoundState(directory,sessionID,"PR_REVIEW");if(boundary==="post_explorer"){for(let record2 of records)if(record2.status!=="PENDING"||record2.next_action!=="route_to_reviewer")throw Error(`BLOCKED: PR_REVIEW post_explorer record ${record2.finding_id} must remain PENDING and route_to_reviewer`);return}let reviewerVerdicts=deriveLatestPrReviewReviewerVerdicts(directory,state),criticVerdicts=boundary==="post_critic"?deriveLatestPrReviewCriticVerdicts(directory,state):void 0;for(let record2 of records){let reviewer=reviewerVerdicts.get(record2.finding_id);if(!reviewer)throw Error(`BLOCKED: PR_REVIEW ${boundary} record ${record2.finding_id} has no authoritative reviewer verdict`);if(record2.severity&&record2.severity!==reviewer.severity)throw Error(`BLOCKED: PR_REVIEW ${boundary} record ${record2.finding_id} severity differs from its reviewer verdict`);let requiresCritic=reviewer.classification==="CONFIRMED"&&["CRITICAL","HIGH","MEDIUM"].includes(reviewer.severity);if(boundary==="post_reviewer"){let expectedStatus=reviewer.classification==="UNVERIFIED"?"PENDING":reviewer.classification;if(record2.status!==expectedStatus)throw Error(`BLOCKED: PR_REVIEW post_reviewer record ${record2.finding_id} status differs from its reviewer verdict`);let expectedAction=requiresCritic?"route_to_critic":reviewer.classification==="CONFIRMED"||reviewer.classification==="PRE_EXISTING"?"report":reviewer.classification==="DISPROVED"?"suppress_with_reason":"route_to_reviewer";if(record2.next_action!==expectedAction)throw Error(`BLOCKED: PR_REVIEW post_reviewer record ${record2.finding_id} action does not match reviewer disposition`);continue}if(!requiresCritic){let expectedStatus=reviewer.classification==="UNVERIFIED"?"PENDING":reviewer.classification,expectedAction=reviewer.classification==="CONFIRMED"||reviewer.classification==="PRE_EXISTING"?"report":reviewer.classification==="DISPROVED"?"suppress_with_reason":"route_to_reviewer";if(record2.status!==expectedStatus||record2.next_action!==expectedAction)throw Error(`BLOCKED: PR_REVIEW post_critic record ${record2.finding_id} cannot override its non-critic reviewer disposition`);continue}let critic=criticVerdicts?.get(record2.finding_id);if(!critic)throw Error(`BLOCKED: PR_REVIEW post_critic record ${record2.finding_id} has no authoritative critic verdict`);if(record2.severity&&record2.severity!==critic.severity)throw Error(`BLOCKED: PR_REVIEW post_critic record ${record2.finding_id} severity differs from its critic verdict`);if(critic.status==="DISPROVED"){if(record2.status!=="DISPROVED"||record2.next_action!=="suppress_with_reason")throw Error(`BLOCKED: PR_REVIEW post_critic record ${record2.finding_id} must preserve the critic DISPROVED disposition`)}else if(record2.status!=="CONFIRMED"||!["report","handoff_to_feedback"].includes(record2.next_action))throw Error(`BLOCKED: PR_REVIEW post_critic record ${record2.finding_id} action does not match its critic verdict`)}}async function markPrReviewArtifactBoundary(directory,sessionID,runId,boundary,artifactPath,findingIds,handoffRequired){let state=await assertPrReviewArtifactBoundary(directory,sessionID,runId,boundary,findingIds),boundaries=new Set(state.prReviewArtifactBoundaries??[]);boundaries.add(boundary);let nextState={...state,updatedAt:isoNow(),prReviewArtifactRunId:runId,prReviewFindingsPath:artifactPath,prReviewArtifactBoundaries:[...boundaries],prReviewHandoffRequired:handoffRequired};return await persistState(directory,nextState),nextState}async function markPrReviewHandoffComplete(directory,sessionID,runId,artifactPath){let state=await requireBoundState(directory,sessionID,"PR_REVIEW");if(state.prReviewArtifactRunId!==runId||!(state.prReviewArtifactBoundaries??[]).includes("post_critic"))throw Error("BLOCKED: PR_REVIEW handoff requires the final findings boundary for the same run");let nextState={...state,updatedAt:isoNow(),prReviewHandoffPath:artifactPath};return await persistState(directory,nextState),nextState}function normalizePrReviewFeedbackHandoffPath(handoffPath){let normalized=handoffPath.trim().replace(/\\/g,"/"),relative4=normalized.startsWith(".swarm/")?normalized.slice(7):normalized,matched=relative4.match(PR_REVIEW_HANDOFF_RELATIVE_PATH_PATTERN);if(!matched)return null;return{runId:matched[1],relativePath:relative4}}async function readBoundedSwarmRegularFile(directory,relativePath,maxBytes,label){let absPath=validateSwarmPath(directory,relativePath),swarmRoot=path14.resolve(directory,".swarm"),rootStat,artifactStat;try{rootStat=await fsp3.lstat(swarmRoot,{bigint:!0}),artifactStat=await fsp3.lstat(absPath,{bigint:!0})}catch(error49){if(error49.code==="ENOENT")throw Error(`BLOCKED: ${label} "${relativePath}" does not exist`);throw error49}if(rootStat.isSymbolicLink()||!rootStat.isDirectory())throw Error(`BLOCKED: ${label} root must be a real project .swarm directory`);if(artifactStat.isSymbolicLink()||!artifactStat.isFile())throw Error(`BLOCKED: ${label} must be a bounded regular file`);if(artifactStat.size>BigInt(maxBytes))throw Error(`BLOCKED: ${label} exceeds ${maxBytes} bytes`);let[realRoot,realArtifact]=await Promise.all([fsp3.realpath(swarmRoot),fsp3.realpath(absPath)]),relativeRealPath=path14.relative(realRoot,realArtifact);if(relativeRealPath===""||relativeRealPath===".."||relativeRealPath.startsWith(`..${path14.sep}`)||path14.isAbsolute(relativeRealPath))throw Error(`BLOCKED: ${label} escapes the project .swarm directory`);await _test_exports.beforeBoundedSwarmFileOpen?.();let handle=await fsp3.open(realArtifact,"r");try{let openedStat=await handle.stat({bigint:!0});if(!openedStat.isFile()||openedStat.size>BigInt(maxBytes)||!sameBigIntFileIdentity(artifactStat,openedStat))throw Error(`BLOCKED: ${label} changed during its bounded read`);let[postRootStat,postArtifactStat,postRealRoot,postRealArtifact]=await Promise.all([fsp3.lstat(swarmRoot,{bigint:!0}),fsp3.lstat(absPath,{bigint:!0}),fsp3.realpath(swarmRoot),fsp3.realpath(absPath)]),postRelativeRealPath=path14.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(`..${path14.sep}`)||path14.isAbsolute(postRelativeRealPath))throw Error(`BLOCKED: ${label} changed or escaped during its bounded read`);let buffer=Buffer.allocUnsafe(maxBytes+1),{bytesRead}=await handle.read(buffer,0,maxBytes+1,0);if(bytesRead>maxBytes)throw Error(`BLOCKED: ${label} exceeds ${maxBytes} bytes`);return buffer.subarray(0,bytesRead).toString("utf8")}finally{await handle.close()}}function sameBigIntFileIdentity(left,right){return left.dev===right.dev&&left.ino===right.ino}function normalizeComparableFsPath(value){let normalized=path14.normalize(path14.resolve(value));return process.platform==="win32"?normalized.toLowerCase():normalized}async function readPrReviewFeedbackHandoffArtifact(directory,relativePath){let raw=await readBoundedSwarmRegularFile(directory,relativePath,PR_REVIEW_HANDOFF_MAX_BYTES,"PR_REVIEW feedback handoff artifact"),parsedJson;try{parsedJson=JSON.parse(raw)}catch{throw Error("BLOCKED: PR_REVIEW feedback handoff artifact is not valid JSON")}let parsed=PrReviewFeedbackHandoffArtifactSchema.safeParse(parsedJson);if(!parsed.success)throw Error("BLOCKED: PR_REVIEW feedback handoff artifact is invalid");if(new Set(parsed.data.finding_ids).size!==parsed.data.finding_ids.length)throw Error("BLOCKED: PR_REVIEW feedback handoff artifact contains duplicate finding IDs");return{artifact:parsed.data,digest:createHash7("sha256").update(raw,"utf8").digest("hex")}}async function readActionableReviewFindingIds(directory,state,runId){let expectedPath=`pr-review/${runId}/findings.jsonl`;if(state.prReviewFindingsPath!==expectedPath)throw Error(`BLOCKED: PR_REVIEW transition requires the exact final findings artifact "${expectedPath}"`);let raw=await readBoundedSwarmRegularFile(directory,expectedPath,PR_REVIEW_FINDINGS_MAX_BYTES,"PR_REVIEW final findings artifact"),latest=new Map;for(let[index,line]of raw.split(/\r?\n/).entries()){if(!line.trim())continue;let value;try{value=JSON.parse(line)}catch{throw Error(`BLOCKED: PR_REVIEW final findings artifact contains invalid JSON at line ${index+1}`)}let parsed=PrReviewFindingProjectionSchema.safeParse(value);if(!parsed.success)throw Error(`BLOCKED: PR_REVIEW final findings artifact contains an invalid record at line ${index+1}`);latest.set(parsed.data.finding_id,parsed.data)}return[...latest.values()].filter((record2)=>record2.status==="CONFIRMED"&&record2.next_action==="handoff_to_feedback").map((record2)=>record2.finding_id).sort()}function canonicalGitHubPrUrl(value){try{let url2=new URL(value);if(url2.protocol!=="https:"||url2.hostname.toLowerCase()!=="github.com")return null;let matched=url2.pathname.match(/^\/([^/]+)\/([^/]+)\/pull\/(\d+)\/?$/);if(!matched)return null;let prNumber=Number(matched[3]);if(!Number.isSafeInteger(prNumber)||prNumber<=0)return null;return`github.com/${matched[1].toLowerCase()}/${matched[2].toLowerCase()}/pull/${prNumber}`}catch{return null}}function workflowIdentity(state){return state.workflowInstanceId??`legacy-${createHash7("sha256").update(`${state.sessionID}\x00${state.mode}\x00${state.activatedAt}`).digest("hex").slice(0,32)}`}function sameHandoffIds(left,right){let normalizedLeft=[...new Set(left)].sort(),normalizedRight=[...new Set(right)].sort();return sameStringArray(normalizedLeft,normalizedRight)}function assertSamePrFeedbackHandoff(state,relativePath,read,requestedPrUrl){let existing=state.prFeedbackReviewHandoff;if(!existing)throw Error(`BLOCKED: session "${state.sessionID}" is already active in PR_FEEDBACK without persisted review handoff provenance`);let artifactPr=canonicalGitHubPrUrl(read.artifact.pr_url),requestedPr=requestedPrUrl?canonicalGitHubPrUrl(requestedPrUrl):artifactPr;if(!artifactPr||requestedPrUrl&&requestedPr!==artifactPr||existing.path!==relativePath||existing.runId!==read.artifact.run_id||existing.digest!==read.digest||existing.sourcePrHeadSha.toLowerCase()!==read.artifact.pr_head_sha.toLowerCase()||canonicalGitHubPrUrl(existing.prUrl)!==artifactPr||!sameHandoffIds(existing.findingIds,read.artifact.finding_ids))throw Error(`BLOCKED: session "${state.sessionID}" is already active in PR_FEEDBACK for a different handoff or PR`)}async function assertPrReviewTerminalReady(directory,sessionID){let state=await requireBoundState(directory,sessionID,"PR_REVIEW");await assertPrReviewCleanCheckout(directory,"PR_REVIEW");let open3=readDelegations(directory).filter((record2)=>record2.parentSessionId===state.sessionID&&record2.mode?.startsWith("swarm-pr-")&&(record2.status==="pending"||record2.status==="running"));if(open3.length>0)throw Error(`BLOCKED: PR_REVIEW transition has ${open3.length} unsettled PR workflow lane(s)`);if(await assertPrReviewBaseCoverageSettled(directory,sessionID),!state.prReviewTriggerEvalPath)throw Error("BLOCKED: PR_REVIEW transition requires a persisted trigger evaluation artifact");if((state.prReviewValidationBatches??[]).some((batch)=>batch.phase==="council"))await assertPrReviewValidationSettled(directory,sessionID,"council");await assertPrReviewValidationSettled(directory,sessionID,"reviewer");let criticInventory=derivePrReviewCriticInventory(directory,state);if(criticInventory.length>0){if(!(state.prReviewValidationBatches??[]).some((batch)=>batch.phase==="critic"))throw Error(`BLOCKED: PR_REVIEW reviewer verdicts require critic coverage for: ${criticInventory.join(", ")}`);await assertPrReviewValidationSettled(directory,sessionID,"critic")}let requiredBoundaries=["post_explorer","post_reviewer","post_critic"],persistedBoundaries=new Set(state.prReviewArtifactBoundaries??[]),missing=requiredBoundaries.filter((boundary)=>!persistedBoundaries.has(boundary));if(!state.prReviewFindingsPath||missing.length>0)throw Error(`BLOCKED: PR_REVIEW transition requires durable findings checkpoints; missing: ${missing.join(", ")||"findings path"}`);if(state.prReviewHandoffRequired&&!state.prReviewHandoffPath)throw Error("BLOCKED: PR_REVIEW actionable findings require a persisted feedback handoff artifact");return state}async function transitionPrReviewToFeedback(directory,sessionID,request){let normalizedSessionID=normalizeSessionID(sessionID),normalizedHandoff=normalizePrReviewFeedbackHandoffPath(request.handoffPath);if(!normalizedHandoff||normalizedHandoff.runId!==request.runId)throw Error("BLOCKED: PR-feedback continuation must use .swarm/pr-review/<run_id>/feedback-handoff.json");let preliminaryRead=await readPrReviewFeedbackHandoffArtifact(directory,normalizedHandoff.relativePath),artifact=preliminaryRead.artifact,artifactPr=canonicalGitHubPrUrl(artifact.pr_url),requestedPr=request.prUrl?canonicalGitHubPrUrl(request.prUrl):null;if(!artifactPr||request.prUrl&&requestedPr!==artifactPr)throw Error("BLOCKED: PR_REVIEW feedback handoff artifact does not match the requested GitHub PR URL");if(artifact.run_id!==request.runId)throw Error("BLOCKED: PR_REVIEW feedback handoff artifact does not match the requested review run");let preliminary=await readPrWorkflowGateState(directory,normalizedSessionID);if(preliminary?.mode==="PR_FEEDBACK")return assertSamePrFeedbackHandoff(preliminary,normalizedHandoff.relativePath,preliminaryRead,request.prUrl),preliminary;let sourceIdentity,sourceRevision=0,provenance;if(preliminary){if(preliminary.mode!=="PR_REVIEW")throw wrongModeError(preliminary,"PR_REVIEW");let ready=await assertPrReviewTerminalReady(directory,normalizedSessionID);if(workflowIdentity(ready)!==workflowIdentity(preliminary)||ready.revision!==preliminary.revision||ready.mode!=="PR_REVIEW"||ready.prReviewHandoffPath!==normalizedHandoff.relativePath||ready.prReviewArtifactRunId!==request.runId||!ready.prHeadSha||ready.prHeadSha.toLowerCase()!==artifact.pr_head_sha.toLowerCase()||canonicalGitHubPrUrl(artifact.pr_url)!==canonicalGitHubPrUrl(request.prUrl??artifact.pr_url))throw Error("BLOCKED: PR_REVIEW feedback handoff does not match the terminal active review state");let actionableIds=await readActionableReviewFindingIds(directory,ready,request.runId);if(!sameHandoffIds(actionableIds,artifact.finding_ids))throw Error("BLOCKED: PR_REVIEW feedback handoff finding IDs do not match the authoritative final findings ledger");sourceIdentity=workflowIdentity(ready),sourceRevision=ready.revision,provenance="active-review-v1"}else{if(!request.prUrl)throw Error("BLOCKED: continuing a completed PR_REVIEW requires an explicit GitHub PR URL");sourceIdentity=`external-${preliminaryRead.digest.slice(0,32)}`,provenance="external-v1"}return await _test_exports.beforePrFeedbackTransitionLock?.(),withSessionStateMutation(directory,normalizedSessionID,async()=>{let current=await readPrWorkflowGateStateFromDisk(directory,normalizedSessionID);if(current?.mode==="PR_FEEDBACK")return assertSamePrFeedbackHandoff(current,normalizedHandoff.relativePath,preliminaryRead,request.prUrl),current;if(provenance==="active-review-v1"){if(!current||current.mode!=="PR_REVIEW"||workflowIdentity(current)!==sourceIdentity||current.revision!==sourceRevision||current.prHeadSha?.toLowerCase()!==artifact.pr_head_sha.toLowerCase()||current.prReviewArtifactRunId!==request.runId||current.prReviewHandoffPath!==normalizedHandoff.relativePath)throw Error("BLOCKED: PR_REVIEW state changed while validating the feedback handoff; retry from current state")}else if(current)throw Error("BLOCKED: another PR workflow became active while validating the external handoff");let lockedRead=await readPrReviewFeedbackHandoffArtifact(directory,normalizedHandoff.relativePath);if(lockedRead.digest!==preliminaryRead.digest)throw Error("BLOCKED: PR_REVIEW feedback handoff artifact changed during transition");if(artifactPr!==canonicalGitHubPrUrl(lockedRead.artifact.pr_url)||lockedRead.artifact.run_id!==request.runId||lockedRead.artifact.pr_head_sha.toLowerCase()!==artifact.pr_head_sha.toLowerCase()||!sameHandoffIds(lockedRead.artifact.finding_ids,artifact.finding_ids))throw Error("BLOCKED: PR_REVIEW feedback handoff artifact changed during transition");let timestamp=isoNow(),nextState={schemaVersion:GATE_SCHEMA_VERSION,revision:sourceRevision,workflowInstanceId:randomUUID2(),sessionID:normalizedSessionID,mode:"PR_FEEDBACK",activatedAt:timestamp,updatedAt:timestamp,prFeedbackReviewHandoff:{path:normalizedHandoff.relativePath,runId:lockedRead.artifact.run_id,sourcePrHeadSha:lockedRead.artifact.pr_head_sha.toLowerCase(),prUrl:lockedRead.artifact.pr_url,findingIds:[...new Set(lockedRead.artifact.finding_ids)].sort(),digest:preliminaryRead.digest,sourceWorkflowInstanceId:sourceIdentity,provenance},prFeedbackTargetUrl:artifact.pr_url};return writeStateWhileLocked(directory,nextState,{replaceWorkflowInstanceId:provenance==="active-review-v1"?current?.workflowInstanceId:void 0})})}async function declarePrFeedbackScope(directory,sessionID,taskId,files){let state=await assertPrFeedbackVerificationSettled(directory,sessionID),revisionDigest=await currentPrFeedbackRevisionDigest(directory,state),previous=state.prFeedbackScopes??[];if(previous.find((entry)=>entry.taskId===taskId)?.consumedByCallId)throw Error(`SCOPE_NOT_DECLARED: PR-feedback scope ${taskId} was already consumed; use a fresh task_id for any retry`);let record2={taskId,files,revisionDigest,declaredAt:isoNow()},nextState={...state,updatedAt:isoNow(),prFeedbackScopes:[...previous.filter((entry)=>entry.taskId!==taskId),record2]};return await persistState(directory,nextState),nextState}async function resolvePrFeedbackScopeDeclaration(directory,sessionID,taskId){let state=await readPrWorkflowGateState(directory,sessionID);if(state?.mode!=="PR_FEEDBACK")return null;let declaration=(state.prFeedbackScopes??[]).find((entry)=>entry.taskId===taskId);if(!declaration)return null;return await assertPrFeedbackVerificationSettled(directory,sessionID),await currentPrFeedbackRevisionDigest(directory,state)===declaration.revisionDigest?declaration:null}async function consumePrFeedbackScopeDeclaration(directory,sessionID,taskId,callID){let declaration=await resolvePrFeedbackScopeDeclaration(directory,sessionID,taskId);if(!declaration)return null;if(declaration.consumedByCallId&&declaration.consumedByCallId!==callID)throw Error(`SCOPE_NOT_DECLARED: PR-feedback scope ${taskId} was already consumed by another Task call`);if(declaration.consumedByCallId===callID)return declaration;let state=await requireBoundState(directory,sessionID,"PR_FEEDBACK"),nextState={...state,updatedAt:isoNow(),prFeedbackScopes:(state.prFeedbackScopes??[]).map((entry)=>entry.taskId===taskId?{...entry,consumedByCallId:callID}:entry)};return await persistState(directory,nextState),{...declaration,consumedByCallId:callID}}async function validatePrFeedbackScopeBinding(directory,binding){if(!binding.workflowSessionId||!binding.workflowRevisionDigest)return!1;let declaration=await resolvePrFeedbackScopeDeclaration(directory,binding.workflowSessionId,binding.taskId);return Boolean(declaration&&declaration.consumedByCallId===binding.dispatchCallId&&declaration.revisionDigest===binding.workflowRevisionDigest&&JSON.stringify(declaration.files)===JSON.stringify(binding.files))}async function enforcePrWorkflowToolBefore(directory,sessionID,toolName,args2,generatedAgentNames=[]){let state=await readPrWorkflowGateState(directory,sessionID);if(!state)return;let normalizedTool=toolName.toLowerCase(),isDirectAgentTask=normalizedTool==="task"||normalizedTool==="run_agent",requestedRoles=["subagent_type","agent"].filter((field)=>Object.hasOwn(args2??{},field)).map((field)=>{let value=args2?.[field];if(typeof value!=="string"||!value.trim())return"";return resolveGeneratedAgentRole(value.trim(),generatedAgentNames)}),isDirectWrite=WRITE_TOOL_NAMES.includes(normalizedTool),command=typeof args2?.command==="string"?args2.command.trim():"",serializedArgs=JSON.stringify(args2??{}),referencesProtectedWorkflowEvidence=containsProtectedWorkflowPath(command||serializedArgs),isInternalWorkflowTool=isPrWorkflowControllerTool(state.mode,normalizedTool),isShellTool=normalizedTool==="bash"||normalizedTool==="shell",isReadOnlyShell=!1,shellPermissionEnvelope=null;if(isShellTool&&command.length>0){let trackingFetchTarget=state.prHeadSha?await _test_exports.resolveCurrentUpstreamPushTargetAsync(directory):null;shellPermissionEnvelope={allowCheckout:!state.prHeadSha,allowFetch:!state.prHeadSha,allowTrackingFetch:Boolean(state.prHeadSha),trackingFetchTarget},isReadOnlyShell=isAllowedPrWorkflowReadOnlyShell(command,shellPermissionEnvelope)}let trustedCapability=getPrWorkflowToolCapability(normalizedTool,state.mode),isNamedReadOnlyTool=trustedCapability!==null&&isTrustedPrWorkflowToolInvocationSafe(normalizedTool,args2??{})||normalizedTool!=="build_check"&&isAllowedPrReviewReadOnlyToolName(normalizedTool)&&readOnlyToolArgumentsAreSafe(args2??{}),isRecoverySafeEvidenceTool=trustedCapability==="observe"&&isTrustedPrWorkflowToolInvocationSafe(normalizedTool,args2??{})||normalizedTool!=="build_check"&&isAllowedPrReviewReadOnlyToolName(normalizedTool)&&readOnlyToolArgumentsAreSafe(args2??{});if(state.checkoutRecovery){if(isRecoverySafeEvidenceTool||isReadOnlyShell||normalizedTool==="abort_pr_workflow"||normalizedTool==="pr_workflow_status"||normalizedTool==="prepare_pr_workflow_checkout")return;throw Error(`BLOCKED: ${state.mode} requires manual Git recovery before controller work can continue. code=${state.checkoutRecovery.code} retryable=false required_action=${state.checkoutRecovery.requiredAction}`)}if(referencesProtectedWorkflowEvidence&&!isInternalWorkflowTool&&!isNamedReadOnlyTool&&!isReadOnlyShell)throw Error(`BLOCKED: active ${state.mode} workflow evidence under .swarm is controller-owned and cannot be modified directly`);let isShellCommandRequiringVerification=isShellTool&&command.length>0&&!isReadOnlyShell,isRemoteReviewTool=/(?:git|github|pull|(?:^|[_-])pr(?:[_-]|$)|issue|review)/i.test(normalizedTool),hasRemoteMutationVerb=/(?:^|[_-])(?:add|approve|cancel|close|comment|commit|convert|create|delete|dismiss|edit|mark|merge|push|ready|reopen|rerun|resolve|submit|transfer|unresolve|update)(?:[_-]|$)/i.test(normalizedTool),hasRemoteReadVerb=/(?:^|[_-])(?:github|git)[_-]+(?:check|checks|checkout|diff|fetch|get|inspect|list|read|search|status|view)(?:[_-]|$)/i.test(normalizedTool)||/(?:^|[_-])(?:github|git)[_-]+(?:pull[_-]+request|pr|issue|review[_-]+thread)[_-]+(?:check|checks|checkout|diff|fetch|get|inspect|list|read|search|status|view)(?:[_-]|$)/i.test(normalizedTool),isRemoteMutationTool=isRemoteReviewTool&&(hasRemoteMutationVerb||!hasRemoteReadVerb),isRemoteCheckoutTool=/(?:^|[_-])(?:github|git)[_-]+checkout(?:[_-]|$)/i.test(normalizedTool),isShellCheckout=(normalizedTool==="bash"||normalizedTool==="shell")&&(/\bgit\b(?:(?![;&|]).){0,200}\b(?:checkout|switch)\b/i.test(command)||/\bgh\s+pr\s+checkout\b/i.test(command)),stderrMergeNormalizedCommand=command.replace(PR_WORKFLOW_TRAILING_STDERR_MERGE_PATTERN,"").trim(),isCanonicalReviewCheckout=/^git\s+switch\s+--detach\s+[0-9a-f]{40,64}$/i.test(stderrMergeNormalizedCommand),detachedFeedbackSwitchMatch=command.match(/^git\s+switch\s+--detach\s+(\S+)$/i),isDetachedFeedbackCheckout=Boolean(detachedFeedbackSwitchMatch?.[1]&&isSafeGitRefToken(detachedFeedbackSwitchMatch[1]))||/^gh\s+pr\s+checkout\b.*\s--detach(?:\s|$)/i.test(command),containsGitCommitShell=isShellCommandRequiringVerification&&/\bgit\b(?:(?![;&|]).){0,200}\bcommit\b/i.test(command),isStandaloneGitCommitShell=containsGitCommitShell&&isSafeStandaloneGitCommit(command),isPublicationShell=isShellCommandRequiringVerification&&(/\bgit\b(?:(?![;&|]).){0,200}\bpush\b/i.test(command)||/\bgh\s+(?:api|pr|issue|run)\b/i.test(command)),isPublicationTool=!isInternalWorkflowTool&&isRemoteMutationTool,isCoderTask=isDirectAgentTask&&requestedRoles.length>0&&requestedRoles.every((role)=>role==="coder"),blockedShellDiagnosis=isShellTool&&command&&!isReadOnlyShell&&shellPermissionEnvelope?` ${describeBlockedPrReviewShellCommand(command,shellPermissionEnvelope)}`:"";if(state.mode==="PR_REVIEW"){if(!(isInternalWorkflowTool||isNamedReadOnlyTool||isReadOnlyShell&&(!isShellCheckout||isCanonicalReviewCheckout))||Boolean(state.prHeadSha)&&(isRemoteCheckoutTool||isShellCheckout)){if(!state.prHeadSha&&isShellCheckout)throw Error("BLOCKED: PR_REVIEW checkout must use standalone commands: fetch the PR head, verify the full commit object with `git cat-file -e <full_pr_head_sha>^{commit}`, then run `git switch --detach <full_pr_head_sha>` and bind that exact head before dispatching explorer lanes. Do not use `--track FETCH_HEAD`."+blockedShellDiagnosis);throw Error("BLOCKED: PR_REVIEW is read-only and fail-closed; only controller tools and positively classified observation tools are allowed, and every agent lane requires structured dispatch_lanes_async"+describePrWorkflowControllerToolNames(state.mode)+blockedShellDiagnosis)}return}if(isDirectAgentTask&&!isCoderTask)throw Error("BLOCKED: PR_FEEDBACK reviewer, test, critic, explorer, and unknown agent lanes require structured dispatch_lanes_async provenance");if(!isInternalWorkflowTool&&!isDirectAgentTask&&!isDirectWrite&&!isShellTool&&!isNamedReadOnlyTool)throw Error("BLOCKED: PR_FEEDBACK rejects unclassified plugin/MCP tools; use positively classified observation tools, built-in structured write tools after verification, or the workflow controller"+describePrWorkflowControllerToolNames(state.mode));if(state.prHeadSha&&(isShellCheckout||isRemoteCheckoutTool))throw Error("BLOCKED: PR_FEEDBACK checkout is immutable after exact PR head binding");if(containsGitCommitShell&&state.prFeedbackReadyToPublish)throw Error("BLOCKED: PR_FEEDBACK is armed for publication; the approved commit is immutable");if((containsGitCommitShell||isPublicationShell)&&hasUnsafeShellControlSyntax(command))throw Error("BLOCKED: PR_FEEDBACK publication commands must be standalone shell commands without control, redirection, or command-substitution syntax");if(containsGitCommitShell&&!isStandaloneGitCommitShell)throw Error("BLOCKED: PR_FEEDBACK commit must use a standalone git commit command after every ordered local gate passes");if(state.prFeedbackReadyToPublish){if(normalizedTool==="complete_pr_workflow")return;if(isNamedReadOnlyTool)return;if((normalizedTool==="bash"||normalizedTool==="shell")&&command.length>0&&isAllowedPrWorkflowReadOnlyShell(command,{allowCheckout:!1,allowFetch:!1,allowTrackingFetch:!1}))return;if(normalizedTool==="bash"||normalizedTool==="shell"){let armed=(await assertPrFeedbackPublicationArmed(directory,sessionID)).prFeedbackReadyToPublish;if(isSafeExactBoundPush(command,armed))return;throw Error(`BLOCKED: PR_FEEDBACK is armed for publication; only the exact approved push is allowed: ${expectedBoundPushCommand(armed)}`)}throw Error("BLOCKED: PR_FEEDBACK is armed for publication; only read-only inspection, the exact approved push, and complete_pr_workflow are allowed")}if(!state.prHeadSha&&normalizedTool==="prepare_pr_workflow_checkout")return;if(!state.prHeadSha&&isDetachedFeedbackCheckout&&!isCanonicalReviewCheckout)throw Error("BLOCKED: PR_FEEDBACK checkout should use one exact local tracking branch, such as `gh pr checkout <number> --branch <local_branch>` or `git switch -c <local_branch> --track <remote>/<branch>`, before binding. If checkout is already detached at the authoritative full PR head SHA, bind it directly; the controller attaches one unambiguous exact tracking ref. Other detached refs are not accepted");if(!state.prHeadSha&&isCanonicalReviewCheckout)return;if(isStandaloneGitCommitShell){await assertPrFeedbackReadyToPublish(directory,sessionID);return}if(isPublicationShell||isPublicationTool)throw Error("BLOCKED: PR_FEEDBACK publication is not armed; finish every ordered gate, create the one approved commit, and call complete_pr_workflow before publishing");if(isShellCommandRequiringVerification){if(!state.prHeadSha&&isShellCheckout)throw Error("BLOCKED: PR_FEEDBACK checkout should use one exact local tracking branch, such as `gh pr checkout <number> --branch <local_branch>` or `git switch -c <local_branch> --track <remote>/<branch>`, before binding. If checkout is already detached at the authoritative full PR head SHA, bind it directly; the controller attaches one unambiguous exact tracking ref");throw Error("BLOCKED: PR_FEEDBACK shell commands fail closed unless they are explicit read-only intake or the one standalone approved git commit; use structured coder/write tools for fixes and run_pr_feedback_stage_a for validation")}if(!isDirectWrite&&!isShellCommandRequiringVerification&&!isRemoteMutationTool&&!isCoderTask&&normalizedTool!=="prepare_pr_feedback_scope")return;if(normalizedTool==="abort_pr_workflow")return;await assertPrFeedbackVerificationSettled(directory,sessionID)}async function completePrWorkflow(directory,sessionID,expectedMode,prHeadSha){let state=await requireBoundState(directory,sessionID,expectedMode),normalizedHead=normalizePrHeadSha(prHeadSha);if(state.prHeadSha!==normalizedHead)throw Error(`BLOCKED: cannot complete ${expectedMode} at PR head "${normalizedHead}"; workflow is bound to "${state.prHeadSha}"`);let open3=readDelegations(directory).filter((record2)=>record2.parentSessionId===state.sessionID&&record2.mode?.startsWith("swarm-pr-")&&(record2.status==="pending"||record2.status==="running"));if(open3.length>0)throw Error(`BLOCKED: ${expectedMode} completion has ${open3.length} unsettled PR workflow lane(s)`);if(expectedMode==="PR_REVIEW"){let readyState=await assertPrReviewTerminalReady(directory,sessionID);if(workflowIdentity(readyState)!==workflowIdentity(state)||readyState.revision!==state.revision)throw Error("BLOCKED: PR_REVIEW state changed while checking terminal readiness; retry from current state")}else{let readyState=await assertPrFeedbackReadyToPublish(directory,sessionID),currentDigest=await currentPrFeedbackRevisionDigest(directory,readyState),armed=readyState.prFeedbackReadyToPublish;if(!armed){let localHead=(await _test_exports.resolveCurrentGitHeadAsync(directory))?.trim();if(!localHead)throw Error("BLOCKED: PR_FEEDBACK cannot arm publication without a verified local Git HEAD");if(await _test_exports.resolveCommitCountSinceAsync(directory,state.prHeadSha,localHead)!==1)throw Error("BLOCKED: PR_FEEDBACK publication requires exactly one descendant commit after the immutable intake head");if(await _test_exports.resolveIsExactSingleChildCommitAsync(directory,state.prHeadSha,localHead)!==!0)throw Error("BLOCKED: PR_FEEDBACK publication commit must be a non-merge direct child of the immutable intake head");if(await _test_exports.resolveIsWorkingTreeCleanAsync(directory)!==!0)throw Error("BLOCKED: PR_FEEDBACK publication requires a clean index and working tree so all approved content is captured by the bound commit");let upstreamTarget=await _test_exports.resolveCurrentUpstreamPushTargetAsync(directory);if(!upstreamTarget)throw Error("BLOCKED: PR_FEEDBACK cannot arm publication without a current branch bound to an exact remote name, remote branch ref, and remote-tracking ref");return await persistState(directory,{...readyState,updatedAt:isoNow(),prFeedbackReadyToPublish:{revisionDigest:currentDigest,localHead,remoteName:upstreamTarget.remoteName,remoteBranchRef:upstreamTarget.remoteBranchRef,remoteRef:upstreamTarget.remoteTrackingRef,validatedAt:isoNow()}}),"ready-to-publish"}if(armed.revisionDigest!==currentDigest)throw Error("BLOCKED: PR_FEEDBACK publication revision differs from the independently approved content digest");let publishedHead=(await _test_exports.resolveCurrentGitHeadAsync(directory))?.trim(),remoteRefs=publishedHead?await _test_exports.resolveRemoteRefsContainingHeadAsync(directory,publishedHead):null,remoteHead=await _test_exports.resolveExactRemoteBranchHeadAsync(directory,armed.remoteName,armed.remoteBranchRef);if(!publishedHead||publishedHead!==armed.localHead||!remoteRefs?.includes(armed.remoteRef)||remoteHead?.toLowerCase()!==armed.localHead.toLowerCase())throw Error(`BLOCKED: PR_FEEDBACK completion requires approved commit ${armed.localHead} at current Git HEAD and intended remote-tracking ref ${armed.remoteRef} at that exact commit`)}return await _test_exports.beforeTerminalClear?.(),await clearPrWorkflowGateState(directory,sessionID,state.revision),"completed"}async function requireAnyActiveState(directory,sessionID){let state=await readPrWorkflowGateState(directory,sessionID);if(!state)throw Error(`BLOCKED: no active PR workflow gate for session "${normalizeSessionID(sessionID)}". The gate is activated by running \`/swarm pr-review <pr-ref>\` (PR_REVIEW) or \`/swarm pr-feedback <pr-ref>\` (PR_FEEDBACK), or by the first dispatch_lanes_async call with mode "swarm-pr-review:*" / "swarm-pr-feedback:*".`);return state}async function requireBoundState(directory,sessionID,expectedMode){let state=await requireAnyActiveState(directory,sessionID);if(state.mode!==expectedMode)throw wrongModeError(state,expectedMode);if(!state.prHeadSha)throw Error(`BLOCKED: active ${expectedMode} workflow is not bound to a PR head`);if(expectedMode==="PR_REVIEW")await assertCurrentCheckoutHead(directory,state.prHeadSha,"PR_REVIEW"),await assertPrReviewCleanCheckout(directory);return state}function wrongModeError(state,expectedMode){return Error(`BLOCKED: session "${state.sessionID}" is active in ${state.mode}, not ${expectedMode}`)}function normalizeWorkflowLanes(lanes){if(!Array.isArray(lanes)||lanes.length===0)throw Error("BLOCKED: PR workflow lane validation requires at least one lane");let normalized=lanes.map((lane)=>{let workflowLane=lane.workflowLane?.trim(),laneId=lane.laneId?.trim()||workflowLane;if(!workflowLane||!laneId)throw Error("BLOCKED: PR workflow lane validation requires every lane to have non-empty laneId and workflow_lane values");let reviewItemIds=lane.reviewItemIds?.map((itemId)=>itemId.trim());if(reviewItemIds?.some((itemId)=>!itemId))throw Error("BLOCKED: PR workflow review_item_ids must not contain empty values");if(reviewItemIds)assertNoDuplicates(reviewItemIds,"review item ids within one lane");let ownedWorkflowLanes=lane.ownedWorkflowLanes?.map((owned)=>owned.trim());if(ownedWorkflowLanes){if(ownedWorkflowLanes.some((owned)=>!owned))throw Error("BLOCKED: PR workflow owned_workflow_lanes must not contain empty values");if(assertNoDuplicates(ownedWorkflowLanes,"owned workflow lanes within one lane"),!ownedWorkflowLanes.includes(workflowLane))throw Error(`BLOCKED: PR workflow lane "${laneId}" must include its own workflow_lane "${workflowLane}" in owned_workflow_lanes`)}return{laneId,workflowLane,...reviewItemIds?{reviewItemIds}:{},...ownedWorkflowLanes?{ownedWorkflowLanes}:{}}});return assertNoDuplicates(normalized.map((lane)=>lane.laneId),"lane ids"),assertNoDuplicates(normalized.map((lane)=>lane.workflowLane),"workflow lane ids"),assertNoDuplicates(normalized.flatMap((lane)=>lane.ownedWorkflowLanes??[lane.workflowLane]),"owned workflow lane ids across lanes"),normalized}function normalizeInventoryIds(inventoryIds){if(!Array.isArray(inventoryIds)||inventoryIds.length===0)throw Error("BLOCKED: PR_FEEDBACK inventory declaration requires at least one feedback item id");let normalized=inventoryIds.map((inventoryId)=>{let itemId=inventoryId.trim();if(!itemId)throw Error("BLOCKED: PR_FEEDBACK inventory declaration contains an empty item id");return itemId});return assertNoDuplicates(normalized,"inventory item ids"),normalized.sort()}function normalizeOwnership(ownership){if(!Array.isArray(ownership)||ownership.length===0)throw Error("BLOCKED: PR_FEEDBACK verification ownership requires at least one lane declaration");let normalized=ownership.map((lane)=>{let laneId=lane.laneId?.trim();if(!laneId)throw Error("BLOCKED: PR_FEEDBACK verification ownership requires every lane to have a non-empty laneId");let ownedItemIds=normalizeInventoryIds(lane.ownedItemIds);return{laneId,ownedItemIds}});return assertNoDuplicates(normalized.map((lane)=>lane.laneId),"PR_FEEDBACK verification lane ids"),normalized}function assertNoDuplicates(values,label){let seen=new Set;for(let value of values){if(seen.has(value))throw Error(`BLOCKED: duplicate ${label} are not allowed: ${value}`);seen.add(value)}}function containsProtectedWorkflowPath(value){return/(?:^|[^A-Za-z0-9_.-])\.swarm(?:[\\/]|$)/i.test(value.replace(/\\\\/g,"\\"))}function isPrWorkflowControllerTool(mode,toolName){if(PR_WORKFLOW_SHARED_CONTROLLER_TOOLS.has(toolName))return!0;return mode==="PR_REVIEW"?PR_REVIEW_CONTROLLER_TOOLS.has(toolName):PR_FEEDBACK_CONTROLLER_TOOLS.has(toolName)}function describePrWorkflowControllerToolNames(mode){let modeTools=mode==="PR_REVIEW"?PR_REVIEW_CONTROLLER_TOOLS:PR_FEEDBACK_CONTROLLER_TOOLS,names=[...PR_WORKFLOW_SHARED_CONTROLLER_TOOLS,...modeTools].sort((a,b)=>a.localeCompare(b));return` Allowed controller tools for ${mode}: ${names.join(", ")}. Observe current state read-only with the pr_workflow_status tool.`}function isTrustedPrWorkflowToolInvocationSafe(toolName,args2){if(toolName==="lint")return args2.mode==="check";if(toolName==="sast_scan")return args2.capture_baseline!==!0;return!0}function isAllowedPrReviewReadOnlyToolName(toolName){if(PR_REVIEW_READ_ONLY_TOOL_NAMES.has(toolName))return!0;let tokens=toolName.split(/[._:/-]+/).filter(Boolean);if(tokens.some((token)=>/^(?:add|alter|and|append|apply|approve|cancel|checkout|close|comment|commit|convert|create|delete|destroy|dismiss|drop|edit|execute|grant|insert|mark|merge|move|patch|prepend|publish|push|ready|remove|rename|replace|resolve|rerun|revoke|run|send|submit|then|transfer|truncate|unresolve|update|upload|write)$/i.test(token)))return!1;return tokens.some((token)=>/^(?:check|checks|diff|fetch|find|get|glob|grep|hover|inspect|list|lookup|open|read|references|scan|screenshot|search|show|status|symbols|tree|view)$/i.test(token))}function readOnlyToolArgumentsAreSafe(value,key="",depth=0){if(depth>8)return!1;let keyTokens=key.replace(/([a-z0-9])([A-Z])/g,"$1_$2").split(/[._:/-]+/).filter(Boolean);if(keyTokens.some((token)=>/^(?:append|body|content|create|data|delete|destination|destroy|edit|insert|mutation|output|patch|payload|prepend|remove|replace|save|set|truncate|update|upload|write)$/i.test(token)))return!1;if(keyTokens.some((token)=>/^(?:method|verb)$/i.test(token)))return typeof value==="string"&&/^(?:GET|HEAD)$/i.test(value.trim());if(keyTokens.length===1&&keyTokens.some((token)=>/^(?:action|operation)$/i.test(token)))return typeof value==="string"&&/^(?:check|diff|fetch|find|get|inspect|list|lookup|open|read|scan|search|show|status|view)$/i.test(value.trim());if(/^mode$/i.test(key)&&typeof value==="string")return/^(?:r|rb|read)$/i.test(value.trim());if(typeof value==="string"){if(keyTokens.some((token)=>/^(?:query|request|sql|statement)$/i.test(token))&&/(?:\b(?:alter|call|comment|create|delete|drop|exec(?:ute)?|grant|insert|merge|mutation|replace|revoke|truncate|update|upsert)\b|\bselect\b[\s\S]{0,4000}\binto\s+[A-Za-z_"'`])/i.test(value))return!1;return!/(?:^(?:POST|PUT|PATCH|DELETE|CONNECT|TRACE|write|edit|patch|create|delete|destroy|remove|replace|truncate|update|upload)$|(?:^|[\r\n])\s*(?:POST|PUT|PATCH|DELETE|CONNECT|TRACE)\s+\S+(?:\s+HTTP\/\d(?:\.\d)?)?|\bmutation\b|\b(?:create|drop|alter|truncate)\s+(?:or\s+replace\s+)?(?:table|database|schema|index|view|function|procedure|trigger|sequence)\b|\b(?:delete\s+from|insert\s+into|merge\s+into|replace\s+into|upsert\s+into)\b|\bupdate\s+[A-Za-z0-9_."'`-]+(?:\s+(?:AS\s+)?[A-Za-z0-9_"'`-]+)?\s+set\b|\b(?:grant|revoke)\s+\S+\s+(?:on|from|to)\b|\b(?:call|exec(?:ute)?)\s+[A-Za-z0-9_."'`-]+|\b(?:rm|rmdir|del|remove-item|move-item|set-content|add-content)\b)/i.test(value)}if(value===null||value===void 0||typeof value==="number"||typeof value==="boolean")return!0;if(Array.isArray(value))return value.every((entry)=>readOnlyToolArgumentsAreSafe(entry,key,depth+1));if(typeof value==="object")return Object.entries(value).every(([childKey,childValue])=>readOnlyToolArgumentsAreSafe(childValue,childKey,depth+1));return!1}function normalizePrWorkflowShellCommand(command){let normalized=command.trim(),withoutTrailingMerge=normalized.replace(PR_WORKFLOW_TRAILING_STDERR_MERGE_PATTERN,"");if(withoutTrailingMerge!==normalized)normalized=withoutTrailingMerge.trim();let strippedCdPrefix=!1;for(let index=0;index<PR_WORKFLOW_MAX_CD_PREFIX_STRIPS;index+=1){let next=normalized.replace(PR_WORKFLOW_CD_PREFIX_PATTERN,"");if(next===normalized)break;normalized=next.trim(),strippedCdPrefix=!0}return{normalized,strippedCdPrefix}}function isAllowedPrWorkflowReadOnlyShell(command,options){let{normalized:inner,strippedCdPrefix}=normalizePrWorkflowShellCommand(command),normalized=inner.replace(/\s+/g," ");if(!normalized)return!1;if(/[\r\n;&|<>`]/.test(inner)||/\$\(|@\(/.test(inner))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;if(/[\r\n;&|<>`]/.test(inner)||/\$\(|@\(/.test(inner))detail="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.";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 hasUnsafeShellControlSyntax(command){return/[;&|<>`\r\n]/.test(command)||/\$\(/.test(command)}function isSafeStandaloneGitCommit(command){if(hasUnsafeShellControlSyntax(command))return!1;if(/(?:^|\s)--(?:allow-empty|amend)(?:\s|=|$)/i.test(command))return!1;return/^[Gg][Ii][Tt](?:\s+-C(?:=|\s+)(?:"[^"\r\n]+"|'[^'\r\n]+'|[^\s;&|<>`]+))?\s+commit(?:\s+(?:"[^"\r\n]*"|'[^'\r\n]*'|[^\s;&|<>`]+))*\s*$/.test(command.trim())}function boundPushTarget(armed){let remote=armed.remoteName,branch=armed.remoteBranchRef.slice(11);if(!armed.remoteBranchRef.startsWith("refs/heads/")||!branch)return null;if(/\s|[;&|<>`]/.test(remote)||/\s|[;&|<>`]/.test(branch))return null;return{remote,branch}}function expectedBoundPushCommand(armed){let target=boundPushTarget(armed);return target?`git push ${target.remote} ${armed.localHead}:refs/heads/${target.branch}`:"(invalid bound remote-tracking ref; restart the workflow)"}function isSafeExactBoundPush(command,armed){if(hasUnsafeShellControlSyntax(command))return!1;let target=boundPushTarget(armed);if(!target)return!1;let match=command.trim().match(/^git\s+push\s+([^\s;&|<>`]+)\s+([^\s;&|<>`]+)\s*$/i);if(!match)return!1;return match[1]===target.remote&&match[2]===`${armed.localHead}:refs/heads/${target.branch}`}function isAllowedPrWorkflowGitIntake(gitArgs,options){if(/(?:--ext-diff|--textconv|--open-files-in-pager|--output(?:=|\s)|--upload-pack(?:=|\s)|--exec(?:=|\s))/i.test(gitArgs))return!1;if(/^(?:status|log|show|diff|rev-parse|merge-base|ls-files|grep|blame|cat-file|for-each-ref|--version|version)(?:\s|$)/i.test(gitArgs))return!0;if(isAllowedReadOnlyGitBranchListing(gitArgs))return!0;if(isAllowedReadOnlyGitStashListing(gitArgs))return!0;if(isAllowedReadOnlyGitWorktreeListing(gitArgs))return!0;if(options.allowFetch&&/^fetch(?:\s|$)/i.test(gitArgs))return!0;if(options.allowTrackingFetch&&isAllowedBoundRemoteTrackingFetch(gitArgs,options.trackingFetchTarget))return!0;if(/^remote(?:\s+-v)?$/i.test(gitArgs))return!0;if(options.allowCheckout&&isAllowedPreBindBranchSetup(gitArgs))return!0;if(options.allowCheckout&&/^(?:checkout|switch)\s+(?:--detach\s+)?[^\s-][^\s]*$/i.test(gitArgs))return!0;return/^config\s+(?:(?:--show-origin|--show-scope|--global|--local|--system|--worktree)\s+)*(?:--list|--get(?:-all)?\s+\S+)$/i.test(gitArgs)}function isAllowedBoundRemoteTrackingFetch(gitArgs,target){if(!target?.remoteName||!target.remoteBranchRef.startsWith("refs/heads/"))return!1;let tokens=gitArgs.trim().split(/\s+/);if(tokens.length!==3||tokens[0].toLowerCase()!=="fetch")return!1;let[,remote,remoteBranch]=tokens,expectedBranch=target.remoteBranchRef.slice(11);return isSafeGitRefToken(remote)&&!remote.includes("/")&&isSafeGitRefToken(remoteBranch)&&!remoteBranch.startsWith("-")&&!remoteBranch.includes(":")&&remote===target.remoteName&&remoteBranch===expectedBranch}function isAllowedPreBindBranchSetup(gitArgs){let tokens=gitArgs.trim().split(/\s+/);if(tokens.length===5){let[verb,createFlag,localBranch,trackFlag,upstream]=tokens;return(verb==="checkout"||verb==="switch")&&(createFlag==="-b"||createFlag==="-c")&&trackFlag==="--track"&&isSafeGitRefToken(localBranch)&&isSafeGitRefToken(upstream)&&upstream.includes("/")}if(tokens.length===3&&tokens[0]==="branch"){let upstream=tokens[1].match(/^--set-upstream-to=(.+)$/)?.[1];return Boolean(upstream&&isSafeGitRefToken(upstream)&&upstream.includes("/")&&isSafeGitRefToken(tokens[2]))}return!1}function isAllowedReadOnlyGitBranchListing(gitArgs){let tokens=gitArgs.trim().split(/\s+/);if(tokens.length===0||tokens[0].toLowerCase()!=="branch")return!1;let listingSelectorInEffect=!1;for(let index=1;index<tokens.length;index+=1){let token=tokens[index];if(/^(?:--list|--contains|--merged|--no-merged|--points-at)$/i.test(token)){listingSelectorInEffect=!0;continue}if(/^(?:-a|--all|-r|--remotes|-v|-vv|--verbose|--show-current|--color|--no-color|--column|--no-column|-i|--ignore-case)$/i.test(token)||/^--(?:sort|format|color)=/i.test(token))continue;if(token.startsWith("-"))return!1;if(!listingSelectorInEffect)return!1}return!0}function isAllowedReadOnlyGitStashListing(gitArgs){let tokens=gitArgs.trim().split(/\s+/);if(tokens.length<2||tokens[0].toLowerCase()!=="stash")return!1;if(tokens[1].toLowerCase()!=="list")return!1;for(let index=2;index<tokens.length;index+=1){let token=tokens[index];if(/^(?:-v|--oneline|--patch|-p|--stat|--color|--no-color)$/i.test(token))continue;if(/^--(?:format|pretty)=/i.test(token))continue;return!1}return!0}function isAllowedReadOnlyGitWorktreeListing(gitArgs){let tokens=gitArgs.trim().split(/\s+/);if(tokens.length<2||tokens[0].toLowerCase()!=="worktree")return!1;if(tokens[1].toLowerCase()!=="list")return!1;for(let index=2;index<tokens.length;index+=1){let token=tokens[index];if(/^(?:-v|--verbose|--porcelain|-z)$/i.test(token))continue;return!1}return!0}function isSafeGitRefToken(value){return/^[A-Za-z0-9][A-Za-z0-9._/-]*$/.test(value)&&!value.includes("..")&&!value.includes("//")&&!value.includes("@{")&&!value.endsWith("/")&&!value.endsWith(".")&&!value.endsWith(".lock")}function isAllowedPrFeedbackGhIntake(command){if(/^gh\s+pr\s+checkout(?:\s|$)/i.test(command))return isAllowedSafeGhPrCheckout(command);if(/^gh\s+--version$/i.test(command)||/^gh\s+pr\s+(?:view|diff|checks|status|list)(?:\s|$)/i.test(command)||/^gh\s+run\s+(?:view|list|watch)(?:\s|$)/i.test(command)||/^gh\s+issue\s+(?:view|list)(?:\s|$)/i.test(command)||/^gh\s+search\s+(?:code|commits|issues|prs|repos)(?:\s|$)/i.test(command)||/^gh\s+auth\s+status(?:\s|$)/i.test(command))return!0;if(!/^gh\s+api(?:\s|$)/i.test(command))return!1;if(/\bmutation\b/i.test(command))return!1;let method=command.match(/\s(?:--method(?:\s+|=)|-X(?:\s+|=)?)([A-Z]+)/i)?.[1];if(method&&method.toUpperCase()!=="GET")return!1;if(/\s(?:--input|--raw-field)(?:\s|=)/i.test(command)||/\s-F(?:\s|=|\S)/.test(command))return!1;return!/\s(?:--field|-f)(?:\s|=)(?!query=)/i.test(command)}function isAllowedSafeGhPrCheckout(command){if(/\s--(?:force|recurse-submodules)(?:\s|=|$)/i.test(command))return!1;let tokens=command.trim().split(/\s+/);if(tokens.length<4||tokens[0]!=="gh"||tokens[1]!=="pr"||tokens[2]!=="checkout")return!1;let target=tokens[3];if(!/^\d+$/.test(target)&&!/^https:\/\/github\.com\/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+\/pull\/\d+$/.test(target))return!1;for(let index=4;index<tokens.length;index+=1){let token=tokens[index],repoEquals=token.match(/^--repo=(.+)$/)?.[1];if(repoEquals){if(!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repoEquals))return!1;continue}let branchEquals=token.match(/^--branch=(.+)$/)?.[1];if(branchEquals){if(!isSafeGitRefToken(branchEquals))return!1;continue}if(token==="--repo"||token==="-R"){let repo=tokens[++index];if(!repo||!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repo))return!1;continue}if(token==="--branch"||token==="-b"){let branch=tokens[++index];if(!branch||!isSafeGitRefToken(branch))return!1;continue}return!1}return!0}function normalizePrHeadSha(prHeadSha){let normalized=prHeadSha.trim();if(!normalized)throw Error("BLOCKED: PR workflow requires a non-empty pr_head_sha");return normalized}async function currentPrFeedbackRevisionDigest(directory,state){if(!state.prHeadSha)throw Error("BLOCKED: PR_FEEDBACK revision binding requires pr_head_sha");let digest2=await resolvePrWorkflowRevisionDigestForGate(directory,state.prHeadSha);if(!digest2)throw Error("BLOCKED: PR_FEEDBACK could not compute a bounded current-revision digest");return digest2}async function resolvePrWorkflowRevisionDigestForGate(directory,baseHeadSha){if(_test_exports.resolvePrWorkflowRevisionDigest!==resolvePrWorkflowRevisionDigest)return _test_exports.resolvePrWorkflowRevisionDigest(directory,baseHeadSha);return resolvePrWorkflowRevisionDigestAsync(directory,baseHeadSha)}function normalizeBatchId(batchId){let normalized=batchId.trim();if(!normalized)throw Error("BLOCKED: PR workflow requires a non-empty batch id");return normalized}function sameStringArray(left,right){return left.length===right.length&&left.every((value,index)=>value===right[index])}function assertExactStringSet(actual,expected,label){let actualSet=new Set(actual),expectedSet=new Set(expected),missing=[...expectedSet].filter((value)=>!actualSet.has(value)),extra=[...actualSet].filter((value)=>!expectedSet.has(value));if(actual.length!==actualSet.size||actualSet.size!==expectedSet.size||missing.length>0||extra.length>0)throw Error(`BLOCKED: ${label} must exactly cover the mechanically derived inventory; missing: ${missing.join(", ")||"(none)"}; extra: ${extra.join(", ")||"(none)"}`)}function derivePrReviewCandidateInventory(directory,state){let sources=[],baseDimensionSources=new Map,baseSourceCreditedDimensions=new Map,baseSourceFullOwnershipCount=new Map;for(let batch of[...state.prReviewBaseDispatches??[]].reverse()){let successful=successfulObligationsFromExactBatch(directory,state,batch.batchId,batch.lanes,"swarm-pr-review:base",batch.validatedAt);for(let lane of batch.lanes){let ownedDimensions=lane.ownedWorkflowLanes?.length?lane.ownedWorkflowLanes:[lane.workflowLane];if(!ownedDimensions.every((dimension)=>successful.has(dimension)))continue;let key=`${batch.batchId}\x00${lane.laneId}`;baseSourceFullOwnershipCount.set(key,ownedDimensions.length);for(let dimension of ownedDimensions)if(!baseDimensionSources.has(dimension)){baseDimensionSources.set(dimension,{batchId:batch.batchId,laneId:lane.laneId});let credited=baseSourceCreditedDimensions.get(key);if(credited)credited.push(dimension);else baseSourceCreditedDimensions.set(key,[dimension])}}}let seenBaseSourceKeys=new Set;for(let{batchId,laneId}of baseDimensionSources.values()){let key=`${batchId}\x00${laneId}`;if(seenBaseSourceKeys.has(key))continue;seenBaseSourceKeys.add(key);let credited=baseSourceCreditedDimensions.get(key),fullOwnershipCount=baseSourceFullOwnershipCount.get(key)??0;sources.push({batchId,laneId,mode:"swarm-pr-review:base",creditedLanes:credited&&credited.length<fullOwnershipCount?credited:void 0})}let selectedCouncilLanes=new Set;for(let batch of[...state.prReviewValidationBatches??[]].reverse()){if(batch.phase!=="council")continue;let successful=successfulObligationsFromExactBatch(directory,state,batch.batchId,batch.lanes,"swarm-pr-review:council",batch.validatedAt);for(let lane of batch.lanes)if(successful.has(lane.workflowLane)&&!selectedCouncilLanes.has(lane.workflowLane))sources.push({batchId:batch.batchId,laneId:lane.laneId,mode:"swarm-pr-review:council"}),selectedCouncilLanes.add(lane.workflowLane)}if(state.prReviewTriggerEvalPath){let triggerPath=validateSwarmPath(directory,state.prReviewTriggerEvalPath),triggerArtifact;try{triggerArtifact=JSON.parse(readFileSync6(triggerPath,"utf-8"))}catch{throw Error("BLOCKED: PR_REVIEW trigger evaluation artifact is missing or invalid")}let receipt;try{receipt=parsePrReviewTriggerReceipt(triggerArtifact)}catch(error49){throw Error(`BLOCKED: PR_REVIEW trigger evaluation is invalid: ${error49 instanceof Error?error49.message:String(error49)}`)}for(let row of receipt.matchedRows)sources.push({batchId:row.source_batch_id,laneId:row.source_lane_id,mode:"swarm-pr-review:micro",workflowLane:row.trigger_id})}let candidateIds=[],extractedLaneKeys=new Set;for(let source of sources){let resolvedArtifact=!1;for(let record2 of findByBatchId(directory,source.batchId,{parentSessionId:state.sessionID})){if(record2.laneId!==source.laneId||record2.mode!==source.mode||record2.status!=="completed"||record2.workspace?.prHeadSha!==state.prHeadSha||record2.workspace?.gitHead!==state.prHeadSha||record2.result?.outputDegraded===!0||record2.result?.transcriptIncomplete===!0||record2.result?.truncated===!0)continue;let ref=record2.result?.outputRef?.trim(),artifact=ref?readLaneOutput(directory,ref)?.artifact:void 0,recordOwnedLanes=record2.ownedWorkflowLanes?.length?record2.ownedWorkflowLanes:record2.workflowLane?[record2.workflowLane]:void 0;if(!artifact||!workflowArtifactHasContractMarker(directory,state,record2,source.mode,record2.workflowLane??source.workflowLane??source.laneId,void 0,void 0,recordOwnedLanes))continue;if(source.workflowLane&&(!recordOwnedLanes?.includes(source.workflowLane)||!prReviewDiscoveryArtifactCoversLane(artifact.text,source.workflowLane,recordOwnedLanes)))continue;resolvedArtifact=!0;let laneKey=`${source.batchId}\x00${source.laneId}`;if(!extractedLaneKeys.has(laneKey))extractedLaneKeys.add(laneKey),candidateIds.push(...extractCandidateIds(artifact.text,source.mode==="swarm-pr-review:micro"?"micro_lane":"base_explorer",source.creditedLanes))}if(source.mode==="swarm-pr-review:micro"&&!resolvedArtifact)throw Error(`BLOCKED: PR_REVIEW mandatory micro-lane provenance is missing or invalid for ${source.workflowLane??source.laneId}`)}return assertNoDuplicates(candidateIds,"PR_REVIEW discovery candidate ids"),candidateIds.length>0?candidateIds.sort():["CLEAN-REVIEW"]}function appendBoundedCandidateIssue(issues,message){if(issues.length<MAX_CANDIDATE_ISSUES_PER_ARTIFACT-1){issues.push(message.slice(0,MAX_BASE_COVERAGE_DIAGNOSTIC_CHARS));return}if(issues.length===MAX_CANDIDATE_ISSUES_PER_ARTIFACT-1)issues.push("additional malformed candidate diagnostics omitted")}function parseCanonicalCandidateRows(text,fallbackFamily){let rows=[],issues=[],headerFamily=null;for(let[index,line]of removeCandidateCodeFences(text).split(/\r?\n/).entries()){let fields=splitPipeFields(line).map((field)=>field.trim()),detectedHeaderFamily=candidateHeaderFamily(fields);if(detectedHeaderFamily){headerFamily=detectedHeaderFamily;continue}let explicitMarker=fields[0]==="[CANDIDATE]",markerlessRow=headerFamily!==null&&Boolean(fields[0])&&!fields[0].startsWith("[");if(!explicitMarker&&!markerlessRow)continue;if(explicitMarker&&headerFamily===null){appendBoundedCandidateIssue(issues,`row ${index+1} field header: candidate output must begin with one exact canonical base or micro [CANDIDATE] header`);continue}let family=headerFamily??fallbackFamily,candidateFields=explicitMarker?fields.slice(1):fields,analysis=analyzeCandidateFields(candidateFields,family);if(!analysis.valid){for(let issue2 of analysis.issues)appendBoundedCandidateIssue(issues,`row ${index+1} field ${issue2.field}: ${issue2.message}`);continue}if(!analysis.candidateId||!analysis.workflowLane)continue;rows.push({candidateId:analysis.candidateId,workflowLane:analysis.workflowLane,evidence:candidateFields.slice(2).join("\x00"),lineNumber:index+1})}return{rows,issues}}function extractCandidateIds(text,fallbackFamily,scopeToLanes){let inScope=(lane)=>!scopeToLanes||lane!==void 0&&scopeToLanes.includes(lane);return parseCanonicalCandidateRows(text,fallbackFamily).rows.filter((row)=>inScope(row.workflowLane)).map((row)=>row.candidateId)}function derivePrReviewCriticInventory(directory,state){return[...deriveLatestPrReviewReviewerVerdicts(directory,state).entries()].filter(([,verdict])=>verdict.classification==="CONFIRMED"&&["CRITICAL","HIGH","MEDIUM"].includes(verdict.severity)).map(([itemId])=>itemId).sort()}function deriveLatestPrReviewCriticVerdicts(directory,state){let reviewerVerdicts=deriveLatestPrReviewReviewerVerdicts(directory,state),criticBatches=(state.prReviewValidationBatches??[]).filter((batch)=>batch.phase==="critic");for(let batch of[...criticBatches].reverse()){let successful=successfulObligationsFromExactBatch(directory,state,batch.batchId,batch.lanes,"swarm-pr-review:critic",batch.validatedAt);if(batch.lanes.some((lane)=>!successful.has(lane.workflowLane))||successful.size!==batch.lanes.length)continue;let required2=batch.lanes.flatMap((lane)=>lane.reviewItemIds??[]),verdicts=new Map;for(let lane of batch.lanes){let ref=findByBatchId(directory,batch.batchId,{parentSessionId:state.sessionID}).find((candidate)=>candidate.laneId===lane.laneId)?.result?.outputRef?.trim(),artifact=ref?readLaneOutput(directory,ref)?.artifact:void 0;if(!artifact)continue;for(let itemId of lane.reviewItemIds??[]){let verdict=parseCriticVerdict(artifact.text,itemId,reviewerVerdicts.get(itemId)?.severity);if(verdict)verdicts.set(itemId,verdict)}}if(required2.every((itemId)=>verdicts.has(itemId)))return verdicts}return new Map}function deriveLatestPrReviewReviewerVerdicts(directory,state){let reviewerBatches=(state.prReviewValidationBatches??[]).filter((batch)=>batch.phase==="reviewer");for(let batch of[...reviewerBatches].reverse()){let successful=successfulObligationsFromExactBatch(directory,state,batch.batchId,batch.lanes,"swarm-pr-review:reviewer",batch.validatedAt);if(batch.lanes.some((lane)=>!successful.has(lane.workflowLane))||successful.size!==batch.lanes.length)continue;let required2=batch.lanes.flatMap((lane)=>lane.reviewItemIds??[]),verdicts=new Map;for(let lane of batch.lanes){let ref=findByBatchId(directory,batch.batchId,{parentSessionId:state.sessionID}).find((candidate)=>candidate.laneId===lane.laneId)?.result?.outputRef?.trim(),artifact=ref?readLaneOutput(directory,ref)?.artifact:void 0;if(!artifact)continue;for(let itemId of lane.reviewItemIds??[]){let verdict=parseReviewerVerdict(artifact.text,itemId);if(verdict)verdicts.set(itemId,verdict)}}if(required2.every((itemId)=>verdicts.has(itemId)))return verdicts}return new Map}function successfulObligationsFromExactBatch(directory,state,batchId,expectedLanes,expectedMode,validatedAt,checkWorkflowLane=!0,forbiddenSubagentSessionIds=new Set,expectedRevisionDigest,diagnostics){let records=findByBatchId(directory,batchId,{parentSessionId:state.sessionID}),successful=new Set,validatedAtMs=Date.parse(validatedAt);if(!Number.isFinite(validatedAtMs))return successful;let expectedByLaneId=new Map(expectedLanes.map((lane)=>[lane.laneId,lane]));if(expectedByLaneId.size!==expectedLanes.length)return successful;let recordCountByLaneId=new Map,recordCountBySubagentSessionId=new Map;for(let record2 of records){if(!record2.laneId||!expectedByLaneId.has(record2.laneId))continue;recordCountByLaneId.set(record2.laneId,(recordCountByLaneId.get(record2.laneId)??0)+1);let subagentSessionId=record2.subagentSessionId?.trim();if(subagentSessionId)recordCountBySubagentSessionId.set(subagentSessionId,(recordCountBySubagentSessionId.get(subagentSessionId)??0)+1)}for(let record2 of records){let expectedLane=record2.laneId?expectedByLaneId.get(record2.laneId):void 0,expectedWorkflowLane=expectedLane?.workflowLane,expectedOwnedLanes=expectedLane?.ownedWorkflowLanes?.length?expectedLane.ownedWorkflowLanes:expectedWorkflowLane!==void 0?[expectedWorkflowLane]:void 0,subagentSessionId=record2.subagentSessionId?.trim();if(expectedWorkflowLane!==void 0&&expectedOwnedLanes!==void 0&&record2.laneId!==void 0&&recordCountByLaneId.get(record2.laneId)===1&&Boolean(subagentSessionId)&&recordCountBySubagentSessionId.get(subagentSessionId)===1&&!forbiddenSubagentSessionIds.has(subagentSessionId)&&record2.createdAt>=validatedAtMs&&(!checkWorkflowLane||record2.workflowLane===expectedWorkflowLane)&&(!checkWorkflowLane||ownedLaneSetsEqual(record2.ownedWorkflowLanes,expectedOwnedLanes))&&record2.mode===expectedMode&&record2.workspace?.prHeadSha===state.prHeadSha&&record2.workspace?.gitHead===state.prHeadSha&&record2.status==="completed"&&record2.result?.outputDegraded!==!0&&record2.result?.transcriptIncomplete!==!0&&record2.result?.truncated!==!0&&(record2.result?.chars??0)>0&&Boolean(record2.result?.digest?.trim())&&Boolean(record2.result?.outputRef?.trim())&&workflowArtifactHasContractMarker(directory,state,record2,expectedMode,expectedWorkflowLane,expectedLane?.reviewItemIds,expectedRevisionDigest,expectedOwnedLanes,diagnostics))for(let obligation of expectedOwnedLanes)successful.add(obligation)}return successful}function ownedLaneSetsEqual(recordOwned,expectedOwned){if(!recordOwned||recordOwned.length===0)return expectedOwned.length===1;let recordSet=new Set(recordOwned),expectedSet=new Set(expectedOwned);if(recordSet.size!==recordOwned.length||recordSet.size!==expectedSet.size)return!1;return recordOwned.every((owned)=>expectedSet.has(owned))}function workflowArtifactHasContractMarker(directory,state,record2,expectedMode,expectedWorkflowLane,reviewItemIds,expectedRevisionDigest,ownedWorkflowLanes,diagnostics){let ref=record2.result?.outputRef?.trim();if(!ref)return!1;let loaded=readLaneOutput(directory,ref);if(!loaded)return!1;let artifact=loaded.artifact,recordPrHeadSha=record2.workspace?.prHeadSha,recordGitHead=record2.workspace?.gitHead,resolvedRevisionDigest=expectedRevisionDigest??(recordPrHeadSha?_test_exports.resolvePrWorkflowRevisionDigest(directory,recordPrHeadSha):null),expectedReviewScope=state.mode==="PR_REVIEW"&&state.prReviewBaseSha&&state.prHeadSha?`complete PR diff ${state.prReviewBaseSha}...${state.prHeadSha}`:void 0;if(artifact.batchId!==record2.batchId||artifact.laneId!==record2.laneId||artifact.mode!==expectedMode||artifact.sessionId!==record2.subagentSessionId||artifact.parentSessionId!==record2.parentSessionId||artifact.agent!==record2.swarmPrefixedAgent||artifact.role!==record2.normalizedAgent||artifact.source!=="collect_lane_results"||artifact.workflowLane!==record2.workflowLane||artifact.workflowLane!==expectedWorkflowLane||!recordPrHeadSha||artifact.prHeadSha!==recordPrHeadSha||!recordGitHead||artifact.gitHead!==recordGitHead||!resolvedRevisionDigest||artifact.revisionDigest!==resolvedRevisionDigest||expectedReviewScope!==void 0&&(record2.workspace?.scope!==expectedReviewScope||artifact.scope!==expectedReviewScope)||artifact.digest!==record2.result?.digest||artifact.chars!==record2.result?.chars)return!1;if(expectedMode==="swarm-pr-review:reviewer")return Boolean(reviewItemIds?.length&&reviewItemIds.every((itemId)=>Boolean(parseReviewerVerdict(artifact.text,itemId))));if(expectedMode==="swarm-pr-review:critic"){let reviewerVerdicts=deriveLatestPrReviewReviewerVerdicts(directory,state);return Boolean(reviewItemIds?.length&&reviewItemIds.every((itemId)=>Boolean(parseCriticVerdict(artifact.text,itemId,reviewerVerdicts.get(itemId)?.severity))))}if(expectedMode==="swarm-pr-feedback:verification")return/^\[FEEDBACK-VERIFIED\]\s*\|/m.test(artifact.text);let feedbackVerdict={"swarm-pr-feedback:stage-b-reviewer":["[STAGE-B-REVIEW]","APPROVE"],"swarm-pr-feedback:stage-b-test":["[STAGE-B-TEST]","PASS"],"swarm-pr-feedback:closeout-reviewer":["[CLOSEOUT-REVIEW]","APPROVE"],"swarm-pr-feedback:closeout-critic":["[CLOSEOUT-CRITIC]","APPROVE"]}[expectedMode];if(feedbackVerdict)return Boolean(reviewItemIds?.length&&reviewItemIds.every((itemId)=>artifactHasExactPositiveVerdictRow(artifact.text,feedbackVerdict[0],itemId,feedbackVerdict[1])));let coveredLanes=ownedWorkflowLanes?.length?ownedWorkflowLanes:[expectedWorkflowLane],coverageAnalyses=coveredLanes.map((coveredLane)=>({coveredLane,analysis:analyzePrReviewDiscoveryArtifact(artifact.text,coveredLane,coveredLanes)}));if(coverageAnalyses.some(({analysis})=>!analysis.covered)){for(let{coveredLane,analysis}of coverageAnalyses){if(analysis.covered||analysis.issues.length===0)continue;if(diagnostics&&diagnostics.length<MAX_BASE_COVERAGE_DIAGNOSTICS){let diagnostic=`batch=${record2.batchId??"(missing)"} lane=${record2.laneId??"(missing)"} workflow_lane=${coveredLane} output_ref=${ref} digest=${record2.result?.digest??"(missing)"}: ${analysis.issues.join("; ")}`;diagnostics.push(diagnostic.slice(0,MAX_BASE_COVERAGE_DIAGNOSTIC_CHARS))}}return!1}if(coveredLanes.length>1){let seenEvidence=new Map;for(let coveredLane of coveredLanes){let evidence2=extractLaneCoverageEvidenceText(artifact.text,coveredLane,coveredLanes);if(evidence2===null)continue;if(seenEvidence.get(evidence2))return!1;seenEvidence.set(evidence2,coveredLane)}}return!0}function analyzePrReviewDiscoveryArtifact(text,expectedWorkflowLane,ownedWorkflowLanes=[expectedWorkflowLane]){let fallbackFamily=PR_REVIEW_BASE_DIMENSION_IDS.includes(expectedWorkflowLane)?"base_explorer":"micro_lane",issues=[],canonicalText=removeCandidateCodeFences(text),firstTabularFields=canonicalText.split(/\r?\n/).map((line)=>splitPipeFields(line).map((field)=>field.trim())).find((fields)=>fields.length>=2&&fields.some((field)=>field.length>0));if((firstTabularFields?candidateHeaderFamily(firstTabularFields):null)!==fallbackFamily)return appendBoundedCandidateIssue(issues,`field header: expected one exact canonical ${fallbackFamily} [CANDIDATE] header before discovery rows`),{covered:!1,evidence:null,issues};let parsed=parseCandidates({output_ref:"pr-workflow:discovery-artifact",batchId:"pr-workflow",laneId:expectedWorkflowLane,agent:"explorer",role:"explorer",digest:"0".repeat(64),text:canonicalText,artifact_status:"ok",source:"collect_lane_results",produced_at:"1970-01-01T00:00:00.000Z"},{accept_partial:!1,accept_degraded:!1,degraded:!1,row_format_version:1,producer:"swarm-pr-review",expected_family:fallbackFamily,...fallbackFamily==="base_explorer"?{expected_lane:expectedWorkflowLane,expected_lanes:[...ownedWorkflowLanes]}:{expected_micro_lane:expectedWorkflowLane,expected_micro_lanes:[...ownedWorkflowLanes]}});if(parsed.error)appendBoundedCandidateIssue(issues,parsed.error);for(let detail of parsed.diagnostics.parse_error_details)appendBoundedCandidateIssue(issues,`row ${detail.row_index+1} field ${detail.field}: ${detail.message}`);if(parsed.error||parsed.diagnostics.parse_error_details.length>0)return{covered:!1,evidence:null,issues};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};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};return{covered:!1,evidence:null,issues}}function prReviewDiscoveryArtifactCoversLane(text,expectedWorkflowLane,ownedWorkflowLanes=[expectedWorkflowLane]){return analyzePrReviewDiscoveryArtifact(text,expectedWorkflowLane,ownedWorkflowLanes).covered}function extractLaneCoverageEvidenceText(text,expectedWorkflowLane,ownedWorkflowLanes=[expectedWorkflowLane]){return analyzePrReviewDiscoveryArtifact(text,expectedWorkflowLane,ownedWorkflowLanes).evidence}function parseReviewerVerdict(text,itemId){let rows=text.split(/\r?\n/).map(pipeFields).filter((fields2)=>fields2[0]==="[REVIEWED]"&&fields2[1]===itemId);if(rows.length!==1)return null;let fields=rows[0];if(fields.length!==10||!fields.slice(1).every(Boolean))return null;let introduced=fields[5].replace(/^introduced_by_pr\s*:\s*/i,"").toUpperCase();if(!REVIEWER_CLASSIFICATIONS.has(fields[2])||!REVIEWER_EVIDENCE_TYPES.has(fields[3])||!REVIEW_SEVERITIES.has(fields[4])||!["YES","NO","UNKNOWN"].includes(introduced))return null;if(fields[7].length<8||fields[8].length<5||fields[9].length<3)return null;return{classification:fields[2],severity:fields[4]}}function parseCriticVerdict(text,itemId,reviewerSeverity){let rows=text.split(/\r?\n/).map(pipeFields).filter((fields2)=>fields2[0]==="[CRITIC]"&&fields2[1]===itemId);if(rows.length!==1)return null;let fields=rows[0];if(fields.length!==6||!fields.slice(1).every(Boolean)||!CRITIC_STATUSES.has(fields[2])||!REVIEW_SEVERITIES.has(fields[3]))return null;if(fields[2]==="NEEDS_MORE_EVIDENCE")return null;if(fields[2]==="DISPROVED"&&fields[3]!=="NONE")return null;if(fields[2]==="UPHELD"&&!["CRITICAL","HIGH","MEDIUM"].includes(fields[3]))return null;if(fields[2]==="DOWNGRADED"&&fields[3]==="CRITICAL")return null;if(reviewerSeverity){let severityRank=new Map([["NONE",0],["INFO",1],["LOW",2],["MEDIUM",3],["HIGH",4],["CRITICAL",5]]),reviewerRank=severityRank.get(reviewerSeverity),criticRank=severityRank.get(fields[3]);if(reviewerRank===void 0||criticRank===void 0)return null;if(fields[2]==="UPHELD"&&criticRank!==reviewerRank)return null;if(fields[2]==="DOWNGRADED"&&criticRank>=reviewerRank)return null}if(fields[4].length<6||fields[5].length<6)return null;return{status:fields[2],severity:fields[3]}}function artifactHasExactPositiveVerdictRow(text,marker,itemId,positiveVerdict){let rows=text.split(/\r?\n/).map(pipeFields).filter((fields)=>fields[0]===marker&&fields[1]===itemId);return rows.length===1&&rows[0].length>=4&&rows[0][2]===positiveVerdict&&rows[0].slice(1,4).every(Boolean)}function pipeFields(line){if(!line.includes("|"))return[];return line.split("|").map((field)=>field.trim())}function feedbackArtifactCoversItems(directory,state,batchId,laneId,itemIds){let ref=findByBatchId(directory,batchId,{parentSessionId:state.sessionID}).find((candidate)=>candidate.laneId===laneId)?.result?.outputRef?.trim(),loaded=ref?readLaneOutput(directory,ref):null;if(!loaded)return!1;let rows=loaded.artifact.text.split(/\r?\n/).map(pipeFields).filter((fields)=>fields[0]==="[FEEDBACK-VERIFIED]");if(rows.length!==itemIds.length)return!1;return itemIds.every((itemId)=>{let matches=rows.filter((fields)=>fields[1]===itemId);return matches.length===1&&matches[0].length===4&&matches[0].slice(1,4).every(Boolean)&&FEEDBACK_CLASSIFICATIONS.has(matches[0][2])})}async function persistState(directory,state){let validated=PrWorkflowGateStateSchema.parse(state);await withSessionStateMutation(directory,validated.sessionID,async()=>{let nextState=await writeStateWhileLocked(directory,validated);Object.assign(state,nextState)})}async function writeStateWhileLocked(directory,state,options={}){let validated=PrWorkflowGateStateSchema.parse(state),current=await readPrWorkflowGateStateFromDisk(directory,validated.sessionID);if(current?current.revision!==validated.revision:validated.revision!==0)throw Error("BLOCKED: PR workflow gate state changed concurrently; reload the active session state before retrying");if(current?.workflowInstanceId&&validated.workflowInstanceId!==current.workflowInstanceId&&options.replaceWorkflowInstanceId!==current.workflowInstanceId)throw Error("BLOCKED: PR workflow gate state changed concurrently; reload the active session state before retrying");let nextState=PrWorkflowGateStateSchema.parse({...validated,revision:validated.revision+1}),filePath=workflowGateStatePath(directory,validated.sessionID);return await writeAtomicJson2(directory,filePath,nextState),rememberState(directory,nextState),nextState}function workflowCheckoutMutationLockRelativePath(){return path14.join(WORKFLOW_GATE_DIR,"checkout.lock")}function workflowCheckoutMutationLockPath(directory){return validateSwarmPath(directory,workflowCheckoutMutationLockRelativePath())}function openCheckoutLockFile(lockPath){return fsp3.open(lockPath,"wx")}function removeCheckoutLockFile(lockPath){return fsp3.rm(lockPath)}function checkoutMutationProjectKey(directory){return normalizeComparableFsPath(directory)}async function withCheckoutMutationDeadline(promise2,phase){let timeout;try{return await Promise.race([promise2,new Promise((resolve9)=>{timeout=setTimeout(()=>{resolve9({status:"timeout",error:new PrWorkflowCheckoutMutationTimeoutError(phase)})},_test_exports.checkoutMutationActionTimeoutMs)})])}finally{if(timeout)clearTimeout(timeout)}}async function withPrWorkflowCheckoutMutationLock(directory,action){let key=checkoutMutationProjectKey(directory),previous=pendingCheckoutMutationsByProject.get(key)??Promise.resolve(),release,current=new Promise((resolve9)=>{release=resolve9}),queued=previous.then(()=>current);pendingCheckoutMutationsByProject.set(key,queued);let previousResult=await withCheckoutMutationDeadline(previous.then(()=>({status:"ready"})),"queue");if(previousResult.status==="timeout")throw release(),queued.then(()=>{if(pendingCheckoutMutationsByProject.get(key)===queued)pendingCheckoutMutationsByProject.delete(key)}),previousResult.error;let lock;try{lock=await acquireCheckoutMutationLock(directory)}catch(error49){if(release(),pendingCheckoutMutationsByProject.get(key)===queued)pendingCheckoutMutationsByProject.delete(key);throw error49}let actionOutcome=Promise.resolve().then(action).then((value)=>({status:"fulfilled",value}),(error49)=>({status:"rejected",error:error49})),outcome=await withCheckoutMutationDeadline(actionOutcome,"action");if(outcome.status==="timeout")throw actionOutcome.then(async()=>{try{await releaseCheckoutMutationLock(lock)}catch{}finally{if(release(),pendingCheckoutMutationsByProject.get(key)===queued)pendingCheckoutMutationsByProject.delete(key)}}),outcome.error;try{if(outcome.status==="rejected")throw outcome.error;return outcome.value}finally{try{await releaseCheckoutMutationLock(lock)}finally{if(release(),pendingCheckoutMutationsByProject.get(key)===queued)pendingCheckoutMutationsByProject.delete(key)}}}async function acquireCheckoutMutationLock(directory){let lockPath=workflowCheckoutMutationLockPath(directory),verifiedParent=await ensurePrWorkflowSafeParentDirectory(directory,lockPath);for(let attempt=0;attempt<STATE_MUTATION_LOCK_MAX_ATTEMPTS;attempt++)try{let handle=await _test_exports.openCheckoutLock(lockPath),lock={ownerToken:randomUUID2(),pid:process.pid,createdAtMs:_test_exports.nowMs()},lockIdentity,writeError;try{let openedStat=await handle.stat({bigint:!0});lockIdentity={dev:openedStat.dev,ino:openedStat.ino},lockIdentity=await assertOpenedSwarmFileIdentity(directory,lockPath,handle,verifiedParent,"PR workflow checkout mutation lock"),await _test_exports.beforeCheckoutLockWrite?.(),await handle.writeFile(JSON.stringify(lock),"utf-8")}catch(error49){writeError=error49}finally{await handle.close().catch(()=>{return})}if(writeError){if(lockIdentity)await removeCheckoutMutationLockByIdentity(directory,lockPath,lockIdentity,verifiedParent);throw writeError}return{path:lockPath,ownerToken:lock.ownerToken}}catch(error49){if(error49.code!=="EEXIST")throw error49;if(await reclaimAbandonedCheckoutMutationLock(lockPath))continue;if(attempt<STATE_MUTATION_LOCK_MAX_ATTEMPTS-1)await delay(STATE_MUTATION_LOCK_RETRY_DELAY_MS)}throw Error("BLOCKED: PR workflow checkout mutation is being handled by another process; retry after that checkout settles")}async function releaseCheckoutMutationLock(lock){let lastError;for(let attempt=0;attempt<WINDOWS_RENAME_MAX_RETRIES3;attempt++){try{if(await removeCheckoutMutationLockIfOwned(lock.path,lock.ownerToken)){completedCheckoutLockOwners.delete(lock.path);return}lastError=Error("PR workflow checkout mutation lock ownership changed before release")}catch(error49){lastError=error49}if(attempt<WINDOWS_RENAME_MAX_RETRIES3-1)await delay(RENAME_RETRY_DELAY_MS)}throw rememberCompletedCheckoutLockOwner(lock.path,lock.ownerToken),lastError instanceof Error?lastError:Error("PR workflow checkout mutation lock release failed")}async function reclaimAbandonedCheckoutMutationLock(lockPath){let lock=await readCheckoutMutationLock(lockPath);if(lock){if(lock.pid===process.pid&&completedCheckoutLockOwners.get(lockPath)===lock.ownerToken){let removed=await removeCheckoutMutationLockIfOwned(lockPath,lock.ownerToken);if(removed)completedCheckoutLockOwners.delete(lockPath);return removed}if(_test_exports.isProcessAlive(lock.pid))return!1;return removeCheckoutMutationLockIfOwned(lockPath,lock.ownerToken)}try{let stat6=await fsp3.stat(lockPath);if(_test_exports.nowMs()-stat6.mtimeMs<STATE_MUTATION_LOCK_UNINITIALIZED_STALE_MS)return!1;return await fsp3.rm(lockPath,{force:!0}),!0}catch(error49){if(error49.code==="ENOENT")return!0;throw error49}}async function readCheckoutMutationLock(lockPath){let raw;try{raw=await fsp3.readFile(lockPath,"utf-8")}catch(error49){if(error49.code==="ENOENT")return null;throw error49}try{let parsed=JSON.parse(raw);if(typeof parsed==="object"&&parsed!==null&&typeof parsed.ownerToken==="string"&&parsed.ownerToken.length>0&&typeof parsed.pid==="number"&&Number.isInteger(parsed.pid)&&parsed.pid>0&&typeof parsed.createdAtMs==="number"&&Number.isFinite(parsed.createdAtMs))return parsed}catch{}return null}async function removeCheckoutMutationLockIfOwned(lockPath,ownerToken){let lock=await readCheckoutMutationLock(lockPath);if(!lock||lock.ownerToken!==ownerToken)return!1;try{return await _test_exports.removeCheckoutLock(lockPath),!0}catch(error49){if(error49.code==="ENOENT")return!1;throw error49}}async function removeCheckoutMutationLockByIdentity(directory,lockPath,identity,verifiedParent){let lastError;for(let attempt=0;attempt<WINDOWS_RENAME_MAX_RETRIES3;attempt++)try{await assertClosedSwarmFileIdentity(directory,lockPath,identity,verifiedParent,"PR workflow checkout mutation lock"),await _test_exports.removeCheckoutLock(lockPath);return}catch(error49){if(error49.code==="ENOENT")return;if(lastError=error49,attempt<WINDOWS_RENAME_MAX_RETRIES3-1)await delay(RENAME_RETRY_DELAY_MS)}throw lastError instanceof Error?lastError:Error("PR workflow checkout mutation lock cleanup failed")}function rememberCompletedCheckoutLockOwner(lockPath,ownerToken){completedCheckoutLockOwners.delete(lockPath),completedCheckoutLockOwners.set(lockPath,ownerToken);while(completedCheckoutLockOwners.size>MAX_COMPLETED_CHECKOUT_LOCK_OWNERS){let oldest=completedCheckoutLockOwners.keys().next().value;if(oldest===void 0)break;completedCheckoutLockOwners.delete(oldest)}}async function withSessionStateMutation(directory,sessionID,action){let key=stateCacheKey(directory,sessionID),previous=pendingStateMutationsByProjectSession.get(key)??Promise.resolve(),release,current=new Promise((resolve9)=>{release=resolve9}),queued=previous.then(()=>current);pendingStateMutationsByProjectSession.set(key,queued),await previous;try{let lock=await acquireSessionStateMutationLock(directory,sessionID);try{return await action()}finally{await releaseSessionStateMutationLock(lock)}}finally{if(release(),pendingStateMutationsByProjectSession.get(key)===queued)pendingStateMutationsByProjectSession.delete(key)}}async function acquireSessionStateMutationLock(directory,sessionID){let lockPath=workflowGateStateLockPath(directory,sessionID),verifiedParent=await ensurePrWorkflowSafeParentDirectory(directory,lockPath);for(let attempt=0;attempt<STATE_MUTATION_LOCK_MAX_ATTEMPTS;attempt++)try{let handle=await fsp3.open(lockPath,"wx"),lock={ownerToken:randomUUID2(),pid:process.pid,createdAtMs:_test_exports.nowMs()},writeError;try{await _test_exports.beforeSessionStateLockWrite?.(),await assertOpenedSwarmFileIdentity(directory,lockPath,handle,verifiedParent,"PR workflow state mutation lock"),await handle.writeFile(JSON.stringify(lock),"utf-8")}catch(error49){writeError=error49}finally{await handle.close().catch(()=>{return})}if(writeError)throw await removeSessionStateMutationLockIfOwned(lockPath,lock.ownerToken),writeError;return{path:lockPath,ownerToken:lock.ownerToken}}catch(error49){if(error49.code!=="EEXIST")throw error49;if(await reclaimAbandonedSessionStateMutationLock(lockPath))continue;if(attempt<STATE_MUTATION_LOCK_MAX_ATTEMPTS-1)await delay(STATE_MUTATION_LOCK_RETRY_DELAY_MS)}throw Error("BLOCKED: PR workflow gate state is being mutated by another process; retry after that session transition finishes")}async function releaseSessionStateMutationLock(lock){try{await removeSessionStateMutationLockIfOwned(lock.path,lock.ownerToken)}catch{}}async function reclaimAbandonedSessionStateMutationLock(lockPath){let lock=await readSessionStateMutationLock(lockPath);if(lock){if(_test_exports.isProcessAlive(lock.pid))return!1;return removeSessionStateMutationLockIfOwned(lockPath,lock.ownerToken)}try{let stat6=await fsp3.stat(lockPath);if(_test_exports.nowMs()-stat6.mtimeMs<STATE_MUTATION_LOCK_UNINITIALIZED_STALE_MS)return!1;return await fsp3.rm(lockPath,{force:!0}),!0}catch(error49){if(error49.code==="ENOENT")return!0;throw error49}}async function readSessionStateMutationLock(lockPath){let raw;try{raw=await fsp3.readFile(lockPath,"utf-8")}catch(error49){if(error49.code==="ENOENT")return null;throw error49}try{let parsed=JSON.parse(raw);if(typeof parsed==="object"&&parsed!==null&&typeof parsed.ownerToken==="string"&&parsed.ownerToken.length>0&&typeof parsed.pid==="number"&&Number.isInteger(parsed.pid)&&parsed.pid>0&&typeof parsed.createdAtMs==="number"&&Number.isFinite(parsed.createdAtMs))return parsed}catch{}return null}async function removeSessionStateMutationLockIfOwned(lockPath,ownerToken){let lock=await readSessionStateMutationLock(lockPath);if(!lock||lock.ownerToken!==ownerToken)return!1;try{return await fsp3.rm(lockPath),!0}catch(error49){if(error49.code==="ENOENT")return!1;throw error49}}function isProcessAlive(pid){try{return process.kill(pid,0),!0}catch(error49){return error49.code!=="ESRCH"}}async function readPrWorkflowGateStateFromDisk(directory,sessionID){let filePath=workflowGateStatePath(directory,sessionID),raw;try{raw=await fsp3.readFile(filePath,"utf-8")}catch(error49){if(error49.code==="ENOENT")return null;throw error49}let parsedJson;try{parsedJson=JSON.parse(raw)}catch{throw Error(`BLOCKED: PR workflow gate state for session "${sessionID}" is not valid JSON`)}let parsed=PrWorkflowGateStateSchema.safeParse(parsedJson);if(!parsed.success)throw Error(`BLOCKED: PR workflow gate state for session "${sessionID}" is invalid`);return parsed.data}function rememberState(directory,state){let cacheKey=stateCacheKey(directory,state.sessionID);trackedStatesByProjectSession.delete(cacheKey),trackedStatesByProjectSession.set(cacheKey,state);while(trackedStatesByProjectSession.size>MAX_TRACKED_SESSIONS){let oldestKey=trackedStatesByProjectSession.keys().next().value;if(!oldestKey)break;trackedStatesByProjectSession.delete(oldestKey)}}function stateCacheKey(directory,sessionID){let resolved=path14.normalize(path14.resolve(directory));return`${process.platform==="win32"?resolved.toLowerCase():resolved}\x00${normalizeSessionID(sessionID)}`}function workflowGateStatePath(directory,sessionID){return validateSwarmPath(directory,workflowGateStateRelativePath(sessionID))}function workflowGateStateLockPath(directory,sessionID){return validateSwarmPath(directory,workflowGateStateLockRelativePath(sessionID))}function workflowGateStateLockRelativePath(sessionID){return path14.join(WORKFLOW_GATE_DIR,`${prWorkflowSessionFileStem(sessionID)}.lock`)}function workflowGateStateRelativePath(sessionID){return path14.join(WORKFLOW_GATE_DIR,`${prWorkflowSessionFileStem(sessionID)}.json`)}function prWorkflowSessionFileStem(sessionID){let normalized=normalizeSessionID(sessionID),slug=normalized.replace(/[^A-Za-z0-9_.-]/g,"_").slice(0,80)||"session",digest2=createHash7("sha256").update(normalized).digest("hex").slice(0,12);return`${slug}-${digest2}`}function normalizeSessionID(sessionID){let normalized=sessionID.trim();if(!normalized)throw Error("BLOCKED: PR workflow gate requires a non-empty sessionID");return normalized}async function ensurePrWorkflowSafeParentDirectory(directory,filePath){let swarmRoot=path14.resolve(directory,".swarm"),parentPath=path14.dirname(path14.resolve(filePath)),relativeParent=path14.relative(swarmRoot,parentPath);if(relativeParent===".."||relativeParent.startsWith(`..${path14.sep}`)||path14.isAbsolute(relativeParent))throw Error("BLOCKED: PR workflow atomic destination escapes the project .swarm directory");await fsp3.mkdir(swarmRoot,{recursive:!0});let currentPath=swarmRoot,currentIdentity=await assertSafeDirectory(currentPath,void 0);for(let segment of relativeParent.split(path14.sep).filter(Boolean)){let nextPath=path14.join(currentPath,segment);await _test_exports.beforeSafeDirectoryCreate?.(currentPath,nextPath),await assertSafeDirectory(currentPath,currentIdentity);try{await fsp3.mkdir(nextPath)}catch(error49){if(error49.code!=="EEXIST")throw error49}await assertSafeDirectory(currentPath,currentIdentity);let nextIdentity=await assertSafeDirectory(nextPath,void 0),[realCurrent,realNext]=await Promise.all([fsp3.realpath(currentPath),fsp3.realpath(nextPath)]);if(normalizeComparableFsPath(path14.dirname(realNext))!==normalizeComparableFsPath(realCurrent))throw Error("BLOCKED: PR workflow directory creation escaped the project .swarm tree");currentPath=nextPath,currentIdentity=nextIdentity}let realRoot=await fsp3.realpath(swarmRoot),realParent=await fsp3.realpath(parentPath),relativeRealParent=path14.relative(realRoot,realParent);if(relativeRealParent===".."||relativeRealParent.startsWith(`..${path14.sep}`)||path14.isAbsolute(relativeRealParent))throw Error("BLOCKED: PR workflow atomic parent escapes the project .swarm directory");return realParent}async function assertSafeDirectory(directoryPath,expectedIdentity){let stat6=await fsp3.lstat(directoryPath,{bigint:!0});if(stat6.isSymbolicLink()||!stat6.isDirectory()||expectedIdentity&&!sameBigIntFileIdentity(stat6,expectedIdentity))throw Error("BLOCKED: PR workflow .swarm path must be a real directory and must not change during the operation");return{dev:stat6.dev,ino:stat6.ino}}async function assertOpenedSwarmFileIdentity(directory,filePath,handle,expectedParent,label){let openedStat=await handle.stat({bigint:!0});if(!openedStat.isFile())throw Error(`BLOCKED: ${label} is not a file`);return await assertClosedSwarmFileIdentity(directory,filePath,openedStat,expectedParent,label),{dev:openedStat.dev,ino:openedStat.ino}}async function assertClosedSwarmFileIdentity(directory,filePath,expectedIdentity,expectedParent,label){if(!expectedIdentity)throw Error(`BLOCKED: ${label} has no identity`);let[stat6,realRoot,realFile,realParent]=await Promise.all([fsp3.lstat(filePath,{bigint:!0}),fsp3.realpath(path14.resolve(directory,".swarm")),fsp3.realpath(filePath),fsp3.realpath(path14.dirname(filePath))]),relativeFile=path14.relative(realRoot,realFile);if(stat6.isSymbolicLink()||!stat6.isFile()||!sameBigIntFileIdentity(stat6,expectedIdentity)||normalizeComparableFsPath(realParent)!==normalizeComparableFsPath(expectedParent)||relativeFile===""||relativeFile===".."||relativeFile.startsWith(`..${path14.sep}`)||path14.isAbsolute(relativeFile))throw Error(`BLOCKED: ${label} changed or escaped .swarm`)}async function writeAtomicJson2(directory,filePath,value){let safeParent=await ensurePrWorkflowSafeParentDirectory(directory,filePath),tempPath=`${filePath}.tmp.${process.pid}.${randomUUID2()}`,tempIdentity,lastError;try{let handle=await fsp3.open(tempPath,"wx");try{await _test_exports.beforeAtomicTempWrite?.(),tempIdentity=await assertOpenedSwarmFileIdentity(directory,tempPath,handle,safeParent,"PR workflow atomic temporary file"),await handle.writeFile(JSON.stringify(value,null,2),"utf-8"),await handle.sync()}finally{await handle.close()}await _test_exports.beforeAtomicRename?.(),await assertClosedSwarmFileIdentity(directory,tempPath,tempIdentity,safeParent,"PR workflow atomic temporary file");for(let attempt=0;attempt<WINDOWS_RENAME_MAX_RETRIES3;attempt++)try{await _test_exports.rename(tempPath,filePath),lastError=void 0;break}catch(error49){lastError=error49;let code=error49.code;if(code!=="EEXIST"&&code!=="EPERM"&&code!=="EBUSY")break;if(attempt<WINDOWS_RENAME_MAX_RETRIES3-1)await delay(RENAME_RETRY_DELAY_MS)}if(lastError)throw lastError;await assertClosedSwarmFileIdentity(directory,filePath,tempIdentity,safeParent,"PR workflow atomic destination file")}finally{try{await fsp3.rm(tempPath,{force:!0})}catch{}}}async function writePrWorkflowAtomicJson(directory,filePath,value){await writeAtomicJson2(directory,filePath,value)}function isoNow(){return new Date().toISOString()}function delay(ms){return new Promise((resolve9)=>setTimeout(resolve9,ms))}var PR_REVIEW_BASE_DIMENSION_IDS,PR_REVIEW_REQUIRED_MICRO_LANE_IDS,PR_REVIEW_DEPTH_TIER_THRESHOLDS,PR_REVIEW_BASE_LANE_FLOORS,PR_REVIEW_MICRO_LANE_FLOORS,GATE_SCHEMA_VERSION=1,MAX_TRACKED_SESSIONS=200,MAX_WORKFLOW_BATCHES=128,WINDOWS_RENAME_MAX_RETRIES3=3,RENAME_RETRY_DELAY_MS=10,STATE_MUTATION_LOCK_MAX_ATTEMPTS=50,STATE_MUTATION_LOCK_RETRY_DELAY_MS=10,STATE_MUTATION_LOCK_UNINITIALIZED_STALE_MS=30000,MAX_COMPLETED_CHECKOUT_LOCK_OWNERS=64,CHECKOUT_MUTATION_ACTION_TIMEOUT_MS=300000,MAX_CANDIDATE_ISSUES_PER_ARTIFACT=8,MAX_BASE_COVERAGE_DIAGNOSTICS=8,MAX_BASE_COVERAGE_DIAGNOSTIC_CHARS=1000,DISPATCH_TOOL_NAME="dispatch_lanes_async",BLOCKING_DISPATCH_TOOL_NAME="dispatch_lanes",WORKFLOW_GATE_DIR="pr-workflow-gates",trackedStatesByProjectSession,pendingStateMutationsByProjectSession,pendingCheckoutMutationsByProject,completedCheckoutLockOwners,PrReviewBaseDimensionIdSchema,PrReviewBaseDispatchRecordSchema,PrFeedbackLaneOwnershipSchema,PrFeedbackVerificationRecordSchema,PrFeedbackStageACheckReceiptSchema,PrFeedbackStageARecordSchema,PrFeedbackGateBatchRecordSchema,PrFeedbackReadyToPublishRecordSchema,PrReviewValidationBatchRecordSchema,PrFeedbackScopeDeclarationRecordSchema,PrWorkflowCheckoutRecoveryRecordSchema,PrFeedbackReviewHandoffRecordSchema,PrWorkflowGateStateSchema,PR_FEEDBACK_PHASE_ORDER,PR_FEEDBACK_PHASE_ROLE,PR_REVIEW_HANDOFF_RELATIVE_PATH_PATTERN,PR_REVIEW_HANDOFF_MAX_BYTES=131072,PR_REVIEW_FINDINGS_MAX_BYTES=10485760,PrReviewFeedbackHandoffArtifactSchema,PrReviewFindingProjectionSchema,_test_exports,PR_WORKFLOW_SHARED_CONTROLLER_TOOLS,PR_REVIEW_CONTROLLER_TOOLS,PR_FEEDBACK_CONTROLLER_TOOLS,PR_REVIEW_READ_ONLY_TOOL_NAMES,PR_WORKFLOW_CD_PREFIX_PATTERN,PR_WORKFLOW_TRAILING_STDERR_MERGE_PATTERN,PR_WORKFLOW_MAX_CD_PREFIX_STRIPS=3,PR_WORKFLOW_GIT_DIR_OVERRIDE_PATTERN,PR_WORKFLOW_GIT_HAS_DIR_OVERRIDE_PATTERN,REVIEWER_CLASSIFICATIONS,REVIEWER_EVIDENCE_TYPES,REVIEW_SEVERITIES,CRITIC_STATUSES,FEEDBACK_CLASSIFICATIONS,PrWorkflowCheckoutMutationTimeoutError;var init_pr_workflow_gate=__esm(()=>{init_zod();init_candidate_contract();init_candidate_parser();init_lane_output_store();init_pending_delegations();init_pr_review_trigger_contract();init_workspace_snapshot();init_constants();init_schema();init_pr_workflow_state();init_tool_metadata();init_utils2();PR_REVIEW_BASE_DIMENSION_IDS=["intent-architecture","correctness-state","tests-falsifiability","security-trust","reliability-performance","compatibility-delivery"],PR_REVIEW_REQUIRED_MICRO_LANE_IDS=PR_REVIEW_REQUIRED_TRIGGER_IDS,PR_REVIEW_DEPTH_TIER_THRESHOLDS={smallMaxChangedLines:50,smallMaxChangedFiles:3,mediumMaxChangedLines:500,mediumMaxChangedFiles:20},PR_REVIEW_BASE_LANE_FLOORS={S:1,M:3,L:PR_REVIEW_BASE_DIMENSION_IDS.length},PR_REVIEW_MICRO_LANE_FLOORS={S:1,M:6,L:PR_REVIEW_REQUIRED_MICRO_LANE_IDS.length};trackedStatesByProjectSession=new Map,pendingStateMutationsByProjectSession=new Map,pendingCheckoutMutationsByProject=new Map,completedCheckoutLockOwners=new Map,PrReviewBaseDimensionIdSchema=exports_external.enum(["intent-architecture","correctness-state","tests-falsifiability","security-trust","reliability-performance","compatibility-delivery"]),PrReviewBaseDispatchRecordSchema=exports_external.object({batchId:exports_external.string().min(1),lanes:exports_external.array(exports_external.object({laneId:exports_external.string().min(1),workflowLane:PrReviewBaseDimensionIdSchema,ownedWorkflowLanes:exports_external.array(PrReviewBaseDimensionIdSchema).min(1).max(PR_REVIEW_BASE_DIMENSION_IDS.length).optional()}).strict()).min(1),validatedAt:exports_external.string().min(1)}).strict(),PrFeedbackLaneOwnershipSchema=exports_external.object({laneId:exports_external.string().min(1),ownedItemIds:exports_external.array(exports_external.string().min(1)).min(1)}).strict(),PrFeedbackVerificationRecordSchema=exports_external.object({batchId:exports_external.string().min(1),ownership:exports_external.array(PrFeedbackLaneOwnershipSchema).min(1),validatedAt:exports_external.string().min(1)}).strict(),PrFeedbackStageACheckReceiptSchema=exports_external.object({category:exports_external.enum(["build","typecheck","lint","diff-check","reproduction"]),workingDirectory:exports_external.string().min(1).optional(),obligationId:exports_external.string().min(1).optional(),validatorContract:exports_external.object({path:exports_external.string().min(1),id:exports_external.string().min(1)}).strict().optional(),command:exports_external.array(exports_external.string().min(1)).min(1),targets:exports_external.array(exports_external.string().min(1)).min(1).optional(),feedbackTargets:exports_external.array(exports_external.object({feedbackItemId:exports_external.string().min(1),target:exports_external.string().min(1),expectedBehavior:exports_external.string().min(8)}).strict()).min(1).optional(),durationMs:exports_external.number().nonnegative()}).strict(),PrFeedbackStageARecordSchema=exports_external.object({revisionDigest:exports_external.string().min(1),checks:exports_external.array(PrFeedbackStageACheckReceiptSchema).min(2).max(258),feedbackItemIds:exports_external.array(exports_external.string().min(1)).min(1).optional(),applicableCategories:exports_external.array(exports_external.enum(["build","typecheck","lint"])).max(3).optional(),applicableObligations:exports_external.array(exports_external.object({id:exports_external.string().min(1),category:exports_external.enum(["build","typecheck","lint"]),workingDirectory:exports_external.string().min(1),source:exports_external.string().min(1),validatorContract:exports_external.object({path:exports_external.string().min(1),id:exports_external.string().min(1)}).strict().optional()}).strict()).max(256).optional(),validatedAt:exports_external.string().min(1)}).strict(),PrFeedbackGateBatchRecordSchema=exports_external.object({batchId:exports_external.string().min(1),phase:exports_external.enum(["stage-b-reviewer","stage-b-test","closeout-reviewer","closeout-critic"]),laneId:exports_external.string().min(1),itemIds:exports_external.array(exports_external.string().min(1)).min(1),revisionDigest:exports_external.string().min(1),validatedAt:exports_external.string().min(1)}).strict(),PrFeedbackReadyToPublishRecordSchema=exports_external.object({revisionDigest:exports_external.string().min(1),localHead:exports_external.string().min(1),remoteName:exports_external.string().min(1),remoteBranchRef:exports_external.string().startsWith("refs/heads/"),remoteRef:exports_external.string().startsWith("refs/remotes/"),validatedAt:exports_external.string().min(1)}).strict(),PrReviewValidationBatchRecordSchema=exports_external.object({batchId:exports_external.string().min(1),phase:exports_external.enum(["council","reviewer","critic"]),lanes:exports_external.array(exports_external.object({laneId:exports_external.string().min(1),workflowLane:exports_external.string().min(1),reviewItemIds:exports_external.array(exports_external.string().min(1)).min(1).optional()}).strict()).min(1),validatedAt:exports_external.string().min(1)}).strict(),PrFeedbackScopeDeclarationRecordSchema=exports_external.object({taskId:exports_external.string().regex(/^\d+\.\d+(?:\.\d+)*$/),files:exports_external.array(exports_external.string().min(1)).min(1).max(1e4),revisionDigest:exports_external.string().min(1),declaredAt:exports_external.string().min(1),consumedByCallId:exports_external.string().min(1).optional()}).strict(),PrWorkflowCheckoutRecoveryRecordSchema=exports_external.object({code:exports_external.enum(["UNMERGED_INDEX","GIT_OPERATION_IN_PROGRESS","DIRTY_SUBMODULE","SWARM_STATE_TRACKING_ERROR","GIT_STATE_INDETERMINATE"]),retryable:exports_external.literal(!1),requiredAction:exports_external.string().min(1).max(2000),evidence:exports_external.object({worktreeRoot:exports_external.string().nullable(),gitDir:exports_external.string().nullable(),operations:exports_external.array(exports_external.string().min(1)).max(16),unmergedCodes:exports_external.array(exports_external.string().min(1)).max(16),paths:exports_external.array(exports_external.string()).max(20),trackedCount:exports_external.number().int().nonnegative(),untrackedCount:exports_external.number().int().nonnegative(),pathsTruncated:exports_external.boolean(),detail:exports_external.string().max(1000).optional()}).strict(),detectedAt:exports_external.string().min(1)}).strict(),PrFeedbackReviewHandoffRecordSchema=exports_external.object({path:exports_external.string().min(1).max(512),runId:exports_external.string().min(1).max(128),sourcePrHeadSha:exports_external.string().regex(/^[0-9a-f]{6,64}$/i),prUrl:exports_external.string().url().max(2000),findingIds:exports_external.array(exports_external.string().min(1).max(128)).min(1).max(1000),digest:exports_external.string().regex(/^[0-9a-f]{64}$/),sourceWorkflowInstanceId:exports_external.string().min(1).max(128),provenance:exports_external.enum(["active-review-v1","external-v1"])}).strict(),PrWorkflowGateStateSchema=exports_external.object({schemaVersion:exports_external.literal(GATE_SCHEMA_VERSION),revision:exports_external.number().int().nonnegative().default(0),workflowInstanceId:exports_external.string().min(1).max(128).optional(),sessionID:exports_external.string().min(1),mode:exports_external.enum(["PR_REVIEW","PR_FEEDBACK"]),activatedAt:exports_external.string().min(1),updatedAt:exports_external.string().min(1),prHeadSha:exports_external.string().min(1).optional(),prReviewBaseRef:exports_external.string().min(1).optional(),prReviewBaseSha:exports_external.string().min(1).optional(),prReviewDepthTier:exports_external.enum(["S","M","L"]).optional(),prReviewDiffStats:exports_external.object({changedLines:exports_external.number().int().nonnegative(),changedFiles:exports_external.number().int().nonnegative(),hasSubmoduleChange:exports_external.boolean().default(!1)}).strict().optional(),prReviewBaseDispatches:exports_external.array(PrReviewBaseDispatchRecordSchema).max(MAX_WORKFLOW_BATCHES).optional(),prReviewBaseDispatch:PrReviewBaseDispatchRecordSchema.optional(),prReviewTriggerLedger:exports_external.array(PrReviewInlineTriggerRowSchema).length(PR_REVIEW_REQUIRED_TRIGGER_IDS.length).optional(),prReviewTriggerEvalPath:exports_external.string().min(1).optional(),prReviewValidationBatches:exports_external.array(PrReviewValidationBatchRecordSchema).max(MAX_WORKFLOW_BATCHES).optional(),prReviewArtifactRunId:exports_external.string().min(1).optional(),prReviewFindingsPath:exports_external.string().min(1).optional(),prReviewArtifactBoundaries:exports_external.array(exports_external.enum(["post_explorer","post_reviewer","post_critic"])).max(3).optional(),prReviewHandoffPath:exports_external.string().min(1).optional(),prReviewHandoffRequired:exports_external.boolean().optional(),checkoutRecovery:PrWorkflowCheckoutRecoveryRecordSchema.optional(),prFeedbackTargetUrl:exports_external.string().url().max(2000).optional(),prFeedbackReviewHandoff:PrFeedbackReviewHandoffRecordSchema.optional(),prFeedbackInventory:exports_external.array(exports_external.string().min(1)).min(1).optional(),prFeedbackVerifications:exports_external.array(PrFeedbackVerificationRecordSchema).max(MAX_WORKFLOW_BATCHES).optional(),prFeedbackVerification:PrFeedbackVerificationRecordSchema.optional(),prFeedbackStageA:PrFeedbackStageARecordSchema.optional(),prFeedbackGateBatches:exports_external.array(PrFeedbackGateBatchRecordSchema).max(MAX_WORKFLOW_BATCHES).optional(),prFeedbackReadyToPublish:PrFeedbackReadyToPublishRecordSchema.optional(),prFeedbackScopes:exports_external.array(PrFeedbackScopeDeclarationRecordSchema).max(MAX_WORKFLOW_BATCHES).optional()}).passthrough();PR_FEEDBACK_PHASE_ORDER=["stage-b-reviewer","stage-b-test","closeout-reviewer","closeout-critic"];PR_FEEDBACK_PHASE_ROLE={"stage-b-reviewer":"reviewer","stage-b-test":"test_engineer","closeout-reviewer":"reviewer","closeout-critic":"critic"};PR_REVIEW_HANDOFF_RELATIVE_PATH_PATTERN=/^pr-review\/([A-Za-z0-9][A-Za-z0-9._-]{0,127})\/feedback-handoff\.json$/,PrReviewFeedbackHandoffArtifactSchema=exports_external.object({schema_version:exports_external.literal(1),run_id:exports_external.string().min(1).max(128),pr_head_sha:exports_external.string().regex(/^[0-9a-f]{6,64}$/i),created_at:exports_external.string().datetime(),pr_url:exports_external.string().url().max(2000),finding_ids:exports_external.array(exports_external.string().min(1).max(128)).min(1).max(1000),summary:exports_external.string().min(1).max(20000),provenance:exports_external.array(exports_external.string().min(1).max(4000)).min(1).max(1000)}).strict();PrReviewFindingProjectionSchema=exports_external.object({finding_id:exports_external.string().min(1).max(128),status:exports_external.enum(["PENDING","CONFIRMED","DISPROVED","PRE_EXISTING"]),next_action:exports_external.enum(["route_to_reviewer","route_to_critic","report","suppress_with_reason","handoff_to_feedback"])}).passthrough();_test_exports={workflowGateStateRelativePath,workflowGateStateLockRelativePath,workflowCheckoutMutationLockRelativePath,withPrWorkflowCheckoutMutationLock,resetTrackedStateCache:()=>{trackedStatesByProjectSession.clear(),pendingStateMutationsByProjectSession.clear(),pendingCheckoutMutationsByProject.clear(),completedCheckoutLockOwners.clear(),_test_exports.beforeTerminalClear=void 0,_test_exports.beforePrFeedbackTransitionLock=void 0,_test_exports.beforePrFeedbackTrackingSwitch=void 0,_test_exports.afterPrFeedbackTrackingSwitch=void 0,_test_exports.beforePrFeedbackTrackingPersist=void 0,_test_exports.beforeBoundedSwarmFileOpen=void 0,_test_exports.beforeSessionStateLockWrite=void 0,_test_exports.beforeCheckoutLockWrite=void 0,_test_exports.beforeSafeDirectoryCreate=void 0,_test_exports.beforeAtomicTempWrite=void 0,_test_exports.beforeAtomicRename=void 0,_test_exports.openCheckoutLock=openCheckoutLockFile,_test_exports.removeCheckoutLock=removeCheckoutLockFile,_test_exports.checkoutMutationActionTimeoutMs=CHECKOUT_MUTATION_ACTION_TIMEOUT_MS},beforeTerminalClear:void 0,beforePrFeedbackTransitionLock:void 0,beforePrFeedbackTrackingSwitch:void 0,afterPrFeedbackTrackingSwitch:void 0,beforePrFeedbackTrackingPersist:void 0,beforeBoundedSwarmFileOpen:void 0,beforeSessionStateLockWrite:void 0,beforeCheckoutLockWrite:void 0,beforeSafeDirectoryCreate:void 0,beforeAtomicTempWrite:void 0,beforeAtomicRename:void 0,openCheckoutLock:openCheckoutLockFile,removeCheckoutLock:removeCheckoutLockFile,checkoutMutationActionTimeoutMs:CHECKOUT_MUTATION_ACTION_TIMEOUT_MS,resolveCurrentGitHead,resolveCurrentGitHeadAsync,resolveCurrentUpstreamPushTarget,resolveCurrentUpstreamPushTargetAsync,resolveCurrentUpstreamRemoteRef,resolveExactRemoteBranchHead,resolveExactRemoteBranchHeadAsync,resolveCommitCountSince,resolveCommitCountSinceAsync,resolveIsWorkingTreeClean,resolveIsWorkingTreeCleanAsync,resolveIsExactSingleChildCommit,resolveIsExactSingleChildCommitAsync,resolvePrReviewDiffStats,resolvePrReviewDiffStatsAsync,resolvePrWorkflowRevisionDigest,resolveRemoteRefsContainingHead,resolveRemoteRefsContainingHeadAsync,parseCriticVerdict,isProcessAlive,isSafeStandaloneGitCommit,rename:fsp3.rename,nowMs:()=>Date.now()};PR_WORKFLOW_SHARED_CONTROLLER_TOOLS=new Set(["abort_pr_workflow","collect_lane_results","complete_pr_workflow","dispatch_lanes_async","prepare_pr_workflow_checkout"]),PR_REVIEW_CONTROLLER_TOOLS=new Set(["parse_lane_candidates","write_pr_review_artifact","write_pr_review_trigger_eval"]),PR_FEEDBACK_CONTROLLER_TOOLS=new Set(["prepare_pr_feedback_scope","run_pr_feedback_stage_a"]);PR_REVIEW_READ_ONLY_TOOL_NAMES=new Set(["ast_grep_search","codesearch","glob","grep","list","lsp","open","read","search","skill","tree","view","web_fetch","web_search","webfetch","websearch"]);PR_WORKFLOW_CD_PREFIX_PATTERN=/^cd\s+(?:\/d\s+)?(?:"[A-Za-z0-9 _.\\/:~+-]+"|'[A-Za-z0-9 _.\\/:~+-]+'|[A-Za-z0-9_.\\/:~+-]+)\s*&&\s*/i,PR_WORKFLOW_TRAILING_STDERR_MERGE_PATTERN=/\s+2>&1\s*$/,PR_WORKFLOW_GIT_DIR_OVERRIDE_PATTERN=/^[Gg][Ii][Tt](?: -C (?:"[^"]+"|'[^']+'|\S+))* (.+)$/,PR_WORKFLOW_GIT_HAS_DIR_OVERRIDE_PATTERN=/^[Gg][Ii][Tt] -C /;REVIEWER_CLASSIFICATIONS=new Set(["CONFIRMED","DISPROVED","UNVERIFIED","PRE_EXISTING"]),REVIEWER_EVIDENCE_TYPES=new Set(["STRUCTURALLY_PROVEN","EXECUTION_PROVEN","STATIC_TRACE_PROVEN","PLAUSIBLE_BUT_UNVERIFIED"]),REVIEW_SEVERITIES=new Set(["CRITICAL","HIGH","MEDIUM","LOW","INFO","NONE"]),CRITIC_STATUSES=new Set(["UPHELD","DOWNGRADED","DISPROVED","NEEDS_MORE_EVIDENCE"]),FEEDBACK_CLASSIFICATIONS=new Set(["CONFIRMED","PARTIAL","DISPROVED","PRE_EXISTING","NEEDS_MORE_EVIDENCE","NEEDS_USER_DECISION"]);PrWorkflowCheckoutMutationTimeoutError=class PrWorkflowCheckoutMutationTimeoutError extends Error{phase;code="PR_WORKFLOW_CHECKOUT_MUTATION_TIMEOUT";retryable=!1;constructor(phase){super(phase==="queue"?"BLOCKED: timed out waiting for the active PR workflow checkout mutation; the existing owner still holds serialization and must settle before retrying":"BLOCKED: PR workflow checkout mutation exceeded its execution deadline; serialization remains held until the in-flight action actually settles");this.phase=phase;this.name="PrWorkflowCheckoutMutationTimeoutError"}}});async function handleAbortPrWorkflowCommand(directory,args2,sessionID){let tokens=(args2??[]).filter((token)=>token.trim().length>0),modeToken=tokens[0]?.toUpperCase(),knownMode=modeToken&&KNOWN_MODES.has(modeToken)?modeToken:void 0,reasonStartIndex=knownMode?1:0,reason=tokens.slice(reasonStartIndex).join(" ").trim().slice(0,500)||void 0;if(modeToken&&!knownMode)return`Error: Unknown mode "${modeToken}". Expected PR_REVIEW or PR_FEEDBACK.
185
+ `,"utf-8")}catch{}return await clearPrWorkflowGateState(directory,sessionID,state.revision),{mode:state.mode,...state.prHeadSha?{prHeadSha:state.prHeadSha}:{},openLanes:openLanes.length}}async function bindPrWorkflowHead(directory,sessionID,prHeadSha){let normalizedHead=normalizePrHeadSha(prHeadSha);return withPrWorkflowCheckoutMutationLock(directory,async()=>withSessionStateMutation(directory,normalizeSessionID(sessionID),async()=>{let state=await readPrWorkflowGateStateFromDisk(directory,normalizeSessionID(sessionID));if(!state)throw Error(`BLOCKED: no active PR workflow gate for session "${normalizeSessionID(sessionID)}". The gate must be activated before the PR head can be bound.`);if(await assertCurrentCheckoutHead(directory,normalizedHead,state.mode),state.prHeadSha&&state.prHeadSha!==normalizedHead)throw Error(`BLOCKED: active ${state.mode} workflow is bound to PR head "${state.prHeadSha}"; received "${normalizedHead}"`);if(!state.prHeadSha)await assertPrReviewCleanCheckout(directory,state.mode);if(!state.prHeadSha&&state.mode==="PR_FEEDBACK")await assertPrFeedbackTrackingCheckout(directory,normalizedHead);if(state.prHeadSha===normalizedHead){if(state.mode==="PR_FEEDBACK")await assertPrFeedbackTrackingCheckout(directory,normalizedHead);return state}let nextState={...state,prHeadSha:normalizedHead,updatedAt:isoNow()};return await _test_exports.beforePrFeedbackTrackingPersist?.(),writeStateWhileLocked(directory,nextState)}))}async function bindPrReviewBase(directory,sessionID,options){let state=await bindPrWorkflowHead(directory,sessionID,options.prHeadSha);if(state.mode!=="PR_REVIEW")throw Error("BLOCKED: only PR_REVIEW can bind a review merge base");let baseRef=options.baseRef.trim(),baseSha=normalizePrHeadSha(options.baseSha).toLowerCase();if(!baseRef)throw Error("BLOCKED: PR_REVIEW base_ref must not be empty");if(state.prReviewBaseRef&&state.prReviewBaseRef!==baseRef||state.prReviewBaseSha&&state.prReviewBaseSha!==baseSha)throw Error(`BLOCKED: active PR_REVIEW is bound to merge-base scope "${state.prReviewBaseRef??"(unbound)"}" at "${state.prReviewBaseSha??"(unbound)"}"; received "${baseRef}" at "${baseSha}"`);if(state.prReviewBaseRef===baseRef&&state.prReviewBaseSha===baseSha)return state;let prHeadSha=normalizePrHeadSha(options.prHeadSha).toLowerCase(),diffStats=await _test_exports.resolvePrReviewDiffStatsAsync(directory,baseSha,prHeadSha);return state={...state,prReviewBaseRef:baseRef,prReviewBaseSha:baseSha,prReviewDepthTier:computePrReviewDepthTier(diffStats),...diffStats?{prReviewDiffStats:diffStats}:{},updatedAt:isoNow()},await persistState(directory,state),state}async function assertCurrentCheckoutHead(directory,expectedHead,mode="PR_REVIEW"){let normalizedExpected=normalizePrHeadSha(expectedHead),currentHead=(await _test_exports.resolveCurrentGitHeadAsync(directory))?.trim();if(!currentHead)throw Error(`BLOCKED: cannot resolve the current Git HEAD in "${directory}" to verify against PR head "${normalizedExpected}". This means Git could not resolve HEAD (the working directory may not be a Git repository, HEAD may be unborn, the commit object may be missing in a shallow clone, the Git binary may not be on PATH, or the bounded Git invocation may have timed out). Verify with: git -C "${directory}" rev-parse --verify HEAD^{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 these bare, standalone commands from that directory: if the commit is not present locally, \`git fetch origin <pr-head-ref>\`; then \`git switch --detach ${normalizedExpected}\`. Do not prefix the switch with \`git -C\`; the read-only shell classifier refuses \`git -C ... switch\`.`;throw Error(`BLOCKED: current checkout HEAD "${currentHead}" does not match PR head "${normalizedExpected}" (working directory: "${directory}"). ${remediation}`)}return normalizedExpected}async function assertPrReviewCleanCheckout(directory,mode="PR_REVIEW"){if(await _test_exports.resolveIsWorkingTreeCleanAsync(directory)!==!0)throw Error(`BLOCKED: ${mode} requires a clean index and working tree at the exact PR head`)}async function assertPrFeedbackTrackingCheckout(directory,prHeadSha){let currentHead=(await _test_exports.resolveCurrentGitHeadAsync(directory))?.trim();if(!currentHead)throw Error("BLOCKED: PR_FEEDBACK requires a resolved exact Git HEAD before first head bind");if(currentHead.toLowerCase()!==prHeadSha.toLowerCase())throw Error(`BLOCKED: PR_FEEDBACK exact head changed before attach; expected ${prHeadSha}, received ${currentHead}`);let currentUpstream=await _test_exports.resolveCurrentUpstreamPushTargetAsync(directory),matchingRemoteRefs=await _test_exports.resolveRemoteRefsContainingHeadAsync(directory,prHeadSha);if(currentUpstream){if(matchingRemoteRefs===null)throw Error("BLOCKED: PR_FEEDBACK could not verify the current upstream against the exact intake PR head; the bounded Git query failed or timed out");if(matchingRemoteRefs.includes(currentUpstream.remoteTrackingRef))return;throw Error(`BLOCKED: PR_FEEDBACK current upstream "${currentUpstream.remoteTrackingRef}" must point to the exact intake PR head "${prHeadSha}"; refusing to replace an existing tracking relationship`)}let candidates=await resolvePrFeedbackTrackingCandidatesAsync(directory,prHeadSha);if(!candidates)throw Error(`BLOCKED: PR_FEEDBACK could not inspect tracked branches for exact PR head "${prHeadSha}"; the bounded Git query failed or timed out`);let{local:localCandidates,remote:remoteCandidates}=candidates;if(localCandidates.length===1){if(await _test_exports.beforePrFeedbackTrackingSwitch?.(),!await switchPrFeedbackTrackingCandidateAsync(directory,localCandidates[0]))throw Error(`BLOCKED: PR_FEEDBACK could not attach exact local tracked branch "${localCandidates[0].branchName}"; it may be checked out in another linked worktree or the bounded Git switch failed`)}else if(localCandidates.length>1)throw Error(`BLOCKED: PR_FEEDBACK exact head "${prHeadSha}" matches multiple local tracked branches: ${localCandidates.map((candidate)=>candidate.branchName).join(", ")}`);else if(remoteCandidates.length===1){if(await _test_exports.beforePrFeedbackTrackingSwitch?.(),!await switchPrFeedbackTrackingCandidateAsync(directory,remoteCandidates[0]))throw Error(`BLOCKED: PR_FEEDBACK could not attach exact remote-tracking branch "${remoteCandidates[0].remoteTrackingRef}"; the bounded Git switch failed or timed out`)}else if(remoteCandidates.length>1)throw Error(`BLOCKED: PR_FEEDBACK exact head "${prHeadSha}" matches multiple remote-tracking refs: ${remoteCandidates.map((candidate)=>candidate.remoteTrackingRef).join(", ")}`);else throw Error("BLOCKED: PR_FEEDBACK requires a current local branch or exact remote-tracking ref that points to the intake PR head before the first bind");await _test_exports.afterPrFeedbackTrackingSwitch?.();let attachedHead=(await _test_exports.resolveCurrentGitHeadAsync(directory))?.trim();if(attachedHead?.toLowerCase()!==prHeadSha.toLowerCase())throw Error(`BLOCKED: PR_FEEDBACK exact head changed after attach; expected ${prHeadSha}, received ${attachedHead??"(unresolved)"}`);if(await _test_exports.resolveIsWorkingTreeCleanAsync(directory)!==!0)throw Error("BLOCKED: PR_FEEDBACK requires a clean working tree after checkout attachment");let attachedUpstream=await _test_exports.resolveCurrentUpstreamPushTargetAsync(directory);if(!attachedUpstream)throw Error("BLOCKED: PR_FEEDBACK could not resolve the attached branch upstream after checkout promotion");if(!(await _test_exports.resolveRemoteRefsContainingHeadAsync(directory,prHeadSha))?.includes(attachedUpstream.remoteTrackingRef))throw Error(`BLOCKED: PR_FEEDBACK upstream "${attachedUpstream.remoteTrackingRef}" must point to the exact intake PR head "${prHeadSha}" before the first head bind`)}async function enforcePrWorkflowDispatchLanesAsync(directory,sessionID,toolName){let state=await readPrWorkflowGateState(directory,sessionID);if(!state)return null;if(toolName===DISPATCH_TOOL_NAME)return state;if(toolName===BLOCKING_DISPATCH_TOOL_NAME)throw Error(`BLOCKED: active ${state.mode} workflow for session "${state.sessionID}" requires ${DISPATCH_TOOL_NAME}; ${BLOCKING_DISPATCH_TOOL_NAME} is not allowed`);return state}async function enforcePrReviewBaseDimensions(directory,sessionID,lanes,options){let state=await bindPrWorkflowHead(directory,sessionID,options.prHeadSha);if(state.mode!=="PR_REVIEW")throw wrongModeError(state,"PR_REVIEW");let normalizedLanes=normalizeWorkflowLanes(lanes),claimedDimensionIds=normalizedLanes.flatMap((lane)=>lane.ownedWorkflowLanes??[lane.workflowLane]);if(claimedDimensionIds.filter((laneId)=>!PR_REVIEW_BASE_DIMENSION_IDS.includes(laneId)).length>0){let expected=PR_REVIEW_BASE_DIMENSION_IDS.join(", "),received=claimedDimensionIds.join(", ")||"(none)";throw Error(`BLOCKED: PR_REVIEW base dispatch lane ids must be drawn from: ${expected}. Received: ${received}`)}if((state.prReviewDepthTier??"L")==="L"&&normalizedLanes.some((lane)=>(lane.ownedWorkflowLanes?.length??1)!==1))throw Error("BLOCKED: PR_REVIEW base dispatch at depth tier L requires one dedicated lane per dimension; consolidated owned_workflow_lanes are allowed only at tiers S and M");let batchId=normalizeBatchId(options.batchId),previous=state.prReviewBaseDispatches??[];if(previous.some((record3)=>record3.batchId===batchId))throw Error(`BLOCKED: PR_REVIEW base batch id "${batchId}" is already recorded`);if(previous.length>=MAX_WORKFLOW_BATCHES)throw Error("BLOCKED: PR_REVIEW base batch limit reached");let record2={batchId,lanes:normalizedLanes.map((lane)=>({laneId:lane.laneId,workflowLane:lane.workflowLane,...lane.ownedWorkflowLanes?{ownedWorkflowLanes:lane.ownedWorkflowLanes}:{}})),validatedAt:isoNow()},nextState={...state,updatedAt:isoNow(),prReviewBaseDispatches:[...previous,record2],prReviewBaseDispatch:record2};return await persistState(directory,nextState),nextState}async function assertPrReviewBaseCoverageSettled(directory,sessionID){let state=await requireBoundState(directory,sessionID,"PR_REVIEW"),batches=state.prReviewBaseDispatches??[];if(batches.length===0)throw Error("BLOCKED: PR_REVIEW requires at least one base batch");let covered=new Set,malformedDiagnostics=[];for(let batch of batches){let successful=successfulObligationsFromExactBatch(directory,state,batch.batchId,batch.lanes,"swarm-pr-review:base",batch.validatedAt,!0,new Set,void 0,malformedDiagnostics);for(let obligation of successful)covered.add(obligation)}let missing=PR_REVIEW_BASE_DIMENSION_IDS.filter((dimension)=>!covered.has(dimension));if(missing.length>0||covered.size!==PR_REVIEW_BASE_DIMENSION_IDS.length)throw Error(`BLOCKED: PR_REVIEW base coverage is incomplete; missing dimensions: ${missing.join(", ")||"(none)"}${malformedDiagnostics.length>0?`; malformed candidate diagnostics: ${malformedDiagnostics.join(" | ")}`:""}`);return state}async function recordPrReviewValidationBatch(directory,sessionID,phase,lanes,options){let state=await bindPrWorkflowHead(directory,sessionID,options.prHeadSha);if(state.mode!=="PR_REVIEW")throw wrongModeError(state,"PR_REVIEW");if(!state.prReviewTriggerEvalPath)throw Error("BLOCKED: PR_REVIEW validation dispatch requires a completed trigger evaluation");if(phase==="reviewer"&&(state.prReviewValidationBatches??[]).some((batch)=>batch.phase==="council"))state=await assertPrReviewValidationSettled(directory,sessionID,"council");else if(phase==="critic")state=await assertPrReviewValidationSettled(directory,sessionID,"reviewer");let normalizedLanes=normalizeWorkflowLanes(lanes);if((phase==="reviewer"||phase==="critic")&&normalizedLanes.some((lane)=>!lane.reviewItemIds?.length))throw Error(`BLOCKED: PR_REVIEW ${phase} lanes require non-empty review_item_ids ownership`);if(phase==="reviewer"||phase==="critic"){assertNoDuplicates(normalizedLanes.flatMap((lane)=>lane.reviewItemIds??[]),`PR_REVIEW ${phase} review item ownership`);let assigned=normalizedLanes.flatMap((lane)=>lane.reviewItemIds??[]),required2=phase==="reviewer"?derivePrReviewCandidateInventory(directory,state):derivePrReviewCriticInventory(directory,state);assertExactStringSet(assigned,required2,`PR_REVIEW ${phase} ownership`)}let batchId=normalizeBatchId(options.batchId),previous=state.prReviewValidationBatches??[];if(previous.some((batch)=>batch.batchId===batchId))throw Error(`BLOCKED: PR_REVIEW validation batch id "${batchId}" is already recorded`);if(previous.length>=MAX_WORKFLOW_BATCHES)throw Error("BLOCKED: PR_REVIEW validation batch limit reached");let record2={batchId,phase,lanes:normalizedLanes,validatedAt:isoNow()},retained=phase==="reviewer"?previous.filter((batch)=>batch.phase!=="critic"):previous,nextState={...state,updatedAt:isoNow(),prReviewValidationBatches:[...retained,record2]};return await persistState(directory,nextState),nextState}async function assertPrReviewValidationSettled(directory,sessionID,phase){let state=await requireBoundState(directory,sessionID,"PR_REVIEW"),declaredPhases=new Set((state.prReviewValidationBatches??[]).map((batch)=>batch.phase)),phases=phase?[phase]:["council","reviewer","critic"].filter((candidate)=>declaredPhases.has(candidate));for(let requiredPhase of phases){let validationBatches=state.prReviewValidationBatches??[],forbiddenSubagentSessionIds=new Set;if(requiredPhase==="critic")for(let reviewerBatch of validationBatches.filter((batch)=>batch.phase==="reviewer"))for(let record2 of findByBatchId(directory,reviewerBatch.batchId,{parentSessionId:state.sessionID})){let subagentSessionId=record2.subagentSessionId?.trim();if(subagentSessionId)forbiddenSubagentSessionIds.add(subagentSessionId)}let batches=validationBatches.filter((batch)=>batch.phase===requiredPhase);if(requiredPhase==="reviewer"){let latestCouncilIndex=-1;for(let index=0;index<validationBatches.length;index++)if(validationBatches[index]?.phase==="council")latestCouncilIndex=index;if(latestCouncilIndex>=0)batches=validationBatches.slice(latestCouncilIndex+1).filter((batch)=>batch.phase==="reviewer")}if(batches.length===0)throw Error(requiredPhase==="reviewer"&&declaredPhases.has("council")?"BLOCKED: PR_REVIEW requires at least one reviewer batch after the latest council batch":`BLOCKED: PR_REVIEW requires at least one ${requiredPhase} batch`);let allObligations=new Set(batches.flatMap((batch)=>batch.lanes.map((lane)=>lane.workflowLane))),settled=new Set,hasFullySuccessfulExactBatch=!1;for(let batch of batches){let successful=successfulObligationsFromExactBatch(directory,state,batch.batchId,batch.lanes,`swarm-pr-review:${requiredPhase}`,batch.validatedAt,!0,forbiddenSubagentSessionIds);if(successful.size===batch.lanes.length&&batch.lanes.every((lane)=>successful.has(lane.workflowLane)))hasFullySuccessfulExactBatch=!0;for(let obligation of successful)settled.add(obligation)}if((requiredPhase==="reviewer"||requiredPhase==="critic")&&!hasFullySuccessfulExactBatch)throw Error(`BLOCKED: PR_REVIEW ${requiredPhase} requires one fully successful exact batch; complementary partial retries are not a coherent verdict set`);let missing=[...allObligations].filter((obligation)=>!settled.has(obligation));if(missing.length>0)throw Error(`BLOCKED: PR_REVIEW ${requiredPhase} obligations lack successful exact artifacts: ${missing.join(", ")}`)}return state}async function declarePrFeedbackInventory(directory,sessionID,inventoryIds,options){let state=await bindPrWorkflowHead(directory,sessionID,options.prHeadSha);if(state.mode!=="PR_FEEDBACK")throw wrongModeError(state,"PR_FEEDBACK");let normalizedInventory=normalizeInventoryIds(inventoryIds),requiredHandoffIds=state.prFeedbackReviewHandoff?.findingIds??[],inventorySet=new Set(normalizedInventory),missingHandoffIds=requiredHandoffIds.filter((findingId)=>!inventorySet.has(findingId));if(missingHandoffIds.length>0)throw Error(`BLOCKED: PR_FEEDBACK inventory must include every continued review finding: ${missingHandoffIds.join(", ")}`);if(state.prFeedbackInventory){if(!sameStringArray(state.prFeedbackInventory,normalizedInventory))throw Error("BLOCKED: PR_FEEDBACK inventory is immutable after declaration");return state}let nextState={...state,updatedAt:isoNow(),prFeedbackInventory:normalizedInventory,prFeedbackVerifications:[]};return await persistState(directory,nextState),nextState}async function enforcePrFeedbackVerificationOwnership(directory,sessionID,ownership,options){let state=await bindPrWorkflowHead(directory,sessionID,options.prHeadSha);if(state.mode!=="PR_FEEDBACK")throw wrongModeError(state,"PR_FEEDBACK");let inventory=state.prFeedbackInventory;if(!inventory||inventory.length===0)throw Error(`BLOCKED: PR_FEEDBACK verification for session "${state.sessionID}" requires a declared feedback inventory before dispatch`);let normalizedOwnership=normalizeOwnership(ownership),inventorySet=new Set(inventory),claimedByItemId=new Map,previous=state.prFeedbackVerifications??[],batchId=normalizeBatchId(options.batchId);if(previous.some((record3)=>record3.batchId===batchId))throw Error(`BLOCKED: PR_FEEDBACK verification batch id "${batchId}" is already recorded`);if(previous.length>=MAX_WORKFLOW_BATCHES)throw Error("BLOCKED: PR_FEEDBACK verification batch limit reached");for(let record3 of previous)for(let lane of record3.ownership)for(let itemId of lane.ownedItemIds)claimedByItemId.set(itemId,lane.laneId);for(let lane of normalizedOwnership)for(let itemId of lane.ownedItemIds){if(!inventorySet.has(itemId))throw Error(`BLOCKED: PR_FEEDBACK verification lane "${lane.laneId}" owns undeclared item "${itemId}"`);let previousLane=claimedByItemId.get(itemId);if(previousLane&&previousLane!==lane.laneId)throw Error(`BLOCKED: PR_FEEDBACK verification item "${itemId}" is owned by both "${previousLane}" and "${lane.laneId}"`);claimedByItemId.set(itemId,lane.laneId)}let record2={batchId,ownership:normalizedOwnership,validatedAt:isoNow()},nextState={...state,updatedAt:isoNow(),prFeedbackVerifications:[...previous,record2],prFeedbackVerification:record2};return await persistState(directory,nextState),nextState}async function assertPrFeedbackVerificationSettled(directory,sessionID){let state=await requireBoundState(directory,sessionID,"PR_FEEDBACK"),currentDigest=await currentPrFeedbackRevisionDigest(directory,state),inventory=state.prFeedbackInventory,batches=state.prFeedbackVerifications??[];if(!inventory||batches.length===0)throw Error("BLOCKED: PR_FEEDBACK requires an immutable inventory and verification batches");let covered=new Set;for(let batch of batches){let successfulLaneIds=successfulObligationsFromExactBatch(directory,state,batch.batchId,batch.ownership.map((lane)=>({laneId:lane.laneId,workflowLane:lane.laneId})),"swarm-pr-feedback:verification",batch.validatedAt,!1,new Set,currentDigest);for(let lane of batch.ownership){if(!successfulLaneIds.has(lane.laneId))continue;if(!feedbackArtifactCoversItems(directory,state,batch.batchId,lane.laneId,lane.ownedItemIds))continue;for(let itemId of lane.ownedItemIds)covered.add(itemId)}}let missing=inventory.filter((itemId)=>!covered.has(itemId));if(missing.length>0||covered.size!==inventory.length)throw Error(`BLOCKED: PR_FEEDBACK verification ownership is incomplete; missing inventory items: ${missing.join(", ")||"(none)"}`);return state}async function recordPrFeedbackStageA(directory,sessionID,revisionDigest,checks3,options={}){let state=await assertPrFeedbackVerificationSettled(directory,sessionID),currentDigest=await currentPrFeedbackRevisionDigest(directory,state);if(revisionDigest!==currentDigest)throw Error("BLOCKED: PR_FEEDBACK Stage A receipt is stale because the working-tree revision changed during validation");if(checks3.length<2||checks3.length>258)throw Error("BLOCKED: PR_FEEDBACK Stage A requires two to 258 controller-created check receipts");let optionalCategoryOrder=["build","typecheck","lint"],applicableCategories=options.applicableCategories??optionalCategoryOrder.filter((category)=>checks3.some((check2)=>check2.category===category));if(assertNoDuplicates(applicableCategories,"PR_FEEDBACK Stage A applicable categories"),applicableCategories.some((category)=>!optionalCategoryOrder.includes(category)))throw Error("BLOCKED: PR_FEEDBACK Stage A applicability may contain only build, typecheck, and lint");let required2=new Set(["diff-check","reproduction",...applicableCategories]),singletonSeen=new Set,applicableObligations=[...options.applicableObligations??[]];assertNoDuplicates(applicableObligations.map(({id})=>id),"PR_FEEDBACK Stage A applicable obligations");let requiredObligationIds=new Set(applicableObligations.map(({id})=>id)),commandDigests=new Set,reproductionFeedbackItemIds=[];for(let check2 of checks3){if(["diff-check","reproduction"].includes(check2.category)&&singletonSeen.has(check2.category))throw Error(`BLOCKED: PR_FEEDBACK Stage A contains duplicate category "${check2.category}"`);if(singletonSeen.add(check2.category),required2.delete(check2.category),check2.obligationId){let obligation=applicableObligations.find((candidate)=>candidate.id===check2.obligationId);if(!obligation||obligation.category!==check2.category||obligation.workingDirectory!==(check2.workingDirectory??".")||!requiredObligationIds.delete(check2.obligationId))throw Error(`BLOCKED: PR_FEEDBACK Stage A receipt does not match one exact applicable obligation: ${check2.obligationId}`);let sourceContract=obligation.source.includes(".pr-validation.json#")?{path:obligation.source.slice(0,obligation.source.lastIndexOf("#")),id:obligation.source.slice(obligation.source.lastIndexOf("#")+1)}:void 0,requiredContract=obligation.validatorContract??sourceContract;if(requiredContract&&(check2.validatorContract?.path!==requiredContract.path||check2.validatorContract.id!==requiredContract.id))throw Error(`BLOCKED: PR_FEEDBACK Stage A obligation ${obligation.id} requires exact validator contract provenance`)}let commandDigest=createHash7("sha256").update(`${check2.obligationId??check2.category}\x00${check2.workingDirectory??"."}\x00${check2.command.join("\x00")}`).digest("hex");if(commandDigests.has(commandDigest))throw Error("BLOCKED: PR_FEEDBACK Stage A cannot reuse one command as multiple check receipts");if(commandDigests.add(commandDigest),check2.category==="diff-check"&&!sameStringArray(check2.command,["git","diff","--check"]))throw Error("BLOCKED: PR_FEEDBACK Stage A diff-check receipt is not the exact git diff --check command");if(check2.category==="reproduction"&&(!check2.targets?.length||!check2.feedbackTargets?.length||check2.targets.some((target)=>!check2.command.join(" ").includes(target))))throw Error("BLOCKED: PR_FEEDBACK Stage A reproduction receipt requires exact selected targets");if(check2.category==="reproduction"){if(reproductionFeedbackItemIds=check2.feedbackTargets.map((mapping)=>mapping.feedbackItemId),assertNoDuplicates(reproductionFeedbackItemIds,"PR_FEEDBACK Stage A reproduction feedback item mappings"),check2.feedbackTargets.some((mapping)=>!check2.targets.includes(mapping.target)))throw Error("BLOCKED: PR_FEEDBACK Stage A feedback mappings must reference exact executed reproduction targets")}}if(required2.size>0)throw Error(`BLOCKED: PR_FEEDBACK Stage A is missing required checks: ${[...required2].join(", ")}`);if(requiredObligationIds.size>0)throw Error(`BLOCKED: PR_FEEDBACK Stage A is missing applicable workspace obligations: ${[...requiredObligationIds].join(", ")}`);if(!sameStringArray(reproductionFeedbackItemIds,state.prFeedbackInventory??[]))throw Error("BLOCKED: PR_FEEDBACK Stage A reproduction must map every immutable feedback item exactly once and in declared order");let nextState={...state,updatedAt:isoNow(),prFeedbackStageA:{revisionDigest:currentDigest,checks:[...checks3],feedbackItemIds:reproductionFeedbackItemIds,applicableCategories:optionalCategoryOrder.filter((category)=>applicableCategories.includes(category)),applicableObligations,validatedAt:isoNow()},prFeedbackGateBatches:[],prFeedbackReadyToPublish:void 0};return await persistState(directory,nextState),nextState}async function recordPrFeedbackGateBatch(directory,sessionID,phase,lane,options){let state=await bindPrWorkflowHead(directory,sessionID,options.prHeadSha);if(state.mode!=="PR_FEEDBACK")throw wrongModeError(state,"PR_FEEDBACK");let inventory=state.prFeedbackInventory;if(!inventory?.length)throw Error("BLOCKED: PR_FEEDBACK ordered gates require an immutable feedback inventory");let normalized=normalizeOwnership([lane])[0];if(!sameStringArray(normalized.ownedItemIds,inventory))throw Error(`BLOCKED: PR_FEEDBACK ${phase} must own every inventory item exactly once and in declared order`);let phaseIndex=PR_FEEDBACK_PHASE_ORDER.indexOf(phase),prerequisite=PR_FEEDBACK_PHASE_ORDER[phaseIndex-1];if(prerequisite)state=await assertPrFeedbackGatePhaseSettled(directory,sessionID,prerequisite);let{prFeedbackStageA:stageA,prFeedbackInventory:refreshedInventory}=state,currentDigest=await currentPrFeedbackRevisionDigest(directory,state);if(!stageA||!refreshedInventory||stageA.revisionDigest!==currentDigest||!sameStringArray(stageA.feedbackItemIds??[],refreshedInventory)||options.revisionDigest!==currentDigest)throw Error(`BLOCKED: PR_FEEDBACK ${phase} requires fresh Stage A checks on the current revision`);let batchId=normalizeBatchId(options.batchId),previous=state.prFeedbackGateBatches??[];if(previous.some((batch)=>batch.batchId===batchId))throw Error(`BLOCKED: PR_FEEDBACK gate batch id "${batchId}" is already recorded`);let retained=previous.filter((batch)=>PR_FEEDBACK_PHASE_ORDER.indexOf(batch.phase)<phaseIndex),record2={batchId,phase,laneId:normalized.laneId,itemIds:normalized.ownedItemIds,revisionDigest:currentDigest,validatedAt:isoNow()},nextState={...state,updatedAt:isoNow(),prFeedbackGateBatches:[...retained,record2]};return await persistState(directory,nextState),nextState}async function assertPrFeedbackGatePhaseSettled(directory,sessionID,phase){let state=await requireBoundState(directory,sessionID,"PR_FEEDBACK"),currentDigest=await currentPrFeedbackRevisionDigest(directory,state);if(state.prFeedbackStageA?.revisionDigest!==currentDigest)throw Error(`BLOCKED: PR_FEEDBACK ${phase} cannot use stale Stage A evidence`);if(!sameStringArray(state.prFeedbackStageA?.feedbackItemIds??[],state.prFeedbackInventory??[]))throw Error(`BLOCKED: PR_FEEDBACK ${phase} Stage A reproduction is not bound to the exact immutable feedback inventory`);let batch=[...state.prFeedbackGateBatches??[]].reverse().find((candidate)=>candidate.phase===phase);if(!batch||batch.revisionDigest!==currentDigest)throw Error(`BLOCKED: PR_FEEDBACK ${phase} has no validation batch on the current revision`);if(!successfulObligationsFromExactBatch(directory,state,batch.batchId,[{laneId:batch.laneId,workflowLane:phase,reviewItemIds:batch.itemIds}],`swarm-pr-feedback:${phase}`,batch.validatedAt,!0,new Set,currentDigest).has(phase))throw Error(`BLOCKED: PR_FEEDBACK ${phase} requires one complete, non-degraded positive verdict row per inventory item`);if(findByBatchId(directory,batch.batchId,{parentSessionId:state.sessionID}).find((candidate)=>candidate.laneId===batch.laneId)?.workspace?.dirtyHash!==currentDigest)throw Error(`BLOCKED: PR_FEEDBACK ${phase} artifact is not bound to the current revision digest`);return assertIndependentFeedbackGateSessions(directory,state,phase),state}function assertIndependentFeedbackGateSessions(directory,state,throughPhase){let throughIndex=PR_FEEDBACK_PHASE_ORDER.indexOf(throughPhase),batches=(state.prFeedbackGateBatches??[]).filter((batch)=>PR_FEEDBACK_PHASE_ORDER.indexOf(batch.phase)<=throughIndex),seenSessions=new Set;for(let batch of batches){let matching=findByBatchId(directory,batch.batchId,{parentSessionId:state.sessionID}).filter((record3)=>record3.laneId===batch.laneId);if(matching.length!==1)throw Error(`BLOCKED: PR_FEEDBACK ${batch.phase} must resolve from exactly one durable child session`);let record2=matching[0],expectedRole=PR_FEEDBACK_PHASE_ROLE[batch.phase];if(!(record2.normalizedAgent===expectedRole||expectedRole==="critic"&&record2.normalizedAgent.startsWith("critic_")))throw Error(`BLOCKED: PR_FEEDBACK ${batch.phase} requires role ${expectedRole}, received ${record2.normalizedAgent||"(unknown)"}`);if(seenSessions.has(record2.subagentSessionId))throw Error(`BLOCKED: PR_FEEDBACK independent phases reused child session "${record2.subagentSessionId}"`);seenSessions.add(record2.subagentSessionId)}}async function assertPrFeedbackReadyToPublish(directory,sessionID){let state=await assertPrFeedbackVerificationSettled(directory,sessionID);for(let phase of PR_FEEDBACK_PHASE_ORDER)state=await assertPrFeedbackGatePhaseSettled(directory,sessionID,phase);return state}async function assertPrFeedbackPublicationArmed(directory,sessionID){let state=await requireBoundState(directory,sessionID,"PR_FEEDBACK"),armed=state.prFeedbackReadyToPublish;if(!armed)throw Error("BLOCKED: PR_FEEDBACK publication is not armed; call complete_pr_workflow once after every ordered gate passes");let currentDigest=await currentPrFeedbackRevisionDigest(directory,state);if(armed.revisionDigest!==currentDigest)throw Error("BLOCKED: PR_FEEDBACK changed after publication was armed; rerun Stage A and every independent gate");if((await _test_exports.resolveCurrentGitHeadAsync(directory))?.trim()!==armed.localHead)throw Error("BLOCKED: PR_FEEDBACK current Git HEAD changed after publication was armed");if(await _test_exports.resolveIsWorkingTreeCleanAsync(directory)!==!0)throw Error("BLOCKED: PR_FEEDBACK working tree changed after publication was armed");let currentTarget=await _test_exports.resolveCurrentUpstreamPushTargetAsync(directory);if(!currentTarget||currentTarget.remoteName!==armed.remoteName||currentTarget.remoteBranchRef!==armed.remoteBranchRef||currentTarget.remoteTrackingRef!==armed.remoteRef)throw Error("BLOCKED: PR_FEEDBACK upstream publication target changed after publication was armed");return state}async function markPrReviewTriggerEvaluationComplete(directory,sessionID,artifactPath){let state=await assertPrReviewBaseCoverageSettled(directory,sessionID),normalizedPath=artifactPath.trim();if(!normalizedPath)throw Error("BLOCKED: PR_REVIEW trigger artifact path is required");let nextState={...state,updatedAt:isoNow(),prReviewTriggerEvalPath:normalizedPath};return await persistState(directory,nextState),nextState}async function bindPrReviewTriggerLedger(directory,sessionID,input){let ledger;try{ledger=validatePrReviewInlineTriggerLedger(input)}catch(error49){throw Error(`BLOCKED: invalid PR_REVIEW trigger_evaluation: ${error49 instanceof Error?error49.message:String(error49)}`)}let state=await assertPrReviewBaseCoverageSettled(directory,sessionID);if(state.prReviewTriggerLedger){let frozen;try{frozen=validatePrReviewInlineTriggerLedger(state.prReviewTriggerLedger)}catch(error49){throw Error(`BLOCKED: persisted PR_REVIEW trigger ledger is invalid: ${error49 instanceof Error?error49.message:String(error49)}`)}if(prReviewTriggerLedgerDigest(frozen.rows)!==prReviewTriggerLedgerDigest(ledger.rows))throw Error("BLOCKED: PR_REVIEW trigger_evaluation must remain exactly identical across every micro dispatch and the final receipt");return state}let nextState={...state,updatedAt:isoNow(),prReviewTriggerLedger:ledger.rows};return await persistState(directory,nextState),nextState}async function assertPrReviewArtifactBoundary(directory,sessionID,runId,boundary,findingIds){let state=await requireBoundState(directory,sessionID,"PR_REVIEW");if(!state.prReviewTriggerEvalPath)throw Error("BLOCKED: PR_REVIEW findings persistence requires the trigger evaluation artifact");let persistedBoundaries=state.prReviewArtifactBoundaries??[],boundaryOrder=["post_explorer","post_reviewer","post_critic"],boundaryIndex=boundaryOrder.indexOf(boundary),requiredPriorBoundary=boundaryOrder[boundaryIndex-1];if(requiredPriorBoundary&&!persistedBoundaries.includes(requiredPriorBoundary))throw Error(`BLOCKED: PR_REVIEW ${boundary} findings require the prior ${requiredPriorBoundary} checkpoint`);if(persistedBoundaries.some((persisted)=>boundaryOrder.indexOf(persisted)>boundaryIndex))throw Error(`BLOCKED: PR_REVIEW ${boundary} findings cannot be persisted after a later checkpoint`);if(boundary==="post_reviewer")state=await assertPrReviewValidationSettled(directory,sessionID,"reviewer");else if(boundary==="post_critic"){if(await assertPrReviewValidationSettled(directory,sessionID,"reviewer"),derivePrReviewCriticInventory(directory,state).length>0)state=await assertPrReviewValidationSettled(directory,sessionID,"critic")}if(state.prReviewArtifactRunId&&state.prReviewArtifactRunId!==runId)throw Error(`BLOCKED: PR_REVIEW artifacts are already bound to run "${state.prReviewArtifactRunId}"`);let expectedFindingIds=derivePrReviewCandidateInventory(directory,state),normalizedFindingIds=[...new Set(findingIds)].sort();if(normalizedFindingIds.length!==findingIds.length||JSON.stringify(normalizedFindingIds)!==JSON.stringify([...expectedFindingIds].sort()))throw Error(`BLOCKED: PR_REVIEW ${boundary} findings must exactly cover the discovered candidate inventory`);return state}async function assertPrReviewArtifactRecordsMatchAuthoritativeVerdicts(directory,sessionID,boundary,records){let state=await requireBoundState(directory,sessionID,"PR_REVIEW");if(boundary==="post_explorer"){for(let record2 of records)if(record2.status!=="PENDING"||record2.next_action!=="route_to_reviewer")throw Error(`BLOCKED: PR_REVIEW post_explorer record ${record2.finding_id} must remain PENDING and route_to_reviewer`);return}let reviewerVerdicts=deriveLatestPrReviewReviewerVerdicts(directory,state),criticVerdicts=boundary==="post_critic"?deriveLatestPrReviewCriticVerdicts(directory,state):void 0;for(let record2 of records){let reviewer=reviewerVerdicts.get(record2.finding_id);if(!reviewer)throw Error(`BLOCKED: PR_REVIEW ${boundary} record ${record2.finding_id} has no authoritative reviewer verdict`);if(record2.severity&&record2.severity!==reviewer.severity)throw Error(`BLOCKED: PR_REVIEW ${boundary} record ${record2.finding_id} severity differs from its reviewer verdict`);let requiresCritic=reviewer.classification==="CONFIRMED"&&["CRITICAL","HIGH","MEDIUM"].includes(reviewer.severity);if(boundary==="post_reviewer"){let expectedStatus=reviewer.classification==="UNVERIFIED"?"PENDING":reviewer.classification;if(record2.status!==expectedStatus)throw Error(`BLOCKED: PR_REVIEW post_reviewer record ${record2.finding_id} status differs from its reviewer verdict`);let expectedAction=requiresCritic?"route_to_critic":reviewer.classification==="CONFIRMED"||reviewer.classification==="PRE_EXISTING"?"report":reviewer.classification==="DISPROVED"?"suppress_with_reason":"route_to_reviewer";if(record2.next_action!==expectedAction)throw Error(`BLOCKED: PR_REVIEW post_reviewer record ${record2.finding_id} action does not match reviewer disposition`);continue}if(!requiresCritic){let expectedStatus=reviewer.classification==="UNVERIFIED"?"PENDING":reviewer.classification,expectedAction=reviewer.classification==="CONFIRMED"||reviewer.classification==="PRE_EXISTING"?"report":reviewer.classification==="DISPROVED"?"suppress_with_reason":"route_to_reviewer";if(record2.status!==expectedStatus||record2.next_action!==expectedAction)throw Error(`BLOCKED: PR_REVIEW post_critic record ${record2.finding_id} cannot override its non-critic reviewer disposition`);continue}let critic=criticVerdicts?.get(record2.finding_id);if(!critic)throw Error(`BLOCKED: PR_REVIEW post_critic record ${record2.finding_id} has no authoritative critic verdict`);if(record2.severity&&record2.severity!==critic.severity)throw Error(`BLOCKED: PR_REVIEW post_critic record ${record2.finding_id} severity differs from its critic verdict`);if(critic.status==="DISPROVED"){if(record2.status!=="DISPROVED"||record2.next_action!=="suppress_with_reason")throw Error(`BLOCKED: PR_REVIEW post_critic record ${record2.finding_id} must preserve the critic DISPROVED disposition`)}else if(record2.status!=="CONFIRMED"||!["report","handoff_to_feedback"].includes(record2.next_action))throw Error(`BLOCKED: PR_REVIEW post_critic record ${record2.finding_id} action does not match its critic verdict`)}}async function markPrReviewArtifactBoundary(directory,sessionID,runId,boundary,artifactPath,findingIds,handoffRequired){let state=await assertPrReviewArtifactBoundary(directory,sessionID,runId,boundary,findingIds),boundaries=new Set(state.prReviewArtifactBoundaries??[]);boundaries.add(boundary);let nextState={...state,updatedAt:isoNow(),prReviewArtifactRunId:runId,prReviewFindingsPath:artifactPath,prReviewArtifactBoundaries:[...boundaries],prReviewHandoffRequired:handoffRequired};return await persistState(directory,nextState),nextState}async function markPrReviewHandoffComplete(directory,sessionID,runId,artifactPath){let state=await requireBoundState(directory,sessionID,"PR_REVIEW");if(state.prReviewArtifactRunId!==runId||!(state.prReviewArtifactBoundaries??[]).includes("post_critic"))throw Error("BLOCKED: PR_REVIEW handoff requires the final findings boundary for the same run");let nextState={...state,updatedAt:isoNow(),prReviewHandoffPath:artifactPath};return await persistState(directory,nextState),nextState}function normalizePrReviewFeedbackHandoffPath(handoffPath){let normalized=handoffPath.trim().replace(/\\/g,"/"),relative4=normalized.startsWith(".swarm/")?normalized.slice(7):normalized,matched=relative4.match(PR_REVIEW_HANDOFF_RELATIVE_PATH_PATTERN);if(!matched)return null;return{runId:matched[1],relativePath:relative4}}async function readBoundedSwarmRegularFile(directory,relativePath,maxBytes,label){let absPath=validateSwarmPath(directory,relativePath),swarmRoot=path14.resolve(directory,".swarm"),rootStat,artifactStat;try{rootStat=await fsp3.lstat(swarmRoot,{bigint:!0}),artifactStat=await fsp3.lstat(absPath,{bigint:!0})}catch(error49){if(error49.code==="ENOENT")throw Error(`BLOCKED: ${label} "${relativePath}" does not exist`);throw error49}if(rootStat.isSymbolicLink()||!rootStat.isDirectory())throw Error(`BLOCKED: ${label} root must be a real project .swarm directory`);if(artifactStat.isSymbolicLink()||!artifactStat.isFile())throw Error(`BLOCKED: ${label} must be a bounded regular file`);if(artifactStat.size>BigInt(maxBytes))throw Error(`BLOCKED: ${label} exceeds ${maxBytes} bytes`);let[realRoot,realArtifact]=await Promise.all([fsp3.realpath(swarmRoot),fsp3.realpath(absPath)]),relativeRealPath=path14.relative(realRoot,realArtifact);if(relativeRealPath===""||relativeRealPath===".."||relativeRealPath.startsWith(`..${path14.sep}`)||path14.isAbsolute(relativeRealPath))throw Error(`BLOCKED: ${label} escapes the project .swarm directory`);await _test_exports.beforeBoundedSwarmFileOpen?.();let handle=await fsp3.open(realArtifact,"r");try{let openedStat=await handle.stat({bigint:!0});if(!openedStat.isFile()||openedStat.size>BigInt(maxBytes)||!sameBigIntFileIdentity(artifactStat,openedStat))throw Error(`BLOCKED: ${label} changed during its bounded read`);let[postRootStat,postArtifactStat,postRealRoot,postRealArtifact]=await Promise.all([fsp3.lstat(swarmRoot,{bigint:!0}),fsp3.lstat(absPath,{bigint:!0}),fsp3.realpath(swarmRoot),fsp3.realpath(absPath)]),postRelativeRealPath=path14.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(`..${path14.sep}`)||path14.isAbsolute(postRelativeRealPath))throw Error(`BLOCKED: ${label} changed or escaped during its bounded read`);let buffer=Buffer.allocUnsafe(maxBytes+1),{bytesRead}=await handle.read(buffer,0,maxBytes+1,0);if(bytesRead>maxBytes)throw Error(`BLOCKED: ${label} exceeds ${maxBytes} bytes`);return buffer.subarray(0,bytesRead).toString("utf8")}finally{await handle.close()}}function sameBigIntFileIdentity(left,right){return left.dev===right.dev&&left.ino===right.ino}function normalizeComparableFsPath(value){let normalized=path14.normalize(path14.resolve(value));return process.platform==="win32"?normalized.toLowerCase():normalized}async function readPrReviewFeedbackHandoffArtifact(directory,relativePath){let raw=await readBoundedSwarmRegularFile(directory,relativePath,PR_REVIEW_HANDOFF_MAX_BYTES,"PR_REVIEW feedback handoff artifact"),parsedJson;try{parsedJson=JSON.parse(raw)}catch{throw Error("BLOCKED: PR_REVIEW feedback handoff artifact is not valid JSON")}let parsed=PrReviewFeedbackHandoffArtifactSchema.safeParse(parsedJson);if(!parsed.success)throw Error("BLOCKED: PR_REVIEW feedback handoff artifact is invalid");if(new Set(parsed.data.finding_ids).size!==parsed.data.finding_ids.length)throw Error("BLOCKED: PR_REVIEW feedback handoff artifact contains duplicate finding IDs");return{artifact:parsed.data,digest:createHash7("sha256").update(raw,"utf8").digest("hex")}}async function readActionableReviewFindingIds(directory,state,runId){let expectedPath=`pr-review/${runId}/findings.jsonl`;if(state.prReviewFindingsPath!==expectedPath)throw Error(`BLOCKED: PR_REVIEW transition requires the exact final findings artifact "${expectedPath}"`);let raw=await readBoundedSwarmRegularFile(directory,expectedPath,PR_REVIEW_FINDINGS_MAX_BYTES,"PR_REVIEW final findings artifact"),latest=new Map;for(let[index,line]of raw.split(/\r?\n/).entries()){if(!line.trim())continue;let value;try{value=JSON.parse(line)}catch{throw Error(`BLOCKED: PR_REVIEW final findings artifact contains invalid JSON at line ${index+1}`)}let parsed=PrReviewFindingProjectionSchema.safeParse(value);if(!parsed.success)throw Error(`BLOCKED: PR_REVIEW final findings artifact contains an invalid record at line ${index+1}`);latest.set(parsed.data.finding_id,parsed.data)}return[...latest.values()].filter((record2)=>record2.status==="CONFIRMED"&&record2.next_action==="handoff_to_feedback").map((record2)=>record2.finding_id).sort()}function canonicalGitHubPrUrl(value){try{let url2=new URL(value);if(url2.protocol!=="https:"||url2.hostname.toLowerCase()!=="github.com")return null;let matched=url2.pathname.match(/^\/([^/]+)\/([^/]+)\/pull\/(\d+)\/?$/);if(!matched)return null;let prNumber=Number(matched[3]);if(!Number.isSafeInteger(prNumber)||prNumber<=0)return null;return`github.com/${matched[1].toLowerCase()}/${matched[2].toLowerCase()}/pull/${prNumber}`}catch{return null}}function workflowIdentity(state){return state.workflowInstanceId??`legacy-${createHash7("sha256").update(`${state.sessionID}\x00${state.mode}\x00${state.activatedAt}`).digest("hex").slice(0,32)}`}function sameHandoffIds(left,right){let normalizedLeft=[...new Set(left)].sort(),normalizedRight=[...new Set(right)].sort();return sameStringArray(normalizedLeft,normalizedRight)}function assertSamePrFeedbackHandoff(state,relativePath,read,requestedPrUrl){let existing=state.prFeedbackReviewHandoff;if(!existing)throw Error(`BLOCKED: session "${state.sessionID}" is already active in PR_FEEDBACK without persisted review handoff provenance`);let artifactPr=canonicalGitHubPrUrl(read.artifact.pr_url),requestedPr=requestedPrUrl?canonicalGitHubPrUrl(requestedPrUrl):artifactPr;if(!artifactPr||requestedPrUrl&&requestedPr!==artifactPr||existing.path!==relativePath||existing.runId!==read.artifact.run_id||existing.digest!==read.digest||existing.sourcePrHeadSha.toLowerCase()!==read.artifact.pr_head_sha.toLowerCase()||canonicalGitHubPrUrl(existing.prUrl)!==artifactPr||!sameHandoffIds(existing.findingIds,read.artifact.finding_ids))throw Error(`BLOCKED: session "${state.sessionID}" is already active in PR_FEEDBACK for a different handoff or PR`)}async function assertPrReviewTerminalReady(directory,sessionID){let state=await requireBoundState(directory,sessionID,"PR_REVIEW");await assertPrReviewCleanCheckout(directory,"PR_REVIEW");let open3=readDelegations(directory).filter((record2)=>record2.parentSessionId===state.sessionID&&record2.mode?.startsWith("swarm-pr-")&&(record2.status==="pending"||record2.status==="running"));if(open3.length>0)throw Error(`BLOCKED: PR_REVIEW transition has ${open3.length} unsettled PR workflow lane(s)`);if(await assertPrReviewBaseCoverageSettled(directory,sessionID),!state.prReviewTriggerEvalPath)throw Error("BLOCKED: PR_REVIEW transition requires a persisted trigger evaluation artifact");if((state.prReviewValidationBatches??[]).some((batch)=>batch.phase==="council"))await assertPrReviewValidationSettled(directory,sessionID,"council");await assertPrReviewValidationSettled(directory,sessionID,"reviewer");let criticInventory=derivePrReviewCriticInventory(directory,state);if(criticInventory.length>0){if(!(state.prReviewValidationBatches??[]).some((batch)=>batch.phase==="critic"))throw Error(`BLOCKED: PR_REVIEW reviewer verdicts require critic coverage for: ${criticInventory.join(", ")}`);await assertPrReviewValidationSettled(directory,sessionID,"critic")}let requiredBoundaries=["post_explorer","post_reviewer","post_critic"],persistedBoundaries=new Set(state.prReviewArtifactBoundaries??[]),missing=requiredBoundaries.filter((boundary)=>!persistedBoundaries.has(boundary));if(!state.prReviewFindingsPath||missing.length>0)throw Error(`BLOCKED: PR_REVIEW transition requires durable findings checkpoints; missing: ${missing.join(", ")||"findings path"}`);if(state.prReviewHandoffRequired&&!state.prReviewHandoffPath)throw Error("BLOCKED: PR_REVIEW actionable findings require a persisted feedback handoff artifact");return state}async function transitionPrReviewToFeedback(directory,sessionID,request){let normalizedSessionID=normalizeSessionID(sessionID),normalizedHandoff=normalizePrReviewFeedbackHandoffPath(request.handoffPath);if(!normalizedHandoff||normalizedHandoff.runId!==request.runId)throw Error("BLOCKED: PR-feedback continuation must use .swarm/pr-review/<run_id>/feedback-handoff.json");let preliminaryRead=await readPrReviewFeedbackHandoffArtifact(directory,normalizedHandoff.relativePath),artifact=preliminaryRead.artifact,artifactPr=canonicalGitHubPrUrl(artifact.pr_url),requestedPr=request.prUrl?canonicalGitHubPrUrl(request.prUrl):null;if(!artifactPr||request.prUrl&&requestedPr!==artifactPr)throw Error("BLOCKED: PR_REVIEW feedback handoff artifact does not match the requested GitHub PR URL");if(artifact.run_id!==request.runId)throw Error("BLOCKED: PR_REVIEW feedback handoff artifact does not match the requested review run");let preliminary=await readPrWorkflowGateState(directory,normalizedSessionID);if(preliminary?.mode==="PR_FEEDBACK")return assertSamePrFeedbackHandoff(preliminary,normalizedHandoff.relativePath,preliminaryRead,request.prUrl),preliminary;let sourceIdentity,sourceRevision=0,provenance;if(preliminary){if(preliminary.mode!=="PR_REVIEW")throw wrongModeError(preliminary,"PR_REVIEW");let ready=await assertPrReviewTerminalReady(directory,normalizedSessionID);if(workflowIdentity(ready)!==workflowIdentity(preliminary)||ready.revision!==preliminary.revision||ready.mode!=="PR_REVIEW"||ready.prReviewHandoffPath!==normalizedHandoff.relativePath||ready.prReviewArtifactRunId!==request.runId||!ready.prHeadSha||ready.prHeadSha.toLowerCase()!==artifact.pr_head_sha.toLowerCase()||canonicalGitHubPrUrl(artifact.pr_url)!==canonicalGitHubPrUrl(request.prUrl??artifact.pr_url))throw Error("BLOCKED: PR_REVIEW feedback handoff does not match the terminal active review state");let actionableIds=await readActionableReviewFindingIds(directory,ready,request.runId);if(!sameHandoffIds(actionableIds,artifact.finding_ids))throw Error("BLOCKED: PR_REVIEW feedback handoff finding IDs do not match the authoritative final findings ledger");sourceIdentity=workflowIdentity(ready),sourceRevision=ready.revision,provenance="active-review-v1"}else{if(!request.prUrl)throw Error("BLOCKED: continuing a completed PR_REVIEW requires an explicit GitHub PR URL");sourceIdentity=`external-${preliminaryRead.digest.slice(0,32)}`,provenance="external-v1"}return await _test_exports.beforePrFeedbackTransitionLock?.(),withSessionStateMutation(directory,normalizedSessionID,async()=>{let current=await readPrWorkflowGateStateFromDisk(directory,normalizedSessionID);if(current?.mode==="PR_FEEDBACK")return assertSamePrFeedbackHandoff(current,normalizedHandoff.relativePath,preliminaryRead,request.prUrl),current;if(provenance==="active-review-v1"){if(!current||current.mode!=="PR_REVIEW"||workflowIdentity(current)!==sourceIdentity||current.revision!==sourceRevision||current.prHeadSha?.toLowerCase()!==artifact.pr_head_sha.toLowerCase()||current.prReviewArtifactRunId!==request.runId||current.prReviewHandoffPath!==normalizedHandoff.relativePath)throw Error("BLOCKED: PR_REVIEW state changed while validating the feedback handoff; retry from current state")}else if(current)throw Error("BLOCKED: another PR workflow became active while validating the external handoff");let lockedRead=await readPrReviewFeedbackHandoffArtifact(directory,normalizedHandoff.relativePath);if(lockedRead.digest!==preliminaryRead.digest)throw Error("BLOCKED: PR_REVIEW feedback handoff artifact changed during transition");if(artifactPr!==canonicalGitHubPrUrl(lockedRead.artifact.pr_url)||lockedRead.artifact.run_id!==request.runId||lockedRead.artifact.pr_head_sha.toLowerCase()!==artifact.pr_head_sha.toLowerCase()||!sameHandoffIds(lockedRead.artifact.finding_ids,artifact.finding_ids))throw Error("BLOCKED: PR_REVIEW feedback handoff artifact changed during transition");let timestamp=isoNow(),nextState={schemaVersion:GATE_SCHEMA_VERSION,revision:sourceRevision,workflowInstanceId:randomUUID2(),sessionID:normalizedSessionID,mode:"PR_FEEDBACK",activatedAt:timestamp,updatedAt:timestamp,prFeedbackReviewHandoff:{path:normalizedHandoff.relativePath,runId:lockedRead.artifact.run_id,sourcePrHeadSha:lockedRead.artifact.pr_head_sha.toLowerCase(),prUrl:lockedRead.artifact.pr_url,findingIds:[...new Set(lockedRead.artifact.finding_ids)].sort(),digest:preliminaryRead.digest,sourceWorkflowInstanceId:sourceIdentity,provenance},prFeedbackTargetUrl:artifact.pr_url};return writeStateWhileLocked(directory,nextState,{replaceWorkflowInstanceId:provenance==="active-review-v1"?current?.workflowInstanceId:void 0})})}async function declarePrFeedbackScope(directory,sessionID,taskId,files){let state=await assertPrFeedbackVerificationSettled(directory,sessionID),revisionDigest=await currentPrFeedbackRevisionDigest(directory,state),previous=state.prFeedbackScopes??[];if(previous.find((entry)=>entry.taskId===taskId)?.consumedByCallId)throw Error(`SCOPE_NOT_DECLARED: PR-feedback scope ${taskId} was already consumed; use a fresh task_id for any retry`);let record2={taskId,files,revisionDigest,declaredAt:isoNow()},nextState={...state,updatedAt:isoNow(),prFeedbackScopes:[...previous.filter((entry)=>entry.taskId!==taskId),record2]};return await persistState(directory,nextState),nextState}async function resolvePrFeedbackScopeDeclaration(directory,sessionID,taskId){let state=await readPrWorkflowGateState(directory,sessionID);if(state?.mode!=="PR_FEEDBACK")return null;let declaration=(state.prFeedbackScopes??[]).find((entry)=>entry.taskId===taskId);if(!declaration)return null;return await assertPrFeedbackVerificationSettled(directory,sessionID),await currentPrFeedbackRevisionDigest(directory,state)===declaration.revisionDigest?declaration:null}async function consumePrFeedbackScopeDeclaration(directory,sessionID,taskId,callID){let declaration=await resolvePrFeedbackScopeDeclaration(directory,sessionID,taskId);if(!declaration)return null;if(declaration.consumedByCallId&&declaration.consumedByCallId!==callID)throw Error(`SCOPE_NOT_DECLARED: PR-feedback scope ${taskId} was already consumed by another Task call`);if(declaration.consumedByCallId===callID)return declaration;let state=await requireBoundState(directory,sessionID,"PR_FEEDBACK"),nextState={...state,updatedAt:isoNow(),prFeedbackScopes:(state.prFeedbackScopes??[]).map((entry)=>entry.taskId===taskId?{...entry,consumedByCallId:callID}:entry)};return await persistState(directory,nextState),{...declaration,consumedByCallId:callID}}async function validatePrFeedbackScopeBinding(directory,binding){if(!binding.workflowSessionId||!binding.workflowRevisionDigest)return!1;let declaration=await resolvePrFeedbackScopeDeclaration(directory,binding.workflowSessionId,binding.taskId);return Boolean(declaration&&declaration.consumedByCallId===binding.dispatchCallId&&declaration.revisionDigest===binding.workflowRevisionDigest&&JSON.stringify(declaration.files)===JSON.stringify(binding.files))}async function enforcePrWorkflowToolBefore(directory,sessionID,toolName,args2,generatedAgentNames=[]){let state=await readPrWorkflowGateState(directory,sessionID);if(!state)return;let normalizedTool=toolName.toLowerCase(),isDirectAgentTask=normalizedTool==="task"||normalizedTool==="run_agent",requestedRoles=["subagent_type","agent"].filter((field)=>Object.hasOwn(args2??{},field)).map((field)=>{let value=args2?.[field];if(typeof value!=="string"||!value.trim())return"";return resolveGeneratedAgentRole(value.trim(),generatedAgentNames)}),isDirectWrite=WRITE_TOOL_NAMES.includes(normalizedTool),command=typeof args2?.command==="string"?args2.command.trim():"",serializedArgs=JSON.stringify(args2??{}),referencesProtectedWorkflowEvidence=containsProtectedWorkflowPath(command||serializedArgs),isInternalWorkflowTool=isPrWorkflowControllerTool(state.mode,normalizedTool),isShellTool=normalizedTool==="bash"||normalizedTool==="shell",isReadOnlyShell=!1,shellPermissionEnvelope=null;if(isShellTool&&command.length>0){let trackingFetchTarget=state.prHeadSha?await _test_exports.resolveCurrentUpstreamPushTargetAsync(directory):null;shellPermissionEnvelope={allowCheckout:!state.prHeadSha,allowFetch:!state.prHeadSha,allowTrackingFetch:Boolean(state.prHeadSha),trackingFetchTarget},isReadOnlyShell=isAllowedPrWorkflowReadOnlyShell(command,shellPermissionEnvelope)}let trustedCapability=getPrWorkflowToolCapability(normalizedTool,state.mode),isNamedReadOnlyTool=trustedCapability!==null&&isTrustedPrWorkflowToolInvocationSafe(normalizedTool,args2??{})||normalizedTool!=="build_check"&&isAllowedPrReviewReadOnlyToolName(normalizedTool)&&readOnlyToolArgumentsAreSafe(args2??{}),isRecoverySafeEvidenceTool=trustedCapability==="observe"&&isTrustedPrWorkflowToolInvocationSafe(normalizedTool,args2??{})||normalizedTool!=="build_check"&&isAllowedPrReviewReadOnlyToolName(normalizedTool)&&readOnlyToolArgumentsAreSafe(args2??{});if(state.checkoutRecovery){if(isRecoverySafeEvidenceTool||isReadOnlyShell||normalizedTool==="abort_pr_workflow"||normalizedTool==="pr_workflow_status"||normalizedTool==="prepare_pr_workflow_checkout")return;throw Error(`BLOCKED: ${state.mode} requires manual Git recovery before controller work can continue. code=${state.checkoutRecovery.code} retryable=false required_action=${state.checkoutRecovery.requiredAction}`)}if(referencesProtectedWorkflowEvidence&&!isInternalWorkflowTool&&!isNamedReadOnlyTool&&!isReadOnlyShell)throw Error(`BLOCKED: active ${state.mode} workflow evidence under .swarm is controller-owned and cannot be modified directly`);let isShellCommandRequiringVerification=isShellTool&&command.length>0&&!isReadOnlyShell,isRemoteReviewTool=/(?:git|github|pull|(?:^|[_-])pr(?:[_-]|$)|issue|review)/i.test(normalizedTool),hasRemoteMutationVerb=/(?:^|[_-])(?:add|approve|cancel|close|comment|commit|convert|create|delete|dismiss|edit|mark|merge|push|ready|reopen|rerun|resolve|submit|transfer|unresolve|update)(?:[_-]|$)/i.test(normalizedTool),hasRemoteReadVerb=/(?:^|[_-])(?:github|git)[_-]+(?:check|checks|checkout|diff|fetch|get|inspect|list|read|search|status|view)(?:[_-]|$)/i.test(normalizedTool)||/(?:^|[_-])(?:github|git)[_-]+(?:pull[_-]+request|pr|issue|review[_-]+thread)[_-]+(?:check|checks|checkout|diff|fetch|get|inspect|list|read|search|status|view)(?:[_-]|$)/i.test(normalizedTool),isRemoteMutationTool=isRemoteReviewTool&&(hasRemoteMutationVerb||!hasRemoteReadVerb),isRemoteCheckoutTool=/(?:^|[_-])(?:github|git)[_-]+checkout(?:[_-]|$)/i.test(normalizedTool),isShellCheckout=(normalizedTool==="bash"||normalizedTool==="shell")&&(/\bgit\b(?:(?![;&|]).){0,200}\b(?:checkout|switch)\b/i.test(command)||/\bgh\s+pr\s+checkout\b/i.test(command)),stderrMergeNormalizedCommand=command.replace(PR_WORKFLOW_TRAILING_STDERR_MERGE_PATTERN,"").trim(),isCanonicalReviewCheckout=/^git\s+switch\s+--detach\s+[0-9a-f]{40,64}$/i.test(stderrMergeNormalizedCommand),detachedFeedbackSwitchMatch=command.match(/^git\s+switch\s+--detach\s+(\S+)$/i),isDetachedFeedbackCheckout=Boolean(detachedFeedbackSwitchMatch?.[1]&&isSafeGitRefToken(detachedFeedbackSwitchMatch[1]))||/^gh\s+pr\s+checkout\b.*\s--detach(?:\s|$)/i.test(command),containsGitCommitShell=isShellCommandRequiringVerification&&/\bgit\b(?:(?![;&|]).){0,200}\bcommit\b/i.test(command),isStandaloneGitCommitShell=containsGitCommitShell&&isSafeStandaloneGitCommit(command),isPublicationShell=isShellCommandRequiringVerification&&(/\bgit\b(?:(?![;&|]).){0,200}\bpush\b/i.test(command)||/\bgh\s+(?:api|pr|issue|run)\b/i.test(command)),isPublicationTool=!isInternalWorkflowTool&&isRemoteMutationTool,isCoderTask=isDirectAgentTask&&requestedRoles.length>0&&requestedRoles.every((role)=>role==="coder"),blockedShellDiagnosis=isShellTool&&command&&!isReadOnlyShell&&shellPermissionEnvelope?` ${describeBlockedPrReviewShellCommand(command,shellPermissionEnvelope)}`:"";if(state.mode==="PR_REVIEW"){if(!(isInternalWorkflowTool||isNamedReadOnlyTool||isReadOnlyShell&&(!isShellCheckout||isCanonicalReviewCheckout))||Boolean(state.prHeadSha)&&(isRemoteCheckoutTool||isShellCheckout)){if(!state.prHeadSha&&isShellCheckout)throw Error("BLOCKED: PR_REVIEW checkout must use standalone commands: fetch the PR head, verify the full commit object with `git cat-file -e <full_pr_head_sha>^{commit}`, then run `git switch --detach <full_pr_head_sha>` and bind that exact head before dispatching explorer lanes. Do not use `--track FETCH_HEAD`."+blockedShellDiagnosis);throw Error("BLOCKED: PR_REVIEW is read-only and fail-closed; only controller tools and positively classified observation tools are allowed, and every agent lane requires structured dispatch_lanes_async"+describePrWorkflowControllerToolNames(state.mode)+blockedShellDiagnosis)}return}if(isDirectAgentTask&&!isCoderTask)throw Error("BLOCKED: PR_FEEDBACK reviewer, test, critic, explorer, and unknown agent lanes require structured dispatch_lanes_async provenance");if(!isInternalWorkflowTool&&!isDirectAgentTask&&!isDirectWrite&&!isShellTool&&!isNamedReadOnlyTool)throw Error("BLOCKED: PR_FEEDBACK rejects unclassified plugin/MCP tools; use positively classified observation tools, built-in structured write tools after verification, or the workflow controller"+describePrWorkflowControllerToolNames(state.mode));if(state.prHeadSha&&(isShellCheckout||isRemoteCheckoutTool))throw Error("BLOCKED: PR_FEEDBACK checkout is immutable after exact PR head binding");if(containsGitCommitShell&&state.prFeedbackReadyToPublish)throw Error("BLOCKED: PR_FEEDBACK is armed for publication; the approved commit is immutable");if((containsGitCommitShell||isPublicationShell)&&hasUnsafeShellControlSyntax(command))throw Error("BLOCKED: PR_FEEDBACK publication commands must be standalone shell commands without control, redirection, or command-substitution syntax");if(containsGitCommitShell&&!isStandaloneGitCommitShell)throw Error("BLOCKED: PR_FEEDBACK commit must use a standalone git commit command after every ordered local gate passes");if(state.prFeedbackReadyToPublish){if(normalizedTool==="complete_pr_workflow")return;if(isNamedReadOnlyTool)return;if((normalizedTool==="bash"||normalizedTool==="shell")&&command.length>0&&isAllowedPrWorkflowReadOnlyShell(command,{allowCheckout:!1,allowFetch:!1,allowTrackingFetch:!1}))return;if(normalizedTool==="bash"||normalizedTool==="shell"){let armed=(await assertPrFeedbackPublicationArmed(directory,sessionID)).prFeedbackReadyToPublish;if(isSafeExactBoundPush(command,armed))return;throw Error(`BLOCKED: PR_FEEDBACK is armed for publication; only the exact approved push is allowed: ${expectedBoundPushCommand(armed)}`)}throw Error("BLOCKED: PR_FEEDBACK is armed for publication; only read-only inspection, the exact approved push, and complete_pr_workflow are allowed")}if(!state.prHeadSha&&normalizedTool==="prepare_pr_workflow_checkout")return;if(!state.prHeadSha&&isDetachedFeedbackCheckout&&!isCanonicalReviewCheckout)throw Error("BLOCKED: PR_FEEDBACK checkout should use one exact local tracking branch, such as `gh pr checkout <number> --branch <local_branch>` or `git switch -c <local_branch> --track <remote>/<branch>`, before binding. If checkout is already detached at the authoritative full PR head SHA, bind it directly; the controller attaches one unambiguous exact tracking ref. Other detached refs are not accepted");if(!state.prHeadSha&&isCanonicalReviewCheckout)return;if(isStandaloneGitCommitShell){await assertPrFeedbackReadyToPublish(directory,sessionID);return}if(isPublicationShell||isPublicationTool)throw Error("BLOCKED: PR_FEEDBACK publication is not armed; finish every ordered gate, create the one approved commit, and call complete_pr_workflow before publishing");if(isShellCommandRequiringVerification){if(!state.prHeadSha&&isShellCheckout)throw Error("BLOCKED: PR_FEEDBACK checkout should use one exact local tracking branch, such as `gh pr checkout <number> --branch <local_branch>` or `git switch -c <local_branch> --track <remote>/<branch>`, before binding. If checkout is already detached at the authoritative full PR head SHA, bind it directly; the controller attaches one unambiguous exact tracking ref");throw Error("BLOCKED: PR_FEEDBACK shell commands fail closed unless they are explicit read-only intake or the one standalone approved git commit; use structured coder/write tools for fixes and run_pr_feedback_stage_a for validation")}if(!isDirectWrite&&!isShellCommandRequiringVerification&&!isRemoteMutationTool&&!isCoderTask&&normalizedTool!=="prepare_pr_feedback_scope")return;if(normalizedTool==="abort_pr_workflow")return;await assertPrFeedbackVerificationSettled(directory,sessionID)}async function completePrWorkflow(directory,sessionID,expectedMode,prHeadSha){let state=await requireBoundState(directory,sessionID,expectedMode),normalizedHead=normalizePrHeadSha(prHeadSha);if(state.prHeadSha!==normalizedHead)throw Error(`BLOCKED: cannot complete ${expectedMode} at PR head "${normalizedHead}"; workflow is bound to "${state.prHeadSha}"`);let open3=readDelegations(directory).filter((record2)=>record2.parentSessionId===state.sessionID&&record2.mode?.startsWith("swarm-pr-")&&(record2.status==="pending"||record2.status==="running"));if(open3.length>0)throw Error(`BLOCKED: ${expectedMode} completion has ${open3.length} unsettled PR workflow lane(s)`);if(expectedMode==="PR_REVIEW"){let readyState=await assertPrReviewTerminalReady(directory,sessionID);if(workflowIdentity(readyState)!==workflowIdentity(state)||readyState.revision!==state.revision)throw Error("BLOCKED: PR_REVIEW state changed while checking terminal readiness; retry from current state")}else{let readyState=await assertPrFeedbackReadyToPublish(directory,sessionID),currentDigest=await currentPrFeedbackRevisionDigest(directory,readyState),armed=readyState.prFeedbackReadyToPublish;if(!armed){let localHead=(await _test_exports.resolveCurrentGitHeadAsync(directory))?.trim();if(!localHead)throw Error("BLOCKED: PR_FEEDBACK cannot arm publication without a verified local Git HEAD");if(await _test_exports.resolveCommitCountSinceAsync(directory,state.prHeadSha,localHead)!==1)throw Error("BLOCKED: PR_FEEDBACK publication requires exactly one descendant commit after the immutable intake head");if(await _test_exports.resolveIsExactSingleChildCommitAsync(directory,state.prHeadSha,localHead)!==!0)throw Error("BLOCKED: PR_FEEDBACK publication commit must be a non-merge direct child of the immutable intake head");if(await _test_exports.resolveIsWorkingTreeCleanAsync(directory)!==!0)throw Error("BLOCKED: PR_FEEDBACK publication requires a clean index and working tree so all approved content is captured by the bound commit");let upstreamTarget=await _test_exports.resolveCurrentUpstreamPushTargetAsync(directory);if(!upstreamTarget)throw Error("BLOCKED: PR_FEEDBACK cannot arm publication without a current branch bound to an exact remote name, remote branch ref, and remote-tracking ref");return await persistState(directory,{...readyState,updatedAt:isoNow(),prFeedbackReadyToPublish:{revisionDigest:currentDigest,localHead,remoteName:upstreamTarget.remoteName,remoteBranchRef:upstreamTarget.remoteBranchRef,remoteRef:upstreamTarget.remoteTrackingRef,validatedAt:isoNow()}}),"ready-to-publish"}if(armed.revisionDigest!==currentDigest)throw Error("BLOCKED: PR_FEEDBACK publication revision differs from the independently approved content digest");let publishedHead=(await _test_exports.resolveCurrentGitHeadAsync(directory))?.trim(),remoteRefs=publishedHead?await _test_exports.resolveRemoteRefsContainingHeadAsync(directory,publishedHead):null,remoteHead=await _test_exports.resolveExactRemoteBranchHeadAsync(directory,armed.remoteName,armed.remoteBranchRef);if(!publishedHead||publishedHead!==armed.localHead||!remoteRefs?.includes(armed.remoteRef)||remoteHead?.toLowerCase()!==armed.localHead.toLowerCase())throw Error(`BLOCKED: PR_FEEDBACK completion requires approved commit ${armed.localHead} at current Git HEAD and intended remote-tracking ref ${armed.remoteRef} at that exact commit`)}return await _test_exports.beforeTerminalClear?.(),await clearPrWorkflowGateState(directory,sessionID,state.revision),"completed"}async function requireAnyActiveState(directory,sessionID){let state=await readPrWorkflowGateState(directory,sessionID);if(!state)throw Error(`BLOCKED: no active PR workflow gate for session "${normalizeSessionID(sessionID)}". The gate is activated by running \`/swarm pr-review <pr-ref>\` (PR_REVIEW) or \`/swarm pr-feedback <pr-ref>\` (PR_FEEDBACK), or by the first dispatch_lanes_async call with mode "swarm-pr-review:*" / "swarm-pr-feedback:*".`);return state}async function requireBoundState(directory,sessionID,expectedMode){let state=await requireAnyActiveState(directory,sessionID);if(state.mode!==expectedMode)throw wrongModeError(state,expectedMode);if(!state.prHeadSha)throw Error(`BLOCKED: active ${expectedMode} workflow is not bound to a PR head`);if(expectedMode==="PR_REVIEW")await assertCurrentCheckoutHead(directory,state.prHeadSha,"PR_REVIEW"),await assertPrReviewCleanCheckout(directory);return state}function wrongModeError(state,expectedMode){return Error(`BLOCKED: session "${state.sessionID}" is active in ${state.mode}, not ${expectedMode}`)}function normalizeWorkflowLanes(lanes){if(!Array.isArray(lanes)||lanes.length===0)throw Error("BLOCKED: PR workflow lane validation requires at least one lane");let normalized=lanes.map((lane)=>{let workflowLane=lane.workflowLane?.trim(),laneId=lane.laneId?.trim()||workflowLane;if(!workflowLane||!laneId)throw Error("BLOCKED: PR workflow lane validation requires every lane to have non-empty laneId and workflow_lane values");let reviewItemIds=lane.reviewItemIds?.map((itemId)=>itemId.trim());if(reviewItemIds?.some((itemId)=>!itemId))throw Error("BLOCKED: PR workflow review_item_ids must not contain empty values");if(reviewItemIds)assertNoDuplicates(reviewItemIds,"review item ids within one lane");let ownedWorkflowLanes=lane.ownedWorkflowLanes?.map((owned)=>owned.trim());if(ownedWorkflowLanes){if(ownedWorkflowLanes.some((owned)=>!owned))throw Error("BLOCKED: PR workflow owned_workflow_lanes must not contain empty values");if(assertNoDuplicates(ownedWorkflowLanes,"owned workflow lanes within one lane"),!ownedWorkflowLanes.includes(workflowLane))throw Error(`BLOCKED: PR workflow lane "${laneId}" must include its own workflow_lane "${workflowLane}" in owned_workflow_lanes`)}return{laneId,workflowLane,...reviewItemIds?{reviewItemIds}:{},...ownedWorkflowLanes?{ownedWorkflowLanes}:{}}});return assertNoDuplicates(normalized.map((lane)=>lane.laneId),"lane ids"),assertNoDuplicates(normalized.map((lane)=>lane.workflowLane),"workflow lane ids"),assertNoDuplicates(normalized.flatMap((lane)=>lane.ownedWorkflowLanes??[lane.workflowLane]),"owned workflow lane ids across lanes"),normalized}function normalizeInventoryIds(inventoryIds){if(!Array.isArray(inventoryIds)||inventoryIds.length===0)throw Error("BLOCKED: PR_FEEDBACK inventory declaration requires at least one feedback item id");let normalized=inventoryIds.map((inventoryId)=>{let itemId=inventoryId.trim();if(!itemId)throw Error("BLOCKED: PR_FEEDBACK inventory declaration contains an empty item id");return itemId});return assertNoDuplicates(normalized,"inventory item ids"),normalized.sort()}function normalizeOwnership(ownership){if(!Array.isArray(ownership)||ownership.length===0)throw Error("BLOCKED: PR_FEEDBACK verification ownership requires at least one lane declaration");let normalized=ownership.map((lane)=>{let laneId=lane.laneId?.trim();if(!laneId)throw Error("BLOCKED: PR_FEEDBACK verification ownership requires every lane to have a non-empty laneId");let ownedItemIds=normalizeInventoryIds(lane.ownedItemIds);return{laneId,ownedItemIds}});return assertNoDuplicates(normalized.map((lane)=>lane.laneId),"PR_FEEDBACK verification lane ids"),normalized}function assertNoDuplicates(values,label){let seen=new Set;for(let value of values){if(seen.has(value))throw Error(`BLOCKED: duplicate ${label} are not allowed: ${value}`);seen.add(value)}}function containsProtectedWorkflowPath(value){return/(?:^|[^A-Za-z0-9_.-])\.swarm(?:[\\/]|$)/i.test(value.replace(/\\\\/g,"\\"))}function isPrWorkflowControllerTool(mode,toolName){if(PR_WORKFLOW_SHARED_CONTROLLER_TOOLS.has(toolName))return!0;return mode==="PR_REVIEW"?PR_REVIEW_CONTROLLER_TOOLS.has(toolName):PR_FEEDBACK_CONTROLLER_TOOLS.has(toolName)}function describePrWorkflowControllerToolNames(mode){let modeTools=mode==="PR_REVIEW"?PR_REVIEW_CONTROLLER_TOOLS:PR_FEEDBACK_CONTROLLER_TOOLS,names=[...PR_WORKFLOW_SHARED_CONTROLLER_TOOLS,...modeTools].sort((a,b)=>a.localeCompare(b));return` Allowed controller tools for ${mode}: ${names.join(", ")}. Observe current state read-only with the pr_workflow_status tool.`}function isTrustedPrWorkflowToolInvocationSafe(toolName,args2){if(toolName==="lint")return args2.mode==="check";if(toolName==="sast_scan")return args2.capture_baseline!==!0;return!0}function isAllowedPrReviewReadOnlyToolName(toolName){if(PR_REVIEW_READ_ONLY_TOOL_NAMES.has(toolName))return!0;let tokens=toolName.split(/[._:/-]+/).filter(Boolean);if(tokens.some((token)=>/^(?:add|alter|and|append|apply|approve|cancel|checkout|close|comment|commit|convert|create|delete|destroy|dismiss|drop|edit|execute|grant|insert|mark|merge|move|patch|prepend|publish|push|ready|remove|rename|replace|resolve|rerun|revoke|run|send|submit|then|transfer|truncate|unresolve|update|upload|write)$/i.test(token)))return!1;return tokens.some((token)=>/^(?:check|checks|diff|fetch|find|get|glob|grep|hover|inspect|list|lookup|open|read|references|scan|screenshot|search|show|status|symbols|tree|view)$/i.test(token))}function readOnlyToolArgumentsAreSafe(value,key="",depth=0){if(depth>8)return!1;let keyTokens=key.replace(/([a-z0-9])([A-Z])/g,"$1_$2").split(/[._:/-]+/).filter(Boolean);if(keyTokens.some((token)=>/^(?:append|body|content|create|data|delete|destination|destroy|edit|insert|mutation|output|patch|payload|prepend|remove|replace|save|set|truncate|update|upload|write)$/i.test(token)))return!1;if(keyTokens.some((token)=>/^(?:method|verb)$/i.test(token)))return typeof value==="string"&&/^(?:GET|HEAD)$/i.test(value.trim());if(keyTokens.length===1&&keyTokens.some((token)=>/^(?:action|operation)$/i.test(token)))return typeof value==="string"&&/^(?:check|diff|fetch|find|get|inspect|list|lookup|open|read|scan|search|show|status|view)$/i.test(value.trim());if(/^mode$/i.test(key)&&typeof value==="string")return/^(?:r|rb|read)$/i.test(value.trim());if(typeof value==="string"){if(keyTokens.some((token)=>/^(?:query|request|sql|statement)$/i.test(token))&&/(?:\b(?:alter|call|comment|create|delete|drop|exec(?:ute)?|grant|insert|merge|mutation|replace|revoke|truncate|update|upsert)\b|\bselect\b[\s\S]{0,4000}\binto\s+[A-Za-z_"'`])/i.test(value))return!1;return!/(?:^(?:POST|PUT|PATCH|DELETE|CONNECT|TRACE|write|edit|patch|create|delete|destroy|remove|replace|truncate|update|upload)$|(?:^|[\r\n])\s*(?:POST|PUT|PATCH|DELETE|CONNECT|TRACE)\s+\S+(?:\s+HTTP\/\d(?:\.\d)?)?|\bmutation\b|\b(?:create|drop|alter|truncate)\s+(?:or\s+replace\s+)?(?:table|database|schema|index|view|function|procedure|trigger|sequence)\b|\b(?:delete\s+from|insert\s+into|merge\s+into|replace\s+into|upsert\s+into)\b|\bupdate\s+[A-Za-z0-9_."'`-]+(?:\s+(?:AS\s+)?[A-Za-z0-9_"'`-]+)?\s+set\b|\b(?:grant|revoke)\s+\S+\s+(?:on|from|to)\b|\b(?:call|exec(?:ute)?)\s+[A-Za-z0-9_."'`-]+|\b(?:rm|rmdir|del|remove-item|move-item|set-content|add-content)\b)/i.test(value)}if(value===null||value===void 0||typeof value==="number"||typeof value==="boolean")return!0;if(Array.isArray(value))return value.every((entry)=>readOnlyToolArgumentsAreSafe(entry,key,depth+1));if(typeof value==="object")return Object.entries(value).every(([childKey,childValue])=>readOnlyToolArgumentsAreSafe(childValue,childKey,depth+1));return!1}function normalizePrWorkflowShellCommand(command){let normalized=command.trim(),withoutTrailingMerge=normalized.replace(PR_WORKFLOW_TRAILING_STDERR_MERGE_PATTERN,"");if(withoutTrailingMerge!==normalized)normalized=withoutTrailingMerge.trim();let strippedCdPrefix=!1;for(let index=0;index<PR_WORKFLOW_MAX_CD_PREFIX_STRIPS;index+=1){let next=normalized.replace(PR_WORKFLOW_CD_PREFIX_PATTERN,"");if(next===normalized)break;normalized=next.trim(),strippedCdPrefix=!0}return{normalized,strippedCdPrefix}}function isAllowedPrWorkflowReadOnlyShell(command,options){let{normalized:inner,strippedCdPrefix}=normalizePrWorkflowShellCommand(command),normalized=inner.replace(/\s+/g," ");if(!normalized)return!1;if(/[\r\n;&|<>`]/.test(inner)||/\$\(|@\(/.test(inner))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;if(/[\r\n;&|<>`]/.test(inner)||/\$\(|@\(/.test(inner))detail="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.";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 hasUnsafeShellControlSyntax(command){return/[;&|<>`\r\n]/.test(command)||/\$\(/.test(command)}function isSafeStandaloneGitCommit(command){if(hasUnsafeShellControlSyntax(command))return!1;if(/(?:^|\s)--(?:allow-empty|amend)(?:\s|=|$)/i.test(command))return!1;return/^[Gg][Ii][Tt](?:\s+-C(?:=|\s+)(?:"[^"\r\n]+"|'[^'\r\n]+'|[^\s;&|<>`]+))?\s+commit(?:\s+(?:"[^"\r\n]*"|'[^'\r\n]*'|[^\s;&|<>`]+))*\s*$/.test(command.trim())}function boundPushTarget(armed){let remote=armed.remoteName,branch=armed.remoteBranchRef.slice(11);if(!armed.remoteBranchRef.startsWith("refs/heads/")||!branch)return null;if(/\s|[;&|<>`]/.test(remote)||/\s|[;&|<>`]/.test(branch))return null;return{remote,branch}}function expectedBoundPushCommand(armed){let target=boundPushTarget(armed);return target?`git push ${target.remote} ${armed.localHead}:refs/heads/${target.branch}`:"(invalid bound remote-tracking ref; restart the workflow)"}function isSafeExactBoundPush(command,armed){if(hasUnsafeShellControlSyntax(command))return!1;let target=boundPushTarget(armed);if(!target)return!1;let match=command.trim().match(/^git\s+push\s+([^\s;&|<>`]+)\s+([^\s;&|<>`]+)\s*$/i);if(!match)return!1;return match[1]===target.remote&&match[2]===`${armed.localHead}:refs/heads/${target.branch}`}function isAllowedPrWorkflowGitIntake(gitArgs,options){if(/(?:--ext-diff|--textconv|--open-files-in-pager|--output(?:=|\s)|--upload-pack(?:=|\s)|--exec(?:=|\s))/i.test(gitArgs))return!1;if(/^(?:status|log|show|diff|rev-parse|merge-base|ls-files|grep|blame|cat-file|for-each-ref|--version|version)(?:\s|$)/i.test(gitArgs))return!0;if(isAllowedReadOnlyGitBranchListing(gitArgs))return!0;if(isAllowedReadOnlyGitStashListing(gitArgs))return!0;if(isAllowedReadOnlyGitWorktreeListing(gitArgs))return!0;if(options.allowFetch&&/^fetch(?:\s|$)/i.test(gitArgs))return!0;if(options.allowTrackingFetch&&isAllowedBoundRemoteTrackingFetch(gitArgs,options.trackingFetchTarget))return!0;if(/^remote(?:\s+-v)?$/i.test(gitArgs))return!0;if(options.allowCheckout&&isAllowedPreBindBranchSetup(gitArgs))return!0;if(options.allowCheckout&&/^(?:checkout|switch)\s+(?:--detach\s+)?[^\s-][^\s]*$/i.test(gitArgs))return!0;return/^config\s+(?:(?:--show-origin|--show-scope|--global|--local|--system|--worktree)\s+)*(?:--list|--get(?:-all)?\s+\S+)$/i.test(gitArgs)}function isAllowedBoundRemoteTrackingFetch(gitArgs,target){if(!target?.remoteName||!target.remoteBranchRef.startsWith("refs/heads/"))return!1;let tokens=gitArgs.trim().split(/\s+/);if(tokens.length!==3||tokens[0].toLowerCase()!=="fetch")return!1;let[,remote,remoteBranch]=tokens,expectedBranch=target.remoteBranchRef.slice(11);return isSafeGitRefToken(remote)&&!remote.includes("/")&&isSafeGitRefToken(remoteBranch)&&!remoteBranch.startsWith("-")&&!remoteBranch.includes(":")&&remote===target.remoteName&&remoteBranch===expectedBranch}function isAllowedPreBindBranchSetup(gitArgs){let tokens=gitArgs.trim().split(/\s+/);if(tokens.length===5){let[verb,createFlag,localBranch,trackFlag,upstream]=tokens;return(verb==="checkout"||verb==="switch")&&(createFlag==="-b"||createFlag==="-c")&&trackFlag==="--track"&&isSafeGitRefToken(localBranch)&&isSafeGitRefToken(upstream)&&upstream.includes("/")}if(tokens.length===3&&tokens[0]==="branch"){let upstream=tokens[1].match(/^--set-upstream-to=(.+)$/)?.[1];return Boolean(upstream&&isSafeGitRefToken(upstream)&&upstream.includes("/")&&isSafeGitRefToken(tokens[2]))}return!1}function isAllowedReadOnlyGitBranchListing(gitArgs){let tokens=gitArgs.trim().split(/\s+/);if(tokens.length===0||tokens[0].toLowerCase()!=="branch")return!1;let listingSelectorInEffect=!1;for(let index=1;index<tokens.length;index+=1){let token=tokens[index];if(/^(?:--list|--contains|--merged|--no-merged|--points-at)$/i.test(token)){listingSelectorInEffect=!0;continue}if(/^(?:-a|--all|-r|--remotes|-v|-vv|--verbose|--show-current|--color|--no-color|--column|--no-column|-i|--ignore-case)$/i.test(token)||/^--(?:sort|format|color)=/i.test(token))continue;if(token.startsWith("-"))return!1;if(!listingSelectorInEffect)return!1}return!0}function isAllowedReadOnlyGitStashListing(gitArgs){let tokens=gitArgs.trim().split(/\s+/);if(tokens.length<2||tokens[0].toLowerCase()!=="stash")return!1;if(tokens[1].toLowerCase()!=="list")return!1;for(let index=2;index<tokens.length;index+=1){let token=tokens[index];if(/^(?:-v|--oneline|--patch|-p|--stat|--color|--no-color)$/i.test(token))continue;if(/^--(?:format|pretty)=/i.test(token))continue;return!1}return!0}function isAllowedReadOnlyGitWorktreeListing(gitArgs){let tokens=gitArgs.trim().split(/\s+/);if(tokens.length<2||tokens[0].toLowerCase()!=="worktree")return!1;if(tokens[1].toLowerCase()!=="list")return!1;for(let index=2;index<tokens.length;index+=1){let token=tokens[index];if(/^(?:-v|--verbose|--porcelain|-z)$/i.test(token))continue;return!1}return!0}function isSafeGitRefToken(value){return/^[A-Za-z0-9][A-Za-z0-9._/-]*$/.test(value)&&!value.includes("..")&&!value.includes("//")&&!value.includes("@{")&&!value.endsWith("/")&&!value.endsWith(".")&&!value.endsWith(".lock")}function isAllowedPrFeedbackGhIntake(command){if(/^gh\s+pr\s+checkout(?:\s|$)/i.test(command))return isAllowedSafeGhPrCheckout(command);if(/^gh\s+--version$/i.test(command)||/^gh\s+pr\s+(?:view|diff|checks|status|list)(?:\s|$)/i.test(command)||/^gh\s+run\s+(?:view|list|watch)(?:\s|$)/i.test(command)||/^gh\s+issue\s+(?:view|list)(?:\s|$)/i.test(command)||/^gh\s+search\s+(?:code|commits|issues|prs|repos)(?:\s|$)/i.test(command)||/^gh\s+auth\s+status(?:\s|$)/i.test(command))return!0;if(!/^gh\s+api(?:\s|$)/i.test(command))return!1;if(/\bmutation\b/i.test(command))return!1;let method=command.match(/\s(?:--method(?:\s+|=)|-X(?:\s+|=)?)([A-Z]+)/i)?.[1];if(method&&method.toUpperCase()!=="GET")return!1;if(/\s(?:--input|--raw-field)(?:\s|=)/i.test(command)||/\s-F(?:\s|=|\S)/.test(command))return!1;return!/\s(?:--field|-f)(?:\s|=)(?!query=)/i.test(command)}function isAllowedSafeGhPrCheckout(command){if(/\s--(?:force|recurse-submodules)(?:\s|=|$)/i.test(command))return!1;let tokens=command.trim().split(/\s+/);if(tokens.length<4||tokens[0]!=="gh"||tokens[1]!=="pr"||tokens[2]!=="checkout")return!1;let target=tokens[3];if(!/^\d+$/.test(target)&&!/^https:\/\/github\.com\/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+\/pull\/\d+$/.test(target))return!1;for(let index=4;index<tokens.length;index+=1){let token=tokens[index],repoEquals=token.match(/^--repo=(.+)$/)?.[1];if(repoEquals){if(!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repoEquals))return!1;continue}let branchEquals=token.match(/^--branch=(.+)$/)?.[1];if(branchEquals){if(!isSafeGitRefToken(branchEquals))return!1;continue}if(token==="--repo"||token==="-R"){let repo=tokens[++index];if(!repo||!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repo))return!1;continue}if(token==="--branch"||token==="-b"){let branch=tokens[++index];if(!branch||!isSafeGitRefToken(branch))return!1;continue}return!1}return!0}function normalizePrHeadSha(prHeadSha){let normalized=prHeadSha.trim();if(!normalized)throw Error("BLOCKED: PR workflow requires a non-empty pr_head_sha");return normalized}async function currentPrFeedbackRevisionDigest(directory,state){if(!state.prHeadSha)throw Error("BLOCKED: PR_FEEDBACK revision binding requires pr_head_sha");let digest2=await resolvePrWorkflowRevisionDigestForGate(directory,state.prHeadSha);if(!digest2)throw Error("BLOCKED: PR_FEEDBACK could not compute a bounded current-revision digest");return digest2}async function resolvePrWorkflowRevisionDigestForGate(directory,baseHeadSha){if(_test_exports.resolvePrWorkflowRevisionDigest!==resolvePrWorkflowRevisionDigest)return _test_exports.resolvePrWorkflowRevisionDigest(directory,baseHeadSha);return resolvePrWorkflowRevisionDigestAsync(directory,baseHeadSha)}function normalizeBatchId(batchId){let normalized=batchId.trim();if(!normalized)throw Error("BLOCKED: PR workflow requires a non-empty batch id");return normalized}function sameStringArray(left,right){return left.length===right.length&&left.every((value,index)=>value===right[index])}function assertExactStringSet(actual,expected,label){let actualSet=new Set(actual),expectedSet=new Set(expected),missing=[...expectedSet].filter((value)=>!actualSet.has(value)),extra=[...actualSet].filter((value)=>!expectedSet.has(value));if(actual.length!==actualSet.size||actualSet.size!==expectedSet.size||missing.length>0||extra.length>0)throw Error(`BLOCKED: ${label} must exactly cover the mechanically derived inventory; missing: ${missing.join(", ")||"(none)"}; extra: ${extra.join(", ")||"(none)"}`)}function derivePrReviewCandidateInventory(directory,state){let sources=[],baseDimensionSources=new Map,baseSourceCreditedDimensions=new Map,baseSourceFullOwnershipCount=new Map;for(let batch of[...state.prReviewBaseDispatches??[]].reverse()){let successful=successfulObligationsFromExactBatch(directory,state,batch.batchId,batch.lanes,"swarm-pr-review:base",batch.validatedAt);for(let lane of batch.lanes){let ownedDimensions=lane.ownedWorkflowLanes?.length?lane.ownedWorkflowLanes:[lane.workflowLane];if(!ownedDimensions.every((dimension)=>successful.has(dimension)))continue;let key=`${batch.batchId}\x00${lane.laneId}`;baseSourceFullOwnershipCount.set(key,ownedDimensions.length);for(let dimension of ownedDimensions)if(!baseDimensionSources.has(dimension)){baseDimensionSources.set(dimension,{batchId:batch.batchId,laneId:lane.laneId});let credited=baseSourceCreditedDimensions.get(key);if(credited)credited.push(dimension);else baseSourceCreditedDimensions.set(key,[dimension])}}}let seenBaseSourceKeys=new Set;for(let{batchId,laneId}of baseDimensionSources.values()){let key=`${batchId}\x00${laneId}`;if(seenBaseSourceKeys.has(key))continue;seenBaseSourceKeys.add(key);let credited=baseSourceCreditedDimensions.get(key),fullOwnershipCount=baseSourceFullOwnershipCount.get(key)??0;sources.push({batchId,laneId,mode:"swarm-pr-review:base",creditedLanes:credited&&credited.length<fullOwnershipCount?credited:void 0})}let selectedCouncilLanes=new Set;for(let batch of[...state.prReviewValidationBatches??[]].reverse()){if(batch.phase!=="council")continue;let successful=successfulObligationsFromExactBatch(directory,state,batch.batchId,batch.lanes,"swarm-pr-review:council",batch.validatedAt);for(let lane of batch.lanes)if(successful.has(lane.workflowLane)&&!selectedCouncilLanes.has(lane.workflowLane))sources.push({batchId:batch.batchId,laneId:lane.laneId,mode:"swarm-pr-review:council"}),selectedCouncilLanes.add(lane.workflowLane)}if(state.prReviewTriggerEvalPath){let triggerPath=validateSwarmPath(directory,state.prReviewTriggerEvalPath),triggerArtifact;try{triggerArtifact=JSON.parse(readFileSync6(triggerPath,"utf-8"))}catch{throw Error("BLOCKED: PR_REVIEW trigger evaluation artifact is missing or invalid")}let receipt;try{receipt=parsePrReviewTriggerReceipt(triggerArtifact)}catch(error49){throw Error(`BLOCKED: PR_REVIEW trigger evaluation is invalid: ${error49 instanceof Error?error49.message:String(error49)}`)}for(let row of receipt.matchedRows)sources.push({batchId:row.source_batch_id,laneId:row.source_lane_id,mode:"swarm-pr-review:micro",workflowLane:row.trigger_id})}let candidateIds=[],extractedLaneKeys=new Set;for(let source of sources){let resolvedArtifact=!1;for(let record2 of findByBatchId(directory,source.batchId,{parentSessionId:state.sessionID})){if(record2.laneId!==source.laneId||record2.mode!==source.mode||record2.status!=="completed"||record2.workspace?.prHeadSha!==state.prHeadSha||record2.workspace?.gitHead!==state.prHeadSha||record2.result?.outputDegraded===!0||record2.result?.transcriptIncomplete===!0||record2.result?.truncated===!0)continue;let ref=record2.result?.outputRef?.trim(),artifact=ref?readLaneOutput(directory,ref)?.artifact:void 0,recordOwnedLanes=record2.ownedWorkflowLanes?.length?record2.ownedWorkflowLanes:record2.workflowLane?[record2.workflowLane]:void 0;if(!artifact||!workflowArtifactHasContractMarker(directory,state,record2,source.mode,record2.workflowLane??source.workflowLane??source.laneId,void 0,void 0,recordOwnedLanes))continue;if(source.workflowLane&&(!recordOwnedLanes?.includes(source.workflowLane)||!prReviewDiscoveryArtifactCoversLane(artifact.text,source.workflowLane,recordOwnedLanes)))continue;resolvedArtifact=!0;let laneKey=`${source.batchId}\x00${source.laneId}`;if(!extractedLaneKeys.has(laneKey))extractedLaneKeys.add(laneKey),candidateIds.push(...extractCandidateIds(artifact.text,source.mode==="swarm-pr-review:micro"?"micro_lane":"base_explorer",source.creditedLanes))}if(source.mode==="swarm-pr-review:micro"&&!resolvedArtifact)throw Error(`BLOCKED: PR_REVIEW mandatory micro-lane provenance is missing or invalid for ${source.workflowLane??source.laneId}`)}return assertNoDuplicates(candidateIds,"PR_REVIEW discovery candidate ids"),candidateIds.length>0?candidateIds.sort():["CLEAN-REVIEW"]}function appendBoundedCandidateIssue(issues,message){if(issues.length<MAX_CANDIDATE_ISSUES_PER_ARTIFACT-1){issues.push(message.slice(0,MAX_BASE_COVERAGE_DIAGNOSTIC_CHARS));return}if(issues.length===MAX_CANDIDATE_ISSUES_PER_ARTIFACT-1)issues.push("additional malformed candidate diagnostics omitted")}function parseCanonicalCandidateRows(text,fallbackFamily){let rows=[],issues=[],headerFamily=null;for(let[index,line]of removeCandidateCodeFences(text).split(/\r?\n/).entries()){let fields=splitPipeFields(line).map((field)=>field.trim()),detectedHeaderFamily=candidateHeaderFamily(fields);if(detectedHeaderFamily){headerFamily=detectedHeaderFamily;continue}let explicitMarker=fields[0]==="[CANDIDATE]",markerlessRow=headerFamily!==null&&Boolean(fields[0])&&!fields[0].startsWith("[");if(!explicitMarker&&!markerlessRow)continue;if(explicitMarker&&headerFamily===null){appendBoundedCandidateIssue(issues,`row ${index+1} field header: candidate output must begin with one exact canonical base or micro [CANDIDATE] header`);continue}let family=headerFamily??fallbackFamily,candidateFields=explicitMarker?fields.slice(1):fields,analysis=analyzeCandidateFields(candidateFields,family);if(!analysis.valid){for(let issue2 of analysis.issues)appendBoundedCandidateIssue(issues,`row ${index+1} field ${issue2.field}: ${issue2.message}`);continue}if(!analysis.candidateId||!analysis.workflowLane)continue;rows.push({candidateId:analysis.candidateId,workflowLane:analysis.workflowLane,evidence:candidateFields.slice(2).join("\x00"),lineNumber:index+1})}return{rows,issues}}function extractCandidateIds(text,fallbackFamily,scopeToLanes){let inScope=(lane)=>!scopeToLanes||lane!==void 0&&scopeToLanes.includes(lane);return parseCanonicalCandidateRows(text,fallbackFamily).rows.filter((row)=>inScope(row.workflowLane)).map((row)=>row.candidateId)}function derivePrReviewCriticInventory(directory,state){return[...deriveLatestPrReviewReviewerVerdicts(directory,state).entries()].filter(([,verdict])=>verdict.classification==="CONFIRMED"&&["CRITICAL","HIGH","MEDIUM"].includes(verdict.severity)).map(([itemId])=>itemId).sort()}function deriveLatestPrReviewCriticVerdicts(directory,state){let reviewerVerdicts=deriveLatestPrReviewReviewerVerdicts(directory,state),criticBatches=(state.prReviewValidationBatches??[]).filter((batch)=>batch.phase==="critic");for(let batch of[...criticBatches].reverse()){let successful=successfulObligationsFromExactBatch(directory,state,batch.batchId,batch.lanes,"swarm-pr-review:critic",batch.validatedAt);if(batch.lanes.some((lane)=>!successful.has(lane.workflowLane))||successful.size!==batch.lanes.length)continue;let required2=batch.lanes.flatMap((lane)=>lane.reviewItemIds??[]),verdicts=new Map;for(let lane of batch.lanes){let ref=findByBatchId(directory,batch.batchId,{parentSessionId:state.sessionID}).find((candidate)=>candidate.laneId===lane.laneId)?.result?.outputRef?.trim(),artifact=ref?readLaneOutput(directory,ref)?.artifact:void 0;if(!artifact)continue;for(let itemId of lane.reviewItemIds??[]){let verdict=parseCriticVerdict(artifact.text,itemId,reviewerVerdicts.get(itemId)?.severity);if(verdict)verdicts.set(itemId,verdict)}}if(required2.every((itemId)=>verdicts.has(itemId)))return verdicts}return new Map}function deriveLatestPrReviewReviewerVerdicts(directory,state){let reviewerBatches=(state.prReviewValidationBatches??[]).filter((batch)=>batch.phase==="reviewer");for(let batch of[...reviewerBatches].reverse()){let successful=successfulObligationsFromExactBatch(directory,state,batch.batchId,batch.lanes,"swarm-pr-review:reviewer",batch.validatedAt);if(batch.lanes.some((lane)=>!successful.has(lane.workflowLane))||successful.size!==batch.lanes.length)continue;let required2=batch.lanes.flatMap((lane)=>lane.reviewItemIds??[]),verdicts=new Map;for(let lane of batch.lanes){let ref=findByBatchId(directory,batch.batchId,{parentSessionId:state.sessionID}).find((candidate)=>candidate.laneId===lane.laneId)?.result?.outputRef?.trim(),artifact=ref?readLaneOutput(directory,ref)?.artifact:void 0;if(!artifact)continue;for(let itemId of lane.reviewItemIds??[]){let verdict=parseReviewerVerdict(artifact.text,itemId);if(verdict)verdicts.set(itemId,verdict)}}if(required2.every((itemId)=>verdicts.has(itemId)))return verdicts}return new Map}function successfulObligationsFromExactBatch(directory,state,batchId,expectedLanes,expectedMode,validatedAt,checkWorkflowLane=!0,forbiddenSubagentSessionIds=new Set,expectedRevisionDigest,diagnostics){let records=findByBatchId(directory,batchId,{parentSessionId:state.sessionID}),successful=new Set,validatedAtMs=Date.parse(validatedAt);if(!Number.isFinite(validatedAtMs))return successful;let expectedByLaneId=new Map(expectedLanes.map((lane)=>[lane.laneId,lane]));if(expectedByLaneId.size!==expectedLanes.length)return successful;let recordCountByLaneId=new Map,recordCountBySubagentSessionId=new Map;for(let record2 of records){if(!record2.laneId||!expectedByLaneId.has(record2.laneId))continue;recordCountByLaneId.set(record2.laneId,(recordCountByLaneId.get(record2.laneId)??0)+1);let subagentSessionId=record2.subagentSessionId?.trim();if(subagentSessionId)recordCountBySubagentSessionId.set(subagentSessionId,(recordCountBySubagentSessionId.get(subagentSessionId)??0)+1)}for(let record2 of records){let expectedLane=record2.laneId?expectedByLaneId.get(record2.laneId):void 0,expectedWorkflowLane=expectedLane?.workflowLane,expectedOwnedLanes=expectedLane?.ownedWorkflowLanes?.length?expectedLane.ownedWorkflowLanes:expectedWorkflowLane!==void 0?[expectedWorkflowLane]:void 0,subagentSessionId=record2.subagentSessionId?.trim();if(expectedWorkflowLane!==void 0&&expectedOwnedLanes!==void 0&&record2.laneId!==void 0&&recordCountByLaneId.get(record2.laneId)===1&&Boolean(subagentSessionId)&&recordCountBySubagentSessionId.get(subagentSessionId)===1&&!forbiddenSubagentSessionIds.has(subagentSessionId)&&record2.createdAt>=validatedAtMs&&(!checkWorkflowLane||record2.workflowLane===expectedWorkflowLane)&&(!checkWorkflowLane||ownedLaneSetsEqual(record2.ownedWorkflowLanes,expectedOwnedLanes))&&record2.mode===expectedMode&&record2.workspace?.prHeadSha===state.prHeadSha&&record2.workspace?.gitHead===state.prHeadSha&&record2.status==="completed"&&record2.result?.outputDegraded!==!0&&record2.result?.transcriptIncomplete!==!0&&record2.result?.truncated!==!0&&(record2.result?.chars??0)>0&&Boolean(record2.result?.digest?.trim())&&Boolean(record2.result?.outputRef?.trim())&&workflowArtifactHasContractMarker(directory,state,record2,expectedMode,expectedWorkflowLane,expectedLane?.reviewItemIds,expectedRevisionDigest,expectedOwnedLanes,diagnostics))for(let obligation of expectedOwnedLanes)successful.add(obligation)}return successful}function ownedLaneSetsEqual(recordOwned,expectedOwned){if(!recordOwned||recordOwned.length===0)return expectedOwned.length===1;let recordSet=new Set(recordOwned),expectedSet=new Set(expectedOwned);if(recordSet.size!==recordOwned.length||recordSet.size!==expectedSet.size)return!1;return recordOwned.every((owned)=>expectedSet.has(owned))}function workflowArtifactHasContractMarker(directory,state,record2,expectedMode,expectedWorkflowLane,reviewItemIds,expectedRevisionDigest,ownedWorkflowLanes,diagnostics){let ref=record2.result?.outputRef?.trim();if(!ref)return!1;let loaded=readLaneOutput(directory,ref);if(!loaded)return!1;let artifact=loaded.artifact,recordPrHeadSha=record2.workspace?.prHeadSha,recordGitHead=record2.workspace?.gitHead,resolvedRevisionDigest=expectedRevisionDigest??(recordPrHeadSha?_test_exports.resolvePrWorkflowRevisionDigest(directory,recordPrHeadSha):null),expectedReviewScope=state.mode==="PR_REVIEW"&&state.prReviewBaseSha&&state.prHeadSha?`complete PR diff ${state.prReviewBaseSha}...${state.prHeadSha}`:void 0;if(artifact.batchId!==record2.batchId||artifact.laneId!==record2.laneId||artifact.mode!==expectedMode||artifact.sessionId!==record2.subagentSessionId||artifact.parentSessionId!==record2.parentSessionId||artifact.agent!==record2.swarmPrefixedAgent||artifact.role!==record2.normalizedAgent||artifact.source!=="collect_lane_results"||artifact.workflowLane!==record2.workflowLane||artifact.workflowLane!==expectedWorkflowLane||!recordPrHeadSha||artifact.prHeadSha!==recordPrHeadSha||!recordGitHead||artifact.gitHead!==recordGitHead||!resolvedRevisionDigest||artifact.revisionDigest!==resolvedRevisionDigest||expectedReviewScope!==void 0&&(record2.workspace?.scope!==expectedReviewScope||artifact.scope!==expectedReviewScope)||artifact.digest!==record2.result?.digest||artifact.chars!==record2.result?.chars)return!1;if(expectedMode==="swarm-pr-review:reviewer")return Boolean(reviewItemIds?.length&&reviewItemIds.every((itemId)=>Boolean(parseReviewerVerdict(artifact.text,itemId))));if(expectedMode==="swarm-pr-review:critic"){let reviewerVerdicts=deriveLatestPrReviewReviewerVerdicts(directory,state);return Boolean(reviewItemIds?.length&&reviewItemIds.every((itemId)=>Boolean(parseCriticVerdict(artifact.text,itemId,reviewerVerdicts.get(itemId)?.severity))))}if(expectedMode==="swarm-pr-feedback:verification")return/^\[FEEDBACK-VERIFIED\]\s*\|/m.test(artifact.text);let feedbackVerdict={"swarm-pr-feedback:stage-b-reviewer":["[STAGE-B-REVIEW]","APPROVE"],"swarm-pr-feedback:stage-b-test":["[STAGE-B-TEST]","PASS"],"swarm-pr-feedback:closeout-reviewer":["[CLOSEOUT-REVIEW]","APPROVE"],"swarm-pr-feedback:closeout-critic":["[CLOSEOUT-CRITIC]","APPROVE"]}[expectedMode];if(feedbackVerdict)return Boolean(reviewItemIds?.length&&reviewItemIds.every((itemId)=>artifactHasExactPositiveVerdictRow(artifact.text,feedbackVerdict[0],itemId,feedbackVerdict[1])));let coveredLanes=ownedWorkflowLanes?.length?ownedWorkflowLanes:[expectedWorkflowLane],coverageAnalyses=coveredLanes.map((coveredLane)=>({coveredLane,analysis:analyzePrReviewDiscoveryArtifact(artifact.text,coveredLane,coveredLanes)}));if(coverageAnalyses.some(({analysis})=>!analysis.covered)){for(let{coveredLane,analysis}of coverageAnalyses){if(analysis.covered||analysis.issues.length===0)continue;if(diagnostics&&diagnostics.length<MAX_BASE_COVERAGE_DIAGNOSTICS){let diagnostic=`batch=${record2.batchId??"(missing)"} lane=${record2.laneId??"(missing)"} workflow_lane=${coveredLane} output_ref=${ref} digest=${record2.result?.digest??"(missing)"}: ${analysis.issues.join("; ")}`;diagnostics.push(diagnostic.slice(0,MAX_BASE_COVERAGE_DIAGNOSTIC_CHARS))}}return!1}if(coveredLanes.length>1){let seenEvidence=new Map;for(let coveredLane of coveredLanes){let evidence2=extractLaneCoverageEvidenceText(artifact.text,coveredLane,coveredLanes);if(evidence2===null)continue;if(seenEvidence.get(evidence2))return!1;seenEvidence.set(evidence2,coveredLane)}}return!0}function analyzePrReviewDiscoveryArtifact(text,expectedWorkflowLane,ownedWorkflowLanes=[expectedWorkflowLane]){let fallbackFamily=PR_REVIEW_BASE_DIMENSION_IDS.includes(expectedWorkflowLane)?"base_explorer":"micro_lane",issues=[],canonicalText=removeCandidateCodeFences(text),firstTabularFields=canonicalText.split(/\r?\n/).map((line)=>splitPipeFields(line).map((field)=>field.trim())).find((fields)=>fields.length>=2&&fields.some((field)=>field.length>0));if((firstTabularFields?candidateHeaderFamily(firstTabularFields):null)!==fallbackFamily)return appendBoundedCandidateIssue(issues,`field header: expected one exact canonical ${fallbackFamily} [CANDIDATE] header before discovery rows`),{covered:!1,evidence:null,issues};let parsed=parseCandidates({output_ref:"pr-workflow:discovery-artifact",batchId:"pr-workflow",laneId:expectedWorkflowLane,agent:"explorer",role:"explorer",digest:"0".repeat(64),text:canonicalText,artifact_status:"ok",source:"collect_lane_results",produced_at:"1970-01-01T00:00:00.000Z"},{accept_partial:!1,accept_degraded:!1,degraded:!1,row_format_version:1,producer:"swarm-pr-review",expected_family:fallbackFamily,...fallbackFamily==="base_explorer"?{expected_lane:expectedWorkflowLane,expected_lanes:[...ownedWorkflowLanes]}:{expected_micro_lane:expectedWorkflowLane,expected_micro_lanes:[...ownedWorkflowLanes]}});if(parsed.error)appendBoundedCandidateIssue(issues,parsed.error);for(let detail of parsed.diagnostics.parse_error_details)appendBoundedCandidateIssue(issues,`row ${detail.row_index+1} field ${detail.field}: ${detail.message}`);if(parsed.error||parsed.diagnostics.parse_error_details.length>0)return{covered:!1,evidence:null,issues};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};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};return{covered:!1,evidence:null,issues}}function prReviewDiscoveryArtifactCoversLane(text,expectedWorkflowLane,ownedWorkflowLanes=[expectedWorkflowLane]){return analyzePrReviewDiscoveryArtifact(text,expectedWorkflowLane,ownedWorkflowLanes).covered}function extractLaneCoverageEvidenceText(text,expectedWorkflowLane,ownedWorkflowLanes=[expectedWorkflowLane]){return analyzePrReviewDiscoveryArtifact(text,expectedWorkflowLane,ownedWorkflowLanes).evidence}function parseReviewerVerdict(text,itemId){let rows=text.split(/\r?\n/).map(pipeFields).filter((fields2)=>fields2[0]==="[REVIEWED]"&&fields2[1]===itemId);if(rows.length!==1)return null;let fields=rows[0];if(fields.length!==10||!fields.slice(1).every(Boolean))return null;let introduced=fields[5].replace(/^introduced_by_pr\s*:\s*/i,"").toUpperCase();if(!REVIEWER_CLASSIFICATIONS.has(fields[2])||!REVIEWER_EVIDENCE_TYPES.has(fields[3])||!REVIEW_SEVERITIES.has(fields[4])||!["YES","NO","UNKNOWN"].includes(introduced))return null;if(fields[7].length<8||fields[8].length<5||fields[9].length<3)return null;return{classification:fields[2],severity:fields[4]}}function parseCriticVerdict(text,itemId,reviewerSeverity){let rows=text.split(/\r?\n/).map(pipeFields).filter((fields2)=>fields2[0]==="[CRITIC]"&&fields2[1]===itemId);if(rows.length!==1)return null;let fields=rows[0];if(fields.length!==6||!fields.slice(1).every(Boolean)||!CRITIC_STATUSES.has(fields[2])||!REVIEW_SEVERITIES.has(fields[3]))return null;if(fields[2]==="NEEDS_MORE_EVIDENCE")return null;if(fields[2]==="DISPROVED"&&fields[3]!=="NONE")return null;if(fields[2]==="UPHELD"&&!["CRITICAL","HIGH","MEDIUM"].includes(fields[3]))return null;if(fields[2]==="DOWNGRADED"&&fields[3]==="CRITICAL")return null;if(reviewerSeverity){let severityRank=new Map([["NONE",0],["INFO",1],["LOW",2],["MEDIUM",3],["HIGH",4],["CRITICAL",5]]),reviewerRank=severityRank.get(reviewerSeverity),criticRank=severityRank.get(fields[3]);if(reviewerRank===void 0||criticRank===void 0)return null;if(fields[2]==="UPHELD"&&criticRank!==reviewerRank)return null;if(fields[2]==="DOWNGRADED"&&criticRank>=reviewerRank)return null}if(fields[4].length<6||fields[5].length<6)return null;return{status:fields[2],severity:fields[3]}}function artifactHasExactPositiveVerdictRow(text,marker,itemId,positiveVerdict){let rows=text.split(/\r?\n/).map(pipeFields).filter((fields)=>fields[0]===marker&&fields[1]===itemId);return rows.length===1&&rows[0].length>=4&&rows[0][2]===positiveVerdict&&rows[0].slice(1,4).every(Boolean)}function pipeFields(line){if(!line.includes("|"))return[];return line.split("|").map((field)=>field.trim())}function feedbackArtifactCoversItems(directory,state,batchId,laneId,itemIds){let ref=findByBatchId(directory,batchId,{parentSessionId:state.sessionID}).find((candidate)=>candidate.laneId===laneId)?.result?.outputRef?.trim(),loaded=ref?readLaneOutput(directory,ref):null;if(!loaded)return!1;let rows=loaded.artifact.text.split(/\r?\n/).map(pipeFields).filter((fields)=>fields[0]==="[FEEDBACK-VERIFIED]");if(rows.length!==itemIds.length)return!1;return itemIds.every((itemId)=>{let matches=rows.filter((fields)=>fields[1]===itemId);return matches.length===1&&matches[0].length===4&&matches[0].slice(1,4).every(Boolean)&&FEEDBACK_CLASSIFICATIONS.has(matches[0][2])})}async function persistState(directory,state){let validated=PrWorkflowGateStateSchema.parse(state);await withSessionStateMutation(directory,validated.sessionID,async()=>{let nextState=await writeStateWhileLocked(directory,validated);Object.assign(state,nextState)})}async function writeStateWhileLocked(directory,state,options={}){let validated=PrWorkflowGateStateSchema.parse(state),current=await readPrWorkflowGateStateFromDisk(directory,validated.sessionID);if(current?current.revision!==validated.revision:validated.revision!==0)throw Error("BLOCKED: PR workflow gate state changed concurrently; reload the active session state before retrying");if(current?.workflowInstanceId&&validated.workflowInstanceId!==current.workflowInstanceId&&options.replaceWorkflowInstanceId!==current.workflowInstanceId)throw Error("BLOCKED: PR workflow gate state changed concurrently; reload the active session state before retrying");let nextState=PrWorkflowGateStateSchema.parse({...validated,revision:validated.revision+1}),filePath=workflowGateStatePath(directory,validated.sessionID);return await writeAtomicJson2(directory,filePath,nextState),rememberState(directory,nextState),nextState}function workflowCheckoutMutationLockRelativePath(){return path14.join(WORKFLOW_GATE_DIR,"checkout.lock")}function workflowCheckoutMutationLockPath(directory){return validateSwarmPath(directory,workflowCheckoutMutationLockRelativePath())}function openCheckoutLockFile(lockPath){return fsp3.open(lockPath,"wx")}function removeCheckoutLockFile(lockPath){return fsp3.rm(lockPath)}function checkoutMutationProjectKey(directory){return normalizeComparableFsPath(directory)}async function withCheckoutMutationDeadline(promise2,phase){let timeout;try{return await Promise.race([promise2,new Promise((resolve9)=>{timeout=setTimeout(()=>{resolve9({status:"timeout",error:new PrWorkflowCheckoutMutationTimeoutError(phase)})},_test_exports.checkoutMutationActionTimeoutMs)})])}finally{if(timeout)clearTimeout(timeout)}}async function withPrWorkflowCheckoutMutationLock(directory,action){let key=checkoutMutationProjectKey(directory),previous=pendingCheckoutMutationsByProject.get(key)??Promise.resolve(),release,current=new Promise((resolve9)=>{release=resolve9}),queued=previous.then(()=>current);pendingCheckoutMutationsByProject.set(key,queued);let previousResult=await withCheckoutMutationDeadline(previous.then(()=>({status:"ready"})),"queue");if(previousResult.status==="timeout")throw release(),queued.then(()=>{if(pendingCheckoutMutationsByProject.get(key)===queued)pendingCheckoutMutationsByProject.delete(key)}),previousResult.error;let lock;try{lock=await acquireCheckoutMutationLock(directory)}catch(error49){if(release(),pendingCheckoutMutationsByProject.get(key)===queued)pendingCheckoutMutationsByProject.delete(key);throw error49}let actionOutcome=Promise.resolve().then(action).then((value)=>({status:"fulfilled",value}),(error49)=>({status:"rejected",error:error49})),outcome=await withCheckoutMutationDeadline(actionOutcome,"action");if(outcome.status==="timeout")throw actionOutcome.then(async()=>{try{await releaseCheckoutMutationLock(lock)}catch{}finally{if(release(),pendingCheckoutMutationsByProject.get(key)===queued)pendingCheckoutMutationsByProject.delete(key)}}),outcome.error;try{if(outcome.status==="rejected")throw outcome.error;return outcome.value}finally{try{await releaseCheckoutMutationLock(lock)}finally{if(release(),pendingCheckoutMutationsByProject.get(key)===queued)pendingCheckoutMutationsByProject.delete(key)}}}async function acquireCheckoutMutationLock(directory){let lockPath=workflowCheckoutMutationLockPath(directory),verifiedParent=await ensurePrWorkflowSafeParentDirectory(directory,lockPath);for(let attempt=0;attempt<STATE_MUTATION_LOCK_MAX_ATTEMPTS;attempt++)try{let handle=await _test_exports.openCheckoutLock(lockPath),lock={ownerToken:randomUUID2(),pid:process.pid,createdAtMs:_test_exports.nowMs()},lockIdentity,writeError;try{let openedStat=await handle.stat({bigint:!0});lockIdentity={dev:openedStat.dev,ino:openedStat.ino},lockIdentity=await assertOpenedSwarmFileIdentity(directory,lockPath,handle,verifiedParent,"PR workflow checkout mutation lock"),await _test_exports.beforeCheckoutLockWrite?.(),await handle.writeFile(JSON.stringify(lock),"utf-8")}catch(error49){writeError=error49}finally{await handle.close().catch(()=>{return})}if(writeError){if(lockIdentity)await removeCheckoutMutationLockByIdentity(directory,lockPath,lockIdentity,verifiedParent);throw writeError}return{path:lockPath,ownerToken:lock.ownerToken}}catch(error49){if(error49.code!=="EEXIST")throw error49;if(await reclaimAbandonedCheckoutMutationLock(lockPath))continue;if(attempt<STATE_MUTATION_LOCK_MAX_ATTEMPTS-1)await delay(STATE_MUTATION_LOCK_RETRY_DELAY_MS)}throw Error("BLOCKED: PR workflow checkout mutation is being handled by another process; retry after that checkout settles")}async function releaseCheckoutMutationLock(lock){let lastError;for(let attempt=0;attempt<WINDOWS_RENAME_MAX_RETRIES3;attempt++){try{if(await removeCheckoutMutationLockIfOwned(lock.path,lock.ownerToken)){completedCheckoutLockOwners.delete(lock.path);return}lastError=Error("PR workflow checkout mutation lock ownership changed before release")}catch(error49){lastError=error49}if(attempt<WINDOWS_RENAME_MAX_RETRIES3-1)await delay(RENAME_RETRY_DELAY_MS)}throw rememberCompletedCheckoutLockOwner(lock.path,lock.ownerToken),lastError instanceof Error?lastError:Error("PR workflow checkout mutation lock release failed")}async function reclaimAbandonedCheckoutMutationLock(lockPath){let lock=await readCheckoutMutationLock(lockPath);if(lock){if(lock.pid===process.pid&&completedCheckoutLockOwners.get(lockPath)===lock.ownerToken){let removed=await removeCheckoutMutationLockIfOwned(lockPath,lock.ownerToken);if(removed)completedCheckoutLockOwners.delete(lockPath);return removed}if(_test_exports.isProcessAlive(lock.pid))return!1;return removeCheckoutMutationLockIfOwned(lockPath,lock.ownerToken)}try{let stat6=await fsp3.stat(lockPath);if(_test_exports.nowMs()-stat6.mtimeMs<STATE_MUTATION_LOCK_UNINITIALIZED_STALE_MS)return!1;return await fsp3.rm(lockPath,{force:!0}),!0}catch(error49){if(error49.code==="ENOENT")return!0;throw error49}}async function readCheckoutMutationLock(lockPath){let raw;try{raw=await fsp3.readFile(lockPath,"utf-8")}catch(error49){if(error49.code==="ENOENT")return null;throw error49}try{let parsed=JSON.parse(raw);if(typeof parsed==="object"&&parsed!==null&&typeof parsed.ownerToken==="string"&&parsed.ownerToken.length>0&&typeof parsed.pid==="number"&&Number.isInteger(parsed.pid)&&parsed.pid>0&&typeof parsed.createdAtMs==="number"&&Number.isFinite(parsed.createdAtMs))return parsed}catch{}return null}async function removeCheckoutMutationLockIfOwned(lockPath,ownerToken){let lock=await readCheckoutMutationLock(lockPath);if(!lock||lock.ownerToken!==ownerToken)return!1;try{return await _test_exports.removeCheckoutLock(lockPath),!0}catch(error49){if(error49.code==="ENOENT")return!1;throw error49}}async function removeCheckoutMutationLockByIdentity(directory,lockPath,identity,verifiedParent){let lastError;for(let attempt=0;attempt<WINDOWS_RENAME_MAX_RETRIES3;attempt++)try{await assertClosedSwarmFileIdentity(directory,lockPath,identity,verifiedParent,"PR workflow checkout mutation lock"),await _test_exports.removeCheckoutLock(lockPath);return}catch(error49){if(error49.code==="ENOENT")return;if(lastError=error49,attempt<WINDOWS_RENAME_MAX_RETRIES3-1)await delay(RENAME_RETRY_DELAY_MS)}throw lastError instanceof Error?lastError:Error("PR workflow checkout mutation lock cleanup failed")}function rememberCompletedCheckoutLockOwner(lockPath,ownerToken){completedCheckoutLockOwners.delete(lockPath),completedCheckoutLockOwners.set(lockPath,ownerToken);while(completedCheckoutLockOwners.size>MAX_COMPLETED_CHECKOUT_LOCK_OWNERS){let oldest=completedCheckoutLockOwners.keys().next().value;if(oldest===void 0)break;completedCheckoutLockOwners.delete(oldest)}}async function withSessionStateMutation(directory,sessionID,action){let key=stateCacheKey(directory,sessionID),previous=pendingStateMutationsByProjectSession.get(key)??Promise.resolve(),release,current=new Promise((resolve9)=>{release=resolve9}),queued=previous.then(()=>current);pendingStateMutationsByProjectSession.set(key,queued),await previous;try{let lock=await acquireSessionStateMutationLock(directory,sessionID);try{return await action()}finally{await releaseSessionStateMutationLock(lock)}}finally{if(release(),pendingStateMutationsByProjectSession.get(key)===queued)pendingStateMutationsByProjectSession.delete(key)}}async function acquireSessionStateMutationLock(directory,sessionID){let lockPath=workflowGateStateLockPath(directory,sessionID),verifiedParent=await ensurePrWorkflowSafeParentDirectory(directory,lockPath);for(let attempt=0;attempt<STATE_MUTATION_LOCK_MAX_ATTEMPTS;attempt++)try{let handle=await fsp3.open(lockPath,"wx"),lock={ownerToken:randomUUID2(),pid:process.pid,createdAtMs:_test_exports.nowMs()},writeError;try{await _test_exports.beforeSessionStateLockWrite?.(),await assertOpenedSwarmFileIdentity(directory,lockPath,handle,verifiedParent,"PR workflow state mutation lock"),await handle.writeFile(JSON.stringify(lock),"utf-8")}catch(error49){writeError=error49}finally{await handle.close().catch(()=>{return})}if(writeError)throw await removeSessionStateMutationLockIfOwned(lockPath,lock.ownerToken),writeError;return{path:lockPath,ownerToken:lock.ownerToken}}catch(error49){if(error49.code!=="EEXIST")throw error49;if(await reclaimAbandonedSessionStateMutationLock(lockPath))continue;if(attempt<STATE_MUTATION_LOCK_MAX_ATTEMPTS-1)await delay(STATE_MUTATION_LOCK_RETRY_DELAY_MS)}throw Error("BLOCKED: PR workflow gate state is being mutated by another process; retry after that session transition finishes")}async function releaseSessionStateMutationLock(lock){try{await removeSessionStateMutationLockIfOwned(lock.path,lock.ownerToken)}catch{}}async function reclaimAbandonedSessionStateMutationLock(lockPath){let lock=await readSessionStateMutationLock(lockPath);if(lock){if(_test_exports.isProcessAlive(lock.pid))return!1;return removeSessionStateMutationLockIfOwned(lockPath,lock.ownerToken)}try{let stat6=await fsp3.stat(lockPath);if(_test_exports.nowMs()-stat6.mtimeMs<STATE_MUTATION_LOCK_UNINITIALIZED_STALE_MS)return!1;return await fsp3.rm(lockPath,{force:!0}),!0}catch(error49){if(error49.code==="ENOENT")return!0;throw error49}}async function readSessionStateMutationLock(lockPath){let raw;try{raw=await fsp3.readFile(lockPath,"utf-8")}catch(error49){if(error49.code==="ENOENT")return null;throw error49}try{let parsed=JSON.parse(raw);if(typeof parsed==="object"&&parsed!==null&&typeof parsed.ownerToken==="string"&&parsed.ownerToken.length>0&&typeof parsed.pid==="number"&&Number.isInteger(parsed.pid)&&parsed.pid>0&&typeof parsed.createdAtMs==="number"&&Number.isFinite(parsed.createdAtMs))return parsed}catch{}return null}async function removeSessionStateMutationLockIfOwned(lockPath,ownerToken){let lock=await readSessionStateMutationLock(lockPath);if(!lock||lock.ownerToken!==ownerToken)return!1;try{return await fsp3.rm(lockPath),!0}catch(error49){if(error49.code==="ENOENT")return!1;throw error49}}function isProcessAlive(pid){try{return process.kill(pid,0),!0}catch(error49){return error49.code!=="ESRCH"}}async function readPrWorkflowGateStateFromDisk(directory,sessionID){let filePath=workflowGateStatePath(directory,sessionID),raw;try{raw=await fsp3.readFile(filePath,"utf-8")}catch(error49){if(error49.code==="ENOENT")return null;throw error49}let parsedJson;try{parsedJson=JSON.parse(raw)}catch{throw Error(`BLOCKED: PR workflow gate state for session "${sessionID}" is not valid JSON`)}let parsed=PrWorkflowGateStateSchema.safeParse(parsedJson);if(!parsed.success)throw Error(`BLOCKED: PR workflow gate state for session "${sessionID}" is invalid`);return parsed.data}function rememberState(directory,state){let cacheKey=stateCacheKey(directory,state.sessionID);trackedStatesByProjectSession.delete(cacheKey),trackedStatesByProjectSession.set(cacheKey,state);while(trackedStatesByProjectSession.size>MAX_TRACKED_SESSIONS){let oldestKey=trackedStatesByProjectSession.keys().next().value;if(!oldestKey)break;trackedStatesByProjectSession.delete(oldestKey)}}function stateCacheKey(directory,sessionID){let resolved=path14.normalize(path14.resolve(directory));return`${process.platform==="win32"?resolved.toLowerCase():resolved}\x00${normalizeSessionID(sessionID)}`}function workflowGateStatePath(directory,sessionID){return validateSwarmPath(directory,workflowGateStateRelativePath(sessionID))}function workflowGateStateLockPath(directory,sessionID){return validateSwarmPath(directory,workflowGateStateLockRelativePath(sessionID))}function workflowGateStateLockRelativePath(sessionID){return path14.join(WORKFLOW_GATE_DIR,`${prWorkflowSessionFileStem(sessionID)}.lock`)}function workflowGateStateRelativePath(sessionID){return path14.join(WORKFLOW_GATE_DIR,`${prWorkflowSessionFileStem(sessionID)}.json`)}function prWorkflowSessionFileStem(sessionID){let normalized=normalizeSessionID(sessionID),slug=normalized.replace(/[^A-Za-z0-9_.-]/g,"_").slice(0,80)||"session",digest2=createHash7("sha256").update(normalized).digest("hex").slice(0,12);return`${slug}-${digest2}`}function normalizeSessionID(sessionID){let normalized=sessionID.trim();if(!normalized)throw Error("BLOCKED: PR workflow gate requires a non-empty sessionID");return normalized}async function ensurePrWorkflowSafeParentDirectory(directory,filePath){let swarmRoot=path14.resolve(directory,".swarm"),parentPath=path14.dirname(path14.resolve(filePath)),relativeParent=path14.relative(swarmRoot,parentPath);if(relativeParent===".."||relativeParent.startsWith(`..${path14.sep}`)||path14.isAbsolute(relativeParent))throw Error("BLOCKED: PR workflow atomic destination escapes the project .swarm directory");await fsp3.mkdir(swarmRoot,{recursive:!0});let currentPath=swarmRoot,currentIdentity=await assertSafeDirectory(currentPath,void 0);for(let segment of relativeParent.split(path14.sep).filter(Boolean)){let nextPath=path14.join(currentPath,segment);await _test_exports.beforeSafeDirectoryCreate?.(currentPath,nextPath),await assertSafeDirectory(currentPath,currentIdentity);try{await fsp3.mkdir(nextPath)}catch(error49){if(error49.code!=="EEXIST")throw error49}await assertSafeDirectory(currentPath,currentIdentity);let nextIdentity=await assertSafeDirectory(nextPath,void 0),[realCurrent,realNext]=await Promise.all([fsp3.realpath(currentPath),fsp3.realpath(nextPath)]);if(normalizeComparableFsPath(path14.dirname(realNext))!==normalizeComparableFsPath(realCurrent))throw Error("BLOCKED: PR workflow directory creation escaped the project .swarm tree");currentPath=nextPath,currentIdentity=nextIdentity}let realRoot=await fsp3.realpath(swarmRoot),realParent=await fsp3.realpath(parentPath),relativeRealParent=path14.relative(realRoot,realParent);if(relativeRealParent===".."||relativeRealParent.startsWith(`..${path14.sep}`)||path14.isAbsolute(relativeRealParent))throw Error("BLOCKED: PR workflow atomic parent escapes the project .swarm directory");return realParent}async function assertSafeDirectory(directoryPath,expectedIdentity){let stat6=await fsp3.lstat(directoryPath,{bigint:!0});if(stat6.isSymbolicLink()||!stat6.isDirectory()||expectedIdentity&&!sameBigIntFileIdentity(stat6,expectedIdentity))throw Error("BLOCKED: PR workflow .swarm path must be a real directory and must not change during the operation");return{dev:stat6.dev,ino:stat6.ino}}async function assertOpenedSwarmFileIdentity(directory,filePath,handle,expectedParent,label){let openedStat=await handle.stat({bigint:!0});if(!openedStat.isFile())throw Error(`BLOCKED: ${label} is not a file`);return await assertClosedSwarmFileIdentity(directory,filePath,openedStat,expectedParent,label),{dev:openedStat.dev,ino:openedStat.ino}}async function assertClosedSwarmFileIdentity(directory,filePath,expectedIdentity,expectedParent,label){if(!expectedIdentity)throw Error(`BLOCKED: ${label} has no identity`);let[stat6,realRoot,realFile,realParent]=await Promise.all([fsp3.lstat(filePath,{bigint:!0}),fsp3.realpath(path14.resolve(directory,".swarm")),fsp3.realpath(filePath),fsp3.realpath(path14.dirname(filePath))]),relativeFile=path14.relative(realRoot,realFile);if(stat6.isSymbolicLink()||!stat6.isFile()||!sameBigIntFileIdentity(stat6,expectedIdentity)||normalizeComparableFsPath(realParent)!==normalizeComparableFsPath(expectedParent)||relativeFile===""||relativeFile===".."||relativeFile.startsWith(`..${path14.sep}`)||path14.isAbsolute(relativeFile))throw Error(`BLOCKED: ${label} changed or escaped .swarm`)}async function writeAtomicJson2(directory,filePath,value){let safeParent=await ensurePrWorkflowSafeParentDirectory(directory,filePath),tempPath=`${filePath}.tmp.${process.pid}.${randomUUID2()}`,tempIdentity,lastError;try{let handle=await fsp3.open(tempPath,"wx");try{await _test_exports.beforeAtomicTempWrite?.(),tempIdentity=await assertOpenedSwarmFileIdentity(directory,tempPath,handle,safeParent,"PR workflow atomic temporary file"),await handle.writeFile(JSON.stringify(value,null,2),"utf-8"),await handle.sync()}finally{await handle.close()}await _test_exports.beforeAtomicRename?.(),await assertClosedSwarmFileIdentity(directory,tempPath,tempIdentity,safeParent,"PR workflow atomic temporary file");for(let attempt=0;attempt<WINDOWS_RENAME_MAX_RETRIES3;attempt++)try{await _test_exports.rename(tempPath,filePath),lastError=void 0;break}catch(error49){lastError=error49;let code=error49.code;if(code!=="EEXIST"&&code!=="EPERM"&&code!=="EBUSY")break;if(attempt<WINDOWS_RENAME_MAX_RETRIES3-1)await delay(RENAME_RETRY_DELAY_MS)}if(lastError)throw lastError;await assertClosedSwarmFileIdentity(directory,filePath,tempIdentity,safeParent,"PR workflow atomic destination file")}finally{try{await fsp3.rm(tempPath,{force:!0})}catch{}}}async function writePrWorkflowAtomicJson(directory,filePath,value){await writeAtomicJson2(directory,filePath,value)}function isoNow(){return new Date().toISOString()}function delay(ms){return new Promise((resolve9)=>setTimeout(resolve9,ms))}var PR_REVIEW_BASE_DIMENSION_IDS,PR_REVIEW_REQUIRED_MICRO_LANE_IDS,PR_REVIEW_DEPTH_TIER_THRESHOLDS,PR_REVIEW_BASE_LANE_FLOORS,PR_REVIEW_MICRO_LANE_FLOORS,GATE_SCHEMA_VERSION=1,MAX_TRACKED_SESSIONS=200,MAX_WORKFLOW_BATCHES=128,WINDOWS_RENAME_MAX_RETRIES3=3,RENAME_RETRY_DELAY_MS=10,STATE_MUTATION_LOCK_MAX_ATTEMPTS=50,STATE_MUTATION_LOCK_RETRY_DELAY_MS=10,STATE_MUTATION_LOCK_UNINITIALIZED_STALE_MS=30000,MAX_COMPLETED_CHECKOUT_LOCK_OWNERS=64,CHECKOUT_MUTATION_ACTION_TIMEOUT_MS=300000,MAX_CANDIDATE_ISSUES_PER_ARTIFACT=8,MAX_BASE_COVERAGE_DIAGNOSTICS=8,MAX_BASE_COVERAGE_DIAGNOSTIC_CHARS=1000,DISPATCH_TOOL_NAME="dispatch_lanes_async",BLOCKING_DISPATCH_TOOL_NAME="dispatch_lanes",WORKFLOW_GATE_DIR="pr-workflow-gates",trackedStatesByProjectSession,pendingStateMutationsByProjectSession,pendingCheckoutMutationsByProject,completedCheckoutLockOwners,PrReviewBaseDimensionIdSchema,PrReviewBaseDispatchRecordSchema,PrFeedbackLaneOwnershipSchema,PrFeedbackVerificationRecordSchema,PrFeedbackStageACheckReceiptSchema,PrFeedbackStageARecordSchema,PrFeedbackGateBatchRecordSchema,PrFeedbackReadyToPublishRecordSchema,PrReviewValidationBatchRecordSchema,PrFeedbackScopeDeclarationRecordSchema,PrWorkflowCheckoutRecoveryRecordSchema,PrFeedbackReviewHandoffRecordSchema,PrWorkflowGateStateSchema,PR_FEEDBACK_PHASE_ORDER,PR_FEEDBACK_PHASE_ROLE,PR_REVIEW_HANDOFF_RELATIVE_PATH_PATTERN,PR_REVIEW_HANDOFF_MAX_BYTES=131072,PR_REVIEW_FINDINGS_MAX_BYTES=10485760,PrReviewFeedbackHandoffArtifactSchema,PrReviewFindingProjectionSchema,_test_exports,PR_WORKFLOW_SHARED_CONTROLLER_TOOLS,PR_REVIEW_CONTROLLER_TOOLS,PR_FEEDBACK_CONTROLLER_TOOLS,PR_REVIEW_READ_ONLY_TOOL_NAMES,PR_WORKFLOW_CD_PREFIX_PATTERN,PR_WORKFLOW_TRAILING_STDERR_MERGE_PATTERN,PR_WORKFLOW_MAX_CD_PREFIX_STRIPS=3,PR_WORKFLOW_GIT_DIR_OVERRIDE_PATTERN,PR_WORKFLOW_GIT_HAS_DIR_OVERRIDE_PATTERN,REVIEWER_CLASSIFICATIONS,REVIEWER_EVIDENCE_TYPES,REVIEW_SEVERITIES,CRITIC_STATUSES,FEEDBACK_CLASSIFICATIONS,PrWorkflowCheckoutMutationTimeoutError;var init_pr_workflow_gate=__esm(()=>{init_zod();init_candidate_contract();init_candidate_parser();init_lane_output_store();init_pending_delegations();init_pr_review_trigger_contract();init_workspace_snapshot();init_constants();init_schema();init_pr_workflow_state();init_tool_metadata();init_utils2();PR_REVIEW_BASE_DIMENSION_IDS=["intent-architecture","correctness-state","tests-falsifiability","security-trust","reliability-performance","compatibility-delivery"],PR_REVIEW_REQUIRED_MICRO_LANE_IDS=PR_REVIEW_REQUIRED_TRIGGER_IDS,PR_REVIEW_DEPTH_TIER_THRESHOLDS={smallMaxChangedLines:100,smallMaxChangedFiles:5,mediumMaxChangedLines:1500,mediumMaxChangedFiles:50},PR_REVIEW_BASE_LANE_FLOORS={S:1,M:3,L:PR_REVIEW_BASE_DIMENSION_IDS.length},PR_REVIEW_MICRO_LANE_FLOORS={S:1,M:6,L:PR_REVIEW_REQUIRED_MICRO_LANE_IDS.length};trackedStatesByProjectSession=new Map,pendingStateMutationsByProjectSession=new Map,pendingCheckoutMutationsByProject=new Map,completedCheckoutLockOwners=new Map,PrReviewBaseDimensionIdSchema=exports_external.enum(["intent-architecture","correctness-state","tests-falsifiability","security-trust","reliability-performance","compatibility-delivery"]),PrReviewBaseDispatchRecordSchema=exports_external.object({batchId:exports_external.string().min(1),lanes:exports_external.array(exports_external.object({laneId:exports_external.string().min(1),workflowLane:PrReviewBaseDimensionIdSchema,ownedWorkflowLanes:exports_external.array(PrReviewBaseDimensionIdSchema).min(1).max(PR_REVIEW_BASE_DIMENSION_IDS.length).optional()}).strict()).min(1),validatedAt:exports_external.string().min(1)}).strict(),PrFeedbackLaneOwnershipSchema=exports_external.object({laneId:exports_external.string().min(1),ownedItemIds:exports_external.array(exports_external.string().min(1)).min(1)}).strict(),PrFeedbackVerificationRecordSchema=exports_external.object({batchId:exports_external.string().min(1),ownership:exports_external.array(PrFeedbackLaneOwnershipSchema).min(1),validatedAt:exports_external.string().min(1)}).strict(),PrFeedbackStageACheckReceiptSchema=exports_external.object({category:exports_external.enum(["build","typecheck","lint","diff-check","reproduction"]),workingDirectory:exports_external.string().min(1).optional(),obligationId:exports_external.string().min(1).optional(),validatorContract:exports_external.object({path:exports_external.string().min(1),id:exports_external.string().min(1)}).strict().optional(),command:exports_external.array(exports_external.string().min(1)).min(1),targets:exports_external.array(exports_external.string().min(1)).min(1).optional(),feedbackTargets:exports_external.array(exports_external.object({feedbackItemId:exports_external.string().min(1),target:exports_external.string().min(1),expectedBehavior:exports_external.string().min(8)}).strict()).min(1).optional(),durationMs:exports_external.number().nonnegative()}).strict(),PrFeedbackStageARecordSchema=exports_external.object({revisionDigest:exports_external.string().min(1),checks:exports_external.array(PrFeedbackStageACheckReceiptSchema).min(2).max(258),feedbackItemIds:exports_external.array(exports_external.string().min(1)).min(1).optional(),applicableCategories:exports_external.array(exports_external.enum(["build","typecheck","lint"])).max(3).optional(),applicableObligations:exports_external.array(exports_external.object({id:exports_external.string().min(1),category:exports_external.enum(["build","typecheck","lint"]),workingDirectory:exports_external.string().min(1),source:exports_external.string().min(1),validatorContract:exports_external.object({path:exports_external.string().min(1),id:exports_external.string().min(1)}).strict().optional()}).strict()).max(256).optional(),validatedAt:exports_external.string().min(1)}).strict(),PrFeedbackGateBatchRecordSchema=exports_external.object({batchId:exports_external.string().min(1),phase:exports_external.enum(["stage-b-reviewer","stage-b-test","closeout-reviewer","closeout-critic"]),laneId:exports_external.string().min(1),itemIds:exports_external.array(exports_external.string().min(1)).min(1),revisionDigest:exports_external.string().min(1),validatedAt:exports_external.string().min(1)}).strict(),PrFeedbackReadyToPublishRecordSchema=exports_external.object({revisionDigest:exports_external.string().min(1),localHead:exports_external.string().min(1),remoteName:exports_external.string().min(1),remoteBranchRef:exports_external.string().startsWith("refs/heads/"),remoteRef:exports_external.string().startsWith("refs/remotes/"),validatedAt:exports_external.string().min(1)}).strict(),PrReviewValidationBatchRecordSchema=exports_external.object({batchId:exports_external.string().min(1),phase:exports_external.enum(["council","reviewer","critic"]),lanes:exports_external.array(exports_external.object({laneId:exports_external.string().min(1),workflowLane:exports_external.string().min(1),reviewItemIds:exports_external.array(exports_external.string().min(1)).min(1).optional()}).strict()).min(1),validatedAt:exports_external.string().min(1)}).strict(),PrFeedbackScopeDeclarationRecordSchema=exports_external.object({taskId:exports_external.string().regex(/^\d+\.\d+(?:\.\d+)*$/),files:exports_external.array(exports_external.string().min(1)).min(1).max(1e4),revisionDigest:exports_external.string().min(1),declaredAt:exports_external.string().min(1),consumedByCallId:exports_external.string().min(1).optional()}).strict(),PrWorkflowCheckoutRecoveryRecordSchema=exports_external.object({code:exports_external.enum(["UNMERGED_INDEX","GIT_OPERATION_IN_PROGRESS","DIRTY_SUBMODULE","SWARM_STATE_TRACKING_ERROR","GIT_STATE_INDETERMINATE"]),retryable:exports_external.literal(!1),requiredAction:exports_external.string().min(1).max(2000),evidence:exports_external.object({worktreeRoot:exports_external.string().nullable(),gitDir:exports_external.string().nullable(),operations:exports_external.array(exports_external.string().min(1)).max(16),unmergedCodes:exports_external.array(exports_external.string().min(1)).max(16),paths:exports_external.array(exports_external.string()).max(20),trackedCount:exports_external.number().int().nonnegative(),untrackedCount:exports_external.number().int().nonnegative(),pathsTruncated:exports_external.boolean(),detail:exports_external.string().max(1000).optional()}).strict(),detectedAt:exports_external.string().min(1)}).strict(),PrFeedbackReviewHandoffRecordSchema=exports_external.object({path:exports_external.string().min(1).max(512),runId:exports_external.string().min(1).max(128),sourcePrHeadSha:exports_external.string().regex(/^[0-9a-f]{6,64}$/i),prUrl:exports_external.string().url().max(2000),findingIds:exports_external.array(exports_external.string().min(1).max(128)).min(1).max(1000),digest:exports_external.string().regex(/^[0-9a-f]{64}$/),sourceWorkflowInstanceId:exports_external.string().min(1).max(128),provenance:exports_external.enum(["active-review-v1","external-v1"])}).strict(),PrWorkflowGateStateSchema=exports_external.object({schemaVersion:exports_external.literal(GATE_SCHEMA_VERSION),revision:exports_external.number().int().nonnegative().default(0),workflowInstanceId:exports_external.string().min(1).max(128).optional(),sessionID:exports_external.string().min(1),mode:exports_external.enum(["PR_REVIEW","PR_FEEDBACK"]),activatedAt:exports_external.string().min(1),updatedAt:exports_external.string().min(1),prHeadSha:exports_external.string().min(1).optional(),prReviewBaseRef:exports_external.string().min(1).optional(),prReviewBaseSha:exports_external.string().min(1).optional(),prReviewDepthTier:exports_external.enum(["S","M","L"]).optional(),prReviewDiffStats:exports_external.object({changedLines:exports_external.number().int().nonnegative(),changedFiles:exports_external.number().int().nonnegative(),hasSubmoduleChange:exports_external.boolean().default(!1)}).strict().optional(),prReviewBaseDispatches:exports_external.array(PrReviewBaseDispatchRecordSchema).max(MAX_WORKFLOW_BATCHES).optional(),prReviewBaseDispatch:PrReviewBaseDispatchRecordSchema.optional(),prReviewTriggerLedger:exports_external.array(PrReviewInlineTriggerRowSchema).length(PR_REVIEW_REQUIRED_TRIGGER_IDS.length).optional(),prReviewTriggerEvalPath:exports_external.string().min(1).optional(),prReviewValidationBatches:exports_external.array(PrReviewValidationBatchRecordSchema).max(MAX_WORKFLOW_BATCHES).optional(),prReviewArtifactRunId:exports_external.string().min(1).optional(),prReviewFindingsPath:exports_external.string().min(1).optional(),prReviewArtifactBoundaries:exports_external.array(exports_external.enum(["post_explorer","post_reviewer","post_critic"])).max(3).optional(),prReviewHandoffPath:exports_external.string().min(1).optional(),prReviewHandoffRequired:exports_external.boolean().optional(),checkoutRecovery:PrWorkflowCheckoutRecoveryRecordSchema.optional(),prFeedbackTargetUrl:exports_external.string().url().max(2000).optional(),prFeedbackReviewHandoff:PrFeedbackReviewHandoffRecordSchema.optional(),prFeedbackInventory:exports_external.array(exports_external.string().min(1)).min(1).optional(),prFeedbackVerifications:exports_external.array(PrFeedbackVerificationRecordSchema).max(MAX_WORKFLOW_BATCHES).optional(),prFeedbackVerification:PrFeedbackVerificationRecordSchema.optional(),prFeedbackStageA:PrFeedbackStageARecordSchema.optional(),prFeedbackGateBatches:exports_external.array(PrFeedbackGateBatchRecordSchema).max(MAX_WORKFLOW_BATCHES).optional(),prFeedbackReadyToPublish:PrFeedbackReadyToPublishRecordSchema.optional(),prFeedbackScopes:exports_external.array(PrFeedbackScopeDeclarationRecordSchema).max(MAX_WORKFLOW_BATCHES).optional()}).passthrough();PR_FEEDBACK_PHASE_ORDER=["stage-b-reviewer","stage-b-test","closeout-reviewer","closeout-critic"];PR_FEEDBACK_PHASE_ROLE={"stage-b-reviewer":"reviewer","stage-b-test":"test_engineer","closeout-reviewer":"reviewer","closeout-critic":"critic"};PR_REVIEW_HANDOFF_RELATIVE_PATH_PATTERN=/^pr-review\/([A-Za-z0-9][A-Za-z0-9._-]{0,127})\/feedback-handoff\.json$/,PrReviewFeedbackHandoffArtifactSchema=exports_external.object({schema_version:exports_external.literal(1),run_id:exports_external.string().min(1).max(128),pr_head_sha:exports_external.string().regex(/^[0-9a-f]{6,64}$/i),created_at:exports_external.string().datetime(),pr_url:exports_external.string().url().max(2000),finding_ids:exports_external.array(exports_external.string().min(1).max(128)).min(1).max(1000),summary:exports_external.string().min(1).max(20000),provenance:exports_external.array(exports_external.string().min(1).max(4000)).min(1).max(1000)}).strict();PrReviewFindingProjectionSchema=exports_external.object({finding_id:exports_external.string().min(1).max(128),status:exports_external.enum(["PENDING","CONFIRMED","DISPROVED","PRE_EXISTING"]),next_action:exports_external.enum(["route_to_reviewer","route_to_critic","report","suppress_with_reason","handoff_to_feedback"])}).passthrough();_test_exports={workflowGateStateRelativePath,workflowGateStateLockRelativePath,workflowCheckoutMutationLockRelativePath,withPrWorkflowCheckoutMutationLock,resetTrackedStateCache:()=>{trackedStatesByProjectSession.clear(),pendingStateMutationsByProjectSession.clear(),pendingCheckoutMutationsByProject.clear(),completedCheckoutLockOwners.clear(),_test_exports.beforeTerminalClear=void 0,_test_exports.beforePrFeedbackTransitionLock=void 0,_test_exports.beforePrFeedbackTrackingSwitch=void 0,_test_exports.afterPrFeedbackTrackingSwitch=void 0,_test_exports.beforePrFeedbackTrackingPersist=void 0,_test_exports.beforeBoundedSwarmFileOpen=void 0,_test_exports.beforeSessionStateLockWrite=void 0,_test_exports.beforeCheckoutLockWrite=void 0,_test_exports.beforeSafeDirectoryCreate=void 0,_test_exports.beforeAtomicTempWrite=void 0,_test_exports.beforeAtomicRename=void 0,_test_exports.openCheckoutLock=openCheckoutLockFile,_test_exports.removeCheckoutLock=removeCheckoutLockFile,_test_exports.checkoutMutationActionTimeoutMs=CHECKOUT_MUTATION_ACTION_TIMEOUT_MS},beforeTerminalClear:void 0,beforePrFeedbackTransitionLock:void 0,beforePrFeedbackTrackingSwitch:void 0,afterPrFeedbackTrackingSwitch:void 0,beforePrFeedbackTrackingPersist:void 0,beforeBoundedSwarmFileOpen:void 0,beforeSessionStateLockWrite:void 0,beforeCheckoutLockWrite:void 0,beforeSafeDirectoryCreate:void 0,beforeAtomicTempWrite:void 0,beforeAtomicRename:void 0,openCheckoutLock:openCheckoutLockFile,removeCheckoutLock:removeCheckoutLockFile,checkoutMutationActionTimeoutMs:CHECKOUT_MUTATION_ACTION_TIMEOUT_MS,resolveCurrentGitHead,resolveCurrentGitHeadAsync,resolveCurrentUpstreamPushTarget,resolveCurrentUpstreamPushTargetAsync,resolveCurrentUpstreamRemoteRef,resolveExactRemoteBranchHead,resolveExactRemoteBranchHeadAsync,resolveCommitCountSince,resolveCommitCountSinceAsync,resolveIsWorkingTreeClean,resolveIsWorkingTreeCleanAsync,resolveIsExactSingleChildCommit,resolveIsExactSingleChildCommitAsync,resolvePrReviewDiffStats,resolvePrReviewDiffStatsAsync,resolvePrWorkflowRevisionDigest,resolveRemoteRefsContainingHead,resolveRemoteRefsContainingHeadAsync,parseCriticVerdict,isProcessAlive,isSafeStandaloneGitCommit,rename:fsp3.rename,nowMs:()=>Date.now()};PR_WORKFLOW_SHARED_CONTROLLER_TOOLS=new Set(["abort_pr_workflow","collect_lane_results","complete_pr_workflow","dispatch_lanes_async","prepare_pr_workflow_checkout"]),PR_REVIEW_CONTROLLER_TOOLS=new Set(["parse_lane_candidates","write_pr_review_artifact","write_pr_review_trigger_eval"]),PR_FEEDBACK_CONTROLLER_TOOLS=new Set(["prepare_pr_feedback_scope","run_pr_feedback_stage_a"]);PR_REVIEW_READ_ONLY_TOOL_NAMES=new Set(["ast_grep_search","codesearch","glob","grep","list","lsp","open","read","search","skill","tree","view","web_fetch","web_search","webfetch","websearch"]);PR_WORKFLOW_CD_PREFIX_PATTERN=/^cd\s+(?:\/d\s+)?(?:"[A-Za-z0-9 _.\\/:~+-]+"|'[A-Za-z0-9 _.\\/:~+-]+'|[A-Za-z0-9_.\\/:~+-]+)\s*&&\s*/i,PR_WORKFLOW_TRAILING_STDERR_MERGE_PATTERN=/\s+2>&1\s*$/,PR_WORKFLOW_GIT_DIR_OVERRIDE_PATTERN=/^[Gg][Ii][Tt](?: -C (?:"[^"]+"|'[^']+'|\S+))* (.+)$/,PR_WORKFLOW_GIT_HAS_DIR_OVERRIDE_PATTERN=/^[Gg][Ii][Tt] -C /;REVIEWER_CLASSIFICATIONS=new Set(["CONFIRMED","DISPROVED","UNVERIFIED","PRE_EXISTING"]),REVIEWER_EVIDENCE_TYPES=new Set(["STRUCTURALLY_PROVEN","EXECUTION_PROVEN","STATIC_TRACE_PROVEN","PLAUSIBLE_BUT_UNVERIFIED"]),REVIEW_SEVERITIES=new Set(["CRITICAL","HIGH","MEDIUM","LOW","INFO","NONE"]),CRITIC_STATUSES=new Set(["UPHELD","DOWNGRADED","DISPROVED","NEEDS_MORE_EVIDENCE"]),FEEDBACK_CLASSIFICATIONS=new Set(["CONFIRMED","PARTIAL","DISPROVED","PRE_EXISTING","NEEDS_MORE_EVIDENCE","NEEDS_USER_DECISION"]);PrWorkflowCheckoutMutationTimeoutError=class PrWorkflowCheckoutMutationTimeoutError extends Error{phase;code="PR_WORKFLOW_CHECKOUT_MUTATION_TIMEOUT";retryable=!1;constructor(phase){super(phase==="queue"?"BLOCKED: timed out waiting for the active PR workflow checkout mutation; the existing owner still holds serialization and must settle before retrying":"BLOCKED: PR workflow checkout mutation exceeded its execution deadline; serialization remains held until the in-flight action actually settles");this.phase=phase;this.name="PrWorkflowCheckoutMutationTimeoutError"}}});async function handleAbortPrWorkflowCommand(directory,args2,sessionID){let tokens=(args2??[]).filter((token)=>token.trim().length>0),modeToken=tokens[0]?.toUpperCase(),knownMode=modeToken&&KNOWN_MODES.has(modeToken)?modeToken:void 0,reasonStartIndex=knownMode?1:0,reason=tokens.slice(reasonStartIndex).join(" ").trim().slice(0,500)||void 0;if(modeToken&&!knownMode)return`Error: Unknown mode "${modeToken}". Expected PR_REVIEW or PR_FEEDBACK.
186
186
 
187
187
  ${USAGE}`;if(!sessionID?.trim())return`Error: abort-pr-workflow requires an active sessionID.
188
188
 
@@ -792,11 +792,12 @@ ${stderr}`:stderr;if(output.length>maxLength)output=`${output.slice(0,maxLength)
792
792
  ... (child output truncated to bounded limit)`;return output}function extractFileLineReferences(output){let lines=[],patterns=[/([A-Za-z]:[\\/])?[^\s:]+\.(ts|tsx|js|jsx):(\d+):(\d+)/g,/(?:error|Error|FAIL|Failed)[:\s]+([^\s]+\.(ts|tsx|js|jsx)?:?:\d+)/gi,/FAIL\s+([^\s]+\.(test|spec)\.(ts|tsx|js|jsx))/gi];for(let pattern of patterns){let matches=Array.from(output.matchAll(pattern));for(let match of matches)if(match[0])lines.push(match[0])}return Array.from(new Set(lines))}async function handleCiSimulateCommand(directory,args2){let prRef=args2[0]??await getCurrentBranchOrRef(directory);if(!isSafeGitRef(prRef))return"CI simulation failed: PR ref must be a safe git branch or commit reference.";let lines=[];lines.push("# CI Simulation Report"),lines.push(""),lines.push(`PR ref: **${prRef}**`),lines.push(`Started: ${new Date().toISOString()}`),lines.push("");let worktreePath,result={success:!1,worktreePath:"",steps:[]};try{let baseBranch=_internals40.getDefaultBaseBranch(directory);if(!isSafeGitRef(baseBranch))throw Error("Detected default branch is not a safe git reference.");lines.push("## Setup"),lines.push(""),lines.push(`Creating temporary worktree from ${baseBranch}...`),worktreePath=await setupWorktree(directory,prRef,baseBranch,(createdPath)=>{worktreePath=createdPath}),result.worktreePath=worktreePath,lines.push(`Worktree: \`${worktreePath}\``),lines.push("");let lastCommit=(await runGit5(["log","--oneline","-1","--format=%s"],worktreePath)).stdout.trim();lines.push(`Last commit in worktree: \`${lastCommit}\``),lines.push(""),lines.push("## Validation Suite"),lines.push(""),result.steps=await runValidationSuite(worktreePath);for(let step of result.steps){let status=step.exitCode===0?"✅ PASS":"❌ FAIL";if(lines.push(`### ${status}: ${step.step}`),lines.push(""),lines.push(`Command: \`${step.command}\``),lines.push(`Duration: ${(step.durationMs/1000).toFixed(1)}s`),step.exitCode!==0){lines.push(`Exit code: ${step.exitCode}`);let fileRefs=extractFileLineReferences(`${step.stdout}
793
793
  ${step.stderr}`);if(fileRefs.length>0){lines.push(""),lines.push("**Failure locations:**");for(let ref of fileRefs.slice(0,20))lines.push(` - \`${ref}\``)}lines.push(""),lines.push("**Output:**"),lines.push("```"),lines.push(formatStepOutput(step.stdout,step.stderr,step.outputTruncated)),lines.push("```")}lines.push("")}let allPassed=result.steps.every((s)=>s.exitCode===0);result.success=allPassed,lines.push("## Summary"),lines.push("");let passed=result.steps.filter((s)=>s.exitCode===0).length,failed=result.steps.filter((s)=>s.exitCode!==0).length;if(lines.push(`Validation: ${passed}/${result.steps.length} steps passed, ${failed} failed`),lines.push(""),allPassed)lines.push("✅ **All checks passed — CI simulation succeeded**");else{lines.push("❌ **CI simulation failed — these failures would cause a merge-queue kick-out**"),lines.push(""),lines.push("To reproduce locally, run in the worktree:"),lines.push("```bash"),lines.push(`cd "${worktreePath}"`);for(let step of result.steps.filter((s)=>s.exitCode!==0))lines.push(`# ${step.step}: ${step.command}`);lines.push("```")}}catch(err){let errMsg=err instanceof Error?err.message:String(err);result.error=errMsg,lines.push(""),lines.push("## Error"),lines.push(""),lines.push("```"),lines.push(errMsg),lines.push("```")}finally{if(worktreePath)lines.push(""),lines.push("---"),lines.push(""),lines.push("*Cleaning up temporary worktree...*"),await cleanupWorktree(worktreePath,directory),lines.push(`Worktree removed: \`${worktreePath}\``)}return lines.join(`
794
794
  `)}var GIT_TIMEOUT_MS5=30000,VALIDATION_TIMEOUT_MS=300000,OUTPUT_LIMIT_BYTES=12000,_internals40;var init_ci_simulate=__esm(()=>{init_branch();init_external_tool_runner();init_logger();_internals40={runExternalTool,getDefaultBaseBranch,platform:process.platform,osTmpdir:()=>os14.tmpdir(),fs:{existsSync:fs39.existsSync,rmSync:fs39.rmSync}}});async function handleClarifyCommand(_directory,args2){let description=args2.join(" ").trim();if(description)return`[MODE: CLARIFY-SPEC] ${description}`;return"[MODE: CLARIFY-SPEC] Please enter MODE: CLARIFY-SPEC and clarify the existing spec."}function parseModelString(model){if(!model||!model.trim())return;let separator=model.indexOf("/");if(separator<=0||separator===model.length-1)throw Error(`fallback model must use provider/model syntax, got: "${model}"`);return{providerID:model.slice(0,separator),modelID:model.slice(separator+1)}}async function dispatchWithModelFallback(opts){let maxRetries=Math.max(0,opts.maxTransientRetriesPerModel??1),backoff=opts.backoffMs??defaultBackoff,sleep2=opts.sleep??defaultSleep,attempts=0,lastError,anyDispatched=!1;for(let fallbackIndex=0;;fallbackIndex++){let model,modelUsed;if(fallbackIndex>0){let fbStr=opts.resolveFallback(fallbackIndex);if(fbStr===null)break;try{model=parseModelString(fbStr)}catch{continue}modelUsed=fbStr,opts.onFallback?.({toModel:fbStr,fallbackIndex})}for(let retry=0;retry<=maxRetries;retry++){attempts++,anyDispatched=!0;try{return{result:await opts.dispatch(model),modelUsed,fallbackIndex,attempts}}catch(err){if(lastError=err,opts.classify(err)==="permanent")throw err;if(retry<maxRetries)await sleep2(backoff(retry+1))}}}throw lastError??Error(anyDispatched?"dispatchWithModelFallback: all models exhausted":"dispatchWithModelFallback: no dispatch attempted")}var defaultBackoff=(retryAttempt)=>2**(retryAttempt-1)*1000,defaultSleep=(ms)=>new Promise((resolve35)=>setTimeout(resolve35,ms));function isAbortError(err){if(typeof err!=="object"||err===null)return!1;let name=err.name;return name==="AbortError"||name==="TimeoutError"}var exports_curator_llm_factory={};__export(exports_curator_llm_factory,{createCuratorLLMDelegate:()=>createCuratorLLMDelegate});function resolveCuratorAgentName(mode,sessionId){let suffix={init:"curator_init",phase:"curator_phase",postmortem:"curator_postmortem",consolidation:"curator_consolidation"}[mode],registeredNames={init:swarmState.curatorInitAgentNames,phase:swarmState.curatorPhaseAgentNames,postmortem:swarmState.curatorPostmortemAgentNames,consolidation:swarmState.curatorConsolidationAgentNames}[mode];if(registeredNames.length===1)return registeredNames[0];if(registeredNames.length===0)return suffix;let prefixMap=new Map;for(let name of registeredNames){let prefix=name.endsWith(suffix)?name.slice(0,name.length-suffix.length):"";prefixMap.set(prefix,name)}let matchForAgent=(agentName)=>{let bestPrefix="",bestName="";for(let[prefix,name]of prefixMap)if(prefix&&agentName.startsWith(prefix)){if(prefix.length>bestPrefix.length)bestPrefix=prefix,bestName=name}return bestName};if(sessionId){let callingAgent=swarmState.activeAgent.get(sessionId);if(callingAgent){let match=matchForAgent(callingAgent);if(match)return match;let defaultCurator=prefixMap.get("");if(defaultCurator)return defaultCurator}}for(let activeAgentName of swarmState.activeAgent.values()){let match=matchForAgent(activeAgentName);if(match)return match}return prefixMap.get("")??registeredNames[0]}function createCuratorLLMDelegate(directory,mode="init",sessionId){let client=swarmState.opencodeClient;if(!client)return;return async(_systemPrompt,userInput,signal)=>{let ephemeralSessionId,cleanup=()=>{if(ephemeralSessionId){let id=ephemeralSessionId;ephemeralSessionId=void 0,client.session.delete({path:{id}}).catch(()=>{})}};if(signal?.aborted)throw Error("CURATOR_LLM_TIMEOUT");let sdkOpts=signal?{signal}:{};try{let createResult=await client.session.create({...sessionId?{body:{parentID:sessionId,title:`curator_${mode} background`}}:{},query:{directory},...sdkOpts});if(!createResult.data)throw Error(`Failed to create curator session: ${JSON.stringify(createResult.error)}`);if(ephemeralSessionId=createResult.data.id,signal?.aborted)throw Error("CURATOR_LLM_TIMEOUT");let agentName=resolveCuratorAgentName(mode,sessionId),baseRole=stripKnownSwarmPrefix(agentName),swarmId=baseRole!==agentName?agentName.slice(0,agentName.length-baseRole.length-1):void 0,swarmAgents=getSwarmAgents(swarmId),promptSessionId=ephemeralSessionId;return(await dispatchWithModelFallback({dispatch:async(model)=>{let promptResult=await client.session.prompt({path:{id:promptSessionId},body:{agent:agentName,...model?{model}:{},tools:{write:!1,edit:!1,patch:!1},parts:[{type:"text",text:userInput}]},...sdkOpts});if(!promptResult.data)throw Error(`Curator LLM prompt failed: ${JSON.stringify(promptResult.error)}`);return promptResult.data},resolveFallback:(index)=>resolveFallbackModel(baseRole,index,swarmAgents),maxTransientRetriesPerModel:0,classify:(err)=>{if(isAbortError(err))return"permanent";let msg=err instanceof Error?err.message:String(err);return isTransientProviderError(msg)?"transient":"permanent"},onFallback:({toModel})=>{if(sessionId)telemetry.modelFallback(sessionId,agentName,swarmAgents?.[baseRole]?.model??"default",toModel,"transient_model_error")}})).result.parts.filter((p)=>p.type==="text").map((p)=>p.text).join(`
795
- `)}catch(err){if(isAbortError(err))throw Error("CURATOR_LLM_TIMEOUT");throw err}finally{cleanup()}}}var init_curator_llm_factory=__esm(()=>{init_agents2();init_schema();init_state2();init_telemetry();init_provider_error_classification()});import*as os15 from"node:os";import*as path75 from"node:path";function resolveHiveDataDir(){let platform=process.platform,home=process.env.HOME||os15.homedir();if(platform==="win32")return path75.join(process.env.LOCALAPPDATA||path75.join(home,"AppData","Local"),"opencode-swarm","Data");if(platform==="darwin")return path75.join(home,"Library","Application Support","opencode-swarm");return path75.join(process.env.XDG_DATA_HOME||path75.join(home,".local","share"),"opencode-swarm")}function resolveHiveKnowledgePath(){return path75.join(resolveHiveDataDir(),"shared-learnings.jsonl")}function resolveHiveRejectedPath(){return path75.join(resolveHiveDataDir(),"shared-learnings-rejected.jsonl")}function resolveHiveEventsPath(){return path75.join(resolveHiveDataDir(),"shared-knowledge-events.jsonl")}var init_hive_paths=()=>{};function isActiveSwarmKnowledgeEntry(entry){return isActiveStatus(entry.status)}function findActiveSwarmNearDuplicate(lesson,entries,threshold){return findNearDuplicate(lesson,entries.filter(isActiveSwarmKnowledgeEntry),threshold)}function distinctPhaseCount(records){let phases=new Set;for(let record3 of records??[])if(Number.isInteger(record3.phase_number))phases.add(record3.phase_number);return phases.size}function reinforceSwarmKnowledgeEntry(entry,confirmation){if(!isActiveSwarmKnowledgeEntry(entry))return{entryId:entry.id,reinforced:!1,reason:"inactive"};if((entry.confirmed_by??[]).some((record3)=>record3.phase_number===confirmation.phase_number))return{entryId:entry.id,reinforced:!1,reason:"already_confirmed_phase"};return entry.confirmed_by=[...entry.confirmed_by??[],confirmation],entry.updated_at=confirmation.confirmed_at,entry.phases_alive=0,entry.confidence=computeConfidence(distinctPhaseCount(entry.confirmed_by),entry.auto_generated??!1),{entryId:entry.id,reinforced:!0,reason:"reinforced"}}var init_knowledge_reinforcement=__esm(()=>{init_knowledge_store();init_knowledge_types()});var exports_knowledge_events={};__export(exports_knowledge_events,{resolveLegacyApplicationLogPath:()=>resolveLegacyApplicationLogPath,resolveKnowledgeEventsPath:()=>resolveKnowledgeEventsPath,resolveKnowledgeCounterBaselinePath:()=>resolveKnowledgeCounterBaselinePath,resolveHiveEventsPath:()=>resolveHiveEventsPath2,recordKnowledgeEvent:()=>recordKnowledgeEvent,recordHiveKnowledgeEvent:()=>recordHiveKnowledgeEvent,recomputeCounters:()=>recomputeCounters,readLegacyApplicationRecords:()=>readLegacyApplicationRecords,readKnowledgeEvents:()=>readKnowledgeEvents,readKnowledgeCounterRollups:()=>readKnowledgeCounterRollups,readHiveKnowledgeEvents:()=>readHiveKnowledgeEvents,newTraceId:()=>newTraceId,newEventId:()=>newEventId,effectiveRetrievalOutcomes:()=>effectiveRetrievalOutcomes,countViolationsInWindow:()=>countViolationsInWindow,countEntryViolationsInWindow:()=>countEntryViolationsInWindow,countEntryContradictionsInWindow:()=>countEntryContradictionsInWindow,countEmptyTraceTerminals:()=>countEmptyTraceTerminals,applyKnowledgeVerdictFeedback:()=>applyKnowledgeVerdictFeedback,appendKnowledgeEvent:()=>appendKnowledgeEvent,appendHiveKnowledgeEvent:()=>appendHiveKnowledgeEvent,_internals:()=>_internals41,RECEIPT_EVENT_TYPES:()=>RECEIPT_EVENT_TYPES,MAX_VIOLATION_TIMESTAMPS:()=>MAX_VIOLATION_TIMESTAMPS,MAX_EVENT_LOG_ENTRIES:()=>MAX_EVENT_LOG_ENTRIES,KNOWLEDGE_EVENT_SCHEMA_VERSION:()=>KNOWLEDGE_EVENT_SCHEMA_VERSION});import{randomUUID as randomUUID7}from"node:crypto";import{existsSync as existsSync29}from"node:fs";import{appendFile as appendFile6,mkdir as mkdir12,readFile as readFile15,stat as stat9}from"node:fs/promises";import*as path76 from"node:path";function resolveKnowledgeEventsPath(directory){return path76.join(resolveKnowledgeStoreDir(directory),"knowledge-events.jsonl")}function resolveKnowledgeCounterBaselinePath(directory){return path76.join(resolveKnowledgeStoreDir(directory),"knowledge-counter-baseline.json")}function resolveLegacyApplicationLogPath(directory){return path76.join(resolveKnowledgeStoreDir(directory),"knowledge-application.jsonl")}function newTraceId(){return randomUUID7()}function newEventId(){return randomUUID7()}function withDefaults(event){return{schema_version:KNOWLEDGE_EVENT_SCHEMA_VERSION,...event,event_id:event.event_id||newEventId(),timestamp:event.timestamp||new Date().toISOString()}}async function appendKnowledgeEvent(directory,event){let populated=withDefaults(event),filePath=resolveKnowledgeEventsPath(directory),dirPath=path76.dirname(filePath);await mkdir12(dirPath,{recursive:!0});let release;try{release=await import_proper_lockfile4.default.lock(dirPath,{retries:{retries:200,minTimeout:10,maxTimeout:100}}),await appendFile6(filePath,`${JSON.stringify(populated)}
795
+ `)}catch(err){if(isAbortError(err))throw Error("CURATOR_LLM_TIMEOUT");throw err}finally{cleanup()}}}var init_curator_llm_factory=__esm(()=>{init_agents2();init_schema();init_state2();init_telemetry();init_provider_error_classification()});import*as os15 from"node:os";import*as path75 from"node:path";function resolveHiveDataDir(){let platform=process.platform,home=process.env.HOME||os15.homedir();if(platform==="win32")return path75.join(process.env.LOCALAPPDATA||path75.join(home,"AppData","Local"),"opencode-swarm","Data");if(platform==="darwin")return path75.join(home,"Library","Application Support","opencode-swarm");return path75.join(process.env.XDG_DATA_HOME||path75.join(home,".local","share"),"opencode-swarm")}function resolveHiveKnowledgePath(){return path75.join(resolveHiveDataDir(),"shared-learnings.jsonl")}function resolveHiveRejectedPath(){return path75.join(resolveHiveDataDir(),"shared-learnings-rejected.jsonl")}function resolveHiveEventsPath(){return path75.join(resolveHiveDataDir(),"shared-knowledge-events.jsonl")}var init_hive_paths=()=>{};function isActiveSwarmKnowledgeEntry(entry){return isActiveStatus(entry.status)}function findActiveSwarmNearDuplicate(lesson,entries,threshold){return findNearDuplicate(lesson,entries.filter(isActiveSwarmKnowledgeEntry),threshold)}function distinctPhaseCount(records){let phases=new Set;for(let record3 of records??[])if(Number.isInteger(record3.phase_number))phases.add(record3.phase_number);return phases.size}function reinforceSwarmKnowledgeEntry(entry,confirmation){if(!isActiveSwarmKnowledgeEntry(entry))return{entryId:entry.id,reinforced:!1,reason:"inactive"};if((entry.confirmed_by??[]).some((record3)=>record3.phase_number===confirmation.phase_number))return{entryId:entry.id,reinforced:!1,reason:"already_confirmed_phase"};return entry.confirmed_by=[...entry.confirmed_by??[],confirmation],entry.updated_at=confirmation.confirmed_at,entry.phases_alive=0,entry.confidence=computeConfidence(distinctPhaseCount(entry.confirmed_by),entry.auto_generated??!1),{entryId:entry.id,reinforced:!0,reason:"reinforced"}}var init_knowledge_reinforcement=__esm(()=>{init_knowledge_store();init_knowledge_types()});var exports_knowledge_events={};__export(exports_knowledge_events,{resolveLegacyApplicationLogPath:()=>resolveLegacyApplicationLogPath,resolveKnowledgeEventsPath:()=>resolveKnowledgeEventsPath,resolveKnowledgeCounterBaselinePath:()=>resolveKnowledgeCounterBaselinePath,resolveHiveEventsPath:()=>resolveHiveEventsPath2,recordKnowledgeEventsBatch:()=>recordKnowledgeEventsBatch,recordKnowledgeEvent:()=>recordKnowledgeEvent,recordHiveKnowledgeEvent:()=>recordHiveKnowledgeEvent,recomputeCounters:()=>recomputeCounters,readLegacyApplicationRecords:()=>readLegacyApplicationRecords,readKnowledgeEvents:()=>readKnowledgeEvents,readKnowledgeCounterRollups:()=>readKnowledgeCounterRollups,readHiveKnowledgeEvents:()=>readHiveKnowledgeEvents,newTraceId:()=>newTraceId,newEventId:()=>newEventId,effectiveRetrievalOutcomes:()=>effectiveRetrievalOutcomes,countViolationsInWindow:()=>countViolationsInWindow,countEntryViolationsInWindow:()=>countEntryViolationsInWindow,countEntryContradictionsInWindow:()=>countEntryContradictionsInWindow,countEmptyTraceTerminals:()=>countEmptyTraceTerminals,applyKnowledgeVerdictFeedback:()=>applyKnowledgeVerdictFeedback,appendKnowledgeEventsBatch:()=>appendKnowledgeEventsBatch,appendKnowledgeEvent:()=>appendKnowledgeEvent,appendHiveKnowledgeEvent:()=>appendHiveKnowledgeEvent,_internals:()=>_internals41,RECEIPT_EVENT_TYPES:()=>RECEIPT_EVENT_TYPES,MAX_VIOLATION_TIMESTAMPS:()=>MAX_VIOLATION_TIMESTAMPS,MAX_EVENT_LOG_ENTRIES:()=>MAX_EVENT_LOG_ENTRIES,KNOWLEDGE_EVENT_SCHEMA_VERSION:()=>KNOWLEDGE_EVENT_SCHEMA_VERSION});import{randomUUID as randomUUID7}from"node:crypto";import{existsSync as existsSync29}from"node:fs";import{appendFile as appendFile6,mkdir as mkdir12,readFile as readFile15,stat as stat9}from"node:fs/promises";import*as path76 from"node:path";function resolveKnowledgeEventsPath(directory){return path76.join(resolveKnowledgeStoreDir(directory),"knowledge-events.jsonl")}function resolveKnowledgeCounterBaselinePath(directory){return path76.join(resolveKnowledgeStoreDir(directory),"knowledge-counter-baseline.json")}function resolveLegacyApplicationLogPath(directory){return path76.join(resolveKnowledgeStoreDir(directory),"knowledge-application.jsonl")}function newTraceId(){return randomUUID7()}function newEventId(){return randomUUID7()}function withDefaults(event){return{schema_version:KNOWLEDGE_EVENT_SCHEMA_VERSION,...event,event_id:event.event_id||newEventId(),timestamp:event.timestamp||new Date().toISOString()}}async function appendKnowledgeEvent(directory,event){let[populated]=await appendKnowledgeEventsBatch(directory,[event]);return populated}async function appendKnowledgeEventsBatch(directory,events){if(events.length===0)return[];let populated=events.map(withDefaults),filePath=resolveKnowledgeEventsPath(directory),dirPath=path76.dirname(filePath);await mkdir12(dirPath,{recursive:!0});let release;try{release=await import_proper_lockfile4.default.lock(dirPath,{retries:{retries:200,minTimeout:10,maxTimeout:100}}),await appendFile6(filePath,`${populated.map((e)=>JSON.stringify(e)).join(`
796
+ `)}
796
797
  `,"utf-8");try{let lines=(await readFile15(filePath,"utf-8")).split(`
797
798
  `).filter((line)=>line.trim().length>0);if(lines.length>MAX_EVENT_LOG_ENTRIES){let evicted=lines.slice(0,lines.length-MAX_EVENT_LOG_ENTRIES),trimmed=lines.slice(lines.length-MAX_EVENT_LOG_ENTRIES);await foldEvictedEventsIntoBaseline(directory,evicted,filePath),await atomicWriteFile(filePath,`${trimmed.join(`
798
799
  `)}
799
- `)}}catch(err){warn(`[knowledge-events] local cap trim failed (non-fatal): ${err instanceof Error?err.message:String(err)}`)}}finally{if(release)await release().catch(()=>{})}return populated}async function recordKnowledgeEvent(directory,event){try{return await appendKnowledgeEvent(directory,event)}catch(err){return warn(`[knowledge-events] recordKnowledgeEvent failed: ${err instanceof Error?err.message:String(err)}`),null}}async function appendHiveKnowledgeEvent(event){let populated=withDefaults(event),filePath=resolveHiveEventsPath2(),dirPath=path76.dirname(filePath);await mkdir12(dirPath,{recursive:!0});let release;try{release=await import_proper_lockfile4.default.lock(dirPath,{retries:{retries:200,minTimeout:10,maxTimeout:100},stale:5000}),await appendFile6(filePath,`${JSON.stringify(populated)}
800
+ `)}}catch(err){warn(`[knowledge-events] local cap trim failed (non-fatal): ${err instanceof Error?err.message:String(err)}`)}}finally{if(release)await release().catch(()=>{})}return populated}async function recordKnowledgeEvent(directory,event){try{return await appendKnowledgeEvent(directory,event)}catch(err){return warn(`[knowledge-events] recordKnowledgeEvent failed: ${err instanceof Error?err.message:String(err)}`),null}}async function recordKnowledgeEventsBatch(directory,events){try{return await appendKnowledgeEventsBatch(directory,events)}catch(err){return warn(`[knowledge-events] recordKnowledgeEventsBatch failed: ${err instanceof Error?err.message:String(err)}`),null}}async function appendHiveKnowledgeEvent(event){let populated=withDefaults(event),filePath=resolveHiveEventsPath2(),dirPath=path76.dirname(filePath);await mkdir12(dirPath,{recursive:!0});let release;try{release=await import_proper_lockfile4.default.lock(dirPath,{retries:{retries:200,minTimeout:10,maxTimeout:100},stale:5000}),await appendFile6(filePath,`${JSON.stringify(populated)}
800
801
  `,"utf-8");try{let lines=(await readFile15(filePath,"utf-8")).split(`
801
802
  `).filter((line)=>line.trim().length>0);if(lines.length>MAX_EVENT_LOG_ENTRIES){let trimmed=lines.slice(lines.length-MAX_EVENT_LOG_ENTRIES);await atomicWriteFile(filePath,`${trimmed.join(`
802
803
  `)}
@@ -804,7 +805,7 @@ ${step.stderr}`);if(fileRefs.length>0){lines.push(""),lines.push("**Failure loca
804
805
  `)){if(out.length>=max)break;let trimmed=line.trim();if(!trimmed)continue;try{out.push(JSON.parse(trimmed))}catch{warn(`[knowledge-events] Skipping corrupted JSONL line in ${filePath}: ${trimmed.slice(0,80)}`)}}return out}async function readHiveKnowledgeEvents(){let filePath=resolveHiveEventsPath2();if(!existsSync29(filePath))return[];let content=await readFile15(filePath,"utf-8");return parseEventLines(content.split(`
805
806
  `),filePath)}async function readLegacyApplicationRecords(directory){let filePath=resolveLegacyApplicationLogPath(directory);if(!existsSync29(filePath))return[];let content=await readFile15(filePath,"utf-8"),out=[];for(let line of content.split(`
806
807
  `)){let trimmed=line.trim();if(!trimmed)continue;try{out.push(JSON.parse(trimmed))}catch{warn(`[knowledge-events] Skipping corrupted JSONL line in ${filePath}: ${trimmed.slice(0,80)}`)}}return out}function emptyRollup(){return{shown_count:0,acknowledged_count:0,applied_explicit_count:0,ignored_count:0,violated_count:0,contradicted_count:0,n_a_count:0,succeeded_after_shown_count:0,failed_after_shown_count:0,partial_after_shown_count:0,violation_timestamps:[]}}function cloneRollup(input){return{...emptyRollup(),...input,violation_timestamps:[...input.violation_timestamps??[]]}}function cloneRollupMap(input){let out=new Map;for(let[id,rollup]of input)out.set(id,cloneRollup(rollup));return out}function normalizeRollupTimestamps(rollup){if(rollup.violation_timestamps.length>1)rollup.violation_timestamps.sort((a,b)=>a<b?1:a>b?-1:0);if(rollup.violation_timestamps.length>MAX_VIOLATION_TIMESTAMPS)rollup.violation_timestamps=rollup.violation_timestamps.slice(0,MAX_VIOLATION_TIMESTAMPS);return rollup}function mergeRollupInto(target,source){if(target.shown_count+=source.shown_count??0,target.acknowledged_count+=source.acknowledged_count??0,target.applied_explicit_count+=source.applied_explicit_count??0,target.ignored_count+=source.ignored_count??0,target.violated_count+=source.violated_count??0,target.contradicted_count+=source.contradicted_count??0,target.n_a_count+=source.n_a_count??0,target.succeeded_after_shown_count+=source.succeeded_after_shown_count??0,target.failed_after_shown_count+=source.failed_after_shown_count??0,target.partial_after_shown_count+=source.partial_after_shown_count??0,source.last_applied_at)target.last_applied_at=maxIso(target.last_applied_at,source.last_applied_at);if(source.last_acknowledged_at)target.last_acknowledged_at=maxIso(target.last_acknowledged_at,source.last_acknowledged_at);target.violation_timestamps.push(...source.violation_timestamps??[]),normalizeRollupTimestamps(target)}function get(map3,id){let r=map3.get(id);if(!r)r=emptyRollup(),map3.set(id,r);return r}function maxIso(current,candidate){if(!current)return candidate;return candidate>current?candidate:current}async function readCounterBaseline(directory){let filePath=resolveKnowledgeCounterBaselinePath(directory);if(!existsSync29(filePath))return new Map;let raw;try{raw=JSON.parse(await readFile15(filePath,"utf-8"))}catch(err){return warn(`[knowledge-events] corrupted counter baseline at ${filePath}; ignoring folded baseline and replaying live events only: ${err instanceof Error?err.message:String(err)}`),new Map}let map3=new Map;for(let[id,rollup]of Object.entries(raw))map3.set(id,normalizeRollupTimestamps(cloneRollup(rollup)));return map3}async function writeCounterBaseline(directory,baseline){let filePath=resolveKnowledgeCounterBaselinePath(directory),out={};for(let[id,rollup]of[...baseline.entries()].sort(([a],[b])=>a.localeCompare(b)))out[id]=normalizeRollupTimestamps(cloneRollup(rollup));await atomicWriteFile(filePath,`${JSON.stringify(out,null,2)}
807
- `)}async function statCacheKey(filePath){try{let fileStat=await stat9(filePath);return`${fileStat.mtimeMs}:${fileStat.ctimeMs}:${fileStat.size}`}catch(err){if(err?.code==="ENOENT")return"missing";throw err}}async function buildCounterRollupCacheKey(directory){let[eventsKey,legacyKey,baselineKey]=await Promise.all([statCacheKey(resolveKnowledgeEventsPath(directory)),statCacheKey(resolveLegacyApplicationLogPath(directory)),statCacheKey(resolveKnowledgeCounterBaselinePath(directory))]);return`${eventsKey}|${legacyKey}|${baselineKey}`}function setCounterRollupCache(directory,key,rollups){if(counterRollupCache.has(directory))counterRollupCache.delete(directory);counterRollupCache.set(directory,{key,rollups:cloneRollupMap(rollups)});while(counterRollupCache.size>MAX_COUNTER_ROLLUP_CACHE_DIRS){let oldestKey=counterRollupCache.keys().next().value;if(oldestKey===void 0)break;counterRollupCache.delete(oldestKey)}}function parseEventLines(lines,filePath){let out=[];for(let line of lines){let trimmed=line.trim();if(!trimmed)continue;try{out.push(JSON.parse(trimmed))}catch{warn(`[knowledge-events] Skipping corrupted JSONL line in ${filePath}: ${trimmed.slice(0,80)}`)}}return out}async function foldEvictedEventsIntoBaseline(directory,evictedLines,filePath){let evictedEvents=parseEventLines(evictedLines,filePath);if(evictedEvents.length===0)return;let baseline=await readCounterBaseline(directory);for(let[id,rollup]of recomputeCounters(evictedEvents))mergeRollupInto(get(baseline,id),rollup);await writeCounterBaseline(directory,baseline)}function recomputeCounters(events,legacyRecords=[],baseline=new Map){let map3=new Map,retrievedIds=new Set;for(let[id,rollup]of baseline)if(map3.set(id,cloneRollup(rollup)),(rollup.shown_count??0)>0)retrievedIds.add(id);for(let e of events)switch(e.type){case"retrieved":{for(let id of e.result_ids)retrievedIds.add(id),get(map3,id).shown_count+=1;break}case"acknowledged":{if(!e.knowledge_id)break;let r=get(map3,e.knowledge_id);r.acknowledged_count+=1,r.last_acknowledged_at=maxIso(r.last_acknowledged_at,e.timestamp);break}case"applied":{if(!e.knowledge_id)break;let r=get(map3,e.knowledge_id);r.applied_explicit_count+=1,r.last_applied_at=maxIso(r.last_applied_at,e.timestamp);break}case"ignored":if(!e.knowledge_id)break;get(map3,e.knowledge_id).ignored_count+=1;break;case"violated":{if(!e.knowledge_id)break;let r=get(map3,e.knowledge_id);r.violated_count+=1,r.violation_timestamps.push(e.timestamp);break}case"contradicted":if(!e.knowledge_id)break;get(map3,e.knowledge_id).contradicted_count+=1;break;case"n_a":if(!e.knowledge_id)break;get(map3,e.knowledge_id).n_a_count+=1;break;case"no_relevant":break;case"outcome":{if(!e.knowledge_id)break;let r=get(map3,e.knowledge_id);if(e.outcome==="success")r.succeeded_after_shown_count+=1;else if(e.outcome==="failure")r.failed_after_shown_count+=1;else if(e.outcome==="partial")r.partial_after_shown_count+=1;break}}for(let rec of legacyRecords){let r=get(map3,rec.knowledgeId);switch(rec.result){case"shown":if(!retrievedIds.has(rec.knowledgeId))r.shown_count+=1;break;case"acknowledged":r.acknowledged_count+=1,r.last_acknowledged_at=maxIso(r.last_acknowledged_at,rec.timestamp);break;case"applied":r.applied_explicit_count+=1,r.last_applied_at=maxIso(r.last_applied_at,rec.timestamp);break;case"ignored":r.ignored_count+=1;break;case"violated":r.violated_count+=1,r.violation_timestamps.push(rec.timestamp);break}}for(let r of map3.values())normalizeRollupTimestamps(r);return map3}function countViolationsInWindow(timestamps,windowDays,now=new Date){let cutoff=now.getTime()-windowDays*24*60*60*1000,count=0;for(let ts of timestamps){let t=Date.parse(ts);if(!Number.isNaN(t)&&t>=cutoff)count+=1}return count}function countEmptyTraceTerminals(events){let n=0;for(let e of events)if(e.type==="no_relevant")n+=1;return n}async function countEntryViolationsInWindow(directory,entryId,windowDays,now=new Date){try{let cutoff=now.getTime()-windowDays*24*60*60*1000,[events,legacyRecords]=await Promise.all([readKnowledgeEvents(directory),readLegacyApplicationRecords(directory)]),count=0;for(let e of events){if(e.type!=="violated"||e.knowledge_id!==entryId)continue;let t=Date.parse(e.timestamp);if(!Number.isNaN(t)&&t>=cutoff)count+=1}for(let rec of legacyRecords){if(rec.result!=="violated"||rec.knowledgeId!==entryId)continue;let t=Date.parse(rec.timestamp);if(!Number.isNaN(t)&&t>=cutoff)count+=1}return count}catch{return 0}}async function countEntryContradictionsInWindow(directory,entryId,windowDays,now=new Date){try{let cutoff=now.getTime()-windowDays*24*60*60*1000,events=await readKnowledgeEvents(directory),count=0;for(let e of events){if(e.type!=="contradicted"||e.knowledge_id!==entryId)continue;let t=Date.parse(e.timestamp);if(!Number.isNaN(t)&&t>=cutoff)count+=1}return count}catch{return 0}}async function readKnowledgeCounterRollups(directory){try{let cacheKey=await buildCounterRollupCacheKey(directory),cached3=counterRollupCache.get(directory);if(cached3?.key===cacheKey)return counterRollupCache.delete(directory),counterRollupCache.set(directory,cached3),cloneRollupMap(cached3.rollups);let[events,legacyRecords,baseline]=await Promise.all([readKnowledgeEvents(directory),readLegacyApplicationRecords(directory),readCounterBaseline(directory)]),rollups=recomputeCounters(events,legacyRecords,baseline);return setCounterRollupCache(directory,cacheKey,rollups),cloneRollupMap(rollups)}catch(err){return warn(`[knowledge-events] readKnowledgeCounterRollups failed: ${err instanceof Error?err.message:String(err)}`),new Map}}function effectiveRetrievalOutcomes(stored,rollup){let base=stored??{applied_count:0,succeeded_after_count:0,failed_after_count:0};if(!rollup)return base;let{n_a_count:_na,...rollupWithoutNa}=rollup;return{...base,...rollupWithoutNa,succeeded_after_shown_count:(base.succeeded_after_shown_count??0)+(rollup.succeeded_after_shown_count??0),failed_after_shown_count:(base.failed_after_shown_count??0)+(rollup.failed_after_shown_count??0)}}async function applyKnowledgeVerdictFeedback(directory,options){try{let events=await readKnowledgeEvents(directory),markerIndex=options?.sinceTimestamp&&options.sinceEventId?events.findIndex((e)=>e.timestamp===options.sinceTimestamp&&e.event_id===options.sinceEventId):-1,actionable=events.filter((e,index)=>{if(e.type!=="applied"&&e.type!=="violated"&&e.type!=="ignored")return!1;if(options?.sinceTimestamp&&e.timestamp<options.sinceTimestamp)return!1;if(options?.sinceTimestamp&&e.timestamp===options.sinceTimestamp){if(!options.sinceEventId)return!1;if(markerIndex<0)return!1;return index>markerIndex}return!0});if(actionable.length===0)return{processed:0,bumps:0};let groups=new Map,lastProcessedTimestamp,lastProcessedEventId;for(let event of actionable){if(typeof event.timestamp==="string"&&(!lastProcessedTimestamp||event.timestamp>=lastProcessedTimestamp))lastProcessedTimestamp=event.timestamp,lastProcessedEventId=event.event_id;let kid=event.knowledge_id;if(!kid)continue;let g=groups.get(kid)??{applied:0,violated:0,ignored:0};if(event.type==="applied")g.applied++;else if(event.type==="violated")g.violated++;else if(event.type==="ignored")g.ignored++;groups.set(kid,g)}let deltas=[];for(let[id,counts]of groups){let positives=counts.applied,negatives=counts.violated+counts.ignored;if(positives===0&&negatives===0)continue;let delta=positives>negatives?VERDICT_CONFIDENCE_BOOST:-VERDICT_CONFIDENCE_DECAY;deltas.push({id,delta})}if(deltas.length>0){let{bumpKnowledgeConfidenceBatch}=await Promise.resolve().then(() => (init_knowledge_store(),exports_knowledge_store));await bumpKnowledgeConfidenceBatch(directory,deltas,options?.floorOptions)}return{processed:groups.size,bumps:deltas.length,lastProcessedTimestamp,lastProcessedEventId}}catch(err){return warn(`[knowledge-events] applyKnowledgeVerdictFeedback failed (fail-open): ${err instanceof Error?err.message:String(err)}`),{processed:0,bumps:0}}}var import_proper_lockfile4,KNOWLEDGE_EVENT_SCHEMA_VERSION=1,MAX_EVENT_LOG_ENTRIES=5000,counterRollupCache,MAX_COUNTER_ROLLUP_CACHE_DIRS=32,RECEIPT_EVENT_TYPES,resolveHiveEventsPath2,MAX_VIOLATION_TIMESTAMPS=10,VERDICT_CONFIDENCE_BOOST=0.03,VERDICT_CONFIDENCE_DECAY=0.05,_internals41;var init_knowledge_events=__esm(()=>{init_task_file();init_hive_paths();init_logger();init_knowledge_link();import_proper_lockfile4=__toESM(require_proper_lockfile(),1),counterRollupCache=new Map,RECEIPT_EVENT_TYPES=new Set(["acknowledged","applied","ignored","contradicted","violated","n_a","override","no_relevant"]);resolveHiveEventsPath2=resolveHiveEventsPath;_internals41={resolveKnowledgeEventsPath,resolveKnowledgeCounterBaselinePath,appendKnowledgeEvent,recordKnowledgeEvent,readKnowledgeEvents,readCounterBaseline,readLegacyApplicationRecords,readKnowledgeCounterRollups,effectiveRetrievalOutcomes,recomputeCounters,applyKnowledgeVerdictFeedback,newTraceId,newEventId,resolveHiveEventsPath:resolveHiveEventsPath2,appendHiveKnowledgeEvent,recordHiveKnowledgeEvent,readHiveKnowledgeEvents,mergeRollupInto}});var exports_config_fingerprint={};__export(exports_config_fingerprint,{cohortConfigFingerprint:()=>cohortConfigFingerprint,_internals:()=>_internals42});import{createHash as createHash22}from"node:crypto";function cohortConfigFingerprint(input){let canonical=JSON.stringify(sortKeys(input));return createHash22("sha256").update(canonical).digest("hex").slice(0,12)}function sortKeys(value){if(Array.isArray(value))return value.map(sortKeys);if(value&&typeof value==="object"){let obj=value,out={};for(let key of Object.keys(obj).sort())out[key]=sortKeys(obj[key]);return out}return value}var _internals42;var init_config_fingerprint=__esm(()=>{_internals42={cohortConfigFingerprint,sortKeys}});import{randomUUID as randomUUID8}from"node:crypto";import{existsSync as existsSync30}from"node:fs";import{mkdir as mkdir13,readFile as readFile16,writeFile as writeFile7}from"node:fs/promises";import*as path77 from"node:path";function readValidatedId(raw){let parsed=JSON.parse(raw);if(parsed&&typeof parsed.worktree_id==="string"&&UUID_RE.test(parsed.worktree_id))return parsed.worktree_id;return}async function resolveWorktreeId(directory){let dir=path77.normalize(path77.resolve(directory,".swarm")),idPath=path77.join(dir,WORKTREE_ID_FILENAME),repairInvalidFile=!1;try{if(_internals43.existsSync(idPath)){let raw=await _internals43.readFile(idPath,"utf-8"),validated=readValidatedId(raw);if(validated!==void 0)return validated;repairInvalidFile=!0}}catch{}let newId=_internals43.randomUUID();try{await _internals43.mkdir(dir,{recursive:!0});let record3={worktree_id:newId,created_at:new Date().toISOString()},payload=`${JSON.stringify(record3,null,2)}
808
+ `)}async function statCacheKey(filePath){try{let fileStat=await stat9(filePath);return`${fileStat.mtimeMs}:${fileStat.ctimeMs}:${fileStat.size}`}catch(err){if(err?.code==="ENOENT")return"missing";throw err}}async function buildCounterRollupCacheKey(directory){let[eventsKey,legacyKey,baselineKey]=await Promise.all([statCacheKey(resolveKnowledgeEventsPath(directory)),statCacheKey(resolveLegacyApplicationLogPath(directory)),statCacheKey(resolveKnowledgeCounterBaselinePath(directory))]);return`${eventsKey}|${legacyKey}|${baselineKey}`}function setCounterRollupCache(directory,key,rollups){if(counterRollupCache.has(directory))counterRollupCache.delete(directory);counterRollupCache.set(directory,{key,rollups:cloneRollupMap(rollups)});while(counterRollupCache.size>MAX_COUNTER_ROLLUP_CACHE_DIRS){let oldestKey=counterRollupCache.keys().next().value;if(oldestKey===void 0)break;counterRollupCache.delete(oldestKey)}}function parseEventLines(lines,filePath){let out=[];for(let line of lines){let trimmed=line.trim();if(!trimmed)continue;try{out.push(JSON.parse(trimmed))}catch{warn(`[knowledge-events] Skipping corrupted JSONL line in ${filePath}: ${trimmed.slice(0,80)}`)}}return out}async function foldEvictedEventsIntoBaseline(directory,evictedLines,filePath){let evictedEvents=parseEventLines(evictedLines,filePath);if(evictedEvents.length===0)return;let baseline=await readCounterBaseline(directory);for(let[id,rollup]of recomputeCounters(evictedEvents))mergeRollupInto(get(baseline,id),rollup);await writeCounterBaseline(directory,baseline)}function recomputeCounters(events,legacyRecords=[],baseline=new Map){let map3=new Map,retrievedIds=new Set;for(let[id,rollup]of baseline)if(map3.set(id,cloneRollup(rollup)),(rollup.shown_count??0)>0)retrievedIds.add(id);for(let e of events)switch(e.type){case"retrieved":{for(let id of e.result_ids)retrievedIds.add(id),get(map3,id).shown_count+=1;break}case"acknowledged":{if(!e.knowledge_id)break;let r=get(map3,e.knowledge_id);r.acknowledged_count+=1,r.last_acknowledged_at=maxIso(r.last_acknowledged_at,e.timestamp);break}case"applied":{if(!e.knowledge_id)break;let r=get(map3,e.knowledge_id);r.applied_explicit_count+=1,r.last_applied_at=maxIso(r.last_applied_at,e.timestamp);break}case"ignored":if(!e.knowledge_id)break;get(map3,e.knowledge_id).ignored_count+=1;break;case"violated":{if(!e.knowledge_id)break;let r=get(map3,e.knowledge_id);r.violated_count+=1,r.violation_timestamps.push(e.timestamp);break}case"contradicted":if(!e.knowledge_id)break;get(map3,e.knowledge_id).contradicted_count+=1;break;case"n_a":if(!e.knowledge_id)break;get(map3,e.knowledge_id).n_a_count+=1;break;case"no_relevant":break;case"unacknowledged":break;case"outcome":{if(!e.knowledge_id)break;let r=get(map3,e.knowledge_id);if(e.outcome==="success")r.succeeded_after_shown_count+=1;else if(e.outcome==="failure")r.failed_after_shown_count+=1;else if(e.outcome==="partial")r.partial_after_shown_count+=1;break}}for(let rec of legacyRecords){let r=get(map3,rec.knowledgeId);switch(rec.result){case"shown":if(!retrievedIds.has(rec.knowledgeId))r.shown_count+=1;break;case"acknowledged":r.acknowledged_count+=1,r.last_acknowledged_at=maxIso(r.last_acknowledged_at,rec.timestamp);break;case"applied":r.applied_explicit_count+=1,r.last_applied_at=maxIso(r.last_applied_at,rec.timestamp);break;case"ignored":r.ignored_count+=1;break;case"violated":r.violated_count+=1,r.violation_timestamps.push(rec.timestamp);break}}for(let r of map3.values())normalizeRollupTimestamps(r);return map3}function countViolationsInWindow(timestamps,windowDays,now=new Date){let cutoff=now.getTime()-windowDays*24*60*60*1000,count=0;for(let ts of timestamps){let t=Date.parse(ts);if(!Number.isNaN(t)&&t>=cutoff)count+=1}return count}function countEmptyTraceTerminals(events){let n=0;for(let e of events)if(e.type==="no_relevant")n+=1;return n}async function countEntryViolationsInWindow(directory,entryId,windowDays,now=new Date){try{let cutoff=now.getTime()-windowDays*24*60*60*1000,[events,legacyRecords]=await Promise.all([readKnowledgeEvents(directory),readLegacyApplicationRecords(directory)]),count=0;for(let e of events){if(e.type!=="violated"||e.knowledge_id!==entryId)continue;let t=Date.parse(e.timestamp);if(!Number.isNaN(t)&&t>=cutoff)count+=1}for(let rec of legacyRecords){if(rec.result!=="violated"||rec.knowledgeId!==entryId)continue;let t=Date.parse(rec.timestamp);if(!Number.isNaN(t)&&t>=cutoff)count+=1}return count}catch{return 0}}async function countEntryContradictionsInWindow(directory,entryId,windowDays,now=new Date){try{let cutoff=now.getTime()-windowDays*24*60*60*1000,events=await readKnowledgeEvents(directory),count=0;for(let e of events){if(e.type!=="contradicted"||e.knowledge_id!==entryId)continue;let t=Date.parse(e.timestamp);if(!Number.isNaN(t)&&t>=cutoff)count+=1}return count}catch{return 0}}async function readKnowledgeCounterRollups(directory){try{let cacheKey=await buildCounterRollupCacheKey(directory),cached3=counterRollupCache.get(directory);if(cached3?.key===cacheKey)return counterRollupCache.delete(directory),counterRollupCache.set(directory,cached3),cloneRollupMap(cached3.rollups);let[events,legacyRecords,baseline]=await Promise.all([readKnowledgeEvents(directory),readLegacyApplicationRecords(directory),readCounterBaseline(directory)]),rollups=recomputeCounters(events,legacyRecords,baseline);return setCounterRollupCache(directory,cacheKey,rollups),cloneRollupMap(rollups)}catch(err){return warn(`[knowledge-events] readKnowledgeCounterRollups failed: ${err instanceof Error?err.message:String(err)}`),new Map}}function effectiveRetrievalOutcomes(stored,rollup){let base=stored??{applied_count:0,succeeded_after_count:0,failed_after_count:0};if(!rollup)return base;let{n_a_count:_na,...rollupWithoutNa}=rollup;return{...base,...rollupWithoutNa,succeeded_after_shown_count:(base.succeeded_after_shown_count??0)+(rollup.succeeded_after_shown_count??0),failed_after_shown_count:(base.failed_after_shown_count??0)+(rollup.failed_after_shown_count??0)}}async function applyKnowledgeVerdictFeedback(directory,options){try{let events=await readKnowledgeEvents(directory),markerIndex=options?.sinceTimestamp&&options.sinceEventId?events.findIndex((e)=>e.timestamp===options.sinceTimestamp&&e.event_id===options.sinceEventId):-1,actionable=events.filter((e,index)=>{if(e.type!=="applied"&&e.type!=="violated"&&e.type!=="ignored")return!1;if(options?.sinceTimestamp&&e.timestamp<options.sinceTimestamp)return!1;if(options?.sinceTimestamp&&e.timestamp===options.sinceTimestamp){if(!options.sinceEventId)return!1;if(markerIndex<0)return!1;return index>markerIndex}return!0});if(actionable.length===0)return{processed:0,bumps:0};let groups=new Map,lastProcessedTimestamp,lastProcessedEventId;for(let event of actionable){if(typeof event.timestamp==="string"&&(!lastProcessedTimestamp||event.timestamp>=lastProcessedTimestamp))lastProcessedTimestamp=event.timestamp,lastProcessedEventId=event.event_id;let kid=event.knowledge_id;if(!kid)continue;let g=groups.get(kid)??{applied:0,violated:0,ignored:0};if(event.type==="applied")g.applied++;else if(event.type==="violated")g.violated++;else if(event.type==="ignored")g.ignored++;groups.set(kid,g)}let deltas=[];for(let[id,counts]of groups){let positives=counts.applied,negatives=counts.violated+counts.ignored;if(positives===0&&negatives===0)continue;let delta=positives>negatives?VERDICT_CONFIDENCE_BOOST:-VERDICT_CONFIDENCE_DECAY;deltas.push({id,delta})}if(deltas.length>0){let{bumpKnowledgeConfidenceBatch}=await Promise.resolve().then(() => (init_knowledge_store(),exports_knowledge_store));await bumpKnowledgeConfidenceBatch(directory,deltas,options?.floorOptions)}return{processed:groups.size,bumps:deltas.length,lastProcessedTimestamp,lastProcessedEventId}}catch(err){return warn(`[knowledge-events] applyKnowledgeVerdictFeedback failed (fail-open): ${err instanceof Error?err.message:String(err)}`),{processed:0,bumps:0}}}var import_proper_lockfile4,KNOWLEDGE_EVENT_SCHEMA_VERSION=1,MAX_EVENT_LOG_ENTRIES=5000,counterRollupCache,MAX_COUNTER_ROLLUP_CACHE_DIRS=32,RECEIPT_EVENT_TYPES,resolveHiveEventsPath2,MAX_VIOLATION_TIMESTAMPS=10,VERDICT_CONFIDENCE_BOOST=0.03,VERDICT_CONFIDENCE_DECAY=0.05,_internals41;var init_knowledge_events=__esm(()=>{init_task_file();init_hive_paths();init_logger();init_knowledge_link();import_proper_lockfile4=__toESM(require_proper_lockfile(),1),counterRollupCache=new Map,RECEIPT_EVENT_TYPES=new Set(["acknowledged","applied","ignored","contradicted","violated","n_a","override","no_relevant"]);resolveHiveEventsPath2=resolveHiveEventsPath;_internals41={resolveKnowledgeEventsPath,resolveKnowledgeCounterBaselinePath,appendKnowledgeEvent,recordKnowledgeEvent,readKnowledgeEvents,readCounterBaseline,readLegacyApplicationRecords,readKnowledgeCounterRollups,effectiveRetrievalOutcomes,recomputeCounters,applyKnowledgeVerdictFeedback,newTraceId,newEventId,resolveHiveEventsPath:resolveHiveEventsPath2,appendHiveKnowledgeEvent,recordHiveKnowledgeEvent,readHiveKnowledgeEvents,mergeRollupInto}});var exports_config_fingerprint={};__export(exports_config_fingerprint,{cohortConfigFingerprint:()=>cohortConfigFingerprint,_internals:()=>_internals42});import{createHash as createHash22}from"node:crypto";function cohortConfigFingerprint(input){let canonical=JSON.stringify(sortKeys(input));return createHash22("sha256").update(canonical).digest("hex").slice(0,12)}function sortKeys(value){if(Array.isArray(value))return value.map(sortKeys);if(value&&typeof value==="object"){let obj=value,out={};for(let key of Object.keys(obj).sort())out[key]=sortKeys(obj[key]);return out}return value}var _internals42;var init_config_fingerprint=__esm(()=>{_internals42={cohortConfigFingerprint,sortKeys}});import{randomUUID as randomUUID8}from"node:crypto";import{existsSync as existsSync30}from"node:fs";import{mkdir as mkdir13,readFile as readFile16,writeFile as writeFile7}from"node:fs/promises";import*as path77 from"node:path";function readValidatedId(raw){let parsed=JSON.parse(raw);if(parsed&&typeof parsed.worktree_id==="string"&&UUID_RE.test(parsed.worktree_id))return parsed.worktree_id;return}async function resolveWorktreeId(directory){let dir=path77.normalize(path77.resolve(directory,".swarm")),idPath=path77.join(dir,WORKTREE_ID_FILENAME),repairInvalidFile=!1;try{if(_internals43.existsSync(idPath)){let raw=await _internals43.readFile(idPath,"utf-8"),validated=readValidatedId(raw);if(validated!==void 0)return validated;repairInvalidFile=!0}}catch{}let newId=_internals43.randomUUID();try{await _internals43.mkdir(dir,{recursive:!0});let record3={worktree_id:newId,created_at:new Date().toISOString()},payload=`${JSON.stringify(record3,null,2)}
808
809
  `;if(repairInvalidFile)await _internals43.writeFile(idPath,payload,{encoding:"utf-8",flag:"w"});else try{await _internals43.writeFile(idPath,payload,{encoding:"utf-8",flag:"wx"})}catch(err){if(err?.code==="EEXIST"||_internals43.existsSync(idPath)){let raw=await _internals43.readFile(idPath,"utf-8"),validated=readValidatedId(raw);if(validated!==void 0)return validated}throw err}}catch{}return newId}var WORKTREE_ID_FILENAME="worktree-id.json",UUID_RE,_internals43;var init_worktree_identity=__esm(()=>{UUID_RE=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;_internals43={readFile:readFile16,writeFile:writeFile7,existsSync:existsSync30,mkdir:mkdir13,randomUUID:randomUUID8}});var exports_curation_policy={};__export(exports_curation_policy,{readCohortConfigFingerprint:()=>readCohortConfigFingerprint,buildConfigFingerprintInput:()=>buildConfigFingerprintInput,authorizeCuration:()=>authorizeCuration,_internals:()=>_internals44});import{appendFile as appendFile7,mkdir as mkdir14,readFile as readFile17}from"node:fs/promises";import*as path78 from"node:path";async function authorizeCuration(input,context,quorum=DEFAULT_QUORUM){let{directory,action,entryId}=input,proposal={entryId,action,reason:input.reason,evidenceScope:input.evidenceScope,proposedAt:new Date().toISOString(),status:"pending"},persistProposal=(p)=>{queueMicrotask(async()=>{try{let storeDir=_internals44.resolveKnowledgeStoreDir(directory);await mkdir14(storeDir,{recursive:!0}),await appendFile7(path78.join(storeDir,"curation-proposals.jsonl"),`${JSON.stringify(p)}
809
810
  `,"utf-8")}catch{}})},linked=_internals44.isLinked(directory);if(linked){let currentFp=_internals44.cohortConfigFingerprint(buildConfigFingerprintInput(context.config)),cohortFp=await _internals44.readCohortConfigFingerprint(directory);if(cohortFp!==null&&currentFp!==cohortFp)return persistProposal(proposal),{authorized:!1,basis:"config-mismatch",detail:`Cohort config fingerprint mismatch: this worktree (${currentFp}) differs from the cohort (${cohortFp}). Cohort members will curate with different semantics. Align knowledge config across linked worktrees before destructive curation.`,proposal}}let entry=context.entry;if(!entry)return persistProposal(proposal),{authorized:!1,basis:"entry-not-found",detail:`Entry ${entryId} not found in the store.`,proposal};if(input.override?.actor==="manual-override"&&input.override.reason)return{authorized:!0,basis:"override",detail:`Operator override: ${input.override.reason}`,expectedRevision:entry.revision,expectedContentHash:entry.content_hash};if(!linked)return{authorized:!0,basis:"config-skipped-unlinked",detail:"Worktree is not cohort-linked; local curation is permitted (no cross-worktree safety concern).",expectedRevision:entry.revision,expectedContentHash:entry.content_hash};if(entry.producer==null)return persistProposal(proposal),{authorized:!1,basis:"protected-unknown-owner",detail:`Entry ${entryId} has no producer provenance (legacy). Destructive action is protected by default; recorded as a proposal. An audited override is required to force it.`,proposal};let actorWorktreeId=input.actorWorktreeId??await _internals44.resolveWorktreeId(directory);if(entry.producer.worktree_id===actorWorktreeId)return{authorized:!0,basis:"owner",detail:`Acting worktree is the proven producer of entry ${entryId}; owner-scoped ${input.evidenceScope} evidence authorized.`,expectedRevision:entry.revision,expectedContentHash:entry.content_hash};if(input.evidenceScope==="local-session")return persistProposal(proposal),{authorized:!1,basis:"not-owner-local-evidence",detail:`Entry ${entryId} is owned by worktree ${entry.producer.worktree_id}; the acting worktree (${actorWorktreeId}) has only local-session evidence. Absence of local evidence is not negative evidence; recorded as a proposal. Use cohort-wide evidence or an override.`,proposal};if(input.evidenceScope==="cohort-wide"){let events=await _internals44.readKnowledgeEvents(directory),NEGATIVE_EVENT_TYPES=new Set(["violated","contradicted"]),cohortEvidence=events.filter((e)=>("type"in e)&&NEGATIVE_EVENT_TYPES.has(e.type??"")&&("knowledge_id"in e)&&e.knowledge_id===entryId).length;if(cohortEvidence>=quorum.minCohortEvidence)return{authorized:!0,basis:"quorum",detail:`Cohort quorum met for entry ${entryId}: ${cohortEvidence} `+`cohort-wide evidence events (≥ ${quorum.minCohortEvidence} required).`,expectedRevision:entry.revision,expectedContentHash:entry.content_hash};return persistProposal(proposal),{authorized:!1,basis:"quorum-insufficient",detail:`Cohort quorum NOT met for entry ${entryId}: ${cohortEvidence} cohort-wide evidence events (< ${quorum.minCohortEvidence} required).`,proposal}}return persistProposal(proposal),{authorized:!1,basis:"not-owner-local-evidence",detail:`Entry ${entryId} is owned by worktree ${entry.producer.worktree_id}; the acting worktree (${actorWorktreeId}) is not the producer and has not supplied cohort-wide quorum evidence.`,proposal}}function buildConfigFingerprintInput(config3){return{dedup_threshold:config3.dedup_threshold,scope_filter:config3.scope_filter,validation_enabled:config3.validation_enabled,evergreen_confidence:config3.evergreen_confidence,evergreen_utility:config3.evergreen_utility,low_utility_threshold:config3.low_utility_threshold,default_max_phases:config3.default_max_phases,todo_max_phases:config3.todo_max_phases,confidence_floor_action:config3.confidence_floor_action,contradiction_threshold_action:config3.contradiction_threshold_action,contradiction_quarantine_threshold:config3.contradiction_quarantine_threshold,schema_version:config3.schema_version,swarm_max_entries:config3.swarm_max_entries,retrieval:{mmr_lambda:config3.retrieval?.mmr_lambda,cold_start_bonus:config3.retrieval?.cold_start_bonus,synonym_min_cooccurrence:config3.retrieval?.synonym_min_cooccurrence}}}async function readCohortConfigFingerprint(directory){if(!_internals44.isLinked(directory))return null;let pointer=_internals44.readLinkPointer(directory);if(!pointer?.linkId)return null;let linkDir=_internals44.resolveLinkDir(pointer.linkId),cohortConfigPath=path78.join(linkDir,"cohort-config.json");try{let raw=await _internals44.readFile(cohortConfigPath,"utf-8"),parsed=JSON.parse(raw);return typeof parsed.fingerprint==="string"?parsed.fingerprint:null}catch{return null}}var DEFAULT_QUORUM,_internals44;var init_curation_policy=__esm(()=>{init_knowledge_events();init_knowledge_link();init_config_fingerprint();init_worktree_identity();DEFAULT_QUORUM={minCohortEvidence:3};_internals44={resolveWorktreeId,readKnowledgeEvents,cohortConfigFingerprint,readCohortConfigFingerprint,readFile:readFile17,isLinked,readLinkPointer,resolveLinkDir,resolveKnowledgeStoreDir}});function hasNonEmptyList(v){return Array.isArray(v)&&v.length>0}function validateActionability(entry){let hasPredicate=hasNonEmptyList(entry.forbidden_actions)||hasNonEmptyList(entry.required_actions)||hasNonEmptyList(entry.verification_checks)||typeof entry.verification_predicate==="string"&&entry.verification_predicate.trim().length>0,hasScope=hasNonEmptyList(entry.applies_to_tools)||hasNonEmptyList(entry.applies_to_agents);if(hasPredicate&&hasScope)return{actionable:!0};return{actionable:!1,reason:!hasPredicate&&!hasScope?"missing_predicate_and_scope":!hasPredicate?"missing_predicate":"missing_scope"}}var exports_knowledge_validator={};__export(exports_knowledge_validator,{validateSkillPath:()=>validateSkillPath,validateSkillCandidatePath:()=>validateSkillCandidatePath,validateLesson:()=>validateLesson,validateActionableFields:()=>validateActionableFields,validateActionability:()=>validateActionability,unarchiveEntry:()=>unarchiveEntry,scanContentSafety:()=>scanContentSafety,restoreEntry:()=>restoreEntry,resolveUnactionablePath:()=>resolveUnactionablePath,quarantineEntry:()=>quarantineEntry,auditEntryHealth:()=>auditEntryHealth,appendUnactionable:()=>appendUnactionable,_internals:()=>_internals45,SECURITY_DEGRADING_PATTERNS:()=>SECURITY_DEGRADING_PATTERNS,RETIRED_SKILL_HISTORY_MAX:()=>RETIRED_SKILL_HISTORY_MAX,INVISIBLE_FORMAT_CHARS:()=>INVISIBLE_FORMAT_CHARS,INJECTION_PATTERNS:()=>INJECTION_PATTERNS,DANGEROUS_COMMAND_WARNING_PATTERNS:()=>DANGEROUS_COMMAND_WARNING_PATTERNS,DANGEROUS_COMMAND_PATTERNS:()=>DANGEROUS_COMMAND_PATTERNS,DANGEROUS_COMMAND_ERROR_PATTERNS:()=>DANGEROUS_COMMAND_ERROR_PATTERNS,ALLOWED_SKILL_PATH_PREFIXES:()=>ALLOWED_SKILL_PATH_PREFIXES,ACTIONABLE_STRING_MAX:()=>ACTIONABLE_STRING_MAX,ACTIONABLE_LIST_MAX:()=>ACTIONABLE_LIST_MAX});import{appendFile as appendFile8,mkdir as mkdir15}from"node:fs/promises";import*as path79 from"node:path";function scanContentSafety(text){if(typeof text!=="string"||text.length===0)return null;let normalized=text.normalize("NFKC").replace(INVISIBLE_FORMAT_CHARS," ").replace(/\s+/g," ").toLowerCase();for(let pattern of DANGEROUS_COMMAND_ERROR_PATTERNS)if(pattern.test(normalized))return"dangerous command pattern detected";for(let pattern of SECURITY_DEGRADING_PATTERNS)if(pattern.test(normalized))return"security-degrading instruction detected";for(let pattern of INJECTION_PATTERNS)if(pattern.test(text))return"injection pattern detected";return null}function normalizeText(text){return text.normalize("NFKC").toLowerCase().replace(/[^\w\s]/g," ").replace(/\s+/g," ").trim()}function extractContextWords(text,word,contextWindow=3){let words=text.split(" "),context=new Set;if(!word.includes(" ")){let from=0,idx=words.indexOf(word,from);while(idx!==-1){let start=Math.max(0,idx-contextWindow),end=Math.min(words.length,idx+contextWindow+1);for(let i2=start;i2<end;i2++)if(i2!==idx&&words[i2]&&words[i2].length>0)context.add(words[i2]);from=idx+1,idx=words.indexOf(word,from)}return context}let termLen=word.split(" ").length,i=0;while(i<=words.length-termLen)if(words.slice(i,i+termLen).join(" ")===word){let start=Math.max(0,i-contextWindow),end=Math.min(words.length,i+termLen+contextWindow);for(let j=start;j<end;j++)if(j<i||j>=i+termLen){if(words[j]&&words[j].length>0)context.add(words[j])}i+=termLen}else i+=1;return context}function hasSignificantOverlap(set1,set22){if(set1.size===0||set22.size===0)return!1;return[...set1].some((word)=>set22.has(word))}function detectContradiction(candidate,existingLessons){let candidateTags=inferTags2(candidate);if(candidateTags.length===0)return!1;let candidateNorm=normalizeText(candidate);for(let existing of existingLessons){let existingTags=inferTags2(existing);if(!candidateTags.some((t)=>existingTags.includes(t)))continue;let existingNorm=normalizeText(existing);for(let[wordA,wordB]of NEGATION_PAIRS){if(candidateNorm.includes(wordA)&&existingNorm.includes(wordB)){let contextA=extractContextWords(candidateNorm,wordA),contextB=extractContextWords(existingNorm,wordB);if(hasSignificantOverlap(contextA,contextB))return!0}if(candidateNorm.includes(wordB)&&existingNorm.includes(wordA)){let contextB=extractContextWords(candidateNorm,wordB),contextA=extractContextWords(existingNorm,wordA);if(hasSignificantOverlap(contextA,contextB))return!0}}}return!1}function isVagueLesson(lesson){let words=normalizeText(lesson).split(/\s+/),hasTechRef=words.some((w)=>TECH_REFERENCE_WORDS.has(w)),hasActionVerb=words.some((w)=>ACTION_VERB_WORDS.has(w));return!hasTechRef&&!hasActionVerb}function validateLesson(candidate,existingLessons,meta3){if(!candidate||typeof candidate!=="string")return{valid:!1,layer:1,reason:"lesson too short (min 15 chars)",severity:"error"};if(!Array.isArray(existingLessons))existingLessons=[];if(candidate.length<15)return{valid:!1,layer:1,reason:"lesson too short (min 15 chars)",severity:"error"};if(candidate.length>280)return{valid:!1,layer:1,reason:"lesson too long (max 280 chars)",severity:"error"};if(!VALID_CATEGORIES.has(meta3.category))return{valid:!1,layer:1,reason:`invalid category: ${meta3.category}`,severity:"error"};let isGlobalScope=meta3.scope==="global",isStackScope=/^stack:[a-zA-Z0-9_-]{1,64}$/.test(meta3.scope);if(!isGlobalScope&&!isStackScope)return{valid:!1,layer:1,reason:"invalid scope: must be 'global' or 'stack:<name>'",severity:"error"};if(!(meta3.confidence>=0&&meta3.confidence<=1))return{valid:!1,layer:1,reason:"confidence out of range [0.0, 1.0]",severity:"error"};let normalizedCandidate=candidate.normalize("NFKC").replace(INVISIBLE_FORMAT_CHARS," ").replace(/\s+/g," ").toLowerCase();for(let pattern of DANGEROUS_COMMAND_ERROR_PATTERNS)if(pattern.test(normalizedCandidate))return{valid:!1,layer:2,reason:"dangerous command pattern detected",severity:"error"};for(let pattern of DANGEROUS_COMMAND_WARNING_PATTERNS)if(pattern.test(normalizedCandidate))return{valid:!0,layer:2,reason:"potentially dangerous command pattern queued for review",severity:"warning"};for(let pattern of SECURITY_DEGRADING_PATTERNS)if(pattern.test(normalizedCandidate))return{valid:!1,layer:2,reason:"security-degrading instruction detected",severity:"error"};for(let pattern of INJECTION_PATTERNS)if(pattern.test(candidate))return{valid:!1,layer:2,reason:"injection pattern detected",severity:"error"};if(detectContradiction(candidate,existingLessons))return{valid:!0,layer:3,reason:"possible contradiction with an existing lesson with shared tags",severity:"warning"};if(isVagueLesson(candidate))return{valid:!0,layer:3,reason:"lesson may be too vague (no tech reference or action verb)",severity:"warning"};return{valid:!0,layer:null,reason:null,severity:null}}function isCleanShortString(s){if(typeof s!=="string")return!1;if(s.length===0||s.length>ACTIONABLE_STRING_MAX)return!1;return!/[\x00-\x08\x0b-\x0c\x0e-\x1f\x7f]/.test(s)}function validateSkillPath(p){if(typeof p!=="string")return!1;if(p.length===0||p.length>256)return!1;if(p.includes("\x00"))return!1;if(path79.isAbsolute(p))return!1;if(p.includes(".."))return!1;let norm=p.replace(/\\/g,"/");return ALLOWED_SKILL_PATH_PREFIXES.some((prefix)=>norm.startsWith(prefix))}function validateSkillCandidatePath(p){if(typeof p!=="string")return!1;if(p.length===0||p.length>256)return!1;if(p.includes("\x00"))return!1;if(path79.isAbsolute(p))return!1;if(p.includes(".."))return!1;let norm=p.replace(/\\/g,"/");if(!norm.startsWith(".swarm/skills/candidates/"))return!1;let filename=norm.slice(25);return/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\.json$/i.test(filename)}function validateActionableFields(fields){let errors5=[];if(!fields)return{valid:!0,errors:errors5};function checkStringList(name,list){if(list===void 0)return;if(!Array.isArray(list)){errors5.push(`${name} must be an array`);return}if(list.length>ACTIONABLE_LIST_MAX)errors5.push(`${name} exceeds ${ACTIONABLE_LIST_MAX} items`);for(let item of list){if(!isCleanShortString(item)){errors5.push(`${name} contains invalid string`);return}let unsafe=scanContentSafety(item);if(unsafe){errors5.push(`${name} contains unsafe content: ${unsafe}`);return}}}function checkNameList(name,list){if(list===void 0)return;if(!Array.isArray(list)){errors5.push(`${name} must be an array`);return}if(list.length>ACTIONABLE_LIST_MAX)errors5.push(`${name} exceeds ${ACTIONABLE_LIST_MAX} items`);for(let item of list)if(typeof item!=="string"||!NAME_PATTERN2.test(item)){errors5.push(`${name} contains invalid name`);return}}if(checkStringList("triggers",fields.triggers),checkStringList("required_actions",fields.required_actions),checkStringList("forbidden_actions",fields.forbidden_actions),checkStringList("verification_checks",fields.verification_checks),checkNameList("applies_to_agents",fields.applies_to_agents),checkNameList("applies_to_tools",fields.applies_to_tools),fields.source_refs!==void 0){if(!Array.isArray(fields.source_refs))errors5.push("source_refs must be an array");else if(fields.source_refs.length>ACTIONABLE_LIST_MAX)errors5.push(`source_refs exceeds ${ACTIONABLE_LIST_MAX} items`);else for(let ref of fields.source_refs)if(typeof ref!=="string"||ref.length===0||ref.length>ACTIONABLE_STRING_MAX||SOURCE_REF_FORBIDDEN.test(ref)){errors5.push("source_refs contains invalid value");break}}if(fields.source_knowledge_ids!==void 0){if(!Array.isArray(fields.source_knowledge_ids))errors5.push("source_knowledge_ids must be an array");else for(let id of fields.source_knowledge_ids)if(typeof id!=="string"||id.length===0||id.length>64){errors5.push("source_knowledge_ids contains invalid value");break}}if(fields.directive_priority!==void 0&&!VALID_DIRECTIVE_PRIORITIES.has(String(fields.directive_priority)))errors5.push("directive_priority must be low|medium|high|critical");if(fields.generated_skill_slug!==void 0){if(typeof fields.generated_skill_slug!=="string"||!/^[a-z0-9][a-z0-9-]{0,63}$/.test(fields.generated_skill_slug))errors5.push("generated_skill_slug must be a kebab-case slug")}if(fields.generated_skill_path!==void 0&&!validateSkillPath(fields.generated_skill_path))errors5.push("generated_skill_path must be repo-local under allowed prefix");if(fields.draft_generated_skill_slug!==void 0){if(typeof fields.draft_generated_skill_slug!=="string"||!/^[a-z0-9][a-z0-9-]{0,63}$/.test(fields.draft_generated_skill_slug))errors5.push("draft_generated_skill_slug must be a kebab-case slug")}if(fields.draft_generated_skill_path!==void 0&&!validateSkillPath(fields.draft_generated_skill_path))errors5.push("draft_generated_skill_path must be repo-local under allowed prefix");if(fields.retired_skill_history!==void 0){if(!Array.isArray(fields.retired_skill_history))errors5.push("retired_skill_history must be an array of slugs");else if(fields.retired_skill_history.length>RETIRED_SKILL_HISTORY_MAX)errors5.push(`retired_skill_history exceeds ${RETIRED_SKILL_HISTORY_MAX} items`);else if(!fields.retired_skill_history.every((s)=>typeof s==="string"&&/^[a-z0-9][a-z0-9-]{0,63}$/.test(s)))errors5.push("retired_skill_history entries must be kebab-case slugs")}return{valid:errors5.length===0,errors:errors5}}function resolveUnactionablePath(directory){return path79.join(resolveKnowledgeStoreDir(directory),"knowledge-unactionable.jsonl")}async function appendUnactionable(directory,entry,reason){let filePath=resolveUnactionablePath(directory),dirPath=path79.dirname(filePath);await mkdir15(dirPath,{recursive:!0}),await transactKnowledge(filePath,(existing)=>{let record3={...entry,status:"quarantined_unactionable",unactionable_reason:reason,quarantined_at:new Date().toISOString()},duplicate=findNearDuplicate(record3.lesson,existing,0.6);if(duplicate?.unactionable_reason===reason)return duplicate.quarantined_at=record3.quarantined_at,duplicate.updated_at=record3.updated_at,existing;let next=[...existing,record3];return next.length>200?next.slice(-200):next})}function auditEntryHealth(entry){let utilityScore=entry.utility_score;if((entry.retrieval_outcomes?.shown_count??entry.retrieval_outcomes?.applied_count??0)>=5&&utilityScore!==void 0&&utilityScore<=0)return{healthy:!1,concern:"Low-utility entry"};if(entry.confidence<0.1)return{healthy:!1,concern:"Near-zero confidence"};if(entry.auto_generated===!0&&entry.confirmed_by.length===0)return{healthy:!1,concern:"Unconfirmed auto-generated"};return{healthy:!0}}async function quarantineEntry(directory,entryId,reason,reportedBy,curationContext){if(!directory||directory.includes("..")){warn("[knowledge-validator] quarantineEntry: directory traversal attempt blocked");return}if(!entryId||entryId.includes("\x00")||entryId.includes(`
810
811
  `)){warn("[knowledge-validator] quarantineEntry: invalid entryId rejected");return}if(!["architect","user","auto"].includes(reportedBy))return;let sanitizedReason=reason.slice(0,500).replace(/[\x00-\x08\x0b-\x0c\x0e-\x1f\x7f\x0d]/g,""),knowledgePath=resolveSwarmKnowledgePath(directory),quarantinePath=path79.join(resolveKnowledgeStoreDir(directory),"knowledge-quarantined.jsonl"),rejectedPath=resolveSwarmRejectedPath(directory),swarmDir=resolveKnowledgeStoreDir(directory);await mkdir15(swarmDir,{recursive:!0});let release;try{release=await import_proper_lockfile5.default.lock(swarmDir,{retries:{retries:5,minTimeout:100,maxTimeout:500},stale:5000});let entries=await readKnowledge(knowledgePath),entry=entries.find((e)=>e.id===entryId);if(!entry)return;if(curationContext){let refreshedContext={...curationContext.context,entry},decision=await authorizeCuration(curationContext.input,refreshedContext);if(!decision.authorized){warn(`[knowledge-validator] quarantineEntry blocked by cohort-safety policy (basis: ${decision.basis}): ${decision.detail}`);return}}let remaining=entries.filter((e)=>e.id!==entryId),quarantined={...entry,status:"quarantined",original_status:entry.status,quarantine_reason:sanitizedReason,quarantined_at:new Date().toISOString(),reported_by:reportedBy},jsonlContent=remaining.length>0?`${remaining.map((e)=>JSON.stringify(e)).join(`
@@ -961,7 +962,7 @@ TASK: CURATOR_POSTMORTEM [plan_id]
961
962
  PLAN_SUMMARY: [plan phases, task counts, completion status]
962
963
  CURATOR_DIGESTS: [running digest from curator_phase across all phases]
963
964
  KNOWLEDGE_ENTRIES: [JSON array of existing entries with UUIDs]
964
- KNOWLEDGE_EVENTS_SUMMARY: [aggregated violation/applied/ignored counts per entry]
965
+ KNOWLEDGE_EVENTS_SUMMARY: [aggregated violation/applied/ignored/unacknowledged counts per entry — "unacknowledged" means a delegate was shown the directive and filed no ack; it is an audit-only delivery signal, NEVER negative evidence: do not treat it as ignored/violated or count it toward never-applied archival reasoning]
965
966
  PENDING_PROPOSALS: [skill/motif proposals awaiting triage]
966
967
  UNACTIONABLE_QUARANTINE: [entries flagged unactionable with retry status]
967
968
  DRIFT_REPORTS: [per-phase alignment/drift scores if available]
@@ -1319,15 +1320,15 @@ ${summary}`}catch(learningErr){warn(`[curator] learning summary failed: ${learni
1319
1320
  `).filter((l)=>l.trim().length>0);if(lines.length<=MAX_PROMOTION_EVIDENCE_ENTRIES)return;let kept=lines.slice(lines.length-MAX_PROMOTION_EVIDENCE_ENTRIES),tmp=`${filePath}.tmp`;await writeFile14(tmp,`${kept.join(`
1320
1321
  `)}
1321
1322
  `,"utf-8"),await rename11(tmp,filePath)}async function loadPromotionEvidenceByEntry(directory){let filePath=resolvePromotionEvidencePath(directory),content;try{content=await readFile26(filePath,"utf-8")}catch{return{}}let out={};for(let line of content.split(`
1322
- `)){let trimmed=line.trim();if(!trimmed)continue;let rec=parseRecord(trimmed);if(!rec)continue;let bucket=out[rec.entry_id];if(bucket)bucket.push(rec);else out[rec.entry_id]=[rec]}return out}var MAX_PROMOTION_EVIDENCE_ENTRIES=2000;var init_promotion_evidence_store=__esm(()=>{init_logger();init_utils2()});var exports_hive_promoter={};__export(exports_hive_promoter,{resolveHiveKnowledgePath:()=>resolveHiveKnowledgePath2,promoteToHive:()=>promoteToHive,promoteFromSwarm:()=>promoteFromSwarm,isHiveEligible:()=>isHiveEligible,createHivePromoterHook:()=>createHivePromoterHook,countDistinctProjects:()=>countDistinctProjects,checkHivePromotions:()=>checkHivePromotions,_internals:()=>_internals55});import{createHash as createHash27}from"node:crypto";import path93 from"node:path";function carryActionableFields(source){let out={};if(source.triggers?.length)out.triggers=[...source.triggers];if(source.required_actions?.length)out.required_actions=[...source.required_actions];if(source.forbidden_actions?.length)out.forbidden_actions=[...source.forbidden_actions];if(source.verification_checks?.length)out.verification_checks=[...source.verification_checks];if(source.verification_predicate)out.verification_predicate=source.verification_predicate;if(source.applies_to_agents?.length)out.applies_to_agents=[...source.applies_to_agents];if(source.applies_to_tools?.length)out.applies_to_tools=[...source.applies_to_tools];if(source.directive_priority)out.directive_priority=source.directive_priority;return out}function isHiveEligible(entry,autoPromoteDays){return describeEligibilityRoute(entry,autoPromoteDays).passed}function countDistinctProjects(confirmedBy){let cohortIds=new Set,legacyProjectNames=new Set;for(let record3 of confirmedBy)if(typeof record3.cohort_id==="string"&&record3.cohort_id.length>0)cohortIds.add(record3.cohort_id);else legacyProjectNames.add(record3.project_name);return cohortIds.size+legacyProjectNames.size}function hasProjectConfirmation(hiveEntry,projectName,cohortId){return hiveEntry.confirmed_by.some((record3)=>{if(cohortId&&record3.cohort_id)return record3.cohort_id===cohortId;return record3.project_name===projectName})}function calculateEncounterScore(currentScore,isSameProject,config3){let weight=isSameProject?config3.same_project_weight:config3.cross_project_weight,increment=config3.encounter_increment*weight,newScore=currentScore+increment;return Math.min(Math.max(newScore,config3.min_encounter_score),config3.max_encounter_score)}function isSameOrigin(hiveEntry,sourceCohortId){if(hiveEntry.lineage?.source_cohort_id)return hiveEntry.lineage.source_cohort_id===sourceCohortId;let firstWithCohort=hiveEntry.confirmed_by.find((c)=>c.cohort_id);if(firstWithCohort)return firstWithCohort.cohort_id===sourceCohortId;return!1}function sanitizeReason(raw){if(raw===void 0)return;let cleaned="";for(let ch of raw){let code=ch.codePointAt(0)??0;if(code<32||code>=127&&code<=159)cleaned+=" ";else cleaned+=ch}let trimmed=cleaned.trim();if(trimmed.length===0)return;return trimmed.slice(0,MAX_OVERRIDE_REASON_LEN)}function buildLineage(args2){return{actor:args2.actor,source_entry_id:args2.sourceEntryId,source_cohort_id:args2.sourceCohortId,source_revision:args2.sourceRevision,prior_confidence:args2.priorConfidence,prior_phases_alive:args2.priorPhasesAlive,merged_from:args2.mergedFrom,promotion_event_id:args2.promotionEventId,reason:args2.reason,override_failed_gates:args2.overrideFailedGates}}function lessonRevision(lesson){return createHash27("sha256").update(lesson).digest("hex").slice(0,12)}async function checkHivePromotions(swarmEntries,config3,directory){let empty={timestamp:new Date().toISOString(),new_promotions:0,encounters_incremented:0,advancements:0,total_hive_entries:0};if(config3.hive_enabled===!1)return empty;let sourceCohort=await _internals55.resolveCohortId(directory),evidence2=await _internals55.loadPromotionEvidence(directory),diagnostics=[],activeSwarm=swarmEntries.filter((e)=>isActiveStatus(e.status)),activeSwarmBigrams=activeSwarm.map((e)=>typeof e.lesson==="string"?wordBigrams(e.lesson):new Set),candidates=[],rejectsOutside=[];for(let swarmEntry of swarmEntries){if(typeof swarmEntry.lesson!=="string"||swarmEntry.lesson.length===0)continue;let swarmBigram=wordBigrams(swarmEntry.lesson),decision=evaluatePromotionPolicy({entry:swarmEntry,config:config3,evidence:evidence2[swarmEntry.id]??[]});if(!decision.eligible){diagnostics.push(`skip promote '${swarmEntry.lesson.slice(0,40)}…': ${decision.reason}`);continue}let validationResult=_internals55.validateLesson(swarmEntry.lesson,[],{category:swarmEntry.category,scope:swarmEntry.scope,confidence:swarmEntry.confidence});if(validationResult.severity==="error"){rejectsOutside.push({id:crypto.randomUUID(),lesson:swarmEntry.lesson,rejection_reason:validationResult.reason||"validation failed for hive promotion",rejected_at:new Date().toISOString(),rejection_layer:validationResult.layer||2});continue}candidates.push({swarmEntry,swarmBigram,promotionEventId:crypto.randomUUID()})}let hiveDir=resolveHiveDataDir(),result=await _internals55.transactHiveStore(async(ctx)=>{let newPromotions=0,encounters=0,advancements=0,merges=0,audit=[],rejects=[...rejectsOutside],entries=[...ctx.entries],hiveBigrams=entries.map((e)=>typeof e.lesson==="string"?wordBigrams(e.lesson):new Set),addedBigrams=[],findExistingDuplicate=(lessonBigram,threshold)=>{for(let i=0;i<entries.length;i++)if(jaccardBigram(lessonBigram,hiveBigrams[i])>=threshold)return entries[i];return},isDuplicateOfAdded=(lessonBigram,threshold)=>{for(let ab of addedBigrams)if(jaccardBigram(lessonBigram,ab)>=threshold)return!0;return!1};for(let{swarmEntry,swarmBigram,promotionEventId}of candidates){let existingDup=findExistingDuplicate(swarmBigram,config3.dedup_threshold);if(existingDup){if(existingDup.lineage){let mergeAudit=await authorizeAndRecordHiveMerge({survivingEntry:existingDup,losingSourceId:swarmEntry.id,config:config3,hiveDir});if(mergeAudit)merges++,audit.push(mergeAudit)}continue}if(isDuplicateOfAdded(swarmBigram,config3.dedup_threshold)){let lastAdded=entries[entries.length-1];if(lastAdded?.lineage){let mergeAudit=await authorizeAndRecordHiveMerge({survivingEntry:lastAdded,losingSourceId:swarmEntry.id,config:config3,hiveDir});if(mergeAudit)merges++,audit.push(mergeAudit)}continue}let newHiveEntry={id:crypto.randomUUID(),tier:"hive",lesson:swarmEntry.lesson,category:swarmEntry.category,tags:swarmEntry.tags,scope:swarmEntry.scope,confidence:0.5,status:"candidate",confirmed_by:[],retrieval_outcomes:{applied_count:0,succeeded_after_count:0,failed_after_count:0},schema_version:config3.schema_version||KNOWLEDGE_SCHEMA_VERSION,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),source_project:swarmEntry.project_name,encounter_score:config3.initial_encounter_score,lineage:buildLineage({actor:"auto",sourceEntryId:swarmEntry.id,sourceCohortId:sourceCohort.cohortId,sourceRevision:lessonRevision(swarmEntry.lesson),priorConfidence:swarmEntry.confidence,priorPhasesAlive:swarmEntry.phases_alive,promotionEventId}),...carryActionableFields(swarmEntry)};entries.push(newHiveEntry),addedBigrams.push(swarmBigram),hiveBigrams.push(swarmBigram),newPromotions++,audit.push(stagePromotionAudit({entryId:newHiveEntry.id,lesson:newHiveEntry.lesson,actor:"auto",sourceEntryId:swarmEntry.id,sourceCohortId:sourceCohort.cohortId,promotionEventId}))}for(let hiveEntry of entries){if(!Array.isArray(hiveEntry.confirmed_by))hiveEntry.confirmed_by=[];let hiveBigram=typeof hiveEntry.lesson==="string"?wordBigrams(hiveEntry.lesson):new Set,nearDuplicate;for(let i=0;i<activeSwarm.length;i++)if(jaccardBigram(hiveBigram,activeSwarmBigrams[i])>=config3.dedup_threshold){nearDuplicate=activeSwarm[i];break}if(!nearDuplicate)continue;if(hiveEntry.lineage?.source_entry_id&&hiveEntry.lineage.source_entry_id===nearDuplicate.id)continue;let sameProject=isSameOrigin(hiveEntry,sourceCohort.cohortId);if(hasProjectConfirmation(hiveEntry,nearDuplicate.project_name,sourceCohort.cohortId))continue;let newConfirmation={project_name:nearDuplicate.project_name,cohort_id:sourceCohort.cohortId,confirmed_at:new Date().toISOString()};hiveEntry.confirmed_by.push(newConfirmation);let currentScore=hiveEntry.encounter_score??1;if(hiveEntry.encounter_score=calculateEncounterScore(currentScore,sameProject,config3),encounters++,hiveEntry.updated_at=new Date().toISOString(),hiveEntry.status==="candidate"&&countDistinctProjects(hiveEntry.confirmed_by)>=3)hiveEntry.status="established",advancements++}if(!(newPromotions>0||encounters>0||advancements>0||merges>0)&&rejects.length===0)return{kind:"noop",return:{newPromotions,encounters,advancements,total:entries.length}};return{kind:"commit",entries,maxEntries:config3.hive_max_entries,rejects:rejects.length>0?rejects:void 0,audit:audit.length>0?audit:void 0,return:{newPromotions,encounters,advancements,total:entries.length}}});if(!result.committed)return{timestamp:new Date().toISOString(),new_promotions:0,encounters_incremented:0,advancements:0,total_hive_entries:0,diagnostics:[...diagnostics,...result.diagnostics,"hive promotion transaction did not commit (see prior diagnostics)"]};let ret=result.return;return{timestamp:new Date().toISOString(),new_promotions:ret?.newPromotions??0,encounters_incremented:ret?.encounters??0,advancements:ret?.advancements??0,total_hive_entries:ret?.total??0,diagnostics:[...diagnostics,...result.diagnostics]}}function stagePromotionAudit(args2){let event={type:"promotion",schema_version:1,event_id:args2.promotionEventId,timestamp:new Date().toISOString(),entry_id:args2.entryId,actor:args2.actor,reason:args2.reason,source_entry_id:args2.sourceEntryId,source_cohort_id:args2.sourceCohortId,override_failed_gates:args2.overrideFailedGates,lesson_excerpt:args2.lesson.slice(0,80)};return{line:JSON.stringify(event)}}function stageMergeAudit(args2){let event={type:"merge",schema_version:1,event_id:crypto.randomUUID(),timestamp:new Date().toISOString(),entry_id:args2.survivingEntryId,action:"merge",merged_from:args2.mergedFromId,authorized:args2.authorized,authorization_basis:args2.authorizationBasis};return{line:JSON.stringify(event)}}async function authorizeAndRecordHiveMerge(args2){let{survivingEntry,losingSourceId,config:config3,hiveDir}=args2,mergedFrom=survivingEntry.lineage?.merged_from??[];if(mergedFrom.includes(losingSourceId))return;let authorized=!0,basis="config-skipped-unlinked";try{let decision=await _internals55.authorizeCuration({directory:hiveDir,action:"merge",entryId:survivingEntry.id,reason:`hive dedup-merge: near-duplicate source ${losingSourceId}`,evidenceScope:"cohort-wide"},{config:config3,entry:{id:survivingEntry.id,producer:null,status:survivingEntry.status}});authorized=decision.authorized,basis=decision.basis}catch(err){authorized=!1,basis=`authorize-error:${err instanceof Error?err.message:String(err)}`}return survivingEntry.lineage=survivingEntry.lineage??{actor:"auto"},survivingEntry.lineage.merged_from=[...mergedFrom,losingSourceId],survivingEntry.updated_at=new Date().toISOString(),stageMergeAudit({survivingEntryId:survivingEntry.id,mergedFromId:losingSourceId,authorized,authorizationBasis:basis})}function createHivePromoterHook(directory,config3){return safeHook(async(_input,_output)=>{let swarmEntries=await _internals55.readSwarmEntries(directory),promotionSummary=await _internals55.checkHivePromotions(swarmEntries,config3,directory);if(!await _internals55.readCuratorSummary(directory))return;if(!(promotionSummary.new_promotions>0||promotionSummary.encounters_incremented>0||promotionSummary.advancements>0))return;await _internals55.appendCuratorRecommendation(directory,{action:"promote",lesson:`Hive promotion: ${promotionSummary.new_promotions} new, ${promotionSummary.encounters_incremented} encounters, ${promotionSummary.advancements} advancements, ${promotionSummary.total_hive_entries} total entries`,reason:JSON.stringify({timestamp:promotionSummary.timestamp,new_promotions:promotionSummary.new_promotions,encounters_incremented:promotionSummary.encounters_incremented,advancements:promotionSummary.advancements,total_hive_entries:promotionSummary.total_hive_entries})})})}function normalizeManualActionability(fields){if(!fields)return{};let out={};for(let key of MANUAL_ACTIONABILITY_KEYS){let normalized=dedupeCapped(fields[key],{cap:MANUAL_ACTIONABILITY_CAP});if(normalized.length>0)out[key]=normalized}return out}async function promoteToHive(directory,lesson,category,options,config3,actionable){let trimmedLesson=lesson.trim(),actionableFields=normalizeManualActionability(actionable),sourceCohort=await _internals55.resolveCohortId(directory),policyConfig=config3??_internals55.loadDefaultKnowledgeConfig(),result=await _internals55.transactHiveStore(async(ctx)=>{if(findNearDuplicate(trimmedLesson,ctx.entries,policyConfig.dedup_threshold))return{kind:"noop",return:"Lesson already exists in hive (near-duplicate)."};let validationResult=_internals55.validateLesson(trimmedLesson,ctx.entries.map((e)=>e.lesson),{category:category||"process",scope:"global",confidence:1});if(validationResult.severity==="error")return{kind:"noop",return:`Lesson rejected by validator: ${validationResult.reason}`};let swarmStandIn={id:"manual-direct",tier:"swarm",lesson:trimmedLesson,category:category||"process",tags:["hive-fast-track"],scope:"global",confidence:1,status:"promoted",confirmed_by:[],retrieval_outcomes:{applied_count:0,succeeded_after_count:0,failed_after_count:0},schema_version:KNOWLEDGE_SCHEMA_VERSION,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),project_name:path93.basename(directory)||"unknown",...actionableFields},decision=evaluatePromotionPolicy({entry:swarmStandIn,config:policyConfig,evidence:[]}),force=options?.force===!0,reason=sanitizeReason(options?.reason),actor,overrideFailedGates;if(decision.eligible)actor="manual";else if(force&&reason&&reason.length>0)actor="manual-override",overrideFailedGates=failedGateNames(decision);else return{kind:"noop",return:`Promotion blocked by policy: ${decision.reason}. Use --force --reason "<why>" to record an audited override.`};let promotionEventId=crypto.randomUUID(),newHiveEntry={id:crypto.randomUUID(),tier:"hive",lesson:trimmedLesson,category:category||"process",tags:[],scope:"global",confidence:1,status:"promoted",confirmed_by:[],retrieval_outcomes:{applied_count:0,succeeded_after_count:0,failed_after_count:0},schema_version:KNOWLEDGE_SCHEMA_VERSION,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),source_project:path93.basename(directory)||"unknown",encounter_score:1,lineage:buildLineage({actor,sourceCohortId:sourceCohort.cohortId,promotionEventId,reason:reason||void 0,overrideFailedGates}),...carryActionableFields(swarmStandIn)},entries=[...ctx.entries,newHiveEntry],audit=[stagePromotionAudit({entryId:newHiveEntry.id,lesson:newHiveEntry.lesson,actor,sourceCohortId:sourceCohort.cohortId,promotionEventId,reason:reason||void 0,overrideFailedGates})];return{kind:"commit",entries,audit,return:`Promoted to hive: "${trimmedLesson.slice(0,50)}${trimmedLesson.length>50?"...":""}" (confidence: 1.0, source: manual${actor==="manual-override"?"-override":""})`}});if(result.return!==void 0)return result.return;return`Promotion failed: ${result.diagnostics.join("; ")||"transaction did not commit"}`}async function promoteFromSwarm(directory,lessonId,options,config3){let swarmEntry=(await readKnowledge(resolveSwarmKnowledgePath(directory))).find((e)=>e.id===lessonId);if(!swarmEntry)throw Error(`Lesson ${lessonId} not found in .swarm/knowledge.jsonl`);let sourceCohort=await _internals55.resolveCohortId(directory),policyConfig=config3??_internals55.loadDefaultKnowledgeConfig(),result=await _internals55.transactHiveStore(async(ctx)=>{if(findNearDuplicate(swarmEntry.lesson,ctx.entries,policyConfig.dedup_threshold))return{kind:"noop",return:"Lesson already exists in hive (near-duplicate)."};let validationResult=_internals55.validateLesson(swarmEntry.lesson,ctx.entries.map((e)=>e.lesson),{category:swarmEntry.category,scope:swarmEntry.scope,confidence:swarmEntry.confidence});if(validationResult.severity==="error")return{kind:"noop",return:`Lesson rejected by validator: ${validationResult.reason}`};let decision=evaluatePromotionPolicy({entry:swarmEntry,config:policyConfig,evidence:[]}),force=options?.force===!0,reason=sanitizeReason(options?.reason),actor,overrideFailedGates;if(decision.eligible)actor="manual";else if(force&&reason&&reason.length>0)actor="manual-override",overrideFailedGates=failedGateNames(decision);else return{kind:"noop",return:`Promotion blocked by policy: ${decision.reason}. Use --force --reason "<why>" to record an audited override.`};let promotionEventId=crypto.randomUUID(),newHiveEntry={id:crypto.randomUUID(),tier:"hive",lesson:swarmEntry.lesson,category:swarmEntry.category,tags:swarmEntry.tags,scope:swarmEntry.scope,confidence:1,status:"promoted",confirmed_by:[],retrieval_outcomes:{applied_count:0,succeeded_after_count:0,failed_after_count:0},schema_version:swarmEntry.schema_version||KNOWLEDGE_SCHEMA_VERSION,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),source_project:swarmEntry.project_name,encounter_score:1,lineage:buildLineage({actor,sourceEntryId:swarmEntry.id,sourceCohortId:sourceCohort.cohortId,promotionEventId,reason:reason||void 0,overrideFailedGates}),...carryActionableFields(swarmEntry)},entries=[...ctx.entries,newHiveEntry],audit=[stagePromotionAudit({entryId:newHiveEntry.id,lesson:newHiveEntry.lesson,actor,sourceEntryId:swarmEntry.id,sourceCohortId:sourceCohort.cohortId,promotionEventId,reason:reason||void 0,overrideFailedGates})];return{kind:"commit",entries,audit,return:`Promoted lesson ${lessonId} from swarm to hive: "${swarmEntry.lesson.slice(0,50)}${swarmEntry.lesson.length>50?"...":""}"`}});if(result.return!==void 0)return result.return;return`Promotion failed: ${result.diagnostics.join("; ")||"transaction did not commit"}`}var MAX_OVERRIDE_REASON_LEN=280,_internals55,MANUAL_ACTIONABILITY_CAP=20,MANUAL_ACTIONABILITY_KEYS;var init_hive_promoter=__esm(()=>{init_schema();init_cohort_identity();init_curation_policy();init_hive_paths();init_curator();init_hive_policy();init_hive_transaction();init_knowledge_store();init_knowledge_types();init_knowledge_validator();init_promotion_evidence_store();init_utils2();init_knowledge_store();_internals55={readSwarmEntries:(directory)=>readKnowledge(resolveSwarmKnowledgePath(directory)),checkHivePromotions,readCuratorSummary,appendCuratorRecommendation,resolveCohortId,transactHiveStore,validateLesson,authorizeCuration,loadPromotionEvidence:async(directory)=>loadPromotionEvidenceByEntry(directory),loadDefaultKnowledgeConfig:()=>KnowledgeConfigSchema.parse({})};MANUAL_ACTIONABILITY_KEYS=["applies_to_tools","applies_to_agents","required_actions","forbidden_actions","verification_checks"]});var exports_curator_drift={};__export(exports_curator_drift,{writeDriftReport:()=>writeDriftReport,runDeterministicDriftCheck:()=>runDeterministicDriftCheck,readPriorDriftReports:()=>readPriorDriftReports,buildDriftInjectionText:()=>buildDriftInjectionText,_internals:()=>_internals56});import*as fs42 from"node:fs";import*as path94 from"node:path";async function readPriorDriftReports(directory){let swarmDir=path94.join(directory,".swarm"),entries=await fs42.promises.readdir(swarmDir).catch(()=>null);if(entries===null)return[];let reportFiles=entries.filter((name)=>name.startsWith(DRIFT_REPORT_PREFIX)&&name.endsWith(".json")).sort(),reports=[];for(let filename of reportFiles){let content=await readSwarmFileAsync(directory,filename);if(content===null)continue;try{let report=JSON.parse(content);if(typeof report.phase!=="number"||typeof report.alignment!=="string"||typeof report.timestamp!=="string"||typeof report.drift_score!=="number"||typeof report.schema_version!=="number"||!Array.isArray(report.compounding_effects)){warn(`[curator-drift] Skipping corrupt drift report: ${filename}`);continue}reports.push(report)}catch{warn(`[curator-drift] Skipping unreadable drift report: ${filename}`)}}return reports.sort((a,b)=>a.phase-b.phase),reports}async function writeDriftReport(directory,report){let filename=`${DRIFT_REPORT_PREFIX}${report.phase}.json`,filePath=validateSwarmPath(directory,filename),swarmDir=path94.dirname(filePath);await fs42.promises.mkdir(swarmDir,{recursive:!0});try{await fs42.promises.writeFile(filePath,JSON.stringify(report,null,2),"utf-8")}catch(err){throw Error(`[curator-drift] Failed to write drift report to ${filePath}: ${String(err)}`)}return filePath}function extractRequirementIds(text){let matches=text.match(/FR-\d{3,}/g);return matches?[...new Set(matches)]:[]}async function runDeterministicDriftCheck(directory,phase,curatorResult,config3,injectAdvisory){try{let planMd=await readSwarmFileAsync(directory,"plan.md"),specMd=readEffectiveSpecSync(directory)?.content??null,priorReports=await _internals56.readPriorDriftReports(directory),complianceCount=curatorResult.compliance.length,warningCompliance=curatorResult.compliance.filter((obs)=>obs.severity==="warning"),alignment="ALIGNED",driftScore=0,specRequirements=specMd?extractRequirementIds(specMd):[],planRequirements=planMd?extractRequirementIds(planMd):[],digestRequirements=extractRequirementIds(JSON.stringify(curatorResult.digest)+JSON.stringify(curatorResult.compliance)+JSON.stringify(curatorResult.knowledge_recommendations??[]));if(!planMd)alignment="MINOR_DRIFT",driftScore=0.3;else if(specRequirements.length>0){let coveredInPlan=specRequirements.filter((fr)=>planRequirements.includes(fr)),coveredInDigest=specRequirements.filter((fr)=>digestRequirements.includes(fr)),specCoverageRatio=coveredInPlan.length/specRequirements.length,implementationRatio=coveredInDigest.length/specRequirements.length;if(specCoverageRatio<0.5)alignment="MAJOR_DRIFT",driftScore=Math.min(0.9,0.6+(1-specCoverageRatio)*0.3);else if(warningCompliance.length>=3)alignment="MAJOR_DRIFT",driftScore=Math.min(0.9,0.5+warningCompliance.length*0.1);else if(warningCompliance.length>=1||complianceCount>=3)alignment="MINOR_DRIFT",driftScore=Math.min(0.49,0.2+complianceCount*0.05);else if(implementationRatio<0.5)alignment="MINOR_DRIFT",driftScore=Math.min(0.6,0.2+(1-implementationRatio)*0.3)}else if(warningCompliance.length>=3)alignment="MAJOR_DRIFT",driftScore=Math.min(0.9,0.5+warningCompliance.length*0.1);else if(warningCompliance.length>=1||complianceCount>=3)alignment="MINOR_DRIFT",driftScore=Math.min(0.49,0.2+complianceCount*0.05);let keyCorrections=warningCompliance.map((obs)=>obs.description),firstDeviation=warningCompliance.length>0?{phase,task:"unknown",description:warningCompliance[0]?.description??""}:null,requirementsChecked=curatorResult.digest.tasks_total,requirementsSatisfied=curatorResult.digest.tasks_completed,coverageNote=specRequirements.length>0?` [${digestRequirements.filter((fr)=>specRequirements.includes(fr)).length}/${specRequirements.length} FRs covered]`:"",injectionSummary=`Phase ${phase}: ${alignment} (${driftScore.toFixed(2)})${coverageNote} — ${firstDeviation?firstDeviation.description:"all requirements on track"}.${keyCorrections.length>0?`Correction: ${keyCorrections[0]??""}.`:""}`.slice(0,config3.drift_inject_max_chars),report={schema_version:1,phase,timestamp:new Date().toISOString(),alignment,drift_score:driftScore,first_deviation:firstDeviation,compounding_effects:priorReports.filter((r)=>r.alignment!=="ALIGNED").map((r)=>`Phase ${r.phase}: ${r.alignment}`).slice(0,5),corrections:keyCorrections.slice(0,5),requirements_checked:requirementsChecked,requirements_satisfied:requirementsSatisfied,scope_additions:[],injection_summary:injectionSummary},reportPath=await _internals56.writeDriftReport(directory,report);if(getGlobalEventBus().publish("curator.drift.completed",{phase,alignment,drift_score:driftScore,report_path:reportPath}),injectAdvisory&&alignment!=="ALIGNED"&&driftScore>0)try{let advisoryText=`CURATOR DRIFT DETECTED (phase ${phase}, score ${driftScore.toFixed(2)}): ${injectionSummary.slice(0,300)}. Review .swarm/${DRIFT_REPORT_PREFIX}${phase}.json and address spec alignment before proceeding. Consider running critic_drift_verifier before phase completion to get a proper drift review.`;injectAdvisory(advisoryText)}catch{}return{phase,report,report_path:reportPath,injection_text:injectionSummary}}catch(err){getGlobalEventBus().publish("curator.error",{operation:"drift",phase,error:String(err)});let defaultReport={schema_version:1,phase,timestamp:new Date().toISOString(),alignment:"ALIGNED",drift_score:0,first_deviation:null,compounding_effects:[],corrections:[],requirements_checked:0,requirements_satisfied:0,scope_additions:[],injection_summary:`Phase ${phase}: drift analysis unavailable (${String(err)})`};return{phase,report:defaultReport,report_path:"",injection_text:""}}}function buildDriftInjectionText(report,maxChars){if(maxChars<=0)return"";let text;if(report.alignment==="ALIGNED"&&report.drift_score<0.1)text=`<drift_report>Phase ${report.phase}: ALIGNED, all requirements on track.</drift_report>`;else{let keyFinding=report.first_deviation?.description??"no deviation recorded",score=report.drift_score??0,correctionClause=report.corrections?.[0]?`Correction: ${report.corrections[0]}.`:"";text=`<drift_report>Phase ${report.phase}: ${report.alignment} (${score.toFixed(2)}) — ${keyFinding}. ${correctionClause}</drift_report>`}return text.slice(0,maxChars)}var DRIFT_REPORT_PREFIX="drift-report-phase-",_internals56;var init_curator_drift=__esm(()=>{init_event_bus();init_effective_spec();init_logger();init_utils2();_internals56={readPriorDriftReports,writeDriftReport,runDeterministicDriftCheck,buildDriftInjectionText}});var exports_curator_postmortem={};__export(exports_curator_postmortem,{runCuratorPostMortem:()=>runCuratorPostMortem,_internals:()=>_internals57});import{existsSync as existsSync39,readdirSync as readdirSync11,readFileSync as readFileSync31}from"node:fs";import*as path95 from"node:path";async function collectKnowledgeSummary(directory,scope="project",sessionID,out){let batch=await claimNextScanBatch(directory,MAX_KNOWLEDGE_ENTRIES);if(out)out.generation=batch.generation;let entries=batch.entries,batchIds=new Set(entries.map((e)=>e.id)),events=(await readKnowledgeEvents(directory)).filter((e)=>{let kid=e.knowledge_id??e.entry_id;return kid!=null&&batchIds.has(kid)});if(scope==="session"&&sessionID)events=events.filter((e)=>e.session_id===sessionID);let countsMap=new Map;for(let e of events){if(e.type!=="applied"&&e.type!=="violated"&&e.type!=="ignored")continue;let kid=e.knowledge_id??e.entry_id;if(!kid)continue;let c=countsMap.get(kid)??{applied:0,violated:0,ignored:0};if(e.type==="applied")c.applied++;else if(e.type==="violated")c.violated++;else if(e.type==="ignored")c.ignored++;countsMap.set(kid,c)}return entries.map((entry)=>{let c=countsMap.get(entry.id)??{applied:0,violated:0,ignored:0};return{id:entry.id,lesson:entry.lesson,applied:c.applied,violated:c.violated,ignored:c.ignored,confidence:entry.confidence??0.5,status:entry.status??"active"}})}function extractSection(text,sectionName){let pattern=new RegExp(`^${sectionName}:\\s*\\n([\\s\\S]*?)(?=\\n[A-Z_]+:\\s*(?:\\n|$)|$)`,"m");return text.match(pattern)?.[1]?.trim()||null}function normalizeRecommendationAction(raw){let value=String(raw??"").toLowerCase().trim();if(value==="promote"||value==="promote_to_hive")return"promote";if(value==="archive"||value==="flag_stale")return"archive";if(value==="rewrite")return"rewrite";if(value==="flag_contradiction")return"flag_contradiction";if(value==="merge")return null;return null}function normalizeProposalSlug(raw){return raw.trim().replace(/^proposals[\\/]/,"").replace(/\.md$/i,"").replace(/\.json$/i,"")}function parseStructuredPostMortemActions(llmOutput){let parsed={summary:extractSection(llmOutput,"SUMMARY"),recommendations:[],queueTriage:[],diagnostics:[]},fence=/```(?:json|jsonc)?\s+postmortem_actions\s*\n([\s\S]*?)\n```/g;for(let match of llmOutput.matchAll(fence)){let data;try{data=JSON.parse(match[1])}catch(err){parsed.diagnostics.push(`postmortem_actions malformed_json: ${err instanceof Error?err.message:String(err)}`);continue}if(!data||typeof data!=="object"||Array.isArray(data)){parsed.diagnostics.push("postmortem_actions expected object");continue}let obj=data;if(typeof obj.summary==="string"&&obj.summary.trim())parsed.summary=obj.summary.trim().slice(0,1000);if(Array.isArray(obj.curation_recommendations))for(let[index,item]of obj.curation_recommendations.entries()){if(!item||typeof item!=="object"){parsed.diagnostics.push(`curation_recommendations[${index}] invalid object`);continue}let rec=item,action=normalizeRecommendationAction(rec.action),lesson=String(rec.lesson??rec.reason??"").trim(),reason=String(rec.reason??lesson).trim();if(!action||!reason){parsed.diagnostics.push(`curation_recommendations[${index}] missing action/reason`);continue}if(action==="rewrite"&&lesson.length<15){parsed.diagnostics.push(`curation_recommendations[${index}] rewrite missing lesson`);continue}parsed.recommendations.push({action,entry_id:typeof rec.entry_id==="string"?normalizeRecommendationEntryIdToken(rec.entry_id):void 0,lesson:(lesson||reason).slice(0,280),reason:reason.slice(0,280),category:typeof rec.category==="string"?rec.category:void 0,confidence:typeof rec.confidence==="number"?rec.confidence:void 0,triggers:stringArray(rec.triggers),required_actions:stringArray(rec.required_actions),forbidden_actions:stringArray(rec.forbidden_actions),applies_to_agents:stringArray(rec.applies_to_agents),applies_to_tools:stringArray(rec.applies_to_tools),verification_checks:stringArray(rec.verification_checks),directive_priority:directivePriority(rec.directive_priority)})}if(Array.isArray(obj.queue_triage))for(let[index,item]of obj.queue_triage.entries()){if(!item||typeof item!=="object"){parsed.diagnostics.push(`queue_triage[${index}] invalid object`);continue}let triage=item,proposalId=String(triage.proposal_id??"").trim(),action=String(triage.action??"").toLowerCase().trim();if(!proposalId||action!=="apply"&&action!=="reject"){parsed.diagnostics.push(`queue_triage[${index}] missing proposal_id/action`);continue}parsed.queueTriage.push({proposal_id:proposalId.slice(0,120),action,reason:String(triage.reason??"").slice(0,280)})}}return parsed}function stringArray(value){if(!Array.isArray(value))return;let strings=value.filter((item)=>typeof item==="string").map((item)=>item.trim()).filter((item)=>item.length>0);return strings.length>0?strings:void 0}function directivePriority(value){if(value==="low"||value==="medium"||value==="high"||value==="critical")return value;return}function parseLegacyPostMortemActions(llmOutput){let parsed={summary:extractSection(llmOutput,"SUMMARY"),recommendations:[],queueTriage:[],diagnostics:[]},curation=extractSection(llmOutput,"CURATION_RECOMMENDATIONS");if(curation){let recIndex=0;for(let line of curation.split(`
1323
+ `)){let trimmed=line.trim();if(!trimmed)continue;let rec=parseRecord(trimmed);if(!rec)continue;let bucket=out[rec.entry_id];if(bucket)bucket.push(rec);else out[rec.entry_id]=[rec]}return out}var MAX_PROMOTION_EVIDENCE_ENTRIES=2000;var init_promotion_evidence_store=__esm(()=>{init_logger();init_utils2()});var exports_hive_promoter={};__export(exports_hive_promoter,{resolveHiveKnowledgePath:()=>resolveHiveKnowledgePath2,promoteToHive:()=>promoteToHive,promoteFromSwarm:()=>promoteFromSwarm,isHiveEligible:()=>isHiveEligible,createHivePromoterHook:()=>createHivePromoterHook,countDistinctProjects:()=>countDistinctProjects,checkHivePromotions:()=>checkHivePromotions,_internals:()=>_internals55});import{createHash as createHash27}from"node:crypto";import path93 from"node:path";function carryActionableFields(source){let out={};if(source.triggers?.length)out.triggers=[...source.triggers];if(source.required_actions?.length)out.required_actions=[...source.required_actions];if(source.forbidden_actions?.length)out.forbidden_actions=[...source.forbidden_actions];if(source.verification_checks?.length)out.verification_checks=[...source.verification_checks];if(source.verification_predicate)out.verification_predicate=source.verification_predicate;if(source.applies_to_agents?.length)out.applies_to_agents=[...source.applies_to_agents];if(source.applies_to_tools?.length)out.applies_to_tools=[...source.applies_to_tools];if(source.directive_priority)out.directive_priority=source.directive_priority;return out}function isHiveEligible(entry,autoPromoteDays){return describeEligibilityRoute(entry,autoPromoteDays).passed}function countDistinctProjects(confirmedBy){let cohortIds=new Set,legacyProjectNames=new Set;for(let record3 of confirmedBy)if(typeof record3.cohort_id==="string"&&record3.cohort_id.length>0)cohortIds.add(record3.cohort_id);else legacyProjectNames.add(record3.project_name);return cohortIds.size+legacyProjectNames.size}function hasProjectConfirmation(hiveEntry,projectName,cohortId){return hiveEntry.confirmed_by.some((record3)=>{if(cohortId&&record3.cohort_id)return record3.cohort_id===cohortId;return record3.project_name===projectName})}function calculateEncounterScore(currentScore,isSameProject,config3){let weight=isSameProject?config3.same_project_weight:config3.cross_project_weight,increment=config3.encounter_increment*weight,newScore=currentScore+increment;return Math.min(Math.max(newScore,config3.min_encounter_score),config3.max_encounter_score)}function isSameOrigin(hiveEntry,sourceCohortId){if(hiveEntry.lineage?.source_cohort_id)return hiveEntry.lineage.source_cohort_id===sourceCohortId;let firstWithCohort=hiveEntry.confirmed_by.find((c)=>c.cohort_id);if(firstWithCohort)return firstWithCohort.cohort_id===sourceCohortId;return!1}function sanitizeReason(raw){if(raw===void 0)return;let cleaned="";for(let ch of raw){let code=ch.codePointAt(0)??0;if(code<32||code>=127&&code<=159)cleaned+=" ";else cleaned+=ch}let trimmed=cleaned.trim();if(trimmed.length===0)return;return trimmed.slice(0,MAX_OVERRIDE_REASON_LEN)}function buildLineage(args2){return{actor:args2.actor,source_entry_id:args2.sourceEntryId,source_cohort_id:args2.sourceCohortId,source_revision:args2.sourceRevision,prior_confidence:args2.priorConfidence,prior_phases_alive:args2.priorPhasesAlive,merged_from:args2.mergedFrom,promotion_event_id:args2.promotionEventId,reason:args2.reason,override_failed_gates:args2.overrideFailedGates}}function lessonRevision(lesson){return createHash27("sha256").update(lesson).digest("hex").slice(0,12)}async function checkHivePromotions(swarmEntries,config3,directory){let empty={timestamp:new Date().toISOString(),new_promotions:0,encounters_incremented:0,advancements:0,total_hive_entries:0};if(config3.hive_enabled===!1)return empty;let sourceCohort=await _internals55.resolveCohortId(directory),evidence2=await _internals55.loadPromotionEvidence(directory),diagnostics=[],activeSwarm=swarmEntries.filter((e)=>isActiveStatus(e.status)),activeSwarmBigrams=activeSwarm.map((e)=>typeof e.lesson==="string"?wordBigrams(e.lesson):new Set),candidates=[],rejectsOutside=[];for(let swarmEntry of swarmEntries){if(typeof swarmEntry.lesson!=="string"||swarmEntry.lesson.length===0)continue;let swarmBigram=wordBigrams(swarmEntry.lesson),decision=evaluatePromotionPolicy({entry:swarmEntry,config:config3,evidence:evidence2[swarmEntry.id]??[]});if(!decision.eligible){diagnostics.push(`skip promote '${swarmEntry.lesson.slice(0,40)}…': ${decision.reason}`);continue}let validationResult=_internals55.validateLesson(swarmEntry.lesson,[],{category:swarmEntry.category,scope:swarmEntry.scope,confidence:swarmEntry.confidence});if(validationResult.severity==="error"){rejectsOutside.push({id:crypto.randomUUID(),lesson:swarmEntry.lesson,rejection_reason:validationResult.reason||"validation failed for hive promotion",rejected_at:new Date().toISOString(),rejection_layer:validationResult.layer||2});continue}candidates.push({swarmEntry,swarmBigram,promotionEventId:crypto.randomUUID()})}let hiveDir=resolveHiveDataDir(),result=await _internals55.transactHiveStore(async(ctx)=>{let newPromotions=0,encounters=0,advancements=0,merges=0,audit=[],rejects=[...rejectsOutside],entries=[...ctx.entries],hiveBigrams=entries.map((e)=>typeof e.lesson==="string"?wordBigrams(e.lesson):new Set),addedBigrams=[],findExistingDuplicate=(lessonBigram,threshold)=>{for(let i=0;i<entries.length;i++)if(jaccardBigram(lessonBigram,hiveBigrams[i])>=threshold)return entries[i];return},isDuplicateOfAdded=(lessonBigram,threshold)=>{for(let ab of addedBigrams)if(jaccardBigram(lessonBigram,ab)>=threshold)return!0;return!1};for(let{swarmEntry,swarmBigram,promotionEventId}of candidates){let existingDup=findExistingDuplicate(swarmBigram,config3.dedup_threshold);if(existingDup){if(existingDup.lineage){let mergeAudit=await authorizeAndRecordHiveMerge({survivingEntry:existingDup,losingSourceId:swarmEntry.id,config:config3,hiveDir});if(mergeAudit)merges++,audit.push(mergeAudit)}continue}if(isDuplicateOfAdded(swarmBigram,config3.dedup_threshold)){let lastAdded=entries[entries.length-1];if(lastAdded?.lineage){let mergeAudit=await authorizeAndRecordHiveMerge({survivingEntry:lastAdded,losingSourceId:swarmEntry.id,config:config3,hiveDir});if(mergeAudit)merges++,audit.push(mergeAudit)}continue}let newHiveEntry={id:crypto.randomUUID(),tier:"hive",lesson:swarmEntry.lesson,category:swarmEntry.category,tags:swarmEntry.tags,scope:swarmEntry.scope,confidence:0.5,status:"candidate",confirmed_by:[],retrieval_outcomes:{applied_count:0,succeeded_after_count:0,failed_after_count:0},schema_version:config3.schema_version||KNOWLEDGE_SCHEMA_VERSION,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),source_project:swarmEntry.project_name,encounter_score:config3.initial_encounter_score,lineage:buildLineage({actor:"auto",sourceEntryId:swarmEntry.id,sourceCohortId:sourceCohort.cohortId,sourceRevision:lessonRevision(swarmEntry.lesson),priorConfidence:swarmEntry.confidence,priorPhasesAlive:swarmEntry.phases_alive,promotionEventId}),...carryActionableFields(swarmEntry)};entries.push(newHiveEntry),addedBigrams.push(swarmBigram),hiveBigrams.push(swarmBigram),newPromotions++,audit.push(stagePromotionAudit({entryId:newHiveEntry.id,lesson:newHiveEntry.lesson,actor:"auto",sourceEntryId:swarmEntry.id,sourceCohortId:sourceCohort.cohortId,promotionEventId}))}for(let hiveEntry of entries){if(!Array.isArray(hiveEntry.confirmed_by))hiveEntry.confirmed_by=[];let hiveBigram=typeof hiveEntry.lesson==="string"?wordBigrams(hiveEntry.lesson):new Set,nearDuplicate;for(let i=0;i<activeSwarm.length;i++)if(jaccardBigram(hiveBigram,activeSwarmBigrams[i])>=config3.dedup_threshold){nearDuplicate=activeSwarm[i];break}if(!nearDuplicate)continue;if(hiveEntry.lineage?.source_entry_id&&hiveEntry.lineage.source_entry_id===nearDuplicate.id)continue;let sameProject=isSameOrigin(hiveEntry,sourceCohort.cohortId);if(hasProjectConfirmation(hiveEntry,nearDuplicate.project_name,sourceCohort.cohortId))continue;let newConfirmation={project_name:nearDuplicate.project_name,cohort_id:sourceCohort.cohortId,confirmed_at:new Date().toISOString()};hiveEntry.confirmed_by.push(newConfirmation);let currentScore=hiveEntry.encounter_score??1;if(hiveEntry.encounter_score=calculateEncounterScore(currentScore,sameProject,config3),encounters++,hiveEntry.updated_at=new Date().toISOString(),hiveEntry.status==="candidate"&&countDistinctProjects(hiveEntry.confirmed_by)>=3)hiveEntry.status="established",advancements++}if(!(newPromotions>0||encounters>0||advancements>0||merges>0)&&rejects.length===0)return{kind:"noop",return:{newPromotions,encounters,advancements,total:entries.length}};return{kind:"commit",entries,maxEntries:config3.hive_max_entries,rejects:rejects.length>0?rejects:void 0,audit:audit.length>0?audit:void 0,return:{newPromotions,encounters,advancements,total:entries.length}}});if(!result.committed)return{timestamp:new Date().toISOString(),new_promotions:0,encounters_incremented:0,advancements:0,total_hive_entries:0,diagnostics:[...diagnostics,...result.diagnostics,"hive promotion transaction did not commit (see prior diagnostics)"]};let ret=result.return;return{timestamp:new Date().toISOString(),new_promotions:ret?.newPromotions??0,encounters_incremented:ret?.encounters??0,advancements:ret?.advancements??0,total_hive_entries:ret?.total??0,diagnostics:[...diagnostics,...result.diagnostics]}}function stagePromotionAudit(args2){let event={type:"promotion",schema_version:1,event_id:args2.promotionEventId,timestamp:new Date().toISOString(),entry_id:args2.entryId,actor:args2.actor,reason:args2.reason,source_entry_id:args2.sourceEntryId,source_cohort_id:args2.sourceCohortId,override_failed_gates:args2.overrideFailedGates,lesson_excerpt:args2.lesson.slice(0,80)};return{line:JSON.stringify(event)}}function stageMergeAudit(args2){let event={type:"merge",schema_version:1,event_id:crypto.randomUUID(),timestamp:new Date().toISOString(),entry_id:args2.survivingEntryId,action:"merge",merged_from:args2.mergedFromId,authorized:args2.authorized,authorization_basis:args2.authorizationBasis};return{line:JSON.stringify(event)}}async function authorizeAndRecordHiveMerge(args2){let{survivingEntry,losingSourceId,config:config3,hiveDir}=args2,mergedFrom=survivingEntry.lineage?.merged_from??[];if(mergedFrom.includes(losingSourceId))return;let authorized=!0,basis="config-skipped-unlinked";try{let decision=await _internals55.authorizeCuration({directory:hiveDir,action:"merge",entryId:survivingEntry.id,reason:`hive dedup-merge: near-duplicate source ${losingSourceId}`,evidenceScope:"cohort-wide"},{config:config3,entry:{id:survivingEntry.id,producer:null,status:survivingEntry.status}});authorized=decision.authorized,basis=decision.basis}catch(err){authorized=!1,basis=`authorize-error:${err instanceof Error?err.message:String(err)}`}return survivingEntry.lineage=survivingEntry.lineage??{actor:"auto"},survivingEntry.lineage.merged_from=[...mergedFrom,losingSourceId],survivingEntry.updated_at=new Date().toISOString(),stageMergeAudit({survivingEntryId:survivingEntry.id,mergedFromId:losingSourceId,authorized,authorizationBasis:basis})}function createHivePromoterHook(directory,config3){return safeHook(async(_input,_output)=>{let swarmEntries=await _internals55.readSwarmEntries(directory),promotionSummary=await _internals55.checkHivePromotions(swarmEntries,config3,directory);if(!await _internals55.readCuratorSummary(directory))return;if(!(promotionSummary.new_promotions>0||promotionSummary.encounters_incremented>0||promotionSummary.advancements>0))return;await _internals55.appendCuratorRecommendation(directory,{action:"promote",lesson:`Hive promotion: ${promotionSummary.new_promotions} new, ${promotionSummary.encounters_incremented} encounters, ${promotionSummary.advancements} advancements, ${promotionSummary.total_hive_entries} total entries`,reason:JSON.stringify({timestamp:promotionSummary.timestamp,new_promotions:promotionSummary.new_promotions,encounters_incremented:promotionSummary.encounters_incremented,advancements:promotionSummary.advancements,total_hive_entries:promotionSummary.total_hive_entries})})})}function normalizeManualActionability(fields){if(!fields)return{};let out={};for(let key of MANUAL_ACTIONABILITY_KEYS){let normalized=dedupeCapped(fields[key],{cap:MANUAL_ACTIONABILITY_CAP});if(normalized.length>0)out[key]=normalized}return out}async function promoteToHive(directory,lesson,category,options,config3,actionable){let trimmedLesson=lesson.trim(),actionableFields=normalizeManualActionability(actionable),sourceCohort=await _internals55.resolveCohortId(directory),policyConfig=config3??_internals55.loadDefaultKnowledgeConfig(),result=await _internals55.transactHiveStore(async(ctx)=>{if(findNearDuplicate(trimmedLesson,ctx.entries,policyConfig.dedup_threshold))return{kind:"noop",return:"Lesson already exists in hive (near-duplicate)."};let validationResult=_internals55.validateLesson(trimmedLesson,ctx.entries.map((e)=>e.lesson),{category:category||"process",scope:"global",confidence:1});if(validationResult.severity==="error")return{kind:"noop",return:`Lesson rejected by validator: ${validationResult.reason}`};let swarmStandIn={id:"manual-direct",tier:"swarm",lesson:trimmedLesson,category:category||"process",tags:["hive-fast-track"],scope:"global",confidence:1,status:"promoted",confirmed_by:[],retrieval_outcomes:{applied_count:0,succeeded_after_count:0,failed_after_count:0},schema_version:KNOWLEDGE_SCHEMA_VERSION,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),project_name:path93.basename(directory)||"unknown",...actionableFields},decision=evaluatePromotionPolicy({entry:swarmStandIn,config:policyConfig,evidence:[]}),force=options?.force===!0,reason=sanitizeReason(options?.reason),actor,overrideFailedGates;if(decision.eligible)actor="manual";else if(force&&reason&&reason.length>0)actor="manual-override",overrideFailedGates=failedGateNames(decision);else return{kind:"noop",return:`Promotion blocked by policy: ${decision.reason}. Use --force --reason "<why>" to record an audited override.`};let promotionEventId=crypto.randomUUID(),newHiveEntry={id:crypto.randomUUID(),tier:"hive",lesson:trimmedLesson,category:category||"process",tags:[],scope:"global",confidence:1,status:"promoted",confirmed_by:[],retrieval_outcomes:{applied_count:0,succeeded_after_count:0,failed_after_count:0},schema_version:KNOWLEDGE_SCHEMA_VERSION,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),source_project:path93.basename(directory)||"unknown",encounter_score:1,lineage:buildLineage({actor,sourceCohortId:sourceCohort.cohortId,promotionEventId,reason:reason||void 0,overrideFailedGates}),...carryActionableFields(swarmStandIn)},entries=[...ctx.entries,newHiveEntry],audit=[stagePromotionAudit({entryId:newHiveEntry.id,lesson:newHiveEntry.lesson,actor,sourceCohortId:sourceCohort.cohortId,promotionEventId,reason:reason||void 0,overrideFailedGates})];return{kind:"commit",entries,audit,return:`Promoted to hive: "${trimmedLesson.slice(0,50)}${trimmedLesson.length>50?"...":""}" (confidence: 1.0, source: manual${actor==="manual-override"?"-override":""})`}});if(result.return!==void 0)return result.return;return`Promotion failed: ${result.diagnostics.join("; ")||"transaction did not commit"}`}async function promoteFromSwarm(directory,lessonId,options,config3){let swarmEntry=(await readKnowledge(resolveSwarmKnowledgePath(directory))).find((e)=>e.id===lessonId);if(!swarmEntry)throw Error(`Lesson ${lessonId} not found in .swarm/knowledge.jsonl`);let sourceCohort=await _internals55.resolveCohortId(directory),policyConfig=config3??_internals55.loadDefaultKnowledgeConfig(),result=await _internals55.transactHiveStore(async(ctx)=>{if(findNearDuplicate(swarmEntry.lesson,ctx.entries,policyConfig.dedup_threshold))return{kind:"noop",return:"Lesson already exists in hive (near-duplicate)."};let validationResult=_internals55.validateLesson(swarmEntry.lesson,ctx.entries.map((e)=>e.lesson),{category:swarmEntry.category,scope:swarmEntry.scope,confidence:swarmEntry.confidence});if(validationResult.severity==="error")return{kind:"noop",return:`Lesson rejected by validator: ${validationResult.reason}`};let decision=evaluatePromotionPolicy({entry:swarmEntry,config:policyConfig,evidence:[]}),force=options?.force===!0,reason=sanitizeReason(options?.reason),actor,overrideFailedGates;if(decision.eligible)actor="manual";else if(force&&reason&&reason.length>0)actor="manual-override",overrideFailedGates=failedGateNames(decision);else return{kind:"noop",return:`Promotion blocked by policy: ${decision.reason}. Use --force --reason "<why>" to record an audited override.`};let promotionEventId=crypto.randomUUID(),newHiveEntry={id:crypto.randomUUID(),tier:"hive",lesson:swarmEntry.lesson,category:swarmEntry.category,tags:swarmEntry.tags,scope:swarmEntry.scope,confidence:1,status:"promoted",confirmed_by:[],retrieval_outcomes:{applied_count:0,succeeded_after_count:0,failed_after_count:0},schema_version:swarmEntry.schema_version||KNOWLEDGE_SCHEMA_VERSION,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),source_project:swarmEntry.project_name,encounter_score:1,lineage:buildLineage({actor,sourceEntryId:swarmEntry.id,sourceCohortId:sourceCohort.cohortId,promotionEventId,reason:reason||void 0,overrideFailedGates}),...carryActionableFields(swarmEntry)},entries=[...ctx.entries,newHiveEntry],audit=[stagePromotionAudit({entryId:newHiveEntry.id,lesson:newHiveEntry.lesson,actor,sourceEntryId:swarmEntry.id,sourceCohortId:sourceCohort.cohortId,promotionEventId,reason:reason||void 0,overrideFailedGates})];return{kind:"commit",entries,audit,return:`Promoted lesson ${lessonId} from swarm to hive: "${swarmEntry.lesson.slice(0,50)}${swarmEntry.lesson.length>50?"...":""}"`}});if(result.return!==void 0)return result.return;return`Promotion failed: ${result.diagnostics.join("; ")||"transaction did not commit"}`}var MAX_OVERRIDE_REASON_LEN=280,_internals55,MANUAL_ACTIONABILITY_CAP=20,MANUAL_ACTIONABILITY_KEYS;var init_hive_promoter=__esm(()=>{init_schema();init_cohort_identity();init_curation_policy();init_hive_paths();init_curator();init_hive_policy();init_hive_transaction();init_knowledge_store();init_knowledge_types();init_knowledge_validator();init_promotion_evidence_store();init_utils2();init_knowledge_store();_internals55={readSwarmEntries:(directory)=>readKnowledge(resolveSwarmKnowledgePath(directory)),checkHivePromotions,readCuratorSummary,appendCuratorRecommendation,resolveCohortId,transactHiveStore,validateLesson,authorizeCuration,loadPromotionEvidence:async(directory)=>loadPromotionEvidenceByEntry(directory),loadDefaultKnowledgeConfig:()=>KnowledgeConfigSchema.parse({})};MANUAL_ACTIONABILITY_KEYS=["applies_to_tools","applies_to_agents","required_actions","forbidden_actions","verification_checks"]});var exports_curator_drift={};__export(exports_curator_drift,{writeDriftReport:()=>writeDriftReport,runDeterministicDriftCheck:()=>runDeterministicDriftCheck,readPriorDriftReports:()=>readPriorDriftReports,buildDriftInjectionText:()=>buildDriftInjectionText,_internals:()=>_internals56});import*as fs42 from"node:fs";import*as path94 from"node:path";async function readPriorDriftReports(directory){let swarmDir=path94.join(directory,".swarm"),entries=await fs42.promises.readdir(swarmDir).catch(()=>null);if(entries===null)return[];let reportFiles=entries.filter((name)=>name.startsWith(DRIFT_REPORT_PREFIX)&&name.endsWith(".json")).sort(),reports=[];for(let filename of reportFiles){let content=await readSwarmFileAsync(directory,filename);if(content===null)continue;try{let report=JSON.parse(content);if(typeof report.phase!=="number"||typeof report.alignment!=="string"||typeof report.timestamp!=="string"||typeof report.drift_score!=="number"||typeof report.schema_version!=="number"||!Array.isArray(report.compounding_effects)){warn(`[curator-drift] Skipping corrupt drift report: ${filename}`);continue}reports.push(report)}catch{warn(`[curator-drift] Skipping unreadable drift report: ${filename}`)}}return reports.sort((a,b)=>a.phase-b.phase),reports}async function writeDriftReport(directory,report){let filename=`${DRIFT_REPORT_PREFIX}${report.phase}.json`,filePath=validateSwarmPath(directory,filename),swarmDir=path94.dirname(filePath);await fs42.promises.mkdir(swarmDir,{recursive:!0});try{await fs42.promises.writeFile(filePath,JSON.stringify(report,null,2),"utf-8")}catch(err){throw Error(`[curator-drift] Failed to write drift report to ${filePath}: ${String(err)}`)}return filePath}function extractRequirementIds(text){let matches=text.match(/FR-\d{3,}/g);return matches?[...new Set(matches)]:[]}async function runDeterministicDriftCheck(directory,phase,curatorResult,config3,injectAdvisory){try{let planMd=await readSwarmFileAsync(directory,"plan.md"),specMd=readEffectiveSpecSync(directory)?.content??null,priorReports=await _internals56.readPriorDriftReports(directory),complianceCount=curatorResult.compliance.length,warningCompliance=curatorResult.compliance.filter((obs)=>obs.severity==="warning"),alignment="ALIGNED",driftScore=0,specRequirements=specMd?extractRequirementIds(specMd):[],planRequirements=planMd?extractRequirementIds(planMd):[],digestRequirements=extractRequirementIds(JSON.stringify(curatorResult.digest)+JSON.stringify(curatorResult.compliance)+JSON.stringify(curatorResult.knowledge_recommendations??[]));if(!planMd)alignment="MINOR_DRIFT",driftScore=0.3;else if(specRequirements.length>0){let coveredInPlan=specRequirements.filter((fr)=>planRequirements.includes(fr)),coveredInDigest=specRequirements.filter((fr)=>digestRequirements.includes(fr)),specCoverageRatio=coveredInPlan.length/specRequirements.length,implementationRatio=coveredInDigest.length/specRequirements.length;if(specCoverageRatio<0.5)alignment="MAJOR_DRIFT",driftScore=Math.min(0.9,0.6+(1-specCoverageRatio)*0.3);else if(warningCompliance.length>=3)alignment="MAJOR_DRIFT",driftScore=Math.min(0.9,0.5+warningCompliance.length*0.1);else if(warningCompliance.length>=1||complianceCount>=3)alignment="MINOR_DRIFT",driftScore=Math.min(0.49,0.2+complianceCount*0.05);else if(implementationRatio<0.5)alignment="MINOR_DRIFT",driftScore=Math.min(0.6,0.2+(1-implementationRatio)*0.3)}else if(warningCompliance.length>=3)alignment="MAJOR_DRIFT",driftScore=Math.min(0.9,0.5+warningCompliance.length*0.1);else if(warningCompliance.length>=1||complianceCount>=3)alignment="MINOR_DRIFT",driftScore=Math.min(0.49,0.2+complianceCount*0.05);let keyCorrections=warningCompliance.map((obs)=>obs.description),firstDeviation=warningCompliance.length>0?{phase,task:"unknown",description:warningCompliance[0]?.description??""}:null,requirementsChecked=curatorResult.digest.tasks_total,requirementsSatisfied=curatorResult.digest.tasks_completed,coverageNote=specRequirements.length>0?` [${digestRequirements.filter((fr)=>specRequirements.includes(fr)).length}/${specRequirements.length} FRs covered]`:"",injectionSummary=`Phase ${phase}: ${alignment} (${driftScore.toFixed(2)})${coverageNote} — ${firstDeviation?firstDeviation.description:"all requirements on track"}.${keyCorrections.length>0?`Correction: ${keyCorrections[0]??""}.`:""}`.slice(0,config3.drift_inject_max_chars),report={schema_version:1,phase,timestamp:new Date().toISOString(),alignment,drift_score:driftScore,first_deviation:firstDeviation,compounding_effects:priorReports.filter((r)=>r.alignment!=="ALIGNED").map((r)=>`Phase ${r.phase}: ${r.alignment}`).slice(0,5),corrections:keyCorrections.slice(0,5),requirements_checked:requirementsChecked,requirements_satisfied:requirementsSatisfied,scope_additions:[],injection_summary:injectionSummary},reportPath=await _internals56.writeDriftReport(directory,report);if(getGlobalEventBus().publish("curator.drift.completed",{phase,alignment,drift_score:driftScore,report_path:reportPath}),injectAdvisory&&alignment!=="ALIGNED"&&driftScore>0)try{let advisoryText=`CURATOR DRIFT DETECTED (phase ${phase}, score ${driftScore.toFixed(2)}): ${injectionSummary.slice(0,300)}. Review .swarm/${DRIFT_REPORT_PREFIX}${phase}.json and address spec alignment before proceeding. Consider running critic_drift_verifier before phase completion to get a proper drift review.`;injectAdvisory(advisoryText)}catch{}return{phase,report,report_path:reportPath,injection_text:injectionSummary}}catch(err){getGlobalEventBus().publish("curator.error",{operation:"drift",phase,error:String(err)});let defaultReport={schema_version:1,phase,timestamp:new Date().toISOString(),alignment:"ALIGNED",drift_score:0,first_deviation:null,compounding_effects:[],corrections:[],requirements_checked:0,requirements_satisfied:0,scope_additions:[],injection_summary:`Phase ${phase}: drift analysis unavailable (${String(err)})`};return{phase,report:defaultReport,report_path:"",injection_text:""}}}function buildDriftInjectionText(report,maxChars){if(maxChars<=0)return"";let text;if(report.alignment==="ALIGNED"&&report.drift_score<0.1)text=`<drift_report>Phase ${report.phase}: ALIGNED, all requirements on track.</drift_report>`;else{let keyFinding=report.first_deviation?.description??"no deviation recorded",score=report.drift_score??0,correctionClause=report.corrections?.[0]?`Correction: ${report.corrections[0]}.`:"";text=`<drift_report>Phase ${report.phase}: ${report.alignment} (${score.toFixed(2)}) — ${keyFinding}. ${correctionClause}</drift_report>`}return text.slice(0,maxChars)}var DRIFT_REPORT_PREFIX="drift-report-phase-",_internals56;var init_curator_drift=__esm(()=>{init_event_bus();init_effective_spec();init_logger();init_utils2();_internals56={readPriorDriftReports,writeDriftReport,runDeterministicDriftCheck,buildDriftInjectionText}});var exports_curator_postmortem={};__export(exports_curator_postmortem,{runCuratorPostMortem:()=>runCuratorPostMortem,_internals:()=>_internals57});import{existsSync as existsSync39,readdirSync as readdirSync11,readFileSync as readFileSync31}from"node:fs";import*as path95 from"node:path";async function collectKnowledgeSummary(directory,scope="project",sessionID,out){let batch=await claimNextScanBatch(directory,MAX_KNOWLEDGE_ENTRIES);if(out)out.generation=batch.generation;let entries=batch.entries,batchIds=new Set(entries.map((e)=>e.id)),events=(await readKnowledgeEvents(directory)).filter((e)=>{let kid=e.knowledge_id??e.entry_id;return kid!=null&&batchIds.has(kid)});if(scope==="session"&&sessionID)events=events.filter((e)=>e.session_id===sessionID);let countsMap=new Map;for(let e of events){if(e.type!=="applied"&&e.type!=="violated"&&e.type!=="ignored"&&e.type!=="unacknowledged")continue;let kid=e.knowledge_id??e.entry_id;if(!kid)continue;let c=countsMap.get(kid)??{applied:0,violated:0,ignored:0,unacknowledged:0};if(e.type==="applied")c.applied++;else if(e.type==="violated")c.violated++;else if(e.type==="ignored")c.ignored++;else c.unacknowledged++;countsMap.set(kid,c)}return entries.map((entry)=>{let c=countsMap.get(entry.id)??{applied:0,violated:0,ignored:0,unacknowledged:0};return{id:entry.id,lesson:entry.lesson,applied:c.applied,violated:c.violated,ignored:c.ignored,unacknowledged:c.unacknowledged,confidence:entry.confidence??0.5,status:entry.status??"active"}})}function extractSection(text,sectionName){let pattern=new RegExp(`^${sectionName}:\\s*\\n([\\s\\S]*?)(?=\\n[A-Z_]+:\\s*(?:\\n|$)|$)`,"m");return text.match(pattern)?.[1]?.trim()||null}function normalizeRecommendationAction(raw){let value=String(raw??"").toLowerCase().trim();if(value==="promote"||value==="promote_to_hive")return"promote";if(value==="archive"||value==="flag_stale")return"archive";if(value==="rewrite")return"rewrite";if(value==="flag_contradiction")return"flag_contradiction";if(value==="merge")return null;return null}function normalizeProposalSlug(raw){return raw.trim().replace(/^proposals[\\/]/,"").replace(/\.md$/i,"").replace(/\.json$/i,"")}function parseStructuredPostMortemActions(llmOutput){let parsed={summary:extractSection(llmOutput,"SUMMARY"),recommendations:[],queueTriage:[],diagnostics:[]},fence=/```(?:json|jsonc)?\s+postmortem_actions\s*\n([\s\S]*?)\n```/g;for(let match of llmOutput.matchAll(fence)){let data;try{data=JSON.parse(match[1])}catch(err){parsed.diagnostics.push(`postmortem_actions malformed_json: ${err instanceof Error?err.message:String(err)}`);continue}if(!data||typeof data!=="object"||Array.isArray(data)){parsed.diagnostics.push("postmortem_actions expected object");continue}let obj=data;if(typeof obj.summary==="string"&&obj.summary.trim())parsed.summary=obj.summary.trim().slice(0,1000);if(Array.isArray(obj.curation_recommendations))for(let[index,item]of obj.curation_recommendations.entries()){if(!item||typeof item!=="object"){parsed.diagnostics.push(`curation_recommendations[${index}] invalid object`);continue}let rec=item,action=normalizeRecommendationAction(rec.action),lesson=String(rec.lesson??rec.reason??"").trim(),reason=String(rec.reason??lesson).trim();if(!action||!reason){parsed.diagnostics.push(`curation_recommendations[${index}] missing action/reason`);continue}if(action==="rewrite"&&lesson.length<15){parsed.diagnostics.push(`curation_recommendations[${index}] rewrite missing lesson`);continue}parsed.recommendations.push({action,entry_id:typeof rec.entry_id==="string"?normalizeRecommendationEntryIdToken(rec.entry_id):void 0,lesson:(lesson||reason).slice(0,280),reason:reason.slice(0,280),category:typeof rec.category==="string"?rec.category:void 0,confidence:typeof rec.confidence==="number"?rec.confidence:void 0,triggers:stringArray(rec.triggers),required_actions:stringArray(rec.required_actions),forbidden_actions:stringArray(rec.forbidden_actions),applies_to_agents:stringArray(rec.applies_to_agents),applies_to_tools:stringArray(rec.applies_to_tools),verification_checks:stringArray(rec.verification_checks),directive_priority:directivePriority(rec.directive_priority)})}if(Array.isArray(obj.queue_triage))for(let[index,item]of obj.queue_triage.entries()){if(!item||typeof item!=="object"){parsed.diagnostics.push(`queue_triage[${index}] invalid object`);continue}let triage=item,proposalId=String(triage.proposal_id??"").trim(),action=String(triage.action??"").toLowerCase().trim();if(!proposalId||action!=="apply"&&action!=="reject"){parsed.diagnostics.push(`queue_triage[${index}] missing proposal_id/action`);continue}parsed.queueTriage.push({proposal_id:proposalId.slice(0,120),action,reason:String(triage.reason??"").slice(0,280)})}}return parsed}function stringArray(value){if(!Array.isArray(value))return;let strings=value.filter((item)=>typeof item==="string").map((item)=>item.trim()).filter((item)=>item.length>0);return strings.length>0?strings:void 0}function directivePriority(value){if(value==="low"||value==="medium"||value==="high"||value==="critical")return value;return}function parseLegacyPostMortemActions(llmOutput){let parsed={summary:extractSection(llmOutput,"SUMMARY"),recommendations:[],queueTriage:[],diagnostics:[]},curation=extractSection(llmOutput,"CURATION_RECOMMENDATIONS");if(curation){let recIndex=0;for(let line of curation.split(`
1323
1324
  `)){let trimmed=line.trim();if(!trimmed.startsWith("-"))continue;let body=trimmed.replace(/^-\s*/,""),[head2,reasonPart=""]=body.split(/\s+—\s+|\s+-\s+/,2),[rawAction,rest=""]=head2.split(/:\s*/,2),lowerRaw=rawAction.toLowerCase().trim(),action=normalizeRecommendationAction(rawAction);if(!action){if(lowerRaw==="merge")parsed.diagnostics.push("legacy curation_recommendations unsupported action 'merge' — dropped");else if(lowerRaw)parsed.diagnostics.push(`legacy curation_recommendations unrecognized action '${lowerRaw}'`);continue}let idMatch=rest.match(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i),reason=(reasonPart||rest).trim();if(!reason){parsed.diagnostics.push(`legacy curation_recommendations[${recIndex}] missing reason`);continue}parsed.recommendations.push({action,entry_id:idMatch?.[0],lesson:reason.slice(0,280),reason:reason.slice(0,280)}),recIndex++}}let queue=extractSection(llmOutput,"QUEUE_TRIAGE");if(queue)for(let line of queue.split(`
1324
1325
  `)){let trimmed=line.trim();if(!trimmed.startsWith("-"))continue;if(trimmed.includes(":")){let match=trimmed.match(/^-\s*([^:]+):\s*(APPLY|REJECT)\b\s*(?:—|-)?\s*(.*)$/i);if(!match){parsed.diagnostics.push("legacy queue_triage malformed line");continue}parsed.queueTriage.push({proposal_id:match[1].trim().slice(0,120),action:match[2].toLowerCase(),reason:match[3].trim().slice(0,280)})}}return parsed}function parsePostMortemActions(llmOutput){let structured=parseStructuredPostMortemActions(llmOutput),legacy=parseLegacyPostMortemActions(llmOutput);return{summary:structured.summary??legacy.summary,recommendations:structured.recommendations.length>0?structured.recommendations:legacy.recommendations,queueTriage:structured.queueTriage.length>0?structured.queueTriage:legacy.queueTriage,diagnostics:[...structured.diagnostics,...legacy.diagnostics]}}async function executePostMortemActions(directory,parsed,options,generation){let warnings=[],result={knowledge_applied:0,knowledge_skipped:0,hive_promotions:0,hive_encounters_incremented:0,hive_advancements:0,proposals_approved:0,proposals_rejected:0,proposals_skipped:0},knowledgeConfig=options.knowledgeConfig??await _internals57.loadDefaultKnowledgeConfig(directory);if(parsed.recommendations.length>0){try{let knowledgeResult=await _internals57.applyCuratorKnowledgeUpdates(directory,parsed.recommendations,knowledgeConfig,generation);result.knowledge_applied=knowledgeResult.applied,result.knowledge_skipped=knowledgeResult.skipped}catch(err){warnings.push(`Post-mortem knowledge actions failed: ${err instanceof Error?err.message:String(err)}`)}try{let entries=await _internals57.readSwarmKnowledge(directory),hiveResult=await _internals57.checkHivePromotions(entries,knowledgeConfig,directory);result.hive_promotions=hiveResult.new_promotions,result.hive_encounters_incremented=hiveResult.encounters_incremented,result.hive_advancements=hiveResult.advancements}catch(err){warnings.push(`Post-mortem hive promotion check failed: ${err instanceof Error?err.message:String(err)}`)}}if(parsed.queueTriage.length>0)try{let proposalResult=await _internals57.applyProposalTriage(directory,parsed.queueTriage);result.proposals_approved=proposalResult.approved.length,result.proposals_rejected=proposalResult.rejected.length,result.proposals_skipped=proposalResult.skipped.length}catch(err){warnings.push(`Post-mortem proposal triage failed: ${err instanceof Error?err.message:String(err)}`)}return{result,warnings}}async function verifyPostMortemKnowledgeActions(directory,recommendations){if(recommendations.length===0)return[];let activeEntries=(await _internals57.readSwarmKnowledge(directory)).filter((entry)=>isActiveStatus(entry.status)),exactIds=new Set(activeEntries.map((entry)=>entry.id)),prefixMatches=new Map;return recommendations.map((rec)=>{let inputId=typeof rec.entry_id==="string"?normalizeRecommendationEntryIdToken(rec.entry_id)??null:null;if(!inputId){let isNewPromote=rec.action==="promote";return{action:rec.action,input_entry_id:null,resolved_entry_id:null,status:isNewPromote?"new_entry":"missing_entry_id",reason:isNewPromote?"promote without entry_id will create a new candidate if actionable":`${rec.action} requires an existing entry_id`}}if(exactIds.has(inputId))return{action:rec.action,input_entry_id:inputId,resolved_entry_id:inputId,status:"exact_match",reason:"entry_id matched an existing knowledge entry exactly"};let matches=prefixMatches.get(inputId);if(!matches)matches=activeEntries.filter((entry)=>entry.id.startsWith(inputId)),prefixMatches.set(inputId,matches);if(matches.length===1)return{action:rec.action,input_entry_id:inputId,resolved_entry_id:matches[0].id,status:"prefix_match",reason:"entry_id prefix resolved to one existing knowledge entry"};return{action:rec.action,input_entry_id:inputId,resolved_entry_id:null,status:matches.length===0?"not_found":"ambiguous_prefix",reason:matches.length===0?"entry_id did not match any existing knowledge entry":`entry_id prefix matched ${matches.length} knowledge entries`}})}function buildStateFreshnessSection(args2){return["## Generated Against State",`- Plan context: ${args2.planLoaded?`loaded (${args2.planId})`:"unavailable (plan_id: unknown; project-level fallback)"}`,`- Scope: ${args2.scope}${args2.sessionID?` (${args2.sessionID})`:""}`,`- Knowledge entries summarized: ${args2.knowledgeSummary.length}`,`- Pending proposals summarized: ${args2.proposals.length}`,`- Unactionable entries summarized: ${args2.unactionable.length}`,`- Retrospectives summarized: ${args2.retrospectives.length}`,`- Drift reports summarized: ${args2.driftReports.length}`].join(`
1325
1326
  `)}function buildActionVerificationSection(verification){let lines=["## Post-Mortem Action Verification"];if(verification.length===0)return lines.push("- Knowledge actions: none supplied."),lines.join(`
1326
1327
  `);for(let item of verification){let input=item.input_entry_id??"new",resolved=item.resolved_entry_id?` => ${item.resolved_entry_id}`:"";lines.push(`- ${item.action}: ${input}${resolved} [${item.status}] ${item.reason}`)}return lines.join(`
1327
1328
  `)}async function repairPostMortemActions(llmOutput,diagnostics,options){if(!options.llmDelegate||diagnostics.length===0)return null;let ac=new AbortController,timer=setTimeout(()=>ac.abort(),30000);try{let repairPrompt=["Repair the supplied CURATOR_POSTMORTEM output into one valid fenced JSON block.","Return only this fence:","```json postmortem_actions",'{"summary":"...","curation_recommendations":[],"queue_triage":[]}',"```","Allowed curation action values: promote, archive, rewrite, flag_contradiction.","For new promote recommendations, include at least one scope field (applies_to_agents or applies_to_tools) and at least one predicate field (required_actions, forbidden_actions, or verification_checks).","Existing entry_id values may be full UUIDs or unique 8+ character hex prefixes copied from KNOWLEDGE_ENTRIES.","Allowed queue_triage action values: apply, reject.","Do not include unsupported actions such as merge.","Diagnostics:",diagnostics.join("; "),"Original output:",llmOutput.slice(0,8000)].join(`
1328
1329
  `),repaired=await options.llmDelegate("",repairPrompt,ac.signal),parsed=_internals57.parsePostMortemActions(repaired);if(parsed.diagnostics.length===0)return parsed;return null}catch{return null}finally{clearTimeout(timer)}}function readJsonlFile(filePath,maxLines){try{if(!existsSync39(filePath))return[];let content=readFileSync31(filePath,"utf-8"),results=[],max=maxLines!==void 0&&maxLines>0?maxLines:1/0;for(let line of content.split(`
1329
- `)){if(results.length>=max)break;if(!line.trim())continue;try{results.push(JSON.parse(line))}catch{}}return results}catch{return[]}}function collectRetrospectives(directory){let results=[],evidenceDir=path95.join(directory,".swarm","evidence");try{if(!existsSync39(evidenceDir))return results;let retroDirs=readdirSync11(evidenceDir,{withFileTypes:!0}).filter((e)=>e.isDirectory()&&e.name.startsWith("retro-")).slice(0,MAX_RETROSPECTIVES);for(let entry of retroDirs){let retroPath=path95.join(evidenceDir,entry.name,"evidence.json");if(existsSync39(retroPath))try{results.push(readFileSync31(retroPath,"utf-8"))}catch{}}}catch{}return results}async function collectDriftReports(directory){try{return(await _internals57.readPriorDriftReports(directory)).slice(-MAX_DRIFT_REPORTS).map((report)=>JSON.stringify(report,null,2))}catch{return[]}}function collectPendingProposals(directory){let results=[],insightPath=path95.join(directory,".swarm","insight-candidates.jsonl");if(existsSync39(insightPath))try{results.push({source:"insight-candidates",content:readFileSync31(insightPath,"utf-8")})}catch{}let proposalsDir=path95.join(directory,".swarm","skills","proposals");try{if(existsSync39(proposalsDir)){let proposalFiles=readdirSync11(proposalsDir).filter((e)=>e.endsWith(".md")||e.endsWith(".json")).slice(0,MAX_PROPOSALS);for(let entry of proposalFiles)try{results.push({source:`proposals/${entry}`,content:readFileSync31(path95.join(proposalsDir,entry),"utf-8")})}catch{}}}catch{}return results}function isReportValid(reportPath){try{if(!existsSync39(reportPath))return!1;let content=readFileSync31(reportPath,"utf-8").trim();if(content.length===0)return!1;if(!content.startsWith("# Post-Mortem Report:"))return!1;return!0}catch{return!1}}async function acquirePostMortemLock(directory,planId){let result=await tryAcquireLock(directory,`post-mortem-${planId}.lock`,"curator-postmortem",planId);if(result.acquired)return{acquired:!0,release:result.lock?._release};return{acquired:!1}}function buildDataOnlyReport(planId,planSummary,knowledgeSummary,curatorDigest,proposals,unactionable,retrospectives,driftReports,context){let now=new Date().toISOString(),lines=[];lines.push(`# Post-Mortem Report: ${planId}`),lines.push(`Generated: ${now}`),lines.push(""),lines.push(buildStateFreshnessSection({planId,scope:context?.scope??"project",sessionID:context?.sessionID,planLoaded:context?.planLoaded??planId!=="unknown",knowledgeSummary,proposals,unactionable,retrospectives,driftReports})),lines.push(""),lines.push("## Project Summary"),lines.push(planSummary),lines.push(""),lines.push("## Knowledge Metrics");let totalEntries=knowledgeSummary.length,totalApplied=knowledgeSummary.reduce((s,e)=>s+e.applied,0),totalViolated=knowledgeSummary.reduce((s,e)=>s+e.violated,0),totalIgnored=knowledgeSummary.reduce((s,e)=>s+e.ignored,0),neverApplied=knowledgeSummary.filter((e)=>e.applied===0&&e.violated===0&&e.ignored===0);if(lines.push(`- Total entries: ${totalEntries}`),lines.push(`- Application events: ${totalApplied} applied, ${totalViolated} violated, ${totalIgnored} ignored`),lines.push(`- Never-applied entries: ${neverApplied.length}`),totalApplied+totalViolated>0){let appRate=(totalApplied/(totalApplied+totalViolated)*100).toFixed(1);lines.push(`- Application rate: ${appRate}%`)}if(lines.push(""),neverApplied.length>0){lines.push("### Never-Applied Entries (review for retirement)");for(let e of neverApplied.slice(0,10))lines.push(`- \`${e.id}\` (confidence: ${e.confidence.toFixed(2)}): ${e.lesson.slice(0,80)}`);if(neverApplied.length>10)lines.push(`- ... and ${neverApplied.length-10} more`);lines.push("")}let highViolation=knowledgeSummary.filter((e)=>e.violated>0).sort((a,b)=>b.violated-a.violated).slice(0,5);if(highViolation.length>0){lines.push("### High-Violation Entries");for(let e of highViolation)lines.push(`- \`${e.id}\` — ${e.violated} violations, ${e.applied} applied: ${e.lesson.slice(0,80)}`);lines.push("")}lines.push("## Queue Status"),lines.push(`- Pending proposals: ${proposals.length}`),lines.push(`- Unactionable quarantine: ${unactionable.length}`);for(let p of proposals)lines.push(` - ${p.source}`);if(lines.push(""),retrospectives.length>0)lines.push("## Retrospectives"),lines.push(`${retrospectives.length} phase retrospective(s) recorded.`),lines.push("");if(driftReports.length>0){lines.push("## Drift Reports");for(let dr of driftReports)try{let parsed=JSON.parse(dr);lines.push(`- Phase ${parsed.phase}: ${parsed.alignment} (score: ${parsed.drift_score})`)}catch{lines.push("- (unparseable drift report)")}lines.push("")}if(curatorDigest){lines.push("## Curator Digest Summary");let trimmed=curatorDigest.length>1000?`${curatorDigest.slice(0,1000)}...`:curatorDigest;lines.push(trimmed),lines.push("")}return lines.join(`
1330
- `)}function assembleLLMInput(planId,scope,sessionID,planSummary,knowledgeSummary,curatorDigest,proposals,unactionable,retrospectives,driftReports){let sections=[];sections.push(`TASK: CURATOR_POSTMORTEM ${planId}`),sections.push(`SCOPE: ${scope}${sessionID?` (${sessionID})`:""}`),sections.push(`PLAN_SUMMARY: ${planSummary}`),sections.push(`CURATOR_DIGESTS: ${curatorDigest??"none"}`);let eventsSummary=knowledgeSummary.map((e)=>`${e.id}: applied=${e.applied} violated=${e.violated} ignored=${e.ignored} confidence=${e.confidence.toFixed(2)} status=${e.status}`).join(`
1330
+ `)){if(results.length>=max)break;if(!line.trim())continue;try{results.push(JSON.parse(line))}catch{}}return results}catch{return[]}}function collectRetrospectives(directory){let results=[],evidenceDir=path95.join(directory,".swarm","evidence");try{if(!existsSync39(evidenceDir))return results;let retroDirs=readdirSync11(evidenceDir,{withFileTypes:!0}).filter((e)=>e.isDirectory()&&e.name.startsWith("retro-")).slice(0,MAX_RETROSPECTIVES);for(let entry of retroDirs){let retroPath=path95.join(evidenceDir,entry.name,"evidence.json");if(existsSync39(retroPath))try{results.push(readFileSync31(retroPath,"utf-8"))}catch{}}}catch{}return results}async function collectDriftReports(directory){try{return(await _internals57.readPriorDriftReports(directory)).slice(-MAX_DRIFT_REPORTS).map((report)=>JSON.stringify(report,null,2))}catch{return[]}}function collectPendingProposals(directory){let results=[],insightPath=path95.join(directory,".swarm","insight-candidates.jsonl");if(existsSync39(insightPath))try{results.push({source:"insight-candidates",content:readFileSync31(insightPath,"utf-8")})}catch{}let proposalsDir=path95.join(directory,".swarm","skills","proposals");try{if(existsSync39(proposalsDir)){let proposalFiles=readdirSync11(proposalsDir).filter((e)=>e.endsWith(".md")||e.endsWith(".json")).slice(0,MAX_PROPOSALS);for(let entry of proposalFiles)try{results.push({source:`proposals/${entry}`,content:readFileSync31(path95.join(proposalsDir,entry),"utf-8")})}catch{}}}catch{}return results}function isReportValid(reportPath){try{if(!existsSync39(reportPath))return!1;let content=readFileSync31(reportPath,"utf-8").trim();if(content.length===0)return!1;if(!content.startsWith("# Post-Mortem Report:"))return!1;return!0}catch{return!1}}async function acquirePostMortemLock(directory,planId){let result=await tryAcquireLock(directory,`post-mortem-${planId}.lock`,"curator-postmortem",planId);if(result.acquired)return{acquired:!0,release:result.lock?._release};return{acquired:!1}}function buildDataOnlyReport(planId,planSummary,knowledgeSummary,curatorDigest,proposals,unactionable,retrospectives,driftReports,context){let now=new Date().toISOString(),lines=[];lines.push(`# Post-Mortem Report: ${planId}`),lines.push(`Generated: ${now}`),lines.push(""),lines.push(buildStateFreshnessSection({planId,scope:context?.scope??"project",sessionID:context?.sessionID,planLoaded:context?.planLoaded??planId!=="unknown",knowledgeSummary,proposals,unactionable,retrospectives,driftReports})),lines.push(""),lines.push("## Project Summary"),lines.push(planSummary),lines.push(""),lines.push("## Knowledge Metrics");let totalEntries=knowledgeSummary.length,totalApplied=knowledgeSummary.reduce((s,e)=>s+e.applied,0),totalViolated=knowledgeSummary.reduce((s,e)=>s+e.violated,0),totalIgnored=knowledgeSummary.reduce((s,e)=>s+e.ignored,0),totalUnacknowledged=knowledgeSummary.reduce((s,e)=>s+e.unacknowledged,0),neverApplied=knowledgeSummary.filter((e)=>e.applied===0&&e.violated===0&&e.ignored===0);if(lines.push(`- Total entries: ${totalEntries}`),lines.push(`- Application events: ${totalApplied} applied, ${totalViolated} violated, ${totalIgnored} ignored`),lines.push(`- Unacknowledged deliveries: ${totalUnacknowledged} (shown to a delegate that filed no ack/receipt)`),lines.push(`- Never-applied entries: ${neverApplied.length}`),totalApplied+totalViolated>0){let appRate=(totalApplied/(totalApplied+totalViolated)*100).toFixed(1);lines.push(`- Application rate: ${appRate}%`)}if(lines.push(""),neverApplied.length>0){lines.push("### Never-Applied Entries (review for retirement)");for(let e of neverApplied.slice(0,10))lines.push(`- \`${e.id}\` (confidence: ${e.confidence.toFixed(2)}): ${e.lesson.slice(0,80)}`);if(neverApplied.length>10)lines.push(`- ... and ${neverApplied.length-10} more`);lines.push("")}let highViolation=knowledgeSummary.filter((e)=>e.violated>0).sort((a,b)=>b.violated-a.violated).slice(0,5);if(highViolation.length>0){lines.push("### High-Violation Entries");for(let e of highViolation)lines.push(`- \`${e.id}\` — ${e.violated} violations, ${e.applied} applied: ${e.lesson.slice(0,80)}`);lines.push("")}lines.push("## Queue Status"),lines.push(`- Pending proposals: ${proposals.length}`),lines.push(`- Unactionable quarantine: ${unactionable.length}`);for(let p of proposals)lines.push(` - ${p.source}`);if(lines.push(""),retrospectives.length>0)lines.push("## Retrospectives"),lines.push(`${retrospectives.length} phase retrospective(s) recorded.`),lines.push("");if(driftReports.length>0){lines.push("## Drift Reports");for(let dr of driftReports)try{let parsed=JSON.parse(dr);lines.push(`- Phase ${parsed.phase}: ${parsed.alignment} (score: ${parsed.drift_score})`)}catch{lines.push("- (unparseable drift report)")}lines.push("")}if(curatorDigest){lines.push("## Curator Digest Summary");let trimmed=curatorDigest.length>1000?`${curatorDigest.slice(0,1000)}...`:curatorDigest;lines.push(trimmed),lines.push("")}return lines.join(`
1331
+ `)}function assembleLLMInput(planId,scope,sessionID,planSummary,knowledgeSummary,curatorDigest,proposals,unactionable,retrospectives,driftReports){let sections=[];sections.push(`TASK: CURATOR_POSTMORTEM ${planId}`),sections.push(`SCOPE: ${scope}${sessionID?` (${sessionID})`:""}`),sections.push(`PLAN_SUMMARY: ${planSummary}`),sections.push(`CURATOR_DIGESTS: ${curatorDigest??"none"}`);let eventsSummary=knowledgeSummary.map((e)=>`${e.id}: applied=${e.applied} violated=${e.violated} ignored=${e.ignored} unacknowledged=${e.unacknowledged} confidence=${e.confidence.toFixed(2)} status=${e.status}`).join(`
1331
1332
  `);sections.push(`KNOWLEDGE_EVENTS_SUMMARY:
1332
1333
  ${eventsSummary||"none"}`);let knEntries=knowledgeSummary.map((e)=>JSON.stringify({id:e.id,lesson:e.lesson.slice(0,MAX_INPUT_TEXT_CHARS)})).join(`
1333
1334
  `);sections.push(`KNOWLEDGE_ENTRIES:
@@ -1663,7 +1664,7 @@ Flags:
1663
1664
  --out <dir> output directory (default "docs")
1664
1665
  --lang <name> target language for the reference/ docs (default: inferred)
1665
1666
  --update sync existing docs to current code/spec instead of generating fresh`;var init_design_docs=__esm(()=>{init_config();init_warning_buffer();_internals72={loadPluginConfigWithMeta}});import*as os18 from"node:os";import*as path112 from"node:path";function getPluginConfigDir(){return path112.join(process.env.XDG_CONFIG_HOME||path112.join(os18.homedir(),".config"),"opencode")}function getHostConfigDir(){let override=process.env.OPENCODE_CONFIG_DIR;if(override&&override.trim()!=="")return override;return getPluginConfigDir()}function getHostDataDir(){let base=process.env.XDG_DATA_HOME||path112.join(os18.homedir(),".local","share");return path112.join(base,"opencode")}function getHostCacheDir(){let base=process.env.XDG_CACHE_HOME||path112.join(os18.homedir(),".cache");return path112.join(base,"opencode")}function getHostSkillCacheDir(){return path112.join(getHostCacheDir(),"skills")}function getPluginCachePaths(){let cacheBase=process.env.XDG_CACHE_HOME||path112.join(os18.homedir(),".cache"),configDir=getPluginConfigDir(),paths=[path112.join(cacheBase,"opencode","node_modules","opencode-swarm"),path112.join(cacheBase,"opencode","packages","opencode-swarm@latest"),path112.join(configDir,"node_modules","opencode-swarm")];if(process.platform==="darwin"){let libCaches=path112.join(os18.homedir(),"Library","Caches");paths.push(path112.join(libCaches,"opencode","node_modules","opencode-swarm"),path112.join(libCaches,"opencode","packages","opencode-swarm@latest"))}if(process.platform==="win32"){let localAppData=process.env.LOCALAPPDATA||path112.join(os18.homedir(),"AppData","Local"),appData=process.env.APPDATA||path112.join(os18.homedir(),"AppData","Roaming");paths.push(path112.join(localAppData,"opencode","node_modules","opencode-swarm"),path112.join(localAppData,"opencode","packages","opencode-swarm@latest"),path112.join(appData,"opencode","node_modules","opencode-swarm"))}return paths}var init_cache_paths=()=>{};async function readDurableGateEvidence(directory,taskId){try{return await readTaskEvidence(directory,taskId)}catch{return null}}function getDurableGateEvidenceStatus(evidence2){if(!evidence2?.gates||typeof evidence2.gates!=="object")return{isComplete:!1,missingGates:[],evidenceExists:evidence2!=null,invalid:!1};if(!Array.isArray(evidence2.required_gates)||evidence2.required_gates.length===0)return{isComplete:!1,missingGates:["required_gates"],evidenceExists:!0,invalid:!1};let missingGates=evidence2.required_gates.filter((gate)=>evidence2.gates[gate]==null);return{isComplete:missingGates.length===0,missingGates,evidenceExists:!0,invalid:!1}}async function getDurableGateEvidenceStatusForTask(directory,taskId){if(!isValidTaskId2(taskId))return{isComplete:!1,missingGates:[],evidenceExists:!1,invalid:!1};try{return getDurableGateEvidenceStatus(readTaskEvidenceRaw(directory,taskId))}catch{return{isComplete:!1,missingGates:["invalid_gate_evidence"],evidenceExists:!0,invalid:!0}}}function gateEvidenceToEntry(taskId,gate,type,evidence2){let gateRecord=evidence2.gates[gate];if(!gateRecord)return null;let base={task_id:taskId,timestamp:gateRecord.timestamp,agent:gateRecord.agent||gate,verdict:"pass",summary:`Gate evidence recorded by ${gate}`,metadata:{source:"durable_gate_evidence",gate}};if(type==="review")return{...base,type,risk:"low",issues:[]};if(type==="approval")return{...base,type};return{...base,type,tests_passed:0,tests_failed:0,failures:[]}}function mergeDurableGateEntriesFromEvidence(taskId,entries,evidence2){if(!evidence2?.gates)return entries;let merged=[...entries];for(let gate of Object.keys(evidence2.gates).sort()){let type=GATE_EVIDENCE_TYPE_BY_GATE[gate]??"approval";if((type==="review"||type==="test")&&merged.some((entry2)=>entry2.type===type))continue;let entry=gateEvidenceToEntry(taskId,gate,type,evidence2);if(entry)merged.push(entry)}return merged}var GATE_EVIDENCE_TYPE_BY_GATE;var init_gate_bridge=__esm(()=>{init_gate_evidence();GATE_EVIDENCE_TYPE_BY_GATE={reviewer:"review",test_engineer:"test"}});import{existsSync as existsSync49,mkdirSync as mkdirSync31,readFileSync as readFileSync34,writeFileSync as writeFileSync19}from"node:fs";import{homedir as homedir11}from"node:os";import{join as join86}from"node:path";function isStrictSemver(value){return typeof value==="string"&&STRICT_SEMVER.test(value)}function cacheDir(){let xdg=process.env.XDG_CACHE_HOME,base=xdg&&xdg.length>0?xdg:join86(homedir11(),".cache");return join86(base,"opencode-swarm")}function cacheFile(){return join86(cacheDir(),"version-check.json")}function readVersionCache(){try{let path113=cacheFile();if(!existsSync49(path113))return null;let raw=readFileSync34(path113,"utf-8"),parsed=JSON.parse(raw);if(typeof parsed?.checkedAt!=="number")return null;let npmLatest=typeof parsed.npmLatest==="string"?parsed.npmLatest:null;return{checkedAt:parsed.checkedAt,npmLatest}}catch{return null}}function writeVersionCache(entry){try{let dir=cacheDir();mkdirSync31(dir,{recursive:!0}),writeFileSync19(cacheFile(),JSON.stringify(entry,null,2),"utf-8")}catch{}}function parseVersion(version3){let trimmed=version3.trim(),match=SEMVER_REGEX.exec(trimmed);if(!match)return null;return{major:Number.parseInt(match[1],10),minor:Number.parseInt(match[2],10),patch:Number.parseInt(match[3],10),prerelease:match[4]??null}}function normalizeVersionCandidate(version3){if(typeof version3!=="string")return null;let trimmed=version3.trim();return SEMVER_REGEX.test(trimmed)?trimmed:null}function compareVersions(a,b){let aParsed=parseVersion(a),bParsed=parseVersion(b);if(!aParsed||!bParsed)return 0;if(aParsed.major!==bParsed.major)return aParsed.major>bParsed.major?1:-1;if(aParsed.minor!==bParsed.minor)return aParsed.minor>bParsed.minor?1:-1;if(aParsed.patch!==bParsed.patch)return aParsed.patch>bParsed.patch?1:-1;if(aParsed.prerelease&&!bParsed.prerelease)return-1;if(!aParsed.prerelease&&bParsed.prerelease)return 1;if(aParsed.prerelease&&bParsed.prerelease)return aParsed.prerelease<bParsed.prerelease?-1:aParsed.prerelease>bParsed.prerelease?1:0;return 0}async function fetchLatestVersion(signal){try{let res=await _internals73.fetch(NPM_REGISTRY_URL,{signal,headers:{Accept:"application/json"}});if(!res.ok)return null;if(!(res.headers.get("content-type")??"").toLowerCase().includes("json"))return null;let lengthHeader=res.headers.get("content-length");if(lengthHeader){let advertised=Number.parseInt(lengthHeader,10);if(Number.isFinite(advertised)&&advertised>MAX_RESPONSE_BYTES)return null}let text=await res.text();if(text.length>MAX_RESPONSE_BYTES)return null;let body;try{body=JSON.parse(text)}catch{return null}return isStrictSemver(body.version)?body.version:null}catch{return null}}function scheduleVersionCheck(runningVersion,emitWarning,options){if(_checkLatched)return;_checkLatched=!0;let now=options?.now??(()=>Date.now()),fetchImpl=options?.fetchImpl??fetchLatestVersion;queueMicrotask(()=>{runVersionCheck(runningVersion,emitWarning,now,fetchImpl).catch(()=>{})})}async function runVersionCheck(runningVersion,emitWarning,now,fetchImpl){let cached3=readVersionCache(),t=now();if(cached3&&t-cached3.checkedAt<CHECK_INTERVAL_MS){if(cached3.npmLatest)maybeWarn(runningVersion,cached3.npmLatest,emitWarning);return}let controller=new AbortController,timeout=setTimeout(()=>controller.abort(),FETCH_TIMEOUT_MS),npmLatest=null;try{let fetchedVersion=await fetchImpl(controller.signal);npmLatest=normalizeVersionCandidate(fetchedVersion)}finally{clearTimeout(timeout)}if(writeVersionCache({checkedAt:t,npmLatest}),npmLatest)maybeWarn(runningVersion,npmLatest,emitWarning)}function maybeWarn(runningVersion,npmLatest,emitWarning){if(compareVersions(npmLatest,runningVersion)>0)emitWarning(`[opencode-swarm] Update available: ${runningVersion} → ${npmLatest}. OpenCode caches plugins indefinitely. Run \`bunx opencode-swarm update\` to refresh. Also run \`/swarm config doctor\` to check for available config migrations.`)}var NPM_REGISTRY_URL="https://registry.npmjs.org/opencode-swarm/latest",CHECK_INTERVAL_MS=86400000,FETCH_TIMEOUT_MS=5000,SEMVER_REGEX,MAX_RESPONSE_BYTES=262144,STRICT_SEMVER,_checkLatched=!1,_internals73;var init_version_check=__esm(()=>{SEMVER_REGEX=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*))*))?(?:\+([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$/,STRICT_SEMVER=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*))*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;_internals73={fetch:(input,init)=>fetch(input,init)}});import{existsSync as existsSync50,readFileSync as readFileSync35}from"node:fs";import{readFile as readFile33}from"node:fs/promises";import{join as join87}from"node:path";async function readRawLines(filePath){if(!existsSync50(filePath))return{entries:[],corrupt:0};let content=await readFile33(filePath,"utf-8"),entries=[],corrupt=0;for(let line of content.split(`
1666
- `)){let trimmed=line.trim();if(!trimmed)continue;try{entries.push(JSON.parse(trimmed))}catch{corrupt++}}return{entries,corrupt}}function hasV2Counters(entry){let ro=entry.retrieval_outcomes;if(!ro||typeof ro!=="object")return!1;return typeof ro.shown_count==="number"&&typeof ro.applied_explicit_count==="number"&&typeof ro.ignored_count==="number"}function cacheStatus(){let cache2=readVersionCache();if(!cache2?.npmLatest)return"unknown";return compareVersions(cache2.npmLatest,version3)>0?"stale":"fresh"}async function computeKnowledgeDebug(directory){let swarmPath2=resolveSwarmKnowledgePath(directory),hivePath=resolveHiveKnowledgePath2(),eventsPath=resolveKnowledgeEventsPath(directory),[swarmRaw,hiveRaw]=await Promise.all([readRawLines(swarmPath2),readRawLines(hivePath)]),rawEntries=[...swarmRaw.entries,...hiveRaw.entries],corrupt=swarmRaw.corrupt+hiveRaw.corrupt,schemaVersions={},missingV2=0;for(let e of rawEntries){let sv=String(typeof e.schema_version==="number"?e.schema_version:"unknown");if(schemaVersions[sv]=(schemaVersions[sv]??0)+1,!hasV2Counters(e))missingV2++}let normalizedCount=0,active=0,archived=0,quarantined=0,enforcedDirectives=0,escalatedDirectives=0;try{let swarm=await readKnowledge(swarmPath2),hive=await readKnowledge(hivePath);for(let e of[...swarm,...hive]){if(normalizedCount++,e.status==="archived")archived++;else if(e.status==="quarantined")quarantined++;else active++;if(e.status!=="archived"&&e.status!=="quarantined"){if(e.enforcement_mode==="enforce")enforcedDirectives++;if(Array.isArray(e.escalation_history)&&e.escalation_history.length>0)escalatedDirectives++}}}catch{}let rejected=0;try{rejected=(await readRejectedLessons(directory)).length}catch{}let eventCount=0,retrieval7d=0,eventsByType={};try{let events=await readKnowledgeEvents(directory);eventCount=events.length;let cutoff=Date.now()-SEVEN_DAYS_MS2;for(let ev of events){if(eventsByType[ev.type]=(eventsByType[ev.type]??0)+1,ev.type!=="retrieved")continue;let t=Date.parse(ev.timestamp);if(!Number.isNaN(t)&&t>=cutoff)retrieval7d++}}catch{}let unactionableQueueDepth=await safeJsonlCount(resolveUnactionablePathSafe(directory)),insightCandidatesPending=await safeJsonlCount(resolveInsightCandidatesPathSafe(directory)),synonymPairs=0;try{synonymPairs=Object.keys((await readSynonymMap(directory)).pairs).length}catch{}let cohortLinked=!1,cohortPointerVersion=null,cohortLinkId=null,cohortId=null,cohortIdentitySource=null,cohortDegraded=!1,cohortSharedRoot=null,cohortGeneration=null,cohortLocalOrphaned=!1;try{let pointer=readLinkPointer(directory);if(pointer)cohortLinked=!0,cohortPointerVersion=pointer.version,cohortLinkId=pointer.linkId,cohortId=pointer.cohortId??null,cohortIdentitySource=pointer.identitySource??null,cohortDegraded=pointer.degraded??!1,cohortSharedRoot=resolveLinkDir(pointer.linkId),cohortGeneration=pointer.generation??null,cohortLocalOrphaned=getLinkedLocalKnowledgeStatus(directory).orphaned}catch{}let hiveEntriesWithLineage=0,hiveOverridePromotions=0,hiveOverrideEntries=[];try{let hive=await readKnowledge(hivePath);for(let e of hive)if(e.lineage){if(hiveEntriesWithLineage++,e.lineage.actor==="manual-override"){if(hiveOverridePromotions++,hiveOverrideEntries.length<20)hiveOverrideEntries.push({id:e.id,lesson_excerpt:e.lesson.slice(0,80),override_failed_gates:e.lineage.override_failed_gates,reason:e.lineage.reason,promotion_event_id:e.lineage.promotion_event_id})}}}catch{}return{plugin_version:version3,directory,swarm_path:swarmPath2,hive_path:hivePath,events_path:eventsPath,raw_entry_count:rawEntries.length,normalized_entry_count:normalizedCount,corrupt_line_count:corrupt,schema_versions:schemaVersions,entries_missing_v2_counters:missingV2,status_breakdown:{active,archived,quarantined,rejected},event_count:eventCount,retrieval_events_7d:retrieval7d,cache_status:cacheStatus(),learning:{unactionable_queue_depth:unactionableQueueDepth,insight_candidates_pending:insightCandidatesPending,synonym_pairs:synonymPairs,enforced_directives:enforcedDirectives,escalated_directives:escalatedDirectives,events_by_type:eventsByType,shown_vs_applied:{shown:eventsByType.retrieved??0,applied_explicit:eventsByType.applied??0,ignored:eventsByType.ignored??0,contradicted:eventsByType.contradicted??0,violated:eventsByType.violated??0,no_relevant:eventsByType.no_relevant??0}},cohort:{linked:cohortLinked,pointer_version:cohortPointerVersion,link_id:cohortLinkId,cohort_id:cohortId,identity_source:cohortIdentitySource,degraded:cohortDegraded,shared_root:cohortSharedRoot,generation:cohortGeneration,local_orphaned:cohortLocalOrphaned},hive:{entries_with_lineage:hiveEntriesWithLineage,override_promotions:hiveOverridePromotions,override_entries:hiveOverrideEntries},curation:await computeCurationDiagnostics(directory,swarmRaw.entries),memory:computeMemoryCohortDiagnostics(directory)}}function computeMemoryCohortDiagnostics(directory){try{let pointer=readMemoryLinkPointer(directory),provider=null,configFingerprintMatch=null;try{let{loadPluginConfig:loadPluginConfig2}=(init_loader(),__toCommonJS(exports_loader)),cfg=loadPluginConfig2(directory);if(provider=cfg.memory?.provider??null,pointer&&cfg.memory){let cohortConfigPath=join87(resolveLinkDir(pointer.linkId),"memory","memory-cohort-config.json");if(existsSync50(cohortConfigPath)){let stored=JSON.parse(readFileSync35(cohortConfigPath,"utf-8")),expected=computeMemoryCohortFingerprint(buildMemoryCohortFingerprintInput({provider:cfg.memory.provider??"sqlite",redaction:{rejectDurableSecrets:cfg.memory.redaction?.rejectDurableSecrets??!0},embeddings:{model:cfg.memory.embeddings?.model??"Xenova/all-MiniLM-L6-v2",dimension:cfg.memory.embeddings?.dimension??384,version:cfg.memory.embeddings?.version}}));configFingerprintMatch=stored.fingerprint===expected}}}catch{}if(pointer)return{linked:!0,pointer_version:pointer.version,link_id:pointer.linkId,cohort_id:pointer.cohortId??null,identity_source:pointer.identitySource??null,degraded:pointer.degraded??!1,shared_root:pointer.linkId?resolveLinkDir(pointer.linkId):null,generation:pointer.generation??null,provider,config_fingerprint_match:configFingerprintMatch};return{linked:!1,pointer_version:null,link_id:null,cohort_id:null,identity_source:null,degraded:!1,shared_root:null,generation:null,provider,config_fingerprint_match:null}}catch{return{linked:!1,pointer_version:null,link_id:null,cohort_id:null,identity_source:null,degraded:!1,shared_root:null,generation:null,provider:null,config_fingerprint_match:null}}}async function computeCurationDiagnostics(directory,entries){let scanGeneration=0,scanCompleted=!1,scanRemaining=0;try{let{getScanStatus:getScanStatus2}=await Promise.resolve().then(() => (init_scan_cursor(),exports_scan_cursor)),status=await getScanStatus2(directory);scanGeneration=status.generation,scanCompleted=status.completed,scanRemaining=status.remaining_estimate}catch{}let configMatch=null;try{let{isLinked:isLinked2}=await Promise.resolve().then(() => (init_knowledge_link(),exports_knowledge_link));if(isLinked2(directory)){let{KnowledgeConfigSchema:KnowledgeConfigSchema2}=await Promise.resolve().then(() => (init_schema(),exports_schema)),config3;try{let{loadPluginConfigWithMeta:loadPluginConfigWithMeta2}=await Promise.resolve().then(() => (init_config(),exports_config)),loaded=loadPluginConfigWithMeta2(directory);config3=KnowledgeConfigSchema2.parse(loaded.config.knowledge??{})}catch{config3=KnowledgeConfigSchema2.parse({})}let{cohortConfigFingerprint:cohortConfigFingerprint2}=await Promise.resolve().then(() => (init_config_fingerprint(),exports_config_fingerprint)),{buildConfigFingerprintInput:buildConfigFingerprintInput2,readCohortConfigFingerprint:readCohortConfigFingerprint2}=await Promise.resolve().then(() => (init_curation_policy(),exports_curation_policy)),currentFp=cohortConfigFingerprint2(buildConfigFingerprintInput2(config3)),cohortFp=await readCohortConfigFingerprint2(directory);configMatch=cohortFp===null?null:currentFp===cohortFp}}catch{}let withProvenance=0,unknownOwner=0;for(let e of entries)if(e.producer!=null)withProvenance++;else unknownOwner++;let pendingProposals=await countPendingProposals(directory);return{scan_generation:scanGeneration,scan_completed:scanCompleted,scan_remaining_estimate:scanRemaining,config_fingerprint_match:configMatch,entries_with_provenance:withProvenance,entries_unknown_owner:unknownOwner,pending_proposals:pendingProposals}}async function countPendingProposals(directory){let proposalsPath;try{proposalsPath=join87(resolveKnowledgeStoreDir(directory),"curation-proposals.jsonl")}catch{return 0}if(!existsSync50(proposalsPath))return 0;try{let content=await readFile33(proposalsPath,"utf-8"),n=0;for(let line of content.split(`
1667
+ `)){let trimmed=line.trim();if(!trimmed)continue;try{entries.push(JSON.parse(trimmed))}catch{corrupt++}}return{entries,corrupt}}function hasV2Counters(entry){let ro=entry.retrieval_outcomes;if(!ro||typeof ro!=="object")return!1;return typeof ro.shown_count==="number"&&typeof ro.applied_explicit_count==="number"&&typeof ro.ignored_count==="number"}function cacheStatus(){let cache2=readVersionCache();if(!cache2?.npmLatest)return"unknown";return compareVersions(cache2.npmLatest,version3)>0?"stale":"fresh"}async function computeKnowledgeDebug(directory){let swarmPath2=resolveSwarmKnowledgePath(directory),hivePath=resolveHiveKnowledgePath2(),eventsPath=resolveKnowledgeEventsPath(directory),[swarmRaw,hiveRaw]=await Promise.all([readRawLines(swarmPath2),readRawLines(hivePath)]),rawEntries=[...swarmRaw.entries,...hiveRaw.entries],corrupt=swarmRaw.corrupt+hiveRaw.corrupt,schemaVersions={},missingV2=0;for(let e of rawEntries){let sv=String(typeof e.schema_version==="number"?e.schema_version:"unknown");if(schemaVersions[sv]=(schemaVersions[sv]??0)+1,!hasV2Counters(e))missingV2++}let normalizedCount=0,active=0,archived=0,quarantined=0,enforcedDirectives=0,escalatedDirectives=0;try{let swarm=await readKnowledge(swarmPath2),hive=await readKnowledge(hivePath);for(let e of[...swarm,...hive]){if(normalizedCount++,e.status==="archived")archived++;else if(e.status==="quarantined")quarantined++;else active++;if(e.status!=="archived"&&e.status!=="quarantined"){if(e.enforcement_mode==="enforce")enforcedDirectives++;if(Array.isArray(e.escalation_history)&&e.escalation_history.length>0)escalatedDirectives++}}}catch{}let rejected=0;try{rejected=(await readRejectedLessons(directory)).length}catch{}let eventCount=0,retrieval7d=0,eventsByType={};try{let events=await readKnowledgeEvents(directory);eventCount=events.length;let cutoff=Date.now()-SEVEN_DAYS_MS2;for(let ev of events){if(eventsByType[ev.type]=(eventsByType[ev.type]??0)+1,ev.type!=="retrieved")continue;let t=Date.parse(ev.timestamp);if(!Number.isNaN(t)&&t>=cutoff)retrieval7d++}}catch{}let unactionableQueueDepth=await safeJsonlCount(resolveUnactionablePathSafe(directory)),insightCandidatesPending=await safeJsonlCount(resolveInsightCandidatesPathSafe(directory)),synonymPairs=0;try{synonymPairs=Object.keys((await readSynonymMap(directory)).pairs).length}catch{}let cohortLinked=!1,cohortPointerVersion=null,cohortLinkId=null,cohortId=null,cohortIdentitySource=null,cohortDegraded=!1,cohortSharedRoot=null,cohortGeneration=null,cohortLocalOrphaned=!1;try{let pointer=readLinkPointer(directory);if(pointer)cohortLinked=!0,cohortPointerVersion=pointer.version,cohortLinkId=pointer.linkId,cohortId=pointer.cohortId??null,cohortIdentitySource=pointer.identitySource??null,cohortDegraded=pointer.degraded??!1,cohortSharedRoot=resolveLinkDir(pointer.linkId),cohortGeneration=pointer.generation??null,cohortLocalOrphaned=getLinkedLocalKnowledgeStatus(directory).orphaned}catch{}let hiveEntriesWithLineage=0,hiveOverridePromotions=0,hiveOverrideEntries=[];try{let hive=await readKnowledge(hivePath);for(let e of hive)if(e.lineage){if(hiveEntriesWithLineage++,e.lineage.actor==="manual-override"){if(hiveOverridePromotions++,hiveOverrideEntries.length<20)hiveOverrideEntries.push({id:e.id,lesson_excerpt:e.lesson.slice(0,80),override_failed_gates:e.lineage.override_failed_gates,reason:e.lineage.reason,promotion_event_id:e.lineage.promotion_event_id})}}}catch{}return{plugin_version:version3,directory,swarm_path:swarmPath2,hive_path:hivePath,events_path:eventsPath,raw_entry_count:rawEntries.length,normalized_entry_count:normalizedCount,corrupt_line_count:corrupt,schema_versions:schemaVersions,entries_missing_v2_counters:missingV2,status_breakdown:{active,archived,quarantined,rejected},event_count:eventCount,retrieval_events_7d:retrieval7d,cache_status:cacheStatus(),learning:{unactionable_queue_depth:unactionableQueueDepth,insight_candidates_pending:insightCandidatesPending,synonym_pairs:synonymPairs,enforced_directives:enforcedDirectives,escalated_directives:escalatedDirectives,events_by_type:eventsByType,shown_vs_applied:{shown:eventsByType.retrieved??0,applied_explicit:eventsByType.applied??0,ignored:eventsByType.ignored??0,contradicted:eventsByType.contradicted??0,violated:eventsByType.violated??0,no_relevant:eventsByType.no_relevant??0,unacknowledged:eventsByType.unacknowledged??0}},cohort:{linked:cohortLinked,pointer_version:cohortPointerVersion,link_id:cohortLinkId,cohort_id:cohortId,identity_source:cohortIdentitySource,degraded:cohortDegraded,shared_root:cohortSharedRoot,generation:cohortGeneration,local_orphaned:cohortLocalOrphaned},hive:{entries_with_lineage:hiveEntriesWithLineage,override_promotions:hiveOverridePromotions,override_entries:hiveOverrideEntries},curation:await computeCurationDiagnostics(directory,swarmRaw.entries),memory:computeMemoryCohortDiagnostics(directory)}}function computeMemoryCohortDiagnostics(directory){try{let pointer=readMemoryLinkPointer(directory),provider=null,configFingerprintMatch=null;try{let{loadPluginConfig:loadPluginConfig2}=(init_loader(),__toCommonJS(exports_loader)),cfg=loadPluginConfig2(directory);if(provider=cfg.memory?.provider??null,pointer&&cfg.memory){let cohortConfigPath=join87(resolveLinkDir(pointer.linkId),"memory","memory-cohort-config.json");if(existsSync50(cohortConfigPath)){let stored=JSON.parse(readFileSync35(cohortConfigPath,"utf-8")),expected=computeMemoryCohortFingerprint(buildMemoryCohortFingerprintInput({provider:cfg.memory.provider??"sqlite",redaction:{rejectDurableSecrets:cfg.memory.redaction?.rejectDurableSecrets??!0},embeddings:{model:cfg.memory.embeddings?.model??"Xenova/all-MiniLM-L6-v2",dimension:cfg.memory.embeddings?.dimension??384,version:cfg.memory.embeddings?.version}}));configFingerprintMatch=stored.fingerprint===expected}}}catch{}if(pointer)return{linked:!0,pointer_version:pointer.version,link_id:pointer.linkId,cohort_id:pointer.cohortId??null,identity_source:pointer.identitySource??null,degraded:pointer.degraded??!1,shared_root:pointer.linkId?resolveLinkDir(pointer.linkId):null,generation:pointer.generation??null,provider,config_fingerprint_match:configFingerprintMatch};return{linked:!1,pointer_version:null,link_id:null,cohort_id:null,identity_source:null,degraded:!1,shared_root:null,generation:null,provider,config_fingerprint_match:null}}catch{return{linked:!1,pointer_version:null,link_id:null,cohort_id:null,identity_source:null,degraded:!1,shared_root:null,generation:null,provider:null,config_fingerprint_match:null}}}async function computeCurationDiagnostics(directory,entries){let scanGeneration=0,scanCompleted=!1,scanRemaining=0;try{let{getScanStatus:getScanStatus2}=await Promise.resolve().then(() => (init_scan_cursor(),exports_scan_cursor)),status=await getScanStatus2(directory);scanGeneration=status.generation,scanCompleted=status.completed,scanRemaining=status.remaining_estimate}catch{}let configMatch=null;try{let{isLinked:isLinked2}=await Promise.resolve().then(() => (init_knowledge_link(),exports_knowledge_link));if(isLinked2(directory)){let{KnowledgeConfigSchema:KnowledgeConfigSchema2}=await Promise.resolve().then(() => (init_schema(),exports_schema)),config3;try{let{loadPluginConfigWithMeta:loadPluginConfigWithMeta2}=await Promise.resolve().then(() => (init_config(),exports_config)),loaded=loadPluginConfigWithMeta2(directory);config3=KnowledgeConfigSchema2.parse(loaded.config.knowledge??{})}catch{config3=KnowledgeConfigSchema2.parse({})}let{cohortConfigFingerprint:cohortConfigFingerprint2}=await Promise.resolve().then(() => (init_config_fingerprint(),exports_config_fingerprint)),{buildConfigFingerprintInput:buildConfigFingerprintInput2,readCohortConfigFingerprint:readCohortConfigFingerprint2}=await Promise.resolve().then(() => (init_curation_policy(),exports_curation_policy)),currentFp=cohortConfigFingerprint2(buildConfigFingerprintInput2(config3)),cohortFp=await readCohortConfigFingerprint2(directory);configMatch=cohortFp===null?null:currentFp===cohortFp}}catch{}let withProvenance=0,unknownOwner=0;for(let e of entries)if(e.producer!=null)withProvenance++;else unknownOwner++;let pendingProposals=await countPendingProposals(directory);return{scan_generation:scanGeneration,scan_completed:scanCompleted,scan_remaining_estimate:scanRemaining,config_fingerprint_match:configMatch,entries_with_provenance:withProvenance,entries_unknown_owner:unknownOwner,pending_proposals:pendingProposals}}async function countPendingProposals(directory){let proposalsPath;try{proposalsPath=join87(resolveKnowledgeStoreDir(directory),"curation-proposals.jsonl")}catch{return 0}if(!existsSync50(proposalsPath))return 0;try{let content=await readFile33(proposalsPath,"utf-8"),n=0;for(let line of content.split(`
1667
1668
  `)){let trimmed=line.trim();if(!trimmed)continue;try{if(JSON.parse(trimmed).status==="pending")n++}catch{}}return n}catch{return 0}}async function safeJsonlCount(filePath){if(!filePath||!existsSync50(filePath))return 0;try{let content=await readFile33(filePath,"utf-8"),n=0;for(let line of content.split(`
1668
1669
  `))if(line.trim())n++;return n}catch{return 0}}function resolveUnactionablePathSafe(directory){try{return resolveUnactionablePath(directory)}catch{return null}}function resolveInsightCandidatesPathSafe(directory){try{return resolveInsightCandidatesPath(directory)}catch{return null}}async function checkKnowledgeHealth(directory){let debug;try{debug=await computeKnowledgeDebug(directory)}catch{return{name:"Knowledge health",status:"⚠️",detail:"Could not compute knowledge diagnostics"}}let{status_breakdown:sb,learning:lr,cohort:co,hive:hv,curation:cu}=debug,cohortTag=co.linked?` | cohort[linked id=${co.link_id}${co.cohort_id?` cohort=${co.cohort_id}`:""}${co.identity_source?` via=${co.identity_source}`:""}${co.degraded?" DEGRADED":""}${co.local_orphaned?" local-orphan":""}${co.generation!==null?` gen=${co.generation}`:""}]`:" | cohort[local]",hiveTag=hv.entries_with_lineage>0||hv.override_promotions>0?` | hive[lineage=${hv.entries_with_lineage} overrides=${hv.override_promotions}]`:" | hive[local]",scanPart=cu.scan_completed?`scan[gen=${cu.scan_generation} complete]`:`scan[gen=${cu.scan_generation} remaining=${cu.scan_remaining_estimate}]`,fpPart=cu.config_fingerprint_match===null?"fp=n/a":cu.config_fingerprint_match?"fp=match":"fp=MISMATCH",provenanceTotal=cu.entries_with_provenance+cu.entries_unknown_owner,curationTag=` | curation[${scanPart} ${fpPart} provenance=${cu.entries_with_provenance}/${provenanceTotal} proposals=${cu.pending_proposals}]`,summary=`active=${sb.active} archived=${sb.archived} quarantined=${sb.quarantined} rejected=${sb.rejected} | events=${debug.event_count} (retrieved/7d=${debug.retrieval_events_7d}) | learning[enforce=${lr.enforced_directives} escalated=${lr.escalated_directives} synonyms=${lr.synonym_pairs} unactionable=${lr.unactionable_queue_depth} insights_pending=${lr.insight_candidates_pending}] | schema=${JSON.stringify(debug.schema_versions)}`+cohortTag+hiveTag+curationTag,warnings=[];if(co.linked&&co.degraded)warnings.push(`cohort identity is degraded (via ${co.identity_source}): shared store is machine-local, not portable across machines`);if(co.linked&&co.local_orphaned)warnings.push("local .swarm/knowledge.jsonl is orphaned by the link store (benign; resolver ignores it)");if(lr.unactionable_queue_depth>UNACTIONABLE_BACKLOG_WARN)warnings.push(`${lr.unactionable_queue_depth} lessons stuck in the unactionable queue (curator may not be draining)`);if(lr.insight_candidates_pending>INSIGHT_BACKLOG_WARN)warnings.push(`${lr.insight_candidates_pending} micro-reflection insight candidates pending (curator may not be folding them in)`);if(debug.corrupt_line_count>0)warnings.push(`${debug.corrupt_line_count} corrupt JSONL line(s) (raw=${debug.raw_entry_count} vs normalized=${debug.normalized_entry_count})`);if(debug.entries_missing_v2_counters>0)warnings.push(`${debug.entries_missing_v2_counters} entr(y/ies) missing v2 counters (normalized on read)`);if(debug.cache_status==="stale")warnings.push("stale plugin cache — run `bunx opencode-swarm update` (knowledge tools may be running old code)");if(hv.override_promotions>0){let sample=hv.override_entries[0],gates=sample?.override_failed_gates?.join(",")??"?";warnings.push(`${hv.override_promotions} hive entr(y/ies) promoted via --force override (failed gates: ${gates}${sample?.reason?`; reason: "${sample.reason.slice(0,60)}"`:""})`)}if(cu.config_fingerprint_match===!1)warnings.push("cohort config fingerprint mismatch: this worktree curates with different knowledge semantics than the cohort — align knowledge config across linked worktrees");if(cu.pending_proposals>0)warnings.push(`${cu.pending_proposals} pending curation proposal(s) awaiting confirmation (blocked destructive actions recorded in curation-proposals.jsonl)`);if(warnings.length>0)return{name:"Knowledge health",status:"⚠️",detail:`${summary} — ${warnings.join("; ")}`};return{name:"Knowledge health",status:"✅",detail:summary}}var version3,SEVEN_DAYS_MS2=604800000,UNACTIONABLE_BACKLOG_WARN=100,INSIGHT_BACKLOG_WARN=50;var init_knowledge_diagnostics=__esm(()=>{init_package();init_knowledge_events();init_knowledge_link();init_knowledge_store();init_knowledge_validator();init_micro_reflector();init_memory_link();init_redaction();init_synonym_map();init_version_check();({version:version3}=package_default)});import*as child_process8 from"node:child_process";import{existsSync as existsSync51,readdirSync as readdirSync13,readFileSync as readFileSync36,statSync as statSync22}from"node:fs";import*as path113 from"node:path";import{fileURLToPath as fileURLToPath2}from"node:url";function resolveCachePackageRoot(cachePath){let nestedPackageRoot=path113.join(cachePath,"node_modules","opencode-swarm");return existsSync51(nestedPackageRoot)?nestedPackageRoot:cachePath}function validateTaskDag(plan){let allTaskIds=new Set;for(let phase of plan.phases)for(let task of phase.tasks)allTaskIds.add(task.id);let missingDeps=[];for(let phase of plan.phases)for(let task of phase.tasks)for(let dep of task.depends)if(!allTaskIds.has(dep))missingDeps.push(`${task.id} depends on missing ${dep}`);return{valid:missingDeps.length===0,missingDeps}}async function checkEvidenceCompleteness(directory,plan){let completedTaskIds=[];for(let phase of plan.phases)for(let task of phase.tasks)if(task.status==="completed")completedTaskIds.push(task.id);if(completedTaskIds.length>0){let evidenceTaskIds=new Set(await listEvidenceTaskIds(directory)),missingEvidence=[];for(let id of completedTaskIds){let gateStatus=await getDurableGateEvidenceStatusForTask(directory,id);if(gateStatus.isComplete)continue;if(gateStatus.evidenceExists&&gateStatus.missingGates.length>0){missingEvidence.push(id);continue}if(evidenceTaskIds.has(id))continue;missingEvidence.push(id)}if(missingEvidence.length===0)return{name:"Evidence",status:"✅",detail:`All ${completedTaskIds.length} completed tasks have evidence`};else return{name:"Evidence",status:"❌",detail:`${missingEvidence.length} completed task(s) missing evidence: ${missingEvidence.join(", ")}`}}return{name:"Evidence",status:"✅",detail:"No completed tasks yet"}}async function checkSwarmIdentity(plan){let activeSwarmId=process.env.OPENCODE_SWARM_ID;if(plan&&!activeSwarmId)return{name:"Swarm Identity",status:"❌",detail:"Plan exists but OPENCODE_SWARM_ID not set in environment"};if(!plan&&!activeSwarmId)return{name:"Swarm Identity",status:"✅",detail:"No conflict detected"};if(!plan)return{name:"Swarm Identity",status:"✅",detail:`No plan, but OPENCODE_SWARM_ID is '${activeSwarmId}'`};if(plan&&plan.swarm!==activeSwarmId)return{name:"Swarm Identity",status:"❌",detail:`Swarm identity mismatch: plan says '${plan.swarm}', active is '${activeSwarmId}'`};return{name:"Swarm Identity",status:"✅",detail:`Swarm identity consistent: '${plan.swarm}'`}}async function checkPhaseBoundaries(plan){if(!plan)return{name:"Phase Boundaries",status:"✅",detail:"No plan to validate"};let mismatches=[];for(let phase of plan.phases)for(let task of phase.tasks){let taskPhaseNum=parseInt(task.id.split(".")[0],10);if(Number.isNaN(taskPhaseNum))mismatches.push(`Task ${task.id} has invalid phase number`);else if(taskPhaseNum!==phase.id)mismatches.push(`Task ${task.id} found under Phase ${phase.id}`)}if(mismatches.length===0)return{name:"Phase Boundaries",status:"✅",detail:"All tasks correctly aligned to phases"};return{name:"Phase Boundaries",status:"❌",detail:mismatches.join("; ")}}async function checkOrphanedEvidence(directory,plan){if(!plan)return{name:"Orphaned Evidence",status:"✅",detail:"No plan to cross-reference"};let planTaskIds=new Set;for(let phase of plan.phases)for(let task of phase.tasks)planTaskIds.add(task.id);try{let orphaned=(await listEvidenceTaskIds(directory)).filter((id)=>!planTaskIds.has(id)&&!/^retro-/.test(id));if(orphaned.length===0)return{name:"Orphaned Evidence",status:"✅",detail:"All evidence entries reference valid plan tasks"};return{name:"Orphaned Evidence",status:"❌",detail:`Evidence for [${orphaned.join(", ")}] not in plan`}}catch{return{name:"Orphaned Evidence",status:"❌",detail:"Could not read evidence directory"}}}async function checkPlanSync(directory,plan){if(!plan)return{name:"Plan Sync",status:"✅",detail:"No plan.json present"};try{let jsonTaskCount=0;for(let phase of plan.phases)jsonTaskCount+=phase.tasks.length;let planMdContent=await readSwarmFileAsync(directory,"plan.md");if(!planMdContent)return{name:"Plan Sync",status:"✅",detail:"plan.md not present"};let mdTaskCount=(planMdContent.match(/^- \[[ xX~]/gm)||[]).length;if(jsonTaskCount===mdTaskCount)return{name:"Plan Sync",status:"✅",detail:`plan.json and plan.md both have ${jsonTaskCount} tasks`};return{name:"Plan Sync",status:"❌",detail:`plan.json: ${jsonTaskCount} tasks, plan.md: ${mdTaskCount} — run /swarm sync-plan`}}catch{return{name:"Plan Sync",status:"❌",detail:"Could not compare plan files"}}}async function checkConfigBackups(directory){try{let backupCount=readdirSync13(directory).filter((f)=>/\.opencode-swarm\.yaml\.bak/.test(f)).length;if(backupCount<=5)return{name:"Config Backups",status:"✅",detail:`${backupCount} backup file(s) — within acceptable range`};if(backupCount<=19)return{name:"Config Backups",status:"❌",detail:`${backupCount} backup config files found — consider cleanup`};return{name:"Config Backups",status:"❌",detail:`${backupCount} backup config files found — cleanup required`}}catch{return{name:"Config Backups",status:"✅",detail:"Could not check backup files"}}}async function checkGitRepository(directory){try{if(!existsSync51(directory)||!statSync22(directory).isDirectory())return{name:"Git Repository",status:"❌",detail:"Invalid directory — cannot check git status"};return child_process8.execSync("git rev-parse --git-dir",{cwd:directory,stdio:"pipe"}),{name:"Git Repository",status:"✅",detail:"Git repository detected"}}catch{return{name:"Git Repository",status:"❌",detail:"Not a git repository — version control recommended"}}}async function checkSpecStaleness(directory,plan){let specContent=readEffectiveSpecSync(directory)?.content??null;if(!specContent)return{name:"Spec Staleness",status:"✅",detail:"No effective spec present"};if(!plan)return{name:"Spec Staleness",status:"✅",detail:"No plan to compare spec against"};let titleMatch=specContent.match(/^#\s+(.+)$/m);if(!titleMatch)return{name:"Spec Staleness",status:"✅",detail:"Spec title not detectable"};let specTitle=titleMatch[1].trim(),planTitle=plan.title.trim();if(specTitle.toLowerCase()===planTitle.toLowerCase())return{name:"Spec Staleness",status:"✅",detail:"Spec and plan titles are aligned"};return{name:"Spec Staleness",status:"❌",detail:`Spec/plan title mismatch: spec says '${specTitle}', plan says '${planTitle}'`}}async function checkConfigParseability(directory){let configPath=path113.join(directory,".opencode/opencode-swarm.json");if(!existsSync51(configPath))return{name:"Config Parseability",status:"✅",detail:"No project config file present (using defaults)"};try{let content=readFileSync36(configPath,"utf-8");return JSON.parse(content),{name:"Config Parseability",status:"✅",detail:"Project config is valid JSON"}}catch(err){return{name:"Config Parseability",status:"❌",detail:`Project config at .opencode/opencode-swarm.json is not valid JSON: ${err instanceof Error?err.message:"Unknown error"}`}}}function resolveGrammarDir(thisDir){let normalized=thisDir.replace(/\\/g,"/"),isSource=normalized.endsWith("/src/services"),isCliBundle=normalized.endsWith("/cli");return isSource||isCliBundle?path113.join(thisDir,"..","lang","grammars"):path113.join(thisDir,"lang","grammars")}async function checkGrammarWasmFiles(){let grammarFiles=["tree-sitter-javascript.wasm","tree-sitter-typescript.wasm","tree-sitter-tsx.wasm","tree-sitter-python.wasm","tree-sitter-go.wasm","tree-sitter-rust.wasm","tree-sitter-cpp.wasm","tree-sitter-c-sharp.wasm","tree-sitter-css.wasm","tree-sitter-bash.wasm","tree-sitter-ruby.wasm","tree-sitter-php.wasm","tree-sitter-java.wasm","tree-sitter-kotlin.wasm","tree-sitter-swift.wasm","tree-sitter-dart.wasm","tree-sitter-powershell.wasm","tree-sitter-ini.wasm","tree-sitter-regex.wasm"],thisDir=path113.dirname(fileURLToPath2(import.meta.url)),grammarDir=resolveGrammarDir(thisDir),missing=[];if(!existsSync51(path113.join(grammarDir,"tree-sitter.wasm")))missing.push("tree-sitter.wasm (core runtime)");for(let file3 of grammarFiles)if(!existsSync51(path113.join(grammarDir,file3)))missing.push(file3);if(missing.length===0)return{name:"Grammar WASM Files",status:"✅",detail:`Core runtime + all ${grammarFiles.length} grammar WASM files present`};return{name:"Grammar WASM Files",status:"❌",detail:`${missing.length} WASM file(s) missing: ${missing.join(", ")}`}}async function checkCheckpointManifest(directory){let manifestPath=path113.join(directory,".swarm/checkpoints.json");if(!existsSync51(manifestPath))return{name:"Checkpoint Manifest",status:"✅",detail:"No checkpoint manifest (no checkpoints saved)"};try{let content=readFileSync36(manifestPath,"utf-8"),parsed=JSON.parse(content);if(!parsed.checkpoints||!Array.isArray(parsed.checkpoints))return{name:"Checkpoint Manifest",status:"❌",detail:"checkpoints.json missing 'checkpoints' array"};let invalidCount=0;for(let cp2 of parsed.checkpoints)if(typeof cp2.label!=="string"||typeof cp2.sha!=="string"||typeof cp2.timestamp!=="string")invalidCount++;if(invalidCount>0)return{name:"Checkpoint Manifest",status:"❌",detail:`${invalidCount} checkpoint(s) have invalid structure (missing label/sha/timestamp)`};return{name:"Checkpoint Manifest",status:"✅",detail:`Checkpoint manifest valid — ${parsed.checkpoints.length} checkpoint(s)`}}catch(err){if(err instanceof SyntaxError)return{name:"Checkpoint Manifest",status:"❌",detail:"checkpoints.json is not valid JSON"};return{name:"Checkpoint Manifest",status:"❌",detail:"Could not read checkpoint manifest"}}}async function checkEventStreamIntegrity(directory){let eventsPath=path113.join(directory,".swarm/events.jsonl");if(!existsSync51(eventsPath))return{name:"Event Stream",status:"✅",detail:"No events.jsonl present"};try{let lines=readFileSync36(eventsPath,"utf-8").split(`
1669
1670
  `).filter((line)=>line.trim()!==""),malformedCount=0;for(let line of lines)try{JSON.parse(line)}catch{malformedCount++}if(malformedCount===0)return{name:"Event Stream",status:"✅",detail:`events.jsonl is valid — ${lines.length} event(s)`};return{name:"Event Stream",status:"❌",detail:`events.jsonl has ${malformedCount} malformed line(s) — possible data corruption`}}catch{return{name:"Event Stream",status:"❌",detail:"Could not read events.jsonl"}}}async function checkSteeringDirectives(directory){let eventsPath=path113.join(directory,".swarm/events.jsonl");if(!existsSync51(eventsPath))return{name:"Steering Directives",status:"✅",detail:"No events.jsonl — no steering directives to check"};try{let lines=readFileSync36(eventsPath,"utf-8").split(`
@@ -6031,41 +6032,41 @@ ${rendered.map((r)=>r.line).join(`
6031
6032
  ${rendered.map((r)=>r.line).join(`
6032
6033
  `)}`;return rendered.length>0?{block,renderedIds:rendered.map((r)=>r.id)}:{block:null,renderedIds:[]}}function buildDirectiveBlock(entries,charBudget,cfg){if(entries.length===0)return{block:null,renderedIds:[]};let maxDisplay=cfg.max_lesson_display_chars??120,records=[];for(let e of entries){let trigger=e.triggers&&e.triggers.length>0?sanitizeLessonForContext(e.triggers[0]).slice(0,maxDisplay):"",required3=e.required_actions&&e.required_actions.length>0?sanitizeLessonForContext(e.required_actions[0]).slice(0,maxDisplay):"",forbidden=e.forbidden_actions&&e.forbidden_actions.length>0?sanitizeLessonForContext(e.forbidden_actions[0]).slice(0,maxDisplay):"",verification=e.verification_checks&&e.verification_checks.length>0?sanitizeLessonForContext(e.verification_checks[0]).slice(0,maxDisplay):"",skillRef=e.generated_skill_path?`file:${sanitizeLessonForContext(e.generated_skill_path)}`:"",priority=e.directive_priority??"medium",lesson=sanitizeLessonForContext(e.lesson).slice(0,maxDisplay),rec=[];if(rec.push(`- id: ${e.id}`),rec.push(` confidence: ${Number(e.confidence).toFixed(2)}`),rec.push(` priority: ${priority}`),rec.push(` lesson: ${lesson}`),trigger)rec.push(` trigger: ${trigger}`);if(required3)rec.push(` required: ${required3}`);if(forbidden)rec.push(` forbidden: ${forbidden}`);if(skillRef)rec.push(` skill: ${skillRef}`);if(verification)rec.push(` verification: ${verification}`);records.push({id:e.id,lines:rec})}let block=["<swarm_knowledge_directives>",...records.flatMap((r)=>r.lines),"</swarm_knowledge_directives>"].join(`
6033
6034
  `);while(block.length>charBudget&&records.length>0)records.pop(),block=["<swarm_knowledge_directives>",...records.flatMap((r)=>r.lines),"</swarm_knowledge_directives>"].join(`
6034
- `);if(records.length===0)return{block:null,renderedIds:[]};return{block,renderedIds:records.map((r)=>r.id)}}var sanitizeLessonForContext=sanitizeContextText,DELEGATE_DIRECTIVE_BLOCK_TAG="<delegate_knowledge_directives>";function buildDelegateDirectiveBlock(entries,cfg,traceId){if(entries.length===0)return null;let maxDisplay=cfg.max_lesson_display_chars??120,FIELD_CAP=240,renderList=(items)=>{if(!items||items.length===0)return null;let joined=items.map((s)=>sanitizeLessonForContext(s)).filter((s)=>s.length>0).join("; ");if(!joined)return null;return joined.length>FIELD_CAP?`${joined.slice(0,FIELD_CAP)}…`:joined},sorted=[...entries].sort((a,b)=>{let pr=directivePriorityRank(a.directive_priority)-directivePriorityRank(b.directive_priority);if(pr!==0)return pr;return a.id<b.id?-1:a.id>b.id?1:0}),lines=[];if(lines.push(DELEGATE_DIRECTIVE_BLOCK_TAG),lines.push("These directives were learned from prior swarm runs and scoped to your role. Apply them to the task below."),lines.push("ACK CONTRACT: end your FINAL message with one line per CRITICAL directive in this block:"),lines.push(" KNOWLEDGE_APPLIED:<id> — you applied it"),lines.push(" KNOWLEDGE_IGNORED:<id> reason=<short why> — you intentionally did not apply it"),lines.push(" KNOWLEDGE_N_A:<id> reason=<why> — it did not apply to your task"),lines.push("Omitting a critical id is a contract violation."),traceId)lines.push(`trace_id: ${traceId}`);for(let e of sorted){let priority=e.directive_priority??"medium",lesson=sanitizeLessonForContext(e.lesson).slice(0,maxDisplay);lines.push(`- id: ${e.id}`),lines.push(` priority: ${priority}`),lines.push(` lesson: ${lesson}`);let forbidden=renderList(e.forbidden_actions);if(forbidden)lines.push(` forbidden: ${forbidden}`);let required3=renderList(e.required_actions);if(required3)lines.push(` required: ${required3}`);let verification=renderList(e.verification_checks);if(verification)lines.push(` verification: ${verification}`)}return lines.push("</delegate_knowledge_directives>"),lines.join(`
6035
+ `);if(records.length===0)return{block:null,renderedIds:[]};return{block,renderedIds:records.map((r)=>r.id)}}var sanitizeLessonForContext=sanitizeContextText,DELEGATE_DIRECTIVE_BLOCK_TAG="<delegate_knowledge_directives>";function buildDelegateDirectiveBlock(entries,cfg,traceId){if(entries.length===0)return null;let maxDisplay=cfg.max_lesson_display_chars??120,FIELD_CAP=240,renderList=(items)=>{if(!items||items.length===0)return null;let joined=items.map((s)=>sanitizeLessonForContext(s)).filter((s)=>s.length>0).join("; ");if(!joined)return null;return joined.length>FIELD_CAP?`${joined.slice(0,FIELD_CAP)}…`:joined},sorted=[...entries].sort((a,b)=>{let pr=directivePriorityRank(a.directive_priority)-directivePriorityRank(b.directive_priority);if(pr!==0)return pr;return a.id<b.id?-1:a.id>b.id?1:0}),lines=[];if(lines.push(DELEGATE_DIRECTIVE_BLOCK_TAG),lines.push("These directives were learned from prior swarm runs and scoped to your role. Apply them to the task below."),lines.push("ACK CONTRACT: end your FINAL message with one line per directive in this block:"),lines.push(" KNOWLEDGE_APPLIED:<id> — you applied it"),lines.push(" KNOWLEDGE_IGNORED:<id> reason=<short why> — you judged it relevant but deliberately chose not to follow it (counts against the directive)"),lines.push(" KNOWLEDGE_N_A:<id> reason=<why> — it was not relevant to your task (neutral; prefer this when the directive simply did not apply)"),lines.push("Omitting a critical id is a contract violation. Omitting any other id is recorded as unacknowledged."),traceId)lines.push(`trace_id: ${traceId}`);for(let e of sorted){let priority=e.directive_priority??"medium",lesson=sanitizeLessonForContext(e.lesson).slice(0,maxDisplay);lines.push(`- id: ${e.id}`),lines.push(` priority: ${priority}`),lines.push(` lesson: ${lesson}`);let forbidden=renderList(e.forbidden_actions);if(forbidden)lines.push(` forbidden: ${forbidden}`);let required3=renderList(e.required_actions);if(required3)lines.push(` required: ${required3}`);let verification=renderList(e.verification_checks);if(verification)lines.push(` verification: ${verification}`)}return lines.push("</delegate_knowledge_directives>"),lines.join(`
6035
6036
  `)}function parseDelegateDirectiveBlock(text){if(!text||!text.includes(DELEGATE_DIRECTIVE_BLOCK_TAG))return[];let start=text.indexOf(DELEGATE_DIRECTIVE_BLOCK_TAG),endTag="</delegate_knowledge_directives>",endIdx=text.indexOf(endTag,start),body=endIdx>=0?text.slice(start,endIdx):text.slice(start),out=[];for(let line of body.split(`
6036
6037
  `)){let idM=/^- id:\s*(\S+)\s*$/.exec(line);if(idM){out.push({id:idM[1],priority:"medium"});continue}let prM=/^\s+priority:\s*(low|medium|high|critical)\s*$/.exec(line);if(prM&&out.length>0)out[out.length-1].priority=prM[1]}return out}function parseDelegateDirectiveTraceId(text){if(!text||!text.includes(DELEGATE_DIRECTIVE_BLOCK_TAG))return;let start=text.indexOf(DELEGATE_DIRECTIVE_BLOCK_TAG),endTag="</delegate_knowledge_directives>",endIdx=text.indexOf(endTag,start),body=endIdx>=0?text.slice(start,endIdx):text.slice(start);for(let line of body.split(`
6037
- `)){let m=/^trace_id:\s*(\S+)\s*$/m.exec(line);if(m)return m[1]}return}var knowledgeGeneration=0;function bumpKnowledgeGeneration(){return knowledgeGeneration++,knowledgeGeneration}function getKnowledgeGeneration(){return knowledgeGeneration}async function injectForDelegate(params){let{directory,agent,taskTitle,sessionId,config:config3}=params,cap2=config3.delegate_max_inject_count??8,expectedTools=params.expectedTools&&params.expectedTools.length>0?params.expectedTools:defaultExpectedToolsForAgent(agent);if(cap2<=0)return{entries:[],trace_id:""};let role=stripKnownSwarmPrefix(agent).toLowerCase(),firstTool=expectedTools.length>0?expectedTools[0]:void 0,context={currentPhase:taskTitle??"",taskTitle,lastUserMessage:taskTitle,targetAgent:agent,currentTool:firstTool,mode:"delegation"},searchFn=params.searchFn??(_internals141.searchKnowledge===defaultSearchKnowledge?searchKnowledge:_internals141.searchKnowledge);try{let search=await searchFn({directory,config:config3,context,mode:"delegate_inject",agent,sessionId,tier:"all",applyScopeFilter:!0,applyRoleScope:!1,maxResults:Math.max(40,cap2*4),emitEvent:!1}),capped=search.results.filter((e)=>matchesDelegateScope(e,role,expectedTools)).slice(0,cap2);if(capped.length>0){let ranks={},scores={};if(capped.forEach((e,idx)=>{ranks[e.id]=idx+1,scores[e.id]=e.finalScore}),await _internals141.recordKnowledgeEvent(directory,{type:"retrieved",trace_id:search.trace_id,session_id:sessionId??"unknown",phase:params.phase??taskTitle,agent,query:taskTitle??"",retrieval_mode:"delegate_inject",result_ids:capped.map((e)=>e.id),ranks,scores}),params.phase){let shownIds=capped.map((e)=>e.id);_internals141.recordLessonsShown(directory,shownIds,params.phase).catch(()=>{}),_internals141.recordKnowledgeShown(directory,shownIds,{phase:params.phase,targetAgent:agent,sessionId}).catch(()=>{});let phaseNum=phaseNumberOf(params.phase);if(phaseNum!==void 0){let projectName=(await loadPlan(directory).catch(()=>null))?.title??"unknown";_internals141.confirmEntriesPhase(directory,shownIds,phaseNum,projectName).catch(()=>{})}}}if(capped.length===0)try{await _internals141.recordKnowledgeEvent(directory,{type:"retrieved",trace_id:search.trace_id,session_id:sessionId??"unknown",phase:params.phase??taskTitle,agent,query:taskTitle??"",retrieval_mode:"delegate_inject",result_ids:[],ranks:{},scores:{}}),await _internals141.recordKnowledgeEvent(directory,{type:"no_relevant",trace_id:search.trace_id,session_id:sessionId??"unknown",phase:params.phase??taskTitle,agent,reason:"empty delegate retrieval"})}catch{}return{entries:capped,trace_id:search.trace_id}}catch{return{entries:[],trace_id:""}}}async function injectForDelegateIntoMessages(directory,config3,output,agentName,sessionId){if(!output.messages||output.messages.length===0)return;if(output.messages.some((m)=>m.parts?.some((p)=>p.text?.includes(DELEGATE_DIRECTIVE_BLOCK_TAG))))return;let taskTitle;for(let i=output.messages.length-1;i>=0;i--){let m=output.messages[i];if(m.info?.role==="user"){let t=m.parts?.map((p)=>p.text??"").join(" ").trim();if(t){taskTitle=t.slice(0,800);break}}}let plan=await loadPlan(directory).catch(()=>null),phaseLabel=plan?extractCurrentPhaseFromPlan(plan)??`Phase ${plan.current_phase??1}`:void 0,{entries,trace_id}=await injectForDelegate({directory,agent:agentName,expectedTools:defaultExpectedToolsForAgent(agentName),taskTitle,sessionId,phase:phaseLabel,config:config3}),block=buildDelegateDirectiveBlock(entries,config3,trace_id);if(!block)return;injectKnowledgeMessage(output,block)}function isOrchestratorAgent(agentName){return stripKnownSwarmPrefix(agentName).toLowerCase()==="architect"}var DELEGATED_AGENTS=new Set(["coder","reviewer","test_engineer","sme","docs","designer","critic","curator"]);function isDelegatedAgent(agentName){let stripped=stripKnownSwarmPrefix(agentName).toLowerCase();return DELEGATED_AGENTS.has(stripped)}var DELEGATE_DEFAULT_TOOLS={coder:["edit","write","patch","bash"],reviewer:["read","grep","glob"],test_engineer:["edit","write","bash","read"],sme:["read","grep","glob","webfetch"],docs:["read","edit","write","grep"],designer:["read","write","edit"],critic:["read","grep","glob"],curator:["read","grep","glob"]};function defaultExpectedToolsForAgent(agentName){let role=stripKnownSwarmPrefix(agentName).toLowerCase();return[...DELEGATE_DEFAULT_TOOLS[role]??[]]}var DIRECTIVE_PRIORITY_RANK={critical:0,high:1,medium:2,low:3};function directivePriorityRank(p){return DIRECTIVE_PRIORITY_RANK[p??"medium"]??2}function matchesDelegateScope(entry,role,expectedTools){let agents=(entry.applies_to_agents??[]).map((a)=>stripKnownSwarmPrefix(a).toLowerCase()),tools=(entry.applies_to_tools??[]).map((t)=>t.toLowerCase());if(agents.length===0&&tools.length===0)return!0;let normRole=stripKnownSwarmPrefix(role).toLowerCase();if(agents.includes(normRole))return!0;let expected=expectedTools.map((t)=>t.toLowerCase());if(tools.some((t)=>expected.includes(t)))return!0;return!1}function injectKnowledgeMessage(output,text){if(!output.messages)return;if(output.messages.some((m)=>m.parts?.some((p)=>p.text?.includes(INJECTION_SENTINEL))))return;let insertIdx=output.messages.length-1;for(let i=output.messages.length-1;i>=0;i--)if(output.messages[i].info?.role==="user"){insertIdx=i;break}let knowledgeMessage={info:{role:"system"},parts:[{type:"text",text:`${INJECTION_SENTINEL}${text}`}]};output.messages.splice(insertIdx,0,knowledgeMessage)}function createKnowledgeInjectorHook(directory,config3,modelLimitOverrides={},unifiedInjectionTokens=void 0){function buildContextCacheKey(phase,ctx){let parts=[String(phase),String(getKnowledgeGeneration()),ctx.currentTool??"",ctx.currentAction??"",ctx.targetAgent??"",ctx.taskId??"",(ctx.filePaths??[]).slice(0,8).join(","),ctx.lastUserMessage?createHash39("sha1").update(ctx.lastUserMessage).digest("hex").slice(0,16):""].join("|");return createHash39("sha1").update(parts).digest("hex").slice(0,16)}let lastSeenCacheKey=null,cachedInjectionText=null,cachedShownIds=[],cachedCriticalIds=[];return safeHook(async(_input,output)=>{if(!output.messages||output.messages.length===0)return;let plan=await loadPlan(directory),currentPhase=plan?.current_phase??1,CHARS_PER_TOKEN=3.0303030303030303,{modelID,providerID}=extractModelInfo(output.messages),modelLimitTokens=resolveModelLimit(modelID,providerID,modelLimitOverrides),MODEL_LIMIT_CHARS=Math.floor(modelLimitTokens*CHARS_PER_TOKEN),existingChars=output.messages.reduce((sum,msg)=>{return sum+(msg.parts?.reduce((s,p)=>s+(p.text?.length??0),0)??0)},0),headroomChars=MODEL_LIMIT_CHARS-existingChars,MIN_INJECT_CHARS=config3.context_budget_threshold??300;if(headroomChars<MIN_INJECT_CHARS){warn(`[knowledge-injector] Skipping: only ${headroomChars} chars of headroom remain (existing: ${existingChars}, limit: ${MODEL_LIMIT_CHARS})`),recordInjectionSkip(directory,"headroom_budget",{extra:{headroomChars,existingChars,modelLimitChars:MODEL_LIMIT_CHARS,modelID}});return}let maxInjectChars=config3.inject_char_budget??2000,effectiveBudget=headroomChars>=MODEL_LIMIT_CHARS*0.6?maxInjectChars:headroomChars>=MODEL_LIMIT_CHARS*0.2?Math.floor(maxInjectChars*0.5):Math.floor(maxInjectChars*0.25),mctx=resolveMessageTransformContext(output),agentName=mctx.agent,sessionId=mctx.sessionID;if(!agentName){recordInjectionSkip(directory,"no_agent_name",{sessionId});return}if(unifiedInjectionTokens!==void 0){let sessionID2=sessionId,seDemand=sessionID2?getSystemEnhancerDemand(sessionID2):0,allocation=allocateInjectionBudget(seDemand,effectiveBudget,{totalBudgetTokens:unifiedInjectionTokens});effectiveBudget=Math.floor(allocation.knowledgeInjectorTokens/0.33)}if(isDelegatedAgent(agentName)){await injectForDelegateIntoMessages(directory,config3,output,agentName,sessionId);return}if(!isOrchestratorAgent(agentName)){recordInjectionSkip(directory,"not_architect",{agent:agentName,sessionId});return}let phaseDescription=plan?extractCurrentPhaseFromPlan(plan)??`Phase ${currentPhase}`:"Phase 0",projectName=plan?.title??"unknown",lastUserMessage;for(let i=output.messages.length-1;i>=0;i--){let m=output.messages[i];if(m.info?.role==="user"){let t=m.parts?.map((p)=>p.text??"").join(" ").trim();if(t){lastUserMessage=t.slice(0,800);break}}}let taskId=getCurrentTaskId(plan),retrievalCtx={projectName,currentPhase:phaseDescription,mode:"phase_start",lastUserMessage,taskId},cacheKey=buildContextCacheKey(currentPhase,retrievalCtx);if(cacheKey===lastSeenCacheKey&&cachedInjectionText!==null){injectKnowledgeMessage(output,cachedInjectionText);let sessionID2=sessionId;if(sessionID2)if(cachedCriticalIds.length>0)setCriticalShownIds(sessionID2,{ids:cachedCriticalIds,phase:`Phase ${currentPhase}`,generatedAt:Date.now()});else clearCriticalShownIds(sessionID2);return}lastSeenCacheKey=cacheKey,cachedInjectionText=null,cachedShownIds=[],cachedCriticalIds=[];let search=await(_internals141.searchKnowledge===defaultSearchKnowledge?searchKnowledge:_internals141.searchKnowledge)({directory,config:config3,context:retrievalCtx,mode:"auto_injection",agent:"architect",sessionId,emitEvent:!1}),filteredEntries=search.results,freshPreamble=null;try{let driftReports=await readPriorDriftReports(directory);if(driftReports.length>0){let latestReport=driftReports[driftReports.length-1],driftText=buildDriftInjectionText(latestReport,500);if(driftText)freshPreamble=sanitizeContextText(driftText)}}catch{}try{let briefingContent=await readSwarmFileAsync(directory,"curator-briefing.md");if(briefingContent){let truncatedBriefing=sanitizeContextText(briefingContent).slice(0,500);freshPreamble=freshPreamble?`<curator_briefing>${truncatedBriefing}</curator_briefing>
6038
+ `)){let m=/^trace_id:\s*(\S+)\s*$/m.exec(line);if(m)return m[1]}return}var knowledgeGeneration=0;function bumpKnowledgeGeneration(){return knowledgeGeneration++,knowledgeGeneration}function getKnowledgeGeneration(){return knowledgeGeneration}async function injectForDelegate(params){let{directory,agent,taskTitle,sessionId,config:config3}=params,cap2=config3.delegate_max_inject_count??8,expectedTools=params.expectedTools&&params.expectedTools.length>0?params.expectedTools:defaultExpectedToolsForAgent(agent);if(cap2<=0)return{entries:[],trace_id:""};let role=stripKnownSwarmPrefix(agent).toLowerCase(),firstTool=expectedTools.length>0?expectedTools[0]:void 0,context={currentPhase:taskTitle??"",taskTitle,lastUserMessage:taskTitle,targetAgent:agent,currentTool:firstTool,mode:"delegation"},searchFn=params.searchFn??(_internals141.searchKnowledge===defaultSearchKnowledge?searchKnowledge:_internals141.searchKnowledge);try{let search=await searchFn({directory,config:config3,context,mode:"delegate_inject",agent,sessionId,tier:"all",applyScopeFilter:!0,applyRoleScope:!1,maxResults:Math.max(40,cap2*4),emitEvent:!1}),capped=search.results.filter((e)=>matchesDelegateScope(e,role,expectedTools)).slice(0,cap2);if(capped.length>0){let ranks={},scores={};if(capped.forEach((e,idx)=>{ranks[e.id]=idx+1,scores[e.id]=e.finalScore}),await _internals141.recordKnowledgeEvent(directory,{type:"retrieved",trace_id:search.trace_id,session_id:sessionId??"unknown",phase:params.phase??taskTitle,agent,query:taskTitle??"",retrieval_mode:"delegate_inject",result_ids:capped.map((e)=>e.id),ranks,scores}),params.phase){let shownIds=capped.map((e)=>e.id);_internals141.recordLessonsShown(directory,shownIds,params.phase).catch(()=>{}),_internals141.recordKnowledgeShown(directory,shownIds,{phase:params.phase,targetAgent:agent,sessionId}).catch(()=>{});let phaseNum=phaseNumberOf(params.phase);if(phaseNum!==void 0){let projectName=(await loadPlan(directory).catch(()=>null))?.title??"unknown";_internals141.confirmEntriesPhase(directory,shownIds,phaseNum,projectName).catch(()=>{})}}}if(capped.length===0)try{await _internals141.recordKnowledgeEvent(directory,{type:"retrieved",trace_id:search.trace_id,session_id:sessionId??"unknown",phase:params.phase??taskTitle,agent,query:taskTitle??"",retrieval_mode:"delegate_inject",result_ids:[],ranks:{},scores:{}}),await _internals141.recordKnowledgeEvent(directory,{type:"no_relevant",trace_id:search.trace_id,session_id:sessionId??"unknown",phase:params.phase??taskTitle,agent,reason:"empty delegate retrieval"})}catch{}return{entries:capped,trace_id:search.trace_id}}catch{return{entries:[],trace_id:""}}}async function injectForDelegateIntoMessages(directory,config3,output,agentName,sessionId){if(!output.messages||output.messages.length===0)return;if(output.messages.some((m)=>m.parts?.some((p)=>p.text?.includes(DELEGATE_DIRECTIVE_BLOCK_TAG))))return;let taskTitle;for(let i=output.messages.length-1;i>=0;i--){let m=output.messages[i];if(m.info?.role==="user"){let t=m.parts?.map((p)=>p.text??"").join(" ").trim();if(t){taskTitle=t.slice(0,800);break}}}let plan=await loadPlan(directory).catch(()=>null),phaseLabel=plan?extractCurrentPhaseFromPlan(plan)??`Phase ${plan.current_phase??1}`:void 0,{entries,trace_id}=await injectForDelegate({directory,agent:agentName,expectedTools:defaultExpectedToolsForAgent(agentName),taskTitle,sessionId,phase:phaseLabel,config:config3}),block=buildDelegateDirectiveBlock(entries,config3,trace_id);if(!block)return;injectKnowledgeMessage(output,block)}function isOrchestratorAgent(agentName){return stripKnownSwarmPrefix(agentName).toLowerCase()==="architect"}var DELEGATED_AGENTS=new Set(["coder","reviewer","test_engineer","sme","docs","designer","critic","curator"]);function isDelegatedAgent(agentName){let stripped=stripKnownSwarmPrefix(agentName).toLowerCase();return DELEGATED_AGENTS.has(stripped)}var DELEGATE_DEFAULT_TOOLS={coder:["edit","write","patch","bash"],reviewer:["read","grep","glob"],test_engineer:["edit","write","bash","read"],sme:["read","grep","glob","webfetch"],docs:["read","edit","write","grep"],designer:["read","write","edit"],critic:["read","grep","glob"],curator:["read","grep","glob"]};function defaultExpectedToolsForAgent(agentName){let role=stripKnownSwarmPrefix(agentName).toLowerCase();return[...DELEGATE_DEFAULT_TOOLS[role]??[]]}var DIRECTIVE_PRIORITY_RANK={critical:0,high:1,medium:2,low:3};function directivePriorityRank(p){return DIRECTIVE_PRIORITY_RANK[p??"medium"]??2}function matchesDelegateScope(entry,role,expectedTools){let agents=(entry.applies_to_agents??[]).map((a)=>stripKnownSwarmPrefix(a).toLowerCase()),tools=(entry.applies_to_tools??[]).map((t)=>t.toLowerCase());if(agents.length===0&&tools.length===0)return!0;let normRole=stripKnownSwarmPrefix(role).toLowerCase();if(agents.includes(normRole))return!0;let expected=expectedTools.map((t)=>t.toLowerCase());if(tools.some((t)=>expected.includes(t)))return!0;return!1}function injectKnowledgeMessage(output,text){if(!output.messages)return;if(output.messages.some((m)=>m.parts?.some((p)=>p.text?.includes(INJECTION_SENTINEL))))return;let insertIdx=output.messages.length-1;for(let i=output.messages.length-1;i>=0;i--)if(output.messages[i].info?.role==="user"){insertIdx=i;break}let knowledgeMessage={info:{role:"system"},parts:[{type:"text",text:`${INJECTION_SENTINEL}${text}`}]};output.messages.splice(insertIdx,0,knowledgeMessage)}function createKnowledgeInjectorHook(directory,config3,modelLimitOverrides={},unifiedInjectionTokens=void 0){function buildContextCacheKey(phase,ctx){let parts=[String(phase),String(getKnowledgeGeneration()),ctx.currentTool??"",ctx.currentAction??"",ctx.targetAgent??"",ctx.taskId??"",(ctx.filePaths??[]).slice(0,8).join(","),ctx.lastUserMessage?createHash39("sha1").update(ctx.lastUserMessage).digest("hex").slice(0,16):""].join("|");return createHash39("sha1").update(parts).digest("hex").slice(0,16)}let lastSeenCacheKey=null,cachedInjectionText=null,cachedShownIds=[],cachedCriticalIds=[];return safeHook(async(_input,output)=>{if(!output.messages||output.messages.length===0)return;let plan=await loadPlan(directory),currentPhase=plan?.current_phase??1,mctx=resolveMessageTransformContext(output),agentName=mctx.agent,sessionId=mctx.sessionID,CHARS_PER_TOKEN=3.0303030303030303,{modelID,providerID}=extractModelInfo(output.messages),modelLimitTokens=resolveModelLimit(modelID,providerID,modelLimitOverrides),MODEL_LIMIT_CHARS=Math.floor(modelLimitTokens*CHARS_PER_TOKEN),existingChars=output.messages.reduce((sum,msg)=>{return sum+(msg.parts?.reduce((s,p)=>s+(p.text?.length??0),0)??0)},0),headroomChars=MODEL_LIMIT_CHARS-existingChars,MIN_INJECT_CHARS=config3.context_budget_threshold??300;if(headroomChars<MIN_INJECT_CHARS){warn(`[knowledge-injector] Skipping: only ${headroomChars} chars of headroom remain (existing: ${existingChars}, limit: ${MODEL_LIMIT_CHARS})`),recordInjectionSkip(directory,"headroom_budget",{agent:agentName,sessionId,extra:{headroomChars,existingChars,modelLimitChars:MODEL_LIMIT_CHARS,modelID}});return}let maxInjectChars=config3.inject_char_budget??2000,effectiveBudget=headroomChars>=MODEL_LIMIT_CHARS*0.6?maxInjectChars:headroomChars>=MODEL_LIMIT_CHARS*0.2?Math.floor(maxInjectChars*0.5):Math.floor(maxInjectChars*0.25);if(!agentName){recordInjectionSkip(directory,"no_agent_name",{sessionId});return}if(unifiedInjectionTokens!==void 0){let sessionID2=sessionId,seDemand=sessionID2?getSystemEnhancerDemand(sessionID2):0,allocation=allocateInjectionBudget(seDemand,effectiveBudget,{totalBudgetTokens:unifiedInjectionTokens});effectiveBudget=Math.floor(allocation.knowledgeInjectorTokens/0.33)}if(isDelegatedAgent(agentName)){await injectForDelegateIntoMessages(directory,config3,output,agentName,sessionId);return}if(!isOrchestratorAgent(agentName)){recordInjectionSkip(directory,"not_architect",{agent:agentName,sessionId});return}let phaseDescription=plan?extractCurrentPhaseFromPlan(plan)??`Phase ${currentPhase}`:"Phase 0",projectName=plan?.title??"unknown",lastUserMessage;for(let i=output.messages.length-1;i>=0;i--){let m=output.messages[i];if(m.info?.role==="user"){let t=m.parts?.map((p)=>p.text??"").join(" ").trim();if(t){lastUserMessage=t.slice(0,800);break}}}let taskId=getCurrentTaskId(plan),retrievalCtx={projectName,currentPhase:phaseDescription,mode:"phase_start",lastUserMessage,taskId},cacheKey=buildContextCacheKey(currentPhase,retrievalCtx);if(cacheKey===lastSeenCacheKey&&cachedInjectionText!==null){injectKnowledgeMessage(output,cachedInjectionText);let sessionID2=sessionId;if(sessionID2)if(cachedCriticalIds.length>0)setCriticalShownIds(sessionID2,{ids:cachedCriticalIds,phase:`Phase ${currentPhase}`,generatedAt:Date.now()});else clearCriticalShownIds(sessionID2);return}lastSeenCacheKey=cacheKey,cachedInjectionText=null,cachedShownIds=[],cachedCriticalIds=[];let search=await(_internals141.searchKnowledge===defaultSearchKnowledge?searchKnowledge:_internals141.searchKnowledge)({directory,config:config3,context:retrievalCtx,mode:"auto_injection",agent:"architect",sessionId,emitEvent:!1}),filteredEntries=search.results,freshPreamble=null;try{let driftReports=await readPriorDriftReports(directory);if(driftReports.length>0){let latestReport=driftReports[driftReports.length-1],driftText=buildDriftInjectionText(latestReport,500);if(driftText)freshPreamble=sanitizeContextText(driftText)}}catch{}try{let briefingContent=await readSwarmFileAsync(directory,"curator-briefing.md");if(briefingContent){let truncatedBriefing=sanitizeContextText(briefingContent).slice(0,500);freshPreamble=freshPreamble?`<curator_briefing>${truncatedBriefing}</curator_briefing>
6038
6039
 
6039
6040
  ${freshPreamble}`:`<curator_briefing>${truncatedBriefing}</curator_briefing>`}}catch{}if(filteredEntries.length===0){let sessionID2=sessionId;if(sessionID2)clearCriticalShownIds(sessionID2);cachedShownIds=[],cachedCriticalIds=[],recordInjectionSkip(directory,"no_matching_entries",{agent:agentName,sessionId:sessionID2,phase:currentPhase});try{await _internals141.recordKnowledgeEvent(directory,{type:"retrieved",trace_id:search.trace_id,session_id:sessionID2??"unknown",phase:retrievalCtx.currentPhase,task_id:retrievalCtx.taskId,agent:"architect",query:retrievalCtx.lastUserMessage??retrievalCtx.currentPhase??"",retrieval_mode:"auto_injection",result_ids:[],ranks:{},scores:{}})}catch{}if(freshPreamble===null){try{await _internals141.recordKnowledgeEvent(directory,{type:"no_relevant",trace_id:search.trace_id,session_id:sessionID2??"unknown",phase:retrievalCtx.currentPhase,task_id:retrievalCtx.taskId,agent:"architect",reason:"empty auto-injection retrieval"})}catch{}return}cachedInjectionText=freshPreamble,injectKnowledgeMessage(output,cachedInjectionText);return}let runMemory=null;try{runMemory=await getRunMemorySummary(directory)}catch(err){warn(`[knowledge-injector] run memory summary unavailable: ${err instanceof Error?err.message:String(err)}`)}let isFullBudget=effectiveBudget===maxInjectChars,directiveBudget=Math.floor(effectiveBudget*0.45),lessonBudget=Math.floor(effectiveBudget*0.3),directiveEntries=filteredEntries.filter((e)=>e.triggers&&e.triggers.length>0||e.required_actions&&e.required_actions.length>0||e.forbidden_actions&&e.forbidden_actions.length>0||e.directive_priority==="critical"||e.directive_priority==="high"||e.generated_skill_path),directiveBuilt=buildDirectiveBlock(directiveEntries,directiveBudget,config3),directiveBlock=directiveBuilt.block,lessonBuilt=buildKnowledgeBlock(filteredEntries,lessonBudget,config3,projectName),lessonBlock=lessonBuilt.block,renderedDirectiveIdSet=new Set(directiveBuilt.renderedIds);if(cachedShownIds=[...new Set([...directiveBuilt.renderedIds,...lessonBuilt.renderedIds])],cachedShownIds.length===0)recordInjectionSkip(directory,"rendered_id_match_failed",{agent:agentName,sessionId,phase:currentPhase,extra:{filteredCount:filteredEntries.length,directiveCount:directiveEntries.length}});let parts=[],remaining=effectiveBudget;try{let escalations=await _internals141.readRecentEscalations(directory),escalationBriefing=_internals141.buildEscalationBriefing(escalations);if(escalationBriefing&&escalationBriefing.length<=remaining)parts.push(escalationBriefing),remaining-=escalationBriefing.length}catch{}if(directiveBlock)parts.push(directiveBlock),remaining-=directiveBlock.length;if(lessonBlock)parts.push(lessonBlock),remaining-=lessonBlock.length;if(runMemory&&remaining>300){let sanitizedRunMemory=sanitizeContextText(runMemory);parts.push(sanitizedRunMemory),remaining-=sanitizedRunMemory.length}if(freshPreamble&&remaining>200){let preambleToUse=freshPreamble;if(!isFullBudget)preambleToUse=preambleToUse.replace(/<curator_briefing>[\s\S]*?<\/curator_briefing>\s*/g,"");if(preambleToUse.trim().length>0&&preambleToUse.length<=remaining)parts.push(preambleToUse),remaining-=preambleToUse.length}try{let rejected=await readRejectedLessons(directory);if(rejected.length>0&&remaining>150){let rejectedBlock=`⚠️ Previously rejected patterns (do not re-learn):
6040
6041
  `+rejected.slice(-3).map((r)=>` ⚠️ REJECTED PATTERN: "${sanitizeLessonForContext(r.lesson).slice(0,80)}" — ${sanitizeLessonForContext(r.rejection_reason)}`).join(`
6041
6042
  `);if(rejectedBlock.length<=remaining)parts.push(rejectedBlock)}}catch(err){warn(`[knowledge-injector] rejected pattern warnings unavailable: ${err instanceof Error?err.message:String(err)}`)}cachedInjectionText=parts.join(`
6042
6043
 
6043
6044
  `),injectKnowledgeMessage(output,cachedInjectionText);let sessionID=sessionId;if(sessionID){let criticalIds=filteredEntries.filter((e)=>renderedDirectiveIdSet.has(e.id)).filter((e)=>e.directive_priority==="critical"&&isActiveStatus(e.status)).map((e)=>e.id);if(cachedCriticalIds=criticalIds,criticalIds.length>0)setCriticalShownIds(sessionID,{ids:criticalIds,phase:`Phase ${currentPhase}`,generatedAt:Date.now()});else clearCriticalShownIds(sessionID)}if(cachedShownIds.length>0){let phaseLabel=`Phase ${currentPhase}`,scoreById=new Map(filteredEntries.map((e)=>[e.id,e.finalScore])),ranks={},scores={};cachedShownIds.forEach((id,idx)=>{ranks[id]=idx+1,scores[id]=scoreById.get(id)??0}),await _internals141.recordKnowledgeEvent(directory,{type:"retrieved",trace_id:search.trace_id,session_id:sessionId??"unknown",phase:retrievalCtx.currentPhase,task_id:retrievalCtx.taskId,agent:"architect",query:retrievalCtx.lastUserMessage??retrievalCtx.currentPhase??"",retrieval_mode:"auto_injection",result_ids:cachedShownIds,ranks,scores}),_internals141.recordKnowledgeShown(directory,cachedShownIds,{phase:phaseLabel,tool:retrievalCtx.currentTool,action:retrievalCtx.currentAction,targetAgent:retrievalCtx.targetAgent,taskId:retrievalCtx.taskId}).catch(()=>{}),_internals141.recordLessonsShown(directory,cachedShownIds,phaseLabel).catch(()=>{}),_internals141.confirmEntriesPhase(directory,cachedShownIds,currentPhase,projectName).catch(()=>{})}})}var _internals141={searchKnowledge,recordKnowledgeEvent,recordKnowledgeShown,readRecentEscalations,buildEscalationBriefing,recordLessonsShown,confirmEntriesPhase};init_knowledge_link();init_logger();init_knowledge_events();var RECEIPT_VALIDITY_MS=1800000,NO_TRACE_SENTINEL="none",VALID_OUTCOMES=new Set(["applied","ignored","contradicted","violated","n_a"]);async function validateReceipt(ctx){let{items,no_relevant_knowledge}=ctx;if(items.length===0&&!no_relevant_knowledge)return reject("empty_receipt","no items and no_relevant_knowledge is false");for(let item of items)if(!VALID_OUTCOMES.has(item.outcome))return reject("invalid_outcome",`item ${item.id}: outcome ${item.outcome}`);if(no_relevant_knowledge&&items.length>0)return reject("invalid_outcome","no_relevant_knowledge cannot be combined with items");let events;try{events=await readKnowledgeEvents(ctx.directory)}catch(err){return log("[receipt-validator] readKnowledgeEvents failed (fail-open, accepting)",{trace_id:ctx.trace_id,error:err instanceof Error?err.message:String(err)}),{ok:!0,accepted:items,idempotent_skips:[],trace:null,closes_no_relevant:no_relevant_knowledge}}if(ctx.trace_id===NO_TRACE_SENTINEL||ctx.trace_id===""){if(items.length>0)return reject("trace_not_found",`items filed against the ${NO_TRACE_SENTINEL} sentinel trace`);return{ok:!0,accepted:[],idempotent_skips:[],trace:null,closes_no_relevant:no_relevant_knowledge}}let trace=findTrace(events,ctx.trace_id);if(!trace)return reject("trace_not_found",`no retrieved event for trace_id ${ctx.trace_id}`);if(trace.session_id!==ctx.session_id)return reject("wrong_session",`trace session ${trace.session_id} != receipt session ${ctx.session_id}`);let parsed=Date.parse(trace.timestamp),ageMs=Date.now()-parsed;if(!Number.isFinite(parsed)||ageMs>RECEIPT_VALIDITY_MS)return reject("expired",Number.isFinite(parsed)?`trace age ${Math.round(ageMs/1000)}s exceeds ${RECEIPT_VALIDITY_MS/1000}s`:`trace timestamp '${trace.timestamp}' is unparseable (fail-closed)`);let prior=new Map;for(let e of events){if(e.type!=="applied"&&e.type!=="ignored"&&e.type!=="contradicted"&&e.type!=="violated"&&e.type!=="n_a")continue;if(e.trace_id!==ctx.trace_id)continue;let kid=e.knowledge_id;if(!kid)continue;prior.set(kid,e.type)}let resultSet=new Set(trace.result_ids),accepted=[],idempotent_skips=[],rejected_items=[];for(let item of items){if(!resultSet.has(item.id)){rejected_items.push({item,reason:"id_not_in_trace"});continue}let prev=prior.get(item.id);if(prev===item.outcome){idempotent_skips.push(item);continue}if(prev!==void 0&&prev!==item.outcome){rejected_items.push({item,reason:"duplicate_conflicting_terminal"});continue}accepted.push(item),prior.set(item.id,item.outcome)}if(rejected_items.length>0&&accepted.length===0&&idempotent_skips.length===0){let first=rejected_items[0];return{ok:!1,rejected:!0,reason:first.reason,detail:`${first.reason} for id ${first.item.id}`,rejected_items}}return{ok:!0,accepted,idempotent_skips,trace,closes_no_relevant:no_relevant_knowledge,...rejected_items.length>0&&{rejected_items}}}function reject(reason,detail){return{ok:!1,rejected:!0,reason,detail}}function findTrace(events,traceId){for(let e of events)if(e.type==="retrieved"&&e.trace_id===traceId)return e;return null}init_promotion_evidence_store();init_skill_propagation_gate();init_utils2();function isTaskTool3(tool3){return tool3==="Task"||tool3==="task"}function extractTaskId2(prompt){let m=/\btask[_-]?id\s*[:=]\s*([A-Za-z0-9._-]{1,80})/i.exec(prompt);return m?m[1]:void 0}async function appendUnacknowledgedCritical(directory,record3){let filePath=validateSwarmPath(directory,"unacknowledged-criticals.jsonl");await mkdir43(path210.dirname(filePath),{recursive:!0}),await appendFile21(filePath,`${JSON.stringify(record3)}
6044
- `,"utf-8")}async function collectDelegateAcks(params){let result={emitted:[],unacknowledgedCriticals:[]};try{let shown=parseDelegateDirectiveBlock(params.prompt);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??"unknown",taskId=params.taskId??extractTaskId2(params.prompt),recoveredTraceId=parseDelegateDirectiveTraceId(params.prompt),traceId=recoveredTraceId??newTraceId(),isLegacyPrompt=recoveredTraceId===void 0,ackItems=[],ackByItemId=new Map;for(let ack of acks){if(!shownById.has(ack.id))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);let written=await recordKnowledgeEvent(params.directory,{type:ack.result,trace_id:traceId,knowledge_id:ack.id,session_id:sessionId,task_id:taskId,agent:params.agent,reason:ack.reason});if(written?.event_id)eventIdByKnowledgeId.set(ack.id,written.event_id);if(ack.result==="violated")violatedIds.add(ack.id);result.emitted.push({id:ack.id,type:ack.result})}else{let validation2=await validateReceipt({directory:params.directory,trace_id:traceId,session_id:sessionId,task_id:taskId,agent:params.agent,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);let written=await recordKnowledgeEvent(params.directory,{type:item.outcome,trace_id:traceId,knowledge_id:item.id,session_id:sessionId,task_id:taskId,agent:params.agent,reason:ack.reason});if(written?.event_id)eventIdByKnowledgeId.set(item.id,written.event_id);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)}if(!validation2.ok)for(let id of ackByItemId.keys())ackedIds.add(id)}try{let cohortId=await ensureCohortIdCached(params.directory,sessionId),linkId=readLinkPointer(params.directory)?.linkId,now=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_event_id:eid,phase:void 0,timestamp:now})}await appendPromotionEvidence(params.directory,evidenceRecords)}catch{}for(let id of criticalIds){if(ackedIds.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,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{}}if(violatedIds.size>0)await escalateViolatedEntries(params.directory,[...violatedIds])}catch{}return result}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;await collectDelegateAcks({directory,prompt,transcript,agent,sessionId})}var PRIORITY_RANK={critical:0,high:1,medium:2,low:3};function buildDirectiveComplianceBlock(directives){if(directives.length===0)return null;let sorted=[...directives].sort((a,b)=>{let pr=(PRIORITY_RANK[a.priority]??2)-(PRIORITY_RANK[b.priority]??2);if(pr!==0)return pr;return a.id<b.id?-1:a.id>b.id?1:0}),lines=[];lines.push("<directives_to_verify>"),lines.push("Produce a DIRECTIVE_COMPLIANCE verdict for EVERY id below. Run any verification_predicate provided.");for(let d of sorted){if(lines.push(`- id: ${d.id}`),lines.push(` priority: ${d.priority}`),d.lesson)lines.push(` lesson: ${d.lesson}`);if(d.verification_predicate)lines.push(` verification_predicate: ${d.verification_predicate}`)}return lines.push("</directives_to_verify>"),lines.push(""),lines.push(`DIRECTIVE_COMPLIANCE: one line per knowledge directive shown during this phase (the IDs are listed in the DIRECTIVES TO VERIFY block of your prompt). Use exactly one of:
6045
+ `,"utf-8")}async function collectDelegateAcks(params){let result={emitted:[],unacknowledgedCriticals:[],unacknowledgedNonCritical:[]};try{let shown=parseDelegateDirectiveBlock(params.prompt);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??"unknown",taskId=params.taskId??extractTaskId2(params.prompt),recoveredTraceId=parseDelegateDirectiveTraceId(params.prompt),traceId=recoveredTraceId??newTraceId(),isLegacyPrompt=recoveredTraceId===void 0,ackItems=[],ackByItemId=new Map;for(let ack of acks){if(!shownById.has(ack.id))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);let written=await recordKnowledgeEvent(params.directory,{type:ack.result,trace_id:traceId,knowledge_id:ack.id,session_id:sessionId,task_id:taskId,agent:params.agent,reason:ack.reason});if(written?.event_id)eventIdByKnowledgeId.set(ack.id,written.event_id);if(ack.result==="violated")violatedIds.add(ack.id);result.emitted.push({id:ack.id,type:ack.result})}else{let validation2=await validateReceipt({directory:params.directory,trace_id:traceId,session_id:sessionId,task_id:taskId,agent:params.agent,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);let written=await recordKnowledgeEvent(params.directory,{type:item.outcome,trace_id:traceId,knowledge_id:item.id,session_id:sessionId,task_id:taskId,agent:params.agent,reason:ack.reason});if(written?.event_id)eventIdByKnowledgeId.set(item.id,written.event_id);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 rejected of validation2.rejected_items??[])ackedIds.add(rejected.item.id)}if(!validation2.ok)for(let id of ackByItemId.keys())ackedIds.add(id)}try{let cohortId=await ensureCohortIdCached(params.directory,sessionId),linkId=readLinkPointer(params.directory)?.linkId,now=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_event_id:eid,phase:void 0,timestamp:now})}await appendPromotionEvidence(params.directory,evidenceRecords)}catch{}for(let id of criticalIds){if(ackedIds.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,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;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 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;await collectDelegateAcks({directory,prompt,transcript,agent,sessionId})}var PRIORITY_RANK={critical:0,high:1,medium:2,low:3};function buildDirectiveComplianceBlock(directives){if(directives.length===0)return null;let sorted=[...directives].sort((a,b)=>{let pr=(PRIORITY_RANK[a.priority]??2)-(PRIORITY_RANK[b.priority]??2);if(pr!==0)return pr;return a.id<b.id?-1:a.id>b.id?1:0}),lines=[];lines.push("<directives_to_verify>"),lines.push("Produce a DIRECTIVE_COMPLIANCE verdict for EVERY id below. Run any verification_predicate provided.");for(let d of sorted){if(lines.push(`- id: ${d.id}`),lines.push(` priority: ${d.priority}`),d.lesson)lines.push(` lesson: ${d.lesson}`);if(d.verification_predicate)lines.push(` verification_predicate: ${d.verification_predicate}`)}return lines.push("</directives_to_verify>"),lines.push(""),lines.push(`DIRECTIVE_COMPLIANCE: one line per knowledge directive shown during this phase (the IDs are listed in the DIRECTIVES TO VERIFY block of your prompt). Use exactly one of:
6045
6046
  VERIFIED:<id> evidence=<file:line | predicate_passed>
6046
6047
  VIOLATED:<id> evidence=<file:line | failing_predicate>
6047
6048
  N/A:<id> reason=<why it does not apply to this change>
6048
6049
  Every listed directive ID MUST appear exactly once. If a directive carries a verification_predicate, you MUST run it and report predicate_passed / failing_predicate as the evidence. Omitting a listed directive ID is itself a VIOLATED verdict.`),lines.join(`
6049
6050
  `)}function parseDirectivesToVerifyBlock(text){if(!text||!text.includes("<directives_to_verify>"))return[];let start=text.indexOf("<directives_to_verify>"),end=text.indexOf("</directives_to_verify>",start),body=end>=0?text.slice(start,end):text.slice(start),out=[];for(let line of body.split(`
6050
- `)){let idM=/^- id:\s*(\S+)\s*$/.exec(line);if(idM){out.push({id:idM[1],priority:"medium"});continue}if(out.length===0)continue;let current=out[out.length-1],prM=/^\s+priority:\s*(low|medium|high|critical)\s*$/.exec(line);if(prM){current.priority=prM[1];continue}let predM=/^\s+verification_predicate:\s*(.+?)\s*$/.exec(line);if(predM){current.verification_predicate=predM[1];continue}let lessonM=/^\s+lesson:\s*(.+?)\s*$/.exec(line);if(lessonM)current.lesson=lessonM[1]}return out}init_schema();init_manager();init_logger();init_extractors();init_knowledge_events();init_knowledge_store();init_knowledge_types();import{existsSync as existsSync101}from"node:fs";async function collectPhaseDirectiveIds(directory,phaseLabel){let events=await readKnowledgeEvents(directory),ids=new Set;for(let e of events){if(e.type!=="retrieved")continue;if(phaseLabel&&e.phase!==phaseLabel)continue;for(let id of e.result_ids)ids.add(id)}return[...ids]}async function readEntriesById(directory){let map3=new Map,swarm=await readKnowledge(resolveSwarmKnowledgePath(directory));for(let e of swarm)map3.set(e.id,e);let hivePath=resolveHiveKnowledgePath2();if(existsSync101(hivePath)){let hive=await readKnowledge(hivePath);for(let e of hive)if(!map3.has(e.id))map3.set(e.id,e)}return map3}async function readPhaseDirectivesToVerify(directory,phaseLabel){try{let ids=await collectPhaseDirectiveIds(directory,phaseLabel);if(ids.length===0)return[];let entries=await readEntriesById(directory),out=[];for(let id of ids){let e=entries.get(id);if(!e)continue;if(!isActiveStatus(e.status))continue;out.push({id,priority:e.directive_priority??"medium",lesson:e.lesson,verification_predicate:e.verification_predicate})}return out}catch{return[]}}init_skill_propagation_gate();function isTaskTool4(tool3){return tool3==="Task"||tool3==="task"}function hasDelegateDirectiveBlock(text){return parseDelegateDirectiveBlock(text).length>0}function hasDirectiveComplianceBlock(text){return parseDirectivesToVerifyBlock(text).length>0}async function injectDelegateDirectivesBefore(directory,input,config3){try{let debugSkip=(reason,data)=>{return log("[delegate-directive-injection] skipped",{reason,caller_agent:typeof input.agent==="string"?input.agent:void 0,tool:input.tool,...data}),0};if(config3.enabled===!1)return debugSkip("knowledge_disabled");if(!isTaskTool4(input.tool))return debugSkip("not_task_tool");let callerAgent=typeof input.agent==="string"?input.agent:"",callerRole=stripKnownSwarmPrefix(callerAgent).toLowerCase();if(!callerAgent||callerRole!=="architect")return debugSkip("caller_not_allowed",{caller_role:callerRole});let argsRecord=input.args&&typeof input.args==="object"?input.args:null;if(!argsRecord)return debugSkip("missing_args");let promptRaw=argsRecord.prompt;if(typeof promptRaw!=="string")return debugSkip("missing_prompt");let parsed=parseDelegationArgs(input.args);if(!parsed)return debugSkip("unparseable_delegation_args");let targetAgent=parsed.targetAgent;if(!isDelegatedAgent(targetAgent))return debugSkip("target_not_delegated_agent",{target_agent:targetAgent});if(hasDelegateDirectiveBlock(promptRaw)||hasDirectiveComplianceBlock(promptRaw))return debugSkip("already_injected",{target_agent:targetAgent});let sessionId=typeof input.sessionID==="string"?input.sessionID:void 0,plan=await loadPlan(directory).catch(()=>null),phaseLabel=plan?extractCurrentPhaseFromPlan(plan)??`Phase ${plan.current_phase??1}`:void 0,{entries,trace_id}=await injectForDelegate({directory,agent:targetAgent,expectedTools:defaultExpectedToolsForAgent(targetAgent),taskTitle:promptRaw.slice(0,800),sessionId,phase:phaseLabel,config:config3}),prefixParts=[],delegateBlock=buildDelegateDirectiveBlock(entries,config3,trace_id);if(delegateBlock)prefixParts.push(delegateBlock);if(stripKnownSwarmPrefix(targetAgent).toLowerCase()==="reviewer"){let toVerify=await readPhaseDirectivesToVerify(directory,phaseLabel),complianceBlock=buildDirectiveComplianceBlock(toVerify);if(complianceBlock)prefixParts.push(complianceBlock)}if(prefixParts.length===0)return debugSkip("no_directives_to_inject",{target_agent:targetAgent});return argsRecord.prompt=`${prefixParts.join(`
6051
+ `)){let idM=/^- id:\s*(\S+)\s*$/.exec(line);if(idM){out.push({id:idM[1],priority:"medium"});continue}if(out.length===0)continue;let current=out[out.length-1],prM=/^\s+priority:\s*(low|medium|high|critical)\s*$/.exec(line);if(prM){current.priority=prM[1];continue}let predM=/^\s+verification_predicate:\s*(.+?)\s*$/.exec(line);if(predM){current.verification_predicate=predM[1];continue}let lessonM=/^\s+lesson:\s*(.+?)\s*$/.exec(line);if(lessonM)current.lesson=lessonM[1]}return out}init_schema();init_manager();init_logger();init_extractors();init_knowledge_events();init_knowledge_events();init_knowledge_store();init_knowledge_types();import{existsSync as existsSync101}from"node:fs";async function collectPhaseDirectiveIds(directory,phaseLabel){let events=await readKnowledgeEvents(directory),ids=new Set;for(let e of events){if(e.type!=="retrieved")continue;if(phaseLabel&&e.phase!==phaseLabel)continue;for(let id of e.result_ids)ids.add(id)}return[...ids]}async function readEntriesById(directory){let map3=new Map,swarm=await readKnowledge(resolveSwarmKnowledgePath(directory));for(let e of swarm)map3.set(e.id,e);let hivePath=resolveHiveKnowledgePath2();if(existsSync101(hivePath)){let hive=await readKnowledge(hivePath);for(let e of hive)if(!map3.has(e.id))map3.set(e.id,e)}return map3}async function readPhaseDirectivesToVerify(directory,phaseLabel){try{let ids=await collectPhaseDirectiveIds(directory,phaseLabel);if(ids.length===0)return[];let entries=await readEntriesById(directory),out=[];for(let id of ids){let e=entries.get(id);if(!e)continue;if(!isActiveStatus(e.status))continue;out.push({id,priority:e.directive_priority??"medium",lesson:e.lesson,verification_predicate:e.verification_predicate})}return out}catch{return[]}}init_skill_propagation_gate();function recordDelegateInjectionSkip(directory,reason,options){recordKnowledgeEvent(directory,{type:"injection_skip",reason,agent:options?.agent,session_id:options?.sessionId,detail:options?.detail}).catch(()=>{})}function isTaskTool4(tool3){return tool3==="Task"||tool3==="task"}function hasDelegateDirectiveBlock(text){return parseDelegateDirectiveBlock(text).length>0}function hasDirectiveComplianceBlock(text){return parseDirectivesToVerifyBlock(text).length>0}async function injectDelegateDirectivesBefore(directory,input,config3){let sessionId;try{sessionId=typeof input.sessionID==="string"?input.sessionID:void 0;let debugSkip=(reason,data)=>{return log("[delegate-directive-injection] skipped",{reason,caller_agent:typeof input.agent==="string"?input.agent:void 0,tool:input.tool,...data}),0};if(config3.enabled===!1)return debugSkip("knowledge_disabled");if(!isTaskTool4(input.tool))return debugSkip("not_task_tool");let callerAgent=typeof input.agent==="string"?input.agent:"",callerRole=stripKnownSwarmPrefix(callerAgent).toLowerCase();if(!callerAgent||callerRole!=="architect")return recordDelegateInjectionSkip(directory,"delegate_caller_not_allowed",{agent:callerAgent||void 0,sessionId,detail:{caller_role:callerRole}}),debugSkip("caller_not_allowed",{caller_role:callerRole});let argsRecord=input.args&&typeof input.args==="object"?input.args:null;if(!argsRecord)return recordDelegateInjectionSkip(directory,"delegate_missing_args",{agent:callerAgent,sessionId}),debugSkip("missing_args");let promptRaw=argsRecord.prompt;if(typeof promptRaw!=="string")return recordDelegateInjectionSkip(directory,"delegate_missing_prompt",{agent:callerAgent,sessionId}),debugSkip("missing_prompt");let parsed=parseDelegationArgs(input.args);if(!parsed)return recordDelegateInjectionSkip(directory,"delegate_unparseable_delegation_args",{agent:callerAgent,sessionId}),debugSkip("unparseable_delegation_args");let targetAgent=parsed.targetAgent;if(!isDelegatedAgent(targetAgent))return recordDelegateInjectionSkip(directory,"delegate_target_not_delegated_agent",{agent:targetAgent,sessionId,detail:{target_agent:targetAgent}}),debugSkip("target_not_delegated_agent",{target_agent:targetAgent});if(hasDelegateDirectiveBlock(promptRaw)||hasDirectiveComplianceBlock(promptRaw))return recordDelegateInjectionSkip(directory,"delegate_already_injected",{agent:targetAgent,sessionId}),debugSkip("already_injected",{target_agent:targetAgent});let plan=await loadPlan(directory).catch(()=>null),phaseLabel=plan?extractCurrentPhaseFromPlan(plan)??`Phase ${plan.current_phase??1}`:void 0,{entries,trace_id}=await injectForDelegate({directory,agent:targetAgent,expectedTools:defaultExpectedToolsForAgent(targetAgent),taskTitle:promptRaw.slice(0,800),sessionId,phase:phaseLabel,config:config3}),prefixParts=[],delegateBlock=buildDelegateDirectiveBlock(entries,config3,trace_id);if(delegateBlock)prefixParts.push(delegateBlock);if(stripKnownSwarmPrefix(targetAgent).toLowerCase()==="reviewer"){let toVerify=await readPhaseDirectivesToVerify(directory,phaseLabel),complianceBlock=buildDirectiveComplianceBlock(toVerify);if(complianceBlock)prefixParts.push(complianceBlock)}if(prefixParts.length===0)return recordDelegateInjectionSkip(directory,"delegate_no_directives_to_inject",{agent:targetAgent,sessionId}),debugSkip("no_directives_to_inject",{target_agent:targetAgent});return argsRecord.prompt=`${prefixParts.join(`
6051
6052
 
6052
6053
  `)}
6053
6054
 
6054
- ${promptRaw}`,log("[delegate-directive-injection] injected",{caller_agent:callerAgent,caller_role:callerRole,target_agent:targetAgent,count:entries.length,session_id:sessionId}),entries.length}catch(err){return warn(`[delegate-directive-injection] non-fatal: ${err instanceof Error?err.message:String(err)}`),0}}init_state2();init_normalize_tool_name();var ledgerBySession=new Map,MAX_TRACKED_SESSIONS7=500,MAX_LEDGER_ENTRIES_PER_SESSION=200,droppedEntryCounts=new Map,callStartTimes2=new Map;function createDelegationLedgerHook(config3,_directory,injectAdvisory){let enabled=config3.enabled??!0;return{toolAfter:async(input,output)=>{if(!enabled)return;let sessionId=input.sessionID,startKey=`${sessionId}:${input.callID}`,startTime=callStartTimes2.get(startKey)??Date.now();callStartTimes2.delete(startKey);let duration_ms=Date.now()-startTime,args2=input.args??{},file3=typeof args2.path==="string"?args2.path:typeof args2.filePath==="string"?args2.filePath:typeof args2.file==="string"?args2.file:void 0,session=swarmState.agentSessions.get(sessionId),agentName=swarmState.activeAgent?.get(sessionId)??session?.agentName??"unknown",outputStr=String(output.output??""),success3=!outputStr.startsWith("Error:")&&!outputStr.startsWith("error: "),entry={agent:agentName,tool:input.tool,file:file3,duration_ms,success:success3,timestamp:Date.now()},existing=ledgerBySession.get(sessionId)??[];if(existing.push(entry),existing.length>MAX_LEDGER_ENTRIES_PER_SESSION){let dropped=existing.length-MAX_LEDGER_ENTRIES_PER_SESSION;existing.splice(0,dropped),droppedEntryCounts.set(sessionId,(droppedEntryCounts.get(sessionId)??0)+dropped)}ledgerBySession.set(sessionId,existing);while(ledgerBySession.size>MAX_TRACKED_SESSIONS7){let oldest=ledgerBySession.keys().next().value;if(oldest===void 0||oldest===sessionId)break;ledgerBySession.delete(oldest),droppedEntryCounts.delete(oldest)}},onArchitectResume:(architectSessionId)=>{if(!enabled)return;let allEntries=[],totalDroppedEntries=0;for(let[sessionId,entries]of ledgerBySession){if(sessionId===architectSessionId)continue;allEntries.push(...entries),totalDroppedEntries+=droppedEntryCounts.get(sessionId)??0}if(allEntries.length===0)return;for(let sessionId of ledgerBySession.keys())if(sessionId!==architectSessionId)ledgerBySession.delete(sessionId),droppedEntryCounts.delete(sessionId);let toolCallCount=allEntries.length,filesModified=[...new Set(allEntries.filter((e)=>isWriteTool3(e.tool)&&e.file).map((e)=>e.file))],filesRead=[...new Set(allEntries.filter((e)=>isReadTool(e.tool)&&e.file).map((e)=>e.file))],failedCalls=allEntries.filter((e)=>!e.success).length,scopeViolations=allEntries.filter((e)=>e.tool.includes("scope")).length,summary=["DELEGATION SUMMARY:",` Tool calls: ${toolCallCount}${failedCalls>0?` (${failedCalls} failed)`:""}`,filesModified.length>0?` Files modified: ${filesModified.slice(0,5).join(", ")}${filesModified.length>5?` (+${filesModified.length-5} more)`:""}`:null,filesRead.length>0?` Files read: ${filesRead.slice(0,5).join(", ")}${filesRead.length>5?` (+${filesRead.length-5} more)`:""}`:null,scopeViolations>0?` ⚠️ ${scopeViolations} scope violation(s) detected`:null,totalDroppedEntries>0?` ...and ${totalDroppedEntries} earlier call(s) omitted (per-session ledger cap)`:null].filter(Boolean).join(`
6055
+ ${promptRaw}`,log("[delegate-directive-injection] injected",{caller_agent:callerAgent,caller_role:callerRole,target_agent:targetAgent,count:entries.length,session_id:sessionId}),entries.length}catch(err){let message=err instanceof Error?err.message:String(err);return recordDelegateInjectionSkip(directory,"delegate_injection_error",{sessionId,detail:{message}}),warn(`[delegate-directive-injection] non-fatal: ${message}`),0}}init_state2();init_normalize_tool_name();var ledgerBySession=new Map,MAX_TRACKED_SESSIONS7=500,MAX_LEDGER_ENTRIES_PER_SESSION=200,droppedEntryCounts=new Map,callStartTimes2=new Map;function createDelegationLedgerHook(config3,_directory,injectAdvisory){let enabled=config3.enabled??!0;return{toolAfter:async(input,output)=>{if(!enabled)return;let sessionId=input.sessionID,startKey=`${sessionId}:${input.callID}`,startTime=callStartTimes2.get(startKey)??Date.now();callStartTimes2.delete(startKey);let duration_ms=Date.now()-startTime,args2=input.args??{},file3=typeof args2.path==="string"?args2.path:typeof args2.filePath==="string"?args2.filePath:typeof args2.file==="string"?args2.file:void 0,session=swarmState.agentSessions.get(sessionId),agentName=swarmState.activeAgent?.get(sessionId)??session?.agentName??"unknown",outputStr=String(output.output??""),success3=!outputStr.startsWith("Error:")&&!outputStr.startsWith("error: "),entry={agent:agentName,tool:input.tool,file:file3,duration_ms,success:success3,timestamp:Date.now()},existing=ledgerBySession.get(sessionId)??[];if(existing.push(entry),existing.length>MAX_LEDGER_ENTRIES_PER_SESSION){let dropped=existing.length-MAX_LEDGER_ENTRIES_PER_SESSION;existing.splice(0,dropped),droppedEntryCounts.set(sessionId,(droppedEntryCounts.get(sessionId)??0)+dropped)}ledgerBySession.set(sessionId,existing);while(ledgerBySession.size>MAX_TRACKED_SESSIONS7){let oldest=ledgerBySession.keys().next().value;if(oldest===void 0||oldest===sessionId)break;ledgerBySession.delete(oldest),droppedEntryCounts.delete(oldest)}},onArchitectResume:(architectSessionId)=>{if(!enabled)return;let allEntries=[],totalDroppedEntries=0;for(let[sessionId,entries]of ledgerBySession){if(sessionId===architectSessionId)continue;allEntries.push(...entries),totalDroppedEntries+=droppedEntryCounts.get(sessionId)??0}if(allEntries.length===0)return;for(let sessionId of ledgerBySession.keys())if(sessionId!==architectSessionId)ledgerBySession.delete(sessionId),droppedEntryCounts.delete(sessionId);let toolCallCount=allEntries.length,filesModified=[...new Set(allEntries.filter((e)=>isWriteTool3(e.tool)&&e.file).map((e)=>e.file))],filesRead=[...new Set(allEntries.filter((e)=>isReadTool(e.tool)&&e.file).map((e)=>e.file))],failedCalls=allEntries.filter((e)=>!e.success).length,scopeViolations=allEntries.filter((e)=>e.tool.includes("scope")).length,summary=["DELEGATION SUMMARY:",` Tool calls: ${toolCallCount}${failedCalls>0?` (${failedCalls} failed)`:""}`,filesModified.length>0?` Files modified: ${filesModified.slice(0,5).join(", ")}${filesModified.length>5?` (+${filesModified.length-5} more)`:""}`:null,filesRead.length>0?` Files read: ${filesRead.slice(0,5).join(", ")}${filesRead.length>5?` (+${filesRead.length-5} more)`:""}`:null,scopeViolations>0?` ⚠️ ${scopeViolations} scope violation(s) detected`:null,totalDroppedEntries>0?` ...and ${totalDroppedEntries} earlier call(s) omitted (per-session ledger cap)`:null].filter(Boolean).join(`
6055
6056
  `);try{injectAdvisory(architectSessionId,summary)}catch{}}}}var WRITE_TOOL_PATTERNS=["write","edit","patch","create","insert","replace","append","prepend"];function isWriteTool3(toolName){let normalized=normalizeToolNameLowerCase(toolName);return WRITE_TOOL_PATTERNS.some((p)=>normalized.includes(p))}var READ_TOOL_PATTERNS=["read","cat","view","fetch","get"];function isReadTool(toolName){let normalized=normalizeToolNameLowerCase(toolName);return READ_TOOL_PATTERNS.some((p)=>normalized.includes(p))}init_constants();init_schema();import*as fs116 from"node:fs";init_constants();import*as fs115 from"node:fs";import*as path211 from"node:path";var READ_ONLY_TOOLS=new Set(["check_gate_status","completion_verify","evidence_check","get_approved_plan","get_qa_gate_profile","diff","diff_summary","imports","symbols","batch_symbols","search","repo_map","retrieve_summary","knowledge_recall","knowledge_query","co_change_analyzer","complexity_hotspots","detect_domains","lint","lint_spec","pkg_audit","placeholder_scan","pre_check_batch","quality_budget","sast_scan","sbom_generate","schema_drift","secretscan","syntax_check","test_impact","todo_extract","doc_scan","doc_extract","req_coverage","req_coverage".toLowerCase(),"read","glob","grep","list","ls","view"]),WRITE_LIKE_TOOLS=new Set([...WRITE_TOOL_NAMES,"multiedit","multi_edit","todo_write","save_plan","update_task_status","phase_complete","declare_scope","declare_council_criteria","submit_council_verdicts","submit_phase_council_verdicts","set_qa_gates","write_retro","write_drift_evidence","write_hallucination_evidence","write_mutation_evidence","knowledge_add","knowledge_remove","curator_analyze","consensus_mine","suggest_patch"]),SHELL_TOOLS=new Set(["bash","shell","exec","run"]),NETWORK_TOOLS=new Set(["web_search","webfetch","web_fetch","fetch","http","request","gitingest"]),SUBAGENT_TOOLS=new Set(["task","agent","delegate"]),HIGH_RISK_BUILD_PATHS=["src/index.ts","src/hooks/guardrails.ts","src/hooks/delegation-gate.ts","src/hooks/scope-guard.ts","src/hooks/full-auto-permission.ts","src/hooks/full-auto-intercept.ts","src/full-auto/","src/config/schema.ts","src/config/constants.ts","src/tools/phase-complete.ts","src/tools/index.ts","package.json","package-lock.json","bun.lock","biome.json","tsconfig.json","CHANGELOG.md",".release-please-manifest.json","release-please-config.json","dist/",".github/workflows/"],ALWAYS_PROTECTED_PREFIXES=[".git/",".git\\"],PROTECTED_PATH_DEFAULTS=[".git",".github/workflows",".opencode",".swarm","package.json","package-lock.json","bun.lock","CHANGELOG.md",".release-please-manifest.json","release-please-config.json"],SAFE_SHELL_PATTERNS=[/^(?:cat|head|tail|less|more|file|stat|wc|sort|uniq|tr|cut|awk|sed)\b/,/^(?:ls|pwd|whoami|hostname|uname|env|date|which|type|tree)\b/,/^(?:echo|printf|true|false|test)\b/,/^(?:grep|rg|ag|find|fd|locate)\b/,/^git\s+(?:status|log|show|diff|branch|describe|rev-parse|rev-list|ls-files|config\s+--get|remote\s+-v|stash\s+list)/,/^(?:bun|npm|yarn|pnpm)\s+(?:run\s+(?:typecheck|lint|test|build)|test|typecheck|lint)\b/,/^node\s+(?:--version|-v|--input-type)/,/^bunx\s+biome\s+(?:ci|check|lint|format)\b/],DENY_SHELL_PATTERNS=[/\brm\s+(?:-[^\s]*\s+)*(?:\/|~|\.)?\s*$|\brm\s+-[rRf]+/i,/\bdd\s+if=/i,/\bmkfs\b/i,/\bshutdown\b|\breboot\b|\bhalt\b|\bpoweroff\b/i,/\b(?:chown|chmod)\s+-R\s+/i,/\bkill\s+-9\b/i,/\bpkill\b|\bkillall\b/i,/\bgit\s+push\s+--force(?!-with-lease)/i,/\bgit\s+push\s+(?:[^\s]+\s+)?(?:main|master|production|prod)\b/i,/\bgit\s+reset\s+--hard\b/i,/\bgit\s+clean\s+-(?:f|d|x)/i,/\bgit\s+branch\s+-D\b/i,/\bgit\s+checkout\s+\.|\bgit\s+restore\s+\./i,/\b(?:cat|head|tail|less|more)\s+[^\n]*(?:\.env|credentials|id_rsa|id_ed25519|\.pem|\.key)/i,/\bprintenv\b.*(?:SECRET|TOKEN|KEY|PASSWORD)/i,/\bcurl\s+[^|]*\|\s*(?:sh|bash|zsh|fish)\b/i,/\bwget\s+[^|]*\|\s*(?:sh|bash|zsh|fish)\b/i,/\bsudo\s+(?:rm|chmod|chown|dd|mkfs|shutdown)/i,/\bnpm\s+publish\b/i,/\bbun\s+publish\b/i,/\bbunx?\s+publish\b/i,/\bterraform\s+(?:apply|destroy)\b/i,/\bkubectl\s+(?:delete|apply\s+-f)/i,/\bdrop\s+(?:database|table)\b/i,/\bsed\s+-i\b(?=[^\n]*\b(?:biome\.json|eslintrc|oxlintrc)\b)(?=[^\n]*\b(?:error|warn|off)\b)/i,/\b(?:cat|tee)\b[^\n]*>\s*[^\n]*\b(biome\.json|eslintrc|oxlintrc)\b[^\n]*\b(error|warn|off)\b/i],ESCALATE_SHELL_PATTERNS=[/\bcurl\b/i,/\bwget\b/i,/\bssh\b/i,/\bscp\b/i,/\brsync\b/i,/\bsudo\b/i,/\bchmod\b/i,/\bchown\b/i,/\bnpm\s+(?:install|i|add)\b/i,/\bbun\s+(?:install|i|add|remove|update)\b/i,/\byarn\s+(?:install|add|remove|upgrade)\b/i,/\bpnpm\s+(?:install|add|remove|update)\b/i,/\bpip\s+install\b/i,/\bgit\s+push\b/i,/\bgit\s+pull\b/i,/\bgit\s+rebase\b/i,/\bgit\s+merge\b/i,/\bgit\s+commit\b/i,/\b(sed\s+-i|echo\s+|printf\s+)[^\n]*\b(biome\.jsonc?|eslintrc|eslint\.config|oxlintrc|prettierrc|secretscanignore|golangci|tsconfig\.json|tsconfig\.[^.]+\.json)\b/i,/\b(?:cat|tee)\b[^\n]*>\s*[^\n]*\b(biome\.jsonc?|eslintrc|eslint\.config|oxlintrc|prettierrc|secretscanignore|golangci|tsconfig\.json|tsconfig\.[^.]+\.json)\b/i];function isReadOnlyTool(toolName){if(!toolName)return!1;return READ_ONLY_TOOLS.has(toolName.toLowerCase())}function isWriteLikeTool(toolName){if(!toolName)return!1;return WRITE_LIKE_TOOLS.has(toolName.toLowerCase())}function isSubagentDelegation(toolName,args2){let lower=toolName?.toLowerCase()??"";if(SUBAGENT_TOOLS.has(lower))return!0;if(lower==="task"&&args2&&typeof args2==="object")return!0;return!1}function isWithinDirectory(target,root){if(!target||!root)return!1;let resolvedTarget=path211.resolve(target),resolvedRoot=path211.resolve(root);if(resolvedTarget===resolvedRoot)return!0;let withSep=resolvedRoot.endsWith(path211.sep)?resolvedRoot:resolvedRoot+path211.sep;if(process.platform==="win32")return resolvedTarget.toLowerCase().startsWith(withSep.toLowerCase());return resolvedTarget.startsWith(withSep)}var SEGMENT_PROTECTED=new Set([".git",".swarm","package.json","package-lock.json","bun.lock","CHANGELOG.md",".release-please-manifest.json","release-please-config.json"]);function isProtectedPath2(filePath,config3){if(!filePath)return!1;let normalized=normalizePath(filePath);for(let prefix of ALWAYS_PROTECTED_PREFIXES){let np=normalizePath(prefix);if(normalized===np||normalized.startsWith(`${np}/`))return!0}let segments=normalized.split("/").filter(Boolean),allowDefaults=config3?.permission_policy?.allow_defaults!==!1;if(allowDefaults){for(let seg of segments)if(SEGMENT_PROTECTED.has(seg))return!0}let protectedList=[...allowDefaults?PROTECTED_PATH_DEFAULTS:[],...config3?.permission_policy?.protected_paths??[]];for(let candidate of protectedList){let c=normalizePath(candidate);if(!c)continue;if(normalized===c)return!0;if(normalized.startsWith(`${c}/`))return!0;if(!c.includes("/")&&segments.includes(c))return!0}return!1}function classifyPathRisk(filePath,context){if(!filePath)return{withinProjectRoot:!1,withinDeclaredScope:null,protected:!1,highRiskBuild:!1};let absolute=path211.isAbsolute(filePath)?filePath:path211.resolve(context.directory,filePath),resolvedAbsolute=(()=>{try{let candidate=absolute,depth=0;while(depth<32){if(fs115.existsSync(candidate)){if(isWithinDirectory(candidate,context.directory))try{return fs115.realpathSync(candidate)}catch{return candidate}return absolute}let parent=path211.dirname(candidate);if(parent===candidate)break;candidate=parent,depth+=1}return absolute}catch{return absolute}})(),withinProjectRoot=isWithinDirectory(absolute,context.directory)&&isWithinDirectory(resolvedAbsolute,context.directory),relative46=normalizePath(path211.relative(context.directory,absolute)),withinDeclaredScope=null;if(Array.isArray(context.declaredScope))withinDeclaredScope=context.declaredScope.length===0?!1:context.declaredScope.some((scope)=>{let s=normalizePath(scope);if(!s)return!1;return relative46===s||relative46.startsWith(`${s}/`)});let highRiskBuild=HIGH_RISK_BUILD_PATHS.some((entry)=>{let e=normalizePath(entry);if(e.endsWith("/"))return relative46.startsWith(e);return relative46===e||relative46.startsWith(`${e}/`)});return{withinProjectRoot,withinDeclaredScope,protected:!1,highRiskBuild}}var SHELL_METACHARACTER_PATTERN=/[|&;<>`$]|\$\(|\\\n/;function classifyCommandRisk(command,_cwd,_context){if(!command||typeof command!=="string")return{decision:"escalate_critic",reason:"shell command empty or non-string — cannot classify deterministically"};let trimmed=command.trim();for(let re of DENY_SHELL_PATTERNS)if(re.test(trimmed))return{decision:"deny",reason:`shell command matches deny pattern (${re.source})`};let hasMetacharacter=SHELL_METACHARACTER_PATTERN.test(trimmed);if(!hasMetacharacter){for(let re of SAFE_SHELL_PATTERNS)if(re.test(trimmed))return{decision:"allow",reason:"shell command matches deterministically safe pattern"}}for(let re of ESCALATE_SHELL_PATTERNS)if(re.test(trimmed))return{decision:"escalate_critic",reason:`shell command matches escalate pattern (${re.source})`};if(hasMetacharacter)return{decision:"escalate_critic",reason:"shell command contains metacharacters (|, &, ;, <, >, $, backtick) — verify with critic"};return{decision:"escalate_critic",reason:"shell command not in deterministic allow/deny set"}}var PATH_ARG_KEYS=["file_path","filepath","path","file","target","to","dest","destination","output_path"];function extractPathArgs(toolName,args2){if(!args2||typeof args2!=="object")return[];let found=[];for(let key of PATH_ARG_KEYS){let v=args2[key];if(typeof v==="string"&&v.trim())found.push(v)}let filesArg=args2.files;if(Array.isArray(filesArg)){for(let f of filesArg)if(typeof f==="string"&&f.trim())found.push(f);else if(f&&typeof f==="object"&&typeof f.path==="string")found.push(f.path)}let editsArg=args2.edits;if(Array.isArray(editsArg)){for(let e of editsArg)if(e&&typeof e==="object"&&typeof e.file_path==="string")found.push(e.file_path)}if(toolName==="declare_scope"&&Array.isArray(args2.files));return found}function extractCommandArg(args2){if(!args2||typeof args2!=="object")return;return typeof args2.command==="string"&&args2.command||typeof args2.cmd==="string"&&args2.cmd||typeof args2.script==="string"&&args2.script||void 0}function extractURLArg(args2){if(!args2||typeof args2!=="object")return;return typeof args2.url==="string"&&args2.url||typeof args2.uri==="string"&&args2.uri||typeof args2.endpoint==="string"&&args2.endpoint||void 0}function isTrustedDomain(url3,config3){let domains=config3?.permission_policy?.trusted_domains??[];if(domains.length===0)return!1;let host="";try{host=new URL(url3).hostname.toLowerCase()}catch{return!1}return domains.some((d)=>{let dl=d.toLowerCase();return host===dl||host.endsWith(`.${dl}`)})}function classifyFullAutoToolAction(input){let tool3=input.toolName?.toLowerCase()??"",config3=input.fullAutoConfig,mode=config3?.mode??"supervised";if(!(mode==="strict"||config3?.permission_policy?.enabled!==!1))return{action:"allow",reason:"permission policy disabled by config",tier:"local"};if(isReadOnlyTool(tool3))return{action:"allow",reason:"read-only tool",tier:"safe"};if(isSubagentDelegation(tool3,input.args)){let subagentName=typeof input.args?.subagent_type==="string"&&input.args.subagent_type||typeof input.args?.agent==="string"&&input.args.agent||"unknown";return{action:"escalate_critic",reason:"subagent delegation requires plan/scope verification",risk:"high",context:{tool:tool3,subagent:subagentName,currentTaskID:input.currentTaskID,currentPhase:input.currentPhase}}}if(tool3==="phase_complete")return{action:"escalate_critic",reason:"phase_complete requires Full-Auto approval evidence",risk:"high",context:{tool:tool3,currentPhase:input.currentPhase}};if(tool3==="update_task_status"){let status=typeof input.args?.status==="string"&&input.args.status||"";if(status==="completed"){if(mode==="strict"||config3?.oversight?.on_task_completion===!0)return{action:"escalate_critic",reason:"task completion requires Full-Auto critic verification",risk:"medium",context:{tool:tool3,status}}}else{if(mode==="strict")return{action:"escalate_critic",reason:`strict mode: update_task_status with status=${status} requires critic verification`,risk:"medium",context:{tool:tool3,status}};return{action:"allow",reason:`update_task_status with status=${status} is a routine state change`,tier:"local"}}}if(tool3==="save_plan")return{action:"escalate_critic",reason:"plan mutation requires Full-Auto critic verification",risk:"high",context:{tool:tool3}};if(NETWORK_TOOLS.has(tool3)){let url3=extractURLArg(input.args);if(url3&&isTrustedDomain(url3,config3))return{action:"allow",reason:"network tool with trusted domain",tier:"local"};return{action:"escalate_critic",reason:"network/web tool — verify intent and target",risk:"medium",context:{tool:tool3,url:url3}}}if(SHELL_TOOLS.has(tool3)){let command=extractCommandArg(input.args);if(!command)return{action:"deny",reason:"shell tool invoked without a command argument",code:"shell_no_command",recoverable:!0};let cmdRisk=classifyCommandRisk(command,input.workingDirectory??"",{directory:input.directory});if(cmdRisk.decision==="deny")return{action:"deny",reason:cmdRisk.reason,code:"shell_deny",recoverable:!0};if(cmdRisk.decision==="allow")return{action:"allow",reason:cmdRisk.reason,tier:"local"};return{action:"escalate_critic",reason:cmdRisk.reason,risk:"medium",context:{tool:tool3,command}}}if(isWriteLikeTool(tool3)||tool3==="patch"||tool3==="edit"){let paths=extractPathArgs(tool3,input.args);if(paths.length===0){if(new Set(["declare_scope","declare_council_criteria","submit_council_verdicts","submit_phase_council_verdicts","set_qa_gates","write_retro","write_drift_evidence","write_hallucination_evidence","write_mutation_evidence","knowledge_add","knowledge_remove","curator_analyze","consensus_mine"]).has(tool3))return{action:"allow",reason:`pathless plan/evidence tool '${tool3}' allowed under Full-Auto`,tier:"local"};return{action:"escalate_critic",reason:"write-like tool without explicit path — verify side effects",risk:"medium",context:{tool:tool3,args:input.args}}}for(let p of paths){let risk=classifyPathRisk(p,{directory:input.directory,declaredScope:input.declaredScope??null});if(!risk.withinProjectRoot)return{action:"deny",reason:`write target outside project root: ${p}`,code:"path_out_of_root",recoverable:!0};if(isProtectedPath2(path211.relative(input.directory,path211.resolve(input.directory,p)),config3))return{action:"escalate_critic",reason:`write to protected path requires critic approval: ${p}`,risk:"high",context:{tool:tool3,path:p}};if(risk.highRiskBuild)return{action:"escalate_critic",reason:`write to high-risk build/plugin path requires critic approval: ${p}`,risk:"high",context:{tool:tool3,path:p}};if(input.normalizedAgentName==="coder"&&Array.isArray(input.declaredScope)&&input.declaredScope.length>0&&risk.withinDeclaredScope===!1)return{action:"deny",reason:`coder write outside declared scope: ${p}`,code:"path_out_of_scope",recoverable:!0}}return{action:"allow",reason:"write within project root and declared scope",tier:"local"}}return{action:"escalate_critic",reason:`tool '${tool3||"<empty>"}' not deterministically classifiable`,risk:"medium",context:{tool:tool3}}}function buildStructuredDenial(decision,tool3){return{full_auto_denial:!0,tool:tool3,code:decision.code,reason:decision.reason,recoverable:decision.recoverable,guidance:decision.recoverable?"Choose a safer path: stay within the project root, respect declared scope, avoid destructive shell, and avoid protected paths. Consider declaring scope or escalating to a human.":"This action cannot be retried under Full-Auto. Ask a human to authorize it."}}init_state3();init_file_locks();init_state2();init_logger();init_normalize_tool_name();init_utils2();var RETURN_WARNING_PATTERNS=[{category:"skipped_tests",regex:/\b(?:skipped (?:the )?tests?|tests? (?:were |was )?skipped|did(?:n['']t)? run tests?|tests? not run|bypass(?:ed)? (?:the )?tests?|test (?:step|phase) (?:was )?bypass|tests? (?:are )?failing|tests? (?:are )?broken)\b/i},{category:"tool_timeout",regex:/\b(?:tool|process|command|test|build|lint)\s+(?:timed out|timeout|hung|killed|aborted|terminated|did not (?:complete|finish))/i},{category:"scope_changed",regex:/\b(?:expanded|changed|widened|exceeded|broke|extended|enlarged|grew|altered|adjusted) (?:the )?(?:declared |working |task |allowed )?(?:scope|file ?list|file ?set|working set|set of files)\b|\bscope (?:expansion|creep|drift|change)\b/i},{category:"external_instructions",regex:/\b(?:followed |received |applied |honored |obeyed )?(?:instructions|directives|guidance|orders|commands|hints) (?:from|in|per|according to) (?:the )?(?:tool output|web|search|fetched|fetch|external|untrusted|upstream|page|site|doc|documentation|response|prompt)\b|\bper (?:the )?(?:upstream|external|fetched|web|tool) (?:doc|documentation|page|response|content|guidance)\b/i},{category:"unable_to_verify",regex:/\b(?:unable|could ?n['']t|cannot|can ?not|wasn['']?t able) (?:to )?(?:verify|confirm|reproduce|test|check|validate|prove)\b|\bverification (?:deferred|skipped|postponed|incomplete|pending|impossible)\b/i},{category:"missing_evidence",regex:/\b(?:no |missing |without |lacking )(?:evidence|proof|verification|tests? passing|test results|coverage)\b|\bevidence (?:is )?(?:missing|absent|unavailable)\b/i},{category:"out_of_scope_files",regex:/\b(?:created|generated|wrote|modified|added|edited|patched|touched) (?:files? |code )?(?:outside|beyond|past|not in|that (?:are|were) outside) (?:the )?(?:declared |task |coder |allowed )?(?:scope|file ?list|file ?set|allowed (?:paths|files))\b/i}],SEVERE_CATEGORIES=new Set(["external_instructions","out_of_scope_files"]),CANONICAL_ROLES_LOWER=new Set(ALL_AGENT_NAMES.map((s)=>s.toLowerCase()));function isExactCanonicalRole(name){return CANONICAL_ROLES_LOWER.has(name.toLowerCase())}function isTaskTool5(toolName){let lower=toolName?.toLowerCase()??"";return lower==="task"||lower==="agent"||lower==="delegate"}function extractText(value){if(typeof value==="string")return value;if(value&&typeof value==="object"){let o=value;if(typeof o.output==="string")return o.output;if(typeof o.text==="string")return o.text;if(typeof o.summary==="string")return o.summary;try{return JSON.stringify(o)}catch{return""}}return""}function detectReturnWarnings(text){let warnings=[];if(!text)return warnings;let seen=new Set;for(let{category,regex}of RETURN_WARNING_PATTERNS){let m=text.match(regex);if(!m)continue;let key=`${category}:${m[0].toLowerCase()}`;if(seen.has(key))continue;seen.add(key),warnings.push({category,matched:m[0]})}return warnings}async function writeDelegationEvent(directory,event){let lockTaskId=`full-auto-delegation-${Date.now()}`,lockResult;try{lockResult=await tryAcquireLock(directory,"events.jsonl","full-auto-delegation",lockTaskId)}catch(error93){warn(`[full-auto/delegation] failed to acquire lock: ${error93 instanceof Error?error93.message:String(error93)}`)}try{let eventsPath=validateSwarmPath(directory,"events.jsonl");fs116.appendFileSync(eventsPath,`${JSON.stringify(event)}
6056
6057
  `,"utf-8")}catch(error93){throw error48(`[full-auto/delegation] failed to write event: ${error93 instanceof Error?error93.message:String(error93)}`),error93}finally{if(lockResult?.acquired&&lockResult.lock._release)try{await lockResult.lock._release()}catch(releaseError){error48("[full-auto/delegation] lock release failed:",releaseError)}}}function createFullAutoDelegationHook(options){let{config:config3,directory}=options;return{toolBefore:async(input,output)=>{let tool3=(normalizeToolName(input.tool)??input.tool??"").toLowerCase();if(!isTaskTool5(tool3))return;let sessionID=input.sessionID;if(!sessionID)return;let runState=loadFullAutoRunState(directory,sessionID);if(!runState||runState.status!=="running")return;let args2=output.args??{},subagentRaw=typeof args2.subagent_type==="string"&&args2.subagent_type||typeof args2.agent==="string"&&args2.agent||"",generatedAgentRegistry=swarmState.generatedAgentNames,canonicalRole=generatedAgentRegistry.length>0?resolveGeneratedAgentRole(subagentRaw,generatedAgentRegistry):getCanonicalAgentRole(subagentRaw);if(subagentRaw&&canonicalRole!==subagentRaw&&!isExactCanonicalRole(subagentRaw)){if(!subagentRaw.slice(0,subagentRaw.length-canonicalRole.length-1))throw Error(`FULL_AUTO_DELEGATION_DENY: subagent name '${subagentRaw}' has no valid prefix before the canonical role '${canonicalRole}'. Generated agent names must include a non-empty swarm prefix.`)}let promptText=typeof args2.prompt==="string"&&args2.prompt||typeof args2.message==="string"&&args2.message||typeof args2.task==="string"&&args2.task||"";if(incrementFullAutoCounter(directory,sessionID,"coderDelegations"),!subagentRaw||!isKnownCanonicalRole(canonicalRole))throw Error(`FULL_AUTO_DELEGATION_DENY: unknown subagent '${subagentRaw}' (canonical role '${canonicalRole}' is not a registered plugin role). Choose a generated agent whose suffix matches one of the canonical roles.`);if(promptText&&typeof promptText==="string"){let candidatePaths=promptText.match(/\b[A-Za-z0-9._/-]+\.(?:ts|tsx|js|jsx|json|md|yml|yaml|toml|lock|sh|env)\b/g);if(candidatePaths){for(let p of candidatePaths)if(isProtectedPath2(p,config3.full_auto))await writeDelegationEvent(directory,{type:"full_auto_subagent_warning",timestamp:new Date().toISOString(),session_id:sessionID,subagent:subagentRaw,canonical_role:canonicalRole,phase:"outbound",category:"protected_path_in_prompt",matched:p})}}},toolAfter:async(input,output)=>{let tool3=(normalizeToolName(input.tool)??input.tool??"").toLowerCase();if(!isTaskTool5(tool3))return;let sessionID=input.sessionID;if(!sessionID)return;let runState=loadFullAutoRunState(directory,sessionID);if(!runState||runState.status!=="running")return;let text=extractText(output.output),warnings=detectReturnWarnings(text);if(warnings.length===0)return;let severe=warnings.some((w)=>SEVERE_CATEGORIES.has(w.category));if(await writeDelegationEvent(directory,{type:"full_auto_subagent_warning",timestamp:new Date().toISOString(),session_id:sessionID,phase:"return",warnings,severe}),runState.counters.consecutiveNoProgressTurns=severe?runState.counters.consecutiveNoProgressTurns+1:runState.counters.consecutiveNoProgressTurns,saveFullAutoRunState(directory,runState),severe){let updated=loadFullAutoRunState(directory,sessionID);if(updated&&updated.status==="running")updated.status="paused",updated.pauseReason=`severe subagent return warning: ${warnings.filter((w)=>SEVERE_CATEGORIES.has(w.category)).map((w)=>w.category).join(",")}`,saveFullAutoRunState(directory,updated)}}}}import*as fs117 from"node:fs";var PATTERNS=[{category:"instruction_override",regex:/\bignore (?:all |any |the )?(?:previous|prior|earlier|above) (?:instructions|prompts|rules|directives)\b/i},{category:"instruction_override",regex:/\bdisregard (?:all |any |the )?(?:previous|prior|earlier|above) (?:instructions|prompts|rules)\b/i},{category:"instruction_override",regex:/\bforget (?:all |any |everything|the )?(?:previous|above|prior) (?:instructions|prompts|rules)\b/i},{category:"system_role_override",regex:/\b(?:you are now|act as|pretend to be|from now on you are)\s+(?:a |an |the )?(?:system|developer|root|admin|superuser)\b/i},{category:"system_role_override",regex:/\b<\|?(?:system|developer|im_start|imstart)\|?>/i},{category:"credential_request",regex:/\b(?:please |kindly |)(?:paste|share|reveal|send|provide|leak|print|echo|cat) (?:your |the |my )?(?:api[_ -]?key|password|token|secret|credentials|\.env)\b/i},{category:"credential_request",regex:/\b(?:show|dump|export) (?:env(?:ironment)?|secrets|credentials|keys?)\b/i},{category:"exfiltration_request",regex:/\b(?:upload|exfiltrate|send) (?:contents of |files? from |the )?(?:home|repo|workspace|project|secrets?|env(?:ironment)?)\b/i},{category:"exfiltration_request",regex:/\bcurl\s+-d\s+@/i},{category:"guardrail_disable_request",regex:/\bdisable (?:full[- ]auto|guardrails?|safety|policy|oversight|critic)\b/i},{category:"guardrail_disable_request",regex:/\bturn (?:off|disable) (?:full[- ]auto|guardrails?|safety|policy)\b/i},{category:"curl_pipe_shell",regex:/\bcurl\b[^|\n]*\|\s*(?:sh|bash|zsh|fish)\b/i},{category:"untrusted_run_command",regex:/\b(?:run|execute|paste) (?:this|the following) (?:command|script|bash|shell)\b/i}];function buildExcerpt(text,match){let idx=match.index??0,start=Math.max(0,idx-120),end=Math.min(text.length,idx+match[0].length+120),slice=text.slice(start,end).replace(/\s+/g," ").trim();return slice.length>280?`${slice.slice(0,280)}…`:slice}function probeFullAutoInput(text){let warnings=[];if(!text||typeof text!=="string")return{hasWarning:!1,warnings};let seen=new Set;for(let{category,regex}of PATTERNS){let m=text.match(regex);if(!m)continue;let key=`${category}:${m[0].toLowerCase()}`;if(seen.has(key))continue;seen.add(key),warnings.push({category,matched:m[0],excerpt:buildExcerpt(text,m)})}return{hasWarning:warnings.length>0,warnings}}var RISKY_FOLLOWUP_TOOLS=new Set(["bash","shell","exec","web_search","webfetch","web_fetch","fetch","http","request"]),SECRET_TOOL_PATTERNS=[/\b(?:cat|head|tail|less|more)\s+[^\n]*\.env/i,/\bprintenv\b.*(?:SECRET|TOKEN|KEY|PASSWORD)/i];function shouldEscalateAfterWarning(toolName,commandOrUrl){let lower=toolName?.toLowerCase()??"";if(RISKY_FOLLOWUP_TOOLS.has(lower))return!0;if(typeof commandOrUrl==="string"){for(let re of SECRET_TOOL_PATTERNS)if(re.test(commandOrUrl))return!0}return!1}init_state3();init_file_locks();init_logger();init_normalize_tool_name();init_utils2();var PROBED_TOOLS=new Set(["web_search","webfetch","web_fetch","fetch","http","request","doc_extract","doc_scan","gitingest","extract_code_blocks","retrieve_summary","retrieve_lane_output","search","read","view"]);async function writeWarningEvent(directory,sessionID,tool3,probe2){let event={type:"full_auto_input_warning",timestamp:new Date().toISOString(),session_id:sessionID,tool:tool3,warnings:probe2.warnings},lockTaskId=`full-auto-input-warning-${Date.now()}`,lockResult;try{lockResult=await tryAcquireLock(directory,"events.jsonl","full-auto-input-warning",lockTaskId)}catch(error93){warn(`[full-auto/input-probe] failed to acquire lock: ${error93 instanceof Error?error93.message:String(error93)}`)}try{let eventsPath=validateSwarmPath(directory,"events.jsonl");fs117.appendFileSync(eventsPath,`${JSON.stringify(event)}
6057
6058
  `,"utf-8")}catch(error93){error48(`[full-auto/input-probe] failed to write event: ${error93 instanceof Error?error93.message:String(error93)}`)}finally{if(lockResult?.acquired&&lockResult.lock._release)try{await lockResult.lock._release()}catch(releaseError){error48("[full-auto/input-probe] lock release failed:",releaseError)}}}function extractText2(out){if(typeof out==="string")return out;if(out&&typeof out==="object"){let candidate=out;if(typeof candidate.output==="string")return candidate.output;if(typeof candidate.text==="string")return candidate.text;if(typeof candidate.body==="string")return candidate.body;try{return JSON.stringify(candidate)}catch{return""}}return""}var MAX_TRACKED_SESSIONS8=256,WARNING_TTL_MS=300000,fullAutoInputWarningStash=new Map;function isExpired2(w,nowMs=Date.now()){let at=Date.parse(w.at);if(!Number.isFinite(at))return!0;return nowMs-at>WARNING_TTL_MS}function evictExpired(){let now=Date.now();for(let[sid,w]of fullAutoInputWarningStash)if(isExpired2(w,now))fullAutoInputWarningStash.delete(sid);while(fullAutoInputWarningStash.size>MAX_TRACKED_SESSIONS8){let firstKey=fullAutoInputWarningStash.keys().next().value;if(firstKey===void 0)break;fullAutoInputWarningStash.delete(firstKey)}}function setPendingInputWarning(sessionID,warning){fullAutoInputWarningStash.delete(sessionID),fullAutoInputWarningStash.set(sessionID,warning),evictExpired()}function consumePendingInputWarning(sessionID){let warning=fullAutoInputWarningStash.get(sessionID);if(warning)fullAutoInputWarningStash.delete(sessionID);if(warning&&isExpired2(warning))return;return warning}function peekPendingInputWarning(sessionID){let w=fullAutoInputWarningStash.get(sessionID);if(!w)return;if(isExpired2(w)){fullAutoInputWarningStash.delete(sessionID);return}return w}function createFullAutoInputProbeHook(options){let{directory}=options;return{toolAfter:async(input,output)=>{let tool3=(normalizeToolName(input.tool)??input.tool??"").toLowerCase();if(!PROBED_TOOLS.has(tool3))return;let sessionID=input.sessionID;if(!sessionID)return;let runState=loadFullAutoRunState(directory,sessionID);if(!runState||runState.status!=="running")return;let text=extractText2(output.output);if(!text)return;let probe2=probeFullAutoInput(text);if(!probe2.hasWarning)return;setPendingInputWarning(sessionID,{tool:tool3,at:new Date().toISOString(),categories:probe2.warnings.map((w)=>w.category)}),await writeWarningEvent(directory,sessionID,tool3,probe2)}}}init_constants();init_schema();init_state3();init_scope_persistence();init_state2();init_normalize_tool_name();function createFullAutoPermissionHook(options){let{config:config3,directory}=options,fullAutoConfig=config3.full_auto;return{toolBefore:async(input,output)=>{let toolName=normalizeToolName(input.tool)??input.tool,sessionID=input.sessionID;if(!sessionID)return;let stateHealth=isFullAutoStateUnreadable();if(stateHealth.unreadable){if(isReadOnlyTool(toolName))return;throw Error(`FULL_AUTO_STATE_UNREADABLE: tool '${toolName}' blocked because the Full-Auto durable state file is unreadable (${stateHealth.reason}). Restore .swarm/full-auto-state.json (or .bak) and re-run /swarm full-auto on.`)}let runState=loadFullAutoRunState(directory,sessionID);if(!runState||runState.status==="idle")return;if(runState.status==="paused"||runState.status==="terminated"){if(isReadOnlyTool(toolName))return;let rawReason=runState.pauseReason??runState.terminateReason??"no reason recorded",statusPrefix=rawReason.includes("infrastructure failure")&&runState.status==="paused"?"FULL_AUTO_PAUSED:OVERSIGHT_INFRASTRUCTURE_FAILURE":`FULL_AUTO_${runState.status.toUpperCase()}`;throw Error(`${statusPrefix}: tool '${toolName}' blocked because Full-Auto run is ${runState.status} (${rawReason}). Re-enable with /swarm full-auto on after the underlying issue is resolved.`)}let session=swarmState.agentSessions.get(sessionID),activeAgent=swarmState.activeAgent.get(sessionID)??session?.agentName??ORCHESTRATOR_NAME,normalizedAgentName=stripKnownSwarmPrefix(activeAgent),taskId=session?.currentTaskId??null,binding=taskId?resolveAuthorizedScopeBinding({directory,taskId,activeSessionId:sessionID}):resolveAuthorizedScopeBindingForSession({directory,activeSessionId:sessionID});if(!taskId&&binding&&session)taskId=binding.taskId,session.currentTaskId=binding.taskId,session.declaredCoderScope=[...binding.files];let declaredScope=binding?.files??null,argsObj=output.args??void 0,lowerTool=toolName?.toLowerCase()??"",phaseFromArgs;if(lowerTool==="phase_complete"){if(phaseFromArgs=parsePhaseArg(argsObj),phaseFromArgs===void 0)throw Error("FULL_AUTO_DENY [phase_complete_invalid_phase]: phase_complete called without a valid 'phase' argument. Provide a positive integer phase before calling phase_complete.")}let effectivePhase=phaseFromArgs??runState.currentPhase,safeMode=["assisted","supervised","strict"].includes(runState.mode)?runState.mode:"strict",effectiveFullAutoConfig=fullAutoConfig?{...fullAutoConfig,mode:safeMode}:{mode:safeMode},classifierInput={sessionID,agentName:activeAgent,normalizedAgentName,toolName,args:argsObj,directory,declaredScope,currentTaskID:taskId,currentPhase:effectivePhase,planSummary:void 0,changedFiles:session&&taskId?getModifiedFilesForTask(session,taskId):void 0,fullAutoConfig:effectiveFullAutoConfig},decision=classifyFullAutoToolAction(classifierInput),pendingWarning=peekPendingInputWarning(sessionID);if(pendingWarning){let commandOrUrl=typeof argsObj?.command==="string"&&argsObj.command||typeof argsObj?.url==="string"&&argsObj.url||void 0;if(shouldEscalateAfterWarning(toolName,commandOrUrl))decision={action:"escalate_critic",reason:`risky follow-up after prompt-injection warning (${pendingWarning.categories.join(",")})`,risk:"high",context:{tool:toolName,priorWarningTool:pendingWarning.tool,categories:pendingWarning.categories}},consumePendingInputWarning(sessionID)}if(decision.action==="allow"){tickAndMaybeDispatchCadence(directory,sessionID,"toolCalls",config3,{activeAgent}),resetFullAutoDenials(directory,sessionID);return}if(decision.action==="deny"){let denial=buildStructuredDenial(decision,toolName);recordFullAutoDenial(directory,sessionID,{tool:toolName,code:decision.code,reason:decision.reason});let updated2=loadFullAutoRunState(directory,sessionID);if(updated2){let pauseDecision=shouldPauseForDenials(updated2,fullAutoConfig);if(pauseDecision.pause)if(pauseDecision.mode==="terminate")terminateFullAutoRun(directory,sessionID,pauseDecision.reason??"denial-limit");else pauseFullAutoRun(directory,sessionID,pauseDecision.reason??"denial-limit")}throw Error(`FULL_AUTO_DENY [${decision.code}]: ${decision.reason}. ${JSON.stringify(denial)}`)}if(decision.action==="pause")throw pauseFullAutoRun(directory,sessionID,decision.reason),Error(`FULL_AUTO_PAUSE [${decision.code}]: ${decision.reason}`);if(decision.action==="escalate_human")throw terminateFullAutoRun(directory,sessionID,decision.reason),Error(`FULL_AUTO_ESCALATE_HUMAN [${decision.code}]: ${decision.reason}`);let triggerSource=mapTriggerSource(decision,toolName),criticModel=fullAutoConfig?.critic_model??config3.agents?.critic?.model??"opencode/big-pickle",oversightAgentName=resolveOversightAgentNameFromActive(activeAgent);if(lowerTool==="phase_complete"&&effectivePhase!==void 0){let stateForPhase=loadFullAutoRunState(directory,sessionID);if(stateForPhase&&stateForPhase.currentPhase!==effectivePhase){stateForPhase.currentPhase=effectivePhase;try{saveFullAutoRunState(directory,stateForPhase)}catch(persistErr){let msg=persistErr instanceof Error?persistErr.message:String(persistErr);throw Error(`FULL_AUTO_BLOCKED: failed to persist phase ${effectivePhase} to durable run state — ${msg}`)}}}let outcome;try{outcome=await dispatchFullAutoOversight({directory,sessionID,trigger:decision.reason,triggerSource,phase:effectivePhase,taskID:taskId??void 0,planID:runState.planID,architectOutput:output.args?JSON.stringify(output.args):void 0,actionContext:{tool:toolName,...decision.context??{}},criticModel,oversightAgentName,fullAutoConfig:{fail_closed:fullAutoConfig?.fail_closed!==!1,max_dispatch_retries:fullAutoConfig?.oversight?.max_dispatch_retries??2,max_consecutive_dispatch_failures:fullAutoConfig?.oversight?.max_consecutive_dispatch_failures??3}})}catch(error93){let reason=error93 instanceof Error?error93.message:String(error93);throw pauseFullAutoRun(directory,sessionID,`oversight dispatcher exception: ${reason}`),Error(`FULL_AUTO_BLOCKED: oversight dispatch threw — ${reason}`)}if(outcome.decision==="allow"){tickAndMaybeDispatchCadence(directory,sessionID,"toolCalls",config3,{activeAgent}),resetFullAutoDenials(directory,sessionID);return}if(outcome.decision==="pause")throw Error(`FULL_AUTO_BLOCKED: critic verdict ${outcome.verdict} — ${outcome.reasoning}`);if(outcome.decision==="escalate_human")throw Error(`FULL_AUTO_ESCALATE_HUMAN: critic verdict ${outcome.verdict} — ${outcome.reasoning}`);recordFullAutoDenial(directory,sessionID,{tool:toolName,code:`critic_${outcome.verdict}`.toLowerCase(),reason:outcome.reasoning||`critic verdict ${outcome.verdict}`});let updated=loadFullAutoRunState(directory,sessionID);if(updated){let pauseDecision=shouldPauseForDenials(updated,fullAutoConfig);if(pauseDecision.pause)if(pauseDecision.mode==="terminate")terminateFullAutoRun(directory,sessionID,pauseDecision.reason??"denial-limit");else pauseFullAutoRun(directory,sessionID,pauseDecision.reason??"denial-limit")}throw Error(`FULL_AUTO_CRITIC_DENY: ${outcome.verdict} — ${outcome.reasoning}`)}}}function parsePhaseArg(args2){if(!args2)return;let raw=args2.phase,n;if(typeof raw==="number")n=raw;else if(typeof raw==="string"&&raw.trim()){let trimmed=raw.trim();if(!/^[1-9][0-9]*$/.test(trimmed))return;n=Number.parseInt(trimmed,10)}else return;if(!Number.isFinite(n)||!Number.isInteger(n)||n<1)return;if(n>Number.MAX_SAFE_INTEGER)return;return n}function mapTriggerSource(decision,toolName){if(decision.action!=="escalate_critic")return"tool_action";let lower=toolName?.toLowerCase()??"";if(lower==="phase_complete")return"phase_boundary";if(lower==="update_task_status")return"task_completion";if(decision.risk==="high")return"risk";return"tool_action"}function resolveOversightAgentNameFromActive(activeAgent){if(!activeAgent)return"critic_oversight";if(stripKnownSwarmPrefix(activeAgent)===ORCHESTRATOR_NAME){let lastIdx=activeAgent.toLowerCase().lastIndexOf("architect");if(lastIdx>0)return`${activeAgent.slice(0,lastIdx)}critic_oversight`}return"critic_oversight"}init_guardrails2();init_hive_promoter();init_stored_input_args();import*as fs118 from"node:fs";import*as path212 from"node:path";import*as child_process13 from"node:child_process";var WIN32_CMD_BINARIES=new Set(["npm","npx","pnpm","yarn"]),_internals142={spawn:child_process13.spawn};function spawnAsync(command,cwd,timeoutMs){return new Promise((resolve79)=>{try{let[rawCmd,...args2]=command,cmd=process.platform==="win32"&&WIN32_CMD_BINARIES.has(rawCmd)&&!rawCmd.includes(".")?`${rawCmd}.cmd`:rawCmd,proc=_internals142.spawn(cmd,args2,{cwd,stdio:["ignore","pipe","pipe"]}),stdout="",stderr="",done=!1,MAX_OUTPUT=524288;proc.stdout.on("data",(d)=>{if(stdout.length<MAX_OUTPUT){if(stdout+=d,stdout.length>=MAX_OUTPUT){stdout=stdout.slice(0,MAX_OUTPUT);try{proc.stdout.destroy()}catch{}}}}),proc.stderr.on("data",(d)=>{if(stderr.length<MAX_OUTPUT){if(stderr+=d,stderr.length>=MAX_OUTPUT){stderr=stderr.slice(0,MAX_OUTPUT);try{proc.stderr.destroy()}catch{}}}});let timer=setTimeout(()=>{if(done)return;done=!0;try{proc.stdout.destroy()}catch{}try{proc.stderr.destroy()}catch{}try{proc.kill()}catch{}resolve79(null)},timeoutMs);proc.on("close",(code)=>{if(done)return;done=!0,clearTimeout(timer),resolve79({exitCode:code??1,stdout,stderr})}),proc.on("error",()=>{if(done)return;done=!0,clearTimeout(timer),resolve79(null)})}catch{resolve79(null)}})}var emittedSkipAdvisories=new Set;function detectPackageManager(projectDir){if(fs118.existsSync(path212.join(projectDir,"bun.lockb")))return"bun";if(fs118.existsSync(path212.join(projectDir,"pnpm-lock.yaml")))return"pnpm";if(fs118.existsSync(path212.join(projectDir,"yarn.lock")))return"yarn";if(fs118.existsSync(path212.join(projectDir,"package-lock.json")))return"npm";return"bun"}function detectTypecheckCommand(projectDir){let pkgPath=path212.join(projectDir,"package.json");if(fs118.existsSync(pkgPath))try{let pkg=JSON.parse(fs118.readFileSync(pkgPath,"utf8")),scripts=pkg.scripts;if(scripts?.typecheck)return{command:[detectPackageManager(projectDir),"run","typecheck"],language:"typescript"};if(scripts?.["type-check"])return{command:[detectPackageManager(projectDir),"run","type-check"],language:"typescript"};let deps={...pkg.dependencies,...pkg.devDependencies};if(!deps?.typescript&&!fs118.existsSync(path212.join(projectDir,"tsconfig.json")));if(deps?.typescript||fs118.existsSync(path212.join(projectDir,"tsconfig.json")))return{command:["npx","tsc","--noEmit"],language:"typescript"}}catch{return null}if(fs118.existsSync(path212.join(projectDir,"go.mod")))return{command:["go","vet","./..."],language:"go"};if(fs118.existsSync(path212.join(projectDir,"Cargo.toml")))return{command:["cargo","check"],language:"rust"};if(fs118.existsSync(path212.join(projectDir,"pyproject.toml"))||fs118.existsSync(path212.join(projectDir,"requirements.txt"))||fs118.existsSync(path212.join(projectDir,"setup.py")))return{command:null,language:"python"};try{if(fs118.readdirSync(projectDir).some((f)=>f.endsWith(".csproj")||f.endsWith(".sln")))return{command:["dotnet","build","--no-restore"],language:"csharp"}}catch{}return null}async function runWithTimeout(command,cwd,timeoutMs){let result=await spawnAsync(command,cwd,timeoutMs);if(result===null)return null;return{exitCode:result.exitCode,stderr:result.stderr}}function createIncrementalVerifyHook(config3,projectDir,injectMessage){return{toolAfter:async(input,output)=>{if(!config3.enabled)return;if(input.tool!=="Task")return;let args2=(typeof input.callID==="string"?getStoredInputArgs(input.callID):void 0)??input.args??output.args,subagentType=typeof args2?.subagent_type==="string"?args2.subagent_type:"",agentName=subagentType.replace(/^[^_]+_/,"");if(!config3.triggerAgents.includes(agentName)&&!config3.triggerAgents.includes(subagentType))return;let commandToRun=null;if(config3.command!=null)if(Array.isArray(config3.command))commandToRun=config3.command;else commandToRun=config3.command.split(" ");else{let detected=detectTypecheckCommand(projectDir);if(detected===null)return;if(detected.command===null){let dedupKey=`${input.sessionID}:${detected.language}`;if(!emittedSkipAdvisories.has(dedupKey))emittedSkipAdvisories.add(dedupKey),injectMessage(input.sessionID,`POST-CODER CHECK SKIPPED: ${detected.language} project detected but no default checker available. Set incremental_verify.command in .swarm/config.json to enable.`);return}commandToRun=detected.command}if(commandToRun===null)return;let result=await runWithTimeout(commandToRun,projectDir,config3.timeoutMs);if(result===null)return;if(result.exitCode===0)injectMessage(input.sessionID,"POST-CODER CHECK PASSED: No type errors.");else{let errorSummary=result.stderr.slice(0,800);injectMessage(input.sessionID,`POST-CODER CHECK FAILED: Type errors detected after coder delegation. Address these before proceeding.
6058
6059
  ${errorSummary}`)}}}}init_pending_delegations();init_constants();init_file_locks();init_state2();init_recovery();init_utils();init_core3();init_merge();init_worktree_merge_status();init_worktree_ownership_tag();init_worktree_provisioning_owner();import*as fs119 from"node:fs";import*as fsPromises10 from"node:fs/promises";import*as path213 from"node:path";var INIT_ORPHAN_RECOVERY_TIMEOUT_MS=1e4,OWNERSHIP_TAG_SCAN_TIMEOUT_MS2=2000;async function listOwnershipTagSessionIds(directory){let scan=await scanBackgroundWorktreeOwnershipTagsForRecovery(directory);if(scan.status==="uncertain")return scan;return{status:"ok",sessionIds:[...new Set(scan.owners.map((owner)=>owner.sessionId))]}}var ORPHAN_RECOVERY_LOCK_FILE=WORKTREE_LIFECYCLE_LOCK_FILE,_internals143={rmSync:fs119.rmSync,removeWorktree,isLocked,listActiveLocks,tryAcquireLock,listOwnershipTagSessionIds,scanDelegationsForRecovery,scanDelegationFallbacksForRecovery,scanWorktreeMergeFailuresForRecovery,scanWorktreeProvisioningOwnersForRecovery};async function writeAdvisoryFile(directory,cleanupResult,warnings,attempted,removedWorktrees=[]){let advisoryPath=path213.join(directory,".swarm","advisories","init-orphan-recovery.json"),advisory={initTimestamp:new Date().toISOString(),warnings,errors:cleanupResult.errors,reclaimed:{removedBranches:cleanupResult.removed,removedWorktrees,prunedWorktrees:attempted},...cleanupResult.skippedRecoveryBranches&&cleanupResult.skippedRecoveryBranches.length>0?{preservedRecoveryBranches:cleanupResult.skippedRecoveryBranches}:{},...cleanupResult.recoveryReadError?{recoveryReadError:!0,note:"skipped all lane-branch deletions this pass because .swarm/recovery/ was unreadable (fail-safe)"}:{}};try{await fsPromises10.mkdir(path213.dirname(advisoryPath),{recursive:!0}),await fsPromises10.writeFile(advisoryPath,JSON.stringify(advisory,null,2),"utf-8")}catch{log("initOrphanRecovery advisory file write failed (non-fatal)")}}async function enumerateOrphanedWorktreeDirs(directory,activeSessionIds,protectedWorktreePaths=new Set){let orphanedDirs=[],worktreeRoot=path213.resolve(path213.dirname(directory),SWARM_WORKTREE_DIR_NAME),entries;try{entries=await fsPromises10.readdir(worktreeRoot,{withFileTypes:!0})}catch{return[]}for(let entry of entries){if(!entry.isDirectory())continue;let sessionId=entry.name;if(activeSessionIds.includes(sessionId))continue;let sessionEntries;try{sessionEntries=await fsPromises10.readdir(path213.join(worktreeRoot,sessionId),{withFileTypes:!0})}catch{continue}for(let laneEntry of sessionEntries){if(!laneEntry.isDirectory())continue;let worktreePath=path213.join(worktreeRoot,sessionId,laneEntry.name);if(protectedWorktreePaths.has(path213.resolve(worktreePath)))continue;orphanedDirs.push(worktreePath)}}return orphanedDirs}async function isCrossProcessLockHeld(directory){if(_internals143.isLocked(directory,ORPHAN_RECOVERY_LOCK_FILE))return!0;if(_internals143.listActiveLocks(directory).length>0)return!0;return!1}async function removeOrphanedWorktreeDir(worktreePath,projectRoot){if(!fs119.existsSync(path213.join(worktreePath,".git")))try{_internals143.rmSync(worktreePath,{recursive:!0,force:!0});return}catch(error93){return error93 instanceof Error?error93.message:String(error93)}let removeResult=await _internals143.removeWorktree(worktreePath,projectRoot);if(!("error"in removeResult))return;try{_internals143.rmSync(worktreePath,{recursive:!0,force:!0});return}catch{return removeResult.error}}async function crossProcessAdvisoryResult(directory,warning){let result={attempted:!0,crossProcessLockHeld:!0,warnings:[warning],orphanedBranches:[],removedWorktrees:[],prunedWorktrees:!1};return await writeAdvisoryFile(directory,{removed:[],skipped:[],errors:[]},result.warnings,!1,[]),result}function worktreePathKey(worktreePath,directory){let absolutePath2=path213.isAbsolute(worktreePath)?worktreePath:path213.resolve(directory,worktreePath),normalized=path213.normalize(absolutePath2);return process.platform==="win32"?normalized.toLowerCase():normalized}async function runInitOrphanRecovery(directory){let result,recoveryLockRelease;try{if(await isCrossProcessLockHeld(directory))return crossProcessAdvisoryResult(directory,"Cross-process lock held — another opencode process may be active. "+"Skipping destructive cleanup to preserve its worktrees/branches. Run '/swarm status' or check '.swarm/locks/' to identify active processes.");let lockAcquireResult=await _internals143.tryAcquireLock(directory,ORPHAN_RECOVERY_LOCK_FILE,"init-orphan-recovery","init");if(!lockAcquireResult.acquired)return crossProcessAdvisoryResult(directory,"Cross-process lifecycle lock was acquired by another process during init; skipping destructive cleanup to preserve its worktrees/branches.");recoveryLockRelease=lockAcquireResult.lock._release;let activeSessionIds=Array.from(swarmState.agentSessions.keys()),provisioningOwnerScan=await withTimeout(Promise.resolve(_internals143.scanWorktreeProvisioningOwnersForRecovery(directory)),INIT_ORPHAN_RECOVERY_TIMEOUT_MS,Error("worktree provisioning ownership scan exceeded its bounded init budget"));if(provisioningOwnerScan.status==="uncertain")throw Error(`worktree provisioning ownership state is uncertain; destructive orphan cleanup skipped: ${provisioningOwnerScan.reason}`);for(let owner of provisioningOwnerScan.owners){if(!activeSessionIds.includes(owner.worktreeSessionId))activeSessionIds.push(owner.worktreeSessionId);if(!activeSessionIds.includes(owner.parentSessionId))activeSessionIds.push(owner.parentSessionId)}let ownershipTagScan=await withTimeout(_internals143.listOwnershipTagSessionIds(directory),OWNERSHIP_TAG_SCAN_TIMEOUT_MS2,Error("background ownership tag scan exceeded its bounded init budget"));if(ownershipTagScan.status==="uncertain")throw Error(`background ownership tag state is uncertain; destructive orphan cleanup skipped: ${ownershipTagScan.reason}`);for(let sessionId of ownershipTagScan.sessionIds)if(!activeSessionIds.includes(sessionId))activeSessionIds.push(sessionId);let fallbackOwnerScan=await withTimeout(_internals143.scanDelegationFallbacksForRecovery(directory),INIT_ORPHAN_RECOVERY_TIMEOUT_MS,Error("background delegation fallback ownership scan exceeded its bounded init budget"));if(fallbackOwnerScan.status==="uncertain")throw Error(`background fallback ownership state is uncertain; destructive orphan cleanup skipped: ${fallbackOwnerScan.reason}`);let primaryOwnerScan=await withTimeout(Promise.resolve(_internals143.scanDelegationsForRecovery(directory)),INIT_ORPHAN_RECOVERY_TIMEOUT_MS,Error("background primary ownership scan exceeded its bounded init budget"));if(primaryOwnerScan.status==="uncertain")throw Error(`background primary ownership state is uncertain; destructive orphan cleanup skipped: ${primaryOwnerScan.reason}`);let isUnsettledWorktreeOwner=(record3)=>Boolean(record3.worktree)&&!(record3.coderSettlement?.state==="settled"&&record3.coderSettlement.outcome?.kind==="standard-worktree"&&(record3.coderSettlement.outcome.result==="merged"||record3.coderSettlement.outcome.result==="unchanged")),durableWorktreeOwners=primaryOwnerScan.owners.filter(isUnsettledWorktreeOwner),mergeOwnerScan=await withTimeout(Promise.resolve(_internals143.scanWorktreeMergeFailuresForRecovery(directory)),INIT_ORPHAN_RECOVERY_TIMEOUT_MS,Error("worktree merge ownership scan exceeded its bounded init budget"));if(mergeOwnerScan.status==="uncertain")throw Error(`worktree merge ownership state is uncertain; destructive orphan cleanup skipped: ${mergeOwnerScan.reason}`);let allDurableOwners=[...durableWorktreeOwners,...fallbackOwnerScan.owners.map((artifact)=>artifact.record).filter(isUnsettledWorktreeOwner)],preservedMergeFailures=mergeOwnerScan.failures.map(([,failure])=>failure).filter((failure)=>typeof failure.worktreePath==="string"),protectedWorktreePaths=new Set([...allDurableOwners.map((record3)=>record3.worktree?.worktreePath),...preservedMergeFailures.map((failure)=>failure.worktreePath)].filter((value)=>typeof value==="string").map((value)=>path213.resolve(value)));for(let owner of allDurableOwners){let worktreeSessionId=owner.worktree?.worktreeSessionId;if(worktreeSessionId&&!activeSessionIds.includes(worktreeSessionId))activeSessionIds.push(worktreeSessionId);if(!activeSessionIds.includes(owner.parentSessionId))activeSessionIds.push(owner.parentSessionId)}for(let failure of preservedMergeFailures){let segments=failure.branch?.split("/")??[],worktreeSessionId=segments[0]==="swarm"&&segments.length>=4?segments[2]:segments[0]==="swarm-lane"&&segments.length>=3?segments[1]:void 0;if(worktreeSessionId&&!activeSessionIds.includes(worktreeSessionId))activeSessionIds.push(worktreeSessionId)}let orphanedWorktreeDirs=await withTimeout(enumerateOrphanedWorktreeDirs(directory,activeSessionIds,protectedWorktreePaths),INIT_ORPHAN_RECOVERY_TIMEOUT_MS,Error(`runInitOrphanRecovery exceeded ${INIT_ORPHAN_RECOVERY_TIMEOUT_MS}ms budget during worktree enumeration; continuing without orphan reclamation`)),removedWorktrees=[],worktreeWarnings=[],recoveryRecords=listRecoveryRecords(directory),recoveryReadError=recoveryReadErrored(directory),recoveryWorktreePaths=new Set(recoveryRecords.map((record3)=>worktreePathKey(record3.worktreePath,directory)));if(recoveryReadError)worktreeWarnings.push("Recovery records are unreadable or fail schema validation; skipped all orphaned worktree deletion this pass (fail-safe).");else for(let worktreePath of orphanedWorktreeDirs){if(recoveryWorktreePaths.has(worktreePathKey(worktreePath,directory))){worktreeWarnings.push(`Preserved recovery worktree "${worktreePath}"; an unresolved recovery record still references it.`);continue}let error93=await removeOrphanedWorktreeDir(worktreePath,directory);if(error93)worktreeWarnings.push(`Could not reclaim orphaned worktree "${worktreePath}": ${error93}`);else removedWorktrees.push(worktreePath)}let cleanupResult=await withTimeout(cleanupOrphanedBranches(directory,activeSessionIds),INIT_ORPHAN_RECOVERY_TIMEOUT_MS,Error(`runInitOrphanRecovery exceeded ${INIT_ORPHAN_RECOVERY_TIMEOUT_MS}ms budget during branch cleanup; continuing without orphan reclamation`)),branchWarnings=cleanupResult.errors.map((e)=>`Could not delete orphaned branch "${e.branch}": ${e.error}`),allWarnings=[...worktreeWarnings,...branchWarnings];result={attempted:!0,crossProcessLockHeld:!1,warnings:allWarnings,orphanedBranches:cleanupResult.removed,removedWorktrees,prunedWorktrees:cleanupResult.recoveryReadError!==!0},await writeAdvisoryFile(directory,cleanupResult,allWarnings,!0,removedWorktrees)}catch(err){let msg=err instanceof Error?err.message:String(err);log("initOrphanRecovery timed out or failed (non-fatal)",{error:msg}),result={attempted:!1,crossProcessLockHeld:!1,warnings:[`Orphan recovery timed out or failed: ${msg}`],orphanedBranches:[],removedWorktrees:[],prunedWorktrees:!1,diagnostic:{file:".swarm/advisories/init-orphan-recovery.json",reason:msg}},await writeAdvisoryFile(directory,{removed:[],skipped:[],skippedRecoveryBranches:[],errors:[]},result.warnings,!1,[])}finally{try{await recoveryLockRelease?.()}catch{}}return result}init_state2();import*as fs120 from"node:fs/promises";import*as path214 from"node:path";var ADVISORY_FILENAME="init-orphan-recovery.json";function createInitOrphanRecoveryAdvisoryHook(directory){let consumedBySession=new Set;async function readAdvisoryFile(){let advisoryPath=path214.join(directory,".swarm","advisories",ADVISORY_FILENAME);try{let content=await fs120.readFile(advisoryPath,"utf-8");return JSON.parse(content)}catch{return null}}async function deleteAdvisoryFile(){let advisoryPath=path214.join(directory,".swarm","advisories",ADVISORY_FILENAME);try{await fs120.unlink(advisoryPath)}catch{}}function formatError3(error93){return`ORPHAN_RECOVERY_ERROR: Could not reclaim branch "${error93.branch}": ${error93.error}`}async function messagesTransform(_input,output){let messages=output.messages;if(!messages||messages.length===0)return;let sessionId=messages[messages.length-1]?.info?.sessionID;if(!sessionId)return;let activeAgent=swarmState.activeAgent.get(sessionId),session=swarmState.agentSessions.get(sessionId),ORCHESTRATOR_NAME2="Architect";if(!(activeAgent?activeAgent===ORCHESTRATOR_NAME2||activeAgent.endsWith("_Architect"):session?session.agentName===ORCHESTRATOR_NAME2||session.agentName.endsWith("_Architect"):!1))return;if(consumedBySession.has(sessionId))return;let advisory=await readAdvisoryFile();if(!advisory)return;consumedBySession.add(sessionId),await deleteAdvisoryFile();let reclaimedForGate=advisory.reclaimed;if(!((advisory.warnings?.length??0)>0||(advisory.errors?.length??0)>0||(reclaimedForGate?.removedBranches?.length??0)>0||(reclaimedForGate?.removedWorktrees?.length??0)>0))return;let targetSession=ensureAgentSession(sessionId),timestamp=advisory.initTimestamp?new Date(advisory.initTimestamp).toLocaleString():"unknown";pushAdvisory(targetSession,`[INIT ORPHAN RECOVERY] Plugin init detected the following at ${timestamp}:`);for(let warning of advisory.warnings??[])pushAdvisory(targetSession,` WARNING: ${warning}`);for(let err of advisory.errors??[])pushAdvisory(targetSession,` ERROR: ${formatError3(err)}`);let reclaimed=advisory.reclaimed;if((reclaimed?.removedBranches?.length??0)>0)pushAdvisory(targetSession,` Reclaimed ${reclaimed.removedBranches.length} orphaned branch(es): ${reclaimed.removedBranches.join(", ")}`);if(reclaimed?.removedWorktrees&&reclaimed.removedWorktrees.length>0)pushAdvisory(targetSession,` Reclaimed ${reclaimed.removedWorktrees.length} orphaned worktree directory(ies): ${reclaimed.removedWorktrees.join(", ")}`);if(reclaimed?.prunedWorktrees)pushAdvisory(targetSession," Stale worktree metadata pruned.")}return{messagesTransform}}init_delegation_gate();import*as fs121 from"node:fs";import*as path216 from"node:path";function computeNextMode(params){let{issueReference,traceState,workflowArtifacts}=params,noop={nextMode:null,directive:null,nextLastTransition:traceState.lastTransition,nextCompleted:traceState.completed};if(!issueReference||issueReference.flags.trace!==!0)return noop;if(traceState.completed)return noop;if(workflowArtifacts.specIssueNumber===null||workflowArtifacts.specIssueNumber!==issueReference.number||traceState.issueNumber!==issueReference.number)return noop;if(!workflowArtifacts.specExists)return noop;if(!workflowArtifacts.planExists&&(traceState.lastTransition===null||traceState.lastTransition==="ISSUE_INGEST_TO_PLAN")){if(traceState.lastTransition==="ISSUE_INGEST_TO_PLAN")return noop;return{nextMode:"PLAN",directive:null,nextLastTransition:"ISSUE_INGEST_TO_PLAN",nextCompleted:!1}}if(!workflowArtifacts.criticApproved)return noop;if(workflowArtifacts.planExists&&!workflowArtifacts.allPhasesComplete){if(traceState.lastTransition==="PLAN_TO_EXECUTE")return noop;return{nextMode:"EXECUTE",directive:null,nextLastTransition:"PLAN_TO_EXECUTE",nextCompleted:!1}}if(!workflowArtifacts.planExists)return noop;if(traceState.lastTransition==="EXECUTE_TO_COMMIT")return noop;return{nextMode:null,directive:"All phases complete. Compose commit-pr to publish the PR. Read .swarm/issue-reference.json for Closes #N.",nextLastTransition:"EXECUTE_TO_COMMIT",nextCompleted:!0}}init_manager();import{existsSync as existsSync105,mkdirSync as mkdirSync54,readFileSync as readFileSync80,renameSync as renameSync34,unlinkSync as unlinkSync35,writeFileSync as writeFileSync36}from"node:fs";import*as path215 from"node:path";async function _defaultLoadPlanFromLedger(directory){return loadPlanJsonOnly(directory)}var _internals144={readFileSync:readFileSync80,writeFileSync:writeFileSync36,existsSync:existsSync105,renameSync:renameSync34,mkdirSync:mkdirSync54,unlinkSync:unlinkSync35,loadPlanFromLedger:_defaultLoadPlanFromLedger};function isPhaseComplete(status){return status==="complete"||status==="completed"}function isValidIssueReference(obj){if(typeof obj!=="object"||obj===null)return!1;let o=obj;if(typeof o.url!=="string"||!o.url.startsWith("https://github.com/"))return!1;return typeof o.owner==="string"&&typeof o.repo==="string"&&typeof o.number==="number"&&typeof o.timestamp==="string"&&typeof o.flags==="object"&&o.flags!==null}function isValidTraceState(obj){if(typeof obj!=="object"||obj===null)return!1;let o=obj;return typeof o.issueNumber==="number"&&(o.lastTransition===null||typeof o.lastTransition==="string")&&typeof o.completed==="boolean"}function readIssueReference(directory){try{let filePath=path215.join(directory,".swarm","issue-reference.json"),raw=_internals144.readFileSync(filePath,"utf-8"),parsed=JSON.parse(raw);if(!isValidIssueReference(parsed))return null;return parsed}catch{return null}}function readTraceState(directory){let defaultState={issueNumber:0,lastTransition:null,completed:!1};try{let filePath=path215.join(directory,".swarm","issue-trace-state.json"),raw=_internals144.readFileSync(filePath,"utf-8"),parsed=JSON.parse(raw);if(!isValidTraceState(parsed))return defaultState;return parsed}catch{return defaultState}}function writeTraceState(directory,state){let swarmDir=path215.join(directory,".swarm");_internals144.mkdirSync(swarmDir,{recursive:!0});let finalPath=path215.join(swarmDir,"issue-trace-state.json"),tmpPath=path215.join(swarmDir,`issue-trace-state.tmp.${process.pid}.${Date.now()}.json`);_internals144.writeFileSync(tmpPath,JSON.stringify(state,null,2),"utf-8");try{_internals144.renameSync(tmpPath,finalPath)}catch{try{_internals144.unlinkSync(finalPath)}catch{}try{_internals144.renameSync(tmpPath,finalPath)}catch(retryErr){try{_internals144.unlinkSync(tmpPath)}catch{}throw retryErr}}}function readSpecIssueNumber(directory){try{let filePath=path215.join(directory,".swarm","spec.md"),raw=_internals144.readFileSync(filePath,"utf-8"),sectionStart=raw.indexOf("## Source Issue");if(sectionStart===-1)return null;let nextHeading=raw.indexOf(`
6059
6060
  ## `,sectionStart+14),sectionEnd=nextHeading===-1?raw.length:nextHeading,section=raw.slice(sectionStart,sectionEnd),numberMatch=section.match(/-\s+Number:\s*(\d+)/);if(numberMatch)return parseInt(numberMatch[1],10);let urlMatch=section.match(/-\s+URL:.*\/issues\/(\d+)/);if(urlMatch)return parseInt(urlMatch[1],10);return null}catch{return null}}async function readPlanPhaseStatus(directory){let plan=await _internals144.loadPlanFromLedger(directory);if(!plan||plan.phases.length===0)return{allComplete:!1};return{allComplete:plan.phases.every((phase)=>isPhaseComplete(phase.status))}}function specExists(directory){return _internals144.existsSync(path215.join(directory,".swarm","spec.md"))}function planExists(directory){return _internals144.existsSync(path215.join(directory,".swarm","plan.json"))}var _internals145={readIssueReference,readTraceState,writeTraceState,readSpecIssueNumber,readPlanPhaseStatus,specExists,planExists,isPlanCriticApproved},cachedApproval=null;async function boundedApprovalCheck(directory,timeoutMs){try{let ledgerPath=path216.join(directory,".swarm","plan-ledger.jsonl"),currentSize=-1;try{currentSize=fs121.statSync(ledgerPath).size}catch{let timeout=new Promise((resolve80)=>{setTimeout(()=>resolve80(!1),timeoutMs)});return await Promise.race([_internals145.isPlanCriticApproved(directory),timeout])}if(cachedApproval&&cachedApproval.dir===directory&&cachedApproval.size===currentSize)return cachedApproval.result;let timer;try{let timeout=new Promise((resolve80)=>{timer=setTimeout(()=>resolve80(!1),timeoutMs)}),result=await Promise.race([_internals145.isPlanCriticApproved(directory),timeout]);return cachedApproval={dir:directory,size:currentSize,result},result}finally{if(timer!==void 0)clearTimeout(timer)}}catch{return!1}}function createIssueTraceHook(_config,directory,approvalTimeoutMs=5000){return{messagesTransform:async(_input,output)=>{try{let issueRef=_internals145.readIssueReference(directory);if(!issueRef||issueRef.flags.trace!==!0)return;let traceState=_internals145.readTraceState(directory),_specExists=_internals145.specExists(directory),_specIssueNumber=_internals145.readSpecIssueNumber(directory),_planExists=_internals145.planExists(directory),_criticApproved=await boundedApprovalCheck(directory,approvalTimeoutMs),_allPhasesComplete=(await _internals145.readPlanPhaseStatus(directory)).allComplete,result=computeNextMode({issueReference:issueRef,traceState,workflowArtifacts:{specExists:_specExists,specIssueNumber:_specIssueNumber,planExists:_planExists,criticApproved:_criticApproved,allPhasesComplete:_allPhasesComplete}});if(result.nextMode===null&&result.directive===null)return;let finalDirective=result.directive?result.directive.replace("#N",`#${issueRef.number}`):null,messagesToAdd=[];if(result.nextMode!==null)messagesToAdd.push({role:"system",content:[{type:"text",text:`[MODE: ${result.nextMode}]`}]});if(finalDirective!==null)messagesToAdd.push({role:"system",content:[{type:"text",text:finalDirective}]});_internals145.writeTraceState(directory,{issueNumber:traceState.issueNumber,lastTransition:result.nextLastTransition,completed:result.nextCompleted});let out=output;if(out.messages)out.messages.push(...messagesToAdd)}catch{}}}}init_schema();init_state2();init_logger();import{appendFile as appendFile22,mkdir as mkdir45}from"node:fs/promises";import*as path217 from"node:path";var HIGH_RISK_TOOLS=new Set(["save_plan","update_task_status","phase_complete","task","Task","skill_regenerate","skill_retire"]),DEFAULT_MAX_GATE_DENIALS=5,DEFAULT_GATE_STALENESS_MS=600000;async function knowledgeApplicationGateBefore(directory,input,config3){if(!config3.enabled)return;let toolName=typeof input.tool==="string"?input.tool:"";if(!(config3.high_risk_tools?new Set(config3.high_risk_tools):HIGH_RISK_TOOLS).has(toolName))return;let agentRaw=typeof input.agent==="string"?input.agent:"";if(!agentRaw)return;if(stripKnownSwarmPrefix(agentRaw)!=="architect")return;let sessionID=typeof input.sessionID==="string"?input.sessionID:void 0;if(!sessionID){if(config3.mode==="enforce")throw Error("KNOWLEDGE_ENFORCE_GATE_DENY: missing sessionID on tool.execute.before; refusing to evaluate critical-directive ack state");_internals146.writeWarnEvent(directory,{timestamp:new Date().toISOString(),event:"knowledge_application_gate_warn",tool:toolName,agent:agentRaw,reason:"missing_sessionID",mode:config3.mode}).catch(()=>{});return}let cached3=swarmState.currentCriticalShownIds.get(sessionID);if(!cached3||cached3.ids.length===0){clearGateDenialCount(sessionID);return}let ackedIds=new Set;for(let id of cached3.ids)for(let result of["applied","ignored","violated"]){let key=buildAckDedupKey(sessionID,id,result);if(swarmState.knowledgeAckDedup.has(key)){ackedIds.add(id);break}}let unacked=cached3.ids.filter((id)=>!ackedIds.has(id));if(unacked.length===0){clearGateDenialCount(sessionID);return}if(config3.mode==="enforce"&&config3.critical_requires_ack){let maxDenials=config3.max_gate_denials??DEFAULT_MAX_GATE_DENIALS,stalenessMs=config3.gate_staleness_ms??DEFAULT_GATE_STALENESS_MS,age=Date.now()-cached3.generatedAt;if(age>stalenessMs){for(let id of unacked)addKnowledgeAckDedup(buildAckDedupKey(sessionID,id,"applied"));clearCriticalShownIds(sessionID),clearGateDenialCount(sessionID),await writeWarnEvent2(directory,{timestamp:new Date().toISOString(),event:"knowledge_application_gate_staleness_clear",tool:toolName,agent:agentRaw,sessionID,cleared_ids:unacked,age_ms:age,staleness_threshold_ms:stalenessMs}).catch((err)=>{warn(`[knowledge-application-gate] staleness-clear audit write failed: ${err instanceof Error?err.message:String(err)}`)});return}let directiveKey=buildGateDenialDirectiveKey(cached3.ids),denials=incrementGateDenialCount(sessionID,directiveKey);if(denials>maxDenials){for(let id of unacked)addKnowledgeAckDedup(buildAckDedupKey(sessionID,id,"applied"));clearCriticalShownIds(sessionID),clearGateDenialCount(sessionID),await writeWarnEvent2(directory,{timestamp:new Date().toISOString(),event:"knowledge_application_gate_denial_limit_clear",tool:toolName,agent:agentRaw,sessionID,cleared_ids:unacked,denial_count:denials,max_gate_denials:maxDenials}).catch((err)=>{warn(`[knowledge-application-gate] denial-limit-clear audit write failed: ${err instanceof Error?err.message:String(err)}`)});return}let ids=unacked.join(", ");throw Error(`KNOWLEDGE_ENFORCE_GATE_DENY: ${toolName} blocked — critical knowledge directive(s) ${ids} require KNOWLEDGE_APPLIED:<id>, KNOWLEDGE_IGNORED:<id> reason=..., or KNOWLEDGE_VIOLATED:<id> reason=... before this action.`)}writeWarnEvent2(directory,{timestamp:new Date().toISOString(),event:"knowledge_application_gate_warn",tool:toolName,agent:agentRaw,sessionID,unacknowledged_critical_ids:unacked}).catch(()=>{})}async function writeWarnEvent2(directory,record3){let filePath=path217.join(directory,".swarm","events.jsonl");await mkdir45(path217.dirname(filePath),{recursive:!0}),await appendFile22(filePath,`${JSON.stringify(record3)}
6060
6061
  `,"utf-8")}async function knowledgeApplicationTransformScan(directory,output,sessionID){if(!output?.messages)return;if(!sessionID)return;let target;for(let i=output.messages.length-1;i>=0;i--){let m=output.messages[i],agent=m.info?.agent;if(typeof agent==="string"&&stripKnownSwarmPrefix(agent)==="architect"){target=m;break}}if(!target)return;let text=(target.parts??[]).map((p)=>typeof p.text==="string"?p.text:"").join(`
6061
- `);if(!text)return;let acks=parseAcknowledgments(text);if(acks.length===0)return;let ctx={sessionId:sessionID};for(let ack of acks){let key=buildAckDedupKey(sessionID,ack.id,ack.result);if(swarmState.knowledgeAckDedup.has(key))continue;addKnowledgeAckDedup(key);try{await recordAcknowledgment(directory,ack,ctx)}catch(err){warn(`[knowledge-application-gate] transform-scan record failed: ${err instanceof Error?err.message:String(err)}`)}}}var _internals146={knowledgeApplicationGateBefore,knowledgeApplicationTransformScan,HIGH_RISK_TOOLS,writeWarnEvent:writeWarnEvent2};init_knowledge_curator();init_micro_reflector();init_normalize_tool_name();init_pr_subscriptions();init_utils();init_stored_input_args();init_normalize_tool_name();var MAX_OUTPUT_SCAN_BYTES=65536,PR_URL_PATTERN=/https:\/\/github\.com\/([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)\/pull\/(\d+)/,_internals147={subscribe,log};function extractPrUrl(text){let match=PR_URL_PATTERN.exec(text.slice(0,MAX_OUTPUT_SCAN_BYTES));if(!match)return null;let owner=match[1],repo=match[2],prNumber=Number.parseInt(match[3],10);if(!Number.isSafeInteger(prNumber)||prNumber<=0)return null;return{repoFullName:`${owner}/${repo}`,prNumber,prUrl:`https://github.com/${owner}/${repo}/pull/${prNumber}`}}function createPrAutoSubscribeHook(directory,config3){return{toolAfter:async(input,output)=>{try{if(!config3.enabled||!config3.auto_subscribe_on_pr_create)return;let sessionID=typeof input.sessionID==="string"?input.sessionID.trim():"";if(!sessionID)return;let tool3=normalizeToolNameLowerCase(input.tool??"");if(tool3!=="bash"&&tool3!=="shell")return;let args2=(typeof input.callID==="string"?getStoredInputArgs(input.callID):void 0)??input.args??output.args;if(!(typeof args2?.command==="string"?args2.command:"").includes("gh pr create"))return;let outputText2=typeof output.output==="string"?output.output:"";if(!outputText2)return;let prInfo=extractPrUrl(outputText2);if(!prInfo)return;await _internals147.subscribe(directory,{sessionID,prNumber:prInfo.prNumber,repoFullName:prInfo.repoFullName,prUrl:prInfo.prUrl,maxSubscriptions:config3.max_subscriptions}),_internals147.log("[pr-monitor] Auto-subscribed session to created PR",{sessionID,pr:`${prInfo.repoFullName}#${prInfo.prNumber}`})}catch(err){_internals147.log("[pr-monitor] Auto-subscribe failed (non-fatal)",{error:err instanceof Error?err.message:String(err)})}}}}init_pr_workflow_gate();init_pr_feedback_event_queue();init_pr_workflow_auto_wake();init_pr_workflow_gate();var DEFAULT_WAKE_TIMEOUT_MS=5000,_internals148={readPrWorkflowGateState,claimPrFeedbackMonitorEvents,readPrFeedbackMonitorQueue},DEFAULT_MAX_CONSECUTIVE_UNPRODUCTIVE_WAKES=5,DEFAULT_WAKE_COOLDOWN_MS=30000,DEFAULT_BANNER_COOLDOWN_MS=20000,MAX_FALLBACK_BANNER_INJECTIONS_PER_SESSION=20,BANNER_PREFIX_PATTERN=/^--- \[(?:PR_REVIEW|PR_FEEDBACK) WORKFLOW ACTIVE/,MAX_TRACKED_WAKE_SESSIONS=200;function canonicalGitHubPrUrl5(value){try{let url3=new URL(value),match=url3.pathname.match(/^\/([^/]+)\/([^/]+)\/pull\/(\d+)\/?$/);if(url3.protocol!=="https:"||url3.hostname.toLowerCase()!=="github.com"||!match)return null;let number7=Number(match[3]);if(!Number.isSafeInteger(number7)||number7<=0)return null;return`github.com/${match[1].toLowerCase()}/${match[2].toLowerCase()}/pull/${number7}`}catch{return null}}function sameGitHubPr3(left,right){let leftCanonical=canonicalGitHubPrUrl5(left);return leftCanonical!==null&&leftCanonical===canonicalGitHubPrUrl5(right)}function formatQueuedMonitorEventsText(events){if(events.length===0)return"";return["Queued PR monitor events are now authorized for this PR_FEEDBACK workflow and must be treated as feedback inputs for the current round:",...events.map((event)=>`- ${event.type} on ${event.repoFullName}#${event.prNumber}: ${event.message.split(`
6062
+ `);if(!text)return;let acks=parseAcknowledgments(text);if(acks.length===0)return;let ctx={sessionId:sessionID};for(let ack of acks){let key=buildAckDedupKey(sessionID,ack.id,ack.result);if(swarmState.knowledgeAckDedup.has(key))continue;addKnowledgeAckDedup(key);try{await recordAcknowledgment(directory,ack,ctx)}catch(err){warn(`[knowledge-application-gate] transform-scan record failed: ${err instanceof Error?err.message:String(err)}`)}}}var _internals146={knowledgeApplicationGateBefore,knowledgeApplicationTransformScan,HIGH_RISK_TOOLS,writeWarnEvent:writeWarnEvent2};init_knowledge_curator();init_micro_reflector();init_normalize_tool_name();init_pr_subscriptions();init_utils();init_stored_input_args();init_normalize_tool_name();var MAX_OUTPUT_SCAN_BYTES=65536,PR_URL_PATTERN=/https:\/\/github\.com\/([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)\/pull\/(\d+)/,_internals147={subscribe,log};function extractPrUrl(text){let match=PR_URL_PATTERN.exec(text.slice(0,MAX_OUTPUT_SCAN_BYTES));if(!match)return null;let owner=match[1],repo=match[2],prNumber=Number.parseInt(match[3],10);if(!Number.isSafeInteger(prNumber)||prNumber<=0)return null;return{repoFullName:`${owner}/${repo}`,prNumber,prUrl:`https://github.com/${owner}/${repo}/pull/${prNumber}`}}function createPrAutoSubscribeHook(directory,config3){return{toolAfter:async(input,output)=>{try{if(!config3.enabled||!config3.auto_subscribe_on_pr_create)return;let sessionID=typeof input.sessionID==="string"?input.sessionID.trim():"";if(!sessionID)return;let tool3=normalizeToolNameLowerCase(input.tool??"");if(tool3!=="bash"&&tool3!=="shell")return;let args2=(typeof input.callID==="string"?getStoredInputArgs(input.callID):void 0)??input.args??output.args;if(!(typeof args2?.command==="string"?args2.command:"").includes("gh pr create"))return;let outputText2=typeof output.output==="string"?output.output:"";if(!outputText2)return;let prInfo=extractPrUrl(outputText2);if(!prInfo)return;await _internals147.subscribe(directory,{sessionID,prNumber:prInfo.prNumber,repoFullName:prInfo.repoFullName,prUrl:prInfo.prUrl,maxSubscriptions:config3.max_subscriptions}),_internals147.log("[pr-monitor] Auto-subscribed session to created PR",{sessionID,pr:`${prInfo.repoFullName}#${prInfo.prNumber}`})}catch(err){_internals147.log("[pr-monitor] Auto-subscribe failed (non-fatal)",{error:err instanceof Error?err.message:String(err)})}}}}init_pr_workflow_gate();init_pr_feedback_event_queue();init_pr_workflow_auto_wake();init_pr_workflow_gate();var DEFAULT_WAKE_TIMEOUT_MS=5000,_internals148={readPrWorkflowGateState,claimPrFeedbackMonitorEvents,readPrFeedbackMonitorQueue},DEFAULT_MAX_CONSECUTIVE_UNPRODUCTIVE_WAKES=5,DEFAULT_WAKE_COOLDOWN_MS=30000,DEFAULT_BANNER_COOLDOWN_MS=20000,MAX_FALLBACK_BANNER_INJECTIONS_PER_SESSION=20,BANNER_PREFIX_PATTERN=/^--- \[(?:PR_REVIEW|PR_FEEDBACK) WORKFLOW ACTIVE/,DEFAULT_TOTAL_WAKE_CEILINGS={S:12,M:54,L:102},MAX_TRACKED_WAKE_SESSIONS=200;function canonicalGitHubPrUrl5(value){try{let url3=new URL(value),match=url3.pathname.match(/^\/([^/]+)\/([^/]+)\/pull\/(\d+)\/?$/);if(url3.protocol!=="https:"||url3.hostname.toLowerCase()!=="github.com"||!match)return null;let number7=Number(match[3]);if(!Number.isSafeInteger(number7)||number7<=0)return null;return`github.com/${match[1].toLowerCase()}/${match[2].toLowerCase()}/pull/${number7}`}catch{return null}}function sameGitHubPr3(left,right){let leftCanonical=canonicalGitHubPrUrl5(left);return leftCanonical!==null&&leftCanonical===canonicalGitHubPrUrl5(right)}function formatQueuedMonitorEventsText(events){if(events.length===0)return"";return["Queued PR monitor events are now authorized for this PR_FEEDBACK workflow and must be treated as feedback inputs for the current round:",...events.map((event)=>`- ${event.type} on ${event.repoFullName}#${event.prNumber}: ${event.message.split(`
6062
6063
  `)[0]}`),"Do not expand or replace an already-declared immutable feedback inventory; if these events require a later round, finish or abort the current round first."].join(`
6063
- `)}function blockedText(mode,options={}){let lines=[`[${mode} WORKFLOW ACTIVE]`,`The ${mode} workflow gate is still active. Continue with the required structured lanes, evidence, and controller tools until \`complete_pr_workflow\` succeeds.`,`If the bind/checkout path is unreachable — for example a compound \`git fetch && git checkout\` was rejected as read-only shell syntax, the PR head cannot be fetched, or the working tree is on the wrong branch — call \`abort_pr_workflow\` (mode: "${mode}", reason: "<one-line cause>") to clear the gate, or ask the user to run \`/swarm abort-pr-workflow\`.`];if(options.suspended){let max=options.maxConsecutive;lines.push(`Auto-resume is suspended after ${max??"the configured number of"} consecutive unproductive retries (the durable gate \`revision\` did not advance). The session will not be re-awoken automatically. Run \`/swarm abort-pr-workflow\` or call \`abort_pr_workflow\` to clear the gate, or complete the workflow with \`complete_pr_workflow\` to publish normally.`)}if(options.userInterrupted)lines.push("Auto-resume is paused after a user interruption. The durable workflow gate is preserved, but the plugin will not re-awaken this session. Send a new message to continue, or run `/swarm abort-pr-workflow` to clear the workflow.");if(options.recovery)lines.push(`Auto-resume is disabled because manual Git recovery is required. code=${options.recovery.code} retryable=false required_action=${options.recovery.requiredAction}`);return lines.join(`
6064
- `)}function workflowBanner(mode,options={}){let lines=[`--- [${mode} WORKFLOW ACTIVE — output below is not a terminal verdict; \`complete_pr_workflow\` clears the gate on success; if the bind/checkout path is unreachable call \`abort_pr_workflow\` or run \`/swarm abort-pr-workflow\`] ---`];if(options.suspended){let max=options.maxConsecutive;lines.push(`[Auto-resume is suspended after ${max??"the configured number of"} consecutive unproductive retries. Run \`/swarm abort-pr-workflow\` or call \`abort_pr_workflow\` to clear the gate, or complete the workflow with \`complete_pr_workflow\`.]`)}if(options.userInterrupted)lines.push("[Auto-resume paused after a user interruption. Send a new message to continue, or run `/swarm abort-pr-workflow` to clear the workflow.]");if(options.recovery)lines.push(`[Manual Git recovery required; auto-resume disabled. code=${options.recovery.code} retryable=false required_action=${options.recovery.requiredAction}]`);return lines.join(" ")}function createPrWorkflowResponseGate(options){let wakeTimeoutMs=options.wakeTimeoutMs??DEFAULT_WAKE_TIMEOUT_MS,maxConsecutive=options.maxConsecutiveUnproductiveWakes??DEFAULT_MAX_CONSECUTIVE_UNPRODUCTIVE_WAKES,wakeCooldownMs=options.wakeCooldownMs??DEFAULT_WAKE_COOLDOWN_MS,bannerCooldownMs=options.bannerCooldownMs??DEFAULT_BANNER_COOLDOWN_MS,activeWakeSessions=new Set,wakeBudgets=new Map,bannerStamps=new Map,banneredMessages=new Map,fallbackInjections=new Map,session=options.client?.session;function evictIfOverBound(){while(wakeBudgets.size>MAX_TRACKED_WAKE_SESSIONS){let oldestKey=wakeBudgets.keys().next().value;if(oldestKey===void 0)break;wakeBudgets.delete(oldestKey)}}function evictBannerDedupeMapsIfOverBound(){while(bannerStamps.size>MAX_TRACKED_WAKE_SESSIONS){let oldestKey=bannerStamps.keys().next().value;if(oldestKey===void 0)break;bannerStamps.delete(oldestKey)}while(banneredMessages.size>MAX_TRACKED_WAKE_SESSIONS){let oldestKey=banneredMessages.keys().next().value;if(oldestKey===void 0)break;banneredMessages.delete(oldestKey)}while(fallbackInjections.size>MAX_TRACKED_WAKE_SESSIONS){let oldestKey=fallbackInjections.keys().next().value;if(oldestKey===void 0)break;fallbackInjections.delete(oldestKey)}}function resetBudget(sessionID){wakeBudgets.delete(sessionID),bannerStamps.delete(sessionID),banneredMessages.delete(sessionID),fallbackInjections.delete(sessionID)}return{event:async(input)=>{let wakeDecision=await observePrWorkflowAutoWakeEvent(options.directory,input.event),event2=input.event,sessionID=event2?.properties?.sessionID??event2?.data?.sessionID;if(event2?.type!=="session.idle"||typeof sessionID!=="string"||!sessionID.trim()||wakeDecision.suppressWake||activeWakeSessions.has(sessionID))return;activeWakeSessions.add(sessionID);try{let state=await _internals148.readPrWorkflowGateState(options.directory,sessionID);if(!state){resetBudget(sessionID),clearPrWorkflowAutoWakeState(options.directory,sessionID);return}if(state.checkoutRecovery)return;if(isPrWorkflowAutoWakeSuppressed(options.directory,sessionID))return;if(!session)return;evictIfOverBound();let budget=wakeBudgets.get(sessionID);if(!budget)budget={consecutiveUnproductive:0,lastWakeAt:0,suspended:!1},wakeBudgets.set(sessionID,budget);if(budget.suspended)return;let now=Date.now();if(budget.lastSeenRevision!==void 0&&state.revision>budget.lastSeenRevision)budget.consecutiveUnproductive=0;if(budget.consecutiveUnproductive>0&&budget.lastWakeAt>0&&now-budget.lastWakeAt<wakeCooldownMs)return;let madeProgress=budget.lastSeenRevision===void 0?!0:state.revision>budget.lastSeenRevision,pluginWakeMessageID=markPrWorkflowPluginWake(options.directory,sessionID),feedbackTarget=state.prFeedbackTargetUrl??state.prFeedbackReviewHandoff?.prUrl,queuedMonitorEvents=(state.mode==="PR_FEEDBACK"&&!state.prFeedbackInventory&&feedbackTarget?await _internals148.readPrFeedbackMonitorQueue(options.directory,sessionID).catch(()=>null):null)?.events.filter((event3)=>!event3.claimedWorkflowInstanceId&&Boolean(feedbackTarget)&&sameGitHubPr3(event3.prUrl,feedbackTarget??""))??[],queuedMonitorText=queuedMonitorEvents.length>0?`
6065
- ${formatQueuedMonitorEventsText(queuedMonitorEvents)}`:"",promptRejected=!1,promptAccepted=!1,timer;try{let args2={path:{id:sessionID},body:{messageID:pluginWakeMessageID,parts:[{type:"text",text:`${blockedText(state.mode,{suspended:!1,maxConsecutive})}
6066
- Do not stop or summarize. Inspect the durable gate, dispatch or collect the next missing required lane, and continue until complete_pr_workflow succeeds. If the bind/checkout path is genuinely unreachable, call abort_pr_workflow instead of looping.${queuedMonitorText}`}]}},call=session.promptAsync?session.promptAsync(args2):session.prompt(args2),result=await Promise.race([call,new Promise((_resolve,reject2)=>{timer=setTimeout(()=>reject2(Error("PR workflow resume prompt timed out")),wakeTimeoutMs)})]);if(result?.error!=null)throw promptRejected=!0,Error(`PR workflow resume prompt failed: ${String(result.error)}`);promptAccepted=!0}finally{if(timer)clearTimeout(timer);if(promptRejected)cancelPrWorkflowPluginWake(options.directory,sessionID,pluginWakeMessageID);let postWakeState=await _internals148.readPrWorkflowGateState(options.directory,sessionID);if(promptAccepted&&queuedMonitorEvents.length>0&&feedbackTarget&&state.workflowInstanceId&&postWakeState?.mode==="PR_FEEDBACK"&&postWakeState.workflowInstanceId===state.workflowInstanceId&&!postWakeState.prFeedbackInventory&&sameGitHubPr3(postWakeState.prFeedbackTargetUrl??postWakeState.prFeedbackReviewHandoff?.prUrl??"",feedbackTarget))await _internals148.claimPrFeedbackMonitorEvents(options.directory,sessionID,state.workflowInstanceId,feedbackTarget,queuedMonitorEvents.map((event3)=>event3.dedupToken)).catch(()=>[]);if(budget.lastWakeAt=now,postWakeState===null)resetBudget(sessionID);else{let currentRevision=postWakeState.revision,effectiveMadeProgress=madeProgress||budget.lastSeenRevision!==void 0&&currentRevision>budget.lastSeenRevision;if(budget.lastSeenRevision=currentRevision,!effectiveMadeProgress){if(budget.consecutiveUnproductive+=1,budget.consecutiveUnproductive>=maxConsecutive)budget.suspended=!0}else budget.consecutiveUnproductive=0}}}finally{activeWakeSessions.delete(sessionID)}},textComplete:async(input,output)=>{if(!input.sessionID?.trim())return;let state=await _internals148.readPrWorkflowGateState(options.directory,input.sessionID);if(!state){resetBudget(input.sessionID),clearPrWorkflowAutoWakeState(options.directory,input.sessionID);return}if(!output.text.trim())return;if(BANNER_PREFIX_PATTERN.test(output.text))return;let messageID=input.messageID?.trim();if(messageID){if(banneredMessages.get(input.sessionID)===messageID)return}else{let injected=fallbackInjections.get(input.sessionID)??0;if(injected>=MAX_FALLBACK_BANNER_INJECTIONS_PER_SESSION)return;fallbackInjections.set(input.sessionID,injected+1),evictBannerDedupeMapsIfOverBound()}let suspended=wakeBudgets.get(input.sessionID)?.suspended??!1,userInterrupted=isPrWorkflowAutoWakeSuppressed(options.directory,input.sessionID),recovery=state.checkoutRecovery?{code:state.checkoutRecovery.code,requiredAction:state.checkoutRecovery.requiredAction}:void 0,forceFullBanner=suspended||userInterrupted||Boolean(recovery),now=Date.now(),lastBannerAt=bannerStamps.get(input.sessionID),withinCooldown=lastBannerAt!==void 0&&now-lastBannerAt<bannerCooldownMs;if(messageID)banneredMessages.set(input.sessionID,messageID),evictBannerDedupeMapsIfOverBound();if(!forceFullBanner&&withinCooldown){output.text=`--- [${state.mode} WORKFLOW ACTIVE] ---
6064
+ `)}function blockedText(mode,options={}){let lines=[`[${mode} WORKFLOW ACTIVE]`,`The ${mode} workflow gate is still active. Continue with the required structured lanes, evidence, and controller tools until \`complete_pr_workflow\` succeeds.`,`If the bind/checkout path is unreachable — for example a compound \`git fetch && git checkout\` was rejected as read-only shell syntax, the PR head cannot be fetched, or the working tree is on the wrong branch — call \`abort_pr_workflow\` (mode: "${mode}", reason: "<one-line cause>") to clear the gate, or ask the user to run \`/swarm abort-pr-workflow\`.`];if(options.suspended)if(options.suspendedReason==="total")lines.push("Auto-resume is suspended because the total per-session wake budget has been exhausted. The session will not be re-awoken automatically. Run `/swarm abort-pr-workflow`, call `abort_pr_workflow`, or complete the workflow with `complete_pr_workflow` to publish normally.");else{let max=options.maxConsecutive;lines.push(`Auto-resume is suspended after ${max??"the configured number of"} consecutive unproductive retries (the durable gate \`revision\` did not advance). The session will not be re-awoken automatically. Run \`/swarm abort-pr-workflow\` or call \`abort_pr_workflow\` to clear the gate, or complete the workflow with \`complete_pr_workflow\` to publish normally.`)}if(options.userInterrupted)lines.push("Auto-resume is paused after a user interruption. The durable workflow gate is preserved, but the plugin will not re-awaken this session. Send a new message to continue, or run `/swarm abort-pr-workflow` to clear the workflow.");if(options.recovery)lines.push(`Auto-resume is disabled because manual Git recovery is required. code=${options.recovery.code} retryable=false required_action=${options.recovery.requiredAction}`);return lines.join(`
6065
+ `)}function workflowBanner(mode,options={}){let lines=[`--- [${mode} WORKFLOW ACTIVE — output below is not a terminal verdict; \`complete_pr_workflow\` clears the gate on success; if the bind/checkout path is unreachable call \`abort_pr_workflow\` or run \`/swarm abort-pr-workflow\`] ---`];if(options.suspended)if(options.suspendedReason==="total")lines.push("[Auto-resume is suspended because the total per-session wake budget has been exhausted. Run `/swarm abort-pr-workflow`, call `abort_pr_workflow`, or complete the workflow with `complete_pr_workflow`.]");else{let max=options.maxConsecutive;lines.push(`[Auto-resume is suspended after ${max??"the configured number of"} consecutive unproductive retries. Run \`/swarm abort-pr-workflow\` or call \`abort_pr_workflow\` to clear the gate, or complete the workflow with \`complete_pr_workflow\`.]`)}if(options.userInterrupted)lines.push("[Auto-resume paused after a user interruption. Send a new message to continue, or run `/swarm abort-pr-workflow` to clear the workflow.]");if(options.recovery)lines.push(`[Manual Git recovery required; auto-resume disabled. code=${options.recovery.code} retryable=false required_action=${options.recovery.requiredAction}]`);return lines.join(" ")}function createPrWorkflowResponseGate(options){let wakeTimeoutMs=options.wakeTimeoutMs??DEFAULT_WAKE_TIMEOUT_MS,maxConsecutive=options.maxConsecutiveUnproductiveWakes??DEFAULT_MAX_CONSECUTIVE_UNPRODUCTIVE_WAKES,wakeCooldownMs=options.wakeCooldownMs??DEFAULT_WAKE_COOLDOWN_MS,bannerCooldownMs=options.bannerCooldownMs??DEFAULT_BANNER_COOLDOWN_MS,resolveTotalWakeCeiling=(tier)=>{if(options.totalWakeCeiling===void 0)return DEFAULT_TOTAL_WAKE_CEILINGS[tier];return typeof options.totalWakeCeiling==="number"?options.totalWakeCeiling:options.totalWakeCeiling[tier]??DEFAULT_TOTAL_WAKE_CEILINGS[tier]},activeWakeSessions=new Set,wakeBudgets=new Map,bannerStamps=new Map,banneredMessages=new Map,fallbackInjections=new Map,session=options.client?.session;function evictIfOverBound(){while(wakeBudgets.size>MAX_TRACKED_WAKE_SESSIONS){let evicted=!1;for(let[key,budget]of wakeBudgets){if(budget.suspended)continue;wakeBudgets.delete(key),evicted=!0;break}if(!evicted)break}}function evictBannerDedupeMapsIfOverBound(){while(bannerStamps.size>MAX_TRACKED_WAKE_SESSIONS){let oldestKey=bannerStamps.keys().next().value;if(oldestKey===void 0)break;bannerStamps.delete(oldestKey)}while(banneredMessages.size>MAX_TRACKED_WAKE_SESSIONS){let oldestKey=banneredMessages.keys().next().value;if(oldestKey===void 0)break;banneredMessages.delete(oldestKey)}while(fallbackInjections.size>MAX_TRACKED_WAKE_SESSIONS){let oldestKey=fallbackInjections.keys().next().value;if(oldestKey===void 0)break;fallbackInjections.delete(oldestKey)}}function resetBudget(sessionID){wakeBudgets.delete(sessionID),bannerStamps.delete(sessionID),banneredMessages.delete(sessionID),fallbackInjections.delete(sessionID)}return{event:async(input)=>{let wakeDecision=await observePrWorkflowAutoWakeEvent(options.directory,input.event),event2=input.event,sessionID=event2?.properties?.sessionID??event2?.data?.sessionID;if(event2?.type!=="session.idle"||typeof sessionID!=="string"||!sessionID.trim()||wakeDecision.suppressWake||activeWakeSessions.has(sessionID))return;activeWakeSessions.add(sessionID);try{let state=await _internals148.readPrWorkflowGateState(options.directory,sessionID);if(!state){resetBudget(sessionID),clearPrWorkflowAutoWakeState(options.directory,sessionID);return}if(state.checkoutRecovery)return;if(isPrWorkflowAutoWakeSuppressed(options.directory,sessionID))return;if(!session)return;evictIfOverBound();let budget=wakeBudgets.get(sessionID);if(!budget)budget={consecutiveUnproductive:0,lastWakeAt:0,suspended:!1,totalWakes:0,suspendedReason:"consecutive"},wakeBudgets.set(sessionID,budget);if(budget.suspended)return;let now=Date.now();if(budget.lastSeenRevision!==void 0&&state.revision>budget.lastSeenRevision)budget.consecutiveUnproductive=0;if(budget.consecutiveUnproductive>0&&budget.lastWakeAt>0&&now-budget.lastWakeAt<wakeCooldownMs)return;let madeProgress=budget.lastSeenRevision===void 0?!0:state.revision>budget.lastSeenRevision,pluginWakeMessageID=markPrWorkflowPluginWake(options.directory,sessionID),feedbackTarget=state.prFeedbackTargetUrl??state.prFeedbackReviewHandoff?.prUrl,queuedMonitorEvents=(state.mode==="PR_FEEDBACK"&&!state.prFeedbackInventory&&feedbackTarget?await _internals148.readPrFeedbackMonitorQueue(options.directory,sessionID).catch(()=>null):null)?.events.filter((event3)=>!event3.claimedWorkflowInstanceId&&Boolean(feedbackTarget)&&sameGitHubPr3(event3.prUrl,feedbackTarget??""))??[],queuedMonitorText=queuedMonitorEvents.length>0?`
6066
+ ${formatQueuedMonitorEventsText(queuedMonitorEvents)}`:"",promptRejected=!1,promptAccepted=!1,timer;try{let args2={path:{id:sessionID},body:{messageID:pluginWakeMessageID,parts:[{type:"text",text:`${blockedText(state.mode,{suspended:!1,suspendedReason:void 0,maxConsecutive})}
6067
+ Do not stop or summarize. Inspect the durable gate, dispatch or collect the next missing required lane, and continue until complete_pr_workflow succeeds. If the bind/checkout path is genuinely unreachable, call abort_pr_workflow instead of looping.${queuedMonitorText}`}]}},call=session.promptAsync?session.promptAsync(args2):session.prompt(args2),result=await Promise.race([call,new Promise((_resolve,reject2)=>{timer=setTimeout(()=>reject2(Error("PR workflow resume prompt timed out")),wakeTimeoutMs)})]);if(result?.error!=null)throw promptRejected=!0,Error(`PR workflow resume prompt failed: ${String(result.error)}`);promptAccepted=!0}finally{if(timer)clearTimeout(timer);if(promptRejected)cancelPrWorkflowPluginWake(options.directory,sessionID,pluginWakeMessageID);let postWakeState;try{postWakeState=await _internals148.readPrWorkflowGateState(options.directory,sessionID)}catch{postWakeState=state}if(promptAccepted&&queuedMonitorEvents.length>0&&feedbackTarget&&state.workflowInstanceId&&postWakeState?.mode==="PR_FEEDBACK"&&postWakeState.workflowInstanceId===state.workflowInstanceId&&!postWakeState.prFeedbackInventory&&sameGitHubPr3(postWakeState.prFeedbackTargetUrl??postWakeState.prFeedbackReviewHandoff?.prUrl??"",feedbackTarget))await _internals148.claimPrFeedbackMonitorEvents(options.directory,sessionID,state.workflowInstanceId,feedbackTarget,queuedMonitorEvents.map((event3)=>event3.dedupToken)).catch(()=>[]);if(budget.lastWakeAt=now,postWakeState===null)resetBudget(sessionID);else{let currentRevision=postWakeState.revision,effectiveMadeProgress=madeProgress||budget.lastSeenRevision!==void 0&&currentRevision>budget.lastSeenRevision;if(budget.lastSeenRevision=currentRevision,!effectiveMadeProgress){if(budget.consecutiveUnproductive+=1,budget.consecutiveUnproductive>=maxConsecutive)budget.suspended=!0,budget.suspendedReason="consecutive"}else budget.consecutiveUnproductive=0;budget.totalWakes+=1;let tier=postWakeState.prReviewDepthTier??"L",totalCeiling=resolveTotalWakeCeiling(tier);if(budget.totalWakes>=totalCeiling)budget.suspended=!0,budget.suspendedReason="total"}}}finally{activeWakeSessions.delete(sessionID)}},textComplete:async(input,output)=>{if(!input.sessionID?.trim())return;let state=await _internals148.readPrWorkflowGateState(options.directory,input.sessionID);if(!state){resetBudget(input.sessionID),clearPrWorkflowAutoWakeState(options.directory,input.sessionID);return}if(!output.text.trim())return;if(BANNER_PREFIX_PATTERN.test(output.text))return;let messageID=input.messageID?.trim();if(messageID){if(banneredMessages.get(input.sessionID)===messageID)return}else{let injected=fallbackInjections.get(input.sessionID)??0;if(injected>=MAX_FALLBACK_BANNER_INJECTIONS_PER_SESSION)return;fallbackInjections.set(input.sessionID,injected+1),evictBannerDedupeMapsIfOverBound()}let budget=wakeBudgets.get(input.sessionID),suspended=budget?.suspended??!1,suspendedReason=budget?.suspendedReason,userInterrupted=isPrWorkflowAutoWakeSuppressed(options.directory,input.sessionID),recovery=state.checkoutRecovery?{code:state.checkoutRecovery.code,requiredAction:state.checkoutRecovery.requiredAction}:void 0,forceFullBanner=suspended||userInterrupted||Boolean(recovery),now=Date.now(),lastBannerAt=bannerStamps.get(input.sessionID),withinCooldown=lastBannerAt!==void 0&&now-lastBannerAt<bannerCooldownMs;if(messageID)banneredMessages.set(input.sessionID,messageID),evictBannerDedupeMapsIfOverBound();if(!forceFullBanner&&withinCooldown){output.text=`--- [${state.mode} WORKFLOW ACTIVE] ---
6067
6068
 
6068
- ${output.text}`;return}let banner=workflowBanner(state.mode,{suspended,userInterrupted,maxConsecutive,recovery});bannerStamps.set(input.sessionID,now),evictBannerDedupeMapsIfOverBound(),output.text=`${banner}
6069
+ ${output.text}`;return}let banner=workflowBanner(state.mode,{suspended,suspendedReason,userInterrupted,maxConsecutive,recovery});bannerStamps.set(input.sessionID,now),evictBannerDedupeMapsIfOverBound(),output.text=`${banner}
6069
6070
 
6070
6071
  ${output.text}`},_inspectWakeBudget:(sessionID)=>wakeBudgets.get(sessionID)}}init_pending_delegations();init_pr_workflow_gate();var MAX_PARENT_DEPTH=16,MAX_TRACKED_SESSION_PARENTS=512;function rememberBounded2(parents,childSessionID,parentSessionID){parents.delete(childSessionID),parents.set(childSessionID,parentSessionID);while(parents.size>MAX_TRACKED_SESSION_PARENTS){let oldest=parents.keys().next().value;if(typeof oldest!=="string")break;parents.delete(oldest)}}function createPrWorkflowSessionResolver(options){let session=options.client?.session,parents=new Map;return{observeEvent:(input)=>{let event=input.event;if(event?.type!=="session.created"&&event?.type!=="session.updated")return;let child=event.properties?.info?.id,parent=event.properties?.info?.parentID;if(typeof child==="string"&&child.trim()&&typeof parent==="string"&&parent.trim())rememberBounded2(parents,child.trim(),parent.trim())},resolve:async(sessionID)=>{let original=sessionID.trim();if(!original)return sessionID;let current=original,visited=new Set;for(let depth=0;depth<MAX_PARENT_DEPTH;depth+=1){if(visited.has(current))break;if(visited.add(current),await readPrWorkflowGateState(options.directory,current))return current;let parent=parents.get(current);if(!parent)parent=findByCorrelationId(options.directory,current)?.parentSessionId;if(!parent&&session?.get){let result=await session.get({path:{id:current},query:{directory:options.directory}});if(result?.error==null){let candidate=result?.data?.parentID;if(typeof candidate==="string"&&candidate.trim())parent=candidate.trim()}}if(!parent)return original;rememberBounded2(parents,current,parent),current=parent}return original}}}init_review_receipt_collector();init_schema();init_scope_binding();init_state2();init_normalize_tool_name();init_review_receipt();init_review_receipt_scope();init_reviewer_scope_file_fingerprint();init_skill_propagation_gate();init_task_result_classifier();function lifecycleTarget(args2){let delegation=parseDelegationArgs(args2);return delegation?stripKnownSwarmPrefix(delegation.targetAgent).toLowerCase():""}function isTaskTool6(tool3){if(typeof tool3!=="string")return!1;let normalized=normalizeToolName(tool3);return normalized==="Task"||normalized==="task"}function generationFingerprintsAreCurrent(directory,generation){let{modifiedFiles,modifiedFileFingerprints:fingerprints}=generation;if(modifiedFiles.length===0||modifiedFiles.length!==fingerprints.length||new Set(modifiedFiles).size!==modifiedFiles.length||new Set(fingerprints.map((entry)=>entry.file)).size!==fingerprints.length)return!1;let fingerprintBytes=0;for(let file3 of modifiedFiles){let stored=fingerprints.filter((entry)=>entry.file===file3),current=captureReviewerScopeFileFingerprint(directory,file3,MAX_REVIEWER_SCOPE_FINGERPRINT_AGGREGATE_BYTES-fingerprintBytes);if(stored.length!==1||!current||!reviewerScopeFileFingerprintsEqual(stored[0],current))return!1;if(current.kind==="file")fingerprintBytes+=current.size}return!0}function scopeMatchesGenerationFingerprints(scope,generation){let records=new Map;for(let line of scope.content.split(`
6071
6072
  `).slice(1)){if(!line)continue;try{let parsed=JSON.parse(line);if(typeof parsed.path==="string")records.set(parsed.path,parsed)}catch{return!1}}if(records.size!==generation.modifiedFileFingerprints.length||scope.files.length!==generation.modifiedFiles.length)return!1;return generation.modifiedFileFingerprints.every((fingerprint)=>{let record3=records.get(fingerprint.file);if(!record3)return!1;return fingerprint.kind==="deleted"?record3.state==="deleted":record3.state==="file"&&record3.bytes===fingerprint.size&&record3.sha256===fingerprint.hash})}async function beginApprovedReviewerScopeLifecycle(input){if(!isTaskTool6(input.tool))return null;let taskId=await resolveReviewerScopeTaskId(input.directory,input.args);if(!taskId)return null;let target=lifecycleTarget(input.args);if(target==="coder"){let binding=getScopeBindingForParentDispatch({parentSessionId:input.parentSessionID,dispatchCallId:input.callID});if(binding?.taskId!==taskId)return null;let rawArgs=input.args&&typeof input.args==="object"?input.args:null;return startReviewerScopeGeneration({parentSessionID:input.parentSessionID,taskId,coderCallID:input.callID,background:rawArgs?.background===!0||rawArgs?.background==="true",declaredFiles:binding.files})?"coder_started":null}if(target==="reviewer"){let ready=peekReadyReviewerScopeGeneration({parentSessionID:input.parentSessionID,taskId});if(!ready||!generationFingerprintsAreCurrent(input.directory,ready)){if(ready)discardReviewerScopeGenerationForCoderCall({parentSessionID:input.parentSessionID,taskId,coderCallID:ready.coderCallID});throw Error("REVIEWER_SCOPE_STALE: coder post-write fingerprints are incomplete or changed before reviewer dispatch")}let snapshot=await buildReviewerTaskScope(input.directory,ready.modifiedFiles,input.maxBytes,{taskId:ready.taskId,coderCallID:ready.coderCallID,generation:ready.generation,sessionIncarnation:ready.sessionIncarnation}),current=peekReadyReviewerScopeGeneration({parentSessionID:input.parentSessionID,taskId}),exactGenerationStillCurrent=current!==null&&current.coderCallID===ready.coderCallID&&current.generation===ready.generation&&current.sessionIncarnation===ready.sessionIncarnation&&isReviewerScopeGenerationCurrent({parentSessionID:input.parentSessionID,taskId,coderCallID:ready.coderCallID,generation:ready.generation,sessionIncarnation:ready.sessionIncarnation});if(!snapshot||!current||!exactGenerationStillCurrent||!generationFingerprintsAreCurrent(input.directory,current)||!scopeMatchesGenerationFingerprints(snapshot,current))throw discardReviewerScopeGenerationForCoderCall({parentSessionID:input.parentSessionID,taskId,coderCallID:ready.coderCallID}),Error("REVIEWER_SCOPE_STALE: exact reviewer dispatch scope changed during capture");let claimed=claimReviewerScopeGeneration({parentSessionID:input.parentSessionID,taskId,reviewerCallID:input.callID});if(!claimed||claimed.coderCallID!==ready.coderCallID||claimed.generation!==ready.generation||claimed.sessionIncarnation!==ready.sessionIncarnation||!attachReviewerScopeGenerationDispatchSnapshot({parentSessionID:input.parentSessionID,taskId,reviewerCallID:input.callID,snapshot:{hash:computeScopeFingerprint(snapshot.content,snapshot.description).hash,description:snapshot.description,files:[...snapshot.files],headSha:snapshot.headSha,taskId:claimed.taskId,coderCallID:claimed.coderCallID,generation:claimed.generation,sessionIncarnation:claimed.sessionIncarnation}}))throw discardReviewerScopeGenerationClaim({parentSessionID:input.parentSessionID,taskId,reviewerCallID:input.callID}),Error("REVIEWER_SCOPE_STALE: exact reviewer dispatch scope could not be captured");return"reviewer_claimed"}return null}async function completeReviewerScopeLifecycle(input){if(!isTaskTool6(input.tool))return null;if(lifecycleTarget(input.args)!=="coder")return null;let result=classifyTaskResult(input.output);if(result==="running")return null;let taskId=await resolveReviewerScopeTaskId(input.directory,input.args);if(!taskId)return discardReviewerScopeGenerationForCoderCall({parentSessionID:input.parentSessionID,coderCallID:input.callID}),null;if(result==="non_success")return discardReviewerScopeGenerationForCoderCall({parentSessionID:input.parentSessionID,taskId,coderCallID:input.callID}),null;return markReviewerScopeGenerationReady({parentSessionID:input.parentSessionID,taskId,coderCallID:input.callID})?"coder_ready":null}init_schema();init_bun_compat();init_logger();var import_picomatch2=__toESM(require_picomatch2(),1);import{existsSync as existsSync106,readdirSync as readdirSync34,readFileSync as readFileSync81,statSync as statSync45}from"node:fs";import*as path218 from"node:path";var PREDICATE_TIMEOUT_MS=15000,GREP_MAX_FILES=1e4,GREP_MAX_BYTES_PER_FILE=1e6,GREP_SKIP_DIRECTORIES=new Set([".git",".swarm","node_modules","dist","coverage"]),TOOL_BINARY_ALLOWLIST=new Set(["rg","grep","git","biome","eslint","tsc","ruff"]);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=path218.resolve(directory),resolved=path218.resolve(baseDir,concrete),rel=path218.relative(baseDir,resolved);if(rel.startsWith("..")||path218.isAbsolute(rel))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(path218.delimiter)){if(!dir)continue;for(let name of candidates){let candidate=path218.join(dir,name);if(existsSync106(candidate))return candidate}}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((resolve81)=>setTimeout(()=>resolve81("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 entries;try{entries=readdirSync34(dir,{withFileTypes:!0})}catch{return}for(let entry of entries){if(visited>=GREP_MAX_FILES)return;let fullPath=path218.join(dir,entry.name),relPath=path218.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(statSync45(fullPath).size>GREP_MAX_BYTES_PER_FILE)continue;let found=readFileSync81(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(path218.normalize(p))}return out}async function runFileModifiedPredicate(rest,directory,expectModified){let label=expectModified?"file_modified":"file_not_modified",safe=validateRepoRelativeGlob(directory,rest);if(safe===null)return{result:"error",detail:`${label}: unsafe or empty path "${rest}"`};let changed=await changedPaths(directory);if(changed===null)return{result:"error",detail:`${label}: git unavailable or failed`};let target=path218.normalize(safe),isChanged=changed.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)"}}}init_knowledge_escalator();init_knowledge_events();init_skill_propagation_gate();var VERDICT_PATTERN=/\b(VERIFIED|VIOLATED|N\/A)\s*:\s*([A-Za-z0-9._-]{1,80})(?:\s+(?:evidence|reason)\s*=\s*([^\n\r]+?))?(?=$|[\n\r]|\s+(?:VERIFIED|VIOLATED|N\/A)\b)/gi;function parseReviewerDirectiveCompliance(text){if(!text||typeof text!=="string")return[];let out=[];for(let m of text.matchAll(VERDICT_PATTERN)){let verb=m[1].toUpperCase(),id=m[2],evidence2=m[3]?.trim().slice(0,280),verdict=verb==="VERIFIED"?"verified":verb==="VIOLATED"?"violated":"n_a";out.push({id,verdict,evidence:evidence2})}return out}function verdictToEventType(v){return v==="verified"?"applied":v==="violated"?"violated":"n_a"}async function reconcileReviewerVerdicts(params){let result={emitted:[],omittedCriticals:[]};try{let verifyById=new Map(params.directivesToVerify.map((d)=>[d.id,d]));if(verifyById.size===0)return result;let verdicts=parseReviewerDirectiveCompliance(params.transcript),addressed=new Set,violatedIds=new Set,traceId=newTraceId(),sessionId=params.sessionId??"unknown",agent=params.agent??"reviewer";for(let v of verdicts){let directive=verifyById.get(v.id);if(!directive)continue;addressed.add(v.id);let type=verdictToEventType(v.verdict),predicateCheck;if(v.verdict==="violated"&&directive.verification_predicate){let outcome=await runDirectivePredicate(directive.verification_predicate,params.directory);predicateCheck={predicate:directive.verification_predicate,result:outcome.result,detail:outcome.detail}}if(await recordKnowledgeEvent(params.directory,{type,trace_id:traceId,knowledge_id:v.id,session_id:sessionId,task_id:params.taskId,phase:params.phase,agent,source:"reviewer",reason:v.evidence,predicate_check:predicateCheck}),type==="violated")violatedIds.add(v.id);result.emitted.push({id:v.id,type,source:"reviewer"})}for(let d of params.directivesToVerify){if(d.priority!=="critical")continue;if(addressed.has(d.id))continue;result.omittedCriticals.push(d.id),await recordKnowledgeEvent(params.directory,{type:"violated",trace_id:traceId,knowledge_id:d.id,session_id:sessionId,task_id:params.taskId,phase:params.phase,agent,source:"reviewer",reason:"reviewer_omitted"}),violatedIds.add(d.id),result.emitted.push({id:d.id,type:"violated",source:"reviewer"})}if(violatedIds.size>0)await escalateViolatedEntries(params.directory,[...violatedIds])}catch{}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"})}init_constants();init_schema();init_scope_binding();init_scope_persistence();init_state2();init_normalize_tool_name();init_pr_workflow_gate();init_write_target_resolver();import*as path219 from"node:path";var WRITE_TOOLS2=new Set(WRITE_TOOL_NAMES);function createScopeGuardHook(config3,fallbackDirectory,injectAdvisory){let enabled=config3.enabled??!0,_skipInTurbo=config3.skip_in_turbo??!1;return{toolBefore:async(input,output)=>{if(!enabled)return;let toolName=normalizeToolName(input.tool);if(!WRITE_TOOLS2.has(toolName))return;let sessionId=input.sessionID,activeAgent=swarmState.activeAgent.get(sessionId),session=swarmState.agentSessions.get(sessionId),agentName=activeAgent??session?.agentName??"unknown",agentRole=stripKnownSwarmPrefix(agentName);if(agentRole===ORCHESTRATOR_NAME)return;if(agentRole!=="coder")return;let directory=_internals149.resolveSessionWorkspaceDirectory(sessionId,fallbackDirectory),targets=_internals149.resolveWriteTargets(toolName,output.args,{directory});if(targets.status==="unverifiable")throw Error(`WRITE TARGET UNVERIFIABLE: ${agentName} invoked ${toolName}: ${targets.reason}`);if(targets.paths.length===0)return;let taskId=_internals149.resolveTaskId(session),binding=taskId?_internals149.resolveAuthorizedScopeBinding({directory,taskId,activeSessionId:sessionId}):_internals149.resolveAuthorizedScopeBindingForSession({directory,activeSessionId:sessionId});if(!binding){if(binding=_internals149.getAuthorizedPrFeedbackScopeBinding({directory,activeSessionId:sessionId,taskId:taskId??void 0})??_internals149.resolveAuthorizedPrFeedbackScopeBindingFromDisk({directory,activeSessionId:sessionId,taskId:taskId??void 0}),binding&&!await _internals149.validatePrFeedbackScopeBinding(directory,binding))binding=null}if(!taskId&&binding&&session)taskId=binding.taskId,session.currentTaskId=binding.taskId,session.declaredCoderScope=[...binding.files];let declaredScope=binding?.files??null;if(!declaredScope||declaredScope.length===0){let mismatch=_internals149.describeScopeWorkspaceMismatch({directory,activeSessionId:sessionId,taskId});if(mismatch)throw Error(`${mismatch} ${agentName} cannot invoke ${toolName} for task ${taskId??"unknown"}.`);throw Error(`SCOPE_NOT_DECLARED: ${agentName} cannot invoke ${toolName} without a validated scope for task ${taskId??"unknown"}.`)}for(let rawPath of targets.paths){let filePath=sanitizePath(rawPath);if(!isFileInScope(filePath,declaredScope,directory))reportScopeViolation(agentName,filePath,taskId,session,injectAdvisory,swarmState,declaredScope)}}}}function isFileInScope(filePath,scopeEntries,directory){let dir=directory??process.cwd(),resolvedFile=path219.resolve(dir,filePath);return scopeEntries.filter((scope)=>scope.length>0).some((scope)=>{let resolvedScope=path219.resolve(dir,scope);if(resolvedFile===resolvedScope)return!0;let rel=path219.relative(resolvedScope,resolvedFile);return rel.length>0&&!rel.startsWith("..")&&!path219.isAbsolute(rel)})}function sanitizePath(raw){let result="";for(let i=0;i<raw.length;i++){let c=raw.charCodeAt(i);if(c<=31||c===127||c>=128&&c<=159){result+="_";continue}result+=raw[i]}return result.replace(/\[[\d;]*m/g,"")}var _internals149={sanitizePath,resolveWriteTargets:resolveWriteTargets2,resolveAuthorizedScopeBinding,resolveAuthorizedScopeBindingForSession,getAuthorizedPrFeedbackScopeBinding,resolveAuthorizedPrFeedbackScopeBindingFromDisk,validatePrFeedbackScopeBinding,resolveSessionWorkspaceDirectory,describeScopeWorkspaceMismatch,resolveTaskId:(session)=>session?.currentTaskId??null};function reportScopeViolation(agentName,filePath,taskId,session,injectAdvisory,state,scopeEntries){let violationMessage=`SCOPE VIOLATION: ${agentName} attempted to modify '${filePath}' which is not in declared scope for task ${taskId??"unknown"}. Declared scope: [${scopeEntries.slice(0,3).join(", ")}${scopeEntries.length>3?"...":""}]`;if(session)session.lastScopeViolation=violationMessage,session.scopeViolationDetected=!0;if(injectAdvisory)for(let[archSessionId,archSession]of state.agentSessions){let archAgent=state.activeAgent.get(archSessionId)??archSession.agentName;if(stripKnownSwarmPrefix(archAgent)===ORCHESTRATOR_NAME){try{injectAdvisory(archSessionId,`[SCOPE GUARD] ${violationMessage}`)}catch{}break}}throw Error(violationMessage)}init_constants();init_schema();init_state2();init_normalize_tool_name();function createSelfReviewHook(config3,injectAdvisory){let enabled=config3.enabled??!0,skipInTurbo=config3.skip_in_turbo??!0;return{toolAfter:async(input,output)=>{if(!enabled)return;if(normalizeToolName(input.tool)!=="update_task_status")return;let args2=output.args;if(args2?.status!=="in_progress")return;let taskId=typeof args2?.task_id==="string"?args2.task_id:"unknown",sessionId=input.sessionID,agentName=swarmState.activeAgent.get(sessionId)??swarmState.agentSessions.get(sessionId)?.agentName??"";if(stripKnownSwarmPrefix(agentName)!==ORCHESTRATOR_NAME)return;if(skipInTurbo){let session=swarmState.agentSessions.get(sessionId);if(session&&session.turboMode===!0)return}let advisory=[`[SELF-REVIEW] Task ${taskId} is now delegated to coder.`,"After coder completes, review for:"," • Broken conditionals (inverted if/else, wrong comparisons)"," • Off-by-one errors (array bounds, loop indices)"," • Assumptions contradicting existing codebase patterns"," • Missing error handling (uncaught exceptions, unhandled promises)"," • Scope creep (changes outside the declared task spec)","Delegate to critic with self-review focus before marking complete."].join(`
@@ -6180,7 +6181,7 @@ ${body}`,{dedupeKey:dedupKey})}init_zod();init_task_file();init_logger();import{
6180
6181
  `)}catch(auditError){log(`writeCouncilEvidence: failed to append round-history audit log: ${auditError instanceof Error?auditError.message:String(auditError)}`)}}var COUNCIL_DEFAULTS={enabled:!1,maxRounds:3,parallelTimeoutMs:30000,vetoPriority:!0,requireAllMembers:!1,minimumMembers:3,phaseConcernsAllowComplete:!0};function synthesizeCouncilVerdicts(taskId,swarmId,verdicts,criteria,roundNumber,config3={}){let cfg={...COUNCIL_DEFAULTS,...config3},timestamp=new Date().toISOString(),quorumSize=new Set(verdicts.map((v)=>v.agent)).size,rejectingMembers=verdicts.filter((v)=>v.verdict==="REJECT").map((v)=>v.agent),overallVerdict;if(cfg.vetoPriority&&rejectingMembers.length>0)overallVerdict="REJECT";else if(verdicts.some((v)=>v.verdict==="CONCERNS")||!cfg.vetoPriority&&rejectingMembers.length>0)overallVerdict="CONCERNS";else overallVerdict="APPROVE";let unresolvedConflicts=detectConflicts2(verdicts),rejectingSet=new Set(rejectingMembers),vetoFindings=verdicts.filter((v)=>rejectingSet.has(v.agent)).flatMap((v)=>v.findings),requiredFixes=vetoFindings.filter((f)=>f.severity==="CRITICAL"||f.severity==="HIGH"||f.severity==="MEDIUM"),advisoryFindings=[...vetoFindings.filter((f)=>f.severity==="LOW"),...verdicts.filter((v)=>!rejectingSet.has(v.agent)).flatMap((v)=>v.findings)],blockingConcernsCount=promoteBlockingConcerns(verdicts,rejectingSet,requiredFixes,advisoryFindings),allAssessedIds=new Set(verdicts.flatMap((v)=>v.criteriaAssessed)),allUnmetIds=new Set(verdicts.flatMap((v)=>v.criteriaUnmet)),allCriteriaMet=[...new Set((criteria?.criteria??[]).filter((c)=>c.mandatory).map((c)=>c.id))].every((id)=>allAssessedIds.has(id)&&!allUnmetIds.has(id)),unifiedFeedbackMd=buildUnifiedFeedback(taskId,overallVerdict,rejectingMembers,requiredFixes,advisoryFindings,unresolvedConflicts,roundNumber,cfg.maxRounds,blockingConcernsCount);return{taskId,swarmId,timestamp,overallVerdict,vetoedBy:rejectingMembers.length>0?rejectingMembers:null,memberVerdicts:verdicts,unresolvedConflicts,requiredFixes,advisoryFindings,unifiedFeedbackMd,roundNumber,allCriteriaMet,quorumSize,blockingConcernsCount,...verdicts.length===0&&{emptyVerdictsWarning:!0}}}function promoteBlockingConcerns(verdicts,rejectingSet,requiredFixes,advisoryFindings){let blocking=verdicts.filter((v)=>v.verdict==="CONCERNS"&&!rejectingSet.has(v.agent)).flatMap((v)=>v.findings).filter((f)=>f.severity==="CRITICAL"||f.severity==="HIGH");if(blocking.length===0)return 0;requiredFixes.push(...blocking);let blockingSet=new Set(blocking);for(let i=advisoryFindings.length-1;i>=0;i--)if(blockingSet.has(advisoryFindings[i]))advisoryFindings.splice(i,1);return blocking.length}function detectConflicts2(verdicts){let conflicts=[],locationMap=new Map;for(let verdict of verdicts)for(let finding of verdict.findings){let key=finding.location.toLowerCase();if(!key)continue;let entries=locationMap.get(key);if(entries)entries.push({agent:verdict.agent,detail:finding.detail});else locationMap.set(key,[{agent:verdict.agent,detail:finding.detail}])}for(let[location,entries]of locationMap){if(entries.length<2)continue;let addDirectives=entries.filter((e)=>/\badd\b|\binclude\b|\binsert\b/i.test(e.detail)),removeDirectives=entries.filter((e)=>/\bremove\b|\bdelete\b|\beliminate\b/i.test(e.detail));if(addDirectives.length>0&&removeDirectives.length>0)conflicts.push(`Conflict at ${location}: ${addDirectives.map((e)=>`${e.agent} says "${e.detail}"`).join(", ")} vs ${removeDirectives.map((e)=>`${e.agent} says "${e.detail}"`).join(", ")}`)}return conflicts}function buildUnifiedFeedback(taskId,verdict,vetoedBy,requiredFixes,advisoryFindings,conflicts,roundNumber,maxRounds,blockingConcernsCount=0){let lines=[`## Work Complete Council — Round ${roundNumber}/${maxRounds}`,`**Task:** ${taskId} **Overall verdict:** ${verdict}`,""];if(vetoedBy.length>0)lines.push(`> ⛔ **BLOCKED** by: ${vetoedBy.join(", ")}`),lines.push("");if(blockingConcernsCount>0)lines.push(`> ⚠️ **BLOCKING CONCERNS**: ${blockingConcernsCount} HIGH/CRITICAL finding(s) from CONCERNS members require investigation and resolution before advancement.`),lines.push("");if(requiredFixes.length>0){lines.push("### Required Fixes (must resolve before re-submission)");for(let f of requiredFixes)lines.push(`- **[${f.severity}]** \`${f.location}\` — ${f.detail}`,` _Evidence:_ ${f.evidence}`);lines.push("")}if(conflicts.length>0){lines.push("### Conflicts to Resolve"),lines.push("_The following reviewers gave contradictory instructions. Architect must resolve before sending to coder._");for(let c of conflicts)lines.push(`- ${c}`);lines.push("")}if(advisoryFindings.length>0){lines.push("### Advisory Findings (non-blocking)");for(let f of advisoryFindings)lines.push(`- **[${f.severity}]** \`${f.location}\` — ${f.detail}`);lines.push("")}if(verdict==="APPROVE")lines.push("> ✅ **All council members approved.** Work may advance to `complete`.");else if(roundNumber>=maxRounds)lines.push(`> ⚠️ **Max rounds (${maxRounds}) reached.** Escalate to user — do not auto-advance.`);return lines.join(`
6181
6182
  `)}function synthesizePhaseCouncilAdvisory(phaseNumber,phaseSummary,verdicts,roundNumber,config3={},_workingDir){let cfg={...COUNCIL_DEFAULTS,...config3},timestamp=new Date().toISOString(),scope="phase",quorumSize=new Set(verdicts.map((v)=>v.agent)).size,rejectingMembers=verdicts.filter((v)=>v.verdict==="REJECT").map((v)=>v.agent),overallVerdict;if(cfg.vetoPriority&&rejectingMembers.length>0)overallVerdict="REJECT";else if(verdicts.some((v)=>v.verdict==="CONCERNS")||!cfg.vetoPriority&&rejectingMembers.length>0)overallVerdict="CONCERNS";else overallVerdict="APPROVE";let unresolvedConflicts=detectConflicts2(verdicts),rejectingSet=new Set(rejectingMembers),vetoFindings=verdicts.filter((v)=>rejectingSet.has(v.agent)).flatMap((v)=>v.findings),requiredFixes=vetoFindings.filter((f)=>f.severity==="CRITICAL"||f.severity==="HIGH"||f.severity==="MEDIUM"),advisoryFindings=[...vetoFindings.filter((f)=>f.severity==="LOW"),...verdicts.filter((v)=>!rejectingSet.has(v.agent)).flatMap((v)=>v.findings)],blockingConcernsCount=promoteBlockingConcerns(verdicts,rejectingSet,requiredFixes,advisoryFindings),advisoryNotes=[];if(advisoryFindings.length>0)advisoryNotes.push(`Phase ${phaseNumber} council found ${advisoryFindings.length} advisory finding(s). Review before proceeding to next phase.`);if(verdicts.length<3)advisoryNotes.push(`Phase council quorum is ${verdicts.length} members — consider convening additional members for broader review coverage.`);let allCriteriaMet=new Set(verdicts.flatMap((v)=>v.criteriaUnmet)).size===0&&verdicts.length>0,unifiedFeedbackMd=buildPhaseCouncilFeedback(phaseNumber,phaseSummary,overallVerdict,rejectingMembers,requiredFixes,advisoryFindings,unresolvedConflicts,roundNumber,cfg.maxRounds,blockingConcernsCount),evidencePath=`.swarm/evidence/${phaseNumber}/phase-council.json`;return{phaseNumber,scope:"phase",timestamp,overallVerdict,vetoedBy:rejectingMembers.length>0?rejectingMembers:null,memberVerdicts:verdicts,unresolvedConflicts,requiredFixes,advisoryFindings,advisoryNotes,unifiedFeedbackMd,roundNumber,allCriteriaMet,quorumSize,blockingConcernsCount,evidencePath,phaseSummary}}function buildPhaseCouncilFeedback(phaseNumber,phaseSummary,verdict,vetoedBy,requiredFixes,advisoryFindings,conflicts,roundNumber,maxRounds,blockingConcernsCount=0){let lines=[`## Phase Council Review — Round ${roundNumber}/${maxRounds}`,`**Phase:** ${phaseNumber} **Overall verdict:** ${verdict}`,""];if(phaseSummary)lines.push(`**Phase Summary:** ${phaseSummary}`),lines.push("");if(vetoedBy.length>0)lines.push(`> ⛔ **BLOCKED** by: ${vetoedBy.join(", ")}`),lines.push("");if(blockingConcernsCount>0)lines.push(`> ⚠️ **BLOCKING CONCERNS**: ${blockingConcernsCount} HIGH/CRITICAL finding(s) from CONCERNS members require investigation and resolution before phase completion.`),lines.push("");if(requiredFixes.length>0){lines.push("### Required Fixes (must resolve before re-submission)");for(let f of requiredFixes)lines.push(`- **[${f.severity}]** \`${f.location}\` — ${f.detail}`,` _Evidence:_ ${f.evidence}`);lines.push("")}if(conflicts.length>0){lines.push("### Conflicts to Resolve"),lines.push("_The following reviewers gave contradictory instructions. Architect must resolve before sending to coder._");for(let c of conflicts)lines.push(`- ${c}`);lines.push("")}if(advisoryFindings.length>0){lines.push("### Advisory Findings (non-blocking)");for(let f of advisoryFindings)lines.push(`- **[${f.severity}]** \`${f.location}\` — ${f.detail}`);lines.push("")}if(verdict==="APPROVE")lines.push("> ✅ **Phase council approved.** Phase may proceed to completion.");else if(roundNumber>=maxRounds)lines.push(`> ⚠️ **Max rounds (${maxRounds}) reached.** Escalate to user — do not auto-advance.`);return lines.join(`
6182
6183
  `)}function synthesizeFinalCouncilAdvisory(projectSummary,verdicts,roundNumber,config3={}){let cfg={...COUNCIL_DEFAULTS,...config3},timestamp=new Date().toISOString(),quorumSize=new Set(verdicts.map((v)=>v.agent)).size,rejectingMembers=verdicts.filter((v)=>v.verdict==="REJECT").map((v)=>v.agent),overallVerdict;if(cfg.vetoPriority&&rejectingMembers.length>0)overallVerdict="REJECT";else if(verdicts.some((v)=>v.verdict==="CONCERNS")||!cfg.vetoPriority&&rejectingMembers.length>0)overallVerdict="CONCERNS";else overallVerdict="APPROVE";let unresolvedConflicts=detectConflicts2(verdicts),rejectingSet=new Set(rejectingMembers),vetoFindings=verdicts.filter((v)=>rejectingSet.has(v.agent)).flatMap((v)=>v.findings),requiredFixes=vetoFindings.filter((f)=>f.severity==="CRITICAL"||f.severity==="HIGH"||f.severity==="MEDIUM"),advisoryFindings=[...vetoFindings.filter((f)=>f.severity==="LOW"),...verdicts.filter((v)=>!rejectingSet.has(v.agent)).flatMap((v)=>v.findings)],blockingConcernsCount=promoteBlockingConcerns(verdicts,rejectingSet,requiredFixes,advisoryFindings),advisoryNotes=[];if(advisoryFindings.length>0)advisoryNotes.push(`Final council found ${advisoryFindings.length} advisory finding(s). Review before project close.`);if(quorumSize<3)advisoryNotes.push(`Final council quorum is ${quorumSize} members - dispatch additional project-scoped council members before closing the project.`);let allCriteriaMet=new Set(verdicts.flatMap((v)=>v.criteriaUnmet)).size===0&&verdicts.length>0,unifiedFeedbackMd=buildFinalCouncilFeedback(projectSummary,overallVerdict,rejectingMembers,requiredFixes,advisoryFindings,unresolvedConflicts,roundNumber,cfg.maxRounds,blockingConcernsCount);return{scope:"project",timestamp,overallVerdict,vetoedBy:rejectingMembers.length>0?rejectingMembers:null,memberVerdicts:verdicts,unresolvedConflicts,requiredFixes,advisoryFindings,advisoryNotes,unifiedFeedbackMd,roundNumber,allCriteriaMet,quorumSize,evidencePath:".swarm/evidence/final-council.json",blockingConcernsCount,projectSummary}}function buildFinalCouncilFeedback(projectSummary,verdict,vetoedBy,requiredFixes,advisoryFindings,conflicts,roundNumber,maxRounds,blockingConcernsCount=0){let lines=[`## Final Council Review - Round ${roundNumber}/${maxRounds}`,`**Scope:** completed project **Overall verdict:** ${verdict}`,""];if(projectSummary)lines.push(`**Project Summary:** ${projectSummary}`),lines.push("");if(blockingConcernsCount>0)lines.push(`> ⚠️ **BLOCKING CONCERNS**: ${blockingConcernsCount} HIGH/CRITICAL finding(s) from CONCERNS members require investigation and resolution before project close.`),lines.push("");if(vetoedBy.length>0)lines.push(`> BLOCKED: project close is blocked by ${vetoedBy.join(", ")}`),lines.push("");if(requiredFixes.length>0){lines.push("### Required Fixes (must resolve before project close)");for(let f of requiredFixes)lines.push(`- **[${f.severity}]** \`${f.location}\` - ${f.detail}`,` _Evidence:_ ${f.evidence}`);lines.push("")}if(conflicts.length>0){lines.push("### Conflicts to Resolve"),lines.push("_The following council members gave contradictory project-close instructions. Architect must resolve before closing the project._");for(let c of conflicts)lines.push(`- ${c}`);lines.push("")}if(advisoryFindings.length>0){lines.push("### Advisory Findings (non-blocking)");for(let f of advisoryFindings)lines.push(`- **[${f.severity}]** \`${f.location}\` - ${f.detail}`);lines.push("")}if(verdict==="APPROVE")lines.push("> Final council approved. Project may proceed to close.");else if(roundNumber>=maxRounds)lines.push(`> Max rounds (${maxRounds}) reached. Escalate to user - do not close the project automatically.`);return lines.join(`
6183
- `)}init_zod();init_task_file();import{existsSync as existsSync115,mkdirSync as mkdirSync58,readFileSync as readFileSync89}from"node:fs";import{join as join187}from"node:path";var COUNCIL_DIR=".swarm/council",CouncilCriteriaSchema=exports_external.object({taskId:exports_external.string(),criteria:exports_external.array(exports_external.object({id:exports_external.string(),description:exports_external.string(),mandatory:exports_external.boolean()})),declaredAt:exports_external.string()});async function writeCriteria(workingDir,taskId,criteria){let dir=join187(workingDir,COUNCIL_DIR);mkdirSync58(dir,{recursive:!0});let payload={taskId,criteria,declaredAt:new Date().toISOString()};await atomicWriteFile(join187(dir,`${safeId(taskId)}.json`),JSON.stringify(payload,null,2))}function readCriteria(workingDir,taskId){let filePath=join187(workingDir,COUNCIL_DIR,`${safeId(taskId)}.json`);if(!existsSync115(filePath))return null;try{return CouncilCriteriaSchema.parse(JSON.parse(readFileSync89(filePath,"utf-8")))}catch{return null}}function safeId(id){return id.replace(/[^a-zA-Z0-9_-]/g,"_")}init_state2();init_create_tool();init_resolve_working_directory();var FindingSchema=exports_external.object({severity:exports_external.enum(["CRITICAL","HIGH","MEDIUM","LOW"]),category:exports_external.string().min(1),location:exports_external.string(),detail:exports_external.string(),evidence:exports_external.string()}),VerdictSchema=exports_external.object({agent:exports_external.enum(["critic","reviewer","sme","test_engineer","explorer"]),verdict:exports_external.enum(["APPROVE","CONCERNS","REJECT"]),verdictRound:exports_external.number().int().min(1).max(10).optional(),confidence:exports_external.number().min(0).max(1),findings:exports_external.array(FindingSchema),criteriaAssessed:exports_external.array(exports_external.string()),criteriaUnmet:exports_external.array(exports_external.string()),durationMs:exports_external.number().nonnegative()}),ArgsSchema=exports_external.object({taskId:exports_external.string().min(1).regex(/^\d+\.\d+(\.\d+)*$/,'Task ID must be in N.M or N.M.P format (e.g. "1.1")'),swarmId:exports_external.string().min(1),roundNumber:exports_external.number().int().min(1).max(10).default(1),verdicts:exports_external.array(VerdictSchema).min(1).max(5),working_directory:exports_external.string().optional()}),submit_council_verdicts=createSwarmTool({description:"Submit pre-collected council member verdicts for synthesis. PREREQUISITE — "+"you MUST dispatch each council member (critic, reviewer, sme, test_engineer, explorer) as separate Agent tasks and collect their verdict responses BEFORE "+"calling this tool. This tool performs synthesis only — it does NOT dispatch, "+"invoke, or contact council members. Calling this tool without first collecting real verdicts from dispatched agents constitutes a council bypass. Returns the synthesized verdict, required fixes, and a quorum report showing which members voted and which were absent. Architect-only. Config-gated via council.enabled.",args:{taskId:exports_external.string().min(1).regex(/^\d+\.\d+(\.\d+)*$/,"Task ID must be in N.M or N.M.P format").describe('Task ID being evaluated, e.g. "1.1", "1.2.3"'),swarmId:exports_external.string().min(1).describe('Swarm identifier, e.g. "mega"'),roundNumber:exports_external.number().int().min(1).max(10).optional().describe("1-indexed round number. Defaults to 1."),verdicts:exports_external.array(exports_external.object({agent:exports_external.enum(["critic","reviewer","sme","test_engineer","explorer"]),verdict:exports_external.enum(["APPROVE","CONCERNS","REJECT"]),verdictRound:exports_external.number().int().min(1).max(10).optional(),confidence:exports_external.number().min(0).max(1),findings:exports_external.array(exports_external.object({severity:exports_external.enum(["CRITICAL","HIGH","MEDIUM","LOW"]),category:exports_external.string().min(1),location:exports_external.string(),detail:exports_external.string(),evidence:exports_external.string()})),criteriaAssessed:exports_external.array(exports_external.string()),criteriaUnmet:exports_external.array(exports_external.string()),durationMs:exports_external.number()})).min(1).max(5).describe("Array of CouncilMemberVerdict objects. Must include between 1 and 5 entries, one per participating member (critic, reviewer, sme, test_engineer, explorer)."),working_directory:exports_external.string().optional().describe("Explicit project root directory. When provided, .swarm/council/ and .swarm/evidence/ are resolved relative to this path instead of the plugin context directory.")},async execute(args2,directory,ctx){let parsed=ArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,reason:"invalid arguments",errors:parsed.error.issues.map((i)=>({path:i.path.join("."),message:i.message}))},null,2);let input=parsed.data,dirResult=resolveWorkingDirectory(input.working_directory,directory);if(!dirResult.success)return JSON.stringify({success:!1,reason:dirResult.message},null,2);let workingDir=dirResult.directory,config3=loadPluginConfig(workingDir);if(!config3.council?.enabled)return JSON.stringify({success:!1,reason:"council feature is disabled — set council.enabled: true in .opencode/opencode-swarm.json to enable"},null,2);let effectiveMinimum=config3.council?.requireAllMembers?5:config3.council?.minimumMembers??3,ALL_MEMBERS=["critic","reviewer","sme","test_engineer","explorer"],distinctMembers=new Set(input.verdicts.map((v)=>v.agent)),membersVoted=[...distinctMembers],membersAbsent=ALL_MEMBERS.filter((m)=>!distinctMembers.has(m)),sessionID=ctx?.sessionID,session=sessionID?getAgentSession(sessionID):void 0,requirementKey=`${input.taskId}:${input.roundNumber}`;if(session&&!session.pendingCouncilRequirements)session.pendingCouncilRequirements=new Map;let pendingRequirements=session?.pendingCouncilRequirements?.get(requirementKey);if(pendingRequirements&&pendingRequirements.size>0){let stillMissingMembers=[...pendingRequirements].filter((member)=>!distinctMembers.has(member));if(stillMissingMembers.length>0)return JSON.stringify({success:!1,reason:"cherry_pick_detected",message:`Incomplete re-dispatch: ${stillMissingMembers.join(", ")} were required from the previous insufficient_quorum response but are still absent. Dispatch ALL absent members in one parallel batch.`,stillMissingMembers,membersProvided:membersVoted},null,2)}if(membersVoted.length<effectiveMinimum){if(session?.pendingCouncilRequirements)session.pendingCouncilRequirements.set(requirementKey,new Set(membersAbsent));return JSON.stringify({success:!1,reason:"insufficient_quorum",message:`Council quorum not met: ${membersVoted.length} of ${effectiveMinimum} required members provided verdicts. Members voted: [${membersVoted.join(", ")}]. Members absent: [${membersAbsent.join(", ")}]. Dispatch the absent council members as Agent tasks and collect their verdicts before calling submit_council_verdicts.`,membersVoted,membersAbsent,quorumRequired:effectiveMinimum},null,2)}let staleVerdicts=input.roundNumber>1?input.verdicts.filter((v)=>(v.verdictRound??1)<input.roundNumber):[];if(staleVerdicts.length>0)return JSON.stringify({success:!1,reason:"stale_verdict_detected",message:`Round ${input.roundNumber} requires fresh verdicts. One or more submitted verdicts are from an older round.`,staleVerdicts:staleVerdicts.map((v)=>({agent:v.agent,verdictRound:v.verdictRound}))},null,2);let criteria=readCriteria(workingDir,input.taskId),verdicts=input.verdicts,synthesis=synthesizeCouncilVerdicts(input.taskId,input.swarmId,verdicts,criteria,input.roundNumber,config3.council),dissenters=synthesis.memberVerdicts.filter((v)=>v.verdict==="CONCERNS"||v.verdict==="REJECT").map((v)=>v.agent);if(session?.pendingCouncilRequirements){if(session.pendingCouncilRequirements.delete(requirementKey),dissenters.length>0){let nextRoundKey=`${input.taskId}:${input.roundNumber+1}`;session.pendingCouncilRequirements.set(nextRoundKey,new Set(dissenters))}}if(synthesis.overallVerdict==="CONCERNS"&&synthesis.blockingConcernsCount>0)return JSON.stringify({success:!1,reason:"blocking_concerns_unresolved",overallVerdict:synthesis.overallVerdict,blockingConcernsCount:synthesis.blockingConcernsCount,requiredFixes:synthesis.requiredFixes,unifiedFeedbackMd:synthesis.unifiedFeedbackMd,message:`Council returned CONCERNS with ${synthesis.blockingConcernsCount} HIGH/CRITICAL finding(s) promoted to requiredFixes. These must be resolved before the task can advance. Do NOT write evidence or proceed — address every requiredFix and resubmit.`},null,2);await writeCouncilEvidence(workingDir,synthesis);try{if(sessionID){if(session)pushCouncilAdvisory(session,synthesis)}}catch{}return JSON.stringify({success:!0,overallVerdict:synthesis.overallVerdict,vetoedBy:synthesis.vetoedBy,roundNumber:synthesis.roundNumber,allCriteriaMet:synthesis.allCriteriaMet,requiredFixesCount:synthesis.requiredFixes.length,advisoryFindingsCount:synthesis.advisoryFindings.length,unresolvedConflictsCount:synthesis.unresolvedConflicts.length,membersVoted,membersAbsent,quorumSize:membersVoted.length,quorumMet:!0,unifiedFeedbackMd:synthesis.unifiedFeedbackMd},null,2)}});init_zod();init_loader();import*as fs132 from"node:fs";import*as path233 from"node:path";var ADVISORY_HEADER="[general_council] (advisory; not blocking)";function pushGeneralCouncilAdvisory(session,result){if(!session)return;let body=renderAdvisoryBody(result);if(!body)return;pushAdvisory(session,`${ADVISORY_HEADER}
6184
+ `)}init_zod();init_task_file();import{existsSync as existsSync115,mkdirSync as mkdirSync58,readFileSync as readFileSync89}from"node:fs";import{join as join187}from"node:path";var COUNCIL_DIR=".swarm/council",CouncilCriteriaSchema=exports_external.object({taskId:exports_external.string(),criteria:exports_external.array(exports_external.object({id:exports_external.string(),description:exports_external.string(),mandatory:exports_external.boolean()})),declaredAt:exports_external.string()});async function writeCriteria(workingDir,taskId,criteria){let dir=join187(workingDir,COUNCIL_DIR);mkdirSync58(dir,{recursive:!0});let payload={taskId,criteria,declaredAt:new Date().toISOString()};await atomicWriteFile(join187(dir,`${safeId(taskId)}.json`),JSON.stringify(payload,null,2))}function readCriteria(workingDir,taskId){let filePath=join187(workingDir,COUNCIL_DIR,`${safeId(taskId)}.json`);if(!existsSync115(filePath))return null;try{return CouncilCriteriaSchema.parse(JSON.parse(readFileSync89(filePath,"utf-8")))}catch{return null}}function safeId(id){return id.replace(/[^a-zA-Z0-9_-]/g,"_")}init_state2();init_create_tool();init_resolve_working_directory();var FindingSchema=exports_external.object({severity:exports_external.enum(["CRITICAL","HIGH","MEDIUM","LOW"]),category:exports_external.string().min(1),location:exports_external.string(),detail:exports_external.string(),evidence:exports_external.string()}),VerdictSchema=exports_external.object({agent:exports_external.enum(["critic","reviewer","sme","test_engineer","explorer"]),verdict:exports_external.enum(["APPROVE","CONCERNS","REJECT"]),verdictRound:exports_external.number().int().min(1).max(10).optional(),confidence:exports_external.number().min(0).max(1),findings:exports_external.array(FindingSchema),criteriaAssessed:exports_external.array(exports_external.string()),criteriaUnmet:exports_external.array(exports_external.string()),durationMs:exports_external.number().nonnegative()}),ArgsSchema=exports_external.object({taskId:exports_external.string().min(1).regex(/^\d+\.\d+(\.\d+)*$/,'Task ID must be in N.M or N.M.P format (e.g. "1.1")'),swarmId:exports_external.string().min(1),roundNumber:exports_external.number().int().min(1).max(10).default(1),verdicts:exports_external.array(VerdictSchema).min(1).max(5),working_directory:exports_external.string().optional()}),submit_council_verdicts=createSwarmTool({description:"Submit pre-collected council member verdicts for synthesis. PREREQUISITE — "+"you MUST dispatch each council member (critic, reviewer, sme, test_engineer, explorer) as separate Agent tasks and collect their verdict responses BEFORE "+"calling this tool. This tool performs synthesis only — it does NOT dispatch, "+"invoke, or contact council members. Calling this tool without first collecting real verdicts from dispatched agents constitutes a council bypass. Returns the synthesized verdict, required fixes, and a quorum report showing which members voted and which were absent. Architect-only. Config-gated via council.enabled.",args:{taskId:exports_external.string().min(1).regex(/^\d+\.\d+(\.\d+)*$/,"Task ID must be in N.M or N.M.P format").describe('Task ID being evaluated, e.g. "1.1", "1.2.3"'),swarmId:exports_external.string().min(1).describe('Swarm identifier, e.g. "mega"'),roundNumber:exports_external.number().int().min(1).max(10).optional().describe("1-indexed round number. Defaults to 1."),verdicts:exports_external.array(exports_external.object({agent:exports_external.enum(["critic","reviewer","sme","test_engineer","explorer"]),verdict:exports_external.enum(["APPROVE","CONCERNS","REJECT"]),verdictRound:exports_external.number().int().min(1).max(10).optional(),confidence:exports_external.number().min(0).max(1),findings:exports_external.array(exports_external.object({severity:exports_external.enum(["CRITICAL","HIGH","MEDIUM","LOW"]),category:exports_external.string().min(1),location:exports_external.string(),detail:exports_external.string(),evidence:exports_external.string()})),criteriaAssessed:exports_external.array(exports_external.string()),criteriaUnmet:exports_external.array(exports_external.string()),durationMs:exports_external.number()})).min(1).max(5).describe("Array of CouncilMemberVerdict objects. Must include between 1 and 5 entries, one per participating member (critic, reviewer, sme, test_engineer, explorer)."),working_directory:exports_external.string().optional().describe("Explicit project root directory. When provided, .swarm/council/ and .swarm/evidence/ are resolved relative to this path instead of the plugin context directory.")},async execute(args2,directory,ctx){let parsed=ArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,reason:"invalid arguments",errors:parsed.error.issues.map((i)=>({path:i.path.join("."),message:i.message}))},null,2);let input=parsed.data,dirResult=resolveWorkingDirectory(input.working_directory,directory);if(!dirResult.success)return JSON.stringify({success:!1,reason:dirResult.message},null,2);let workingDir=dirResult.directory,config3=loadPluginConfig(workingDir);if(!config3.council?.enabled)return JSON.stringify({success:!1,reason:"council feature is disabled — set council.enabled: true in .opencode/opencode-swarm.json to enable"},null,2);let effectiveMinimum=config3.council?.requireAllMembers?5:config3.council?.minimumMembers??3,ALL_MEMBERS=["critic","reviewer","sme","test_engineer","explorer"],distinctMembers=new Set(input.verdicts.map((v)=>v.agent)),membersVoted=[...distinctMembers],membersAbsent=ALL_MEMBERS.filter((m)=>!distinctMembers.has(m)),sessionID=ctx?.sessionID,session=sessionID?getAgentSession(sessionID):void 0,requirementKey=`${input.taskId}:${input.roundNumber}`;if(session&&!session.pendingCouncilRequirements)session.pendingCouncilRequirements=new Map;let pendingRequirements=session?.pendingCouncilRequirements?.get(requirementKey);if(pendingRequirements&&pendingRequirements.size>0){let stillMissingMembers=[...pendingRequirements].filter((member)=>!distinctMembers.has(member));if(stillMissingMembers.length>0)return JSON.stringify({success:!1,reason:"cherry_pick_detected",message:`Incomplete re-dispatch: ${stillMissingMembers.join(", ")} were required from the previous insufficient_quorum response but are still absent. Dispatch ALL absent members in one parallel batch.`,stillMissingMembers,membersProvided:membersVoted},null,2)}if(membersVoted.length<effectiveMinimum){if(session?.pendingCouncilRequirements)session.pendingCouncilRequirements.set(requirementKey,new Set(membersAbsent));return JSON.stringify({success:!1,reason:"insufficient_quorum",message:`Council quorum not met: ${membersVoted.length} of ${effectiveMinimum} required members provided verdicts. Members voted: [${membersVoted.join(", ")}]. Members absent: [${membersAbsent.join(", ")}]. Dispatch the absent council members as Agent tasks and collect their verdicts before calling submit_council_verdicts.`,membersVoted,membersAbsent,quorumRequired:effectiveMinimum},null,2)}let staleVerdicts=input.roundNumber>1?input.verdicts.filter((v)=>(v.verdictRound??input.roundNumber)<input.roundNumber):[];if(staleVerdicts.length>0)return JSON.stringify({success:!1,reason:"stale_verdict_detected",message:`Round ${input.roundNumber} requires fresh verdicts. One or more submitted verdicts are from an older round.`,staleVerdicts:staleVerdicts.map((v)=>({agent:v.agent,verdictRound:v.verdictRound}))},null,2);let criteria=readCriteria(workingDir,input.taskId),verdicts=input.verdicts,synthesis=synthesizeCouncilVerdicts(input.taskId,input.swarmId,verdicts,criteria,input.roundNumber,config3.council),dissenters=synthesis.memberVerdicts.filter((v)=>v.verdict==="CONCERNS"||v.verdict==="REJECT").map((v)=>v.agent);if(session?.pendingCouncilRequirements){if(session.pendingCouncilRequirements.delete(requirementKey),dissenters.length>0){let nextRoundKey=`${input.taskId}:${input.roundNumber+1}`;session.pendingCouncilRequirements.set(nextRoundKey,new Set(dissenters))}}if(synthesis.overallVerdict==="CONCERNS"&&synthesis.blockingConcernsCount>0)return JSON.stringify({success:!1,reason:"blocking_concerns_unresolved",overallVerdict:synthesis.overallVerdict,blockingConcernsCount:synthesis.blockingConcernsCount,requiredFixes:synthesis.requiredFixes,unifiedFeedbackMd:synthesis.unifiedFeedbackMd,message:`Council returned CONCERNS with ${synthesis.blockingConcernsCount} HIGH/CRITICAL finding(s) promoted to requiredFixes. These must be resolved before the task can advance. Do NOT write evidence or proceed — address every requiredFix and resubmit.`},null,2);await writeCouncilEvidence(workingDir,synthesis);try{if(sessionID){if(session)pushCouncilAdvisory(session,synthesis)}}catch{}return JSON.stringify({success:!0,overallVerdict:synthesis.overallVerdict,vetoedBy:synthesis.vetoedBy,roundNumber:synthesis.roundNumber,allCriteriaMet:synthesis.allCriteriaMet,requiredFixesCount:synthesis.requiredFixes.length,advisoryFindingsCount:synthesis.advisoryFindings.length,unresolvedConflictsCount:synthesis.unresolvedConflicts.length,membersVoted,membersAbsent,quorumSize:membersVoted.length,quorumMet:!0,unifiedFeedbackMd:synthesis.unifiedFeedbackMd},null,2)}});init_zod();init_loader();import*as fs132 from"node:fs";import*as path233 from"node:path";var ADVISORY_HEADER="[general_council] (advisory; not blocking)";function pushGeneralCouncilAdvisory(session,result){if(!session)return;let body=renderAdvisoryBody(result);if(!body)return;pushAdvisory(session,`${ADVISORY_HEADER}
6184
6185
  ${body}`)}function renderAdvisoryBody(result){return result.synthesis.trim()}var EXPLICIT_DISAGREEMENT_MARKERS=["i disagree with","i would push back on","contrary to","this contradicts","unlike "],STRONG_RECOMMENDATION_MARKERS=["recommend","best approach","should use","i suggest","the answer is","the right choice is"];function tokenize2(text){return text.toLowerCase().replace(/[^a-z0-9\s]/g," ").split(/\s+/).filter((t)=>t.length>=3)}function termOverlap(a,b){let tokensA=new Set(tokenize2(a)),tokensB=new Set(tokenize2(b));if(tokensA.size===0||tokensB.size===0)return 0;let intersection3=0;for(let t of tokensA)if(tokensB.has(t))intersection3++;let union3=tokensA.size+tokensB.size-intersection3;return union3===0?0:intersection3/union3}function extractMarkerSentence(response,markers){let lower=response.toLowerCase(),sentences=response.split(/(?<=[.!?])\s+/);for(let sentence of sentences){let sentLower=sentence.toLowerCase();if(markers.some((m)=>sentLower.includes(m)))return sentence.trim()}for(let marker of markers){let idx=lower.indexOf(marker);if(idx!==-1){let slice=response.slice(idx,idx+200);return slice.split(/\n/)[0]?.trim()??slice.trim()}}return null}function dedupeByTopic(disagreements){let result=[];for(let d of disagreements){let topicLower=d.topic.toLowerCase(),existing=result.find((r)=>r.topic.toLowerCase().includes(topicLower)||topicLower.includes(r.topic.toLowerCase()));if(existing){for(let pos of d.positions)if(!existing.positions.some((p)=>p.memberId===pos.memberId))existing.positions.push(pos)}else result.push(d)}return result}function detectExplicitMarkers(responses){let out=[];for(let member of responses){let markerSentence=extractMarkerSentence(member.response,EXPLICIT_DISAGREEMENT_MARKERS);if(!markerSentence)continue;let position={memberId:member.memberId,claim:markerSentence,evidence:member.sources[0]?.url??"(no source cited in marker sentence)"};out.push({topic:markerSentence.slice(0,80),positions:[position]})}return out}function extractRecommendation(response){return extractMarkerSentence(response,STRONG_RECOMMENDATION_MARKERS)}function detectClaimDivergence(responses){let recommendations=[];for(let member of responses){let rec=extractRecommendation(member.response);if(!rec)continue;recommendations.push({memberId:member.memberId,text:rec,evidence:member.sources[0]?.url??"(no source cited)"})}let out=[];for(let i=0;i<recommendations.length;i++)for(let j=i+1;j<recommendations.length;j++){let a=recommendations[i],b=recommendations[j];if(!a||!b)continue;let topicOverlap=termOverlap(a.text,b.text);if(topicOverlap>0.4)continue;if(topicOverlap>0&&topicOverlap<0.3){let topic=`${a.text.slice(0,50)} vs ${b.text.slice(0,50)}`;out.push({topic,positions:[{memberId:a.memberId,claim:a.text,evidence:a.evidence},{memberId:b.memberId,claim:b.text,evidence:b.evidence}]})}}return out}function detectDisagreements(responses){if(!Array.isArray(responses)||responses.length<2)return[];let safeResponses=responses.filter((r)=>typeof r?.memberId==="string"&&typeof r?.response==="string"),explicit=detectExplicitMarkers(safeResponses),divergent=detectClaimDivergence(safeResponses),combined=[...explicit,...divergent];return dedupeByTopic(combined).slice(0,10)}var CONSENSUS_WEIGHT_THRESHOLD=0.6;function tokenize3(text){return text.toLowerCase().replace(/[^a-z0-9\s]/g," ").split(/\s+/).filter((t)=>t.length>=4)}function similarity(a,b){let tokensA=new Set(tokenize3(a)),tokensB=new Set(tokenize3(b));if(tokensA.size===0||tokensB.size===0)return 0;let intersection3=0;for(let t of tokensA)if(tokensB.has(t))intersection3++;let union3=tokensA.size+tokensB.size-intersection3;return union3===0?0:intersection3/union3}function extractClaims(response){return response.split(/(?<=[.!?])\s+/).map((s)=>s.trim()).filter((s)=>s.length>=30&&s.length<=400)}function buildConsensusClusters(responses){if(responses.length<2)return[];let totalMembers=responses.length,clusters=[];for(let member of responses){let confidence=clamp012(member.confidence??0.5),claims=extractClaims(member.response??"");for(let claim of claims){let assigned=!1;for(let cluster of clusters)if(similarity(cluster.representative,claim)>=0.5){if(!cluster.memberIds.has(member.memberId))cluster.weightedAgreement+=confidence,cluster.memberIds.add(member.memberId);if(claim.length>cluster.representative.length)cluster.representative=claim;assigned=!0;break}if(!assigned)clusters.push({representative:claim,weightedAgreement:confidence,memberIds:new Set([member.memberId])})}}return clusters.filter((c)=>c.memberIds.size>=2&&c.weightedAgreement/totalMembers>=CONSENSUS_WEIGHT_THRESHOLD).sort((a,b)=>b.weightedAgreement-a.weightedAgreement||b.memberIds.size-a.memberIds.size).map((c)=>c.representative)}function clamp012(n){if(typeof n!=="number"||Number.isNaN(n))return 0;if(n<0)return 0;if(n>1)return 1;return n}function computePersistingDisagreements(disagreements,round2){if(disagreements.length===0)return[];if(round2.length===0)return disagreements;return disagreements.filter((d)=>{let disputants=new Set(d.positions.map((p)=>p.memberId));return!round2.some((r)=>{if(!disputants.has(r.memberId))return!1;if(!r.disagreementTopics?.includes(d.topic))return!1;return/\bconcede\b/i.test(r.response??"")})})}function dedupeSources(round1,round2){let seen=new Set,out=[],allSources=[...round1,...round2].flatMap((r)=>r.sources??[]);for(let src of allSources){if(!src?.url)continue;if(seen.has(src.url))continue;seen.add(src.url),out.push(src)}return out}function renderSynthesisMarkdown(question,mode,roundsCompleted,members,consensusPoints,persistingDisagreements,allSources){let memberLines=members.map((m)=>`- ${m.memberId} (${m.model}, ${m.role})`).join(`
6185
6186
  `),consensusBlock=consensusPoints.length>0?consensusPoints.map((c)=>`- ${c}`).join(`
6186
6187
  `):"_No consensus claims reached the weighted-agreement threshold._",disagreementsBlock=persistingDisagreements.length>0?persistingDisagreements.map((d)=>`- **${d.topic}**
@@ -6353,7 +6354,7 @@ ${task.acceptance??""}`,matchesFreeText=idPattern.test(taskText),matchesFrRefs=t
6353
6354
  `);for(let i=0;i<lines.length;i++){let line=lines[i];if(regex.test(line)){if(total++,matches.length<opts.maxResults)matches.push({file:file3,lineNumber:i+1,lineText:truncateLine(line,opts.maxLines)});regex.lastIndex=0}}}return{matches,truncated:truncated||total>opts.maxResults,total,query:opts.query,mode:opts.mode,maxResults:opts.maxResults,engine:"fallback",warning:"Fallback search uses bounded filesystem traversal and does not fully emulate ripgrep gitignore behavior."}}var search=createSwarmTool({description:"Search for text within workspace files using ripgrep-style interface. Supports literal and regex search modes with glob include/exclude filtering. Returns structured JSON output with file paths, line numbers, and line content.",args:{query:exports_external.string().describe("Search query string (literal or regex depending on mode)"),mode:exports_external.enum(["literal","regex"]).default("literal").describe("Search mode: literal for exact string match, regex for regular expression"),include:exports_external.string().optional().describe('Glob pattern for files to include (e.g., "*.ts", "src/**/*.js")'),exclude:exports_external.string().optional().describe('Glob pattern for files to exclude (e.g., "node_modules/**", "*.test.ts")'),max_results:exports_external.number().default(DEFAULT_MAX_RESULTS4).describe("Maximum number of matches to return"),max_lines:exports_external.number().default(DEFAULT_MAX_LINES).describe("Maximum characters per line in results")},execute:async(args2,directory)=>{let query,mode="literal",include,exclude,maxResults=DEFAULT_MAX_RESULTS4,maxLines=DEFAULT_MAX_LINES;try{let obj=args2;query=String(obj.query??""),mode=obj.mode==="regex"?"regex":"literal",include=typeof obj.include==="string"?obj.include:void 0,exclude=typeof obj.exclude==="string"?obj.exclude:void 0;let rawMaxResults=typeof obj.max_results==="number"?obj.max_results:DEFAULT_MAX_RESULTS4,sanitizedMaxResults=Number.isNaN(rawMaxResults)?DEFAULT_MAX_RESULTS4:rawMaxResults;maxResults=Math.min(Math.max(0,sanitizedMaxResults),HARD_CAP_RESULTS4);let rawMaxLines=typeof obj.max_lines==="number"?obj.max_lines:DEFAULT_MAX_LINES,sanitizedMaxLines=Number.isNaN(rawMaxLines)?DEFAULT_MAX_LINES:rawMaxLines;maxLines=Math.min(Math.max(0,sanitizedMaxLines),HARD_CAP_LINES)}catch{return JSON.stringify({error:!0,type:"invalid-query",message:"Could not parse search arguments"},null,2)}if(!query||query.trim()==="")return JSON.stringify({error:!0,type:"invalid-query",message:"Query cannot be empty"},null,2);if(query.length>MAX_QUERY_LENGTH)return JSON.stringify({error:!0,type:"invalid-query",message:`Query exceeds maximum length of ${MAX_QUERY_LENGTH} characters`},null,2);if(containsControlChars(query))return JSON.stringify({error:!0,type:"invalid-query",message:"Query contains invalid control characters"},null,2);if(include&&containsPathTraversal(include))return JSON.stringify({error:!0,type:"path-escape",message:"Include pattern contains path traversal sequence"},null,2);if(exclude&&containsPathTraversal(exclude))return JSON.stringify({error:!0,type:"path-escape",message:"Exclude pattern contains path traversal sequence"},null,2);if(include&&containsWindowsAttacks4(include))return JSON.stringify({error:!0,type:"path-escape",message:"Include pattern contains invalid Windows-specific sequence"},null,2);if(exclude&&containsWindowsAttacks4(exclude))return JSON.stringify({error:!0,type:"path-escape",message:"Exclude pattern contains invalid Windows-specific sequence"},null,2);if(!fs163.existsSync(directory))return JSON.stringify({error:!0,type:"unknown",message:"Workspace directory does not exist"},null,2);let result;if(_internals185.resolveRipgrepBinary())result=await ripgrepSearch({query,mode,include,exclude,maxResults,maxLines,workspace:directory});else result=await fallbackSearch({query,mode,include,exclude,maxResults,maxLines,workspace:directory});if("error"in result&&result.error)return JSON.stringify(result,null,2);return JSON.stringify(result,null,2)}}),_internals185={resolvePackagedRipgrep,resolveExecutableFromPath,resolveRipgrepBinary,runExternalTool,fallbackSearch};init_secretscan();init_zod();init_qa_gate_profile();init_manager();init_utils3();init_create_tool();async function executeSetQaGates(args2,directory){let plan=await loadPlanJsonOnly(directory);if(!plan)return{success:!1,reason:"plan_json_unavailable",message:"Cannot configure QA gates: plan.json is missing or invalid. Create a plan first (e.g. via /swarm specify or save_plan)."};let planId=derivePlanId(plan);getOrCreateProfile(directory,planId,args2.project_type);let partial3={};for(let key of["reviewer","test_engineer","council_mode","sme_enabled","critic_pre_plan","hallucination_guard","sast_enabled","mutation_test","phase_council","drift_check","final_council"])if(args2[key]!==void 0)partial3[key]=args2[key];try{let updated=setGates(directory,planId,partial3);return{success:!0,plan_id:planId,message:`QA gates updated for plan_id=${planId}`,profile:{plan_id:updated.plan_id,gates:{...updated.gates},locked_at:updated.locked_at,locked_by_snapshot_seq:updated.locked_by_snapshot_seq,profile_hash:computeProfileHash(updated)}}}catch(err2){let msg=err2 instanceof Error?err2.message:String(err2),lower=msg.toLowerCase(),reason="set_gates_failed";if(lower.includes("locked"))reason="profile_locked";else if(lower.includes("ratchet"))reason="ratchet_violation";return{success:!1,reason,message:msg,plan_id:planId}}}var set_qa_gates=createSwarmTool({description:"Configure the QA gate profile for the current plan. Architect-only. Ratchet-tighter: can enable additional gates but cannot disable gates that are already enabled. Rejects all writes once the profile is locked (after critic approval). Creates the profile with defaults if none exists. plan_id is derived automatically from plan.json.",args:{reviewer:exports_external.boolean().optional().describe("Enable the reviewer gate (true) — cannot be disabled."),test_engineer:exports_external.boolean().optional().describe("Enable the test_engineer gate (true) — cannot be disabled once on."),council_mode:exports_external.boolean().optional().describe("Enable council mode — replaces per-task Stage B (reviewer + test_engineer) with the full 5-member council (critic, reviewer, sme, test_engineer, explorer) per task."),sme_enabled:exports_external.boolean().optional().describe("Enable SME consultation."),critic_pre_plan:exports_external.boolean().optional().describe("Enable critic_pre_plan review before plan approval."),hallucination_guard:exports_external.boolean().optional().describe("Enable hallucination_guard checks on plan and implementation claims."),sast_enabled:exports_external.boolean().optional().describe("Enable SAST scanning as a required QA gate."),mutation_test:exports_external.boolean().optional().describe("Enable the mutation-testing gate (default: off). Requires mutation tests to achieve a passing kill rate before phase completion; WARN verdict allows advancement, FAIL blocks."),phase_council:exports_external.boolean().optional().describe("Enable the phase_council gate (default: off). When on, a full 5-member council (critic, reviewer, sme, test_engineer, explorer) reviews all work completed in a phase holistically at phase_complete time. Requires council.enabled: true in config."),drift_check:exports_external.boolean().optional().describe("Enable drift verification gate (default: on). Blocks phase_complete until drift-verifier.json has an approved verdict. When disabled, drift verification is skipped entirely."),final_council:exports_external.boolean().optional().describe("Enable the final_council gate (default: off). When on, after all phases complete the architect dispatches critic, reviewer, sme, test_engineer, and explorer with project-scoped context, collects their CouncilMemberVerdict objects, and calls write_final_council_evidence. This is not General Council mode and does not require council.general.enabled."),project_type:exports_external.string().optional().describe('Project type label (e.g. "ts", "python"). Only applied when the profile is being created for the first time.')},execute:async(args2,directory)=>{return JSON.stringify(await executeSetQaGates(args2??{},directory),null,2)}});init_zod();init_skill_generator();init_create_tool();var skill_apply=createSwarmTool({description:"Activate a draft skill proposal (.swarm/skills/proposals/<slug>.md) into .opencode/skills/generated/<slug>/SKILL.md.",args:{slug:exports_external.string().min(1).describe("Slug of the proposal to activate."),force:exports_external.boolean().optional().default(!1).describe("Overwrite an existing active SKILL.md even if it lacks the generator stamp. Default false."),evaluate:exports_external.boolean().optional().default(!1).describe("Validate the proposal against .swarm/skills/evals/<slug> before activation. Default false."),confirm_unevaluated:exports_external.boolean().optional().default(!1).describe('Allow activation when evaluateSkillChange returns status "unevaluated" (no eval set exists). Default false — the activation is blocked with a surfaced reason so the caller can confirm. Generated skills auto-derive an eval stub from their source directives, so this only applies to non-directive skills with no stub.')},execute:async(args2,directory)=>{let a=args2??{};if(!a.slug||typeof a.slug!=="string")return JSON.stringify({activated:!1,reason:"slug required"});let result=await activateProposal(directory,a.slug,a.force??!1,{evaluate:a.evaluate??!1,confirmUnevaluated:a.confirm_unevaluated??!1});return JSON.stringify(result,null,2)}});init_zod();init_skill_generator();init_create_tool();var skill_generate=createSwarmTool({description:'Compile mature knowledge entries into a SKILL.md. mode="draft" writes a proposal under .swarm/skills/proposals; mode="active" writes the live skill under .opencode/skills/generated and stamps source entries.',args:{source_knowledge_ids:exports_external.array(exports_external.string()).optional().describe("Optional explicit knowledge ids to compile. If omitted, all mature candidates are clustered and emitted."),slug:exports_external.string().optional().describe("Optional slug for the FIRST cluster. Sanitized; rejected if invalid."),mode:exports_external.enum(["draft","active"]).default("draft"),force:exports_external.boolean().optional().default(!1),evaluate:exports_external.boolean().optional().default(!1).describe("Validate generated skill content against .swarm/skills/evals/<slug> before writing. Default false."),min_confidence:exports_external.number().min(0).max(1).optional(),min_confirmations:exports_external.number().int().min(1).max(50).optional()},execute:async(args2,directory)=>{let a=args2??{},result=await generateSkills({directory,mode:a.mode??"draft",slug:a.slug,sourceKnowledgeIds:a.source_knowledge_ids,force:a.force??!1,evaluate:a.evaluate??!1,minConfidence:a.min_confidence,minConfirmations:a.min_confirmations});return JSON.stringify(result,null,2)}});init_zod();init_config();init_schema();init_skill_improver();init_create_tool();var skill_improve=createSwarmTool({description:'Run the skill_improver capability under daily quota. Writes a proposal under .swarm/skill-improver/proposals/<timestamp>.md. With mode="draft_skills" it also drafts SKILL.md proposals for mature clusters. Quota is enforced via .swarm/skill-improver-quota.json.',args:{targets:exports_external.array(exports_external.enum(["skills","spec","architect_prompt","knowledge"])).optional(),mode:exports_external.enum(["proposal","draft_skills"]).optional(),max_calls:exports_external.number().int().min(1).max(100).optional().describe("Override the per-run reservation count (capped by daily max)."),evaluate:exports_external.boolean().optional().default(!1).describe('When mode="draft_skills", validate generated draft skills before writing proposals. Default false.')},execute:async(args2,directory,ctx)=>{let a=args2??{},{config:config3}=loadPluginConfigWithMeta(directory),parsed=SkillImproverConfigSchema.parse(config3.skill_improver??{}),enrichmentConfig=KnowledgeConfigSchema.parse(config3.knowledge??{}).enrichment??{max_calls_per_day:30,quota_window:"utc"};if(!parsed.enabled)return JSON.stringify({ran:!1,reason:'skill_improver is disabled. Set "skill_improver.enabled": true in opencode-swarm config to use this tool.'},null,2);let result=await runSkillImprover({directory,config:parsed,targets:a.targets,mode:a.mode,maxCalls:a.max_calls,sessionId:ctx?.sessionID,enrichmentQuota:{maxCalls:enrichmentConfig.max_calls_per_day,window:enrichmentConfig.quota_window},evaluateDrafts:a.evaluate??!1});return JSON.stringify(result,null,2)}});init_zod();init_skill_generator();init_create_tool();var skill_inspect=createSwarmTool({description:"Read a generated skill (active or draft) and return its full markdown body and metadata.",args:{slug:exports_external.string().min(1).describe("Slug of the skill to inspect."),prefer:exports_external.enum(["auto","proposal","active"]).optional().default("auto")},execute:async(args2,directory)=>{let a=args2??{};if(!a.slug||typeof a.slug!=="string")return JSON.stringify({found:!1,reason:"slug required"});let result=await inspectSkill(directory,a.slug,a.prefer??"auto");return JSON.stringify(result,null,2)}});init_skill_generator();init_create_tool();var skill_list=createSwarmTool({description:"List generated skill drafts (under .swarm/skills/proposals) and active generated skills (under .opencode/skills/generated).",args:{},execute:async(_args,directory)=>{let result=await listSkills(directory);return JSON.stringify(result,null,2)}});init_zod();init_skill_generator();init_create_tool();var skill_regenerate=createSwarmTool({description:"Regenerate an active skill by re-clustering its source knowledge entries and updating the SKILL.md in place.",args:{slug:exports_external.string().min(1).describe("Slug of the active skill to regenerate."),evaluate:exports_external.boolean().optional().default(!1).describe("Validate regenerated content against .swarm/skills/evals/<slug> before writing. Default false.")},execute:async(args2,directory)=>{let a=args2??{};if(!a.slug||typeof a.slug!=="string")return JSON.stringify({regenerated:!1,reason:"slug required"});let result=await regenerateSkill(directory,a.slug,{evaluate:a.evaluate??!1});return JSON.stringify(result,null,2)}});init_zod();init_skill_generator();init_create_tool();var skill_retire=createSwarmTool({description:"Retire a generated skill by adding a retired.marker file. Retired skills are excluded from scoring and injection.",args:{slug:exports_external.string().min(1).describe("Slug of the active skill to retire."),reason:exports_external.string().optional().describe("Optional reason for retirement.")},execute:async(args2,directory)=>{let a=args2??{};if(!a.slug||typeof a.slug!=="string")return JSON.stringify({retired:!1,reason:"slug required"});let result=await retireSkill(directory,a.slug,a.reason);return JSON.stringify(result,null,2)}});init_zod();init_config();init_schema();init_create_tool();import{mkdir as mkdir50,rename as rename20,writeFile as writeFile30}from"node:fs/promises";import*as path271 from"node:path";var MAX_SPEC_BYTES2=262144,spec_write=createSwarmTool({description:"Write the canonical project spec to .swarm/spec.md. Atomic write, size-bounded (256 KiB), heading-required. Honors spec_writer.allow_spec_write.",args:{content:exports_external.string().min(20).max(MAX_SPEC_BYTES2),mode:exports_external.enum(["replace","append"]).optional().default("replace")},execute:async(args2,directory)=>{let a=args2??{},content=a.content,mode=a.mode??"replace";if(typeof content!=="string"||content.length<20)return JSON.stringify({written:!1,reason:"content must be a string >=20 chars"});if(content.length>MAX_SPEC_BYTES2)return JSON.stringify({written:!1,reason:`content exceeds ${MAX_SPEC_BYTES2} bytes`});let{config:config3}=loadPluginConfigWithMeta(directory);if(!SpecWriterConfigSchema.parse(config3.spec_writer??{}).allow_spec_write)return JSON.stringify({written:!1,reason:"spec_writer.allow_spec_write is false"},null,2);if(content.indexOf("\x00")!==-1)return JSON.stringify({written:!1,reason:"content contains null byte"},null,2);if(!/^#\s+/m.test(content))return JSON.stringify({written:!1,reason:'spec must contain at least one top-level "# Heading"'},null,2);let target=path271.join(directory,".swarm","spec.md");await mkdir50(path271.dirname(target),{recursive:!0});let tmp=`${target}.tmp-${process.pid}-${Date.now()}`,finalContent=content;if(mode==="append")try{if(finalContent=`${(await(await import("node:fs/promises")).readFile(target,"utf-8")).replace(/\s+$/,"")}
6354
6355
 
6355
6356
  ${content}
6356
- `,finalContent.length>MAX_SPEC_BYTES2)return JSON.stringify({written:!1,reason:"append would exceed max spec size (256 KiB); rewrite explicitly"},null,2)}catch{}return await writeFile30(tmp,finalContent,"utf-8"),await rename20(tmp,target),JSON.stringify({written:!0,path:target,bytes:finalContent.length},null,2)}});init_zod();init_knowledge_store();init_skill_generator();init_create_tool();import{existsSync as existsSync137}from"node:fs";import{readdir as readdir19,readFile as readFile50}from"node:fs/promises";import{join as join219}from"node:path";var run_stale_reconciliation=createSwarmTool({description:"Reconcile skills against the knowledge store. clear=false: mark skills stale when source knowledge is archived or deleted. clear=true: clear stale.marker on affected active skills (proposal files under .swarm/skills/proposals are scanned but not modified — they are drafts, not yet active skills).",args:{clear:exports_external.boolean().optional().default(!1).describe("If true, clear stale markers for affected skills. If false (default), mark affected skills stale.")},execute:async(args2,directory)=>{if(typeof directory!=="string"||!directory)return JSON.stringify({found:0,skills:[]},null,2);let archivedIds=await _internals186.getArchivedKnowledgeIds(directory),archivedSet=new Set(archivedIds),allKnownIds=new Set,swarmPath3=_internals186.resolveSwarmKnowledgePath(directory),hivePath=_internals186.resolveHiveKnowledgePath();try{let swarmEntries=await _internals186.readKnowledge(swarmPath3);for(let e of swarmEntries)allKnownIds.add(e.id)}catch{}try{let hiveEntries=await _internals186.readKnowledge(hivePath);for(let e of hiveEntries)allKnownIds.add(e.id)}catch{}let skillEntries=[];for(let dir of[join219(directory,".opencode","skills","generated"),join219(directory,".swarm","skills","proposals")]){if(!_internals186.existsSync(dir))continue;let entries=await _internals186.readdir(dir,{withFileTypes:!0});for(let entry of entries)if(entry.isDirectory())skillEntries.push({slug:entry.name,path:join219(dir,entry.name),isProposal:!1});else if(entry.name.endsWith(".md")){let slug=entry.name.replace(/\.md$/,"");skillEntries.push({slug,path:join219(dir,entry.name),isProposal:!0})}}let results=[];for(let{slug,path:path272,isProposal}of skillEntries){let skillMdPath=isProposal?path272:join219(path272,"SKILL.md");if(!_internals186.existsSync(skillMdPath))continue;let content=await _internals186.readFile(skillMdPath,"utf-8"),sourceIds=_internals186.parseDraftFrontmatter(content)?.sourceKnowledgeIds??[];if(sourceIds.length===0)continue;let affected=sourceIds.filter((id)=>archivedSet.has(id)||!allKnownIds.has(id));if(affected.length===0)continue;if(args2.clear){if(!isProposal){let markerPath=join219(path272,"stale.marker");if(_internals186.existsSync(markerPath))try{await _internals186.clearSkillStale(path272),results.push({slug,reason:affected.join(", "),action:"cleared"})}catch{}}}else if(!isProposal)try{await _internals186.retireOrMarkStale(directory,path272,archivedSet),results.push({slug,reason:affected.join(", "),action:"marked_stale"})}catch{}}return JSON.stringify({found:results.length,skills:results},null,2)}}),_internals186={run_stale_reconciliation,clearSkillStale,retireOrMarkStale,parseDraftFrontmatter,getArchivedKnowledgeIds,readKnowledge,resolveSwarmKnowledgePath,resolveHiveKnowledgePath:resolveHiveKnowledgePath2,readdir:readdir19,readFile:readFile50,existsSync:existsSync137};init_zod();init_loader();import{existsSync as existsSync138,mkdirSync as mkdirSync63,readFileSync as readFileSync112,renameSync as renameSync37,unlinkSync as unlinkSync38,writeFileSync as writeFileSync44}from"node:fs";import path272 from"node:path";init_config2();init_gateway();init_reward_capture();init_logger();init_create_tool();init_resolve_working_directory();var VerdictSchema2=exports_external.object({agent:exports_external.enum(["critic","reviewer","sme","test_engineer","explorer"]),verdict:exports_external.enum(["APPROVE","CONCERNS","REJECT"]),verdictRound:exports_external.number().int().min(1).max(10).optional(),confidence:exports_external.number().min(0).max(1),findings:exports_external.array(exports_external.object({severity:exports_external.enum(["CRITICAL","HIGH","MEDIUM","LOW"]),category:exports_external.string().min(1),location:exports_external.string(),detail:exports_external.string(),evidence:exports_external.string()})),criteriaAssessed:exports_external.array(exports_external.string()),criteriaUnmet:exports_external.array(exports_external.string()),durationMs:exports_external.number().nonnegative()}),ArgsSchema4=exports_external.object({phaseNumber:exports_external.number().int().min(1),swarmId:exports_external.string().min(1),phaseSummary:exports_external.string().min(1),roundNumber:exports_external.number().int().min(1).max(10).optional(),verdicts:exports_external.array(VerdictSchema2).min(1).max(5),working_directory:exports_external.string().optional(),provenanceAgentName:exports_external.string().min(1).optional(),provenanceSessionId:exports_external.string().min(1).optional()}),submit_phase_council_verdicts=createSwarmTool({description:"Submit pre-collected council member verdicts for PHASE-LEVEL synthesis. "+"PREREQUISITE — you MUST dispatch each council member (critic, reviewer, sme, "+"test_engineer, explorer) as separate Agent tasks with PHASE-SCOPED context and collect their verdict responses BEFORE calling this tool. This tool performs "+"synthesis only — it does NOT dispatch, invoke, or contact council members. "+"Writes .swarm/evidence/{phase}/phase-council.json which is required by phase_complete Gate 5 when phase_council is enabled. Architect-only. Config-gated via council.enabled.",args:{phaseNumber:exports_external.number().int().min(1).describe("Phase number being reviewed (e.g. 1, 2, 3)"),swarmId:exports_external.string().min(1).describe('Swarm identifier, e.g. "mega"'),phaseSummary:exports_external.string().min(1).describe("2–4 sentence summary of what the phase accomplished"),roundNumber:exports_external.number().int().min(1).max(10).optional().describe("1-indexed round number. Defaults to 1."),verdicts:exports_external.array(exports_external.object({agent:exports_external.enum(["critic","reviewer","sme","test_engineer","explorer"]),verdict:exports_external.enum(["APPROVE","CONCERNS","REJECT"]),verdictRound:exports_external.number().int().min(1).max(10).optional(),confidence:exports_external.number().min(0).max(1),findings:exports_external.array(exports_external.object({severity:exports_external.enum(["CRITICAL","HIGH","MEDIUM","LOW"]),category:exports_external.string().min(1),location:exports_external.string(),detail:exports_external.string(),evidence:exports_external.string()})),criteriaAssessed:exports_external.array(exports_external.string()),criteriaUnmet:exports_external.array(exports_external.string()),durationMs:exports_external.number()})).min(1).max(5).describe("Collected CouncilMemberVerdict objects from all dispatched council members"),working_directory:exports_external.string().optional().describe("Working directory where the plan is located"),provenanceAgentName:exports_external.string().min(1).optional().describe("Agent name that produced this evidence (optional provenance)"),provenanceSessionId:exports_external.string().min(1).optional().describe("Session ID of the agent that produced this evidence (optional provenance)")},async execute(args2,directory,ctx){let parsed=ArgsSchema4.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,reason:"invalid arguments",errors:parsed.error.issues.map((i)=>({path:i.path.join("."),message:i.message}))},null,2);let input=parsed.data,dirResult=resolveWorkingDirectory(input.working_directory,directory);if(!dirResult.success)return JSON.stringify({success:!1,reason:dirResult.message},null,2);let workingDir=dirResult.directory,config3=loadPluginConfig(workingDir);if(!config3.council?.enabled)return JSON.stringify({success:!1,reason:"council feature is disabled — set council.enabled: true in .opencode/opencode-swarm.json to enable"},null,2);let effectiveMinimum=config3.council?.requireAllMembers?5:config3.council?.minimumMembers??3,ALL_MEMBERS=["critic","reviewer","sme","test_engineer","explorer"],distinctMembers=new Set(input.verdicts.map((v)=>v.agent)),membersVoted=[...distinctMembers],membersAbsent=ALL_MEMBERS.filter((m)=>!distinctMembers.has(m));if(membersVoted.length<effectiveMinimum)return JSON.stringify({success:!1,reason:"insufficient_quorum",message:`Phase council quorum not met: ${membersVoted.length} of ${effectiveMinimum} required members provided verdicts. Members voted: [${membersVoted.join(", ")}]. Members absent: [${membersAbsent.join(", ")}]. Dispatch the absent council members with phase-scoped context and collect their verdicts before calling submit_phase_council_verdicts.`,membersVoted,membersAbsent,quorumRequired:effectiveMinimum},null,2);let staleVerdicts=(input.roundNumber??1)>1?input.verdicts.filter((v)=>(v.verdictRound??1)<(input.roundNumber??1)):[];if(staleVerdicts.length>0)return JSON.stringify({success:!1,reason:"stale_verdict_detected",message:`Round ${input.roundNumber??1} requires fresh verdicts. One or more submitted verdicts are from an older round.`,staleVerdicts:staleVerdicts.map((v)=>({agent:v.agent,verdictRound:v.verdictRound}))},null,2);let synthesis=synthesizePhaseCouncilAdvisory(input.phaseNumber,input.phaseSummary,input.verdicts,input.roundNumber??1,config3.council,workingDir),mutationGapFinding=input.verdicts.some((verdict)=>verdict.findings.some((finding)=>finding.category==="mutation_gap"))?null:getPhaseMutationGapFinding(input.phaseNumber,workingDir);if(mutationGapFinding){if(addMutationGapFindingToSynthesis(synthesis,mutationGapFinding),mutationGapFinding.severity==="CRITICAL"||mutationGapFinding.severity==="HIGH")synthesis.blockingConcernsCount++}if(synthesis.blockingConcernsCount>0)return JSON.stringify({success:!1,reason:"blocking_concerns_unresolved",overallVerdict:synthesis.overallVerdict,blockingConcernsCount:synthesis.blockingConcernsCount,requiredFixes:synthesis.requiredFixes,unifiedFeedbackMd:synthesis.unifiedFeedbackMd,message:`Phase council returned CONCERNS with ${synthesis.blockingConcernsCount} HIGH/CRITICAL finding(s) promoted to requiredFixes. These must be resolved before the phase can complete. Do NOT write evidence or proceed — address every requiredFix and resubmit.`},null,2);let provenance=input.provenanceAgentName||input.provenanceSessionId?{agent_name:input.provenanceAgentName,session_id:input.provenanceSessionId,captured_at:new Date().toISOString()}:void 0;writePhaseCouncilEvidence(workingDir,synthesis,provenance);try{let memoryConfig=config3.memory;if(memoryConfig?.enabled===!0&&ctx?.sessionID){let provider=createConfiguredMemoryProvider(workingDir,memoryConfig);try{let rewardSynthesis={scope:"phase",phaseNumber:synthesis.phaseNumber,overallVerdict:synthesis.overallVerdict,allCriteriaMet:synthesis.allCriteriaMet,requiredFixesCount:synthesis.requiredFixes?.length??0,roundNumber:synthesis.roundNumber,quorumSize:membersVoted.length},verdictSynthesisJson=JSON.stringify(rewardSynthesis),cap2=memoryConfig.qLearning.verdictPayloadCapBytes;if(typeof cap2==="number"&&cap2>0&&verdictSynthesisJson.length>cap2)verdictSynthesisJson=JSON.stringify(truncateObjectForJson(rewardSynthesis,cap2));await applyCouncilReward(provider,{runId:ctx.sessionID,unitId:void 0,reward:COUNCIL_VERDICT_REWARDS[synthesis.overallVerdict],eta:memoryConfig.qLearning.learningRate,initialQValue:memoryConfig.qLearning.initialQValue,qLearning:memoryConfig.qLearning,verdictSynthesisJson,timestamp:new Date().toISOString(),verdictLabel:synthesis.overallVerdict})}finally{await provider.close?.()}}}catch(rewardErr){warn(`[submit-phase-council-verdicts] phase council reward capture failed: ${rewardErr instanceof Error?rewardErr.message:String(rewardErr)}`)}return JSON.stringify({success:!0,overallVerdict:synthesis.overallVerdict,vetoedBy:synthesis.vetoedBy,roundNumber:synthesis.roundNumber,allCriteriaMet:synthesis.allCriteriaMet,requiredFixesCount:synthesis.requiredFixes?.length??0,advisoryFindingsCount:synthesis.advisoryFindings?.length??0,unresolvedConflictsCount:synthesis.unresolvedConflicts?.length??0,advisoryNotes:synthesis.advisoryNotes??[],mutationGapEmitted:mutationGapFinding!==null,membersVoted,membersAbsent,quorumSize:membersVoted.length,quorumMet:!0,evidencePath:synthesis.evidencePath,unifiedFeedbackMd:synthesis.unifiedFeedbackMd},null,2)}});function getPhaseMutationGapFinding(phaseNumber,workingDir){let mutationGatePath=path272.join(workingDir,".swarm","evidence",String(phaseNumber),"mutation-gate.json");try{let raw=readFileSync112(mutationGatePath,"utf-8"),gateEntry=(JSON.parse(raw).entries??[]).find((entry)=>entry?.type==="mutation-gate");if(!gateEntry)return{severity:"HIGH",category:"mutation_gap",location:`.swarm/evidence/${phaseNumber}/mutation-gate.json`,detail:"Mutation gate evidence is missing a mutation-gate entry for this phase.",evidence:'Expected entries[].type="mutation-gate" with verdict in mutation-gate.json.'};if(gateEntry.verdict==="skip")return{severity:"MEDIUM",category:"mutation_gap",location:`.swarm/evidence/${phaseNumber}/mutation-gate.json`,detail:"Mutation testing was skipped for this phase; coverage is unverified.",evidence:'mutation-gate.json recorded verdict="skip". Run mutation_test and write_mutation_evidence.'};if(gateEntry.verdict==="warn")return{severity:"LOW",category:"mutation_gap",location:`.swarm/evidence/${phaseNumber}/mutation-gate.json`,detail:"Mutation gate reported WARN; mutation coverage may be insufficient.",evidence:'mutation-gate.json recorded verdict="warn" indicating below-pass mutation quality.'};if(gateEntry.verdict==="fail")return{severity:"HIGH",category:"mutation_gap",location:`.swarm/evidence/${phaseNumber}/mutation-gate.json`,detail:"Mutation gate reported FAIL; mutation testing quality is below the required threshold.",evidence:'mutation-gate.json recorded verdict="fail" indicating insufficient mutation kill rate.'};return null}catch(error93){if(error93.code==="ENOENT")return{severity:"HIGH",category:"mutation_gap",location:`.swarm/evidence/${phaseNumber}/mutation-gate.json`,detail:"Mutation gate evidence file is missing for this phase, so mutation coverage cannot be verified.",evidence:"No .swarm/evidence/{phase}/mutation-gate.json was found at council synthesis time."};return{severity:"MEDIUM",category:"mutation_gap",location:`.swarm/evidence/${phaseNumber}/mutation-gate.json`,detail:"Mutation gate evidence could not be read, so mutation coverage cannot be verified.",evidence:error93 instanceof Error?error93.message:String(error93)}}}function writePhaseCouncilEvidence(workingDir,synthesis,provenance){let evidenceDir=path272.join(workingDir,".swarm","evidence",String(synthesis.phaseNumber));mkdirSync63(evidenceDir,{recursive:!0});let evidenceFile=path272.join(evidenceDir,"phase-council.json"),evidenceBundle={entries:[{type:"phase-council",phase_number:synthesis.phaseNumber,scope:"phase",timestamp:synthesis.timestamp,verdict:synthesis.overallVerdict,quorumSize:synthesis.quorumSize,phaseSummary:synthesis.phaseSummary??"",requiredFixes:synthesis.requiredFixes.map((finding)=>({severity:finding.severity,category:finding.category,location:finding.location,detail:finding.detail,evidence:finding.evidence})),advisoryNotes:synthesis.advisoryNotes,advisoryFindings:synthesis.advisoryFindings.map((finding)=>({severity:finding.severity,category:finding.category,location:finding.location,detail:finding.detail,evidence:finding.evidence})),roundNumber:synthesis.roundNumber,allCriteriaMet:synthesis.allCriteriaMet,...provenance?{provenance}:{}}]},tempFile=`${evidenceFile}.tmp-${Date.now()}`;try{writeFileSync44(tempFile,JSON.stringify(evidenceBundle,null,2),"utf-8"),renameSync37(tempFile,evidenceFile)}finally{if(existsSync138(tempFile))unlinkSync38(tempFile)}}function addMutationGapFindingToSynthesis(synthesis,finding){if(finding.severity==="CRITICAL"||finding.severity==="HIGH"||finding.severity==="MEDIUM")synthesis.requiredFixes.push(finding);else synthesis.advisoryFindings.push(finding);synthesis.unifiedFeedbackMd+=formatMutationGapFeedback(finding)}function formatMutationGapFeedback(finding){return`
6357
+ `,finalContent.length>MAX_SPEC_BYTES2)return JSON.stringify({written:!1,reason:"append would exceed max spec size (256 KiB); rewrite explicitly"},null,2)}catch{}return await writeFile30(tmp,finalContent,"utf-8"),await rename20(tmp,target),JSON.stringify({written:!0,path:target,bytes:finalContent.length},null,2)}});init_zod();init_knowledge_store();init_skill_generator();init_create_tool();import{existsSync as existsSync137}from"node:fs";import{readdir as readdir19,readFile as readFile50}from"node:fs/promises";import{join as join219}from"node:path";var run_stale_reconciliation=createSwarmTool({description:"Reconcile skills against the knowledge store. clear=false: mark skills stale when source knowledge is archived or deleted. clear=true: clear stale.marker on affected active skills (proposal files under .swarm/skills/proposals are scanned but not modified — they are drafts, not yet active skills).",args:{clear:exports_external.boolean().optional().default(!1).describe("If true, clear stale markers for affected skills. If false (default), mark affected skills stale.")},execute:async(args2,directory)=>{if(typeof directory!=="string"||!directory)return JSON.stringify({found:0,skills:[]},null,2);let archivedIds=await _internals186.getArchivedKnowledgeIds(directory),archivedSet=new Set(archivedIds),allKnownIds=new Set,swarmPath3=_internals186.resolveSwarmKnowledgePath(directory),hivePath=_internals186.resolveHiveKnowledgePath();try{let swarmEntries=await _internals186.readKnowledge(swarmPath3);for(let e of swarmEntries)allKnownIds.add(e.id)}catch{}try{let hiveEntries=await _internals186.readKnowledge(hivePath);for(let e of hiveEntries)allKnownIds.add(e.id)}catch{}let skillEntries=[];for(let dir of[join219(directory,".opencode","skills","generated"),join219(directory,".swarm","skills","proposals")]){if(!_internals186.existsSync(dir))continue;let entries=await _internals186.readdir(dir,{withFileTypes:!0});for(let entry of entries)if(entry.isDirectory())skillEntries.push({slug:entry.name,path:join219(dir,entry.name),isProposal:!1});else if(entry.name.endsWith(".md")){let slug=entry.name.replace(/\.md$/,"");skillEntries.push({slug,path:join219(dir,entry.name),isProposal:!0})}}let results=[];for(let{slug,path:path272,isProposal}of skillEntries){let skillMdPath=isProposal?path272:join219(path272,"SKILL.md");if(!_internals186.existsSync(skillMdPath))continue;let content=await _internals186.readFile(skillMdPath,"utf-8"),sourceIds=_internals186.parseDraftFrontmatter(content)?.sourceKnowledgeIds??[];if(sourceIds.length===0)continue;let affected=sourceIds.filter((id)=>archivedSet.has(id)||!allKnownIds.has(id));if(affected.length===0)continue;if(args2.clear){if(!isProposal){let markerPath=join219(path272,"stale.marker");if(_internals186.existsSync(markerPath))try{await _internals186.clearSkillStale(path272),results.push({slug,reason:affected.join(", "),action:"cleared"})}catch{}}}else if(!isProposal)try{await _internals186.retireOrMarkStale(directory,path272,archivedSet),results.push({slug,reason:affected.join(", "),action:"marked_stale"})}catch{}}return JSON.stringify({found:results.length,skills:results},null,2)}}),_internals186={run_stale_reconciliation,clearSkillStale,retireOrMarkStale,parseDraftFrontmatter,getArchivedKnowledgeIds,readKnowledge,resolveSwarmKnowledgePath,resolveHiveKnowledgePath:resolveHiveKnowledgePath2,readdir:readdir19,readFile:readFile50,existsSync:existsSync137};init_zod();init_loader();import{existsSync as existsSync138,mkdirSync as mkdirSync63,readFileSync as readFileSync112,renameSync as renameSync37,unlinkSync as unlinkSync38,writeFileSync as writeFileSync44}from"node:fs";import path272 from"node:path";init_config2();init_gateway();init_reward_capture();init_logger();init_create_tool();init_resolve_working_directory();var VerdictSchema2=exports_external.object({agent:exports_external.enum(["critic","reviewer","sme","test_engineer","explorer"]),verdict:exports_external.enum(["APPROVE","CONCERNS","REJECT"]),verdictRound:exports_external.number().int().min(1).max(10).optional(),confidence:exports_external.number().min(0).max(1),findings:exports_external.array(exports_external.object({severity:exports_external.enum(["CRITICAL","HIGH","MEDIUM","LOW"]),category:exports_external.string().min(1),location:exports_external.string(),detail:exports_external.string(),evidence:exports_external.string()})),criteriaAssessed:exports_external.array(exports_external.string()),criteriaUnmet:exports_external.array(exports_external.string()),durationMs:exports_external.number().nonnegative()}),ArgsSchema4=exports_external.object({phaseNumber:exports_external.number().int().min(1),swarmId:exports_external.string().min(1),phaseSummary:exports_external.string().min(1),roundNumber:exports_external.number().int().min(1).max(10).optional(),verdicts:exports_external.array(VerdictSchema2).min(1).max(5),working_directory:exports_external.string().optional(),provenanceAgentName:exports_external.string().min(1).optional(),provenanceSessionId:exports_external.string().min(1).optional()}),submit_phase_council_verdicts=createSwarmTool({description:"Submit pre-collected council member verdicts for PHASE-LEVEL synthesis. "+"PREREQUISITE — you MUST dispatch each council member (critic, reviewer, sme, "+"test_engineer, explorer) as separate Agent tasks with PHASE-SCOPED context and collect their verdict responses BEFORE calling this tool. This tool performs "+"synthesis only — it does NOT dispatch, invoke, or contact council members. "+"Writes .swarm/evidence/{phase}/phase-council.json which is required by phase_complete Gate 5 when phase_council is enabled. Architect-only. Config-gated via council.enabled.",args:{phaseNumber:exports_external.number().int().min(1).describe("Phase number being reviewed (e.g. 1, 2, 3)"),swarmId:exports_external.string().min(1).describe('Swarm identifier, e.g. "mega"'),phaseSummary:exports_external.string().min(1).describe("2–4 sentence summary of what the phase accomplished"),roundNumber:exports_external.number().int().min(1).max(10).optional().describe("1-indexed round number. Defaults to 1."),verdicts:exports_external.array(exports_external.object({agent:exports_external.enum(["critic","reviewer","sme","test_engineer","explorer"]),verdict:exports_external.enum(["APPROVE","CONCERNS","REJECT"]),verdictRound:exports_external.number().int().min(1).max(10).optional(),confidence:exports_external.number().min(0).max(1),findings:exports_external.array(exports_external.object({severity:exports_external.enum(["CRITICAL","HIGH","MEDIUM","LOW"]),category:exports_external.string().min(1),location:exports_external.string(),detail:exports_external.string(),evidence:exports_external.string()})),criteriaAssessed:exports_external.array(exports_external.string()),criteriaUnmet:exports_external.array(exports_external.string()),durationMs:exports_external.number()})).min(1).max(5).describe("Collected CouncilMemberVerdict objects from all dispatched council members"),working_directory:exports_external.string().optional().describe("Working directory where the plan is located"),provenanceAgentName:exports_external.string().min(1).optional().describe("Agent name that produced this evidence (optional provenance)"),provenanceSessionId:exports_external.string().min(1).optional().describe("Session ID of the agent that produced this evidence (optional provenance)")},async execute(args2,directory,ctx){let parsed=ArgsSchema4.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,reason:"invalid arguments",errors:parsed.error.issues.map((i)=>({path:i.path.join("."),message:i.message}))},null,2);let input=parsed.data,dirResult=resolveWorkingDirectory(input.working_directory,directory);if(!dirResult.success)return JSON.stringify({success:!1,reason:dirResult.message},null,2);let workingDir=dirResult.directory,config3=loadPluginConfig(workingDir);if(!config3.council?.enabled)return JSON.stringify({success:!1,reason:"council feature is disabled — set council.enabled: true in .opencode/opencode-swarm.json to enable"},null,2);let effectiveMinimum=config3.council?.requireAllMembers?5:config3.council?.minimumMembers??3,ALL_MEMBERS=["critic","reviewer","sme","test_engineer","explorer"],distinctMembers=new Set(input.verdicts.map((v)=>v.agent)),membersVoted=[...distinctMembers],membersAbsent=ALL_MEMBERS.filter((m)=>!distinctMembers.has(m));if(membersVoted.length<effectiveMinimum)return JSON.stringify({success:!1,reason:"insufficient_quorum",message:`Phase council quorum not met: ${membersVoted.length} of ${effectiveMinimum} required members provided verdicts. Members voted: [${membersVoted.join(", ")}]. Members absent: [${membersAbsent.join(", ")}]. Dispatch the absent council members with phase-scoped context and collect their verdicts before calling submit_phase_council_verdicts.`,membersVoted,membersAbsent,quorumRequired:effectiveMinimum},null,2);let round=input.roundNumber??1,staleVerdicts=round>1?input.verdicts.filter((v)=>(v.verdictRound??round)<round):[];if(staleVerdicts.length>0)return JSON.stringify({success:!1,reason:"stale_verdict_detected",message:`Round ${round} requires fresh verdicts. One or more submitted verdicts are from an older round.`,staleVerdicts:staleVerdicts.map((v)=>({agent:v.agent,verdictRound:v.verdictRound}))},null,2);let synthesis=synthesizePhaseCouncilAdvisory(input.phaseNumber,input.phaseSummary,input.verdicts,round,config3.council,workingDir),mutationGapFinding=input.verdicts.some((verdict)=>verdict.findings.some((finding)=>finding.category==="mutation_gap"))?null:getPhaseMutationGapFinding(input.phaseNumber,workingDir);if(mutationGapFinding){if(addMutationGapFindingToSynthesis(synthesis,mutationGapFinding),mutationGapFinding.severity==="CRITICAL"||mutationGapFinding.severity==="HIGH")synthesis.blockingConcernsCount++}if(synthesis.blockingConcernsCount>0)return JSON.stringify({success:!1,reason:"blocking_concerns_unresolved",overallVerdict:synthesis.overallVerdict,blockingConcernsCount:synthesis.blockingConcernsCount,requiredFixes:synthesis.requiredFixes,unifiedFeedbackMd:synthesis.unifiedFeedbackMd,message:`Phase council returned CONCERNS with ${synthesis.blockingConcernsCount} HIGH/CRITICAL finding(s) promoted to requiredFixes. These must be resolved before the phase can complete. Do NOT write evidence or proceed — address every requiredFix and resubmit.`},null,2);let provenance=input.provenanceAgentName||input.provenanceSessionId?{agent_name:input.provenanceAgentName,session_id:input.provenanceSessionId,captured_at:new Date().toISOString()}:void 0;writePhaseCouncilEvidence(workingDir,synthesis,provenance);try{let memoryConfig=config3.memory;if(memoryConfig?.enabled===!0&&ctx?.sessionID){let provider=createConfiguredMemoryProvider(workingDir,memoryConfig);try{let rewardSynthesis={scope:"phase",phaseNumber:synthesis.phaseNumber,overallVerdict:synthesis.overallVerdict,allCriteriaMet:synthesis.allCriteriaMet,requiredFixesCount:synthesis.requiredFixes?.length??0,roundNumber:synthesis.roundNumber,quorumSize:membersVoted.length},verdictSynthesisJson=JSON.stringify(rewardSynthesis),cap2=memoryConfig.qLearning.verdictPayloadCapBytes;if(typeof cap2==="number"&&cap2>0&&verdictSynthesisJson.length>cap2)verdictSynthesisJson=JSON.stringify(truncateObjectForJson(rewardSynthesis,cap2));await applyCouncilReward(provider,{runId:ctx.sessionID,unitId:void 0,reward:COUNCIL_VERDICT_REWARDS[synthesis.overallVerdict],eta:memoryConfig.qLearning.learningRate,initialQValue:memoryConfig.qLearning.initialQValue,qLearning:memoryConfig.qLearning,verdictSynthesisJson,timestamp:new Date().toISOString(),verdictLabel:synthesis.overallVerdict})}finally{await provider.close?.()}}}catch(rewardErr){warn(`[submit-phase-council-verdicts] phase council reward capture failed: ${rewardErr instanceof Error?rewardErr.message:String(rewardErr)}`)}return JSON.stringify({success:!0,overallVerdict:synthesis.overallVerdict,vetoedBy:synthesis.vetoedBy,roundNumber:synthesis.roundNumber,allCriteriaMet:synthesis.allCriteriaMet,requiredFixesCount:synthesis.requiredFixes?.length??0,advisoryFindingsCount:synthesis.advisoryFindings?.length??0,unresolvedConflictsCount:synthesis.unresolvedConflicts?.length??0,advisoryNotes:synthesis.advisoryNotes??[],mutationGapEmitted:mutationGapFinding!==null,membersVoted,membersAbsent,quorumSize:membersVoted.length,quorumMet:!0,evidencePath:synthesis.evidencePath,unifiedFeedbackMd:synthesis.unifiedFeedbackMd},null,2)}});function getPhaseMutationGapFinding(phaseNumber,workingDir){let mutationGatePath=path272.join(workingDir,".swarm","evidence",String(phaseNumber),"mutation-gate.json");try{let raw=readFileSync112(mutationGatePath,"utf-8"),gateEntry=(JSON.parse(raw).entries??[]).find((entry)=>entry?.type==="mutation-gate");if(!gateEntry)return{severity:"HIGH",category:"mutation_gap",location:`.swarm/evidence/${phaseNumber}/mutation-gate.json`,detail:"Mutation gate evidence is missing a mutation-gate entry for this phase.",evidence:'Expected entries[].type="mutation-gate" with verdict in mutation-gate.json.'};if(gateEntry.verdict==="skip")return{severity:"MEDIUM",category:"mutation_gap",location:`.swarm/evidence/${phaseNumber}/mutation-gate.json`,detail:"Mutation testing was skipped for this phase; coverage is unverified.",evidence:'mutation-gate.json recorded verdict="skip". Run mutation_test and write_mutation_evidence.'};if(gateEntry.verdict==="warn")return{severity:"LOW",category:"mutation_gap",location:`.swarm/evidence/${phaseNumber}/mutation-gate.json`,detail:"Mutation gate reported WARN; mutation coverage may be insufficient.",evidence:'mutation-gate.json recorded verdict="warn" indicating below-pass mutation quality.'};if(gateEntry.verdict==="fail")return{severity:"HIGH",category:"mutation_gap",location:`.swarm/evidence/${phaseNumber}/mutation-gate.json`,detail:"Mutation gate reported FAIL; mutation testing quality is below the required threshold.",evidence:'mutation-gate.json recorded verdict="fail" indicating insufficient mutation kill rate.'};return null}catch(error93){if(error93.code==="ENOENT")return{severity:"HIGH",category:"mutation_gap",location:`.swarm/evidence/${phaseNumber}/mutation-gate.json`,detail:"Mutation gate evidence file is missing for this phase, so mutation coverage cannot be verified.",evidence:"No .swarm/evidence/{phase}/mutation-gate.json was found at council synthesis time."};return{severity:"MEDIUM",category:"mutation_gap",location:`.swarm/evidence/${phaseNumber}/mutation-gate.json`,detail:"Mutation gate evidence could not be read, so mutation coverage cannot be verified.",evidence:error93 instanceof Error?error93.message:String(error93)}}}function writePhaseCouncilEvidence(workingDir,synthesis,provenance){let evidenceDir=path272.join(workingDir,".swarm","evidence",String(synthesis.phaseNumber));mkdirSync63(evidenceDir,{recursive:!0});let evidenceFile=path272.join(evidenceDir,"phase-council.json"),evidenceBundle={entries:[{type:"phase-council",phase_number:synthesis.phaseNumber,scope:"phase",timestamp:synthesis.timestamp,verdict:synthesis.overallVerdict,quorumSize:synthesis.quorumSize,phaseSummary:synthesis.phaseSummary??"",requiredFixes:synthesis.requiredFixes.map((finding)=>({severity:finding.severity,category:finding.category,location:finding.location,detail:finding.detail,evidence:finding.evidence})),advisoryNotes:synthesis.advisoryNotes,advisoryFindings:synthesis.advisoryFindings.map((finding)=>({severity:finding.severity,category:finding.category,location:finding.location,detail:finding.detail,evidence:finding.evidence})),roundNumber:synthesis.roundNumber,allCriteriaMet:synthesis.allCriteriaMet,...provenance?{provenance}:{}}]},tempFile=`${evidenceFile}.tmp-${Date.now()}`;try{writeFileSync44(tempFile,JSON.stringify(evidenceBundle,null,2),"utf-8"),renameSync37(tempFile,evidenceFile)}finally{if(existsSync138(tempFile))unlinkSync38(tempFile)}}function addMutationGapFindingToSynthesis(synthesis,finding){if(finding.severity==="CRITICAL"||finding.severity==="HIGH"||finding.severity==="MEDIUM")synthesis.requiredFixes.push(finding);else synthesis.advisoryFindings.push(finding);synthesis.unifiedFeedbackMd+=formatMutationGapFeedback(finding)}function formatMutationGapFeedback(finding){return`
6357
6358
 
6358
6359
  ### Mutation Coverage Gap
6359
6360
  - **[${finding.severity}]** \`${finding.location}\` (${finding.category}) — ${finding.detail}