opencode-swarm 7.148.2 → 7.148.4

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 (64) hide show
  1. package/dist/background/delegation-health.d.ts +100 -0
  2. package/dist/background/pending-delegations.d.ts +97 -0
  3. package/dist/background/queue.d.ts +45 -7
  4. package/dist/background/worker.d.ts +24 -3
  5. package/dist/cli/{config-doctor-6danhdcy.js → config-doctor-ycf9ws4p.js} +2 -2
  6. package/dist/cli/{core-0ghwny8q.js → core-a1bhs3xa.js} +1 -1
  7. package/dist/cli/{curation-policy-hkdghd3a.js → curation-policy-fbvctttr.js} +5 -5
  8. package/dist/cli/{curator-wvm7qbkk.js → curator-8y57gq1g.js} +26 -26
  9. package/dist/cli/{curator-llm-factory-6n47j5qn.js → curator-llm-factory-rj4vw5fd.js} +26 -26
  10. package/dist/cli/{evidence-summary-service-0xwrkmf9.js → evidence-summary-service-wkp0gfpd.js} +10 -10
  11. package/dist/cli/{gate-evidence-6e5yhcy6.js → gate-evidence-qty15skw.js} +5 -5
  12. package/dist/cli/{guardrail-explain-tgv7rvap.js → guardrail-explain-2n3ahs0m.js} +27 -27
  13. package/dist/cli/{guardrail-log-k0zk6rbs.js → guardrail-log-bmxrb3r2.js} +3 -3
  14. package/dist/cli/{guardrail-reset-4fw16xmb.js → guardrail-reset-be3sx0am.js} +26 -26
  15. package/dist/cli/{hive-promoter-zemwxxw1.js → hive-promoter-te5d78yt.js} +26 -26
  16. package/dist/cli/{index-x9q0b3a8.js → index-0045n7qe.js} +2 -2
  17. package/dist/cli/{index-7jaq84cg.js → index-1vbmra32.js} +1 -1
  18. package/dist/cli/{index-q6kscnts.js → index-622phhp5.js} +3 -3
  19. package/dist/cli/{index-84ytts36.js → index-6kw1a3bk.js} +4 -4
  20. package/dist/cli/{index-nqwn8sf0.js → index-7rerkeg8.js} +1 -1
  21. package/dist/cli/{index-x4kgn37c.js → index-8djgxw2w.js} +2 -2
  22. package/dist/cli/{index-ndqhtgrc.js → index-8kzrgjt6.js} +1 -1
  23. package/dist/cli/{index-x9jppg8b.js → index-9m8jy3av.js} +2 -2
  24. package/dist/cli/{index-xn7h24x4.js → index-9qzkcmry.js} +3 -3
  25. package/dist/cli/{index-5vyej8pc.js → index-b1c83zf9.js} +5 -5
  26. package/dist/cli/{index-s0nss8c4.js → index-b94487xm.js} +1 -1
  27. package/dist/cli/{index-pzt7ed53.js → index-bccfz7br.js} +4 -4
  28. package/dist/cli/{index-mbcyz77e.js → index-gswx08pr.js} +4 -4
  29. package/dist/cli/{index-hsq8nyen.js → index-hj1xd3pg.js} +265 -83
  30. package/dist/cli/{index-ebt47fnp.js → index-j382eh60.js} +1 -1
  31. package/dist/cli/{index-m5z2fgs4.js → index-k1s8gxjh.js} +1 -1
  32. package/dist/cli/{index-zpn3wqvp.js → index-kg4knw6r.js} +2 -2
  33. package/dist/cli/{index-r9g7ymv2.js → index-nq4tkfpc.js} +1 -1
  34. package/dist/cli/{index-k2ad2vtb.js → index-qbvq3xt2.js} +1 -1
  35. package/dist/cli/{index-3pbvdde0.js → index-qpewzk0q.js} +2 -2
  36. package/dist/cli/{index-2n9rwvcc.js → index-qwmrt51t.js} +1 -1
  37. package/dist/cli/{index-03wz9h63.js → index-rzzwem6x.js} +28 -28
  38. package/dist/cli/{index-s0s1e5jp.js → index-skgeytf6.js} +6 -6
  39. package/dist/cli/{index-wgrvq2bc.js → index-sxtz2d26.js} +6 -6
  40. package/dist/cli/{index-092deqxs.js → index-t25evmna.js} +400 -12
  41. package/dist/cli/{index-2zz8b0rb.js → index-vhefvcta.js} +2 -2
  42. package/dist/cli/{index-rsn4jm90.js → index-vrp2zva8.js} +1 -1
  43. package/dist/cli/{index-nxydm56k.js → index-w00hn0dd.js} +2 -2
  44. package/dist/cli/{index-crpkb5x6.js → index-ye7kpzrk.js} +5 -5
  45. package/dist/cli/{index-mgcffsk0.js → index-yq89bgnz.js} +1 -1
  46. package/dist/cli/index.js +26 -26
  47. package/dist/cli/{knowledge-escalator-rfw35yt1.js → knowledge-escalator-9w53tx55.js} +10 -10
  48. package/dist/cli/{knowledge-events-wmjm5wn6.js → knowledge-events-my31zepa.js} +8 -8
  49. package/dist/cli/{knowledge-link-5dctq0ax.js → knowledge-link-spw879rs.js} +4 -4
  50. package/dist/cli/{knowledge-store-f2ev6s5p.js → knowledge-store-yf59mxp5.js} +5 -5
  51. package/dist/cli/{knowledge-validator-6cmwpx9e.js → knowledge-validator-8n569fp4.js} +7 -7
  52. package/dist/cli/{pending-delegations-h4gr264y.js → pending-delegations-f4wvyzbf.js} +10 -2
  53. package/dist/cli/{pr-subscriptions-9mg6mwc0.js → pr-subscriptions-f4xw1rxy.js} +2 -2
  54. package/dist/cli/{runner-9g2pcg10.js → runner-rk26nk58.js} +5 -5
  55. package/dist/cli/{scan-cursor-x1ma7edk.js → scan-cursor-www6dbn8.js} +6 -6
  56. package/dist/cli/{schema-g5ggmb47.js → schema-vyg0k7rh.js} +1 -1
  57. package/dist/cli/{scope-persistence-gt0zpp6a.js → scope-persistence-3qbr019s.js} +6 -6
  58. package/dist/cli/{skill-generator-q6m110d5.js → skill-generator-fh8emssb.js} +12 -12
  59. package/dist/cli/{worktree-collision-ownership-e0p490vw.js → worktree-collision-ownership-wqy7mgb3.js} +2 -2
  60. package/dist/cli/{worktree-isolation-akwwt8n5.js → worktree-isolation-sbsdx1yj.js} +26 -26
  61. package/dist/hooks/delegation-gate.d.ts +1 -0
  62. package/dist/index.js +16 -15
  63. package/dist/services/status-service.d.ts +55 -3
  64. 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.148.2",description:"Architect-centric agentic swarm plugin for OpenCode - hub-and-spoke orchestration with SME consultation, code generation, and QA review",main:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",default:"./dist/index.js"},"./package.json":"./package.json"},bin:{"opencode-swarm":"./dist/cli/index.js"},type:"module",engines:{bun:">=1.3.13"},license:"MIT",repository:{type:"git",url:"https://github.com/ZaxbyHub/opencode-swarm.git"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},keywords:["opencode","opencode-plugin","ai","agents","orchestration","swarm","multi-agent","llm"],files:["dist","dist/lang/grammars","binaries","evaluation-fixtures",".opencode/skills/brainstorm",".opencode/skills/specify",".opencode/skills/clarify-spec",".opencode/skills/resume",".opencode/skills/clarify",".opencode/skills/discover",".opencode/skills/consult",".opencode/skills/pre-phase-briefing",".opencode/skills/council",".opencode/skills/deep-dive",".opencode/skills/deep-research",".opencode/skills/codebase-review-swarm",".opencode/skills/swarm-implement",".opencode/skills/design-docs",".opencode/skills/swarm-pr-review",".opencode/skills/swarm",".opencode/skills/swarm-pr-feedback",".opencode/skills/swarm-pr-subscribe",".opencode/skills/swarm-ci-monitor",".opencode/skills/issue-ingest",".opencode/skills/plan",".opencode/skills/critic-gate",".opencode/skills/execute",".opencode/skills/phase-wrap",".opencode/skills/loop",".opencode/skills/writing-tests",".opencode/skills/running-tests",".opencode/skills/engineering-conventions",".opencode/skills/commit-pr",".opencode/skills/ci-failure-batching",".opencode/skills/gate-attribution",".opencode/skills/merge-queue-readiness",".opencode/skills/skill-edit-validation",".opencode/skills/worktree-retry-cleanup",".opencode/skills/test-file-split",".opencode/skills/fork-pr-operations",".opencode/skills/parallel-work-check",".opencode/skills/ci-fix-monitor",".opencode/skills/issue-tracer",".opencode/skills/orchestrating-subagents",".opencode/skills/durable-session-state","tests/fixtures/memory-recall","README.md","LICENSE"],scripts:{clean:`bun -e "require('fs').rmSync('dist',{recursive:true,force:true})"`,build:"bun run clean && bun run scripts/copy-grammars.ts && bun build src/index.ts --outdir dist --target node --format esm --external web-tree-sitter --minify-whitespace --minify-syntax && bun build src/cli/index.ts --outdir dist/cli --target bun --format esm --external bash-parser --splitting && bun run scripts/copy-grammars.ts --to-dist && tsc --emitDeclarationOnly",typecheck:"tsc --noEmit",test:"bun test",lint:"biome lint .","lint:ci":"biome ci .","test:unit:ci":"bun scripts/ci/run-unit-tests-local.ts","drift:check":"bun run scripts/drift-check.ts","check:runtime-src-refs":"bun run scripts/check-runtime-src-refs.ts","drift:fix":"bun run scripts/drift-check.ts --fix --confirm","skills:sync":"bun run scripts/sync-qa-gate-skills.ts",format:"biome format . --write",check:"biome check --write .",dev:"bun run build && opencode","package:smoke":"node scripts/package-smoke.mjs",prepare:"bun run build","repro:704":"node scripts/repro-704.mjs","repro:1144":"bun scripts/repro-1144.mjs","repro:1873":"bun build scripts/repro-1873-entry.ts --outdir dist-build-test/repro-1873 --target node --format esm && node scripts/repro-1873.mjs","check:events":"bun run scripts/check-event-contract.ts","check:retention":"bun run scripts/check-retention-registry.ts","check:test-file-cap":"bun run scripts/check-test-file-cap.ts","check:pending-fragment":"bun run scripts/check-pending-fragment.ts","check:gate-portability":"bun run scripts/check-gate-portability.ts","check:bare-spawn":"bun run scripts/check-bare-executable-spawn.ts","check:memory-recall":"bun run scripts/memory-recall-regression.ts"},dependencies:{"@opencode-ai/plugin":"^1.18.3","@opencode-ai/sdk":"^1.18.3","@vscode/tree-sitter-wasm":"^0.3.0","bash-parser":"^0.5.0","p-limit":"^7.3.0",picomatch:"^4.0.4","proper-lockfile":"^4.1.2","quick-lru":"^7.3.0","web-tree-sitter":"^0.25.0",zod:"^4.1.8"},devDependencies:{"@biomejs/biome":"2.3.14","@types/picomatch":"^4.0.3","bun-types":"1.3.8","js-yaml":"^4.1.1",typescript:"^5.7.3"},peerDependencies:{"@xenova/transformers":"^2.17.2"},peerDependenciesMeta:{"@xenova/transformers":{optional:!0}}}});var QA_AGENTS,PIPELINE_AGENTS,ORCHESTRATOR_NAME="architect",ALL_SUBAGENT_NAMES,ALL_AGENT_NAMES;var init_agent_names=__esm(()=>{QA_AGENTS=["reviewer","critic","critic_oversight","critic_finding_validator"],PIPELINE_AGENTS=["explorer","coder","test_engineer"],ALL_SUBAGENT_NAMES=["sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","curator_postmortem","curator_consolidation","council_generalist","council_skeptic","council_domain_expert","skill_improver","spec_writer",...QA_AGENTS,...PIPELINE_AGENTS],ALL_AGENT_NAMES=["architect",...ALL_SUBAGENT_NAMES]});function getPrWorkflowToolCapability(toolName,mode){let metadata=TOOL_METADATA[toolName];if(!metadata?.prWorkflow?.modes.includes(mode))return null;return metadata.prWorkflow.capability}var TOOL_METADATA,TOOL_NAMES,TOOL_NAME_SET,TOOL_DESCRIPTIONS,AGENT_TOOL_MAP;var init_tool_metadata=__esm(()=>{init_agent_names();TOOL_METADATA={diff:{description:"structured git diff with contract change detection",agents:["architect","reviewer","critic_finding_validator","critic_oversight","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},diff_summary:{description:"filter classified AST changes by category, risk level, or file for reviewer drill-down",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},syntax_check:{description:"check syntax of source files using tree-sitter parsers across multiple languages, returning per-file errors",agents:["architect","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},placeholder_scan:{description:"todo and FIXME comment detection",agents:["architect","reviewer","critic_finding_validator"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},imports:{description:"find all consumers that import from a given file — use before refactoring shared modules to avoid breaking unseen dependents",agents:["architect","sme","researcher","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},lint:{description:"run project linter in check or fix mode; supports biome, eslint, ruff, clippy, and more, returns structured results",agents:["architect","reviewer","critic_finding_validator","coder"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},secretscan:{description:"scan for secrets (API keys, tokens, passwords) via regex and entropy; returns redacted previews, excludes common dirs",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},sast_scan:{description:"static analysis security scan",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},build_check:{description:"discover and run build, typecheck, and test commands for various project ecosystems in the working directory",agents:["architect","coder","test_engineer"]},pre_check_batch:{description:"parallel verification: lint:check + secretscan + sast_scan + quality_budget",agents:["architect","reviewer","critic_finding_validator"]},quality_budget:{description:"code quality budget check",agents:["architect"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},symbols:{description:"extract exported symbols (functions, classes, interfaces, types) from source files; supports TypeScript, JavaScript, and Python",agents:["architect","sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},complexity_hotspots:{description:"git churn × complexity risk map",agents:["architect","sme","researcher","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","critic_oversight","explorer","test_engineer"]},schema_drift:{description:"OpenAPI spec vs route drift",agents:["architect","sme","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},todo_extract:{description:"structured TODO/FIXME extraction",agents:["architect","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},evidence_check:{description:"verify task evidence completeness",agents:["architect","critic_oversight"]},check_gate_status:{description:"check the gate status of a specific task",agents:["architect","critic_oversight"]},completion_verify:{description:"verify completed tasks have required evidence",agents:["architect","critic_oversight"]},complete_pr_workflow:{description:"validate terminal PR workflow evidence and clear its durable session gate",agents:["architect"]},abort_pr_workflow:{description:"abort an unrecoverable PR_REVIEW/PR_FEEDBACK mechanical gate and clear its durable session state",agents:["architect"]},approve_plan_critic:{description:"record a MANUAL plan_critic_gate approval snapshot to unblock the ratchet-tighter critic_pre_plan execution gate when the critic already returned APPROVED but the mechanical recorder failed to persist it (issue #2012)",agents:["architect"]},prepare_pr_workflow_checkout:{description:"prepare an auditable PR workflow checkout or restore its exact original branch/HEAD and preserved stash after terminal cleanup",agents:["architect"]},record_implementation_review:{description:"record fresh-context reviewer + critic APPROVE verdicts for the implementation diff so the /swarm issue --trace workflow can satisfy its review gate before commit-pr handoff",agents:["architect"]},record_issue_publication:{description:"record a publication receipt so the /swarm issue --trace workflow reaches its terminal published state after the PR is created/updated",agents:["architect"]},record_issue_reproduction:{description:"record the reproduction outcome for the current traced issue so the /swarm issue --trace workflow can satisfy its reproduction gate and transition to PLAN",agents:["architect"]},record_recurrence_sweep:{description:"record the recurrence sweep (defect class, predicates, hit dispositions, guardrail proof) so the /swarm issue --trace workflow can satisfy its recurrence gate before commit-pr handoff",agents:["architect"]},rebind_pr_feedback_head:{description:"rebind a PR_FEEDBACK workflow to a new verified remote PR head after merge/rebase/conflict repair, invalidating ancestry-bound receipts so the mechanical ladder re-runs",agents:["architect"]},run_pr_feedback_stage_a:{description:"execute and persist mandatory PR-feedback Stage A checks on a content-bound revision",agents:["architect"]},submit_council_verdicts:{description:"submit pre-collected council member verdicts for synthesis (architect MUST dispatch critic/reviewer/sme/test_engineer/explorer as Agent tasks first; this tool synthesizes only, it does not contact members)",agents:[]},submit_phase_council_verdicts:{description:"submit pre-collected phase-level council member verdicts for holistic phase synthesis (architect MUST dispatch all 5 council members with phase-scoped context first; this tool synthesizes only, it does not contact members)",agents:[]},declare_council_criteria:{description:"pre-declare acceptance criteria for a task before the coder starts work; criteria are read back during council evaluation",agents:[]},sbom_generate:{description:"SBOM generation for dependency inventory",agents:["architect"]},checkpoint:{description:"create named git checkpoints for save, restore, and delete — use before risky operations to enable rollback",agents:["architect"]},pkg_audit:{description:"dependency vulnerability scan — npm/pip/cargo",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},parse_lane_candidates:{description:"Parse [CANDIDATE] rows from a dispatch_lanes or collect_lane_results artifact (by output_ref), produce structured records with provenance, optionally persist to a per-batch sidecar JSONL. Pure-parser variant exists as internal module.",agents:["architect"]},plan_conflict_check:{description:"read-only advisory check (#1656): compute a pairwise file-conflict matrix for N proposed parallel task groups using declared scopes and optional git co-change; returns a verdict (all_disjoint / conflicts_present / unknown_scopes), per-pair evidence, and a suggested serialization order. Writes nothing — the execution gate independently recomputes the verdict inline at dispatch time via the same helper. Call BEFORE attempting parallel dispatch to confirm disjointness.",agents:["architect"]},write_pr_review_trigger_eval:{description:"persist the complete PR-review trigger evaluation with exact-set validation, dispatch provenance, and live merge-base verification",agents:["architect"]},write_pr_review_artifact:{description:"persist schema-validated PR-review findings checkpoints and exact actionable feedback handoffs under the active run",agents:["architect"]},prepare_pr_feedback_scope:{description:"prepare an exact file scope for one PR-feedback coder Task after immutable feedback verification settles",agents:["architect"]},test_runner:{description:"auto-detect and run tests",agents:["architect","reviewer","critic_finding_validator","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},test_impact:{description:"identify test files impacted by changed source files via import analysis",agents:["architect","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},mutation_test:{description:"executes pre-generated mutation patches against tests, evaluates kill rate against quality gate thresholds",agents:["architect","test_engineer"]},generate_mutants:{description:"generate LLM-based mutation testing patches for source files; returns MutationPatch[] for direct consumption by the mutation_test tool",agents:["architect"]},detect_domains:{description:"detect which SME domains are relevant for a given text",agents:["architect","sme","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic","critic_oversight","explorer"]},git_blame:{description:"per-line git blame metadata: sha, author, date, summary for each line in a file",agents:["reviewer","critic_finding_validator","explorer","architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},gitingest:{description:"fetch a GitHub repository full content via gitingest.com",agents:["architect","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_summary:{description:"retrieve the full content of a stored tool output summary",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_lane_output:{description:"retrieve paged full dispatch lane output by output_ref; use before consuming truncated lane previews or routing candidates from lane results",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},extract_code_blocks:{description:"extract code blocks from text content and save them to files",agents:["docs","docs_design","designer","spec_writer","coder","test_engineer"]},phase_complete:{description:"preflight every applicable phase gate, report all blockers, and atomically commit a current passing snapshot",agents:["architect"]},run_phase_review:{description:"run the bounded phase-final review engine and persist complete content-addressed review evidence",agents:["architect"]},repair_gate_evidence:{description:"quarantine corrupt exact-task gate evidence and install a fresh blocked generation that requires every gate to rerun",agents:["architect"]},repair_knowledge_receipt_ledger:{description:"validate or repair authoritative knowledge receipts, preserve corrupt authority in bounded quarantine, and require scoped re-evaluation",agents:["architect"]},record_directive_override:{description:"record an audited architect override for identified critical-directive violations without bypassing unreadable authority",agents:["architect"]},save_plan:{description:"save a structured implementation plan",agents:["architect"]},update_task_status:{description:"mark tasks complete, track phase progress",agents:["architect"]},lint_spec:{description:"validate .swarm/spec.md format and required fields",agents:["architect","spec_writer"]},write_retro:{description:"document phase retrospectives via phase_complete workflow, capture lessons learned",agents:["architect"]},write_drift_evidence:{description:"write drift verification evidence for a completed phase",agents:["architect"]},write_hallucination_evidence:{description:"write hallucination verification evidence for a completed phase",agents:["architect"]},write_mutation_evidence:{description:"write mutation gate evidence for a completed phase; normalizes PASS/WARN/FAIL/SKIP verdicts and writes .swarm/evidence/{phase}/mutation-gate.json",agents:["architect"]},declare_scope:{description:"declare file scope for next coder delegation",agents:["architect"]},knowledge_query:{description:"query swarm or hive knowledge with optional filters",agents:["architect","skill_improver","spec_writer"]},doc_scan:{description:"scan project documentation files and build an index manifest",agents:["architect","docs_design","skill_improver","spec_writer","explorer"]},doc_extract:{description:"extract actionable constraints from project documentation",agents:["architect","docs_design","skill_improver","spec_writer"]},curator_analyze:{description:"run curator phase analysis and optionally apply knowledge recommendations",agents:["architect"]},consensus_mine:{description:"mine cross-run consensus from existing .swarm evidence into an immutable proposals-only report; also deletes its own reports past consensus.report_retention, appends to the shared recommendation dedup ledger (in the shared cohort root, outside this project, when a knowledge link is active), and mirrors proposals into pending swarm-memory proposals when memory is enabled",agents:["architect","curator_phase","curator_postmortem"]},knowledge_add:{description:"store a new lesson in the knowledge base",agents:["architect","coder"]},knowledge_recall:{description:"search the knowledge base for relevant past decisions",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"]},knowledge_remove:{description:"delete an outdated swarm knowledge entry by ID (swarm tier only)",agents:["architect"]},co_change_analyzer:{description:"detect hidden couplings by analyzing git history",agents:["architect"]},context_status:{description:"report current context-window headroom for the active session — returns tokens-used, usageSource (provider|estimated), model-limit, usage-percent, threshold-state (none/warn/critical), model name, and provider. Pure read-only: no state mutation, no warning injection. Works whether context_budget.enabled is true or false.",agents:["architect"]},search:{description:"Workspace-scoped ripgrep-style text search with structured JSON output. Supports literal and regex modes, glob filtering, and result limits. NOTE: This is text search, not structural AST search — use symbols and imports tools for structural queries.",agents:["architect","sme","docs","docs_design","designer","critic_hallucination_verifier","skill_improver","spec_writer","reviewer","critic_finding_validator","critic_oversight","explorer","coder","test_engineer","researcher"]},ast_grep:{description:"Read-only structural AST search using ast-grep patterns with optional language and glob filters. Use for syntax-aware code pattern searches; does not rewrite files.",agents:["architect","sme","docs","docs_design","critic_hallucination_verifier","spec_writer","explorer","coder","test_engineer","researcher"]},actionlint_scan:{description:"Run actionlint against GitHub Actions workflow YAML files with structured findings. Resolves actionlint lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},osv_scan:{description:"Run OSV-Scanner against a workspace path and return structured dependency vulnerability findings. Resolves osv-scanner lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},gh_evidence:{description:"Fetch bounded GitHub pull request or issue metadata through gh for review and CI evidence. Resolves gh lazily and is read-only.",agents:["architect","researcher"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},pr_workflow_status:{description:"Read-only architect observation of local git state (HEAD, branch, clean/dirty with a bounded changed-file list, remotes) plus a session-pinned PR workflow gate summary. Use to observe state under the fail-closed PR_REVIEW/PR_FEEDBACK gate. Never executes PR-controlled scripts and never reads another session gate.",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},batch_symbols:{description:"Batched symbol extraction across multiple files. Returns per-file symbol summaries with isolated error handling.",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","explorer"]},suggest_patch:{description:"Reviewer-safe structured patch suggestion tool. Produces context-anchored patch artifacts without file modification. Returns structured diagnostics on context mismatch.",agents:["architect","reviewer","critic_finding_validator"]},req_coverage:{description:"query requirement coverage status for tracked functional requirements",agents:["critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","critic","critic_oversight"]},get_approved_plan:{description:"retrieve the last critic-approved immutable plan snapshot for baseline drift comparison",agents:["critic_drift_verifier","critic","critic_oversight"]},repo_map:{description:"query the repo code graph: importers, dependencies, blast radius, localization, ontology facts, package boundaries, and heuristic preflight packets before refactoring; ontology findings are advisory, not formal proofs",agents:["architect","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},get_qa_gate_profile:{description:"retrieve the QA gate profile for the current or exact future plan identity: gates (reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council), lock state, and profile hash. Read-only and never creates state.",agents:["architect"]},set_qa_gates:{description:"configure the QA gate profile for the current plan or bootstrap an exact future plan with swarm_id and plan_title. Architect-only. The initial selection may set explicit true/false values over defaults; later changes are ratchet-tighter and rejected once locked after critic approval. Supports: reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council, plus adopt_legacy_binding_only for exact-binding recovery without mutating gates.",agents:["architect"]},web_search:{description:"External web search (Tavily or Brave) for architect-driven council research, SME domain research, researcher auto-research, and skill-improver research. Returns titled results with snippets, URLs, normalized query metadata, temporal intent, freshness, and removed stale years. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides. Requires a search API key. Used by the architect in MODE: COUNCIL to gather a RESEARCH CONTEXT before dispatching council agents, by SME for opt-in external skill/source evaluation, and by the researcher agent for multi-source auto-research.",agents:["sme","researcher","skill_improver"]},web_fetch:{description:"Fetch the readable text of a single http(s) URL (architect-only). Returns decoded page text, document title, final URL after redirects, and an evidence reference. Reads primary sources that web_search only surfaces as snippets. Config-gated on council.general.enabled. Blocks private/loopback/link-local/metadata addresses (re-validated and re-pinned across redirects); enforces timeout and body size cap.",agents:[]},convene_general_council:{description:"Synthesize responses from a multi-model General Council. Accepts parallel member responses (Round 1, optionally Round 2), detects disagreements, and returns consensus points, persisting disagreements, and a structured synthesis. Architect-only. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides.",agents:[]},write_final_council_evidence:{description:"Persist project-scoped final council evidence to .swarm/evidence/final-council.json. PREREQUISITE: dispatch critic, reviewer, sme, test_engineer, and explorer as project-scoped Agent tasks and collect their CouncilMemberVerdict JSON — this tool synthesizes only. Rejects on insufficient quorum or CONCERNS with unresolved requiredFixes; normalizes verdicts to approved/concerns/rejected. Architect-only.",agents:[]},skill_generate:{description:"compile knowledge entries into a structured SKILL.md draft",agents:["skill_improver"]},skill_list:{description:"list generated skill files and their status",agents:["skill_improver"]},skill_apply:{description:"activate a draft skill proposal",agents:[]},skill_inspect:{description:"inspect the content and source entries of a skill file",agents:["skill_improver"]},run_stale_reconciliation:{description:"reconcile skills against the knowledge store: mark skills stale when source knowledge is archived or deleted, or clear stale markers",agents:["architect"]},skill_regenerate:{description:"regenerate an active skill by re-clustering its source knowledge entries and updating the SKILL.md in place",agents:[]},skill_retire:{description:"retire a generated skill by adding a retired.marker file; retired skills are excluded from scoring and injection",agents:[]},skill_improve:{description:"run the skill_improver agent to review and refine skills",agents:["skill_improver"]},spec_write:{description:"author or update .swarm/spec.md for the current project",agents:["spec_writer"]},knowledge_receipt:{description:"file a receipt for retrieved knowledge (applied/ignored/contradicted + new lessons), recorded as immutable knowledge events",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},knowledge_archive:{description:"archive (default), quarantine, or purge a swarm or hive knowledge entry by ID with an immutable audit tombstone; purge requires an admin flag",agents:["architect"]},swarm_memory_recall:{description:"recall scoped Swarm memory for the current repository as untrusted background",agents:[]},swarm_memory_propose:{description:"create a pending Swarm memory proposal; does not write durable memory directly",agents:[]},swarm_memory_outcome:{description:"record useful, dead-end, or corrected outcomes and, when enabled, synchronously refresh deterministic memory lessons",agents:[]},swarm_command:{description:"run supported /swarm commands through the canonical command registry",agents:["architect","sme","researcher","docs","docs_design","designer","reviewer","critic_finding_validator","critic","explorer","coder","test_engineer"]},dispatch_lanes:{description:"dispatch read-only exploration/review lanes concurrently and BLOCK until all finish; prefer dispatch_lanes_async for non-blocking dispatch, use this only when promptAsync is unavailable",agents:["architect"]},dispatch_lanes_async:{description:"launch read-only advisory lanes non-blockingly and return a batch id plus lane session handles immediately so you can keep working; launch_timeout_ms is only a promptAsync acceptance budget, not a lane runtime timeout; poll incrementally with collect_lane_results (wait omitted or false) while doing independent investigation, or join with wait: true when you need all results",agents:["architect"]},collect_lane_results:{description:"collect or poll results for a dispatch_lanes_async batch; supports both non-blocking polling (wait omitted or false) and blocking join (wait: true). Non-blocking polls include pending lane identities by default and process settled lanes incrementally while continuing independent work; busy/retry lanes are not timed out just because they run for a long time. Does not advance workflow gates. Inline output for a settled lane is delivered only once: later polls of the same lane set output_omitted_repeat: true and omit output, but still include output_ref for recovery via retrieve_lane_output.",agents:["architect"]},summarize_work:{description:"emit a short structured summary of completed work (key decisions, assumptions, risks, constraints) at task completion; rolls up per phase for architecture-supervisor review. Advisory, never blocks.",agents:["architect","sme","researcher","docs","docs_design","designer","explorer","coder","test_engineer"]},write_architecture_supervisor_evidence:{description:"persist the architecture supervisor verdict for a phase (architect MUST dispatch critic_architecture_supervisor first and collect its JSON verdict; this tool persists only, it does not contact the supervisor)",agents:["architect"]},lean_turbo_plan_lanes:{description:"partition phase tasks into parallel lanes based on file-scope conflicts for Lean Turbo execution",agents:[]},lean_turbo_acquire_locks:{description:"acquire file locks for all files in a lane (all-or-nothing) before lane execution",agents:[]},lean_turbo_runner_status:{description:"read Lean Turbo run state from .swarm/turbo-state.json",agents:[]},lean_turbo_review:{description:"dispatch a read-only reviewer agent to evaluate a completed Lean Turbo phase",agents:[]},lean_turbo_run_phase:{description:"Execute a phase using Lean Turbo parallel lane execution. Plans lanes, acquires file locks, and dispatches coder agents concurrently. Use when Lean Turbo is active and you want to execute all tasks in a phase in parallel lanes.",agents:[]},lean_turbo_status:{description:"returns Lean Turbo configuration and active status for the current session",agents:[]},swarm_apply_patch:{description:"Apply a unified diff patch to workspace files with exact context matching, atomic writes, and path validation. Use standard unified diff format only — does NOT support *** Begin Patch / *** Update File payloads (use native apply_patch for those).",agents:["coder","test_engineer"]},external_skill_discover:{description:"Discover external skill candidates from configured sources. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_list:{description:"List external skill candidates in the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_inspect:{description:"Inspect a specific external skill candidate by ID. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_promote:{description:"Promote a validated external skill candidate to an active generated skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_reject:{description:"Reject an external skill candidate after evaluation. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_delete:{description:"Delete an external skill candidate from the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_revoke:{description:"Revoke a previously promoted external skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},epic_decide_phase:{description:"Compute the Epic Mode verdict for a phase WITHOUT dispatching coders. Runs preflight + calibration + the three gates (p-threshold, hot-module, greenfield), persists the decision, and returns the verdict so the architect can dispatch waves via the visible Task tool (promote) or fall back to per-task serial (demote). Pair with `epic_plan_waves` to get the wave plan when promoted. Use when /swarm epic is on for the session.",agents:["architect"]},epic_plan_waves:{description:"Partition a phase's pending tasks into ordered concurrent waves for Epic Mode dispatch. A wave is a set of tasks with mutually disjoint declared scopes and all dependencies satisfied by prior waves. Returns `{ waves: [{ waveId, taskIds, files }, ...], serializedTasks, degradedTasks }`. "+'For each wave in order, the architect dispatches one `Task(subagent_type="coder", ...)` per `taskId` — all in one assistant message — so the wave runs concurrently and each coder appears as a visible subagent. '+"Wait for the wave to finish before dispatching the next. Pair with `epic_decide_phase` (called first; this tool is only relevant on a `promote` verdict). "+"Preflight reject reasons: `no-plan`, `no-phase`, `phase-empty`, `phase-already-complete`, `scopes-missing` (call `declare_scope` for `missingScopes`), `git-failed` (transient — retry), `planner-error`.",agents:["architect"]},epic_record_divergence:{description:"After every `update_task_status(completed)`, record the task's declared-vs-actual divergence to .swarm/epic/divergence.jsonl. Feeds Epic Mode's self-calibration loop (Capability D). Best-effort: never blocks.",agents:["architect"]}},TOOL_NAMES=Object.keys(TOOL_METADATA),TOOL_NAME_SET=new Set(TOOL_NAMES);TOOL_DESCRIPTIONS=Object.fromEntries(Object.entries(TOOL_METADATA).map(([name,meta])=>[name,meta.description])),AGENT_TOOL_MAP=(()=>{let map=Object.fromEntries(ALL_AGENT_NAMES.map((agent)=>[agent,[]]));for(let[name,meta]of Object.entries(TOOL_METADATA))for(let agent of meta.agents)map[agent].push(name);return map})()});function deepMergeInternal(base,override,depth){if(depth>=10)throw Error("deepMerge exceeded maximum depth of 10");let result={...base};for(let key of Object.keys(override)){let baseVal=base[key],overrideVal=override[key];if(typeof baseVal==="object"&&baseVal!==null&&typeof overrideVal==="object"&&overrideVal!==null&&!Array.isArray(baseVal)&&!Array.isArray(overrideVal))result[key]=deepMergeInternal(baseVal,overrideVal,depth+1);else result[key]=overrideVal}return result}function deepMerge(base,override){if(!base)return override;if(!override)return base;return deepMergeInternal(base,override,0)}var MAX_MERGE_DEPTH=10;function freezeSet(items){let set=new Set(items),proxy=new Proxy(set,{get(target,prop){if(prop==="add"||prop==="delete"||prop==="clear")return()=>{throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")};if(prop==="forEach")return(callback,thisArg)=>{let wrapped=(v,k)=>callback.call(thisArg??void 0,v,k,proxy);return set.forEach(wrapped)};let value=Reflect.get(target,prop);return typeof value==="function"?value.bind(target):value},set(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},deleteProperty(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},defineProperty(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},setPrototypeOf(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")}});return proxy}function isQAAgent(name){return QA_AGENTS.includes(name)}function isSubagent(name){return ALL_SUBAGENT_NAMES.includes(name)}function isLowCapabilityModel(modelId){let lower=(modelId||"").toLowerCase();return LOW_CAPABILITY_MODELS.some((substr)=>lower.includes(substr))}var OPENCODE_NATIVE_AGENTS,CLAUDE_CODE_NATIVE_COMMANDS,MEMORY_AGENT_TOOL_MAP,EXTERNAL_SKILL_TOOL_NAMES,EXTERNAL_SKILL_AGENT_TOOL_MAP,COUNCIL_TOOL_NAMES,COUNCIL_AGENT_TOOL_MAP,GENERAL_COUNCIL_TOOL_NAMES,GENERAL_COUNCIL_AGENT_TOOL_MAP,TURBO_TOOL_NAMES,TURBO_AGENT_TOOL_MAP,SKILL_TOOL_NAMES,SKILL_AGENT_TOOL_MAP,WRITE_TOOL_NAMES,SUMMARIZER_EXEMPT_TOOL_NAMES,DEFAULT_MODELS,DEFAULT_AGENT_CONFIGS,DEFAULT_SCORING_CONFIG,LOW_CAPABILITY_MODELS,TURBO_MODE_BANNER=`## \uD83D\uDE80 TURBO MODE ACTIVE
1
+ import{createRequire}from"node:module";var __create=Object.create;var{getPrototypeOf:__getProtoOf,defineProperty:__defProp,getOwnPropertyNames:__getOwnPropNames,getOwnPropertyDescriptor:__getOwnPropDesc}=Object,__hasOwnProp=Object.prototype.hasOwnProperty;function __accessProp(key){return this[key]}var __toESMCache_node,__toESMCache_esm,__toESM=(mod,isNodeMode,target)=>{var canCache=mod!=null&&typeof mod==="object";if(canCache){var cache=isNodeMode?__toESMCache_node??=new WeakMap:__toESMCache_esm??=new WeakMap,cached=cache.get(mod);if(cached)return cached}target=mod!=null?__create(__getProtoOf(mod)):{};let to=isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target;for(let key of __getOwnPropNames(mod))if(!__hasOwnProp.call(to,key))__defProp(to,key,{get:__accessProp.bind(mod,key),enumerable:!0});if(canCache)cache.set(mod,to);return to},__toCommonJS=(from)=>{var entry=(__moduleCache??=new WeakMap).get(from),desc;if(entry)return entry;if(entry=__defProp({},"__esModule",{value:!0}),from&&typeof from==="object"||typeof from==="function"){for(var key of __getOwnPropNames(from))if(!__hasOwnProp.call(entry,key))__defProp(entry,key,{get:__accessProp.bind(from,key),enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return __moduleCache.set(from,entry),entry},__moduleCache,__commonJS=(cb,mod)=>()=>(mod||cb((mod={exports:{}}).exports,mod),mod.exports);var __returnValue=(v)=>v;function __exportSetter(name,newValue){this[name]=__returnValue.bind(null,newValue)}var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0,configurable:!0,set:__exportSetter.bind(all,name)})};var __esm=(fn2,res)=>()=>(fn2&&(res=fn2(fn2=0)),res);var __require=createRequire(import.meta.url);var package_default;var init_package=__esm(()=>{package_default={name:"opencode-swarm",version:"7.148.4",description:"Architect-centric agentic swarm plugin for OpenCode - hub-and-spoke orchestration with SME consultation, code generation, and QA review",main:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",default:"./dist/index.js"},"./package.json":"./package.json"},bin:{"opencode-swarm":"./dist/cli/index.js"},type:"module",engines:{bun:">=1.3.13"},license:"MIT",repository:{type:"git",url:"https://github.com/ZaxbyHub/opencode-swarm.git"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},keywords:["opencode","opencode-plugin","ai","agents","orchestration","swarm","multi-agent","llm"],files:["dist","dist/lang/grammars","binaries","evaluation-fixtures",".opencode/skills/brainstorm",".opencode/skills/specify",".opencode/skills/clarify-spec",".opencode/skills/resume",".opencode/skills/clarify",".opencode/skills/discover",".opencode/skills/consult",".opencode/skills/pre-phase-briefing",".opencode/skills/council",".opencode/skills/deep-dive",".opencode/skills/deep-research",".opencode/skills/codebase-review-swarm",".opencode/skills/swarm-implement",".opencode/skills/design-docs",".opencode/skills/swarm-pr-review",".opencode/skills/swarm",".opencode/skills/swarm-pr-feedback",".opencode/skills/swarm-pr-subscribe",".opencode/skills/swarm-ci-monitor",".opencode/skills/issue-ingest",".opencode/skills/plan",".opencode/skills/critic-gate",".opencode/skills/execute",".opencode/skills/phase-wrap",".opencode/skills/loop",".opencode/skills/writing-tests",".opencode/skills/running-tests",".opencode/skills/engineering-conventions",".opencode/skills/commit-pr",".opencode/skills/ci-failure-batching",".opencode/skills/gate-attribution",".opencode/skills/merge-queue-readiness",".opencode/skills/skill-edit-validation",".opencode/skills/worktree-retry-cleanup",".opencode/skills/test-file-split",".opencode/skills/fork-pr-operations",".opencode/skills/parallel-work-check",".opencode/skills/ci-fix-monitor",".opencode/skills/issue-tracer",".opencode/skills/orchestrating-subagents",".opencode/skills/durable-session-state","tests/fixtures/memory-recall","README.md","LICENSE"],scripts:{clean:`bun -e "require('fs').rmSync('dist',{recursive:true,force:true})"`,build:"bun run clean && bun run scripts/copy-grammars.ts && bun build src/index.ts --outdir dist --target node --format esm --external web-tree-sitter --minify-whitespace --minify-syntax && bun build src/cli/index.ts --outdir dist/cli --target bun --format esm --external bash-parser --splitting && bun run scripts/copy-grammars.ts --to-dist && tsc --emitDeclarationOnly",typecheck:"tsc --noEmit",test:"bun test",lint:"biome lint .","lint:ci":"biome ci .","test:unit:ci":"bun scripts/ci/run-unit-tests-local.ts","drift:check":"bun run scripts/drift-check.ts","check:runtime-src-refs":"bun run scripts/check-runtime-src-refs.ts","drift:fix":"bun run scripts/drift-check.ts --fix --confirm","skills:sync":"bun run scripts/sync-qa-gate-skills.ts",format:"biome format . --write",check:"biome check --write .",dev:"bun run build && opencode","package:smoke":"node scripts/package-smoke.mjs",prepare:"bun run build","repro:704":"node scripts/repro-704.mjs","repro:1144":"bun scripts/repro-1144.mjs","repro:1873":"bun build scripts/repro-1873-entry.ts --outdir dist-build-test/repro-1873 --target node --format esm && node scripts/repro-1873.mjs","check:events":"bun run scripts/check-event-contract.ts","check:retention":"bun run scripts/check-retention-registry.ts","check:test-file-cap":"bun run scripts/check-test-file-cap.ts","check:pending-fragment":"bun run scripts/check-pending-fragment.ts","check:gate-portability":"bun run scripts/check-gate-portability.ts","check:bare-spawn":"bun run scripts/check-bare-executable-spawn.ts","check:memory-recall":"bun run scripts/memory-recall-regression.ts"},dependencies:{"@opencode-ai/plugin":"^1.18.3","@opencode-ai/sdk":"^1.18.3","@vscode/tree-sitter-wasm":"^0.3.0","bash-parser":"^0.5.0","p-limit":"^7.3.0",picomatch:"^4.0.4","proper-lockfile":"^4.1.2","quick-lru":"^7.3.0","web-tree-sitter":"^0.25.0",zod:"^4.1.8"},devDependencies:{"@biomejs/biome":"2.3.14","@types/picomatch":"^4.0.3","bun-types":"1.3.8","js-yaml":"^4.1.1",typescript:"^5.7.3"},peerDependencies:{"@xenova/transformers":"^2.17.2"},peerDependenciesMeta:{"@xenova/transformers":{optional:!0}}}});var QA_AGENTS,PIPELINE_AGENTS,ORCHESTRATOR_NAME="architect",ALL_SUBAGENT_NAMES,ALL_AGENT_NAMES;var init_agent_names=__esm(()=>{QA_AGENTS=["reviewer","critic","critic_oversight","critic_finding_validator"],PIPELINE_AGENTS=["explorer","coder","test_engineer"],ALL_SUBAGENT_NAMES=["sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","curator_postmortem","curator_consolidation","council_generalist","council_skeptic","council_domain_expert","skill_improver","spec_writer",...QA_AGENTS,...PIPELINE_AGENTS],ALL_AGENT_NAMES=["architect",...ALL_SUBAGENT_NAMES]});function getPrWorkflowToolCapability(toolName,mode){let metadata=TOOL_METADATA[toolName];if(!metadata?.prWorkflow?.modes.includes(mode))return null;return metadata.prWorkflow.capability}var TOOL_METADATA,TOOL_NAMES,TOOL_NAME_SET,TOOL_DESCRIPTIONS,AGENT_TOOL_MAP;var init_tool_metadata=__esm(()=>{init_agent_names();TOOL_METADATA={diff:{description:"structured git diff with contract change detection",agents:["architect","reviewer","critic_finding_validator","critic_oversight","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},diff_summary:{description:"filter classified AST changes by category, risk level, or file for reviewer drill-down",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},syntax_check:{description:"check syntax of source files using tree-sitter parsers across multiple languages, returning per-file errors",agents:["architect","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},placeholder_scan:{description:"todo and FIXME comment detection",agents:["architect","reviewer","critic_finding_validator"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},imports:{description:"find all consumers that import from a given file — use before refactoring shared modules to avoid breaking unseen dependents",agents:["architect","sme","researcher","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},lint:{description:"run project linter in check or fix mode; supports biome, eslint, ruff, clippy, and more, returns structured results",agents:["architect","reviewer","critic_finding_validator","coder"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},secretscan:{description:"scan for secrets (API keys, tokens, passwords) via regex and entropy; returns redacted previews, excludes common dirs",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},sast_scan:{description:"static analysis security scan",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},build_check:{description:"discover and run build, typecheck, and test commands for various project ecosystems in the working directory",agents:["architect","coder","test_engineer"]},pre_check_batch:{description:"parallel verification: lint:check + secretscan + sast_scan + quality_budget",agents:["architect","reviewer","critic_finding_validator"]},quality_budget:{description:"code quality budget check",agents:["architect"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},symbols:{description:"extract exported symbols (functions, classes, interfaces, types) from source files; supports TypeScript, JavaScript, and Python",agents:["architect","sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},complexity_hotspots:{description:"git churn × complexity risk map",agents:["architect","sme","researcher","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","critic_oversight","explorer","test_engineer"]},schema_drift:{description:"OpenAPI spec vs route drift",agents:["architect","sme","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},todo_extract:{description:"structured TODO/FIXME extraction",agents:["architect","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},evidence_check:{description:"verify task evidence completeness",agents:["architect","critic_oversight"]},check_gate_status:{description:"check the gate status of a specific task",agents:["architect","critic_oversight"]},completion_verify:{description:"verify completed tasks have required evidence",agents:["architect","critic_oversight"]},complete_pr_workflow:{description:"validate terminal PR workflow evidence and clear its durable session gate",agents:["architect"]},abort_pr_workflow:{description:"abort an unrecoverable PR_REVIEW/PR_FEEDBACK mechanical gate and clear its durable session state",agents:["architect"]},approve_plan_critic:{description:"record a MANUAL plan_critic_gate approval snapshot to unblock the ratchet-tighter critic_pre_plan execution gate when the critic already returned APPROVED but the mechanical recorder failed to persist it (issue #2012)",agents:["architect"]},prepare_pr_workflow_checkout:{description:"prepare an auditable PR workflow checkout or restore its exact original branch/HEAD and preserved stash after terminal cleanup",agents:["architect"]},record_implementation_review:{description:"record fresh-context reviewer + critic APPROVE verdicts for the implementation diff so the /swarm issue --trace workflow can satisfy its review gate before commit-pr handoff",agents:["architect"]},record_issue_publication:{description:"record a publication receipt so the /swarm issue --trace workflow reaches its terminal published state after the PR is created/updated",agents:["architect"]},record_issue_reproduction:{description:"record the reproduction outcome for the current traced issue so the /swarm issue --trace workflow can satisfy its reproduction gate and transition to PLAN",agents:["architect"]},record_recurrence_sweep:{description:"record the recurrence sweep (defect class, predicates, hit dispositions, guardrail proof) so the /swarm issue --trace workflow can satisfy its recurrence gate before commit-pr handoff",agents:["architect"]},rebind_pr_feedback_head:{description:"rebind a PR_FEEDBACK workflow to a new verified remote PR head after merge/rebase/conflict repair, invalidating ancestry-bound receipts so the mechanical ladder re-runs",agents:["architect"]},run_pr_feedback_stage_a:{description:"execute and persist mandatory PR-feedback Stage A checks on a content-bound revision",agents:["architect"]},submit_council_verdicts:{description:"submit pre-collected council member verdicts for synthesis (architect MUST dispatch critic/reviewer/sme/test_engineer/explorer as Agent tasks first; this tool synthesizes only, it does not contact members)",agents:[]},submit_phase_council_verdicts:{description:"submit pre-collected phase-level council member verdicts for holistic phase synthesis (architect MUST dispatch all 5 council members with phase-scoped context first; this tool synthesizes only, it does not contact members)",agents:[]},declare_council_criteria:{description:"pre-declare acceptance criteria for a task before the coder starts work; criteria are read back during council evaluation",agents:[]},sbom_generate:{description:"SBOM generation for dependency inventory",agents:["architect"]},checkpoint:{description:"create named git checkpoints for save, restore, and delete — use before risky operations to enable rollback",agents:["architect"]},pkg_audit:{description:"dependency vulnerability scan — npm/pip/cargo",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},parse_lane_candidates:{description:"Parse [CANDIDATE] rows from a dispatch_lanes or collect_lane_results artifact (by output_ref), produce structured records with provenance, optionally persist to a per-batch sidecar JSONL. Pure-parser variant exists as internal module.",agents:["architect"]},plan_conflict_check:{description:"read-only advisory check (#1656): compute a pairwise file-conflict matrix for N proposed parallel task groups using declared scopes and optional git co-change; returns a verdict (all_disjoint / conflicts_present / unknown_scopes), per-pair evidence, and a suggested serialization order. Writes nothing — the execution gate independently recomputes the verdict inline at dispatch time via the same helper. Call BEFORE attempting parallel dispatch to confirm disjointness.",agents:["architect"]},write_pr_review_trigger_eval:{description:"persist the complete PR-review trigger evaluation with exact-set validation, dispatch provenance, and live merge-base verification",agents:["architect"]},write_pr_review_artifact:{description:"persist schema-validated PR-review findings checkpoints and exact actionable feedback handoffs under the active run",agents:["architect"]},prepare_pr_feedback_scope:{description:"prepare an exact file scope for one PR-feedback coder Task after immutable feedback verification settles",agents:["architect"]},test_runner:{description:"auto-detect and run tests",agents:["architect","reviewer","critic_finding_validator","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},test_impact:{description:"identify test files impacted by changed source files via import analysis",agents:["architect","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},mutation_test:{description:"executes pre-generated mutation patches against tests, evaluates kill rate against quality gate thresholds",agents:["architect","test_engineer"]},generate_mutants:{description:"generate LLM-based mutation testing patches for source files; returns MutationPatch[] for direct consumption by the mutation_test tool",agents:["architect"]},detect_domains:{description:"detect which SME domains are relevant for a given text",agents:["architect","sme","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic","critic_oversight","explorer"]},git_blame:{description:"per-line git blame metadata: sha, author, date, summary for each line in a file",agents:["reviewer","critic_finding_validator","explorer","architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},gitingest:{description:"fetch a GitHub repository full content via gitingest.com",agents:["architect","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_summary:{description:"retrieve the full content of a stored tool output summary",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_lane_output:{description:"retrieve paged full dispatch lane output by output_ref; use before consuming truncated lane previews or routing candidates from lane results",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},extract_code_blocks:{description:"extract code blocks from text content and save them to files",agents:["docs","docs_design","designer","spec_writer","coder","test_engineer"]},phase_complete:{description:"preflight every applicable phase gate, report all blockers, and atomically commit a current passing snapshot",agents:["architect"]},run_phase_review:{description:"run the bounded phase-final review engine and persist complete content-addressed review evidence",agents:["architect"]},repair_gate_evidence:{description:"quarantine corrupt exact-task gate evidence and install a fresh blocked generation that requires every gate to rerun",agents:["architect"]},repair_knowledge_receipt_ledger:{description:"validate or repair authoritative knowledge receipts, preserve corrupt authority in bounded quarantine, and require scoped re-evaluation",agents:["architect"]},record_directive_override:{description:"record an audited architect override for identified critical-directive violations without bypassing unreadable authority",agents:["architect"]},save_plan:{description:"save a structured implementation plan",agents:["architect"]},update_task_status:{description:"mark tasks complete, track phase progress",agents:["architect"]},lint_spec:{description:"validate .swarm/spec.md format and required fields",agents:["architect","spec_writer"]},write_retro:{description:"document phase retrospectives via phase_complete workflow, capture lessons learned",agents:["architect"]},write_drift_evidence:{description:"write drift verification evidence for a completed phase",agents:["architect"]},write_hallucination_evidence:{description:"write hallucination verification evidence for a completed phase",agents:["architect"]},write_mutation_evidence:{description:"write mutation gate evidence for a completed phase; normalizes PASS/WARN/FAIL/SKIP verdicts and writes .swarm/evidence/{phase}/mutation-gate.json",agents:["architect"]},declare_scope:{description:"declare file scope for next coder delegation",agents:["architect"]},knowledge_query:{description:"query swarm or hive knowledge with optional filters",agents:["architect","skill_improver","spec_writer"]},doc_scan:{description:"scan project documentation files and build an index manifest",agents:["architect","docs_design","skill_improver","spec_writer","explorer"]},doc_extract:{description:"extract actionable constraints from project documentation",agents:["architect","docs_design","skill_improver","spec_writer"]},curator_analyze:{description:"run curator phase analysis and optionally apply knowledge recommendations",agents:["architect"]},consensus_mine:{description:"mine cross-run consensus from existing .swarm evidence into an immutable proposals-only report; also deletes its own reports past consensus.report_retention, appends to the shared recommendation dedup ledger (in the shared cohort root, outside this project, when a knowledge link is active), and mirrors proposals into pending swarm-memory proposals when memory is enabled",agents:["architect","curator_phase","curator_postmortem"]},knowledge_add:{description:"store a new lesson in the knowledge base",agents:["architect","coder"]},knowledge_recall:{description:"search the knowledge base for relevant past decisions",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"]},knowledge_remove:{description:"delete an outdated swarm knowledge entry by ID (swarm tier only)",agents:["architect"]},co_change_analyzer:{description:"detect hidden couplings by analyzing git history",agents:["architect"]},context_status:{description:"report current context-window headroom for the active session — returns tokens-used, usageSource (provider|estimated), model-limit, usage-percent, threshold-state (none/warn/critical), model name, and provider. Pure read-only: no state mutation, no warning injection. Works whether context_budget.enabled is true or false.",agents:["architect"]},search:{description:"Workspace-scoped ripgrep-style text search with structured JSON output. Supports literal and regex modes, glob filtering, and result limits. NOTE: This is text search, not structural AST search — use symbols and imports tools for structural queries.",agents:["architect","sme","docs","docs_design","designer","critic_hallucination_verifier","skill_improver","spec_writer","reviewer","critic_finding_validator","critic_oversight","explorer","coder","test_engineer","researcher"]},ast_grep:{description:"Read-only structural AST search using ast-grep patterns with optional language and glob filters. Use for syntax-aware code pattern searches; does not rewrite files.",agents:["architect","sme","docs","docs_design","critic_hallucination_verifier","spec_writer","explorer","coder","test_engineer","researcher"]},actionlint_scan:{description:"Run actionlint against GitHub Actions workflow YAML files with structured findings. Resolves actionlint lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},osv_scan:{description:"Run OSV-Scanner against a workspace path and return structured dependency vulnerability findings. Resolves osv-scanner lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},gh_evidence:{description:"Fetch bounded GitHub pull request or issue metadata through gh for review and CI evidence. Resolves gh lazily and is read-only.",agents:["architect","researcher"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},pr_workflow_status:{description:"Read-only architect observation of local git state (HEAD, branch, clean/dirty with a bounded changed-file list, remotes) plus a session-pinned PR workflow gate summary. Use to observe state under the fail-closed PR_REVIEW/PR_FEEDBACK gate. Never executes PR-controlled scripts and never reads another session gate.",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},batch_symbols:{description:"Batched symbol extraction across multiple files. Returns per-file symbol summaries with isolated error handling.",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","explorer"]},suggest_patch:{description:"Reviewer-safe structured patch suggestion tool. Produces context-anchored patch artifacts without file modification. Returns structured diagnostics on context mismatch.",agents:["architect","reviewer","critic_finding_validator"]},req_coverage:{description:"query requirement coverage status for tracked functional requirements",agents:["critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","critic","critic_oversight"]},get_approved_plan:{description:"retrieve the last critic-approved immutable plan snapshot for baseline drift comparison",agents:["critic_drift_verifier","critic","critic_oversight"]},repo_map:{description:"query the repo code graph: importers, dependencies, blast radius, localization, ontology facts, package boundaries, and heuristic preflight packets before refactoring; ontology findings are advisory, not formal proofs",agents:["architect","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},get_qa_gate_profile:{description:"retrieve the QA gate profile for the current or exact future plan identity: gates (reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council), lock state, and profile hash. Read-only and never creates state.",agents:["architect"]},set_qa_gates:{description:"configure the QA gate profile for the current plan or bootstrap an exact future plan with swarm_id and plan_title. Architect-only. The initial selection may set explicit true/false values over defaults; later changes are ratchet-tighter and rejected once locked after critic approval. Supports: reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council, plus adopt_legacy_binding_only for exact-binding recovery without mutating gates.",agents:["architect"]},web_search:{description:"External web search (Tavily or Brave) for architect-driven council research, SME domain research, researcher auto-research, and skill-improver research. Returns titled results with snippets, URLs, normalized query metadata, temporal intent, freshness, and removed stale years. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides. Requires a search API key. Used by the architect in MODE: COUNCIL to gather a RESEARCH CONTEXT before dispatching council agents, by SME for opt-in external skill/source evaluation, and by the researcher agent for multi-source auto-research.",agents:["sme","researcher","skill_improver"]},web_fetch:{description:"Fetch the readable text of a single http(s) URL (architect-only). Returns decoded page text, document title, final URL after redirects, and an evidence reference. Reads primary sources that web_search only surfaces as snippets. Config-gated on council.general.enabled. Blocks private/loopback/link-local/metadata addresses (re-validated and re-pinned across redirects); enforces timeout and body size cap.",agents:[]},convene_general_council:{description:"Synthesize responses from a multi-model General Council. Accepts parallel member responses (Round 1, optionally Round 2), detects disagreements, and returns consensus points, persisting disagreements, and a structured synthesis. Architect-only. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides.",agents:[]},write_final_council_evidence:{description:"Persist project-scoped final council evidence to .swarm/evidence/final-council.json. PREREQUISITE: dispatch critic, reviewer, sme, test_engineer, and explorer as project-scoped Agent tasks and collect their CouncilMemberVerdict JSON — this tool synthesizes only. Rejects on insufficient quorum or CONCERNS with unresolved requiredFixes; normalizes verdicts to approved/concerns/rejected. Architect-only.",agents:[]},skill_generate:{description:"compile knowledge entries into a structured SKILL.md draft",agents:["skill_improver"]},skill_list:{description:"list generated skill files and their status",agents:["skill_improver"]},skill_apply:{description:"activate a draft skill proposal",agents:[]},skill_inspect:{description:"inspect the content and source entries of a skill file",agents:["skill_improver"]},run_stale_reconciliation:{description:"reconcile skills against the knowledge store: mark skills stale when source knowledge is archived or deleted, or clear stale markers",agents:["architect"]},skill_regenerate:{description:"regenerate an active skill by re-clustering its source knowledge entries and updating the SKILL.md in place",agents:[]},skill_retire:{description:"retire a generated skill by adding a retired.marker file; retired skills are excluded from scoring and injection",agents:[]},skill_improve:{description:"run the skill_improver agent to review and refine skills",agents:["skill_improver"]},spec_write:{description:"author or update .swarm/spec.md for the current project",agents:["spec_writer"]},knowledge_receipt:{description:"file a receipt for retrieved knowledge (applied/ignored/contradicted + new lessons), recorded as immutable knowledge events",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},knowledge_archive:{description:"archive (default), quarantine, or purge a swarm or hive knowledge entry by ID with an immutable audit tombstone; purge requires an admin flag",agents:["architect"]},swarm_memory_recall:{description:"recall scoped Swarm memory for the current repository as untrusted background",agents:[]},swarm_memory_propose:{description:"create a pending Swarm memory proposal; does not write durable memory directly",agents:[]},swarm_memory_outcome:{description:"record useful, dead-end, or corrected outcomes and, when enabled, synchronously refresh deterministic memory lessons",agents:[]},swarm_command:{description:"run supported /swarm commands through the canonical command registry",agents:["architect","sme","researcher","docs","docs_design","designer","reviewer","critic_finding_validator","critic","explorer","coder","test_engineer"]},dispatch_lanes:{description:"dispatch read-only exploration/review lanes concurrently and BLOCK until all finish; prefer dispatch_lanes_async for non-blocking dispatch, use this only when promptAsync is unavailable",agents:["architect"]},dispatch_lanes_async:{description:"launch read-only advisory lanes non-blockingly and return a batch id plus lane session handles immediately so you can keep working; launch_timeout_ms is only a promptAsync acceptance budget, not a lane runtime timeout; poll incrementally with collect_lane_results (wait omitted or false) while doing independent investigation, or join with wait: true when you need all results",agents:["architect"]},collect_lane_results:{description:"collect or poll results for a dispatch_lanes_async batch; supports both non-blocking polling (wait omitted or false) and blocking join (wait: true). Non-blocking polls include pending lane identities by default and process settled lanes incrementally while continuing independent work; busy/retry lanes are not timed out just because they run for a long time. Does not advance workflow gates. Inline output for a settled lane is delivered only once: later polls of the same lane set output_omitted_repeat: true and omit output, but still include output_ref for recovery via retrieve_lane_output.",agents:["architect"]},summarize_work:{description:"emit a short structured summary of completed work (key decisions, assumptions, risks, constraints) at task completion; rolls up per phase for architecture-supervisor review. Advisory, never blocks.",agents:["architect","sme","researcher","docs","docs_design","designer","explorer","coder","test_engineer"]},write_architecture_supervisor_evidence:{description:"persist the architecture supervisor verdict for a phase (architect MUST dispatch critic_architecture_supervisor first and collect its JSON verdict; this tool persists only, it does not contact the supervisor)",agents:["architect"]},lean_turbo_plan_lanes:{description:"partition phase tasks into parallel lanes based on file-scope conflicts for Lean Turbo execution",agents:[]},lean_turbo_acquire_locks:{description:"acquire file locks for all files in a lane (all-or-nothing) before lane execution",agents:[]},lean_turbo_runner_status:{description:"read Lean Turbo run state from .swarm/turbo-state.json",agents:[]},lean_turbo_review:{description:"dispatch a read-only reviewer agent to evaluate a completed Lean Turbo phase",agents:[]},lean_turbo_run_phase:{description:"Execute a phase using Lean Turbo parallel lane execution. Plans lanes, acquires file locks, and dispatches coder agents concurrently. Use when Lean Turbo is active and you want to execute all tasks in a phase in parallel lanes.",agents:[]},lean_turbo_status:{description:"returns Lean Turbo configuration and active status for the current session",agents:[]},swarm_apply_patch:{description:"Apply a unified diff patch to workspace files with exact context matching, atomic writes, and path validation. Use standard unified diff format only — does NOT support *** Begin Patch / *** Update File payloads (use native apply_patch for those).",agents:["coder","test_engineer"]},external_skill_discover:{description:"Discover external skill candidates from configured sources. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_list:{description:"List external skill candidates in the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_inspect:{description:"Inspect a specific external skill candidate by ID. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_promote:{description:"Promote a validated external skill candidate to an active generated skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_reject:{description:"Reject an external skill candidate after evaluation. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_delete:{description:"Delete an external skill candidate from the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_revoke:{description:"Revoke a previously promoted external skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},epic_decide_phase:{description:"Compute the Epic Mode verdict for a phase WITHOUT dispatching coders. Runs preflight + calibration + the three gates (p-threshold, hot-module, greenfield), persists the decision, and returns the verdict so the architect can dispatch waves via the visible Task tool (promote) or fall back to per-task serial (demote). Pair with `epic_plan_waves` to get the wave plan when promoted. Use when /swarm epic is on for the session.",agents:["architect"]},epic_plan_waves:{description:"Partition a phase's pending tasks into ordered concurrent waves for Epic Mode dispatch. A wave is a set of tasks with mutually disjoint declared scopes and all dependencies satisfied by prior waves. Returns `{ waves: [{ waveId, taskIds, files }, ...], serializedTasks, degradedTasks }`. "+'For each wave in order, the architect dispatches one `Task(subagent_type="coder", ...)` per `taskId` — all in one assistant message — so the wave runs concurrently and each coder appears as a visible subagent. '+"Wait for the wave to finish before dispatching the next. Pair with `epic_decide_phase` (called first; this tool is only relevant on a `promote` verdict). "+"Preflight reject reasons: `no-plan`, `no-phase`, `phase-empty`, `phase-already-complete`, `scopes-missing` (call `declare_scope` for `missingScopes`), `git-failed` (transient — retry), `planner-error`.",agents:["architect"]},epic_record_divergence:{description:"After every `update_task_status(completed)`, record the task's declared-vs-actual divergence to .swarm/epic/divergence.jsonl. Feeds Epic Mode's self-calibration loop (Capability D). Best-effort: never blocks.",agents:["architect"]}},TOOL_NAMES=Object.keys(TOOL_METADATA),TOOL_NAME_SET=new Set(TOOL_NAMES);TOOL_DESCRIPTIONS=Object.fromEntries(Object.entries(TOOL_METADATA).map(([name,meta])=>[name,meta.description])),AGENT_TOOL_MAP=(()=>{let map=Object.fromEntries(ALL_AGENT_NAMES.map((agent)=>[agent,[]]));for(let[name,meta]of Object.entries(TOOL_METADATA))for(let agent of meta.agents)map[agent].push(name);return map})()});function deepMergeInternal(base,override,depth){if(depth>=10)throw Error("deepMerge exceeded maximum depth of 10");let result={...base};for(let key of Object.keys(override)){let baseVal=base[key],overrideVal=override[key];if(typeof baseVal==="object"&&baseVal!==null&&typeof overrideVal==="object"&&overrideVal!==null&&!Array.isArray(baseVal)&&!Array.isArray(overrideVal))result[key]=deepMergeInternal(baseVal,overrideVal,depth+1);else result[key]=overrideVal}return result}function deepMerge(base,override){if(!base)return override;if(!override)return base;return deepMergeInternal(base,override,0)}var MAX_MERGE_DEPTH=10;function freezeSet(items){let set=new Set(items),proxy=new Proxy(set,{get(target,prop){if(prop==="add"||prop==="delete"||prop==="clear")return()=>{throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")};if(prop==="forEach")return(callback,thisArg)=>{let wrapped=(v,k)=>callback.call(thisArg??void 0,v,k,proxy);return set.forEach(wrapped)};let value=Reflect.get(target,prop);return typeof value==="function"?value.bind(target):value},set(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},deleteProperty(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},defineProperty(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},setPrototypeOf(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")}});return proxy}function isQAAgent(name){return QA_AGENTS.includes(name)}function isSubagent(name){return ALL_SUBAGENT_NAMES.includes(name)}function isLowCapabilityModel(modelId){let lower=(modelId||"").toLowerCase();return LOW_CAPABILITY_MODELS.some((substr)=>lower.includes(substr))}var OPENCODE_NATIVE_AGENTS,CLAUDE_CODE_NATIVE_COMMANDS,MEMORY_AGENT_TOOL_MAP,EXTERNAL_SKILL_TOOL_NAMES,EXTERNAL_SKILL_AGENT_TOOL_MAP,COUNCIL_TOOL_NAMES,COUNCIL_AGENT_TOOL_MAP,GENERAL_COUNCIL_TOOL_NAMES,GENERAL_COUNCIL_AGENT_TOOL_MAP,TURBO_TOOL_NAMES,TURBO_AGENT_TOOL_MAP,SKILL_TOOL_NAMES,SKILL_AGENT_TOOL_MAP,WRITE_TOOL_NAMES,SUMMARIZER_EXEMPT_TOOL_NAMES,DEFAULT_MODELS,DEFAULT_AGENT_CONFIGS,DEFAULT_SCORING_CONFIG,LOW_CAPABILITY_MODELS,TURBO_MODE_BANNER=`## \uD83D\uDE80 TURBO MODE ACTIVE
2
2
 
3
3
  **Speed optimization enabled for this session.**
4
4
 
@@ -180,16 +180,16 @@ ${trimmed}`}else malformedRows++;continue}let rowFields=fields.slice(0,CANDIDATE
180
180
  `),totalLines=lines.length,startLine=Math.max(0,offset);if(startLine>=totalLines)return{totalLines,startLine,endLine:totalLines,content:"",exhausted:!0};let endLine=Math.min(startLine+limit,totalLines);return{totalLines,startLine,endLine,content:lines.slice(startLine,endLine).join(`
181
181
  `),exhausted:!1}}function buildPreviewMarker(args2){let retrieval=args2.ref?` retrieve_lane_output ref=${args2.ref} for full output.`:" no full output artifact is available; treat this lane as degraded.";return`
182
182
  [... lane output preview omitted middle content.${args2.degraded?" Artifact storage degraded.":""}${retrieval} ...]
183
- `}function laneOutputRelativePath(ref){let[,batchDigest,laneDigest,outputDigest]=ref.split(":");return path8.join("lane-results",batchDigest,laneDigest,`${outputDigest}.json`)}function hasValidArtifactIntegrity(artifact,expectedRef){let digest=digestText(artifact.text);if(artifact.digest!==digest)return!1;if(artifact.chars!==artifact.text.length)return!1;if(artifact.bytes!==Buffer.byteLength(artifact.text,"utf-8"))return!1;let batchDigest=digestText(artifact.batchId),laneDigest=digestText(artifact.laneId),expectedArtifactRef=`${LANE_OUTPUT_REF_PREFIX}:${batchDigest}:${laneDigest}:${digest}`;return artifact.ref===expectedRef&&artifact.ref===expectedArtifactRef}function artifactIdentityMatchesInput(artifact,input){return artifact.agent===input.agent&&artifact.role===input.role&&artifact.sessionId===input.sessionId&&artifact.parentSessionId===input.parentSessionId&&artifact.mode===input.mode&&artifact.workflowLane===input.workflowLane&&artifact.prHeadSha===input.prHeadSha&&artifact.gitHead===input.gitHead&&artifact.revisionDigest===input.revisionDigest&&artifact.scope===input.scope&&artifact.source===input.source}function writeAtomicJson(absPath,value){mkdirSync2(path8.dirname(absPath),{recursive:!0});let tempFile=`${absPath}.tmp-${Date.now()}-${process.pid}`;try{writeFileSync(tempFile,JSON.stringify(value,null,2),"utf-8");let lastRenameError;for(let attempt=0;attempt<WINDOWS_RENAME_MAX_RETRIES2;attempt++)try{renameSync(tempFile,absPath),lastRenameError=void 0;break}catch(err){lastRenameError=err;let code=err.code;if(code!=="EEXIST"&&code!=="EBUSY"&&code!=="EPERM")break}if(lastRenameError)throw lastRenameError}finally{if(existsSync3(tempFile))try{unlinkSync(tempFile)}catch{}}}function digestText(text){return createHash2("sha256").update(text).digest("hex")}var LANE_OUTPUT_REF_PREFIX="L1",MAX_LANE_OUTPUT_STORED_BYTES=10485760,LANE_OUTPUT_SCHEMA_VERSION=1,REF_RE,LaneOutputArtifactSchema,WINDOWS_RENAME_MAX_RETRIES2=3;var init_lane_output_store=__esm(()=>{init_zod();init_utils2();REF_RE=/^L1:[a-f0-9]{64}:[a-f0-9]{64}:[a-f0-9]{64}$/,LaneOutputArtifactSchema=exports_external.object({schemaVersion:exports_external.literal(LANE_OUTPUT_SCHEMA_VERSION),ref:exports_external.string().regex(REF_RE),batchId:exports_external.string().min(1),laneId:exports_external.string().min(1),agent:exports_external.string().min(1),role:exports_external.string().min(1),sessionId:exports_external.string().min(1).optional(),parentSessionId:exports_external.string().min(1).optional(),mode:exports_external.string().min(1).optional(),workflowLane:exports_external.string().min(1).optional(),prHeadSha:exports_external.string().min(1).optional(),gitHead:exports_external.string().min(1).optional(),revisionDigest:exports_external.string().min(1).optional(),scope:exports_external.string().min(1).optional(),source:exports_external.enum(["dispatch_lanes","collect_lane_results"]),text:exports_external.string(),chars:exports_external.number().int().nonnegative(),bytes:exports_external.number().int().nonnegative(),digest:exports_external.string().regex(/^[a-f0-9]{64}$/),messageCount:exports_external.number().int().nonnegative().optional(),transcriptIncomplete:exports_external.boolean().optional(),createdAt:exports_external.string(),updatedAt:exports_external.string()}).strict()});import*as crypto2 from"node:crypto";import*as fs5 from"node:fs";import*as path9 from"node:path";function getLockFilePath(directory,filePath){let normalized=path9.resolve(directory,filePath),baseDir=path9.resolve(directory)+path9.sep;if(!(process.platform==="win32"?normalized.toLowerCase().startsWith(baseDir.toLowerCase()):normalized.startsWith(baseDir)))throw Error("Invalid file path: path traversal not allowed");let pathForHash=process.platform==="win32"?normalized.toLowerCase():normalized,hash2=crypto2.createHash("sha256").update(pathForHash).digest("hex"),lockPath=path9.join(directory,LOCKS_DIR,`${hash2}.lock`),legacyPaths=[pathForHash];if(process.platform==="win32"&&normalized!==pathForHash)legacyPaths.push(normalized);for(let legacyPath of legacyPaths){let oldHash=Buffer.from(legacyPath).toString("base64").replace(/[/+=]/g,"_"),oldLockPath=path9.join(directory,LOCKS_DIR,`${oldHash}.lock`);if(fs5.existsSync(oldLockPath))return oldLockPath}return lockPath}function getMetaPath(lockPath){return`${lockPath.replace(/\.lock$/,"")}.meta`}async function writeMetaFile(metaPath,metadata){let tmpPath=`${metaPath}.tmp`;try{await _internals7.writeFile(tmpPath,JSON.stringify(metadata),"utf-8"),await fs5.promises.rename(tmpPath,metaPath)}catch(err){try{await fs5.promises.unlink(tmpPath)}catch{}throw err}}function readMetaFile(metaPath){try{let content=fs5.readFileSync(metaPath,"utf-8");return JSON.parse(content)}catch{return null}}async function tryAcquireLock(directory,filePath,agent,taskId){let lockPath=getLockFilePath(directory,filePath),locksDir=path9.dirname(lockPath);if(!fs5.existsSync(locksDir))fs5.mkdirSync(locksDir,{recursive:!0});if(!fs5.existsSync(lockPath))fs5.writeFileSync(lockPath,"","utf-8");let release;try{release=await import_proper_lockfile2.default.lock(lockPath,{stale:LOCK_TIMEOUT_MS,retries:{retries:5,minTimeout:10,maxTimeout:500,factor:2},realpath:!1})}catch(err){let code=err.code;if(code==="ELOCKED"||code==="EEXIST")return{acquired:!1};throw err}return{acquired:!0,lock:{filePath,agent,taskId,timestamp:new Date().toISOString(),expiresAt:Date.now()+LOCK_TIMEOUT_MS,_release:release}}}function isLocked(directory,filePath){let plLockDir=`${getLockFilePath(directory,filePath)}.lock`;if(fs5.existsSync(plLockDir)){let acquiredAt=Date.now();try{acquiredAt=fs5.statSync(plLockDir).mtimeMs}catch{}return{filePath,agent:"unknown",taskId:"unknown",timestamp:new Date(acquiredAt).toISOString(),expiresAt:acquiredAt+LOCK_TIMEOUT_MS}}return null}function listActiveLocks(directory){let locksDir=path9.join(directory,LOCKS_DIR),locks=[];if(!fs5.existsSync(locksDir))return locks;let files=fs5.readdirSync(locksDir),now=Date.now();for(let file2 of files){if(!file2.endsWith(".lock"))continue;let lockPath=path9.join(locksDir,file2);try{if(fs5.statSync(lockPath).isFile()){let plLockDir=`${lockPath}.lock`;if(fs5.existsSync(plLockDir)){let metaPath=getMetaPath(lockPath),meta3=readMetaFile(metaPath);if(meta3){if(meta3.expiresAt<now)continue;locks.push({filePath:meta3.originalPath,agent:meta3.agent,taskId:meta3.taskId,timestamp:meta3.acquiredAt,expiresAt:meta3.expiresAt,laneId:meta3.laneId})}else{let acquiredAt=Date.now();try{acquiredAt=fs5.statSync(plLockDir).mtimeMs}catch{}let expiresAt=acquiredAt+LOCK_TIMEOUT_MS;if(expiresAt<now)continue;locks.push({filePath:lockPath,agent:"unknown",taskId:"unknown",timestamp:new Date(acquiredAt).toISOString(),expiresAt})}}}}catch{}}return locks}async function acquireLaneLocks(directory,laneId,files,agent,taskId,sessionID){let acquiredLocks=[],conflicts=[];for(let file2 of files){let result=await tryAcquireLock(directory,file2,agent,taskId);if(!result.acquired){for(let lock of acquiredLocks)try{if(lock._release)await lock._release();let lockPath2=getLockFilePath(directory,lock.filePath),metaPath2=getMetaPath(lockPath2);try{fs5.unlinkSync(metaPath2)}catch{}try{fs5.unlinkSync(lockPath2)}catch{}}catch{}return conflicts.push(file2),{acquired:!1,conflicts}}let lockPath=getLockFilePath(directory,file2),metaPath=getMetaPath(lockPath),meta3={originalPath:file2,laneId,taskId,agent,sessionID,acquiredAt:result.lock.timestamp,expiresAt:result.lock.expiresAt};try{await writeMetaFile(metaPath,meta3)}catch(err){for(let lock of acquiredLocks)try{if(lock._release)await lock._release();let lp=getLockFilePath(directory,lock.filePath),mp=getMetaPath(lp);try{fs5.unlinkSync(mp)}catch{}try{fs5.unlinkSync(lp)}catch{}}catch{}if(result.lock._release)await result.lock._release();try{fs5.unlinkSync(lockPath)}catch{}throw err}result.lock.laneId=laneId,acquiredLocks.push(result.lock)}return{acquired:!0,locks:acquiredLocks}}async function releaseLaneLocks(directory,laneId){let locksDir=path9.join(directory,LOCKS_DIR);if(!fs5.existsSync(locksDir))return 0;let files=fs5.readdirSync(locksDir),releasedCount=0;for(let file2 of files){if(!file2.endsWith(".meta"))continue;let metaPath=path9.join(locksDir,file2),meta3=readMetaFile(metaPath);if(!meta3||meta3.laneId!==laneId)continue;let lockPath=metaPath.replace(/\.meta$/,".lock");try{try{await import_proper_lockfile2.default.unlock(lockPath,{realpath:!1})}catch{}try{fs5.unlinkSync(lockPath)}catch{}try{fs5.unlinkSync(metaPath)}catch{}releasedCount++}catch{}}return releasedCount}var import_proper_lockfile2,LOCKS_DIR=".swarm/locks",LOCK_TIMEOUT_MS=300000,_internals7;var init_file_locks=__esm(()=>{import_proper_lockfile2=__toESM(require_proper_lockfile(),1),_internals7={tryAcquireLock,writeFile:fs5.promises.writeFile}});function defineEntry(kind,input){let entry={kind,category:input.category,severity:input.severity,privacyClass:input.privacyClass,producer:input.producer,consumers:input.consumers,retentionOwnerIssue:input.retentionOwnerIssue,requiredWorkflowIds:input.requiredWorkflowIds??NO_WORKFLOW_IDS,forbiddenWorkflowIds:input.forbiddenWorkflowIds??NO_WORKFLOW_IDS,requiresParent:input.requiresParent??!1,allowsLinks:input.allowsLinks??!0,otelMapping:input.otelMapping??"none",docAnchor:`#${kind}`,testFile:"tests/unit/observability/catalog-contract.test.ts"};if(input.futureOwnerIssue!==void 0)return Object.freeze({...entry,futureOwnerIssue:input.futureOwnerIssue});return Object.freeze(entry)}function getCatalogEntry(kind){return Object.hasOwn(EVENT_CATALOG,kind)?EVENT_CATALOG[kind]:void 0}var NO_WORKFLOW_IDS,NO_CONSUMERS,REQUIRE_SESSION,REQUIRE_SESSION_AND_TASK,REQUIRE_TASK,FORBID_SESSION,CONSUMER_COST_ACCOUNTING,CONSUMER_GATE_STATS,CONSUMER_HEARTBEAT_LISTENER,CATALOG_SOURCE,catalog,EVENT_CATALOG,CATALOG_KINDS;var init_catalog=__esm(()=>{NO_WORKFLOW_IDS=Object.freeze([]),NO_CONSUMERS=Object.freeze([]),REQUIRE_SESSION=Object.freeze(["hostSessionId"]),REQUIRE_SESSION_AND_TASK=Object.freeze(["hostSessionId","taskId"]),REQUIRE_TASK=Object.freeze(["taskId"]),FORBID_SESSION=Object.freeze(["hostSessionId"]),CONSUMER_COST_ACCOUNTING=Object.freeze(["src/services/cost-accounting.ts:127"]),CONSUMER_GATE_STATS=Object.freeze(["src/evaluation/gate-stats.ts:99"]),CONSUMER_HEARTBEAT_LISTENER=Object.freeze(["src/telemetry.ts:186"]);CATALOG_SOURCE=[["session_started",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:491",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"openinference"}],["session_ended",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:495",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"openinference"}],["agent_activated",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:499",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"openinference"}],["task_state_changed",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:536",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK,otelMapping:"openinference"}],["phase_changed",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:584",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"openinference"}],["heartbeat",{category:"lifecycle",severity:"debug",privacyClass:"pseudonymous",producer:"src/telemetry.ts:766",consumers:CONSUMER_HEARTBEAT_LISTENER,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,allowsLinks:!1}],["turbo_mode_changed",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:774",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION}],["environment_detected",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:799",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,allowsLinks:!1}],["delegation_begin",{category:"delegation",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:503",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK,otelMapping:"genai"}],["delegation_end",{category:"delegation",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:513",consumers:CONSUMER_COST_ACCOUNTING,retentionOwnerIssue:2043,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK,otelMapping:"genai"}],["model_fallback",{category:"delegation",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:617",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"genai"}],["model_unresolved",{category:"delegation",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:631",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"genai"}],["gate_passed",{category:"gate",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:545",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK}],["gate_failed",{category:"gate",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:562",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK}],["gate_parse_error",{category:"gate",severity:"warning",privacyClass:"sensitive",producer:"src/telemetry.ts:549",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_TASK,forbiddenWorkflowIds:FORBID_SESSION}],["reviewer_gate_decision",{category:"gate",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:572",consumers:CONSUMER_GATE_STATS,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK}],["budget_updated",{category:"cost",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:588",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2043,requiredWorkflowIds:REQUIRE_SESSION}],["context_pruned",{category:"guardrail",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:607",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["hard_limit_hit",{category:"guardrail",severity:"error",privacyClass:"pseudonymous",producer:"src/telemetry.ts:645",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["revision_limit_hit",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:654",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["loop_detected",{category:"guardrail",severity:"warning",privacyClass:"sensitive",producer:"src/telemetry.ts:658",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["scope_violation",{category:"guardrail",severity:"error",privacyClass:"sensitive",producer:"src/telemetry.ts:754",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["qa_skip_violation",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:762",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["auto_oversight_escalation",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:784",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["no_op_strong_warning",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:672",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["gate_denial_loop",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:693",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["execution_stall_warning",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:707",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["execution_stall_denied",{category:"guardrail",severity:"error",privacyClass:"pseudonymous",producer:"src/telemetry.ts:724",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["swarm_internals_read_denied",{category:"guardrail",severity:"error",privacyClass:"sensitive",producer:"src/telemetry.ts:741",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_hard_stop_delivered",{category:"prm",severity:"error",privacyClass:"pseudonymous",producer:"src/telemetry.ts:991",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_pattern_detected",{category:"prm",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:814",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_course_correction_injected",{category:"prm",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:828",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_escalation_triggered",{category:"prm",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:841",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_hard_stop",{category:"prm",severity:"critical",privacyClass:"pseudonymous",producer:"src/telemetry.ts:855",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["evidence_lock_acquired",{category:"evidence",severity:"info",privacyClass:"sensitive",producer:"src/evidence/lock.ts:99",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,requiredWorkflowIds:REQUIRE_TASK,forbiddenWorkflowIds:FORBID_SESSION}],["evidence_lock_contended",{category:"evidence",severity:"notice",privacyClass:"sensitive",producer:"src/evidence/lock.ts:134",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,requiredWorkflowIds:REQUIRE_TASK,forbiddenWorkflowIds:FORBID_SESSION}],["evidence_lock_stale_recovered",{category:"evidence",severity:"notice",privacyClass:"sensitive",producer:"src/evidence/lock.ts:91",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,requiredWorkflowIds:REQUIRE_TASK,forbiddenWorkflowIds:FORBID_SESSION}],["plan_ledger_cas_retry",{category:"plan",severity:"notice",privacyClass:"operational",producer:"src/plan/manager.ts:344",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,forbiddenWorkflowIds:FORBID_SESSION}],["plan_md_write_failed",{category:"plan",severity:"warning",privacyClass:"sensitive",producer:"src/plan/manager.ts:1861",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,forbiddenWorkflowIds:FORBID_SESSION}],["snapshot_failed",{category:"plan",severity:"error",privacyClass:"sensitive",producer:"src/plan/ledger.ts:1143",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,forbiddenWorkflowIds:FORBID_SESSION}],["agent_conflict_detected",{category:"conflict",severity:"warning",privacyClass:"pseudonymous",producer:"src/hooks/conflict-resolution.ts:73",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:Object.freeze(["hostSessionId","phaseId"])}],["close_archive_result",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:892",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047}],["knowledge_receipt_transition",{category:"knowledge",severity:"info",privacyClass:"pseudonymous",producer:"src/hooks/knowledge-receipt-observability.ts:197",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["knowledge_maintenance",{category:"knowledge",severity:"notice",privacyClass:"pseudonymous",producer:"src/knowledge/hive-quarantine.ts:1265",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["residue_health",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:914",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["context_telemetry_health",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:938",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["skill_usage_health",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:975",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}]],catalog={};for(let[kind,input]of CATALOG_SOURCE)catalog[kind]=defineEntry(kind,input);EVENT_CATALOG=Object.freeze(catalog),CATALOG_KINDS=Object.freeze(Object.keys(EVENT_CATALOG))});var OBSERVABILITY_SCHEMA_VERSION=1,EventCategorySchema,EventSeveritySchema,PrivacyClassSchema,TimingConfidenceSchema,SpanLinkSchema,TraceContextSchema,WorkflowIdsSchema,LineageSchema,ProvenanceSchema,OutcomeSchema,PolicySchema,LegacyProjectionSchema,ObservabilityEventSchema;var init_envelope=__esm(()=>{init_zod();EventCategorySchema=exports_external.enum(["lifecycle","delegation","gate","plan","evidence","guardrail","knowledge","cost","prm","conflict","unrecognized"]),EventSeveritySchema=exports_external.enum(["debug","info","notice","warning","error","critical"]),PrivacyClassSchema=exports_external.enum(["operational","pseudonymous","sensitive","content"]),TimingConfidenceSchema=exports_external.enum(["exact","writer-clock","inferred","unknown"]),SpanLinkSchema=exports_external.object({traceId:exports_external.string(),spanId:exports_external.string(),kind:exports_external.enum(["resume","lane","cross-process","retry","parent-batch"]),note:exports_external.string().optional()}),TraceContextSchema=exports_external.object({traceId:exports_external.string(),spanId:exports_external.string(),parentSpanId:exports_external.string().optional(),links:exports_external.array(SpanLinkSchema)}),WorkflowIdsSchema=exports_external.object({rootConversationId:exports_external.string().optional(),hostSessionId:exports_external.string().optional(),swarmSessionId:exports_external.string().optional(),taskId:exports_external.string().optional(),phaseId:exports_external.string().optional(),laneId:exports_external.string().optional(),batchId:exports_external.string().optional(),resultId:exports_external.string().optional(),councilRoundId:exports_external.string().optional(),backgroundInvocationId:exports_external.string().optional(),knowledgeTraceId:exports_external.string().optional(),knowledgeEntryId:exports_external.string().optional(),prRunId:exports_external.string().optional()}),LineageSchema=exports_external.object({projectRef:exports_external.string().optional(),cohortRef:exports_external.string().optional(),worktreeRef:exports_external.string().optional()}),ProvenanceSchema=exports_external.object({pluginVersion:exports_external.string().optional(),opencodeVersion:exports_external.string().optional(),runtime:exports_external.string().optional(),runtimeVersion:exports_external.string().optional(),os:exports_external.string().optional(),arch:exports_external.string().optional(),model:exports_external.string().optional(),provider:exports_external.string().optional(),gitSha:exports_external.string().optional(),configHash:exports_external.string().optional()}),OutcomeSchema=exports_external.object({status:exports_external.enum(["success","failure","partial","unknown"]).optional(),reason:exports_external.string().optional(),errorName:exports_external.string().optional(),errorMessage:exports_external.string().optional(),retryIndex:exports_external.number().optional(),durationMs:exports_external.number().optional()}),PolicySchema=exports_external.object({sampled:exports_external.boolean(),sampleRate:exports_external.number(),dropReason:exports_external.string().optional(),privacyClass:PrivacyClassSchema}),LegacyProjectionSchema=exports_external.object({sourceStore:exports_external.string(),sourceSchemaVersion:exports_external.number().nullable(),timingConfidence:TimingConfidenceSchema,unknown:exports_external.array(exports_external.string()),extra:exports_external.record(exports_external.string(),exports_external.unknown()),raw:exports_external.unknown()}),ObservabilityEventSchema=exports_external.object({schemaVersion:exports_external.number(),eventId:exports_external.string(),kind:exports_external.string(),category:EventCategorySchema,severity:EventSeveritySchema,occurredAt:exports_external.string(),observedAt:exports_external.string(),writerSequence:exports_external.number(),trace:TraceContextSchema,workflow:WorkflowIdsSchema,lineage:LineageSchema,provenance:ProvenanceSchema,outcome:OutcomeSchema,policy:PolicySchema,legacy:LegacyProjectionSchema,relationshipViolations:exports_external.array(exports_external.string())})});import{createHash as createHash4,randomBytes,randomUUID as randomUUID2}from"node:crypto";function newTraceId(){for(let attempt=0;attempt<MAX_REGENERATION_ATTEMPTS;attempt++){let hex3=randomBytes(TRACE_ID_BYTES).toString("hex");if(hex3!==ALL_ZERO_TRACE_ID)return hex3}return SENTINEL_TRACE_ID}function newSpanId(){for(let attempt=0;attempt<MAX_REGENERATION_ATTEMPTS;attempt++){let hex3=randomBytes(SPAN_ID_BYTES).toString("hex");if(hex3!==ALL_ZERO_SPAN_ID)return hex3}return SENTINEL_SPAN_ID}function newEventId(){return randomUUID2()}function takeIdBytes(){let need=TRACE_ID_BYTES+SPAN_ID_BYTES;if(_poolOffset+need>_pool.length)_pool=randomBytes(POOL_BYTES),_poolOffset=0;let slice=_pool.subarray(_poolOffset,_poolOffset+need);return _poolOffset+=need,slice}function newTraceAndSpanId(){let buffer=takeIdBytes(),traceId=buffer.subarray(0,TRACE_ID_BYTES).toString("hex"),spanId=buffer.subarray(TRACE_ID_BYTES).toString("hex");if(traceId===ALL_ZERO_TRACE_ID||spanId===ALL_ZERO_SPAN_ID)return{traceId:newTraceId(),spanId:newSpanId()};return{traceId,spanId}}function resolveLineageSalt(){let configured=process.env[LINEAGE_SALT_ENV];if(typeof configured==="string"&&configured.length>0)return configured;return DEFAULT_LINEAGE_SALT}function pseudonymousRef(absolutePath,salt){return createHash4("sha256").update(salt+LINEAGE_SEPARATOR+absolutePath,"utf8").digest("hex").slice(0,PSEUDONYMOUS_REF_LENGTH)}var TRACE_ID_BYTES=16,SPAN_ID_BYTES=8,TRACE_ID_HEX_LENGTH,SPAN_ID_HEX_LENGTH,ALL_ZERO_TRACE_ID,ALL_ZERO_SPAN_ID,SENTINEL_TRACE_ID,SENTINEL_SPAN_ID,MAX_REGENERATION_ATTEMPTS=4,LINEAGE_SALT_ENV="SWARM_OBSERVABILITY_LINEAGE_SALT",DEFAULT_LINEAGE_SALT="opencode-swarm/observability/lineage/v1",LINEAGE_SEPARATOR="\x00",PSEUDONYMOUS_REF_LENGTH=16,POOL_DRAWS=128,POOL_BYTES,_pool,_poolOffset;var init_ids=__esm(()=>{TRACE_ID_HEX_LENGTH=TRACE_ID_BYTES*2,SPAN_ID_HEX_LENGTH=SPAN_ID_BYTES*2,ALL_ZERO_TRACE_ID="0".repeat(TRACE_ID_HEX_LENGTH),ALL_ZERO_SPAN_ID="0".repeat(SPAN_ID_HEX_LENGTH),SENTINEL_TRACE_ID=`${"0".repeat(TRACE_ID_HEX_LENGTH-1)}1`,SENTINEL_SPAN_ID=`${"0".repeat(SPAN_ID_HEX_LENGTH-1)}1`;POOL_BYTES=(TRACE_ID_BYTES+SPAN_ID_BYTES)*POOL_DRAWS,_pool=Buffer.alloc(0),_poolOffset=Number.POSITIVE_INFINITY});function degradedProjection(marker,data){return{sourceStore:".swarm/telemetry.jsonl",sourceSchemaVersion:null,timingConfidence:"writer-clock",unknown:[marker],extra:EMPTY_EXTRA,raw:data}}function knownKeySetFor(knownKeys){let cached2=_knownKeySetCache.get(knownKeys);if(cached2!==void 0)return cached2;let built=new Set(knownKeys);return _knownKeySetCache.set(knownKeys,built),built}function adaptLegacyTelemetryPayload(kind,data,knownKeys){if(data===null||typeof data!=="object")return degradedProjection("<non-object-payload>",data);try{let record2=data,known=knownKeySetFor(knownKeys),ownKeys=Object.keys(record2),extra;for(let key of ownKeys){if(known.has(key))continue;if(extra??={},key==="__proto__"){Object.defineProperty(extra,key,{value:record2[key],enumerable:!0,writable:!0,configurable:!0});continue}extra[key]=record2[key]}let unknownFields;for(let key of knownKeys)if(record2[key]===void 0)unknownFields??=[],unknownFields.push(key);return{sourceStore:".swarm/telemetry.jsonl",sourceSchemaVersion:null,timingConfidence:"writer-clock",unknown:unknownFields??EMPTY_UNKNOWN,extra:extra??EMPTY_EXTRA,raw:data}}catch{return degradedProjection("<payload-introspection-failed>",data)}}function nonEmptyString(value){return typeof value==="string"&&value.length>0?value:void 0}function extractWorkflowIds(data){let ids={};try{if(data===null||typeof data!=="object")return ids;let record2=data,hostSessionId=nonEmptyString(record2.sessionId);if(hostSessionId!==void 0)ids.hostSessionId=hostSessionId;let taskId=nonEmptyString(record2.taskId);if(taskId!==void 0)ids.taskId=taskId;let laneId=nonEmptyString(record2.laneId);if(laneId!==void 0)ids.laneId=laneId;let batchId=nonEmptyString(record2.batchId);if(batchId!==void 0)ids.batchId=batchId;let knowledgeTraceId=nonEmptyString(record2.knowledgeTraceId);if(knowledgeTraceId!==void 0)ids.knowledgeTraceId=knowledgeTraceId;let knowledgeEntryId=nonEmptyString(record2.knowledgeEntryId);if(knowledgeEntryId!==void 0)ids.knowledgeEntryId=knowledgeEntryId;let phase=record2.phase;if(typeof phase==="number"&&Number.isFinite(phase))ids.phaseId=String(phase);else{let phaseString=nonEmptyString(phase);if(phaseString!==void 0)ids.phaseId=phaseString}}catch{}return ids}function extractOutcome(data){let outcome={};try{if(data===null||typeof data!=="object")return outcome;let record2=data,result=nonEmptyString(record2.result);if(result!==void 0){let normalized=result.toLowerCase();outcome.status=Object.hasOwn(RESULT_STATUS_MAP,normalized)?RESULT_STATUS_MAP[normalized]:"unknown"}let reason=nonEmptyString(record2.reason);if(reason!==void 0)outcome.reason=reason;let errorName=nonEmptyString(record2.errorName);if(errorName!==void 0)outcome.errorName=errorName;let errorMessage=nonEmptyString(record2.errorMessage);if(errorMessage!==void 0)outcome.errorMessage=errorMessage;let retryIndex=record2.retry_index;if(typeof retryIndex==="number"&&Number.isFinite(retryIndex))outcome.retryIndex=retryIndex}catch{}return outcome}var LEGACY_TELEMETRY_SOURCE_STORE=".swarm/telemetry.jsonl",LEGACY_ADAPTER_RULES,KNOWN_TELEMETRY_KEYS,EMPTY_EXTRA,EMPTY_UNKNOWN,_knownKeySetCache,RESULT_STATUS_MAP;var init_legacy=__esm(()=>{LEGACY_ADAPTER_RULES=Object.freeze(["Preserve unknown fields: an own key the contract does not recognize is kept under `extra` by reference and is never dropped.","Record the source store and its schema version: `sourceStore` names the file; `sourceSchemaVersion` is the version the store declares.","Preserve originally reported values: values are aliased, never coerced, normalized, rounded, or re-serialized.","Record timing confidence: a time read by the writer at record time is `writer-clock`, never `exact`.","Unknown is not zero: the adapter lists in `unknown` every catalogued key the PRODUCER left undefined, and never itself defaults one to 0, \"\", false, or null. The guarantee stops at the adapter boundary — a producer that pre-coerces its own defaults defeats it, because the adapter only ever sees the coerced value. The known instance is `delegation_end` (`src/telemetry.ts` `delegationEnd`, pre-existing): it coerces `?? 0` / `?? null` / `?? 'unavailable'` before emitting, so its cost fields can never appear in `unknown`; there, `cost_source: 'unavailable'` is how absence stays recoverable.","Missing lineage stays missing: an absent correlation ID stays `undefined` and is never synthesized to make a join succeed.","Never drop unrecognized fields: no allowlist filter is applied to the payload on the way through."]),KNOWN_TELEMETRY_KEYS=Object.freeze({session_started:Object.freeze(["sessionId","agentName"]),session_ended:Object.freeze(["sessionId","reason"]),agent_activated:Object.freeze(["sessionId","agentName","oldName"]),delegation_begin:Object.freeze(["sessionId","agentName","taskId"]),delegation_end:Object.freeze(["sessionId","agentName","taskId","result","tokens_input","tokens_output","tokens_reasoning","tokens_cache","cost_usd","cost_source","model","gate","retry_index"]),task_state_changed:Object.freeze(["sessionId","taskId","newState","oldState"]),gate_passed:Object.freeze(["sessionId","gate","taskId"]),gate_parse_error:Object.freeze(["taskId","errorName","errorMessage"]),gate_failed:Object.freeze(["sessionId","gate","taskId","reason"]),reviewer_gate_decision:Object.freeze(["sessionId","gate","taskId","blocked","allowed","reasonCode","evidenceKind"]),phase_changed:Object.freeze(["sessionId","oldPhase","newPhase"]),budget_updated:Object.freeze(["sessionId","budgetPct","agentName"]),context_pruned:Object.freeze(["sessionId","agentName","trigger","usageSource","beforeTokens","afterTokens","modelLimit","maskedMessages","maskedToolParts","maskedTokensFreed","prunedMessages","prunedTextParts","prunedToolParts","prunedTokensFreed"]),model_fallback:Object.freeze(["sessionId","agentName","fromModel","toModel","reason"]),model_unresolved:Object.freeze(["sessionId","agentName","model","detail"]),hard_limit_hit:Object.freeze(["sessionId","agentName","limitType","value"]),revision_limit_hit:Object.freeze(["sessionId","agentName"]),loop_detected:Object.freeze(["sessionId","agentName","loopType"]),scope_violation:Object.freeze(["sessionId","agentName","file","reason"]),qa_skip_violation:Object.freeze(["sessionId","agentName","skipCount"]),heartbeat:Object.freeze(["sessionId"]),turbo_mode_changed:Object.freeze(["sessionId","enabled","agentName"]),auto_oversight_escalation:Object.freeze(["sessionId","reason","interactionCount","deadlockCount","phase"]),environment_detected:Object.freeze(["sessionId","hostOS","shellFamily","executionMode"]),prm_pattern_detected:Object.freeze(["sessionId","pattern","severity","category","stepRange"]),prm_course_correction_injected:Object.freeze(["sessionId","pattern","level"]),prm_escalation_triggered:Object.freeze(["sessionId","pattern","level","occurrenceCount"]),prm_hard_stop:Object.freeze(["sessionId","pattern","level","occurrenceCount"]),no_op_strong_warning:Object.freeze(["sessionId","agentName","count","threshold"]),gate_denial_loop:Object.freeze(["sessionId","tool","code","count"]),execution_stall_warning:Object.freeze(["sessionId","count","threshold"]),execution_stall_denied:Object.freeze(["sessionId","tool","count","threshold"]),swarm_internals_read_denied:Object.freeze(["sessionId","tool","target"]),prm_hard_stop_delivered:Object.freeze(["sessionId","pattern","level","occurrenceCount"]),evidence_lock_acquired:Object.freeze(["directory","evidencePath","agent","taskId","attempt"]),evidence_lock_contended:Object.freeze(["directory","evidencePath","agent","taskId","attempt"]),evidence_lock_stale_recovered:Object.freeze(["directory","evidencePath","agent","taskId","attempt"]),plan_ledger_cas_retry:Object.freeze(["attempt","expectedHashPrefix","delayMs"]),plan_md_write_failed:Object.freeze(["directory","error","timestamp"]),snapshot_failed:Object.freeze(["error","retries","source"]),agent_conflict_detected:Object.freeze(["type","timestamp","sessionId","phase","taskId","sourceAgent","targetAgent","conflictType","resolutionPath","summary"]),knowledge_receipt_transition:Object.freeze(["transition","reasonCode","schemaVersion","receiptSemantics","knowledgeTraceId","knowledgeEntryId","sessionId","taskId","phase","receiptOutcome","receiptSource"]),knowledge_maintenance:Object.freeze(["phase","abortReason","selectedCount","storeEntriesBefore","storeEntriesAfter","backupBytes","storeSha256Prefix","token12"]),residue_health:Object.freeze(["trigger","scanned","matched","eligible","ambiguous","quarantined","preserved","total_bytes","oldest_age_ms","grammar_counts"]),context_telemetry_health:Object.freeze(["trigger","accepted_count","compacted_count","retained_count","dropped_count","corrupt_count","oldest_timestamp","newest_timestamp","bytes","limit_bytes"]),skill_usage_health:Object.freeze(["trigger","accepted","compacted","dropped","skills_dropped","corrupt","pending_retained","uncertain_retained","uncertain_expired","pending_evicted","no_source_knowledge","no_matching_knowledge","bump_retry","bump_unrecoverable","bump_applied_zero","pressure","curator_skipped","bytes","limit_bytes","oldest_timestamp","newest_timestamp","coverage"])}),EMPTY_EXTRA=Object.freeze({});EMPTY_UNKNOWN=Object.freeze([]),_knownKeySetCache=new WeakMap;RESULT_STATUS_MAP=Object.freeze({success:"success",succeeded:"success",ok:"success",pass:"success",passed:"success",complete:"success",completed:"success",failure:"failure",failed:"failure",fail:"failure",error:"failure",partial:"partial"})});function validateEventRelationships(event){let violations=[];try{let entry=getCatalogEntry(event.kind),links=Array.isArray(event.trace?.links)?event.trace.links:[];if(entry===void 0)violations.push(`${RELATIONSHIP_VIOLATION_CODES.unknownKind}:${event.kind}`);else{let workflow=event.workflow??{};for(let id of entry.requiredWorkflowIds)if(workflow[id]===void 0)violations.push(`${RELATIONSHIP_VIOLATION_CODES.requiredWorkflowIdMissing}:${id}`);for(let id of entry.forbiddenWorkflowIds)if(workflow[id]!==void 0)violations.push(`${RELATIONSHIP_VIOLATION_CODES.forbiddenWorkflowIdPresent}:${id}`);let parentSpanId=event.trace?.parentSpanId;if(!entry.requiresParent&&parentSpanId!==void 0)violations.push(RELATIONSHIP_VIOLATION_CODES.parentSpanNotAllowed);if(entry.requiresParent&&parentSpanId===void 0)violations.push(RELATIONSHIP_VIOLATION_CODES.parentSpanMissing);if(parentSpanId!==void 0&&!SPAN_ID_PATTERN.test(String(parentSpanId)))violations.push(RELATIONSHIP_VIOLATION_CODES.malformedParentSpanId);if(!entry.allowsLinks&&links.length>0)violations.push(RELATIONSHIP_VIOLATION_CODES.linksNotAllowed)}for(let index=0;index<links.length;index++){let link=links[index];if(link===void 0||link===null)continue;if(!TRACE_ID_PATTERN.test(String(link.traceId)))violations.push(`${RELATIONSHIP_VIOLATION_CODES.malformedLinkTraceId}:${index}`);if(!SPAN_ID_PATTERN.test(String(link.spanId)))violations.push(`${RELATIONSHIP_VIOLATION_CODES.malformedLinkSpanId}:${index}`)}}catch{return{ok:!1,violations:[RELATIONSHIP_VIOLATION_CODES.validationFailed]}}return violations.length===0?{ok:!0}:{ok:!1,violations}}var TRACE_ID_PATTERN,SPAN_ID_PATTERN,RELATIONSHIP_VIOLATION_CODES;var init_relationships=__esm(()=>{init_catalog();TRACE_ID_PATTERN=/^[0-9a-f]{32}$/,SPAN_ID_PATTERN=/^[0-9a-f]{16}$/,RELATIONSHIP_VIOLATION_CODES=Object.freeze({unknownKind:"unknown_kind",requiredWorkflowIdMissing:"required_workflow_id_missing",forbiddenWorkflowIdPresent:"forbidden_workflow_id_present",parentSpanNotAllowed:"parent_span_not_allowed",parentSpanMissing:"parent_span_missing",malformedParentSpanId:"malformed_parent_span_id",linksNotAllowed:"links_not_allowed",malformedLinkTraceId:"malformed_link_trace_id",malformedLinkSpanId:"malformed_link_span_id",validationFailed:"relationship_validation_failed"})});function shouldSample(traceId,rate){if(typeof rate!=="number"||!Number.isFinite(rate))return!0;if(rate>=1)return!0;if(rate<=0)return!1;if(typeof traceId!=="string"||traceId.length<8)return!0;let suffix=traceId.slice(-8).toLowerCase();if(!SAMPLE_SUFFIX_PATTERN.test(suffix))return!0;let value=Number.parseInt(suffix,16);if(!Number.isFinite(value))return!0;return value/4294967295<rate}var DEFAULT_SAMPLE_RATE=1,SAMPLE_SUFFIX_PATTERN,METRIC_LABEL_ALLOWLIST,ALLOWED_LABELS,CARDINALITY_VIOLATION_CODES;var init_sampling=__esm(()=>{SAMPLE_SUFFIX_PATTERN=/^[0-9a-f]{8}$/;METRIC_LABEL_ALLOWLIST=Object.freeze(["kind","category","severity","outcome_status","cost_source","privacy_class","runtime","os","provider","sampled"]),ALLOWED_LABELS=new Set(METRIC_LABEL_ALLOWLIST),CARDINALITY_VIOLATION_CODES=Object.freeze({notAllowlisted:"label_not_allowlisted",highCardinalityShape:"high_cardinality_label_shape"})});function initObservability(input){try{let salt=resolveLineageSalt(),lineage={},directory=typeof input.directory==="string"&&input.directory.length>0?input.directory:void 0;if(directory!==void 0)lineage.projectRef=pseudonymousRef(directory,salt);if(typeof input.cohortLabel==="string"&&input.cohortLabel.length>0)lineage.cohortRef=pseudonymousRef(`${directory??""}\x00cohort\x00${input.cohortLabel}`,salt);if(typeof input.worktreeId==="string"&&input.worktreeId.length>0)lineage.worktreeRef=pseudonymousRef(`${directory??""}\x00worktree\x00${input.worktreeId}`,salt);if(_lineage=Object.freeze(lineage),_provenance=Object.freeze(input.provenance?{...input.provenance}:{}),typeof input.sampleRate==="number"&&Number.isFinite(input.sampleRate))_sampleRate=input.sampleRate}catch{}}function nextWriterSequence(){if(_writerSequence>=Number.MAX_SAFE_INTEGER)_writerSequence=0;return _writerSequence+=1,_writerSequence}function safeNowIso(){try{return new Date().toISOString()}catch{return FALLBACK_TIMESTAMP}}function buildFallbackObservation(kind,data,writerSequence){let now=safeNowIso();return{schemaVersion:OBSERVABILITY_SCHEMA_VERSION,eventId:FALLBACK_EVENT_ID,kind,category:"unrecognized",severity:"error",occurredAt:now,observedAt:now,writerSequence,trace:{traceId:FALLBACK_TRACE_ID,spanId:FALLBACK_SPAN_ID,links:[]},workflow:{},lineage:{},provenance:{},outcome:{},policy:{sampled:shouldSample(FALLBACK_TRACE_ID,_sampleRate),sampleRate:_sampleRate,privacyClass:"operational"},legacy:{sourceStore:LEGACY_TELEMETRY_SOURCE_STORE,sourceSchemaVersion:null,timingConfidence:"unknown",unknown:[],extra:{},raw:data},relationshipViolations:[OBSERVATION_BUILD_FAILED]}}function createObservation(kind,data){let writerSequence=nextWriterSequence();try{let entry=getCatalogEntry(kind),{traceId,spanId}=newTraceAndSpanId(),observedAt=new Date().toISOString(),knownKeys=Object.hasOwn(KNOWN_TELEMETRY_KEYS,kind)?KNOWN_TELEMETRY_KEYS[kind]:EMPTY_KNOWN_KEYS,event={schemaVersion:OBSERVABILITY_SCHEMA_VERSION,eventId:newEventId(),kind,category:entry?.category??"unrecognized",severity:entry?.severity??"warning",occurredAt:observedAt,observedAt,writerSequence,trace:{traceId,spanId,links:[]},workflow:extractWorkflowIds(data),lineage:_lineage,provenance:_provenance,outcome:extractOutcome(data),policy:{sampled:shouldSample(traceId,_sampleRate),sampleRate:_sampleRate,privacyClass:entry?.privacyClass??"operational"},legacy:adaptLegacyTelemetryPayload(kind,data,knownKeys),relationshipViolations:[]},validation=validateEventRelationships(event);if(!validation.ok)event.relationshipViolations=validation.violations;return event}catch{return buildFallbackObservation(kind,data,writerSequence)}}function toLegacyTelemetryLine(event){return{timestamp:event.observedAt,event:event.kind,...event.legacy.raw}}var _provenance,_lineage,_writerSequence=0,_sampleRate,EMPTY_KNOWN_KEYS,FALLBACK_EVENT_ID="00000000-0000-4000-8000-000000000000",FALLBACK_TRACE_ID="00000000000000000000000000000001",FALLBACK_SPAN_ID="0000000000000001",FALLBACK_TIMESTAMP="1970-01-01T00:00:00.000Z",OBSERVATION_BUILD_FAILED="observation_build_failed";var init_observe=__esm(()=>{init_catalog();init_envelope();init_ids();init_legacy();init_relationships();init_sampling();_provenance=Object.freeze({}),_lineage=Object.freeze({}),_sampleRate=DEFAULT_SAMPLE_RATE,EMPTY_KNOWN_KEYS=Object.freeze([])});var OTEL_GENAI_ATTRIBUTES,OPENINFERENCE_ATTRIBUTES,NO_ATTRIBUTES;var init_otel_mapping=__esm(()=>{OTEL_GENAI_ATTRIBUTES=Object.freeze({kind:"gen_ai.operation.name","provenance.provider":"gen_ai.system","provenance.model":"gen_ai.request.model","legacy.raw.model":"gen_ai.response.model","legacy.raw.agentName":"gen_ai.agent.name","workflow.hostSessionId":"gen_ai.conversation.id","outcome.status":"gen_ai.response.finish_reasons","legacy.raw.tokens_input":"gen_ai.usage.input_tokens","legacy.raw.tokens_output":"gen_ai.usage.output_tokens","legacy.raw.tokens_cache":"gen_ai.usage.cache_read_input_tokens","legacy.raw.tokens_reasoning":"swarm.gen_ai.usage.reasoning_tokens","legacy.raw.cost_usd":"swarm.gen_ai.usage.cost_usd"}),OPENINFERENCE_ATTRIBUTES=Object.freeze({kind:"openinference.span.kind","provenance.model":"llm.model_name","provenance.provider":"llm.provider","legacy.raw.agentName":"agent.name","workflow.hostSessionId":"session.id","legacy.raw.tokens_input":"llm.token_count.prompt","legacy.raw.tokens_output":"llm.token_count.completion","legacy.raw.tokens_cache":"llm.token_count.prompt_details.cache_read","legacy.raw.tokens_reasoning":"llm.token_count.completion_details.reasoning","legacy.raw.cost_usd":"swarm.llm.cost_usd"}),NO_ATTRIBUTES=Object.freeze({})});var init_observability=__esm(()=>{init_catalog();init_envelope();init_ids();init_legacy();init_observe();init_otel_mapping();init_relationships();init_sampling()});var exports_telemetry={};__export(exports_telemetry,{telemetry:()=>telemetry,stopHeartbeatTracking:()=>stopHeartbeatTracking,startHeartbeatTracking:()=>startHeartbeatTracking,rotateTelemetryIfNeeded:()=>rotateTelemetryIfNeeded,resetTelemetryForTesting:()=>resetTelemetryForTesting,resetHeartbeatTrackingForTesting:()=>resetHeartbeatTrackingForTesting,initTelemetry:()=>initTelemetry,getLastHeartbeat:()=>getLastHeartbeat,flushAndDrainTelemetry:()=>flushAndDrainTelemetry,emit:()=>emit,addTelemetryListener:()=>addTelemetryListener,_internals:()=>_internals8,ROTATION_CHECK_INTERVAL:()=>ROTATION_CHECK_INTERVAL});import*as fs6 from"node:fs";import{createWriteStream}from"node:fs";import*as os3 from"node:os";import*as path10 from"node:path";function capHeartbeatMap(){while(heartbeatTimestamps.size>=500){let oldestKey=heartbeatTimestamps.keys().next().value;if(oldestKey===void 0)break;heartbeatTimestamps.delete(oldestKey)}}function startHeartbeatTracking(){if(_heartbeatTrackingActive)return;_heartbeatTrackingActive=!0;let listener=(event,data)=>{if(event!=="heartbeat")return;let payload=data;if(!payload?.sessionId)return;heartbeatTimestamps.set(payload.sessionId,Date.now()),capHeartbeatMap()};_heartbeatListener=listener,addTelemetryListener(listener)}function getLastHeartbeat(sessionId){return heartbeatTimestamps.get(sessionId)}function stopHeartbeatTracking(){if(_heartbeatTrackingActive=!1,_heartbeatListener!==null){let idx=_listeners.indexOf(_heartbeatListener);if(idx>=0)_listeners.splice(idx,1);_heartbeatListener=null}}function resetHeartbeatTrackingForTesting(){if(_heartbeatTrackingActive=!1,heartbeatTimestamps.clear(),_heartbeatListener!==null){let idx=_listeners.indexOf(_heartbeatListener);if(idx>=0)_listeners.splice(idx,1);_heartbeatListener=null}}function resetTelemetryForTesting(){if(_disabled=!1,_projectDirectory=null,_listeners.length=0,_emitCount=0,resetHeartbeatTrackingForTesting(),_writeStream!==null)_writeStream.end(),_writeStream=null}function initTelemetry(projectDirectory){if(_writeStream!==null||_disabled)return;try{_projectDirectory=projectDirectory;let swarmDir=path10.join(projectDirectory,".swarm");if(!fs6.existsSync(swarmDir))fs6.mkdirSync(swarmDir,{recursive:!0});let telemetryPath=path10.join(swarmDir,"telemetry.jsonl"),stream=createWriteStream(telemetryPath,{flags:"a"});stream.on("error",()=>{if(_writeStream===stream)_disabled=!0,_writeStream=null}),_writeStream=stream}catch{_disabled=!0,_writeStream=null}}function emit(event,data){try{if(_disabled||_writeStream===null)return;let canonical=_internals8.createObservation(event,data),line=JSON.stringify(_internals8.toLegacyTelemetryLine(canonical))+os3.EOL,stream=_writeStream;stream.write(line,(err)=>{if(err&&_writeStream===stream)_disabled=!0,_writeStream=null});for(let listener of _listeners)try{listener(event,data)}catch{}if(_emitCount++,_emitCount>=ROTATION_CHECK_INTERVAL)_emitCount=0,_internals8.rotateTelemetryIfNeeded()}catch{}}function addTelemetryListener(callback){_listeners.push(callback)}function rotateTelemetryIfNeeded(maxBytes=10485760){try{if(_projectDirectory===null)return;let telemetryPath=path10.join(_projectDirectory,".swarm","telemetry.jsonl");if(!fs6.existsSync(telemetryPath))return;if(fs6.statSync(telemetryPath).size<maxBytes)return;let rotatedPath=path10.join(_projectDirectory,".swarm","telemetry.jsonl.1");if(fs6.renameSync(telemetryPath,rotatedPath),_writeStream!==null){_writeStream.end();let stream=createWriteStream(telemetryPath,{flags:"a"});stream.on("error",()=>{if(_writeStream===stream)_disabled=!0,_writeStream=null}),_writeStream=stream}}catch{}}async function flushAndDrainTelemetry(){let stream=_writeStream;if(stream===null||_projectDirectory===null)return;let next;try{let telemetryPath=path10.join(_projectDirectory,".swarm","telemetry.jsonl");next=createWriteStream(telemetryPath,{flags:"a"}),next.on("error",()=>{if(_writeStream===next)_disabled=!0,_writeStream=null}),_writeStream=next}catch{_disabled=!0,_writeStream=null;return}await new Promise((resolve5)=>{stream.end(()=>resolve5())})}var _writeStream=null,_projectDirectory=null,_listeners,_disabled=!1,_heartbeatTrackingActive=!1,_heartbeatListener=null,heartbeatTimestamps,_emitCount=0,ROTATION_CHECK_INTERVAL=50,telemetry,_internals8;var init_telemetry=__esm(()=>{init_observability();_listeners=[],heartbeatTimestamps=new Map;telemetry={sessionStarted(sessionId,agentName){_internals8.emit("session_started",{sessionId,agentName})},sessionEnded(sessionId,reason){_internals8.emit("session_ended",{sessionId,reason})},agentActivated(sessionId,agentName,oldName){_internals8.emit("agent_activated",{sessionId,agentName,oldName})},delegationBegin(sessionId,agentName,taskId){_internals8.emit("delegation_begin",{sessionId,agentName,taskId})},delegationEnd(sessionId,agentName,taskId,result,costFields){_internals8.emit("delegation_end",{sessionId,agentName,taskId,result,tokens_input:costFields?.tokens_input??0,tokens_output:costFields?.tokens_output??0,tokens_reasoning:costFields?.tokens_reasoning??0,tokens_cache:costFields?.tokens_cache??0,cost_usd:costFields?.cost_usd??null,cost_source:costFields?.cost_source??"unavailable",model:costFields?.model,gate:costFields?.gate,retry_index:costFields?.retry_index})},taskStateChanged(sessionId,taskId,newState,oldState){_internals8.emit("task_state_changed",{sessionId,taskId,newState,oldState})},gatePassed(sessionId,gate,taskId){_internals8.emit("gate_passed",{sessionId,gate,taskId})},gateParseError(taskId,error49){_internals8.emit("gate_parse_error",{taskId,errorName:error49.name,errorMessage:error49.message.slice(0,200)})},gateFailed(sessionId,gate,taskId,reason){_internals8.emit("gate_failed",{sessionId,gate,taskId,reason})},reviewerGateDecision(sessionId,taskId,blocked,reasonCode,evidenceKind){_internals8.emit("reviewer_gate_decision",{sessionId,gate:"qa_gate",taskId,blocked,allowed:!blocked,reasonCode,evidenceKind})},phaseChanged(sessionId,oldPhase,newPhase){_internals8.emit("phase_changed",{sessionId,oldPhase,newPhase})},budgetUpdated(sessionId,budgetPct,agentName){_internals8.emit("budget_updated",{sessionId,budgetPct,agentName})},contextPruned(data){_internals8.emit("context_pruned",data)},modelFallback(sessionId,agentName,fromModel,toModel,reason){_internals8.emit("model_fallback",{sessionId,agentName,fromModel,toModel,reason})},modelUnresolved(agentName,model,detail){_internals8.emit("model_unresolved",{sessionId:"preflight",agentName,model,detail})},hardLimitHit(sessionId,agentName,limitType,value){_internals8.emit("hard_limit_hit",{sessionId,agentName,limitType,value})},revisionLimitHit(sessionId,agentName){_internals8.emit("revision_limit_hit",{sessionId,agentName})},loopDetected(sessionId,agentName,loopType){_internals8.emit("loop_detected",{sessionId,agentName,loopType})},noOpStrongWarning(sessionId,agentName,count,threshold){_internals8.emit("no_op_strong_warning",{sessionId,agentName,count,threshold})},gateDenialLoop(sessionId,tool,code,count){_internals8.emit("gate_denial_loop",{sessionId,tool,code,count})},executionStallWarning(sessionId,count,threshold){_internals8.emit("execution_stall_warning",{sessionId,count,threshold})},executionStallDenied(sessionId,tool,count,threshold){_internals8.emit("execution_stall_denied",{sessionId,tool,count,threshold})},swarmInternalsReadDenied(sessionId,tool,target){_internals8.emit("swarm_internals_read_denied",{sessionId,tool,target})},scopeViolation(sessionId,agentName,file2,reason){_internals8.emit("scope_violation",{sessionId,agentName,file:file2,reason})},qaSkipViolation(sessionId,agentName,skipCount){_internals8.emit("qa_skip_violation",{sessionId,agentName,skipCount})},heartbeat(sessionId){_internals8.emit("heartbeat",{sessionId})},turboModeChanged(sessionId,enabled,agentName){_internals8.emit("turbo_mode_changed",{sessionId,enabled,agentName})},autoOversightEscalation(sessionId,reason,interactionCount,deadlockCount,phase){_internals8.emit("auto_oversight_escalation",{sessionId,reason,interactionCount,deadlockCount,phase})},environmentDetected(sessionId,hostOS,shellFamily,executionMode){_internals8.emit("environment_detected",{sessionId,hostOS,shellFamily,executionMode})},prmPatternDetected(sessionId,pattern,severity,category,stepRange){_internals8.emit("prm_pattern_detected",{sessionId,pattern,severity,category,stepRange})},prmCourseCorrectionInjected(sessionId,pattern,level){_internals8.emit("prm_course_correction_injected",{sessionId,pattern,level})},prmEscalationTriggered(sessionId,pattern,level,occurrenceCount){_internals8.emit("prm_escalation_triggered",{sessionId,pattern,level,occurrenceCount})},prmHardStop(sessionId,pattern,level,occurrenceCount){_internals8.emit("prm_hard_stop",{sessionId,pattern,level,occurrenceCount})},closeArchiveResult(data){_internals8.emit("close_archive_result",data)},residueHealth(data){_internals8.emit("residue_health",data)},contextTelemetryHealth(data){_internals8.emit("context_telemetry_health",data)},skillUsageHealth(data){_internals8.emit("skill_usage_health",data)},prmHardStopDelivered(sessionId,pattern,level,occurrenceCount){_internals8.emit("prm_hard_stop_delivered",{sessionId,pattern,level,occurrenceCount})}},_internals8={telemetry,emit,rotateTelemetryIfNeeded,flushAndDrainTelemetry,heartbeatListenerCount:()=>_heartbeatListener!==null?1:0,createObservation,toLegacyTelemetryLine}});import*as fs7 from"node:fs";import*as os4 from"node:os";import*as path11 from"node:path";function isAbsoluteDirectoryInput(value){return typeof value==="string"&&value.trim().length>0&&path11.isAbsolute(value)}function hasExplicitProjectBoundary(directory){if(!isAbsoluteDirectoryInput(directory))return!1;for(let marker of PROJECT_BOUNDARY_MARKERS)try{let stat5=_internals9.lstatSync(path11.join(directory,marker.name));if(!stat5.isSymbolicLink()&&marker.accepts(stat5))return!0}catch{}return!1}function isStrictPathDescendant(candidate,root){if(!isAbsoluteDirectoryInput(candidate)||!isAbsoluteDirectoryInput(root))return!1;let relative3=path11.relative(root,candidate);return relative3!==""&&relative3!==".."&&!relative3.startsWith(`..${path11.sep}`)&&!path11.isAbsolute(relative3)}function isMissingPathError(error49){let code=error49?.code;return code==="ENOENT"||code==="ENOTDIR"}function isWeakConfigContainerRoot(directory,dependencies){try{let resolved=dependencies.realpathSync(directory);return resolved===dependencies.realpathSync(os4.tmpdir())||resolved===dependencies.realpathSync(os4.homedir())}catch{let resolved=path11.resolve(directory);return resolved===path11.resolve(os4.tmpdir())||resolved===path11.resolve(os4.homedir())}}function projectIndicatorState(directory,dependencies,options={}){let allowConfigOnly=options.allowConfigOnly??!0;for(let indicator of PROJECT_ROOT_INDICATORS){if(!allowConfigOnly&&indicator===".opencode")continue;try{let indicatorStat=dependencies.statSync(path11.join(directory,indicator));if(indicatorStat.isFile()||indicatorStat.isDirectory())return"present"}catch(error49){if(!isMissingPathError(error49))return"inaccessible"}}return"absent"}function assertProjectRoot(directory,dependencies=fs7,artifactLabel="runtime state"){let resolved;try{resolved=dependencies.realpathSync(directory)}catch{throw warn(`[project-boundary] Cannot canonicalize directory "${directory}" — failing closed`),Error(`Cannot verify project root for "${directory}" — directory may not exist or is inaccessible`)}if(hasExplicitProjectBoundary(resolved))return;let current=resolved,depth=0;while(!0){if(depth>=MAX_PROJECT_ROOT_DEPTH)throw warn(`[project-boundary] Ancestor search exceeded ${MAX_PROJECT_ROOT_DEPTH} levels for "${resolved}" — failing closed`),Error(`Cannot verify project root for "${resolved}" — ancestor search exceeded ${MAX_PROJECT_ROOT_DEPTH} levels`);depth++;let parent=path11.dirname(current);if(parent===current)break;if(path11.dirname(parent)===parent){current=parent;continue}let parentSwarm=path11.join(parent,".swarm"),parentSwarmStat;try{parentSwarmStat=dependencies.statSync(parentSwarm)}catch(error49){if(isMissingPathError(error49)){current=parent;continue}throw warn(`[project-boundary] Cannot inspect ancestor state "${parentSwarm}" — failing closed`),Error(`Cannot verify project root for "${resolved}" — ancestor state "${parentSwarm}" is inaccessible`)}if(parentSwarmStat.isDirectory()){let indicatorState=projectIndicatorState(parent,dependencies,{allowConfigOnly:!isWeakConfigContainerRoot(parent,dependencies)});if(indicatorState==="inaccessible")throw warn(`[project-boundary] Cannot inspect project indicators in ancestor "${parent}" — failing closed`),Error(`Cannot verify project root for "${resolved}" — project indicators in ancestor "${parent}" are inaccessible`);if(indicatorState==="present")throw warn(`[project-boundary] Rejecting write to subdirectory "${resolved}" — parent "${parent}" already contains .swarm/`),Error(`Cannot write ${artifactLabel} in "${resolved}" — parent directory "${parent}" already contains a .swarm/ folder. Runtime state must be written to the project root.`)}current=parent}}var MAX_PROJECT_ROOT_DEPTH=20,PROJECT_ROOT_INDICATORS,PROJECT_BOUNDARY_MARKERS,_internals9;var init_project_boundary=__esm(()=>{init_logger();PROJECT_ROOT_INDICATORS=["package.json",".git",".opencode","Cargo.toml","go.mod","pyproject.toml","Gemfile","composer.json","pom.xml","build.gradle","CMakeLists.txt"],PROJECT_BOUNDARY_MARKERS=[{name:".git",accepts:(stat5)=>stat5.isFile()||stat5.isDirectory()},{name:".opencode",accepts:(stat5)=>stat5.isDirectory()}];_internals9={lstatSync:fs7.lstatSync}});function backoffMs(attempt){let base=Math.min(BACKOFF_START_MS*2**attempt,BACKOFF_MAX_MS),jitter=base*BACKOFF_JITTER_RATIO*(Math.random()*2-1);return Math.max(1,Math.round(base+jitter))}async function withEvidenceLock(directory,evidencePath,agent,taskId,fn2,timeoutMs=60000){assertProjectRoot(directory);let deadline=Date.now()+timeoutMs,attempt=0;while(!0){let result=await tryAcquireLock(directory,evidencePath,agent,taskId);if(result.acquired){let lock=result.lock;if(attempt>0)emit("evidence_lock_stale_recovered",{directory,evidencePath,agent,taskId,attempt});emit("evidence_lock_acquired",{directory,evidencePath,agent,taskId,attempt});try{return await fn2()}finally{if(lock._release)try{await lock._release()}catch{}}}if(Date.now()>=deadline)throw new EvidenceLockTimeoutError(directory,evidencePath,agent,taskId,timeoutMs);emit("evidence_lock_contended",{directory,evidencePath,agent,taskId,attempt});let delay=Math.min(backoffMs(attempt),deadline-Date.now());if(delay>0)await new Promise((resolve6)=>setTimeout(resolve6,delay));attempt++}}var EvidenceLockTimeoutError,BACKOFF_START_MS=50,BACKOFF_MAX_MS=2000,BACKOFF_JITTER_RATIO=0.25;var init_lock=__esm(()=>{init_file_locks();init_telemetry();init_project_boundary();EvidenceLockTimeoutError=class EvidenceLockTimeoutError extends Error{directory;evidencePath;agent;taskId;constructor(directory,evidencePath,agent,taskId,timeoutMs){super(`Evidence lock timeout after ${timeoutMs}ms for ${evidencePath} (agent=${agent}, task=${taskId})`);this.name="EvidenceLockTimeoutError",this.directory=directory,this.evidencePath=evidencePath,this.agent=agent,this.taskId=taskId}}});import*as fs8 from"node:fs";import*as path12 from"node:path";function sleepSync(ms){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,ms)}catch{let start=Date.now();while(Date.now()-start<ms);}}function healthArtifactPath(directory){return validateSwarmPath(directory,BACKGROUND_DELEGATIONS_HEALTH_FILE)}function readDelegationHealthArtifact(directory){let raw;try{raw=fs8.readFileSync(healthArtifactPath(directory),"utf-8")}catch{return null}try{let parsed=DelegationLedgerHealthSchema.safeParse(JSON.parse(raw));return parsed.success?parsed.data:null}catch{return null}}function writeDelegationHealthArtifact(directory,update){let base=readDelegationHealthArtifact(directory)??{schemaVersion:1,updatedAt:0,ledger:{bytes:0,limitBytes:MAX_RECOVERY_LEDGER_BYTES,pressurePct:0,band:"ok"},checkpoint:null,recovery:null,lastUncertainty:null,counts:{activeOwners:0,pendingAdvisories:0,lateTerminals:0,orphanWorktreeOwners:0}},next={schemaVersion:1,updatedAt:Date.now(),ledger:update.ledger??base.ledger,checkpoint:update.checkpoint===void 0?base.checkpoint:update.checkpoint,recovery:update.recovery===void 0?base.recovery:update.recovery,lastUncertainty:update.lastUncertainty??base.lastUncertainty,counts:update.counts??base.counts};if(update.uncertainty)next.lastUncertainty=update.uncertainty;let parsed=DelegationLedgerHealthSchema.safeParse(next);if(!parsed.success)return null;try{fs8.mkdirSync(path12.resolve(directory,".swarm"),{recursive:!0});let target=healthArtifactPath(directory),tmp=`${target}.tmp-${process.pid}-${Math.random().toString(36).slice(2,10)}`;fs8.writeFileSync(tmp,`${JSON.stringify(parsed.data)}
184
- `,"utf-8");let lastError;for(let attempt=0;attempt<5;attempt++)try{_healthInternals.renameOnce(tmp,target),lastError=void 0;break}catch(err){lastError=err;let code=err.code;if(code!=="EEXIST"&&code!=="EBUSY"&&code!=="EPERM")break;if(attempt<4)sleepSync(15)}if(lastError!==void 0){try{fs8.rmSync(tmp,{force:!0})}catch{}return null}return parsed.data}catch{return null}}function recordDelegationRecoveryObservation(directory,observation){try{writeDelegationHealthArtifact(directory,{recovery:{source:observation.source,at:Date.now(),ok:observation.ok,...observation.reason?{reason:observation.reason}:{},...observation.repairHint?{repairHint:observation.repairHint}:{}},...observation.ok?{}:{uncertainty:{reason:observation.reason??"recovery failed",at:Date.now(),source:"recovery",...observation.repairHint?{repairHint:observation.repairHint}:{}}}})}catch{}}function collectDelegationLedgerHealth(directory,options){let artifact=readDelegationHealthArtifact(directory),ledgerBytes=0,ledgerExists=!1;try{ledgerBytes=fs8.statSync(validateSwarmPath(directory,"background-delegations.jsonl")).size,ledgerExists=!0}catch{ledgerExists=!1}if(!artifact&&!ledgerExists)return null;let limitBytes=options.ledgerLimitBytes,pressurePct=Math.min(100,Math.round(ledgerBytes/limitBytes*1000)/10),band=ledgerBytes>limitBytes?"fail-closed":ledgerBytes>options.highWaterBytes?"compact-overdue":ledgerBytes>options.lowWaterBytes?"nominal":"ok";return{schemaVersion:1,updatedAt:artifact?.updatedAt??0,ledger:{bytes:ledgerBytes,limitBytes,pressurePct,band},checkpoint:artifact?.checkpoint??null,recovery:artifact?.recovery??null,lastUncertainty:artifact?.lastUncertainty??null,counts:artifact?.counts??{activeOwners:0,pendingAdvisories:0,lateTerminals:0,orphanWorktreeOwners:0}}}var BACKGROUND_DELEGATIONS_HEALTH_FILE="background-delegations-health.json",MAX_RECOVERY_LEDGER_BYTES=4194304,DelegationCheckpointAuditSchema,CheckpointSectionSchema,RecoverySectionSchema,UncertaintySectionSchema,DelegationLedgerHealthSchema,_healthInternals;var init_delegation_health=__esm(()=>{init_zod();init_utils2();DelegationCheckpointAuditSchema=exports_external.object({dispatchCount:exports_external.number().int().nonnegative(),terminalsByStatus:exports_external.object({completed:exports_external.number().int().nonnegative(),error:exports_external.number().int().nonnegative(),cancelled:exports_external.number().int().nonnegative(),stale:exports_external.number().int().nonnegative()}).strict(),settledCount:exports_external.number().int().nonnegative(),preservedCount:exports_external.number().int().nonnegative(),lateTerminalCount:exports_external.number().int().nonnegative(),compactedTransitionCount:exports_external.number().int().nonnegative(),compactedRecordCount:exports_external.number().int().nonnegative(),firstDispatchAt:exports_external.number().int().nonnegative().nullable(),lastTerminalAt:exports_external.number().int().nonnegative().nullable(),lastCompactionAt:exports_external.number().int().nonnegative()}).strict(),CheckpointSectionSchema=exports_external.object({sequence:exports_external.number().int().positive(),createdAt:exports_external.number().int().nonnegative(),liveRecords:exports_external.number().int().nonnegative(),closedSummaries:exports_external.number().int().nonnegative(),bytes:exports_external.number().int().nonnegative(),audit:DelegationCheckpointAuditSchema}).strict(),RecoverySectionSchema=exports_external.object({source:exports_external.enum(["checkpoint+tail","checkpoint+ledger-suffix","legacy-ledger","unknown"]),at:exports_external.number().int().nonnegative(),ok:exports_external.boolean(),reason:exports_external.string().min(1).max(2000).optional(),repairHint:exports_external.string().min(1).max(2000).optional()}).strict(),UncertaintySectionSchema=exports_external.object({reason:exports_external.string().min(1).max(2000),at:exports_external.number().int().nonnegative(),source:exports_external.string().min(1).max(256),repairHint:exports_external.string().min(1).max(2000).optional()}).strict(),DelegationLedgerHealthSchema=exports_external.object({schemaVersion:exports_external.literal(1),updatedAt:exports_external.number().int().nonnegative(),ledger:exports_external.object({bytes:exports_external.number().int().nonnegative(),limitBytes:exports_external.number().int().positive(),pressurePct:exports_external.number().min(0).max(100),band:exports_external.enum(["ok","nominal","compact-overdue","fail-closed"])}).strict(),checkpoint:CheckpointSectionSchema.nullable(),recovery:RecoverySectionSchema.nullable(),lastUncertainty:UncertaintySectionSchema.nullable(),counts:exports_external.object({activeOwners:exports_external.number().int().nonnegative(),pendingAdvisories:exports_external.number().int().nonnegative(),lateTerminals:exports_external.number().int().nonnegative(),orphanWorktreeOwners:exports_external.number().int().nonnegative()}).strict()}).strict();_healthInternals={renameOnce:(from,to)=>{fs8.renameSync(from,to)}}});import{createHash as createHash5}from"node:crypto";function resolveLaneAtomicDisposition(receipt){if(new Set(receipt.assignedReviewItemIds).size!==receipt.assignedReviewItemIds.length)return null;let acceptedAll=receipt.rejectedReviewItemIds.length===0&&receipt.acceptedReviewItemIds.length===receipt.assignedReviewItemIds.length&&receipt.acceptedReviewItemIds.every((itemId,index)=>itemId===receipt.assignedReviewItemIds[index]),rejectedAll=receipt.acceptedReviewItemIds.length===0&&receipt.rejectedReviewItemIds.length===receipt.assignedReviewItemIds.length&&receipt.rejectedReviewItemIds.every((itemId,index)=>itemId===receipt.assignedReviewItemIds[index]);return acceptedAll?"accepted":rejectedAll?"rejected":null}function encodePrReviewCollectionReceiptFooter(binding,result,receipt){let payload=buildPrReviewCollectionReceiptPayload(binding,result,receipt);if(!payload)return null;let footer=`${PR_REVIEW_COLLECTION_RECEIPT_PREFIX}${JSON.stringify(payload)}`;return footer.length<=MAX_PR_REVIEW_COLLECTION_RECEIPT_CHARS?footer:null}function buildPrReviewCollectionReceiptPayload(binding,result,receipt){let disposition=resolveLaneAtomicDisposition(receipt);if(!disposition)return null;let parsed=PrReviewCollectionReceiptPayloadSchema.safeParse({schemaVersion:1,parentSessionId:binding.parentSessionId,batchId:binding.batchId??binding.callID,laneId:binding.laneId??binding.correlationId,mode:binding.mode,workflowLane:binding.workflowLane,outputDigest:result.digest,disposition,reviewItemIds:receipt.assignedReviewItemIds});if(!parsed.success)return null;return parsed.data}function projectPrReviewCollectionReceipt(payload){let assignedReviewItemIds=[...payload.reviewItemIds];return{assignedReviewItemIds,acceptedReviewItemIds:payload.disposition==="accepted"?[...assignedReviewItemIds]:[],rejectedReviewItemIds:payload.disposition==="rejected"?[...assignedReviewItemIds]:[]}}function reviewItemDigest(reviewItemIds){return createHash5("sha256").update(JSON.stringify(reviewItemIds)).digest("hex")}function encodePrReviewCollectionReceiptShedMarker(payload){let marker={schemaVersion:1,parentSessionId:payload.parentSessionId,batchId:payload.batchId,laneId:payload.laneId,mode:payload.mode,workflowLane:payload.workflowLane,outputDigest:payload.outputDigest,disposition:payload.disposition,reviewItemCount:payload.reviewItemIds.length,reviewItemDigest:reviewItemDigest(payload.reviewItemIds)};return`${PR_REVIEW_COLLECTION_RECEIPT_SHED_PREFIX}${JSON.stringify(marker)}`}function encodePrReviewCollectionReceiptShedMarkerFromReceipt(binding,result,receipt){let payload=buildPrReviewCollectionReceiptPayload(binding,result,receipt);return payload?encodePrReviewCollectionReceiptShedMarker(payload):null}function parsePrReviewCollectionReceiptShedMarker(binding,result){if(!result.text)return null;let lines=result.text.split(/\r?\n/),markerLines=lines.filter((line)=>line.startsWith(PR_REVIEW_COLLECTION_RECEIPT_SHED_PREFIX)),finalLine=lines.at(-1);if(markerLines.length!==1||!finalLine?.startsWith(PR_REVIEW_COLLECTION_RECEIPT_SHED_PREFIX)||finalLine.length>MAX_PR_REVIEW_COLLECTION_RECEIPT_CHARS)return null;let decoded;try{decoded=JSON.parse(finalLine.slice(PR_REVIEW_COLLECTION_RECEIPT_SHED_PREFIX.length))}catch{return null}let parsed=PrReviewCollectionReceiptShedMarkerSchema.safeParse(decoded);if(!parsed.success)return null;let marker=parsed.data;return marker.parentSessionId===binding.parentSessionId&&marker.batchId===(binding.batchId??binding.callID)&&marker.laneId===(binding.laneId??binding.correlationId)&&marker.mode===binding.mode&&marker.workflowLane===binding.workflowLane&&marker.outputDigest===result.digest?marker:null}function projectPrReviewCollectionReceiptShedMarker(marker,reviewItemIds){if(marker.reviewItemCount!==reviewItemIds.length||marker.reviewItemDigest!==reviewItemDigest(reviewItemIds))return null;let assignedReviewItemIds=[...reviewItemIds];return{assignedReviewItemIds,acceptedReviewItemIds:marker.disposition==="accepted"?[...assignedReviewItemIds]:[],rejectedReviewItemIds:marker.disposition==="rejected"?[...assignedReviewItemIds]:[]}}function parsePrReviewCollectionReceiptFooter(binding,result){if(!result.text)return null;let lines=result.text.split(/\r?\n/),receiptLines=lines.filter((line)=>line.startsWith(PR_REVIEW_COLLECTION_RECEIPT_PREFIX)),finalLine=lines.at(-1);if(receiptLines.length!==1||!finalLine?.startsWith(PR_REVIEW_COLLECTION_RECEIPT_PREFIX)||finalLine.length>MAX_PR_REVIEW_COLLECTION_RECEIPT_CHARS)return null;let decoded;try{decoded=JSON.parse(finalLine.slice(PR_REVIEW_COLLECTION_RECEIPT_PREFIX.length))}catch{return null}let parsed=PrReviewCollectionReceiptPayloadSchema.safeParse(decoded);if(!parsed.success)return null;let payload=parsed.data;return payload.parentSessionId===binding.parentSessionId&&payload.batchId===(binding.batchId??binding.callID)&&payload.laneId===(binding.laneId??binding.correlationId)&&payload.mode===binding.mode&&payload.workflowLane===binding.workflowLane&&payload.outputDigest===result.digest?payload:null}var PR_REVIEW_COLLECTION_RECEIPT_PREFIX="[PR_REVIEW_COLLECTION_RECEIPT_V1] ",PR_REVIEW_COLLECTION_RECEIPT_SHED_PREFIX="[PR_REVIEW_COLLECTION_RECEIPT_SHED_V1] ",MAX_PR_REVIEW_COLLECTION_RECEIPT_CHARS=65536,MAX_PR_REVIEW_COLLECTION_RECEIPT_ITEM_IDS=1e4,PrReviewCollectionReceiptPayloadSchema,PrReviewCollectionReceiptShedMarkerSchema;var init_pr_review_collection_receipt=__esm(()=>{init_zod();PrReviewCollectionReceiptPayloadSchema=exports_external.object({schemaVersion:exports_external.literal(1),parentSessionId:exports_external.string().min(1).max(256),batchId:exports_external.string().min(1).max(120),laneId:exports_external.string().min(1).max(120),mode:exports_external.enum(["swarm-pr-review:reviewer","swarm-pr-review:critic"]),workflowLane:exports_external.string().min(1).max(120),outputDigest:exports_external.string().regex(/^[a-f0-9]{64}$/),disposition:exports_external.enum(["accepted","rejected"]),reviewItemIds:exports_external.array(exports_external.string().min(1).max(160)).min(1).max(MAX_PR_REVIEW_COLLECTION_RECEIPT_ITEM_IDS)}).strict().superRefine((payload,context)=>{if(new Set(payload.reviewItemIds).size!==payload.reviewItemIds.length)context.addIssue({code:exports_external.ZodIssueCode.custom,message:"review item IDs must be unique"})}),PrReviewCollectionReceiptShedMarkerSchema=exports_external.object({schemaVersion:exports_external.literal(1),parentSessionId:exports_external.string().min(1).max(256),batchId:exports_external.string().min(1).max(120),laneId:exports_external.string().min(1).max(120),mode:exports_external.enum(["swarm-pr-review:reviewer","swarm-pr-review:critic"]),workflowLane:exports_external.string().min(1).max(120),outputDigest:exports_external.string().regex(/^[a-f0-9]{64}$/),disposition:exports_external.enum(["accepted","rejected"]),reviewItemCount:exports_external.number().int().positive().max(MAX_PR_REVIEW_COLLECTION_RECEIPT_ITEM_IDS),reviewItemDigest:exports_external.string().regex(/^[a-f0-9]{64}$/)}).strict()});var exports_pending_delegations={};__export(exports_pending_delegations,{writeDelegationFallback:()=>writeDelegationFallback,updateCoderSettlement:()=>updateCoderSettlement,sweepStaleDelegations:()=>sweepStaleDelegations,scanDelegationsForRecovery:()=>scanDelegationsForRecovery,scanDelegationFallbacksForRecovery:()=>scanDelegationFallbacksForRecovery,scanBackgroundCoderReservationsForAdmission:()=>scanBackgroundCoderReservationsForAdmission,reserveBackgroundCoderSlot:()=>reserveBackgroundCoderSlot,removeDelegationFallback:()=>removeDelegationFallback,releasePreparedBackgroundAdvisories:()=>releasePreparedBackgroundAdvisories,releaseBackgroundCoderReservation:()=>releaseBackgroundCoderReservation,recordPendingDelegationDetailed:()=>recordPendingDelegationDetailed,recordPendingDelegation:()=>recordPendingDelegation,recordDelegationIngestionResult:()=>recordDelegationIngestionResult,readDelegations:()=>readDelegations,readDelegationFallback:()=>readDelegationFallback,putPendingBackgroundAdvisory:()=>putPendingBackgroundAdvisory,promoteDelegationFallback:()=>promoteDelegationFallback,preparePendingBackgroundAdvisories:()=>preparePendingBackgroundAdvisories,normalizeBackgroundObservedFiles:()=>normalizeBackgroundObservedFiles,listDelegationFallbacks:()=>listDelegationFallbacks,isUnsettledWorktreeOwner:()=>isUnsettledWorktreeOwner,findOpenAsyncLaneBatches:()=>findOpenAsyncLaneBatches,findDelegationForCompletion:()=>findDelegationForCompletion,findByCorrelationId:()=>findByCorrelationId,findByBatchId:()=>findByBatchId,compactBackgroundDelegations:()=>compactBackgroundDelegations,claimTerminalResult:()=>claimTerminalResult,claimDelegationIngestion:()=>claimDelegationIngestion,claimCoderSettlement:()=>claimCoderSettlement,buildPromptSnapshot:()=>buildPromptSnapshot,buildBackgroundCompletionEventId:()=>buildBackgroundCompletionEventId,buildBackgroundCoderReservationId:()=>buildBackgroundCoderReservationId,bindBackgroundCoderReservation:()=>bindBackgroundCoderReservation,appendDelegationTransition:()=>appendDelegationTransition,acknowledgeObservedBackgroundAdvisories:()=>acknowledgeObservedBackgroundAdvisories,_checkpointInternals:()=>_checkpointInternals,TOMBSTONE_MIN_AGE_MS:()=>TOMBSTONE_MIN_AGE_MS,MAX_RECOVERY_LEDGER_BYTES:()=>MAX_RECOVERY_LEDGER_BYTES,MAX_LIVE_BACKGROUND_FALLBACKS:()=>MAX_LIVE_BACKGROUND_FALLBACKS,MAX_LIVE_BACKGROUND_CODER_RESERVATIONS:()=>MAX_LIVE_BACKGROUND_CODER_RESERVATIONS,MAX_CHECKPOINT_RECORDS:()=>MAX_CHECKPOINT_RECORDS,MAX_CHECKPOINT_BYTES:()=>MAX_CHECKPOINT_BYTES,MAX_BACKGROUND_OBSERVED_FILES:()=>MAX_BACKGROUND_OBSERVED_FILES,MAX_BACKGROUND_ADVISORY_CHARS:()=>MAX_BACKGROUND_ADVISORY_CHARS,DELEGATION_COMPACTION_LOW_WATER_BYTES:()=>DELEGATION_COMPACTION_LOW_WATER_BYTES,DELEGATION_COMPACTION_HIGH_WATER_BYTES:()=>DELEGATION_COMPACTION_HIGH_WATER_BYTES,DEFAULT_SWEEPABLE_DELEGATION_STATUSES:()=>DEFAULT_SWEEPABLE_DELEGATION_STATUSES,DEFAULT_STALE_DELEGATION_TIMEOUT_MS:()=>DEFAULT_STALE_DELEGATION_TIMEOUT_MS,BACKGROUND_INGESTION_LEASE_MS:()=>BACKGROUND_INGESTION_LEASE_MS,BACKGROUND_DELEGATION_FALLBACK_DIR:()=>BACKGROUND_DELEGATION_FALLBACK_DIR,BACKGROUND_DELEGATIONS_MANIFEST_FILE:()=>BACKGROUND_DELEGATIONS_MANIFEST_FILE,BACKGROUND_DELEGATIONS_FILE:()=>BACKGROUND_DELEGATIONS_FILE,BACKGROUND_DELEGATIONS_CHECKPOINT_FILE:()=>BACKGROUND_DELEGATIONS_CHECKPOINT_FILE,BACKGROUND_CODER_RESERVATIONS_FILE:()=>BACKGROUND_CODER_RESERVATIONS_FILE});import{createHash as createHash6}from"node:crypto";import*as fs9 from"node:fs";import*as path13 from"node:path";import{isDeepStrictEqual}from"node:util";function storePath(directory){return validateSwarmPath(directory,BACKGROUND_DELEGATIONS_FILE)}function checkpointPath(directory){return validateSwarmPath(directory,BACKGROUND_DELEGATIONS_CHECKPOINT_FILE)}function manifestPath(directory){return validateSwarmPath(directory,BACKGROUND_DELEGATIONS_MANIFEST_FILE)}function writeDurableFileSync(target,contents){let tmp=`${target}.tmp-${process.pid}-${Math.random().toString(36).slice(2,10)}`;try{let fd=fs9.openSync(tmp,"w");try{if(typeof contents==="string")fs9.writeSync(fd,contents);else fs9.writeSync(fd,contents,0,contents.length);fs9.fsyncSync(fd)}finally{fs9.closeSync(fd)}_checkpointInternals.renameWithRetry(tmp,target)}catch(err){try{fs9.rmSync(tmp,{force:!0})}catch{}throw err}try{let dfd=fs9.openSync(path13.dirname(target),"r");try{fs9.fsyncSync(dfd)}finally{fs9.closeSync(dfd)}}catch{}}function readJsonFileWithRetry(target){let raw;try{raw=fs9.readFileSync(target,"utf-8")}catch(err){let code=err.code;if(code==="ENOENT")return{status:"absent"};return{status:"invalid",reason:`unreadable (${code??"unknown error"})`}}try{return{status:"ok",value:JSON.parse(raw)}}catch(err){return{status:"invalid",reason:`malformed JSON (${err instanceof Error?err.message:String(err)})`}}}function readDelegationManifest(directory){let read=readJsonFileWithRetry(manifestPath(directory));if(read.status==="absent")return{kind:"absent"};if(read.status==="invalid")return{kind:"invalid",reason:read.reason};let parsed=ManifestSchema.safeParse(read.value);if(!parsed.success)return{kind:"invalid",reason:"manifest fails schema validation"};return{kind:"ok",manifest:parsed.data}}function readDelegationCheckpoint(directory){let bytes=0;try{bytes=fs9.statSync(checkpointPath(directory)).size}catch{}if(bytes>MAX_CHECKPOINT_BYTES)return{kind:"invalid",reason:`checkpoint exceeds the ${MAX_CHECKPOINT_BYTES}-byte bound`};let read=readJsonFileWithRetry(checkpointPath(directory));if(read.status==="absent")return{kind:"absent"};if(read.status==="invalid")return{kind:"invalid",reason:read.reason};let parsed=CheckpointSchema.safeParse(read.value);if(!parsed.success)return{kind:"invalid",reason:"checkpoint fails schema validation"};return{kind:"ok",checkpoint:parsed.data,bytes}}function sha256Hex(data){return createHash6("sha256").update(data).digest("hex")}function checkpointPayloadChecksum(checkpoint){return sha256Hex(JSON.stringify([checkpoint.schemaVersion,checkpoint.sequence,checkpoint.writerId,checkpoint.rootPath,checkpoint.createdAt,checkpoint.cutLedgerBytes,checkpoint.cutLedgerDigest,checkpoint.records,checkpoint.closed,checkpoint.audit]))}function loadFoldedState(directory,options){let manifestRead=readDelegationManifest(directory);if(manifestRead.kind==="invalid")return{status:"uncertain",reason:`background delegation manifest is invalid: ${manifestRead.reason}`,repairHint:CHECKPOINT_RESET_HINT};if(manifestRead.kind==="absent")return loadLegacyLedger(directory,options.strict);let manifest=manifestRead.manifest;if(manifest.rootPath!==path13.resolve(directory))return{status:"uncertain",reason:"background delegation checkpoint is bound to a different project root",repairHint:CHECKPOINT_REBIND_HINT};let checkpointRead=readDelegationCheckpoint(directory);if(checkpointRead.kind==="invalid"||checkpointRead.kind==="absent")return{status:"uncertain",reason:`background delegation checkpoint is invalid${checkpointRead.kind==="invalid"?`: ${checkpointRead.reason}`:" (file missing)"} while a manifest is published`,repairHint:CHECKPOINT_RESET_HINT};let checkpoint=checkpointRead.checkpoint;if(checkpoint.sequence!==manifest.sequence&&checkpoint.sequence!==manifest.sequence+1)return{status:"uncertain",reason:`background delegation checkpoint/manifest sequence mismatch (checkpoint ${checkpoint.sequence}, manifest ${manifest.sequence})`,repairHint:CHECKPOINT_RESET_HINT};if(checkpoint.sequence===manifest.sequence&&manifest.checkpointChecksum!==checkpoint.payloadChecksum)return{status:"uncertain",reason:"background delegation manifest checksum does not match its checkpoint",repairHint:CHECKPOINT_RESET_HINT};if(checkpointPayloadChecksum(checkpoint)!==checkpoint.payloadChecksum)return{status:"uncertain",reason:"background delegation checkpoint payload checksum mismatch",repairHint:CHECKPOINT_RESET_HINT};let stat5;try{stat5=fs9.statSync(storePath(directory))}catch(error49){return{status:"uncertain",reason:`background delegation ledger metadata is unreadable: ${error49 instanceof Error?error49.message:String(error49)}`}}let tail,mode;if(stat5.size>=checkpoint.cutLedgerBytes&&checkpoint.cutLedgerBytes>0){let prefix=readLedgerRegion(directory,0,checkpoint.cutLedgerBytes);if(sha256Hex(prefix)===checkpoint.cutLedgerDigest){let suffixBytes=stat5.size-checkpoint.cutLedgerBytes;if(suffixBytes>MAX_RECOVERY_LEDGER_BYTES)return{status:"uncertain",reason:`background delegation ledger changed beyond the ${MAX_RECOVERY_LEDGER_BYTES}-byte recovery bound`};tail=suffixBytes===0?Buffer.alloc(0):readLedgerRegion(directory,checkpoint.cutLedgerBytes,suffixBytes),mode="checkpoint+ledger-suffix"}else tail=readBoundedRecentLedgerWindow(directory,stat5.size),mode="checkpoint+tail"}else tail=readBoundedRecentLedgerWindow(directory,stat5.size),mode="checkpoint+tail";let records=new Map;for(let record2 of checkpoint.records)records.set(record2.correlationId,record2);for(let summary of checkpoint.closed)records.set(summary.correlationId,summary);let foldError=foldLedgerTail(records,tail,options.strict,checkpoint);if(foldError)return{status:"uncertain",reason:foldError};return{status:"ok",mode,records,manifest,checkpoint}}function readLedgerRegion(directory,offset,length){let fd=fs9.openSync(storePath(directory),"r");try{let buffer=Buffer.alloc(length),read=0;while(read<length){let n=fs9.readSync(fd,buffer,read,length-read,offset+read);if(n<=0)break;read+=n}return read===length?buffer:buffer.subarray(0,read)}finally{fs9.closeSync(fd)}}function readBoundedRecentLedgerWindow(directory,size){if(size===0)return Buffer.alloc(0);if(size<=MAX_RECOVERY_LEDGER_BYTES)return readLedgerRegion(directory,0,size);let window2=readLedgerRegion(directory,size-MAX_RECOVERY_LEDGER_BYTES,MAX_RECOVERY_LEDGER_BYTES),firstNewline=window2.indexOf(10);return firstNewline===-1?Buffer.alloc(0):window2.subarray(firstNewline+1)}function foldLedgerTail(records,tail,strict,checkpoint){let lineNumber=0;for(let line of tail.toString("utf-8").split(`
183
+ `}function laneOutputRelativePath(ref){let[,batchDigest,laneDigest,outputDigest]=ref.split(":");return path8.join("lane-results",batchDigest,laneDigest,`${outputDigest}.json`)}function hasValidArtifactIntegrity(artifact,expectedRef){let digest=digestText(artifact.text);if(artifact.digest!==digest)return!1;if(artifact.chars!==artifact.text.length)return!1;if(artifact.bytes!==Buffer.byteLength(artifact.text,"utf-8"))return!1;let batchDigest=digestText(artifact.batchId),laneDigest=digestText(artifact.laneId),expectedArtifactRef=`${LANE_OUTPUT_REF_PREFIX}:${batchDigest}:${laneDigest}:${digest}`;return artifact.ref===expectedRef&&artifact.ref===expectedArtifactRef}function artifactIdentityMatchesInput(artifact,input){return artifact.agent===input.agent&&artifact.role===input.role&&artifact.sessionId===input.sessionId&&artifact.parentSessionId===input.parentSessionId&&artifact.mode===input.mode&&artifact.workflowLane===input.workflowLane&&artifact.prHeadSha===input.prHeadSha&&artifact.gitHead===input.gitHead&&artifact.revisionDigest===input.revisionDigest&&artifact.scope===input.scope&&artifact.source===input.source}function writeAtomicJson(absPath,value){mkdirSync2(path8.dirname(absPath),{recursive:!0});let tempFile=`${absPath}.tmp-${Date.now()}-${process.pid}`;try{writeFileSync(tempFile,JSON.stringify(value,null,2),"utf-8");let lastRenameError;for(let attempt=0;attempt<WINDOWS_RENAME_MAX_RETRIES2;attempt++)try{renameSync(tempFile,absPath),lastRenameError=void 0;break}catch(err){lastRenameError=err;let code=err.code;if(code!=="EEXIST"&&code!=="EBUSY"&&code!=="EPERM")break}if(lastRenameError)throw lastRenameError}finally{if(existsSync3(tempFile))try{unlinkSync(tempFile)}catch{}}}function digestText(text){return createHash2("sha256").update(text).digest("hex")}var LANE_OUTPUT_REF_PREFIX="L1",MAX_LANE_OUTPUT_STORED_BYTES=10485760,LANE_OUTPUT_SCHEMA_VERSION=1,REF_RE,LaneOutputArtifactSchema,WINDOWS_RENAME_MAX_RETRIES2=3;var init_lane_output_store=__esm(()=>{init_zod();init_utils2();REF_RE=/^L1:[a-f0-9]{64}:[a-f0-9]{64}:[a-f0-9]{64}$/,LaneOutputArtifactSchema=exports_external.object({schemaVersion:exports_external.literal(LANE_OUTPUT_SCHEMA_VERSION),ref:exports_external.string().regex(REF_RE),batchId:exports_external.string().min(1),laneId:exports_external.string().min(1),agent:exports_external.string().min(1),role:exports_external.string().min(1),sessionId:exports_external.string().min(1).optional(),parentSessionId:exports_external.string().min(1).optional(),mode:exports_external.string().min(1).optional(),workflowLane:exports_external.string().min(1).optional(),prHeadSha:exports_external.string().min(1).optional(),gitHead:exports_external.string().min(1).optional(),revisionDigest:exports_external.string().min(1).optional(),scope:exports_external.string().min(1).optional(),source:exports_external.enum(["dispatch_lanes","collect_lane_results"]),text:exports_external.string(),chars:exports_external.number().int().nonnegative(),bytes:exports_external.number().int().nonnegative(),digest:exports_external.string().regex(/^[a-f0-9]{64}$/),messageCount:exports_external.number().int().nonnegative().optional(),transcriptIncomplete:exports_external.boolean().optional(),createdAt:exports_external.string(),updatedAt:exports_external.string()}).strict()});import*as crypto2 from"node:crypto";import*as fs5 from"node:fs";import*as path9 from"node:path";function getLockFilePath(directory,filePath){let normalized=path9.resolve(directory,filePath),baseDir=path9.resolve(directory)+path9.sep;if(!(process.platform==="win32"?normalized.toLowerCase().startsWith(baseDir.toLowerCase()):normalized.startsWith(baseDir)))throw Error("Invalid file path: path traversal not allowed");let pathForHash=process.platform==="win32"?normalized.toLowerCase():normalized,hash2=crypto2.createHash("sha256").update(pathForHash).digest("hex"),lockPath=path9.join(directory,LOCKS_DIR,`${hash2}.lock`),legacyPaths=[pathForHash];if(process.platform==="win32"&&normalized!==pathForHash)legacyPaths.push(normalized);for(let legacyPath of legacyPaths){let oldHash=Buffer.from(legacyPath).toString("base64").replace(/[/+=]/g,"_"),oldLockPath=path9.join(directory,LOCKS_DIR,`${oldHash}.lock`);if(fs5.existsSync(oldLockPath))return oldLockPath}return lockPath}function getMetaPath(lockPath){return`${lockPath.replace(/\.lock$/,"")}.meta`}async function writeMetaFile(metaPath,metadata){let tmpPath=`${metaPath}.tmp`;try{await _internals7.writeFile(tmpPath,JSON.stringify(metadata),"utf-8"),await fs5.promises.rename(tmpPath,metaPath)}catch(err){try{await fs5.promises.unlink(tmpPath)}catch{}throw err}}function readMetaFile(metaPath){try{let content=fs5.readFileSync(metaPath,"utf-8");return JSON.parse(content)}catch{return null}}async function tryAcquireLock(directory,filePath,agent,taskId){let lockPath=getLockFilePath(directory,filePath),locksDir=path9.dirname(lockPath);if(!fs5.existsSync(locksDir))fs5.mkdirSync(locksDir,{recursive:!0});if(!fs5.existsSync(lockPath))fs5.writeFileSync(lockPath,"","utf-8");let release;try{release=await import_proper_lockfile2.default.lock(lockPath,{stale:LOCK_TIMEOUT_MS,retries:{retries:5,minTimeout:10,maxTimeout:500,factor:2},realpath:!1})}catch(err){let code=err.code;if(code==="ELOCKED"||code==="EEXIST")return{acquired:!1};throw err}return{acquired:!0,lock:{filePath,agent,taskId,timestamp:new Date().toISOString(),expiresAt:Date.now()+LOCK_TIMEOUT_MS,_release:release}}}function isLocked(directory,filePath){let plLockDir=`${getLockFilePath(directory,filePath)}.lock`;if(fs5.existsSync(plLockDir)){let acquiredAt=Date.now();try{acquiredAt=fs5.statSync(plLockDir).mtimeMs}catch{}return{filePath,agent:"unknown",taskId:"unknown",timestamp:new Date(acquiredAt).toISOString(),expiresAt:acquiredAt+LOCK_TIMEOUT_MS}}return null}function listActiveLocks(directory){let locksDir=path9.join(directory,LOCKS_DIR),locks=[];if(!fs5.existsSync(locksDir))return locks;let files=fs5.readdirSync(locksDir),now=Date.now();for(let file2 of files){if(!file2.endsWith(".lock"))continue;let lockPath=path9.join(locksDir,file2);try{if(fs5.statSync(lockPath).isFile()){let plLockDir=`${lockPath}.lock`;if(fs5.existsSync(plLockDir)){let metaPath=getMetaPath(lockPath),meta3=readMetaFile(metaPath);if(meta3){if(meta3.expiresAt<now)continue;locks.push({filePath:meta3.originalPath,agent:meta3.agent,taskId:meta3.taskId,timestamp:meta3.acquiredAt,expiresAt:meta3.expiresAt,laneId:meta3.laneId})}else{let acquiredAt=Date.now();try{acquiredAt=fs5.statSync(plLockDir).mtimeMs}catch{}let expiresAt=acquiredAt+LOCK_TIMEOUT_MS;if(expiresAt<now)continue;locks.push({filePath:lockPath,agent:"unknown",taskId:"unknown",timestamp:new Date(acquiredAt).toISOString(),expiresAt})}}}}catch{}}return locks}async function acquireLaneLocks(directory,laneId,files,agent,taskId,sessionID){let acquiredLocks=[],conflicts=[];for(let file2 of files){let result=await tryAcquireLock(directory,file2,agent,taskId);if(!result.acquired){for(let lock of acquiredLocks)try{if(lock._release)await lock._release();let lockPath2=getLockFilePath(directory,lock.filePath),metaPath2=getMetaPath(lockPath2);try{fs5.unlinkSync(metaPath2)}catch{}try{fs5.unlinkSync(lockPath2)}catch{}}catch{}return conflicts.push(file2),{acquired:!1,conflicts}}let lockPath=getLockFilePath(directory,file2),metaPath=getMetaPath(lockPath),meta3={originalPath:file2,laneId,taskId,agent,sessionID,acquiredAt:result.lock.timestamp,expiresAt:result.lock.expiresAt};try{await writeMetaFile(metaPath,meta3)}catch(err){for(let lock of acquiredLocks)try{if(lock._release)await lock._release();let lp=getLockFilePath(directory,lock.filePath),mp=getMetaPath(lp);try{fs5.unlinkSync(mp)}catch{}try{fs5.unlinkSync(lp)}catch{}}catch{}if(result.lock._release)await result.lock._release();try{fs5.unlinkSync(lockPath)}catch{}throw err}result.lock.laneId=laneId,acquiredLocks.push(result.lock)}return{acquired:!0,locks:acquiredLocks}}async function releaseLaneLocks(directory,laneId){let locksDir=path9.join(directory,LOCKS_DIR);if(!fs5.existsSync(locksDir))return 0;let files=fs5.readdirSync(locksDir),releasedCount=0;for(let file2 of files){if(!file2.endsWith(".meta"))continue;let metaPath=path9.join(locksDir,file2),meta3=readMetaFile(metaPath);if(!meta3||meta3.laneId!==laneId)continue;let lockPath=metaPath.replace(/\.meta$/,".lock");try{try{await import_proper_lockfile2.default.unlock(lockPath,{realpath:!1})}catch{}try{fs5.unlinkSync(lockPath)}catch{}try{fs5.unlinkSync(metaPath)}catch{}releasedCount++}catch{}}return releasedCount}var import_proper_lockfile2,LOCKS_DIR=".swarm/locks",LOCK_TIMEOUT_MS=300000,_internals7;var init_file_locks=__esm(()=>{import_proper_lockfile2=__toESM(require_proper_lockfile(),1),_internals7={tryAcquireLock,writeFile:fs5.promises.writeFile}});function defineEntry(kind,input){let entry={kind,category:input.category,severity:input.severity,privacyClass:input.privacyClass,producer:input.producer,consumers:input.consumers,retentionOwnerIssue:input.retentionOwnerIssue,requiredWorkflowIds:input.requiredWorkflowIds??NO_WORKFLOW_IDS,forbiddenWorkflowIds:input.forbiddenWorkflowIds??NO_WORKFLOW_IDS,requiresParent:input.requiresParent??!1,allowsLinks:input.allowsLinks??!0,otelMapping:input.otelMapping??"none",docAnchor:`#${kind}`,testFile:"tests/unit/observability/catalog-contract.test.ts"};if(input.futureOwnerIssue!==void 0)return Object.freeze({...entry,futureOwnerIssue:input.futureOwnerIssue});return Object.freeze(entry)}function getCatalogEntry(kind){return Object.hasOwn(EVENT_CATALOG,kind)?EVENT_CATALOG[kind]:void 0}var NO_WORKFLOW_IDS,NO_CONSUMERS,REQUIRE_SESSION,REQUIRE_SESSION_AND_TASK,REQUIRE_TASK,FORBID_SESSION,CONSUMER_COST_ACCOUNTING,CONSUMER_GATE_STATS,CONSUMER_HEARTBEAT_LISTENER,CATALOG_SOURCE,catalog,EVENT_CATALOG,CATALOG_KINDS;var init_catalog=__esm(()=>{NO_WORKFLOW_IDS=Object.freeze([]),NO_CONSUMERS=Object.freeze([]),REQUIRE_SESSION=Object.freeze(["hostSessionId"]),REQUIRE_SESSION_AND_TASK=Object.freeze(["hostSessionId","taskId"]),REQUIRE_TASK=Object.freeze(["taskId"]),FORBID_SESSION=Object.freeze(["hostSessionId"]),CONSUMER_COST_ACCOUNTING=Object.freeze(["src/services/cost-accounting.ts:127"]),CONSUMER_GATE_STATS=Object.freeze(["src/evaluation/gate-stats.ts:99"]),CONSUMER_HEARTBEAT_LISTENER=Object.freeze(["src/telemetry.ts:186"]);CATALOG_SOURCE=[["session_started",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:491",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"openinference"}],["session_ended",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:495",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"openinference"}],["agent_activated",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:499",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"openinference"}],["task_state_changed",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:536",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK,otelMapping:"openinference"}],["phase_changed",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:584",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"openinference"}],["heartbeat",{category:"lifecycle",severity:"debug",privacyClass:"pseudonymous",producer:"src/telemetry.ts:766",consumers:CONSUMER_HEARTBEAT_LISTENER,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,allowsLinks:!1}],["turbo_mode_changed",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:774",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION}],["environment_detected",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:799",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,allowsLinks:!1}],["delegation_begin",{category:"delegation",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:503",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK,otelMapping:"genai"}],["delegation_end",{category:"delegation",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:513",consumers:CONSUMER_COST_ACCOUNTING,retentionOwnerIssue:2043,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK,otelMapping:"genai"}],["model_fallback",{category:"delegation",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:617",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"genai"}],["model_unresolved",{category:"delegation",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:631",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"genai"}],["gate_passed",{category:"gate",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:545",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK}],["gate_failed",{category:"gate",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:562",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK}],["gate_parse_error",{category:"gate",severity:"warning",privacyClass:"sensitive",producer:"src/telemetry.ts:549",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_TASK,forbiddenWorkflowIds:FORBID_SESSION}],["reviewer_gate_decision",{category:"gate",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:572",consumers:CONSUMER_GATE_STATS,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK}],["budget_updated",{category:"cost",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:588",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2043,requiredWorkflowIds:REQUIRE_SESSION}],["context_pruned",{category:"guardrail",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:607",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["hard_limit_hit",{category:"guardrail",severity:"error",privacyClass:"pseudonymous",producer:"src/telemetry.ts:645",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["revision_limit_hit",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:654",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["loop_detected",{category:"guardrail",severity:"warning",privacyClass:"sensitive",producer:"src/telemetry.ts:658",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["scope_violation",{category:"guardrail",severity:"error",privacyClass:"sensitive",producer:"src/telemetry.ts:754",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["qa_skip_violation",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:762",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["auto_oversight_escalation",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:784",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["no_op_strong_warning",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:672",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["gate_denial_loop",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:693",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["execution_stall_warning",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:707",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["execution_stall_denied",{category:"guardrail",severity:"error",privacyClass:"pseudonymous",producer:"src/telemetry.ts:724",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["swarm_internals_read_denied",{category:"guardrail",severity:"error",privacyClass:"sensitive",producer:"src/telemetry.ts:741",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_hard_stop_delivered",{category:"prm",severity:"error",privacyClass:"pseudonymous",producer:"src/telemetry.ts:991",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_pattern_detected",{category:"prm",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:814",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_course_correction_injected",{category:"prm",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:828",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_escalation_triggered",{category:"prm",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:841",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_hard_stop",{category:"prm",severity:"critical",privacyClass:"pseudonymous",producer:"src/telemetry.ts:855",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["evidence_lock_acquired",{category:"evidence",severity:"info",privacyClass:"sensitive",producer:"src/evidence/lock.ts:99",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,requiredWorkflowIds:REQUIRE_TASK,forbiddenWorkflowIds:FORBID_SESSION}],["evidence_lock_contended",{category:"evidence",severity:"notice",privacyClass:"sensitive",producer:"src/evidence/lock.ts:134",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,requiredWorkflowIds:REQUIRE_TASK,forbiddenWorkflowIds:FORBID_SESSION}],["evidence_lock_stale_recovered",{category:"evidence",severity:"notice",privacyClass:"sensitive",producer:"src/evidence/lock.ts:91",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,requiredWorkflowIds:REQUIRE_TASK,forbiddenWorkflowIds:FORBID_SESSION}],["plan_ledger_cas_retry",{category:"plan",severity:"notice",privacyClass:"operational",producer:"src/plan/manager.ts:344",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,forbiddenWorkflowIds:FORBID_SESSION}],["plan_md_write_failed",{category:"plan",severity:"warning",privacyClass:"sensitive",producer:"src/plan/manager.ts:1861",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,forbiddenWorkflowIds:FORBID_SESSION}],["snapshot_failed",{category:"plan",severity:"error",privacyClass:"sensitive",producer:"src/plan/ledger.ts:1143",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,forbiddenWorkflowIds:FORBID_SESSION}],["agent_conflict_detected",{category:"conflict",severity:"warning",privacyClass:"pseudonymous",producer:"src/hooks/conflict-resolution.ts:73",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:Object.freeze(["hostSessionId","phaseId"])}],["close_archive_result",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:892",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047}],["knowledge_receipt_transition",{category:"knowledge",severity:"info",privacyClass:"pseudonymous",producer:"src/hooks/knowledge-receipt-observability.ts:197",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["knowledge_maintenance",{category:"knowledge",severity:"notice",privacyClass:"pseudonymous",producer:"src/knowledge/hive-quarantine.ts:1265",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["residue_health",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:914",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["context_telemetry_health",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:938",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["skill_usage_health",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:975",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}]],catalog={};for(let[kind,input]of CATALOG_SOURCE)catalog[kind]=defineEntry(kind,input);EVENT_CATALOG=Object.freeze(catalog),CATALOG_KINDS=Object.freeze(Object.keys(EVENT_CATALOG))});var OBSERVABILITY_SCHEMA_VERSION=1,EventCategorySchema,EventSeveritySchema,PrivacyClassSchema,TimingConfidenceSchema,SpanLinkSchema,TraceContextSchema,WorkflowIdsSchema,LineageSchema,ProvenanceSchema,OutcomeSchema,PolicySchema,LegacyProjectionSchema,ObservabilityEventSchema;var init_envelope=__esm(()=>{init_zod();EventCategorySchema=exports_external.enum(["lifecycle","delegation","gate","plan","evidence","guardrail","knowledge","cost","prm","conflict","unrecognized"]),EventSeveritySchema=exports_external.enum(["debug","info","notice","warning","error","critical"]),PrivacyClassSchema=exports_external.enum(["operational","pseudonymous","sensitive","content"]),TimingConfidenceSchema=exports_external.enum(["exact","writer-clock","inferred","unknown"]),SpanLinkSchema=exports_external.object({traceId:exports_external.string(),spanId:exports_external.string(),kind:exports_external.enum(["resume","lane","cross-process","retry","parent-batch"]),note:exports_external.string().optional()}),TraceContextSchema=exports_external.object({traceId:exports_external.string(),spanId:exports_external.string(),parentSpanId:exports_external.string().optional(),links:exports_external.array(SpanLinkSchema)}),WorkflowIdsSchema=exports_external.object({rootConversationId:exports_external.string().optional(),hostSessionId:exports_external.string().optional(),swarmSessionId:exports_external.string().optional(),taskId:exports_external.string().optional(),phaseId:exports_external.string().optional(),laneId:exports_external.string().optional(),batchId:exports_external.string().optional(),resultId:exports_external.string().optional(),councilRoundId:exports_external.string().optional(),backgroundInvocationId:exports_external.string().optional(),knowledgeTraceId:exports_external.string().optional(),knowledgeEntryId:exports_external.string().optional(),prRunId:exports_external.string().optional()}),LineageSchema=exports_external.object({projectRef:exports_external.string().optional(),cohortRef:exports_external.string().optional(),worktreeRef:exports_external.string().optional()}),ProvenanceSchema=exports_external.object({pluginVersion:exports_external.string().optional(),opencodeVersion:exports_external.string().optional(),runtime:exports_external.string().optional(),runtimeVersion:exports_external.string().optional(),os:exports_external.string().optional(),arch:exports_external.string().optional(),model:exports_external.string().optional(),provider:exports_external.string().optional(),gitSha:exports_external.string().optional(),configHash:exports_external.string().optional()}),OutcomeSchema=exports_external.object({status:exports_external.enum(["success","failure","partial","unknown"]).optional(),reason:exports_external.string().optional(),errorName:exports_external.string().optional(),errorMessage:exports_external.string().optional(),retryIndex:exports_external.number().optional(),durationMs:exports_external.number().optional()}),PolicySchema=exports_external.object({sampled:exports_external.boolean(),sampleRate:exports_external.number(),dropReason:exports_external.string().optional(),privacyClass:PrivacyClassSchema}),LegacyProjectionSchema=exports_external.object({sourceStore:exports_external.string(),sourceSchemaVersion:exports_external.number().nullable(),timingConfidence:TimingConfidenceSchema,unknown:exports_external.array(exports_external.string()),extra:exports_external.record(exports_external.string(),exports_external.unknown()),raw:exports_external.unknown()}),ObservabilityEventSchema=exports_external.object({schemaVersion:exports_external.number(),eventId:exports_external.string(),kind:exports_external.string(),category:EventCategorySchema,severity:EventSeveritySchema,occurredAt:exports_external.string(),observedAt:exports_external.string(),writerSequence:exports_external.number(),trace:TraceContextSchema,workflow:WorkflowIdsSchema,lineage:LineageSchema,provenance:ProvenanceSchema,outcome:OutcomeSchema,policy:PolicySchema,legacy:LegacyProjectionSchema,relationshipViolations:exports_external.array(exports_external.string())})});import{createHash as createHash4,randomBytes,randomUUID as randomUUID2}from"node:crypto";function newTraceId(){for(let attempt=0;attempt<MAX_REGENERATION_ATTEMPTS;attempt++){let hex3=randomBytes(TRACE_ID_BYTES).toString("hex");if(hex3!==ALL_ZERO_TRACE_ID)return hex3}return SENTINEL_TRACE_ID}function newSpanId(){for(let attempt=0;attempt<MAX_REGENERATION_ATTEMPTS;attempt++){let hex3=randomBytes(SPAN_ID_BYTES).toString("hex");if(hex3!==ALL_ZERO_SPAN_ID)return hex3}return SENTINEL_SPAN_ID}function newEventId(){return randomUUID2()}function takeIdBytes(){let need=TRACE_ID_BYTES+SPAN_ID_BYTES;if(_poolOffset+need>_pool.length)_pool=randomBytes(POOL_BYTES),_poolOffset=0;let slice=_pool.subarray(_poolOffset,_poolOffset+need);return _poolOffset+=need,slice}function newTraceAndSpanId(){let buffer=takeIdBytes(),traceId=buffer.subarray(0,TRACE_ID_BYTES).toString("hex"),spanId=buffer.subarray(TRACE_ID_BYTES).toString("hex");if(traceId===ALL_ZERO_TRACE_ID||spanId===ALL_ZERO_SPAN_ID)return{traceId:newTraceId(),spanId:newSpanId()};return{traceId,spanId}}function resolveLineageSalt(){let configured=process.env[LINEAGE_SALT_ENV];if(typeof configured==="string"&&configured.length>0)return configured;return DEFAULT_LINEAGE_SALT}function pseudonymousRef(absolutePath,salt){return createHash4("sha256").update(salt+LINEAGE_SEPARATOR+absolutePath,"utf8").digest("hex").slice(0,PSEUDONYMOUS_REF_LENGTH)}var TRACE_ID_BYTES=16,SPAN_ID_BYTES=8,TRACE_ID_HEX_LENGTH,SPAN_ID_HEX_LENGTH,ALL_ZERO_TRACE_ID,ALL_ZERO_SPAN_ID,SENTINEL_TRACE_ID,SENTINEL_SPAN_ID,MAX_REGENERATION_ATTEMPTS=4,LINEAGE_SALT_ENV="SWARM_OBSERVABILITY_LINEAGE_SALT",DEFAULT_LINEAGE_SALT="opencode-swarm/observability/lineage/v1",LINEAGE_SEPARATOR="\x00",PSEUDONYMOUS_REF_LENGTH=16,POOL_DRAWS=128,POOL_BYTES,_pool,_poolOffset;var init_ids=__esm(()=>{TRACE_ID_HEX_LENGTH=TRACE_ID_BYTES*2,SPAN_ID_HEX_LENGTH=SPAN_ID_BYTES*2,ALL_ZERO_TRACE_ID="0".repeat(TRACE_ID_HEX_LENGTH),ALL_ZERO_SPAN_ID="0".repeat(SPAN_ID_HEX_LENGTH),SENTINEL_TRACE_ID=`${"0".repeat(TRACE_ID_HEX_LENGTH-1)}1`,SENTINEL_SPAN_ID=`${"0".repeat(SPAN_ID_HEX_LENGTH-1)}1`;POOL_BYTES=(TRACE_ID_BYTES+SPAN_ID_BYTES)*POOL_DRAWS,_pool=Buffer.alloc(0),_poolOffset=Number.POSITIVE_INFINITY});function degradedProjection(marker,data){return{sourceStore:".swarm/telemetry.jsonl",sourceSchemaVersion:null,timingConfidence:"writer-clock",unknown:[marker],extra:EMPTY_EXTRA,raw:data}}function knownKeySetFor(knownKeys){let cached2=_knownKeySetCache.get(knownKeys);if(cached2!==void 0)return cached2;let built=new Set(knownKeys);return _knownKeySetCache.set(knownKeys,built),built}function adaptLegacyTelemetryPayload(kind,data,knownKeys){if(data===null||typeof data!=="object")return degradedProjection("<non-object-payload>",data);try{let record2=data,known=knownKeySetFor(knownKeys),ownKeys=Object.keys(record2),extra;for(let key of ownKeys){if(known.has(key))continue;if(extra??={},key==="__proto__"){Object.defineProperty(extra,key,{value:record2[key],enumerable:!0,writable:!0,configurable:!0});continue}extra[key]=record2[key]}let unknownFields;for(let key of knownKeys)if(record2[key]===void 0)unknownFields??=[],unknownFields.push(key);return{sourceStore:".swarm/telemetry.jsonl",sourceSchemaVersion:null,timingConfidence:"writer-clock",unknown:unknownFields??EMPTY_UNKNOWN,extra:extra??EMPTY_EXTRA,raw:data}}catch{return degradedProjection("<payload-introspection-failed>",data)}}function nonEmptyString(value){return typeof value==="string"&&value.length>0?value:void 0}function extractWorkflowIds(data){let ids={};try{if(data===null||typeof data!=="object")return ids;let record2=data,hostSessionId=nonEmptyString(record2.sessionId);if(hostSessionId!==void 0)ids.hostSessionId=hostSessionId;let taskId=nonEmptyString(record2.taskId);if(taskId!==void 0)ids.taskId=taskId;let laneId=nonEmptyString(record2.laneId);if(laneId!==void 0)ids.laneId=laneId;let batchId=nonEmptyString(record2.batchId);if(batchId!==void 0)ids.batchId=batchId;let knowledgeTraceId=nonEmptyString(record2.knowledgeTraceId);if(knowledgeTraceId!==void 0)ids.knowledgeTraceId=knowledgeTraceId;let knowledgeEntryId=nonEmptyString(record2.knowledgeEntryId);if(knowledgeEntryId!==void 0)ids.knowledgeEntryId=knowledgeEntryId;let phase=record2.phase;if(typeof phase==="number"&&Number.isFinite(phase))ids.phaseId=String(phase);else{let phaseString=nonEmptyString(phase);if(phaseString!==void 0)ids.phaseId=phaseString}}catch{}return ids}function extractOutcome(data){let outcome={};try{if(data===null||typeof data!=="object")return outcome;let record2=data,result=nonEmptyString(record2.result);if(result!==void 0){let normalized=result.toLowerCase();outcome.status=Object.hasOwn(RESULT_STATUS_MAP,normalized)?RESULT_STATUS_MAP[normalized]:"unknown"}let reason=nonEmptyString(record2.reason);if(reason!==void 0)outcome.reason=reason;let errorName=nonEmptyString(record2.errorName);if(errorName!==void 0)outcome.errorName=errorName;let errorMessage=nonEmptyString(record2.errorMessage);if(errorMessage!==void 0)outcome.errorMessage=errorMessage;let retryIndex=record2.retry_index;if(typeof retryIndex==="number"&&Number.isFinite(retryIndex))outcome.retryIndex=retryIndex}catch{}return outcome}var LEGACY_TELEMETRY_SOURCE_STORE=".swarm/telemetry.jsonl",LEGACY_ADAPTER_RULES,KNOWN_TELEMETRY_KEYS,EMPTY_EXTRA,EMPTY_UNKNOWN,_knownKeySetCache,RESULT_STATUS_MAP;var init_legacy=__esm(()=>{LEGACY_ADAPTER_RULES=Object.freeze(["Preserve unknown fields: an own key the contract does not recognize is kept under `extra` by reference and is never dropped.","Record the source store and its schema version: `sourceStore` names the file; `sourceSchemaVersion` is the version the store declares.","Preserve originally reported values: values are aliased, never coerced, normalized, rounded, or re-serialized.","Record timing confidence: a time read by the writer at record time is `writer-clock`, never `exact`.","Unknown is not zero: the adapter lists in `unknown` every catalogued key the PRODUCER left undefined, and never itself defaults one to 0, \"\", false, or null. The guarantee stops at the adapter boundary — a producer that pre-coerces its own defaults defeats it, because the adapter only ever sees the coerced value. The known instance is `delegation_end` (`src/telemetry.ts` `delegationEnd`, pre-existing): it coerces `?? 0` / `?? null` / `?? 'unavailable'` before emitting, so its cost fields can never appear in `unknown`; there, `cost_source: 'unavailable'` is how absence stays recoverable.","Missing lineage stays missing: an absent correlation ID stays `undefined` and is never synthesized to make a join succeed.","Never drop unrecognized fields: no allowlist filter is applied to the payload on the way through."]),KNOWN_TELEMETRY_KEYS=Object.freeze({session_started:Object.freeze(["sessionId","agentName"]),session_ended:Object.freeze(["sessionId","reason"]),agent_activated:Object.freeze(["sessionId","agentName","oldName"]),delegation_begin:Object.freeze(["sessionId","agentName","taskId"]),delegation_end:Object.freeze(["sessionId","agentName","taskId","result","tokens_input","tokens_output","tokens_reasoning","tokens_cache","cost_usd","cost_source","model","gate","retry_index"]),task_state_changed:Object.freeze(["sessionId","taskId","newState","oldState"]),gate_passed:Object.freeze(["sessionId","gate","taskId"]),gate_parse_error:Object.freeze(["taskId","errorName","errorMessage"]),gate_failed:Object.freeze(["sessionId","gate","taskId","reason"]),reviewer_gate_decision:Object.freeze(["sessionId","gate","taskId","blocked","allowed","reasonCode","evidenceKind"]),phase_changed:Object.freeze(["sessionId","oldPhase","newPhase"]),budget_updated:Object.freeze(["sessionId","budgetPct","agentName"]),context_pruned:Object.freeze(["sessionId","agentName","trigger","usageSource","beforeTokens","afterTokens","modelLimit","maskedMessages","maskedToolParts","maskedTokensFreed","prunedMessages","prunedTextParts","prunedToolParts","prunedTokensFreed"]),model_fallback:Object.freeze(["sessionId","agentName","fromModel","toModel","reason"]),model_unresolved:Object.freeze(["sessionId","agentName","model","detail"]),hard_limit_hit:Object.freeze(["sessionId","agentName","limitType","value"]),revision_limit_hit:Object.freeze(["sessionId","agentName"]),loop_detected:Object.freeze(["sessionId","agentName","loopType"]),scope_violation:Object.freeze(["sessionId","agentName","file","reason"]),qa_skip_violation:Object.freeze(["sessionId","agentName","skipCount"]),heartbeat:Object.freeze(["sessionId"]),turbo_mode_changed:Object.freeze(["sessionId","enabled","agentName"]),auto_oversight_escalation:Object.freeze(["sessionId","reason","interactionCount","deadlockCount","phase"]),environment_detected:Object.freeze(["sessionId","hostOS","shellFamily","executionMode"]),prm_pattern_detected:Object.freeze(["sessionId","pattern","severity","category","stepRange"]),prm_course_correction_injected:Object.freeze(["sessionId","pattern","level"]),prm_escalation_triggered:Object.freeze(["sessionId","pattern","level","occurrenceCount"]),prm_hard_stop:Object.freeze(["sessionId","pattern","level","occurrenceCount"]),no_op_strong_warning:Object.freeze(["sessionId","agentName","count","threshold"]),gate_denial_loop:Object.freeze(["sessionId","tool","code","count"]),execution_stall_warning:Object.freeze(["sessionId","count","threshold"]),execution_stall_denied:Object.freeze(["sessionId","tool","count","threshold"]),swarm_internals_read_denied:Object.freeze(["sessionId","tool","target"]),prm_hard_stop_delivered:Object.freeze(["sessionId","pattern","level","occurrenceCount"]),evidence_lock_acquired:Object.freeze(["directory","evidencePath","agent","taskId","attempt"]),evidence_lock_contended:Object.freeze(["directory","evidencePath","agent","taskId","attempt"]),evidence_lock_stale_recovered:Object.freeze(["directory","evidencePath","agent","taskId","attempt"]),plan_ledger_cas_retry:Object.freeze(["attempt","expectedHashPrefix","delayMs"]),plan_md_write_failed:Object.freeze(["directory","error","timestamp"]),snapshot_failed:Object.freeze(["error","retries","source"]),agent_conflict_detected:Object.freeze(["type","timestamp","sessionId","phase","taskId","sourceAgent","targetAgent","conflictType","resolutionPath","summary"]),knowledge_receipt_transition:Object.freeze(["transition","reasonCode","schemaVersion","receiptSemantics","knowledgeTraceId","knowledgeEntryId","sessionId","taskId","phase","receiptOutcome","receiptSource"]),knowledge_maintenance:Object.freeze(["phase","abortReason","selectedCount","storeEntriesBefore","storeEntriesAfter","backupBytes","storeSha256Prefix","token12"]),residue_health:Object.freeze(["trigger","scanned","matched","eligible","ambiguous","quarantined","preserved","total_bytes","oldest_age_ms","grammar_counts"]),context_telemetry_health:Object.freeze(["trigger","accepted_count","compacted_count","retained_count","dropped_count","corrupt_count","oldest_timestamp","newest_timestamp","bytes","limit_bytes"]),skill_usage_health:Object.freeze(["trigger","accepted","compacted","dropped","skills_dropped","corrupt","pending_retained","uncertain_retained","uncertain_expired","pending_evicted","no_source_knowledge","no_matching_knowledge","bump_retry","bump_unrecoverable","bump_applied_zero","pressure","curator_skipped","bytes","limit_bytes","oldest_timestamp","newest_timestamp","coverage"])}),EMPTY_EXTRA=Object.freeze({});EMPTY_UNKNOWN=Object.freeze([]),_knownKeySetCache=new WeakMap;RESULT_STATUS_MAP=Object.freeze({success:"success",succeeded:"success",ok:"success",pass:"success",passed:"success",complete:"success",completed:"success",failure:"failure",failed:"failure",fail:"failure",error:"failure",partial:"partial"})});function validateEventRelationships(event){let violations=[];try{let entry=getCatalogEntry(event.kind),links=Array.isArray(event.trace?.links)?event.trace.links:[];if(entry===void 0)violations.push(`${RELATIONSHIP_VIOLATION_CODES.unknownKind}:${event.kind}`);else{let workflow=event.workflow??{};for(let id of entry.requiredWorkflowIds)if(workflow[id]===void 0)violations.push(`${RELATIONSHIP_VIOLATION_CODES.requiredWorkflowIdMissing}:${id}`);for(let id of entry.forbiddenWorkflowIds)if(workflow[id]!==void 0)violations.push(`${RELATIONSHIP_VIOLATION_CODES.forbiddenWorkflowIdPresent}:${id}`);let parentSpanId=event.trace?.parentSpanId;if(!entry.requiresParent&&parentSpanId!==void 0)violations.push(RELATIONSHIP_VIOLATION_CODES.parentSpanNotAllowed);if(entry.requiresParent&&parentSpanId===void 0)violations.push(RELATIONSHIP_VIOLATION_CODES.parentSpanMissing);if(parentSpanId!==void 0&&!SPAN_ID_PATTERN.test(String(parentSpanId)))violations.push(RELATIONSHIP_VIOLATION_CODES.malformedParentSpanId);if(!entry.allowsLinks&&links.length>0)violations.push(RELATIONSHIP_VIOLATION_CODES.linksNotAllowed)}for(let index=0;index<links.length;index++){let link=links[index];if(link===void 0||link===null)continue;if(!TRACE_ID_PATTERN.test(String(link.traceId)))violations.push(`${RELATIONSHIP_VIOLATION_CODES.malformedLinkTraceId}:${index}`);if(!SPAN_ID_PATTERN.test(String(link.spanId)))violations.push(`${RELATIONSHIP_VIOLATION_CODES.malformedLinkSpanId}:${index}`)}}catch{return{ok:!1,violations:[RELATIONSHIP_VIOLATION_CODES.validationFailed]}}return violations.length===0?{ok:!0}:{ok:!1,violations}}var TRACE_ID_PATTERN,SPAN_ID_PATTERN,RELATIONSHIP_VIOLATION_CODES;var init_relationships=__esm(()=>{init_catalog();TRACE_ID_PATTERN=/^[0-9a-f]{32}$/,SPAN_ID_PATTERN=/^[0-9a-f]{16}$/,RELATIONSHIP_VIOLATION_CODES=Object.freeze({unknownKind:"unknown_kind",requiredWorkflowIdMissing:"required_workflow_id_missing",forbiddenWorkflowIdPresent:"forbidden_workflow_id_present",parentSpanNotAllowed:"parent_span_not_allowed",parentSpanMissing:"parent_span_missing",malformedParentSpanId:"malformed_parent_span_id",linksNotAllowed:"links_not_allowed",malformedLinkTraceId:"malformed_link_trace_id",malformedLinkSpanId:"malformed_link_span_id",validationFailed:"relationship_validation_failed"})});function shouldSample(traceId,rate){if(typeof rate!=="number"||!Number.isFinite(rate))return!0;if(rate>=1)return!0;if(rate<=0)return!1;if(typeof traceId!=="string"||traceId.length<8)return!0;let suffix=traceId.slice(-8).toLowerCase();if(!SAMPLE_SUFFIX_PATTERN.test(suffix))return!0;let value=Number.parseInt(suffix,16);if(!Number.isFinite(value))return!0;return value/4294967295<rate}var DEFAULT_SAMPLE_RATE=1,SAMPLE_SUFFIX_PATTERN,METRIC_LABEL_ALLOWLIST,ALLOWED_LABELS,CARDINALITY_VIOLATION_CODES;var init_sampling=__esm(()=>{SAMPLE_SUFFIX_PATTERN=/^[0-9a-f]{8}$/;METRIC_LABEL_ALLOWLIST=Object.freeze(["kind","category","severity","outcome_status","cost_source","privacy_class","runtime","os","provider","sampled"]),ALLOWED_LABELS=new Set(METRIC_LABEL_ALLOWLIST),CARDINALITY_VIOLATION_CODES=Object.freeze({notAllowlisted:"label_not_allowlisted",highCardinalityShape:"high_cardinality_label_shape"})});function initObservability(input){try{let salt=resolveLineageSalt(),lineage={},directory=typeof input.directory==="string"&&input.directory.length>0?input.directory:void 0;if(directory!==void 0)lineage.projectRef=pseudonymousRef(directory,salt);if(typeof input.cohortLabel==="string"&&input.cohortLabel.length>0)lineage.cohortRef=pseudonymousRef(`${directory??""}\x00cohort\x00${input.cohortLabel}`,salt);if(typeof input.worktreeId==="string"&&input.worktreeId.length>0)lineage.worktreeRef=pseudonymousRef(`${directory??""}\x00worktree\x00${input.worktreeId}`,salt);if(_lineage=Object.freeze(lineage),_provenance=Object.freeze(input.provenance?{...input.provenance}:{}),typeof input.sampleRate==="number"&&Number.isFinite(input.sampleRate))_sampleRate=input.sampleRate}catch{}}function nextWriterSequence(){if(_writerSequence>=Number.MAX_SAFE_INTEGER)_writerSequence=0;return _writerSequence+=1,_writerSequence}function safeNowIso(){try{return new Date().toISOString()}catch{return FALLBACK_TIMESTAMP}}function buildFallbackObservation(kind,data,writerSequence){let now=safeNowIso();return{schemaVersion:OBSERVABILITY_SCHEMA_VERSION,eventId:FALLBACK_EVENT_ID,kind,category:"unrecognized",severity:"error",occurredAt:now,observedAt:now,writerSequence,trace:{traceId:FALLBACK_TRACE_ID,spanId:FALLBACK_SPAN_ID,links:[]},workflow:{},lineage:{},provenance:{},outcome:{},policy:{sampled:shouldSample(FALLBACK_TRACE_ID,_sampleRate),sampleRate:_sampleRate,privacyClass:"operational"},legacy:{sourceStore:LEGACY_TELEMETRY_SOURCE_STORE,sourceSchemaVersion:null,timingConfidence:"unknown",unknown:[],extra:{},raw:data},relationshipViolations:[OBSERVATION_BUILD_FAILED]}}function createObservation(kind,data){let writerSequence=nextWriterSequence();try{let entry=getCatalogEntry(kind),{traceId,spanId}=newTraceAndSpanId(),observedAt=new Date().toISOString(),knownKeys=Object.hasOwn(KNOWN_TELEMETRY_KEYS,kind)?KNOWN_TELEMETRY_KEYS[kind]:EMPTY_KNOWN_KEYS,event={schemaVersion:OBSERVABILITY_SCHEMA_VERSION,eventId:newEventId(),kind,category:entry?.category??"unrecognized",severity:entry?.severity??"warning",occurredAt:observedAt,observedAt,writerSequence,trace:{traceId,spanId,links:[]},workflow:extractWorkflowIds(data),lineage:_lineage,provenance:_provenance,outcome:extractOutcome(data),policy:{sampled:shouldSample(traceId,_sampleRate),sampleRate:_sampleRate,privacyClass:entry?.privacyClass??"operational"},legacy:adaptLegacyTelemetryPayload(kind,data,knownKeys),relationshipViolations:[]},validation=validateEventRelationships(event);if(!validation.ok)event.relationshipViolations=validation.violations;return event}catch{return buildFallbackObservation(kind,data,writerSequence)}}function toLegacyTelemetryLine(event){return{timestamp:event.observedAt,event:event.kind,...event.legacy.raw}}var _provenance,_lineage,_writerSequence=0,_sampleRate,EMPTY_KNOWN_KEYS,FALLBACK_EVENT_ID="00000000-0000-4000-8000-000000000000",FALLBACK_TRACE_ID="00000000000000000000000000000001",FALLBACK_SPAN_ID="0000000000000001",FALLBACK_TIMESTAMP="1970-01-01T00:00:00.000Z",OBSERVATION_BUILD_FAILED="observation_build_failed";var init_observe=__esm(()=>{init_catalog();init_envelope();init_ids();init_legacy();init_relationships();init_sampling();_provenance=Object.freeze({}),_lineage=Object.freeze({}),_sampleRate=DEFAULT_SAMPLE_RATE,EMPTY_KNOWN_KEYS=Object.freeze([])});var OTEL_GENAI_ATTRIBUTES,OPENINFERENCE_ATTRIBUTES,NO_ATTRIBUTES;var init_otel_mapping=__esm(()=>{OTEL_GENAI_ATTRIBUTES=Object.freeze({kind:"gen_ai.operation.name","provenance.provider":"gen_ai.system","provenance.model":"gen_ai.request.model","legacy.raw.model":"gen_ai.response.model","legacy.raw.agentName":"gen_ai.agent.name","workflow.hostSessionId":"gen_ai.conversation.id","outcome.status":"gen_ai.response.finish_reasons","legacy.raw.tokens_input":"gen_ai.usage.input_tokens","legacy.raw.tokens_output":"gen_ai.usage.output_tokens","legacy.raw.tokens_cache":"gen_ai.usage.cache_read_input_tokens","legacy.raw.tokens_reasoning":"swarm.gen_ai.usage.reasoning_tokens","legacy.raw.cost_usd":"swarm.gen_ai.usage.cost_usd"}),OPENINFERENCE_ATTRIBUTES=Object.freeze({kind:"openinference.span.kind","provenance.model":"llm.model_name","provenance.provider":"llm.provider","legacy.raw.agentName":"agent.name","workflow.hostSessionId":"session.id","legacy.raw.tokens_input":"llm.token_count.prompt","legacy.raw.tokens_output":"llm.token_count.completion","legacy.raw.tokens_cache":"llm.token_count.prompt_details.cache_read","legacy.raw.tokens_reasoning":"llm.token_count.completion_details.reasoning","legacy.raw.cost_usd":"swarm.llm.cost_usd"}),NO_ATTRIBUTES=Object.freeze({})});var init_observability=__esm(()=>{init_catalog();init_envelope();init_ids();init_legacy();init_observe();init_otel_mapping();init_relationships();init_sampling()});var exports_telemetry={};__export(exports_telemetry,{telemetry:()=>telemetry,stopHeartbeatTracking:()=>stopHeartbeatTracking,startHeartbeatTracking:()=>startHeartbeatTracking,rotateTelemetryIfNeeded:()=>rotateTelemetryIfNeeded,resetTelemetryForTesting:()=>resetTelemetryForTesting,resetHeartbeatTrackingForTesting:()=>resetHeartbeatTrackingForTesting,initTelemetry:()=>initTelemetry,getLastHeartbeat:()=>getLastHeartbeat,flushAndDrainTelemetry:()=>flushAndDrainTelemetry,emit:()=>emit,addTelemetryListener:()=>addTelemetryListener,_internals:()=>_internals8,ROTATION_CHECK_INTERVAL:()=>ROTATION_CHECK_INTERVAL});import*as fs6 from"node:fs";import{createWriteStream}from"node:fs";import*as os3 from"node:os";import*as path10 from"node:path";function capHeartbeatMap(){while(heartbeatTimestamps.size>=500){let oldestKey=heartbeatTimestamps.keys().next().value;if(oldestKey===void 0)break;heartbeatTimestamps.delete(oldestKey)}}function startHeartbeatTracking(){if(_heartbeatTrackingActive)return;_heartbeatTrackingActive=!0;let listener=(event,data)=>{if(event!=="heartbeat")return;let payload=data;if(!payload?.sessionId)return;heartbeatTimestamps.set(payload.sessionId,Date.now()),capHeartbeatMap()};_heartbeatListener=listener,addTelemetryListener(listener)}function getLastHeartbeat(sessionId){return heartbeatTimestamps.get(sessionId)}function stopHeartbeatTracking(){if(_heartbeatTrackingActive=!1,_heartbeatListener!==null){let idx=_listeners.indexOf(_heartbeatListener);if(idx>=0)_listeners.splice(idx,1);_heartbeatListener=null}}function resetHeartbeatTrackingForTesting(){if(_heartbeatTrackingActive=!1,heartbeatTimestamps.clear(),_heartbeatListener!==null){let idx=_listeners.indexOf(_heartbeatListener);if(idx>=0)_listeners.splice(idx,1);_heartbeatListener=null}}function resetTelemetryForTesting(){if(_disabled=!1,_projectDirectory=null,_listeners.length=0,_emitCount=0,resetHeartbeatTrackingForTesting(),_writeStream!==null)_writeStream.end(),_writeStream=null}function initTelemetry(projectDirectory){if(_writeStream!==null||_disabled)return;try{_projectDirectory=projectDirectory;let swarmDir=path10.join(projectDirectory,".swarm");if(!fs6.existsSync(swarmDir))fs6.mkdirSync(swarmDir,{recursive:!0});let telemetryPath=path10.join(swarmDir,"telemetry.jsonl"),stream=createWriteStream(telemetryPath,{flags:"a"});stream.on("error",()=>{if(_writeStream===stream)_disabled=!0,_writeStream=null}),_writeStream=stream}catch{_disabled=!0,_writeStream=null}}function emit(event,data){try{if(_disabled||_writeStream===null)return;let canonical=_internals8.createObservation(event,data),line=JSON.stringify(_internals8.toLegacyTelemetryLine(canonical))+os3.EOL,stream=_writeStream;stream.write(line,(err)=>{if(err&&_writeStream===stream)_disabled=!0,_writeStream=null});for(let listener of _listeners)try{listener(event,data)}catch{}if(_emitCount++,_emitCount>=ROTATION_CHECK_INTERVAL)_emitCount=0,_internals8.rotateTelemetryIfNeeded()}catch{}}function addTelemetryListener(callback){_listeners.push(callback)}function rotateTelemetryIfNeeded(maxBytes=10485760){try{if(_projectDirectory===null)return;let telemetryPath=path10.join(_projectDirectory,".swarm","telemetry.jsonl");if(!fs6.existsSync(telemetryPath))return;if(fs6.statSync(telemetryPath).size<maxBytes)return;let rotatedPath=path10.join(_projectDirectory,".swarm","telemetry.jsonl.1");if(fs6.renameSync(telemetryPath,rotatedPath),_writeStream!==null){_writeStream.end();let stream=createWriteStream(telemetryPath,{flags:"a"});stream.on("error",()=>{if(_writeStream===stream)_disabled=!0,_writeStream=null}),_writeStream=stream}}catch{}}async function flushAndDrainTelemetry(){let stream=_writeStream;if(stream===null||_projectDirectory===null)return;let next;try{let telemetryPath=path10.join(_projectDirectory,".swarm","telemetry.jsonl");next=createWriteStream(telemetryPath,{flags:"a"}),next.on("error",()=>{if(_writeStream===next)_disabled=!0,_writeStream=null}),_writeStream=next}catch{_disabled=!0,_writeStream=null;return}await new Promise((resolve5)=>{stream.end(()=>resolve5())})}var _writeStream=null,_projectDirectory=null,_listeners,_disabled=!1,_heartbeatTrackingActive=!1,_heartbeatListener=null,heartbeatTimestamps,_emitCount=0,ROTATION_CHECK_INTERVAL=50,telemetry,_internals8;var init_telemetry=__esm(()=>{init_observability();_listeners=[],heartbeatTimestamps=new Map;telemetry={sessionStarted(sessionId,agentName){_internals8.emit("session_started",{sessionId,agentName})},sessionEnded(sessionId,reason){_internals8.emit("session_ended",{sessionId,reason})},agentActivated(sessionId,agentName,oldName){_internals8.emit("agent_activated",{sessionId,agentName,oldName})},delegationBegin(sessionId,agentName,taskId){_internals8.emit("delegation_begin",{sessionId,agentName,taskId})},delegationEnd(sessionId,agentName,taskId,result,costFields){_internals8.emit("delegation_end",{sessionId,agentName,taskId,result,tokens_input:costFields?.tokens_input??0,tokens_output:costFields?.tokens_output??0,tokens_reasoning:costFields?.tokens_reasoning??0,tokens_cache:costFields?.tokens_cache??0,cost_usd:costFields?.cost_usd??null,cost_source:costFields?.cost_source??"unavailable",model:costFields?.model,gate:costFields?.gate,retry_index:costFields?.retry_index})},taskStateChanged(sessionId,taskId,newState,oldState){_internals8.emit("task_state_changed",{sessionId,taskId,newState,oldState})},gatePassed(sessionId,gate,taskId){_internals8.emit("gate_passed",{sessionId,gate,taskId})},gateParseError(taskId,error49){_internals8.emit("gate_parse_error",{taskId,errorName:error49.name,errorMessage:error49.message.slice(0,200)})},gateFailed(sessionId,gate,taskId,reason){_internals8.emit("gate_failed",{sessionId,gate,taskId,reason})},reviewerGateDecision(sessionId,taskId,blocked,reasonCode,evidenceKind){_internals8.emit("reviewer_gate_decision",{sessionId,gate:"qa_gate",taskId,blocked,allowed:!blocked,reasonCode,evidenceKind})},phaseChanged(sessionId,oldPhase,newPhase){_internals8.emit("phase_changed",{sessionId,oldPhase,newPhase})},budgetUpdated(sessionId,budgetPct,agentName){_internals8.emit("budget_updated",{sessionId,budgetPct,agentName})},contextPruned(data){_internals8.emit("context_pruned",data)},modelFallback(sessionId,agentName,fromModel,toModel,reason){_internals8.emit("model_fallback",{sessionId,agentName,fromModel,toModel,reason})},modelUnresolved(agentName,model,detail){_internals8.emit("model_unresolved",{sessionId:"preflight",agentName,model,detail})},hardLimitHit(sessionId,agentName,limitType,value){_internals8.emit("hard_limit_hit",{sessionId,agentName,limitType,value})},revisionLimitHit(sessionId,agentName){_internals8.emit("revision_limit_hit",{sessionId,agentName})},loopDetected(sessionId,agentName,loopType){_internals8.emit("loop_detected",{sessionId,agentName,loopType})},noOpStrongWarning(sessionId,agentName,count,threshold){_internals8.emit("no_op_strong_warning",{sessionId,agentName,count,threshold})},gateDenialLoop(sessionId,tool,code,count){_internals8.emit("gate_denial_loop",{sessionId,tool,code,count})},executionStallWarning(sessionId,count,threshold){_internals8.emit("execution_stall_warning",{sessionId,count,threshold})},executionStallDenied(sessionId,tool,count,threshold){_internals8.emit("execution_stall_denied",{sessionId,tool,count,threshold})},swarmInternalsReadDenied(sessionId,tool,target){_internals8.emit("swarm_internals_read_denied",{sessionId,tool,target})},scopeViolation(sessionId,agentName,file2,reason){_internals8.emit("scope_violation",{sessionId,agentName,file:file2,reason})},qaSkipViolation(sessionId,agentName,skipCount){_internals8.emit("qa_skip_violation",{sessionId,agentName,skipCount})},heartbeat(sessionId){_internals8.emit("heartbeat",{sessionId})},turboModeChanged(sessionId,enabled,agentName){_internals8.emit("turbo_mode_changed",{sessionId,enabled,agentName})},autoOversightEscalation(sessionId,reason,interactionCount,deadlockCount,phase){_internals8.emit("auto_oversight_escalation",{sessionId,reason,interactionCount,deadlockCount,phase})},environmentDetected(sessionId,hostOS,shellFamily,executionMode){_internals8.emit("environment_detected",{sessionId,hostOS,shellFamily,executionMode})},prmPatternDetected(sessionId,pattern,severity,category,stepRange){_internals8.emit("prm_pattern_detected",{sessionId,pattern,severity,category,stepRange})},prmCourseCorrectionInjected(sessionId,pattern,level){_internals8.emit("prm_course_correction_injected",{sessionId,pattern,level})},prmEscalationTriggered(sessionId,pattern,level,occurrenceCount){_internals8.emit("prm_escalation_triggered",{sessionId,pattern,level,occurrenceCount})},prmHardStop(sessionId,pattern,level,occurrenceCount){_internals8.emit("prm_hard_stop",{sessionId,pattern,level,occurrenceCount})},closeArchiveResult(data){_internals8.emit("close_archive_result",data)},residueHealth(data){_internals8.emit("residue_health",data)},contextTelemetryHealth(data){_internals8.emit("context_telemetry_health",data)},skillUsageHealth(data){_internals8.emit("skill_usage_health",data)},prmHardStopDelivered(sessionId,pattern,level,occurrenceCount){_internals8.emit("prm_hard_stop_delivered",{sessionId,pattern,level,occurrenceCount})}},_internals8={telemetry,emit,rotateTelemetryIfNeeded,flushAndDrainTelemetry,heartbeatListenerCount:()=>_heartbeatListener!==null?1:0,createObservation,toLegacyTelemetryLine}});import*as fs7 from"node:fs";import*as os4 from"node:os";import*as path11 from"node:path";function isAbsoluteDirectoryInput(value){return typeof value==="string"&&value.trim().length>0&&path11.isAbsolute(value)}function hasExplicitProjectBoundary(directory){if(!isAbsoluteDirectoryInput(directory))return!1;for(let marker of PROJECT_BOUNDARY_MARKERS)try{let stat5=_internals9.lstatSync(path11.join(directory,marker.name));if(!stat5.isSymbolicLink()&&marker.accepts(stat5))return!0}catch{}return!1}function isStrictPathDescendant(candidate,root){if(!isAbsoluteDirectoryInput(candidate)||!isAbsoluteDirectoryInput(root))return!1;let relative3=path11.relative(root,candidate);return relative3!==""&&relative3!==".."&&!relative3.startsWith(`..${path11.sep}`)&&!path11.isAbsolute(relative3)}function isMissingPathError(error49){let code=error49?.code;return code==="ENOENT"||code==="ENOTDIR"}function isWeakConfigContainerRoot(directory,dependencies){try{let resolved=dependencies.realpathSync(directory);return resolved===dependencies.realpathSync(os4.tmpdir())||resolved===dependencies.realpathSync(os4.homedir())}catch{let resolved=path11.resolve(directory);return resolved===path11.resolve(os4.tmpdir())||resolved===path11.resolve(os4.homedir())}}function projectIndicatorState(directory,dependencies,options={}){let allowConfigOnly=options.allowConfigOnly??!0;for(let indicator of PROJECT_ROOT_INDICATORS){if(!allowConfigOnly&&indicator===".opencode")continue;try{let indicatorStat=dependencies.statSync(path11.join(directory,indicator));if(indicatorStat.isFile()||indicatorStat.isDirectory())return"present"}catch(error49){if(!isMissingPathError(error49))return"inaccessible"}}return"absent"}function assertProjectRoot(directory,dependencies=fs7,artifactLabel="runtime state"){let resolved;try{resolved=dependencies.realpathSync(directory)}catch{throw warn(`[project-boundary] Cannot canonicalize directory "${directory}" — failing closed`),Error(`Cannot verify project root for "${directory}" — directory may not exist or is inaccessible`)}if(hasExplicitProjectBoundary(resolved))return;let current=resolved,depth=0;while(!0){if(depth>=MAX_PROJECT_ROOT_DEPTH)throw warn(`[project-boundary] Ancestor search exceeded ${MAX_PROJECT_ROOT_DEPTH} levels for "${resolved}" — failing closed`),Error(`Cannot verify project root for "${resolved}" — ancestor search exceeded ${MAX_PROJECT_ROOT_DEPTH} levels`);depth++;let parent=path11.dirname(current);if(parent===current)break;if(path11.dirname(parent)===parent){current=parent;continue}let parentSwarm=path11.join(parent,".swarm"),parentSwarmStat;try{parentSwarmStat=dependencies.statSync(parentSwarm)}catch(error49){if(isMissingPathError(error49)){current=parent;continue}throw warn(`[project-boundary] Cannot inspect ancestor state "${parentSwarm}" — failing closed`),Error(`Cannot verify project root for "${resolved}" — ancestor state "${parentSwarm}" is inaccessible`)}if(parentSwarmStat.isDirectory()){let indicatorState=projectIndicatorState(parent,dependencies,{allowConfigOnly:!isWeakConfigContainerRoot(parent,dependencies)});if(indicatorState==="inaccessible")throw warn(`[project-boundary] Cannot inspect project indicators in ancestor "${parent}" — failing closed`),Error(`Cannot verify project root for "${resolved}" — project indicators in ancestor "${parent}" are inaccessible`);if(indicatorState==="present")throw warn(`[project-boundary] Rejecting write to subdirectory "${resolved}" — parent "${parent}" already contains .swarm/`),Error(`Cannot write ${artifactLabel} in "${resolved}" — parent directory "${parent}" already contains a .swarm/ folder. Runtime state must be written to the project root.`)}current=parent}}var MAX_PROJECT_ROOT_DEPTH=20,PROJECT_ROOT_INDICATORS,PROJECT_BOUNDARY_MARKERS,_internals9;var init_project_boundary=__esm(()=>{init_logger();PROJECT_ROOT_INDICATORS=["package.json",".git",".opencode","Cargo.toml","go.mod","pyproject.toml","Gemfile","composer.json","pom.xml","build.gradle","CMakeLists.txt"],PROJECT_BOUNDARY_MARKERS=[{name:".git",accepts:(stat5)=>stat5.isFile()||stat5.isDirectory()},{name:".opencode",accepts:(stat5)=>stat5.isDirectory()}];_internals9={lstatSync:fs7.lstatSync}});function backoffMs(attempt){let base=Math.min(BACKOFF_START_MS*2**attempt,BACKOFF_MAX_MS),jitter=base*BACKOFF_JITTER_RATIO*(Math.random()*2-1);return Math.max(1,Math.round(base+jitter))}async function withEvidenceLock(directory,evidencePath,agent,taskId,fn2,timeoutMs=60000){assertProjectRoot(directory);let deadline=Date.now()+timeoutMs,attempt=0;while(!0){let result=await tryAcquireLock(directory,evidencePath,agent,taskId);if(result.acquired){let lock=result.lock;if(attempt>0)emit("evidence_lock_stale_recovered",{directory,evidencePath,agent,taskId,attempt});emit("evidence_lock_acquired",{directory,evidencePath,agent,taskId,attempt});try{return await fn2()}finally{if(lock._release)try{await lock._release()}catch{}}}if(Date.now()>=deadline)throw new EvidenceLockTimeoutError(directory,evidencePath,agent,taskId,timeoutMs);emit("evidence_lock_contended",{directory,evidencePath,agent,taskId,attempt});let delay=Math.min(backoffMs(attempt),deadline-Date.now());if(delay>0)await new Promise((resolve6)=>setTimeout(resolve6,delay));attempt++}}var EvidenceLockTimeoutError,BACKOFF_START_MS=50,BACKOFF_MAX_MS=2000,BACKOFF_JITTER_RATIO=0.25;var init_lock=__esm(()=>{init_file_locks();init_telemetry();init_project_boundary();EvidenceLockTimeoutError=class EvidenceLockTimeoutError extends Error{directory;evidencePath;agent;taskId;constructor(directory,evidencePath,agent,taskId,timeoutMs){super(`Evidence lock timeout after ${timeoutMs}ms for ${evidencePath} (agent=${agent}, task=${taskId})`);this.name="EvidenceLockTimeoutError",this.directory=directory,this.evidencePath=evidencePath,this.agent=agent,this.taskId=taskId}}});import*as fs8 from"node:fs";import*as path12 from"node:path";function sleepSync(ms){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,ms)}catch{let start=Date.now();while(Date.now()-start<ms);}}function healthArtifactPath(directory){return validateSwarmPath(directory,BACKGROUND_DELEGATIONS_HEALTH_FILE)}function readDelegationHealthArtifact(directory){let raw;try{raw=fs8.readFileSync(healthArtifactPath(directory),"utf-8")}catch{return null}try{let parsed=DelegationLedgerHealthSchema.safeParse(JSON.parse(raw));return parsed.success?parsed.data:null}catch{return null}}function writeDelegationHealthArtifact(directory,update){let base=readDelegationHealthArtifact(directory)??{schemaVersion:1,updatedAt:0,ledger:{bytes:0,limitBytes:MAX_RECOVERY_LEDGER_BYTES,pressurePct:0,band:"ok"},checkpoint:null,recovery:null,lastUncertainty:null,counts:{activeOwners:0,pendingAdvisories:0,lateTerminals:0,orphanWorktreeOwners:0},maintenance:null},next={schemaVersion:1,updatedAt:Date.now(),ledger:update.ledger??base.ledger,checkpoint:update.checkpoint===void 0?base.checkpoint:update.checkpoint,recovery:update.recovery===void 0?base.recovery:update.recovery,lastUncertainty:update.lastUncertainty??base.lastUncertainty,counts:update.counts??base.counts,maintenance:update.maintenance===void 0?base.maintenance??null:update.maintenance};if(update.uncertainty)next.lastUncertainty=update.uncertainty;let parsed=DelegationLedgerHealthSchema.safeParse(next);if(!parsed.success)return null;try{fs8.mkdirSync(path12.resolve(directory,".swarm"),{recursive:!0});let target=healthArtifactPath(directory),tmp=`${target}.tmp-${process.pid}-${Math.random().toString(36).slice(2,10)}`;fs8.writeFileSync(tmp,`${JSON.stringify(parsed.data)}
184
+ `,"utf-8");let lastError;for(let attempt=0;attempt<5;attempt++)try{_healthInternals.renameOnce(tmp,target),lastError=void 0;break}catch(err){lastError=err;let code=err.code;if(code!=="EEXIST"&&code!=="EBUSY"&&code!=="EPERM")break;if(attempt<4)sleepSync(15)}if(lastError!==void 0){try{fs8.rmSync(tmp,{force:!0})}catch{}return null}return parsed.data}catch{return null}}function recordDelegationRecoveryObservation(directory,observation){try{writeDelegationHealthArtifact(directory,{recovery:{source:observation.source,at:Date.now(),ok:observation.ok,...observation.reason?{reason:observation.reason}:{},...observation.repairHint?{repairHint:observation.repairHint}:{}},...observation.ok?{}:{uncertainty:{reason:observation.reason??"recovery failed",at:Date.now(),source:"recovery",...observation.repairHint?{repairHint:observation.repairHint}:{}}}})}catch{}}function appendDelegationMaintenanceObservation(directory,observation){try{let current=readDelegationHealthArtifact(directory)?.maintenance??null,section={lastRunAt:observation.at,lastOkAt:observation.status==="ok"?observation.at:current?.lastOkAt??null,lastFailure:observation.status==="failure"&&observation.reason?{reason:observation.reason,at:observation.at}:current?.lastFailure??null,lastContentionAt:observation.status==="contention"?observation.at:current?.lastContentionAt??null,lastSummary:observation.summary??current?.lastSummary??{sweptStale:0,released:0,renewed:0,retained:0},facts:[...current?.facts??[],...observation.facts].slice(-MAX_MAINTENANCE_FACTS)};writeDelegationHealthArtifact(directory,{maintenance:section})}catch{}}function collectDelegationLedgerHealth(directory,options){let artifact=readDelegationHealthArtifact(directory),ledgerBytes=0,ledgerExists=!1;try{ledgerBytes=fs8.statSync(validateSwarmPath(directory,"background-delegations.jsonl")).size,ledgerExists=!0}catch{ledgerExists=!1}if(!artifact&&!ledgerExists)return null;let limitBytes=options.ledgerLimitBytes,pressurePct=Math.min(100,Math.round(ledgerBytes/limitBytes*1000)/10),band=ledgerBytes>limitBytes?"fail-closed":ledgerBytes>options.highWaterBytes?"compact-overdue":ledgerBytes>options.lowWaterBytes?"nominal":"ok";return{schemaVersion:1,updatedAt:artifact?.updatedAt??0,ledger:{bytes:ledgerBytes,limitBytes,pressurePct,band},checkpoint:artifact?.checkpoint??null,recovery:artifact?.recovery??null,lastUncertainty:artifact?.lastUncertainty??null,counts:artifact?.counts??{activeOwners:0,pendingAdvisories:0,lateTerminals:0,orphanWorktreeOwners:0},maintenance:artifact?.maintenance??null}}var BACKGROUND_DELEGATIONS_HEALTH_FILE="background-delegations-health.json",MAX_RECOVERY_LEDGER_BYTES=4194304,DelegationCheckpointAuditSchema,CheckpointSectionSchema,RecoverySectionSchema,UncertaintySectionSchema,MAX_MAINTENANCE_FACTS=20,DelegationMaintenanceFactSchema,MaintenanceSectionSchema,DelegationLedgerHealthSchema,_healthInternals;var init_delegation_health=__esm(()=>{init_zod();init_utils2();DelegationCheckpointAuditSchema=exports_external.object({dispatchCount:exports_external.number().int().nonnegative(),terminalsByStatus:exports_external.object({completed:exports_external.number().int().nonnegative(),error:exports_external.number().int().nonnegative(),cancelled:exports_external.number().int().nonnegative(),stale:exports_external.number().int().nonnegative()}).strict(),settledCount:exports_external.number().int().nonnegative(),preservedCount:exports_external.number().int().nonnegative(),lateTerminalCount:exports_external.number().int().nonnegative(),compactedTransitionCount:exports_external.number().int().nonnegative(),compactedRecordCount:exports_external.number().int().nonnegative(),firstDispatchAt:exports_external.number().int().nonnegative().nullable(),lastTerminalAt:exports_external.number().int().nonnegative().nullable(),lastCompactionAt:exports_external.number().int().nonnegative()}).strict(),CheckpointSectionSchema=exports_external.object({sequence:exports_external.number().int().positive(),createdAt:exports_external.number().int().nonnegative(),liveRecords:exports_external.number().int().nonnegative(),closedSummaries:exports_external.number().int().nonnegative(),bytes:exports_external.number().int().nonnegative(),audit:DelegationCheckpointAuditSchema}).strict(),RecoverySectionSchema=exports_external.object({source:exports_external.enum(["checkpoint+tail","checkpoint+ledger-suffix","legacy-ledger","unknown"]),at:exports_external.number().int().nonnegative(),ok:exports_external.boolean(),reason:exports_external.string().min(1).max(2000).optional(),repairHint:exports_external.string().min(1).max(2000).optional()}).strict(),UncertaintySectionSchema=exports_external.object({reason:exports_external.string().min(1).max(2000),at:exports_external.number().int().nonnegative(),source:exports_external.string().min(1).max(256),repairHint:exports_external.string().min(1).max(2000).optional()}).strict(),DelegationMaintenanceFactSchema=exports_external.object({at:exports_external.number().int().nonnegative(),kind:exports_external.enum(["release","retained-ambiguity","retained-protected-legacy","lease-renewed","maintenance-failure","lock-contention"]),reservationId:exports_external.string().min(1).max(256).optional(),correlationId:exports_external.string().min(1).max(256).optional(),generation:exports_external.number().int().positive().optional(),reason:exports_external.string().min(1).max(2000)}).strict(),MaintenanceSectionSchema=exports_external.object({lastRunAt:exports_external.number().int().nonnegative(),lastOkAt:exports_external.number().int().nonnegative().nullable(),lastFailure:exports_external.object({reason:exports_external.string().min(1).max(2000),at:exports_external.number().int().nonnegative()}).strict().nullable(),lastContentionAt:exports_external.number().int().nonnegative().nullable(),lastSummary:exports_external.object({sweptStale:exports_external.number().int().nonnegative(),released:exports_external.number().int().nonnegative(),renewed:exports_external.number().int().nonnegative(),retained:exports_external.number().int().nonnegative()}).strict(),facts:exports_external.array(DelegationMaintenanceFactSchema).max(MAX_MAINTENANCE_FACTS)}).strict(),DelegationLedgerHealthSchema=exports_external.object({schemaVersion:exports_external.literal(1),updatedAt:exports_external.number().int().nonnegative(),ledger:exports_external.object({bytes:exports_external.number().int().nonnegative(),limitBytes:exports_external.number().int().positive(),pressurePct:exports_external.number().min(0).max(100),band:exports_external.enum(["ok","nominal","compact-overdue","fail-closed"])}).strict(),checkpoint:CheckpointSectionSchema.nullable(),recovery:RecoverySectionSchema.nullable(),lastUncertainty:UncertaintySectionSchema.nullable(),counts:exports_external.object({activeOwners:exports_external.number().int().nonnegative(),pendingAdvisories:exports_external.number().int().nonnegative(),lateTerminals:exports_external.number().int().nonnegative(),orphanWorktreeOwners:exports_external.number().int().nonnegative()}).strict(),maintenance:MaintenanceSectionSchema.nullable().optional()}).strict();_healthInternals={renameOnce:(from,to)=>{fs8.renameSync(from,to)}}});import{createHash as createHash5}from"node:crypto";function resolveLaneAtomicDisposition(receipt){if(new Set(receipt.assignedReviewItemIds).size!==receipt.assignedReviewItemIds.length)return null;let acceptedAll=receipt.rejectedReviewItemIds.length===0&&receipt.acceptedReviewItemIds.length===receipt.assignedReviewItemIds.length&&receipt.acceptedReviewItemIds.every((itemId,index)=>itemId===receipt.assignedReviewItemIds[index]),rejectedAll=receipt.acceptedReviewItemIds.length===0&&receipt.rejectedReviewItemIds.length===receipt.assignedReviewItemIds.length&&receipt.rejectedReviewItemIds.every((itemId,index)=>itemId===receipt.assignedReviewItemIds[index]);return acceptedAll?"accepted":rejectedAll?"rejected":null}function encodePrReviewCollectionReceiptFooter(binding,result,receipt){let payload=buildPrReviewCollectionReceiptPayload(binding,result,receipt);if(!payload)return null;let footer=`${PR_REVIEW_COLLECTION_RECEIPT_PREFIX}${JSON.stringify(payload)}`;return footer.length<=MAX_PR_REVIEW_COLLECTION_RECEIPT_CHARS?footer:null}function buildPrReviewCollectionReceiptPayload(binding,result,receipt){let disposition=resolveLaneAtomicDisposition(receipt);if(!disposition)return null;let parsed=PrReviewCollectionReceiptPayloadSchema.safeParse({schemaVersion:1,parentSessionId:binding.parentSessionId,batchId:binding.batchId??binding.callID,laneId:binding.laneId??binding.correlationId,mode:binding.mode,workflowLane:binding.workflowLane,outputDigest:result.digest,disposition,reviewItemIds:receipt.assignedReviewItemIds});if(!parsed.success)return null;return parsed.data}function projectPrReviewCollectionReceipt(payload){let assignedReviewItemIds=[...payload.reviewItemIds];return{assignedReviewItemIds,acceptedReviewItemIds:payload.disposition==="accepted"?[...assignedReviewItemIds]:[],rejectedReviewItemIds:payload.disposition==="rejected"?[...assignedReviewItemIds]:[]}}function reviewItemDigest(reviewItemIds){return createHash5("sha256").update(JSON.stringify(reviewItemIds)).digest("hex")}function encodePrReviewCollectionReceiptShedMarker(payload){let marker={schemaVersion:1,parentSessionId:payload.parentSessionId,batchId:payload.batchId,laneId:payload.laneId,mode:payload.mode,workflowLane:payload.workflowLane,outputDigest:payload.outputDigest,disposition:payload.disposition,reviewItemCount:payload.reviewItemIds.length,reviewItemDigest:reviewItemDigest(payload.reviewItemIds)};return`${PR_REVIEW_COLLECTION_RECEIPT_SHED_PREFIX}${JSON.stringify(marker)}`}function encodePrReviewCollectionReceiptShedMarkerFromReceipt(binding,result,receipt){let payload=buildPrReviewCollectionReceiptPayload(binding,result,receipt);return payload?encodePrReviewCollectionReceiptShedMarker(payload):null}function parsePrReviewCollectionReceiptShedMarker(binding,result){if(!result.text)return null;let lines=result.text.split(/\r?\n/),markerLines=lines.filter((line)=>line.startsWith(PR_REVIEW_COLLECTION_RECEIPT_SHED_PREFIX)),finalLine=lines.at(-1);if(markerLines.length!==1||!finalLine?.startsWith(PR_REVIEW_COLLECTION_RECEIPT_SHED_PREFIX)||finalLine.length>MAX_PR_REVIEW_COLLECTION_RECEIPT_CHARS)return null;let decoded;try{decoded=JSON.parse(finalLine.slice(PR_REVIEW_COLLECTION_RECEIPT_SHED_PREFIX.length))}catch{return null}let parsed=PrReviewCollectionReceiptShedMarkerSchema.safeParse(decoded);if(!parsed.success)return null;let marker=parsed.data;return marker.parentSessionId===binding.parentSessionId&&marker.batchId===(binding.batchId??binding.callID)&&marker.laneId===(binding.laneId??binding.correlationId)&&marker.mode===binding.mode&&marker.workflowLane===binding.workflowLane&&marker.outputDigest===result.digest?marker:null}function projectPrReviewCollectionReceiptShedMarker(marker,reviewItemIds){if(marker.reviewItemCount!==reviewItemIds.length||marker.reviewItemDigest!==reviewItemDigest(reviewItemIds))return null;let assignedReviewItemIds=[...reviewItemIds];return{assignedReviewItemIds,acceptedReviewItemIds:marker.disposition==="accepted"?[...assignedReviewItemIds]:[],rejectedReviewItemIds:marker.disposition==="rejected"?[...assignedReviewItemIds]:[]}}function parsePrReviewCollectionReceiptFooter(binding,result){if(!result.text)return null;let lines=result.text.split(/\r?\n/),receiptLines=lines.filter((line)=>line.startsWith(PR_REVIEW_COLLECTION_RECEIPT_PREFIX)),finalLine=lines.at(-1);if(receiptLines.length!==1||!finalLine?.startsWith(PR_REVIEW_COLLECTION_RECEIPT_PREFIX)||finalLine.length>MAX_PR_REVIEW_COLLECTION_RECEIPT_CHARS)return null;let decoded;try{decoded=JSON.parse(finalLine.slice(PR_REVIEW_COLLECTION_RECEIPT_PREFIX.length))}catch{return null}let parsed=PrReviewCollectionReceiptPayloadSchema.safeParse(decoded);if(!parsed.success)return null;let payload=parsed.data;return payload.parentSessionId===binding.parentSessionId&&payload.batchId===(binding.batchId??binding.callID)&&payload.laneId===(binding.laneId??binding.correlationId)&&payload.mode===binding.mode&&payload.workflowLane===binding.workflowLane&&payload.outputDigest===result.digest?payload:null}var PR_REVIEW_COLLECTION_RECEIPT_PREFIX="[PR_REVIEW_COLLECTION_RECEIPT_V1] ",PR_REVIEW_COLLECTION_RECEIPT_SHED_PREFIX="[PR_REVIEW_COLLECTION_RECEIPT_SHED_V1] ",MAX_PR_REVIEW_COLLECTION_RECEIPT_CHARS=65536,MAX_PR_REVIEW_COLLECTION_RECEIPT_ITEM_IDS=1e4,PrReviewCollectionReceiptPayloadSchema,PrReviewCollectionReceiptShedMarkerSchema;var init_pr_review_collection_receipt=__esm(()=>{init_zod();PrReviewCollectionReceiptPayloadSchema=exports_external.object({schemaVersion:exports_external.literal(1),parentSessionId:exports_external.string().min(1).max(256),batchId:exports_external.string().min(1).max(120),laneId:exports_external.string().min(1).max(120),mode:exports_external.enum(["swarm-pr-review:reviewer","swarm-pr-review:critic"]),workflowLane:exports_external.string().min(1).max(120),outputDigest:exports_external.string().regex(/^[a-f0-9]{64}$/),disposition:exports_external.enum(["accepted","rejected"]),reviewItemIds:exports_external.array(exports_external.string().min(1).max(160)).min(1).max(MAX_PR_REVIEW_COLLECTION_RECEIPT_ITEM_IDS)}).strict().superRefine((payload,context)=>{if(new Set(payload.reviewItemIds).size!==payload.reviewItemIds.length)context.addIssue({code:exports_external.ZodIssueCode.custom,message:"review item IDs must be unique"})}),PrReviewCollectionReceiptShedMarkerSchema=exports_external.object({schemaVersion:exports_external.literal(1),parentSessionId:exports_external.string().min(1).max(256),batchId:exports_external.string().min(1).max(120),laneId:exports_external.string().min(1).max(120),mode:exports_external.enum(["swarm-pr-review:reviewer","swarm-pr-review:critic"]),workflowLane:exports_external.string().min(1).max(120),outputDigest:exports_external.string().regex(/^[a-f0-9]{64}$/),disposition:exports_external.enum(["accepted","rejected"]),reviewItemCount:exports_external.number().int().positive().max(MAX_PR_REVIEW_COLLECTION_RECEIPT_ITEM_IDS),reviewItemDigest:exports_external.string().regex(/^[a-f0-9]{64}$/)}).strict()});var exports_pending_delegations={};__export(exports_pending_delegations,{writeDelegationFallback:()=>writeDelegationFallback,updateCoderSettlement:()=>updateCoderSettlement,sweepStaleDelegations:()=>sweepStaleDelegations,scanDelegationsForRecovery:()=>scanDelegationsForRecovery,scanDelegationFallbacksForRecovery:()=>scanDelegationFallbacksForRecovery,scanBackgroundCoderReservationsForAdmission:()=>scanBackgroundCoderReservationsForAdmission,reserveBackgroundCoderSlot:()=>reserveBackgroundCoderSlot,removeDelegationFallback:()=>removeDelegationFallback,releasePreparedBackgroundAdvisories:()=>releasePreparedBackgroundAdvisories,releaseBackgroundCoderReservation:()=>releaseBackgroundCoderReservation,recordPendingDelegationDetailed:()=>recordPendingDelegationDetailed,recordPendingDelegation:()=>recordPendingDelegation,recordDelegationIngestionResult:()=>recordDelegationIngestionResult,readDelegations:()=>readDelegations,readDelegationFallback:()=>readDelegationFallback,putPendingBackgroundAdvisory:()=>putPendingBackgroundAdvisory,promoteDelegationFallback:()=>promoteDelegationFallback,preparePendingBackgroundAdvisories:()=>preparePendingBackgroundAdvisories,normalizeBackgroundObservedFiles:()=>normalizeBackgroundObservedFiles,maintainBackgroundDelegations:()=>maintainBackgroundDelegations,listDelegationFallbacks:()=>listDelegationFallbacks,isUnsettledWorktreeOwner:()=>isUnsettledWorktreeOwner,findOpenAsyncLaneBatches:()=>findOpenAsyncLaneBatches,findDelegationForCompletion:()=>findDelegationForCompletion,findByCorrelationId:()=>findByCorrelationId,findByBatchId:()=>findByBatchId,compactBackgroundDelegations:()=>compactBackgroundDelegations,claimTerminalResult:()=>claimTerminalResult,claimDelegationIngestion:()=>claimDelegationIngestion,claimCoderSettlement:()=>claimCoderSettlement,buildPromptSnapshot:()=>buildPromptSnapshot,buildBackgroundCompletionEventId:()=>buildBackgroundCompletionEventId,buildBackgroundCoderReservationId:()=>buildBackgroundCoderReservationId,bindBackgroundCoderReservation:()=>bindBackgroundCoderReservation,appendDelegationTransition:()=>appendDelegationTransition,acknowledgeObservedBackgroundAdvisories:()=>acknowledgeObservedBackgroundAdvisories,_checkpointInternals:()=>_checkpointInternals,TOMBSTONE_MIN_AGE_MS:()=>TOMBSTONE_MIN_AGE_MS,MAX_RECOVERY_LEDGER_BYTES:()=>MAX_RECOVERY_LEDGER_BYTES,MAX_LIVE_BACKGROUND_FALLBACKS:()=>MAX_LIVE_BACKGROUND_FALLBACKS,MAX_LIVE_BACKGROUND_CODER_RESERVATIONS:()=>MAX_LIVE_BACKGROUND_CODER_RESERVATIONS,MAX_CHECKPOINT_RECORDS:()=>MAX_CHECKPOINT_RECORDS,MAX_CHECKPOINT_BYTES:()=>MAX_CHECKPOINT_BYTES,MAX_BACKGROUND_OBSERVED_FILES:()=>MAX_BACKGROUND_OBSERVED_FILES,MAX_BACKGROUND_ADVISORY_CHARS:()=>MAX_BACKGROUND_ADVISORY_CHARS,DELEGATION_COMPACTION_LOW_WATER_BYTES:()=>DELEGATION_COMPACTION_LOW_WATER_BYTES,DELEGATION_COMPACTION_HIGH_WATER_BYTES:()=>DELEGATION_COMPACTION_HIGH_WATER_BYTES,DEFAULT_SWEEPABLE_DELEGATION_STATUSES:()=>DEFAULT_SWEEPABLE_DELEGATION_STATUSES,DEFAULT_STALE_DELEGATION_TIMEOUT_MS:()=>DEFAULT_STALE_DELEGATION_TIMEOUT_MS,BACKGROUND_INGESTION_LEASE_MS:()=>BACKGROUND_INGESTION_LEASE_MS,BACKGROUND_DELEGATION_FALLBACK_DIR:()=>BACKGROUND_DELEGATION_FALLBACK_DIR,BACKGROUND_DELEGATIONS_MANIFEST_FILE:()=>BACKGROUND_DELEGATIONS_MANIFEST_FILE,BACKGROUND_DELEGATIONS_FILE:()=>BACKGROUND_DELEGATIONS_FILE,BACKGROUND_DELEGATIONS_CHECKPOINT_FILE:()=>BACKGROUND_DELEGATIONS_CHECKPOINT_FILE,BACKGROUND_CODER_RESERVATION_LEASE_MS:()=>BACKGROUND_CODER_RESERVATION_LEASE_MS,BACKGROUND_CODER_RESERVATION_LEASE_MIN_MS:()=>BACKGROUND_CODER_RESERVATION_LEASE_MIN_MS,BACKGROUND_CODER_RESERVATION_LEASE_MAX_MS:()=>BACKGROUND_CODER_RESERVATION_LEASE_MAX_MS,BACKGROUND_CODER_RESERVATIONS_FILE:()=>BACKGROUND_CODER_RESERVATIONS_FILE});import{createHash as createHash6}from"node:crypto";import*as fs9 from"node:fs";import*as path13 from"node:path";import{isDeepStrictEqual}from"node:util";function clampReservationLeaseMs(leaseMs){if(leaseMs===void 0)return BACKGROUND_CODER_RESERVATION_LEASE_MS;if(!Number.isFinite(leaseMs))return BACKGROUND_CODER_RESERVATION_LEASE_MS;return Math.min(Math.max(Math.round(leaseMs),BACKGROUND_CODER_RESERVATION_LEASE_MIN_MS),BACKGROUND_CODER_RESERVATION_LEASE_MAX_MS)}function isValidReservationGeneration(generation){return generation===void 0||Number.isInteger(generation)&&generation>=1&&generation<=MAX_BACKGROUND_DELEGATION_GENERATION}function storePath(directory){return validateSwarmPath(directory,BACKGROUND_DELEGATIONS_FILE)}function checkpointPath(directory){return validateSwarmPath(directory,BACKGROUND_DELEGATIONS_CHECKPOINT_FILE)}function manifestPath(directory){return validateSwarmPath(directory,BACKGROUND_DELEGATIONS_MANIFEST_FILE)}function writeDurableFileSync(target,contents){let tmp=`${target}.tmp-${process.pid}-${Math.random().toString(36).slice(2,10)}`;try{let fd=fs9.openSync(tmp,"w");try{if(typeof contents==="string")fs9.writeSync(fd,contents);else fs9.writeSync(fd,contents,0,contents.length);fs9.fsyncSync(fd)}finally{fs9.closeSync(fd)}_checkpointInternals.renameWithRetry(tmp,target)}catch(err){try{fs9.rmSync(tmp,{force:!0})}catch{}throw err}try{let dfd=fs9.openSync(path13.dirname(target),"r");try{fs9.fsyncSync(dfd)}finally{fs9.closeSync(dfd)}}catch{}}function readJsonFileWithRetry(target){let raw;try{raw=fs9.readFileSync(target,"utf-8")}catch(err){let code=err.code;if(code==="ENOENT")return{status:"absent"};return{status:"invalid",reason:`unreadable (${code??"unknown error"})`}}try{return{status:"ok",value:JSON.parse(raw)}}catch(err){return{status:"invalid",reason:`malformed JSON (${err instanceof Error?err.message:String(err)})`}}}function readDelegationManifest(directory){let read=readJsonFileWithRetry(manifestPath(directory));if(read.status==="absent")return{kind:"absent"};if(read.status==="invalid")return{kind:"invalid",reason:read.reason};let parsed=ManifestSchema.safeParse(read.value);if(!parsed.success)return{kind:"invalid",reason:"manifest fails schema validation"};return{kind:"ok",manifest:parsed.data}}function readDelegationCheckpoint(directory){let bytes=0;try{bytes=fs9.statSync(checkpointPath(directory)).size}catch{}if(bytes>MAX_CHECKPOINT_BYTES)return{kind:"invalid",reason:`checkpoint exceeds the ${MAX_CHECKPOINT_BYTES}-byte bound`};let read=readJsonFileWithRetry(checkpointPath(directory));if(read.status==="absent")return{kind:"absent"};if(read.status==="invalid")return{kind:"invalid",reason:read.reason};let parsed=CheckpointSchema.safeParse(read.value);if(!parsed.success)return{kind:"invalid",reason:"checkpoint fails schema validation"};return{kind:"ok",checkpoint:parsed.data,bytes}}function sha256Hex(data){return createHash6("sha256").update(data).digest("hex")}function checkpointPayloadChecksum(checkpoint){return sha256Hex(JSON.stringify([checkpoint.schemaVersion,checkpoint.sequence,checkpoint.writerId,checkpoint.rootPath,checkpoint.createdAt,checkpoint.cutLedgerBytes,checkpoint.cutLedgerDigest,checkpoint.records,checkpoint.closed,checkpoint.audit]))}function loadFoldedState(directory,options){let manifestRead=readDelegationManifest(directory);if(manifestRead.kind==="invalid")return{status:"uncertain",reason:`background delegation manifest is invalid: ${manifestRead.reason}`,repairHint:CHECKPOINT_RESET_HINT};if(manifestRead.kind==="absent")return loadLegacyLedger(directory,options.strict);let manifest=manifestRead.manifest;if(manifest.rootPath!==path13.resolve(directory))return{status:"uncertain",reason:"background delegation checkpoint is bound to a different project root",repairHint:CHECKPOINT_REBIND_HINT};let checkpointRead=readDelegationCheckpoint(directory);if(checkpointRead.kind==="invalid"||checkpointRead.kind==="absent")return{status:"uncertain",reason:`background delegation checkpoint is invalid${checkpointRead.kind==="invalid"?`: ${checkpointRead.reason}`:" (file missing)"} while a manifest is published`,repairHint:CHECKPOINT_RESET_HINT};let checkpoint=checkpointRead.checkpoint;if(checkpoint.sequence!==manifest.sequence&&checkpoint.sequence!==manifest.sequence+1)return{status:"uncertain",reason:`background delegation checkpoint/manifest sequence mismatch (checkpoint ${checkpoint.sequence}, manifest ${manifest.sequence})`,repairHint:CHECKPOINT_RESET_HINT};if(checkpoint.sequence===manifest.sequence&&manifest.checkpointChecksum!==checkpoint.payloadChecksum)return{status:"uncertain",reason:"background delegation manifest checksum does not match its checkpoint",repairHint:CHECKPOINT_RESET_HINT};if(checkpointPayloadChecksum(checkpoint)!==checkpoint.payloadChecksum)return{status:"uncertain",reason:"background delegation checkpoint payload checksum mismatch",repairHint:CHECKPOINT_RESET_HINT};let stat5;try{stat5=fs9.statSync(storePath(directory))}catch(error49){return{status:"uncertain",reason:`background delegation ledger metadata is unreadable: ${error49 instanceof Error?error49.message:String(error49)}`}}let tail,mode;if(stat5.size>=checkpoint.cutLedgerBytes&&checkpoint.cutLedgerBytes>0){let prefix=readLedgerRegion(directory,0,checkpoint.cutLedgerBytes);if(sha256Hex(prefix)===checkpoint.cutLedgerDigest){let suffixBytes=stat5.size-checkpoint.cutLedgerBytes;if(suffixBytes>MAX_RECOVERY_LEDGER_BYTES)return{status:"uncertain",reason:`background delegation ledger changed beyond the ${MAX_RECOVERY_LEDGER_BYTES}-byte recovery bound`};tail=suffixBytes===0?Buffer.alloc(0):readLedgerRegion(directory,checkpoint.cutLedgerBytes,suffixBytes),mode="checkpoint+ledger-suffix"}else tail=readBoundedRecentLedgerWindow(directory,stat5.size),mode="checkpoint+tail"}else tail=readBoundedRecentLedgerWindow(directory,stat5.size),mode="checkpoint+tail";let records=new Map;for(let record2 of checkpoint.records)records.set(record2.correlationId,record2);for(let summary of checkpoint.closed)records.set(summary.correlationId,summary);let foldError=foldLedgerTail(records,tail,options.strict,checkpoint);if(foldError)return{status:"uncertain",reason:foldError};return{status:"ok",mode,records,manifest,checkpoint}}function readLedgerRegion(directory,offset,length){let fd=fs9.openSync(storePath(directory),"r");try{let buffer=Buffer.alloc(length),read=0;while(read<length){let n=fs9.readSync(fd,buffer,read,length-read,offset+read);if(n<=0)break;read+=n}return read===length?buffer:buffer.subarray(0,read)}finally{fs9.closeSync(fd)}}function readBoundedRecentLedgerWindow(directory,size){if(size===0)return Buffer.alloc(0);if(size<=MAX_RECOVERY_LEDGER_BYTES)return readLedgerRegion(directory,0,size);let window2=readLedgerRegion(directory,size-MAX_RECOVERY_LEDGER_BYTES,MAX_RECOVERY_LEDGER_BYTES),firstNewline=window2.indexOf(10);return firstNewline===-1?Buffer.alloc(0):window2.subarray(firstNewline+1)}function foldLedgerTail(records,tail,strict,checkpoint){let lineNumber=0;for(let line of tail.toString("utf-8").split(`
185
185
  `)){lineNumber+=1;let trimmed=line.trim();if(!trimmed)continue;let parsedJson;try{parsedJson=JSON.parse(trimmed)}catch{if(strict)return`background delegation ledger has malformed JSON at line ${lineNumber}`;continue}let parsed=RecordSchema.safeParse(parsedJson);if(!parsed.success){if(strict)return`background delegation ledger has an invalid record at line ${lineNumber}`;continue}let existing=checkpoint?records.get(parsed.data.correlationId):void 0;if(checkpoint&&existing&&!(parsed.data.updatedAt>existing.updatedAt)&&!(parsed.data.updatedAt===existing.updatedAt&&parsed.data.updatedAt>checkpoint.createdAt))continue;records.set(parsed.data.correlationId,parsed.data)}return null}function loadLegacyLedger(directory,strict){if(!strict){let raw2;try{raw2=fs9.readFileSync(storePath(directory),"utf-8")}catch(err){if(err.code!=="ENOENT")warn(`[background] readDelegations failed: ${err instanceof Error?err.message:String(err)}`);return{status:"ok",mode:"legacy",records:new Map,manifest:null,checkpoint:null}}let records2=new Map,foldError2=foldLedgerTail(records2,Buffer.from(raw2,"utf-8"),!1);return{status:"ok",mode:"legacy",records:records2,manifest:null,checkpoint:null}}let absolutePath;try{if(absolutePath=storePath(directory),fs9.statSync(absolutePath).size>MAX_RECOVERY_LEDGER_BYTES)return{status:"uncertain",reason:`background delegation ledger exceeds the ${MAX_RECOVERY_LEDGER_BYTES}-byte recovery bound`}}catch(error49){if(error49.code==="ENOENT")return{status:"ok",mode:"legacy",records:new Map,manifest:null,checkpoint:null};return{status:"uncertain",reason:`background delegation ledger metadata is unreadable: ${error49 instanceof Error?error49.message:String(error49)}`}}let raw;try{raw=fs9.readFileSync(absolutePath,"utf-8")}catch(error49){return{status:"uncertain",reason:`background delegation ledger is unreadable: ${error49 instanceof Error?error49.message:String(error49)}`}}if(Buffer.byteLength(raw,"utf8")>MAX_RECOVERY_LEDGER_BYTES)return{status:"uncertain",reason:`background delegation ledger changed beyond the ${MAX_RECOVERY_LEDGER_BYTES}-byte recovery bound`};let records=new Map,foldError=foldLedgerTail(records,Buffer.from(raw,"utf-8"),!0);if(foldError)return{status:"uncertain",reason:foldError};return{status:"ok",mode:"legacy",records,manifest:null,checkpoint:null}}function loadRecordsForWrite(directory){let load=loadFoldedState(directory,{strict:!1});if(load.status==="uncertain")return recordLedgerUncertainty(directory,load.reason,"mutation",load.repairHint),null;return[...load.records.values()]}function findRecordForWrite(records,correlationId){if(!records)return null;for(let record2 of records)if(record2.correlationId===correlationId)return record2;return null}function recordLedgerUncertainty(directory,reason,source,repairHint){try{writeDelegationHealthArtifact(directory,{uncertainty:{reason,at:Date.now(),source,...repairHint?{repairHint}:{}}})}catch{}}function isUnsettledWorktreeOwner(record2){return Boolean(record2.worktree)&&!(record2.coderSettlement?.state==="settled"&&record2.coderSettlement.outcome?.kind==="standard-worktree"&&(record2.coderSettlement.outcome.result==="merged"||record2.coderSettlement.outcome.result==="unchanged"))}function isCheckpointLiveRecord(record2){if(!isTerminal(record2.status))return!0;if(record2.advisoryInbox?.state==="pending")return!0;let settlement=record2.coderSettlement;if(settlement&&settlement.state!=="settled")return!0;if(settlement?.state==="settled"&&isUnsettledWorktreeOwner(record2))return!0;if(isActiveCoderOwner(record2))return!0;return!1}function buildClosedSummary(record2){let summary={...record2};if(delete summary.prompt,delete summary.taskChangeContext,summary.result)summary.result=stripResultBody(record2,summary.result);if(summary.terminalResult)summary.terminalResult={...summary.terminalResult,result:dropResultBody(summary.terminalResult.result)};let parsed=RecordSchema.safeParse(summary);return parsed.success?parsed.data:null}function stripResultBody(record2,result){let{text:_text,error:_error,...rest}=result,receipt=parsePrReviewCollectionReceiptFooter(record2,result),shedMarker=receipt?null:parsePrReviewCollectionReceiptShedMarker(record2,result),receiptText=receipt?`${PR_REVIEW_COLLECTION_RECEIPT_PREFIX}${JSON.stringify(receipt)}`:shedMarker?`${PR_REVIEW_COLLECTION_RECEIPT_SHED_PREFIX}${JSON.stringify(shedMarker)}`:void 0;return receiptText?{...rest,text:receiptText,outputPreviewChars:receiptText.length}:rest}function dropResultBody(result){let{text:_text,error:_error,outputPreviewChars:_preview,...rest}=result;return rest}function dropRetainedPrReviewReceipt(record2){let compact=(result)=>{let payload=parsePrReviewCollectionReceiptFooter(record2,result);if(!payload){let marker2=parsePrReviewCollectionReceiptShedMarker(record2,result);if(!marker2)return dropResultBody(result);let markerText=`${PR_REVIEW_COLLECTION_RECEIPT_SHED_PREFIX}${JSON.stringify(marker2)}`,{text:_text2,error:_error2,...rest2}=result;return{...rest2,text:markerText,outputPreviewChars:markerText.length}}let marker=encodePrReviewCollectionReceiptShedMarker(payload),{text:_text,error:_error,...rest}=result;return{...rest,text:marker,outputPreviewChars:marker.length}};return{...record2,...record2.result?{result:compact(record2.result)}:{},...record2.terminalResult?{terminalResult:{...record2.terminalResult,result:dropResultBody(record2.terminalResult.result)}}:{}}}function emptyAudit(){return{dispatchCount:0,terminalsByStatus:{completed:0,error:0,cancelled:0,stale:0},settledCount:0,preservedCount:0,lateTerminalCount:0,compactedTransitionCount:0,compactedRecordCount:0,firstDispatchAt:null,lastTerminalAt:null,lastCompactionAt:0}}function terminalEventStatusOf(record2){if(record2.terminalResult)return record2.terminalResult.status;if(record2.status==="completed"||record2.status==="error"||record2.status==="cancelled"||record2.status==="stale")return record2.status;return null}function mergeCheckpointAudit(previous,previousCheckpoint,folded,healthLateTerminals,retiredLineCount,newlySummarizedCount,now){let prev=previous??emptyAudit(),prevById=new Map;if(previousCheckpoint){for(let record2 of previousCheckpoint.records)prevById.set(record2.correlationId,record2);for(let summary of previousCheckpoint.closed)prevById.set(summary.correlationId,summary)}let audit={dispatchCount:prev.dispatchCount,terminalsByStatus:{...prev.terminalsByStatus},settledCount:prev.settledCount,preservedCount:prev.preservedCount,lateTerminalCount:Math.max(prev.lateTerminalCount,healthLateTerminals),compactedTransitionCount:capCounter(prev.compactedTransitionCount,retiredLineCount),compactedRecordCount:capCounter(prev.compactedRecordCount,newlySummarizedCount),firstDispatchAt:prev.firstDispatchAt,lastTerminalAt:prev.lastTerminalAt,lastCompactionAt:now},minCreated=Number.POSITIVE_INFINITY,maxTerminal=0;for(let record2 of folded){let prevRecord=prevById.get(record2.correlationId);if(!prevRecord)audit.dispatchCount+=1;let terminalStatus=terminalEventStatusOf(record2);if(terminalStatus){if((prevRecord?terminalEventStatusOf(prevRecord):null)!==terminalStatus)audit.terminalsByStatus[terminalStatus]+=1;maxTerminal=Math.max(maxTerminal,record2.terminalResult?.recordedAt??record2.completedAt??0)}if(record2.coderSettlement?.state==="settled"&&prevRecord?.coderSettlement?.state!=="settled")audit.settledCount+=1;if(record2.coderSettlement?.state==="preserved"&&prevRecord?.coderSettlement?.state!=="preserved")audit.preservedCount+=1;minCreated=Math.min(minCreated,record2.createdAt)}return audit.firstDispatchAt=Number.isFinite(minCreated)?Math.min(prev.firstDispatchAt??Number.POSITIVE_INFINITY,minCreated):prev.firstDispatchAt,audit.lastTerminalAt=Math.max(prev.lastTerminalAt??0,maxTerminal)||null,audit}function capCounter(previous,delta){return Number.isSafeInteger(previous+delta)?previous+delta:Number.MAX_SAFE_INTEGER}async function compactBackgroundDelegations(directory,options={}){try{let outcome={status:"skipped",reason:"not attempted"};return await withEvidenceLock(directory,BACKGROUND_DELEGATIONS_FILE,STORE_LOCK_AGENT,STORE_LOCK_TASK,async()=>{outcome=compactDelegationsLocked(directory,options)}),outcome}catch(err){let message=err instanceof Error?err.message:String(err);return warn(`[background] compactBackgroundDelegations failed: ${message}`),{status:"uncertain",reason:message}}}function compactDelegationsLocked(directory,options){let load=loadFoldedState(directory,{strict:!1});if(load.status==="uncertain")return recordLedgerUncertainty(directory,load.reason,"compaction",load.repairHint),{status:"uncertain",reason:load.reason};let ledgerBytes;try{ledgerBytes=fs9.readFileSync(storePath(directory))}catch(err){if(err.code==="ENOENT")return{status:"skipped",reason:"no ledger to compact"};return{status:"uncertain",reason:err instanceof Error?err.message:String(err)}}if(ledgerBytes.length<=DELEGATION_COMPACTION_HIGH_WATER_BYTES&&!options.force)return{status:"skipped",reason:"ledger below the compaction high-water mark"};let cutLedgerBytes=ledgerBytes.length,retiredLineCount=countCompleteLines(ledgerBytes),now=Date.now(),folded=[...load.records.values()],live=[],closedCandidates=[];for(let record2 of folded)if(isCheckpointLiveRecord(record2))live.push(record2);else closedCandidates.push(buildClosedSummary(record2)??record2);if(live.length>MAX_CHECKPOINT_RECORDS)return recordLedgerUncertainty(directory,`checkpoint live-record budget exceeded (${live.length} > ${MAX_CHECKPOINT_RECORDS}); compaction skipped`,"compaction"),{status:"skipped",reason:`live record count ${live.length} exceeds the checkpoint budget ${MAX_CHECKPOINT_RECORDS}`};closedCandidates.sort((a,b)=>b.updatedAt-a.updatedAt);let used=Buffer.byteLength(JSON.stringify({schemaVersion:1,sequence:1,writerId:WRITER_ID,rootPath:path13.resolve(directory),createdAt:now,cutLedgerBytes,cutLedgerDigest:sha256Hex(ledgerBytes),records:live,closed:[],audit:emptyAudit(),payloadChecksum:"0".repeat(64)}),"utf-8"),selectionBudget=MAX_CHECKPOINT_BYTES-CHECKPOINT_SELECTION_RESERVE_BYTES,keptClosed=[],evicted=0;for(let entry of closedCandidates){let retainedEntry=entry,cost=Buffer.byteLength(JSON.stringify(retainedEntry),"utf-8")+1;if(used+cost>selectionBudget){if(now-entry.updatedAt<TOMBSTONE_MIN_AGE_MS){if(retainedEntry=dropRetainedPrReviewReceipt(entry),cost=Buffer.byteLength(JSON.stringify(retainedEntry),"utf-8")+1,used+cost<=selectionBudget){used+=cost,keptClosed.push(retainedEntry);continue}return recordLedgerUncertainty(directory,"checkpoint byte budget would evict a young closed summary; compaction skipped","compaction"),{status:"skipped",reason:"checkpoint byte budget would evict a young closed summary"}}evicted+=1;continue}used+=cost,keptClosed.push(retainedEntry)}let sequence=Math.max(load.manifest?.sequence??0,load.checkpoint?.sequence??0,0)+1,healthLateTerminals=0;try{healthLateTerminals=readDelegationHealthArtifact(directory)?.counts.lateTerminals??0}catch{healthLateTerminals=0}let previousClosedIds=new Set((load.checkpoint?.closed??[]).map((entry)=>entry.correlationId)),newlySummarized=keptClosed.filter((entry)=>!previousClosedIds.has(entry.correlationId)).length,audit=mergeCheckpointAudit(load.checkpoint?.audit??null,load.checkpoint,folded,healthLateTerminals,retiredLineCount,newlySummarized+evicted,now),checkpointCandidate={schemaVersion:1,sequence,writerId:WRITER_ID,rootPath:path13.resolve(directory),createdAt:now,cutLedgerBytes,cutLedgerDigest:sha256Hex(ledgerBytes),records:live,closed:keptClosed,audit,payloadChecksum:"0".repeat(64)},normalizedCheckpoint=CheckpointSchema.safeParse(checkpointCandidate);if(!normalizedCheckpoint.success)return recordLedgerUncertainty(directory,"generated checkpoint failed schema normalization; compaction skipped","compaction"),{status:"skipped",reason:"generated checkpoint failed schema normalization"};let checkpoint=normalizedCheckpoint.data;checkpoint.payloadChecksum=checkpointPayloadChecksum(checkpoint);let checkpointJson=`${JSON.stringify(checkpoint)}
186
186
  `;if(Buffer.byteLength(checkpointJson,"utf-8")>MAX_CHECKPOINT_BYTES)return recordLedgerUncertainty(directory,"serialized checkpoint exceeds the byte budget; compaction skipped","compaction"),{status:"skipped",reason:"serialized checkpoint exceeds the byte budget"};writeDurableFileSync(checkpointPath(directory),checkpointJson),writeDurableFileSync(manifestPath(directory),`${JSON.stringify({schemaVersion:1,sequence,checkpointChecksum:checkpoint.payloadChecksum,writerId:WRITER_ID,rootPath:checkpoint.rootPath,updatedAt:now})}
187
187
  `);let currentSize;try{currentSize=fs9.statSync(storePath(directory)).size}catch(err){return{status:"uncertain",reason:`ledger vanished during compaction: ${err instanceof Error?err.message:String(err)}`}}if(currentSize<cutLedgerBytes)return{status:"skipped",reason:"ledger shrank during compaction; checkpoint published unrolled"};let tailContent=currentSize>cutLedgerBytes?readLedgerRegion(directory,cutLedgerBytes,currentSize-cutLedgerBytes):Buffer.alloc(0);writeDurableFileSync(storePath(directory),tailContent);try{let pressurePct=Math.min(100,Math.round(tailContent.length/MAX_RECOVERY_LEDGER_BYTES*1000)/10);writeDelegationHealthArtifact(directory,{ledger:{bytes:tailContent.length,limitBytes:MAX_RECOVERY_LEDGER_BYTES,pressurePct,band:tailContent.length>DELEGATION_COMPACTION_HIGH_WATER_BYTES?"compact-overdue":tailContent.length>DELEGATION_COMPACTION_LOW_WATER_BYTES?"nominal":"ok"},checkpoint:{sequence,createdAt:now,liveRecords:live.length,closedSummaries:keptClosed.length,bytes:Buffer.byteLength(checkpointJson,"utf-8"),audit},counts:{activeOwners:folded.filter((record2)=>isActiveCoderOwner(record2)).length,pendingAdvisories:folded.filter((record2)=>record2.advisoryInbox?.state==="pending").length,lateTerminals:audit.lateTerminalCount,orphanWorktreeOwners:folded.filter(isUnsettledWorktreeOwner).length}})}catch{}return{status:"compacted",sequence,tailBytes:tailContent.length,checkpointBytes:Buffer.byteLength(checkpointJson,"utf-8")}}function countCompleteLines(buffer){let count=0;for(let byte of buffer)if(byte===10)count+=1;return count}function maybeCompactDelegationsLocked(directory){try{if(fs9.statSync(storePath(directory)).size<=DELEGATION_COMPACTION_HIGH_WATER_BYTES)return;let outcome=compactDelegationsLocked(directory,{});if(outcome.status==="uncertain")warn(`[background] post-append compaction skipped: ${outcome.reason}`)}catch(err){warn(`[background] post-append compaction check failed: ${err instanceof Error?err.message:String(err)}`)}}function ensureSwarmDir(directory){fs9.mkdirSync(path13.resolve(directory,".swarm"),{recursive:!0})}function readDelegations(directory){let load=loadFoldedState(directory,{strict:!1});if(load.status==="uncertain")return warn(`[background] readDelegations: authoritative state uncertain (${load.reason}); returning empty`),[];return[...load.records.values()]}function scanDelegationsForRecovery(directory){let load=loadFoldedState(directory,{strict:!0});if(load.status==="uncertain"){let manifestKind=readDelegationManifest(directory).kind;return{status:"uncertain",reason:load.reason,source:manifestKind==="absent"?"legacy-ledger":"unknown",...load.repairHint?{repairHint:load.repairHint}:{}}}let source=load.mode==="legacy"?"legacy-ledger":load.mode;return{status:"ok",owners:[...load.records.values()],source}}function findByCorrelationId(directory,correlationId){if(!correlationId)return null;for(let record2 of readDelegations(directory))if(record2.correlationId===correlationId)return record2;return null}function appendRecord(directory,record2){ensureSwarmDir(directory),fs9.appendFileSync(storePath(directory),`${JSON.stringify(record2)}
188
188
  `,"utf-8")}function buildPendingRecord(input,now){return{schemaVersion:input.worktree?3:input.batchId?2:1,correlationId:input.correlationId,jobId:input.jobId,subagentSessionId:input.subagentSessionId,parentSessionId:input.parentSessionId,callID:input.callID,normalizedAgent:input.normalizedAgent,swarmPrefixedAgent:input.swarmPrefixedAgent,planTaskId:input.planTaskId,evidenceTaskId:input.evidenceTaskId,status:"pending",createdAt:now,updatedAt:now,...input.batchId?{batchId:input.batchId}:{},...input.laneId?{laneId:input.laneId}:{},...input.mode?{mode:input.mode}:{},...input.workflowLane?{workflowLane:input.workflowLane}:{},...input.ownedWorkflowLanes?.length?{ownedWorkflowLanes:[...input.ownedWorkflowLanes]}:{},...input.promptHash?{promptHash:input.promptHash}:{},...input.workspace?{workspace:input.workspace}:{},...input.taskChangeContext?{taskChangeContext:input.taskChangeContext}:{},...input.workflowGeneration!==void 0?{workflowGeneration:input.workflowGeneration}:{},...input.worktree?{worktree:input.worktree}:{},...input.coderReservationId?{coderReservationId:input.coderReservationId}:{},...input.prompt?{prompt:input.prompt}:{},...input.generation!==void 0?{generation:input.generation}:{}}}function pendingLaunchIdentity(record2,summaryAware){return{correlationId:record2.correlationId,jobId:record2.jobId,subagentSessionId:record2.subagentSessionId,parentSessionId:record2.parentSessionId,callID:record2.callID,normalizedAgent:record2.normalizedAgent,swarmPrefixedAgent:record2.swarmPrefixedAgent,planTaskId:record2.planTaskId,evidenceTaskId:record2.evidenceTaskId,batchId:record2.batchId,laneId:record2.laneId,mode:record2.mode,workflowLane:record2.workflowLane,ownedWorkflowLanes:record2.ownedWorkflowLanes,promptHash:record2.promptHash,workspace:record2.workspace,...summaryAware?{}:{taskChangeContext:record2.taskChangeContext,workflowGeneration:record2.workflowGeneration,worktree:record2.worktree,coderReservationId:record2.coderReservationId,prompt:record2.prompt,generation:record2.generation??1}}}function samePendingLaunchIdentity(left,right){let summaryAware=isTerminal(left.status)&&left.prompt===void 0&&left.taskChangeContext===void 0;return isDeepStrictEqual(pendingLaunchIdentity(left,summaryAware),pendingLaunchIdentity(right,summaryAware))}async function recordPendingDelegationDetailed(directory,input,options={}){let now=Date.now(),record2=buildPendingRecord(input,now),parsedRecord=RecordSchema.safeParse(record2);if(!parsedRecord.success)return warn("[background] recordPendingDelegation rejected invalid input"),{status:"failed",record:null};try{let outcome={status:"failed",record:null};return await withEvidenceLock(directory,BACKGROUND_DELEGATIONS_FILE,STORE_LOCK_AGENT,STORE_LOCK_TASK,async()=>{if(options.staleTimeoutMs&&options.staleTimeoutMs>0)sweepStaleLocked(directory,options.staleTimeoutMs,now);let records=loadRecordsForWrite(directory);if(records===null)return;let existing=findRecordForWrite(records,parsedRecord.data.correlationId);if(existing){outcome={status:samePendingLaunchIdentity(existing,parsedRecord.data)?"duplicate":"conflict",record:existing};return}appendRecord(directory,parsedRecord.data),maybeCompactDelegationsLocked(directory),outcome={status:"recorded",record:parsedRecord.data}}),outcome}catch(err){return warn(`[background] recordPendingDelegation failed: ${err instanceof Error?err.message:String(err)}`),{status:"failed",record:null}}}async function recordPendingDelegation(directory,input,options={}){let outcome=await recordPendingDelegationDetailed(directory,input,options);return outcome.status==="recorded"||outcome.status==="duplicate"?outcome.record:null}function buildPromptSnapshot(text,maxChars){let boundedMax=Math.max(0,Math.min(maxChars,20000)),truncated=text.length>boundedMax;return{text:truncated?text.slice(0,boundedMax):text,chars:text.length,truncated,digest:createHash6("sha256").update(text).digest("hex")}}async function appendDelegationTransition(directory,correlationId,transition){let now=Date.now();try{let next=null;return await withEvidenceLock(directory,BACKGROUND_DELEGATIONS_FILE,STORE_LOCK_AGENT,STORE_LOCK_TASK,async()=>{let records=loadRecordsForWrite(directory);if(records===null)return;let current=findRecordForWrite(records,correlationId);if(!current)return;if(transition.expectedCurrentStatuses&&!transition.expectedCurrentStatuses.includes(current.status)){next=current;return}if(isTerminal(current.status)&&transition.status!=="consumed"&&transition.status!=="ingestion_error"&&!(current.status==="completed"&&transition.status==="stale")){next=current;return}next={...current,schemaVersion:current.schemaVersion===1?2:current.schemaVersion,status:transition.status,updatedAt:now,...transition.completedAt!==void 0?{completedAt:transition.completedAt}:transition.status==="completed"||transition.status==="error"?{completedAt:now}:{},...transition.result?{result:transition.result}:{}},appendRecord(directory,next),maybeCompactDelegationsLocked(directory)}),next}catch(err){return warn(`[background] appendDelegationTransition failed: ${err instanceof Error?err.message:String(err)}`),null}}function buildBackgroundCompletionEventId(input){let canonical=JSON.stringify([input.correlationId,input.jobId,input.status,input.resultDigest]);return`bgc1:${createHash6("sha256").update(canonical).digest("hex")}`}function sameJson(left,right){return JSON.stringify(left)===JSON.stringify(right)}function sameTerminalEvent(left,right){return left.eventId===right.eventId&&left.status===right.status&&sameRetainedResult(left.result,right.result)}function sameRetainedResult(left,right){return left.chars===right.chars&&left.truncated===right.truncated&&left.digest===right.digest&&left.outputRef===right.outputRef&&left.outputPreviewChars===right.outputPreviewChars&&left.outputDegraded===right.outputDegraded&&left.outputArtifactError===right.outputArtifactError&&left.transcriptIncomplete===right.transcriptIncomplete&&left.messageCount===right.messageCount&&sameJson(left.salvagedWorkflowLanes,right.salvagedWorkflowLanes)&&sameJson(left.salvagedWorkflowLaneRecoveries,right.salvagedWorkflowLaneRecoveries)}function settlementProvenanceFor(record2){let baseline=record2.taskChangeContext?.baseline;if(!baseline)return null;return{correlationId:record2.correlationId,parentSessionId:record2.parentSessionId,callID:record2.callID,planTaskId:record2.planTaskId,baseline,worktree:record2.worktree??null}}function terminalDisposition(record2){if(record2.status==="consumed")return"consumed";if(record2.coderSettlement?.state==="settling")return"resume_settlement";if(record2.coderSettlement?.state==="preserved")return"preserved";if(record2.status==="ingestion_error")return"retry_ingestion";return"duplicate"}async function claimTerminalResult(directory,correlationId,terminalResult){let parsedTerminal=TerminalResultSchema.safeParse(terminalResult);if(!correlationId||!parsedTerminal.success)return null;let claim=null;try{return await withEvidenceLock(directory,BACKGROUND_DELEGATIONS_FILE,STORE_LOCK_AGENT,STORE_LOCK_TASK,async()=>{let records=loadRecordsForWrite(directory);if(records===null)return;let current=findRecordForWrite(records,correlationId);if(!current)return;if(current.terminalResult){if(!sameTerminalEvent(current.terminalResult,parsedTerminal.data)){warn(`[background] claimTerminalResult: different terminal event for correlationId=${correlationId}; existing={status: ${current.terminalResult.status}, eventId: ${current.terminalResult.eventId}} incoming={status: ${parsedTerminal.data.status}, eventId: ${parsedTerminal.data.eventId}}; rejected`),incrementLateTerminalCount(directory);return}claim={disposition:terminalDisposition(current),record:current};return}if(current.status!=="pending"&&current.status!=="running")return;let coderSettlement=current.coderSettlement;if(current.normalizedAgent==="coder"&&!coderSettlement){let provenance=settlementProvenanceFor(current);if(provenance)coderSettlement={state:"pending",provenance,observedFiles:null,updatedAt:parsedTerminal.data.recordedAt}}let foldUpdatedAt=Math.max(parsedTerminal.data.recordedAt,current.updatedAt),next={...current,schemaVersion:3,status:parsedTerminal.data.status,terminalResult:parsedTerminal.data,result:parsedTerminal.data.result,completedAt:parsedTerminal.data.recordedAt,updatedAt:foldUpdatedAt,...coderSettlement?{coderSettlement}:{}};if(!RecordSchema.safeParse(next).success)return;appendRecord(directory,next),maybeCompactDelegationsLocked(directory),claim={disposition:"claimed",record:next}}),claim}catch(err){return warn(`[background] claimTerminalResult failed: ${err instanceof Error?err.message:String(err)}`),null}}function incrementLateTerminalCount(directory){try{let artifact=readDelegationHealthArtifact(directory),current=artifact?.counts.lateTerminals??0;writeDelegationHealthArtifact(directory,{counts:{activeOwners:artifact?.counts.activeOwners??0,pendingAdvisories:artifact?.counts.pendingAdvisories??0,lateTerminals:current+1,orphanWorktreeOwners:artifact?.counts.orphanWorktreeOwners??0}})}catch{}}async function claimCoderSettlement(directory,correlationId,operationId,input={}){if(!correlationId||!operationId||operationId.length>256)return null;let claim=null;try{return await withEvidenceLock(directory,BACKGROUND_DELEGATIONS_FILE,STORE_LOCK_AGENT,STORE_LOCK_TASK,async()=>{let records=loadRecordsForWrite(directory);if(records===null)return;let current=findRecordForWrite(records,correlationId);if(!current||current.normalizedAgent!=="coder"||current.terminalResult?.status!=="completed")return;let provenance=settlementProvenanceFor(current);if(!provenance)return;let existing=current.coderSettlement??{state:"pending",provenance,observedFiles:null,updatedAt:current.updatedAt};if(existing.state==="settled"||existing.state==="preserved"){claim={disposition:existing.state,record:current};return}if(existing.state==="settling"&&existing.operationId!==operationId)return;if(existing.sourceHeadAfterCommit!==void 0&&input.sourceHeadAfterCommit!==void 0&&existing.sourceHeadAfterCommit!==input.sourceHeadAfterCommit)return;if(existing.targetHeadBeforeMerge!==void 0&&input.targetHeadBeforeMerge!==void 0&&existing.targetHeadBeforeMerge!==input.targetHeadBeforeMerge)return;let settlement={...existing,state:"settling",operationId,...input.sourceHeadAfterCommit!==void 0?{sourceHeadAfterCommit:input.sourceHeadAfterCommit}:{},...input.targetHeadBeforeMerge!==void 0?{targetHeadBeforeMerge:input.targetHeadBeforeMerge}:{},updatedAt:Date.now()},next={...current,schemaVersion:3,coderSettlement:settlement,updatedAt:settlement.updatedAt};if(!RecordSchema.safeParse(next).success)return;appendRecord(directory,next),maybeCompactDelegationsLocked(directory),claim={disposition:existing.state==="settling"?"resume":"claimed",record:next}}),claim}catch(err){return warn(`[background] claimCoderSettlement failed: ${err instanceof Error?err.message:String(err)}`),null}}function normalizeObservedFile(value){if(typeof value!=="string")return null;let trimmed=value.trim().replace(/\\/g,"/");if(trimmed.length===0||trimmed.length>4096||trimmed.includes("\x00")||path13.posix.isAbsolute(trimmed)||/^[A-Za-z]:\//.test(trimmed))return null;let normalized=path13.posix.normalize(trimmed).replace(/^\.\//,"");if(normalized==="."||normalized===".."||normalized.startsWith("../")||normalized.endsWith("/"))return null;return normalized}function normalizeBackgroundObservedFiles(files){if(!Array.isArray(files)||files.length>MAX_BACKGROUND_OBSERVED_FILES)return null;let normalized=new Set;for(let file2 of files){let candidate=normalizeObservedFile(file2);if(!candidate)return null;normalized.add(candidate)}return[...normalized].sort()}async function updateCoderSettlement(directory,correlationId,input){if(!correlationId||!input.operationId)return null;let result=null;try{return await withEvidenceLock(directory,BACKGROUND_DELEGATIONS_FILE,STORE_LOCK_AGENT,STORE_LOCK_TASK,async()=>{let records=loadRecordsForWrite(directory);if(records===null)return;let current=findRecordForWrite(records,correlationId),existing=current?.coderSettlement;if(!current||!existing)return;if(existing.state==="settled"||existing.state==="preserved"){result=current;return}if(existing.state!=="settling"||existing.operationId!==input.operationId)return;if(existing.sourceHeadAfterCommit!==void 0&&input.sourceHeadAfterCommit!==void 0&&existing.sourceHeadAfterCommit!==input.sourceHeadAfterCommit)return;if(existing.targetHeadBeforeMerge!==void 0&&input.targetHeadBeforeMerge!==void 0&&existing.targetHeadBeforeMerge!==input.targetHeadBeforeMerge)return;if((input.state==="settled"||input.state==="preserved")&&!input.outcome)return;if(input.outcome&&(existing.provenance.worktree&&input.outcome.kind!=="standard-worktree"||!existing.provenance.worktree&&input.outcome.kind!=="shared-root"))return;if(input.state==="settled"&&input.outcome&&(input.outcome.result==="partial"||input.outcome.result==="failed"))return;if(input.state==="preserved"&&input.outcome&&input.outcome.result!=="partial"&&input.outcome.result!=="failed")return;let observedFiles=existing.observedFiles;if(input.observedFiles!==void 0)if(input.observedFiles===null)observedFiles=null;else{let normalized=normalizeBackgroundObservedFiles(input.observedFiles);if(!normalized)return;observedFiles=normalized}if(input.state==="settled"&&observedFiles===null)return;let updatedAt=Date.now(),settlement={...existing,state:input.state,...input.sourceHeadAfterCommit!==void 0?{sourceHeadAfterCommit:input.sourceHeadAfterCommit}:{},...input.targetHeadBeforeMerge!==void 0?{targetHeadBeforeMerge:input.targetHeadBeforeMerge}:{},observedFiles,...input.outcome?{outcome:input.outcome}:{},updatedAt},next={...current,schemaVersion:3,coderSettlement:settlement,updatedAt};if(!RecordSchema.safeParse(next).success)return;appendRecord(directory,next),maybeCompactDelegationsLocked(directory),result=next}),result}catch(err){return warn(`[background] updateCoderSettlement failed: ${err instanceof Error?err.message:String(err)}`),null}}async function claimDelegationIngestion(directory,correlationId,options){if(!correlationId||!options.claimantId)return null;let now=options.now??Date.now(),leaseMs=Math.max(1000,Math.min(options.leaseMs??INGESTION_CLAIM_LEASE_MS,300000)),claim=null;try{return await withEvidenceLock(directory,BACKGROUND_DELEGATIONS_FILE,STORE_LOCK_AGENT,STORE_LOCK_TASK,async()=>{let records=loadRecordsForWrite(directory);if(records===null)return;let current=findRecordForWrite(records,correlationId);if(!current?.terminalResult)return;if(current.status==="consumed"){claim={disposition:"consumed",record:current};return}if(current.ingestion?.state==="claimed"&&(current.ingestion.leaseExpiresAt??Number.MAX_SAFE_INTEGER)>now){claim={disposition:"busy",record:current};return}if(current.coderSettlement?.state==="preserved"){claim={disposition:"preserved",record:current};return}if(current.terminalResult.status!=="completed"||current.normalizedAgent==="coder"&&current.coderSettlement?.state!=="settled"){claim={disposition:"not_ready",record:current};return}if(current.status!=="completed"&&current.status!=="ingestion_error"){claim={disposition:"not_ready",record:current};return}let disposition=current.status==="ingestion_error"||current.ingestion?.state==="claimed"?"retry":"claimed",attempt=(current.ingestion?.attempt??0)+1,claimToken=createHash6("sha256").update(JSON.stringify([correlationId,options.claimantId,attempt,now])).digest("hex"),next={...current,schemaVersion:3,ingestion:{state:"claimed",attempt,updatedAt:now,claimToken,leaseExpiresAt:now+leaseMs},updatedAt:now};appendRecord(directory,next),maybeCompactDelegationsLocked(directory),claim={disposition,record:next}}),claim}catch(err){return warn(`[background] claimDelegationIngestion failed: ${err instanceof Error?err.message:String(err)}`),null}}async function recordDelegationIngestionResult(directory,correlationId,claimToken,success2,options={}){if(!correlationId||!claimToken)return null;let result=null;try{return await withEvidenceLock(directory,BACKGROUND_DELEGATIONS_FILE,STORE_LOCK_AGENT,STORE_LOCK_TASK,async()=>{let records=loadRecordsForWrite(directory);if(records===null)return;let current=findRecordForWrite(records,correlationId);if(!current)return;if(success2&&current.status==="consumed"&&current.ingestion?.state==="consumed"&&current.ingestion.claimToken===claimToken||!success2&&current.status==="ingestion_error"&&current.ingestion?.state==="retryable"&&current.ingestion.claimToken===claimToken){result=current;return}if(current.ingestion?.state!=="claimed"||current.ingestion.claimToken!==claimToken||(current.ingestion.leaseExpiresAt??0)<=(options.now??Date.now()))return;let updatedAt=options.now??Date.now(),next={...current,schemaVersion:3,status:success2?"consumed":"ingestion_error",ingestion:{state:success2?"consumed":"retryable",attempt:current.ingestion.attempt,claimToken,updatedAt},updatedAt};appendRecord(directory,next),maybeCompactDelegationsLocked(directory),result=next}),result}catch(err){return warn(`[background] recordDelegationIngestionResult failed: ${err instanceof Error?err.message:String(err)}`),null}}async function putPendingBackgroundAdvisory(directory,correlationId,input){let createdAt=input.createdAt??Date.now(),parsed=AdvisoryInboxSchema.safeParse({eventId:input.eventId,parentSessionId:input.parentSessionId,state:"pending",message:input.message,createdAt});if(!correlationId||!parsed.success)return null;let result=null;try{return await withEvidenceLock(directory,BACKGROUND_DELEGATIONS_FILE,STORE_LOCK_AGENT,STORE_LOCK_TASK,async()=>{let records=loadRecordsForWrite(directory);if(records===null)return;let current=findRecordForWrite(records,correlationId);if(!current?.terminalResult||current.terminalResult.eventId!==parsed.data.eventId||current.parentSessionId!==parsed.data.parentSessionId)return;if(current.advisoryInbox){if(current.advisoryInbox.eventId===parsed.data.eventId&&current.advisoryInbox.parentSessionId===parsed.data.parentSessionId&&current.advisoryInbox.message===parsed.data.message)result=current.advisoryInbox;return}let next={...current,schemaVersion:3,advisoryInbox:parsed.data,updatedAt:createdAt};appendRecord(directory,next),maybeCompactDelegationsLocked(directory),result=parsed.data}),result}catch(err){return warn(`[background] putPendingBackgroundAdvisory failed: ${err instanceof Error?err.message:String(err)}`),null}}async function preparePendingBackgroundAdvisories(directory,parentSessionId,options){if(!parentSessionId||!options.preparationId)return[];let now=options.now??Date.now(),leaseMs=Math.max(1000,Math.min(options.leaseMs??ADVISORY_PREPARE_LEASE_MS,300000)),prepared=[];try{return await withEvidenceLock(directory,BACKGROUND_DELEGATIONS_FILE,STORE_LOCK_AGENT,STORE_LOCK_TASK,async()=>{let records=loadRecordsForWrite(directory);if(records===null)return;for(let current of records){if(prepared.length>=1)break;let advisory=current.advisoryInbox;if(!advisory||advisory.parentSessionId!==parentSessionId||advisory.state!=="pending")continue;if(advisory.preparation&&advisory.preparation.id!==options.preparationId&&advisory.preparation.leaseExpiresAt>now)continue;let nextAdvisory={...advisory,preparation:{id:options.preparationId,preparedAt:now,leaseExpiresAt:now+leaseMs}},next={...current,schemaVersion:3,advisoryInbox:nextAdvisory,updatedAt:now};appendRecord(directory,next),maybeCompactDelegationsLocked(directory),prepared.push(nextAdvisory)}}),prepared}catch(err){return warn(`[background] preparePendingBackgroundAdvisories failed: ${err instanceof Error?err.message:String(err)}`),[]}}async function releaseBackgroundAdvisoryPreparation(directory,parentSessionId,preparationId,eventIds){let uniqueEventIds=[...new Set(eventIds)];if(!parentSessionId||!preparationId||uniqueEventIds.length!==1)return!1;try{return await withEvidenceLock(directory,BACKGROUND_DELEGATIONS_FILE,STORE_LOCK_AGENT,STORE_LOCK_TASK,async()=>{let records=loadRecordsForWrite(directory);if(records===null)return!1;let byEvent=new Map;for(let current of records){let advisory=current.advisoryInbox;if(advisory?.parentSessionId===parentSessionId&&uniqueEventIds.includes(advisory.eventId))byEvent.set(advisory.eventId,current)}for(let eventId of uniqueEventIds){let advisory=byEvent.get(eventId)?.advisoryInbox;if(!advisory||advisory.state!=="pending"||advisory.preparation?.id!==preparationId)return!1}for(let eventId of uniqueEventIds){let current=byEvent.get(eventId);if(!current?.advisoryInbox)return!1;let now=Date.now(),next={...current,schemaVersion:3,advisoryInbox:{...current.advisoryInbox,preparation:void 0},updatedAt:now};appendRecord(directory,next)}return maybeCompactDelegationsLocked(directory),!0})}catch(err){return warn(`[background] releasePreparedBackgroundAdvisories failed: ${err instanceof Error?err.message:String(err)}`),!1}}async function acknowledgeObservedBackgroundAdvisories(directory,parentSessionId,observedTexts){if(!parentSessionId||observedTexts.length===0)return 0;let acknowledged=0;try{return await withEvidenceLock(directory,BACKGROUND_DELEGATIONS_FILE,STORE_LOCK_AGENT,STORE_LOCK_TASK,async()=>{let records=loadRecordsForWrite(directory);if(records===null)return;let now=Date.now();for(let current of records){let advisory=current.advisoryInbox;if(!advisory||advisory.parentSessionId!==parentSessionId||advisory.state!=="pending"||!observedTexts.some((text)=>{let advisoryBlock=text.match(/\[ADVISORIES\]([\s\S]*?)\[\/ADVISORIES\]/);if(advisoryBlock)return advisoryBlock[1].split(`
189
189
  ---
190
- `).some((entry)=>entry.trim()===advisory.message);return text.includes(advisory.message)}))continue;let next={...current,schemaVersion:3,advisoryInbox:{...advisory,state:"delivered",deliveredAt:now,preparation:void 0},updatedAt:now};appendRecord(directory,next),acknowledged+=1}if(acknowledged>0)maybeCompactDelegationsLocked(directory)}),acknowledged}catch(err){return warn(`[background] acknowledgeObservedBackgroundAdvisories failed: ${err instanceof Error?err.message:String(err)}`),0}}async function releasePreparedBackgroundAdvisories(directory,parentSessionId,preparationId,eventIds){return releaseBackgroundAdvisoryPreparation(directory,parentSessionId,preparationId,eventIds)}function findByBatchId(directory,batchId,opts){if(!batchId)return[];return readDelegations(directory).filter((record2)=>record2.batchId===batchId&&(opts?.parentSessionId===void 0||record2.parentSessionId===opts.parentSessionId))}function findOpenAsyncLaneBatches(directory){return readDelegations(directory).filter((record2)=>record2.batchId!==void 0&&(record2.status==="pending"||record2.status==="running"))}function isTerminal(status){return status==="completed"||status==="error"||status==="cancelled"||status==="stale"||status==="consumed"}function sweepStaleLocked(directory,timeoutMs,now,statuses=DEFAULT_SWEEPABLE_DELEGATION_STATUSES,filters={}){let swept=0,{excludeCorrelationIds,includeCorrelationIds}=filters,records=loadRecordsForWrite(directory);if(records===null)return 0;for(let record2 of records){if(includeCorrelationIds!==void 0&&!includeCorrelationIds.has(record2.correlationId))continue;if(excludeCorrelationIds?.has(record2.correlationId))continue;if(!statuses.has(record2.status))continue;if(now-record2.updatedAt<=timeoutMs)continue;appendRecord(directory,{...record2,status:"stale",updatedAt:now}),swept+=1}if(swept>0)maybeCompactDelegationsLocked(directory);return swept}async function sweepStaleDelegations(directory,timeoutMs,options={}){if(!timeoutMs||timeoutMs<=0)return 0;let statuses=options.statuses??DEFAULT_SWEEPABLE_DELEGATION_STATUSES,filters={excludeCorrelationIds:options.excludeCorrelationIds,includeCorrelationIds:options.includeCorrelationIds};try{return await withEvidenceLock(directory,BACKGROUND_DELEGATIONS_FILE,STORE_LOCK_AGENT,STORE_LOCK_TASK,async()=>sweepStaleLocked(directory,timeoutMs,Date.now(),statuses,filters))}catch(err){return warn(`[background] sweepStaleDelegations failed: ${err instanceof Error?err.message:String(err)}`),0}}function fallbackRelativePath(correlationId){let digest=createHash6("sha256").update(correlationId).digest("hex");return path13.join(BACKGROUND_DELEGATION_FALLBACK_DIR,`${digest}.json`)}function fallbackPath(directory,correlationId){return validateSwarmPath(directory,fallbackRelativePath(correlationId))}function fallbackDirectoryPath(directory){return path13.dirname(validateSwarmPath(directory,path13.join(BACKGROUND_DELEGATION_FALLBACK_DIR,".containment-anchor")))}async function readFallbackFile(directory,correlationId){for(let attempt=0;attempt<5;attempt++)try{let raw=await fs9.promises.readFile(fallbackPath(directory,correlationId),"utf-8"),parsedJson=JSON.parse(raw),parsed=FallbackArtifactSchema.safeParse(parsedJson);if(!parsed.success||parsed.data.correlationId!==correlationId)return null;return parsed.data}catch(err){if(err.code==="ENOENT"&&attempt<4){await new Promise((resolve8)=>setTimeout(resolve8,10));continue}return null}return null}async function readDelegationFallback(directory,correlationId){if(!correlationId)return null;return readFallbackFile(directory,correlationId)}async function listDelegationFallbacks(directory){let entries;try{entries=fs9.readdirSync(fallbackDirectoryPath(directory),{withFileTypes:!0}).filter((entry)=>entry.isFile()&&entry.name.endsWith(".json")).slice(0,MAX_LIVE_BACKGROUND_FALLBACKS)}catch{return[]}let artifacts=[];for(let entry of entries)try{let raw=await fs9.promises.readFile(path13.join(fallbackDirectoryPath(directory),entry.name),"utf-8"),parsed=FallbackArtifactSchema.safeParse(JSON.parse(raw));if(parsed.success)artifacts.push(parsed.data)}catch{}return artifacts}async function scanDelegationFallbacksForRecovery(directory){let fallbackDir,entries;try{fallbackDir=fallbackDirectoryPath(directory),entries=fs9.readdirSync(fallbackDir,{withFileTypes:!0}).filter((entry)=>entry.isFile()&&entry.name.endsWith(".json"))}catch(error49){if(error49.code==="ENOENT")return{status:"ok",owners:[]};return{status:"uncertain",reason:`background fallback directory is unreadable: ${error49 instanceof Error?error49.message:String(error49)}`}}if(entries.length>MAX_LIVE_BACKGROUND_FALLBACKS)return{status:"uncertain",reason:`background fallback owner count exceeds the ${MAX_LIVE_BACKGROUND_FALLBACKS}-artifact safety bound`};let artifacts=[];for(let entry of entries){let artifactPath=path13.join(fallbackDir,entry.name),raw;try{if(fs9.statSync(artifactPath).size>MAX_RECOVERY_FALLBACK_BYTES)return{status:"uncertain",reason:`background fallback artifact "${entry.name}" exceeds the recovery size bound`};raw=await fs9.promises.readFile(artifactPath,"utf-8")}catch(error49){return{status:"uncertain",reason:`background fallback artifact "${entry.name}" is unreadable: ${error49 instanceof Error?error49.message:String(error49)}`}}if(Buffer.byteLength(raw,"utf8")>MAX_RECOVERY_FALLBACK_BYTES)return{status:"uncertain",reason:`background fallback artifact "${entry.name}" changed beyond the recovery size bound`};let parsedJson;try{parsedJson=JSON.parse(raw)}catch{return{status:"uncertain",reason:`background fallback artifact "${entry.name}" has malformed JSON`}}let parsed=FallbackArtifactSchema.safeParse(parsedJson);if(!parsed.success)return{status:"uncertain",reason:`background fallback artifact "${entry.name}" has an invalid owner record`};artifacts.push(parsed.data)}return{status:"ok",owners:artifacts}}function countFallbackFiles(directory){try{return fs9.readdirSync(fallbackDirectoryPath(directory),{withFileTypes:!0}).filter((entry)=>entry.isFile()&&entry.name.endsWith(".json")).length}catch(err){if(err.code==="ENOENT")return 0;return MAX_LIVE_BACKGROUND_FALLBACKS}}async function writeDelegationFallback(directory,input,options={}){let now=Date.now(),record2={...buildPendingRecord(input,now),schemaVersion:3},artifact={schemaVersion:1,correlationId:input.correlationId,createdAt:now,record:record2},parsed=FallbackArtifactSchema.safeParse(artifact);if(!parsed.success)return null;let requestedCap=Math.floor(Math.max(1,options.maxLive??MAX_LIVE_BACKGROUND_FALLBACKS)),maxLive=Math.min(requestedCap,MAX_LIVE_BACKGROUND_FALLBACKS);try{return await withEvidenceLock(directory,BACKGROUND_DELEGATION_FALLBACK_DIR,STORE_LOCK_AGENT,FALLBACK_LOCK_TASK,async()=>{let existing=await readFallbackFile(directory,input.correlationId);if(existing)return samePendingRecord(existing.record,parsed.data.record)?existing:null;if(countFallbackFiles(directory)>=maxLive)return null;let absPath=fallbackPath(directory,input.correlationId);return fs9.mkdirSync(path13.dirname(absPath),{recursive:!0}),await bunWrite(absPath,`${JSON.stringify(parsed.data)}
190
+ `).some((entry)=>entry.trim()===advisory.message);return text.includes(advisory.message)}))continue;let next={...current,schemaVersion:3,advisoryInbox:{...advisory,state:"delivered",deliveredAt:now,preparation:void 0},updatedAt:now};appendRecord(directory,next),acknowledged+=1}if(acknowledged>0)maybeCompactDelegationsLocked(directory)}),acknowledged}catch(err){return warn(`[background] acknowledgeObservedBackgroundAdvisories failed: ${err instanceof Error?err.message:String(err)}`),0}}async function releasePreparedBackgroundAdvisories(directory,parentSessionId,preparationId,eventIds){return releaseBackgroundAdvisoryPreparation(directory,parentSessionId,preparationId,eventIds)}function findByBatchId(directory,batchId,opts){if(!batchId)return[];return readDelegations(directory).filter((record2)=>record2.batchId===batchId&&(opts?.parentSessionId===void 0||record2.parentSessionId===opts.parentSessionId))}function findOpenAsyncLaneBatches(directory){return readDelegations(directory).filter((record2)=>record2.batchId!==void 0&&(record2.status==="pending"||record2.status==="running"))}function isTerminal(status){return status==="completed"||status==="error"||status==="cancelled"||status==="stale"||status==="consumed"}function sweepStaleLocked(directory,timeoutMs,now,statuses=DEFAULT_SWEEPABLE_DELEGATION_STATUSES,filters={},limits={}){let swept=0,{excludeCorrelationIds,includeCorrelationIds}=filters,records=loadRecordsForWrite(directory);if(records===null)return 0;for(let record2 of records){if(limits.maxSweep!==void 0&&swept>=limits.maxSweep)break;if(includeCorrelationIds!==void 0&&!includeCorrelationIds.has(record2.correlationId))continue;if(excludeCorrelationIds?.has(record2.correlationId))continue;if(!statuses.has(record2.status))continue;if(now-record2.updatedAt<=timeoutMs)continue;appendRecord(directory,{...record2,status:"stale",updatedAt:now}),swept+=1}if(swept>0)maybeCompactDelegationsLocked(directory);return swept}async function sweepStaleDelegations(directory,timeoutMs,options={}){if(!timeoutMs||timeoutMs<=0)return 0;let statuses=options.statuses??DEFAULT_SWEEPABLE_DELEGATION_STATUSES,filters={excludeCorrelationIds:options.excludeCorrelationIds,includeCorrelationIds:options.includeCorrelationIds};try{return await withEvidenceLock(directory,BACKGROUND_DELEGATIONS_FILE,STORE_LOCK_AGENT,STORE_LOCK_TASK,async()=>sweepStaleLocked(directory,timeoutMs,Date.now(),statuses,filters))}catch(err){return warn(`[background] sweepStaleDelegations failed: ${err instanceof Error?err.message:String(err)}`),0}}function fallbackRelativePath(correlationId){let digest=createHash6("sha256").update(correlationId).digest("hex");return path13.join(BACKGROUND_DELEGATION_FALLBACK_DIR,`${digest}.json`)}function fallbackPath(directory,correlationId){return validateSwarmPath(directory,fallbackRelativePath(correlationId))}function fallbackDirectoryPath(directory){return path13.dirname(validateSwarmPath(directory,path13.join(BACKGROUND_DELEGATION_FALLBACK_DIR,".containment-anchor")))}async function readFallbackFile(directory,correlationId){for(let attempt=0;attempt<5;attempt++)try{let raw=await fs9.promises.readFile(fallbackPath(directory,correlationId),"utf-8"),parsedJson=JSON.parse(raw),parsed=FallbackArtifactSchema.safeParse(parsedJson);if(!parsed.success||parsed.data.correlationId!==correlationId)return null;return parsed.data}catch(err){if(err.code==="ENOENT"&&attempt<4){await new Promise((resolve8)=>setTimeout(resolve8,10));continue}return null}return null}async function readDelegationFallback(directory,correlationId){if(!correlationId)return null;return readFallbackFile(directory,correlationId)}async function listDelegationFallbacks(directory){let entries;try{entries=fs9.readdirSync(fallbackDirectoryPath(directory),{withFileTypes:!0}).filter((entry)=>entry.isFile()&&entry.name.endsWith(".json")).slice(0,MAX_LIVE_BACKGROUND_FALLBACKS)}catch{return[]}let artifacts=[];for(let entry of entries)try{let raw=await fs9.promises.readFile(path13.join(fallbackDirectoryPath(directory),entry.name),"utf-8"),parsed=FallbackArtifactSchema.safeParse(JSON.parse(raw));if(parsed.success)artifacts.push(parsed.data)}catch{}return artifacts}async function scanDelegationFallbacksForRecovery(directory){let fallbackDir,entries;try{fallbackDir=fallbackDirectoryPath(directory),entries=fs9.readdirSync(fallbackDir,{withFileTypes:!0}).filter((entry)=>entry.isFile()&&entry.name.endsWith(".json"))}catch(error49){if(error49.code==="ENOENT")return{status:"ok",owners:[]};return{status:"uncertain",reason:`background fallback directory is unreadable: ${error49 instanceof Error?error49.message:String(error49)}`}}if(entries.length>MAX_LIVE_BACKGROUND_FALLBACKS)return{status:"uncertain",reason:`background fallback owner count exceeds the ${MAX_LIVE_BACKGROUND_FALLBACKS}-artifact safety bound`};let artifacts=[];for(let entry of entries){let artifactPath=path13.join(fallbackDir,entry.name),raw;try{if(fs9.statSync(artifactPath).size>MAX_RECOVERY_FALLBACK_BYTES)return{status:"uncertain",reason:`background fallback artifact "${entry.name}" exceeds the recovery size bound`};raw=await fs9.promises.readFile(artifactPath,"utf-8")}catch(error49){return{status:"uncertain",reason:`background fallback artifact "${entry.name}" is unreadable: ${error49 instanceof Error?error49.message:String(error49)}`}}if(Buffer.byteLength(raw,"utf8")>MAX_RECOVERY_FALLBACK_BYTES)return{status:"uncertain",reason:`background fallback artifact "${entry.name}" changed beyond the recovery size bound`};let parsedJson;try{parsedJson=JSON.parse(raw)}catch{return{status:"uncertain",reason:`background fallback artifact "${entry.name}" has malformed JSON`}}let parsed=FallbackArtifactSchema.safeParse(parsedJson);if(!parsed.success)return{status:"uncertain",reason:`background fallback artifact "${entry.name}" has an invalid owner record`};artifacts.push(parsed.data)}return{status:"ok",owners:artifacts}}function countFallbackFiles(directory){try{return fs9.readdirSync(fallbackDirectoryPath(directory),{withFileTypes:!0}).filter((entry)=>entry.isFile()&&entry.name.endsWith(".json")).length}catch(err){if(err.code==="ENOENT")return 0;return MAX_LIVE_BACKGROUND_FALLBACKS}}async function writeDelegationFallback(directory,input,options={}){let now=Date.now(),record2={...buildPendingRecord(input,now),schemaVersion:3},artifact={schemaVersion:1,correlationId:input.correlationId,createdAt:now,record:record2},parsed=FallbackArtifactSchema.safeParse(artifact);if(!parsed.success)return null;let requestedCap=Math.floor(Math.max(1,options.maxLive??MAX_LIVE_BACKGROUND_FALLBACKS)),maxLive=Math.min(requestedCap,MAX_LIVE_BACKGROUND_FALLBACKS);try{return await withEvidenceLock(directory,BACKGROUND_DELEGATION_FALLBACK_DIR,STORE_LOCK_AGENT,FALLBACK_LOCK_TASK,async()=>{let existing=await readFallbackFile(directory,input.correlationId);if(existing)return samePendingRecord(existing.record,parsed.data.record)?existing:null;if(countFallbackFiles(directory)>=maxLive)return null;let absPath=fallbackPath(directory,input.correlationId);return fs9.mkdirSync(path13.dirname(absPath),{recursive:!0}),await bunWrite(absPath,`${JSON.stringify(parsed.data)}
191
191
  `),parsed.data})}catch(err){return warn(`[background] writeDelegationFallback failed: ${err instanceof Error?err.message:String(err)}`),null}}async function removeDelegationFallback(directory,correlationId){if(!correlationId)return!1;try{return await withEvidenceLock(directory,BACKGROUND_DELEGATION_FALLBACK_DIR,STORE_LOCK_AGENT,FALLBACK_LOCK_TASK,async()=>{try{return await fs9.promises.unlink(fallbackPath(directory,correlationId)),!0}catch(err){return err.code==="ENOENT"}})}catch(err){return warn(`[background] removeDelegationFallback failed: ${err instanceof Error?err.message:String(err)}`),!1}}async function findDelegationForCompletion(directory,correlationId){if(!correlationId)return null;let primary=findByCorrelationId(directory,correlationId);if(primary)return{source:"primary",record:primary};let fallback=await readDelegationFallback(directory,correlationId);return fallback?{source:"fallback",record:fallback.record,fallback}:null}function samePromotionIdentity(primary,fallback){return primary.correlationId===fallback.correlationId&&primary.subagentSessionId===fallback.subagentSessionId&&primary.parentSessionId===fallback.parentSessionId&&primary.callID===fallback.callID&&primary.planTaskId===fallback.planTaskId&&primary.coderReservationId===fallback.coderReservationId&&sameJson(primary.worktree??null,fallback.worktree??null)&&sameJson(primary.taskChangeContext??null,fallback.taskChangeContext??null)}function samePendingRecord(left,right){let{createdAt:_leftCreatedAt,updatedAt:_leftUpdatedAt,...leftIdentity}=left,{createdAt:_rightCreatedAt,updatedAt:_rightUpdatedAt,...rightIdentity}=right;return sameJson(leftIdentity,rightIdentity)}async function promoteDelegationFallback(directory,correlationId){if(!correlationId)return null;try{return await withEvidenceLock(directory,BACKGROUND_DELEGATION_FALLBACK_DIR,STORE_LOCK_AGENT,FALLBACK_LOCK_TASK,async()=>{let fallback=await readFallbackFile(directory,correlationId);if(!fallback){let primary=findByCorrelationId(directory,correlationId);return primary?{source:"primary",record:primary}:null}let promoted=null;if(await withEvidenceLock(directory,BACKGROUND_DELEGATIONS_FILE,STORE_LOCK_AGENT,STORE_LOCK_TASK,async()=>{let records=loadRecordsForWrite(directory);if(records===null)return;let current=findRecordForWrite(records,correlationId);if(current){if(samePromotionIdentity(current,fallback.record))promoted=current;return}appendRecord(directory,fallback.record),maybeCompactDelegationsLocked(directory),promoted=fallback.record}),!promoted)return null;try{await fs9.promises.unlink(fallbackPath(directory,correlationId))}catch(err){if(err.code!=="ENOENT")return null}return{source:"primary",record:promoted}})}catch(err){return warn(`[background] promoteDelegationFallback failed: ${err instanceof Error?err.message:String(err)}`),null}}function reservationStorePath(directory){return validateSwarmPath(directory,BACKGROUND_CODER_RESERVATIONS_FILE)}function buildBackgroundCoderReservationId(input){let ownerIdentity=input.planTaskId===null?["call",input.parentSessionId,input.callID]:["task",input.parentSessionId,input.planTaskId];return`bgcr1:${createHash6("sha256").update(JSON.stringify(ownerIdentity)).digest("hex")}`}function scanBackgroundCoderReservationsForAdmission(directory){let absolutePath,raw;try{if(absolutePath=reservationStorePath(directory),fs9.statSync(absolutePath).size>MAX_BACKGROUND_CODER_RESERVATION_STORE_BYTES)return{status:"uncertain",reason:`background coder reservation store exceeds the ${MAX_BACKGROUND_CODER_RESERVATION_STORE_BYTES}-byte safety bound`};raw=fs9.readFileSync(absolutePath,"utf-8")}catch(error49){if(error49.code==="ENOENT")return{status:"ok",reservations:[]};return{status:"uncertain",reason:`background coder reservation store is unreadable: ${error49 instanceof Error?error49.message:String(error49)}`}}if(Buffer.byteLength(raw,"utf8")>MAX_BACKGROUND_CODER_RESERVATION_STORE_BYTES)return{status:"uncertain",reason:"background coder reservation store changed beyond its safety bound"};let parsedJson;try{parsedJson=JSON.parse(raw)}catch{return{status:"uncertain",reason:"background coder reservation store contains malformed JSON"}}let parsed=BackgroundCoderReservationStoreSchema.safeParse(parsedJson);if(!parsed.success)return{status:"uncertain",reason:"background coder reservation store failed strict schema validation"};return{status:"ok",reservations:parsed.data.reservations}}async function writeBackgroundCoderReservations(directory,reservations){let parsed=BackgroundCoderReservationStoreSchema.safeParse({schemaVersion:1,reservations});if(!parsed.success)return!1;try{return await bunWrite(reservationStorePath(directory),`${JSON.stringify(parsed.data)}
192
- `),!0}catch(error49){return warn(`[background] reservation write failed: ${error49 instanceof Error?error49.message:String(error49)}`),!1}}function reservationOwnerKey(input){return input.planTaskId===null?`call:${input.parentSessionId}:${input.callID}`:`task:${input.parentSessionId}:${input.planTaskId}`}function isActiveCoderOwner(record2){if(record2.normalizedAgent!=="coder"||record2.status==="consumed")return!1;if(record2.status==="pending"||record2.status==="running"||record2.status==="completed"||record2.status==="ingestion_error")return!0;if(record2.coderSettlement?.state==="preserved")return!0;return record2.worktree!==void 0}async function scanDurableCoderOwners(directory){let fallbackScan=await scanDelegationFallbacksForRecovery(directory);if(fallbackScan.status==="uncertain")return fallbackScan;let primaryScan=scanDelegationsForRecovery(directory);if(primaryScan.status==="uncertain")return primaryScan;let recordsByCorrelation=new Map;for(let artifact of fallbackScan.owners)recordsByCorrelation.set(artifact.correlationId,artifact.record);let primaryByCorrelation=new Map,primaryByReservationId=new Map;for(let record2 of primaryScan.owners){if(primaryByCorrelation.set(record2.correlationId,record2),record2.coderReservationId){let owners=primaryByReservationId.get(record2.coderReservationId)??[];owners.push(record2),primaryByReservationId.set(record2.coderReservationId,owners)}recordsByCorrelation.set(record2.correlationId,record2)}return{status:"ok",recordsByCorrelation,primaryByCorrelation,primaryByReservationId}}function exactReservationOwnerCoordinates(reservation,record2){return record2.coderReservationId===reservation.reservationId&&record2.parentSessionId===reservation.parentSessionId&&record2.planTaskId===reservation.planTaskId&&record2.callID===reservation.callID}function exactReservationRecordMatch(reservation,record2){return exactReservationOwnerCoordinates(reservation,record2)&&record2.correlationId===reservation.correlationId}function findExactPrimaryReservationOwner(reservation,ownerScan){if(reservation.correlationId!==null){let primary=ownerScan.primaryByCorrelation.get(reservation.correlationId);return primary&&exactReservationRecordMatch(reservation,primary)?primary:null}let exactOwners=(ownerScan.primaryByReservationId.get(reservation.reservationId)??[]).filter((record2)=>exactReservationOwnerCoordinates(reservation,record2));return exactOwners.length===1?exactOwners[0]:null}function hasProvenReleasedReservationOwner(record2){if(record2.status==="consumed")return!0;return record2.worktree===void 0&&(record2.status==="error"||record2.status==="cancelled")&&record2.terminalResult?.status===record2.status}function validateReservationIdentity(input){return typeof input.parentSessionId==="string"&&input.parentSessionId.length>0&&input.parentSessionId.length<=256&&input.parentSessionId.trim()===input.parentSessionId&&typeof input.callID==="string"&&input.callID.length>0&&input.callID.length<=256&&input.callID.trim()===input.callID&&(input.planTaskId===null||typeof input.planTaskId==="string"&&input.planTaskId.length>0&&input.planTaskId.length<=256&&input.planTaskId.trim()===input.planTaskId)}async function reserveBackgroundCoderSlot(directory,input){if(!validateReservationIdentity(input)||!Number.isInteger(input.maxConcurrent)||input.maxConcurrent<1||input.maxConcurrent>64||(input.occupiedTaskIds?.length??0)>64)return{ok:!1,reason:"invalid"};let occupiedTaskIds=new Set;for(let taskId of input.occupiedTaskIds??[]){if(typeof taskId!=="string"||taskId.length===0||taskId.length>256||taskId.trim()!==taskId)return{ok:!1,reason:"invalid"};occupiedTaskIds.add(taskId)}try{return await withEvidenceLock(directory,BACKGROUND_CODER_RESERVATIONS_FILE,STORE_LOCK_AGENT,RESERVATION_LOCK_TASK,async()=>{let reservationScan=scanBackgroundCoderReservationsForAdmission(directory);if(reservationScan.status==="uncertain")return{ok:!1,reason:"uncertain",detail:reservationScan.reason};let ownerScan=await scanDurableCoderOwners(directory);if(ownerScan.status==="uncertain")return{ok:!1,reason:"uncertain",detail:ownerScan.reason};let reservations=reservationScan.reservations.filter((reservation2)=>{let primary=findExactPrimaryReservationOwner(reservation2,ownerScan);return!(primary&&hasProvenReleasedReservationOwner(primary))});if(reservations.length!==reservationScan.reservations.length&&!await writeBackgroundCoderReservations(directory,reservations))return{ok:!1,reason:"uncertain",detail:"finished reservation reconciliation could not be persisted"};let activeOwnerKeys=new Set;for(let taskId of occupiedTaskIds)activeOwnerKeys.add(reservationOwnerKey({parentSessionId:input.parentSessionId,planTaskId:taskId,callID:""}));for(let reservation2 of reservations)if(reservation2.parentSessionId===input.parentSessionId)activeOwnerKeys.add(reservationOwnerKey(reservation2));for(let record2 of ownerScan.recordsByCorrelation.values())if(record2.parentSessionId===input.parentSessionId&&isActiveCoderOwner(record2))activeOwnerKeys.add(reservationOwnerKey({parentSessionId:record2.parentSessionId,planTaskId:record2.planTaskId,callID:record2.callID}));let reservationId=buildBackgroundCoderReservationId(input),existing=reservations.find((reservation2)=>reservation2.reservationId===reservationId);if(existing)return{ok:!1,reason:input.planTaskId===null?"duplicate_call":"duplicate_task",activeCount:activeOwnerKeys.size,existing};let incomingOwnerKey=reservationOwnerKey(input);if(input.planTaskId!==null&&activeOwnerKeys.has(incomingOwnerKey))return{ok:!1,reason:"duplicate_task",activeCount:activeOwnerKeys.size};if(activeOwnerKeys.size>=input.maxConcurrent)return{ok:!1,reason:"capacity",activeCount:activeOwnerKeys.size};if(reservations.length>=MAX_LIVE_BACKGROUND_CODER_RESERVATIONS)return{ok:!1,reason:"capacity",activeCount:activeOwnerKeys.size,detail:"durable reservation store is at its hard safety cap"};let now=input.now??Date.now(),reservation={reservationId,parentSessionId:input.parentSessionId,planTaskId:input.planTaskId,callID:input.callID,state:"reserved",correlationId:null,createdAt:now,updatedAt:now};if(!await writeBackgroundCoderReservations(directory,[...reservations,reservation]))return{ok:!1,reason:"uncertain",detail:"durable reservation claim could not be persisted"};return{ok:!0,reservation,activeCount:activeOwnerKeys.size+1}})}catch(error49){return{ok:!1,reason:"uncertain",detail:`background coder reservation lock failed: ${error49 instanceof Error?error49.message:String(error49)}`}}}async function bindBackgroundCoderReservation(directory,input){if(!validateReservationIdentity(input)||!input.reservationId||!input.correlationId||input.correlationId.length>256||input.correlationId.trim()!==input.correlationId||input.reservationId!==buildBackgroundCoderReservationId(input))return null;try{return await withEvidenceLock(directory,BACKGROUND_CODER_RESERVATIONS_FILE,STORE_LOCK_AGENT,RESERVATION_LOCK_TASK,async()=>{let scan=scanBackgroundCoderReservationsForAdmission(directory);if(scan.status==="uncertain")return null;let index=scan.reservations.findIndex((reservation)=>reservation.reservationId===input.reservationId);if(index<0)return null;let current=scan.reservations[index];if(current.parentSessionId!==input.parentSessionId||current.planTaskId!==input.planTaskId||current.callID!==input.callID)return null;if(current.state==="bound")return current.correlationId===input.correlationId?current:null;let next={...current,state:"bound",correlationId:input.correlationId,updatedAt:input.now??Date.now()},reservations=[...scan.reservations];return reservations[index]=next,await writeBackgroundCoderReservations(directory,reservations)?next:null})}catch{return null}}async function releaseBackgroundCoderReservation(directory,input){if(!validateReservationIdentity(input)||!input.reservationId||input.reservationId!==buildBackgroundCoderReservationId(input)||input.correlationId!==null&&(input.correlationId.length===0||input.correlationId.length>256||input.correlationId.trim()!==input.correlationId))return!1;try{return await withEvidenceLock(directory,BACKGROUND_CODER_RESERVATIONS_FILE,STORE_LOCK_AGENT,RESERVATION_LOCK_TASK,async()=>{let scan=scanBackgroundCoderReservationsForAdmission(directory);if(scan.status==="uncertain")return!1;let index=scan.reservations.findIndex((reservation)=>reservation.reservationId===input.reservationId);if(index<0)return!1;let current=scan.reservations[index];if(current.parentSessionId!==input.parentSessionId||current.planTaskId!==input.planTaskId||current.callID!==input.callID||current.correlationId!==input.correlationId)return!1;if(input.reason==="consumed"){if(current.state!=="bound"||!current.correlationId)return!1;let ownerScan=await scanDurableCoderOwners(directory);if(ownerScan.status==="uncertain")return!1;let primary=ownerScan.primaryByCorrelation.get(current.correlationId);if(!primary||primary.status!=="consumed"||!exactReservationRecordMatch(current,primary))return!1}let reservations=scan.reservations.filter((_,reservationIndex)=>reservationIndex!==index);return writeBackgroundCoderReservations(directory,reservations)})}catch{return!1}}var BACKGROUND_DELEGATIONS_FILE="background-delegations.jsonl",BACKGROUND_DELEGATION_FALLBACK_DIR="background-delegation-fallback",BACKGROUND_CODER_RESERVATIONS_FILE="background-coder-reservations.json",BACKGROUND_DELEGATIONS_CHECKPOINT_FILE="background-delegations.checkpoint.json",BACKGROUND_DELEGATIONS_MANIFEST_FILE="background-delegations.manifest.json",MAX_LIVE_BACKGROUND_FALLBACKS=256,MAX_LIVE_BACKGROUND_CODER_RESERVATIONS=256,MAX_BACKGROUND_OBSERVED_FILES=5000,MAX_BACKGROUND_ADVISORY_CHARS=4000,MAX_BACKGROUND_DELEGATION_GENERATION=1e6,MAX_RECOVERY_FALLBACK_BYTES=1048576,DELEGATION_COMPACTION_LOW_WATER_BYTES=262144,DELEGATION_COMPACTION_HIGH_WATER_BYTES=1048576,MAX_CHECKPOINT_BYTES=2097152,CHECKPOINT_SELECTION_RESERVE_BYTES=65536,MAX_CHECKPOINT_RECORDS=2048,TOMBSTONE_MIN_AGE_MS=259200000,STORE_LOCK_AGENT="background",STORE_LOCK_TASK="background-delegations",FALLBACK_LOCK_TASK="background-delegation-fallback",RESERVATION_LOCK_TASK="background-coder-reservations",ADVISORY_PREPARE_LEASE_MS=30000,INGESTION_CLAIM_LEASE_MS=30000,BACKGROUND_INGESTION_LEASE_MS=30000,DEFAULT_STALE_DELEGATION_TIMEOUT_MS=1800000,DEFAULT_SWEEPABLE_DELEGATION_STATUSES,WorkflowLaneRecoverySchema,ResultSchema,WorkspaceSchema,TaskChangeContextSchema,WorktreeDescriptorSchema,TerminalResultSchema,NormalizedObservedFileSchema,SettlementProvenanceSchema,SettlementOutcomeSchema,CoderSettlementSchema,AdvisoryPreparationSchema,AdvisoryInboxSchema,DelegationIngestionSchema,BackgroundCoderReservationSchema,BackgroundCoderReservationStoreSchema,PromptSchema,RecordSchema,FallbackArtifactSchema,SHA256_HEX,CheckpointSchema,ManifestSchema,WRITER_ID,_checkpointInternals,CHECKPOINT_REBIND_HINT="remove .swarm/background-delegations.manifest.json (manifest only) after verifying no in-flight background delegations; recovery then falls back to the full-ledger read. Only if you also want to discard pre-cut closed summaries and audit history — which for a compacted (rolled) ledger exist ONLY in .swarm/background-delegations.checkpoint.json — remove the checkpoint too or use the full reset below",CHECKPOINT_RESET_HINT="the rolled tail no longer carries pre-checkpoint state: stop swarm processes, verify no in-flight background delegations, and remove .swarm/background-delegations.manifest.json, .swarm/background-delegations.checkpoint.json, and .swarm/background-delegations.jsonl to reset the store (or restore them from backup)",MAX_BACKGROUND_CODER_RESERVATION_STORE_BYTES=2097152;var init_pending_delegations=__esm(()=>{init_zod();init_lock();init_utils2();init_bun_compat();init_logger();init_delegation_health();init_pr_review_collection_receipt();init_delegation_health();init_delegation_health();DEFAULT_SWEEPABLE_DELEGATION_STATUSES=new Set(["pending","running","ingestion_error"]),WorkflowLaneRecoverySchema=exports_external.object({workflowLane:exports_external.string(),kind:exports_external.enum(["legacy-verdict-row-recovery","parser-normalization","parser-row-recovery","truncated-preview-durable-artifact","transcript-incomplete-terminal-candidate","clean-attestation-salvaged"]),reason:exports_external.string()}).strict(),ResultSchema=exports_external.object({text:exports_external.string().optional(),error:exports_external.string().optional(),chars:exports_external.number(),truncated:exports_external.boolean(),digest:exports_external.string(),outputRef:exports_external.string().optional(),outputPreviewChars:exports_external.number().optional(),outputDegraded:exports_external.boolean().optional(),outputArtifactError:exports_external.string().optional(),transcriptIncomplete:exports_external.boolean().optional(),messageCount:exports_external.number().optional(),salvagedWorkflowLanes:exports_external.array(exports_external.string()).optional(),salvagedWorkflowLaneRecoveries:exports_external.array(WorkflowLaneRecoverySchema).optional()}).strict(),WorkspaceSchema=exports_external.object({directory:exports_external.string(),gitHead:exports_external.string().nullable(),dirtyHash:exports_external.string().nullable(),changedFiles:exports_external.array(exports_external.string()).nullable().optional(),prHeadSha:exports_external.string().nullable(),scope:exports_external.string().nullable()}).strict(),TaskChangeContextSchema=exports_external.object({declaredFiles:exports_external.array(exports_external.string()).nullable(),baseline:WorkspaceSchema,workflowGeneration:exports_external.number().int().nonnegative().optional()}).strict(),WorktreeDescriptorSchema=exports_external.object({callID:exports_external.string().min(1).max(256),parentSessionId:exports_external.string().min(1).max(256),taskId:exports_external.string().min(1).max(256),planTaskId:exports_external.string().min(1).max(256).nullable(),worktreePath:exports_external.string().min(1).max(4096),branchName:exports_external.string().min(1).max(1024),worktreeId:exports_external.string().min(1).max(256),worktreeSessionId:exports_external.string().min(1).max(256),mergeStrategy:exports_external.enum(["merge","rebase","cherry-pick"]),laneIndex:exports_external.number().int().nonnegative().max(255),worktreeDir:exports_external.string().min(1).max(4096).nullable()}).strict(),TerminalResultSchema=exports_external.object({eventId:exports_external.string().min(1).max(256),status:exports_external.enum(["completed","error","cancelled"]),recordedAt:exports_external.number().int().nonnegative(),result:ResultSchema}).strict(),NormalizedObservedFileSchema=exports_external.string().min(1).max(4096).refine((value)=>normalizeObservedFile(value)===value),SettlementProvenanceSchema=exports_external.object({correlationId:exports_external.string().min(1).max(256),parentSessionId:exports_external.string().min(1).max(256),callID:exports_external.string().max(256),planTaskId:exports_external.string().min(1).max(256).nullable(),baseline:WorkspaceSchema,worktree:WorktreeDescriptorSchema.nullable()}).strict(),SettlementOutcomeSchema=exports_external.object({kind:exports_external.enum(["shared-root","standard-worktree"]),result:exports_external.enum(["ready","merged","unchanged","partial","failed"]),reason:exports_external.string().min(1).max(2000).optional(),sourceHeadAfterCommit:exports_external.string().min(1).max(256).nullable().optional(),targetHeadBeforeMerge:exports_external.string().min(1).max(256).nullable().optional(),targetHeadAfterMerge:exports_external.string().min(1).max(256).nullable().optional()}).strict(),CoderSettlementSchema=exports_external.object({state:exports_external.enum(["pending","settling","settled","preserved"]),provenance:SettlementProvenanceSchema,operationId:exports_external.string().min(1).max(256).optional(),sourceHeadAfterCommit:exports_external.string().min(1).max(256).nullable().optional(),targetHeadBeforeMerge:exports_external.string().min(1).max(256).nullable().optional(),observedFiles:exports_external.array(NormalizedObservedFileSchema).max(MAX_BACKGROUND_OBSERVED_FILES).nullable(),outcome:SettlementOutcomeSchema.optional(),updatedAt:exports_external.number().int().nonnegative()}).strict().superRefine((value,context)=>{if(value.state!=="pending"&&!value.operationId)context.addIssue({code:exports_external.ZodIssueCode.custom,message:"settling, settled, and preserved states require operationId"});if((value.state==="settled"||value.state==="preserved")&&!value.outcome)context.addIssue({code:exports_external.ZodIssueCode.custom,message:"terminal settlement state requires outcome"})}),AdvisoryPreparationSchema=exports_external.object({id:exports_external.string().min(1).max(256),preparedAt:exports_external.number().int().nonnegative(),leaseExpiresAt:exports_external.number().int().nonnegative()}).strict(),AdvisoryInboxSchema=exports_external.object({eventId:exports_external.string().min(1).max(256),parentSessionId:exports_external.string().min(1).max(256),state:exports_external.enum(["pending","delivered"]),message:exports_external.string().min(1).max(MAX_BACKGROUND_ADVISORY_CHARS),createdAt:exports_external.number().int().nonnegative(),preparation:AdvisoryPreparationSchema.optional(),deliveredAt:exports_external.number().int().nonnegative().optional()}).strict().superRefine((value,context)=>{if(value.state==="delivered"&&value.deliveredAt===void 0)context.addIssue({code:exports_external.ZodIssueCode.custom,message:"delivered advisory requires deliveredAt"});if(value.state==="delivered"&&value.preparation!==void 0)context.addIssue({code:exports_external.ZodIssueCode.custom,message:"delivered advisory cannot retain a preparation lease"})}),DelegationIngestionSchema=exports_external.object({state:exports_external.enum(["claimed","retryable","consumed"]),attempt:exports_external.number().int().positive(),updatedAt:exports_external.number().int().nonnegative(),claimToken:exports_external.string().min(1).max(256),leaseExpiresAt:exports_external.number().int().nonnegative().optional()}).strict().superRefine((value,context)=>{if(value.state==="claimed"&&value.leaseExpiresAt===void 0)context.addIssue({code:exports_external.ZodIssueCode.custom,message:"claimed ingestion requires a lease expiry"});if(value.state!=="claimed"&&value.leaseExpiresAt!==void 0)context.addIssue({code:exports_external.ZodIssueCode.custom,message:"completed ingestion cannot retain a claim lease"})}),BackgroundCoderReservationSchema=exports_external.object({reservationId:exports_external.string().min(1).max(256),parentSessionId:exports_external.string().min(1).max(256),planTaskId:exports_external.string().min(1).max(256).nullable(),callID:exports_external.string().min(1).max(256),state:exports_external.enum(["reserved","bound"]),correlationId:exports_external.string().min(1).max(256).nullable(),createdAt:exports_external.number().int().nonnegative(),updatedAt:exports_external.number().int().nonnegative()}).strict().superRefine((value,context)=>{if(value.state==="reserved"&&value.correlationId!==null)context.addIssue({code:exports_external.ZodIssueCode.custom,message:"unbound reservation cannot have a correlationId"});if(value.state==="bound"&&value.correlationId===null)context.addIssue({code:exports_external.ZodIssueCode.custom,message:"bound reservation requires a correlationId"})}),BackgroundCoderReservationStoreSchema=exports_external.object({schemaVersion:exports_external.literal(1),reservations:exports_external.array(BackgroundCoderReservationSchema).max(MAX_LIVE_BACKGROUND_CODER_RESERVATIONS)}).strict().superRefine((value,context)=>{let ids=new Set;for(let reservation of value.reservations){if(ids.has(reservation.reservationId)){context.addIssue({code:exports_external.ZodIssueCode.custom,message:"duplicate reservationId"});return}if(reservation.reservationId!==buildBackgroundCoderReservationId({parentSessionId:reservation.parentSessionId,planTaskId:reservation.planTaskId,callID:reservation.callID})){context.addIssue({code:exports_external.ZodIssueCode.custom,message:"reservationId does not match owner identity"});return}ids.add(reservation.reservationId)}}),PromptSchema=exports_external.object({text:exports_external.string(),chars:exports_external.number(),truncated:exports_external.boolean(),digest:exports_external.string()}).strict(),RecordSchema=exports_external.object({schemaVersion:exports_external.union([exports_external.literal(1),exports_external.literal(2),exports_external.literal(3)]),correlationId:exports_external.string().min(1),jobId:exports_external.string().nullable(),subagentSessionId:exports_external.string().min(1),parentSessionId:exports_external.string().min(1),callID:exports_external.string(),normalizedAgent:exports_external.string(),swarmPrefixedAgent:exports_external.string(),planTaskId:exports_external.string().nullable(),evidenceTaskId:exports_external.string().nullable(),status:exports_external.enum(["pending","running","ingestion_error","completed","error","cancelled","stale","consumed"]),createdAt:exports_external.number(),updatedAt:exports_external.number(),batchId:exports_external.string().optional(),laneId:exports_external.string().optional(),mode:exports_external.string().optional(),workflowLane:exports_external.string().optional(),ownedWorkflowLanes:exports_external.array(exports_external.string().min(1).max(120)).min(1).max(11).optional(),promptHash:exports_external.string().optional(),workspace:WorkspaceSchema.optional(),taskChangeContext:TaskChangeContextSchema.optional(),workflowGeneration:exports_external.number().int().nonnegative().optional(),worktree:WorktreeDescriptorSchema.optional(),coderReservationId:exports_external.string().min(1).max(256).optional(),prompt:PromptSchema.optional(),generation:exports_external.number().int().positive().max(MAX_BACKGROUND_DELEGATION_GENERATION).optional(),terminalResult:TerminalResultSchema.optional(),coderSettlement:CoderSettlementSchema.optional(),advisoryInbox:AdvisoryInboxSchema.optional(),ingestion:DelegationIngestionSchema.optional(),result:ResultSchema.optional(),completedAt:exports_external.number().optional()}).strict(),FallbackArtifactSchema=exports_external.object({schemaVersion:exports_external.literal(1),correlationId:exports_external.string().min(1).max(256),createdAt:exports_external.number().int().nonnegative(),record:RecordSchema}).strict().superRefine((value,context)=>{if(value.record.correlationId!==value.correlationId||value.record.subagentSessionId!==value.correlationId||value.record.status!=="pending")context.addIssue({code:exports_external.ZodIssueCode.custom,message:"fallback identity/status does not match its pending record"})});SHA256_HEX=/^[0-9a-f]{64}$/,CheckpointSchema=exports_external.object({schemaVersion:exports_external.literal(1),sequence:exports_external.number().int().positive(),writerId:exports_external.string().min(1).max(128),rootPath:exports_external.string().min(1).max(4096),createdAt:exports_external.number().int().nonnegative(),cutLedgerBytes:exports_external.number().int().nonnegative(),cutLedgerDigest:exports_external.string().regex(SHA256_HEX),records:exports_external.array(RecordSchema).max(MAX_CHECKPOINT_RECORDS),closed:exports_external.array(RecordSchema),audit:DelegationCheckpointAuditSchema,payloadChecksum:exports_external.string().regex(SHA256_HEX)}).strict(),ManifestSchema=exports_external.object({schemaVersion:exports_external.literal(1),sequence:exports_external.number().int().positive(),checkpointChecksum:exports_external.string().regex(SHA256_HEX),writerId:exports_external.string().min(1).max(128),rootPath:exports_external.string().min(1).max(4096),updatedAt:exports_external.number().int().nonnegative()}).strict(),WRITER_ID=`w-${process.pid}-${Math.random().toString(36).slice(2,10)}`,_checkpointInternals={renameWithRetry:(from,to)=>{let lastError;for(let attempt=0;attempt<5;attempt++)try{_checkpointInternals.renameOnce(from,to);return}catch(err){lastError=err;let code=err.code;if(code!=="EEXIST"&&code!=="EBUSY"&&code!=="EPERM")throw err;_checkpointInternals.syncSleep(15)}throw lastError},renameOnce:(from,to)=>{fs9.renameSync(from,to)},syncSleep:(ms)=>{try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,ms)}catch{let start=Date.now();while(Date.now()-start<ms);}}}});function serializedPrReviewArtifactInputBytes(value){return new TextEncoder().encode(JSON.stringify(value)).byteLength}function quoted(value){return`"${value}"`}function formatEnum(values){return values.map((value)=>quoted(value)).join(" | ")}function getPathValue(input,path14){let current=input;for(let segment of path14){if(current===null||current===void 0)return;if(typeof segment==="number"){if(!Array.isArray(current))return;current=current[segment];continue}if(typeof segment==="symbol"||typeof current!=="object")return;current=current[segment]}return current}function formatActualValue(value){if(value===void 0)return"(omitted)";if(typeof value==="string")return quoted(value);try{let json2=JSON.stringify(value);if(!json2)return String(value);return json2.length<=160?json2:`${json2.slice(0,157)}...`}catch{return String(value)}}function formatIssueExpected(issue2){if(issue2.code==="invalid_value"&&"values"in issue2)return formatEnum(issue2.values);if(issue2.code==="invalid_type")return`${issue2.expected}`;if(issue2.code==="too_small"&&issue2.minimum===1)return"a non-empty value";return issue2.message}function formatPrReviewValidationIssues(issues,input){let rendered=[];for(let issue2 of issues){if(issue2.code==="unrecognized_keys"){let parent=getPathValue(input,issue2.path);for(let key of issue2.keys){let parentPath=issue2.path.map(String),value=parent&&typeof parent==="object"?parent[key]:void 0;rendered.push(`field ${[...parentPath,key].join(".")}: expected no unknown key, got ${formatActualValue(value)}`)}continue}let path14=issue2.path.length>0?issue2.path.map(String).join("."):"(root)";rendered.push(`field ${path14}: expected ${formatIssueExpected(issue2)}, got ${formatActualValue(getPathValue(input,issue2.path))}`)}return rendered}function buildPrReviewContractCard(){let{reviewer,critic}=PR_REVIEW_VERDICT_ROW_DESCRIPTORS,positiveReviewer=encodePrReviewVerdictRow("reviewer",[reviewer.marker,"C-1","CONFIRMED","STRUCTURALLY_PROVEN","HIGH","YES","src/index.ts:1","rationale with | pipe","probe with \\ backslash","reviewer notes"]),positiveCritic=encodePrReviewVerdictRow("critic",[critic.marker,"C-1","UPHELD","HIGH",`rationale with
192
+ `),!0}catch(error49){return warn(`[background] reservation write failed: ${error49 instanceof Error?error49.message:String(error49)}`),!1}}function reservationOwnerKey(input){return input.planTaskId===null?`call:${input.parentSessionId}:${input.callID}`:`task:${input.parentSessionId}:${input.planTaskId}`}function isActiveCoderOwner(record2){if(record2.normalizedAgent!=="coder"||record2.status==="consumed")return!1;if(record2.status==="pending"||record2.status==="running"||record2.status==="completed"||record2.status==="ingestion_error")return!0;if(record2.coderSettlement?.state==="preserved")return!0;return record2.worktree!==void 0}async function scanDurableCoderOwners(directory){let fallbackScan=await scanDelegationFallbacksForRecovery(directory);if(fallbackScan.status==="uncertain")return fallbackScan;let primaryScan=scanDelegationsForRecovery(directory);if(primaryScan.status==="uncertain")return primaryScan;let recordsByCorrelation=new Map;for(let artifact of fallbackScan.owners)recordsByCorrelation.set(artifact.correlationId,artifact.record);let primaryByCorrelation=new Map,primaryByReservationId=new Map;for(let record2 of primaryScan.owners){if(primaryByCorrelation.set(record2.correlationId,record2),record2.coderReservationId){let owners=primaryByReservationId.get(record2.coderReservationId)??[];owners.push(record2),primaryByReservationId.set(record2.coderReservationId,owners)}recordsByCorrelation.set(record2.correlationId,record2)}return{status:"ok",recordsByCorrelation,primaryByCorrelation,primaryByReservationId}}function exactReservationOwnerCoordinates(reservation,record2){return record2.coderReservationId===reservation.reservationId&&record2.parentSessionId===reservation.parentSessionId&&record2.planTaskId===reservation.planTaskId&&record2.callID===reservation.callID}function exactReservationRecordMatch(reservation,record2){return exactReservationOwnerCoordinates(reservation,record2)&&record2.correlationId===reservation.correlationId}function findExactPrimaryReservationOwner(reservation,ownerScan){if(reservation.correlationId!==null){let primary=ownerScan.primaryByCorrelation.get(reservation.correlationId);return primary&&exactReservationRecordMatch(reservation,primary)?primary:null}let exactOwners=(ownerScan.primaryByReservationId.get(reservation.reservationId)??[]).filter((record2)=>exactReservationOwnerCoordinates(reservation,record2));return exactOwners.length===1?exactOwners[0]:null}function hasProvenReleasedReservationOwner(record2){if(record2.status==="consumed")return!0;return record2.worktree===void 0&&(record2.status==="error"||record2.status==="cancelled")&&record2.terminalResult?.status===record2.status}function validateReservationIdentity(input){return typeof input.parentSessionId==="string"&&input.parentSessionId.length>0&&input.parentSessionId.length<=256&&input.parentSessionId.trim()===input.parentSessionId&&typeof input.callID==="string"&&input.callID.length>0&&input.callID.length<=256&&input.callID.trim()===input.callID&&(input.planTaskId===null||typeof input.planTaskId==="string"&&input.planTaskId.length>0&&input.planTaskId.length<=256&&input.planTaskId.trim()===input.planTaskId)}async function reserveBackgroundCoderSlot(directory,input){if(!validateReservationIdentity(input)||!Number.isInteger(input.maxConcurrent)||input.maxConcurrent<1||input.maxConcurrent>64||(input.occupiedTaskIds?.length??0)>64||!isValidReservationGeneration(input.generation))return{ok:!1,reason:"invalid"};let occupiedTaskIds=new Set;for(let taskId of input.occupiedTaskIds??[]){if(typeof taskId!=="string"||taskId.length===0||taskId.length>256||taskId.trim()!==taskId)return{ok:!1,reason:"invalid"};occupiedTaskIds.add(taskId)}try{return await withEvidenceLock(directory,BACKGROUND_CODER_RESERVATIONS_FILE,STORE_LOCK_AGENT,RESERVATION_LOCK_TASK,async()=>{let reservationScan=scanBackgroundCoderReservationsForAdmission(directory);if(reservationScan.status==="uncertain")return{ok:!1,reason:"uncertain",detail:reservationScan.reason};let ownerScan=await scanDurableCoderOwners(directory);if(ownerScan.status==="uncertain")return{ok:!1,reason:"uncertain",detail:ownerScan.reason};let reservations=reservationScan.reservations.filter((reservation2)=>{let primary=findExactPrimaryReservationOwner(reservation2,ownerScan);return!(primary&&hasProvenReleasedReservationOwner(primary))});if(reservations.length!==reservationScan.reservations.length&&!await writeBackgroundCoderReservations(directory,reservations))return{ok:!1,reason:"uncertain",detail:"finished reservation reconciliation could not be persisted"};let activeOwnerKeys=new Set;for(let taskId of occupiedTaskIds)activeOwnerKeys.add(reservationOwnerKey({parentSessionId:input.parentSessionId,planTaskId:taskId,callID:""}));for(let reservation2 of reservations)if(reservation2.parentSessionId===input.parentSessionId)activeOwnerKeys.add(reservationOwnerKey(reservation2));for(let record2 of ownerScan.recordsByCorrelation.values())if(record2.parentSessionId===input.parentSessionId&&isActiveCoderOwner(record2))activeOwnerKeys.add(reservationOwnerKey({parentSessionId:record2.parentSessionId,planTaskId:record2.planTaskId,callID:record2.callID}));let reservationId=buildBackgroundCoderReservationId(input),existing=reservations.find((reservation2)=>reservation2.reservationId===reservationId);if(existing)return{ok:!1,reason:input.planTaskId===null?"duplicate_call":"duplicate_task",activeCount:activeOwnerKeys.size,existing};let incomingOwnerKey=reservationOwnerKey(input);if(input.planTaskId!==null&&activeOwnerKeys.has(incomingOwnerKey))return{ok:!1,reason:"duplicate_task",activeCount:activeOwnerKeys.size};if(activeOwnerKeys.size>=input.maxConcurrent)return{ok:!1,reason:"capacity",activeCount:activeOwnerKeys.size};if(reservations.length>=MAX_LIVE_BACKGROUND_CODER_RESERVATIONS)return{ok:!1,reason:"capacity",activeCount:activeOwnerKeys.size,detail:"durable reservation store is at its hard safety cap"};let now=input.now??Date.now(),leaseMs=clampReservationLeaseMs(input.leaseMs),reservation={reservationId,parentSessionId:input.parentSessionId,planTaskId:input.planTaskId,callID:input.callID,state:"reserved",correlationId:null,generation:input.generation??1,leaseExpiresAt:now+leaseMs,createdAt:now,updatedAt:now};if(!await writeBackgroundCoderReservations(directory,[...reservations,reservation]))return{ok:!1,reason:"uncertain",detail:"durable reservation claim could not be persisted"};return{ok:!0,reservation,activeCount:activeOwnerKeys.size+1}})}catch(error49){return{ok:!1,reason:"uncertain",detail:`background coder reservation lock failed: ${error49 instanceof Error?error49.message:String(error49)}`}}}async function bindBackgroundCoderReservation(directory,input){if(!validateReservationIdentity(input)||!input.reservationId||!input.correlationId||input.correlationId.length>256||input.correlationId.trim()!==input.correlationId||input.reservationId!==buildBackgroundCoderReservationId(input)||!isValidReservationGeneration(input.generation))return null;try{return await withEvidenceLock(directory,BACKGROUND_CODER_RESERVATIONS_FILE,STORE_LOCK_AGENT,RESERVATION_LOCK_TASK,async()=>{let scan=scanBackgroundCoderReservationsForAdmission(directory);if(scan.status==="uncertain")return null;let index=scan.reservations.findIndex((reservation)=>reservation.reservationId===input.reservationId);if(index<0)return null;let current=scan.reservations[index];if(current.parentSessionId!==input.parentSessionId||current.planTaskId!==input.planTaskId||current.callID!==input.callID)return null;if(current.state==="bound"){if(current.correlationId!==input.correlationId)return null;let now2=input.now??Date.now(),leaseMs2=clampReservationLeaseMs(input.leaseMs),next2={...current,leaseExpiresAt:now2+leaseMs2,updatedAt:now2},reservations2=[...scan.reservations];return reservations2[index]=next2,await writeBackgroundCoderReservations(directory,reservations2)?next2:current}let currentGeneration=current.generation??1;if(input.generation!==void 0&&input.generation<currentGeneration)return null;let now=input.now??Date.now(),leaseMs=clampReservationLeaseMs(input.leaseMs),next={...current,state:"bound",correlationId:input.correlationId,...input.generation!==void 0||current.generation===void 0?{generation:input.generation??currentGeneration}:{},leaseExpiresAt:now+leaseMs,updatedAt:now},reservations=[...scan.reservations];return reservations[index]=next,await writeBackgroundCoderReservations(directory,reservations)?next:null})}catch{return null}}async function releaseBackgroundCoderReservation(directory,input){if(!validateReservationIdentity(input)||!input.reservationId||input.reservationId!==buildBackgroundCoderReservationId(input)||input.correlationId!==null&&(input.correlationId.length===0||input.correlationId.length>256||input.correlationId.trim()!==input.correlationId)||!isValidReservationGeneration(input.generation))return!1;try{return await withEvidenceLock(directory,BACKGROUND_CODER_RESERVATIONS_FILE,STORE_LOCK_AGENT,RESERVATION_LOCK_TASK,async()=>{let scan=scanBackgroundCoderReservationsForAdmission(directory);if(scan.status==="uncertain")return!1;let index=scan.reservations.findIndex((reservation)=>reservation.reservationId===input.reservationId);if(index<0)return!1;let current=scan.reservations[index];if(current.parentSessionId!==input.parentSessionId||current.planTaskId!==input.planTaskId||current.callID!==input.callID||current.correlationId!==input.correlationId)return!1;if(input.generation!==void 0&&current.generation!==void 0&&input.generation!==current.generation)return warn(`[background] refusing reservation release: terminal generation ${input.generation} does not match owned generation ${current.generation} for ${input.reservationId}`),!1;if(input.reason==="consumed"){if(current.state!=="bound"||!current.correlationId)return!1;let ownerScan=await scanDurableCoderOwners(directory);if(ownerScan.status==="uncertain")return!1;let primary=ownerScan.primaryByCorrelation.get(current.correlationId);if(!primary||primary.status!=="consumed"||!exactReservationRecordMatch(current,primary))return!1}let reservations=scan.reservations.filter((_,reservationIndex)=>reservationIndex!==index);return writeBackgroundCoderReservations(directory,reservations)})}catch{return!1}}async function maintainBackgroundDelegations(directory,options={}){let now=options.now??Date.now(),staleTimeoutMs=options.staleTimeoutMs??DEFAULT_STALE_DELEGATION_TIMEOUT_MS,maxRecords=options.maxRecords??DEFAULT_MAINTENANCE_BATCH,lockTimeoutMs=options.lockTimeoutMs??DEFAULT_MAINTENANCE_LOCK_TIMEOUT_MS,reason=options.reason??"manual",result={status:"ok",sweptStale:0,released:[],renewed:[],retained:[],examinedReservations:0},facts=[],emitObservation=(status,failureReason)=>{return appendDelegationMaintenanceObservation(directory,{at:now,status,reason:failureReason,summary:status==="ok"?{sweptStale:result.sweptStale,released:result.released.length,renewed:result.renewed.length,retained:result.retained.length}:void 0,facts}),{...result,status,...failureReason?{reason:failureReason}:{}}};try{result.sweptStale=await withEvidenceLock(directory,BACKGROUND_DELEGATIONS_FILE,STORE_LOCK_AGENT,STORE_LOCK_TASK,async()=>sweepStaleLocked(directory,staleTimeoutMs,now,DEFAULT_SWEEPABLE_DELEGATION_STATUSES,{},{maxSweep:maxRecords}),lockTimeoutMs)}catch(error49){if(error49 instanceof EvidenceLockTimeoutError)return facts.push({at:now,kind:"lock-contention",reason:`maintenance point '${reason}' skipped: delegations store lock contended`}),emitObservation("contention",error49.message);return facts.push({at:now,kind:"maintenance-failure",reason:`maintenance point '${reason}' sweep failed: ${error49 instanceof Error?error49.message:String(error49)}`}),emitObservation("failure",error49 instanceof Error?error49.message:String(error49))}try{await withEvidenceLock(directory,BACKGROUND_CODER_RESERVATIONS_FILE,STORE_LOCK_AGENT,RESERVATION_LOCK_TASK,async()=>{let reservationScan=scanBackgroundCoderReservationsForAdmission(directory);if(reservationScan.status==="uncertain"){result.status="failure",result.reason=reservationScan.reason,facts.push({at:now,kind:"maintenance-failure",reason:`reservation store uncertain: ${reservationScan.reason}`});return}let ownerScan=await scanDurableCoderOwners(directory);if(ownerScan.status==="uncertain"){result.status="failure",result.reason=ownerScan.reason,facts.push({at:now,kind:"maintenance-failure",reason:`owner evidence uncertain; all reservations retained: ${ownerScan.reason}`});return}let batch=reservationScan.reservations.slice(0,maxRecords);result.examinedReservations=batch.length;let next=[],mutated=!1;for(let reservation of batch){let generation=reservation.generation??1,primary=findExactPrimaryReservationOwner(reservation,ownerScan);if(primary&&hasProvenReleasedReservationOwner(primary)){if((primary.generation??1)!==generation){result.retained.push({reservationId:reservation.reservationId,reason:"owner-terminal-older-generation"}),facts.push({at:now,kind:"retained-ambiguity",reservationId:reservation.reservationId,correlationId:reservation.correlationId??void 0,generation,reason:`proven-terminal owner is generation ${primary.generation??1}, reservation owns ${generation}`}),next.push(reservation);continue}mutated=!0,result.released.push({reservationId:reservation.reservationId,generation,reason:"proven-terminal-owner"}),facts.push({at:now,kind:"release",reservationId:reservation.reservationId,correlationId:reservation.correlationId??void 0,generation,reason:"proven-terminal-owner"});continue}if(reservation.leaseExpiresAt===void 0){result.retained.push({reservationId:reservation.reservationId,reason:"protected-legacy-no-lease"}),facts.push({at:now,kind:"retained-protected-legacy",reservationId:reservation.reservationId,generation,reason:"legacy reservation without leaseExpiresAt"}),next.push(reservation);continue}if(!(reservation.leaseExpiresAt<=now)){next.push(reservation);continue}if(primary){if((primary.generation??1)!==generation){result.retained.push({reservationId:reservation.reservationId,reason:"owner-older-generation"}),facts.push({at:now,kind:"retained-ambiguity",reservationId:reservation.reservationId,correlationId:reservation.correlationId??void 0,generation,reason:`owner record is generation ${primary.generation??1}, reservation owns ${generation}`}),next.push(reservation);continue}if(primary.status==="stale"){mutated=!0,result.released.push({reservationId:reservation.reservationId,generation,reason:"owner-swept-stale"}),facts.push({at:now,kind:"release",reservationId:reservation.reservationId,correlationId:reservation.correlationId??void 0,generation,reason:"owner record durably stale"});continue}if(isActiveCoderOwner(primary)){mutated=!0,result.renewed.push({reservationId:reservation.reservationId,generation}),facts.push({at:now,kind:"lease-renewed",reservationId:reservation.reservationId,correlationId:reservation.correlationId??void 0,generation,reason:"exact owner record still active"}),next.push({...reservation,leaseExpiresAt:now+BACKGROUND_CODER_RESERVATION_LEASE_MS,updatedAt:now});continue}result.retained.push({reservationId:reservation.reservationId,reason:"owner-terminal-unproven"}),facts.push({at:now,kind:"retained-ambiguity",reservationId:reservation.reservationId,correlationId:reservation.correlationId??void 0,generation,reason:`owner status '${primary.status}' does not prove release`}),next.push(reservation);continue}if(reservation.correlationId!==null&&ownerScan.recordsByCorrelation.has(reservation.correlationId)){result.retained.push({reservationId:reservation.reservationId,reason:"owner-identity-mismatch"}),facts.push({at:now,kind:"retained-ambiguity",reservationId:reservation.reservationId,correlationId:reservation.correlationId??void 0,generation,reason:"correlation exists under a different owner identity"}),next.push(reservation);continue}if(now-reservation.createdAt>staleTimeoutMs){mutated=!0,result.released.push({reservationId:reservation.reservationId,generation,reason:"unbound-orphan"}),facts.push({at:now,kind:"release",reservationId:reservation.reservationId,generation,reason:"no durable owner anywhere and pre-launch window exceeded"});continue}result.retained.push({reservationId:reservation.reservationId,reason:"unbound-within-stale-window"}),facts.push({at:now,kind:"retained-ambiguity",reservationId:reservation.reservationId,generation,reason:"no owner record yet; still inside the pre-launch stale window"}),next.push(reservation)}if(next.push(...reservationScan.reservations.slice(maxRecords)),mutated){if(!await writeBackgroundCoderReservations(directory,next))result.status="failure",result.reason="reservation reconciliation could not be persisted",facts.push({at:now,kind:"maintenance-failure",reason:"reservation store write failed during reconciliation"})}},lockTimeoutMs)}catch(error49){if(error49 instanceof EvidenceLockTimeoutError)return facts.push({at:now,kind:"lock-contention",reason:`maintenance point '${reason}' skipped: reservation store lock contended`}),emitObservation("contention",error49.message);return facts.push({at:now,kind:"maintenance-failure",reason:`maintenance point '${reason}' reconciliation failed: ${error49 instanceof Error?error49.message:String(error49)}`}),emitObservation("failure",error49 instanceof Error?error49.message:String(error49))}if(result.status==="failure")return emitObservation("failure",result.reason);return emitObservation("ok")}var BACKGROUND_DELEGATIONS_FILE="background-delegations.jsonl",BACKGROUND_DELEGATION_FALLBACK_DIR="background-delegation-fallback",BACKGROUND_CODER_RESERVATIONS_FILE="background-coder-reservations.json",BACKGROUND_DELEGATIONS_CHECKPOINT_FILE="background-delegations.checkpoint.json",BACKGROUND_DELEGATIONS_MANIFEST_FILE="background-delegations.manifest.json",MAX_LIVE_BACKGROUND_FALLBACKS=256,MAX_LIVE_BACKGROUND_CODER_RESERVATIONS=256,MAX_BACKGROUND_OBSERVED_FILES=5000,MAX_BACKGROUND_ADVISORY_CHARS=4000,MAX_BACKGROUND_DELEGATION_GENERATION=1e6,MAX_RECOVERY_FALLBACK_BYTES=1048576,DELEGATION_COMPACTION_LOW_WATER_BYTES=262144,DELEGATION_COMPACTION_HIGH_WATER_BYTES=1048576,MAX_CHECKPOINT_BYTES=2097152,CHECKPOINT_SELECTION_RESERVE_BYTES=65536,MAX_CHECKPOINT_RECORDS=2048,TOMBSTONE_MIN_AGE_MS=259200000,STORE_LOCK_AGENT="background",STORE_LOCK_TASK="background-delegations",FALLBACK_LOCK_TASK="background-delegation-fallback",RESERVATION_LOCK_TASK="background-coder-reservations",ADVISORY_PREPARE_LEASE_MS=30000,INGESTION_CLAIM_LEASE_MS=30000,BACKGROUND_INGESTION_LEASE_MS=30000,BACKGROUND_CODER_RESERVATION_LEASE_MS=900000,BACKGROUND_CODER_RESERVATION_LEASE_MAX_MS=3600000,BACKGROUND_CODER_RESERVATION_LEASE_MIN_MS=60000,DEFAULT_STALE_DELEGATION_TIMEOUT_MS=1800000,DEFAULT_SWEEPABLE_DELEGATION_STATUSES,WorkflowLaneRecoverySchema,ResultSchema,WorkspaceSchema,TaskChangeContextSchema,WorktreeDescriptorSchema,TerminalResultSchema,NormalizedObservedFileSchema,SettlementProvenanceSchema,SettlementOutcomeSchema,CoderSettlementSchema,AdvisoryPreparationSchema,AdvisoryInboxSchema,DelegationIngestionSchema,BackgroundCoderReservationSchema,BackgroundCoderReservationStoreSchema,PromptSchema,RecordSchema,FallbackArtifactSchema,SHA256_HEX,CheckpointSchema,ManifestSchema,WRITER_ID,_checkpointInternals,CHECKPOINT_REBIND_HINT="remove .swarm/background-delegations.manifest.json (manifest only) after verifying no in-flight background delegations; recovery then falls back to the full-ledger read. Only if you also want to discard pre-cut closed summaries and audit history — which for a compacted (rolled) ledger exist ONLY in .swarm/background-delegations.checkpoint.json — remove the checkpoint too or use the full reset below",CHECKPOINT_RESET_HINT="the rolled tail no longer carries pre-checkpoint state: stop swarm processes, verify no in-flight background delegations, and remove .swarm/background-delegations.manifest.json, .swarm/background-delegations.checkpoint.json, and .swarm/background-delegations.jsonl to reset the store (or restore them from backup)",MAX_BACKGROUND_CODER_RESERVATION_STORE_BYTES=2097152,DEFAULT_MAINTENANCE_LOCK_TIMEOUT_MS=5000,DEFAULT_MAINTENANCE_BATCH=256;var init_pending_delegations=__esm(()=>{init_zod();init_lock();init_utils2();init_bun_compat();init_logger();init_delegation_health();init_pr_review_collection_receipt();init_delegation_health();init_delegation_health();DEFAULT_SWEEPABLE_DELEGATION_STATUSES=new Set(["pending","running","ingestion_error"]),WorkflowLaneRecoverySchema=exports_external.object({workflowLane:exports_external.string(),kind:exports_external.enum(["legacy-verdict-row-recovery","parser-normalization","parser-row-recovery","truncated-preview-durable-artifact","transcript-incomplete-terminal-candidate","clean-attestation-salvaged"]),reason:exports_external.string()}).strict(),ResultSchema=exports_external.object({text:exports_external.string().optional(),error:exports_external.string().optional(),chars:exports_external.number(),truncated:exports_external.boolean(),digest:exports_external.string(),outputRef:exports_external.string().optional(),outputPreviewChars:exports_external.number().optional(),outputDegraded:exports_external.boolean().optional(),outputArtifactError:exports_external.string().optional(),transcriptIncomplete:exports_external.boolean().optional(),messageCount:exports_external.number().optional(),salvagedWorkflowLanes:exports_external.array(exports_external.string()).optional(),salvagedWorkflowLaneRecoveries:exports_external.array(WorkflowLaneRecoverySchema).optional()}).strict(),WorkspaceSchema=exports_external.object({directory:exports_external.string(),gitHead:exports_external.string().nullable(),dirtyHash:exports_external.string().nullable(),changedFiles:exports_external.array(exports_external.string()).nullable().optional(),prHeadSha:exports_external.string().nullable(),scope:exports_external.string().nullable()}).strict(),TaskChangeContextSchema=exports_external.object({declaredFiles:exports_external.array(exports_external.string()).nullable(),baseline:WorkspaceSchema,workflowGeneration:exports_external.number().int().nonnegative().optional()}).strict(),WorktreeDescriptorSchema=exports_external.object({callID:exports_external.string().min(1).max(256),parentSessionId:exports_external.string().min(1).max(256),taskId:exports_external.string().min(1).max(256),planTaskId:exports_external.string().min(1).max(256).nullable(),worktreePath:exports_external.string().min(1).max(4096),branchName:exports_external.string().min(1).max(1024),worktreeId:exports_external.string().min(1).max(256),worktreeSessionId:exports_external.string().min(1).max(256),mergeStrategy:exports_external.enum(["merge","rebase","cherry-pick"]),laneIndex:exports_external.number().int().nonnegative().max(255),worktreeDir:exports_external.string().min(1).max(4096).nullable()}).strict(),TerminalResultSchema=exports_external.object({eventId:exports_external.string().min(1).max(256),status:exports_external.enum(["completed","error","cancelled"]),recordedAt:exports_external.number().int().nonnegative(),result:ResultSchema}).strict(),NormalizedObservedFileSchema=exports_external.string().min(1).max(4096).refine((value)=>normalizeObservedFile(value)===value),SettlementProvenanceSchema=exports_external.object({correlationId:exports_external.string().min(1).max(256),parentSessionId:exports_external.string().min(1).max(256),callID:exports_external.string().max(256),planTaskId:exports_external.string().min(1).max(256).nullable(),baseline:WorkspaceSchema,worktree:WorktreeDescriptorSchema.nullable()}).strict(),SettlementOutcomeSchema=exports_external.object({kind:exports_external.enum(["shared-root","standard-worktree"]),result:exports_external.enum(["ready","merged","unchanged","partial","failed"]),reason:exports_external.string().min(1).max(2000).optional(),sourceHeadAfterCommit:exports_external.string().min(1).max(256).nullable().optional(),targetHeadBeforeMerge:exports_external.string().min(1).max(256).nullable().optional(),targetHeadAfterMerge:exports_external.string().min(1).max(256).nullable().optional()}).strict(),CoderSettlementSchema=exports_external.object({state:exports_external.enum(["pending","settling","settled","preserved"]),provenance:SettlementProvenanceSchema,operationId:exports_external.string().min(1).max(256).optional(),sourceHeadAfterCommit:exports_external.string().min(1).max(256).nullable().optional(),targetHeadBeforeMerge:exports_external.string().min(1).max(256).nullable().optional(),observedFiles:exports_external.array(NormalizedObservedFileSchema).max(MAX_BACKGROUND_OBSERVED_FILES).nullable(),outcome:SettlementOutcomeSchema.optional(),updatedAt:exports_external.number().int().nonnegative()}).strict().superRefine((value,context)=>{if(value.state!=="pending"&&!value.operationId)context.addIssue({code:exports_external.ZodIssueCode.custom,message:"settling, settled, and preserved states require operationId"});if((value.state==="settled"||value.state==="preserved")&&!value.outcome)context.addIssue({code:exports_external.ZodIssueCode.custom,message:"terminal settlement state requires outcome"})}),AdvisoryPreparationSchema=exports_external.object({id:exports_external.string().min(1).max(256),preparedAt:exports_external.number().int().nonnegative(),leaseExpiresAt:exports_external.number().int().nonnegative()}).strict(),AdvisoryInboxSchema=exports_external.object({eventId:exports_external.string().min(1).max(256),parentSessionId:exports_external.string().min(1).max(256),state:exports_external.enum(["pending","delivered"]),message:exports_external.string().min(1).max(MAX_BACKGROUND_ADVISORY_CHARS),createdAt:exports_external.number().int().nonnegative(),preparation:AdvisoryPreparationSchema.optional(),deliveredAt:exports_external.number().int().nonnegative().optional()}).strict().superRefine((value,context)=>{if(value.state==="delivered"&&value.deliveredAt===void 0)context.addIssue({code:exports_external.ZodIssueCode.custom,message:"delivered advisory requires deliveredAt"});if(value.state==="delivered"&&value.preparation!==void 0)context.addIssue({code:exports_external.ZodIssueCode.custom,message:"delivered advisory cannot retain a preparation lease"})}),DelegationIngestionSchema=exports_external.object({state:exports_external.enum(["claimed","retryable","consumed"]),attempt:exports_external.number().int().positive(),updatedAt:exports_external.number().int().nonnegative(),claimToken:exports_external.string().min(1).max(256),leaseExpiresAt:exports_external.number().int().nonnegative().optional()}).strict().superRefine((value,context)=>{if(value.state==="claimed"&&value.leaseExpiresAt===void 0)context.addIssue({code:exports_external.ZodIssueCode.custom,message:"claimed ingestion requires a lease expiry"});if(value.state!=="claimed"&&value.leaseExpiresAt!==void 0)context.addIssue({code:exports_external.ZodIssueCode.custom,message:"completed ingestion cannot retain a claim lease"})}),BackgroundCoderReservationSchema=exports_external.object({reservationId:exports_external.string().min(1).max(256),parentSessionId:exports_external.string().min(1).max(256),planTaskId:exports_external.string().min(1).max(256).nullable(),callID:exports_external.string().min(1).max(256),state:exports_external.enum(["reserved","bound"]),correlationId:exports_external.string().min(1).max(256).nullable(),generation:exports_external.number().int().min(1).max(MAX_BACKGROUND_DELEGATION_GENERATION).optional(),leaseExpiresAt:exports_external.number().int().nonnegative().optional(),createdAt:exports_external.number().int().nonnegative(),updatedAt:exports_external.number().int().nonnegative()}).strict().superRefine((value,context)=>{if(value.state==="reserved"&&value.correlationId!==null)context.addIssue({code:exports_external.ZodIssueCode.custom,message:"unbound reservation cannot have a correlationId"});if(value.state==="bound"&&value.correlationId===null)context.addIssue({code:exports_external.ZodIssueCode.custom,message:"bound reservation requires a correlationId"})}),BackgroundCoderReservationStoreSchema=exports_external.object({schemaVersion:exports_external.literal(1),reservations:exports_external.array(BackgroundCoderReservationSchema).max(MAX_LIVE_BACKGROUND_CODER_RESERVATIONS)}).strict().superRefine((value,context)=>{let ids=new Set;for(let reservation of value.reservations){if(ids.has(reservation.reservationId)){context.addIssue({code:exports_external.ZodIssueCode.custom,message:"duplicate reservationId"});return}if(reservation.reservationId!==buildBackgroundCoderReservationId({parentSessionId:reservation.parentSessionId,planTaskId:reservation.planTaskId,callID:reservation.callID})){context.addIssue({code:exports_external.ZodIssueCode.custom,message:"reservationId does not match owner identity"});return}ids.add(reservation.reservationId)}}),PromptSchema=exports_external.object({text:exports_external.string(),chars:exports_external.number(),truncated:exports_external.boolean(),digest:exports_external.string()}).strict(),RecordSchema=exports_external.object({schemaVersion:exports_external.union([exports_external.literal(1),exports_external.literal(2),exports_external.literal(3)]),correlationId:exports_external.string().min(1),jobId:exports_external.string().nullable(),subagentSessionId:exports_external.string().min(1),parentSessionId:exports_external.string().min(1),callID:exports_external.string(),normalizedAgent:exports_external.string(),swarmPrefixedAgent:exports_external.string(),planTaskId:exports_external.string().nullable(),evidenceTaskId:exports_external.string().nullable(),status:exports_external.enum(["pending","running","ingestion_error","completed","error","cancelled","stale","consumed"]),createdAt:exports_external.number(),updatedAt:exports_external.number(),batchId:exports_external.string().optional(),laneId:exports_external.string().optional(),mode:exports_external.string().optional(),workflowLane:exports_external.string().optional(),ownedWorkflowLanes:exports_external.array(exports_external.string().min(1).max(120)).min(1).max(11).optional(),promptHash:exports_external.string().optional(),workspace:WorkspaceSchema.optional(),taskChangeContext:TaskChangeContextSchema.optional(),workflowGeneration:exports_external.number().int().nonnegative().optional(),worktree:WorktreeDescriptorSchema.optional(),coderReservationId:exports_external.string().min(1).max(256).optional(),prompt:PromptSchema.optional(),generation:exports_external.number().int().positive().max(MAX_BACKGROUND_DELEGATION_GENERATION).optional(),terminalResult:TerminalResultSchema.optional(),coderSettlement:CoderSettlementSchema.optional(),advisoryInbox:AdvisoryInboxSchema.optional(),ingestion:DelegationIngestionSchema.optional(),result:ResultSchema.optional(),completedAt:exports_external.number().optional()}).strict(),FallbackArtifactSchema=exports_external.object({schemaVersion:exports_external.literal(1),correlationId:exports_external.string().min(1).max(256),createdAt:exports_external.number().int().nonnegative(),record:RecordSchema}).strict().superRefine((value,context)=>{if(value.record.correlationId!==value.correlationId||value.record.subagentSessionId!==value.correlationId||value.record.status!=="pending")context.addIssue({code:exports_external.ZodIssueCode.custom,message:"fallback identity/status does not match its pending record"})});SHA256_HEX=/^[0-9a-f]{64}$/,CheckpointSchema=exports_external.object({schemaVersion:exports_external.literal(1),sequence:exports_external.number().int().positive(),writerId:exports_external.string().min(1).max(128),rootPath:exports_external.string().min(1).max(4096),createdAt:exports_external.number().int().nonnegative(),cutLedgerBytes:exports_external.number().int().nonnegative(),cutLedgerDigest:exports_external.string().regex(SHA256_HEX),records:exports_external.array(RecordSchema).max(MAX_CHECKPOINT_RECORDS),closed:exports_external.array(RecordSchema),audit:DelegationCheckpointAuditSchema,payloadChecksum:exports_external.string().regex(SHA256_HEX)}).strict(),ManifestSchema=exports_external.object({schemaVersion:exports_external.literal(1),sequence:exports_external.number().int().positive(),checkpointChecksum:exports_external.string().regex(SHA256_HEX),writerId:exports_external.string().min(1).max(128),rootPath:exports_external.string().min(1).max(4096),updatedAt:exports_external.number().int().nonnegative()}).strict(),WRITER_ID=`w-${process.pid}-${Math.random().toString(36).slice(2,10)}`,_checkpointInternals={renameWithRetry:(from,to)=>{let lastError;for(let attempt=0;attempt<5;attempt++)try{_checkpointInternals.renameOnce(from,to);return}catch(err){lastError=err;let code=err.code;if(code!=="EEXIST"&&code!=="EBUSY"&&code!=="EPERM")throw err;_checkpointInternals.syncSleep(15)}throw lastError},renameOnce:(from,to)=>{fs9.renameSync(from,to)},syncSleep:(ms)=>{try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,ms)}catch{let start=Date.now();while(Date.now()-start<ms);}}}});function serializedPrReviewArtifactInputBytes(value){return new TextEncoder().encode(JSON.stringify(value)).byteLength}function quoted(value){return`"${value}"`}function formatEnum(values){return values.map((value)=>quoted(value)).join(" | ")}function getPathValue(input,path14){let current=input;for(let segment of path14){if(current===null||current===void 0)return;if(typeof segment==="number"){if(!Array.isArray(current))return;current=current[segment];continue}if(typeof segment==="symbol"||typeof current!=="object")return;current=current[segment]}return current}function formatActualValue(value){if(value===void 0)return"(omitted)";if(typeof value==="string")return quoted(value);try{let json2=JSON.stringify(value);if(!json2)return String(value);return json2.length<=160?json2:`${json2.slice(0,157)}...`}catch{return String(value)}}function formatIssueExpected(issue2){if(issue2.code==="invalid_value"&&"values"in issue2)return formatEnum(issue2.values);if(issue2.code==="invalid_type")return`${issue2.expected}`;if(issue2.code==="too_small"&&issue2.minimum===1)return"a non-empty value";return issue2.message}function formatPrReviewValidationIssues(issues,input){let rendered=[];for(let issue2 of issues){if(issue2.code==="unrecognized_keys"){let parent=getPathValue(input,issue2.path);for(let key of issue2.keys){let parentPath=issue2.path.map(String),value=parent&&typeof parent==="object"?parent[key]:void 0;rendered.push(`field ${[...parentPath,key].join(".")}: expected no unknown key, got ${formatActualValue(value)}`)}continue}let path14=issue2.path.length>0?issue2.path.map(String).join("."):"(root)";rendered.push(`field ${path14}: expected ${formatIssueExpected(issue2)}, got ${formatActualValue(getPathValue(input,issue2.path))}`)}return rendered}function buildPrReviewContractCard(){let{reviewer,critic}=PR_REVIEW_VERDICT_ROW_DESCRIPTORS,positiveReviewer=encodePrReviewVerdictRow("reviewer",[reviewer.marker,"C-1","CONFIRMED","STRUCTURALLY_PROVEN","HIGH","YES","src/index.ts:1","rationale with | pipe","probe with \\ backslash","reviewer notes"]),positiveCritic=encodePrReviewVerdictRow("critic",[critic.marker,"C-1","UPHELD","HIGH",`rationale with
193
193
  line break`,"required change with\rcarriage return"]),discardedReviewer=encodePrReviewVerdictRow("reviewer",[reviewer.marker,PR_REVIEW_DISCARDED_EXAMPLE_ITEM_ID,"DISPROVED","STRUCTURALLY_PROVEN","NONE","YES","src/example.ts:1","illustrative only","not routable","not routable"]),discardedCritic=encodePrReviewVerdictRow("critic",[critic.marker,PR_REVIEW_DISCARDED_EXAMPLE_ITEM_ID,"DISPROVED","NONE","illustrative only","not routable"]);return[PR_REVIEW_CONTRACT_CARD_HEADER,"Live markers:",`REVIEWED row: ${reviewer.fieldRoles.map((role,index)=>index===0?reviewer.marker:role).join(" | ")}`,`REVIEWED classifications: ${PR_REVIEW_REVIEWER_CLASSIFICATIONS.join(", ")}`,`REVIEWED evidence types: ${PR_REVIEW_REVIEWER_EVIDENCE_TYPES.join(", ")}`,`REVIEWED severities: ${PR_REVIEW_SEVERITIES.join(", ")}`,`CRITIC row: ${critic.fieldRoles.map((role,index)=>index===0?critic.marker:role).join(" | ")}`,`CRITIC statuses: ${PR_REVIEW_CRITIC_STATUSES.join(", ")}`,`CRITIC severities: ${PR_REVIEW_SEVERITIES.join(", ")}`,"Escapes inside free-text fields only: \\\\ => backslash, \\| => literal pipe, \\n => newline, \\r => carriage return","Literal backslash before a real delimiter must be written as \\\\| (backslash, then delimiter).","DISCOVERY and FEEDBACK rows keep their existing row grammars; this card governs REVIEWED and CRITIC rows only.",`Positive REVIEWED example: ${positiveReviewer}`,`Positive CRITIC example: ${positiveCritic}`,`DISCARDED REVIEWED EXAMPLE: ${discardedReviewer}`,`DISCARDED CRITIC EXAMPLE: ${discardedCritic}`,"Routing rules:","- Emit exactly one live REVIEWED row per assigned item in reviewer lanes.","- Emit exactly one live CRITIC row per assigned item in critic lanes.","- DISPROVED requires severity NONE.","- NEEDS_MORE_EVIDENCE is not a terminal critic transport row.","- DISCARDED examples above are documentation only; they are not routable live rows.","Defaults and ownership:","- assigned_item_ids and workflow_lane come only from the controller block.","- Omit no assigned row; emit no row for an unassigned or discarded example ID.","- A settled lane is immutable and is never reprocessed on later collection.","Transition matrix:","- reviewer lane: assigned item -> exactly one REVIEWED row -> critic routing or terminal disposition.","- critic lane: assigned reviewer claim -> exactly one CRITIC row -> final finding disposition.","- malformed, duplicate, missing, or discarded rows -> contract failure and bounded retry; never acceptance.","Retry and deadline semantics:","- Malformed live rows fail closed and may be retried only within the controller retry bound.","- A waited collection deadline terminalizes active lanes as error after bounded partial salvage.","- Partial discovery salvage never turns an incomplete REVIEWED or CRITIC verdict into acceptance."].join(`
194
194
  `)}function encodePrReviewVerdictField(value){return value.replace(/\\/g,"\\\\").replace(/\|/g,"\\|").replace(/\n/g,"\\n").replace(/\r/g,"\\r")}function encodePrReviewVerdictRow(kind,fields){let descriptor=PR_REVIEW_VERDICT_ROW_DESCRIPTORS[kind],parsed=descriptor.schema.safeParse(fields);if(!parsed.success)throw Error(`${kind} verdict row requires ${descriptor.fieldCount} schema-valid fields beginning with ${descriptor.marker}: ${formatPrReviewValidationIssues(parsed.error.issues,fields).join("; ")}`);return parsed.data.map(encodePrReviewVerdictField).join(" | ")}function parsePrReviewVerdictRow(line,kind){let descriptor=PR_REVIEW_VERDICT_ROW_DESCRIPTORS[kind],fields=[],current="",usedCanonicalEscape=!1;for(let index=0;index<line.length;index++){let char=line[index];if(char==="\\"){let next=line[index+1];if(next==="\\"){current+="\\",usedCanonicalEscape=!0,index++;continue}if(next==="|"){current+="|",usedCanonicalEscape=!0,index++;continue}if(next==="n"){current+=`
195
195
  `,usedCanonicalEscape=!0,index++;continue}if(next==="r"){current+="\r",usedCanonicalEscape=!0,index++;continue}current+="\\";continue}if(char==="|"){fields.push(current.trim()),current="";continue}current+=char}if(fields.push(current.trim()),fields[0]!==descriptor.marker)return null;if(fields.length>descriptor.fieldCount){let retained=fields.slice(0,descriptor.fieldCount-1);return retained.push(fields.slice(descriptor.fieldCount-1).join("|")),{marker:descriptor.marker,fields:retained,recoveredOverflow:!0,overflowClass:fields.length===descriptor.fieldCount+1&&fields[fields.length-1]===""?"legacy-fidelity-safe":"legacy-lossy"}}return{marker:descriptor.marker,fields,recoveredOverflow:!1,overflowClass:fields.length===descriptor.fieldCount?usedCanonicalEscape?"canonical":"legacy-fidelity-safe":"legacy-lossy"}}function formatPrReviewRuntimeFieldError(field,expected,got){return`field ${field}: expected ${expected}, got ${formatActualValue(got)}`}function pad(value,width){return`${value}`.padStart(width,"0")}function generatePrReviewRunId(now=new Date){return`pr-review-${now.getUTCFullYear()}${pad(now.getUTCMonth()+1,2)}${pad(now.getUTCDate(),2)}${pad(now.getUTCHours(),2)}${pad(now.getUTCMinutes(),2)}${pad(now.getUTCSeconds(),2)}${pad(now.getUTCMilliseconds(),3)}`}var PR_REVIEW_REVIEWER_CLASSIFICATIONS,PR_REVIEW_REVIEWER_EVIDENCE_TYPES,PR_REVIEW_SEVERITIES,PR_REVIEW_CRITIC_STATUSES,PR_REVIEW_FINDING_STATUSES,PR_REVIEW_FINDING_ACTIONS,PR_REVIEW_ARTIFACT_BOUNDARIES,PR_REVIEW_CONTRACT_CARD_HEADER="[PR-REVIEW CONTRACT CARD]",PR_REVIEW_FINDINGS_MAX_BYTES=10485760,PR_REVIEW_FINDINGS_WRITE_MAX_BYTES=3145728,PR_REVIEW_HANDOFF_MAX_BYTES=131072,PR_REVIEW_HANDOFF_WRITE_MAX_BYTES=122880,PR_REVIEW_DISCARDED_EXAMPLE_ITEM_ID="discarded-id",PrReviewRunIdSchema,PrReviewFindingSchema,PrReviewHandoffSchema,WritePrReviewArtifactArgsSchema,introducedByPrSchema,PrReviewReviewerVerdictFieldsSchema,PrReviewCriticVerdictFieldsSchema,PR_REVIEW_VERDICT_ROW_DESCRIPTORS;var init_pr_review_contract=__esm(()=>{init_zod();PR_REVIEW_REVIEWER_CLASSIFICATIONS=["CONFIRMED","DISPROVED","UNVERIFIED","PRE_EXISTING"],PR_REVIEW_REVIEWER_EVIDENCE_TYPES=["STRUCTURALLY_PROVEN","EXECUTION_PROVEN","STATIC_TRACE_PROVEN","PLAUSIBLE_BUT_UNVERIFIED"],PR_REVIEW_SEVERITIES=["CRITICAL","HIGH","MEDIUM","LOW","INFO","NONE"],PR_REVIEW_CRITIC_STATUSES=["UPHELD","DOWNGRADED","DISPROVED","NEEDS_MORE_EVIDENCE"],PR_REVIEW_FINDING_STATUSES=["PENDING","CONFIRMED","DISPROVED","PRE_EXISTING"],PR_REVIEW_FINDING_ACTIONS=["route_to_reviewer","route_to_critic","report","suppress_with_reason","handoff_to_feedback"],PR_REVIEW_ARTIFACT_BOUNDARIES=["post_explorer","post_reviewer","post_critic"];PrReviewRunIdSchema=exports_external.string().regex(/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/,"run_id must be a safe relative identifier"),PrReviewFindingSchema=exports_external.object({finding_id:exports_external.string().trim().min(1).max(128),status:exports_external.enum(PR_REVIEW_FINDING_STATUSES),file_line:exports_external.string().trim().min(1).max(1000),evidence:exports_external.string().trim().min(1).max(20000),next_action:exports_external.enum(PR_REVIEW_FINDING_ACTIONS),severity:exports_external.enum(PR_REVIEW_SEVERITIES).optional(),category:exports_external.string().trim().min(1).max(128).optional()}).strict(),PrReviewHandoffSchema=exports_external.object({pr_url:exports_external.string().url().max(2000),finding_ids:exports_external.array(exports_external.string().trim().min(1).max(128)).min(1).max(1000),summary:exports_external.string().trim().min(1).max(20000),provenance:exports_external.array(exports_external.string().trim().min(1).max(4000)).min(1).max(1000)}).strict(),WritePrReviewArtifactArgsSchema=exports_external.discriminatedUnion("kind",[exports_external.object({kind:exports_external.literal("findings"),run_id:PrReviewRunIdSchema.optional(),pr_head_sha:exports_external.string().trim().regex(/^[0-9a-f]{6,64}$/i),boundary:exports_external.enum(PR_REVIEW_ARTIFACT_BOUNDARIES),records:exports_external.array(PrReviewFindingSchema).min(1).max(1000)}).strict(),exports_external.object({kind:exports_external.literal("handoff"),run_id:PrReviewRunIdSchema.optional(),pr_head_sha:exports_external.string().trim().regex(/^[0-9a-f]{6,64}$/i),handoff:PrReviewHandoffSchema}).strict()]).superRefine((value,ctx)=>{let bytes=serializedPrReviewArtifactInputBytes(value),maxBytes=value.kind==="findings"?PR_REVIEW_FINDINGS_WRITE_MAX_BYTES:PR_REVIEW_HANDOFF_WRITE_MAX_BYTES;if(bytes>maxBytes)ctx.addIssue({code:"custom",path:[value.kind==="findings"?"records":"handoff"],message:`serialized UTF-8 payload must be at most ${maxBytes} bytes (got ${bytes})`})}),introducedByPrSchema=exports_external.string().regex(/^(?:introduced_by_pr\s*:\s*)?(?:YES|NO|UNKNOWN)$/i),PrReviewReviewerVerdictFieldsSchema=exports_external.tuple([exports_external.literal("[REVIEWED]"),exports_external.string().min(1),exports_external.enum(PR_REVIEW_REVIEWER_CLASSIFICATIONS),exports_external.enum(PR_REVIEW_REVIEWER_EVIDENCE_TYPES),exports_external.enum(PR_REVIEW_SEVERITIES),introducedByPrSchema,exports_external.string().min(1),exports_external.string().min(8),exports_external.string().min(5),exports_external.string().min(3)]).superRefine((fields,ctx)=>{if(fields[2]==="DISPROVED"&&fields[4]!=="NONE")ctx.addIssue({code:"custom",path:[4],message:"DISPROVED reviewer severity must be NONE"})}),PrReviewCriticVerdictFieldsSchema=exports_external.tuple([exports_external.literal("[CRITIC]"),exports_external.string().min(1),exports_external.enum(PR_REVIEW_CRITIC_STATUSES),exports_external.enum(PR_REVIEW_SEVERITIES),exports_external.string().min(6),exports_external.string().min(6)]).superRefine((fields,ctx)=>{let status=fields[2],severity=fields[3];if(status==="NEEDS_MORE_EVIDENCE")ctx.addIssue({code:"custom",path:[2],message:"NEEDS_MORE_EVIDENCE is not a terminal transport verdict"});if(status==="DISPROVED"&&severity!=="NONE")ctx.addIssue({code:"custom",path:[3],message:"DISPROVED critic severity must be NONE"});if(status==="UPHELD"&&!["CRITICAL","HIGH","MEDIUM"].includes(severity))ctx.addIssue({code:"custom",path:[3],message:"UPHELD critic severity must be CRITICAL, HIGH, or MEDIUM"});if(status==="DOWNGRADED"&&severity==="CRITICAL")ctx.addIssue({code:"custom",path:[3],message:"DOWNGRADED critic severity cannot be CRITICAL"})}),PR_REVIEW_VERDICT_ROW_DESCRIPTORS={reviewer:{marker:"[REVIEWED]",fieldCount:10,fieldRoles:["marker","item_id","classification","evidence_type","severity","introduced_by_pr","file:line","rationale","probe","reviewer_notes"],schema:PrReviewReviewerVerdictFieldsSchema},critic:{marker:"[CRITIC]",fieldCount:6,fieldRoles:["marker","item_id","status","severity","rationale","required_change"],schema:PrReviewCriticVerdictFieldsSchema}}});import{createHash as createHash7}from"node:crypto";function rawTriggerIds(input){if(!Array.isArray(input))return null;let ids=[];for(let row of input){if(typeof row!=="object"||row===null)return null;let triggerId=row.trigger_id;if(typeof triggerId!=="string"||!triggerId.trim())return null;ids.push(triggerId.trim())}return ids}function assertExactTriggerIdSet(input){let ids=rawTriggerIds(input);if(!ids)return;let expected=new Set(PR_REVIEW_REQUIRED_TRIGGER_IDS),seen=new Set,duplicate=new Set;for(let id of ids){if(seen.has(id))duplicate.add(id);seen.add(id)}if(duplicate.size>0)throw Error(`duplicate trigger IDs: ${[...duplicate].join(", ")}`);let unknown2=[...seen].filter((id)=>!expected.has(id));if(unknown2.length>0)throw Error(`unknown trigger IDs: ${unknown2.join(", ")}. trigger_id must be one of the 11 mandatory micro-lane IDs: ${[...expected].join(", ")}. Base-lane IDs and mode strings (e.g. swarm-pr-review:base) are NOT trigger IDs.`);let missing=[...expected].filter((id)=>!seen.has(id));if(missing.length>0)throw Error(`missing trigger IDs: ${missing.join(", ")}`)}function assertMatchedRowsHaveProvenance(input){if(!Array.isArray(input))return;for(let row of input){if(typeof row!=="object"||row===null)continue;let value=row;if(value.result!=="MATCHED")continue;if(typeof value.source_batch_id!=="string"||!value.source_batch_id.trim()||typeof value.source_lane_id!=="string"||!value.source_lane_id.trim())throw Error(`MATCHED rows require source_batch_id and source_lane_id: ${String(value.trigger_id??"(missing trigger_id)")}`)}}function assertNoLegacyNoMatchResult(input){if(!Array.isArray(input))return;for(let row of input){if(typeof row!=="object"||row===null)continue;if(row.result==="NO-MATCH")throw Error("NO-MATCH is not a valid PR_REVIEW trigger result; use MATCHED or NOT_TRIGGERED with concrete evidence")}}function exactTriggerRows(rows){let expected=new Set(PR_REVIEW_REQUIRED_TRIGGER_IDS),seen=new Set,duplicate=new Set;for(let row of rows){if(seen.has(row.trigger_id))duplicate.add(row.trigger_id);seen.add(row.trigger_id)}let unknown2=[...seen].filter((id)=>!expected.has(id)),missing=[...expected].filter((id)=>!seen.has(id));if(duplicate.size>0||unknown2.length>0||missing.length>0)throw Error(`PR_REVIEW trigger ledger must be exact; missing: ${missing.join(", ")||"(none)"}; duplicate: ${[...duplicate].join(", ")||"(none)"}; unknown: ${unknown2.join(", ")||"(none)"}`);let byId=new Map(rows.map((row)=>[row.trigger_id,row]));return PR_REVIEW_REQUIRED_TRIGGER_IDS.map((id)=>{let row=byId.get(id);if(!row)throw Error(`missing trigger row: ${id}`);return row})}function summarizeTriggerRows(rows){let orderedRows=exactTriggerRows(rows);if(orderedRows.find((row)=>row.trigger_id==="unclassified-risk")?.result!=="MATCHED")throw Error("PR_REVIEW trigger ledger requires unclassified-risk to remain MATCHED as the fallback family");return{rows:orderedRows,matchedIds:orderedRows.filter((row)=>row.result==="MATCHED").map((row)=>row.trigger_id),notTriggeredIds:orderedRows.filter((row)=>row.result==="NOT_TRIGGERED").map((row)=>row.trigger_id)}}function parseRows(input,schema,label){let parsed=exports_external.array(schema).safeParse(input);if(!parsed.success)throw Error(`${label}: ${parsed.error.issues.map((issue2)=>`${issue2.path.join(".")}: ${issue2.message}`).join("; ")}`);return parsed.data}function validatePrReviewInlineTriggerLedger(input){return assertExactTriggerIdSet(input),assertNoLegacyNoMatchResult(input),summarizeTriggerRows(parseRows(input,PrReviewInlineTriggerRowSchema,"Invalid trigger ledger"))}function validatePrReviewPersistedInputLedger(input){return assertExactTriggerIdSet(input),assertNoLegacyNoMatchResult(input),assertMatchedRowsHaveProvenance(input),summarizeTriggerRows(parseRows(input,PrReviewPersistedInputRowSchema,"Invalid persisted trigger ledger"))}function validatePrReviewWriterInputLedger(input){return assertExactTriggerIdSet(input),assertNoLegacyNoMatchResult(input),assertMatchedRowsHaveProvenance(input),summarizeTriggerRows(parseRows(input,PrReviewWriterInputRowSchema,"Invalid final-writer trigger ledger"))}function assertCanonicalDefinitionFields(rows){let definitions=new Map(PR_REVIEW_TRIGGER_DEFINITIONS.map((definition)=>[definition.id,definition]));for(let row of rows){let definition=definitions.get(row.trigger_id);if(!definition||row.scope!==definition.scope||row.trigger_row!==definition.trigger_row||row.micro_lane!==definition.micro_lane)throw Error(`PR_REVIEW trigger definition drift for ${row.trigger_id}: scope, trigger_row, and micro_lane must match the canonical definition`)}}function dispatchedMicroLaneCount(rows){return new Set(rows.filter((row)=>row.result==="MATCHED").map((row)=>`${row.source_batch_id}\x00${row.source_lane_id}`)).size}function buildPrReviewTriggerReceiptV2(input){let envelope=ReceiptEnvelopeSchema.parse(input),validated=validatePrReviewPersistedInputLedger(input.rows),dispatchedCount=dispatchedMicroLaneCount(validated.rows);if(envelope.dispatched_micro_lane_count!==dispatchedCount)throw Error(`PR_REVIEW trigger receipt dispatched_micro_lane_count is inconsistent: expected ${dispatchedCount}`);let rows=validated.rows.map((row)=>{let definition=PR_REVIEW_TRIGGER_DEFINITIONS.find((candidate)=>candidate.id===row.trigger_id);if(!definition)throw Error(`unknown trigger definition: ${row.trigger_id}`);return{trigger_id:row.trigger_id,scope:definition.scope,trigger_row:definition.trigger_row,micro_lane:definition.micro_lane,result:row.result,evidence:row.evidence,...row.result==="MATCHED"?{source_batch_id:row.source_batch_id,source_lane_id:row.source_lane_id}:{}}});return V2ReceiptSchema.parse({...envelope,schema_version:2,trigger_count:rows.length,matched_count:validated.matchedIds.length,not_triggered_count:validated.notTriggeredIds.length,no_match_count:0,rows,coverage_degradations:input.coverage_degradations??[],...input.base_verification?{base_verification:input.base_verification}:{}})}function prReviewTriggerLedgerDigest(rows){let canonical=rows.map((row)=>[row.trigger_id,row.result,row.evidence]);return createHash7("sha256").update(JSON.stringify(canonical)).digest("hex")}function parsedReceipt(schemaVersion,rows,coverageDegradations=[],baseVerification){return{schemaVersion,rows,matchedRows:rows.filter((row)=>row.result==="MATCHED"),notTriggeredRows:rows.filter((row)=>row.result==="NOT_TRIGGERED"),coverageDegradations,...baseVerification?{baseVerification}:{}}}function parsePrReviewTriggerReceipt(input){if(typeof input!=="object"||input===null)throw Error("PR_REVIEW trigger receipt must be an object");let schemaVersion=input.schema_version;if(schemaVersion===2){let receipt=V2ReceiptSchema.parse(input);assertCanonicalDefinitionFields(receipt.rows);let normalizedRows=receipt.rows.map((row)=>({trigger_id:row.trigger_id,result:row.result,evidence:row.evidence,...row.result==="MATCHED"?{source_batch_id:row.source_batch_id,source_lane_id:row.source_lane_id}:{}})),validated2=validatePrReviewPersistedInputLedger(normalizedRows),counts={trigger_count:validated2.rows.length,matched_count:validated2.matchedIds.length,not_triggered_count:validated2.notTriggeredIds.length,no_match_count:0,dispatched_micro_lane_count:dispatchedMicroLaneCount(validated2.rows)};for(let[field,expected]of Object.entries(counts))if(receipt[field]!==expected)throw Error(`PR_REVIEW trigger receipt ${field} is inconsistent: expected ${expected}`);return parsedReceipt(2,validated2.rows,receipt.coverage_degradations,receipt.base_verification)}if(schemaVersion!==void 0&&schemaVersion!==1)throw Error(`Unsupported PR_REVIEW trigger schema_version: ${schemaVersion}`);let legacyEnvelope=schemaVersion===1?V1ReceiptSchema.parse(input):UnversionedRowOnlyReceiptSchema.parse(input),rowsInput=legacyEnvelope.rows,parsedLegacyRows=parseRows(rowsInput,LegacyRowSchema,"Invalid legacy trigger ledger; all rows must be MATCHED with complete source provenance");assertCanonicalDefinitionFields(parsedLegacyRows.filter((row)=>("scope"in row)));let legacyRows=parsedLegacyRows.map((row)=>({trigger_id:row.trigger_id,result:row.result,evidence:row.evidence,source_batch_id:row.source_batch_id,source_lane_id:row.source_lane_id})),validated=summarizeTriggerRows(legacyRows);if(schemaVersion===1){let receipt=legacyEnvelope,countFields={trigger_count:validated.rows.length,matched_count:validated.rows.length,no_match_count:0,dispatched_micro_lane_count:dispatchedMicroLaneCount(validated.rows)};for(let[field,expected]of Object.entries(countFields))if(receipt[field]!==expected)throw Error(`Historical PR_REVIEW trigger receipt ${field} is inconsistent: expected ${expected}`)}return parsedReceipt(schemaVersion===1?1:0,validated.rows)}var PR_REVIEW_TRIGGER_DEFINITIONS,PR_REVIEW_REQUIRED_TRIGGER_IDS,PR_REVIEW_TRIGGER_RECEIPT_MAX_BYTES=2097152,TriggerIdSchema,TriggerEvidenceSchema,PrReviewInlineTriggerRowSchema,PrReviewPersistedInputRowSchema,PrReviewWriterInputRowSchema,TriggerDefinitionFieldShape,V2MatchedRowSchema,V2NotTriggeredRowSchema,V2RowSchema,TriggerCoverageDegradationSchema,ReceiptEnvelopeSchema,V2ReceiptSchema,LegacyRowFieldShape,LegacyBasicRowSchema,LegacyFullRowSchema,LegacyRowSchema,V1ReceiptSchema,UnversionedRowOnlyReceiptSchema;var init_pr_review_trigger_contract=__esm(()=>{init_zod();PR_REVIEW_TRIGGER_DEFINITIONS=[{id:"auth-identity-secrets",scope:"universal",trigger_row:"authentication, authorization, identity, sessions, permissions, secrets, cryptography",micro_lane:"Identity and secret boundaries"},{id:"untrusted-input-boundaries",scope:"universal",trigger_row:"parsing, serialization, queries, templates/rendering, file or network input/output",micro_lane:"Untrusted input and sink analysis"},{id:"subprocess-platform",scope:"universal",trigger_row:"subprocesses, shell commands, filesystem operations, OS/runtime-specific code",micro_lane:"Subprocess and platform safety"},{id:"concurrency-state",scope:"universal",trigger_row:"queues, caches, retries, transactions, locks, state machines, async coordination",micro_lane:"Concurrency and state transitions"},{id:"dependencies-build-release",scope:"universal",trigger_row:"dependency manifests, lockfiles, installers, build scripts, CI, packaging, deployment",micro_lane:"Dependency and delivery integrity"},{id:"api-schema-migrations",scope:"universal",trigger_row:"public API, wire/schema/config/storage formats, migrations, feature flags",micro_lane:"Compatibility and migration safety"},{id:"test-infrastructure",scope:"universal",trigger_row:"tests, mocks, fixtures, harnesses, coverage, CI matrices",micro_lane:"Test validity and isolation"},{id:"ui-accessibility-i18n",scope:"universal",trigger_row:"user interfaces, interaction flows, rendering, accessibility, localization",micro_lane:"UI and human-interface quality"},{id:"privacy-observability",scope:"universal",trigger_row:"telemetry, logs, analytics, traces, retention, diagnostics",micro_lane:"Privacy and observability safety"},{id:"generated-provenance",scope:"universal",trigger_row:"generated, vendored, binary, model-produced, codegen or checked-in build artifacts",micro_lane:"Generated artifact provenance"},{id:"unclassified-risk",scope:"universal",trigger_row:"any changed artifact or behavior not confidently classified by the rows above",micro_lane:"Unclassified high-risk fallback"}],PR_REVIEW_REQUIRED_TRIGGER_IDS=PR_REVIEW_TRIGGER_DEFINITIONS.map((definition)=>definition.id),TriggerIdSchema=exports_external.enum(PR_REVIEW_REQUIRED_TRIGGER_IDS,{error:"unknown PR_REVIEW trigger_id"}),TriggerEvidenceSchema=exports_external.string().trim().min(1).max(4000),PrReviewInlineTriggerRowSchema=exports_external.discriminatedUnion("result",[exports_external.object({trigger_id:TriggerIdSchema,result:exports_external.literal("MATCHED"),evidence:TriggerEvidenceSchema}).strict(),exports_external.object({trigger_id:TriggerIdSchema,result:exports_external.literal("NOT_TRIGGERED"),evidence:TriggerEvidenceSchema}).strict()]),PrReviewPersistedInputRowSchema=exports_external.discriminatedUnion("result",[exports_external.object({trigger_id:TriggerIdSchema,result:exports_external.literal("MATCHED"),evidence:TriggerEvidenceSchema,source_batch_id:exports_external.string().trim().min(1),source_lane_id:exports_external.string().trim().min(1)}).strict(),exports_external.object({trigger_id:TriggerIdSchema,result:exports_external.literal("NOT_TRIGGERED"),evidence:TriggerEvidenceSchema}).strict()]),PrReviewWriterInputRowSchema=exports_external.discriminatedUnion("result",[exports_external.object({trigger_id:TriggerIdSchema,result:exports_external.literal("MATCHED"),evidence:TriggerEvidenceSchema.optional(),source_batch_id:exports_external.string().trim().min(1),source_lane_id:exports_external.string().trim().min(1)}).strict(),exports_external.object({trigger_id:TriggerIdSchema,result:exports_external.literal("NOT_TRIGGERED"),evidence:TriggerEvidenceSchema.optional()}).strict()]);TriggerDefinitionFieldShape={scope:exports_external.literal("universal"),trigger_row:exports_external.string().trim().min(1),micro_lane:exports_external.string().trim().min(1)},V2MatchedRowSchema=exports_external.object({trigger_id:TriggerIdSchema,...TriggerDefinitionFieldShape,result:exports_external.literal("MATCHED"),evidence:TriggerEvidenceSchema,source_batch_id:exports_external.string().trim().min(1),source_lane_id:exports_external.string().trim().min(1)}).strict(),V2NotTriggeredRowSchema=exports_external.object({trigger_id:TriggerIdSchema,...TriggerDefinitionFieldShape,result:exports_external.literal("NOT_TRIGGERED"),evidence:TriggerEvidenceSchema}).strict(),V2RowSchema=exports_external.union([V2MatchedRowSchema,V2NotTriggeredRowSchema]),TriggerCoverageDegradationSchema=exports_external.object({trigger_id:TriggerIdSchema,source_batch_id:exports_external.string().trim().min(1),source_lane_id:exports_external.string().trim().min(1),reason:exports_external.string().trim().min(1)}).strict(),ReceiptEnvelopeSchema=exports_external.object({run_id:exports_external.string().regex(/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/),pr_head_sha:exports_external.string().trim().regex(/^[0-9a-f]{6,64}$/i),base_ref:exports_external.string().trim().regex(/^(?!-)[A-Za-z0-9][A-Za-z0-9._/-]{0,255}$/),base_sha:exports_external.string().trim().regex(/^[0-9a-f]{6,64}$/i),evaluated_at:exports_external.string().datetime(),dispatched_micro_lane_count:exports_external.number().int().min(1)}),V2ReceiptSchema=ReceiptEnvelopeSchema.extend({schema_version:exports_external.literal(2),trigger_count:exports_external.number().int().min(0),matched_count:exports_external.number().int().min(0),not_triggered_count:exports_external.number().int().min(0),no_match_count:exports_external.number().int().min(0),rows:exports_external.array(V2RowSchema),coverage_degradations:exports_external.array(TriggerCoverageDegradationSchema).default([]),base_verification:exports_external.enum(["live","bound_fallback"]).optional()}).strict();LegacyRowFieldShape={trigger_id:TriggerIdSchema,result:exports_external.literal("MATCHED"),evidence:TriggerEvidenceSchema,source_batch_id:exports_external.string().trim().min(1),source_lane_id:exports_external.string().trim().min(1)},LegacyBasicRowSchema=exports_external.object(LegacyRowFieldShape).strict(),LegacyFullRowSchema=exports_external.object({trigger_id:TriggerIdSchema,...TriggerDefinitionFieldShape,result:exports_external.literal("MATCHED"),evidence:TriggerEvidenceSchema,source_batch_id:exports_external.string().trim().min(1),source_lane_id:exports_external.string().trim().min(1)}).strict(),LegacyRowSchema=exports_external.union([LegacyBasicRowSchema,LegacyFullRowSchema]),V1ReceiptSchema=ReceiptEnvelopeSchema.extend({schema_version:exports_external.literal(1),trigger_count:exports_external.number().int().min(0),matched_count:exports_external.number().int().min(0),no_match_count:exports_external.number().int().min(0),rows:exports_external.array(LegacyRowSchema)}).strict(),UnversionedRowOnlyReceiptSchema=exports_external.object({rows:exports_external.array(exports_external.unknown())}).strict()});var exports_workspace_snapshot={};__export(exports_workspace_snapshot,{workspaceSnapshotMatches:()=>workspaceSnapshotMatches,switchPrFeedbackTrackingCandidateAsync:()=>switchPrFeedbackTrackingCandidateAsync,resolveRemoteRefsContainingHeadAsync:()=>resolveRemoteRefsContainingHeadAsync,resolveRemoteRefsContainingHead:()=>resolveRemoteRefsContainingHead,resolvePrWorkflowRevisionDigestDetailedAsync:()=>resolvePrWorkflowRevisionDigestDetailedAsync,resolvePrWorkflowRevisionDigestDetailed:()=>resolvePrWorkflowRevisionDigestDetailed,resolvePrWorkflowRevisionDigestAsync:()=>resolvePrWorkflowRevisionDigestAsync,resolvePrWorkflowRevisionDigest:()=>resolvePrWorkflowRevisionDigest,resolvePrReviewDiffStatsAsync:()=>resolvePrReviewDiffStatsAsync,resolvePrReviewDiffStats:()=>resolvePrReviewDiffStats,resolvePrFeedbackTrackingCandidatesAsync:()=>resolvePrFeedbackTrackingCandidatesAsync,resolveIsWorkingTreeCleanAsync:()=>resolveIsWorkingTreeCleanAsync,resolveIsWorkingTreeClean:()=>resolveIsWorkingTreeClean,resolveIsExactSingleChildCommitAsync:()=>resolveIsExactSingleChildCommitAsync,resolveIsExactSingleChildCommit:()=>resolveIsExactSingleChildCommit,resolveGitControlStateDigestAsync:()=>resolveGitControlStateDigestAsync,resolveGitControlStateDigest:()=>resolveGitControlStateDigest,resolveExactRemoteBranchHeadAsync:()=>resolveExactRemoteBranchHeadAsync,resolveExactRemoteBranchHead:()=>resolveExactRemoteBranchHead,resolveExactMergeBaseAsync:()=>resolveExactMergeBaseAsync,resolveExactMergeBase:()=>resolveExactMergeBase,resolveCurrentUpstreamRemoteRef:()=>resolveCurrentUpstreamRemoteRef,resolveCurrentUpstreamPushTargetAsync:()=>resolveCurrentUpstreamPushTargetAsync,resolveCurrentUpstreamPushTarget:()=>resolveCurrentUpstreamPushTarget,resolveCurrentGitHeadAsync:()=>resolveCurrentGitHeadAsync,resolveCurrentGitHead:()=>resolveCurrentGitHead,resolveCommitCountSinceAsync:()=>resolveCommitCountSinceAsync,resolveCommitCountSince:()=>resolveCommitCountSince,readGitTextAtRevision:()=>readGitTextAtRevision,parsePorcelainV2Snapshot:()=>parsePorcelainV2Snapshot,parsePorcelainPaths:()=>parsePorcelainPaths,isSwarmRuntimePath:()=>isSwarmRuntimePath,digest:()=>digest,compareWorkspaceSnapshots:()=>compareWorkspaceSnapshots,compareWorkspaceSnapshot:()=>compareWorkspaceSnapshot,changedFilesSinceSnapshot:()=>changedFilesSinceSnapshot,captureWorkspaceSnapshot:()=>captureWorkspaceSnapshot,_internals:()=>_internals10});import*as child_process from"node:child_process";import{createHash as createHash8}from"node:crypto";import*as fs10 from"node:fs";import*as path14 from"node:path";async function readBoundedGitOutput(stream,maxBytes,onOverflow){let reader=stream.getReader(),chunks=[],totalBytes=0;try{for(;;){let{done,value}=await reader.read();if(done)break;if(!value)continue;let remaining=maxBytes-totalBytes;if(value.byteLength>remaining){if(remaining>0)chunks.push(value.slice(0,remaining));return onOverflow(),{text:"",truncated:!0}}chunks.push(value),totalBytes+=value.byteLength}let joined=new Uint8Array(totalBytes),offset=0;for(let chunk of chunks)joined.set(chunk,offset),offset+=chunk.byteLength;return{text:new TextDecoder().decode(joined),truncated:!1}}finally{try{await reader.cancel()}catch{}try{reader.releaseLock()}catch{}}}function runGit(directory,args2,timeoutMs=GIT_SNAPSHOT_TIMEOUT_MS){let result=_internals10.spawnSync(_internals10.resolveGitExecutable(),["-C",directory,...args2],{cwd:directory,encoding:"utf-8",timeout:timeoutMs,maxBuffer:GIT_SNAPSHOT_MAX_BUFFER,stdio:["ignore","pipe","pipe"]});if(result.error||result.status!==0)return null;return typeof result.stdout==="string"?result.stdout.trimEnd():null}async function runGitAsync(directory,args2,timeoutMs=_internals10.gitTimeoutMs){let proc,timeout;try{let options={cwd:directory,stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:timeoutMs,killProcessTree:!0};proc=_internals10.bunSpawn([_internals10.resolveGitExecutable(),"-C",directory,...args2],options);let overflowed=!1,stopOverflow=()=>{overflowed=!0;try{proc?.kill("SIGKILL")}catch{}},completed=Promise.all([proc.exited,readBoundedGitOutput(proc.stdout,GIT_SNAPSHOT_MAX_BUFFER,stopOverflow),readBoundedGitOutput(proc.stderr,GIT_SNAPSHOT_MAX_BUFFER,stopOverflow)]),result=await Promise.race([completed.then(([exitCode,stdout,stderr])=>({kind:"completed",exitCode,stdout,stderr})),new Promise((resolve9)=>{timeout=setTimeout(()=>resolve9({kind:"timeout"}),timeoutMs)})]);if(result.kind==="timeout"||overflowed||result.exitCode!==0||result.stdout.truncated||result.stderr.truncated)return null;return result.stdout.text.trimEnd()}catch{return null}finally{if(timeout)clearTimeout(timeout);try{proc?.kill("SIGKILL")}catch{}}}function runGitDetailed(directory,args2,timeoutMs){let result=_internals10.spawnSync(_internals10.resolveGitExecutable(),["-C",directory,...args2],{cwd:directory,encoding:"utf-8",timeout:timeoutMs,maxBuffer:_internals10.gitSnapshotMaxBuffer,stdio:["ignore","pipe","pipe"]}),errorCode=result.error?.code;if(errorCode==="ENOBUFS")return{ok:!1,reason:"buffer-truncated"};if(errorCode==="ETIMEDOUT")return{ok:!1,reason:"timeout"};if(result.error||result.status!==0||typeof result.stdout!=="string")return{ok:!1,reason:"git-failed"};return{ok:!0,text:result.stdout.trimEnd()}}async function runGitAsyncDetailed(directory,args2,timeoutMs){let proc,timeout;try{let options={cwd:directory,stdin:"ignore",stdout:"pipe",stderr:"pipe",killProcessTree:!0};proc=_internals10.bunSpawn([_internals10.resolveGitExecutable(),"-C",directory,...args2],options);let overflowed=!1,stopOverflow=()=>{overflowed=!0;try{proc?.kill("SIGKILL")}catch{}},maxBuffer=_internals10.gitSnapshotMaxBuffer,completed=Promise.all([proc.exited,readBoundedGitOutput(proc.stdout,maxBuffer,stopOverflow),readBoundedGitOutput(proc.stderr,maxBuffer,stopOverflow)]),result=await Promise.race([completed.then(([exitCode,stdout,stderr])=>({kind:"completed",exitCode,stdout,stderr})),new Promise((resolve9)=>{timeout=setTimeout(()=>resolve9({kind:"timeout"}),timeoutMs)})]);if(result.kind==="timeout")return{ok:!1,reason:"timeout"};if(overflowed||result.stdout.truncated||result.stderr.truncated)return{ok:!1,reason:"buffer-truncated"};if(result.exitCode!==0)return{ok:!1,reason:"git-failed"};return{ok:!0,text:result.stdout.text.trimEnd()}}catch{return{ok:!1,reason:"git-failed"}}finally{if(timeout)clearTimeout(timeout);try{proc?.kill("SIGKILL")}catch{}}}function readGitTextAtRevision(directory,revision,relativePath){if(!isSafeGitRevisionToken(revision)||!/^\.?(?:[A-Za-z0-9][A-Za-z0-9._-]*\/)*[A-Za-z0-9][A-Za-z0-9._-]*$/.test(relativePath)||relativePath.split("/").includes(".."))return null;let result=_internals10.spawnSync(_internals10.resolveGitExecutable(),["-C",directory,"show",`${revision}:${relativePath}`],{cwd:directory,encoding:"utf-8",timeout:GIT_SNAPSHOT_TIMEOUT_MS,maxBuffer:GIT_SNAPSHOT_MAX_BUFFER,stdio:["ignore","pipe","pipe"]});if(result.error||result.status!==0||typeof result.stdout!=="string")return null;return result.stdout}function resolveCurrentGitHead(directory){return runGit(directory,["rev-parse","--verify","HEAD^{commit}"])}async function resolveCurrentGitHeadAsync(directory){return await runGitAsync(directory,["rev-parse","--verify","HEAD^{commit}"])}function resolveExactMergeBase(directory,baseRef,prHeadSha){if(!isSafeGitRevisionToken(baseRef)||!isSafeGitRevisionToken(prHeadSha))return null;let mergeBase=runGit(directory,["merge-base","--",baseRef,prHeadSha]);return mergeBase&&/^[0-9a-f]{6,64}$/i.test(mergeBase)?mergeBase:null}async function resolveExactMergeBaseAsync(directory,baseRef,prHeadSha){if(!isSafeGitRevisionToken(baseRef)||!isSafeGitRevisionToken(prHeadSha))return null;let mergeBase=await runGitAsync(directory,["merge-base","--",baseRef,prHeadSha]);return mergeBase&&/^[0-9a-f]{6,64}$/i.test(mergeBase)?mergeBase:null}function resolvePrReviewDiffStats(directory,baseSha,prHeadSha){if(!isSafeGitRevisionToken(baseSha)||!isSafeGitRevisionToken(prHeadSha))return null;let range=`${baseSha}...${prHeadSha}`,output=runGit(directory,["diff","--no-renames","--numstat",range]);if(output===null)return null;let changedLines=0,changedFiles=0;for(let line of output.split(`
@@ -270,7 +270,7 @@ line break`,"required change with\rcarriage return"]),discardedReviewer=encodePr
270
270
  ON qi.profile_id = p.id
271
271
  WHERE p.plan_id = ?
272
272
  AND qi.profile_id IS NULL
273
- LIMIT 1`).get(readablePlanId)??null}function buildExactStoragePlanId(identityHash){return`qa2-${identityHash}`}function hasAnyGatePatch(gates){return Object.values(gates).some((value)=>value!==void 0)}function verifyBoundIdentityBinding(binding,identity){if(binding.identity_hash!==identity.identityHash||binding.raw_swarm!==identity.swarm||binding.raw_title!==identity.title||binding.readable_plan_id!==identity.planId)throw Error(`QA gate profile identity binding is corrupt for swarm_id='${identity.swarm}' and plan_title='${identity.title}'`)}function lookupProfileForIdentityTx(db,identity){let binding=readIdentityBindingByHash(db,identity.identityHash);if(binding){verifyBoundIdentityBinding(binding,identity);let row=readProfileRowById(db,binding.profile_id);if(!row)throw Error(`QA gate profile identity binding points to missing profile_id=${binding.profile_id}`);return{kind:"bound",identity,profile:rowToProfileWithBinding(row,binding)}}let legacyRow=readUnboundLegacyProfileRowByReadablePlanId(db,identity.planId);if(legacyRow)return{kind:"unbound_legacy",identity,profile:rowToProfile(legacyRow)};return{kind:"missing",identity}}function createExactIdentityBindingTx(db,profileId,identity){db.run("INSERT INTO qa_gate_profile_identity (identity_hash, profile_id, raw_swarm, raw_title, readable_plan_id) VALUES (?, ?, ?, ?, ?)",[identity.identityHash,profileId,identity.swarm,identity.title,identity.planId])}function createExactProfileTx(db,identity,projectType,initialGates){let gatesJson=JSON.stringify({...DEFAULT_QA_GATES,...initialGates});db.run("INSERT INTO qa_gate_profile (plan_id, project_type, gates) VALUES (?, ?, ?)",[buildExactStoragePlanId(identity.identityHash),projectType??null,gatesJson]);let row=readProfileRowByPlanId(db,buildExactStoragePlanId(identity.identityHash));if(!row)throw Error(`Failed to create QA gate profile row for exact identity plan_id=${identity.planId}`);createExactIdentityBindingTx(db,row.id,identity);let binding=readIdentityBindingByHash(db,identity.identityHash);if(!binding)throw Error(`Failed to create QA gate profile identity binding for plan_id=${identity.planId}`);return rowToProfileWithBinding(row,binding)}function shouldAdoptLegacyProfile(identity,options){if(options.allowLegacyAdoption!==!0)return!1;return options.legacyAdoptionIdentity?.swarm===identity.swarm&&options.legacyAdoptionIdentity?.title===identity.title}function getProfile(directory,planId){if(!projectDbExists(directory))return null;let db=getProjectDb(directory),row=readProfileRowByPlanId(db,planId);return row?rowToProfile(row):null}function getProfileForIdentity(directory,identity){let lookup=getProfileLookupForIdentity(directory,identity);if(lookup.kind==="bound")return lookup.profile;if(lookup.kind==="unbound_legacy")throw new QaGateProfileIdentityUnboundError(lookup.identity);return null}function getProfileLookupForIdentity(directory,identity){let exact=buildProfileIdentity(identity);if(!projectDbExists(directory))return{kind:"missing",identity:exact};let db=getProjectDb(directory);return lookupProfileForIdentityTx(db,exact)}function hasAnyProfileWithEnabledGate(directory,gate){if(!projectDbExists(directory))return!1;let rows=getProjectDb(directory).query("SELECT gates FROM qa_gate_profile").all();for(let row of rows)try{if(JSON.parse(row.gates)?.[gate]===!0)return!0}catch{}return!1}function getOrCreateProfile(directory,planId,projectType,initialGates={}){let existing=_internals14.getProfile(directory,planId);if(existing)return existing;let db=getProjectDb(directory),seededGates={...DEFAULT_QA_GATES};for(let key of Object.keys(DEFAULT_QA_GATES))if(typeof initialGates[key]==="boolean")seededGates[key]=initialGates[key];let gatesJson=JSON.stringify(seededGates),insert=db.transaction(()=>{db.run("INSERT INTO qa_gate_profile (plan_id, project_type, gates) VALUES (?, ?, ?)",[planId,projectType??null,gatesJson])});try{insert()}catch(err){if(!(err instanceof Error?err.message:String(err)).toLowerCase().includes("unique"))throw err}let after=_internals14.getProfile(directory,planId);if(!after)throw Error(`Failed to create or load QA gate profile for plan_id=${planId}`);return after}function getOrCreateProfileForIdentity(directory,identity,projectType,initialGates={}){let db=getProjectDb(directory),exact=buildProfileIdentity(identity);return withImmediateTransaction(db,()=>{let lookup=lookupProfileForIdentityTx(db,exact);if(lookup.kind==="bound")return lookup.profile;if(lookup.kind==="unbound_legacy")return createExactProfileTx(db,exact,projectType,initialGates);return createExactProfileTx(db,exact,projectType,initialGates)})}function setGates(directory,planId,gates){let db=getProjectDb(directory),savepointName=`qa_gate_profile_set_${qaGateProfileSavepointCounter++}`,startedTransaction=!db.inTransaction;db.run(startedTransaction?"BEGIN IMMEDIATE":`SAVEPOINT ${savepointName}`);try{let currentRow=db.query("SELECT * FROM qa_gate_profile WHERE plan_id = ?").get(planId);if(!currentRow)throw Error(`No QA gate profile found for plan_id=${planId} — call getOrCreateProfile first`);let current=rowToProfile(currentRow);if(current.locked_at!==null)throw Error("Cannot modify gates: QA gate profile is locked after critic approval");_internals14.afterSetGatesRead(current);let merged={...current.gates};for(let key of Object.keys(gates)){let incoming=gates[key];if(incoming===void 0)continue;if(incoming===!1&&current.gates[key]===!0)throw Error(`Cannot disable gate '${key}': sessions can only ratchet tighter`);if(incoming===!0)merged[key]=!0}db.run("UPDATE qa_gate_profile SET gates = ? WHERE plan_id = ?",[JSON.stringify(merged),planId]);let updatedRow=db.query("SELECT * FROM qa_gate_profile WHERE plan_id = ?").get(planId);if(!updatedRow)throw Error(`Failed to re-read QA gate profile after update for plan_id=${planId}`);return db.run(startedTransaction?"COMMIT":`RELEASE ${savepointName}`),rowToProfile(updatedRow)}catch(err){try{if(db.run(startedTransaction?"ROLLBACK":`ROLLBACK TO ${savepointName}`),!startedTransaction)db.run(`RELEASE ${savepointName}`)}catch{}throw err}}function setGatesForIdentity(directory,identity,gates,options={}){let db=getProjectDb(directory),exact=buildProfileIdentity(identity),savepointName=`qa_gate_profile_set_identity_${qaGateProfileSavepointCounter++}`,startedTransaction=!db.inTransaction,finishTransaction=()=>{db.run(startedTransaction?"COMMIT":`RELEASE ${savepointName}`)},rollbackTransaction=()=>{if(db.run(startedTransaction?"ROLLBACK":`ROLLBACK TO ${savepointName}`),!startedTransaction)db.run(`RELEASE ${savepointName}`)};db.run(startedTransaction?"BEGIN IMMEDIATE":`SAVEPOINT ${savepointName}`);try{let lookup=lookupProfileForIdentityTx(db,exact);if(lookup.kind==="missing"){let created=createExactProfileTx(db,exact,options.projectType,gates);return finishTransaction(),created}if(lookup.kind==="unbound_legacy")if(shouldAdoptLegacyProfile(exact,options)){if(createExactIdentityBindingTx(db,lookup.profile.id,exact),lookup=lookupProfileForIdentityTx(db,exact),lookup.kind!=="bound")throw Error(`Failed to adopt legacy QA gate profile for exact identity plan_id=${exact.planId}`)}else if(options.allowLegacyCollisionCreate===!0){let created=createExactProfileTx(db,exact,options.projectType,gates);return finishTransaction(),created}else throw new QaGateProfileIdentityUnboundError(lookup.identity);let current=lookup.profile,currentRow=readProfileRowById(db,current.id);if(!currentRow)throw Error(`Failed to read QA gate profile row for profile_id=${current.id}`);if(_internals14.afterSetGatesForIdentityRead?.({directory,identity:exact,profileId:current.id,storagePlanId:currentRow.plan_id}),current.locked_at!==null){if(!hasAnyGatePatch(gates))return finishTransaction(),current;throw Error("Cannot modify gates: QA gate profile is locked after critic approval")}let merged={...current.gates};for(let key of Object.keys(gates)){let incoming=gates[key];if(incoming===void 0)continue;if(incoming===!1&&current.gates[key]===!0)throw Error(`Cannot disable gate '${key}': sessions can only ratchet tighter`);if(incoming===!0)merged[key]=!0}db.run("UPDATE qa_gate_profile SET gates = ? WHERE id = ?",[JSON.stringify(merged),current.id]);let updatedRow=readProfileRowById(db,current.id),binding=readIdentityBindingByHash(db,exact.identityHash);if(!updatedRow||!binding)throw Error(`Failed to re-read QA gate profile after exact-identity update for plan_id=${exact.planId}`);return finishTransaction(),rowToProfileWithBinding(updatedRow,binding)}catch(err){try{rollbackTransaction()}catch{}throw err}}function lockProfileForIdentity(directory,identity,snapshotSeq){let db=getProjectDb(directory),exact=buildProfileIdentity(identity);return withImmediateTransaction(db,()=>{let lookup=lookupProfileForIdentityTx(db,exact);if(lookup.kind==="missing")throw Error(`No QA gate profile found for exact identity plan_id=${exact.planId} — cannot lock`);if(lookup.kind==="unbound_legacy")throw new QaGateProfileIdentityUnboundError(lookup.identity);if(lookup.profile.locked_at!==null)return lookup.profile;db.run("UPDATE qa_gate_profile SET locked_at = datetime('now'), locked_by_snapshot_seq = ? WHERE id = ?",[snapshotSeq,lookup.profile.id]);let updatedRow=readProfileRowById(db,lookup.profile.id),binding=readIdentityBindingByHash(db,exact.identityHash);if(!updatedRow||!binding)throw Error(`Failed to re-read locked QA gate profile for exact identity plan_id=${exact.planId}`);return rowToProfileWithBinding(updatedRow,binding)})}function computeProfileHash(profile){let payload=JSON.stringify({plan_id:profile.plan_id,identity_hash:profile.identity_hash,gates:profile.gates});return createHash11("sha256").update(payload).digest("hex")}function getEffectiveGates(profile,sessionOverrides){let merged={...profile.gates};for(let key of Object.keys(sessionOverrides))if(sessionOverrides[key]===!0)merged[key]=!0;return merged}var _internals14,DEFAULT_QA_GATES,QaGateProfileIdentityUnboundError,qaGateProfileSavepointCounter=0;var init_qa_gate_profile=__esm(()=>{init_utils3();init_project_db();_internals14={getProfile,getProfileLookupForIdentity,getProfileForIdentity,getOrCreateProfile,getOrCreateProfileForIdentity,setGates,setGatesForIdentity,lockProfileForIdentity,getEffectiveGates,computeProfileHash,hasAnyProfileWithEnabledGate,afterSetGatesRead:()=>{}},DEFAULT_QA_GATES={reviewer:!0,test_engineer:!0,council_mode:!1,sme_enabled:!0,critic_pre_plan:!0,hallucination_guard:!1,sast_enabled:!0,mutation_test:!1,phase_council:!1,drift_check:!0,final_council:!1};QaGateProfileIdentityUnboundError=class QaGateProfileIdentityUnboundError extends Error{identity;constructor(identity){super(`QA gate profile exists for readable plan_id='${identity.planId}' but is not exact-bound to swarm_id='${identity.swarm}' and plan_title='${identity.title}'. ${formatLegacyQaBindingRecovery(identity,"retry the blocked read-only or enforcement operation")}`);this.name="QaGateProfileIdentityUnboundError",this.identity=identity}}});function detectHostOS(){switch(process.platform){case"win32":return"windows";case"darwin":return"macos";case"linux":return"linux";default:return"unknown"}}function detectShellFamily(){if(process.env.PSModulePath)return"powershell";if((process.env.ComSpec??"").toLowerCase().includes("cmd.exe"))return"cmd";let shell=process.env.SHELL??"";if(shell.includes("bash"))return"bash";if(shell.includes("zsh"))return"zsh";if(shell.includes("/sh"))return"sh";return"unknown"}function detectExecutionMode(hostOS){if(process.env.WSL_DISTRO_NAME)return"wsl";if(hostOS==="linux"){if(["DOCKER_CONTAINER","KUBERNETES_SERVICE_HOST","CONTAINER"].some((k)=>process.env[k]))return"docker"}return"native"}function deriveOperatingMode(hostOS,_executionMode){if(hostOS==="linux")return"linux";if(hostOS==="macos")return"macos-native";if(hostOS==="windows")return"windows-native";return"unknown"}function buildCommandPolicy(profile){if(profile.isWindowsNative)return{preferredShell:"powershell",avoidPosixExamples:!0,preferNodeApis:!0,preferToolingOverShell:!0,pathExampleStyle:"windows",examples:{listDir:"Get-ChildItem -Force",removeFile:"Remove-Item file.tmp",setEnv:'$env:DEBUG = "1"',printEnv:"$env:PATH",searchText:'Get-ChildItem -Recurse src | Select-String "foo"'}};return{preferredShell:profile.shellFamily==="unknown"?"bash":profile.shellFamily,avoidPosixExamples:!1,preferNodeApis:!0,preferToolingOverShell:!0,pathExampleStyle:"posix",examples:{listDir:"ls -la",removeFile:"rm file.tmp",setEnv:"export DEBUG=1",printEnv:"echo $PATH",searchText:'grep -R "foo" src/'}}}function detectEnvironmentProfile(){let hostOS=detectHostOS(),shellFamily=detectShellFamily(),executionMode=detectExecutionMode(hostOS),operatingMode=deriveOperatingMode(hostOS,executionMode),isWindowsNative=hostOS==="windows"&&executionMode==="native",isWindowsDocker=!1;return{hostOS,shellFamily,executionMode,operatingMode,isWindowsNative,isWindowsDocker:!1,isWSL:executionMode==="wsl",pathStyle:hostOS==="windows"?"windows":"posix",shellCommandPreference:isWindowsNative?"powershell-native":"posix-native",evidence:{processPlatform:process.platform,comspec:process.env.ComSpec,psModulePath:process.env.PSModulePath,termProgram:process.env.TERM_PROGRAM,shell:process.env.SHELL,wslDistroName:process.env.WSL_DISTRO_NAME,containerMarkers:["DOCKER_CONTAINER","KUBERNETES_SERVICE_HOST","CONTAINER"].filter((k)=>!!process.env[k])}}}function deriveCommandPolicy(profile){return buildCommandPolicy(profile)}import{createHash as createHash12}from"node:crypto";function hashString(value){return createHash12("sha256").update(value).digest("hex")}function circuitKey(sessionID,invocationID,actionDigest,circuitKind){return`${sessionID}\x00${invocationID}\x00${actionDigest}\x00${circuitKind}`}function familyKey(sessionID,invocationID,actionDigest){return`${sessionID}\x00${invocationID}\x00${actionDigest}`}function familyPrefix(sessionID,invocationID){return`${sessionID}\x00${invocationID}\x00`}function sessionPrefix(sessionID){return`${sessionID}\x00`}function removeEntry(key){actionCircuits.delete(key)}function pruneGenerationTokenIfUnused(family){let prefix=`${family}\x00`,hasEntries=[...actionCircuits.keys()].some((key)=>key.startsWith(prefix)),isArmed=armedActions.has(family);if(!hasEntries&&!isArmed)actionGenerationTokens.delete(family)}function sweepExpired(now){for(let[key,entry]of actionCircuits)if(entry.expiresAt<=now)removeEntry(key),pruneGenerationTokenIfUnused(familyKey(entry.sessionID,entry.invocationID,entry.actionDigest));for(let[family,armedToken]of armedActions)if(actionGenerationTokens.get(family)!==armedToken)armedActions.delete(family)}function ensureGenerationToken(sessionID,invocationID,actionDigest){let family=familyKey(sessionID,invocationID,actionDigest),current=actionGenerationTokens.get(family);if(current!==void 0)return current;return actionGenerationTokens.set(family,1),1}function bumpGenerationToken(sessionID,invocationID,actionDigest){let family=familyKey(sessionID,invocationID,actionDigest),next=ensureGenerationToken(sessionID,invocationID,actionDigest)+1;return actionGenerationTokens.set(family,next),armedActions.delete(family),next}function touchEntry(key,entry,now){let touched={...entry,expiresAt:now+ACTION_CIRCUIT_TTL_MS};return actionCircuits.delete(key),actionCircuits.set(key,touched),touched}function enforceCapacity(){while(actionCircuits.size>MAX_TRACKED_ACTION_CIRCUITS){let oldest=actionCircuits.keys().next().value;if(oldest===void 0)break;let entry=actionCircuits.get(oldest);if(removeEntry(oldest),entry)pruneGenerationTokenIfUnused(familyKey(entry.sessionID,entry.invocationID,entry.actionDigest))}}function recordResetAudit(record2){if(resetAudit.push(record2),resetAudit.length>MAX_RESET_AUDIT_ROWS)resetAudit.shift()}function armActionCircuitAttempt(sessionID,invocationID,actionDigest){let token=ensureGenerationToken(sessionID,invocationID,actionDigest);return armedActions.set(familyKey(sessionID,invocationID,actionDigest),token),token}function noteActionCircuitFailure(input){let now=input.now??Date.now();sweepExpired(now);let family=familyKey(input.sessionID,input.invocationID,input.actionDigest),expectedToken=input.generationToken??armedActions.get(family)??null,currentToken=ensureGenerationToken(input.sessionID,input.invocationID,input.actionDigest);if(expectedToken===null||expectedToken!==currentToken)return{entry:null,enteredHardStop:!1,ignoredLateEvent:!0};let key=circuitKey(input.sessionID,input.invocationID,input.actionDigest,input.circuitKind),existing=actionCircuits.get(key),count=(existing?.count??0)+1,hardStop=count>=input.hardStopThreshold,entry={sessionID:input.sessionID,invocationID:input.invocationID,actionDigest:input.actionDigest,circuitKind:input.circuitKind,count,hardStop,generationToken:currentToken,lastSignalDigest:input.signal?hashString(input.signal):null,firstSeenAt:existing?.firstSeenAt??now,updatedAt:now,expiresAt:now+ACTION_CIRCUIT_TTL_MS};return actionCircuits.delete(key),actionCircuits.set(key,entry),enforceCapacity(),{entry,enteredHardStop:hardStop&&!existing?.hardStop,ignoredLateEvent:!1}}function clearActionCircuitEntries(sessionID,invocationID,actionDigest){let prefix=`${familyKey(sessionID,invocationID,actionDigest)}\x00`;for(let key of[...actionCircuits.keys()])if(key.startsWith(prefix))removeEntry(key)}function clearActionCircuit(sessionID,invocationID,actionDigest,options){if(clearActionCircuitEntries(sessionID,invocationID,actionDigest),bumpGenerationToken(sessionID,invocationID,actionDigest),options?.reason)recordResetAudit({sessionID,invocationID,actionDigest,reason:options.reason,actor:options.actor??null,at:options.now??Date.now()})}function resetActionCircuitExternally(input){clearActionCircuit(input.sessionID,input.invocationID,input.actionDigest,{reason:"external",actor:input.actor??null,now:input.now})}function clearInvocationActionCircuits(sessionID,invocationID,now){let prefix=familyPrefix(sessionID,invocationID);for(let key of[...actionCircuits.keys()])if(key.startsWith(prefix))removeEntry(key);for(let family of[...actionGenerationTokens.keys()])if(family.startsWith(prefix))actionGenerationTokens.delete(family),armedActions.delete(family),recordResetAudit({sessionID,invocationID,actionDigest:family.slice(prefix.length),reason:"invocation",actor:null,at:now??Date.now()})}function clearSessionActionCircuits(sessionID,now){let prefix=sessionPrefix(sessionID);for(let key of[...actionCircuits.keys()])if(key.startsWith(prefix))removeEntry(key);for(let family of[...actionGenerationTokens.keys()])if(family.startsWith(prefix)){let familyTail=family.slice(prefix.length),separatorIndex=familyTail.indexOf("\x00"),invocationID=separatorIndex>0?Number(familyTail.slice(0,separatorIndex)):0,actionDigest=separatorIndex>0?familyTail.slice(separatorIndex+1):familyTail;actionGenerationTokens.delete(family),armedActions.delete(family),recordResetAudit({sessionID,invocationID,actionDigest,reason:"session",actor:null,at:now??Date.now()})}}function getBlockingActionCircuit(sessionID,invocationID,actionDigest){let now=Date.now();sweepExpired(now);let prefix=`${familyKey(sessionID,invocationID,actionDigest)}\x00`;for(let[key,entry]of actionCircuits)if(key.startsWith(prefix)&&entry.hardStop)return touchEntry(key,entry,now);return null}function listBlockingActionCircuitsForInvocation(sessionID,invocationID){let now=Date.now();sweepExpired(now);let prefix=familyPrefix(sessionID,invocationID),result=[];for(let[key,entry]of[...actionCircuits])if(key.startsWith(prefix)&&entry.hardStop)result.push(touchEntry(key,entry,now));return result}function peekActionCircuitCount(sessionID,invocationID,actionDigest,circuitKind){return actionCircuits.get(circuitKey(sessionID,invocationID,actionDigest,circuitKind))?.count??0}function expireActionCircuit(sessionID,invocationID,actionDigest,circuitKind){let entry=actionCircuits.get(circuitKey(sessionID,invocationID,actionDigest,circuitKind));if(entry)entry.expiresAt=Date.now()-1}function clearAllActionCircuits(){actionCircuits.clear(),actionGenerationTokens.clear(),armedActions.clear(),resetAudit.length=0}var MAX_TRACKED_ACTION_CIRCUITS=500,ACTION_CIRCUIT_TTL_MS=1800000,MAX_RESET_AUDIT_ROWS=128,actionCircuits,actionGenerationTokens,armedActions,resetAudit,_test_exports;var init_action_circuit=__esm(()=>{actionCircuits=new Map,actionGenerationTokens=new Map,armedActions=new Map,resetAudit=[];_test_exports={ACTION_CIRCUIT_TTL_MS,MAX_TRACKED_ACTION_CIRCUITS,size:()=>actionCircuits.size,getGenerationToken:(sessionID,invocationID,actionDigest)=>ensureGenerationToken(sessionID,invocationID,actionDigest),getResetAudit:()=>resetAudit.map((entry)=>({...entry}))}});import{randomBytes as randomBytes2}from"node:crypto";import*as fs12 from"node:fs";import*as path17 from"node:path";function matchTempGrammar(basename3){return SWARM_TEMP_GRAMMARS.find((g)=>g.match.test(basename3))}function parseTargetBasename(basename3){for(let g of SWARM_TEMP_GRAMMARS){if(!g.parsesTarget)continue;let m=g.match.exec(basename3);if(m?.[1])return m[1]}return null}function assertWellFormedTargetPath(targetPath){if(!path17.isAbsolute(targetPath))throw Error(`atomic-write target must be absolute: ${targetPath}`);if(/[\0-\x1f\x7f]/.test(targetPath))throw Error("atomic-write target contains control characters");if(/[*?]/.test(targetPath)||/(^|[/\\])\{[^}]*\}([/\\]|$)/.test(targetPath))throw Error(`atomic-write target contains glob metacharacters: ${targetPath}`);if(/(^|[/\\])~([/\\]|$)/.test(targetPath))throw Error("atomic-write target contains unresolved home-dir marker (~)");if(/\$\{?[A-Za-z_][A-Za-z0-9_]*\}?/.test(targetPath)||/%[^/\\%]+%/.test(targetPath))throw Error("atomic-write target contains unresolved environment-variable form")}function lstatNotSymlink(p,what){if(fs12.lstatSync(p).isSymbolicLink())throw Error(`${what} is a symlink/reparse point: ${p}`)}function assertSwarmContainedTarget(targetPath){assertWellFormedTargetPath(targetPath);let resolved=path17.normalize(path17.resolve(targetPath)),segments=resolved.split(path17.sep),swarmIdx=-1;for(let i=segments.length-2;i>=1;i--)if(segments[i]===".swarm"){swarmIdx=i;break}if(swarmIdx===-1)throw Error(`atomic-write target is not under a project .swarm root: ${targetPath}`);let swarmRoot=segments.slice(0,swarmIdx+1).join(path17.sep);try{let st=fs12.lstatSync(swarmRoot);if(!st.isDirectory()||st.isSymbolicLink())throw Error(`.swarm root is not a real directory (symlink/reparse or non-dir): ${swarmRoot}`)}catch(err){if(err?.code!=="ENOENT")throw err}let rel=path17.relative(swarmRoot,resolved);if(!rel||rel.startsWith("..")||path17.isAbsolute(rel))throw Error(`atomic-write target escapes .swarm root: ${targetPath}`);let probe=swarmRoot;for(let seg of rel.split(path17.sep)){if(probe=path17.join(probe,seg),!fs12.existsSync(probe))break;lstatNotSymlink(probe,"path segment under .swarm")}return{projectRoot:path17.dirname(swarmRoot),swarmRoot}}function toBuffer(content){if(typeof content==="string")return Buffer.from(content,"utf-8");return content}function syncSleep(ms){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,ms)}catch{let start=Date.now();while(Date.now()-start<ms);}}function renameWithRetry(tempPath,targetPath){let lastError;for(let attempt=0;attempt<=RENAME_RETRY_DELAYS_MS.length;attempt++)try{_internals15.renameSync(tempPath,targetPath);return}catch(err){lastError=err;let code=err?.code;if(!code||!RETRYABLE_RENAME_CODES.has(code))throw err;if(attempt<RENAME_RETRY_DELAYS_MS.length)syncSleep(RENAME_RETRY_DELAYS_MS[attempt])}throw lastError}function writeAtomicSync(targetPath,content,options){if(options?.contained!==!1)assertSwarmContainedTarget(targetPath);else assertWellFormedTargetPath(targetPath);let resolvedTarget=path17.resolve(targetPath),buffer=toBuffer(content),maxBytes=options?.maxBytes??MAX_ATOMIC_WRITE_BYTES;if(buffer.byteLength>maxBytes)throw Error(`atomic write exceeds ${maxBytes} byte bound: ${buffer.byteLength}`);let tempPath=`${resolvedTarget}.${_internals15.randomSuffix()}.tmp`;fs12.mkdirSync(path17.dirname(tempPath),{recursive:!0});try{let fd=fs12.openSync(tempPath,"wx");try{let written=0;while(written<buffer.byteLength)written+=_internals15.writeSync(fd,buffer,written,buffer.byteLength-written);if(options?.skipFsync!==!0)try{_internals15.fsyncSync(fd)}catch{}}finally{fs12.closeSync(fd)}renameWithRetry(tempPath,resolvedTarget)}finally{try{_internals15.unlinkSync(tempPath)}catch{}}try{let dirFd=fs12.openSync(path17.dirname(resolvedTarget),"r");try{fs12.fsyncSync(dirFd)}finally{fs12.closeSync(dirFd)}}catch{}invalidateCachedArtifact(resolvedTarget)}async function atomicWriteSwarmFile(targetPath,content,options){await new Promise((resolve12)=>setImmediate(resolve12)),writeAtomicSync(targetPath,content,options)}function atomicWriteSwarmFileSync(targetPath,content,options){writeAtomicSync(targetPath,content,options)}async function atomicWriteFileAnyRoot(targetPath,content,options){await new Promise((resolve12)=>setImmediate(resolve12)),writeAtomicSync(targetPath,content,{...options,contained:!1})}var UUID_RE="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",SWARM_TEMP_GRAMMARS,WRITER_CLASSIFICATION,MAX_ATOMIC_WRITE_BYTES=268435456,RENAME_RETRY_DELAYS_MS,RETRYABLE_RENAME_CODES,_internals15;var init_atomic_write=__esm(()=>{init_swarm_artifact_cache();SWARM_TEMP_GRAMMARS=[{id:"canonical-v1",era:"canonical",match:/^(.+)\.[0-9a-f]{32}\.tmp$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/utils/atomic-write.ts:atomicWriteSwarmFile","src/utils/atomic-write.ts:atomicWriteFileAnyRoot"]},{id:"target-suffix-tmp-uuid",era:"current",match:new RegExp(`^(.+)\\.tmp\\.${UUID_RE}$`),token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/commands/handoff.ts:48 (pre-#2035)","src/commands/handoff.ts:79 (pre-#2035)","src/memory/local-jsonl-provider.ts:1171","src/config/bundled-skills.ts:241"]},{id:"target-suffix-tmp-pid-uuid",era:"current",match:new RegExp(`^(.+)\\.tmp\\.\\d+\\.${UUID_RE}$`),token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/hooks/pr-workflow-gate.ts:14141"],note:"pre/post-rename file-identity verification (assertOpened/ClosedSwarmFileIdentity, pr-workflow-gate.ts:14083-14130) is writer-specific and load-bearing"},{id:"target-suffix-tmp-num-num-json",era:"current",match:/^(.+)\.tmp\.\d+\.\d+\.json$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/hooks/issue-trace-state.ts:315"],note:"the .json terminator keeps this shape distinct from the bare two-token family — declared before it so first-match wins"},{id:"target-suffix-tmp-num-alnum",era:"current",match:/^(.+)\.tmp\.\d+\.[0-9a-z]+$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/evidence/task-file.ts:67 (pre-#2035)","src/scope/scope-persistence.ts:2304 (pre-#2035)","src/scope/scope-persistence.ts:2318 (pre-#2035)","src/plan/manager.ts:628","src/plan/manager.ts:1793","src/plan/manager.ts:1839","src/review/evidence.ts:160","src/turbo/lean/evidence.ts:182","src/summaries/manager.ts:122","src/evidence/manager.ts:288","src/evidence/manager.ts:456","src/tools/sast-baseline.ts:106","src/tools/repo-graph/storage.ts:397","src/memory/reflection-service.ts:547 (pre-#2035)","src/hooks/review-receipt.ts:608","src/hooks/review-receipt.ts:674","src/hooks/review-receipt.ts:812","src/knowledge/identity.ts:209","src/evidence/phase-participation.ts:303 (pre-#2035)","src/turbo/lean/integration.ts:426","src/turbo/lean/reviewer.ts:403","src/plan/ledger.ts:713","src/services/synonym-map.ts:389","src/services/skill-optimizer/store.ts:340","src/services/skill-optimizer/store.ts:503","src/turbo/epic/state.ts:177","src/turbo/epic/calibration.ts:197","src/commands/archive-sqlite.ts:318","src/memory/jsonl-migration.ts:157"],note:"fsync-discipline / lock-scoped fd writers whose temp naming is pinned by their own durability test suites (plan-durability invariant 5, #2034 crash matrix); grammars registered here so their residue stays discoverable"},{id:"target-suffix-tmp-token",era:"current",match:/^(.+)\.tmp\.[0-9a-z-]{6,}$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/turbo/lean/state.ts:246","src/turbo/lean/recovery.ts:175","src/hooks/delegation-gate/worktree-merge-status.ts:110"]},{id:"target-suffix-tmp-dash",era:"current",match:/^(.+)\.tmp-\d+-[0-9a-z-]+$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/services/skill-evaluator.ts:492 (pre-#2035)","src/services/skill-improver.ts:154 (pre-#2035)","src/services/skill-consolidation.ts:72 (pre-#2035)","src/services/skill-generator.ts:601 (pre-#2035)","src/tools/spec-write.ts:98","src/sdd/effective-spec.ts:1149","src/background/lane-output-store.ts:353","src/background/pending-delegations.ts:924","src/background/delegation-health.ts:300","src/hooks/delegation-gate/worktree-provisioning-owner.ts:100","src/tools/submit-phase-council-verdicts.ts:458","src/summaries/store.ts:46 (pre-#2035)"],note:"background lane/delegation stores keep bounded-retry rename semantics wired into their callers (#2034/#2276 delivery contracts); migration candidates for a follow-up but grammars registered"},{id:"target-suffix-tmp-dash-num",era:"current",match:/^(.+)\.tmp-\d+$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/services/skill-improver-quota.ts:114"]},{id:"target-dot-pid-uuid-tmp",era:"current",match:new RegExp(`^(.+)\\.\\d+\\.${UUID_RE}\\.tmp$`),token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/hooks/knowledge-receipt-ledger-storage.ts:591"],note:"pre/post-rename file-identity verification (existingFileIdentity checks, knowledge-receipt-ledger-storage.ts:544-591) is writer-specific and load-bearing"},{id:"dot-numeric-instance-tmp",era:"current",match:/^\..+(?:\.\d+){2,4}\.[0-9a-z]+\.tmp$/,token:"instance",quarantineEligible:!0,parsesTarget:!1,producers:["src/utils/bun-compat.ts:138","src/tools/repo-graph/freshness.ts:171"],note:"bunWrite Node-fallback internal temp and the repo-graph fingerprint temp (2-4 numeric token groups); leading-dot temps are standalone, target not parsed"},{id:"dot-uuid-instance-tmp",era:"current",match:new RegExp(`^\\..+\\.${UUID_RE}\\.tmp$`),token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/tools/write-pr-review-artifact.ts:121","src/tools/write-pr-review-artifact.ts:141","src/tools/write-pr-review-trigger-eval.ts:96"],note:"bundled-skills writes outside .swarm (project skill roots) and keeps its own contained-directory logic (invariant 4 bundled-skill ownership)"},{id:"tmp-prefix-named",era:"legacy",match:/^\.tmp-.+-\d+-\d+$/,token:"instance",quarantineEligible:!0,parsesTarget:!1,producers:["src/commands/issue.ts:167 (pre-#2035)"],note:"prefix form embeds the filename; target not reliably parseable (dashes), so eligibility relies on the age/tracked/symlink/lock gates"},{id:"target-rebuild-close",era:"current",match:/^(.+)\.(?:rebuild|close)\.\d+\.[0-9a-z]+$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/plan/manager.ts:1979","src/plan/manager.ts:2168"],note:"plan-durability (invariant 5) fd-write paths; grammars registered, writers unchanged in this PR"},{id:"target-migration-pid",era:"current",match:/^(.+)\.migration-\d+$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/scope/scope-persistence.ts:633 (pre-#2035)"]},{id:"dot-tmp-prefix-legacy",era:"legacy",match:/^\.tmp\..+$/,token:"constant",quarantineEligible:!0,parsesTarget:!1,producers:["pre-7.x writers (historical); matched by the pre-#2035 close sweep"],note:"legacy prefix grammar: issue #2035 req 7 preserves its handling — stale instances are quarantined (formerly unlinked) under the same eligibility gates"},{id:"dot-constant-tmp",era:"current",match:/^\..+\.tmp$/,token:"constant",quarantineEligible:!1,parsesTarget:!1,producers:["src/tools/write-drift-evidence.ts:275","src/tools/write-mutation-evidence.ts:169","src/tools/write-hallucination-evidence.ts:121","src/tools/record-implementation-review.ts:87","src/tools/record-recurrence-sweep.ts:125","src/tools/record-issue-reproduction.ts:85","src/tools/record-issue-publication.ts:74","src/tools/write-final-council-evidence.ts:403"],note:"constant-name temps: no per-invocation token — reported when stale, never auto-quarantined (may be an in-flight writer of any process)"},{id:"target-constant-tmp",era:"current",match:/^(.+)\.tmp$/,token:"constant",quarantineEligible:!1,parsesTarget:!1,producers:["src/tools/checkpoint.ts:194","src/full-auto/state.ts:460","src/context-map/persistence.ts:119","src/context-map/capsule-persistence.ts:107","src/test-impact/history-store.ts:225","src/test-impact/history-store.ts:353","src/hooks/promotion-evidence-store.ts:102","src/hooks/skill-usage-log.ts:1145","src/hooks/skill-usage-log.ts:1650","src/hooks/skill-usage-pending.ts:816","src/parallel/file-locks.ts:113","src/plan/ledger.ts:1302","src/plan/ledger.ts:1303"],note:"constant-name temps: reported when stale, never auto-quarantined. file-locks meta sidecars live under the scanner-skipped .swarm/locks/ subtree; the ledger reconcile temp embeds instance tokens but its .tmp-suffix shape maps here (conservatively report-only)"}];WRITER_CLASSIFICATION=Object.freeze({"src/commands/close.ts":"migrated","src/commands/handoff.ts":"migrated","src/commands/simulate.ts":"migrated","src/commands/coupling.ts":"migrated","src/commands/issue.ts":"migrated","src/evidence/task-file.ts":"migrated","src/evidence/phase-participation.ts":"migrated","src/memory/reflection-service.ts":"migrated","src/scope/scope-persistence.ts":"migrated","src/services/skill-consolidation.ts":"migrated","src/services/skill-evaluator.ts":"migrated","src/services/skill-generator.ts":"migrated","src/services/skill-improver.ts":"migrated","src/summaries/store.ts":"migrated","src/background/delegation-health.ts":"registered-bespoke","src/background/lane-output-store.ts":"registered-bespoke","src/background/pending-delegations.ts":"registered-bespoke","src/commands/archive-sqlite.ts":"registered-bespoke","src/context-map/capsule-persistence.ts":"registered-bespoke","src/context-map/persistence.ts":"registered-bespoke","src/context-map/telemetry.ts":"registered-bespoke","src/evidence/documents-retention.ts":"registered-bespoke","src/evidence/manager.ts":"registered-bespoke","src/full-auto/state.ts":"registered-bespoke","src/hooks/delegation-gate/worktree-merge-status.ts":"registered-bespoke","src/hooks/delegation-gate/worktree-provisioning-owner.ts":"registered-bespoke","src/hooks/issue-trace-state.ts":"registered-bespoke","src/hooks/knowledge-receipt-ledger-storage.ts":"registered-bespoke","src/hooks/pr-workflow-gate.ts":"registered-bespoke","src/hooks/promotion-evidence-store.ts":"registered-bespoke","src/hooks/review-receipt.ts":"registered-bespoke","src/hooks/skill-usage-log.ts":"registered-bespoke","src/hooks/skill-usage-pending.ts":"registered-bespoke","src/knowledge/identity.ts":"registered-bespoke","src/memory/jsonl-migration.ts":"external","src/memory/local-jsonl-provider.ts":"registered-bespoke","src/plan/ledger.ts":"registered-bespoke","src/plan/manager.ts":"registered-bespoke","src/review/evidence.ts":"registered-bespoke","src/sdd/effective-spec.ts":"registered-bespoke","src/services/skill-improver-quota.ts":"registered-bespoke","src/services/skill-optimizer/activation.ts":"external","src/services/skill-optimizer/store.ts":"registered-bespoke","src/services/skill-reviser.ts":"external","src/services/synonym-map.ts":"registered-bespoke","src/session/snapshot-writer.ts":"registered-bespoke","src/summaries/manager.ts":"registered-bespoke","src/test-impact/history-store.ts":"registered-bespoke","src/turbo/epic/calibration.ts":"registered-bespoke","src/turbo/epic/state.ts":"registered-bespoke","src/turbo/lean/evidence.ts":"registered-bespoke","src/turbo/lean/integration.ts":"registered-bespoke","src/turbo/lean/recovery.ts":"registered-bespoke","src/turbo/lean/reviewer.ts":"registered-bespoke","src/turbo/lean/state.ts":"registered-bespoke","src/tools/apply-patch.ts":"external","src/tools/checkpoint.ts":"registered-bespoke","src/tools/record-implementation-review.ts":"registered-bespoke","src/tools/record-issue-publication.ts":"registered-bespoke","src/tools/record-issue-reproduction.ts":"registered-bespoke","src/tools/record-recurrence-sweep.ts":"registered-bespoke","src/tools/repo-graph/freshness.ts":"registered-bespoke","src/tools/repo-graph/storage.ts":"registered-bespoke","src/tools/sast-baseline.ts":"registered-bespoke","src/tools/spec-write.ts":"registered-bespoke","src/tools/submit-phase-council-verdicts.ts":"registered-bespoke","src/tools/write-drift-evidence.ts":"registered-bespoke","src/tools/write-final-council-evidence.ts":"registered-bespoke","src/tools/write-hallucination-evidence.ts":"registered-bespoke","src/tools/write-mutation-evidence.ts":"registered-bespoke","src/tools/write-pr-review-artifact.ts":"registered-bespoke","src/tools/write-pr-review-trigger-eval.ts":"registered-bespoke","src/config/bundled-skills.ts":"external","src/services/config-doctor.ts":"external","src/parallel/file-locks.ts":"registered-bespoke","src/utils/bun-compat.ts":"registered-bespoke","src/background/plan-sync-worker.ts":"reader-only","src/config/lane-permissions.ts":"reader-only","src/environment/profile.ts":"reader-only","src/worktree/core.ts":"reader-only"});RENAME_RETRY_DELAYS_MS=[10,25,50,100,200],RETRYABLE_RENAME_CODES=new Set(["EPERM","EBUSY","EACCES","EEXIST"]),_internals15={randomSuffix:()=>randomBytes2(16).toString("hex"),writeSync:(fd,buffer,offset,length)=>fs12.writeSync(fd,buffer,offset,length),renameSync:(from,to)=>fs12.renameSync(from,to),unlinkSync:(p)=>fs12.unlinkSync(p),fsyncSync:(fd)=>fs12.fsyncSync(fd)}});import*as path18 from"node:path";function taskEvidenceRelPath(taskId){return path18.join("evidence",`${taskId}.json`)}function taskEvidencePath(directory,taskId){return path18.join(directory,".swarm",taskEvidenceRelPath(taskId))}async function atomicWriteFile(targetPath,content){await atomicWriteFileAnyRoot(targetPath,content)}function withTaskEvidenceLock(directory,taskId,agent,fn2){return withEvidenceLock(directory,taskEvidenceRelPath(taskId),agent,taskId,fn2)}var init_task_file=__esm(()=>{init_atomic_write();init_lock()});import{createHash as createHash13}from"node:crypto";import*as fs13 from"node:fs";import*as path19 from"node:path";function samePath(left,right){let normalize3=(value)=>process.platform==="win32"?path19.resolve(value).toLowerCase():path19.resolve(value);return normalize3(left)===normalize3(right)}function assertSafeRequirementsParent(directory,create){assertProjectRoot(directory,void 0,"task gate requirements");let rootStat=fs13.lstatSync(directory);if(rootStat.isSymbolicLink()||!rootStat.isDirectory())throw Error("TASK_GATE_REQUIREMENTS_UNREADABLE: project root is not a regular directory");let canonicalRoot=fs13.realpathSync(directory),segments=[".swarm","evidence","task-gate-requirements"],current=canonicalRoot;for(let segment of segments){current=path19.join(current,segment);let info;try{info=fs13.lstatSync(current)}catch(error49){if(error49.code==="ENOENT"){if(!create)return current;try{fs13.mkdirSync(current)}catch(mkdirError){if(mkdirError.code!=="EEXIST")throw mkdirError}info=fs13.lstatSync(current)}else throw error49}if(info.isSymbolicLink()||!info.isDirectory())throw Error("TASK_GATE_REQUIREMENTS_UNREADABLE: receipt parent is redirected or not a directory");let canonicalCurrent=fs13.realpathSync(current);if(!samePath(canonicalCurrent,current))throw Error("TASK_GATE_REQUIREMENTS_UNREADABLE: receipt parent escaped the project root")}return current}function safeTaskGateRequirementsReceiptPath(directory,taskId,createParent){let parent=assertSafeRequirementsParent(directory,createParent);return path19.join(parent,`${taskId}.jsonl`)}function sha256(value){return createHash13("sha256").update(value).digest("hex")}function canonicalReceiptPayload(receipt){return JSON.stringify({...receipt,requiredGates:[...receipt.requiredGates]})}function computeChainHash(receipt){return sha256(canonicalReceiptPayload(receipt))}function readBoundedTextFile(filePath){let pathStat;try{pathStat=fs13.lstatSync(filePath)}catch(error49){if(error49.code==="ENOENT")return null;throw error49}if(pathStat.isSymbolicLink()||!pathStat.isFile())throw Error("TASK_GATE_REQUIREMENTS_UNREADABLE: receipt path is not a regular file");if(pathStat.size>MAX_TASK_GATE_REQUIREMENTS_BYTES)throw Error(`TASK_GATE_REQUIREMENTS_OVERSIZED: ${pathStat.size} bytes exceeds ${MAX_TASK_GATE_REQUIREMENTS_BYTES}`);let descriptor=fs13.openSync(filePath,fs13.constants.O_RDONLY|(fs13.constants.O_NOFOLLOW??0));try{let openedStat=fs13.fstatSync(descriptor);if(!openedStat.isFile()||openedStat.dev!==pathStat.dev||openedStat.ino!==pathStat.ino)throw Error("TASK_GATE_REQUIREMENTS_UNREADABLE: receipt changed while being opened");if(openedStat.size>MAX_TASK_GATE_REQUIREMENTS_BYTES)throw Error(`TASK_GATE_REQUIREMENTS_OVERSIZED: ${openedStat.size} bytes exceeds ${MAX_TASK_GATE_REQUIREMENTS_BYTES}`);return fs13.readFileSync(descriptor,"utf-8")}finally{fs13.closeSync(descriptor)}}async function readTaskGateRequirementsReceipts(directory,taskId){let filePath=safeTaskGateRequirementsReceiptPath(directory,taskId,!1),text=readBoundedTextFile(filePath);if(text===null)return[];let receipts=[];for(let line of text.split(`
273
+ LIMIT 1`).get(readablePlanId)??null}function buildExactStoragePlanId(identityHash){return`qa2-${identityHash}`}function hasAnyGatePatch(gates){return Object.values(gates).some((value)=>value!==void 0)}function verifyBoundIdentityBinding(binding,identity){if(binding.identity_hash!==identity.identityHash||binding.raw_swarm!==identity.swarm||binding.raw_title!==identity.title||binding.readable_plan_id!==identity.planId)throw Error(`QA gate profile identity binding is corrupt for swarm_id='${identity.swarm}' and plan_title='${identity.title}'`)}function lookupProfileForIdentityTx(db,identity){let binding=readIdentityBindingByHash(db,identity.identityHash);if(binding){verifyBoundIdentityBinding(binding,identity);let row=readProfileRowById(db,binding.profile_id);if(!row)throw Error(`QA gate profile identity binding points to missing profile_id=${binding.profile_id}`);return{kind:"bound",identity,profile:rowToProfileWithBinding(row,binding)}}let legacyRow=readUnboundLegacyProfileRowByReadablePlanId(db,identity.planId);if(legacyRow)return{kind:"unbound_legacy",identity,profile:rowToProfile(legacyRow)};return{kind:"missing",identity}}function createExactIdentityBindingTx(db,profileId,identity){db.run("INSERT INTO qa_gate_profile_identity (identity_hash, profile_id, raw_swarm, raw_title, readable_plan_id) VALUES (?, ?, ?, ?, ?)",[identity.identityHash,profileId,identity.swarm,identity.title,identity.planId])}function createExactProfileTx(db,identity,projectType,initialGates){let gatesJson=JSON.stringify({...DEFAULT_QA_GATES,...initialGates});db.run("INSERT INTO qa_gate_profile (plan_id, project_type, gates) VALUES (?, ?, ?)",[buildExactStoragePlanId(identity.identityHash),projectType??null,gatesJson]);let row=readProfileRowByPlanId(db,buildExactStoragePlanId(identity.identityHash));if(!row)throw Error(`Failed to create QA gate profile row for exact identity plan_id=${identity.planId}`);createExactIdentityBindingTx(db,row.id,identity);let binding=readIdentityBindingByHash(db,identity.identityHash);if(!binding)throw Error(`Failed to create QA gate profile identity binding for plan_id=${identity.planId}`);return rowToProfileWithBinding(row,binding)}function shouldAdoptLegacyProfile(identity,options){if(options.allowLegacyAdoption!==!0)return!1;return options.legacyAdoptionIdentity?.swarm===identity.swarm&&options.legacyAdoptionIdentity?.title===identity.title}function getProfile(directory,planId){if(!projectDbExists(directory))return null;let db=getProjectDb(directory),row=readProfileRowByPlanId(db,planId);return row?rowToProfile(row):null}function getProfileForIdentity(directory,identity){let lookup=getProfileLookupForIdentity(directory,identity);if(lookup.kind==="bound")return lookup.profile;if(lookup.kind==="unbound_legacy")throw new QaGateProfileIdentityUnboundError(lookup.identity);return null}function getProfileLookupForIdentity(directory,identity){let exact=buildProfileIdentity(identity);if(!projectDbExists(directory))return{kind:"missing",identity:exact};let db=getProjectDb(directory);return lookupProfileForIdentityTx(db,exact)}function hasAnyProfileWithEnabledGate(directory,gate){if(!projectDbExists(directory))return!1;let rows=getProjectDb(directory).query("SELECT gates FROM qa_gate_profile").all();for(let row of rows)try{if(JSON.parse(row.gates)?.[gate]===!0)return!0}catch{}return!1}function getOrCreateProfile(directory,planId,projectType,initialGates={}){let existing=_internals14.getProfile(directory,planId);if(existing)return existing;let db=getProjectDb(directory),seededGates={...DEFAULT_QA_GATES};for(let key of Object.keys(DEFAULT_QA_GATES))if(typeof initialGates[key]==="boolean")seededGates[key]=initialGates[key];let gatesJson=JSON.stringify(seededGates),insert=db.transaction(()=>{db.run("INSERT INTO qa_gate_profile (plan_id, project_type, gates) VALUES (?, ?, ?)",[planId,projectType??null,gatesJson])});try{insert()}catch(err){if(!(err instanceof Error?err.message:String(err)).toLowerCase().includes("unique"))throw err}let after=_internals14.getProfile(directory,planId);if(!after)throw Error(`Failed to create or load QA gate profile for plan_id=${planId}`);return after}function getOrCreateProfileForIdentity(directory,identity,projectType,initialGates={}){let db=getProjectDb(directory),exact=buildProfileIdentity(identity);return withImmediateTransaction(db,()=>{let lookup=lookupProfileForIdentityTx(db,exact);if(lookup.kind==="bound")return lookup.profile;if(lookup.kind==="unbound_legacy")return createExactProfileTx(db,exact,projectType,initialGates);return createExactProfileTx(db,exact,projectType,initialGates)})}function setGates(directory,planId,gates){let db=getProjectDb(directory),savepointName=`qa_gate_profile_set_${qaGateProfileSavepointCounter++}`,startedTransaction=!db.inTransaction;db.run(startedTransaction?"BEGIN IMMEDIATE":`SAVEPOINT ${savepointName}`);try{let currentRow=db.query("SELECT * FROM qa_gate_profile WHERE plan_id = ?").get(planId);if(!currentRow)throw Error(`No QA gate profile found for plan_id=${planId} — call getOrCreateProfile first`);let current=rowToProfile(currentRow);if(current.locked_at!==null)throw Error("Cannot modify gates: QA gate profile is locked after critic approval");_internals14.afterSetGatesRead(current);let merged={...current.gates};for(let key of Object.keys(gates)){let incoming=gates[key];if(incoming===void 0)continue;if(incoming===!1&&current.gates[key]===!0)throw Error(`Cannot disable gate '${key}': sessions can only ratchet tighter`);if(incoming===!0)merged[key]=!0}db.run("UPDATE qa_gate_profile SET gates = ? WHERE plan_id = ?",[JSON.stringify(merged),planId]);let updatedRow=db.query("SELECT * FROM qa_gate_profile WHERE plan_id = ?").get(planId);if(!updatedRow)throw Error(`Failed to re-read QA gate profile after update for plan_id=${planId}`);return db.run(startedTransaction?"COMMIT":`RELEASE ${savepointName}`),rowToProfile(updatedRow)}catch(err){try{if(db.run(startedTransaction?"ROLLBACK":`ROLLBACK TO ${savepointName}`),!startedTransaction)db.run(`RELEASE ${savepointName}`)}catch{}throw err}}function setGatesForIdentity(directory,identity,gates,options={}){let db=getProjectDb(directory),exact=buildProfileIdentity(identity),savepointName=`qa_gate_profile_set_identity_${qaGateProfileSavepointCounter++}`,startedTransaction=!db.inTransaction,finishTransaction=()=>{db.run(startedTransaction?"COMMIT":`RELEASE ${savepointName}`)},rollbackTransaction=()=>{if(db.run(startedTransaction?"ROLLBACK":`ROLLBACK TO ${savepointName}`),!startedTransaction)db.run(`RELEASE ${savepointName}`)};db.run(startedTransaction?"BEGIN IMMEDIATE":`SAVEPOINT ${savepointName}`);try{let lookup=lookupProfileForIdentityTx(db,exact);if(lookup.kind==="missing"){let created=createExactProfileTx(db,exact,options.projectType,gates);return finishTransaction(),created}if(lookup.kind==="unbound_legacy")if(shouldAdoptLegacyProfile(exact,options)){if(createExactIdentityBindingTx(db,lookup.profile.id,exact),lookup=lookupProfileForIdentityTx(db,exact),lookup.kind!=="bound")throw Error(`Failed to adopt legacy QA gate profile for exact identity plan_id=${exact.planId}`)}else if(options.allowLegacyCollisionCreate===!0){let created=createExactProfileTx(db,exact,options.projectType,gates);return finishTransaction(),created}else throw new QaGateProfileIdentityUnboundError(lookup.identity);let current=lookup.profile,currentRow=readProfileRowById(db,current.id);if(!currentRow)throw Error(`Failed to read QA gate profile row for profile_id=${current.id}`);if(_internals14.afterSetGatesForIdentityRead?.({directory,identity:exact,profileId:current.id,storagePlanId:currentRow.plan_id}),current.locked_at!==null){if(!hasAnyGatePatch(gates))return finishTransaction(),current;throw Error("Cannot modify gates: QA gate profile is locked after critic approval")}let merged={...current.gates};for(let key of Object.keys(gates)){let incoming=gates[key];if(incoming===void 0)continue;if(incoming===!1&&current.gates[key]===!0)throw Error(`Cannot disable gate '${key}': sessions can only ratchet tighter`);if(incoming===!0)merged[key]=!0}db.run("UPDATE qa_gate_profile SET gates = ? WHERE id = ?",[JSON.stringify(merged),current.id]);let updatedRow=readProfileRowById(db,current.id),binding=readIdentityBindingByHash(db,exact.identityHash);if(!updatedRow||!binding)throw Error(`Failed to re-read QA gate profile after exact-identity update for plan_id=${exact.planId}`);return finishTransaction(),rowToProfileWithBinding(updatedRow,binding)}catch(err){try{rollbackTransaction()}catch{}throw err}}function lockProfileForIdentity(directory,identity,snapshotSeq){let db=getProjectDb(directory),exact=buildProfileIdentity(identity);return withImmediateTransaction(db,()=>{let lookup=lookupProfileForIdentityTx(db,exact);if(lookup.kind==="missing")throw Error(`No QA gate profile found for exact identity plan_id=${exact.planId} — cannot lock`);if(lookup.kind==="unbound_legacy")throw new QaGateProfileIdentityUnboundError(lookup.identity);if(lookup.profile.locked_at!==null)return lookup.profile;db.run("UPDATE qa_gate_profile SET locked_at = datetime('now'), locked_by_snapshot_seq = ? WHERE id = ?",[snapshotSeq,lookup.profile.id]);let updatedRow=readProfileRowById(db,lookup.profile.id),binding=readIdentityBindingByHash(db,exact.identityHash);if(!updatedRow||!binding)throw Error(`Failed to re-read locked QA gate profile for exact identity plan_id=${exact.planId}`);return rowToProfileWithBinding(updatedRow,binding)})}function computeProfileHash(profile){let payload=JSON.stringify({plan_id:profile.plan_id,identity_hash:profile.identity_hash,gates:profile.gates});return createHash11("sha256").update(payload).digest("hex")}function getEffectiveGates(profile,sessionOverrides){let merged={...profile.gates};for(let key of Object.keys(sessionOverrides))if(sessionOverrides[key]===!0)merged[key]=!0;return merged}var _internals14,DEFAULT_QA_GATES,QaGateProfileIdentityUnboundError,qaGateProfileSavepointCounter=0;var init_qa_gate_profile=__esm(()=>{init_utils3();init_project_db();_internals14={getProfile,getProfileLookupForIdentity,getProfileForIdentity,getOrCreateProfile,getOrCreateProfileForIdentity,setGates,setGatesForIdentity,lockProfileForIdentity,getEffectiveGates,computeProfileHash,hasAnyProfileWithEnabledGate,afterSetGatesRead:()=>{}},DEFAULT_QA_GATES={reviewer:!0,test_engineer:!0,council_mode:!1,sme_enabled:!0,critic_pre_plan:!0,hallucination_guard:!1,sast_enabled:!0,mutation_test:!1,phase_council:!1,drift_check:!0,final_council:!1};QaGateProfileIdentityUnboundError=class QaGateProfileIdentityUnboundError extends Error{identity;constructor(identity){super(`QA gate profile exists for readable plan_id='${identity.planId}' but is not exact-bound to swarm_id='${identity.swarm}' and plan_title='${identity.title}'. ${formatLegacyQaBindingRecovery(identity,"retry the blocked read-only or enforcement operation")}`);this.name="QaGateProfileIdentityUnboundError",this.identity=identity}}});function detectHostOS(){switch(process.platform){case"win32":return"windows";case"darwin":return"macos";case"linux":return"linux";default:return"unknown"}}function detectShellFamily(){if(process.env.PSModulePath)return"powershell";if((process.env.ComSpec??"").toLowerCase().includes("cmd.exe"))return"cmd";let shell=process.env.SHELL??"";if(shell.includes("bash"))return"bash";if(shell.includes("zsh"))return"zsh";if(shell.includes("/sh"))return"sh";return"unknown"}function detectExecutionMode(hostOS){if(process.env.WSL_DISTRO_NAME)return"wsl";if(hostOS==="linux"){if(["DOCKER_CONTAINER","KUBERNETES_SERVICE_HOST","CONTAINER"].some((k)=>process.env[k]))return"docker"}return"native"}function deriveOperatingMode(hostOS,_executionMode){if(hostOS==="linux")return"linux";if(hostOS==="macos")return"macos-native";if(hostOS==="windows")return"windows-native";return"unknown"}function buildCommandPolicy(profile){if(profile.isWindowsNative)return{preferredShell:"powershell",avoidPosixExamples:!0,preferNodeApis:!0,preferToolingOverShell:!0,pathExampleStyle:"windows",examples:{listDir:"Get-ChildItem -Force",removeFile:"Remove-Item file.tmp",setEnv:'$env:DEBUG = "1"',printEnv:"$env:PATH",searchText:'Get-ChildItem -Recurse src | Select-String "foo"'}};return{preferredShell:profile.shellFamily==="unknown"?"bash":profile.shellFamily,avoidPosixExamples:!1,preferNodeApis:!0,preferToolingOverShell:!0,pathExampleStyle:"posix",examples:{listDir:"ls -la",removeFile:"rm file.tmp",setEnv:"export DEBUG=1",printEnv:"echo $PATH",searchText:'grep -R "foo" src/'}}}function detectEnvironmentProfile(){let hostOS=detectHostOS(),shellFamily=detectShellFamily(),executionMode=detectExecutionMode(hostOS),operatingMode=deriveOperatingMode(hostOS,executionMode),isWindowsNative=hostOS==="windows"&&executionMode==="native",isWindowsDocker=!1;return{hostOS,shellFamily,executionMode,operatingMode,isWindowsNative,isWindowsDocker:!1,isWSL:executionMode==="wsl",pathStyle:hostOS==="windows"?"windows":"posix",shellCommandPreference:isWindowsNative?"powershell-native":"posix-native",evidence:{processPlatform:process.platform,comspec:process.env.ComSpec,psModulePath:process.env.PSModulePath,termProgram:process.env.TERM_PROGRAM,shell:process.env.SHELL,wslDistroName:process.env.WSL_DISTRO_NAME,containerMarkers:["DOCKER_CONTAINER","KUBERNETES_SERVICE_HOST","CONTAINER"].filter((k)=>!!process.env[k])}}}function deriveCommandPolicy(profile){return buildCommandPolicy(profile)}import{createHash as createHash12}from"node:crypto";function hashString(value){return createHash12("sha256").update(value).digest("hex")}function circuitKey(sessionID,invocationID,actionDigest,circuitKind){return`${sessionID}\x00${invocationID}\x00${actionDigest}\x00${circuitKind}`}function familyKey(sessionID,invocationID,actionDigest){return`${sessionID}\x00${invocationID}\x00${actionDigest}`}function familyPrefix(sessionID,invocationID){return`${sessionID}\x00${invocationID}\x00`}function sessionPrefix(sessionID){return`${sessionID}\x00`}function removeEntry(key){actionCircuits.delete(key)}function pruneGenerationTokenIfUnused(family){let prefix=`${family}\x00`,hasEntries=[...actionCircuits.keys()].some((key)=>key.startsWith(prefix)),isArmed=armedActions.has(family);if(!hasEntries&&!isArmed)actionGenerationTokens.delete(family)}function sweepExpired(now){for(let[key,entry]of actionCircuits)if(entry.expiresAt<=now)removeEntry(key),pruneGenerationTokenIfUnused(familyKey(entry.sessionID,entry.invocationID,entry.actionDigest));for(let[family,armedToken]of armedActions)if(actionGenerationTokens.get(family)!==armedToken)armedActions.delete(family)}function ensureGenerationToken(sessionID,invocationID,actionDigest){let family=familyKey(sessionID,invocationID,actionDigest),current=actionGenerationTokens.get(family);if(current!==void 0)return current;return actionGenerationTokens.set(family,1),1}function bumpGenerationToken(sessionID,invocationID,actionDigest){let family=familyKey(sessionID,invocationID,actionDigest),next=ensureGenerationToken(sessionID,invocationID,actionDigest)+1;return actionGenerationTokens.set(family,next),armedActions.delete(family),next}function touchEntry(key,entry,now){let touched={...entry,expiresAt:now+ACTION_CIRCUIT_TTL_MS};return actionCircuits.delete(key),actionCircuits.set(key,touched),touched}function enforceCapacity(){while(actionCircuits.size>MAX_TRACKED_ACTION_CIRCUITS){let oldest=actionCircuits.keys().next().value;if(oldest===void 0)break;let entry=actionCircuits.get(oldest);if(removeEntry(oldest),entry)pruneGenerationTokenIfUnused(familyKey(entry.sessionID,entry.invocationID,entry.actionDigest))}}function recordResetAudit(record2){if(resetAudit.push(record2),resetAudit.length>MAX_RESET_AUDIT_ROWS)resetAudit.shift()}function armActionCircuitAttempt(sessionID,invocationID,actionDigest){let token=ensureGenerationToken(sessionID,invocationID,actionDigest);return armedActions.set(familyKey(sessionID,invocationID,actionDigest),token),token}function noteActionCircuitFailure(input){let now=input.now??Date.now();sweepExpired(now);let family=familyKey(input.sessionID,input.invocationID,input.actionDigest),expectedToken=input.generationToken??armedActions.get(family)??null,currentToken=ensureGenerationToken(input.sessionID,input.invocationID,input.actionDigest);if(expectedToken===null||expectedToken!==currentToken)return{entry:null,enteredHardStop:!1,ignoredLateEvent:!0};let key=circuitKey(input.sessionID,input.invocationID,input.actionDigest,input.circuitKind),existing=actionCircuits.get(key),count=(existing?.count??0)+1,hardStop=count>=input.hardStopThreshold,entry={sessionID:input.sessionID,invocationID:input.invocationID,actionDigest:input.actionDigest,circuitKind:input.circuitKind,count,hardStop,generationToken:currentToken,lastSignalDigest:input.signal?hashString(input.signal):null,firstSeenAt:existing?.firstSeenAt??now,updatedAt:now,expiresAt:now+ACTION_CIRCUIT_TTL_MS};return actionCircuits.delete(key),actionCircuits.set(key,entry),enforceCapacity(),{entry,enteredHardStop:hardStop&&!existing?.hardStop,ignoredLateEvent:!1}}function clearActionCircuitEntries(sessionID,invocationID,actionDigest){let prefix=`${familyKey(sessionID,invocationID,actionDigest)}\x00`;for(let key of[...actionCircuits.keys()])if(key.startsWith(prefix))removeEntry(key)}function clearActionCircuit(sessionID,invocationID,actionDigest,options){if(clearActionCircuitEntries(sessionID,invocationID,actionDigest),bumpGenerationToken(sessionID,invocationID,actionDigest),options?.reason)recordResetAudit({sessionID,invocationID,actionDigest,reason:options.reason,actor:options.actor??null,at:options.now??Date.now()})}function resetActionCircuitExternally(input){clearActionCircuit(input.sessionID,input.invocationID,input.actionDigest,{reason:"external",actor:input.actor??null,now:input.now})}function clearInvocationActionCircuits(sessionID,invocationID,now){let prefix=familyPrefix(sessionID,invocationID);for(let key of[...actionCircuits.keys()])if(key.startsWith(prefix))removeEntry(key);for(let family of[...actionGenerationTokens.keys()])if(family.startsWith(prefix))actionGenerationTokens.delete(family),armedActions.delete(family),recordResetAudit({sessionID,invocationID,actionDigest:family.slice(prefix.length),reason:"invocation",actor:null,at:now??Date.now()})}function clearSessionActionCircuits(sessionID,now){let prefix=sessionPrefix(sessionID);for(let key of[...actionCircuits.keys()])if(key.startsWith(prefix))removeEntry(key);for(let family of[...actionGenerationTokens.keys()])if(family.startsWith(prefix)){let familyTail=family.slice(prefix.length),separatorIndex=familyTail.indexOf("\x00"),invocationID=separatorIndex>0?Number(familyTail.slice(0,separatorIndex)):0,actionDigest=separatorIndex>0?familyTail.slice(separatorIndex+1):familyTail;actionGenerationTokens.delete(family),armedActions.delete(family),recordResetAudit({sessionID,invocationID,actionDigest,reason:"session",actor:null,at:now??Date.now()})}}function getBlockingActionCircuit(sessionID,invocationID,actionDigest){let now=Date.now();sweepExpired(now);let prefix=`${familyKey(sessionID,invocationID,actionDigest)}\x00`;for(let[key,entry]of actionCircuits)if(key.startsWith(prefix)&&entry.hardStop)return touchEntry(key,entry,now);return null}function listBlockingActionCircuitsForInvocation(sessionID,invocationID){let now=Date.now();sweepExpired(now);let prefix=familyPrefix(sessionID,invocationID),result=[];for(let[key,entry]of[...actionCircuits])if(key.startsWith(prefix)&&entry.hardStop)result.push(touchEntry(key,entry,now));return result}function peekActionCircuitCount(sessionID,invocationID,actionDigest,circuitKind){return actionCircuits.get(circuitKey(sessionID,invocationID,actionDigest,circuitKind))?.count??0}function expireActionCircuit(sessionID,invocationID,actionDigest,circuitKind){let entry=actionCircuits.get(circuitKey(sessionID,invocationID,actionDigest,circuitKind));if(entry)entry.expiresAt=Date.now()-1}function clearAllActionCircuits(){actionCircuits.clear(),actionGenerationTokens.clear(),armedActions.clear(),resetAudit.length=0}var MAX_TRACKED_ACTION_CIRCUITS=500,ACTION_CIRCUIT_TTL_MS=1800000,MAX_RESET_AUDIT_ROWS=128,actionCircuits,actionGenerationTokens,armedActions,resetAudit,_test_exports;var init_action_circuit=__esm(()=>{actionCircuits=new Map,actionGenerationTokens=new Map,armedActions=new Map,resetAudit=[];_test_exports={ACTION_CIRCUIT_TTL_MS,MAX_TRACKED_ACTION_CIRCUITS,size:()=>actionCircuits.size,getGenerationToken:(sessionID,invocationID,actionDigest)=>ensureGenerationToken(sessionID,invocationID,actionDigest),getResetAudit:()=>resetAudit.map((entry)=>({...entry}))}});import{randomBytes as randomBytes2}from"node:crypto";import*as fs12 from"node:fs";import*as path17 from"node:path";function matchTempGrammar(basename3){return SWARM_TEMP_GRAMMARS.find((g)=>g.match.test(basename3))}function parseTargetBasename(basename3){for(let g of SWARM_TEMP_GRAMMARS){if(!g.parsesTarget)continue;let m=g.match.exec(basename3);if(m?.[1])return m[1]}return null}function assertWellFormedTargetPath(targetPath){if(!path17.isAbsolute(targetPath))throw Error(`atomic-write target must be absolute: ${targetPath}`);if(/[\0-\x1f\x7f]/.test(targetPath))throw Error("atomic-write target contains control characters");if(/[*?]/.test(targetPath)||/(^|[/\\])\{[^}]*\}([/\\]|$)/.test(targetPath))throw Error(`atomic-write target contains glob metacharacters: ${targetPath}`);if(/(^|[/\\])~([/\\]|$)/.test(targetPath))throw Error("atomic-write target contains unresolved home-dir marker (~)");if(/\$\{?[A-Za-z_][A-Za-z0-9_]*\}?/.test(targetPath)||/%[^/\\%]+%/.test(targetPath))throw Error("atomic-write target contains unresolved environment-variable form")}function lstatNotSymlink(p,what){if(fs12.lstatSync(p).isSymbolicLink())throw Error(`${what} is a symlink/reparse point: ${p}`)}function assertSwarmContainedTarget(targetPath){assertWellFormedTargetPath(targetPath);let resolved=path17.normalize(path17.resolve(targetPath)),segments=resolved.split(path17.sep),swarmIdx=-1;for(let i=segments.length-2;i>=1;i--)if(segments[i]===".swarm"){swarmIdx=i;break}if(swarmIdx===-1)throw Error(`atomic-write target is not under a project .swarm root: ${targetPath}`);let swarmRoot=segments.slice(0,swarmIdx+1).join(path17.sep);try{let st=fs12.lstatSync(swarmRoot);if(!st.isDirectory()||st.isSymbolicLink())throw Error(`.swarm root is not a real directory (symlink/reparse or non-dir): ${swarmRoot}`)}catch(err){if(err?.code!=="ENOENT")throw err}let rel=path17.relative(swarmRoot,resolved);if(!rel||rel.startsWith("..")||path17.isAbsolute(rel))throw Error(`atomic-write target escapes .swarm root: ${targetPath}`);let probe=swarmRoot;for(let seg of rel.split(path17.sep)){if(probe=path17.join(probe,seg),!fs12.existsSync(probe))break;lstatNotSymlink(probe,"path segment under .swarm")}return{projectRoot:path17.dirname(swarmRoot),swarmRoot}}function toBuffer(content){if(typeof content==="string")return Buffer.from(content,"utf-8");return content}function syncSleep(ms){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,ms)}catch{let start=Date.now();while(Date.now()-start<ms);}}function renameWithRetry(tempPath,targetPath){let lastError;for(let attempt=0;attempt<=RENAME_RETRY_DELAYS_MS.length;attempt++)try{_internals15.renameSync(tempPath,targetPath);return}catch(err){lastError=err;let code=err?.code;if(!code||!RETRYABLE_RENAME_CODES.has(code))throw err;if(attempt<RENAME_RETRY_DELAYS_MS.length)syncSleep(RENAME_RETRY_DELAYS_MS[attempt])}throw lastError}function writeAtomicSync(targetPath,content,options){if(options?.contained!==!1)assertSwarmContainedTarget(targetPath);else assertWellFormedTargetPath(targetPath);let resolvedTarget=path17.resolve(targetPath),buffer=toBuffer(content),maxBytes=options?.maxBytes??MAX_ATOMIC_WRITE_BYTES;if(buffer.byteLength>maxBytes)throw Error(`atomic write exceeds ${maxBytes} byte bound: ${buffer.byteLength}`);let tempPath=`${resolvedTarget}.${_internals15.randomSuffix()}.tmp`;fs12.mkdirSync(path17.dirname(tempPath),{recursive:!0});try{let fd=fs12.openSync(tempPath,"wx");try{let written=0;while(written<buffer.byteLength)written+=_internals15.writeSync(fd,buffer,written,buffer.byteLength-written);if(options?.skipFsync!==!0)try{_internals15.fsyncSync(fd)}catch{}}finally{fs12.closeSync(fd)}renameWithRetry(tempPath,resolvedTarget)}finally{try{_internals15.unlinkSync(tempPath)}catch{}}try{let dirFd=fs12.openSync(path17.dirname(resolvedTarget),"r");try{fs12.fsyncSync(dirFd)}finally{fs12.closeSync(dirFd)}}catch{}invalidateCachedArtifact(resolvedTarget)}async function atomicWriteSwarmFile(targetPath,content,options){await new Promise((resolve12)=>setImmediate(resolve12)),writeAtomicSync(targetPath,content,options)}function atomicWriteSwarmFileSync(targetPath,content,options){writeAtomicSync(targetPath,content,options)}async function atomicWriteFileAnyRoot(targetPath,content,options){await new Promise((resolve12)=>setImmediate(resolve12)),writeAtomicSync(targetPath,content,{...options,contained:!1})}var UUID_RE="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",SWARM_TEMP_GRAMMARS,WRITER_CLASSIFICATION,MAX_ATOMIC_WRITE_BYTES=268435456,RENAME_RETRY_DELAYS_MS,RETRYABLE_RENAME_CODES,_internals15;var init_atomic_write=__esm(()=>{init_swarm_artifact_cache();SWARM_TEMP_GRAMMARS=[{id:"canonical-v1",era:"canonical",match:/^(.+)\.[0-9a-f]{32}\.tmp$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/utils/atomic-write.ts:atomicWriteSwarmFile","src/utils/atomic-write.ts:atomicWriteFileAnyRoot"]},{id:"target-suffix-tmp-uuid",era:"current",match:new RegExp(`^(.+)\\.tmp\\.${UUID_RE}$`),token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/commands/handoff.ts:48 (pre-#2035)","src/commands/handoff.ts:79 (pre-#2035)","src/memory/local-jsonl-provider.ts:1171","src/config/bundled-skills.ts:241"]},{id:"target-suffix-tmp-pid-uuid",era:"current",match:new RegExp(`^(.+)\\.tmp\\.\\d+\\.${UUID_RE}$`),token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/hooks/pr-workflow-gate.ts:14141"],note:"pre/post-rename file-identity verification (assertOpened/ClosedSwarmFileIdentity, pr-workflow-gate.ts:14083-14130) is writer-specific and load-bearing"},{id:"target-suffix-tmp-num-num-json",era:"current",match:/^(.+)\.tmp\.\d+\.\d+\.json$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/hooks/issue-trace-state.ts:315"],note:"the .json terminator keeps this shape distinct from the bare two-token family — declared before it so first-match wins"},{id:"target-suffix-tmp-num-alnum",era:"current",match:/^(.+)\.tmp\.\d+\.[0-9a-z]+$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/evidence/task-file.ts:67 (pre-#2035)","src/scope/scope-persistence.ts:2304 (pre-#2035)","src/scope/scope-persistence.ts:2318 (pre-#2035)","src/plan/manager.ts:628","src/plan/manager.ts:1793","src/plan/manager.ts:1839","src/review/evidence.ts:160","src/turbo/lean/evidence.ts:182","src/summaries/manager.ts:122","src/evidence/manager.ts:288","src/evidence/manager.ts:456","src/tools/sast-baseline.ts:106","src/tools/repo-graph/storage.ts:397","src/memory/reflection-service.ts:547 (pre-#2035)","src/hooks/review-receipt.ts:608","src/hooks/review-receipt.ts:674","src/hooks/review-receipt.ts:812","src/knowledge/identity.ts:209","src/evidence/phase-participation.ts:303 (pre-#2035)","src/turbo/lean/integration.ts:426","src/turbo/lean/reviewer.ts:403","src/plan/ledger.ts:713","src/services/synonym-map.ts:389","src/services/skill-optimizer/store.ts:340","src/services/skill-optimizer/store.ts:503","src/turbo/epic/state.ts:177","src/turbo/epic/calibration.ts:197","src/commands/archive-sqlite.ts:318","src/memory/jsonl-migration.ts:157"],note:"fsync-discipline / lock-scoped fd writers whose temp naming is pinned by their own durability test suites (plan-durability invariant 5, #2034 crash matrix); grammars registered here so their residue stays discoverable"},{id:"target-suffix-tmp-token",era:"current",match:/^(.+)\.tmp\.[0-9a-z-]{6,}$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/turbo/lean/state.ts:246","src/turbo/lean/recovery.ts:175","src/hooks/delegation-gate/worktree-merge-status.ts:110"]},{id:"target-suffix-tmp-dash",era:"current",match:/^(.+)\.tmp-\d+-[0-9a-z-]+$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/services/skill-evaluator.ts:492 (pre-#2035)","src/services/skill-improver.ts:154 (pre-#2035)","src/services/skill-consolidation.ts:72 (pre-#2035)","src/services/skill-generator.ts:601 (pre-#2035)","src/tools/spec-write.ts:98","src/sdd/effective-spec.ts:1149","src/background/lane-output-store.ts:353","src/background/pending-delegations.ts:982","src/background/delegation-health.ts:390","src/hooks/delegation-gate/worktree-provisioning-owner.ts:100","src/tools/submit-phase-council-verdicts.ts:458","src/summaries/store.ts:46 (pre-#2035)"],note:"background lane/delegation stores keep bounded-retry rename semantics wired into their callers (#2034/#2276 delivery contracts); migration candidates for a follow-up but grammars registered"},{id:"target-suffix-tmp-dash-num",era:"current",match:/^(.+)\.tmp-\d+$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/services/skill-improver-quota.ts:114"]},{id:"target-dot-pid-uuid-tmp",era:"current",match:new RegExp(`^(.+)\\.\\d+\\.${UUID_RE}\\.tmp$`),token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/hooks/knowledge-receipt-ledger-storage.ts:591"],note:"pre/post-rename file-identity verification (existingFileIdentity checks, knowledge-receipt-ledger-storage.ts:544-591) is writer-specific and load-bearing"},{id:"dot-numeric-instance-tmp",era:"current",match:/^\..+(?:\.\d+){2,4}\.[0-9a-z]+\.tmp$/,token:"instance",quarantineEligible:!0,parsesTarget:!1,producers:["src/utils/bun-compat.ts:138","src/tools/repo-graph/freshness.ts:171"],note:"bunWrite Node-fallback internal temp and the repo-graph fingerprint temp (2-4 numeric token groups); leading-dot temps are standalone, target not parsed"},{id:"dot-uuid-instance-tmp",era:"current",match:new RegExp(`^\\..+\\.${UUID_RE}\\.tmp$`),token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/tools/write-pr-review-artifact.ts:121","src/tools/write-pr-review-artifact.ts:141","src/tools/write-pr-review-trigger-eval.ts:96"],note:"bundled-skills writes outside .swarm (project skill roots) and keeps its own contained-directory logic (invariant 4 bundled-skill ownership)"},{id:"tmp-prefix-named",era:"legacy",match:/^\.tmp-.+-\d+-\d+$/,token:"instance",quarantineEligible:!0,parsesTarget:!1,producers:["src/commands/issue.ts:167 (pre-#2035)"],note:"prefix form embeds the filename; target not reliably parseable (dashes), so eligibility relies on the age/tracked/symlink/lock gates"},{id:"target-rebuild-close",era:"current",match:/^(.+)\.(?:rebuild|close)\.\d+\.[0-9a-z]+$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/plan/manager.ts:1979","src/plan/manager.ts:2168"],note:"plan-durability (invariant 5) fd-write paths; grammars registered, writers unchanged in this PR"},{id:"target-migration-pid",era:"current",match:/^(.+)\.migration-\d+$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/scope/scope-persistence.ts:633 (pre-#2035)"]},{id:"dot-tmp-prefix-legacy",era:"legacy",match:/^\.tmp\..+$/,token:"constant",quarantineEligible:!0,parsesTarget:!1,producers:["pre-7.x writers (historical); matched by the pre-#2035 close sweep"],note:"legacy prefix grammar: issue #2035 req 7 preserves its handling — stale instances are quarantined (formerly unlinked) under the same eligibility gates"},{id:"dot-constant-tmp",era:"current",match:/^\..+\.tmp$/,token:"constant",quarantineEligible:!1,parsesTarget:!1,producers:["src/tools/write-drift-evidence.ts:275","src/tools/write-mutation-evidence.ts:169","src/tools/write-hallucination-evidence.ts:121","src/tools/record-implementation-review.ts:87","src/tools/record-recurrence-sweep.ts:125","src/tools/record-issue-reproduction.ts:85","src/tools/record-issue-publication.ts:74","src/tools/write-final-council-evidence.ts:403"],note:"constant-name temps: no per-invocation token — reported when stale, never auto-quarantined (may be an in-flight writer of any process)"},{id:"target-constant-tmp",era:"current",match:/^(.+)\.tmp$/,token:"constant",quarantineEligible:!1,parsesTarget:!1,producers:["src/tools/checkpoint.ts:194","src/full-auto/state.ts:460","src/context-map/persistence.ts:119","src/context-map/capsule-persistence.ts:107","src/test-impact/history-store.ts:225","src/test-impact/history-store.ts:353","src/hooks/promotion-evidence-store.ts:102","src/hooks/skill-usage-log.ts:1145","src/hooks/skill-usage-log.ts:1650","src/hooks/skill-usage-pending.ts:816","src/parallel/file-locks.ts:113","src/plan/ledger.ts:1302","src/plan/ledger.ts:1303"],note:"constant-name temps: reported when stale, never auto-quarantined. file-locks meta sidecars live under the scanner-skipped .swarm/locks/ subtree; the ledger reconcile temp embeds instance tokens but its .tmp-suffix shape maps here (conservatively report-only)"}];WRITER_CLASSIFICATION=Object.freeze({"src/commands/close.ts":"migrated","src/commands/handoff.ts":"migrated","src/commands/simulate.ts":"migrated","src/commands/coupling.ts":"migrated","src/commands/issue.ts":"migrated","src/evidence/task-file.ts":"migrated","src/evidence/phase-participation.ts":"migrated","src/memory/reflection-service.ts":"migrated","src/scope/scope-persistence.ts":"migrated","src/services/skill-consolidation.ts":"migrated","src/services/skill-evaluator.ts":"migrated","src/services/skill-generator.ts":"migrated","src/services/skill-improver.ts":"migrated","src/summaries/store.ts":"migrated","src/background/delegation-health.ts":"registered-bespoke","src/background/lane-output-store.ts":"registered-bespoke","src/background/pending-delegations.ts":"registered-bespoke","src/commands/archive-sqlite.ts":"registered-bespoke","src/context-map/capsule-persistence.ts":"registered-bespoke","src/context-map/persistence.ts":"registered-bespoke","src/context-map/telemetry.ts":"registered-bespoke","src/evidence/documents-retention.ts":"registered-bespoke","src/evidence/manager.ts":"registered-bespoke","src/full-auto/state.ts":"registered-bespoke","src/hooks/delegation-gate/worktree-merge-status.ts":"registered-bespoke","src/hooks/delegation-gate/worktree-provisioning-owner.ts":"registered-bespoke","src/hooks/issue-trace-state.ts":"registered-bespoke","src/hooks/knowledge-receipt-ledger-storage.ts":"registered-bespoke","src/hooks/pr-workflow-gate.ts":"registered-bespoke","src/hooks/promotion-evidence-store.ts":"registered-bespoke","src/hooks/review-receipt.ts":"registered-bespoke","src/hooks/skill-usage-log.ts":"registered-bespoke","src/hooks/skill-usage-pending.ts":"registered-bespoke","src/knowledge/identity.ts":"registered-bespoke","src/memory/jsonl-migration.ts":"external","src/memory/local-jsonl-provider.ts":"registered-bespoke","src/plan/ledger.ts":"registered-bespoke","src/plan/manager.ts":"registered-bespoke","src/review/evidence.ts":"registered-bespoke","src/sdd/effective-spec.ts":"registered-bespoke","src/services/skill-improver-quota.ts":"registered-bespoke","src/services/skill-optimizer/activation.ts":"external","src/services/skill-optimizer/store.ts":"registered-bespoke","src/services/skill-reviser.ts":"external","src/services/synonym-map.ts":"registered-bespoke","src/session/snapshot-writer.ts":"registered-bespoke","src/summaries/manager.ts":"registered-bespoke","src/test-impact/history-store.ts":"registered-bespoke","src/turbo/epic/calibration.ts":"registered-bespoke","src/turbo/epic/state.ts":"registered-bespoke","src/turbo/lean/evidence.ts":"registered-bespoke","src/turbo/lean/integration.ts":"registered-bespoke","src/turbo/lean/recovery.ts":"registered-bespoke","src/turbo/lean/reviewer.ts":"registered-bespoke","src/turbo/lean/state.ts":"registered-bespoke","src/tools/apply-patch.ts":"external","src/tools/checkpoint.ts":"registered-bespoke","src/tools/record-implementation-review.ts":"registered-bespoke","src/tools/record-issue-publication.ts":"registered-bespoke","src/tools/record-issue-reproduction.ts":"registered-bespoke","src/tools/record-recurrence-sweep.ts":"registered-bespoke","src/tools/repo-graph/freshness.ts":"registered-bespoke","src/tools/repo-graph/storage.ts":"registered-bespoke","src/tools/sast-baseline.ts":"registered-bespoke","src/tools/spec-write.ts":"registered-bespoke","src/tools/submit-phase-council-verdicts.ts":"registered-bespoke","src/tools/write-drift-evidence.ts":"registered-bespoke","src/tools/write-final-council-evidence.ts":"registered-bespoke","src/tools/write-hallucination-evidence.ts":"registered-bespoke","src/tools/write-mutation-evidence.ts":"registered-bespoke","src/tools/write-pr-review-artifact.ts":"registered-bespoke","src/tools/write-pr-review-trigger-eval.ts":"registered-bespoke","src/config/bundled-skills.ts":"external","src/services/config-doctor.ts":"external","src/parallel/file-locks.ts":"registered-bespoke","src/utils/bun-compat.ts":"registered-bespoke","src/background/plan-sync-worker.ts":"reader-only","src/config/lane-permissions.ts":"reader-only","src/environment/profile.ts":"reader-only","src/worktree/core.ts":"reader-only"});RENAME_RETRY_DELAYS_MS=[10,25,50,100,200],RETRYABLE_RENAME_CODES=new Set(["EPERM","EBUSY","EACCES","EEXIST"]),_internals15={randomSuffix:()=>randomBytes2(16).toString("hex"),writeSync:(fd,buffer,offset,length)=>fs12.writeSync(fd,buffer,offset,length),renameSync:(from,to)=>fs12.renameSync(from,to),unlinkSync:(p)=>fs12.unlinkSync(p),fsyncSync:(fd)=>fs12.fsyncSync(fd)}});import*as path18 from"node:path";function taskEvidenceRelPath(taskId){return path18.join("evidence",`${taskId}.json`)}function taskEvidencePath(directory,taskId){return path18.join(directory,".swarm",taskEvidenceRelPath(taskId))}async function atomicWriteFile(targetPath,content){await atomicWriteFileAnyRoot(targetPath,content)}function withTaskEvidenceLock(directory,taskId,agent,fn2){return withEvidenceLock(directory,taskEvidenceRelPath(taskId),agent,taskId,fn2)}var init_task_file=__esm(()=>{init_atomic_write();init_lock()});import{createHash as createHash13}from"node:crypto";import*as fs13 from"node:fs";import*as path19 from"node:path";function samePath(left,right){let normalize3=(value)=>process.platform==="win32"?path19.resolve(value).toLowerCase():path19.resolve(value);return normalize3(left)===normalize3(right)}function assertSafeRequirementsParent(directory,create){assertProjectRoot(directory,void 0,"task gate requirements");let rootStat=fs13.lstatSync(directory);if(rootStat.isSymbolicLink()||!rootStat.isDirectory())throw Error("TASK_GATE_REQUIREMENTS_UNREADABLE: project root is not a regular directory");let canonicalRoot=fs13.realpathSync(directory),segments=[".swarm","evidence","task-gate-requirements"],current=canonicalRoot;for(let segment of segments){current=path19.join(current,segment);let info;try{info=fs13.lstatSync(current)}catch(error49){if(error49.code==="ENOENT"){if(!create)return current;try{fs13.mkdirSync(current)}catch(mkdirError){if(mkdirError.code!=="EEXIST")throw mkdirError}info=fs13.lstatSync(current)}else throw error49}if(info.isSymbolicLink()||!info.isDirectory())throw Error("TASK_GATE_REQUIREMENTS_UNREADABLE: receipt parent is redirected or not a directory");let canonicalCurrent=fs13.realpathSync(current);if(!samePath(canonicalCurrent,current))throw Error("TASK_GATE_REQUIREMENTS_UNREADABLE: receipt parent escaped the project root")}return current}function safeTaskGateRequirementsReceiptPath(directory,taskId,createParent){let parent=assertSafeRequirementsParent(directory,createParent);return path19.join(parent,`${taskId}.jsonl`)}function sha256(value){return createHash13("sha256").update(value).digest("hex")}function canonicalReceiptPayload(receipt){return JSON.stringify({...receipt,requiredGates:[...receipt.requiredGates]})}function computeChainHash(receipt){return sha256(canonicalReceiptPayload(receipt))}function readBoundedTextFile(filePath){let pathStat;try{pathStat=fs13.lstatSync(filePath)}catch(error49){if(error49.code==="ENOENT")return null;throw error49}if(pathStat.isSymbolicLink()||!pathStat.isFile())throw Error("TASK_GATE_REQUIREMENTS_UNREADABLE: receipt path is not a regular file");if(pathStat.size>MAX_TASK_GATE_REQUIREMENTS_BYTES)throw Error(`TASK_GATE_REQUIREMENTS_OVERSIZED: ${pathStat.size} bytes exceeds ${MAX_TASK_GATE_REQUIREMENTS_BYTES}`);let descriptor=fs13.openSync(filePath,fs13.constants.O_RDONLY|(fs13.constants.O_NOFOLLOW??0));try{let openedStat=fs13.fstatSync(descriptor);if(!openedStat.isFile()||openedStat.dev!==pathStat.dev||openedStat.ino!==pathStat.ino)throw Error("TASK_GATE_REQUIREMENTS_UNREADABLE: receipt changed while being opened");if(openedStat.size>MAX_TASK_GATE_REQUIREMENTS_BYTES)throw Error(`TASK_GATE_REQUIREMENTS_OVERSIZED: ${openedStat.size} bytes exceeds ${MAX_TASK_GATE_REQUIREMENTS_BYTES}`);return fs13.readFileSync(descriptor,"utf-8")}finally{fs13.closeSync(descriptor)}}async function readTaskGateRequirementsReceipts(directory,taskId){let filePath=safeTaskGateRequirementsReceiptPath(directory,taskId,!1),text=readBoundedTextFile(filePath);if(text===null)return[];let receipts=[];for(let line of text.split(`
274
274
  `)){if(!line.trim())continue;let parsed=TaskGateRequirementsReceiptSchema.parse(JSON.parse(line));if(parsed.taskId!==taskId)throw Error(`TASK_GATE_REQUIREMENTS_IDENTITY_MISMATCH: expected ${taskId}, found ${parsed.taskId}`);let{chainHash,...withoutChainHash}=parsed;if(computeChainHash(withoutChainHash)!==chainHash)throw Error(`TASK_GATE_REQUIREMENTS_CHAIN_MISMATCH: receipt for ${taskId} failed hash validation`);let previousChainHash=receipts.at(-1)?.chainHash??null;if(parsed.previousChainHash!==previousChainHash)throw Error(`TASK_GATE_REQUIREMENTS_CHAIN_MISMATCH: receipt for ${taskId} failed linkage validation`);receipts.push(parsed)}return receipts}function deriveReceiptRole(event){switch(event.type){case"accepted_mutation":case"dispatch_attempted":case"dispatch_no_mutation":if(typeof event.agentType==="string"&&event.agentType.trim().length>0)return{normalizedRole:event.agentType.trim(),testEngineerExempt:event.agentType==="coder"?event.context?.testEngineerExempt===!0:null};return null;case"stage_b_completed":case"gate_recorded":return{normalizedRole:event.gate,testEngineerExempt:null};default:return null}}function shouldAppendReceipt(current,next,role){if(next.required_gates.length===0)return!1;let currentGeneration=current?.workflow?.generation??-1,nextGeneration=next.workflow?.generation??-1;if(current===null)return!0;if(JSON.stringify(current.required_gates)!==JSON.stringify(next.required_gates))return!0;if((current.test_engineer_exempt??null)!==role.testEngineerExempt)return!0;return currentGeneration!==nextGeneration}async function appendTaskGateRequirementsReceiptIfNeeded(directory,taskId,current,next,event){let role=deriveReceiptRole(event);if(!role||!shouldAppendReceipt(current,next,role))return;let filePath=safeTaskGateRequirementsReceiptPath(directory,taskId,!0),receipts=await readTaskGateRequirementsReceipts(directory,taskId),latest=receipts.at(-1),baseReceipt={schemaVersion:1,taskId,generation:next.workflow?.generation??0,normalizedRole:role.normalizedRole,testEngineerExempt:role.testEngineerExempt,requiredGates:[...next.required_gates],sourceEvent:event.type,sourceTransitionId:event.transitionId??null,recordedAt:new Date().toISOString(),previousChainHash:latest?.chainHash??null},receipt={...baseReceipt,chainHash:computeChainHash(baseReceipt)};if(latest&&latest.generation===receipt.generation&&latest.normalizedRole===receipt.normalizedRole&&latest.testEngineerExempt===receipt.testEngineerExempt&&JSON.stringify(latest.requiredGates)===JSON.stringify(receipt.requiredGates)&&latest.sourceTransitionId===receipt.sourceTransitionId)return;let lines=[...receipts,receipt].map((entry)=>JSON.stringify(entry));assertSafeRequirementsParent(directory,!1),await atomicWriteFile(filePath,`${lines.join(`
275
275
  `)}
276
276
  `),assertSafeRequirementsParent(directory,!1)}var MAX_TASK_GATE_REQUIREMENTS_BYTES=262144,TaskGateRequirementsReceiptSchema;var init_task_gate_requirements=__esm(()=>{init_zod();init_utils2();init_project_boundary();init_task_file();TaskGateRequirementsReceiptSchema=exports_external.object({schemaVersion:exports_external.literal(1),taskId:exports_external.string().min(1).max(120),generation:exports_external.number().int().min(0),normalizedRole:exports_external.string().min(1).max(120),testEngineerExempt:exports_external.boolean().nullable(),requiredGates:exports_external.array(exports_external.string()).min(1).max(16),sourceEvent:exports_external.string().min(1).max(120),sourceTransitionId:exports_external.string().min(1).max(200).nullable(),recordedAt:exports_external.string().min(1).max(128),previousChainHash:exports_external.string().regex(/^[a-f0-9]{64}$/).nullable(),chainHash:exports_external.string().regex(/^[a-f0-9]{64}$/)}).strict()});function checkUnsafeChars(taskId){if(!taskId||taskId.length===0)return"Invalid task ID: empty string";if(/\0/.test(taskId))return"Invalid task ID: contains null bytes";for(let i=0;i<taskId.length;i++)if(taskId.charCodeAt(i)<32)return"Invalid task ID: contains control characters";if(taskId.includes("..")||taskId.includes("/")||taskId.includes("\\"))return"Invalid task ID: path traversal detected";return}function isStrictTaskId(taskId){if(!taskId)return!1;if(checkUnsafeChars(taskId))return!1;return STRICT_TASK_ID_PATTERN.test(taskId)}function assertStrictTaskId(taskId){if(!isStrictTaskId(taskId))throw Error(`Invalid taskId: "${taskId}". Must match N.M or N.M.P (e.g. "1.1", "1.2.3").`)}function sanitizeTaskId(taskId){let unsafeMsg=checkUnsafeChars(taskId);if(unsafeMsg)throw Error(unsafeMsg);if(STRICT_TASK_ID_PATTERN.test(taskId)||RETRO_TASK_ID_REGEX.test(taskId)||INTERNAL_TOOL_ID_REGEX.test(taskId)||GENERAL_TASK_ID_REGEX.test(taskId))return taskId;throw Error(`Invalid task ID: must be alphanumeric (ASCII) with optional hyphens, underscores, or dots, got "${taskId}"`)}function validateTaskIdFormat(taskId){if(!STRICT_TASK_ID_PATTERN.test(taskId))return`Invalid taskId "${taskId}". Must match pattern N.M or N.M.P (e.g., "1.1", "1.2.3")`;return}var STRICT_TASK_ID_PATTERN,RETRO_TASK_ID_REGEX,INTERNAL_TOOL_ID_REGEX,GENERAL_TASK_ID_REGEX;var init_task_id=__esm(()=>{STRICT_TASK_ID_PATTERN=/^\d+\.\d+(\.\d+)*$/,RETRO_TASK_ID_REGEX=/^retro-\d+$/,INTERNAL_TOOL_ID_REGEX=/^(?:sast_scan|quality_budget|syntax_check|placeholder_scan|sbom_generate|build|secretscan)$/,GENERAL_TASK_ID_REGEX=/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/});import*as path20 from"node:path";function isControlCharacter(character){let codePoint=character.codePointAt(0)??0;return codePoint<=31||codePoint>=127&&codePoint<=159}function isBidiControlCharacter(character){return BIDI_CONTROL_CHARACTERS.test(character)}function getPathFlavor(pathLib=path20){return pathLib.sep==="\\"?"win32":"posix"}function pathImplementation(flavor){return flavor==="win32"?path20.win32:path20.posix}function normalizePathIdentity(value,flavor=getPathFlavor()){let normalized=pathImplementation(flavor).normalize(flavor==="win32"?value.replace(/\//g,"\\"):value);return flavor==="win32"?normalized.toLowerCase():normalized}function pathIdentitiesEqual(a,b,flavor=getPathFlavor()){return normalizePathIdentity(a,flavor)===normalizePathIdentity(b,flavor)}function isPathIdentityWithin(target,container,flavor=getPathFlavor()){let pathImpl=pathImplementation(flavor),targetIdentity=normalizePathIdentity(target,flavor),containerIdentity=normalizePathIdentity(container,flavor);if(targetIdentity===containerIdentity)return!0;let relative5=pathImpl.relative(containerIdentity,targetIdentity);return relative5.length>0&&relative5!==".."&&!relative5.startsWith(`..${pathImpl.sep}`)&&!pathImpl.isAbsolute(relative5)}function isPathWithinDeclaredScope(filePath,scopeEntries,cwd=process.cwd(),flavor=getPathFlavor()){let pathImpl=pathImplementation(flavor),resolvedFile=pathImpl.resolve(cwd,filePath);return scopeEntries.some((scope)=>isPathIdentityWithin(resolvedFile,pathImpl.resolve(cwd,scope),flavor))}function isOnDifferentPathRoot(target,cwd,flavor=getPathFlavor()){let pathImpl=pathImplementation(flavor),targetRoot=pathImpl.parse(pathImpl.normalize(target)).root,cwdRoot=pathImpl.parse(pathImpl.normalize(cwd)).root;return!pathIdentitiesEqual(targetRoot,cwdRoot,flavor)}function unsafePathTextReason(value){if([...value].some(isControlCharacter))return"control characters are not allowed in paths";if([...value].some(isBidiControlCharacter))return"bidirectional control characters are not allowed in paths";return null}function sanitizeDiagnosticText(value,maxLength=256){let rendered=String(value).split("").map((character)=>isControlCharacter(character)||isBidiControlCharacter(character)?"?":character).join("").replace(/\s+/gu," ").trim();if(rendered.length<=maxLength)return rendered;return`${rendered.slice(0,Math.max(0,maxLength-1))}…`}var BIDI_CONTROL_CHARACTERS;var init_path_identity=__esm(()=>{BIDI_CONTROL_CHARACTERS=/[\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/u});import*as fs14 from"node:fs";import*as path21 from"node:path";function recoveryDir(directory){return path21.join(directory,".swarm",RECOVERY_DIR_NAME)}function recordPath(directory,sessionId,laneId){let safeSession=sessionId.replace(/[^a-zA-Z0-9._-]/g,"_"),safeLane=laneId.replace(/[^a-zA-Z0-9._-]/g,"_");return path21.join(recoveryDir(directory),`${safeSession}-${safeLane}.json`)}function isRecoveryRecord(value){if(typeof value!=="object"||value===null||Array.isArray(value))return!1;let record2=value,validStatus=record2.status==="failed"||record2.status==="partial"||record2.status==="conflict";return typeof record2.laneId==="string"&&typeof record2.sessionId==="string"&&typeof record2.worktreePath==="string"&&validStatus&&typeof record2.reason==="string"&&typeof record2.recordedAt==="number"&&Number.isFinite(record2.recordedAt)&&typeof record2.replayHint==="string"&&(record2.branchName===void 0||typeof record2.branchName==="string")&&(record2.conflictFiles===void 0||Array.isArray(record2.conflictFiles)&&record2.conflictFiles.every((file2)=>typeof file2==="string"))}function readRecoveryRecords(directory){let dir=recoveryDir(directory),entries;try{entries=fs14.readdirSync(dir,{withFileTypes:!0})}catch{return{records:[],errored:fs14.existsSync(dir)}}let records=[],errored=!1;for(let entry of entries){if(!entry.isFile()||!entry.name.endsWith(".json"))continue;let full=path21.join(dir,entry.name);try{let parsed=JSON.parse(fs14.readFileSync(full,"utf-8"));if(isRecoveryRecord(parsed))records.push(parsed);else errored=!0}catch{errored=!0}}return{records,errored}}function writeRecoveryRecord(directory,record2){try{let dir=recoveryDir(directory);fs14.mkdirSync(dir,{recursive:!0});let filePath=recordPath(directory,record2.sessionId,record2.laneId),payload={...record2,recordedAt:record2.recordedAt??Date.now()},tmpPath=`${filePath}.tmp.${Date.now()}`;fs14.writeFileSync(tmpPath,JSON.stringify(payload,null,2),"utf-8"),fs14.renameSync(tmpPath,filePath)}catch{}}function listRecoveryRecords(directory){return readRecoveryRecords(directory).records}function hasRecoveryRecordForBranch(directory,branchName){return listRecoveryRecords(directory).some((r)=>r.branchName===branchName)}function clearRecoveryRecord(directory,laneId,sessionId){try{let filePath=recordPath(directory,sessionId,laneId);if(fs14.existsSync(filePath))fs14.unlinkSync(filePath)}catch{}}function recoveryReadErrored(directory){return readRecoveryRecords(directory).errored}var RECOVERY_DIR_NAME="recovery";var init_recovery=()=>{};function isGitBinaryMissing(err,cwd){return classifySpawnFailure(err,cwd)==="binary-missing"}function isSpawnCwdMissing(err,cwd){return classifySpawnFailure(err,cwd)==="cwd-missing"}function isSpawnCwdUnreadable(err,cwd){return classifySpawnFailure(err,cwd)==="cwd-unreadable"}var GitUnavailableError,GitBinaryMissingError,GitSpawnCwdError;var init_git_binary_missing_error=__esm(()=>{init_bun_compat();init_bun_compat();GitUnavailableError=class GitUnavailableError extends Error{};GitBinaryMissingError=class GitBinaryMissingError extends GitUnavailableError{name="GitBinaryMissingError";constructor(message="git binary is not available",options){super(message,options)}};GitSpawnCwdError=class GitSpawnCwdError extends GitUnavailableError{name="GitSpawnCwdError";cwd;fault;constructor(cwd,fault,options){super(fault==="missing"?`git could not start: working directory no longer exists: ${cwd}`:`git could not start: working directory could not be inspected (permission denied): ${cwd}`,options);this.cwd=cwd,this.fault=fault}}});function isSwarmSessionId(sessionId){return typeof sessionId==="string"&&SESSION_ID_PATTERN.test(sessionId)}function isPlainSegment(segment){return typeof segment==="string"&&segment.length>0&&segment!=="."&&segment!==".."}function buildSwarmBranchName(sessionId,id,purpose,legacyLane){let[standardPrefix,legacyLanePrefix]=SWARM_WORKTREE_BRANCH_PREFIXES;return legacyLane?`${legacyLanePrefix}${sessionId}/${id}`:`${standardPrefix}${purpose}/${sessionId}/${id}`}function matchSwarmLanePath(lanePath){if(typeof lanePath!=="string"||lanePath==="")return;let segments=lanePath.split(/[\\/]+/).filter((s)=>s.length>0);if(segments.length<3)return;let[base,sessionId,id]=segments.slice(-3);if(!(process.platform==="win32"?base.toLowerCase()===SWARM_WORKTREE_DIR_NAME.toLowerCase():base===SWARM_WORKTREE_DIR_NAME))return;if(!SESSION_ID_PATTERN.test(sessionId??""))return;if(!isPlainSegment(id))return;return{sessionId,id}}function matchSwarmLaneBranch(branch){if(typeof branch!=="string"||branch==="")return;let segments=branch.split("/");if(segments[0]==="swarm-lane"){if(segments.length!==3)return;let[,sessionId,id]=segments;if(!SESSION_ID_PATTERN.test(sessionId??""))return;if(!isPlainSegment(id))return;return{purpose:"lane",sessionId,id,style:"legacy-lane"}}if(segments[0]==="swarm"){if(segments.length!==4)return;let[,purpose,sessionId,id]=segments;if(!isPlainSegment(purpose))return;if(!SESSION_ID_PATTERN.test(sessionId??""))return;if(!isPlainSegment(id))return;return{purpose,sessionId,id,style:"purpose"}}return}var SWARM_WORKTREE_BRANCH_PREFIXES,SESSION_ID_PATTERN;var init_swarm_branch=__esm(()=>{init_constants();SWARM_WORKTREE_BRANCH_PREFIXES=["swarm/","swarm-lane/"],SESSION_ID_PATTERN=/^ses_[A-Za-z0-9]+$/});import*as crypto3 from"node:crypto";import*as fs15 from"node:fs";import*as path22 from"node:path";function resolvePlanEpochIdentity(events,authoritativePlan){let planId=derivePlanId(authoritativePlan),planIdentityHash=derivePlanIdentityHash(authoritativePlan),payloadHash=computePlanHash(authoritativePlan),candidates=extractPlanEpochCandidates(events,planId);if(new Set(candidates.map((candidate)=>`${candidate.planEpoch}:${candidate.rootEventHash}`)).size>1)throw Error(`Conflicting plan epoch metadata detected for ${planId}; refusing to continue.`);if(candidates.length===0)return null;let existing=candidates[0];return{planId,planIdentityHash,planEpoch:existing.planEpoch,rootEventHash:existing.rootEventHash,payloadHash,source:existing.source}}function getLedgerPath(directory){return path22.join(directory,".swarm",LEDGER_FILENAME)}function getPlanJsonPath(directory){return path22.join(directory,".swarm",PLAN_JSON_FILENAME)}function asRecord(value){if(value&&typeof value==="object"&&!Array.isArray(value))return value;return null}function isSha256Hex(value){return/^[a-f0-9]{64}$/i.test(value)}function isUuid(value){return/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value)}function serializeLedgerEvent(event){return JSON.stringify(event)}function computeLedgerEventHash(event){return crypto3.createHash("sha256").update(serializeLedgerEvent(event),"utf8").digest("hex")}function extractPlanEpochCandidates(events,expectedPlanId){if(events.length===0)throw Error("Plan ledger is empty; missing plan_created root.");let rootEvent=events[0];if(rootEvent.event_type!=="plan_created")throw Error(`Plan ledger root must be plan_created; found ${rootEvent.event_type} at seq ${rootEvent.seq}.`);if(rootEvent.plan_id!==expectedPlanId)throw Error(`Plan ledger identity mismatch: expected ${expectedPlanId} but found ${rootEvent.plan_id}.`);let rootEventHash=computeLedgerEventHash(rootEvent),candidates=[],rootPlanEpoch=asRecord(rootEvent.payload)?.plan_epoch;if(typeof rootPlanEpoch==="string"&&rootPlanEpoch.length>0){if(!isUuid(rootPlanEpoch))throw Error("Plan ledger root carries an invalid plan_epoch.");candidates.push({planEpoch:rootPlanEpoch,rootEventHash,source:"root"})}for(let event of events){if(event.event_type!=="snapshot"||event.source!=="plan_epoch_adopted")continue;if(event.plan_id!==expectedPlanId)throw Error(`Plan epoch adoption snapshot at seq ${event.seq} belongs to ${event.plan_id}, expected ${expectedPlanId}.`);let payload=asRecord(event.payload),planEpoch=payload?.plan_epoch,rootHash=payload?.root_event_hash,embeddedPlan=PlanSchema.safeParse(payload?.plan);if(!embeddedPlan.success)throw Error(`Plan epoch adoption snapshot at seq ${event.seq} carries an invalid embedded plan.`);let payloadHash=payload?.payload_hash;if(typeof planEpoch!=="string"||!isUuid(planEpoch))throw Error(`Plan epoch adoption snapshot at seq ${event.seq} has an invalid plan_epoch.`);if(typeof rootHash!=="string"||!isSha256Hex(rootHash))throw Error(`Plan epoch adoption snapshot at seq ${event.seq} has an invalid root_event_hash.`);if(rootHash!==rootEventHash)throw Error(`Plan epoch adoption snapshot at seq ${event.seq} does not match the canonical ledger root.`);if(typeof payloadHash!=="string")throw Error(`Plan epoch adoption snapshot at seq ${event.seq} is missing payload_hash.`);if(derivePlanId(embeddedPlan.data)!==expectedPlanId)throw Error(`Plan epoch adoption snapshot at seq ${event.seq} embeds a different plan identity.`);if(computePlanHash(embeddedPlan.data)!==payloadHash)throw Error(`Plan epoch adoption snapshot at seq ${event.seq} has a mismatched payload_hash.`);candidates.push({planEpoch,rootEventHash:rootHash,source:"plan_epoch_adopted"})}return candidates}function writeFileFsyncedThenRename(tempPath,targetPath,data){let fd=fs15.openSync(tempPath,"w");try{fs15.writeFileSync(fd,data,"utf8"),fs15.fsyncSync(fd)}finally{fs15.closeSync(fd)}fs15.renameSync(tempPath,targetPath)}function fsyncRecoveryDirectory(directory){let fd;try{fd=fs15.openSync(directory,"r"),fs15.fsyncSync(fd)}catch(error49){let code=error49.code;if(process.platform==="win32"&&["EPERM","EACCES","EINVAL","EBADF","EISDIR","ENOTSUP"].includes(code??"")){log(`[ledger] Directory fsync unavailable for recovery archive ${directory}: ${error49 instanceof Error?error49.message:String(error49)}`);return}throw Error(`Failed to fsync recovery archive directory before canonical replacement: ${error49 instanceof Error?error49.message:String(error49)}`)}finally{if(fd!==void 0)fs15.closeSync(fd)}}function findRawMalformedSuffix(content){let decoder=new TextDecoder("utf-8",{fatal:!0}),lineStart=0;for(let index=0;index<=content.length;index++){if(index<content.length&&content[index]!==10)continue;let lineEnd=index;if(lineEnd>lineStart&&content[lineEnd-1]===13)lineEnd--;let line=content.subarray(lineStart,lineEnd);if(line.length>0)try{JSON.parse(decoder.decode(line))}catch{return content.subarray(lineStart)}lineStart=index+1}return Buffer.alloc(0)}function computePlanHash(plan){let normalized={schema_version:plan.schema_version,title:plan.title,swarm:plan.swarm,current_phase:plan.current_phase,migration_status:plan.migration_status,execution_profile:normalizeExecutionProfileForHash(plan.execution_profile),phases:plan.phases.map((phase)=>({id:phase.id,name:phase.name,status:phase.status,required_agents:phase.required_agents?[...phase.required_agents].sort():void 0,tasks:phase.tasks.map((task)=>({id:task.id,phase:task.phase,status:task.status,size:task.size,description:task.description,depends:[...task.depends].sort(),acceptance:task.acceptance,files_touched:[...task.files_touched].sort(),evidence_path:task.evidence_path,blocked_reason:task.blocked_reason}))}))},jsonString=JSON.stringify(normalized);return crypto3.createHash("sha256").update(jsonString,"utf8").digest("hex")}function computePlanStructureHash(plan){let normalized={schema_version:plan.schema_version,title:plan.title,swarm:plan.swarm,current_phase:plan.current_phase,migration_status:plan.migration_status,execution_profile:normalizeExecutionProfileForHash(plan.execution_profile),phases:plan.phases.map((phase)=>({id:phase.id,name:phase.name,required_agents:phase.required_agents?[...phase.required_agents].sort():void 0,tasks:phase.tasks.map((task)=>({id:task.id,phase:task.phase,size:task.size,description:task.description,depends:[...task.depends].sort(),acceptance:task.acceptance,files_touched:[...task.files_touched].sort(),evidence_path:task.evidence_path,blocked_reason:task.blocked_reason}))}))},jsonString=JSON.stringify(normalized);return crypto3.createHash("sha256").update(jsonString,"utf8").digest("hex")}function computeCurrentPlanHash(directory){let planPath=getPlanJsonPath(directory);try{let content=fs15.readFileSync(planPath,"utf8"),plan=JSON.parse(content);return computePlanHash(plan)}catch{return""}}async function ledgerExists(directory){let ledgerPath=getLedgerPath(directory);return fs15.existsSync(ledgerPath)}async function getLatestLedgerSeq(directory){let ledgerPath=getLedgerPath(directory);if(!fs15.existsSync(ledgerPath))return 0;try{let lines=fs15.readFileSync(ledgerPath,"utf8").trim().split(`
@@ -861,7 +861,7 @@ ${expectedBodyBlock}
861
861
  `,"utf-8")}finally{if(lock.lock._release)await lock.lock._release().catch(()=>{})}}async function enforceCoderRetryEscalation(input){if(input.retryCount<3)return;let prior=readCoderRetryEscalations(input.directory,input.taskId,input.retryEpoch);if(!prior.has("sounding_board_consultation"))throw await emitCoderRetryEscalation(input.directory,{...input,rejectionCount:input.retryCount,rejectionHistory:input.retryHistory,action:"sounding_board_consultation"}),Error(`TASK_RETRY_CRITIC_REQUIRED: task ${input.taskId} reached the bounded retry threshold. Dispatch critic_sounding_board for this exact task before another coder attempt.`);if(prior.has("simplification"))throw await emitCoderRetryEscalation(input.directory,{...input,rejectionCount:input.retryCount,rejectionHistory:input.retryHistory,action:"user_escalation"}),Error(`TASK_RETRY_USER_ESCALATION_REQUIRED: task ${input.taskId} failed its critic-guided simplified retry. Stop and ask the user to change scope, authorize repair, or choose a different approach.`);if(!input.criticSatisfied)throw Error(`TASK_RETRY_CRITIC_REQUIRED: task ${input.taskId} is waiting for an exact-generation critic_sounding_board APPROVED verdict.`);await emitCoderRetryEscalation(input.directory,{...input,rejectionCount:input.retryCount,rejectionHistory:input.retryHistory,action:"simplification"})}function canRunWhileTaskAwaitsCompletion(input){let normalizedTool=input.normalizedTool.toLowerCase();if(isReadOnlyTool(normalizedTool))return!0;if(COMPLETION_RECOVERY_TOOLS.has(normalizedTool))return!0;if(normalizedTool==="spec_write"&&input.directory&&fs51.existsSync(path81.join(input.directory,".swarm","spec-staleness.json")))return!0;if(normalizedTool==="save_plan"&&input.args.reconcile_ledger_projection===!0)return!0;if(normalizedTool==="update_task_status"&&input.requestedTaskId===input.awaitingTaskId)return!0;if(input.directory&&input.requestedTaskId&&input.requestedTaskId!==input.awaitingTaskId&&isProvablyDisjoint(input.directory,[input.awaitingTaskId,input.requestedTaskId]))return!0;return!1}async function buildParallelExecutionGuidance(directory,sessionID,session){if(!directory)return null;let plan=await loadPlanJsonOnly(directory);if(!plan)return null;let profile=plan.execution_profile,enabled=profile?.parallelization_enabled===!0,maxConcurrent=profile?.max_concurrent_tasks??10,effectiveMaxConcurrent=session?.maxConcurrencyOverride??maxConcurrent,allTasks=plan.phases.flatMap((phase)=>phase.tasks),blockedTasks=allTasks.filter((task)=>{if(task.status!=="blocked")return!1;let reason=(task.blocked_reason??"").toLowerCase();return reason.includes("fail")||reason.includes("error")||reason.includes("exception")}),totalTasks=allTasks.length,backoffTriggered=!1;if(totalTasks>0&&blockedTasks.length>0){let failureRate=blockedTasks.length/totalTasks,FAILURE_RATE_THRESHOLD=0.2,BACKOFF_MULTIPLIER=0.5;if(failureRate>0.2&&blockedTasks.length>=2){let newConcurrency=Math.max(1,Math.floor(effectiveMaxConcurrent*0.5));if(newConcurrency<effectiveMaxConcurrent)effectiveMaxConcurrent=newConcurrency,session.maxConcurrencyOverride=newConcurrency,backoffTriggered=!0}}if(!enabled||effectiveMaxConcurrent<=1)return null;if(hasActiveLeanTurbo(sessionID))return"[NEXT] Lean Turbo is active; use lean_turbo_run_phase and Lean Turbo lane guidance instead of standard execution-profile slot filling.";let currentPhase=plan.current_phase!==void 0?plan.phases.find((phase)=>phase.id===plan.current_phase):plan.phases.find((phase)=>!isParallelGuidancePhaseComplete(phase));if(!currentPhase)return null;let tasks=currentPhase.tasks;if(tasks.length===0)return null;if(!scopeVerdictAllowsParallel(directory,plan))return`[PARALLEL EXECUTION PROFILE] parallelization_enabled=true max_concurrent_tasks=${effectiveMaxConcurrent}; the active phase's pending tasks are NOT provably file-disjoint (overlapping or unknown declared scopes) — SERIAL fallback active (v8 automatic safety). Run plan_conflict_check on the pending tasks to inspect the conflict matrix and a suggested serialization order, or proceed serially (one coder at a time).`;let completed=new Set;for(let task of allTasks){let taskId=task.id;if(isTaskCompletedForParallelGuidance(task))completed.add(taskId);if(getTaskState(session,taskId)==="complete")completed.add(taskId)}let occupied=new Set;for(let task of allTasks){let taskId=task.id;if(task.status==="in_progress")occupied.add(taskId);let state=getTaskState(session,taskId);if(ACTIVE_PARALLEL_TASK_STATES.has(state))occupied.add(taskId)}let availableSlots=Math.max(0,effectiveMaxConcurrent-occupied.size);if(availableSlots<=0)return`[PARALLEL EXECUTION PROFILE] parallelization_enabled=true max_concurrent_tasks=${effectiveMaxConcurrent}; all standard execution slots are occupied. Continue current active task gates before starting more coder work.`;let eligible=tasks.filter((task)=>{let taskId=task.id;if((task.status??"pending")!=="pending")return!1;if(occupied.has(taskId))return!1;return task.depends.every((dep)=>completed.has(dep))}).map((task)=>task.id).slice(0,availableSlots);if(eligible.length===0)return`[PARALLEL EXECUTION PROFILE] parallelization_enabled=true max_concurrent_tasks=${effectiveMaxConcurrent}; no dependency-ready pending tasks are available for a new coder slot. Continue the current task/gate.`;let failureWarning=backoffTriggered?` (${blockedTasks.length} blocked task(s) detected — concurrency auto-reduced due to failures)`:"";return`[PARALLEL EXECUTION PROFILE] parallelization_enabled=true max_concurrent_tasks=${effectiveMaxConcurrent}; ${occupied.size} slot(s) occupied. Eligible now: ${eligible.join(", ")}. [NEXT] dispatch up to ${availableSlots} eligible coder task(s) before waiting; preserve ONE task per coder call and call declare_scope for each task.${failureWarning}`}function isParallelGuidancePhaseComplete(phase){return phase.status==="complete"||phase.status==="completed"||phase.status==="closed"}function collectPendingTaskIdsForActivePhase(plan){let currentPhase=plan.current_phase!==void 0?plan.phases.find((phase)=>phase.id===plan.current_phase):plan.phases.find((phase)=>!isParallelGuidancePhaseComplete(phase));if(!currentPhase)return[];return currentPhase.tasks.filter((t)=>t.status==="pending").map((t)=>t.id)}function scopeVerdictAllowsParallel(directory,plan){try{let pendingTaskIds=collectPendingTaskIdsForActivePhase(plan);if(pendingTaskIds.length<2)return!1;return computeParallelVerdict(directory,pendingTaskIds).verdict==="all_disjoint"}catch{return!1}}async function getEvidenceTaskId(session,directory){let resolvedPlanPath,primary=session.currentTaskId??session.lastCoderDelegationTaskId;if(primary)return primary;if(session.taskWorkflowStates&&session.taskWorkflowStates.size>0)return session.taskWorkflowStates.keys().next().value??null;try{if(typeof directory!=="string"||directory.length===0)return null;let resolvedDirectory=path81.resolve(directory),planPath=path81.join(resolvedDirectory,".swarm","plan.json");if(resolvedPlanPath=path81.resolve(planPath),!resolvedPlanPath.startsWith(resolvedDirectory+path81.sep)&&resolvedPlanPath!==resolvedDirectory)return null;let planContent=await fs51.promises.readFile(resolvedPlanPath,"utf-8"),plan=EvidenceTaskIdPlanSchema.parse(JSON.parse(planContent));if(!plan||!Array.isArray(plan.phases))return null;for(let phase of plan.phases)if(Array.isArray(phase.tasks)){for(let task of phase.tasks)if(task.status==="in_progress")return task.id??null}}catch(err){if(err instanceof ZodError){let issueSummary=err.issues.slice(0,3).map((issue2)=>issue2.message).join("; ");return warn(`[delegation-gate] getEvidenceTaskId ignored invalid plan schema at ${resolvedPlanPath??"unknown path"}: ${issueSummary}`),null}if(process.env.DEBUG_SWARM&&err instanceof Error)warn(`[delegation-gate] getEvidenceTaskId error: ${err.message} (code=${err.code??"none"})`);return null}return null}async function resolveEvidenceTaskId(args2,session,directory){let rawTaskId=args2?.task_id;if(typeof rawTaskId==="string"&&rawTaskId.length<=20&&isStrictTaskId(rawTaskId.trim()))return rawTaskId.trim();if(args2)try{let plan=await loadPlanJsonOnly(directory);if(plan){let planTaskIds=new Set(plan.phases.flatMap((p)=>p.tasks.map((t)=>t.id))),promptTaskId=resolveDelegatedPlanTaskId(args2,planTaskIds);if(promptTaskId)return promptTaskId}}catch{}return getEvidenceTaskId(session,directory)}function sameReplayPrompt(existing,incoming){if(existing===void 0||incoming===void 0)return existing===incoming;return existing.digest===incoming.digest&&existing.chars===incoming.chars&&existing.truncated===incoming.truncated&&existing.text===incoming.text}function hasStableBackgroundReplayIdentity(existing,incoming){return existing.correlationId===incoming.correlationId&&existing.subagentSessionId===incoming.subagentSessionId&&existing.parentSessionId===incoming.parentSessionId&&existing.callID===incoming.callID&&existing.jobId===incoming.jobId&&existing.normalizedAgent===incoming.normalizedAgent&&existing.swarmPrefixedAgent===incoming.swarmPrefixedAgent&&existing.planTaskId===incoming.planTaskId&&existing.evidenceTaskId===incoming.evidenceTaskId&&sameReplayPrompt(existing.prompt,incoming.prompt)}function hydrateBackgroundReplayInput(existing,incoming){return{...incoming,workspace:existing.workspace,taskChangeContext:existing.taskChangeContext,worktree:existing.worktree,coderReservationId:existing.coderReservationId,prompt:existing.prompt,generation:existing.generation??1}}function createDelegationGateHook(config2,directory){initDurableStatusPath(directory);let enabled=config2.hooks?.delegation_gate!==!1,delegationMaxChars=config2.hooks?.delegation_max_chars??4000,backgroundSubagentsEnabled=config2.hooks?.background_subagents===!0,backgroundPendingTimeoutMs=(config2.hooks?.background_pending_timeout_minutes??30)*60000,MAX_PENDING_CODER_CHANGE_CONTEXTS=128,coderTaskChangeContextByCallID=new Map,begunCoderSettlementsByCallID=new Map,rememberBegunCoderSettlement=(callID,taskId,transitionId)=>{if(!begunCoderSettlementsByCallID.has(callID)&&begunCoderSettlementsByCallID.size>=MAX_PENDING_CODER_CHANGE_CONTEXTS)throw Error(`BEGUN_SETTLEMENT_CONTEXT_CAPACITY: refusing coder dispatch because ${MAX_PENDING_CODER_CHANGE_CONTEXTS} live begun settlements are already tracked`);begunCoderSettlementsByCallID.set(callID,{taskId,transitionId})},backgroundCoderReservationByCallID=new Map,coderObservedFilesByCallID=new Map,stageBDispatchGenerationsByCallID=new Map,gateDispatchPrimaryTaskByCallID=new Map,stageBDispatchContextByCallID=new Map,publishedScopeBindingsByCallID=new Map,publishScopeBinding=async(callID,bindingDirectory,binding)=>{let published=await persistAndRegisterScopeBinding(bindingDirectory,binding);if(!published.ok)throw Error(`${published.code}: ${published.message}`);let entries=publishedScopeBindingsByCallID.get(callID)??[];entries.push({directory:bindingDirectory,binding}),publishedScopeBindingsByCallID.delete(callID),publishedScopeBindingsByCallID.set(callID,entries);while(publishedScopeBindingsByCallID.size>MAX_PENDING_SCOPE_BINDINGS){let oldest=publishedScopeBindingsByCallID.keys().next().value;if(oldest===void 0)break;let evicted=publishedScopeBindingsByCallID.get(oldest)??[];publishedScopeBindingsByCallID.delete(oldest);for(let entry of evicted)clearScopeBindingFromDisk({directory:entry.directory,binding:entry.binding}),clearExactScopeBinding(entry.binding)}},clearPublishedScopeBindings=(callID)=>{let entries=publishedScopeBindingsByCallID.get(callID)??[];publishedScopeBindingsByCallID.delete(callID);for(let entry of entries)clearScopeBindingFromDisk({directory:entry.directory,binding:entry.binding}),clearExactScopeBinding(entry.binding)},taskMetadata=async(input)=>{let result=await claimScopeBindingForChildDurably({directory,parentSessionId:input.parentSessionID,childSessionId:input.childSessionID,dispatchCallId:input.callID});if(!result.ok){if(result.code==="SCOPE_NOT_DECLARED")return;throw Error(`${result.code}: ${result.message}`)}let{previous,claimed}=result.value,entries=publishedScopeBindingsByCallID.get(input.callID)??[];for(let entry of entries)if(entry.directory===directory&&entry.binding.bindingId===previous.bindingId&&entry.binding.generationId===previous.generationId)entry.binding=claimed;let childSession=ensureAgentSession(input.childSessionID,"coder",directory);if(childSession.prmDelegationCallId!==input.callID)childSession.prmDelegationCallId=input.callID,resetPrmSessionState(childSession,input.childSessionID);childSession.currentTaskId=claimed.taskId,childSession.declaredCoderScope=[...claimed.files]},sessionEnded=(sessionID,includeOwnedChildren=!1)=>{if(!sessionID)return;let removed=clearScopeBindings((binding)=>binding.ownerSessionId===sessionID||includeOwnedChildren&&binding.parentOwnerSessionId===sessionID);for(let binding of removed)clearScopeBindingFromDisk({directory:binding.workspaceIdentity,binding});if(removed.some((binding)=>binding.ownerSessionId===sessionID&&binding.activation==="active")){let endedSession=swarmState.agentSessions.get(sessionID);if(endedSession)endedSession.currentTaskId=null,endedSession.declaredCoderScope=null}for(let[callID,entries]of publishedScopeBindingsByCallID){let remaining=entries.filter((entry)=>entry.binding.ownerSessionId!==sessionID&&(!includeOwnedChildren||entry.binding.parentOwnerSessionId!==sessionID));if(remaining.length===0)publishedScopeBindingsByCallID.delete(callID);else if(remaining.length!==entries.length)publishedScopeBindingsByCallID.set(callID,remaining)}},clearCoderTaskChangeContext=(callID)=>{coderTaskChangeContextByCallID.delete(callID),coderObservedFilesByCallID.delete(callID)},rememberStageBDispatchGenerations=(callID,generations)=>{if(!stageBDispatchGenerationsByCallID.has(callID)&&stageBDispatchGenerationsByCallID.size>=MAX_PENDING_CODER_CHANGE_CONTEXTS)throw Error(`STAGE_B_CONTEXT_CAPACITY: refusing Stage B dispatch because ${MAX_PENDING_CODER_CHANGE_CONTEXTS} live generation bindings are already tracked`);stageBDispatchGenerationsByCallID.set(callID,generations)},releasePrelaunchBackgroundCoderReservation=async(callID)=>{let reservation=backgroundCoderReservationByCallID.get(callID);if(!reservation)return;if(await _internals65.releaseBackgroundCoderReservationForDispatch(directory,{...reservation,reason:"recovered"})){backgroundCoderReservationByCallID.delete(callID);return}warn(`[delegation-gate] pre-launch background coder reservation ${reservation.reservationId} could not be released; later admission remains fail-closed`)},rememberCoderObservedFiles=(callID,observedFiles)=>{if(!coderObservedFilesByCallID.has(callID)&&coderObservedFilesByCallID.size>=MAX_PENDING_CODER_CHANGE_CONTEXTS){let oldest=coderObservedFilesByCallID.keys().next().value;if(oldest!==void 0)coderObservedFilesByCallID.delete(oldest)}coderObservedFilesByCallID.set(callID,observedFiles)},rememberCoderTaskChangeContext=(callID,declaredFiles,observationDirectory=directory,workflowGeneration)=>{if(!coderTaskChangeContextByCallID.has(callID)&&coderTaskChangeContextByCallID.size>=MAX_PENDING_CODER_CHANGE_CONTEXTS)throw Error(`BACKGROUND_CODER_CONTEXT_CAPACITY: refusing coder dispatch because ${MAX_PENDING_CODER_CHANGE_CONTEXTS} live change baselines are already tracked`);coderTaskChangeContextByCallID.set(callID,{declaredFiles,baseline:captureWorkspaceSnapshot(observationDirectory),workflowGeneration})},beginForegroundCoderSettlementIfNeeded=async(input,taskId,background,worktree)=>{if(backgroundSubagentsEnabled&&isBackgroundTrue(background))return;let context=coderTaskChangeContextByCallID.get(input.callID);if(!context||context.workflowGeneration===void 0)throw Error(`CODER_SETTLEMENT_CONTEXT_MISSING: no durable baseline or generation for task ${taskId}`);let baselineDirtyFiles=Array.isArray(context.baseline.changedFiles)?context.baseline.changedFiles:[];if(baselineDirtyFiles.length>0){let sample=baselineDirtyFiles.slice(0,5).join(", ");throw Error(`CODER_SETTLEMENT_CLEAN_BASELINE_REQUIRED: ${String(baselineDirtyFiles.length)} uncommitted/untracked change(s) present at dispatch (${sample}${baselineDirtyFiles.length>5?", …":""}). `+"Commit or stash them before dispatching a coder — exact-task settlement cannot attribute coder mutations from a dirty launch baseline. "+`(.swarm/ plugin runtime state is excluded from this check automatically.) Task ${taskId} was not dispatched and no settlement state was created.`)}await beginCoderSettlement({directory,taskId,transitionId:`coder:${input.callID}`,actor:input.sessionID,expectedGeneration:context.workflowGeneration,context,...worktree?{worktree}:{}}),rememberBegunCoderSettlement(input.callID,taskId,`coder:${input.callID}`)},shouldRememberCoderTaskChangeContext=(_declaredFiles,_background)=>!0,backgroundCompletionClaimed=(record2)=>{let callID=record2.callID;clearPublishedScopeBindings(callID),clearCoderTaskChangeContext(callID),begunCoderSettlementsByCallID.delete(callID),stageBDispatchGenerationsByCallID.delete(callID),gateDispatchPrimaryTaskByCallID.delete(callID),stageBDispatchContextByCallID.delete(callID),deleteStoredInputArgs(callID)};if(!enabled)return{messagesTransform:async(_input,_output)=>{},toolBefore:async(input,output)=>{let normalized=normalizeToolName(input.tool),args2=output.args;if(normalized!=="Task"&&normalized!=="task"||!args2||typeof args2.subagent_type!=="string"||stripKnownSwarmPrefix(args2.subagent_type)!=="coder")return;let prepared=await prepareCoderScope(directory,input,args2);await publishScopeBinding(input.callID,directory,prepared.binding)},toolAfter:async(input,output)=>{if((normalizeToolName(input.tool)==="Task"||normalizeToolName(input.tool)==="task")&&outputLooksLikeBackgroundRunning(output))return;clearPublishedScopeBindings(input.callID)},taskMetadata,sessionEnded,backgroundCompletionClaimed,abortDeniedSettlementForCall:async()=>{}};return{toolBefore:async(input,output)=>{if(!input.sessionID)return;let normalized=normalizeToolName(input.tool),preflightArgs=output.args;if((normalized==="Task"||normalized==="task")&&preflightArgs&&typeof preflightArgs.subagent_type==="string"){let preflightAgent=stripKnownSwarmPrefix(preflightArgs.subagent_type);if(preflightAgent.startsWith("critic")){let criticModel=config2.agents?.[preflightAgent]?.model??DEFAULT_MODELS[preflightAgent]??DEFAULT_MODELS.default;try{let{checkSingleModelResolution:checkSingleModelResolution2}=await Promise.resolve().then(() => (init_model_preflight(),exports_model_preflight));if(await checkSingleModelResolution2(criticModel,swarmState.opencodeClient)==="unresolved")throw telemetry.modelUnresolved(preflightAgent,criticModel,"plan-critic dispatch preflight"),Error(`PLAN_CRITIC_MODEL_UNRESOLVED: the ${preflightAgent} agent's model "${criticModel}" does not resolve against the provider catalog — the critic can never run, so the plan-critic gate cannot produce VERDICT: APPROVED. `+`Fix agents.${preflightAgent}.model in opencode-swarm.json (or remove the override to fall back to the default model), then re-run MODE: CRITIC-GATE.`)}catch(error49){if(error49 instanceof Error&&error49.message.startsWith("PLAN_CRITIC_MODEL_UNRESOLVED")){let{invalidateProviderCatalogCache:invalidateProviderCatalogCache2}=await Promise.resolve().then(() => (init_model_preflight(),exports_model_preflight));throw invalidateProviderCatalogCache2(),error49}}}}let completionArgs=output.args;if(completionArgs){let completionPlanTaskIds;try{let plan2=await loadPlanJsonOnly(directory);if(plan2)completionPlanTaskIds=new Set(plan2.phases.flatMap((p)=>p.tasks.map((t)=>t.id)))}catch{}let requestedTaskId=resolveDelegatedPlanTaskId(completionArgs,completionPlanTaskIds);if(requestedTaskId){let{getTaskWorkflowSnapshot:getTaskWorkflowSnapshot3,readTaskEvidence:readTaskEvidence3}=await Promise.resolve().then(() => (init_gate_evidence(),exports_gate_evidence)),recoveredCoder=await recoverCoderSettlement(directory,requestedTaskId);if(recoveredCoder){let recoveredSession=ensureAgentSession(input.sessionID),workflow=getTaskWorkflowSnapshot3(recoveredCoder.evidence);recoveredSession.taskWorkflowStates.set(requestedTaskId,workflow.state),recoveredSession.stageBCompletion?.delete(requestedTaskId),updateTaskWorkflowCache(recoveredSession,requestedTaskId,workflow)}let recoveredTerminal=await recoverPreparedTaskTerminal(directory,requestedTaskId,input.sessionID);if(recoveredTerminal){let recoveredSession=ensureAgentSession(input.sessionID),workflow=getTaskWorkflowSnapshot3(recoveredTerminal.evidence);recoveredSession.taskWorkflowStates.set(requestedTaskId,workflow.state),recoveredSession.stageBCompletion?.delete(requestedTaskId),recoveredSession.taskCouncilApproved?.delete(requestedTaskId),recoveredSession.taskCouncilWorkflowGeneration?.delete(requestedTaskId),updateTaskWorkflowCache(recoveredSession,requestedTaskId,workflow)}let recoveredRepair=null;try{recoveredRepair=await recoverPreparedTaskRepair(directory,requestedTaskId,input.sessionID)}catch(error49){criticalWarn(`[delegation-gate] task-repair recovery deferred for ${requestedTaskId}: ${error49 instanceof Error?error49.message:String(error49)}`)}if(recoveredRepair){let recoveredSession=ensureAgentSession(input.sessionID),workflow=getTaskWorkflowSnapshot3(await readTaskEvidence3(directory,requestedTaskId));recoveredSession.taskWorkflowStates.set(requestedTaskId,workflow.state),recoveredSession.stageBCompletion?.delete(requestedTaskId),recoveredSession.taskCouncilApproved?.delete(requestedTaskId),recoveredSession.taskCouncilWorkflowGeneration?.delete(requestedTaskId),updateTaskWorkflowCache(recoveredSession,requestedTaskId,workflow)}}let taskAwaitingCompletion=await findTaskAwaitingCompletion(directory,requestedTaskId);if(taskAwaitingCompletion){if(!canRunWhileTaskAwaitsCompletion({directory,normalizedTool:normalized,args:completionArgs,awaitingTaskId:taskAwaitingCompletion,requestedTaskId}))throw Error(completionGateViolationMessage(taskAwaitingCompletion))}}if(normalized!=="Task"&&normalized!=="task")return;let args2=output.args;if(!args2)return;let subagentType=args2.subagent_type;if(typeof subagentType!=="string")return;let targetAgent=stripKnownSwarmPrefix(subagentType);if(!backgroundSubagentsEnabled&&isBackgroundTrue(args2.background)&&isKnownCanonicalRole(targetAgent))throw Error(SWARM_BACKGROUND_TASK_BLOCKED_MESSAGE);if(targetAgent==="reviewer")try{let reviewSession=swarmState.agentSessions.get(input.sessionID);if(reviewSession){let reviewTaskId=await resolveEvidenceTaskId(args2,reviewSession,directory),changedFiles=reviewTaskId?getModifiedFilesForTask(reviewSession,reviewTaskId):[];if(changedFiles.length>0){let routing=await routeReviewForChanges(directory,changedFiles);if(shouldParallelizeReview(routing))pushAdvisory(reviewSession,`REVIEW ROUTING: High complexity detected (${routing.reason}). Consider parallel review: ${routing.reviewerCount} reviewers, ${routing.testEngineerCount} test engineers recommended.`)}}}catch{}if(targetAgent==="coder"||targetAgent==="reviewer"){let acceptancePromptText=ACCEPTANCE_ARGS_FIELDS.map((field)=>args2[field]).filter((value)=>typeof value==="string").join(`
862
862
  `),acceptanceCheck=validateCoderReviewerAcceptanceField(acceptancePromptText);if(!acceptanceCheck.valid){let detail=acceptanceCheck.reason==="acceptance_field_empty"?"its ACCEPTANCE field is present but empty/whitespace-only":"it has no ACCEPTANCE field";throw Error(`ACCEPTANCE_FIELD_REQUIRED: the ${targetAgent} delegation was blocked because ${detail}. `+"Every coder/reviewer dispatch MUST carry a non-empty ACCEPTANCE: line in its prompt — the mapped FR-###/SC-### ids "+"(for a single-task dispatch the delegation gate injects their verbatim requirement text from .swarm/spec.md automatically; phase/final-council multi-task reviewer dispatches are NOT auto-injected and must paste the verbatim text yourself) when the task maps to one or more spec requirements, or a one-line task-derived statement of what DONE looks like otherwise (see the ACCEPTANCE FIELD RESOLUTION section of your system prompt and .swarm/spec.md). Add an ACCEPTANCE: line to the delegation prompt and re-dispatch. Do NOT investigate the installed swarm plugin package (node_modules/opencode-swarm, "+"~/.cache/opencode) — the fix is in your dispatch content, not in plugin internals. If this same error "+"repeats after 2 fix attempts, STOP and present the blocker to the user.")}let coverageResult,coverageTaskId=null;try{let coveragePlan=await _internals65.loadPlanJsonOnly(directory);if(coveragePlan){let coveragePlanTaskIds=new Set(coveragePlan.phases.flatMap((phase)=>phase.tasks.map((t)=>t.id)));if(coverageTaskId=resolveDelegatedPlanTaskId(args2,coveragePlanTaskIds),coverageTaskId){let coverageTask=coveragePlan.phases.flatMap((phase)=>phase.tasks).find((t)=>t.id===coverageTaskId),frRefs=coverageTask?.fr_refs;if(coverageTask&&Array.isArray(frRefs)&&frRefs.length>0){let specText=await fs51.promises.readFile(path81.join(directory,".swarm","spec.md"),"utf8");injectSpecRequirementsIntoAcceptance({args:args2,frRefs,specText});let effectiveAcceptanceText=ACCEPTANCE_ARGS_FIELDS.map((field)=>args2[field]).filter((value)=>typeof value==="string").join(`
863
863
  `);coverageResult=checkAcceptanceCoversFrRefs({acceptanceText:effectiveAcceptanceText,frRefs,specText})}}}}catch{coverageResult=void 0}if(coverageResult&&coverageResult.covered===!1)throw buildAcceptanceCoverageMismatchError({targetAgent,coverageTaskId,coverageResult})}if(TASK_GATE_AGENTS.has(targetAgent)){let stageBSession=ensureAgentSession(input.sessionID),resolvedTaskId=await resolveEvidenceTaskId(args2,stageBSession,directory),candidateTaskIds=new Set;if(resolvedTaskId)candidateTaskIds.add(resolvedTaskId);let dispatchPlan=await loadPlanJsonOnly(directory);if(dispatchPlan){let knownIds=new Set(dispatchPlan.phases.flatMap((phase)=>phase.tasks.map((task)=>task.id))),dispatchText=[args2.prompt,args2.description,args2.task,args2.input].filter((value)=>typeof value==="string").join(`
864
- `);for(let match of dispatchText.matchAll(/(?:task-)?(\d+\.\d+(?:\.\d+)*)/gi))if(match[1]&&knownIds.has(match[1]))candidateTaskIds.add(match[1])}let generations=new Map,{getTaskWorkflowSnapshot:getTaskWorkflowSnapshot3,readTaskEvidence:readTaskEvidence3}=await Promise.resolve().then(() => (init_gate_evidence(),exports_gate_evidence));for(let taskId of candidateTaskIds){let workflow=getTaskWorkflowSnapshot3(await readTaskEvidence3(directory,taskId));if(taskId===resolvedTaskId&&await isCouncilGateActive(directory,config2.council)){if(!stageBSession.taskCouncilWorkflowGeneration)stageBSession.taskCouncilWorkflowGeneration=new Map;if(!stageBSession.taskCouncilWorkflowGeneration.has(taskId))stageBSession.taskCouncilWorkflowGeneration.set(taskId,workflow.generation)}if(targetAgent!=="reviewer"&&targetAgent!=="test_engineer"){generations.set(taskId,workflow.generation);continue}if(workflow.authoritative&&(workflow.state==="pre_check_passed"||workflow.state==="reviewer_run")){generations.set(taskId,workflow.generation);continue}if(taskId===resolvedTaskId)throw Error(`TASK_WORKFLOW_STAGE_A_REQUIRED: cannot dispatch ${targetAgent} for task ${taskId} from ${workflow.state}. Stage B (${targetAgent}) requires the task to be at pre_check_passed (or later) — a state written only by the stage_a_passed transition, which is emitted when pre_check_batch completes with the task correctly attributed. `+`Remediation: run pre_check_batch on the task's changed files first. If pre_check_batch passes but the task remains coder_delegated (typical after /swarm reset-session), run /swarm recover ${taskId} to repair Stage A attribution, then re-dispatch.`)}rememberStageBDispatchGenerations(input.callID,generations),gateDispatchPrimaryTaskByCallID.set(input.callID,resolvedTaskId),stageBDispatchContextByCallID.set(input.callID,{taskIds:new Set(generations.keys()),expectedVerdictKind:targetAgent==="test_engineer"?"TESTED":"REVIEWED"});return}if(targetAgent!=="coder")return;let session=ensureAgentSession(input.sessionID);if(!session||!session.taskWorkflowStates)return;let{getTaskWorkflowSnapshot:getTaskWorkflowSnapshot2,readTaskEvidence:readTaskEvidence2,transitionTaskWorkflowEvidence:transitionTaskWorkflowEvidence2}=await Promise.resolve().then(() => (init_gate_evidence(),exports_gate_evidence)),resolvedPreflightTaskId=await resolveEvidenceTaskId(args2,session,directory),preflightPlan=await loadPlanJsonOnly(directory),preflightTaskId=resolvedPreflightTaskId&&preflightPlan?.phases.some((phase)=>phase.tasks.some((task)=>task.id===resolvedPreflightTaskId))?resolvedPreflightTaskId:null,preflightEvidence=preflightTaskId?await readTaskEvidence2(directory,preflightTaskId):null,preflightWorkflow=getTaskWorkflowSnapshot2(preflightEvidence);if(preflightTaskId){if(await enforceCoderRetryEscalation({directory,taskId:preflightTaskId,generation:preflightWorkflow.generation,retryEpoch:preflightWorkflow.retryEpoch,retryCount:preflightWorkflow.retryCount,retryHistory:preflightWorkflow.retryHistory,criticSatisfied:preflightEvidence?.gates.critic_sounding_board!=null}),preflightWorkflow.state==="coder_delegated"){if(!(hasActiveTurboMode(input.sessionID)&&!preflightTaskId.startsWith("3.")))throw Error(`STAGE_A_REQUIRED: Task ${preflightTaskId} has an accepted coder mutation that has not passed pre_check_batch. Run Stage A first. If Stage A fails, the task becomes rework_required and the same-task coder may repair it. Do not send known-broken output to reviewer.`)}}let preparedScope;try{preparedScope=await prepareCoderScope(directory,input,args2)}catch(error49){if(preflightTaskId){let failed=await transitionTaskWorkflowEvidence2(directory,preflightTaskId,{type:"dispatch_no_mutation",agentType:"coder",expectedGeneration:preflightWorkflow.generation,transitionId:`coder-preflight:${input.callID}`}),failedWorkflow=getTaskWorkflowSnapshot2(failed);if(failedWorkflow.retryCount>=3)await emitCoderRetryEscalation(directory,{taskId:preflightTaskId,generation:failedWorkflow.generation,retryEpoch:failedWorkflow.retryEpoch,rejectionCount:failedWorkflow.retryCount,rejectionHistory:failedWorkflow.retryHistory,action:"sounding_board_consultation"})}throw error49}let{plan,taskId:incomingCoderTaskId}=preparedScope;if(incomingCoderTaskId)session.lastCoderDelegationTaskId=incomingCoderTaskId;let coderEvidence=incomingCoderTaskId?await readTaskEvidence2(directory,incomingCoderTaskId):null,coderWorkflow=getTaskWorkflowSnapshot2(coderEvidence),coderDispatchGeneration=coderWorkflow.generation;if(incomingCoderTaskId){if(incomingCoderTaskId!==preflightTaskId)await enforceCoderRetryEscalation({directory,taskId:incomingCoderTaskId,generation:coderWorkflow.generation,retryEpoch:coderWorkflow.retryEpoch,retryCount:coderWorkflow.retryCount,retryHistory:coderWorkflow.retryHistory,criticSatisfied:coderEvidence?.gates.critic_sounding_board!=null})}let reserveBackgroundCoderIfNeeded=async(maxConcurrent2)=>{if(!backgroundSubagentsEnabled||!isBackgroundTrue(args2.background))return;let occupiedTaskIds=[...session.taskWorkflowStates.entries()].filter(([,state])=>state==="coder_delegated").map(([taskId])=>taskId),claim=await _internals65.reserveBackgroundCoderSlotForDispatch(directory,{parentSessionId:input.sessionID,planTaskId:incomingCoderTaskId||null,callID:input.callID,maxConcurrent:maxConcurrent2,occupiedTaskIds});if(!claim.ok){let detail=claim.detail?` ${claim.detail}`:"",code=claim.reason==="capacity"?"PARALLEL_SLOTS_EXHAUSTED":claim.reason==="duplicate_task"||claim.reason==="duplicate_call"?"BACKGROUND_CODER_TASK_RESERVED":"BACKGROUND_CODER_RESERVATION_UNCERTAIN";throw Error(`${code}: background coder admission was blocked (${claim.reason}).${detail}`)}backgroundCoderReservationByCallID.set(input.callID,claim.reservation)};if(!plan){await reserveBackgroundCoderIfNeeded(1);try{if(shouldRememberCoderTaskChangeContext(preparedScope.declaredFiles,args2.background))rememberCoderTaskChangeContext(input.callID,preparedScope.declaredFiles,directory,coderDispatchGeneration);await publishScopeBinding(input.callID,directory,preparedScope.binding),await beginForegroundCoderSettlementIfNeeded(input,incomingCoderTaskId,args2.background)}catch(error49){throw await releasePrelaunchBackgroundCoderReservation(input.callID),clearPublishedScopeBindings(input.callID),clearCoderTaskChangeContext(input.callID),error49}return}let profile=plan?.execution_profile,parallelEnabled=profile?.parallelization_enabled===!0,maxConcurrent=profile?.max_concurrent_tasks??10,effectiveMaxConcurrent=session.maxConcurrencyOverride??maxConcurrent,scopeAllowsParallel=scopeVerdictAllowsParallel(directory,plan),standardWorktreeIsolationActive=parallelEnabled&&effectiveMaxConcurrent>1&&!hasActiveLeanTurbo(input.sessionID),parallelModeActive=standardWorktreeIsolationActive&&scopeAllowsParallel,criticPolicy=resolvePlanCriticPolicyForExecution(directory,plan,session.qaGateSessionOverrides??{});if(log(`[delegation-gate] critic_pre_plan policy task=${incomingCoderTaskId??"unknown"} required=${criticPolicy.required} source=${criticPolicy.source}`),criticPolicy.required)await assertPlanCriticApprovedForExecution(directory,plan);let{declaredFiles:incomingCoderDeclaredFiles,binding:correlatedBinding}=preparedScope;for(let task of plan.phases.flatMap((phase)=>phase.tasks)){let taskId=task.id,durableWorkflow=getTaskWorkflowSnapshot2(await readTaskEvidence2(directory,taskId)),state=durableWorkflow.authoritative?durableWorkflow.state:"idle";if(session.taskWorkflowStates.set(taskId,state),updateTaskWorkflowCache(session,taskId,durableWorkflow),state!=="coder_delegated")continue;let freshnessThreshold=session.sessionRehydratedAt>0?session.sessionRehydratedAt:session.lastPhaseCompleteTimestamp??0,hasCurrentSessionCoderDelegation=(swarmState.delegationChains.get(input.sessionID)??[]).some((d)=>stripKnownSwarmPrefix(d.to)==="coder"&&d.timestamp>freshnessThreshold);if(!durableWorkflow.authoritative&&!hasCurrentSessionCoderDelegation){session.taskWorkflowStates.set(taskId,"idle"),warn(`[delegation-gate] Reset stale coder_delegated state for task ${taskId} — `+"no coder delegation found in current session.");continue}if(hasActiveTurboMode(input.sessionID)){if(!taskId.startsWith("3."))continue}if(parallelModeActive&&incomingCoderTaskId&&taskId!==incomingCoderTaskId)continue;throw Error(`STAGE_A_REQUIRED: Task ${taskId} has an accepted coder mutation that has not passed pre_check_batch. Run Stage A first. If Stage A fails, the task becomes rework_required and the same-task coder may repair it. Do not send known-broken output to reviewer.`)}if(parallelModeActive){let coderDelegatedCount=0;for(let s of session.taskWorkflowStates.values())if(s==="coder_delegated")coderDelegatedCount++;if(coderDelegatedCount>=effectiveMaxConcurrent)throw Error(`PARALLEL_SLOTS_EXHAUSTED: ${coderDelegatedCount} coder task(s) are awaiting review (max_concurrent_tasks=${effectiveMaxConcurrent}). Dispatch reviewer/test_engineer for an in-flight coder task before starting another coder.`)}if(standardWorktreeSerializationSessions.has(input.sessionID)){if(checkStandardWorktreeSerializationRelease(input.sessionID,resolveWorktreeIsolationConfig(config2)),standardWorktreeSerializationSessions.has(input.sessionID))throw Error("STANDARD_WORKTREE_ISOLATION_SERIALIZED: prior standard worktree isolation setup failed in this session; wait for the active coder task to finish before dispatching another coder.")}await reserveBackgroundCoderIfNeeded(parallelModeActive?effectiveMaxConcurrent:1);try{if(!parallelModeActive){if(shouldRememberCoderTaskChangeContext(incomingCoderDeclaredFiles,args2.background))rememberCoderTaskChangeContext(input.callID,incomingCoderDeclaredFiles,directory,coderDispatchGeneration)}if(!standardWorktreeIsolationActive){if(shouldRememberCoderTaskChangeContext(incomingCoderDeclaredFiles,args2.background))rememberCoderTaskChangeContext(input.callID,incomingCoderDeclaredFiles,directory,coderDispatchGeneration);await publishScopeBinding(input.callID,directory,correlatedBinding),await beginForegroundCoderSettlementIfNeeded(input,incomingCoderTaskId,args2.background);return}let resolvedTaskId=incomingCoderTaskId,laneScope=correlatedBinding.files;await precreateStandardWorktreeSession({config:config2,directory,parentSessionID:input.sessionID,callID:input.callID,taskId:resolvedTaskId??sanitizeWorktreeTaskId(input.callID),planTaskId:resolvedTaskId??void 0,description:typeof args2.description==="string"?args2.description:void 0,outputArgs:args2,scope:laneScope&&laneScope.length>0&&resolvedTaskId?{taskId:resolvedTaskId,files:laneScope}:void 0});let standardDispatch=standardWorktreeByCallID.get(input.callID);if(standardDispatch){if(resolvedTaskId)try{let childSessionId=typeof args2.task_id==="string"?args2.task_id.trim():"";if(!childSessionId||childSessionId===input.sessionID)throw Error("SCOPE_CHILD_IDENTITY_MISSING: worktree dispatch did not return a distinct child session id");await savePlan(standardDispatch.handle.worktreePath,plan,{preserveCompletedStatuses:!1});let childBinding=deriveChildScopeBinding(correlatedBinding,{childDirectory:standardDispatch.handle.worktreePath,childSessionId,parentCallId:input.callID});await publishScopeBinding(input.callID,standardDispatch.handle.worktreePath,childBinding);let childSession=ensureAgentSession(childSessionId,"coder",standardDispatch.handle.worktreePath);childSession.currentTaskId=childBinding.taskId,childSession.declaredCoderScope=[...childBinding.files]}catch(error49){throw clearPublishedScopeBindings(input.callID),await cleanupStandardWorktreeForCallId(input.callID,"denied",directory,resolveWorktreeIsolationConfig(config2).worktree_dir),error49}if(shouldRememberCoderTaskChangeContext(incomingCoderDeclaredFiles,args2.background))rememberCoderTaskChangeContext(input.callID,incomingCoderDeclaredFiles,standardDispatch.handle.worktreePath,coderDispatchGeneration)}else{if(shouldRememberCoderTaskChangeContext(incomingCoderDeclaredFiles,args2.background))rememberCoderTaskChangeContext(input.callID,incomingCoderDeclaredFiles,directory,coderDispatchGeneration);let degradation=getStandardWorktreeDegradationReason(input.sessionID);if(degradation)try{let eventsPath=validateSwarmPath(directory,"events.jsonl");await fs51.promises.mkdir(path81.dirname(eventsPath),{recursive:!0}),await fs51.promises.appendFile(eventsPath,`${JSON.stringify({type:"worktree_isolation_degraded",timestamp:new Date().toISOString(),sessionId:input.sessionID,callId:input.callID,taskId:incomingCoderTaskId,reason:degradation.reason.length>500?`${degradation.reason.slice(0,500)}… (truncated)`:degradation.reason,degradedAt:new Date(degradation.at).toISOString()})}
864
+ `);for(let match of dispatchText.matchAll(/(?:task-)?(\d+\.\d+(?:\.\d+)*)/gi))if(match[1]&&knownIds.has(match[1]))candidateTaskIds.add(match[1])}let generations=new Map,{getTaskWorkflowSnapshot:getTaskWorkflowSnapshot3,readTaskEvidence:readTaskEvidence3}=await Promise.resolve().then(() => (init_gate_evidence(),exports_gate_evidence));for(let taskId of candidateTaskIds){let workflow=getTaskWorkflowSnapshot3(await readTaskEvidence3(directory,taskId));if(taskId===resolvedTaskId&&await isCouncilGateActive(directory,config2.council)){if(!stageBSession.taskCouncilWorkflowGeneration)stageBSession.taskCouncilWorkflowGeneration=new Map;if(!stageBSession.taskCouncilWorkflowGeneration.has(taskId))stageBSession.taskCouncilWorkflowGeneration.set(taskId,workflow.generation)}if(targetAgent!=="reviewer"&&targetAgent!=="test_engineer"){generations.set(taskId,workflow.generation);continue}if(workflow.authoritative&&(workflow.state==="pre_check_passed"||workflow.state==="reviewer_run")){generations.set(taskId,workflow.generation);continue}if(taskId===resolvedTaskId)throw Error(`TASK_WORKFLOW_STAGE_A_REQUIRED: cannot dispatch ${targetAgent} for task ${taskId} from ${workflow.state}. Stage B (${targetAgent}) requires the task to be at pre_check_passed (or later) — a state written only by the stage_a_passed transition, which is emitted when pre_check_batch completes with the task correctly attributed. `+`Remediation: run pre_check_batch on the task's changed files first. If pre_check_batch passes but the task remains coder_delegated (typical after /swarm reset-session), run /swarm recover ${taskId} to repair Stage A attribution, then re-dispatch.`)}rememberStageBDispatchGenerations(input.callID,generations),gateDispatchPrimaryTaskByCallID.set(input.callID,resolvedTaskId),stageBDispatchContextByCallID.set(input.callID,{taskIds:new Set(generations.keys()),expectedVerdictKind:targetAgent==="test_engineer"?"TESTED":"REVIEWED"});return}if(targetAgent!=="coder")return;let session=ensureAgentSession(input.sessionID);if(!session||!session.taskWorkflowStates)return;let{getTaskWorkflowSnapshot:getTaskWorkflowSnapshot2,readTaskEvidence:readTaskEvidence2,transitionTaskWorkflowEvidence:transitionTaskWorkflowEvidence2}=await Promise.resolve().then(() => (init_gate_evidence(),exports_gate_evidence)),resolvedPreflightTaskId=await resolveEvidenceTaskId(args2,session,directory),preflightPlan=await loadPlanJsonOnly(directory),preflightTaskId=resolvedPreflightTaskId&&preflightPlan?.phases.some((phase)=>phase.tasks.some((task)=>task.id===resolvedPreflightTaskId))?resolvedPreflightTaskId:null,preflightEvidence=preflightTaskId?await readTaskEvidence2(directory,preflightTaskId):null,preflightWorkflow=getTaskWorkflowSnapshot2(preflightEvidence);if(preflightTaskId){if(await enforceCoderRetryEscalation({directory,taskId:preflightTaskId,generation:preflightWorkflow.generation,retryEpoch:preflightWorkflow.retryEpoch,retryCount:preflightWorkflow.retryCount,retryHistory:preflightWorkflow.retryHistory,criticSatisfied:preflightEvidence?.gates.critic_sounding_board!=null}),preflightWorkflow.state==="coder_delegated"){if(!(hasActiveTurboMode(input.sessionID)&&!preflightTaskId.startsWith("3.")))throw Error(`STAGE_A_REQUIRED: Task ${preflightTaskId} has an accepted coder mutation that has not passed pre_check_batch. Run Stage A first. If Stage A fails, the task becomes rework_required and the same-task coder may repair it. Do not send known-broken output to reviewer.`)}}let preparedScope;try{preparedScope=await prepareCoderScope(directory,input,args2)}catch(error49){if(preflightTaskId){let failed=await transitionTaskWorkflowEvidence2(directory,preflightTaskId,{type:"dispatch_no_mutation",agentType:"coder",expectedGeneration:preflightWorkflow.generation,transitionId:`coder-preflight:${input.callID}`}),failedWorkflow=getTaskWorkflowSnapshot2(failed);if(failedWorkflow.retryCount>=3)await emitCoderRetryEscalation(directory,{taskId:preflightTaskId,generation:failedWorkflow.generation,retryEpoch:failedWorkflow.retryEpoch,rejectionCount:failedWorkflow.retryCount,rejectionHistory:failedWorkflow.retryHistory,action:"sounding_board_consultation"})}throw error49}let{plan,taskId:incomingCoderTaskId}=preparedScope;if(incomingCoderTaskId)session.lastCoderDelegationTaskId=incomingCoderTaskId;let coderEvidence=incomingCoderTaskId?await readTaskEvidence2(directory,incomingCoderTaskId):null,coderWorkflow=getTaskWorkflowSnapshot2(coderEvidence),coderDispatchGeneration=coderWorkflow.generation;if(incomingCoderTaskId){if(incomingCoderTaskId!==preflightTaskId)await enforceCoderRetryEscalation({directory,taskId:incomingCoderTaskId,generation:coderWorkflow.generation,retryEpoch:coderWorkflow.retryEpoch,retryCount:coderWorkflow.retryCount,retryHistory:coderWorkflow.retryHistory,criticSatisfied:coderEvidence?.gates.critic_sounding_board!=null})}let reserveBackgroundCoderIfNeeded=async(maxConcurrent2)=>{if(!backgroundSubagentsEnabled||!isBackgroundTrue(args2.background))return;try{await _internals65.maintainBackgroundDelegationsForDispatch(directory,{lockTimeoutMs:1000,reason:"admission"})}catch(error49){warn(`[delegation-gate] pre-admission background maintenance skipped: ${error49 instanceof Error?error49.message:String(error49)}`)}let occupiedTaskIds=[...session.taskWorkflowStates.entries()].filter(([,state])=>state==="coder_delegated").map(([taskId])=>taskId),claim=await _internals65.reserveBackgroundCoderSlotForDispatch(directory,{parentSessionId:input.sessionID,planTaskId:incomingCoderTaskId||null,callID:input.callID,maxConcurrent:maxConcurrent2,occupiedTaskIds});if(!claim.ok){let detail=claim.detail?` ${claim.detail}`:"",code=claim.reason==="capacity"?"PARALLEL_SLOTS_EXHAUSTED":claim.reason==="duplicate_task"||claim.reason==="duplicate_call"?"BACKGROUND_CODER_TASK_RESERVED":"BACKGROUND_CODER_RESERVATION_UNCERTAIN";throw Error(`${code}: background coder admission was blocked (${claim.reason}).${detail}`)}backgroundCoderReservationByCallID.set(input.callID,claim.reservation)};if(!plan){await reserveBackgroundCoderIfNeeded(1);try{if(shouldRememberCoderTaskChangeContext(preparedScope.declaredFiles,args2.background))rememberCoderTaskChangeContext(input.callID,preparedScope.declaredFiles,directory,coderDispatchGeneration);await publishScopeBinding(input.callID,directory,preparedScope.binding),await beginForegroundCoderSettlementIfNeeded(input,incomingCoderTaskId,args2.background)}catch(error49){throw await releasePrelaunchBackgroundCoderReservation(input.callID),clearPublishedScopeBindings(input.callID),clearCoderTaskChangeContext(input.callID),error49}return}let profile=plan?.execution_profile,parallelEnabled=profile?.parallelization_enabled===!0,maxConcurrent=profile?.max_concurrent_tasks??10,effectiveMaxConcurrent=session.maxConcurrencyOverride??maxConcurrent,scopeAllowsParallel=scopeVerdictAllowsParallel(directory,plan),standardWorktreeIsolationActive=parallelEnabled&&effectiveMaxConcurrent>1&&!hasActiveLeanTurbo(input.sessionID),parallelModeActive=standardWorktreeIsolationActive&&scopeAllowsParallel,criticPolicy=resolvePlanCriticPolicyForExecution(directory,plan,session.qaGateSessionOverrides??{});if(log(`[delegation-gate] critic_pre_plan policy task=${incomingCoderTaskId??"unknown"} required=${criticPolicy.required} source=${criticPolicy.source}`),criticPolicy.required)await assertPlanCriticApprovedForExecution(directory,plan);let{declaredFiles:incomingCoderDeclaredFiles,binding:correlatedBinding}=preparedScope;for(let task of plan.phases.flatMap((phase)=>phase.tasks)){let taskId=task.id,durableWorkflow=getTaskWorkflowSnapshot2(await readTaskEvidence2(directory,taskId)),state=durableWorkflow.authoritative?durableWorkflow.state:"idle";if(session.taskWorkflowStates.set(taskId,state),updateTaskWorkflowCache(session,taskId,durableWorkflow),state!=="coder_delegated")continue;let freshnessThreshold=session.sessionRehydratedAt>0?session.sessionRehydratedAt:session.lastPhaseCompleteTimestamp??0,hasCurrentSessionCoderDelegation=(swarmState.delegationChains.get(input.sessionID)??[]).some((d)=>stripKnownSwarmPrefix(d.to)==="coder"&&d.timestamp>freshnessThreshold);if(!durableWorkflow.authoritative&&!hasCurrentSessionCoderDelegation){session.taskWorkflowStates.set(taskId,"idle"),warn(`[delegation-gate] Reset stale coder_delegated state for task ${taskId} — `+"no coder delegation found in current session.");continue}if(hasActiveTurboMode(input.sessionID)){if(!taskId.startsWith("3."))continue}if(parallelModeActive&&incomingCoderTaskId&&taskId!==incomingCoderTaskId)continue;throw Error(`STAGE_A_REQUIRED: Task ${taskId} has an accepted coder mutation that has not passed pre_check_batch. Run Stage A first. If Stage A fails, the task becomes rework_required and the same-task coder may repair it. Do not send known-broken output to reviewer.`)}if(parallelModeActive){let coderDelegatedCount=0;for(let s of session.taskWorkflowStates.values())if(s==="coder_delegated")coderDelegatedCount++;if(coderDelegatedCount>=effectiveMaxConcurrent)throw Error(`PARALLEL_SLOTS_EXHAUSTED: ${coderDelegatedCount} coder task(s) are awaiting review (max_concurrent_tasks=${effectiveMaxConcurrent}). Dispatch reviewer/test_engineer for an in-flight coder task before starting another coder.`)}if(standardWorktreeSerializationSessions.has(input.sessionID)){if(checkStandardWorktreeSerializationRelease(input.sessionID,resolveWorktreeIsolationConfig(config2)),standardWorktreeSerializationSessions.has(input.sessionID))throw Error("STANDARD_WORKTREE_ISOLATION_SERIALIZED: prior standard worktree isolation setup failed in this session; wait for the active coder task to finish before dispatching another coder.")}await reserveBackgroundCoderIfNeeded(parallelModeActive?effectiveMaxConcurrent:1);try{if(!parallelModeActive){if(shouldRememberCoderTaskChangeContext(incomingCoderDeclaredFiles,args2.background))rememberCoderTaskChangeContext(input.callID,incomingCoderDeclaredFiles,directory,coderDispatchGeneration)}if(!standardWorktreeIsolationActive){if(shouldRememberCoderTaskChangeContext(incomingCoderDeclaredFiles,args2.background))rememberCoderTaskChangeContext(input.callID,incomingCoderDeclaredFiles,directory,coderDispatchGeneration);await publishScopeBinding(input.callID,directory,correlatedBinding),await beginForegroundCoderSettlementIfNeeded(input,incomingCoderTaskId,args2.background);return}let resolvedTaskId=incomingCoderTaskId,laneScope=correlatedBinding.files;await precreateStandardWorktreeSession({config:config2,directory,parentSessionID:input.sessionID,callID:input.callID,taskId:resolvedTaskId??sanitizeWorktreeTaskId(input.callID),planTaskId:resolvedTaskId??void 0,description:typeof args2.description==="string"?args2.description:void 0,outputArgs:args2,scope:laneScope&&laneScope.length>0&&resolvedTaskId?{taskId:resolvedTaskId,files:laneScope}:void 0});let standardDispatch=standardWorktreeByCallID.get(input.callID);if(standardDispatch){if(resolvedTaskId)try{let childSessionId=typeof args2.task_id==="string"?args2.task_id.trim():"";if(!childSessionId||childSessionId===input.sessionID)throw Error("SCOPE_CHILD_IDENTITY_MISSING: worktree dispatch did not return a distinct child session id");await savePlan(standardDispatch.handle.worktreePath,plan,{preserveCompletedStatuses:!1});let childBinding=deriveChildScopeBinding(correlatedBinding,{childDirectory:standardDispatch.handle.worktreePath,childSessionId,parentCallId:input.callID});await publishScopeBinding(input.callID,standardDispatch.handle.worktreePath,childBinding);let childSession=ensureAgentSession(childSessionId,"coder",standardDispatch.handle.worktreePath);childSession.currentTaskId=childBinding.taskId,childSession.declaredCoderScope=[...childBinding.files]}catch(error49){throw clearPublishedScopeBindings(input.callID),await cleanupStandardWorktreeForCallId(input.callID,"denied",directory,resolveWorktreeIsolationConfig(config2).worktree_dir),error49}if(shouldRememberCoderTaskChangeContext(incomingCoderDeclaredFiles,args2.background))rememberCoderTaskChangeContext(input.callID,incomingCoderDeclaredFiles,standardDispatch.handle.worktreePath,coderDispatchGeneration)}else{if(shouldRememberCoderTaskChangeContext(incomingCoderDeclaredFiles,args2.background))rememberCoderTaskChangeContext(input.callID,incomingCoderDeclaredFiles,directory,coderDispatchGeneration);let degradation=getStandardWorktreeDegradationReason(input.sessionID);if(degradation)try{let eventsPath=validateSwarmPath(directory,"events.jsonl");await fs51.promises.mkdir(path81.dirname(eventsPath),{recursive:!0}),await fs51.promises.appendFile(eventsPath,`${JSON.stringify({type:"worktree_isolation_degraded",timestamp:new Date().toISOString(),sessionId:input.sessionID,callId:input.callID,taskId:incomingCoderTaskId,reason:degradation.reason.length>500?`${degradation.reason.slice(0,500)}… (truncated)`:degradation.reason,degradedAt:new Date(degradation.at).toISOString()})}
865
865
  `,"utf-8")}catch(eventError){log(`[delegation-gate] worktree_isolation_degraded event write failed: ${eventError instanceof Error?eventError.message:String(eventError)}`)}await publishScopeBinding(input.callID,directory,correlatedBinding)}await beginForegroundCoderSettlementIfNeeded(input,incomingCoderTaskId,args2.background,standardDispatch?{callID:standardDispatch.callID,parentSessionId:standardDispatch.parentSessionID,taskId:incomingCoderTaskId,planTaskId:standardDispatch.planTaskId??null,worktreePath:standardDispatch.handle.worktreePath,branchName:standardDispatch.handle.branchName,worktreeId:standardDispatch.handle.id,worktreeSessionId:standardDispatch.handle.sessionId,mergeStrategy:standardDispatch.mergeStrategy,laneIndex:standardDispatch.laneIndex,worktreeDir:standardDispatch.worktree_dir??null}:void 0)}catch(error49){throw await releasePrelaunchBackgroundCoderReservation(input.callID),clearPublishedScopeBindings(input.callID),clearCoderTaskChangeContext(input.callID),error49}},messagesTransform:async(_input,output)=>{let messages=output.messages;if(!messages||messages.length===0)return;let lastUserMessageIndex=-1;for(let i=messages.length-1;i>=0;i--)if(messages[i]?.info?.role==="user"){lastUserMessageIndex=i;break}if(lastUserMessageIndex===-1)return;let lastUserMessage=messages[lastUserMessageIndex];if(!lastUserMessage?.parts)return;let agent=lastUserMessage.info?.agent;if(agent==="")return;let strippedAgent=agent?stripKnownSwarmPrefix(agent):void 0;if(strippedAgent&&strippedAgent!=="architect")return;let textPartIndex=lastUserMessage.parts.findIndex((p)=>p?.type==="text"&&p.text!==void 0);if(textPartIndex===-1)return;let textPart=lastUserMessage.parts[textPartIndex],text=textPart.text??"",taskDisclosureSessionID=lastUserMessage.info?.sessionID;if(taskDisclosureSessionID){let currentTaskIdForWindow=ensureAgentSession(taskDisclosureSessionID).currentTaskId;if(currentTaskIdForWindow){let taskLineRegex=/^[ \t]*-[ \t]*(?:\[[ x]\][ \t]+)?(\d+\.\d+(?:\.\d+)*)[:. ].*/gm,taskLines=[];taskLineRegex.lastIndex=0;let regexMatch=taskLineRegex.exec(text);while(regexMatch!==null)taskLines.push({line:regexMatch[0],taskId:regexMatch[1],index:regexMatch.index}),regexMatch=taskLineRegex.exec(text);if(taskLines.length>5){let currentIdx=taskLines.findIndex((t)=>t.taskId===currentTaskIdForWindow),windowStart=Math.max(0,currentIdx-2),windowEnd=Math.min(taskLines.length-1,currentIdx+3),visibleTasks=taskLines.slice(windowStart,windowEnd+1),hiddenBefore=windowStart,hiddenAfter=taskLines.length-1-windowEnd,totalTasks=taskLines.length,visibleCount=visibleTasks.length,firstTaskIndex=taskLines[0].index,lastTask=taskLines[taskLines.length-1],lastTaskEnd=lastTask.index+lastTask.line.length,before=text.slice(0,firstTaskIndex),after=text.slice(lastTaskEnd),visibleLines=visibleTasks.map((t)=>t.line).join(`
866
866
  `),trimComment=`[Task window: showing ${visibleCount} of ${totalTasks} tasks]`,trimmedMiddle=(hiddenBefore>0?`[...${hiddenBefore} tasks hidden...]
867
867
  `:"")+visibleLines+(hiddenAfter>0?`
@@ -871,7 +871,7 @@ ${trimComment}${after}`}}}let sessionID=lastUserMessage.info?.sessionID,planTask
871
871
  ${parallelGuidance??"[NEXT] Execute the next gate for the current task."}`}else guidance=parallelGuidance??"[NEXT] Begin the first plan task and run gates sequentially.";let systemMsgIdx=messages.findIndex((m)=>m&&m.info?.role==="system"),insertIdx=systemMsgIdx>=0?systemMsgIdx+1:0,guidanceMessage={info:{role:"system"},parts:[{type:"text",text:guidance}]};messages.splice(insertIdx,0,guidanceMessage)}}let warnings=[];if(text.length>delegationMaxChars)warnings.push(`Delegation exceeds recommended size (${text.length} chars, limit ${delegationMaxChars}). Consider splitting into smaller tasks.`);if(isCoderDelegation){let fileMatches=text.match(/^FILE:/gm);if(fileMatches&&fileMatches.length>1)warnings.push(`Multiple FILE: directives detected (${fileMatches.length}). Each coder task should target ONE file.`)}if(isCoderDelegation){let taskMatches=text.match(/^TASK:/gm);if(taskMatches&&taskMatches.length>1)warnings.push(`Multiple TASK: sections detected (${taskMatches.length}). Send ONE task per coder call.`)}if(isCoderDelegation){let batchingPattern=/\b(?:and also|then also|additionally|as well as|along with|while you'?re at it)[.,]?\b/gi,batchingMatches=text.match(batchingPattern);if(batchingMatches&&batchingMatches.length>0)warnings.push(`Batching language detected (${batchingMatches.join(", ")}). Break compound objectives into separate coder calls.`)}if(isCoderDelegation){let taskLine=extractTaskLine(text);if(taskLine){if(/\s+and\s+(update|add|remove|modify|refactor|implement|create|delete|fix|change|build|deploy|write|test|move|rename|extend|extract|convert|migrate|upgrade|replace)\b/i.test(taskLine))warnings.push('TASK line contains "and" connecting separate actions')}}if(isCoderDelegation&&sessionID){let delegationChain=swarmState.delegationChains.get(sessionID);if(delegationChain&&delegationChain.length>=2){let coderIndices=[];for(let i=delegationChain.length-1;i>=0;i--)if(stripKnownSwarmPrefix(delegationChain[i].to).includes("coder")){if(coderIndices.unshift(i),coderIndices.length===2)break}if(coderIndices.length===2){let prevCoderIndex=coderIndices[0],betweenCoders=delegationChain.slice(prevCoderIndex+1),hasReviewer=betweenCoders.some((d)=>stripKnownSwarmPrefix(d.to)==="reviewer"),hasTestEngineer=betweenCoders.some((d)=>stripKnownSwarmPrefix(d.to)==="test_engineer"),session=ensureAgentSession(sessionID),priorTaskStuckAtCoder=priorCoderTaskId!==null&&getTaskState(session,priorCoderTaskId)==="coder_delegated";if(!hasReviewer||!hasTestEngineer||priorTaskStuckAtCoder){if(session.qaSkipCount>=1){telemetry.qaSkipViolation(_input.sessionID,session.agentName,session.qaSkipCount+1);let skippedTasks=session.qaSkipTaskIds.join(", ");throw Error(`\uD83D\uDED1 QA GATE ENFORCEMENT: ${session.qaSkipCount+1} consecutive coder delegations without reviewer/test_engineer. Skipped tasks: [${skippedTasks}]. DELEGATE to reviewer and test_engineer NOW before any further coder work.`)}session.qaSkipCount++,session.qaSkipTaskIds.push(currentTaskId??"unknown"),warnings.push("⚠️ PROTOCOL VIOLATION: Previous coder task completed, but QA gate was skipped. "+"You MUST delegate to reviewer (code review) and test_engineer (test execution) before starting a new coder task. Review RULES 7-8 in your system prompt.")}}}}if(warnings.length===0)return;let warningText=`⚠️ BATCH DETECTED: Your coder delegation appears to contain multiple tasks.
872
872
  Rule 3: ONE task per coder call. Split this into separate delegations.
873
873
  ${warnings.map((w)=>`Detected signal: ${w}`).join(`
874
- `)}`,batchWarnSystemIdx=messages.findIndex((m)=>m&&m.info?.role==="system"),batchWarnInsertIdx=batchWarnSystemIdx>=0?batchWarnSystemIdx+1:0,batchWarnMessage={info:{role:"system"},parts:[{type:"text",text:warningText}]};messages.splice(batchWarnInsertIdx,0,batchWarnMessage)},toolAfter:async(input,_output)=>{let normalized=normalizeToolName(input.tool),isTaskTool2=normalized==="Task"||normalized==="task";if(!input.sessionID){if(isTaskTool2&&!outputLooksLikeBackgroundRunning(_output))clearPublishedScopeBindings(input.callID);return}let session=swarmState.agentSessions.get(input.sessionID);if(!session){if(isTaskTool2&&!outputLooksLikeBackgroundRunning(_output))clearPublishedScopeBindings(input.callID);return}let{qaGateSessionOverrides}=ensureAgentSession(input.sessionID),councilActive=await isCouncilGateActive(directory,config2.council,qaGateSessionOverrides??{});if(normalized==="submit_council_verdicts"){try{let result=typeof _output==="string"?JSON.parse(_output):_output;if(result&&typeof result==="object"&&result.success===!0&&typeof result.overallVerdict==="string"){let directArgs=input.args,storedArgs=getStoredInputArgs(input.callID),taskIdRaw=directArgs?.taskId??storedArgs?.taskId,taskId=typeof taskIdRaw==="string"?taskIdRaw:null;if(taskId){if(!session.taskCouncilApproved)session.taskCouncilApproved=new Map;let priorRewarded=session.taskCouncilApproved.get(taskId)?.rewarded===!0;if(session.taskCouncilApproved.set(taskId,{verdict:result.overallVerdict,roundNumber:typeof result.roundNumber==="number"?result.roundNumber:1,quorumSize:typeof result.quorumSize==="number"?result.quorumSize:1,rewarded:priorRewarded}),councilActive&&result.overallVerdict==="APPROVE"&&result.allCriteriaMet===!0&&(result.requiredFixesCount??0)===0)pushAdvisory(session,`Council approved task ${taskId}. Call update_task_status with status="completed" so the central plan/evidence transaction can commit it.`)}}}catch(err){log(`[delegation-gate] toolAfter submit_council_verdicts: failed to parse output: ${err instanceof Error?err.message:String(err)}`)}return}if(normalized==="Task"||normalized==="task"){let standardDispatch=standardWorktreeByCallID.get(input.callID),directArgsRaw=input.args,directArgs=directArgsRaw?{...directArgsRaw}:void 0;if(standardDispatch&&directArgs)if(standardDispatch.planTaskId)directArgs.task_id=standardDispatch.planTaskId;else delete directArgs.task_id;let storedArgs=getStoredInputArgs(input.callID),subagentType=directArgs?.subagent_type??storedArgs?.subagent_type,backgroundResultIsRunning=outputLooksLikeBackgroundRunning(_output),outputTerminalState=_output?.state,isTerminalFailure=outputTerminalState==="failed"||outputTerminalState==="error"||outputTerminalState==="cancelled"||outputTerminalState==="canceled";if(!isTerminalFailure&&typeof subagentType==="string"&&isKnownCanonicalRole(stripKnownSwarmPrefix(subagentType))&&(isBackgroundTrue(directArgs?.background)||isBackgroundTrue(storedArgs?.background)||backgroundResultIsRunning)){let coderReservation=backgroundCoderReservationByCallID.get(input.callID),backgroundRecordDurable=!backgroundSubagentsEnabled,backgroundOwnershipDurable=backgroundRecordDurable,backgroundCorrelationConflict=!1;if(backgroundSubagentsEnabled){let protectUntrackedBackgroundWorktree=async(taskId,reason)=>{if(!standardDispatch)return{detail:"no isolated worktree ownership tag was available",durable:!1};let detail,durable=!1;try{let preserved=await _internals55.preserveBackgroundWorktreeOwnershipForCallId(input.callID);durable=preserved.outcome==="preserved",detail=durable?`ownership tag ${preserved.tag} at ${preserved.ref}`:`ownership preservation failed: ${preserved.error??preserved.outcome}`}catch(err){detail=`ownership preservation threw: ${err instanceof Error?err.message:String(err)}`}return recordWorktreeMergeFailure(taskId??void 0,{outcome:"failed",stage:"background-correlation-persist",message:`${reason}; ${detail}. Automatic orphan reclamation is blocked until the dispatch is recovered.`,worktreePath:standardDispatch.handle.worktreePath,branch:standardDispatch.handle.branchName,queuedAt:Date.now()}),{detail,durable}};try{let{extractDispatchIds:extractDispatchIds2}=await Promise.resolve().then(() => (init_task_envelope(),exports_task_envelope)),{buildPromptSnapshot:buildPromptSnapshot2,findByCorrelationId:findByCorrelationId2}=await Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations)),{captureWorkspaceSnapshot:captureWorkspaceSnapshot2}=await Promise.resolve().then(() => (init_workspace_snapshot(),exports_workspace_snapshot)),{subagentSessionId,jobId}=extractDispatchIds2(_output);if(!subagentSessionId&&!backgroundResultIsRunning){if(await releasePrelaunchBackgroundCoderReservation(input.callID),clearPublishedScopeBindings(input.callID),clearCoderTaskChangeContext(input.callID),storedArgs!==void 0)deleteStoredInputArgs(input.callID);return}if(subagentSessionId){let mergedArgs={...storedArgs??{},...directArgs},evidenceTaskId=await resolveEvidenceTaskId(mergedArgs,session,directory),scope=session.declaredCoderScope&&session.declaredCoderScope.length>0?session.declaredCoderScope.join(","):evidenceTaskId,prHeadShaRaw=mergedArgs.prHeadSha??mergedArgs.pr_head_sha,prHeadSha=typeof prHeadShaRaw==="string"?prHeadShaRaw:null,taskChangeContext=stripKnownSwarmPrefix(subagentType)==="coder"?coderTaskChangeContextByCallID.get(input.callID):void 0,pendingInputDraft={correlationId:subagentSessionId,jobId,subagentSessionId,parentSessionId:input.sessionID,callID:input.callID,normalizedAgent:stripKnownSwarmPrefix(subagentType),swarmPrefixedAgent:subagentType,planTaskId:evidenceTaskId,evidenceTaskId,workspace:taskChangeContext?{...taskChangeContext.baseline,prHeadSha,scope}:captureWorkspaceSnapshot2(directory,{prHeadSha,scope}),taskChangeContext,workflowGeneration:TASK_GATE_AGENTS.has(stripKnownSwarmPrefix(subagentType))?stageBDispatchGenerationsByCallID.get(input.callID)?.get(evidenceTaskId??""):void 0,worktree:standardDispatch?{callID:standardDispatch.callID,parentSessionId:standardDispatch.parentSessionID,taskId:standardDispatch.taskId,planTaskId:standardDispatch.planTaskId??null,worktreePath:standardDispatch.handle.worktreePath,branchName:standardDispatch.handle.branchName,worktreeId:standardDispatch.handle.id,worktreeSessionId:standardDispatch.handle.sessionId,mergeStrategy:standardDispatch.mergeStrategy,laneIndex:standardDispatch.laneIndex,worktreeDir:standardDispatch.worktree_dir??null}:void 0,coderReservationId:coderReservation?.reservationId,prompt:typeof mergedArgs.prompt==="string"?buildPromptSnapshot2(mergedArgs.prompt,delegationMaxChars):void 0,generation:1},existingOwner=findByCorrelationId2(directory,subagentSessionId),pendingInput=existingOwner&&hasStableBackgroundReplayIdentity(existingOwner,pendingInputDraft)?hydrateBackgroundReplayInput(existingOwner,pendingInputDraft):pendingInputDraft,primaryOutcome=await _internals65.recordPendingDelegationForBackground(directory,pendingInput,{staleTimeoutMs:backgroundPendingTimeoutMs});if(backgroundRecordDurable=primaryOutcome.status==="recorded"||primaryOutcome.status==="duplicate",backgroundCorrelationConflict=primaryOutcome.status==="conflict",primaryOutcome.status==="conflict"){let preservation=await protectUntrackedBackgroundWorktree(evidenceTaskId??standardDispatch?.planTaskId,"background correlation id conflicts with an existing immutable launch owner"),worktreeStatus=!standardDispatch?"No isolated worktree was attached to this conflicting call.":preservation.durable?`The current worktree was durably preserved with ${preservation.detail}.`:`The current worktree was not durably preserved (${preservation.detail}); automatic reclamation remains blocked pending recovery.`,reservationStatus=coderReservation?`The current reservation ${coderReservation.reservationId} was retained and was not bound to the conflicting correlation.`:primaryOutcome.record.coderReservationId?`No new reservation was present for this replay; the durable owner's reservation ${primaryOutcome.record.coderReservationId} remains unchanged.`:"No current or durable-owner coder reservation was present.";backgroundOwnershipDurable=preservation.durable,pushAdvisory(session,`BACKGROUND DELEGATION CORRELATION CONFLICT: ${subagentType} (${subagentSessionId}) collided with a different durable launch owner (parent=${primaryOutcome.record.parentSessionId}, call=${primaryOutcome.record.callID}, agent=${primaryOutcome.record.swarmPrefixedAgent}, task=${primaryOutcome.record.planTaskId??"none"}). Inspect that existing owner and reconcile it before continuing. ${worktreeStatus} ${reservationStatus} No fallback owner was written and no reservation was bound. Do not abort, delete, or re-dispatch this correlation until reconciliation is complete. Do not advance task ${evidenceTaskId??"unknown"} until the collision is resolved.`)}else if(primaryOutcome.status==="failed"){if(backgroundRecordDurable=await _internals65.writeDelegationFallbackForBackground(directory,pendingInput)!==null,backgroundRecordDurable)warn(`[delegation-gate] background delegation ${subagentSessionId} persisted to the independent fallback artifact after the primary ledger write failed`)}if(!backgroundCorrelationConflict&&!backgroundRecordDurable){let preservation=await protectUntrackedBackgroundWorktree(evidenceTaskId??standardDispatch?.planTaskId,"both background correlation stores failed");backgroundOwnershipDurable=preservation.durable,pushAdvisory(session,`BACKGROUND DELEGATION UNTRACKED: ${subagentType} (${subagentSessionId}) launched, but both durable correlation stores failed. Recovery protection: ${preservation.detail}. Do not advance task ${evidenceTaskId??"unknown"} until the dispatch is recovered.`)}else if(!backgroundCorrelationConflict){if(backgroundOwnershipDurable=!0,coderReservation){if(!await _internals65.bindBackgroundCoderReservationForDispatch(directory,{...coderReservation,correlationId:subagentSessionId}))pushAdvisory(session,`BACKGROUND CODER RESERVATION UNBOUND: task ${evidenceTaskId??"unknown"} is durably tracked, but its pre-launch reservation could not be bound to ${subagentSessionId}. Further coder admission remains fail-closed until completion or recovery reconciles it.`)}}}else{let preservation=await protectUntrackedBackgroundWorktree(standardDispatch?.planTaskId,"background dispatch returned no trusted correlation id");backgroundOwnershipDurable=preservation.durable,warn("[delegation-gate] background dispatch had no correlation id (no jobId / no envelope) — not tracked"),pushAdvisory(session,`BACKGROUND DELEGATION UNCORRELATED: ${subagentType} launched without a trusted session correlation. Recovery protection: ${preservation.detail}. Do not advance the task until the dispatch is recovered or safely re-dispatched.`)}}catch(err){let preservation=await protectUntrackedBackgroundWorktree(standardDispatch?.planTaskId,"background dispatch correlation recording threw");backgroundOwnershipDurable=preservation.durable,warn(`[delegation-gate] background pending recording failed: ${err instanceof Error?err.message:String(err)}`),pushAdvisory(session,`BACKGROUND DELEGATION DURABILITY FAILURE: ${subagentType} launched, but its completion owner could not be persisted. Recovery protection: ${preservation.detail}. Do not advance the task until the dispatch is recovered.`)}}if(backgroundOwnershipDurable)_internals55.removeWorktreeProvisioningOwner(directory,input.callID);if(backgroundRecordDurable){if(clearCoderTaskChangeContext(input.callID),stageBDispatchGenerationsByCallID.delete(input.callID),gateDispatchPrimaryTaskByCallID.delete(input.callID),stageBDispatchContextByCallID.delete(input.callID),storedArgs!==void 0)deleteStoredInputArgs(input.callID)}if(!backgroundCorrelationConflict)backgroundCoderReservationByCallID.delete(input.callID);if(!backgroundResultIsRunning)clearPublishedScopeBindings(input.callID);return}let foregroundCoderTaskId=typeof subagentType==="string"&&stripKnownSwarmPrefix(subagentType)==="coder"?standardDispatch?.planTaskId??standardDispatch?.taskId??(typeof directArgs?.task_id==="string"?directArgs.task_id:typeof storedArgs?.task_id==="string"?storedArgs.task_id:null):null;clearPublishedScopeBindings(input.callID);try{if(typeof subagentType==="string")try{let mergedArgs={...storedArgs??{},...directArgs??{}};await recordPlanCriticApprovalSnapshotIfApplicable(directory,input,mergedArgs,_output)}catch(err){warn(`[delegation-gate] plan critic approval snapshot failed: ${err instanceof Error?err.message:String(err)}`)}if(typeof subagentType==="string"){let advisoryPrompt={...storedArgs??{},...directArgs??{}}.prompt;if(typeof advisoryPrompt==="string"&&advisoryPrompt.length>0)appendDelegationEnvelopeAdvisory(session,advisoryPrompt,{planTasks:[],validAgents:[...ALL_AGENT_NAMES]})}let standardWorktreeSettled=!standardDispatch,coderSettlementCommitted=!1,coderSettlementEvidence=null,isStandardWorktreeFailure=outputTerminalState==="cancelled"||outputTerminalState==="failed"||outputTerminalState==="error";if(standardDispatch&&!isStandardWorktreeFailure){let taskChangeContext=coderTaskChangeContextByCallID.get(input.callID);if(taskChangeContext)rememberCoderObservedFiles(input.callID,changedFilesSinceSnapshot(taskChangeContext.baseline.directory,taskChangeContext.baseline));standardWorktreeByCallID.delete(input.callID),awaitingMergeByCallID.set(input.callID,{callID:input.callID,parentSessionID:standardDispatch.parentSessionID,taskId:standardDispatch.taskId,planTaskId:standardDispatch.planTaskId,branch:standardDispatch.handle.branchName,worktreePath:standardDispatch.handle.worktreePath,mergeStrategy:standardDispatch.mergeStrategy,queuedAt:Date.now()});let observedForMerge=coderObservedFilesByCallID.get(input.callID);if(!Array.isArray(observedForMerge))throw Error(`CODER_SETTLEMENT_ATTRIBUTION_UNCERTAIN: isolated task ${standardDispatch.planTaskId??standardDispatch.taskId} changed files could not be proven from its clean launch baseline`);standardWorktreeSettled=(await finishStandardWorktreeDispatch(directory,standardDispatch,config2,input.callID,{operationId:`coder:${input.callID}`,onBeforeMerge:(provenance)=>recordCoderMergeProvenance({directory,taskId:standardDispatch.planTaskId??standardDispatch.taskId,transitionId:`coder:${input.callID}`,provenance,observedFiles:observedForMerge}),onMerged:async()=>{coderSettlementEvidence=(await settleCoderDispatch({directory,taskId:standardDispatch.planTaskId??standardDispatch.taskId,transitionId:`coder:${input.callID}`,accepted:observedForMerge.length>0,testEngineerExempt:isMarkdownOnlyTaskChange(coderTaskChangeContextByCallID.get(input.callID)?.declaredFiles,observedForMerge)})).evidence,coderSettlementCommitted=!0}}).catch((err)=>{let reason=err instanceof Error?err.message:String(err);warn(`[delegation-gate] standard worktree merge-back failed for ${standardDispatch.taskId}: ${reason}`),recordWorktreeMergeFailure(standardDispatch.planTaskId??standardDispatch.taskId,{outcome:"failed",stage:"merge-back",message:reason,worktreePath:standardDispatch.handle.worktreePath,branch:standardDispatch.handle.branchName,completedAt:Date.now()});let dispatchSession=ensureAgentSession(standardDispatch.parentSessionID);pushAdvisory(dispatchSession,`STANDARD_WORKTREE_MERGE_FAILED: task ${standardDispatch.taskId} preserved at ${standardDispatch.handle.worktreePath}; reason: ${reason}.`),awaitingMergeByCallID.delete(input.callID)}))?.outcome==="merged"}if(standardDispatch&&isStandardWorktreeFailure){standardWorktreeByCallID.delete(input.callID);let reason=outputTerminalState==="cancelled"?"cancelled":"denied";await _internals55.preserveDirtyWorktreeForCallId(input.callID,reason,directory),await _internals55.removeWorktree(standardDispatch.handle.worktreePath,directory),await _internals55.postMergeCleanup(directory,standardDispatch.handle.branchName),awaitingMergeByCallID.delete(input.callID),recordWorktreeMergeFailure(standardDispatch.planTaskId??standardDispatch.taskId,{outcome:"failed",stage:"task-result",message:`task terminated with ${outputTerminalState??"terminal-failure"}`});let dispatchSession=ensureAgentSession(standardDispatch.parentSessionID);pushAdvisory(dispatchSession,`STANDARD_WORKTREE_TASK_FAILED: task ${standardDispatch.taskId} terminated with ${outputTerminalState??"terminal-failure"}; worktree preserved and cleaned without merge-back.`)}let hasReviewer=!1,hasTestEngineer=!1;if(typeof subagentType==="string"){let targetAgent=stripKnownSwarmPrefix(subagentType);if(targetAgent==="reviewer")hasReviewer=!0;if(targetAgent==="test_engineer")hasTestEngineer=!0;if(!councilActive){if(_output?.status!=="failed"&&!isStandardWorktreeFailure&&(targetAgent==="reviewer"||targetAgent==="test_engineer")&&session.taskWorkflowStates){let stageBEligibleStates=["pre_check_passed","reviewer_run"],attributionResult=parsePerTaskVerdicts(outputText(_output));for(let err of attributionResult.errors)warn(`[delegation-gate] ${err}`);do{if(attributionResult.verdicts.size===0){let dispatchCtx=stageBDispatchContextByCallID.get(input.callID),expectedTasks=dispatchCtx?[...dispatchCtx.taskIds].join(", "):gateDispatchPrimaryTaskByCallID.get(input.callID)??"unknown";warn(`[delegation-gate] STAGE_B_ATTRIBUTION_MISSING: ${targetAgent} dispatch for call ${input.callID} returned no structured verdict lines. Expected tasks: ${expectedTasks}. Agent output must include [REVIEWED] or [TESTED] verdict lines.`);let failClosedTaskIds=dispatchCtx?[...dispatchCtx.taskIds]:gateDispatchPrimaryTaskByCallID.has(input.callID)?[gateDispatchPrimaryTaskByCallID.get(input.callID)]:[];for(let failTaskId of failClosedTaskIds){let failState=session.taskWorkflowStates.get(failTaskId);if(failState&&stageBEligibleStates.includes(failState))session.taskWorkflowStates.set(failTaskId,"rework_required"),session.stageBCompletion?.delete(failTaskId),warn(`[delegation-gate] STAGE_B_ATTRIBUTION_MISSING fail-closed: task ${failTaskId} → rework_required`)}break}let{getTaskWorkflowSnapshot:getTaskWorkflowSnapshot2,readTaskEvidence:readTaskEvidence2,transitionTaskWorkflowEvidence:transitionTaskWorkflowEvidence2}=await Promise.resolve().then(() => (init_gate_evidence(),exports_gate_evidence));for(let[taskId,state]of session.taskWorkflowStates){if(!stageBEligibleStates.includes(state))continue;if(!attributionResult.verdicts.has(taskId))continue;let eligibleState=state,launchGeneration=stageBDispatchGenerationsByCallID.get(input.callID)?.get(taskId);if(launchGeneration===void 0){warn(`[delegation-gate] ignoring unbound Stage B settlement for ${taskId} from call ${input.callID}`);continue}let verdictEntry=attributionResult.verdicts.get(taskId);if(!(stageBDispatchContextByCallID.get(input.callID)?.expectedVerdictKind==="TESTED"?verdictEntry?.verdict==="PASS":verdictEntry?.verdict==="APPROVED")){try{let rejected=await transitionTaskWorkflowEvidence2(directory,taskId,{type:"stage_b_failed",gate:targetAgent,expectedGeneration:launchGeneration,transitionId:`gate-failed:${input.callID}:${taskId}`});session.taskWorkflowStates.set(taskId,"rework_required"),session.stageBCompletion?.delete(taskId),updateTaskWorkflowCache(session,taskId,getTaskWorkflowSnapshot2(rejected))}catch(err){warn(`[delegation-gate] Stage B rejection could not be persisted for ${taskId}: ${err instanceof Error?err.message:String(err)}`)}continue}try{let turbo=hasActiveTurboMode(input.sessionID),{recordGateEvidence:recordGateEvidence2}=await Promise.resolve().then(() => (init_gate_evidence(),exports_gate_evidence));await recordGateEvidence2(directory,taskId,targetAgent,input.sessionID,turbo,{expectedGeneration:launchGeneration,transitionId:`gate:${input.callID}:${taskId}`})}catch(err){warn(`[delegation-gate] Stage B settlement rejected for ${taskId}: ${err instanceof Error?err.message:String(err)}`);continue}recordStageBCompletion(session,taskId,targetAgent);let taskEvidence=await readTaskEvidence2(directory,taskId),reviewerCompletesStageB=targetAgent==="reviewer"&&taskEvidence?.test_engineer_exempt===!0;if(hasBothStageBCompletions(session,taskId)||reviewerCompletesStageB)try{if(eligibleState==="pre_check_passed")advanceTaskState(session,taskId,"reviewer_run",{telemetrySessionId:input.sessionID});advanceTaskState(session,taskId,"tests_run",{telemetrySessionId:input.sessionID})}catch(err){warn(`[delegation-gate] toolAfter stage-b-parallel: could not advance ${taskId} (${eligibleState}) → tests_run: ${err instanceof Error?err.message:String(err)}`)}else try{if(targetAgent==="reviewer"&&eligibleState==="pre_check_passed")advanceTaskState(session,taskId,"reviewer_run",{telemetrySessionId:input.sessionID});else if(targetAgent==="test_engineer"&&eligibleState==="reviewer_run")advanceTaskState(session,taskId,"tests_run",{telemetrySessionId:input.sessionID})}catch(err){warn(`[delegation-gate] toolAfter stage-b-parallel intermediate: could not advance ${taskId} (${eligibleState}) after ${targetAgent}: ${err instanceof Error?err.message:String(err)}`)}}}while(!1)}}}if(typeof subagentType==="string"){let coderSettleTaskId=null;try{let mergedArgs={...storedArgs??{},...directArgs},evidenceTaskId=await resolveEvidenceTaskId(mergedArgs,session,directory);if(!evidenceTaskId&&stripKnownSwarmPrefix(subagentType)==="coder"){let begun=begunCoderSettlementsByCallID.get(input.callID);if(begun?.taskId)evidenceTaskId=begun.taskId}if(coderSettleTaskId=evidenceTaskId,evidenceTaskId){let turbo=hasActiveTurboMode(input.sessionID),gateAgents=["reviewer","test_engineer","docs","designer","critic","critic_sounding_board","explorer","sme"],targetAgentForEvidence=stripKnownSwarmPrefix(subagentType);if(gateAgents.includes(targetAgentForEvidence))if(targetAgentForEvidence==="reviewer"||targetAgentForEvidence==="test_engineer");else{if(!(!isTerminalFailure&&(targetAgentForEvidence!=="critic"&&targetAgentForEvidence!=="critic_sounding_board"||extractPlanCriticVerdict(_output)==="APPROVED")))throw Error(`TASK_GATE_NOT_SATISFIED: ${targetAgentForEvidence} did not return a trusted positive verdict`);let{recordGateEvidence:recordGateEvidence2}=await Promise.resolve().then(() => (init_gate_evidence(),exports_gate_evidence)),gateLaunchGeneration=stageBDispatchGenerationsByCallID.get(input.callID)?.get(evidenceTaskId);if(TASK_GATE_AGENTS.has(targetAgentForEvidence)&&gateLaunchGeneration===void 0)throw Error(`TASK_WORKFLOW_GENERATION_REQUIRED: no launch binding for ${targetAgentForEvidence} task ${evidenceTaskId}`);await recordGateEvidence2(directory,evidenceTaskId,targetAgentForEvidence,input.sessionID,turbo,{expectedGeneration:gateLaunchGeneration,transitionId:`gate:${input.callID}:${evidenceTaskId}`})}else{let{getTaskWorkflowSnapshot:getTaskWorkflowSnapshot2,recordAgentDispatch:recordAgentDispatch2}=await Promise.resolve().then(() => (init_gate_evidence(),exports_gate_evidence)),taskChangeContext=targetAgentForEvidence==="coder"?coderTaskChangeContextByCallID.get(input.callID):void 0,rawObservedFiles=taskChangeContext?coderObservedFilesByCallID.get(input.callID)??changedFilesSinceSnapshot(taskChangeContext.baseline.directory,taskChangeContext.baseline):null;if(targetAgentForEvidence==="coder"&&!Array.isArray(rawObservedFiles))throw Error(`CODER_SETTLEMENT_ATTRIBUTION_UNCERTAIN: shared-root task ${evidenceTaskId} changed files could not be proven from its clean launch baseline`);let observedFiles=taskChangeContext?.declaredFiles&&Array.isArray(rawObservedFiles)?rawObservedFiles.filter((filePath)=>isPathWithinDeclaredScope(filePath,taskChangeContext.declaredFiles,taskChangeContext.baseline.directory)):[],context={testEngineerExempt:targetAgentForEvidence==="coder"&&isMarkdownOnlyTaskChange(taskChangeContext?.declaredFiles,observedFiles)};if(targetAgentForEvidence==="coder"){let accepted=(!standardDispatch||!isTerminalFailure)&&standardWorktreeSettled&&Array.isArray(observedFiles)&&observedFiles.length>0,updated;if(standardDispatch&&!isStandardWorktreeFailure){if(!coderSettlementCommitted||!coderSettlementEvidence)throw Error(`CODER_SETTLEMENT_NOT_COMMITTED: isolated merge for ${evidenceTaskId} did not durably publish accepted-mutation evidence`);updated=coderSettlementEvidence}else updated=(await settleCoderDispatch({directory,taskId:evidenceTaskId,transitionId:`coder:${input.callID}`,accepted,testEngineerExempt:context.testEngineerExempt===!0,settlementFailed:!standardDispatch&&isTerminalFailure})).evidence,coderSettlementCommitted=!0;if(accepted){let workflow=getTaskWorkflowSnapshot2(updated);session.taskWorkflowStates.set(evidenceTaskId,workflow.state),session.stageBCompletion?.delete(evidenceTaskId),session.taskCouncilApproved?.delete(evidenceTaskId),session.taskCouncilWorkflowGeneration?.delete(evidenceTaskId),updateTaskWorkflowCache(session,evidenceTaskId,workflow)}}else await recordAgentDispatch2(directory,evidenceTaskId,targetAgentForEvidence,turbo,context)}}}catch(err){let normalizedAgent=stripKnownSwarmPrefix(subagentType);if(warn(`[delegation-gate] evidence recording failed: ${err instanceof Error?err.message:String(err)}`),normalizedAgent==="coder"){let terminalAbort=!1;if(coderSettleTaskId&&!coderSettlementCommitted){releaseCoderDispatchOwnership(directory,coderSettleTaskId,`coder:${input.callID}`);try{let abortOutcome=await abortCoderSettlementIfDoomed({directory,taskId:coderSettleTaskId,transitionId:`coder:${input.callID}`});terminalAbort=abortOutcome==="aborted"||abortOutcome==="already-aborted"}catch(abortErr){warn(`[delegation-gate] doomed settlement abort failed for ${coderSettleTaskId}: ${abortErr instanceof Error?abortErr.message:String(abortErr)}`)}if(terminalAbort)clearCoderTaskChangeContext(input.callID)}if(terminalAbort)pushAdvisory(session,`CODER_SETTLEMENT_ABORTED: task ${coderSettleTaskId} dispatch ${input.callID} was settled as ABORTED — its launch baseline was dirty or had no git history, so the coder's changes cannot be attributed. Reconcile the workspace (commit, stash, or discard the coder's output), then repair the task with update_task_status and re-dispatch from a clean tree.`);else pushAdvisory(session,`CODER_SETTLEMENT_DURABILITY_FAILURE: task output remains fenced until accepted-mutation evidence for call ${input.callID} is recovered.`);throw err}}finally{if(stripKnownSwarmPrefix(subagentType)==="coder"){if(coderSettlementCommitted)clearCoderTaskChangeContext(input.callID),clearPublishedScopeBindings(input.callID);if(begunCoderSettlementsByCallID.delete(input.callID),!coderSettlementCommitted)stageBDispatchGenerationsByCallID.delete(input.callID),gateDispatchPrimaryTaskByCallID.delete(input.callID),deleteStoredInputArgs(input.callID)}}}if(storedArgs!==void 0)deleteStoredInputArgs(input.callID);if(!subagentType||!hasReviewer||councilActive){let delegationChain=swarmState.delegationChains.get(input.sessionID);if(delegationChain&&delegationChain.length>0){let lastCoderIndex=-1;for(let i=delegationChain.length-1;i>=0;i--)if(stripKnownSwarmPrefix(delegationChain[i].to).includes("coder")){lastCoderIndex=i;break}let searchStart=lastCoderIndex===-1?0:lastCoderIndex,afterCoder=delegationChain.slice(searchStart);for(let delegation of afterCoder){let target=stripKnownSwarmPrefix(delegation.to);if(target==="reviewer")hasReviewer=!0;if(target==="test_engineer")hasTestEngineer=!0}if(lastCoderIndex!==-1&&hasReviewer&&hasTestEngineer)session.qaSkipCount=0,session.qaSkipTaskIds=[]}}if(stageBDispatchGenerationsByCallID.delete(input.callID),gateDispatchPrimaryTaskByCallID.delete(input.callID),stageBDispatchContextByCallID.delete(input.callID),session.taskWorkflowStates){for(let[,state]of session.taskWorkflowStates)if(state==="tests_run"){let taskAwaiting=await findTaskAwaitingCompletion(directory);if(taskAwaiting&&!session.completionGateWarnedForTask.has(taskAwaiting))pushAdvisory(session,completionGateViolationMessage(taskAwaiting)),session.completionGateWarnedForTask.add(taskAwaiting);break}}if(standardWorktreeSettled&&coderSettlementCommitted){if(foregroundCoderTaskId)await completeCoderSettlementCleanup(directory,foregroundCoderTaskId,`coder:${input.callID}`)}}finally{if(foregroundCoderTaskId)releaseCoderDispatchOwnership(directory,foregroundCoderTaskId,`coder:${input.callID}`)}}},taskMetadata,sessionEnded,backgroundCompletionClaimed,abortDeniedSettlementForCall:async(callID)=>{let begun=begunCoderSettlementsByCallID.get(callID);if(!begun?.taskId)return;try{await abortCoderSettlement({directory,taskId:begun.taskId,transitionId:begun.transitionId,reason:"dispatch denied by a fail-closed gate after settlement began"})}catch(error49){criticalWarn(`[delegation-gate] denied-dispatch settlement rollback failed for call ${callID} (task ${begun.taskId}): ${error49 instanceof Error?error49.message:String(error49)}`)}finally{releaseCoderDispatchOwnership(directory,begun.taskId,begun.transitionId),begunCoderSettlementsByCallID.delete(callID),clearCoderTaskChangeContext(callID),clearPublishedScopeBindings(callID),stageBDispatchGenerationsByCallID.delete(callID),gateDispatchPrimaryTaskByCallID.delete(callID),deleteStoredInputArgs(callID)}}}}var EvidenceTaskIdPlanSchema,BoundedPendingScopeMap,pendingCoderScopeByTaskId,SWARM_BACKGROUND_TASK_BLOCKED_MESSAGE="SWARM_BACKGROUND_TASK_BLOCKED: OpenCode background subagents (Task with background=true, requires OPENCODE_EXPERIMENTAL_BACKGROUND_SUBAGENTS=true or OPENCODE_EXPERIMENTAL=true) remain experimental upstream and are disabled by default in swarm. Omit `background` (or set background=false), or explicitly enable hooks.background_subagents only after reviewing the background-subagent recovery and readiness guidance.",COVERAGE_DIAG_SNIPPET_CAP=80,COVERAGE_DIAG_MAX_SCAN=400,COVERAGE_DIAG_MIN_PREFIX=10,ACCEPTANCE_EXPECTED_BODY_CAP=2000,ACCEPTANCE_ARGS_FIELDS,PLAN_CRITIC_TASK_SIGNALS,ACTIVE_PARALLEL_TASK_STATES,COMPLETION_RECOVERY_TOOLS,TASK_GATE_AGENTS,recordPendingDelegationForBackground=async(...args2)=>(await Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations))).recordPendingDelegationDetailed(...args2),writeDelegationFallbackForBackground=async(...args2)=>(await Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations))).writeDelegationFallback(...args2),reserveBackgroundCoderSlotForDispatch=async(...args2)=>(await Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations))).reserveBackgroundCoderSlot(...args2),bindBackgroundCoderReservationForDispatch=async(...args2)=>(await Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations))).bindBackgroundCoderReservation(...args2),releaseBackgroundCoderReservationForDispatch=async(...args2)=>(await Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations))).releaseBackgroundCoderReservation(...args2),_internals65;var init_delegation_gate=__esm(()=>{init_zod();init_workspace_snapshot();init_agent_names();init_constants();init_schema();init_qa_gate_profile();init_policy();init_gate_evidence_classification();init_file_locks();init_review_router();init_ledger();init_manager();init_parallel_verdict();init_utils3();init_prm();init_path_identity();init_scope_binding();init_scope_persistence();init_scope_resolution_diagnostic();init_state2();init_telemetry();init_logger();init_task_id();init_coder_settlement();init_task_repair();init_task_terminal();init_worktree_isolation();init_pr_workflow_gate();init_worktree_isolation();init_worktree_merge_status();init_guardrails2();init_normalize_tool_name();init_utils2();EvidenceTaskIdPlanSchema=exports_external.object({phases:exports_external.array(exports_external.object({tasks:exports_external.array(exports_external.object({id:exports_external.string(),status:exports_external.string().optional()}).passthrough()).optional()}).passthrough()).optional()}).passthrough();BoundedPendingScopeMap=class BoundedPendingScopeMap extends Map{expiresAtByKey=new Map;sweepExpired(now=Date.now()){for(let[key,expiresAt]of this.expiresAtByKey)if(expiresAt<=now)this.delete(key)}set(key,value){this.sweepExpired(),this.delete(key),super.set(key,value),this.expiresAtByKey.set(key,Date.now()+300000);while(this.size>MAX_PENDING_SCOPE_BINDINGS){let oldest=this.keys().next().value;if(!oldest)break;this.delete(oldest)}return this}get(key){return this.sweepExpired(),super.get(key)}has(key){return this.sweepExpired(),super.has(key)}delete(key){return this.expiresAtByKey.delete(key),super.delete(key)}clear(){this.expiresAtByKey.clear(),super.clear()}};pendingCoderScopeByTaskId=new BoundedPendingScopeMap;ACCEPTANCE_ARGS_FIELDS=["prompt","description","task","input","message"];PLAN_CRITIC_TASK_SIGNALS=["critic-gate","plan critic","review plan","review the plan","plan.md","approve the plan","plan approval","pre-implementation review","evaluate this plan","evaluate the plan","assess this plan","assess the plan","plan soundness","before implementation","review the plan below"];ACTIVE_PARALLEL_TASK_STATES=new Set(["coder_delegated","pre_check_passed","reviewer_run","tests_run"]);COMPLETION_RECOVERY_TOOLS=new Set(["get_approved_plan","get_qa_gate_profile","check_gate_status"]),TASK_GATE_AGENTS=new Set(["reviewer","test_engineer","docs","designer","critic","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","explorer","sme"]);_internals65={resolveEvidenceTaskId,resolveDelegatedPlanTaskId,describeCoderScopeFailure,parsePerTaskVerdicts,buildParallelExecutionGuidance,extractTaskFileDirectives,loadPlanJsonOnly,recordPendingDelegationForBackground,writeDelegationFallbackForBackground,reserveBackgroundCoderSlotForDispatch,bindBackgroundCoderReservationForDispatch,releaseBackgroundCoderReservationForDispatch,resetStandardWorktreeIsolationState,PLAN_CRITIC_TASK_SIGNALS,extractPlanCriticVerdict,forceRecordPlanCriticApproval,get provisionWorktree(){return _internals55.provisionWorktree},set provisionWorktree(v){_internals55.provisionWorktree=v},get removeWorktree(){return _internals55.removeWorktree},set removeWorktree(v){_internals55.removeWorktree=v},get attemptMergeBackFromDirty(){return _internals55.attemptMergeBackFromDirty},set attemptMergeBackFromDirty(v){_internals55.attemptMergeBackFromDirty=v},get postMergeCleanup(){return _internals55.postMergeCleanup},set postMergeCleanup(v){_internals55.postMergeCleanup=v},get preserveBackgroundWorktreeOwnershipForCallId(){return _internals55.preserveBackgroundWorktreeOwnershipForCallId},set preserveBackgroundWorktreeOwnershipForCallId(v){_internals55.preserveBackgroundWorktreeOwnershipForCallId=v}}});function positiveIntegerOrDefault(value,fallback){return Number.isInteger(value)&&Number(value)>0?Number(value):fallback}function rememberSession(sessionID,state){if(realtimeLearningNudgeBySession.has(sessionID))realtimeLearningNudgeBySession.delete(sessionID);realtimeLearningNudgeBySession.set(sessionID,state);while(realtimeLearningNudgeBySession.size>500){let oldestSessionID=realtimeLearningNudgeBySession.keys().next().value;if(oldestSessionID===void 0)break;realtimeLearningNudgeBySession.delete(oldestSessionID)}}function recordRealtimeLearningToolCall(sessionID){let prior=realtimeLearningNudgeBySession.get(sessionID),nextState={observedToolCallCount:(prior?.observedToolCallCount??0)+1,lastNudgedAtToolCallCount:prior?.lastNudgedAtToolCallCount??0};return rememberSession(sessionID,nextState),nextState.observedToolCallCount}function getRealtimeLearningToolCallCount(sessionID){if(!sessionID)return 0;return realtimeLearningNudgeBySession.get(sessionID)?.observedToolCallCount??0}function shouldInjectRealtimeLearningNudge(args2){if(!args2.sessionID)return!1;if(args2.config?.enabled===!1)return!1;if(args2.realtimeAdmission?.enabled===!0&&args2.realtimeAdmission?.supersede_nudge!==!1)return!1;let state=realtimeLearningNudgeBySession.get(args2.sessionID),toolCallCount=state?.observedToolCallCount??0,firstAfterToolCalls=positiveIntegerOrDefault(args2.config?.first_after_tool_calls,10),repeatAfterToolCalls=positiveIntegerOrDefault(args2.config?.repeat_after_tool_calls,25);if(toolCallCount<firstAfterToolCalls)return!1;if(!state||state.lastNudgedAtToolCallCount===0)return!0;return toolCallCount-state.lastNudgedAtToolCallCount>=repeatAfterToolCalls}function recordRealtimeLearningNudge(sessionID){let prior=realtimeLearningNudgeBySession.get(sessionID);if(!prior)return;rememberSession(sessionID,{...prior,lastNudgedAtToolCallCount:prior.observedToolCallCount})}function resetRealtimeLearningNudgeState(){realtimeLearningNudgeBySession.clear()}function clearRealtimeLearningNudgeSession(sessionID){realtimeLearningNudgeBySession.delete(sessionID)}function buildRealtimeLearningNudge(args2){return["[SWARM LEARNING NUDGE]",`Session has ${args2.toolCallCount} tool calls in phase ${args2.currentPhase}. Before continuing, decide whether the current work revealed a durable procedural lesson.`,"- If yes, call knowledge_add now with actionable when/then/scope fields so later turns can retrieve it.","- If the signal needs review across evidence, repeated outcomes, or generated-skill health, let the curator phase/postmortem path handle it; curator can emit knowledge_application_findings and skill_candidates without activating skills.","- Prefer reinforcing existing knowledge over noisy one-offs. Do not save transient setup failures, stale negative tool claims, or repo-specific accidents without a reusable trigger.","- If repeated KNOWLEDGE_IGNORED/VIOLATED outcomes or stale generated skills are accumulating, use skill_improve only when enabled/approved; generated skills stay proposal/draft gated and must not auto-activate.","- If there is nothing durable, continue without adding knowledge."].join(`
874
+ `)}`,batchWarnSystemIdx=messages.findIndex((m)=>m&&m.info?.role==="system"),batchWarnInsertIdx=batchWarnSystemIdx>=0?batchWarnSystemIdx+1:0,batchWarnMessage={info:{role:"system"},parts:[{type:"text",text:warningText}]};messages.splice(batchWarnInsertIdx,0,batchWarnMessage)},toolAfter:async(input,_output)=>{let normalized=normalizeToolName(input.tool),isTaskTool2=normalized==="Task"||normalized==="task";if(!input.sessionID){if(isTaskTool2&&!outputLooksLikeBackgroundRunning(_output))clearPublishedScopeBindings(input.callID);return}let session=swarmState.agentSessions.get(input.sessionID);if(!session){if(isTaskTool2&&!outputLooksLikeBackgroundRunning(_output))clearPublishedScopeBindings(input.callID);return}let{qaGateSessionOverrides}=ensureAgentSession(input.sessionID),councilActive=await isCouncilGateActive(directory,config2.council,qaGateSessionOverrides??{});if(normalized==="submit_council_verdicts"){try{let result=typeof _output==="string"?JSON.parse(_output):_output;if(result&&typeof result==="object"&&result.success===!0&&typeof result.overallVerdict==="string"){let directArgs=input.args,storedArgs=getStoredInputArgs(input.callID),taskIdRaw=directArgs?.taskId??storedArgs?.taskId,taskId=typeof taskIdRaw==="string"?taskIdRaw:null;if(taskId){if(!session.taskCouncilApproved)session.taskCouncilApproved=new Map;let priorRewarded=session.taskCouncilApproved.get(taskId)?.rewarded===!0;if(session.taskCouncilApproved.set(taskId,{verdict:result.overallVerdict,roundNumber:typeof result.roundNumber==="number"?result.roundNumber:1,quorumSize:typeof result.quorumSize==="number"?result.quorumSize:1,rewarded:priorRewarded}),councilActive&&result.overallVerdict==="APPROVE"&&result.allCriteriaMet===!0&&(result.requiredFixesCount??0)===0)pushAdvisory(session,`Council approved task ${taskId}. Call update_task_status with status="completed" so the central plan/evidence transaction can commit it.`)}}}catch(err){log(`[delegation-gate] toolAfter submit_council_verdicts: failed to parse output: ${err instanceof Error?err.message:String(err)}`)}return}if(normalized==="Task"||normalized==="task"){let standardDispatch=standardWorktreeByCallID.get(input.callID),directArgsRaw=input.args,directArgs=directArgsRaw?{...directArgsRaw}:void 0;if(standardDispatch&&directArgs)if(standardDispatch.planTaskId)directArgs.task_id=standardDispatch.planTaskId;else delete directArgs.task_id;let storedArgs=getStoredInputArgs(input.callID),subagentType=directArgs?.subagent_type??storedArgs?.subagent_type,backgroundResultIsRunning=outputLooksLikeBackgroundRunning(_output),outputTerminalState=_output?.state,isTerminalFailure=outputTerminalState==="failed"||outputTerminalState==="error"||outputTerminalState==="cancelled"||outputTerminalState==="canceled";if(!isTerminalFailure&&typeof subagentType==="string"&&isKnownCanonicalRole(stripKnownSwarmPrefix(subagentType))&&(isBackgroundTrue(directArgs?.background)||isBackgroundTrue(storedArgs?.background)||backgroundResultIsRunning)){let coderReservation=backgroundCoderReservationByCallID.get(input.callID),backgroundRecordDurable=!backgroundSubagentsEnabled,backgroundOwnershipDurable=backgroundRecordDurable,backgroundCorrelationConflict=!1;if(backgroundSubagentsEnabled){let protectUntrackedBackgroundWorktree=async(taskId,reason)=>{if(!standardDispatch)return{detail:"no isolated worktree ownership tag was available",durable:!1};let detail,durable=!1;try{let preserved=await _internals55.preserveBackgroundWorktreeOwnershipForCallId(input.callID);durable=preserved.outcome==="preserved",detail=durable?`ownership tag ${preserved.tag} at ${preserved.ref}`:`ownership preservation failed: ${preserved.error??preserved.outcome}`}catch(err){detail=`ownership preservation threw: ${err instanceof Error?err.message:String(err)}`}return recordWorktreeMergeFailure(taskId??void 0,{outcome:"failed",stage:"background-correlation-persist",message:`${reason}; ${detail}. Automatic orphan reclamation is blocked until the dispatch is recovered.`,worktreePath:standardDispatch.handle.worktreePath,branch:standardDispatch.handle.branchName,queuedAt:Date.now()}),{detail,durable}};try{let{extractDispatchIds:extractDispatchIds2}=await Promise.resolve().then(() => (init_task_envelope(),exports_task_envelope)),{buildPromptSnapshot:buildPromptSnapshot2,findByCorrelationId:findByCorrelationId2}=await Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations)),{captureWorkspaceSnapshot:captureWorkspaceSnapshot2}=await Promise.resolve().then(() => (init_workspace_snapshot(),exports_workspace_snapshot)),{subagentSessionId,jobId}=extractDispatchIds2(_output);if(!subagentSessionId&&!backgroundResultIsRunning){if(await releasePrelaunchBackgroundCoderReservation(input.callID),clearPublishedScopeBindings(input.callID),clearCoderTaskChangeContext(input.callID),storedArgs!==void 0)deleteStoredInputArgs(input.callID);return}if(subagentSessionId){let mergedArgs={...storedArgs??{},...directArgs},evidenceTaskId=await resolveEvidenceTaskId(mergedArgs,session,directory),scope=session.declaredCoderScope&&session.declaredCoderScope.length>0?session.declaredCoderScope.join(","):evidenceTaskId,prHeadShaRaw=mergedArgs.prHeadSha??mergedArgs.pr_head_sha,prHeadSha=typeof prHeadShaRaw==="string"?prHeadShaRaw:null,taskChangeContext=stripKnownSwarmPrefix(subagentType)==="coder"?coderTaskChangeContextByCallID.get(input.callID):void 0,pendingInputDraft={correlationId:subagentSessionId,jobId,subagentSessionId,parentSessionId:input.sessionID,callID:input.callID,normalizedAgent:stripKnownSwarmPrefix(subagentType),swarmPrefixedAgent:subagentType,planTaskId:evidenceTaskId,evidenceTaskId,workspace:taskChangeContext?{...taskChangeContext.baseline,prHeadSha,scope}:captureWorkspaceSnapshot2(directory,{prHeadSha,scope}),taskChangeContext,workflowGeneration:TASK_GATE_AGENTS.has(stripKnownSwarmPrefix(subagentType))?stageBDispatchGenerationsByCallID.get(input.callID)?.get(evidenceTaskId??""):void 0,worktree:standardDispatch?{callID:standardDispatch.callID,parentSessionId:standardDispatch.parentSessionID,taskId:standardDispatch.taskId,planTaskId:standardDispatch.planTaskId??null,worktreePath:standardDispatch.handle.worktreePath,branchName:standardDispatch.handle.branchName,worktreeId:standardDispatch.handle.id,worktreeSessionId:standardDispatch.handle.sessionId,mergeStrategy:standardDispatch.mergeStrategy,laneIndex:standardDispatch.laneIndex,worktreeDir:standardDispatch.worktree_dir??null}:void 0,coderReservationId:coderReservation?.reservationId,prompt:typeof mergedArgs.prompt==="string"?buildPromptSnapshot2(mergedArgs.prompt,delegationMaxChars):void 0,generation:1},existingOwner=findByCorrelationId2(directory,subagentSessionId),pendingInput=existingOwner&&hasStableBackgroundReplayIdentity(existingOwner,pendingInputDraft)?hydrateBackgroundReplayInput(existingOwner,pendingInputDraft):pendingInputDraft,primaryOutcome=await _internals65.recordPendingDelegationForBackground(directory,pendingInput,{staleTimeoutMs:backgroundPendingTimeoutMs});if(backgroundRecordDurable=primaryOutcome.status==="recorded"||primaryOutcome.status==="duplicate",backgroundCorrelationConflict=primaryOutcome.status==="conflict",primaryOutcome.status==="conflict"){let preservation=await protectUntrackedBackgroundWorktree(evidenceTaskId??standardDispatch?.planTaskId,"background correlation id conflicts with an existing immutable launch owner"),worktreeStatus=!standardDispatch?"No isolated worktree was attached to this conflicting call.":preservation.durable?`The current worktree was durably preserved with ${preservation.detail}.`:`The current worktree was not durably preserved (${preservation.detail}); automatic reclamation remains blocked pending recovery.`,reservationStatus=coderReservation?`The current reservation ${coderReservation.reservationId} was retained and was not bound to the conflicting correlation.`:primaryOutcome.record.coderReservationId?`No new reservation was present for this replay; the durable owner's reservation ${primaryOutcome.record.coderReservationId} remains unchanged.`:"No current or durable-owner coder reservation was present.";backgroundOwnershipDurable=preservation.durable,pushAdvisory(session,`BACKGROUND DELEGATION CORRELATION CONFLICT: ${subagentType} (${subagentSessionId}) collided with a different durable launch owner (parent=${primaryOutcome.record.parentSessionId}, call=${primaryOutcome.record.callID}, agent=${primaryOutcome.record.swarmPrefixedAgent}, task=${primaryOutcome.record.planTaskId??"none"}). Inspect that existing owner and reconcile it before continuing. ${worktreeStatus} ${reservationStatus} No fallback owner was written and no reservation was bound. Do not abort, delete, or re-dispatch this correlation until reconciliation is complete. Do not advance task ${evidenceTaskId??"unknown"} until the collision is resolved.`)}else if(primaryOutcome.status==="failed"){if(backgroundRecordDurable=await _internals65.writeDelegationFallbackForBackground(directory,pendingInput)!==null,backgroundRecordDurable)warn(`[delegation-gate] background delegation ${subagentSessionId} persisted to the independent fallback artifact after the primary ledger write failed`)}if(!backgroundCorrelationConflict&&!backgroundRecordDurable){let preservation=await protectUntrackedBackgroundWorktree(evidenceTaskId??standardDispatch?.planTaskId,"both background correlation stores failed");backgroundOwnershipDurable=preservation.durable,pushAdvisory(session,`BACKGROUND DELEGATION UNTRACKED: ${subagentType} (${subagentSessionId}) launched, but both durable correlation stores failed. Recovery protection: ${preservation.detail}. Do not advance task ${evidenceTaskId??"unknown"} until the dispatch is recovered.`)}else if(!backgroundCorrelationConflict){if(backgroundOwnershipDurable=!0,coderReservation){if(!await _internals65.bindBackgroundCoderReservationForDispatch(directory,{...coderReservation,correlationId:subagentSessionId,generation:pendingInput.generation??1}))pushAdvisory(session,`BACKGROUND CODER RESERVATION UNBOUND: task ${evidenceTaskId??"unknown"} is durably tracked, but its pre-launch reservation could not be bound to ${subagentSessionId}. Further coder admission remains fail-closed until completion or recovery reconciles it.`)}}}else{let preservation=await protectUntrackedBackgroundWorktree(standardDispatch?.planTaskId,"background dispatch returned no trusted correlation id");backgroundOwnershipDurable=preservation.durable,warn("[delegation-gate] background dispatch had no correlation id (no jobId / no envelope) — not tracked"),pushAdvisory(session,`BACKGROUND DELEGATION UNCORRELATED: ${subagentType} launched without a trusted session correlation. Recovery protection: ${preservation.detail}. Do not advance the task until the dispatch is recovered or safely re-dispatched.`)}}catch(err){let preservation=await protectUntrackedBackgroundWorktree(standardDispatch?.planTaskId,"background dispatch correlation recording threw");backgroundOwnershipDurable=preservation.durable,warn(`[delegation-gate] background pending recording failed: ${err instanceof Error?err.message:String(err)}`),pushAdvisory(session,`BACKGROUND DELEGATION DURABILITY FAILURE: ${subagentType} launched, but its completion owner could not be persisted. Recovery protection: ${preservation.detail}. Do not advance the task until the dispatch is recovered.`)}}if(backgroundOwnershipDurable)_internals55.removeWorktreeProvisioningOwner(directory,input.callID);if(backgroundRecordDurable){if(clearCoderTaskChangeContext(input.callID),stageBDispatchGenerationsByCallID.delete(input.callID),gateDispatchPrimaryTaskByCallID.delete(input.callID),stageBDispatchContextByCallID.delete(input.callID),storedArgs!==void 0)deleteStoredInputArgs(input.callID)}if(!backgroundCorrelationConflict)backgroundCoderReservationByCallID.delete(input.callID);if(!backgroundResultIsRunning)clearPublishedScopeBindings(input.callID);return}let foregroundCoderTaskId=typeof subagentType==="string"&&stripKnownSwarmPrefix(subagentType)==="coder"?standardDispatch?.planTaskId??standardDispatch?.taskId??(typeof directArgs?.task_id==="string"?directArgs.task_id:typeof storedArgs?.task_id==="string"?storedArgs.task_id:null):null;clearPublishedScopeBindings(input.callID);try{if(typeof subagentType==="string")try{let mergedArgs={...storedArgs??{},...directArgs??{}};await recordPlanCriticApprovalSnapshotIfApplicable(directory,input,mergedArgs,_output)}catch(err){warn(`[delegation-gate] plan critic approval snapshot failed: ${err instanceof Error?err.message:String(err)}`)}if(typeof subagentType==="string"){let advisoryPrompt={...storedArgs??{},...directArgs??{}}.prompt;if(typeof advisoryPrompt==="string"&&advisoryPrompt.length>0)appendDelegationEnvelopeAdvisory(session,advisoryPrompt,{planTasks:[],validAgents:[...ALL_AGENT_NAMES]})}let standardWorktreeSettled=!standardDispatch,coderSettlementCommitted=!1,coderSettlementEvidence=null,isStandardWorktreeFailure=outputTerminalState==="cancelled"||outputTerminalState==="failed"||outputTerminalState==="error";if(standardDispatch&&!isStandardWorktreeFailure){let taskChangeContext=coderTaskChangeContextByCallID.get(input.callID);if(taskChangeContext)rememberCoderObservedFiles(input.callID,changedFilesSinceSnapshot(taskChangeContext.baseline.directory,taskChangeContext.baseline));standardWorktreeByCallID.delete(input.callID),awaitingMergeByCallID.set(input.callID,{callID:input.callID,parentSessionID:standardDispatch.parentSessionID,taskId:standardDispatch.taskId,planTaskId:standardDispatch.planTaskId,branch:standardDispatch.handle.branchName,worktreePath:standardDispatch.handle.worktreePath,mergeStrategy:standardDispatch.mergeStrategy,queuedAt:Date.now()});let observedForMerge=coderObservedFilesByCallID.get(input.callID);if(!Array.isArray(observedForMerge))throw Error(`CODER_SETTLEMENT_ATTRIBUTION_UNCERTAIN: isolated task ${standardDispatch.planTaskId??standardDispatch.taskId} changed files could not be proven from its clean launch baseline`);standardWorktreeSettled=(await finishStandardWorktreeDispatch(directory,standardDispatch,config2,input.callID,{operationId:`coder:${input.callID}`,onBeforeMerge:(provenance)=>recordCoderMergeProvenance({directory,taskId:standardDispatch.planTaskId??standardDispatch.taskId,transitionId:`coder:${input.callID}`,provenance,observedFiles:observedForMerge}),onMerged:async()=>{coderSettlementEvidence=(await settleCoderDispatch({directory,taskId:standardDispatch.planTaskId??standardDispatch.taskId,transitionId:`coder:${input.callID}`,accepted:observedForMerge.length>0,testEngineerExempt:isMarkdownOnlyTaskChange(coderTaskChangeContextByCallID.get(input.callID)?.declaredFiles,observedForMerge)})).evidence,coderSettlementCommitted=!0}}).catch((err)=>{let reason=err instanceof Error?err.message:String(err);warn(`[delegation-gate] standard worktree merge-back failed for ${standardDispatch.taskId}: ${reason}`),recordWorktreeMergeFailure(standardDispatch.planTaskId??standardDispatch.taskId,{outcome:"failed",stage:"merge-back",message:reason,worktreePath:standardDispatch.handle.worktreePath,branch:standardDispatch.handle.branchName,completedAt:Date.now()});let dispatchSession=ensureAgentSession(standardDispatch.parentSessionID);pushAdvisory(dispatchSession,`STANDARD_WORKTREE_MERGE_FAILED: task ${standardDispatch.taskId} preserved at ${standardDispatch.handle.worktreePath}; reason: ${reason}.`),awaitingMergeByCallID.delete(input.callID)}))?.outcome==="merged"}if(standardDispatch&&isStandardWorktreeFailure){standardWorktreeByCallID.delete(input.callID);let reason=outputTerminalState==="cancelled"?"cancelled":"denied";await _internals55.preserveDirtyWorktreeForCallId(input.callID,reason,directory),await _internals55.removeWorktree(standardDispatch.handle.worktreePath,directory),await _internals55.postMergeCleanup(directory,standardDispatch.handle.branchName),awaitingMergeByCallID.delete(input.callID),recordWorktreeMergeFailure(standardDispatch.planTaskId??standardDispatch.taskId,{outcome:"failed",stage:"task-result",message:`task terminated with ${outputTerminalState??"terminal-failure"}`});let dispatchSession=ensureAgentSession(standardDispatch.parentSessionID);pushAdvisory(dispatchSession,`STANDARD_WORKTREE_TASK_FAILED: task ${standardDispatch.taskId} terminated with ${outputTerminalState??"terminal-failure"}; worktree preserved and cleaned without merge-back.`)}let hasReviewer=!1,hasTestEngineer=!1;if(typeof subagentType==="string"){let targetAgent=stripKnownSwarmPrefix(subagentType);if(targetAgent==="reviewer")hasReviewer=!0;if(targetAgent==="test_engineer")hasTestEngineer=!0;if(!councilActive){if(_output?.status!=="failed"&&!isStandardWorktreeFailure&&(targetAgent==="reviewer"||targetAgent==="test_engineer")&&session.taskWorkflowStates){let stageBEligibleStates=["pre_check_passed","reviewer_run"],attributionResult=parsePerTaskVerdicts(outputText(_output));for(let err of attributionResult.errors)warn(`[delegation-gate] ${err}`);do{if(attributionResult.verdicts.size===0){let dispatchCtx=stageBDispatchContextByCallID.get(input.callID),expectedTasks=dispatchCtx?[...dispatchCtx.taskIds].join(", "):gateDispatchPrimaryTaskByCallID.get(input.callID)??"unknown";warn(`[delegation-gate] STAGE_B_ATTRIBUTION_MISSING: ${targetAgent} dispatch for call ${input.callID} returned no structured verdict lines. Expected tasks: ${expectedTasks}. Agent output must include [REVIEWED] or [TESTED] verdict lines.`);let failClosedTaskIds=dispatchCtx?[...dispatchCtx.taskIds]:gateDispatchPrimaryTaskByCallID.has(input.callID)?[gateDispatchPrimaryTaskByCallID.get(input.callID)]:[];for(let failTaskId of failClosedTaskIds){let failState=session.taskWorkflowStates.get(failTaskId);if(failState&&stageBEligibleStates.includes(failState))session.taskWorkflowStates.set(failTaskId,"rework_required"),session.stageBCompletion?.delete(failTaskId),warn(`[delegation-gate] STAGE_B_ATTRIBUTION_MISSING fail-closed: task ${failTaskId} → rework_required`)}break}let{getTaskWorkflowSnapshot:getTaskWorkflowSnapshot2,readTaskEvidence:readTaskEvidence2,transitionTaskWorkflowEvidence:transitionTaskWorkflowEvidence2}=await Promise.resolve().then(() => (init_gate_evidence(),exports_gate_evidence));for(let[taskId,state]of session.taskWorkflowStates){if(!stageBEligibleStates.includes(state))continue;if(!attributionResult.verdicts.has(taskId))continue;let eligibleState=state,launchGeneration=stageBDispatchGenerationsByCallID.get(input.callID)?.get(taskId);if(launchGeneration===void 0){warn(`[delegation-gate] ignoring unbound Stage B settlement for ${taskId} from call ${input.callID}`);continue}let verdictEntry=attributionResult.verdicts.get(taskId);if(!(stageBDispatchContextByCallID.get(input.callID)?.expectedVerdictKind==="TESTED"?verdictEntry?.verdict==="PASS":verdictEntry?.verdict==="APPROVED")){try{let rejected=await transitionTaskWorkflowEvidence2(directory,taskId,{type:"stage_b_failed",gate:targetAgent,expectedGeneration:launchGeneration,transitionId:`gate-failed:${input.callID}:${taskId}`});session.taskWorkflowStates.set(taskId,"rework_required"),session.stageBCompletion?.delete(taskId),updateTaskWorkflowCache(session,taskId,getTaskWorkflowSnapshot2(rejected))}catch(err){warn(`[delegation-gate] Stage B rejection could not be persisted for ${taskId}: ${err instanceof Error?err.message:String(err)}`)}continue}try{let turbo=hasActiveTurboMode(input.sessionID),{recordGateEvidence:recordGateEvidence2}=await Promise.resolve().then(() => (init_gate_evidence(),exports_gate_evidence));await recordGateEvidence2(directory,taskId,targetAgent,input.sessionID,turbo,{expectedGeneration:launchGeneration,transitionId:`gate:${input.callID}:${taskId}`})}catch(err){warn(`[delegation-gate] Stage B settlement rejected for ${taskId}: ${err instanceof Error?err.message:String(err)}`);continue}recordStageBCompletion(session,taskId,targetAgent);let taskEvidence=await readTaskEvidence2(directory,taskId),reviewerCompletesStageB=targetAgent==="reviewer"&&taskEvidence?.test_engineer_exempt===!0;if(hasBothStageBCompletions(session,taskId)||reviewerCompletesStageB)try{if(eligibleState==="pre_check_passed")advanceTaskState(session,taskId,"reviewer_run",{telemetrySessionId:input.sessionID});advanceTaskState(session,taskId,"tests_run",{telemetrySessionId:input.sessionID})}catch(err){warn(`[delegation-gate] toolAfter stage-b-parallel: could not advance ${taskId} (${eligibleState}) → tests_run: ${err instanceof Error?err.message:String(err)}`)}else try{if(targetAgent==="reviewer"&&eligibleState==="pre_check_passed")advanceTaskState(session,taskId,"reviewer_run",{telemetrySessionId:input.sessionID});else if(targetAgent==="test_engineer"&&eligibleState==="reviewer_run")advanceTaskState(session,taskId,"tests_run",{telemetrySessionId:input.sessionID})}catch(err){warn(`[delegation-gate] toolAfter stage-b-parallel intermediate: could not advance ${taskId} (${eligibleState}) after ${targetAgent}: ${err instanceof Error?err.message:String(err)}`)}}}while(!1)}}}if(typeof subagentType==="string"){let coderSettleTaskId=null;try{let mergedArgs={...storedArgs??{},...directArgs},evidenceTaskId=await resolveEvidenceTaskId(mergedArgs,session,directory);if(!evidenceTaskId&&stripKnownSwarmPrefix(subagentType)==="coder"){let begun=begunCoderSettlementsByCallID.get(input.callID);if(begun?.taskId)evidenceTaskId=begun.taskId}if(coderSettleTaskId=evidenceTaskId,evidenceTaskId){let turbo=hasActiveTurboMode(input.sessionID),gateAgents=["reviewer","test_engineer","docs","designer","critic","critic_sounding_board","explorer","sme"],targetAgentForEvidence=stripKnownSwarmPrefix(subagentType);if(gateAgents.includes(targetAgentForEvidence))if(targetAgentForEvidence==="reviewer"||targetAgentForEvidence==="test_engineer");else{if(!(!isTerminalFailure&&(targetAgentForEvidence!=="critic"&&targetAgentForEvidence!=="critic_sounding_board"||extractPlanCriticVerdict(_output)==="APPROVED")))throw Error(`TASK_GATE_NOT_SATISFIED: ${targetAgentForEvidence} did not return a trusted positive verdict`);let{recordGateEvidence:recordGateEvidence2}=await Promise.resolve().then(() => (init_gate_evidence(),exports_gate_evidence)),gateLaunchGeneration=stageBDispatchGenerationsByCallID.get(input.callID)?.get(evidenceTaskId);if(TASK_GATE_AGENTS.has(targetAgentForEvidence)&&gateLaunchGeneration===void 0)throw Error(`TASK_WORKFLOW_GENERATION_REQUIRED: no launch binding for ${targetAgentForEvidence} task ${evidenceTaskId}`);await recordGateEvidence2(directory,evidenceTaskId,targetAgentForEvidence,input.sessionID,turbo,{expectedGeneration:gateLaunchGeneration,transitionId:`gate:${input.callID}:${evidenceTaskId}`})}else{let{getTaskWorkflowSnapshot:getTaskWorkflowSnapshot2,recordAgentDispatch:recordAgentDispatch2}=await Promise.resolve().then(() => (init_gate_evidence(),exports_gate_evidence)),taskChangeContext=targetAgentForEvidence==="coder"?coderTaskChangeContextByCallID.get(input.callID):void 0,rawObservedFiles=taskChangeContext?coderObservedFilesByCallID.get(input.callID)??changedFilesSinceSnapshot(taskChangeContext.baseline.directory,taskChangeContext.baseline):null;if(targetAgentForEvidence==="coder"&&!Array.isArray(rawObservedFiles))throw Error(`CODER_SETTLEMENT_ATTRIBUTION_UNCERTAIN: shared-root task ${evidenceTaskId} changed files could not be proven from its clean launch baseline`);let observedFiles=taskChangeContext?.declaredFiles&&Array.isArray(rawObservedFiles)?rawObservedFiles.filter((filePath)=>isPathWithinDeclaredScope(filePath,taskChangeContext.declaredFiles,taskChangeContext.baseline.directory)):[],context={testEngineerExempt:targetAgentForEvidence==="coder"&&isMarkdownOnlyTaskChange(taskChangeContext?.declaredFiles,observedFiles)};if(targetAgentForEvidence==="coder"){let accepted=(!standardDispatch||!isTerminalFailure)&&standardWorktreeSettled&&Array.isArray(observedFiles)&&observedFiles.length>0,updated;if(standardDispatch&&!isStandardWorktreeFailure){if(!coderSettlementCommitted||!coderSettlementEvidence)throw Error(`CODER_SETTLEMENT_NOT_COMMITTED: isolated merge for ${evidenceTaskId} did not durably publish accepted-mutation evidence`);updated=coderSettlementEvidence}else updated=(await settleCoderDispatch({directory,taskId:evidenceTaskId,transitionId:`coder:${input.callID}`,accepted,testEngineerExempt:context.testEngineerExempt===!0,settlementFailed:!standardDispatch&&isTerminalFailure})).evidence,coderSettlementCommitted=!0;if(accepted){let workflow=getTaskWorkflowSnapshot2(updated);session.taskWorkflowStates.set(evidenceTaskId,workflow.state),session.stageBCompletion?.delete(evidenceTaskId),session.taskCouncilApproved?.delete(evidenceTaskId),session.taskCouncilWorkflowGeneration?.delete(evidenceTaskId),updateTaskWorkflowCache(session,evidenceTaskId,workflow)}}else await recordAgentDispatch2(directory,evidenceTaskId,targetAgentForEvidence,turbo,context)}}}catch(err){let normalizedAgent=stripKnownSwarmPrefix(subagentType);if(warn(`[delegation-gate] evidence recording failed: ${err instanceof Error?err.message:String(err)}`),normalizedAgent==="coder"){let terminalAbort=!1;if(coderSettleTaskId&&!coderSettlementCommitted){releaseCoderDispatchOwnership(directory,coderSettleTaskId,`coder:${input.callID}`);try{let abortOutcome=await abortCoderSettlementIfDoomed({directory,taskId:coderSettleTaskId,transitionId:`coder:${input.callID}`});terminalAbort=abortOutcome==="aborted"||abortOutcome==="already-aborted"}catch(abortErr){warn(`[delegation-gate] doomed settlement abort failed for ${coderSettleTaskId}: ${abortErr instanceof Error?abortErr.message:String(abortErr)}`)}if(terminalAbort)clearCoderTaskChangeContext(input.callID)}if(terminalAbort)pushAdvisory(session,`CODER_SETTLEMENT_ABORTED: task ${coderSettleTaskId} dispatch ${input.callID} was settled as ABORTED — its launch baseline was dirty or had no git history, so the coder's changes cannot be attributed. Reconcile the workspace (commit, stash, or discard the coder's output), then repair the task with update_task_status and re-dispatch from a clean tree.`);else pushAdvisory(session,`CODER_SETTLEMENT_DURABILITY_FAILURE: task output remains fenced until accepted-mutation evidence for call ${input.callID} is recovered.`);throw err}}finally{if(stripKnownSwarmPrefix(subagentType)==="coder"){if(coderSettlementCommitted)clearCoderTaskChangeContext(input.callID),clearPublishedScopeBindings(input.callID);if(begunCoderSettlementsByCallID.delete(input.callID),!coderSettlementCommitted)stageBDispatchGenerationsByCallID.delete(input.callID),gateDispatchPrimaryTaskByCallID.delete(input.callID),deleteStoredInputArgs(input.callID)}}}if(storedArgs!==void 0)deleteStoredInputArgs(input.callID);if(!subagentType||!hasReviewer||councilActive){let delegationChain=swarmState.delegationChains.get(input.sessionID);if(delegationChain&&delegationChain.length>0){let lastCoderIndex=-1;for(let i=delegationChain.length-1;i>=0;i--)if(stripKnownSwarmPrefix(delegationChain[i].to).includes("coder")){lastCoderIndex=i;break}let searchStart=lastCoderIndex===-1?0:lastCoderIndex,afterCoder=delegationChain.slice(searchStart);for(let delegation of afterCoder){let target=stripKnownSwarmPrefix(delegation.to);if(target==="reviewer")hasReviewer=!0;if(target==="test_engineer")hasTestEngineer=!0}if(lastCoderIndex!==-1&&hasReviewer&&hasTestEngineer)session.qaSkipCount=0,session.qaSkipTaskIds=[]}}if(stageBDispatchGenerationsByCallID.delete(input.callID),gateDispatchPrimaryTaskByCallID.delete(input.callID),stageBDispatchContextByCallID.delete(input.callID),session.taskWorkflowStates){for(let[,state]of session.taskWorkflowStates)if(state==="tests_run"){let taskAwaiting=await findTaskAwaitingCompletion(directory);if(taskAwaiting&&!session.completionGateWarnedForTask.has(taskAwaiting))pushAdvisory(session,completionGateViolationMessage(taskAwaiting)),session.completionGateWarnedForTask.add(taskAwaiting);break}}if(standardWorktreeSettled&&coderSettlementCommitted){if(foregroundCoderTaskId)await completeCoderSettlementCleanup(directory,foregroundCoderTaskId,`coder:${input.callID}`)}}finally{if(foregroundCoderTaskId)releaseCoderDispatchOwnership(directory,foregroundCoderTaskId,`coder:${input.callID}`)}}},taskMetadata,sessionEnded,backgroundCompletionClaimed,abortDeniedSettlementForCall:async(callID)=>{let begun=begunCoderSettlementsByCallID.get(callID);if(!begun?.taskId)return;try{await abortCoderSettlement({directory,taskId:begun.taskId,transitionId:begun.transitionId,reason:"dispatch denied by a fail-closed gate after settlement began"})}catch(error49){criticalWarn(`[delegation-gate] denied-dispatch settlement rollback failed for call ${callID} (task ${begun.taskId}): ${error49 instanceof Error?error49.message:String(error49)}`)}finally{releaseCoderDispatchOwnership(directory,begun.taskId,begun.transitionId),begunCoderSettlementsByCallID.delete(callID),clearCoderTaskChangeContext(callID),clearPublishedScopeBindings(callID),stageBDispatchGenerationsByCallID.delete(callID),gateDispatchPrimaryTaskByCallID.delete(callID),deleteStoredInputArgs(callID)}}}}var EvidenceTaskIdPlanSchema,BoundedPendingScopeMap,pendingCoderScopeByTaskId,SWARM_BACKGROUND_TASK_BLOCKED_MESSAGE="SWARM_BACKGROUND_TASK_BLOCKED: OpenCode background subagents (Task with background=true, requires OPENCODE_EXPERIMENTAL_BACKGROUND_SUBAGENTS=true or OPENCODE_EXPERIMENTAL=true) remain experimental upstream and are disabled by default in swarm. Omit `background` (or set background=false), or explicitly enable hooks.background_subagents only after reviewing the background-subagent recovery and readiness guidance.",COVERAGE_DIAG_SNIPPET_CAP=80,COVERAGE_DIAG_MAX_SCAN=400,COVERAGE_DIAG_MIN_PREFIX=10,ACCEPTANCE_EXPECTED_BODY_CAP=2000,ACCEPTANCE_ARGS_FIELDS,PLAN_CRITIC_TASK_SIGNALS,ACTIVE_PARALLEL_TASK_STATES,COMPLETION_RECOVERY_TOOLS,TASK_GATE_AGENTS,recordPendingDelegationForBackground=async(...args2)=>(await Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations))).recordPendingDelegationDetailed(...args2),writeDelegationFallbackForBackground=async(...args2)=>(await Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations))).writeDelegationFallback(...args2),reserveBackgroundCoderSlotForDispatch=async(...args2)=>(await Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations))).reserveBackgroundCoderSlot(...args2),bindBackgroundCoderReservationForDispatch=async(...args2)=>(await Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations))).bindBackgroundCoderReservation(...args2),releaseBackgroundCoderReservationForDispatch=async(...args2)=>(await Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations))).releaseBackgroundCoderReservation(...args2),maintainBackgroundDelegationsForDispatch=async(...args2)=>(await Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations))).maintainBackgroundDelegations(...args2),_internals65;var init_delegation_gate=__esm(()=>{init_zod();init_workspace_snapshot();init_agent_names();init_constants();init_schema();init_qa_gate_profile();init_policy();init_gate_evidence_classification();init_file_locks();init_review_router();init_ledger();init_manager();init_parallel_verdict();init_utils3();init_prm();init_path_identity();init_scope_binding();init_scope_persistence();init_scope_resolution_diagnostic();init_state2();init_telemetry();init_logger();init_task_id();init_coder_settlement();init_task_repair();init_task_terminal();init_worktree_isolation();init_pr_workflow_gate();init_worktree_isolation();init_worktree_merge_status();init_guardrails2();init_normalize_tool_name();init_utils2();EvidenceTaskIdPlanSchema=exports_external.object({phases:exports_external.array(exports_external.object({tasks:exports_external.array(exports_external.object({id:exports_external.string(),status:exports_external.string().optional()}).passthrough()).optional()}).passthrough()).optional()}).passthrough();BoundedPendingScopeMap=class BoundedPendingScopeMap extends Map{expiresAtByKey=new Map;sweepExpired(now=Date.now()){for(let[key,expiresAt]of this.expiresAtByKey)if(expiresAt<=now)this.delete(key)}set(key,value){this.sweepExpired(),this.delete(key),super.set(key,value),this.expiresAtByKey.set(key,Date.now()+300000);while(this.size>MAX_PENDING_SCOPE_BINDINGS){let oldest=this.keys().next().value;if(!oldest)break;this.delete(oldest)}return this}get(key){return this.sweepExpired(),super.get(key)}has(key){return this.sweepExpired(),super.has(key)}delete(key){return this.expiresAtByKey.delete(key),super.delete(key)}clear(){this.expiresAtByKey.clear(),super.clear()}};pendingCoderScopeByTaskId=new BoundedPendingScopeMap;ACCEPTANCE_ARGS_FIELDS=["prompt","description","task","input","message"];PLAN_CRITIC_TASK_SIGNALS=["critic-gate","plan critic","review plan","review the plan","plan.md","approve the plan","plan approval","pre-implementation review","evaluate this plan","evaluate the plan","assess this plan","assess the plan","plan soundness","before implementation","review the plan below"];ACTIVE_PARALLEL_TASK_STATES=new Set(["coder_delegated","pre_check_passed","reviewer_run","tests_run"]);COMPLETION_RECOVERY_TOOLS=new Set(["get_approved_plan","get_qa_gate_profile","check_gate_status"]),TASK_GATE_AGENTS=new Set(["reviewer","test_engineer","docs","designer","critic","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","explorer","sme"]);_internals65={resolveEvidenceTaskId,resolveDelegatedPlanTaskId,describeCoderScopeFailure,parsePerTaskVerdicts,buildParallelExecutionGuidance,extractTaskFileDirectives,loadPlanJsonOnly,recordPendingDelegationForBackground,writeDelegationFallbackForBackground,reserveBackgroundCoderSlotForDispatch,bindBackgroundCoderReservationForDispatch,releaseBackgroundCoderReservationForDispatch,maintainBackgroundDelegationsForDispatch,resetStandardWorktreeIsolationState,PLAN_CRITIC_TASK_SIGNALS,extractPlanCriticVerdict,forceRecordPlanCriticApproval,get provisionWorktree(){return _internals55.provisionWorktree},set provisionWorktree(v){_internals55.provisionWorktree=v},get removeWorktree(){return _internals55.removeWorktree},set removeWorktree(v){_internals55.removeWorktree=v},get attemptMergeBackFromDirty(){return _internals55.attemptMergeBackFromDirty},set attemptMergeBackFromDirty(v){_internals55.attemptMergeBackFromDirty=v},get postMergeCleanup(){return _internals55.postMergeCleanup},set postMergeCleanup(v){_internals55.postMergeCleanup=v},get preserveBackgroundWorktreeOwnershipForCallId(){return _internals55.preserveBackgroundWorktreeOwnershipForCallId},set preserveBackgroundWorktreeOwnershipForCallId(v){_internals55.preserveBackgroundWorktreeOwnershipForCallId=v}}});function positiveIntegerOrDefault(value,fallback){return Number.isInteger(value)&&Number(value)>0?Number(value):fallback}function rememberSession(sessionID,state){if(realtimeLearningNudgeBySession.has(sessionID))realtimeLearningNudgeBySession.delete(sessionID);realtimeLearningNudgeBySession.set(sessionID,state);while(realtimeLearningNudgeBySession.size>500){let oldestSessionID=realtimeLearningNudgeBySession.keys().next().value;if(oldestSessionID===void 0)break;realtimeLearningNudgeBySession.delete(oldestSessionID)}}function recordRealtimeLearningToolCall(sessionID){let prior=realtimeLearningNudgeBySession.get(sessionID),nextState={observedToolCallCount:(prior?.observedToolCallCount??0)+1,lastNudgedAtToolCallCount:prior?.lastNudgedAtToolCallCount??0};return rememberSession(sessionID,nextState),nextState.observedToolCallCount}function getRealtimeLearningToolCallCount(sessionID){if(!sessionID)return 0;return realtimeLearningNudgeBySession.get(sessionID)?.observedToolCallCount??0}function shouldInjectRealtimeLearningNudge(args2){if(!args2.sessionID)return!1;if(args2.config?.enabled===!1)return!1;if(args2.realtimeAdmission?.enabled===!0&&args2.realtimeAdmission?.supersede_nudge!==!1)return!1;let state=realtimeLearningNudgeBySession.get(args2.sessionID),toolCallCount=state?.observedToolCallCount??0,firstAfterToolCalls=positiveIntegerOrDefault(args2.config?.first_after_tool_calls,10),repeatAfterToolCalls=positiveIntegerOrDefault(args2.config?.repeat_after_tool_calls,25);if(toolCallCount<firstAfterToolCalls)return!1;if(!state||state.lastNudgedAtToolCallCount===0)return!0;return toolCallCount-state.lastNudgedAtToolCallCount>=repeatAfterToolCalls}function recordRealtimeLearningNudge(sessionID){let prior=realtimeLearningNudgeBySession.get(sessionID);if(!prior)return;rememberSession(sessionID,{...prior,lastNudgedAtToolCallCount:prior.observedToolCallCount})}function resetRealtimeLearningNudgeState(){realtimeLearningNudgeBySession.clear()}function clearRealtimeLearningNudgeSession(sessionID){realtimeLearningNudgeBySession.delete(sessionID)}function buildRealtimeLearningNudge(args2){return["[SWARM LEARNING NUDGE]",`Session has ${args2.toolCallCount} tool calls in phase ${args2.currentPhase}. Before continuing, decide whether the current work revealed a durable procedural lesson.`,"- If yes, call knowledge_add now with actionable when/then/scope fields so later turns can retrieve it.","- If the signal needs review across evidence, repeated outcomes, or generated-skill health, let the curator phase/postmortem path handle it; curator can emit knowledge_application_findings and skill_candidates without activating skills.","- Prefer reinforcing existing knowledge over noisy one-offs. Do not save transient setup failures, stale negative tool claims, or repo-specific accidents without a reusable trigger.","- If repeated KNOWLEDGE_IGNORED/VIOLATED outcomes or stale generated skills are accumulating, use skill_improve only when enabled/approved; generated skills stay proposal/draft gated and must not auto-activate.","- If there is nothing durable, continue without adding knowledge."].join(`
875
875
  `)}var REALTIME_LEARNING_NUDGE_ID_PREFIX="realtime-learning-nudge",realtimeLearningNudgeBySession;var init_realtime_learning_nudge=__esm(()=>{realtimeLearningNudgeBySession=new Map});function evictOldestStepSessionIfNeeded(sessionId){if(sessionStepCounters.has(sessionId))return;while(sessionStepCounters.size>=500){let oldestSessionId=sessionStepCounters.keys().next().value;if(oldestSessionId===void 0)break;sessionStepCounters.delete(oldestSessionId)}}function nextTrajectoryStep(sessionId){evictOldestStepSessionIfNeeded(sessionId);let step=(sessionStepCounters.get(sessionId)??0)+1;return sessionStepCounters.set(sessionId,step),step}function clearTrajectoryStepCounters(sessionId){if(sessionId!==void 0)sessionStepCounters.delete(sessionId);else sessionStepCounters.clear()}var sessionStepCounters;var init_trajectory_step_state=__esm(()=>{sessionStepCounters=new Map});function normalizeText2(value){return value?.trim()??""}function entryKey(scope){return[normalizeText2(scope.sessionID),normalizeText2(scope.invocationID),normalizeText2(scope.swarmID),normalizeText2(scope.role)].join("␟")}function parseModelString(model){let value=model.trim();if(!value)return;let separator=value.indexOf("/");if(separator<=0||separator===value.length-1)return;return{providerID:value.slice(0,separator),modelID:value.slice(separator+1)}}function pruneScopedModelOverrides(now){for(let[key,entry]of scopedModelOverrides)if(now-entry.updatedAt>1800000)scopedModelOverrides.delete(key);while(scopedModelOverrides.size>256){let first=scopedModelOverrides.keys().next().value;if(!first)break;scopedModelOverrides.delete(first)}}function selectionFromEntry(entry,chain){if(entry.fallbackIndex>=chain.totalModels)return{generation:entry.generation,fallbackIndex:entry.fallbackIndex,exhausted:!0,totalModels:chain.totalModels};if(entry.fallbackIndex===0)return{generation:entry.generation,fallbackIndex:0,modelString:chain.primary?.modelString,model:chain.primary?.override,exhausted:!1,totalModels:chain.totalModels};let fallback=chain.fallbacks[entry.fallbackIndex-1];return{generation:entry.generation,fallbackIndex:entry.fallbackIndex,modelString:fallback?.modelString,model:fallback?.override,exhausted:!1,totalModels:chain.totalModels}}function normalizeModelChain(primaryModel,fallbackModels){let seen=new Set,normalizedFallbacks=[],normalizedPrimary,primaryText=normalizeText2(primaryModel);if(primaryText){let parsed=parseModelString(primaryText);if(parsed)normalizedPrimary={modelString:primaryText,override:parsed},seen.add(primaryText)}for(let candidate of fallbackModels){let text=normalizeText2(candidate??void 0);if(!text||seen.has(text))continue;let parsed=parseModelString(text);if(!parsed)continue;seen.add(text),normalizedFallbacks.push({modelString:text,override:parsed})}return Object.freeze({primary:normalizedPrimary,fallbacks:Object.freeze(normalizedFallbacks),signature:[primaryText,...normalizedFallbacks.map((entry)=>entry.modelString)].join("␞"),totalModels:1+normalizedFallbacks.length})}function resolveScopedModelSelection(scope,chain,now=Date.now()){pruneScopedModelOverrides(now);let key=entryKey(scope),current=scopedModelOverrides.get(key);if(!current||current.signature!==chain.signature){let next={key,updatedAt:now,generation:(current?.generation??0)+1,fallbackIndex:0,signature:chain.signature};return scopedModelOverrides.delete(key),scopedModelOverrides.set(key,next),selectionFromEntry(next,chain)}return current.updatedAt=now,scopedModelOverrides.delete(key),scopedModelOverrides.set(key,current),selectionFromEntry(current,chain)}function advanceScopedModelSelection(scope,chain,expectedGeneration,now=Date.now()){let key=entryKey(scope),current=scopedModelOverrides.get(key);if(!current||current.signature!==chain.signature)return{accepted:!1,selection:resolveScopedModelSelection(scope,chain,now)};if(current.generation!==expectedGeneration)return current.updatedAt=now,{accepted:!1,selection:selectionFromEntry(current,chain)};return current.updatedAt=now,current.fallbackIndex=Math.min(current.fallbackIndex+1,chain.totalModels),scopedModelOverrides.delete(key),scopedModelOverrides.set(key,current),{accepted:!0,selection:selectionFromEntry(current,chain)}}function resetScopedModelSelection(scope,expectedGeneration){let key=entryKey(scope),current=scopedModelOverrides.get(key);if(!current)return!1;if(expectedGeneration!==void 0&&current.generation!==expectedGeneration)return!1;return scopedModelOverrides.delete(key)}function clearScopedModelSelectionsForSession(sessionID){let normalizedSessionID=normalizeText2(sessionID);for(let[key,entry]of scopedModelOverrides)if(key.startsWith(`${normalizedSessionID}␟`))scopedModelOverrides.delete(entry.key)}function getScopedModelSelectionSnapshot(){return[...scopedModelOverrides.values()].map((entry)=>{let[sessionID,invocationID,swarmID,role]=entry.key.split("␟");return{key:{sessionID,invocationID,swarmID:swarmID||void 0,role},generation:entry.generation,fallbackIndex:entry.fallbackIndex,updatedAt:entry.updatedAt}})}function resetScopedModelSelectionStateForTests(){scopedModelOverrides.clear()}var scopedModelOverrides;var init_model_override_state=__esm(()=>{scopedModelOverrides=new Map});function normalizeText3(value){return value?.trim()??""}function parentCallKey(parentSessionID,callID){return`${normalizeText3(parentSessionID)}␟${normalizeText3(callID)}`}function normalizeRoute(input,now){return{parentSessionID:normalizeText3(input.parentSessionID),invocationID:normalizeText3(input.invocationID),callID:normalizeText3(input.callID),role:normalizeText3(input.role),actionDigest:normalizeText3(input.actionDigest),swarmID:normalizeText3(input.swarmID)||void 0,updatedAt:now}}function routeScope(route){return{sessionID:route.parentSessionID,invocationID:route.invocationID,swarmID:route.swarmID,role:route.role}}function upsertRoute(route){let key=parentCallKey(route.parentSessionID,route.callID),prior=routesByParentCall.get(key);if(prior?.childSessionID)routeKeyByChildSession.delete(prior.childSessionID);if(routesByParentCall.delete(key),routesByParentCall.set(key,route),route.childSessionID)routeKeyByChildSession.set(route.childSessionID,key)}function pruneRoutes(now){for(let[key,route]of routesByParentCall)if(now-route.updatedAt>PENDING_TASK_MODEL_ROUTE_TTL_MS){if(routesByParentCall.delete(key),route.childSessionID)routeKeyByChildSession.delete(route.childSessionID)}while(routesByParentCall.size>MAX_PENDING_TASK_MODEL_ROUTES){let oldestKey=routesByParentCall.keys().next().value;if(typeof oldestKey!=="string")break;let route=routesByParentCall.get(oldestKey);if(routesByParentCall.delete(oldestKey),route?.childSessionID)routeKeyByChildSession.delete(route.childSessionID)}}function matchingRouteForParent(parentSessionID,role,actionDigest){let match,normalizedParent=normalizeText3(parentSessionID),normalizedRole=normalizeText3(role),normalizedDigest=normalizeText3(actionDigest);for(let route of routesByParentCall.values()){if(route.parentSessionID!==normalizedParent||route.role!==normalizedRole)continue;if(normalizedDigest&&route.actionDigest!==normalizedDigest)continue;if(match)return"ambiguous";match=route}return match}function touchRoute(route,now){route.updatedAt=now,upsertRoute(route)}function registerPendingTaskModelRoute(input,now=Date.now()){pruneRoutes(now);let route=normalizeRoute(input,now);return upsertRoute(route),{...route}}function bindPendingTaskModelRouteChild(input,now=Date.now()){pruneRoutes(now);let key=parentCallKey(input.parentSessionID,input.callID),route=routesByParentCall.get(key);if(!route)return;if(route.childSessionID)routeKeyByChildSession.delete(route.childSessionID);return route.childSessionID=normalizeText3(input.childSessionID),touchRoute(route,now),{...route}}function advancePendingTaskModelRoute(input){let now=input.now??Date.now();pruneRoutes(now);let routeKey=routeKeyByChildSession.get(normalizeText3(input.childSessionID));if(!routeKey)return;let route=routesByParentCall.get(routeKey);if(!route||route.role!==normalizeText3(input.role)||route.actionDigest!==normalizeText3(input.actionDigest))return;let chain=normalizeModelChain(input.primaryModel,input.fallbackModels??[]),selection=resolveScopedModelSelection(routeScope(route),chain,now),advanced=advanceScopedModelSelection(routeScope(route),chain,input.expectedGeneration??selection.generation,now);return touchRoute(route,now),{accepted:advanced.accepted,exhausted:advanced.selection.exhausted,fallbackIndex:advanced.selection.fallbackIndex,generation:advanced.selection.generation,scope:routeScope(route),route:{...route}}}async function resolveTaskChatModelOverride(input){let now=input.now??Date.now();pruneRoutes(now);let normalizedChild=normalizeText3(input.childSessionID),normalizedRole=normalizeText3(input.role),route,boundKey=routeKeyByChildSession.get(normalizedChild);if(boundKey)route=routesByParentCall.get(boundKey);let resolvedParentSessionID;if(!route&&input.lookupParentSessionID){if(resolvedParentSessionID=normalizeText3(await input.lookupParentSessionID(normalizedChild)),resolvedParentSessionID){let match=matchingRouteForParent(resolvedParentSessionID,normalizedRole,input.actionDigest);if(match==="ambiguous")return{status:"ambiguous"};route=match}}if(!route)return{status:"missing"};if(route.role!==normalizedRole||input.actionDigest&&route.actionDigest!==normalizeText3(input.actionDigest))return{status:"mismatch",route:{...route}};if(resolvedParentSessionID&&route.parentSessionID!==resolvedParentSessionID)return{status:"mismatch",route:{...route}};let chain=normalizeModelChain(input.primaryModel,input.fallbackModels??[]),selection=resolveScopedModelSelection(routeScope(route),chain,now);if(touchRoute(route,now),selection.exhausted)return{status:"exhausted",fallbackIndex:selection.fallbackIndex,generation:selection.generation,scope:routeScope(route),route:{...route}};if(selection.fallbackIndex===0||!selection.model)return{status:"primary",fallbackIndex:selection.fallbackIndex,generation:selection.generation,scope:routeScope(route),route:{...route}};return{status:"override",model:selection.model,modelString:selection.modelString,fallbackIndex:selection.fallbackIndex,generation:selection.generation,scope:routeScope(route),route:{...route}}}function clearPendingTaskModelRoutesForSession(sessionID){let normalizedSessionID=normalizeText3(sessionID);for(let[key,route]of routesByParentCall)if(route.parentSessionID===normalizedSessionID||route.childSessionID===normalizedSessionID){if(routesByParentCall.delete(key),route.childSessionID)routeKeyByChildSession.delete(route.childSessionID)}clearScopedModelSelectionsForSession(normalizedSessionID)}function getPendingTaskModelRouteSnapshot(){return[...routesByParentCall.values()].map((route)=>({...route}))}function getTaskModelRoutingStateSnapshot(){return{routes:getPendingTaskModelRouteSnapshot(),scopedSelections:getScopedModelSelectionSnapshot()}}function clearAllTaskModelRoutingState(){routesByParentCall.clear(),routeKeyByChildSession.clear(),resetScopedModelSelectionStateForTests()}var MAX_PENDING_TASK_MODEL_ROUTES=256,PENDING_TASK_MODEL_ROUTE_TTL_MS=1800000,routesByParentCall,routeKeyByChildSession;var init_task_model_routing=__esm(()=>{init_model_override_state();routesByParentCall=new Map,routeKeyByChildSession=new Map});import{existsSync as existsSync38,mkdirSync as mkdirSync25,readFileSync as readFileSync27,writeFileSync as writeFileSync17}from"node:fs";import*as path82 from"node:path";function recordSessionStart(directory,startMs){try{let swarmDir=path82.join(directory,".swarm"),sessionDir=path82.join(swarmDir,"session"),filePath=path82.join(sessionDir,SESSION_START_FILE),line=JSON.stringify({startMs,ts:Date.now()});mkdirSync25(sessionDir,{recursive:!0}),writeFileSync17(filePath,`${line}
876
876
  `,{flag:"a"})}catch{}}function readEarliestSessionStart(directory){try{let filePath=path82.join(directory,".swarm","session",SESSION_START_FILE);if(!existsSync38(filePath))return null;let lines=readFileSync27(filePath,"utf-8").split(`
877
877
  `),validStartMs=[];for(let line of lines){if(!line.trim())continue;try{let parsed=JSON.parse(line);if(typeof parsed.startMs==="number"&&Number.isFinite(parsed.startMs))validStartMs.push(parsed.startMs)}catch{}}if(validStartMs.length===0)return null;return new Date(Math.min(...validStartMs)).toISOString()}catch{return null}}var SESSION_START_FILE="session-start.jsonl";var init_session_start_store=()=>{};import{execFile as execFile2}from"node:child_process";function markSuggested(sessionId){if(_suggestedSessions.has(sessionId))return;if(_suggestedSessions.size>=MAX_SUGGESTED_SESSIONS){let oldest=_suggestedSessions.values().next().value;if(oldest!==void 0)_suggestedSessions.delete(oldest)}_suggestedSessions.add(sessionId)}async function countWorktrees(directory){let gitExecutable;try{gitExecutable=await resolveGitExecutableAsync()}catch{return 0}return new Promise((resolve43)=>{try{let child=execFile2(gitExecutable,["-C",directory,"worktree","list","--porcelain"],{timeout:GIT_TIMEOUT_MS3,windowsHide:!0,encoding:"utf-8"},(err,stdout)=>{if(err||typeof stdout!=="string"){resolve43(0);return}let count=0;for(let line of stdout.split(`
@@ -3253,7 +3253,7 @@ Actionability (direct text only; required unless knowledge.promotion_require_act
3253
3253
  `)}var ALL_GATE_NAMES;var init_qa_gates=__esm(()=>{init_qa_gate_profile();init_manager();init_utils3();init_state2();ALL_GATE_NAMES=["reviewer","test_engineer","council_mode","sme_enabled","critic_pre_plan","hallucination_guard","sast_enabled","mutation_test","phase_council","drift_check","final_council"]});import{appendFile as appendFile21,mkdir as mkdir44,readdir as readdir14}from"node:fs/promises";import{dirname as dirname83}from"node:path";async function appendStageARepairEvent(directory,payload){let line=`${JSON.stringify({type:"stage_a_repair",timestamp:new Date().toISOString(),...payload})}
3254
3254
  `;try{let eventsPath=validateSwarmPath(directory,"events.jsonl");await mkdir44(dirname83(eventsPath),{recursive:!0}),await appendFile21(eventsPath,line,"utf-8")}catch(error93){let code=error93.code;if(code&&RETRYABLE_EVENT_CODES.has(code))try{let eventsPath=validateSwarmPath(directory,"events.jsonl");await appendFile21(eventsPath,line,"utf-8");return}catch(retryError){criticalWarn(`[stage-a-repair] audit event write failed after retry: ${retryError instanceof Error?retryError.message:String(retryError)}`);return}criticalWarn(`[stage-a-repair] audit event write failed: ${error93 instanceof Error?error93.message:String(error93)}`)}}async function hasGreenPostSettlementPreCheck(directory,settledAfterMs){let sawSecretscanGreen=!1,sawSastGreen=!1;for(let evidenceType of["secretscan","sast_scan"]){let result;try{result=await loadEvidence(directory,evidenceType,{migrate:!1})}catch{continue}if(result.status!=="found")continue;let entryTypeTag=evidenceType==="sast_scan"?"sast":evidenceType,typed=result.bundle.entries.filter((entry)=>entry.type===entryTypeTag);if(typed.length===0)continue;let last=typed[typed.length-1],ts=Date.parse(String(last.timestamp??""));if(settledAfterMs!==null&&Number.isFinite(ts)&&ts<settledAfterMs)return{green:!1,reason:"pre_check_failed_or_stale"};if(evidenceType==="secretscan"){if((last.verdict==="pass"||last.verdict==="approved"||last.verdict==="info")&&isSecretscanEvidence(last)&&(last.incomplete_files??0)===0&&(last.files_scanned??0)>0&&(last.findings_count??0)===0){sawSecretscanGreen=!0;continue}}else if(last.verdict==="pass"||last.verdict==="approved"||last.verdict==="info"){sawSastGreen=!0;continue}if(last.verdict==="fail"||last.verdict==="rejected")return{green:!1,reason:"pre_check_failed_or_stale"}}if(!sawSecretscanGreen||!sawSastGreen)return{green:!1,reason:"no_pre_check_bundles"};return{green:!0}}async function repairWedgedStageA(directory,options){let requested=options?.taskIds,entries;try{let evidenceDir=validateSwarmPath(directory,"evidence");entries=await readdir14(evidenceDir)}catch{return{results:[],truncated:!1}}let candidates=entries.filter((entry)=>entry.endsWith(".json")&&isStrictTaskId(entry.slice(0,-5))),selected=requested?.length?candidates.filter((entry)=>requested.includes(entry.slice(0,-5))):candidates,truncated=!requested?.length&&candidates.length>MAX_STAGE_A_REPAIR_SCAN,results=[];for(let entry of selected.sort().slice(0,MAX_STAGE_A_REPAIR_SCAN)){let taskId=entry.slice(0,-5);try{let evidence2=await readTaskEvidence(directory,taskId),workflow=getTaskWorkflowSnapshot(evidence2);if(workflow.state!=="coder_delegated"){results.push({taskId,outcome:"skipped_not_wedged",state:workflow.state});continue}if(evidence2?.gates?.pre_check){results.push({taskId,outcome:"skipped_not_wedged",state:workflow.state});continue}let settledAfterMs=null;try{let{states}=await listCoderSettlementWalStates(directory);for(let state of states){if(state.taskId!==taskId)continue;if(state.state!=="COMMITTED")continue;if(state.recordedAt===void 0)continue;let parsed=Date.parse(state.recordedAt);if(!Number.isFinite(parsed))continue;settledAfterMs=settledAfterMs===null?parsed:Math.max(settledAfterMs,parsed)}}catch{}if(settledAfterMs===null){let fallbackTs=Date.parse(workflow.updatedAt);if(Number.isFinite(fallbackTs))settledAfterMs=fallbackTs}let greenness=await hasGreenPostSettlementPreCheck(directory,settledAfterMs);if(!greenness.green){results.push({taskId,outcome:"skipped_not_green",reason:greenness.reason});continue}let transitionId=`stage-a-repair:${taskId}:${workflow.generation}`;await transitionTaskWorkflowEvidence(directory,taskId,{type:"stage_a_passed",expectedGeneration:workflow.generation,transitionId}),await appendStageARepairEvent(directory,{action:"repaired",taskId,transitionId,generation:workflow.generation}),results.push({taskId,outcome:"repaired",generation:workflow.generation,transitionId})}catch(error93){let message=error93 instanceof Error?error93.message:String(error93);await appendStageARepairEvent(directory,{action:"repair-failed",taskId,message:sanitizeDiagnosticText(message,512)}),results.push({taskId,outcome:"error",message})}}return{results,truncated}}var MAX_STAGE_A_REPAIR_SCAN=200,RETRYABLE_EVENT_CODES;var init_stage_a_repair=__esm(()=>{init_manager2();init_gate_evidence();init_utils2();init_path_identity();init_logger();init_task_id();init_coder_settlement();RETRYABLE_EVENT_CODES=new Set(["EBUSY","EPERM"])});function renderOutcome(outcome){switch(outcome.outcome){case"recovered":return`✅ Task ${outcome.taskId}: settlement recovered (${outcome.accepted?"changes attributed":"no workspace change to attribute"}${outcome.forced?", in-process ownership released by --force":""})`;case"already_terminal":return`⏭️ Task ${outcome.taskId}: settlement already ${outcome.state} (nothing to recover)`;case"owned_in_process":return`ℹ️ Task ${outcome.taskId}: dispatch ${sanitizeDiagnosticText(outcome.transitionId)} is still registered as in flight in this process. If no coder is genuinely running, re-run with --force to release it.`;case"owned_by_live_foreign_pid":return`ℹ️ Task ${outcome.taskId}: owned by live process pid ${outcome.processId} (another OpenCode instance). Close that instance or run /swarm recover there; this command never interrupts another live process's dispatch.`;case"unreadable_wal":return`⚠️ Task ${outcome.taskId}: settlement WAL is unreadable — inspect .swarm/coder-settlements/${outcome.taskId}.json`;case"error":return`❌ Task ${outcome.taskId}: recovery failed — ${sanitizeDiagnosticText(outcome.message,512)}`;default:return`❌ Task ${outcome.taskId}: unknown outcome`}}function renderStageARepairOutcome(outcome){switch(outcome.outcome){case"repaired":return`✅ Task ${outcome.taskId}: Stage A repaired — stage_a_passed written at generation ${outcome.generation} without re-running the coder`;case"skipped_not_wedged":return`⏭️ Task ${outcome.taskId}: workflow state is ${outcome.state} with pre_check proof present or not settled — nothing to repair`;case"skipped_not_green":return`⏭️ Task ${outcome.taskId}: no green post-settlement pre-check evidence (${outcome.reason==="no_pre_check_bundles"?"missing or non-green secretscan/SAST bundle — run pre_check_batch first":"latest pre-check run failed or predates the settlement"}) — refusing to mark Stage A passed without proof`;case"error":return`❌ Task ${outcome.taskId}: Stage A repair failed — ${sanitizeDiagnosticText(outcome.message,512)}`;default:return`❌ Task ${outcome.taskId}: unknown repair outcome`}}async function handleRecoverCommand(directory,args2){let force=args2.includes("--force"),positional=args2.filter((arg)=>!arg.startsWith("--")),taskId=positional[0];if(positional.length>1)return["## Coder Settlement Recovery","",`❌ Unexpected arguments: ${positional.join(" ")}`,"Usage: /swarm recover [task_id] [--force]"].join(`
3255
3255
  `);let{states:listed,truncated:listTruncated}=await listCoderSettlementWalStates(directory),report=["## Coder Settlement Recovery",""],hasKnownWal=listed.length>0&&(!taskId||listed.some((entry)=>entry.taskId===taskId));if(listed.length===0)report.push(taskId?`❌ No settlement WAL for task ${taskId} (no settlement WALs found in .swarm/coder-settlements/).`:"No coder settlement WALs found in .swarm/coder-settlements/ — nothing to recover.");else if(taskId&&!hasKnownWal)report.push(`❌ No settlement WAL for task ${taskId}. Known tasks: ${listed.map((entry)=>entry.taskId).join(", ")}`);else{let{results,truncated:recoverTruncated}=await recoverStaleCoderSettlements(directory,{...taskId?{taskIds:[taskId]}:{},force}),lines=results.map((outcome)=>renderOutcome(outcome)),recoveredCount=results.filter((r)=>r.outcome==="recovered").length,blockedCount=results.filter((r)=>r.outcome==="owned_in_process"||r.outcome==="owned_by_live_foreign_pid").length;if(report.push(...lines,"",`Recovered ${recoveredCount} settlement(s)${blockedCount>0?`; ${blockedCount} still owned by a live dispatch (see above for the exact remediation)`:""}.`),listTruncated||recoverTruncated)report.push("","⚠️ More settlement WALs exist than the recovery scan cap (200) — older settlements were NOT listed or processed. Re-run after the tasks above are settled to reach the rest.");if(force&&recoveredCount>0)report.push("","⚠️ --force released in-process ownership before recovery. If any of these dispatches was genuinely still running, its completion will report CODER_SETTLEMENT_IDEMPOTENCY_CONFLICT — that error is expected and safe to ignore; the settlement is already durably recovered.")}try{let{results:repairResults,truncated:repairTruncated}=await repairWedgedStageA(directory,{...taskId?{taskIds:[taskId]}:{}}),repaired=repairResults.filter((r)=>r.outcome==="repaired");if(repairResults.length>0){if(report.push("","## Wedged Stage A Repair","",...repairResults.map(renderStageARepairOutcome),"",repaired.length===0?"No wedged tasks repaired.":`Repaired ${repaired.length} wedged task(s); reviewer/test_engineer dispatch is now permitted for them.`),repairTruncated)report.push("","⚠️ More evidence files exist than the repair scan cap (200) — re-run after the tasks above are processed to reach the rest.")}}catch(err){report.push("",`⚠️ Wedged Stage A repair failed (settlement recovery above is unaffected): ${sanitizeDiagnosticText(err instanceof Error?err.message:String(err),512)}`)}return report.join(`
3256
- `)}var init_recover=__esm(()=>{init_path_identity();init_coder_settlement();init_stage_a_repair()});class CircuitBreaker{state="closed";failureCount=0;successCount=0;lastFailureTime;config;name;onStateChange;constructor(name,config3,onStateChange){this.name=name,this.config={failureThreshold:config3?.failureThreshold??5,resetTimeoutMs:config3?.resetTimeoutMs??30000,successThreshold:config3?.successThreshold??3,callTimeoutMs:config3?.callTimeoutMs??1e4},this.onStateChange=onStateChange}getState(){if(this.state==="open"&&this.lastFailureTime){if(Date.now()-this.lastFailureTime>=this.config.resetTimeoutMs)this.transitionTo("half-open")}return this.state}async execute(fn2){if(this.getState()==="open")throw Error(`Circuit breaker '${this.name}' is open`);let startTime=Date.now();try{let result=await this.executeWithTimeout(fn2),duration5=Date.now()-startTime;return this.recordSuccess(duration5),result}catch(error93){let duration5=Date.now()-startTime;throw this.recordFailure(error93,duration5),error93}}async executeWithTimeout(fn2){if(this.config.callTimeoutMs<=0)return fn2();return new Promise((resolve79,reject)=>{let timeout=setTimeout(()=>{reject(Error(`Call timeout after ${this.config.callTimeoutMs}ms`))},this.config.callTimeoutMs);fn2().then((result)=>{clearTimeout(timeout),resolve79(result)}).catch((error93)=>{clearTimeout(timeout),reject(error93)})})}recordSuccess(duration5){if(this.failureCount=0,this.state==="half-open"){if(this.successCount++,this.successCount>=this.config.successThreshold)this.transitionTo("closed")}this.onStateChange?.("callSuccess",{duration:duration5})}recordFailure(error93,duration5){if(this.failureCount++,this.lastFailureTime=Date.now(),this.state==="half-open")this.transitionTo("open");else if(this.state==="closed"&&this.failureCount>=this.config.failureThreshold)this.transitionTo("open");this.onStateChange?.("callFailure",{error:error93,duration:duration5})}transitionTo(newState2){let oldState=this.state;if(this.state=newState2,newState2==="closed")this.failureCount=0,this.successCount=0,this.onStateChange?.("closed",{timestamp:Date.now(),successCount:0,oldState});else if(newState2==="open")this.successCount=0,this.onStateChange?.("opened",{timestamp:Date.now(),failureCount:this.failureCount,oldState});else if(newState2==="half-open")this.successCount=0,this.onStateChange?.("half-open",{timestamp:Date.now(),oldState})}reset(){this.transitionTo("closed")}getStats(){return{state:this.getState(),failureCount:this.failureCount,successCount:this.successCount,lastFailureTime:this.lastFailureTime}}}class LoopProtection{records=new Map;config;onLoopDetected;constructor(config3,onLoopDetected){this.config=config3,this.onLoopDetected=onLoopDetected}recordAttempt(key){let operationKey=key??this.config.operationKey,now2=Date.now(),record3=this.records.get(operationKey);if(record3&&now2-record3.firstAttempt>this.config.timeWindowMs)record3=void 0;if(!record3)return this.records.set(operationKey,{count:1,firstAttempt:now2,lastAttempt:now2}),!0;if(record3.count++,record3.lastAttempt=now2,record3.count>this.config.maxIterations)return this.onLoopDetected?.(operationKey,record3.count),!1;return!0}canProceed(key){let operationKey=key??this.config.operationKey,record3=this.records.get(operationKey);if(!record3)return!0;if(Date.now()-record3.firstAttempt>this.config.timeWindowMs)return!0;return record3.count<=this.config.maxIterations}getRemainingIterations(key){let operationKey=key??this.config.operationKey,record3=this.records.get(operationKey);if(!record3)return this.config.maxIterations;if(Date.now()-record3.firstAttempt>this.config.timeWindowMs)return this.config.maxIterations;return Math.max(0,this.config.maxIterations-record3.count)}reset(key){let operationKey=key??this.config.operationKey;this.records.delete(operationKey)}resetAll(){this.records.clear()}getIterationCount(key){let operationKey=key??this.config.operationKey,record3=this.records.get(operationKey);if(!record3)return 0;if(Date.now()-record3.firstAttempt>this.config.timeWindowMs)return 0;return record3.count}getTrackedOperations(){return Array.from(this.records.keys())}}function comparePriority(a,b){let priorityOrder={critical:0,high:1,normal:2,low:3},priorityDiff=priorityOrder[a.priority]-priorityOrder[b.priority];if(priorityDiff!==0)return priorityDiff;return a.createdAt-b.createdAt}class AutomationQueue{items=[];maxSize;defaultMaxRetries;defaultBackoffMs;maxBackoffMs;eventBus;overflowStrategy;itemCounter=0;constructor(config3){this.maxSize=config3?.maxSize??1000,this.defaultMaxRetries=config3?.defaultMaxRetries??3,this.defaultBackoffMs=config3?.defaultBackoffMs??1000,this.maxBackoffMs=config3?.maxBackoffMs??60000,this.overflowStrategy=config3?.overflowStrategy??"throw",this.eventBus=getGlobalEventBus()}generateId(){return`queue-${Date.now()}-${++this.itemCounter}`}enqueue(payload,priority="normal",metadata){if(this.items.length>=this.maxSize)if(this.overflowStrategy==="evict-oldest"){let oldestIdx=0;for(let i=1;i<this.items.length;i++)if(this.items[i].createdAt<this.items[oldestIdx].createdAt)oldestIdx=i;let[evicted]=this.items.splice(oldestIdx,1);if(evicted)this.eventBus.publish("queue.item.evicted",{itemId:evicted.id})}else throw Error(`Queue is full (max ${this.maxSize} items)`);let item={id:this.generateId(),priority,payload,createdAt:Date.now(),metadata,retry:{attempts:0,maxAttempts:this.defaultMaxRetries,backoffMs:this.defaultBackoffMs,maxBackoffMs:this.maxBackoffMs}};return this.items.push(item),this.items.sort(comparePriority),this.eventBus.publish("queue.item.enqueued",{itemId:item.id,priority}),item.id}dequeue(){let item=this.items.shift();if(item)this.eventBus.publish("queue.item.dequeued",{itemId:item.id});return item}peek(){return this.items[0]}get(id){return this.items.find((item)=>item.id===id)}remove(id){let index=this.items.findIndex((item)=>item.id===id);if(index!==-1)return this.items.splice(index,1),!0;return!1}complete(id){let removed=this.remove(id);if(removed)this.eventBus.publish("queue.item.completed",{itemId:id});return removed}retry(id,_error){let item=this.get(id);if(!item||!item.retry)return!1;if(item.retry.attempts++,item.retry.lastAttempt=Date.now(),item.retry.attempts>=item.retry.maxAttempts)return this.eventBus.publish("queue.item.failed",{itemId:id,attempts:item.retry.attempts}),this.remove(id),!1;let backoff=Math.min(item.retry.backoffMs*2**(item.retry.attempts-1),item.retry.maxBackoffMs);return item.retry.nextAttemptAt=Date.now()+backoff,this.eventBus.publish("queue.item.retry scheduled",{itemId:id,attempt:item.retry.attempts,nextAttemptAt:item.retry.nextAttemptAt,backoffMs:backoff}),!0}getRetryableItems(){let now2=Date.now();return this.items.filter((item)=>item.retry?.nextAttemptAt&&item.retry.nextAttemptAt<=now2)}size(){return this.items.length}isEmpty(){return this.items.length===0}isFull(){return this.items.length>=this.maxSize}clear(){this.items=[]}getAll(){return[...this.items]}getByPriority(priority){return this.items.filter((item)=>item.priority===priority)}getStats(){return{size:this.items.length,maxSize:this.maxSize,byPriority:{critical:this.items.filter((i)=>i.priority==="critical").length,high:this.items.filter((i)=>i.priority==="high").length,normal:this.items.filter((i)=>i.priority==="normal").length,low:this.items.filter((i)=>i.priority==="low").length},retryable:this.getRetryableItems().length}}}var init_queue=__esm(()=>{init_event_bus()});function sleep2(ms){return new Promise((resolve79)=>setTimeout(resolve79,ms))}class WorkerManager{workers=new Map;eventBus;constructor(){this.eventBus=getGlobalEventBus()}register(registration){if(this.workers.has(registration.name))throw Error(`Worker '${registration.name}' is already registered`);let worker={name:registration.name,handler:registration.handler,queue:registration.queue,concurrency:registration.concurrency??1,status:"idle",activeCount:0,processedCount:0,errorCount:0};if(this.workers.set(registration.name,worker),this.eventBus.publish("worker.started",{workerName:registration.name,concurrency:worker.concurrency}),registration.autoStart)this.start(registration.name)}unregister(name){let worker=this.workers.get(name);if(!worker)return!1;if(worker.status==="running")this.stop(name);return this.workers.delete(name),!0}start(name){let worker=this.workers.get(name);if(!worker)throw Error(`Worker '${name}' is not registered`);if(worker.status==="running")return!1;return worker.status="running",this.startProcessingLoop(worker),this.eventBus.publish("worker.started",{workerName:name,concurrency:worker.concurrency}),!0}startProcessingLoop(worker){(async()=>{while(worker.status==="running"){if(worker.activeCount>=worker.concurrency){await sleep2(50);continue}let item=worker.queue.dequeue();if(!item){await sleep2(100);continue}worker.activeCount++,this.handleItem(worker,item).finally(()=>{worker.activeCount--})}})().catch((error93)=>{this.eventBus.publish("worker.error",{workerName:worker.name,itemId:"loop",error:error93})})}async handleItem(worker,item){try{let result=await worker.handler(item);if(result.success)worker.processedCount++,worker.queue.complete(item.id);else worker.errorCount++,worker.lastError=result.error,worker.queue.retry(item.id,result.error)}catch(error93){worker.errorCount++,worker.lastError=error93,this.eventBus.publish("worker.error",{workerName:worker.name,itemId:item.id,error:error93}),worker.queue.retry(item.id,error93)}}stop(name){let worker=this.workers.get(name);if(!worker)return!1;if(worker.status!=="running")return!1;return worker.status="stopping",this.eventBus.publish("worker.stopped",{workerName:name,processedCount:worker.processedCount,errorCount:worker.errorCount}),worker.status="stopped",!0}startAll(){for(let[name,worker]of this.workers)if(worker.status==="idle"||worker.status==="stopped")this.start(name)}stopAll(){for(let name of this.workers.keys())this.stop(name)}getStatus(name){return this.workers.get(name)?.status}getStats(name){let worker=this.workers.get(name);if(!worker)return;return{status:worker.status,activeCount:worker.activeCount,processedCount:worker.processedCount,errorCount:worker.errorCount,lastError:worker.lastError,queueSize:worker.queue.size()}}getWorkerNames(){return Array.from(this.workers.keys())}isAnyRunning(){for(let worker of this.workers.values())if(worker.status==="running")return!0;return!1}getTotalStats(){let stats2={};for(let name of this.workers.keys())stats2[name]=this.getStats(name);return stats2}}var init_worker=__esm(()=>{init_event_bus()});class BackgroundAutomationManager{config;eventBus;workerManager;queues=new Map;circuitBreakers=new Map;loopProtections=new Map;isInitialized=!1;isRunning=!1;constructor(config3){this.config={enabled:config3.enabled,maxQueueSize:config3.maxQueueSize??1000,maxRetries:config3.maxRetries??3,circuitBreaker:config3.circuitBreaker,loopProtection:config3.loopProtection},this.eventBus=getGlobalEventBus(),this.workerManager=new WorkerManager}initialize(){if(!this.config.enabled){log("[Automation] Framework disabled, skipping initialization");return}if(this.isInitialized){log("[Automation] Already initialized");return}log("[Automation] Initializing framework..."),this.isInitialized=!0,this.eventBus.publish("automation.started",{config:this.config})}start(){if(!this.config.enabled||!this.isInitialized)return;if(this.isRunning)return;log("[Automation] Starting framework..."),this.isRunning=!0,this.eventBus.publish("automation.started",{timestamp:Date.now()})}stop(){if(!this.isRunning)return;log("[Automation] Stopping framework..."),this.workerManager.stopAll(),this.isRunning=!1,this.eventBus.publish("automation.stopped",{timestamp:Date.now()})}isEnabled(){return this.config.enabled}isActive(){return this.isRunning}getOrCreateQueue(name){if(!this.queues.has(name)){let queue=new AutomationQueue({maxSize:this.config.maxQueueSize,defaultMaxRetries:this.config.maxRetries});this.queues.set(name,queue)}return this.queues.get(name)}registerWorker(registration){if(!this.config.enabled)throw Error("Cannot register worker: automation framework is disabled");this.workerManager.register(registration)}startWorker(name){if(!this.config.enabled)return!1;return this.workerManager.start(name)}stopWorker(name){if(!this.config.enabled)return!1;return this.workerManager.stop(name)}getOrCreateCircuitBreaker(name){if(!this.circuitBreakers.has(name)){let cb=new CircuitBreaker(name,this.config.circuitBreaker,(eventType,event)=>{log(`[CircuitBreaker] ${name}: ${eventType}`,event),this.eventBus.publish("circuit.breaker.opened",{breakerName:name,eventType,event})});this.circuitBreakers.set(name,cb)}return this.circuitBreakers.get(name)}getOrCreateLoopProtection(operationKey){if(!this.loopProtections.has(operationKey)){let config3={maxIterations:this.config.loopProtection?.maxIterations??10,timeWindowMs:this.config.loopProtection?.timeWindowMs??60000,operationKey},lp=new LoopProtection(config3,(key,count)=>{log(`[LoopProtection] ${key}: Detected potential loop (${count} iterations)`),this.eventBus.publish("loop.protection.triggered",{operationKey:key,count,timestamp:Date.now()})});this.loopProtections.set(operationKey,lp)}return this.loopProtections.get(operationKey)}subscribe(type,listener){return this.eventBus.subscribe(type,listener)}async publish(type,payload,source){await this.eventBus.publish(type,payload,source)}getStats(){return{enabled:this.config.enabled,initialized:this.isInitialized,running:this.isRunning,queues:Object.fromEntries(Array.from(this.queues.entries()).map(([name,queue])=>[name,queue.getStats()])),workers:this.workerManager.getTotalStats(),circuitBreakers:Object.fromEntries(Array.from(this.circuitBreakers.entries()).map(([name,cb])=>[name,cb.getStats()])),loopProtections:Array.from(this.loopProtections.keys())}}reset(){this.stop(),this.workerManager.stopAll(),this.queues.clear(),this.circuitBreakers.clear(),this.loopProtections.clear(),this.isInitialized=!1}}function createAutomationManager(automationConfig){let config3={enabled:automationConfig?.mode!=="manual",maxQueueSize:500,maxRetries:3,circuitBreaker:{failureThreshold:5,resetTimeoutMs:30000,successThreshold:2,callTimeoutMs:15000},loopProtection:{maxIterations:10,timeWindowMs:60000}},manager=new BackgroundAutomationManager(config3);return manager.initialize(),manager}function resetAutomationManager(){if(managerInstance)managerInstance.reset(),managerInstance=null}var managerInstance=null;var init_manager3=__esm(()=>{init_utils();init_event_bus();init_queue();init_worker()});import*as fs98 from"node:fs";import*as path185 from"node:path";function backupSwarmStateBeforeReset(directory,kind,relEntries){let warnings=[],copied=[],swarmDir=path185.join(directory,".swarm");try{let stat18=fs98.lstatSync(swarmDir);if(stat18.isSymbolicLink()||!stat18.isDirectory())return{backupDir:null,copied,warnings}}catch{return{backupDir:null,copied,warnings}}let timestamp=new Date().toISOString().replace(/[:.]/g,"-"),backupsRoot=path185.join(swarmDir,"reset-backups"),backupDir=path185.join(backupsRoot,`${kind}-${timestamp}`),backupDirCreated=!1,ensureBackupDir=()=>{if(!backupDirCreated)fs98.mkdirSync(backupDir,{recursive:!0}),backupDirCreated=!0};for(let rel of relEntries){let src;try{src=validateSwarmPath(directory,rel)}catch{warnings.push(`skipped backup of ${rel} (path validation failed)`);continue}if(!fs98.existsSync(src))continue;try{ensureBackupDir();let dest=path185.join(backupDir,rel);fs98.mkdirSync(path185.dirname(dest),{recursive:!0}),fs98.cpSync(src,dest,{recursive:!0}),copied.push(rel)}catch(err){warnings.push(`failed to back up ${rel}: ${err instanceof Error?err.message:String(err)}`)}}if(copied.length===0){if(backupDirCreated)try{fs98.rmSync(backupDir,{recursive:!0,force:!0})}catch{}return{backupDir:null,copied,warnings}}return pruneOldResetBackups(backupsRoot,warnings),{backupDir,copied,warnings}}function pruneOldResetBackups(backupsRoot,warnings){try{let entries=fs98.readdirSync(backupsRoot,{withFileTypes:!0}).filter((e)=>e.isDirectory()).map((e)=>e.name).sort().reverse();for(let stale of entries.slice(RESET_BACKUP_RETENTION))try{fs98.rmSync(path185.join(backupsRoot,stale),{recursive:!0,force:!0})}catch(err){warnings.push(`failed to prune old backup ${stale}: ${err instanceof Error?err.message:String(err)}`)}}catch(err){warnings.push(`failed to prune old reset backups: ${err instanceof Error?err.message:String(err)}`)}}var RESET_BACKUP_RETENTION=5;var init_reset_backup=__esm(()=>{init_utils2()});import*as fs99 from"node:fs";import*as path186 from"node:path";async function handleResetCommand(directory,args2){if(!args2.includes("--confirm"))return["## Swarm Reset","","⚠️ This will delete all swarm state from .swarm/ (plan, context, checkpoints, SWARM_PLAN artifacts including .swarm/plan-export/)","","A timestamped backup of the deleted state is saved to `.swarm/reset-backups/` automatically (restore by copying files back). Run `/swarm export` first if you also want a portable JSON snapshot.","","To confirm, run: `/swarm reset --confirm`"].join(`
3256
+ `)}var init_recover=__esm(()=>{init_path_identity();init_coder_settlement();init_stage_a_repair()});class CircuitBreaker{state="closed";failureCount=0;successCount=0;lastFailureTime;config;name;onStateChange;constructor(name,config3,onStateChange){this.name=name,this.config={failureThreshold:config3?.failureThreshold??5,resetTimeoutMs:config3?.resetTimeoutMs??30000,successThreshold:config3?.successThreshold??3,callTimeoutMs:config3?.callTimeoutMs??1e4},this.onStateChange=onStateChange}getState(){if(this.state==="open"&&this.lastFailureTime){if(Date.now()-this.lastFailureTime>=this.config.resetTimeoutMs)this.transitionTo("half-open")}return this.state}async execute(fn2){if(this.getState()==="open")throw Error(`Circuit breaker '${this.name}' is open`);let startTime=Date.now();try{let result=await this.executeWithTimeout(fn2),duration5=Date.now()-startTime;return this.recordSuccess(duration5),result}catch(error93){let duration5=Date.now()-startTime;throw this.recordFailure(error93,duration5),error93}}async executeWithTimeout(fn2){if(this.config.callTimeoutMs<=0)return fn2();return new Promise((resolve79,reject)=>{let timeout=setTimeout(()=>{reject(Error(`Call timeout after ${this.config.callTimeoutMs}ms`))},this.config.callTimeoutMs);fn2().then((result)=>{clearTimeout(timeout),resolve79(result)}).catch((error93)=>{clearTimeout(timeout),reject(error93)})})}recordSuccess(duration5){if(this.failureCount=0,this.state==="half-open"){if(this.successCount++,this.successCount>=this.config.successThreshold)this.transitionTo("closed")}this.onStateChange?.("callSuccess",{duration:duration5})}recordFailure(error93,duration5){if(this.failureCount++,this.lastFailureTime=Date.now(),this.state==="half-open")this.transitionTo("open");else if(this.state==="closed"&&this.failureCount>=this.config.failureThreshold)this.transitionTo("open");this.onStateChange?.("callFailure",{error:error93,duration:duration5})}transitionTo(newState2){let oldState=this.state;if(this.state=newState2,newState2==="closed")this.failureCount=0,this.successCount=0,this.onStateChange?.("closed",{timestamp:Date.now(),successCount:0,oldState});else if(newState2==="open")this.successCount=0,this.onStateChange?.("opened",{timestamp:Date.now(),failureCount:this.failureCount,oldState});else if(newState2==="half-open")this.successCount=0,this.onStateChange?.("half-open",{timestamp:Date.now(),oldState})}reset(){this.transitionTo("closed")}getStats(){return{state:this.getState(),failureCount:this.failureCount,successCount:this.successCount,lastFailureTime:this.lastFailureTime}}}class LoopProtection{records=new Map;config;onLoopDetected;constructor(config3,onLoopDetected){this.config=config3,this.onLoopDetected=onLoopDetected}recordAttempt(key){let operationKey=key??this.config.operationKey,now2=Date.now(),record3=this.records.get(operationKey);if(record3&&now2-record3.firstAttempt>this.config.timeWindowMs)record3=void 0;if(!record3)return this.records.set(operationKey,{count:1,firstAttempt:now2,lastAttempt:now2}),!0;if(record3.count++,record3.lastAttempt=now2,record3.count>this.config.maxIterations)return this.onLoopDetected?.(operationKey,record3.count),!1;return!0}canProceed(key){let operationKey=key??this.config.operationKey,record3=this.records.get(operationKey);if(!record3)return!0;if(Date.now()-record3.firstAttempt>this.config.timeWindowMs)return!0;return record3.count<=this.config.maxIterations}getRemainingIterations(key){let operationKey=key??this.config.operationKey,record3=this.records.get(operationKey);if(!record3)return this.config.maxIterations;if(Date.now()-record3.firstAttempt>this.config.timeWindowMs)return this.config.maxIterations;return Math.max(0,this.config.maxIterations-record3.count)}reset(key){let operationKey=key??this.config.operationKey;this.records.delete(operationKey)}resetAll(){this.records.clear()}getIterationCount(key){let operationKey=key??this.config.operationKey,record3=this.records.get(operationKey);if(!record3)return 0;if(Date.now()-record3.firstAttempt>this.config.timeWindowMs)return 0;return record3.count}getTrackedOperations(){return Array.from(this.records.keys())}}function comparePriority(a,b){let priorityOrder={critical:0,high:1,normal:2,low:3},priorityDiff=priorityOrder[a.priority]-priorityOrder[b.priority];if(priorityDiff!==0)return priorityDiff;return a.createdAt-b.createdAt}class AutomationQueue{items=[];inflight=new Map;terminalIds=new Map;maxSize;defaultMaxRetries;defaultBackoffMs;maxBackoffMs;eventBus;overflowStrategy;itemCounter=0;constructor(config3){this.maxSize=config3?.maxSize??1000,this.defaultMaxRetries=config3?.defaultMaxRetries??3,this.defaultBackoffMs=config3?.defaultBackoffMs??1000,this.maxBackoffMs=config3?.maxBackoffMs??60000,this.overflowStrategy=config3?.overflowStrategy??"throw",this.eventBus=getGlobalEventBus()}generateId(){return`queue-${Date.now()}-${++this.itemCounter}`}enqueue(payload,priority="normal",metadata){if(this.items.length>=this.maxSize)if(this.overflowStrategy==="evict-oldest"){let oldestIdx=0;for(let i=1;i<this.items.length;i++)if(this.items[i].createdAt<this.items[oldestIdx].createdAt)oldestIdx=i;let[evicted]=this.items.splice(oldestIdx,1);if(evicted)this.eventBus.publish("queue.item.evicted",{itemId:evicted.id})}else throw Error(`Queue is full (max ${this.maxSize} items)`);let item={id:this.generateId(),priority,payload,createdAt:Date.now(),metadata,retry:{attempts:0,maxAttempts:this.defaultMaxRetries,backoffMs:this.defaultBackoffMs,maxBackoffMs:this.maxBackoffMs}};return this.items.push(item),this.items.sort(comparePriority),this.eventBus.publish("queue.item.enqueued",{itemId:item.id,priority}),item.id}dequeue(){if(this.inflight.size>=this.maxSize)return;let now2=Date.now(),index=this.items.findIndex((item2)=>item2.retry?.nextAttemptAt===void 0||item2.retry.nextAttemptAt<=now2);if(index===-1)return;let[item]=this.items.splice(index,1);if(!item)return;return this.inflight.set(item.id,item),this.eventBus.publish("queue.item.dequeued",{itemId:item.id}),item}peek(){return this.items[0]}get(id){return this.items.find((item)=>item.id===id)??this.inflight.get(id)}inflightSize(){return this.inflight.size}removeQueuedOrInflight(id){let queuedIndex=this.items.findIndex((item)=>item.id===id);if(queuedIndex!==-1){let[removed]=this.items.splice(queuedIndex,1);return removed}let inflightItem=this.inflight.get(id);if(inflightItem)this.inflight.delete(id);return inflightItem}markTerminal(id,at){if(this.terminalIds.set(id,at),this.terminalIds.size>MAX_TERMINAL_IDS){let oldest=this.terminalIds.keys().next().value;if(oldest!==void 0)this.terminalIds.delete(oldest)}}remove(id){if(this.terminalIds.has(id))return!1;return this.removeQueuedOrInflight(id)!==void 0}complete(id){if(this.terminalIds.has(id))return!1;if(!this.removeQueuedOrInflight(id))return!1;return this.markTerminal(id,Date.now()),this.eventBus.publish("queue.item.completed",{itemId:id}),!0}retry(id,_error){if(this.terminalIds.has(id))return!1;let item=this.get(id);if(!item||!item.retry)return!1;if(item.retry.attempts++,item.retry.lastAttempt=Date.now(),item.retry.attempts>=item.retry.maxAttempts)return this.removeQueuedOrInflight(id),this.markTerminal(id,Date.now()),this.eventBus.publish("queue.item.failed",{itemId:id,attempts:item.retry.attempts}),!1;let backoff=Math.min(item.retry.backoffMs*2**(item.retry.attempts-1),item.retry.maxBackoffMs);if(item.retry.nextAttemptAt=Date.now()+backoff,this.inflight.delete(id),!this.items.some((queued)=>queued.id===id))this.items.push(item),this.items.sort(comparePriority);return this.eventBus.publish("queue.item.retry scheduled",{itemId:id,attempt:item.retry.attempts,nextAttemptAt:item.retry.nextAttemptAt,backoffMs:backoff}),!0}getRetryableItems(){let now2=Date.now();return this.items.filter((item)=>item.retry?.nextAttemptAt&&item.retry.nextAttemptAt<=now2)}size(){return this.items.length}isEmpty(){return this.items.length===0}isFull(){return this.items.length>=this.maxSize}clear(){for(let item of this.items)this.eventBus.publish("queue.item.evicted",{itemId:item.id});this.items=[];for(let item of this.inflight.values())this.eventBus.publish("queue.item.evicted",{itemId:item.id});this.inflight.clear()}getAll(){return[...this.items]}getByPriority(priority){return this.items.filter((item)=>item.priority===priority)}getStats(){return{size:this.items.length,maxSize:this.maxSize,byPriority:{critical:this.items.filter((i)=>i.priority==="critical").length,high:this.items.filter((i)=>i.priority==="high").length,normal:this.items.filter((i)=>i.priority==="normal").length,low:this.items.filter((i)=>i.priority==="low").length},retryable:this.getRetryableItems().length,inflight:this.inflight.size}}}var MAX_TERMINAL_IDS=2048;var init_queue=__esm(()=>{init_event_bus()});function sleep2(ms){return new Promise((resolve79)=>setTimeout(resolve79,ms))}class WorkerManager{workers=new Map;eventBus;constructor(){this.eventBus=getGlobalEventBus()}register(registration){if(this.workers.has(registration.name))throw Error(`Worker '${registration.name}' is already registered`);let worker={name:registration.name,handler:registration.handler,queue:registration.queue,concurrency:registration.concurrency??1,status:"idle",activeCount:0,processedCount:0,errorCount:0};if(this.workers.set(registration.name,worker),this.eventBus.publish("worker.started",{workerName:registration.name,concurrency:worker.concurrency}),registration.autoStart)this.start(registration.name)}unregister(name){let worker=this.workers.get(name);if(!worker)return!1;if(worker.status==="running")this.stop(name);return this.workers.delete(name),!0}start(name){let worker=this.workers.get(name);if(!worker)throw Error(`Worker '${name}' is not registered`);if(worker.status==="running")return!1;return worker.status="running",this.startProcessingLoop(worker),this.eventBus.publish("worker.started",{workerName:name,concurrency:worker.concurrency}),!0}startProcessingLoop(worker){(async()=>{while(worker.status==="running"){if(worker.activeCount>=worker.concurrency){await sleep2(50);continue}let item=worker.queue.dequeue();if(!item){await sleep2(100);continue}worker.activeCount++,this.handleItem(worker,item).finally(()=>{worker.activeCount--})}})().catch((error93)=>{this.eventBus.publish("worker.error",{workerName:worker.name,itemId:"loop",error:error93})})}async handleItem(worker,item){try{let result=await worker.handler(item);if(result.success)worker.processedCount++,worker.queue.complete(item.id);else worker.errorCount++,worker.lastError=result.error,worker.queue.retry(item.id,result.error)}catch(error93){worker.errorCount++,worker.lastError=error93,this.eventBus.publish("worker.error",{workerName:worker.name,itemId:item.id,error:error93}),worker.queue.retry(item.id,error93)}}stop(name){let worker=this.workers.get(name);if(!worker)return!1;if(worker.status!=="running")return!1;return worker.status="stopping",this.eventBus.publish("worker.stopped",{workerName:name,processedCount:worker.processedCount,errorCount:worker.errorCount}),worker.status="stopped",!0}startAll(){for(let[name,worker]of this.workers)if(worker.status==="idle"||worker.status==="stopped")this.start(name)}stopAll(){for(let name of this.workers.keys())this.stop(name)}getStatus(name){return this.workers.get(name)?.status}getStats(name){let worker=this.workers.get(name);if(!worker)return;return{status:worker.status,activeCount:worker.activeCount,processedCount:worker.processedCount,errorCount:worker.errorCount,lastError:worker.lastError,queueSize:worker.queue.size(),queueInflight:worker.queue.inflightSize()}}getWorkerNames(){return Array.from(this.workers.keys())}isAnyRunning(){for(let worker of this.workers.values())if(worker.status==="running")return!0;return!1}getTotalStats(){let stats2={};for(let name of this.workers.keys())stats2[name]=this.getStats(name);return stats2}}var init_worker=__esm(()=>{init_event_bus()});class BackgroundAutomationManager{config;eventBus;workerManager;queues=new Map;circuitBreakers=new Map;loopProtections=new Map;isInitialized=!1;isRunning=!1;constructor(config3){this.config={enabled:config3.enabled,maxQueueSize:config3.maxQueueSize??1000,maxRetries:config3.maxRetries??3,circuitBreaker:config3.circuitBreaker,loopProtection:config3.loopProtection},this.eventBus=getGlobalEventBus(),this.workerManager=new WorkerManager}initialize(){if(!this.config.enabled){log("[Automation] Framework disabled, skipping initialization");return}if(this.isInitialized){log("[Automation] Already initialized");return}log("[Automation] Initializing framework..."),this.isInitialized=!0,this.eventBus.publish("automation.started",{config:this.config})}start(){if(!this.config.enabled||!this.isInitialized)return;if(this.isRunning)return;log("[Automation] Starting framework..."),this.isRunning=!0,this.eventBus.publish("automation.started",{timestamp:Date.now()})}stop(){if(!this.isRunning)return;log("[Automation] Stopping framework..."),this.workerManager.stopAll(),this.isRunning=!1,this.eventBus.publish("automation.stopped",{timestamp:Date.now()})}isEnabled(){return this.config.enabled}isActive(){return this.isRunning}getOrCreateQueue(name){if(!this.queues.has(name)){let queue=new AutomationQueue({maxSize:this.config.maxQueueSize,defaultMaxRetries:this.config.maxRetries});this.queues.set(name,queue)}return this.queues.get(name)}registerWorker(registration){if(!this.config.enabled)throw Error("Cannot register worker: automation framework is disabled");this.workerManager.register(registration)}startWorker(name){if(!this.config.enabled)return!1;return this.workerManager.start(name)}stopWorker(name){if(!this.config.enabled)return!1;return this.workerManager.stop(name)}getOrCreateCircuitBreaker(name){if(!this.circuitBreakers.has(name)){let cb=new CircuitBreaker(name,this.config.circuitBreaker,(eventType,event)=>{log(`[CircuitBreaker] ${name}: ${eventType}`,event),this.eventBus.publish("circuit.breaker.opened",{breakerName:name,eventType,event})});this.circuitBreakers.set(name,cb)}return this.circuitBreakers.get(name)}getOrCreateLoopProtection(operationKey){if(!this.loopProtections.has(operationKey)){let config3={maxIterations:this.config.loopProtection?.maxIterations??10,timeWindowMs:this.config.loopProtection?.timeWindowMs??60000,operationKey},lp=new LoopProtection(config3,(key,count)=>{log(`[LoopProtection] ${key}: Detected potential loop (${count} iterations)`),this.eventBus.publish("loop.protection.triggered",{operationKey:key,count,timestamp:Date.now()})});this.loopProtections.set(operationKey,lp)}return this.loopProtections.get(operationKey)}subscribe(type,listener){return this.eventBus.subscribe(type,listener)}async publish(type,payload,source){await this.eventBus.publish(type,payload,source)}getStats(){return{enabled:this.config.enabled,initialized:this.isInitialized,running:this.isRunning,queues:Object.fromEntries(Array.from(this.queues.entries()).map(([name,queue])=>[name,queue.getStats()])),workers:this.workerManager.getTotalStats(),circuitBreakers:Object.fromEntries(Array.from(this.circuitBreakers.entries()).map(([name,cb])=>[name,cb.getStats()])),loopProtections:Array.from(this.loopProtections.keys())}}reset(){this.stop(),this.workerManager.stopAll(),this.queues.clear(),this.circuitBreakers.clear(),this.loopProtections.clear(),this.isInitialized=!1}}function createAutomationManager(automationConfig){let config3={enabled:automationConfig?.mode!=="manual",maxQueueSize:500,maxRetries:3,circuitBreaker:{failureThreshold:5,resetTimeoutMs:30000,successThreshold:2,callTimeoutMs:15000},loopProtection:{maxIterations:10,timeWindowMs:60000}},manager=new BackgroundAutomationManager(config3);return manager.initialize(),manager}function resetAutomationManager(){if(managerInstance)managerInstance.reset(),managerInstance=null}var managerInstance=null;var init_manager3=__esm(()=>{init_utils();init_event_bus();init_queue();init_worker()});import*as fs98 from"node:fs";import*as path185 from"node:path";function backupSwarmStateBeforeReset(directory,kind,relEntries){let warnings=[],copied=[],swarmDir=path185.join(directory,".swarm");try{let stat18=fs98.lstatSync(swarmDir);if(stat18.isSymbolicLink()||!stat18.isDirectory())return{backupDir:null,copied,warnings}}catch{return{backupDir:null,copied,warnings}}let timestamp=new Date().toISOString().replace(/[:.]/g,"-"),backupsRoot=path185.join(swarmDir,"reset-backups"),backupDir=path185.join(backupsRoot,`${kind}-${timestamp}`),backupDirCreated=!1,ensureBackupDir=()=>{if(!backupDirCreated)fs98.mkdirSync(backupDir,{recursive:!0}),backupDirCreated=!0};for(let rel of relEntries){let src;try{src=validateSwarmPath(directory,rel)}catch{warnings.push(`skipped backup of ${rel} (path validation failed)`);continue}if(!fs98.existsSync(src))continue;try{ensureBackupDir();let dest=path185.join(backupDir,rel);fs98.mkdirSync(path185.dirname(dest),{recursive:!0}),fs98.cpSync(src,dest,{recursive:!0}),copied.push(rel)}catch(err){warnings.push(`failed to back up ${rel}: ${err instanceof Error?err.message:String(err)}`)}}if(copied.length===0){if(backupDirCreated)try{fs98.rmSync(backupDir,{recursive:!0,force:!0})}catch{}return{backupDir:null,copied,warnings}}return pruneOldResetBackups(backupsRoot,warnings),{backupDir,copied,warnings}}function pruneOldResetBackups(backupsRoot,warnings){try{let entries=fs98.readdirSync(backupsRoot,{withFileTypes:!0}).filter((e)=>e.isDirectory()).map((e)=>e.name).sort().reverse();for(let stale of entries.slice(RESET_BACKUP_RETENTION))try{fs98.rmSync(path185.join(backupsRoot,stale),{recursive:!0,force:!0})}catch(err){warnings.push(`failed to prune old backup ${stale}: ${err instanceof Error?err.message:String(err)}`)}}catch(err){warnings.push(`failed to prune old reset backups: ${err instanceof Error?err.message:String(err)}`)}}var RESET_BACKUP_RETENTION=5;var init_reset_backup=__esm(()=>{init_utils2()});import*as fs99 from"node:fs";import*as path186 from"node:path";async function handleResetCommand(directory,args2){if(!args2.includes("--confirm"))return["## Swarm Reset","","⚠️ This will delete all swarm state from .swarm/ (plan, context, checkpoints, SWARM_PLAN artifacts including .swarm/plan-export/)","","A timestamped backup of the deleted state is saved to `.swarm/reset-backups/` automatically (restore by copying files back). Run `/swarm export` first if you also want a portable JSON snapshot.","","To confirm, run: `/swarm reset --confirm`"].join(`
3257
3257
  `);let filesToReset=["plan.md","plan.json","plan-ledger.jsonl","context.md","spec.md","spec-staleness.json","spec-snapshot.md","SWARM_PLAN.md","SWARM_PLAN.json","plan-export/SWARM_PLAN.md","plan-export/SWARM_PLAN.json","checkpoints.json","events.jsonl","run-memory.jsonl","reproduction.json","issue-publication.json","recurrence-sweep.json","implementation-review.json"],results=[];try{let backup=_internals146.backupSwarmStateBeforeReset(directory,"reset",[...filesToReset,"summaries"]);if(backup.backupDir&&backup.copied.length>0){let rel=path186.relative(directory,backup.backupDir);results.push(`- \uD83D\uDCE6 Backed up ${backup.copied.length} item(s) to ${rel}/ (restore by copying files back into .swarm/)`)}for(let w of backup.warnings)results.push(`- ⚠️ Backup warning: ${w}`)}catch(err){results.push(`- ⚠️ Auto-backup failed (continuing with reset): ${err instanceof Error?err.message:String(err)}`)}for(let filename of filesToReset)try{let resolvedPath=validateSwarmPath(directory,filename);if(fs99.existsSync(resolvedPath))fs99.unlinkSync(resolvedPath),results.push(`- ✅ Deleted ${filename}`);else results.push(`- ⏭️ ${filename} not found (skipped)`)}catch{results.push(`- ❌ Failed to delete ${filename}`)}for(let filename of["SWARM_PLAN.md","SWARM_PLAN.json"])try{let rootPath=path186.join(directory,filename);if(fs99.existsSync(rootPath))fs99.unlinkSync(rootPath),results.push(`- ✅ Deleted ${filename} (root)`)}catch(err){results.push(`- ❌ Failed to delete ${filename}: ${err instanceof Error?err.message:String(err)}`)}try{resetAutomationManager(),results.push("- ✅ Stopped background automation (in-memory queues cleared)")}catch{results.push("- ⏭️ Background automation not running (skipped)")}try{let summariesPath=validateSwarmPath(directory,"summaries");if(fs99.existsSync(summariesPath))fs99.rmSync(summariesPath,{recursive:!0,force:!0}),results.push("- ✅ Deleted summaries/ directory");else results.push("- ⏭️ summaries/ not found (skipped)")}catch{results.push("- ❌ Failed to delete summaries/")}return["## Swarm Reset Complete","",...results,"","Swarm state has been cleared. Start fresh with a new plan."].join(`
3258
3258
  `)}var _internals146;var init_reset=__esm(()=>{init_manager3();init_utils2();init_reset_backup();_internals146={backupSwarmStateBeforeReset}});function gateActionArgs(tool3,_args,discriminator){if(normalizeToolNameLowerCase(tool3??"")!=="task")return{};return discriminator?{subagent_type:discriminator}:{}}function gateDenialDiscriminator(tool3,args2){try{if(normalizeToolNameLowerCase(tool3??"")!=="task")return"";let subagentType=args2?.subagent_type;if(typeof subagentType!=="string"||subagentType.length===0)return"";let canonical=stripKnownSwarmPrefix(subagentType).trim().toLowerCase();if(canonical.length===0)return"";return canonical.slice(0,MAX_DISCRIMINATOR_LENGTH)}catch{return""}}function deriveGateDenialCode(message){if(typeof message!=="string")return UNCLASSIFIED_GATE_DENIAL_CODE;let colonIndex=message.indexOf(":");if(colonIndex<=0)return UNCLASSIFIED_GATE_DENIAL_CODE;let candidate=message.slice(0,colonIndex).trim();if(candidate.length===0||candidate.length>MAX_CODE_LENGTH)return UNCLASSIFIED_GATE_DENIAL_CODE;return candidate}function isAbortLikeError(err){if(err&&typeof err==="object"){if(err.name==="AbortError")return!0;let message=err.message;if(typeof message==="string"&&message.startsWith("AbortError"))return!0}return!1}function gateDenialWarnText(count,code){return`
3259
3259
  [swarm] This is denial #${count} with the same cause (${code}). Do NOT retry the same dispatch; fix the named cause or present the blocker to the user.`}function gateDenialStopText(count,code,tool3){return`
@@ -3433,8 +3433,9 @@ INSTRUCTIONS: Re-summarise into a tighter format. Discard completed task details
3433
3433
  [/CONTEXT COMPACTION]`}function buildEmergencyMessage(budgetPct,preserveLastN){return`[CONTEXT COMPACTION — EMERGENCY TIER]
3434
3434
  `+`Context window is ${budgetPct.toFixed(1)}% used. EMERGENCY compaction required.
3435
3435
  INSTRUCTIONS: Retain ONLY the system prompt, the current task context, and the last ${preserveLastN} conversation turns. Discard everything else. If you cannot complete the current task in the remaining context, escalate to the user.
3436
- [/CONTEXT COMPACTION]`}function createCompactionService(config3,directory,injectMessage){return{toolAfter:async(_input,_output)=>{if(!config3.enabled)return;let budgetPct=getSessionBudgetPct(_input.sessionID);if(budgetPct<=0)return;let sessionId=_input.sessionID,state=getSessionState(sessionId);try{if(budgetPct>=config3.emergencyThreshold&&budgetPct>state.lastEmergencyAt+5){state.lastEmergencyAt=budgetPct,state.emergencyCount++;let msg=buildEmergencyMessage(budgetPct,config3.preserveLastNTurns);appendSnapshot(directory,"emergency",budgetPct,msg),state.lastSnapshotAt=new Date().toISOString(),injectMessage(sessionId,msg);return}if(budgetPct>=config3.reflectionThreshold&&budgetPct>state.lastReflectionAt+5){state.lastReflectionAt=budgetPct,state.reflectionCount++;let msg=buildReflectionMessage(budgetPct);appendSnapshot(directory,"reflection",budgetPct,msg),state.lastSnapshotAt=new Date().toISOString(),injectMessage(sessionId,msg);return}if(budgetPct>=config3.observationThreshold&&budgetPct>state.lastObservationAt+5){state.lastObservationAt=budgetPct,state.observationCount++;let msg=buildObservationMessage(budgetPct);appendSnapshot(directory,"observation",budgetPct,msg),state.lastSnapshotAt=new Date().toISOString(),injectMessage(sessionId,msg)}}catch{}}}}function getCompactionMetrics(sessionId){if(sessionId){let state=getSessionState(sessionId);return{compactionCount:state.observationCount+state.reflectionCount+state.emergencyCount,lastSnapshotAt:state.lastSnapshotAt}}let total=0,lastSnapshot=null;for(let state of sessionStates.values())if(total+=state.observationCount+state.reflectionCount+state.emergencyCount,state.lastSnapshotAt&&(!lastSnapshot||state.lastSnapshotAt>lastSnapshot))lastSnapshot=state.lastSnapshotAt;return{compactionCount:total,lastSnapshotAt:lastSnapshot}}var sessionStates,MAX_TRACKED_COMPACTION_SESSIONS=500;var init_compaction_service=__esm(()=>{init_state2();sessionStates=new Map});import*as fsSync12 from"node:fs";import{readFile as readFile45}from"node:fs/promises";import*as path209 from"node:path";function formatLedgerBytes(bytes){if(bytes>=1048576)return`${Math.round(bytes/1048576*10)/10} MiB`;if(bytes>=1024)return`${Math.round(bytes/1024*10)/10} KiB`;return`${bytes} B`}function readSpecStalenessSnapshot(directory){try{let p=path209.join(directory,".swarm","spec-staleness.json");if(!fsSync12.existsSync(p))return{stale:!1};let raw=fsSync12.readFileSync(p,"utf-8"),parsed=JSON.parse(raw);return{stale:!0,reason:typeof parsed?.reason==="string"?parsed.reason:void 0,storedHash:typeof parsed?.specHash_plan==="string"?parsed.specHash_plan:void 0,currentHash:typeof parsed?.specHash_current==="string"||parsed?.specHash_current===null?parsed.specHash_current:void 0}}catch{return{stale:!1}}}function formatAgo(ms){let seconds=Math.floor(ms/1000);if(seconds<60)return`${seconds}s ago`;let minutes=Math.floor(seconds/60);if(minutes<60)return`${minutes}m ago`;let hours=Math.floor(minutes/60);if(hours<24)return`${hours}h ago`;return`${Math.floor(hours/24)}d ago`}async function getStatusData(directory,agents,sessionId){let plan=await loadPlan(directory),status;if(plan&&plan.migration_status!=="migration_failed"){let currentPhase=extractCurrentPhaseFromPlan(plan)||"Unknown",completedTasks=0,totalTasks=0;for(let phase of plan.phases)for(let task2 of phase.tasks)if(totalTasks++,task2.status==="completed")completedTasks++;let agentCount=Object.keys(agents).length,metrics=getCompactionMetrics();status={hasPlan:!0,currentPhase,completedTasks,totalTasks,agentCount,isLegacy:!1,turboMode:hasActiveTurboMode(),contextBudgetPct:getDisplayBudget()?.pct??null,contextBudgetTokens:getDisplayBudget()?.tokens??null,compactionCount:metrics.compactionCount,lastSnapshotAt:metrics.lastSnapshotAt}}else{let planContent=await readSwarmFileAsync(directory,"plan.md");if(!planContent){let metrics=getCompactionMetrics();status={hasPlan:!1,currentPhase:"Unknown",completedTasks:0,totalTasks:0,agentCount:Object.keys(agents).length,isLegacy:!0,turboMode:hasActiveTurboMode(),contextBudgetPct:getDisplayBudget()?.pct??null,contextBudgetTokens:getDisplayBudget()?.tokens??null,compactionCount:metrics.compactionCount,lastSnapshotAt:metrics.lastSnapshotAt}}else{let currentPhase=extractCurrentPhase(planContent)||"Unknown",completedTasks=(planContent.match(/^- \[x\]/gm)||[]).length,incompleteTasks=(planContent.match(/^- \[ \]/gm)||[]).length,totalTasks=completedTasks+incompleteTasks,agentCount=Object.keys(agents).length,metrics=getCompactionMetrics();status={hasPlan:!0,currentPhase,completedTasks,totalTasks,agentCount,isLegacy:!0,turboMode:hasActiveTurboMode(),contextBudgetPct:getDisplayBudget()?.pct??null,contextBudgetTokens:getDisplayBudget()?.tokens??null,compactionCount:metrics.compactionCount,lastSnapshotAt:metrics.lastSnapshotAt}}}let drift=readSpecStalenessSnapshot(directory);if(drift.stale)status.specStale=!0,status.specStaleReason=drift.reason,status.specStaleStoredHash=drift.storedHash,status.specStaleCurrentHash=drift.currentHash;else if(plan&&plan._specStale)status.specStale=!0,status.specStaleReason=plan._specStaleReason;status.recentEscalations=await readRecentEscalations(directory),status.pendingProposals=await countProposals(directory),status.unactionableQueueDepth=await safeLineCount(resolveUnactionablePath(directory)),status.insightCandidatesPending=await safeLineCount(validateSwarmPath(directory,"insight-candidates.jsonl"));try{status.consensusReports=await countConsensusReportFiles(directory)}catch{status.consensusReports=0}try{status.delegationLedgerHealth=collectDelegationLedgerHealth(directory,{ledgerLimitBytes:MAX_RECOVERY_LEDGER_BYTES,lowWaterBytes:DELEGATION_COMPACTION_LOW_WATER_BYTES,highWaterBytes:DELEGATION_COMPACTION_HIGH_WATER_BYTES})??void 0}catch{status.delegationLedgerHealth=void 0}try{let pointer=readLinkPointer(directory);if(pointer)status.cohort={linked:!0,linkId:pointer.linkId,cohortId:pointer.cohortId,identitySource:pointer.identitySource,degraded:pointer.degraded,sharedRoot:resolveLinkDir(pointer.linkId),generation:pointer.generation};else status.cohort={linked:!1}}catch{status.cohort={linked:!1}}try{let memoryPointer=readMemoryLinkPointer(directory),provider,configFingerprintMatch;try{let memoryConfig=MemoryConfigSchema.parse(loadPluginConfig(directory).memory??{});if(provider=memoryConfig.provider,memoryPointer){let cohortConfigPath=path209.join(resolveLinkDir(memoryPointer.linkId),"memory","memory-cohort-config.json");if(fsSync12.existsSync(cohortConfigPath)){let stored=JSON.parse(fsSync12.readFileSync(cohortConfigPath,"utf-8"));if(classifyStoredFingerprintAlgorithmVersion(stored.algorithm_version).status==="comparable"&&typeof stored.fingerprint==="string"){let expected=computeMemoryCohortFingerprint(buildMemoryCohortFingerprintInput(memoryConfig));configFingerprintMatch=stored.fingerprint===expected}}}}catch{}if(memoryPointer)status.memoryCohort={linked:!0,linkId:memoryPointer.linkId,cohortId:memoryPointer.cohortId,identitySource:memoryPointer.identitySource,degraded:memoryPointer.degraded,sharedRoot:resolveLinkDir(memoryPointer.linkId),generation:memoryPointer.generation,provider,configFingerprintMatch};else status.memoryCohort={linked:!1,provider}}catch{status.memoryCohort={linked:!1}}if(status.fullAutoActive=_internals162.hasActiveFullAuto(),status.fullAutoActive){let sid=_internals162.getActiveFullAutoSessionID();if(sid){let runState=_internals162.loadFullAutoRunState(directory,sid);if(runState?.lastEscalation)status.fullAutoEscalation={reason:runState.lastEscalation.reason,interactionCount:runState.lastEscalation.interactionCount,deadlockCount:runState.lastEscalation.deadlockCount,phase:runState.lastEscalation.phase}}}if(sessionId){let timestamp=getLastHeartbeat(sessionId);if(timestamp!==void 0){let agoMs=Date.now()-timestamp;status.lastActivity={sessionId,timestamp,agoMs,agoLabel:formatAgo(agoMs)}}else status.lastActivity={sessionId,timestamp:0,agoMs:null,agoLabel:"never"}}return enrichWithLeanTurbo(status,directory)}function enrichWithLeanTurbo(status,directory){let turboMode=hasActiveTurboMode(),leanActive=_internals162.hasActiveLeanTurbo(),turboStrategy="off";if(leanActive)turboStrategy="lean";else if(turboMode)turboStrategy="standard";status.turboStrategy=turboStrategy;try{let recoveryRecords=listRecoveryRecords(directory);if(recoveryRecords.length>0)status.leanPreservedRecoveryWorktrees=recoveryRecords.map((r)=>({laneId:r.laneId,status:r.status,worktreePath:r.worktreePath,reason:r.reason,replayHint:r.replayHint}))}catch{}if(!leanActive)return status;let leanSessionID=null;for(let[sessionId,session]of swarmState.agentSessions)if(session.turboStrategy==="lean"&&session.leanTurboActive===!0){leanSessionID=sessionId;break}if(leanSessionID){let runState=_internals162.loadLeanTurboRunState(directory,leanSessionID);if(runState){if(status.leanTurboPhase=runState.phase,status.leanMaxParallelCoders=runState.maxParallelCoders,status.leanPauseReason=runState.pauseReason,!Array.isArray(runState.lanes))runState.lanes=[];let activeLanes=0,completedLanes=0;for(let lane of runState.lanes){if(lane.status==="running")activeLanes++;if(lane.status==="completed")completedLanes++}if(status.leanActiveLaneCount=activeLanes,status.leanCompletedLanes=completedLanes,!Array.isArray(runState.degradedTasks))runState.degradedTasks=[],status.leanDegradedTasks=0;if(runState.degradedTasks.length>0){status.leanDegradedTasks=runState.degradedTasks.length;let summaryParts=[];for(let dt of runState.degradedTasks)summaryParts.push(`${dt.taskId} (${dt.reason})`);status.leanDegradationSummary=summaryParts.join("; ")}}}return status}function formatStatusMarkdown(status){let lines=["## Swarm Status","",`**Current Phase**: ${status.currentPhase}`,`**Tasks**: ${status.completedTasks}/${status.totalTasks} complete`,`**Agents**: ${status.agentCount} registered`];if(status.lastActivity){let label=status.lastActivity.agoLabel,annotation=status.lastActivity.agoLabel!=="never"&&status.lastActivity.agoMs!==null&&status.lastActivity.agoMs>120000?" ⚠️ possibly stalled":"";lines.push(""),lines.push(`**Last activity:** ${label}${annotation}`)}if(status.specStale){let reason=status.specStaleReason??"spec.md changed since plan saved",stored=status.specStaleStoredHash??"unknown",current=status.specStaleCurrentHash??"(spec.md missing)";lines.push("",`**Spec drift detected**: ${reason} (stored: ${stored}, current: ${current})`,"Run `/swarm clarify` to enter spec repair mode. Clarify alone does not clear drift: rewrite the spec so recovery can reconcile it, or run `/swarm acknowledge-spec-drift` to dismiss.")}if(status.turboStrategy&&status.turboStrategy!=="off")if(lines.push(""),status.turboStrategy==="lean"){let parts=["lean"];if(status.leanTurboPhase!==void 0)parts.push(`Phase ${status.leanTurboPhase}`);if(status.leanActiveLaneCount!==void 0){let totalLanes=(status.leanActiveLaneCount??0)+(status.leanCompletedLanes??0);parts.push(`${status.leanActiveLaneCount}/${totalLanes} lanes active`)}if(status.leanDegradedTasks!==void 0&&status.leanDegradedTasks>0)parts.push(`${status.leanDegradedTasks} degraded`);if(lines.push(`**Turbo**: ${parts.join(", ")}`),status.leanDegradationSummary)lines.push(` - ${status.leanDegradationSummary}`);if(status.leanPauseReason)lines.push(`**Lean paused**: ${status.leanPauseReason}`)}else lines.push("**Turbo**: standard");else if(status.turboStrategy===void 0&&status.turboMode===!0)lines.push(""),lines.push("**TURBO MODE**: active");if(status.leanPreservedRecoveryWorktrees&&status.leanPreservedRecoveryWorktrees.length>0){lines.push(""),lines.push(`**Preserved recovery worktrees**: ${status.leanPreservedRecoveryWorktrees.length} lane(s) preserved for manual merge-back recovery`);for(let w of status.leanPreservedRecoveryWorktrees)lines.push(` - ${w.laneId} (${w.status}): ${w.reason} — \`${w.replayHint}\``)}if(status.fullAutoActive){if(lines.push(""),lines.push("**Full-Auto**: active"),status.fullAutoEscalation){let e=status.fullAutoEscalation,phaseStr=e.phase!==void 0?` | Phase ${e.phase}`:"";lines.push(` - Escalation: ${e.reason} (interactions=${e.interactionCount}, deadlocks=${e.deadlockCount}${phaseStr})`)}}if(status.contextBudgetPct!==null&&status.contextBudgetPct>0){let pct=status.contextBudgetPct.toFixed(1),budgetTokens=status.contextBudgetTokens;if(budgetTokens!==void 0&&budgetTokens!==null&&budgetTokens>0){let est=Math.round(status.contextBudgetPct/100*budgetTokens);lines.push("",`**Context**: ${pct}% used (est. ${est.toLocaleString()} / ${budgetTokens.toLocaleString()} tokens)`)}else lines.push("",`**Context**: ${pct}% used`);if(status.compactionCount>0)lines.push(`**Compaction events**: ${status.compactionCount} triggered`);if(status.lastSnapshotAt)lines.push(`**Last snapshot**: ${status.lastSnapshotAt}`)}if(status.recentEscalations&&status.recentEscalations.length>0){lines.push("","**Recently Escalated (last 7 days)**:");for(let e of status.recentEscalations)lines.push(` - ${e.entry_id} (${e.from}→${e.to}) reason=${e.reason}`)}let proposals=status.pendingProposals??0,unactionable=status.unactionableQueueDepth??0,insights=status.insightCandidatesPending??0,consensusReports=status.consensusReports??0;if(proposals>0||unactionable>0||insights>0||consensusReports>0){if(lines.push("","**Learning Queues**:"),proposals>0)lines.push(` - Pending proposals: ${proposals} (review with \`/swarm skill list\`)`);if(unactionable>0)lines.push(` - Unactionable queue: ${unactionable} (inspect with \`/swarm knowledge unactionable\`)`);if(insights>0)lines.push(` - Insight candidates: ${insights} (consumed at phase end)`);if(consensusReports>0)lines.push(` - Consensus reports: ${consensusReports} (read under \`.swarm/evolution/consensus/\`; each holds proposals-only recommendations)`)}if(status.cohort?.linked){if(lines.push("","**Knowledge Cohort**:"),lines.push(` - \uD83D\uDD17 Linked to shared store "${status.cohort.linkId}"`),status.cohort.cohortId)lines.push(` cohort: ${status.cohort.cohortId}`);if(status.cohort.identitySource)lines.push(` identity: ${status.cohort.identitySource}`);if(status.cohort.degraded)lines.push(" ⚠ degraded (machine-local, not portable across machines)");if(status.cohort.sharedRoot)lines.push(` shared at: ${status.cohort.sharedRoot}`);if(status.cohort.generation!==void 0)lines.push(` generation: ${status.cohort.generation}`)}else lines.push("","**Knowledge Cohort**: local (not linked — run `/swarm link` to share across worktrees)");if(status.memoryCohort?.linked){if(lines.push("","**Memory Cohort**:"),lines.push(` - \uD83D\uDD17 Memory shared across linked worktrees "${status.memoryCohort.linkId}"`),status.memoryCohort.cohortId)lines.push(` cohort: ${status.memoryCohort.cohortId}`);if(status.memoryCohort.identitySource)lines.push(` identity: ${status.memoryCohort.identitySource}`);if(status.memoryCohort.degraded)lines.push(" ⚠ degraded (machine-local, not portable across machines)");if(status.memoryCohort.sharedRoot)lines.push(` shared at: ${status.memoryCohort.sharedRoot}/memory`);if(status.memoryCohort.generation!==void 0)lines.push(` generation: ${status.memoryCohort.generation}`);if(status.memoryCohort.provider)lines.push(` provider: ${status.memoryCohort.provider}`);if(status.memoryCohort.configFingerprintMatch===!1)lines.push(" ⚠ config fingerprint mismatch — provider/embedding/redaction config differs across cohort members");else if(status.memoryCohort.configFingerprintMatch===!0)lines.push(" config: ✅ fingerprint matches cohort")}else lines.push("","**Memory Cohort**: local (not linked — run `/swarm memory link` to share memory across worktrees; requires `memory.link.enabled: true`)");let delegationHealth=status.delegationLedgerHealth;if(delegationHealth){if(lines.push("","**Background Delegations**:"),lines.push(` - Ledger tail: ${formatLedgerBytes(delegationHealth.ledger.bytes)} / ${formatLedgerBytes(delegationHealth.ledger.limitBytes)} recovery bound (${delegationHealth.ledger.pressurePct}% — ${delegationHealth.ledger.band})`),delegationHealth.checkpoint){let checkpoint2=delegationHealth.checkpoint;lines.push(` - Checkpoint #${checkpoint2.sequence}: ${checkpoint2.liveRecords} live records, ${checkpoint2.closedSummaries} archived summaries (${formatLedgerBytes(checkpoint2.bytes)}, ${new Date(checkpoint2.createdAt).toISOString()})`)}else lines.push(" - Checkpoint: none (full-history recovery)");if(delegationHealth.recovery){let recovery=delegationHealth.recovery;lines.push(` - Recovery: ${recovery.source} (${recovery.ok?"ok":`FAILED: ${recovery.reason??"uncertain"}`})`)}if(delegationHealth.lastUncertainty){let uncertainty=delegationHealth.lastUncertainty;if(lines.push(` - ⚠ Last uncertainty (${new Date(uncertainty.at).toISOString()}, ${uncertainty.source}): ${uncertainty.reason}`),uncertainty.repairHint)lines.push(` repair: ${uncertainty.repairHint}`)}let counts=delegationHealth.counts;if(counts.activeOwners>0||counts.pendingAdvisories>0||counts.lateTerminals>0||counts.orphanWorktreeOwners>0)lines.push(` - Live set: ${counts.activeOwners} active owners, ${counts.pendingAdvisories} pending advisories, ${counts.lateTerminals} late terminals, ${counts.orphanWorktreeOwners} unsettled worktree owners`)}return lines.join(`
3437
- `)}async function handleStatusCommand(directory,agents,sessionId){let statusData=await getStatusData(directory,agents,sessionId);if(!statusData.hasPlan){if(statusData.specStale){let reason=statusData.specStaleReason??"spec.md changed since plan saved",stored=statusData.specStaleStoredHash??"unknown",current=statusData.specStaleCurrentHash??"(spec.md missing)";return["No active swarm plan found.","",`**Spec drift detected**: ${reason} (stored: ${stored}, current: ${current})`,"Run `/swarm clarify` to enter spec repair mode. Clarify alone does not clear drift: rewrite the spec so recovery can reconcile it, or run `/swarm acknowledge-spec-drift` to dismiss."].join(`
3436
+ [/CONTEXT COMPACTION]`}function createCompactionService(config3,directory,injectMessage){return{toolAfter:async(_input,_output)=>{if(!config3.enabled)return;let budgetPct=getSessionBudgetPct(_input.sessionID);if(budgetPct<=0)return;let sessionId=_input.sessionID,state=getSessionState(sessionId);try{if(budgetPct>=config3.emergencyThreshold&&budgetPct>state.lastEmergencyAt+5){state.lastEmergencyAt=budgetPct,state.emergencyCount++;let msg=buildEmergencyMessage(budgetPct,config3.preserveLastNTurns);appendSnapshot(directory,"emergency",budgetPct,msg),state.lastSnapshotAt=new Date().toISOString(),injectMessage(sessionId,msg);return}if(budgetPct>=config3.reflectionThreshold&&budgetPct>state.lastReflectionAt+5){state.lastReflectionAt=budgetPct,state.reflectionCount++;let msg=buildReflectionMessage(budgetPct);appendSnapshot(directory,"reflection",budgetPct,msg),state.lastSnapshotAt=new Date().toISOString(),injectMessage(sessionId,msg);return}if(budgetPct>=config3.observationThreshold&&budgetPct>state.lastObservationAt+5){state.lastObservationAt=budgetPct,state.observationCount++;let msg=buildObservationMessage(budgetPct);appendSnapshot(directory,"observation",budgetPct,msg),state.lastSnapshotAt=new Date().toISOString(),injectMessage(sessionId,msg)}}catch{}}}}function getCompactionMetrics(sessionId){if(sessionId){let state=getSessionState(sessionId);return{compactionCount:state.observationCount+state.reflectionCount+state.emergencyCount,lastSnapshotAt:state.lastSnapshotAt}}let total=0,lastSnapshot=null;for(let state of sessionStates.values())if(total+=state.observationCount+state.reflectionCount+state.emergencyCount,state.lastSnapshotAt&&(!lastSnapshot||state.lastSnapshotAt>lastSnapshot))lastSnapshot=state.lastSnapshotAt;return{compactionCount:total,lastSnapshotAt:lastSnapshot}}var sessionStates,MAX_TRACKED_COMPACTION_SESSIONS=500;var init_compaction_service=__esm(()=>{init_state2();sessionStates=new Map});import*as fsSync12 from"node:fs";import{readFile as readFile45}from"node:fs/promises";import*as path209 from"node:path";async function collectBackgroundWorkStatus(directory){try{await maintainBackgroundDelegations(directory,{lockTimeoutMs:2000,reason:"status"})}catch{}let counts={pending:0,running:0,completed:0,consumed:0,stale:0,cancelled:0,error:0,ingestion_error:0},maintenance=readDelegationHealthArtifact(directory)?.maintenance??null,empty={counts,reservations:[],maintenance,source:"uncertain"},scan;try{scan=scanDelegationsForRecovery(directory)}catch(error93){return{...empty,uncertainty:`delegation recovery scan failed: ${error93 instanceof Error?error93.message:String(error93)}`}}if(scan.status==="uncertain")return{...empty,uncertainty:`delegation ledger over its recovery bound or corrupt: ${scan.reason}`};let reservationScan=scanBackgroundCoderReservationsForAdmission(directory);if(reservationScan.status==="uncertain")return{...empty,uncertainty:`coder reservation store unreadable: ${reservationScan.reason}`};for(let record3 of scan.owners)if(record3.status in counts)counts[record3.status]+=1;let now2=Date.now(),reservations=reservationScan.reservations.map((reservation)=>({reservationId:reservation.reservationId,planTaskId:reservation.planTaskId,generation:reservation.generation??1,state:reservation.state,leaseState:reservation.leaseExpiresAt===void 0?"protected-legacy":reservation.leaseExpiresAt>now2?"active":"expired",...reservation.leaseExpiresAt!==void 0?{leaseExpiresAt:reservation.leaseExpiresAt}:{}}));return{counts,reservations,maintenance,source:"validated-recovery"}}function formatLedgerBytes(bytes){if(bytes>=1048576)return`${Math.round(bytes/1048576*10)/10} MiB`;if(bytes>=1024)return`${Math.round(bytes/1024*10)/10} KiB`;return`${bytes} B`}function readSpecStalenessSnapshot(directory){try{let p=path209.join(directory,".swarm","spec-staleness.json");if(!fsSync12.existsSync(p))return{stale:!1};let raw=fsSync12.readFileSync(p,"utf-8"),parsed=JSON.parse(raw);return{stale:!0,reason:typeof parsed?.reason==="string"?parsed.reason:void 0,storedHash:typeof parsed?.specHash_plan==="string"?parsed.specHash_plan:void 0,currentHash:typeof parsed?.specHash_current==="string"||parsed?.specHash_current===null?parsed.specHash_current:void 0}}catch{return{stale:!1}}}function formatAgo(ms){let seconds=Math.floor(ms/1000);if(seconds<60)return`${seconds}s ago`;let minutes=Math.floor(seconds/60);if(minutes<60)return`${minutes}m ago`;let hours=Math.floor(minutes/60);if(hours<24)return`${hours}h ago`;return`${Math.floor(hours/24)}d ago`}async function getStatusData(directory,agents,sessionId,options){let plan=await loadPlan(directory),status;if(plan&&plan.migration_status!=="migration_failed"){let currentPhase=extractCurrentPhaseFromPlan(plan)||"Unknown",completedTasks=0,totalTasks=0;for(let phase of plan.phases)for(let task2 of phase.tasks)if(totalTasks++,task2.status==="completed")completedTasks++;let agentCount=Object.keys(agents).length,metrics=getCompactionMetrics();status={hasPlan:!0,currentPhase,completedTasks,totalTasks,agentCount,isLegacy:!1,turboMode:hasActiveTurboMode(),contextBudgetPct:getDisplayBudget()?.pct??null,contextBudgetTokens:getDisplayBudget()?.tokens??null,compactionCount:metrics.compactionCount,lastSnapshotAt:metrics.lastSnapshotAt}}else{let planContent=await readSwarmFileAsync(directory,"plan.md");if(!planContent){let metrics=getCompactionMetrics();status={hasPlan:!1,currentPhase:"Unknown",completedTasks:0,totalTasks:0,agentCount:Object.keys(agents).length,isLegacy:!0,turboMode:hasActiveTurboMode(),contextBudgetPct:getDisplayBudget()?.pct??null,contextBudgetTokens:getDisplayBudget()?.tokens??null,compactionCount:metrics.compactionCount,lastSnapshotAt:metrics.lastSnapshotAt}}else{let currentPhase=extractCurrentPhase(planContent)||"Unknown",completedTasks=(planContent.match(/^- \[x\]/gm)||[]).length,incompleteTasks=(planContent.match(/^- \[ \]/gm)||[]).length,totalTasks=completedTasks+incompleteTasks,agentCount=Object.keys(agents).length,metrics=getCompactionMetrics();status={hasPlan:!0,currentPhase,completedTasks,totalTasks,agentCount,isLegacy:!0,turboMode:hasActiveTurboMode(),contextBudgetPct:getDisplayBudget()?.pct??null,contextBudgetTokens:getDisplayBudget()?.tokens??null,compactionCount:metrics.compactionCount,lastSnapshotAt:metrics.lastSnapshotAt}}}let drift=readSpecStalenessSnapshot(directory);if(drift.stale)status.specStale=!0,status.specStaleReason=drift.reason,status.specStaleStoredHash=drift.storedHash,status.specStaleCurrentHash=drift.currentHash;else if(plan&&plan._specStale)status.specStale=!0,status.specStaleReason=plan._specStaleReason;status.recentEscalations=await readRecentEscalations(directory),status.pendingProposals=await countProposals(directory),status.unactionableQueueDepth=await safeLineCount(resolveUnactionablePath(directory)),status.insightCandidatesPending=await safeLineCount(validateSwarmPath(directory,"insight-candidates.jsonl"));try{status.consensusReports=await countConsensusReportFiles(directory)}catch{status.consensusReports=0}try{status.delegationLedgerHealth=collectDelegationLedgerHealth(directory,{ledgerLimitBytes:MAX_RECOVERY_LEDGER_BYTES,lowWaterBytes:DELEGATION_COMPACTION_LOW_WATER_BYTES,highWaterBytes:DELEGATION_COMPACTION_HIGH_WATER_BYTES})??void 0}catch{status.delegationLedgerHealth=void 0}if(options?.backgroundSubagents??(()=>{try{return loadPluginConfig(directory)?.hooks?.background_subagents===!0}catch{return!1}})())status.backgroundWork=await collectBackgroundWorkStatus(directory);try{let pointer=readLinkPointer(directory);if(pointer)status.cohort={linked:!0,linkId:pointer.linkId,cohortId:pointer.cohortId,identitySource:pointer.identitySource,degraded:pointer.degraded,sharedRoot:resolveLinkDir(pointer.linkId),generation:pointer.generation};else status.cohort={linked:!1}}catch{status.cohort={linked:!1}}try{let memoryPointer=readMemoryLinkPointer(directory),provider,configFingerprintMatch;try{let memoryConfig=MemoryConfigSchema.parse(loadPluginConfig(directory).memory??{});if(provider=memoryConfig.provider,memoryPointer){let cohortConfigPath=path209.join(resolveLinkDir(memoryPointer.linkId),"memory","memory-cohort-config.json");if(fsSync12.existsSync(cohortConfigPath)){let stored=JSON.parse(fsSync12.readFileSync(cohortConfigPath,"utf-8"));if(classifyStoredFingerprintAlgorithmVersion(stored.algorithm_version).status==="comparable"&&typeof stored.fingerprint==="string"){let expected=computeMemoryCohortFingerprint(buildMemoryCohortFingerprintInput(memoryConfig));configFingerprintMatch=stored.fingerprint===expected}}}}catch{}if(memoryPointer)status.memoryCohort={linked:!0,linkId:memoryPointer.linkId,cohortId:memoryPointer.cohortId,identitySource:memoryPointer.identitySource,degraded:memoryPointer.degraded,sharedRoot:resolveLinkDir(memoryPointer.linkId),generation:memoryPointer.generation,provider,configFingerprintMatch};else status.memoryCohort={linked:!1,provider}}catch{status.memoryCohort={linked:!1}}if(status.fullAutoActive=_internals162.hasActiveFullAuto(),status.fullAutoActive){let sid=_internals162.getActiveFullAutoSessionID();if(sid){let runState=_internals162.loadFullAutoRunState(directory,sid);if(runState?.lastEscalation)status.fullAutoEscalation={reason:runState.lastEscalation.reason,interactionCount:runState.lastEscalation.interactionCount,deadlockCount:runState.lastEscalation.deadlockCount,phase:runState.lastEscalation.phase}}}if(sessionId){let timestamp=getLastHeartbeat(sessionId);if(timestamp!==void 0){let agoMs=Date.now()-timestamp;status.lastActivity={sessionId,timestamp,agoMs,agoLabel:formatAgo(agoMs)}}else status.lastActivity={sessionId,timestamp:0,agoMs:null,agoLabel:"never"}}return enrichWithLeanTurbo(status,directory)}function enrichWithLeanTurbo(status,directory){let turboMode=hasActiveTurboMode(),leanActive=_internals162.hasActiveLeanTurbo(),turboStrategy="off";if(leanActive)turboStrategy="lean";else if(turboMode)turboStrategy="standard";status.turboStrategy=turboStrategy;try{let recoveryRecords=listRecoveryRecords(directory);if(recoveryRecords.length>0)status.leanPreservedRecoveryWorktrees=recoveryRecords.map((r)=>({laneId:r.laneId,status:r.status,worktreePath:r.worktreePath,reason:r.reason,replayHint:r.replayHint}))}catch{}if(!leanActive)return status;let leanSessionID=null;for(let[sessionId,session]of swarmState.agentSessions)if(session.turboStrategy==="lean"&&session.leanTurboActive===!0){leanSessionID=sessionId;break}if(leanSessionID){let runState=_internals162.loadLeanTurboRunState(directory,leanSessionID);if(runState){if(status.leanTurboPhase=runState.phase,status.leanMaxParallelCoders=runState.maxParallelCoders,status.leanPauseReason=runState.pauseReason,!Array.isArray(runState.lanes))runState.lanes=[];let activeLanes=0,completedLanes=0;for(let lane of runState.lanes){if(lane.status==="running")activeLanes++;if(lane.status==="completed")completedLanes++}if(status.leanActiveLaneCount=activeLanes,status.leanCompletedLanes=completedLanes,!Array.isArray(runState.degradedTasks))runState.degradedTasks=[],status.leanDegradedTasks=0;if(runState.degradedTasks.length>0){status.leanDegradedTasks=runState.degradedTasks.length;let summaryParts=[];for(let dt of runState.degradedTasks)summaryParts.push(`${dt.taskId} (${dt.reason})`);status.leanDegradationSummary=summaryParts.join("; ")}}}return status}function formatStatusMarkdown(status){let lines=["## Swarm Status","",`**Current Phase**: ${status.currentPhase}`,`**Tasks**: ${status.completedTasks}/${status.totalTasks} complete`,`**Agents**: ${status.agentCount} registered`];if(status.lastActivity){let label=status.lastActivity.agoLabel,annotation=status.lastActivity.agoLabel!=="never"&&status.lastActivity.agoMs!==null&&status.lastActivity.agoMs>120000?" ⚠️ possibly stalled":"";lines.push(""),lines.push(`**Last activity:** ${label}${annotation}`)}if(status.specStale){let reason=status.specStaleReason??"spec.md changed since plan saved",stored=status.specStaleStoredHash??"unknown",current=status.specStaleCurrentHash??"(spec.md missing)";lines.push("",`**Spec drift detected**: ${reason} (stored: ${stored}, current: ${current})`,"Run `/swarm clarify` to enter spec repair mode. Clarify alone does not clear drift: rewrite the spec so recovery can reconcile it, or run `/swarm acknowledge-spec-drift` to dismiss.")}if(status.turboStrategy&&status.turboStrategy!=="off")if(lines.push(""),status.turboStrategy==="lean"){let parts=["lean"];if(status.leanTurboPhase!==void 0)parts.push(`Phase ${status.leanTurboPhase}`);if(status.leanActiveLaneCount!==void 0){let totalLanes=(status.leanActiveLaneCount??0)+(status.leanCompletedLanes??0);parts.push(`${status.leanActiveLaneCount}/${totalLanes} lanes active`)}if(status.leanDegradedTasks!==void 0&&status.leanDegradedTasks>0)parts.push(`${status.leanDegradedTasks} degraded`);if(lines.push(`**Turbo**: ${parts.join(", ")}`),status.leanDegradationSummary)lines.push(` - ${status.leanDegradationSummary}`);if(status.leanPauseReason)lines.push(`**Lean paused**: ${status.leanPauseReason}`)}else lines.push("**Turbo**: standard");else if(status.turboStrategy===void 0&&status.turboMode===!0)lines.push(""),lines.push("**TURBO MODE**: active");if(status.leanPreservedRecoveryWorktrees&&status.leanPreservedRecoveryWorktrees.length>0){lines.push(""),lines.push(`**Preserved recovery worktrees**: ${status.leanPreservedRecoveryWorktrees.length} lane(s) preserved for manual merge-back recovery`);for(let w of status.leanPreservedRecoveryWorktrees)lines.push(` - ${w.laneId} (${w.status}): ${w.reason} — \`${w.replayHint}\``)}if(status.fullAutoActive){if(lines.push(""),lines.push("**Full-Auto**: active"),status.fullAutoEscalation){let e=status.fullAutoEscalation,phaseStr=e.phase!==void 0?` | Phase ${e.phase}`:"";lines.push(` - Escalation: ${e.reason} (interactions=${e.interactionCount}, deadlocks=${e.deadlockCount}${phaseStr})`)}}if(status.contextBudgetPct!==null&&status.contextBudgetPct>0){let pct=status.contextBudgetPct.toFixed(1),budgetTokens=status.contextBudgetTokens;if(budgetTokens!==void 0&&budgetTokens!==null&&budgetTokens>0){let est=Math.round(status.contextBudgetPct/100*budgetTokens);lines.push("",`**Context**: ${pct}% used (est. ${est.toLocaleString()} / ${budgetTokens.toLocaleString()} tokens)`)}else lines.push("",`**Context**: ${pct}% used`);if(status.compactionCount>0)lines.push(`**Compaction events**: ${status.compactionCount} triggered`);if(status.lastSnapshotAt)lines.push(`**Last snapshot**: ${status.lastSnapshotAt}`)}if(status.recentEscalations&&status.recentEscalations.length>0){lines.push("","**Recently Escalated (last 7 days)**:");for(let e of status.recentEscalations)lines.push(` - ${e.entry_id} (${e.from}→${e.to}) reason=${e.reason}`)}let proposals=status.pendingProposals??0,unactionable=status.unactionableQueueDepth??0,insights=status.insightCandidatesPending??0,consensusReports=status.consensusReports??0;if(proposals>0||unactionable>0||insights>0||consensusReports>0){if(lines.push("","**Learning Queues**:"),proposals>0)lines.push(` - Pending proposals: ${proposals} (review with \`/swarm skill list\`)`);if(unactionable>0)lines.push(` - Unactionable queue: ${unactionable} (inspect with \`/swarm knowledge unactionable\`)`);if(insights>0)lines.push(` - Insight candidates: ${insights} (consumed at phase end)`);if(consensusReports>0)lines.push(` - Consensus reports: ${consensusReports} (read under \`.swarm/evolution/consensus/\`; each holds proposals-only recommendations)`)}if(status.cohort?.linked){if(lines.push("","**Knowledge Cohort**:"),lines.push(` - \uD83D\uDD17 Linked to shared store "${status.cohort.linkId}"`),status.cohort.cohortId)lines.push(` cohort: ${status.cohort.cohortId}`);if(status.cohort.identitySource)lines.push(` identity: ${status.cohort.identitySource}`);if(status.cohort.degraded)lines.push(" ⚠ degraded (machine-local, not portable across machines)");if(status.cohort.sharedRoot)lines.push(` shared at: ${status.cohort.sharedRoot}`);if(status.cohort.generation!==void 0)lines.push(` generation: ${status.cohort.generation}`)}else lines.push("","**Knowledge Cohort**: local (not linked — run `/swarm link` to share across worktrees)");if(status.memoryCohort?.linked){if(lines.push("","**Memory Cohort**:"),lines.push(` - \uD83D\uDD17 Memory shared across linked worktrees "${status.memoryCohort.linkId}"`),status.memoryCohort.cohortId)lines.push(` cohort: ${status.memoryCohort.cohortId}`);if(status.memoryCohort.identitySource)lines.push(` identity: ${status.memoryCohort.identitySource}`);if(status.memoryCohort.degraded)lines.push(" ⚠ degraded (machine-local, not portable across machines)");if(status.memoryCohort.sharedRoot)lines.push(` shared at: ${status.memoryCohort.sharedRoot}/memory`);if(status.memoryCohort.generation!==void 0)lines.push(` generation: ${status.memoryCohort.generation}`);if(status.memoryCohort.provider)lines.push(` provider: ${status.memoryCohort.provider}`);if(status.memoryCohort.configFingerprintMatch===!1)lines.push(" ⚠ config fingerprint mismatch — provider/embedding/redaction config differs across cohort members");else if(status.memoryCohort.configFingerprintMatch===!0)lines.push(" config: ✅ fingerprint matches cohort")}else lines.push("","**Memory Cohort**: local (not linked — run `/swarm memory link` to share memory across worktrees; requires `memory.link.enabled: true`)");let delegationHealth=status.delegationLedgerHealth;if(delegationHealth){if(lines.push("","**Background Delegations**:"),lines.push(` - Ledger tail: ${formatLedgerBytes(delegationHealth.ledger.bytes)} / ${formatLedgerBytes(delegationHealth.ledger.limitBytes)} recovery bound (${delegationHealth.ledger.pressurePct}% — ${delegationHealth.ledger.band})`),delegationHealth.checkpoint){let checkpoint2=delegationHealth.checkpoint;lines.push(` - Checkpoint #${checkpoint2.sequence}: ${checkpoint2.liveRecords} live records, ${checkpoint2.closedSummaries} archived summaries (${formatLedgerBytes(checkpoint2.bytes)}, ${new Date(checkpoint2.createdAt).toISOString()})`)}else lines.push(" - Checkpoint: none (full-history recovery)");if(delegationHealth.recovery){let recovery=delegationHealth.recovery;lines.push(` - Recovery: ${recovery.source} (${recovery.ok?"ok":`FAILED: ${recovery.reason??"uncertain"}`})`)}if(delegationHealth.lastUncertainty){let uncertainty=delegationHealth.lastUncertainty;if(lines.push(` - ⚠ Last uncertainty (${new Date(uncertainty.at).toISOString()}, ${uncertainty.source}): ${uncertainty.reason}`),uncertainty.repairHint)lines.push(` repair: ${uncertainty.repairHint}`)}let counts=delegationHealth.counts;if(counts.activeOwners>0||counts.pendingAdvisories>0||counts.lateTerminals>0||counts.orphanWorktreeOwners>0)lines.push(` - Live set: ${counts.activeOwners} active owners, ${counts.pendingAdvisories} pending advisories, ${counts.lateTerminals} late terminals, ${counts.orphanWorktreeOwners} unsettled worktree owners`)}let backgroundWork=status.backgroundWork;if(backgroundWork)lines.push(...renderBackgroundWorkLines(backgroundWork));return lines.join(`
3437
+ `)}function renderBackgroundWorkLines(backgroundWork){let lines=["","**Background Work** (opt-in):"];if(backgroundWork.source==="uncertain")lines.push(` - ⚠ State uncertain: ${backgroundWork.uncertainty??"unknown reason"} — counts and reservations are not shown rather than partially trusted`);else{let counts=backgroundWork.counts;if(lines.push(` - Delegations: ${counts.pending} pending, ${counts.running} running, ${counts.completed} completed (unconsumed), ${counts.consumed} consumed, ${counts.stale} stale, ${counts.cancelled} cancelled, ${counts.error} error, ${counts.ingestion_error} ingestion_error`),backgroundWork.reservations.length>0){lines.push(` - Reservations (${backgroundWork.reservations.length} active):`);for(let reservation of backgroundWork.reservations){let lease=reservation.leaseState==="active"&&reservation.leaseExpiresAt?`active until ${new Date(reservation.leaseExpiresAt).toISOString()}`:reservation.leaseState;lines.push(` - ${reservation.reservationId.slice(0,12)}… ${reservation.state} gen ${reservation.generation} task ${reservation.planTaskId??"(call-scoped)"} lease ${lease}`)}}else lines.push(" - Reservations: none");lines.push(" - Source: validated recovery (bounded scan)")}let maintenance=backgroundWork.maintenance;if(maintenance){if(maintenance.lastOkAt!==null){let summary=maintenance.lastSummary;lines.push(` - Maintenance: last ok ${new Date(maintenance.lastOkAt).toISOString()} (swept ${summary.sweptStale}, released ${summary.released}, renewed ${summary.renewed}, retained ${summary.retained})`)}else lines.push(" - Maintenance: no successful run recorded");if(maintenance.lastFailure)lines.push(` - Last maintenance failure (${new Date(maintenance.lastFailure.at).toISOString()}): ${maintenance.lastFailure.reason}`);if(maintenance.lastContentionAt!==null)lines.push(` - Last maintenance lock contention: ${new Date(maintenance.lastContentionAt).toISOString()}`);if(maintenance.facts.length>0){lines.push(` - Recent maintenance facts (${maintenance.facts.length}):`);for(let fact of maintenance.facts.slice(-5).reverse()){let target=fact.reservationId?` ${fact.reservationId.slice(0,12)}…`:fact.correlationId?` ${fact.correlationId.slice(0,12)}…`:"";lines.push(` - ${new Date(fact.at).toISOString()} ${fact.kind}${target} — ${fact.reason}`)}}}return lines}async function handleStatusCommand(directory,agents,sessionId,options){let statusData=await getStatusData(directory,agents,sessionId,options);if(!statusData.hasPlan){if(statusData.backgroundWork){let lines=["No active swarm plan found."];return lines.push(...renderBackgroundWorkLines(statusData.backgroundWork)),lines.join(`
3438
+ `)}if(statusData.specStale){let reason=statusData.specStaleReason??"spec.md changed since plan saved",stored=statusData.specStaleStoredHash??"unknown",current=statusData.specStaleCurrentHash??"(spec.md missing)";return["No active swarm plan found.","",`**Spec drift detected**: ${reason} (stored: ${stored}, current: ${current})`,"Run `/swarm clarify` to enter spec repair mode. Clarify alone does not clear drift: rewrite the spec so recovery can reconcile it, or run `/swarm acknowledge-spec-drift` to dismiss."].join(`
3438
3439
  `)}let delegationHealth=statusData.delegationLedgerHealth;if(delegationHealth&&(delegationHealth.checkpoint||delegationHealth.recovery||delegationHealth.lastUncertainty||delegationHealth.ledger.band!=="ok"||delegationHealth.counts.activeOwners>0||delegationHealth.counts.pendingAdvisories>0||delegationHealth.counts.lateTerminals>0||delegationHealth.counts.orphanWorktreeOwners>0)){let lines=["No active swarm plan found.","","**Background Delegations**:"];if(lines.push(` - Ledger tail: ${formatLedgerBytes(delegationHealth.ledger.bytes)} / ${formatLedgerBytes(delegationHealth.ledger.limitBytes)} recovery bound (${delegationHealth.ledger.pressurePct}% — ${delegationHealth.ledger.band})`),delegationHealth.checkpoint)lines.push(` - Checkpoint #${delegationHealth.checkpoint.sequence} (${delegationHealth.checkpoint.liveRecords} live, ${delegationHealth.checkpoint.closedSummaries} archived)`);if(delegationHealth.recovery)lines.push(` - Recovery: ${delegationHealth.recovery.source} (${delegationHealth.recovery.ok?"ok":`FAILED: ${delegationHealth.recovery.reason??"uncertain"}`})`);let compactCounts=delegationHealth.counts;if(compactCounts.activeOwners>0||compactCounts.pendingAdvisories>0||compactCounts.lateTerminals>0||compactCounts.orphanWorktreeOwners>0)lines.push(` - Live set: ${compactCounts.activeOwners} active owners, ${compactCounts.pendingAdvisories} pending advisories, ${compactCounts.lateTerminals} late terminals, ${compactCounts.orphanWorktreeOwners} unsettled worktree owners`);if(delegationHealth.lastUncertainty){if(lines.push(` - ⚠ Last uncertainty (${new Date(delegationHealth.lastUncertainty.at).toISOString()}): ${delegationHealth.lastUncertainty.reason}`),delegationHealth.lastUncertainty.repairHint)lines.push(` repair: ${delegationHealth.lastUncertainty.repairHint}`)}return lines.join(`
3439
3440
  `)}return"No active swarm plan found."}return formatStatusMarkdown(statusData)}async function safeLineCount(filePath){try{if(!fsSync12.existsSync(filePath))return 0;let content=await readFile45(filePath,"utf-8"),n=0;for(let line of content.split(`
3440
3441
  `))if(line.trim())n++;return n}catch{return 0}}async function countProposals(directory){try{let proposalsDir=validateSwarmPath(directory,"skills/proposals");if(!fsSync12.existsSync(proposalsDir))return 0;let{readdir:readdir17}=await import("node:fs/promises");return(await readdir17(proposalsDir)).filter((f)=>f.endsWith(".md")).length}catch{return 0}}var _internals162;var init_status_service=__esm(()=>{init_delegation_health();init_pending_delegations();init_loader();init_schema();init_store3();init_state3();init_extractors();init_knowledge_escalator();init_knowledge_link();init_knowledge_validator();init_utils2();init_memory_link();init_redaction();init_manager();init_state2();init_telemetry();init_recovery();init_state4();init_compaction_service();_internals162={loadLeanTurboRunState,hasActiveLeanTurbo,hasActiveFullAuto,getActiveFullAutoSessionID,loadFullAutoRunState}});var init_status=__esm(()=>{init_status_service()});async function handleSyncPlanCommand(directory,_args){let plan=await loadPlan(directory);if(!plan)return`## Plan Sync Report
@@ -6315,11 +6316,11 @@ ${instruction}`}async function sendWakePrompt(sessionID,events,messageID){let ac
6315
6316
  `);default:return null}}var CLEAR_UNADDRESSED_DELAY_MS=2000,MAX_PENDING_CLEARS=200,pendingClears,_internals168,AUTO_PR_FEEDBACK_EVENTS,EVENT_CONFIG_MAP,CONTENT_EVENT_TYPES;var init_pr_event_subscribers=__esm(()=>{init_pr_workflow_gate();init_state2();init_utils();init_event_bus();init_pr_event_delivery();init_pr_feedback_event_queue();init_pr_subscriptions();pendingClears=new Map,_internals168={handlePrEvent,getGlobalEventBus,listActive,updateSnapshot,getAgentSession,readPrWorkflowGateState,activatePrWorkflow,enqueuePrFeedbackMonitorEvent,deliverPrActivity,isPrEventDeliveryRegistered,scheduleClearUnaddressed,clearUnaddressedDelayMs:CLEAR_UNADDRESSED_DELAY_MS,log,formatAdvisory},AUTO_PR_FEEDBACK_EVENTS=new Set(["pr.ci.failed","pr.merge.conflict"]),EVENT_CONFIG_MAP={"pr.ci.failed":"notify_ci_failure","pr.ci.passed":"notify_ci_success","pr.new.comment":"notify_new_comments","pr.merge.conflict":"notify_merge_conflict","pr.merge.conflict_resolved":"notify_merge_conflict","pr.review.changes_requested":"notify_review_activity","pr.review.approved":"notify_review_activity","pr.merged":"notify_merged","pr.closed":"notify_closed"};CONTENT_EVENT_TYPES=new Set(["pr.new.comment","pr.review.changes_requested","pr.review.approved","pr.review.comment"])});var exports_status_artifact={};__export(exports_status_artifact,{AutomationStatusArtifact:()=>AutomationStatusArtifact});import*as fs115 from"node:fs";import*as path218 from"node:path";function createEmptySnapshot(mode,capabilities){return{timestamp:Date.now(),mode,enabled:mode!=="manual",currentPhase:0,lastTrigger:null,pendingActions:0,lastOutcome:null,capabilities}}function validateFilename(filename){if(filename.includes("\x00"))throw Error("Invalid filename: contains null byte");let pathSeparators=["/","\\",".."];for(let sep41 of pathSeparators)if(filename.includes(sep41))throw Error(`Invalid filename: contains path separator '${sep41}'`);if(filename.startsWith("/")||filename.startsWith("\\")||/^[a-zA-Z]:/.test(filename))throw Error("Invalid filename: absolute paths not allowed");if(filename.length>MAX_FILENAME_LENGTH)throw Error(`Invalid filename: exceeds maximum length of ${MAX_FILENAME_LENGTH} characters`);if(!SAFE_FILENAME_PATTERN.test(filename))throw Error("Invalid filename: contains unsafe characters");if(filename.includes("/")||filename.includes("\\"))throw Error("Invalid filename: path separators not allowed");if(!filename.trim()||filename.trim()!==filename)throw Error("Invalid filename: cannot be empty or contain leading/trailing whitespace");return filename}class AutomationStatusArtifact{swarmDir;filename;currentSnapshot;constructor(swarmDir,filename="automation-status.json"){let sanitizedFilename=validateFilename(filename);this.swarmDir=swarmDir,this.filename=sanitizedFilename,this.currentSnapshot=this.load()??createEmptySnapshot("manual",{plan_sync:!1,phase_preflight:!1,config_doctor_on_startup:!1,config_doctor_autofix:!1,evidence_auto_summaries:!1,decision_drift_detection:!1})}getFilePath(){return path218.join(this.swarmDir,this.filename)}load(){let filePath=this.getFilePath();try{if(fs115.existsSync(filePath)){let content=fs115.readFileSync(filePath,"utf-8");return JSON.parse(content)}}catch{}return null}write(){let filePath=this.getFilePath();if(!fs115.existsSync(this.swarmDir))fs115.mkdirSync(this.swarmDir,{recursive:!0});fs115.writeFileSync(filePath,JSON.stringify(this.currentSnapshot,null,2),"utf-8")}getSnapshot(){return{...this.currentSnapshot}}read(){let loaded=this.load();if(loaded)this.currentSnapshot=loaded;return this.getSnapshot()}updateConfig(mode,capabilities){this.currentSnapshot={...this.currentSnapshot,mode,enabled:mode!=="manual",timestamp:Date.now(),capabilities},this.write()}updatePhase(phase){this.currentSnapshot={...this.currentSnapshot,currentPhase:phase,timestamp:Date.now()},this.write()}recordTrigger(triggeredAt,triggeredPhase,source,reason){this.currentSnapshot={...this.currentSnapshot,lastTrigger:{triggeredAt,triggeredPhase,source,reason},timestamp:Date.now()},this.write()}updatePendingActions(count){this.currentSnapshot={...this.currentSnapshot,pendingActions:count,timestamp:Date.now()},this.write()}recordOutcome(state,phase,message){this.currentSnapshot={...this.currentSnapshot,lastOutcome:{state,phase,outcomeAt:Date.now(),message:message??null},timestamp:Date.now()},this.write()}clearOutcome(){this.currentSnapshot={...this.currentSnapshot,lastOutcome:{state:"none",phase:null,outcomeAt:null,message:null},timestamp:Date.now()},this.write()}isEnabled(){return this.currentSnapshot.enabled}hasCapability(capability){return this.currentSnapshot.capabilities[capability]===!0}getGuiSummary(){let{currentSnapshot}=this,status="Disabled";if(currentSnapshot.enabled)status=currentSnapshot.mode.charAt(0).toUpperCase()+currentSnapshot.mode.slice(1);let lastTrigger=null;if(currentSnapshot.lastTrigger?.triggeredAt)lastTrigger=new Date(currentSnapshot.lastTrigger.triggeredAt).toLocaleTimeString();let outcome=null;if(currentSnapshot.lastOutcome?.state&&currentSnapshot.lastOutcome.state!=="none")outcome=currentSnapshot.lastOutcome.state;return{status,phase:currentSnapshot.currentPhase,lastTrigger,pending:currentSnapshot.pendingActions,outcome}}}var MAX_FILENAME_LENGTH=255,SAFE_FILENAME_PATTERN;var init_status_artifact=__esm(()=>{SAFE_FILENAME_PATTERN=/^[a-zA-Z0-9._-]+$/});var exports_trigger={};__export(exports_trigger,{PreflightTriggerManager:()=>PreflightTriggerManager,PhaseBoundaryTrigger:()=>PhaseBoundaryTrigger});class PhaseBoundaryTrigger{eventBus;config;lastKnownPhase=0;lastTriggeredPhase=0;constructor(eventBus,config3){this.eventBus=eventBus??getGlobalEventBus(),this.config={minCompletedTasksThreshold:config3?.minCompletedTasksThreshold??1,allowZeroTaskTrigger:config3?.allowZeroTaskTrigger??!1}}setCurrentPhase(phase){this.lastKnownPhase=phase}getCurrentPhase(){return this.lastKnownPhase}get lastTriggeredPhaseValue(){return this.lastTriggeredPhase}detectBoundary(newPhase,completedTasks,totalTasks){if(newPhase===this.lastKnownPhase)return{detected:!1,previousPhase:this.lastKnownPhase,currentPhase:newPhase,reason:"Phase unchanged",completedTaskCount:completedTasks,totalTaskCount:totalTasks};let boundaryResult={detected:!0,previousPhase:this.lastKnownPhase,currentPhase:newPhase,reason:`Phase transition from ${this.lastKnownPhase} to ${newPhase}`,completedTaskCount:completedTasks,totalTaskCount:totalTasks};return this.lastKnownPhase=newPhase,this.eventBus.publish("phase.boundary.detected",boundaryResult),boundaryResult}shouldTriggerPreflight(boundaryResult){if(this.lastTriggeredPhase===boundaryResult.currentPhase)return log("[Trigger] Preflight already triggered for phase",{phase:boundaryResult.currentPhase}),!1;let threshold=this.config.minCompletedTasksThreshold??1;if(!(this.config.allowZeroTaskTrigger||boundaryResult.completedTaskCount>=threshold))return log("[Trigger] Preflight skipped - insufficient task completion",{completed:boundaryResult.completedTaskCount,required:threshold}),!1;return!0}markTriggered(phase){this.lastTriggeredPhase=phase}reset(){this.lastKnownPhase=0,this.lastTriggeredPhase=0}}class PreflightTriggerManager{automationConfig;eventBus;trigger;requestQueue;requestCounter=0;preflightHandler=null;unsubscribe=null;unsubscribeSkipped=null;constructor(automationConfig,eventBus,triggerConfig){this.automationConfig=automationConfig,this.eventBus=eventBus??getGlobalEventBus(),this.trigger=new PhaseBoundaryTrigger(this.eventBus,triggerConfig),this.requestQueue=new AutomationQueue({maxSize:100,defaultMaxRetries:3,overflowStrategy:"evict-oldest"}),this.unsubscribeSkipped=this.eventBus.subscribe("preflight.skipped",(event)=>{let payload=event.payload;if(payload.reason==="queue_overflow"||payload.reason==="queue_enqueue_error")criticalWarn("[PreflightTrigger] preflight skipped",{reason:payload.reason,phase:payload.phase,requestId:payload.requestId,queueDepth:this.requestQueue.size()})})}isEnabled(){if(!this.automationConfig)return!1;if(!this.automationConfig.capabilities)return!1;if(this.automationConfig.mode==="manual")return!1;return this.automationConfig.capabilities.phase_preflight===!0}getMode(){if(!this.automationConfig)return"unknown";return this.automationConfig.mode??"unknown"}updatePhase(phase){this.trigger.setCurrentPhase(phase)}async checkAndTrigger(currentPhase,completedTasks,totalTasks){let phasePreflight=this.automationConfig?.capabilities?.phase_preflight,mode=this.automationConfig?.mode;if(!this.isEnabled())return log("[PreflightTrigger] Disabled via feature flags",{mode:mode??"unknown",phase_preflight:phasePreflight}),await this.eventBus.publish("preflight.skipped",{reason:"feature_disabled",mode:mode??"unknown",phase_preflight:phasePreflight}),!1;let boundaryResult=this.trigger.detectBoundary(currentPhase,completedTasks,totalTasks);if(!boundaryResult.detected)return!1;if(!this.trigger.shouldTriggerPreflight(boundaryResult))return await this.eventBus.publish("preflight.skipped",{reason:"threshold_not_met",boundary:boundaryResult}),!1;return this.triggerPreflight(boundaryResult)}async triggerPreflight(boundaryResult){let requestId=`preflight-${Date.now()}-${++this.requestCounter}`,request={id:requestId,triggeredAt:Date.now(),currentPhase:boundaryResult.currentPhase,source:"phase_boundary",reason:boundaryResult.reason,metadata:{completedTaskCount:boundaryResult.completedTaskCount,totalTaskCount:boundaryResult.totalTaskCount}};try{this.requestQueue.enqueue(request,"high")}catch(error93){log("[PreflightTrigger] Queue enqueue failed (continuing)",{requestId,phase:boundaryResult.currentPhase,error:error93 instanceof Error?error93.message:String(error93)}),await this.eventBus.publish("preflight.skipped",{reason:"queue_enqueue_error",requestId,phase:boundaryResult.currentPhase})}return this.trigger.markTriggered(boundaryResult.currentPhase),await this.eventBus.publish("preflight.requested",request),await this.eventBus.publish("preflight.triggered",{requestId,phase:boundaryResult.currentPhase,timestamp:request.triggeredAt}),log("[PreflightTrigger] Preflight triggered",{requestId,phase:boundaryResult.currentPhase,completed:boundaryResult.completedTaskCount,total:boundaryResult.totalTaskCount}),!0}getPendingRequests(){return this.requestQueue.getAll().map((item)=>item.payload)}getQueueSize(){return this.requestQueue.size()}getStats(){let mode="unknown";try{mode=this.getMode()}catch{mode="unknown"}return{enabled:this.isEnabled(),mode,currentPhase:this.trigger.getCurrentPhase(),lastTriggeredPhase:this.trigger.lastTriggeredPhaseValue,pendingRequests:this.getQueueSize()}}reset(){if(this.trigger.reset(),this.requestQueue.clear(),this.unsubscribe)this.unsubscribe(),this.unsubscribe=null;if(this.unsubscribeSkipped)this.unsubscribeSkipped(),this.unsubscribeSkipped=null}registerHandler(handler){if(this.unsubscribe)this.unsubscribe();this.preflightHandler=handler;let HANDLER_TIMEOUT_MS=120000;this.unsubscribe=this.eventBus.subscribe("preflight.requested",async(event)=>{let request=event.payload,timeoutHandle;try{if(this.preflightHandler)await Promise.race([this.preflightHandler(request),new Promise((_,reject)=>{timeoutHandle=setTimeout(()=>{reject(Error(`Preflight handler timed out after ${HANDLER_TIMEOUT_MS}ms`))},HANDLER_TIMEOUT_MS)})])}catch(error93){log("[PreflightTrigger] Handler error",{requestId:request.id,phase:request.currentPhase,errorType:error93 instanceof Error?error93.name:"unknown"})}finally{clearTimeout(timeoutHandle);let match=this.requestQueue.getAll().find((it)=>it.payload.id===request.id);if(match)this.requestQueue.complete(match.id)}}),log("[PreflightTrigger] Handler registered")}unregisterHandler(){if(this.unsubscribe)this.unsubscribe(),this.unsubscribe=null;this.preflightHandler=null,log("[PreflightTrigger] Handler unregistered")}hasHandler(){return this.preflightHandler!==null}}var init_trigger=__esm(()=>{init_utils();init_event_bus();init_queue()});function truncateWords(text,maxWords){let trimmed=text.trim();if(trimmed.length===0)return{text:trimmed,truncated:!1};let words=trimmed.split(/\s+/);if(words.length<=maxWords)return{text:trimmed,truncated:!1};return{text:`${words.slice(0,maxWords).join(" ")}…`,truncated:!0}}function capArray(items,maxItems){if(items.length<=maxItems)return{items,truncated:!1};return{items:items.slice(0,maxItems),truncated:!0}}function normalizeAgentWorkSummary(input,maxSummaryWords=MAX_AGENT_SUMMARY_WORDS){let truncated=!1,sum=truncateWords(input.summary,maxSummaryWords);truncated||=sum.truncated;let cap2=(items)=>{let r=capArray(items??[],MAX_LIST_ITEMS);return truncated||=r.truncated,r.items},candidate2={schema_version:SUMMARY_SCHEMA_VERSION,phase:input.phase,task_id:input.task_id,session_id:input.session_id,agent:input.agent,parent_agent:input.parent_agent,summary:sum.text,key_decisions:cap2(input.key_decisions),constraints_observed:cap2(input.constraints_observed),constraints_violated:cap2(input.constraints_violated),assumptions:cap2(input.assumptions),risks:cap2(input.risks),files_touched:input.files_touched?capArray(input.files_touched,50).items:void 0,evidence_refs:capArray(input.evidence_refs??[],20).items,created_at:input.created_at??new Date().toISOString(),truncated:truncated||void 0};return AgentWorkSummarySchema.parse(candidate2)}var SUMMARY_SCHEMA_VERSION="1.0.0",MAX_AGENT_SUMMARY_WORDS=100,MAX_PHASE_SUMMARY_WORDS=250,MAX_LIST_ITEMS=5,SupervisorVerdictSchema,AgentWorkSummarySchema,PhaseArchitectureSummarySchema,SupervisorFindingSchema,KnowledgeRecommendationSchema,EvidenceProvenanceSchema,ArchitectureSupervisorReportSchema;var init_schema3=__esm(()=>{init_zod();SupervisorVerdictSchema=exports_external.enum(["APPROVE","CONCERNS","REJECT"]);AgentWorkSummarySchema=exports_external.object({schema_version:exports_external.literal(SUMMARY_SCHEMA_VERSION),phase:exports_external.number().int().min(0).max(999),task_id:exports_external.string().min(1).optional(),session_id:exports_external.string().min(1),agent:exports_external.string().min(1),parent_agent:exports_external.string().min(1).optional(),summary:exports_external.string().min(1),key_decisions:exports_external.array(exports_external.string().min(1)).max(MAX_LIST_ITEMS).default([]),constraints_observed:exports_external.array(exports_external.string().min(1)).max(MAX_LIST_ITEMS).default([]),constraints_violated:exports_external.array(exports_external.string().min(1)).max(MAX_LIST_ITEMS).default([]),assumptions:exports_external.array(exports_external.string().min(1)).max(MAX_LIST_ITEMS).default([]),risks:exports_external.array(exports_external.string().min(1)).max(MAX_LIST_ITEMS).default([]),files_touched:exports_external.array(exports_external.string().min(1)).max(50).optional(),evidence_refs:exports_external.array(exports_external.string().min(1)).max(20).default([]),created_at:exports_external.string().datetime(),truncated:exports_external.boolean().optional()});PhaseArchitectureSummarySchema=exports_external.object({schema_version:exports_external.literal(SUMMARY_SCHEMA_VERSION),phase:exports_external.number().int().min(0).max(999),summary:exports_external.string().default(""),agents_seen:exports_external.array(exports_external.string().min(1)).default([]),tasks_seen:exports_external.array(exports_external.string().min(1)).default([]),key_decisions:exports_external.array(exports_external.string().min(1)).default([]),conflicts:exports_external.array(exports_external.string().min(1)).default([]),unresolved_risks:exports_external.array(exports_external.string().min(1)).default([]),constraint_violations:exports_external.array(exports_external.string().min(1)).default([]),evidence_refs:exports_external.array(exports_external.string().min(1)).default([]),created_at:exports_external.string().datetime()}),SupervisorFindingSchema=exports_external.object({severity:exports_external.enum(["low","medium","high","critical"]),category:exports_external.string().min(1),agents:exports_external.array(exports_external.string().min(1)).default([]),tasks:exports_external.array(exports_external.string().min(1)).default([]),evidence_refs:exports_external.array(exports_external.string().min(1)).default([]),description:exports_external.string().min(1),recommendation:exports_external.string().default("")}),KnowledgeRecommendationSchema=exports_external.object({lesson:exports_external.string().min(1),target_agents:exports_external.array(exports_external.string().min(1)).default([]),confidence:exports_external.number().min(0).max(1).default(0.5),evidence_refs:exports_external.array(exports_external.string().min(1)).default([])}),EvidenceProvenanceSchema=exports_external.object({agent_name:exports_external.string().min(1).optional(),session_id:exports_external.string().min(1).optional(),captured_at:exports_external.string().datetime().optional()}),ArchitectureSupervisorReportSchema=exports_external.object({schema_version:exports_external.literal(SUMMARY_SCHEMA_VERSION),phase:exports_external.number().int().min(0).max(999),verdict:SupervisorVerdictSchema,findings:exports_external.array(SupervisorFindingSchema).default([]),knowledge_recommendations:exports_external.array(KnowledgeRecommendationSchema).default([]),created_at:exports_external.string().datetime(),provenance:EvidenceProvenanceSchema.optional()})});import{existsSync as existsSync118,mkdirSync as mkdirSync65,readFileSync as readFileSync92}from"node:fs";import*as path229 from"node:path";function writeRawSidecar(absPath,bundle){mkdirSync65(path229.dirname(absPath),{recursive:!0}),atomicWriteSwarmFileSync(absPath,JSON.stringify(bundle,null,2))}async function writeAgentSummary(directory,summary){let taskId=summary.task_id??`phase-${summary.phase}-summaries`;return await saveEvidence(directory,taskId,{task_id:taskId,type:"note",timestamp:summary.created_at,agent:summary.agent,verdict:"info",summary:summary.summary,metadata:{kind:AGENT_SUMMARY_METADATA_KIND,phase:summary.phase,session_id:summary.session_id,payload:summary}}),taskId}async function listAgentSummaries(directory,filter={}){let taskIds=await listEvidenceTaskIds(directory),results=[];for(let taskId of taskIds){let loaded=await loadEvidence(directory,taskId);if(loaded.status!=="found")continue;for(let entry of loaded.bundle.entries){if(entry.type!=="note")continue;let meta3=entry.metadata;if(!meta3||meta3.kind!==AGENT_SUMMARY_METADATA_KIND)continue;if(filter.phase!==void 0&&meta3.phase!==filter.phase)continue;if(filter.session!==void 0&&meta3.session_id!==filter.session)continue;let parsed=AgentWorkSummarySchema.safeParse(meta3.payload);if(!parsed.success){warn(`Skipping malformed agent summary in task ${taskId}: ${parsed.error.issues.map((i)=>i.message).join(", ")}`);continue}results.push(parsed.data)}}return results}function writePhaseArchitectureSummary(directory,summary){let rel=path229.join("evidence",String(summary.phase),PHASE_SUMMARY_FILE),abs=validateSwarmPath(directory,rel);return writeRawSidecar(abs,summary),abs}function writeSupervisorReport(directory,report){let rel=path229.join("evidence",String(report.phase),SUPERVISOR_REPORT_FILE),abs=validateSwarmPath(directory,rel),bundle={entries:[{type:SUPERVISOR_ENTRY_TYPE,phase_number:report.phase,scope:"phase",timestamp:report.created_at,verdict:report.verdict,findings:report.findings,knowledge_recommendations:report.knowledge_recommendations,...report.provenance?{provenance:report.provenance}:{}}]};return writeRawSidecar(abs,bundle),abs}function readSupervisorReportRaw(directory,phase){let rel=path229.join("evidence",String(phase),SUPERVISOR_REPORT_FILE),abs;try{abs=validateSwarmPath(directory,rel)}catch{return null}if(!existsSync118(abs))return null;try{return JSON.parse(readFileSync92(abs,"utf-8")).entries?.find((e)=>e.type===SUPERVISOR_ENTRY_TYPE)??null}catch{return null}}var AGENT_SUMMARY_METADATA_KIND="agent_summary",PHASE_SUMMARY_FILE="phase-architecture-summary.json",SUPERVISOR_REPORT_FILE="architecture-supervisor.json",SUPERVISOR_ENTRY_TYPE="architecture-supervisor";var init_store4=__esm(()=>{init_manager2();init_utils2();init_utils();init_atomic_write();init_schema3()});var exports_aggregate={};__export(exports_aggregate,{aggregatePhaseSummary:()=>aggregatePhaseSummary});function dedupe2(values){return Array.from(new Set(values)).filter((v)=>v.trim().length>0)}function detectConflicts(summaries){let observedBy=new Map,violatedBy=new Map;for(let s of summaries){for(let c of s.constraints_observed){if(!observedBy.has(c))observedBy.set(c,new Set);observedBy.get(c)?.add(s.agent)}for(let c of s.constraints_violated){if(!violatedBy.has(c))violatedBy.set(c,new Set);violatedBy.get(c)?.add(s.agent)}}let conflicts=[];for(let[constraint,violators]of violatedBy){let observers=observedBy.get(constraint);if(observers&&observers.size>0){let obs=Array.from(observers).sort().join(", "),vio=Array.from(violators).sort().join(", ");conflicts.push(`Constraint "${constraint}" observed by [${obs}] but violated by [${vio}]`)}}return conflicts.sort()}async function aggregatePhaseSummary(directory,phase,options={}){let summaries=await listAgentSummaries(directory,{phase});if(summaries.length===0)return null;let agentsSeen=dedupe2(summaries.map((s)=>s.agent)).sort(),tasksSeen=dedupe2(summaries.map((s)=>s.task_id).filter((t)=>Boolean(t))).sort(),keyDecisions=dedupe2(summaries.flatMap((s)=>s.key_decisions)),unresolvedRisks=dedupe2(summaries.flatMap((s)=>s.risks)),constraintViolations=dedupe2(summaries.flatMap((s)=>s.constraints_violated)),evidenceRefs=dedupe2(summaries.flatMap((s)=>s.evidence_refs)),conflicts=detectConflicts(summaries),headline=`Phase ${phase}: ${summaries.length} agent summary(ies) across ${tasksSeen.length} task(s); ${constraintViolations.length} constraint violation(s), ${conflicts.length} cross-agent conflict(s).`,cap2=options.maxPhaseSummaryWords??MAX_PHASE_SUMMARY_WORDS,summaryText=truncateWords(headline,cap2).text,phaseSummary={schema_version:SUMMARY_SCHEMA_VERSION,phase,summary:summaryText,agents_seen:agentsSeen,tasks_seen:tasksSeen,key_decisions:keyDecisions,conflicts,unresolved_risks:unresolvedRisks,constraint_violations:constraintViolations,evidence_refs:evidenceRefs,created_at:options.now?.()??new Date().toISOString()};return writePhaseArchitectureSummary(directory,phaseSummary),phaseSummary}var init_aggregate=__esm(()=>{init_schema3();init_store4()});var exports_preflight_integration={};__export(exports_preflight_integration,{runManualPreflight:()=>runManualPreflight,createPreflightIntegration:()=>createPreflightIntegration});function createPreflightIntegration(config3){let{automationConfig,directory,swarmDir,preflightConfig,updateStatusArtifact=!0}=config3;if(automationConfig?.capabilities?.phase_preflight!==!0)throw Error("Preflight is not enabled in automation capabilities. Set automation.capabilities.phase_preflight to true.");let manager=new PreflightTriggerManager(automationConfig,void 0,{directory}),statusArtifact=null;if(updateStatusArtifact&&swarmDir)statusArtifact=new AutomationStatusArtifact(swarmDir);let preflightHandler=async(request)=>{log("[PreflightIntegration] Handling preflight request",{requestId:request.id,phase:request.currentPhase,source:request.source});let report=await runPreflight(directory,request.currentPhase,preflightConfig);if(statusArtifact){let state=report.overall==="pass"?"success":"failure";statusArtifact.recordOutcome(state,request.currentPhase,report.message),log("[PreflightIntegration] Status artifact updated",{state,phase:request.currentPhase,message:report.message})}log("[PreflightIntegration] Preflight complete",{requestId:request.id,overall:report.overall,message:report.message,durationMs:report.totalDurationMs})};return manager.registerHandler(preflightHandler),{manager,cleanup:()=>{manager.unregisterHandler()}}}async function runManualPreflight(directory,phase,config3){return runPreflight(directory,phase,config3)}var init_preflight_integration=__esm(()=>{init_status_artifact();init_trigger();init_preflight_service();init_logger()});var exports_doc_scan={};__export(exports_doc_scan,{scanDocIndex:()=>scanDocIndex,extractDocConstraints:()=>extractDocConstraints,doc_scan:()=>doc_scan,doc_extract:()=>doc_extract});import*as crypto14 from"node:crypto";import*as fs132 from"node:fs";import{mkdir as mkdir48,readdir as readdir17,readFile as readFile48,realpath as realpath11,stat as stat20,writeFile as writeFile26}from"node:fs/promises";import*as path237 from"node:path";function normalizeSeparators(filePath){return filePath.replace(/\\/g,"/")}function matchesDocPattern(filePath,patterns){let normalizedPath2=normalizeSeparators(filePath),basename33=path237.basename(filePath);for(let pattern of patterns){if(!pattern.includes("/")&&!pattern.includes("\\")){if(basename33===pattern)return!0;continue}if(pattern.startsWith("**/")){let filenamePattern=pattern.slice(3);if(basename33===filenamePattern)return!0;continue}let dirPrefix=normalizeSeparators(pattern).replace(/\/\*\*.*$/,"").replace(/\/\*.*$/,"");if(normalizedPath2.startsWith(`${dirPrefix}/`)||normalizedPath2===dirPrefix)return!0}return!1}function extractTitleAndSummary(content,filename){let lines=content.split(`
6316
6317
  `),title=filename,summary="",foundTitle=!1,potentialSummaryLines=[];for(let i=0;i<lines.length&&i<READ_LINES_LIMIT;i++){let line=lines[i].trim();if(!foundTitle&&line.startsWith("# ")){title=line.slice(2).trim(),foundTitle=!0;continue}if(line&&!line.startsWith("#"))potentialSummaryLines.push(line)}for(let line of potentialSummaryLines)if(summary+=(summary?" ":"")+line,summary.length>=MAX_SUMMARY_LENGTH)break;if(summary.length>MAX_SUMMARY_LENGTH)summary=`${summary.slice(0,MAX_SUMMARY_LENGTH-3)}...`;return{title,summary}}function stripMarkdown(text){return text.replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/\*\*([^*]+)\*\*/g,"$1").replace(/`([^`]+)`/g,"$1").replace(/^\s*[-*•]\s+/gm,"").replace(/^\s*\d+\.\s+/gm,"").trim()}async function scanDocIndex(directory){let manifestPath2=path237.join(directory,".swarm","doc-manifest.json"),defaultPatterns=DocsConfigSchema.parse({}).doc_patterns,extraPatterns=["ARCHITECTURE.md","CLAUDE.md","AGENTS.md",".github/*.md","doc/**/*.md"],allPatterns=[...defaultPatterns,...extraPatterns];try{let manifestContent=await readFile48(manifestPath2,"utf-8"),existingManifest=JSON.parse(manifestContent);if(existingManifest.schema_version===1&&existingManifest.files){let cacheValid=!0;for(let file3 of existingManifest.files)try{let fullPath=path237.join(directory,file3.path);if(fs132.statSync(fullPath).mtimeMs>file3.mtime){cacheValid=!1;break}}catch{cacheValid=!1;break}if(cacheValid)return{manifest:existingManifest,cached:!0}}}catch{}let resolvedDirectory=await realpath11(directory).catch(()=>directory),discoveredFiles=[],rootReadable=!1,truncated=!1,walkDir2=async(dir)=>{let entries;try{if(entries=await readdir17(dir,{withFileTypes:!0}),dir===directory)rootReadable=!0}catch{return}for(let entry of entries){let isDir=entry.isDirectory(),isFile=entry.isFile();if(entry.isSymbolicLink())try{let symlinkPath=path237.join(dir,entry.name),resolved=await realpath11(symlinkPath),rel=path237.relative(resolvedDirectory,resolved);if(rel.startsWith("..")||path237.isAbsolute(rel))continue;isFile=(await stat20(symlinkPath)).isFile()}catch{continue}if(isDir){if(!SKIP_DIRECTORIES3.has(entry.name))await walkDir2(path237.join(dir,entry.name));continue}if(!isFile)continue;let fullPath=path237.join(dir,entry.name),relPath=normalizeSeparators(path237.relative(directory,fullPath)),skipThisFile=!1;for(let pattern of SKIP_PATTERNS)if(pattern.test(relPath)){skipThisFile=!0;break}if(skipThisFile)continue;if(!matchesDocPattern(relPath,allPatterns))continue;if(discoveredFiles.length>=MAX_INDEXED_FILES){truncated=!0;return}let fileStat;try{fileStat=await stat20(fullPath)}catch{continue}let content;try{content=await readFile48(fullPath,"utf-8")}catch{continue}let{title,summary}=extractTitleAndSummary(content,path237.basename(relPath));discoveredFiles.push({path:relPath,title,summary,lines:content.split(`
6317
6318
  `).length,mtime:fileStat.mtimeMs})}};if(await walkDir2(directory),!rootReadable)return{manifest:{schema_version:1,scanned_at:new Date().toISOString(),files:[]},cached:!1};if(discoveredFiles.sort((a,b)=>a.path.toLowerCase().localeCompare(b.path.toLowerCase())),discoveredFiles.length>MAX_INDEXED_FILES)discoveredFiles.splice(MAX_INDEXED_FILES),truncated=!0;if(truncated&&discoveredFiles.length>0)discoveredFiles[0].summary=`[Warning: ${MAX_INDEXED_FILES}+ docs found, listing first ${MAX_INDEXED_FILES}] `+discoveredFiles[0].summary;let manifest={schema_version:1,scanned_at:new Date().toISOString(),files:discoveredFiles};try{await mkdir48(path237.dirname(manifestPath2),{recursive:!0}),await writeFile26(manifestPath2,JSON.stringify(manifest,null,2),"utf-8")}catch{}return{manifest,cached:!1}}function isConstraintLine(line){let upperLine=line.toUpperCase();for(let pattern of CONSTRAINT_PATTERNS)if(pattern.test(upperLine))return!0;if(/^\s*[-*•]/.test(line)&&ACTION_WORDS.test(line))return!0;return!1}function extractConstraintsFromContent(content){let lines=content.split(`
6318
- `),constraints=[];for(let line of lines){if(constraints.length>=MAX_CONSTRAINTS_PER_DOC)break;let trimmed=line.trim();if(!trimmed)continue;if(isConstraintLine(trimmed)){let cleaned=stripMarkdown(trimmed),len=cleaned.length;if(len>=MIN_LESSON_LENGTH&&len<=MAX_CONSTRAINT_LENGTH)constraints.push(cleaned)}}return constraints}async function extractDocConstraints(directory,taskFiles,taskDescription){let manifestPath2=path237.join(directory,".swarm","doc-manifest.json"),manifest;try{let content=await readFile48(manifestPath2,"utf-8");manifest=JSON.parse(content)}catch{manifest=(await scanDocIndex(directory)).manifest}let knowledgePath=resolveSwarmKnowledgePath(directory),existingEntries=await readKnowledge(knowledgePath),taskContext=[...taskFiles,taskDescription].join(" "),taskBigrams=wordBigrams(normalize6(taskContext)),extractedCount=0,skippedCount=0,details=[];for(let docFile of manifest.files){let docContext=`${docFile.path} ${docFile.title} ${docFile.summary}`,docBigrams=wordBigrams(normalize6(docContext)),score=jaccardBigram(taskBigrams,docBigrams);if(score<=RELEVANCE_THRESHOLD){skippedCount++;continue}let fullContent;try{fullContent=await readFile48(path237.join(directory,docFile.path),"utf-8")}catch{skippedCount++;continue}let constraints=extractConstraintsFromContent(fullContent);if(constraints.length===0){skippedCount++;continue}let docDetails={path:docFile.path,score,constraints:[]};for(let constraint of constraints)if(!findNearDuplicate(constraint,existingEntries,DEDUP_THRESHOLD2)){let entry={id:crypto14.randomUUID(),tier:"swarm",lesson:constraint,category:"architecture",tags:["doc-scan",path237.basename(docFile.path)],scope:"global",confidence:0.5,status:"candidate",confirmed_by:[],project_name:"",retrieval_outcomes:{applied_count:0,succeeded_after_count:0,failed_after_count:0},schema_version:1,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),auto_generated:!0,hive_eligible:!1};await appendKnowledge(knowledgePath,entry),existingEntries.push(entry),extractedCount++,docDetails.constraints.push(constraint)}if(docDetails.constraints.length>0)details.push(docDetails);else skippedCount++}return{extracted:extractedCount,skipped:skippedCount,details}}var SKIP_DIRECTORIES3,SKIP_PATTERNS,MAX_SUMMARY_LENGTH=200,MAX_INDEXED_FILES=100,READ_LINES_LIMIT=30,MIN_LESSON_LENGTH=15,MAX_CONSTRAINTS_PER_DOC=5,MAX_CONSTRAINT_LENGTH=200,RELEVANCE_THRESHOLD=0.1,DEDUP_THRESHOLD2=0.6,CONSTRAINT_PATTERNS,ACTION_WORDS,doc_scan,doc_extract;var init_doc_scan=__esm(()=>{init_zod();init_schema();init_knowledge_store();init_create_tool();SKIP_DIRECTORIES3=new Set(["node_modules",".git",".swarm","dist","build",".next","vendor","bazel-out","bazel-bin","bazel-genfiles","bazel-testlogs",".gradle","target"]),SKIP_PATTERNS=[/\.test\./,/\.spec\./,/\.d\.ts$/];CONSTRAINT_PATTERNS=[/\bMUST\b/,/\bMUST NOT\b/,/\bSHOULD\b/,/\bSHOULD NOT\b/,/\bDO NOT\b/,/\bALWAYS\b/,/\bNEVER\b/,/\bREQUIRED\b/],ACTION_WORDS=/\b(must|should|don't|avoid|ensure|use|follow)\b/i;doc_scan=createSwarmTool({description:"Scan project documentation files and build an index manifest. Caches results in .swarm/doc-manifest.json for fast subsequent scans.",args:{force:exports_external.boolean().optional().describe("Force re-scan even if cache is valid")},execute:async(args2,directory)=>{let force=!1;try{if(args2&&typeof args2==="object"){if(args2.force===!0)force=!0}}catch{}if(force){let manifestPath2=path237.join(directory,".swarm","doc-manifest.json");try{fs132.unlinkSync(manifestPath2)}catch{}}let{manifest,cached:cached3}=await scanDocIndex(directory);return JSON.stringify({success:!0,files_count:manifest.files.length,cached:cached3,manifest},null,2)}}),doc_extract=createSwarmTool({description:"Extract actionable constraints from project documentation relevant to the current task. Scans docs via doc-manifest, scores relevance via Jaccard bigram similarity, and stores non-duplicate constraints in .swarm/knowledge.jsonl.",args:{task_files:exports_external.array(exports_external.string()).describe("List of file paths involved in the current task"),task_description:exports_external.string().describe("Description of the current task")},execute:async(args2,directory)=>{let taskFiles=[],taskDescription="";try{if(args2&&typeof args2==="object"){let obj=args2;if(Array.isArray(obj.task_files))taskFiles=obj.task_files.filter((f)=>typeof f==="string");if(typeof obj.task_description==="string")taskDescription=obj.task_description}}catch{}if(taskFiles.length===0&&!taskDescription)return JSON.stringify({success:!1,error:"task_files or task_description is required"});let result=await extractDocConstraints(directory,taskFiles,taskDescription);return JSON.stringify({success:!0,...result},null,2)}})});import{existsSync as existsSync122}from"node:fs";import{readFile as readFile49}from"node:fs/promises";import*as path238 from"node:path";function inferCategoriesFromPhase(phaseDescription){let lower=phaseDescription.toLowerCase(),patterns=[{pattern:/\b(?:test|qa|quality|verification|validation)\b/,categories:["testing","debugging"]},{pattern:/\b(?:implement|build|develop|coding|code)\b/,categories:["tooling","architecture","debugging"]},{pattern:/\b(?:integrat|deploy|ci|cd|release|publish)\b/,categories:["integration","tooling","performance"]},{pattern:/\b(?:plan|design|architect|spec|requirement)\b/,categories:["architecture","process"]},{pattern:/\b(?:review|refactor|cleanup|polish|optimi)\b/,categories:["performance","architecture","process"]},{pattern:/\b(?:secur|audit|harden|compliance)\b/,categories:["security","testing"]},{pattern:/\b(?:setup|config|scaffold|init|bootstrap)\b/,categories:["tooling","other"]},{pattern:/\b(?:doc|readme|changelog)\b/,categories:["process","tooling"]}];for(let{pattern,categories}of patterns)if(pattern.test(lower))return categories;return["process","tooling"]}async function transactShownFile(shownFile,mutate){return transactFile(shownFile,async(filePath)=>{if(!existsSync122(filePath))return{};try{let content=await readFile49(filePath,"utf-8");return JSON.parse(content)}catch{return{}}},async(filePath,data)=>{await atomicWriteFile(filePath,JSON.stringify(data,null,2))},mutate)}async function recordLessonsShown(directory,lessonIds,currentPhase){if(lessonIds.length===0)return;let shownFile=path238.join(directory,".swarm",".knowledge-shown.json");try{let phaseMatch=/^Phase\s+(\d+)/i.exec(currentPhase),canonicalKey=phaseMatch?`Phase ${phaseMatch[1]}`:currentPhase;if(!await transactShownFile(shownFile,(shownData)=>{let existing=new Set(shownData[canonicalKey]??[]);for(let id of lessonIds)existing.add(id);return shownData[canonicalKey]=[...existing],shownData}))warn("[swarm] Knowledge: failed to record shown lessons")}catch{warn("[swarm] Knowledge: failed to record shown lessons")}}async function readMergedKnowledge(directory,config3,context,opts){let swarmPath3=resolveSwarmKnowledgePath(directory),swarmEntries=await readKnowledge(swarmPath3),hiveEntries=[];if(config3.hive_enabled!==!1){let hivePath=resolveHiveKnowledgePath2();hiveEntries=await readKnowledge(hivePath)}let seenLessons=new Set,merged=[];for(let entry of hiveEntries){let normalized=normalize6(entry.lesson);seenLessons.add(normalized),merged.push({...entry,relevanceScore:{category:0,confidence:0,keywords:0},finalScore:0})}for(let entry of swarmEntries){let normalized=normalize6(entry.lesson);if(seenLessons.has(normalized))continue;let swarmBigrams=wordBigrams(normalized);if(hiveEntries.some((hiveEntry)=>jaccardBigram(swarmBigrams,wordBigrams(normalize6(hiveEntry.lesson)))>=JACCARD_THRESHOLD2))continue;if(merged.some((m)=>m.tier==="swarm"&&jaccardBigram(swarmBigrams,wordBigrams(normalize6(m.lesson)))>=JACCARD_THRESHOLD2))continue;seenLessons.add(normalized),merged.push({...entry,relevanceScore:{category:0,confidence:0,keywords:0},finalScore:0})}let retractionRecords=await readRetractionRecords(directory),suppressedLessons=new Set(retractionRecords.map((record3)=>record3.normalized_lesson).filter((value)=>typeof value==="string"&&value.length>0)),scopeFilter=config3.scope_filter??["global"],ranked=merged.filter((entry)=>(opts?.skipScopeFilter||scopeFilter.some((pattern)=>(entry.scope??"global")===pattern))&&isActiveStatus(entry.status)&&!suppressedLessons.has(normalize6(entry.lesson))).map((entry)=>{let categoryScore=0;if(context?.currentPhase){if(inferCategoriesFromPhase(context.currentPhase).includes(entry.category))categoryScore=1;else if(entry.category==="process")categoryScore=0.5}else categoryScore=0.5;let confidenceScore=entry.confidence,keywordsScore=0;if(context?.techStack&&entry.tags.length>0){let matchingTags=entry.tags.filter((t)=>context.techStack.some((s)=>t.toLowerCase().includes(s.toLowerCase())||s.toLowerCase().includes(t.toLowerCase()))).length;keywordsScore=Math.min(matchingTags/Math.max(entry.tags.length,1),1)}else if(entry.tags.length===0)keywordsScore=0.5;let tierBoost=0,isSameProject=!1;if(entry.tier==="hive"&&"source_project"in entry){let sourceProject=entry.source_project;isSameProject=!!(context?.projectName&&sourceProject===context.projectName),tierBoost=HIVE_TIER_BOOST}let sameProjectPenalty=isSameProject?DEFAULT_SAME_PROJECT_PENALTY:0,finalScore=categoryScore*0.4+confidenceScore*0.35+keywordsScore*0.25+tierBoost+sameProjectPenalty;return{...entry,relevanceScore:{category:categoryScore,confidence:confidenceScore,keywords:keywordsScore},finalScore:Math.min(Math.max(finalScore,0),1)}});ranked.sort((a,b)=>{let scoreDiff=b.finalScore-a.finalScore;if(Math.abs(scoreDiff)>0.001)return scoreDiff;let dateA=new Date(a.created_at).getTime();return new Date(b.created_at).getTime()-dateA});let maxInject=config3.max_inject_count??5;return ranked.slice(0,maxInject)}async function updateRetrievalOutcome(directory,phaseInfo,phaseSucceeded){let shownFile=path238.join(directory,".swarm",".knowledge-shown.json");try{if(!existsSync122(shownFile))return;let shownIds;try{let content=await readFile49(shownFile,"utf-8");shownIds=JSON.parse(content)[phaseInfo]}catch{return}if(!shownIds||shownIds.length===0)return;let outcome=phaseSucceeded?"success":"failure",evidenceSummary=`${phaseInfo} ${phaseSucceeded?"succeeded":"failed"} after entry was shown`;await transactShownFile(shownFile,(data)=>{return delete data[phaseInfo],data});for(let id of shownIds)await _internals182.recordKnowledgeEvent(directory,{type:"outcome",knowledge_id:id,phase:phaseInfo,outcome,evidence_summary:evidenceSummary})}catch{warn("[swarm] Knowledge: failed to update retrieval outcomes")}}function lc(s){return(s??"").toLowerCase()}function anyMatch(haystack,needles){if(needles.length===0)return!1;let hay=haystack.map(lc);return needles.some((n)=>hay.some((h)=>h.includes(lc(n))))}function tokenizeContext(ctx){let parts=[];if(ctx.taskTitle)parts.push(ctx.taskTitle);if(ctx.taskDescription)parts.push(ctx.taskDescription);if(ctx.lastUserMessage)parts.push(ctx.lastUserMessage);if(ctx.currentAction)parts.push(ctx.currentAction);if(ctx.currentTool)parts.push(ctx.currentTool);if(ctx.targetAgent)parts.push(ctx.targetAgent);if(ctx.declaredScope)parts.push(ctx.declaredScope);if(ctx.recentReviewerFailures)parts.push(...ctx.recentReviewerFailures);if(ctx.recentTestFailures)parts.push(...ctx.recentTestFailures);if(ctx.recentToolErrors)parts.push(...ctx.recentToolErrors);if(ctx.planConstraints)parts.push(...ctx.planConstraints);if(ctx.filePaths)parts.push(...ctx.filePaths);return parts.map(lc)}function scoreDirectiveAgainstContext(entry,ctx){let haystack=tokenizeContext(ctx),triggerHit=entry.triggers&&entry.triggers.length>0?anyMatch(haystack,entry.triggers):!1,actionHit=entry.applies_to_tools&&entry.applies_to_tools.length>0?entry.applies_to_tools.map(lc).some((t)=>t===lc(ctx.currentTool)||t===lc(ctx.currentAction)):!1,agentHit=entry.applies_to_agents&&entry.applies_to_agents.length>0?entry.applies_to_agents.map(lc).some((a)=>a===lc(ctx.targetAgent)):!1,score=0;if(triggerHit)score+=0.5;if(actionHit)score+=0.35;if(agentHit)score+=0.25;if(entry.directive_priority==="critical")score+=0.4;else if(entry.directive_priority==="high")score+=0.2;else if(entry.directive_priority==="medium")score+=0.1;return{triggerHit,actionHit,agentHit,score:Math.min(1,score)}}var JACCARD_THRESHOLD2=0.6,HIVE_TIER_BOOST=0.05,DEFAULT_SAME_PROJECT_PENALTY=-0.05,_internals182;var init_knowledge_reader=__esm(()=>{init_task_file();init_logger();init_knowledge_events();init_knowledge_store();init_knowledge_types();_internals182={readMergedKnowledge,updateRetrievalOutcome,scoreDirectiveAgainstContext,transactShownFile,recordKnowledgeEvent,recordLessonsShown}});function entryText(e){return`${e.lesson} ${e.tags.join(" ")} ${e.category}`}function entryAgePhases(e){let cb=e.confirmed_by;if(!Array.isArray(cb)||cb.length===0)return 0;let phases=new Set;for(let c of cb)if(typeof c?.phase_number==="number")phases.add(c.phase_number);return phases.size>0?phases.size:cb.length}function clampLambda(v){if(typeof v!=="number"||Number.isNaN(v))return 0.5;return Math.min(1,Math.max(0,v))}function mmrRerank(pool,pinned,max,lambda){if(pool.length===0)return[];let bigrams=new Map,bg=(e)=>{let s=bigrams.get(e.id);if(!s)s=wordBigrams(normalize6(e.lesson??"")),bigrams.set(e.id,s);return s},selected=[...pinned],candidates=[...pool],out=[];while(selected.length<max&&candidates.length>0){let bestIdx=-1,bestScore=Number.NEGATIVE_INFINITY,best=null;for(let i=0;i<candidates.length;i++){let c=candidates[i],maxSim=0;for(let s of selected){let sim=jaccardBigram(bg(c),bg(s));if(sim>maxSim)maxSim=sim}let score=lambda*c.finalScore-(1-lambda)*maxSim;if(score>bestScore+0.000000001||Math.abs(score-bestScore)<=0.000000001&&best!==null&&tieBreak(c,best)<0)bestScore=score,bestIdx=i,best=c}if(bestIdx<0||best===null)break;out.push(best),selected.push(best),candidates.splice(bestIdx,1)}return out}function tieBreak(a,b){if(Math.abs(a.finalScore-b.finalScore)>0.000000001)return b.finalScore-a.finalScore;let at=new Date(a.created_at).getTime(),bt=new Date(b.created_at).getTime();if(at!==bt)return bt-at;return a.id<b.id?-1:a.id>b.id?1:0}function statusBoost(status){if(status==="promoted")return 0.15;if(status==="established")return 0.1;return 0}async function searchKnowledge(params){let{directory,config:config3,query,context,mode,agent="unknown",sessionId="unknown",tier="all",emitEvent=!1,applyScopeFilter=!0,forceReadHive=!1,applyRoleScope=!0}=params,traceId=newTraceId2(),max=params.maxResults??config3.max_inject_count??5,results=[],synonymTokens=[],synonymTrace={};try{let mergeConfig={...config3,hive_enabled:tier==="swarm"?!1:forceReadHive?!0:config3.hive_enabled,max_inject_count:Math.max(20,max)},projected={projectName:context?.projectName??"unknown",currentPhase:context?.currentPhase??"",techStack:context?.techStack,recentErrors:[...context?.recentReviewerFailures??[],...context?.recentTestFailures??[],...context?.recentToolErrors??[]]},candidates=await readMergedKnowledge(directory,mergeConfig,projected,{skipScopeFilter:!applyScopeFilter}),counterRollups=await readAuthoritativeKnowledgeCounterRollups(directory);candidates=candidates.filter((e)=>{if(!isActiveStatus(e.status))return!1;if(tier==="hive"&&e.tier!=="hive")return!1;return!0});let role=stripKnownSwarmPrefix(agent).toLowerCase();if(applyRoleScope&&role&&role!=="unknown")candidates=candidates.filter((e)=>{if(!e.applies_to_agents||e.applies_to_agents.length===0)return!0;if(role==="architect")return!0;return e.applies_to_agents.map((a)=>stripKnownSwarmPrefix(a).toLowerCase()).includes(role)});let queryText=(query??"").trim(),queryBigrams=queryText?wordBigrams(normalize6(queryText)):null,hasQuery=queryBigrams!==null,textWeight=hasQuery?TEXT_WEIGHT:0,metaWeight=hasQuery?META_WEIGHT:1,compositeRaw=[queryText,context?.taskTitle,context?.taskDescription,context?.lastUserMessage,context?.currentAction,...context?.recentReviewerFailures??[],...context?.recentTestFailures??[],...context?.recentToolErrors??[]].filter((s)=>typeof s==="string"&&s.length>0).join(" "),compositeNorm=normalize6(compositeRaw),hasComposite=compositeNorm.length>0;try{if(hasComposite){let synMap=await readSynonymMap(directory,config3.retrieval?.synonym_map_max_pairs),synIndex=buildSynonymIndex(synMap,config3.retrieval?.synonym_min_cooccurrence),baseTokens=compositeNorm.split(" ").filter(Boolean);synonymTokens=expandTokens(synIndex,baseTokens)}}catch{synonymTokens=[]}let minConf=typeof config3.directive_min_confidence==="number"?config3.directive_min_confidence:DIRECTIVE_BOOST_MIN_CONFIDENCE,scored=candidates.map((entry)=>{let retrievalOutcomes=effectiveRetrievalOutcomes(entry.retrieval_outcomes,counterRollups.get(entry.id)),textScore=queryBigrams?jaccardBigram(queryBigrams,wordBigrams(normalize6(entryText(entry)))):0,metaScore=entry.finalScore,ds=context?scoreDirectiveAgainstContext(entry,context):{triggerHit:!1,actionHit:!1,agentHit:!1,score:0},confBoost=context&&entry.confidence>=minConf&&(ds.actionHit||ds.agentHit)?0.25:0,generatedSkillBoost=entry.generated_skill_path&&entry.status!=="archived"?0.05:0,outcomeBoost=computeOutcomeSignal(retrievalOutcomes)*OUTCOME_RANK_WEIGHT,coldStartBonus=(retrievalOutcomes.applied_explicit_count??0)===0&&entryAgePhases(entry)<(config3.retrieval?.cold_start_max_age_phases??DEFAULT_COLD_START_MAX_AGE_PHASES)?config3.retrieval?.cold_start_bonus??DEFAULT_COLD_START_BONUS:0,synonymBoost=0;if(synonymTokens.length>0){let entryHay=normalize6(entryText(entry)),matched=[];for(let t of synonymTokens)if(t.length>0&&entryHay.includes(t))matched.push(t);if(matched.length>0)synonymBoost=SYNONYM_TEXT_BOOST,synonymTrace[entry.id]=matched}let triggerRecallBoost=!ds.triggerHit&&hasComposite&&Array.isArray(entry.triggers)&&entry.triggers.some((tr)=>{let n=normalize6(tr);return n.length>=TRIGGER_RECALL_MIN_LEN&&compositeNorm.includes(n)})?TRIGGER_RECALL_BOOST:0,finalScore=Math.min(1,Math.max(0,textWeight*textScore+metaWeight*metaScore+ds.score+confBoost+generatedSkillBoost+outcomeBoost+coldStartBonus+synonymBoost+triggerRecallBoost+(hasQuery&&!entry.confidence_floor_demoted?statusBoost(entry.status):0))),statusScoreBoost=hasQuery&&!entry.confidence_floor_demoted?statusBoost(entry.status):0,isCritical=entry.directive_priority==="critical"&&(ds.triggerHit||ds.actionHit||ds.agentHit),isForceHive=forceReadHive&&entry.tier==="hive";return{...entry,retrieval_outcomes:retrievalOutcomes,finalScore,coldStartBoost:coldStartBonus,score_breakdown:{text_score:textScore,metadata_score:metaScore,directive_score:ds.score,confidence_boost:confBoost,generated_skill_boost:generatedSkillBoost,outcome_boost:outcomeBoost,cold_start_boost:coldStartBonus,synonym_boost:synonymBoost,trigger_recall_boost:triggerRecallBoost,status_boost:statusScoreBoost,final_score:finalScore,...synonymTrace[entry.id]?{synonym_matches:synonymTrace[entry.id]}:{}},__critical:isCritical,__forceHive:isForceHive}});scored.sort((a,b)=>{let diff=b.finalScore-a.finalScore;if(Math.abs(diff)>0.001)return diff;return new Date(b.created_at).getTime()-new Date(a.created_at).getTime()});let top=[],seen=new Set;for(let e of scored){if(top.length>=max)break;if(e.__critical&&!seen.has(e.id))top.push(e),seen.add(e.id)}for(let e of scored){if(top.length>=max)break;if(e.__forceHive&&!seen.has(e.id))top.push(e),seen.add(e.id)}let lambda=clampLambda(config3.retrieval?.mmr_lambda),remaining=scored.filter((e)=>!seen.has(e.id)),selected=mmrRerank(remaining,top,max,lambda);for(let e of selected){if(top.length>=max)break;if(!seen.has(e.id))top.push(e),seen.add(e.id)}results=top.map(({__critical:_c,__forceHive:_f,...rest})=>rest)}catch(err){warn(`[search-knowledge] retrieval failed: ${err instanceof Error?err.message:String(err)}`),results=[]}if(emitEvent){let ranks={},scores={};results.forEach((e,idx)=>{ranks[e.id]=idx+1,scores[e.id]=e.finalScore});let synonymBreakdown={};for(let e of results)if(synonymTrace[e.id])synonymBreakdown[e.id]=synonymTrace[e.id];let scoreBreakdown=synonymTokens.length>0?{synonyms_expanded:synonymTokens,synonym_matches:synonymBreakdown}:void 0;await recordKnowledgeEvent(directory,{type:"retrieved",trace_id:traceId,session_id:sessionId,phase:context?.currentPhase,task_id:context?.taskId,agent,query:query??context?.lastUserMessage??context?.currentPhase??"",retrieval_mode:mode,result_ids:results.map((e)=>e.id),ranks,scores,...scoreBreakdown?{score_breakdown:scoreBreakdown}:{}})}return{trace_id:traceId,results}}var TEXT_WEIGHT=0.6,META_WEIGHT=0.4,DIRECTIVE_BOOST_MIN_CONFIDENCE=0.75,SYNONYM_TEXT_BOOST=0.15,TRIGGER_RECALL_BOOST=0.3,TRIGGER_RECALL_MIN_LEN=3,DEFAULT_COLD_START_BONUS=0.08,DEFAULT_COLD_START_MAX_AGE_PHASES=3,OUTCOME_RANK_WEIGHT=0.1;var init_search_knowledge=__esm(()=>{init_schema();init_synonym_map();init_logger();init_knowledge_events();init_knowledge_reader();init_knowledge_store();init_knowledge_types()});var exports_knowledge_recall={};__export(exports_knowledge_recall,{knowledge_recall:()=>knowledge_recall,_internals:()=>_internals183});var knowledge_recall,_internals183;var init_knowledge_recall=__esm(()=>{init_zod();init_config();init_schema();init_knowledge_events();init_knowledge_receipt_ledger();init_knowledge_types();init_search_knowledge();init_knowledge_diagnostics();init_logger();init_create_tool();knowledge_recall=createSwarmTool({allowWorkingDirectoryOverride:!0,description:"Performs semantic natural-language search across the knowledge base for relevant past decisions, patterns, and lessons learned. Returns ranked results via the unified hybrid retrieval service and a trace_id for knowledge_receipt. This is the tool to use when the user has a QUESTION about what the knowledge base contains. For structured filter-based retrieval (by category, status, or score), use `knowledge_query` instead.",args:{query:exports_external.string().min(3).describe("Natural language search query"),top_n:exports_external.number().int().min(1).max(20).optional().describe("Maximum results to return (default: 5)"),tier:exports_external.enum(["all","swarm","hive"]).optional().describe("Knowledge tier to search (default: 'all')"),debug:exports_external.boolean().optional().describe("Include path/version/health debug metadata in the response"),repair_re_evaluation:exports_external.object({repair_id:exports_external.string().uuid(),phase:exports_external.string().min(1).max(256),task_id:exports_external.string().min(1).max(256).optional(),scope_complete:exports_external.literal(!0)}).optional().describe("Architect-only explicit completion of a repaired receipt scope. The query must comprehensively re-evaluate the exact affected phase/session scope.")},execute:async(args2,directory,ctx)=>{let queryInput,topNInput,tierInput,debugInput,repairInput;try{if(args2&&typeof args2==="object"){let obj=args2;queryInput=obj.query,topNInput=obj.top_n,tierInput=obj.tier,debugInput=obj.debug,repairInput=obj.repair_re_evaluation}}catch{}let wantDebug=debugInput===!0,repairReevaluation;if(repairInput!==void 0){if(stripKnownSwarmPrefix(ctx?.agent??"")!=="architect"||typeof repairInput!=="object"||repairInput===null)return JSON.stringify({results:[],total:0,unverifiable:!0,code:"RECEIPT_REEVALUATION_ARCHITECT_ONLY",error:"Only the architect may complete an explicit receipt repair re-evaluation."});let candidate2=repairInput;if(typeof candidate2.repair_id!=="string"||!candidate2.repair_id||typeof candidate2.phase!=="string"||!candidate2.phase||candidate2.scope_complete!==!0||candidate2.task_id!==void 0&&typeof candidate2.task_id!=="string")return JSON.stringify({results:[],total:0,unverifiable:!0,code:"RECEIPT_REEVALUATION_PROOF_INVALID",error:"Explicit re-evaluation requires repair_id, exact phase, and scope_complete=true."});repairReevaluation={repair_id:candidate2.repair_id,phase:candidate2.phase,scope_complete:!0,...typeof candidate2.task_id==="string"?{task_id:candidate2.task_id}:{}}}if(typeof queryInput!=="string"||queryInput.length<3)return JSON.stringify({results:[],total:0,error:"query must be a string with at least 3 characters"});let topN=5;if(typeof topNInput==="number"&&Number.isInteger(topNInput))topN=Math.max(1,Math.min(20,topNInput));let tier="all";if(tierInput==="swarm"||tierInput==="hive")tier=tierInput;let knowledgeConfig=KnowledgeConfigSchema.parse({});try{let{config:config3}=loadPluginConfigWithMeta(directory);knowledgeConfig=KnowledgeConfigSchema.parse(config3.knowledge??{})}catch{}let{trace_id,results}=await searchKnowledge({directory,config:knowledgeConfig,query:queryInput,mode:"manual",agent:ctx?.agent??"unknown",sessionId:ctx?.sessionID??"unknown",tier,maxResults:topN,applyScopeFilter:!1,forceReadHive:!0,applyRoleScope:!1,emitEvent:!1}),sessionId=ctx?.sessionID??"unknown";if(results.length>0){let membership=await commitDisplayedMembership(directory,{trace_id,session_id:sessionId,exposure_kind:"manual_recall",agent:ctx?.agent??"unknown",grace_days:knowledgeConfig.receipt_close_grace_days,phase:repairReevaluation?.phase,task_id:repairReevaluation?.task_id,repair_re_evaluation:repairReevaluation,entries:results.map((entry,index)=>({entry_id:entry.id,critical:entry.directive_priority==="critical"&&isActiveStatus(entry.status),rank:index+1,score:entry.finalScore}))});if(!membership.ok||membership.memberships.some((item)=>item.terminal))return JSON.stringify({results:[],total:0,unverifiable:!0,code:membership.ok?"terminal_trace_reuse":membership.code,error:membership.ok?"retrieval trace was already terminalized":membership.detail})}else{let empty=await commitEmptyRetrieval(directory,{trace_id,session_id:sessionId,agent:ctx?.agent??"unknown",grace_days:knowledgeConfig.receipt_close_grace_days,phase:repairReevaluation?.phase,task_id:repairReevaluation?.task_id,repair_re_evaluation:repairReevaluation});if(!empty.ok)return JSON.stringify({results:[],total:0,unverifiable:!0,code:empty.code,error:empty.detail});if(!empty.terminal_event_id)return JSON.stringify({results:[],total:0,unverifiable:!0,code:"store_unavailable",error:"empty retrieval terminal did not commit"})}let ranks=Object.fromEntries(results.map((entry,index)=>[entry.id,index+1])),scores=Object.fromEntries(results.map((entry)=>[entry.id,entry.finalScore]));await recordKnowledgeEvent(directory,{type:"retrieved",trace_id,session_id:sessionId,agent:ctx?.agent??"unknown",query:queryInput,retrieval_mode:"manual",result_ids:results.map((entry)=>entry.id),ranks,scores});let scored=results.map((e)=>({id:e.id,confidence:e.confidence,category:e.category,lesson:e.lesson,score:e.finalScore,score_breakdown:e.score_breakdown}));log("[knowledge_recall] completed",{agent:ctx?.agent??"unknown",session_id:ctx?.sessionID??"unknown",query:queryInput,tier,result_count:scored.length,trace_id});let result={results:scored,total:scored.length,trace_id};if(wantDebug)result.debug=await computeKnowledgeDebug(directory);return JSON.stringify(result)}}),_internals183={knowledge_recall}});var exports_prompt_renderer={};__export(exports_prompt_renderer,{renderEnvironmentPrompt:()=>renderEnvironmentPrompt});function renderEnvironmentPrompt(profile,audience){let policy=deriveCommandPolicy(profile),header=["RUNTIME ENVIRONMENT",`- Host OS: ${profile.hostOS}`,`- Shell family: ${profile.shellFamily}`,`- Execution mode: ${profile.executionMode}`,`- Path style: ${profile.pathStyle}`].join(`
6319
+ `),constraints=[];for(let line of lines){if(constraints.length>=MAX_CONSTRAINTS_PER_DOC)break;let trimmed=line.trim();if(!trimmed)continue;if(isConstraintLine(trimmed)){let cleaned=stripMarkdown(trimmed),len=cleaned.length;if(len>=MIN_LESSON_LENGTH&&len<=MAX_CONSTRAINT_LENGTH)constraints.push(cleaned)}}return constraints}async function extractDocConstraints(directory,taskFiles,taskDescription){let manifestPath2=path237.join(directory,".swarm","doc-manifest.json"),manifest;try{let content=await readFile48(manifestPath2,"utf-8");manifest=JSON.parse(content)}catch{manifest=(await scanDocIndex(directory)).manifest}let knowledgePath=resolveSwarmKnowledgePath(directory),existingEntries=await readKnowledge(knowledgePath),taskContext=[...taskFiles,taskDescription].join(" "),taskBigrams=wordBigrams(normalize6(taskContext)),extractedCount=0,skippedCount=0,details=[];for(let docFile of manifest.files){let docContext=`${docFile.path} ${docFile.title} ${docFile.summary}`,docBigrams=wordBigrams(normalize6(docContext)),score=jaccardBigram(taskBigrams,docBigrams);if(score<=RELEVANCE_THRESHOLD){skippedCount++;continue}let fullContent;try{fullContent=await readFile48(path237.join(directory,docFile.path),"utf-8")}catch{skippedCount++;continue}let constraints=extractConstraintsFromContent(fullContent);if(constraints.length===0){skippedCount++;continue}let docDetails={path:docFile.path,score,constraints:[]};for(let constraint of constraints)if(!findNearDuplicate(constraint,existingEntries,DEDUP_THRESHOLD2)){let entry={id:crypto14.randomUUID(),tier:"swarm",lesson:constraint,category:"architecture",tags:["doc-scan",path237.basename(docFile.path)],scope:"global",confidence:0.5,status:"candidate",confirmed_by:[],project_name:"",retrieval_outcomes:{applied_count:0,succeeded_after_count:0,failed_after_count:0},schema_version:1,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),auto_generated:!0,hive_eligible:!1};await appendKnowledge(knowledgePath,entry),existingEntries.push(entry),extractedCount++,docDetails.constraints.push(constraint)}if(docDetails.constraints.length>0)details.push(docDetails);else skippedCount++}return{extracted:extractedCount,skipped:skippedCount,details}}var SKIP_DIRECTORIES3,SKIP_PATTERNS,MAX_SUMMARY_LENGTH=200,MAX_INDEXED_FILES=100,READ_LINES_LIMIT=30,MIN_LESSON_LENGTH=15,MAX_CONSTRAINTS_PER_DOC=5,MAX_CONSTRAINT_LENGTH=200,RELEVANCE_THRESHOLD=0.1,DEDUP_THRESHOLD2=0.6,CONSTRAINT_PATTERNS,ACTION_WORDS,doc_scan,doc_extract;var init_doc_scan=__esm(()=>{init_zod();init_schema();init_knowledge_store();init_create_tool();SKIP_DIRECTORIES3=new Set(["node_modules",".git",".swarm","dist","build",".next","vendor","bazel-out","bazel-bin","bazel-genfiles","bazel-testlogs",".gradle","target"]),SKIP_PATTERNS=[/\.test\./,/\.spec\./,/\.d\.ts$/];CONSTRAINT_PATTERNS=[/\bMUST\b/,/\bMUST NOT\b/,/\bSHOULD\b/,/\bSHOULD NOT\b/,/\bDO NOT\b/,/\bALWAYS\b/,/\bNEVER\b/,/\bREQUIRED\b/],ACTION_WORDS=/\b(must|should|don't|avoid|ensure|use|follow)\b/i;doc_scan=createSwarmTool({description:"Scan project documentation files and build an index manifest. Caches results in .swarm/doc-manifest.json for fast subsequent scans.",args:{force:exports_external.boolean().optional().describe("Force re-scan even if cache is valid")},execute:async(args2,directory)=>{let force=!1;try{if(args2&&typeof args2==="object"){if(args2.force===!0)force=!0}}catch{}if(force){let manifestPath2=path237.join(directory,".swarm","doc-manifest.json");try{fs132.unlinkSync(manifestPath2)}catch{}}let{manifest,cached:cached3}=await scanDocIndex(directory);return JSON.stringify({success:!0,files_count:manifest.files.length,cached:cached3,manifest},null,2)}}),doc_extract=createSwarmTool({description:"Extract actionable constraints from project documentation relevant to the current task. Scans docs via doc-manifest, scores relevance via Jaccard bigram similarity, and stores non-duplicate constraints in .swarm/knowledge.jsonl.",args:{task_files:exports_external.array(exports_external.string()).describe("List of file paths involved in the current task"),task_description:exports_external.string().describe("Description of the current task")},execute:async(args2,directory)=>{let taskFiles=[],taskDescription="";try{if(args2&&typeof args2==="object"){let obj=args2;if(Array.isArray(obj.task_files))taskFiles=obj.task_files.filter((f)=>typeof f==="string");if(typeof obj.task_description==="string")taskDescription=obj.task_description}}catch{}if(taskFiles.length===0&&!taskDescription)return JSON.stringify({success:!1,error:"task_files or task_description is required"});let result=await extractDocConstraints(directory,taskFiles,taskDescription);return JSON.stringify({success:!0,...result},null,2)}})});import{existsSync as existsSync122}from"node:fs";import{readFile as readFile49}from"node:fs/promises";import*as path238 from"node:path";function inferCategoriesFromPhase(phaseDescription){let lower=phaseDescription.toLowerCase(),patterns=[{pattern:/\b(?:test|qa|quality|verification|validation)\b/,categories:["testing","debugging"]},{pattern:/\b(?:implement|build|develop|coding|code)\b/,categories:["tooling","architecture","debugging"]},{pattern:/\b(?:integrat|deploy|ci|cd|release|publish)\b/,categories:["integration","tooling","performance"]},{pattern:/\b(?:plan|design|architect|spec|requirement)\b/,categories:["architecture","process"]},{pattern:/\b(?:review|refactor|cleanup|polish|optimi)\b/,categories:["performance","architecture","process"]},{pattern:/\b(?:secur|audit|harden|compliance)\b/,categories:["security","testing"]},{pattern:/\b(?:setup|config|scaffold|init|bootstrap)\b/,categories:["tooling","other"]},{pattern:/\b(?:doc|readme|changelog)\b/,categories:["process","tooling"]}];for(let{pattern,categories}of patterns)if(pattern.test(lower))return categories;return["process","tooling"]}async function transactShownFile(shownFile,mutate){return transactFile(shownFile,async(filePath)=>{if(!existsSync122(filePath))return{};try{let content=await readFile49(filePath,"utf-8");return JSON.parse(content)}catch{return{}}},async(filePath,data)=>{await atomicWriteFile(filePath,JSON.stringify(data,null,2))},mutate)}async function recordLessonsShown(directory,lessonIds,currentPhase){if(lessonIds.length===0)return;let shownFile=path238.join(directory,".swarm",".knowledge-shown.json");try{let phaseMatch=/^Phase\s+(\d+)/i.exec(currentPhase),canonicalKey=phaseMatch?`Phase ${phaseMatch[1]}`:currentPhase;if(!await transactShownFile(shownFile,(shownData)=>{let existing=new Set(shownData[canonicalKey]??[]);for(let id of lessonIds)existing.add(id);return shownData[canonicalKey]=[...existing],shownData}))warn("[swarm] Knowledge: failed to record shown lessons")}catch{warn("[swarm] Knowledge: failed to record shown lessons")}}async function readMergedKnowledge(directory,config3,context,opts){let swarmPath3=resolveSwarmKnowledgePath(directory),swarmEntries=await readKnowledge(swarmPath3),hiveEntries=[];if(config3.hive_enabled!==!1){let hivePath=resolveHiveKnowledgePath2();hiveEntries=await readKnowledge(hivePath)}let seenLessons=new Set,merged=[];for(let entry of hiveEntries){let normalized=normalize6(entry.lesson);seenLessons.add(normalized),merged.push({...entry,relevanceScore:{category:0,confidence:0,keywords:0},finalScore:0})}for(let entry of swarmEntries){let normalized=normalize6(entry.lesson);if(seenLessons.has(normalized))continue;let swarmBigrams=wordBigrams(normalized);if(hiveEntries.some((hiveEntry)=>jaccardBigram(swarmBigrams,wordBigrams(normalize6(hiveEntry.lesson)))>=JACCARD_THRESHOLD2))continue;if(merged.some((m)=>m.tier==="swarm"&&jaccardBigram(swarmBigrams,wordBigrams(normalize6(m.lesson)))>=JACCARD_THRESHOLD2))continue;seenLessons.add(normalized),merged.push({...entry,relevanceScore:{category:0,confidence:0,keywords:0},finalScore:0})}let retractionRecords=await readRetractionRecords(directory),suppressedLessons=new Set(retractionRecords.map((record3)=>record3.normalized_lesson).filter((value)=>typeof value==="string"&&value.length>0)),scopeFilter=config3.scope_filter??["global"],ranked=merged.filter((entry)=>(opts?.skipScopeFilter||scopeFilter.some((pattern)=>(entry.scope??"global")===pattern))&&isActiveStatus(entry.status)&&!suppressedLessons.has(normalize6(entry.lesson))).map((entry)=>{let categoryScore=0;if(context?.currentPhase){if(inferCategoriesFromPhase(context.currentPhase).includes(entry.category))categoryScore=1;else if(entry.category==="process")categoryScore=0.5}else categoryScore=0.5;let confidenceScore=entry.confidence,keywordsScore=0;if(context?.techStack&&entry.tags.length>0){let matchingTags=entry.tags.filter((t)=>context.techStack.some((s)=>t.toLowerCase().includes(s.toLowerCase())||s.toLowerCase().includes(t.toLowerCase()))).length;keywordsScore=Math.min(matchingTags/Math.max(entry.tags.length,1),1)}else if(entry.tags.length===0)keywordsScore=0.5;let tierBoost=0,isSameProject=!1;if(entry.tier==="hive"&&"source_project"in entry){let sourceProject=entry.source_project;isSameProject=!!(context?.projectName&&sourceProject===context.projectName),tierBoost=HIVE_TIER_BOOST}let sameProjectPenalty=isSameProject?DEFAULT_SAME_PROJECT_PENALTY:0,finalScore=categoryScore*0.4+confidenceScore*0.35+keywordsScore*0.25+tierBoost+sameProjectPenalty;return{...entry,relevanceScore:{category:categoryScore,confidence:confidenceScore,keywords:keywordsScore},finalScore:Math.min(Math.max(finalScore,0),1)}});ranked.sort((a,b)=>{let scoreDiff=b.finalScore-a.finalScore;if(Math.abs(scoreDiff)>0.001)return scoreDiff;let dateA=new Date(a.created_at).getTime();return new Date(b.created_at).getTime()-dateA});let maxInject=config3.max_inject_count??5;return ranked.slice(0,maxInject)}async function updateRetrievalOutcome(directory,phaseInfo,phaseSucceeded){let shownFile=path238.join(directory,".swarm",".knowledge-shown.json");try{if(!existsSync122(shownFile))return;let shownIds;try{let content=await readFile49(shownFile,"utf-8");shownIds=JSON.parse(content)[phaseInfo]}catch{return}if(!shownIds||shownIds.length===0)return;let outcome=phaseSucceeded?"success":"failure",evidenceSummary=`${phaseInfo} ${phaseSucceeded?"succeeded":"failed"} after entry was shown`;await transactShownFile(shownFile,(data)=>{return delete data[phaseInfo],data});for(let id of shownIds)await _internals182.recordKnowledgeEvent(directory,{type:"outcome",knowledge_id:id,phase:phaseInfo,outcome,evidence_summary:evidenceSummary})}catch{warn("[swarm] Knowledge: failed to update retrieval outcomes")}}function lc(s){return(s??"").toLowerCase()}function anyMatch(haystack,needles){if(needles.length===0)return!1;let hay=haystack.map(lc);return needles.some((n)=>hay.some((h)=>h.includes(lc(n))))}function tokenizeContext(ctx){let parts=[];if(ctx.taskTitle)parts.push(ctx.taskTitle);if(ctx.taskDescription)parts.push(ctx.taskDescription);if(ctx.lastUserMessage)parts.push(ctx.lastUserMessage);if(ctx.currentAction)parts.push(ctx.currentAction);if(ctx.currentTool)parts.push(ctx.currentTool);if(ctx.targetAgent)parts.push(ctx.targetAgent);if(ctx.declaredScope)parts.push(ctx.declaredScope);if(ctx.recentReviewerFailures)parts.push(...ctx.recentReviewerFailures);if(ctx.recentTestFailures)parts.push(...ctx.recentTestFailures);if(ctx.recentToolErrors)parts.push(...ctx.recentToolErrors);if(ctx.planConstraints)parts.push(...ctx.planConstraints);if(ctx.filePaths)parts.push(...ctx.filePaths);return parts.map(lc)}function scoreDirectiveAgainstContext(entry,ctx){let haystack=tokenizeContext(ctx),triggerHit=entry.triggers&&entry.triggers.length>0?anyMatch(haystack,entry.triggers):!1,actionHit=entry.applies_to_tools&&entry.applies_to_tools.length>0?entry.applies_to_tools.map(lc).some((t)=>t===lc(ctx.currentTool)||t===lc(ctx.currentAction)):!1,agentHit=entry.applies_to_agents&&entry.applies_to_agents.length>0?entry.applies_to_agents.map(lc).some((a)=>a===lc(ctx.targetAgent)):!1,score=0;if(triggerHit)score+=0.5;if(actionHit)score+=0.35;if(agentHit)score+=0.25;if(entry.directive_priority==="critical")score+=0.4;else if(entry.directive_priority==="high")score+=0.2;else if(entry.directive_priority==="medium")score+=0.1;return{triggerHit,actionHit,agentHit,score:Math.min(1,score)}}var JACCARD_THRESHOLD2=0.6,HIVE_TIER_BOOST=0.05,DEFAULT_SAME_PROJECT_PENALTY=-0.05,_internals182;var init_knowledge_reader=__esm(()=>{init_task_file();init_logger();init_knowledge_events();init_knowledge_store();init_knowledge_types();_internals182={readMergedKnowledge,updateRetrievalOutcome,scoreDirectiveAgainstContext,transactShownFile,recordKnowledgeEvent,recordLessonsShown}});function entryText(e){return`${e.lesson} ${e.tags.join(" ")} ${e.category}`}function entryAgePhases(e){let cb=e.confirmed_by;if(!Array.isArray(cb)||cb.length===0)return 0;let phases=new Set;for(let c of cb)if(typeof c?.phase_number==="number")phases.add(c.phase_number);return phases.size>0?phases.size:cb.length}function clampLambda(v){if(typeof v!=="number"||Number.isNaN(v))return 0.5;return Math.min(1,Math.max(0,v))}function mmrRerank(pool,pinned,max,lambda){if(pool.length===0)return[];let bigrams=new Map,bg=(e)=>{let s=bigrams.get(e.id);if(!s)s=wordBigrams(normalize6(e.lesson??"")),bigrams.set(e.id,s);return s},selected=[...pinned],candidates=[...pool],out=[];while(selected.length<max&&candidates.length>0){let bestIdx=-1,bestScore=Number.NEGATIVE_INFINITY,best=null;for(let i=0;i<candidates.length;i++){let c=candidates[i],maxSim=0;for(let s of selected){let sim=jaccardBigram(bg(c),bg(s));if(sim>maxSim)maxSim=sim}let score=lambda*c.finalScore-(1-lambda)*maxSim;if(score>bestScore+0.000000001||Math.abs(score-bestScore)<=0.000000001&&best!==null&&tieBreak(c,best)<0)bestScore=score,bestIdx=i,best=c}if(bestIdx<0||best===null)break;out.push(best),selected.push(best),candidates.splice(bestIdx,1)}return out}function tieBreak(a,b){if(Math.abs(a.finalScore-b.finalScore)>0.000000001)return b.finalScore-a.finalScore;let at=new Date(a.created_at).getTime(),bt=new Date(b.created_at).getTime();if(at!==bt)return bt-at;return a.id<b.id?-1:a.id>b.id?1:0}function statusBoost(status){if(status==="promoted")return 0.15;if(status==="established")return 0.1;return 0}async function searchKnowledge(params){let{directory,config:config3,query,context,mode,agent="unknown",sessionId="unknown",tier="all",emitEvent=!1,applyScopeFilter=!0,forceReadHive=!1,applyRoleScope=!0}=params,traceId=newTraceId2(),max=params.maxResults??config3.max_inject_count??5,results=[],synonymTokens=[],synonymTrace={};try{let mergeConfig={...config3,hive_enabled:tier==="swarm"?!1:forceReadHive?!0:config3.hive_enabled,max_inject_count:Math.max(20,max)},projected={projectName:context?.projectName??"unknown",currentPhase:context?.currentPhase??"",techStack:context?.techStack,recentErrors:[...context?.recentReviewerFailures??[],...context?.recentTestFailures??[],...context?.recentToolErrors??[]]},candidates=await readMergedKnowledge(directory,mergeConfig,projected,{skipScopeFilter:!applyScopeFilter}),counterRollups=await readAuthoritativeKnowledgeCounterRollups(directory);candidates=candidates.filter((e)=>{if(!isActiveStatus(e.status))return!1;if(tier==="hive"&&e.tier!=="hive")return!1;return!0});let role=stripKnownSwarmPrefix(agent).toLowerCase();if(applyRoleScope&&role&&role!=="unknown")candidates=candidates.filter((e)=>{if(!e.applies_to_agents||e.applies_to_agents.length===0)return!0;if(role==="architect")return!0;return e.applies_to_agents.map((a)=>stripKnownSwarmPrefix(a).toLowerCase()).includes(role)});let queryText=(query??"").trim(),queryBigrams=queryText?wordBigrams(normalize6(queryText)):null,hasQuery=queryBigrams!==null,textWeight=hasQuery?TEXT_WEIGHT:0,metaWeight=hasQuery?META_WEIGHT:1,compositeRaw=[queryText,context?.taskTitle,context?.taskDescription,context?.lastUserMessage,context?.currentAction,...context?.recentReviewerFailures??[],...context?.recentTestFailures??[],...context?.recentToolErrors??[]].filter((s)=>typeof s==="string"&&s.length>0).join(" "),compositeNorm=normalize6(compositeRaw),hasComposite=compositeNorm.length>0;try{if(hasComposite){let synMap=await readSynonymMap(directory,config3.retrieval?.synonym_map_max_pairs),synIndex=buildSynonymIndex(synMap,config3.retrieval?.synonym_min_cooccurrence),baseTokens=compositeNorm.split(" ").filter(Boolean);synonymTokens=expandTokens(synIndex,baseTokens)}}catch{synonymTokens=[]}let minConf=typeof config3.directive_min_confidence==="number"?config3.directive_min_confidence:DIRECTIVE_BOOST_MIN_CONFIDENCE,scored=candidates.map((entry)=>{let retrievalOutcomes=effectiveRetrievalOutcomes(entry.retrieval_outcomes,counterRollups.get(entry.id)),textScore=queryBigrams?jaccardBigram(queryBigrams,wordBigrams(normalize6(entryText(entry)))):0,metaScore=entry.finalScore,ds=context?scoreDirectiveAgainstContext(entry,context):{triggerHit:!1,actionHit:!1,agentHit:!1,score:0},confBoost=context&&entry.confidence>=minConf&&(ds.actionHit||ds.agentHit)?0.25:0,generatedSkillBoost=entry.generated_skill_path&&entry.status!=="archived"?0.05:0,outcomeBoost=computeOutcomeSignal(retrievalOutcomes)*OUTCOME_RANK_WEIGHT,coldStartBonus=(retrievalOutcomes.applied_explicit_count??0)===0&&entryAgePhases(entry)<(config3.retrieval?.cold_start_max_age_phases??DEFAULT_COLD_START_MAX_AGE_PHASES)?config3.retrieval?.cold_start_bonus??DEFAULT_COLD_START_BONUS:0,synonymBoost=0;if(synonymTokens.length>0){let entryHay=normalize6(entryText(entry)),matched=[];for(let t of synonymTokens)if(t.length>0&&entryHay.includes(t))matched.push(t);if(matched.length>0)synonymBoost=SYNONYM_TEXT_BOOST,synonymTrace[entry.id]=matched}let triggerRecallBoost=!ds.triggerHit&&hasComposite&&Array.isArray(entry.triggers)&&entry.triggers.some((tr)=>{let n=normalize6(tr);return n.length>=TRIGGER_RECALL_MIN_LEN&&compositeNorm.includes(n)})?TRIGGER_RECALL_BOOST:0,finalScore=Math.min(1,Math.max(0,textWeight*textScore+metaWeight*metaScore+ds.score+confBoost+generatedSkillBoost+outcomeBoost+coldStartBonus+synonymBoost+triggerRecallBoost+(hasQuery&&!entry.confidence_floor_demoted?statusBoost(entry.status):0))),statusScoreBoost=hasQuery&&!entry.confidence_floor_demoted?statusBoost(entry.status):0,isCritical=entry.directive_priority==="critical"&&(ds.triggerHit||ds.actionHit||ds.agentHit),isForceHive=forceReadHive&&entry.tier==="hive";return{...entry,retrieval_outcomes:retrievalOutcomes,finalScore,coldStartBoost:coldStartBonus,score_breakdown:{text_score:textScore,metadata_score:metaScore,directive_score:ds.score,confidence_boost:confBoost,generated_skill_boost:generatedSkillBoost,outcome_boost:outcomeBoost,cold_start_boost:coldStartBonus,synonym_boost:synonymBoost,trigger_recall_boost:triggerRecallBoost,status_boost:statusScoreBoost,final_score:finalScore,...synonymTrace[entry.id]?{synonym_matches:synonymTrace[entry.id]}:{}},__critical:isCritical,__forceHive:isForceHive}});scored.sort((a,b)=>{let diff=b.finalScore-a.finalScore;if(Math.abs(diff)>0.001)return diff;return new Date(b.created_at).getTime()-new Date(a.created_at).getTime()});let top=[],seen=new Set;for(let e of scored){if(top.length>=max)break;if(e.__critical&&!seen.has(e.id))top.push(e),seen.add(e.id)}for(let e of scored){if(top.length>=max)break;if(e.__forceHive&&!seen.has(e.id))top.push(e),seen.add(e.id)}let lambda=clampLambda(config3.retrieval?.mmr_lambda),remaining=scored.filter((e)=>!seen.has(e.id)),selected=mmrRerank(remaining,top,max,lambda);for(let e of selected){if(top.length>=max)break;if(!seen.has(e.id))top.push(e),seen.add(e.id)}results=top.map(({__critical:_c,__forceHive:_f,...rest})=>rest)}catch(err){warn(`[search-knowledge] retrieval failed: ${err instanceof Error?err.message:String(err)}`),results=[]}if(emitEvent){let ranks={},scores={};results.forEach((e,idx)=>{ranks[e.id]=idx+1,scores[e.id]=e.finalScore});let synonymBreakdown={};for(let e of results)if(synonymTrace[e.id])synonymBreakdown[e.id]=synonymTrace[e.id];let scoreBreakdown=synonymTokens.length>0?{synonyms_expanded:synonymTokens,synonym_matches:synonymBreakdown}:void 0;await recordKnowledgeEvent(directory,{type:"retrieved",trace_id:traceId,session_id:sessionId,phase:context?.currentPhase,task_id:context?.taskId,agent,query:query??context?.lastUserMessage??context?.currentPhase??"",retrieval_mode:mode,result_ids:results.map((e)=>e.id),ranks,scores,...scoreBreakdown?{score_breakdown:scoreBreakdown}:{}})}return{trace_id:traceId,results}}var TEXT_WEIGHT=0.6,META_WEIGHT=0.4,DIRECTIVE_BOOST_MIN_CONFIDENCE=0.75,SYNONYM_TEXT_BOOST=0.15,TRIGGER_RECALL_BOOST=0.3,TRIGGER_RECALL_MIN_LEN=3,DEFAULT_COLD_START_BONUS=0.08,DEFAULT_COLD_START_MAX_AGE_PHASES=3,OUTCOME_RANK_WEIGHT=0.1;var init_search_knowledge=__esm(()=>{init_schema();init_synonym_map();init_logger();init_knowledge_events();init_knowledge_reader();init_knowledge_store();init_knowledge_types()});var exports_knowledge_recall={};__export(exports_knowledge_recall,{knowledge_recall:()=>knowledge_recall,_internals:()=>_internals183});var knowledge_recall,_internals183;var init_knowledge_recall=__esm(()=>{init_zod();init_config();init_schema();init_knowledge_events();init_knowledge_receipt_ledger();init_knowledge_types();init_search_knowledge();init_knowledge_diagnostics();init_logger();init_create_tool();knowledge_recall=createSwarmTool({allowWorkingDirectoryOverride:!0,description:"Performs semantic natural-language search across the knowledge base for relevant past decisions, patterns, and lessons learned. Returns ranked results via the unified hybrid retrieval service and a trace_id for knowledge_receipt. This is the tool to use when the user has a QUESTION about what the knowledge base contains. For structured filter-based retrieval (by category, status, or score), use `knowledge_query` instead.",args:{query:exports_external.string().min(3).describe("Natural language search query"),top_n:exports_external.number().int().min(1).max(20).optional().describe("Maximum results to return (default: 5)"),tier:exports_external.enum(["all","swarm","hive"]).optional().describe("Knowledge tier to search (default: 'all')"),debug:exports_external.boolean().optional().describe("Include path/version/health debug metadata in the response"),repair_re_evaluation:exports_external.object({repair_id:exports_external.string().uuid(),phase:exports_external.string().min(1).max(256),task_id:exports_external.string().min(1).max(256).optional(),scope_complete:exports_external.boolean()}).optional().describe("Architect-only explicit completion of a repaired receipt scope. The query must comprehensively re-evaluate the exact affected phase/session scope.")},execute:async(args2,directory,ctx)=>{let queryInput,topNInput,tierInput,debugInput,repairInput;try{if(args2&&typeof args2==="object"){let obj=args2;queryInput=obj.query,topNInput=obj.top_n,tierInput=obj.tier,debugInput=obj.debug,repairInput=obj.repair_re_evaluation}}catch{}let wantDebug=debugInput===!0,repairReevaluation;if(repairInput!==void 0){if(stripKnownSwarmPrefix(ctx?.agent??"")!=="architect"||typeof repairInput!=="object"||repairInput===null)return JSON.stringify({results:[],total:0,unverifiable:!0,code:"RECEIPT_REEVALUATION_ARCHITECT_ONLY",error:"Only the architect may complete an explicit receipt repair re-evaluation."});let candidate2=repairInput;if(typeof candidate2.repair_id!=="string"||!candidate2.repair_id||typeof candidate2.phase!=="string"||!candidate2.phase||candidate2.scope_complete!==!0||candidate2.task_id!==void 0&&typeof candidate2.task_id!=="string")return JSON.stringify({results:[],total:0,unverifiable:!0,code:"RECEIPT_REEVALUATION_PROOF_INVALID",error:"Explicit re-evaluation requires repair_id, exact phase, and scope_complete=true."});repairReevaluation={repair_id:candidate2.repair_id,phase:candidate2.phase,scope_complete:!0,...typeof candidate2.task_id==="string"?{task_id:candidate2.task_id}:{}}}if(typeof queryInput!=="string"||queryInput.length<3)return JSON.stringify({results:[],total:0,error:"query must be a string with at least 3 characters"});let topN=5;if(typeof topNInput==="number"&&Number.isInteger(topNInput))topN=Math.max(1,Math.min(20,topNInput));let tier="all";if(tierInput==="swarm"||tierInput==="hive")tier=tierInput;let knowledgeConfig=KnowledgeConfigSchema.parse({});try{let{config:config3}=loadPluginConfigWithMeta(directory);knowledgeConfig=KnowledgeConfigSchema.parse(config3.knowledge??{})}catch{}let{trace_id,results}=await searchKnowledge({directory,config:knowledgeConfig,query:queryInput,mode:"manual",agent:ctx?.agent??"unknown",sessionId:ctx?.sessionID??"unknown",tier,maxResults:topN,applyScopeFilter:!1,forceReadHive:!0,applyRoleScope:!1,emitEvent:!1}),sessionId=ctx?.sessionID??"unknown";if(results.length>0){let membership=await commitDisplayedMembership(directory,{trace_id,session_id:sessionId,exposure_kind:"manual_recall",agent:ctx?.agent??"unknown",grace_days:knowledgeConfig.receipt_close_grace_days,phase:repairReevaluation?.phase,task_id:repairReevaluation?.task_id,repair_re_evaluation:repairReevaluation,entries:results.map((entry,index)=>({entry_id:entry.id,critical:entry.directive_priority==="critical"&&isActiveStatus(entry.status),rank:index+1,score:entry.finalScore}))});if(!membership.ok||membership.memberships.some((item)=>item.terminal))return JSON.stringify({results:[],total:0,unverifiable:!0,code:membership.ok?"terminal_trace_reuse":membership.code,error:membership.ok?"retrieval trace was already terminalized":membership.detail})}else{let empty=await commitEmptyRetrieval(directory,{trace_id,session_id:sessionId,agent:ctx?.agent??"unknown",grace_days:knowledgeConfig.receipt_close_grace_days,phase:repairReevaluation?.phase,task_id:repairReevaluation?.task_id,repair_re_evaluation:repairReevaluation});if(!empty.ok)return JSON.stringify({results:[],total:0,unverifiable:!0,code:empty.code,error:empty.detail});if(!empty.terminal_event_id)return JSON.stringify({results:[],total:0,unverifiable:!0,code:"store_unavailable",error:"empty retrieval terminal did not commit"})}let ranks=Object.fromEntries(results.map((entry,index)=>[entry.id,index+1])),scores=Object.fromEntries(results.map((entry)=>[entry.id,entry.finalScore]));await recordKnowledgeEvent(directory,{type:"retrieved",trace_id,session_id:sessionId,agent:ctx?.agent??"unknown",query:queryInput,retrieval_mode:"manual",result_ids:results.map((entry)=>entry.id),ranks,scores});let scored=results.map((e)=>({id:e.id,confidence:e.confidence,category:e.category,lesson:e.lesson,score:e.finalScore,score_breakdown:e.score_breakdown}));log("[knowledge_recall] completed",{agent:ctx?.agent??"unknown",session_id:ctx?.sessionID??"unknown",query:queryInput,tier,result_count:scored.length,trace_id});let result={results:scored,total:scored.length,trace_id};if(wantDebug)result.debug=await computeKnowledgeDebug(directory);return JSON.stringify(result)}}),_internals183={knowledge_recall}});var exports_prompt_renderer={};__export(exports_prompt_renderer,{renderEnvironmentPrompt:()=>renderEnvironmentPrompt});function renderEnvironmentPrompt(profile,audience){let policy=deriveCommandPolicy(profile),header=["RUNTIME ENVIRONMENT",`- Host OS: ${profile.hostOS}`,`- Shell family: ${profile.shellFamily}`,`- Execution mode: ${profile.executionMode}`,`- Path style: ${profile.pathStyle}`].join(`
6319
6320
  `);if(audience==="coder")return[header,policy.avoidPosixExamples?"- Command policy: Prefer PowerShell-native commands and Node.js APIs. Do not start with POSIX commands (ls, grep, rm, cat, export, pwd) unless the environment profile indicates Docker, WSL, or a POSIX shell.":"- Command policy: Use POSIX-native commands and Node.js APIs.","","EXECUTION ENVIRONMENT AWARENESS","- This session includes a runtime environment profile. Follow it exactly.","- Decision ladder when shell commands are necessary:"," 1. Prefer swarm tools and Node.js fs/path APIs."," 2. Use shell only when the task truly requires it."," 3. When shell commands are needed, match the active shell family above."].join(`
6320
6321
  `);return[header,"- Test execution policy: Always execute tests via the swarm test runner tool.",policy.avoidPosixExamples?" Do not describe POSIX shell setup commands unless the profile indicates Docker, WSL, or POSIX shell.":" Use POSIX semantics for test commands.","","ENVIRONMENT-SPECIFIC TEST EXECUTION RULES",profile.isWindowsNative?"- Native Windows + PowerShell: Assume PowerShell semantics for paths and env vars. Prefer Pester for PowerShell modules where appropriate.":profile.isWindowsDocker?"- Windows + Docker: Host paths are Windows-style; in-container operations use POSIX semantics.":"- Linux/macOS: Use POSIX semantics for all shell-related reasoning.","- In all modes: prefer the swarm test runner over ad hoc shell commands.","- When tests are skipped due to environment issues, explicitly mention the environment profile assumptions in your verdict."].join(`
6321
6322
  `)}var init_prompt_renderer=()=>{};var exports_design_doc_drift={};__export(exports_design_doc_drift,{runDesignDocDriftCheck:()=>runDesignDocDriftCheck,_internals:()=>_internals228});import*as fs175 from"node:fs";import*as path290 from"node:path";function mtimeMsOrNull(absPath){try{return fs175.statSync(absPath).mtimeMs}catch{return null}}function resolveAnchorWithin(directory,anchor){if(!anchor||typeof anchor!=="string")return null;let root=path290.resolve(directory),resolved=path290.resolve(root,anchor),rel=path290.relative(root,resolved);if(rel.startsWith("..")||path290.isAbsolute(rel))return null;return resolved}async function runDesignDocDriftCheck(directory,phase,outDir){try{let root=path290.resolve(directory),outAbs=path290.resolve(root,outDir),outRel=path290.relative(root,outAbs);if(outRel.startsWith("..")||path290.isAbsolute(outRel))return null;let docMtimes=new Map,checkedDocs=[],missingDocs=[];for(let[docName,relFile]of Object.entries(DESIGN_DOC_FILES)){let abs=path290.join(outAbs,relFile),mtime=mtimeMsOrNull(abs);if(docMtimes.set(docName,mtime),mtime===null)missingDocs.push(path290.join(outDir,relFile));else checkedDocs.push(path290.join(outDir,relFile))}let traceabilityAbs=path290.join(outAbs,TRACEABILITY_REL),registry3=null;try{if((await fs175.promises.stat(traceabilityAbs)).size<=MAX_TRACEABILITY_BYTES){let raw=await fs175.promises.readFile(traceabilityAbs,"utf-8"),parsed=JSON.parse(raw);registry3=parsed&&typeof parsed==="object"&&!Array.isArray(parsed)?parsed:null}}catch{registry3=null}let noDocs=checkedDocs.length===0||registry3===null,effectiveSpec=readEffectiveSpecSync(root),specMtime=effectiveSpec?.mtime?Date.parse(effectiveSpec.mtime):null,staleSections=[];if(!noDocs&&Array.isArray(registry3?.sections))for(let section of registry3.sections){if(!section||typeof section.section_id!=="string")continue;if(typeof section.doc!=="string"||!docMtimes.has(section.doc))continue;let docMtime=docMtimes.get(section.doc)??null;if(docMtime===null){staleSections.push({section_id:section.section_id,doc:section.doc,reason:"owning design doc is missing"});continue}let flagged=!1;for(let anchor of section.code_anchors??[]){let anchorAbs=resolveAnchorWithin(directory,anchor);if(anchorAbs===null)continue;let anchorMtime=mtimeMsOrNull(anchorAbs);if(anchorMtime!==null&&anchorMtime>docMtime){staleSections.push({section_id:section.section_id,doc:section.doc,reason:`code anchor ${anchor} changed after the doc`}),flagged=!0;break}}if(!flagged&&specMtime!==null&&specMtime>docMtime&&(section.spec_frs?.length??0)>0)staleSections.push({section_id:section.section_id,doc:section.doc,reason:"effective spec changed after the doc"})}let verdict=noDocs?"NO_DOCS":staleSections.length>0?"DOC_STALE":"DOC_FRESH",report={schema_version:1,phase,timestamp:new Date().toISOString(),out_dir:outDir,verdict,stale_sections:staleSections,missing_docs:missingDocs,checked_docs:checkedDocs},filename=`${DOC_DRIFT_REPORT_PREFIX}${phase}.json`,filePath=validateSwarmPath(directory,filename);return await fs175.promises.mkdir(path290.dirname(filePath),{recursive:!0}),await fs175.promises.writeFile(filePath,JSON.stringify(report,null,2),"utf-8"),getGlobalEventBus().publish("curator.docdrift.completed",{phase,verdict,stale_count:staleSections.length,report_path:filePath}),report}catch(err){try{getGlobalEventBus().publish("curator.error",{operation:"docdrift",phase,error:String(err)})}catch{}return warn(`[design-doc-drift] check failed for phase ${phase}: ${String(err)}`),null}}var DOC_DRIFT_REPORT_PREFIX="doc-drift-phase-",MAX_TRACEABILITY_BYTES=1048576,DESIGN_DOC_FILES,TRACEABILITY_REL,_internals228;var init_design_doc_drift=__esm(()=>{init_event_bus();init_effective_spec();init_logger();init_utils2();DESIGN_DOC_FILES={domain:"domain.md","technical-spec":"technical-spec.md","behavior-spec":"behavior-spec.md","reference-impl":path290.join("reference","reference-impl.md"),"idiom-notes":path290.join("reference","idiom-notes.md")},TRACEABILITY_REL=path290.join("reference","traceability.json");_internals228={mtimeMsOrNull,resolveAnchorWithin,DESIGN_DOC_FILES}});var exports_project_context={};__export(exports_project_context,{buildProjectContext:()=>buildProjectContext,_internals:()=>_internals256,LANG_BACKEND_DETECTION_TIMEOUT_MS:()=>LANG_BACKEND_DETECTION_TIMEOUT_MS});import*as fs206 from"node:fs";import*as path328 from"node:path";function detectFileExists2(directory,pattern){if(pattern.includes("*")||pattern.includes("?"))try{let files=fs206.readdirSync(directory),regex=new RegExp(`^${pattern.replace(/\./g,"\\.").replace(/\*/g,".*").replace(/\?/g,".")}$`);return files.some((f)=>regex.test(f))}catch{return!1}try{return fs206.accessSync(path328.join(directory,pattern)),!0}catch{return!1}}function selectTestCommandFromScriptsTest(backend,directory){let pkgRaw;try{pkgRaw=fs206.readFileSync(path328.join(directory,"package.json"),"utf-8")}catch{return null}let pkg;try{pkg=JSON.parse(pkgRaw)}catch{return null}let script=pkg.scripts?.test;if(!script)return null;let fwName=null;if(script.includes("vitest"))fwName="vitest";else if(script.includes("jest"))fwName="jest";else if(script.includes("mocha"))fwName="mocha";else if(script.includes("bun test"))fwName="bun:test";if(!fwName)return null;let fw=backend.test.frameworks.find((f)=>f.name===fwName);return fw?fw.cmd:null}function selectTestCommandFast(backend,directory){let fromScripts=selectTestCommandFromScriptsTest(backend,directory);if(fromScripts!==null)return fromScripts;let sorted=[...backend.test.frameworks].sort((a,b)=>b.priority-a.priority);for(let fw of sorted){if(!detectFileExists2(directory,fw.detect))continue;return fw.cmd}return null}function selectBuildCommandFast(backend,directory){let sorted=[...backend.build.commands].sort((a,b)=>b.priority-a.priority);for(let cmd of sorted){if(cmd.detectFile&&!detectFileExists2(directory,cmd.detectFile))continue;return cmd.cmd}return null}function selectLintCommand(backend,directory){let sorted=[...backend.lint.linters].sort((a,b)=>b.priority-a.priority);for(let lint2 of sorted){if(!detectFileExists2(directory,lint2.detect))continue;return lint2.cmd}return null}async function buildProjectContext(directory){let backend=await _internals256.pickBackend(directory);if(!backend)return null;let ctx=emptyProjectContext();ctx.PROJECT_LANGUAGE=backend.displayName;let buildCmd=selectBuildCommandFast(backend,directory);if(buildCmd)ctx.BUILD_CMD=buildCmd;let testCmd=selectTestCommandFast(backend,directory);if(testCmd)ctx.TEST_CMD=testCmd;let lintCmd=selectLintCommand(backend,directory);if(lintCmd)ctx.LINT_CMD=lintCmd;if(backend.id==="php"){let overlay=getLaravelCommandOverlay(directory);if(overlay){if(ctx.TEST_CMD=overlay.testCommand,overlay.lintCommand)ctx.LINT_CMD=overlay.lintCommand}}let[frameworkSel,entryPoints]=await Promise.all([backend.selectFramework?backend.selectFramework(directory).catch(()=>null):Promise.resolve(null),backend.selectEntryPoints?backend.selectEntryPoints(directory).catch(()=>[]):Promise.resolve([])]);if(frameworkSel)ctx.PROJECT_FRAMEWORK=frameworkSel.name;if(entryPoints.length>0)ctx.ENTRY_POINTS=entryPoints.join(", ");if(backend.prompts.coderConstraints.length>0)ctx.CODER_CONSTRAINTS=bulletList(backend.prompts.coderConstraints);if(backend.prompts.testConstraints&&backend.prompts.testConstraints.length>0)ctx.TEST_CONSTRAINTS=bulletList(backend.prompts.testConstraints);if(backend.prompts.reviewerChecklist.length>0)ctx.REVIEWER_CHECKLIST=bulletList(backend.prompts.reviewerChecklist);let profiles=_internals256.pickedProfiles(directory);if(profiles.length>1)ctx.PROJECT_CONTEXT_SECONDARY_LANGUAGES=profiles.slice(1).map((p)=>p.id).join(", ");return ctx}var LANG_BACKEND_DETECTION_TIMEOUT_MS=300,_internals256;var init_project_context=__esm(()=>{init_dispatch();init_framework_detector();_internals256={pickBackend,pickedProfiles}});init_package();init_agents2();init_critic();import*as path329 from"node:path";import{performance as performance2}from"node:perf_hooks";import{fileURLToPath as fileURLToPath7}from"node:url";init_event_bus();init_evidence_summary_integration();init_manager3();init_manager();init_utils();import*as fs114 from"node:fs";import*as path215 from"node:path";class PlanSyncWorker{directory;debounceMs;pollIntervalMs;syncTimeoutMs;onSyncComplete;status="stopped";watcher=null;pollTimer=null;debounceTimer=null;syncing=!1;pendingSync=!1;lastStat=null;disposed=!1;constructor(options={}){this.directory=options.directory??"",this.debounceMs=options.debounceMs??500,this.pollIntervalMs=options.pollIntervalMs??2000,this.syncTimeoutMs=options.syncTimeoutMs??30000,this.onSyncComplete=options.onSyncComplete}getSwarmDir(){return path215.resolve(this.directory,".swarm")}getPlanJsonPath(){return path215.join(this.getSwarmDir(),"plan.json")}start(){if(this.disposed){log("[PlanSyncWorker] Cannot start - worker has been disposed");return}if(!this.directory){log("[PlanSyncWorker] Cannot start - no directory provided");return}if(this.status==="running"||this.status==="starting"){log("[PlanSyncWorker] Already running or starting");return}this.status="starting",log("[PlanSyncWorker] Starting..."),this.initializeStat(),this.setupPolling(),this.setupNativeWatcher(),this.status="running",log("[PlanSyncWorker] Started watching for plan.json changes")}stop(){if(this.status==="stopped"||this.status==="stopping")return;if(this.status="stopping",log("[PlanSyncWorker] Stopping..."),this.clearDebounce(),this.watcher)this.watcher.close(),this.watcher=null;if(this.pollTimer)clearInterval(this.pollTimer),this.pollTimer=null;this.status="stopped",log("[PlanSyncWorker] Stopped")}dispose(){this.stop(),this.disposed=!0,this.lastStat=null,log("[PlanSyncWorker] Disposed")}getStatus(){return this.status}isRunning(){return this.status==="running"}initializeStat(){try{let stats2=fs114.statSync(this.getPlanJsonPath());this.lastStat={mtimeMs:stats2.mtimeMs,size:stats2.size}}catch{this.lastStat=null}}setupNativeWatcher(){let swarmDir=this.getSwarmDir();try{if(!fs114.existsSync(swarmDir))return log("[PlanSyncWorker] Swarm directory does not exist yet"),!1;return this.watcher=fs114.watch(swarmDir,{persistent:!1},(_eventType,filename)=>{if(this.disposed||this.status!=="running")return;if(filename&&(filename.includes(".tmp.")||filename.endsWith(".rebuild")))return;if(filename==="plan.json"||filename===void 0)this.debouncedSync()}),this.watcher.on("error",(error93)=>{if(this.disposed||this.status!=="running")return;if(log("[PlanSyncWorker] Watcher error, falling back to polling",{error:error93.message}),this.watcher)this.watcher.close(),this.watcher=null;this.setupPolling()}),log("[PlanSyncWorker] Native fs.watch established"),!0}catch(error93){return log("[PlanSyncWorker] Failed to setup native watcher",{error:error93 instanceof Error?error93.message:String(error93)}),!1}}setupPolling(){if(this.pollTimer)clearInterval(this.pollTimer);if(this.pollTimer=setInterval(()=>{if(this.disposed||this.status!=="running")return;this.pollCheck()},this.pollIntervalMs),typeof this.pollTimer.unref==="function")this.pollTimer.unref();log("[PlanSyncWorker] Polling fallback established",{intervalMs:this.pollIntervalMs})}pollCheck(){try{let planPath=this.getPlanJsonPath();if(!fs114.existsSync(planPath)){if(this.lastStat!==null)this.lastStat=null,log("[PlanSyncWorker] plan.json deleted");return}let stats2=fs114.statSync(planPath),currentStat={mtimeMs:stats2.mtimeMs,size:stats2.size};if(this.lastStat===null||currentStat.mtimeMs!==this.lastStat.mtimeMs||currentStat.size!==this.lastStat.size)this.lastStat=currentStat,this.debouncedSync()}catch(error93){log("[PlanSyncWorker] Poll check error",{error:error93 instanceof Error?error93.message:String(error93)})}}debouncedSync(){if(this.disposed||this.status!=="running")return;if(this.debounceTimer)clearTimeout(this.debounceTimer);this.debounceTimer=setTimeout(()=>{if(this.disposed||this.status!=="running")return;this.debounceTimer=null,this.triggerSync()},this.debounceMs)}clearDebounce(){if(this.debounceTimer)clearTimeout(this.debounceTimer),this.debounceTimer=null}triggerSync(){if(this.syncing){this.pendingSync=!0,log("[PlanSyncWorker] Sync pending (in-flight)");return}this.executeSync()}async executeSync(){this.syncing=!0;try{log("[PlanSyncWorker] Syncing plan..."),this.checkForUnauthorizedWrite();let plan=await this.withTimeout(_internals32.loadPlanJsonOnly(this.directory),this.syncTimeoutMs,"Sync operation timed out");if(plan&&plan.phases.length>0)await _internals32.regeneratePlanMarkdown(this.directory,plan),log("[PlanSyncWorker] Sync complete",{title:plan.title,phase:plan.current_phase}),this.safeCallback(!0);else if(plan)log("[PlanSyncWorker] Plan has no phases, skipping markdown regeneration"),this.safeCallback(!0);else log("[PlanSyncWorker] No plan found to sync"),this.safeCallback(!0)}catch(error93){if(error93 instanceof Error&&error93.message.includes("timed out"))log("[PlanSyncWorker] Sync timed out after "+this.syncTimeoutMs+"ms, worker remains active");else log("[PlanSyncWorker] Sync failed",{error:error93 instanceof Error?error93.message:String(error93)});this.safeCallback(!1,error93 instanceof Error?error93:Error(String(error93)))}finally{if(this.syncing=!1,this.pendingSync&&!this.disposed&&this.status==="running")this.pendingSync=!1,log("[PlanSyncWorker] Executing pending sync"),this.executeSync()}}safeCallback(success3,error93){if(this.onSyncComplete)try{this.onSyncComplete(success3,error93)}catch(callbackError){log("[PlanSyncWorker] onSyncComplete callback threw error (ignored)",{callbackError:callbackError instanceof Error?callbackError.message:String(callbackError)})}}checkForUnauthorizedWrite(){try{let swarmDir=this.getSwarmDir(),planJsonPath=path215.join(swarmDir,"plan.json"),markerPath=path215.join(swarmDir,".plan-write-marker"),planStats=fs114.statSync(planJsonPath),planMtimeMs=Math.floor(planStats.mtimeMs),markerContent=fs114.readFileSync(markerPath,"utf8"),marker=JSON.parse(markerContent);if(marker.in_progress===!0){log("[PlanSyncWorker] Skipping unauthorized-write check - plan write in progress");return}let markerTimestampMs=new Date(marker.timestamp).getTime();if(planMtimeMs>markerTimestampMs+5000)log("[PlanSyncWorker] WARNING: plan.json may have been written outside save_plan/savePlan - unauthorized direct write suspected",{planMtimeMs,markerTimestampMs})}catch{}}withTimeout(promise3,ms,timeoutMessage2){return new Promise((resolve88,reject)=>{let timer=setTimeout(()=>{reject(Error(`${timeoutMessage2} (${ms}ms)`))},ms);promise3.then((result)=>{clearTimeout(timer),resolve88(result)}).catch((error93)=>{clearTimeout(timer),reject(error93)})})}}init_pr_event_subscribers();import*as child_process10 from"node:child_process";init_zod();init_gh_evidence();init_bun_compat();init_logger();init_branch();var GIT_TIMEOUT_MS8=30000,EvidencePlanSchema=exports_external.object({phases:exports_external.array(exports_external.object({tasks:exports_external.array(exports_external.object({id:exports_external.string(),status:exports_external.string().optional()}).passthrough()).optional()}).passthrough()).optional()}).passthrough();function ghExec(args2,cwd){let ghBinary=_internals169.resolveGhBinary()??"gh";for(let attempt=0;attempt<MAX_TRANSIENT_RETRIES;attempt++){let result=child_process10.spawnSync(ghBinary,args2,{cwd,encoding:"utf-8",timeout:GIT_TIMEOUT_MS8,windowsHide:!0,maxBuffer:MAX_OUTPUT_BYTES5,stdio:["ignore","pipe","pipe"]});if(result.error){if(isTransientSpawnError(result.error)&&attempt<MAX_TRANSIENT_RETRIES-1){transientBackoff(attempt);continue}if(result.error.code==="ENOENT")throw Error("gh failed to start: ENOENT — gh not installed or not on PATH");throw Error(`gh failed to start: ${result.error.code} — ${result.error.message}`)}if(result.status!==0)throw Error(result.stderr||result.stdout||`gh exited with ${result.status}`);return result.stdout}throw Error("gh exited with null")}var MAX_OUTPUT_BYTES5=5242880,__spawnSyncSeam2={spawnSync:(cmd,args2,options)=>{let mergedEnv=mergeEnvForChild(options?.env,options?.envOverrides);return child_process10.spawnSync(cmd,args2,{...options,env:mergedEnv})}};function spawnSyncWithTransientRetry(command,args2,options){for(let attempt=0;attempt<MAX_TRANSIENT_RETRIES;attempt++){let result=__spawnSyncSeam2.spawnSync(command,args2,options);if(result.error){if(isTransientSpawnError(result.error)&&attempt<MAX_TRANSIENT_RETRIES-1){transientBackoff(attempt);continue}throw Error(`${command} failed: ${result.error.code} — ${result.error.message}`)}if(result.status!==0){let reason=result.stderr||result.stdout||`${command} exited with ${result.status}`;throw Error(`${command} failed: ${reason}`)}return result}throw Error(`${command} exited with null`)}async function ghExecAsync(args2,cwd){return new Promise((resolve90,reject)=>{let ghBinary=_internals169.resolveGhBinary()??"gh",proc=child_process10.spawn(ghBinary,args2,{cwd,stdio:["ignore","pipe","pipe"]}),stdoutChunks=[],stderrChunks=[],stdoutBytes=0,stderrBytes=0,settled=!1;function cleanup(){if(clearTimeout(timer),!proc.killed)try{proc.kill()}catch{}}function settle(fn2){if(settled)return;settled=!0,cleanup(),fn2()}proc.stdout?.on("data",(chunk)=>{if(stdoutBytes+=chunk.length,stdoutBytes>MAX_OUTPUT_BYTES5){settle(()=>reject(Error(`gh ${args2[0]} stdout exceeded ${MAX_OUTPUT_BYTES5} bytes`)));return}stdoutChunks.push(chunk)}),proc.stderr?.on("data",(chunk)=>{if(stderrBytes+=chunk.length,stderrBytes>MAX_OUTPUT_BYTES5){settle(()=>reject(Error(`gh ${args2[0]} stderr exceeded ${MAX_OUTPUT_BYTES5} bytes`)));return}stderrChunks.push(chunk)});let timer=setTimeout(()=>{settle(()=>reject(Error(`gh ${args2[0]} timed out after ${GIT_TIMEOUT_MS8}ms`)))},GIT_TIMEOUT_MS8);proc.on("error",(err)=>{settle(()=>reject(err))}),proc.on("close",(code)=>{settle(()=>{if(code!==0){let stderr=Buffer.concat(stderrChunks).toString("utf-8");reject(Error(stderr||`gh exited with ${code}`))}else{let stdout=Buffer.concat(stdoutChunks).toString("utf-8");resolve90(stdout)}})})})}var _internals169={ghExec,ghExecAsync,spawnSyncWithTransientRetry,spawnSync:__spawnSyncSeam2.spawnSync,readLaneEnvFileFromDiskSync,getMergeGroupRun,resolveGhBinary};async function getPRStatus(prNumber,repoFullName,cwd){let stdout;try{stdout=await _internals169.ghExecAsync(["pr","view",String(prNumber),"--repo",repoFullName,"--json","number,state,mergeable,mergeStateStatus,headRefOid,statusCheckRollup"],cwd)}catch(err){throw Error(`Failed to fetch PR status for ${repoFullName}#${prNumber}: ${err instanceof Error?err.message:String(err)}`)}return JSON.parse(stdout)}async function getPRComments(prNumber,repoFullName,cwd,since){let query=since?`?since=${since}`:"",issueCommentsPath=`repos/${repoFullName}/issues/${prNumber}/comments${query}`,reviewCommentsPath=`repos/${repoFullName}/pulls/${prNumber}/comments${query}`,issueComments,reviewComments;try{let issueRaw=await _internals169.ghExecAsync(["api",issueCommentsPath],cwd);issueComments=JSON.parse(issueRaw)}catch(err){throw Error(`Failed to fetch issue comments for ${repoFullName}#${prNumber}: ${err instanceof Error?err.message:String(err)}`)}try{let reviewRaw=await _internals169.ghExecAsync(["api",reviewCommentsPath],cwd);reviewComments=JSON.parse(reviewRaw)}catch(err){throw Error(`Failed to fetch review comments for ${repoFullName}#${prNumber}: ${err instanceof Error?err.message:String(err)}`)}let mapIssueComment=(c)=>({id:String(c.id??""),author:String(c.user?.login??""),body:neutralizeUntrustedMarkdown(String(c.body??""),"GitHub issue comment"),createdAt:String(c.created_at??""),isReviewComment:!1}),mapReviewComment=(c)=>({id:String(c.id??""),author:String(c.user?.login??""),body:neutralizeUntrustedMarkdown(String(c.body??""),"GitHub review comment"),createdAt:String(c.created_at??""),isReviewComment:!0});return[...issueComments.map(mapIssueComment),...reviewComments.map(mapReviewComment)]}async function getMergeState(prNumber,repoFullName,cwd){let stdout;try{stdout=await _internals169.ghExecAsync(["pr","view",String(prNumber),"--repo",repoFullName,"--json","mergeable,mergeStateStatus,headRefOid"],cwd)}catch(err){throw Error(`Failed to fetch merge state for ${repoFullName}#${prNumber}: ${err instanceof Error?err.message:String(err)}`)}let parsed=JSON.parse(stdout);return{mergeable:parsed.mergeable,mergeStateStatus:parsed.mergeStateStatus,headRefOid:parsed.headRefOid}}async function getPRReviewState(prNumber,repoFullName,cwd){let stdout;try{stdout=await _internals169.ghExecAsync(["pr","view",String(prNumber),"--repo",repoFullName,"--json","reviewDecision,reviewRequests"],cwd)}catch(err){throw Error(`Failed to fetch review state for ${repoFullName}#${prNumber}: ${err instanceof Error?err.message:String(err)}`)}let parsed=JSON.parse(stdout);return{reviewDecision:parsed.reviewDecision??"",reviewRequestCount:parsed.reviewRequests?.length??0}}async function getMergeGroupRun(statusCheckRollup,repoFullName,cwd){let mergeGroupCheck=statusCheckRollup.find((check3)=>check3.name==="Merge pull request"&&check3.detailsUrl);if(!mergeGroupCheck?.detailsUrl)return null;let runIdMatch=mergeGroupCheck.detailsUrl.match(/\/actions\/runs\/(\d+)/);if(!runIdMatch)return null;let runId=runIdMatch[1],stdout;try{stdout=await _internals169.ghExecAsync(["run","view",runId,"--json","status,conclusion,htmlUrl","--repo",repoFullName],cwd)}catch(err){throw Error(`Failed to fetch merge group run for ${repoFullName}: ${err instanceof Error?err.message:String(err)}`)}let parsed=JSON.parse(stdout);return{status:parsed.status??"",conclusion:parsed.conclusion??null,htmlUrl:parsed.htmlUrl??""}}init_utils();init_event_bus();init_pr_subscriptions();var MEANINGFUL_SNAPSHOT_FIELDS=["isWatching","headRefOid","mergeGroupRunStatus","mergeGroupRunConclusion","mergeGroupRunHtmlUrl","lastCommentId"];function shouldSkipIdlePoll(idleCount,cycleNumber){if(idleCount<3)return!1;let skipEvery=idleCount>=6?3:2;return cycleNumber%skipEvery!==0}class PrMonitorWorker{directory;config;onEvent;status="stopped";pollTimer=null;disposed=!1;circuitBreakerMap=new Map;idlePollCountMap=new Map;pollCycleCount=0;reviewStateMap=new Map;mergedOrClosedKeys=new Set;constructor(options){this.directory=options.directory,this.config=options.config,this.onEvent=options.onEvent}start(){if(this.disposed){log("[PrMonitorWorker] Cannot start — worker has been disposed");return}if(!this.directory){log("[PrMonitorWorker] Cannot start — no directory provided");return}if(!this.config.enabled){log("[PrMonitorWorker] Cannot start — pr_monitor.enabled is false");return}if(this.status==="running"||this.status==="starting"){log("[PrMonitorWorker] Already running or starting");return}if(this.status="starting",log("[PrMonitorWorker] Starting..."),this.pollTimer=setInterval(()=>{if(this.disposed||this.status!=="running")return;this.executePollCycle().catch((err)=>{log("[PrMonitorWorker] Unhandled poll cycle error",{error:err instanceof Error?err.message:String(err)})})},this.config.poll_interval_seconds*1000),typeof this.pollTimer.unref==="function")this.pollTimer.unref();this.status="running",log("[PrMonitorWorker] Started polling",{intervalSeconds:this.config.poll_interval_seconds})}stop(){if(this.status==="stopped"||this.status==="stopping")return;if(this.status="stopping",log("[PrMonitorWorker] Stopping..."),this.pollTimer)clearInterval(this.pollTimer),this.pollTimer=null;this.status="stopped",this.circuitBreakerMap.clear(),this.reviewStateMap.clear(),this.idlePollCountMap.clear(),this.pollCycleCount=0,log("[PrMonitorWorker] Stopped")}dispose(){this.stop(),this.disposed=!0,log("[PrMonitorWorker] Disposed")}getStatus(){return this.status}isRunning(){return this.status==="running"}async pollCycle(){if(this.disposed)return;await this.executePollCycle()}async executePollCycle(){log("[PrMonitorWorker] Poll cycle starting");try{let activeSubs=await _internals170.listActive(this.directory);if(activeSubs.length===0){log("[PrMonitorWorker] No active subscriptions"),await this.runSweep();return}let toPoll=activeSubs.slice(0,this.config.max_prs_per_cycle),concurrencyLimit=this.config.max_concurrent_pr_polls;this.pollCycleCount++,await this.processWithConcurrency(toPoll,concurrencyLimit),await this.runSweep()}catch(err){log("[PrMonitorWorker] Poll cycle error",{error:err instanceof Error?err.message:String(err)})}}async processWithConcurrency(subs,concurrencyLimit){let index=0,runNext=async()=>{while(index<subs.length){let currentIndex=index;if(index++,this.disposed)return;await this.pollWithTimeout(subs[currentIndex])}},workers=Array.from({length:Math.min(concurrencyLimit,subs.length)},()=>runNext());await Promise.all(workers)}async pollWithTimeout(sub){let timeoutMs=this.config.poll_timeout_ms,timer,timedOut=!1,timeoutPromise=new Promise((_,reject)=>{timer=setTimeout(()=>{timedOut=!0,reject(Error(`PR poll timed out after ${timeoutMs}ms for ${sub.repoFullName}#${sub.prNumber}`))},timeoutMs)});try{await Promise.race([this.pollSinglePr(sub,()=>timedOut),timeoutPromise])}catch(err){await this.handlePollError(sub,err instanceof Error?err:Error(String(err)))}finally{if(timer)clearTimeout(timer)}}async pollSinglePr(sub,isTimedOut){let correlationId=sub.correlationId;if(!this.circuitBreakerMap.has(correlationId)&&sub.errorCount>0)this.circuitBreakerMap.set(correlationId,{errorCount:sub.errorCount,suspendedUntil:0,cooldownLevel:0});let cb=this.circuitBreakerMap.get(correlationId);if(cb&&cb.suspendedUntil>Date.now()){log("[PrMonitorWorker] PR suspended by circuit breaker",{correlationId,suspendedUntil:new Date(cb.suspendedUntil).toISOString()});return}let idleCount=this.idlePollCountMap.get(correlationId)??0;if(shouldSkipIdlePoll(idleCount,this.pollCycleCount)){log("[PrMonitorWorker] Skipping idle PR poll (backoff)",{correlationId,idleCount});return}try{let[statusResult,commentsResult,mergeResult,reviewResult]=await Promise.all([_internals170.getPRStatus(sub.prNumber,sub.repoFullName,this.directory),_internals170.getPRComments(sub.prNumber,sub.repoFullName,this.directory),_internals170.getMergeState(sub.prNumber,sub.repoFullName,this.directory),_internals170.getPRReviewState(sub.prNumber,sub.repoFullName,this.directory)]);if(isTimedOut?.()){log("[PrMonitorWorker] Skipping late result — poll already timed out",{correlationId:sub.correlationId});return}let mergeGroupRunResult=null,mergeGroupRunFetchSucceeded=!1;try{mergeGroupRunResult=await _internals170.getMergeGroupRun(statusResult.statusCheckRollup,sub.repoFullName,this.directory),mergeGroupRunFetchSucceeded=!0}catch(err){log("[PrMonitorWorker] Failed to fetch merge group run",{correlationId:sub.correlationId,error:err instanceof Error?err.message:String(err)})}if(isTimedOut?.()){log("[PrMonitorWorker] Skipping late result — poll already timed out",{correlationId:sub.correlationId});return}let changes=this.computeChanges(sub,{status:statusResult,comments:commentsResult,merge:mergeResult,review:reviewResult,mergeGroupRun:mergeGroupRunResult},mergeGroupRunFetchSucceeded);if(await this.applyChanges(sub,changes,isTimedOut),!isTimedOut?.()){this.circuitBreakerMap.delete(correlationId),await _internals170.updateSnapshot(this.directory,correlationId,{errorCount:0,lastCheckedAt:Date.now()});let hasMeaningfulSnapshotChange=!1;for(let field of MEANINGFUL_SNAPSHOT_FIELDS)if(Object.hasOwn(changes.snapshotUpdates,field)){let newVal=changes.snapshotUpdates[field],priorVal=sub[field];if(newVal!==priorVal){hasMeaningfulSnapshotChange=!0;break}}if(changes.events.length>0||hasMeaningfulSnapshotChange)this.idlePollCountMap.set(correlationId,0);else this.idlePollCountMap.set(correlationId,(this.idlePollCountMap.get(correlationId)??0)+1)}}catch(err){if(isTimedOut?.()){log("[PrMonitorWorker] Skipping late error — poll already timed out",{correlationId:sub.correlationId});return}await this.handlePollError(sub,err instanceof Error?err:Error(String(err)))}}computeChanges(sub,current,mergeGroupRunFetchSucceeded){let events=[],snapshotUpdates={headRefOid:current.status.headRefOid,mergeableState:current.merge.mergeable,lastCheckedAt:Date.now()};if(mergeGroupRunFetchSucceeded)snapshotUpdates.mergeGroupRunStatus=current.mergeGroupRun?.status,snapshotUpdates.mergeGroupRunConclusion=current.mergeGroupRun?.conclusion??void 0,snapshotUpdates.mergeGroupRunHtmlUrl=current.mergeGroupRun?.htmlUrl;let isMerged=!1,isClosed=!1,newReviewDecision="";if(current.status.headRefOid!==sub.headRefOid)events.push({type:"pr.status.updated",payload:{prNumber:sub.prNumber,repoFullName:sub.repoFullName,prUrl:sub.prUrl,previousOid:sub.headRefOid,currentOid:current.status.headRefOid}});let currentCheckSet=this.serializeChecks(current.status.statusCheckRollup);if(snapshotUpdates.lastCheckRunSet=currentCheckSet,sub.lastCheckRunSet!==void 0&&currentCheckSet!==sub.lastCheckRunSet){let prevChecks=this.parseCheckSet(sub.lastCheckRunSet);this.computeCIEvents(sub,prevChecks,current.status.statusCheckRollup,events)}if(snapshotUpdates.lastCheckRunSet=currentCheckSet,current.comments.length>0){let sorted=[...current.comments].sort((a,b)=>a.createdAt.localeCompare(b.createdAt)),newComments;if(sub.lastCommentId===void 0)newComments=sorted;else{let lastIdx=sorted.findIndex((c)=>c.id===sub.lastCommentId);newComments=lastIdx>=0?sorted.slice(lastIdx+1):sorted}for(let comment of newComments)events.push({type:"pr.new.comment",payload:{prNumber:sub.prNumber,repoFullName:sub.repoFullName,prUrl:sub.prUrl,commentId:comment.id,author:comment.author,body:comment.body,createdAt:comment.createdAt,isReviewComment:comment.isReviewComment}});snapshotUpdates.lastCommentId=sorted[sorted.length-1].id}if(current.merge.mergeable==="CONFLICTING"&&sub.mergeableState!=="CONFLICTING")events.push({type:"pr.merge.conflict",payload:{prNumber:sub.prNumber,repoFullName:sub.repoFullName,prUrl:sub.prUrl,mergeableState:current.merge.mergeable}});else if(sub.mergeableState==="CONFLICTING"&&current.merge.mergeable!=="CONFLICTING")events.push({type:"pr.merge.conflict_resolved",payload:{prNumber:sub.prNumber,repoFullName:sub.repoFullName,prUrl:sub.prUrl,mergeableState:current.merge.mergeable}});let prevReviewDecision=this.reviewStateMap.get(sub.correlationId)??"";if(current.review.reviewDecision&&current.review.reviewDecision!==prevReviewDecision){if(current.review.reviewDecision==="CHANGES_REQUESTED"&&prevReviewDecision!=="CHANGES_REQUESTED")events.push({type:"pr.review.changes_requested",payload:{prNumber:sub.prNumber,repoFullName:sub.repoFullName,prUrl:sub.prUrl,reviewDecision:current.review.reviewDecision}});else if(current.review.reviewDecision==="APPROVED"&&prevReviewDecision!=="APPROVED")events.push({type:"pr.review.approved",payload:{prNumber:sub.prNumber,repoFullName:sub.repoFullName,prUrl:sub.prUrl,reviewDecision:current.review.reviewDecision}});newReviewDecision=current.review.reviewDecision}if(current.status.state==="MERGED")isMerged=!0,events.push({type:"pr.merged",payload:{prNumber:sub.prNumber,repoFullName:sub.repoFullName,prUrl:sub.prUrl,headRefOid:current.status.headRefOid}}),snapshotUpdates.isWatching=!1;if(current.status.state==="CLOSED")isClosed=!0,events.push({type:"pr.closed",payload:{prNumber:sub.prNumber,repoFullName:sub.repoFullName,prUrl:sub.prUrl}}),snapshotUpdates.isWatching=!1;return snapshotUpdates.hasUnaddressedEvents=events.length>0,{events,snapshotUpdates,isMerged,isClosed,newReviewDecision}}computeCIEvents(sub,prevChecks,currentChecks,events){let allPassed=!0,prevMap=new Map(prevChecks.map((c)=>[c.name,c.conclusion])),newlyFailedChecks=[];for(let check3 of currentChecks){if(check3.conclusion==="failure"||check3.conclusion==="FAILURE"){let prev=prevMap.get(check3.name);if(prev!=="failure"&&prev!=="FAILURE")newlyFailedChecks.push({name:check3.name,conclusion:check3.conclusion})}if(check3.conclusion!=="success"&&check3.conclusion!=="SUCCESS")allPassed=!1}if(newlyFailedChecks.length>0)events.push({type:"pr.ci.failed",payload:{prNumber:sub.prNumber,repoFullName:sub.repoFullName,prUrl:sub.prUrl,failedChecks:newlyFailedChecks}});if(allPassed&&currentChecks.length>0){if(prevChecks.some((c)=>c.conclusion!=="success"&&c.conclusion!=="SUCCESS")||prevChecks.length===0)events.push({type:"pr.ci.passed",payload:{prNumber:sub.prNumber,repoFullName:sub.repoFullName,prUrl:sub.prUrl,checkCount:currentChecks.length}})}}async applyChanges(sub,changes,isTimedOut){if(isTimedOut?.()){log("[PrMonitorWorker] Skipping change application — poll already timed out",{correlationId:sub.correlationId});return}for(let{type,payload}of changes.events)await this.emitEvent(type,payload);if(isTimedOut?.()){log("[PrMonitorWorker] Skipping state mutations — poll timed out during event emission",{correlationId:sub.correlationId});return}if(changes.newReviewDecision)this.reviewStateMap.set(sub.correlationId,changes.newReviewDecision);if(changes.isMerged&&this.config.auto_unsubscribe_on_merge||changes.isClosed&&this.config.auto_unsubscribe_on_close)this.mergedOrClosedKeys.add(`${sub.repoFullName}::${sub.prNumber}`);if(changes.isMerged&&this.config.auto_unsubscribe_on_merge){await _internals170.unsubscribe(this.directory,sub.correlationId),this.reviewStateMap.delete(sub.correlationId),this.circuitBreakerMap.delete(sub.correlationId),log("[PrMonitorWorker] Auto-unsubscribed merged PR",{correlationId:sub.correlationId});return}if(changes.isClosed&&this.config.auto_unsubscribe_on_close){await _internals170.unsubscribe(this.directory,sub.correlationId),this.reviewStateMap.delete(sub.correlationId),this.circuitBreakerMap.delete(sub.correlationId),log("[PrMonitorWorker] Auto-unsubscribed closed PR",{correlationId:sub.correlationId});return}if(isTimedOut?.()){log("[PrMonitorWorker] Skipping snapshot update — poll timed out before write",{correlationId:sub.correlationId});return}await _internals170.updateSnapshot(this.directory,sub.correlationId,changes.snapshotUpdates)}async handlePollError(sub,error93){let correlationId=sub.correlationId,cb=this.circuitBreakerMap.get(correlationId)??{errorCount:0,suspendedUntil:0,cooldownLevel:0};if(cb.errorCount++,await _internals170.updateSnapshot(this.directory,correlationId,{errorCount:cb.errorCount,lastCheckedAt:Date.now()}),cb.errorCount>=this.config.failure_threshold){cb.cooldownLevel++;let cooldownSeconds=Math.min(this.config.cooldown_seconds*2**(cb.cooldownLevel-1),this.config.max_cooldown_seconds);cb.suspendedUntil=Date.now()+cooldownSeconds*1000,this.circuitBreakerMap.set(correlationId,cb),error48("[PrMonitorWorker] Circuit breaker tripped for PR",{correlationId,errorCount:cb.errorCount,cooldownSeconds}),await this.emitEvent("pr.error",{prNumber:sub.prNumber,repoFullName:sub.repoFullName,prUrl:sub.prUrl,reason:"circuit_breaker",errorCount:cb.errorCount,cooldownSeconds})}else this.circuitBreakerMap.set(correlationId,cb),log("[PrMonitorWorker] Poll error for PR",{correlationId,errorCount:cb.errorCount,error:error93.message})}async emitEvent(type,payload){let event={type,timestamp:Date.now(),payload,source:"pr-monitor-worker"};try{await _internals170.getGlobalEventBus().publish(type,payload,"pr-monitor-worker")}catch(err){log("[PrMonitorWorker] Event publish failed",{type,error:err instanceof Error?err.message:String(err)})}if(this.onEvent)try{this.onEvent(event)}catch{}}async runSweep(){if(this.config.cleanup_ttl_days>0)try{let keysToPass=this.mergedOrClosedKeys.size>0?this.mergedOrClosedKeys:void 0;await _internals170.sweepStale(this.directory,this.config.cleanup_ttl_days,keysToPass)}catch(err){log("[PrMonitorWorker] Sweep failed",{error:err instanceof Error?err.message:String(err)})}finally{this.mergedOrClosedKeys.clear()}else this.mergedOrClosedKeys.clear()}serializeChecks(checks5){return JSON.stringify(checks5.map((c)=>({n:c.name,c:c.conclusion})))}parseCheckSet(serialized3){try{return JSON.parse(serialized3).map((p)=>({name:p.n,conclusion:p.c}))}catch{return[]}}}var _internals170={getPRStatus,getPRComments,getMergeState,getMergeGroupRun,getPRReviewState,listActive,updateSnapshot,unsubscribe,sweepStale,getGlobalEventBus};init_queue();init_status_artifact();init_trigger();init_worker();import{createHash as createHash58}from"node:crypto";import*as path220 from"node:path";init_zod();init_task_envelope();init_workspace_snapshot();init_plan_schema();init_schema();init_task_result_classifier();init_utils2();init_ledger();init_manager();init_utils3();init_atomic_write();init_lock();init_task_file();import{createHash as createHash57}from"node:crypto";import*as fs116 from"node:fs";import*as path219 from"node:path";var PHASE_PARTICIPATION_FILE="evidence/phase-participation.json",PHASE_PARTICIPATION_QUARANTINE_DIR="evidence/phase-participation-quarantine",MAX_PHASE_PARTICIPATION_BYTES=262144,MAX_PHASE_PARTICIPATION_PENDING=128,MAX_PHASE_PARTICIPATION_RECEIPTS=128,MAX_PHASE_PARTICIPATION_QUARANTINE_FILES=16,MAX_PHASE_PARTICIPATION_QUARANTINE_BYTES=1048576,MAX_PHASE_PARTICIPATION_QUARANTINE_DIRECTORY_ENTRIES=64,MAX_PENDING_IN_MEMORY=128,MAX_ID_CHARS=256,WorkspaceSchema2=exports_external.object({directory:exports_external.string().max(4096),gitHead:exports_external.string().max(256).nullable(),prHeadSha:exports_external.string().max(256).nullable()}).strict(),BindingSchema=exports_external.object({role:exports_external.string().min(1).max(120),prefixedRole:exports_external.string().min(1).max(120),planId:exports_external.string().min(1).max(512),planIdentityHash:exports_external.string().length(64),planStructureHash:exports_external.string().length(64),phase:exports_external.number().int().nonnegative(),taskId:exports_external.string().min(1).max(120).nullable(),parentSessionId:exports_external.string().min(1).max(MAX_ID_CHARS),callId:exports_external.string().min(1).max(MAX_ID_CHARS),policyDigest:exports_external.string().length(64),workspace:WorkspaceSchema2,capturedAt:exports_external.number().int().nonnegative()}).strict(),PendingSchema=BindingSchema.extend({childSessionId:exports_external.string().min(1).max(MAX_ID_CHARS)}).strict(),ReceiptSchema=PendingSchema.extend({receiptId:exports_external.string().length(64),resultDigest:exports_external.string().length(64),completedAt:exports_external.number().int().nonnegative(),childIdentityAvailable:exports_external.boolean()}).strict(),StoreSchema=exports_external.object({schemaVersion:exports_external.literal(1),pending:exports_external.array(PendingSchema).max(MAX_PHASE_PARTICIPATION_PENDING),receipts:exports_external.array(ReceiptSchema).max(MAX_PHASE_PARTICIPATION_RECEIPTS)}).strict(),foregroundReservations=new Map;function emptyStore(){return{schemaVersion:1,pending:[],receipts:[]}}function correlationKey(parentSessionId,callId){return`${parentSessionId}\x00${callId}`}function sha2564(value){return createHash57("sha256").update(value).digest("hex")}function policyDigest(policy){return sha2564(stableCanonicalStringify(policy??{}))}function captureParticipationWorkspace(directory){let workspace=captureWorkspaceSnapshot(directory,{resolveCurrentPrHeadSha:!0});return{directory:workspace.directory,gitHead:workspace.gitHead,prHeadSha:workspace.prHeadSha}}function boundedPut(binding){let key=correlationKey(binding.parentSessionId,binding.callId);foregroundReservations.delete(key),foregroundReservations.set(key,binding);while(foregroundReservations.size>MAX_PENDING_IN_MEMORY){let oldest=foregroundReservations.keys().next().value;if(!oldest)break;foregroundReservations.delete(oldest)}}function takeBinding(parentSessionId,callId){let key=correlationKey(parentSessionId,callId),binding=foregroundReservations.get(key)??null;return foregroundReservations.delete(key),binding}async function persistWithBindingRecovery(directory,binding,operation){try{await withEvidenceLock(directory,PHASE_PARTICIPATION_FILE,"docs","phase-participation",operation)}catch(error93){throw boundedPut(binding),error93}}function buildBinding(input){return{role:stripKnownSwarmPrefix(input.role),prefixedRole:input.role,planId:derivePlanId(input.plan),planIdentityHash:derivePlanIdentityHash(input.plan),planStructureHash:computePlanStructureHash(input.plan),phase:input.phase,taskId:input.taskId,parentSessionId:input.parentSessionId,callId:input.callId,policyDigest:policyDigest(input.policy),workspace:captureParticipationWorkspace(input.directory),capturedAt:Date.now()}}function extractPlanTaskId2(args2){let raw=args2.task_id??args2.taskId;if(typeof raw==="string"&&raw.trim().length>0)return raw.trim().slice(0,120);let text=[args2.prompt,args2.description,args2.task].filter((value)=>typeof value==="string").join(`
6322
- `);return/(?:^|\n)\s*TASK:\s*(\d+\.\d+(?:\.\d+)*)\b/i.exec(text)?.[1]??null}function storePath3(directory){return validateSwarmPath(directory,PHASE_PARTICIPATION_FILE)}function readRawStore(directory){let filePath;try{filePath=storePath3(directory)}catch(error93){return{status:"unreadable",error:error93}}let descriptor,bytes;try{let pathStat=fs116.lstatSync(filePath);if(pathStat.isSymbolicLink()||!pathStat.isFile())return{status:"unreadable",error:Error("Participation projection is not a regular file")};if(pathStat.size>MAX_PHASE_PARTICIPATION_BYTES)return{status:"oversized",bytes:pathStat.size};descriptor=fs116.openSync(filePath,fs116.constants.O_RDONLY|(fs116.constants.O_NOFOLLOW??0));let openedStat=fs116.fstatSync(descriptor);if(!openedStat.isFile()||openedStat.dev!==pathStat.dev||openedStat.ino!==pathStat.ino)return{status:"unreadable",error:Error("Participation projection changed while it was being opened")};if(openedStat.size>MAX_PHASE_PARTICIPATION_BYTES)return{status:"oversized",bytes:openedStat.size};let bounded=Buffer.allocUnsafe(MAX_PHASE_PARTICIPATION_BYTES+1),offset=0;while(offset<bounded.byteLength){let read=fs116.readSync(descriptor,bounded,offset,bounded.byteLength-offset,null);if(read===0)break;offset+=read}if(offset>MAX_PHASE_PARTICIPATION_BYTES)return{status:"oversized",bytes:offset};bytes=bounded.subarray(0,offset)}catch(error93){if(error93.code==="ENOENT")return{status:"missing"};return{status:"unreadable",error:error93}}finally{if(descriptor!==void 0)try{fs116.closeSync(descriptor)}catch{}}try{return{status:"valid",store:StoreSchema.parse(JSON.parse(bytes.toString("utf8")))}}catch{return{status:"corrupt",bytes}}}async function atomicWriteBytes(filePath,bytes){await atomicWriteSwarmFile(filePath,bytes)}async function readBoundedRegularFile(filePath,maxBytes){let pathStat=await fs116.promises.lstat(filePath);if(pathStat.isSymbolicLink()||!pathStat.isFile()||pathStat.size>maxBytes)throw Error("bounded evidence artifact is not a permitted regular file");let handle=await fs116.promises.open(filePath,fs116.constants.O_RDONLY|(fs116.constants.O_NOFOLLOW??0));try{let openedStat=await handle.stat();if(!openedStat.isFile()||openedStat.dev!==pathStat.dev||openedStat.ino!==pathStat.ino||openedStat.size>maxBytes)throw Error("bounded evidence artifact changed while being opened");let bounded=Buffer.allocUnsafe(maxBytes+1),offset=0;while(offset<bounded.byteLength){let{bytesRead}=await handle.read(bounded,offset,bounded.byteLength-offset,null);if(bytesRead===0)break;offset+=bytesRead}if(offset>maxBytes)throw Error("bounded evidence artifact exceeds its byte limit");return bounded.subarray(0,offset)}finally{try{await handle.close()}catch{}}}function quarantineFullError(){return Error("PHASE_PARTICIPATION_QUARANTINE_FULL: preserved corrupt evidence reached its bounded retention limit; an operator must archive the quarantine before docs can be re-dispatched.")}async function quarantineCorruptBytes(directory,bytes){let digest2=sha2564(bytes),quarantineDir=validateSwarmPath(directory,PHASE_PARTICIPATION_QUARANTINE_DIR);await fs116.promises.mkdir(quarantineDir,{recursive:!0});let quarantineStat=await fs116.promises.lstat(quarantineDir);if(quarantineStat.isSymbolicLink()||!quarantineStat.isDirectory())throw Error("PHASE_PARTICIPATION_QUARANTINE_UNREADABLE: quarantine is not a regular directory.");let target=validateSwarmPath(directory,`${PHASE_PARTICIPATION_QUARANTINE_DIR}/${digest2}.bin`);try{if(!(await readBoundedRegularFile(target,MAX_PHASE_PARTICIPATION_BYTES)).equals(bytes))throw Error("hash-addressed quarantine content mismatch");return}catch(error93){if(error93.code!=="ENOENT")throw error93}let count=0,totalBytes=0,scanned=0,handle=await fs116.promises.opendir(quarantineDir,{bufferSize:16});try{for await(let entry of handle){if(scanned+=1,scanned>MAX_PHASE_PARTICIPATION_QUARANTINE_DIRECTORY_ENTRIES)throw quarantineFullError();if(!entry.isFile()||!/^[a-f0-9]{64}\.bin$/.test(entry.name))continue;count+=1;let candidate2=validateSwarmPath(directory,`${PHASE_PARTICIPATION_QUARANTINE_DIR}/${entry.name}`),candidateStat=await fs116.promises.lstat(candidate2);if(candidateStat.isSymbolicLink()||!candidateStat.isFile())throw Error("PHASE_PARTICIPATION_QUARANTINE_UNREADABLE: invalid quarantine artifact.");if(totalBytes+=candidateStat.size,count>=MAX_PHASE_PARTICIPATION_QUARANTINE_FILES||totalBytes+bytes.byteLength>MAX_PHASE_PARTICIPATION_QUARANTINE_BYTES)throw quarantineFullError()}}finally{try{await handle.close()}catch{}}await atomicWriteBytes(target,bytes)}async function loadWritableStoreUnderLock(directory){let read=readRawStore(directory);if(read.status==="missing")return emptyStore();if(read.status==="valid")return read.store;if(read.status==="corrupt")return await quarantineCorruptBytes(directory,read.bytes),emptyStore();if(read.status==="oversized")throw Error(`PHASE_PARTICIPATION_OVERSIZED: ${read.bytes} bytes exceeds ${MAX_PHASE_PARTICIPATION_BYTES}; operator action is required before docs can be re-dispatched.`);throw Error("PHASE_PARTICIPATION_UNREADABLE: operator action is required before docs can be re-dispatched.")}async function writeStore(directory,store){let validatedStore=StoreSchema.parse(store);validatedStore.pending.sort((left,right)=>left.capturedAt-right.capturedAt),validatedStore.receipts.sort((left,right)=>left.completedAt-right.completedAt);let serialized3=JSON.stringify(validatedStore,null,2);while(Buffer.byteLength(serialized3,"utf8")>MAX_PHASE_PARTICIPATION_BYTES){let pendingTime=validatedStore.pending[0]?.capturedAt??1/0,receiptTime=validatedStore.receipts[0]?.completedAt??1/0;if(pendingTime===1/0&&receiptTime===1/0)throw Error("PHASE_PARTICIPATION_WRITE_OVERSIZED: even an empty participation store exceeds its byte limit.");if(pendingTime<=receiptTime)validatedStore.pending.shift();else validatedStore.receipts.shift();validatedStore=StoreSchema.parse(validatedStore),serialized3=JSON.stringify(validatedStore,null,2)}await fs116.promises.mkdir(path219.dirname(storePath3(directory)),{recursive:!0}),await atomicWriteFile(storePath3(directory),serialized3)}function bindingMatchesPlan(binding,plan,phase){return binding.planId===derivePlanId(plan)&&binding.planIdentityHash===derivePlanIdentityHash(plan)&&binding.planStructureHash===computePlanStructureHash(plan)&&binding.phase===phase}function workspaceIdentityIsFresh(expected,current){return path219.resolve(expected.directory)===path219.resolve(current.directory)&&expected.gitHead===current.gitHead&&expected.prHeadSha===current.prHeadSha}function resultText(output){if(!output||typeof output!=="object")return{text:"",childSessionId:null};let record3=output,rawOutput=typeof record3.output==="string"?record3.output:"",envelope=parseTaskEnvelope(rawOutput);if(envelope?.state==="completed")return{text:envelope.resultText??"",childSessionId:envelope.sessionId};return{text:rawOutput,childSessionId:null}}function envelopeFromOutput(output){if(typeof output==="string")return parseTaskEnvelope(output);if(!output||typeof output!=="object")return null;let rawOutput=output.output;return typeof rawOutput==="string"?parseTaskEnvelope(rawOutput):null}function validateMetadata(output,parentSessionId,childSessionId){if(!output||typeof output!=="object")return{valid:!0,childSessionId};let metadata=output.metadata;if(!metadata||typeof metadata!=="object")return{valid:!0,childSessionId};let meta3=metadata;if(typeof meta3.parentSessionId==="string"&&meta3.parentSessionId!==parentSessionId)return{valid:!1,childSessionId:null};let metadataChild=typeof meta3.sessionId==="string"&&meta3.sessionId.length>0?meta3.sessionId:null;if(childSessionId&&metadataChild&&childSessionId!==metadataChild)return{valid:!1,childSessionId:null};return{valid:!0,childSessionId:childSessionId??metadataChild}}function addReceipt(store,pending,text,childIdentityAvailable){let receiptId=sha2564(stableCanonicalStringify({parentSessionId:pending.parentSessionId,callId:pending.callId,childSessionId:pending.childSessionId,planIdentityHash:pending.planIdentityHash,planStructureHash:pending.planStructureHash,phase:pending.phase,role:pending.role})),receipt={...pending,receiptId,resultDigest:sha2564(text),completedAt:Date.now(),childIdentityAvailable};store.receipts=store.receipts.filter((existing)=>existing.receiptId!==receiptId&&!(existing.planIdentityHash===receipt.planIdentityHash&&existing.planStructureHash===receipt.planStructureHash&&existing.phase===receipt.phase&&existing.role===receipt.role)),store.receipts.push(receipt),store.receipts=store.receipts.slice(-MAX_PHASE_PARTICIPATION_RECEIPTS)}async function reserveApprovedPhaseParticipation(input){if(input.tool.toLowerCase()!=="task")return;let rawRole=input.args.subagent_type;if(typeof rawRole!=="string"||stripKnownSwarmPrefix(rawRole)!=="docs")return;let plan=await loadPlan(input.directory);if(!plan)return;let binding=buildBinding({plan,phase:getCurrentPhase(plan),role:rawRole,parentSessionId:input.parentSessionId,callId:input.callId,taskId:extractPlanTaskId2(input.args),policy:input.policy,directory:input.directory});await withEvidenceLock(input.directory,PHASE_PARTICIPATION_FILE,"docs","phase-participation",async()=>{let store=await loadWritableStoreUnderLock(input.directory);await writeStore(input.directory,store)}),boundedPut(binding)}async function observePhaseParticipationToolResult(input){if(input.tool.toLowerCase()!=="task")return;let binding=takeBinding(input.parentSessionId,input.callId);if(!binding)return;let envelope=envelopeFromOutput(input.output);if(envelope?.state==="running"){let{subagentSessionId}=extractDispatchIds(input.output);if(!subagentSessionId||subagentSessionId!==envelope.sessionId)return;let pending2={...binding,childSessionId:subagentSessionId};await persistWithBindingRecovery(input.directory,binding,async()=>{let store=await loadWritableStoreUnderLock(input.directory);store.pending=store.pending.filter((existing)=>existing.childSessionId!==pending2.childSessionId&&!(existing.parentSessionId===pending2.parentSessionId&&existing.callId===pending2.callId)),store.pending.push(pending2),store.pending=store.pending.slice(-MAX_PHASE_PARTICIPATION_PENDING),await writeStore(input.directory,store)});return}if(envelope&&envelope.state!=="completed")return;if(classifyTaskResult(input.output)!=="success")return;let extracted=resultText(input.output),text=extracted.text.trim();if(!text)return;let metadata=validateMetadata(input.output,input.parentSessionId,extracted.childSessionId);if(!metadata.valid)return;let childSessionId=metadata.childSessionId,currentPlan=await loadPlan(input.directory);if(!currentPlan||!bindingMatchesPlan(binding,currentPlan,binding.phase))return;if(!workspaceIdentityIsFresh(binding.workspace,captureParticipationWorkspace(input.directory)))return;let pending={...binding,childSessionId:childSessionId??`unavailable:${sha2564(correlationKey(input.parentSessionId,input.callId))}`};await persistWithBindingRecovery(input.directory,binding,async()=>{let store=await loadWritableStoreUnderLock(input.directory);addReceipt(store,pending,text,childSessionId!==null),await writeStore(input.directory,store)})}async function completeBackgroundPhaseParticipation(input){if(stripKnownSwarmPrefix(input.record.normalizedAgent)!=="docs")return!1;let text=input.resultText.trim();if(!text)return!1;return withEvidenceLock(input.directory,PHASE_PARTICIPATION_FILE,"docs","phase-participation",async()=>{let store=await loadWritableStoreUnderLock(input.directory),currentPlan=await loadPlan(input.directory),existingReceipt=store.receipts.find((receipt)=>receipt.childSessionId===input.record.subagentSessionId&&receipt.parentSessionId===input.record.parentSessionId&&receipt.callId===input.record.callID&&receipt.role===input.record.normalizedAgent&&receipt.prefixedRole===input.record.swarmPrefixedAgent&&receipt.taskId===input.record.planTaskId);if(existingReceipt&&currentPlan&&bindingMatchesPlan(existingReceipt,currentPlan,existingReceipt.phase))return!0;let pending=store.pending.find((candidate2)=>candidate2.childSessionId===input.record.subagentSessionId&&candidate2.parentSessionId===input.record.parentSessionId&&candidate2.callId===input.record.callID&&candidate2.role===input.record.normalizedAgent&&candidate2.prefixedRole===input.record.swarmPrefixedAgent&&candidate2.taskId===input.record.planTaskId);if(!pending)return!1;let plan=currentPlan;if(!plan||!bindingMatchesPlan(pending,plan,pending.phase))return!1;if(!workspaceIdentityIsFresh(pending.workspace,captureParticipationWorkspace(input.directory)))return!1;if(pending.taskId!==null&&input.record.ingestion?.state!=="consumed")return!1;return addReceipt(store,pending,text,!0),store.pending=store.pending.filter((candidate2)=>candidate2.childSessionId!==pending.childSessionId),await writeStore(input.directory,store),!0})}function readPhaseParticipation(directory,plan,phase,role){let read=readRawStore(directory);if(read.status!=="valid")return{status:read.status,found:!1};let canonicalRole2=stripKnownSwarmPrefix(role),currentWorkspace=captureParticipationWorkspace(directory);return{status:"valid",found:read.store.receipts.some((receipt)=>receipt.role===canonicalRole2&&bindingMatchesPlan(receipt,plan,phase)&&workspaceIdentityIsFresh(receipt.workspace,currentWorkspace))}}init_gate_evidence();init_worktree_isolation();init_helpers();init_state2();init_logger();init_merge();init_pending_delegations();init_gate_evidence();init_gate_evidence_classification();init_review_receipt_collector();init_reviewer_scope_file_fingerprint();init_scope_binding();init_state2();init_logger();init_workspace_snapshot();var GATE_EVIDENCE_ROLES=new Set(["reviewer","test_engineer","docs","designer","critic","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","explorer","sme"]);function structuredStageBVerdict(role,text,taskId){let escapedTaskId=taskId.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),match=(role==="reviewer"?new RegExp(`^\\[REVIEWED\\]\\s*\\|\\s*(?:task-)?${escapedTaskId}\\s*\\|\\s*(APPROVED|REJECTED|CONCERNS)\\s*\\|`,"im"):new RegExp(`^\\[TESTED\\]\\s*\\|\\s*(?:task-)?${escapedTaskId}\\s*\\|\\s*(PASS|FAIL|SKIPPED)\\s*\\|`,"im")).exec(text);if(!match)return null;return match[1]==="APPROVED"||match[1]==="PASS"?"pass":"fail"}function normalizeAttributionPath(file3){let normalized=file3.trim().replaceAll("\\","/").replace(/^\.\/+/,""),hasControlCharacter5=[...normalized].some((character)=>{let code=character.charCodeAt(0);return code<=31||code===127});if(!normalized||normalized.startsWith("/")||/^[A-Za-z]:\//.test(normalized)||normalized===".."||normalized.startsWith("../")||normalized.split("/").includes("..")||hasControlCharacter5)return null;return normalized}function normalizedPathSet(files){if(!files)return null;let normalized=new Set;for(let file3 of files){let candidate2=normalizeAttributionPath(file3);if(!candidate2)return null;normalized.add(candidate2)}return normalized}function pathSetsEqual(left,right){return left.size===right.size&&[...left].every((file3)=>right.has(file3))}function hasDistinctBackgroundOwner(input){if(!Number.isFinite(input.candidateCreatedAt)||!Number.isFinite(input.candidateCompletedAt)||input.candidateCreatedAt>input.candidateCompletedAt)return!1;let liveOwners=[...(swarmState.agentSessions.get(input.parentSessionID)?.reviewerScopeGenerations??new Map).values()].filter((generation)=>{if(generation.background!==!0||generation.taskId===input.taskId&&generation.coderCallID===input.coderCallID)return!1;let declared=normalizedPathSet(generation.declaredFiles),routed=normalizedPathSet(generation.modifiedFiles),fingerprints=generation.modifiedFileFingerprints.filter((entry)=>normalizeAttributionPath(entry.file)===input.file),ownerCompletedAt=generation.readyAt??input.candidateCompletedAt;return Number.isFinite(generation.createdAt)&&Number.isFinite(ownerCompletedAt)&&generation.createdAt<=input.candidateCompletedAt&&input.candidateCreatedAt<=ownerCompletedAt&&declared?.has(input.file)===!0&&routed?.has(input.file)===!0&&fingerprints.length===1&&reviewerScopeFileFingerprintsEqual(fingerprints[0],input.fingerprint)}),historicalOwners=getReviewerScopeOwnershipHistory({parentSessionID:input.parentSessionID}).filter((owner)=>{if(owner.taskId===input.taskId&&owner.coderCallID===input.coderCallID)return!1;let declared=normalizedPathSet(owner.declaredFiles),routed=normalizedPathSet(owner.modifiedFiles),fingerprints=owner.modifiedFileFingerprints.filter((entry)=>normalizeAttributionPath(entry.file)===input.file);return owner.parentSessionID===input.parentSessionID&&owner.background===!0&&Number.isFinite(owner.createdAt)&&Number.isFinite(owner.readyAt)&&owner.createdAt<=input.candidateCompletedAt&&input.candidateCreatedAt<=owner.readyAt&&declared?.has(input.file)===!0&&routed?.has(input.file)===!0&&fingerprints.length===1&&reviewerScopeFileFingerprintsEqual(fingerprints[0],input.fingerprint)});return liveOwners.length+historicalOwners.length===1}function isBackgroundGateBearingRecord(record3){return record3.batchId===void 0&&record3.evidenceTaskId!==null&&GATE_EVIDENCE_ROLES.has(record3.normalizedAgent)}function validateStageBWorkspace(directory,record3){let actualWorkspace=captureWorkspaceSnapshot(directory,{scope:record3.workspace?.scope??null,prHeadSha:record3.workspace?.prHeadSha??null,resolveCurrentPrHeadSha:record3.workspace?.prHeadSha!==null}),check3=compareStageBWorkspace(record3,actualWorkspace);return{...check3,ok:!check3.stale}}function compareStageBWorkspace(record3,actualWorkspace){let expectedWorkspace=record3.normalizedAgent==="docs"&&record3.workspace?{...record3.workspace,dirtyHash:null}:record3.workspace;return compareWorkspaceSnapshots(expectedWorkspace,actualWorkspace)}async function ingestBackgroundStageBCompletion(args2){let taskId=args2.record.evidenceTaskId??args2.record.planTaskId;if(!taskId)return{ok:!0,consumed:!1};if(args2.record.normalizedAgent==="coder"){let taskChangeContext=args2.record.taskChangeContext,settledFiles=args2.record.coderSettlement?.state==="settled"?args2.record.coderSettlement.observedFiles:void 0,observedFiles=settledFiles!==void 0?settledFiles:taskChangeContext?changedFilesSinceSnapshot(taskChangeContext.baseline.directory,taskChangeContext.baseline):null;if(observedFiles===null)return{ok:!1,consumed:!1,stale:!0,reason:"background coder files could not be attributed to a clean immutable baseline"};try{let observedSet=normalizedPathSet(observedFiles),declaredSet=normalizedPathSet(taskChangeContext?.declaredFiles??null),completionTime=args2.record.completedAt??args2.record.updatedAt,attributedFiles=observedFiles??[];if(args2.reviewerReceiptOptions?.config?.enabled!==!0){if(observedSet&&declaredSet)attributedFiles=[...observedSet].filter((file3)=>declaredSet.has(file3))}if(args2.reviewerReceiptOptions?.config?.enabled===!0){if(!observedSet||!declaredSet)return{ok:!1,consumed:!1,reason:"background coder changed-file attribution could not be reconstructed exactly"};attributedFiles=[...observedSet].filter((file3)=>declaredSet.has(file3));let generation=getReviewerScopeGenerationForCoderCall({parentSessionID:args2.record.parentSessionId,taskId,coderCallID:args2.record.callID}),generationScope=normalizedPathSet(generation?.declaredFiles??null),routedFiles=normalizedPathSet(generation?.modifiedFiles??null),routedFingerprints=generation?.modifiedFileFingerprints??null;if(generation?.status==="collecting"&&generation.background===!0&&observedSet.size===0&&routedFiles?.size===0&&declaredSet){if(markReviewerScopeGenerationNoChange({parentSessionID:args2.record.parentSessionId,taskId,coderCallID:args2.record.callID}))return{ok:!0,consumed:!0}}let captureRoot=generation?.captureDirectory?.trim()||args2.directory,observedFingerprints=new Map;for(let file3 of observedSet){let captured=captureReviewerScopeFileFingerprint(captureRoot,file3);if(captured.kind==="capture_failed")return{ok:!1,consumed:!1,reason:`background coder post-write fingerprint could not be reconstructed exactly (${captured.code}${captured.retryable?" (retryable)":" (permanent)"} on ${captured.file})`};let fingerprint2=reviewerScopeCaptureToFingerprint(captured);if(!fingerprint2)return{ok:!1,consumed:!1,reason:"background coder post-write fingerprint returned an unusable result"};observedFingerprints.set(file3,fingerprint2)}let changedWithinDeclaredScope=new Set([...observedSet].filter((file3)=>declaredSet.has(file3)&&generationScope?.has(file3))),observedOutsideCurrentScope=[...observedSet].filter((file3)=>!generationScope?.has(file3));if(generation?.status!=="collecting"&&generation?.status!=="ready"||generation.background!==!0||!generationScope||!routedFiles||!routedFingerprints||routedFiles.size===0||!pathSetsEqual(declaredSet,generationScope)||!pathSetsEqual(routedFiles,changedWithinDeclaredScope)||reviewerScopeGenerationHasDeclaredOverlap({parentSessionID:args2.record.parentSessionId,taskId,coderCallID:args2.record.callID,declaredFiles:generation.declaredFiles})||observedOutsideCurrentScope.some((file3)=>!hasDistinctBackgroundOwner({parentSessionID:args2.record.parentSessionId,taskId,coderCallID:args2.record.callID,file:file3,fingerprint:observedFingerprints.get(file3),candidateCreatedAt:args2.record.createdAt,candidateCompletedAt:completionTime}))||[...routedFiles].some((file3)=>{let fingerprints=routedFingerprints.filter((entry)=>normalizeAttributionPath(entry.file)===file3),observedFingerprint=observedFingerprints.get(file3);return!observedSet.has(file3)||!declaredSet.has(file3)||!generationScope.has(file3)||fingerprints.length!==1||!observedFingerprint||!reviewerScopeFileFingerprintsEqual(fingerprints[0],observedFingerprint)}))return{ok:!1,consumed:!1,reason:"background coder scope handoff could not be reconstructed exactly"};attributedFiles=[...routedFiles];for(let file3 of routedFiles){let fingerprint2=observedFingerprints.get(file3);if(fingerprint2)recordReviewerScopeGenerationFileFingerprint({parentSessionID:args2.record.parentSessionId,taskId,coderCallID:args2.record.callID,fingerprint:fingerprint2})}}let parentSession=swarmState.agentSessions.get(args2.record.parentSessionId);if(parentSession){let state=getTaskState(parentSession,taskId);if(state!=="idle"&&state!=="coder_delegated"&&state!=="rework_required")return{ok:!1,consumed:!1,reason:`background coder completion is late for task ${taskId}: current state is ${state}`}}let accepted=attributedFiles.length>0,expectedGeneration=args2.record.taskChangeContext?.workflowGeneration??0,transitionId=`background-coder:${args2.record.correlationId}`,existingEvidence=await readTaskEvidence(args2.directory,taskId),existingWorkflow=getTaskWorkflowSnapshot(existingEvidence),updated=existingWorkflow.authoritative&&existingWorkflow.lastTransitionId===transitionId&&existingWorkflow.lastOutcome===(accepted?"accepted_mutation":"dispatch_no_mutation")&&existingWorkflow.generation===expectedGeneration+(accepted?1:0)?existingEvidence:await transitionTaskWorkflowEvidence(args2.directory,taskId,accepted?{type:"accepted_mutation",agentType:"coder",context:{testEngineerExempt:isMarkdownOnlyTaskChange(taskChangeContext?.declaredFiles,attributedFiles)},expectedGeneration,transitionId}:{type:"dispatch_no_mutation",agentType:"coder",expectedGeneration,transitionId});if(accepted){let workflow=getTaskWorkflowSnapshot(updated),parentSession2=swarmState.agentSessions.get(args2.record.parentSessionId);if(parentSession2){if(!recordModifiedFilesForTask(parentSession2,taskId,attributedFiles))warn(`[background] durable coder mutation for ${taskId} exceeded session file-attribution capacity`);parentSession2.taskWorkflowStates.set(taskId,"coder_delegated"),parentSession2.stageBCompletion?.delete(taskId),parentSession2.taskCouncilApproved?.delete(taskId),parentSession2.taskCouncilWorkflowGeneration?.delete(taskId),updateTaskWorkflowCache(parentSession2,taskId,workflow)}}if(args2.reviewerReceiptOptions?.config?.enabled===!0){let laneGeneration=getReviewerScopeGenerationForCoderCall({parentSessionID:args2.record.parentSessionId,taskId,coderCallID:args2.record.callID});if(laneGeneration!==null&&laneGeneration.workspaceIdentity!==canonicalWorkspaceIdentity(args2.directory))return markReviewerScopeGenerationMergebackPending({parentSessionID:args2.record.parentSessionId,taskId,coderCallID:args2.record.callID}),{ok:!0,consumed:!0}}if(args2.reviewerReceiptOptions?.config?.enabled===!0&&!markReviewerScopeGenerationReady({parentSessionID:args2.record.parentSessionId,taskId,coderCallID:args2.record.callID,primaryWorkspaceIdentity:canonicalWorkspaceIdentity(args2.directory)??void 0}))return{ok:!1,consumed:!1,reason:"background coder scope handoff could not be marked ready after evidence persisted"};return{ok:!0,consumed:!0}}catch(err){return{ok:!1,consumed:!1,reason:`background coder evidence ingestion failed: ${err instanceof Error?err.message:String(err)}`}}}if(!isBackgroundGateBearingRecord(args2.record))return{ok:!0,consumed:!1};let workspaceCheck=validateStageBWorkspace(args2.directory,args2.record);if(workspaceCheck.stale)return{ok:!1,consumed:!1,stale:!0,reason:workspaceCheck.reason??"workspace changed while gate was running"};try{if(args2.record.workflowGeneration===void 0)return{ok:!1,consumed:!1,reason:`stage-b ingestion failed: TASK_WORKFLOW_GENERATION_REQUIRED for ${taskId}`};let existingEvidence=await readTaskEvidence(args2.directory,taskId),stageBRole=args2.record.normalizedAgent==="reviewer"||args2.record.normalizedAgent==="test_engineer"?args2.record.normalizedAgent:null,verdict=stageBRole?structuredStageBVerdict(stageBRole,args2.result.text??"",taskId):null;if(stageBRole&&verdict!=="pass"){let rejected=await transitionTaskWorkflowEvidence(args2.directory,taskId,{type:"stage_b_failed",gate:stageBRole,expectedGeneration:args2.record.workflowGeneration,transitionId:`background-gate-failed:${args2.record.correlationId}`}),parentSession=swarmState.agentSessions.get(args2.record.parentSessionId);if(parentSession)parentSession.taskWorkflowStates.set(taskId,"rework_required"),parentSession.stageBCompletion?.delete(taskId),updateTaskWorkflowCache(parentSession,taskId,getTaskWorkflowSnapshot(rejected));return{ok:!1,consumed:!0,reason:verdict==="fail"?`background ${stageBRole} rejected task ${taskId}`:`background ${stageBRole} returned no valid structured verdict for task ${taskId}`}}if(await recordGateEvidence(args2.directory,taskId,args2.record.normalizedAgent,args2.record.subagentSessionId,hasActiveTurboMode(args2.record.parentSessionId),{expectedGeneration:args2.record.workflowGeneration,transitionId:`background-gate:${args2.record.correlationId}`,ensureDefaultStageB:existingEvidence?.test_engineer_exempt!==!0}),args2.record.normalizedAgent==="reviewer")await collectReviewerReceiptFromTranscript(args2.directory,{targetAgent:args2.record.swarmPrefixedAgent,prompt:args2.record.prompt?.text??"",transcript:args2.result.text??"",sessionID:args2.record.parentSessionId,taskId,reviewerCallID:args2.record.callID,consumeHandoff:!0},args2.reviewerReceiptOptions);if(args2.record.normalizedAgent==="reviewer"||args2.record.normalizedAgent==="test_engineer")applyStageBStateCompletion(taskId,args2.record.normalizedAgent,args2.record.parentSessionId,existingEvidence?.test_engineer_exempt===!0);return{ok:!0,consumed:!0}}catch(err){let message=err instanceof Error?err.message:String(err);return warn(`[background-stage-b] ingestion failed: ${message}`),{ok:!1,consumed:!1,reason:`stage-b ingestion failed: ${message}`}}}function candidateSessions(parentSessionId){let parent=swarmState.agentSessions.get(parentSessionId);return parent?[parent]:[]}function applyStageBStateCompletion(taskId,agent,parentSessionId,testEngineerExempt){for(let session of candidateSessions(parentSessionId)){recordStageBCompletion(session,taskId,agent);let state=getTaskState(session,taskId);if(state==="tests_run"||state==="complete")continue;if(hasBothStageBCompletions(session,taskId)||testEngineerExempt&&agent==="reviewer"){try{if(state==="coder_delegated"||state==="pre_check_passed")advanceTaskState(session,taskId,"reviewer_run",{telemetrySessionId:parentSessionId});if(getTaskState(session,taskId)==="reviewer_run")advanceTaskState(session,taskId,"tests_run",{telemetrySessionId:parentSessionId})}catch(err){warn(`[background-stage-b] could not advance ${taskId} after ${agent}: ${err instanceof Error?err.message:String(err)}`)}continue}if(agent==="reviewer"&&(state==="coder_delegated"||state==="pre_check_passed"))try{advanceTaskState(session,taskId,"reviewer_run",{telemetrySessionId:parentSessionId})}catch(err){warn(`[background-stage-b] could not advance ${taskId} to reviewer_run: ${err instanceof Error?err.message:String(err)}`)}else if(agent==="test_engineer"&&state==="reviewer_run")try{advanceTaskState(session,taskId,"tests_run",{telemetrySessionId:parentSessionId})}catch(err){warn(`[background-stage-b] could not advance ${taskId} to tests_run: ${err instanceof Error?err.message:String(err)}`)}}}init_task_envelope();init_workspace_snapshot();function createBackgroundCompletionObserver(opts){let{config:config3,directory}=opts;return{event:async(input)=>{if(!config3.enabled)return;try{let evt=input?.event;if(!evt||evt.type!=="message.part.updated")return;let part=evt.properties?.part;if(!part||part.type!=="text"||part.synthetic!==!0||typeof part.text!=="string")return;let envelope=parseTaskEnvelope(part.text);if(!envelope||envelope.state!=="completed"&&envelope.state!=="error"&&envelope.state!=="cancelled")return;let parentSessionId=typeof part.sessionID==="string"?part.sessionID:"",lookup=await findDelegationForCompletion(directory,envelope.sessionId);if(!lookup){log(`[background] trusted completion for ${envelope.sessionId} has no durable primary or fallback owner; ignored`);return}if(!parentSessionId||lookup.record.parentSessionId!==parentSessionId||lookup.record.subagentSessionId!==envelope.sessionId){warn(`[background] trusted completion identity mismatch for ${envelope.sessionId}; ignored`);return}let pending=lookup.record;if(lookup.source==="fallback"){let promoted=await promoteDelegationFallback(directory,envelope.sessionId);if(!promoted){warn(`[background] fallback promotion failed for ${envelope.sessionId}; terminal work remains preserved`);return}pending=promoted.record}let text=envelope.state==="error"||envelope.state==="cancelled"?envelope.errorText??"":envelope.resultText??"",result={...envelope.state==="error"?{error:text}:{text},chars:envelope.resultChars??text.length,truncated:envelope.resultTruncated??!1,digest:digest2(text)},terminal={eventId:buildBackgroundCompletionEventId({correlationId:pending.correlationId,jobId:pending.jobId,status:envelope.state,resultDigest:result.digest}),status:envelope.state,recordedAt:pending.terminalResult?.recordedAt??Date.now(),result},terminalClaim=await claimTerminalResult(directory,pending.correlationId,terminal);if(!terminalClaim){warn(`[background] terminal claim failed for ${pending.correlationId}; ignored`);return}let isDuplicate=terminalClaim.disposition==="duplicate",record3=terminalClaim.record;if(opts.onTerminalClaimed?.(record3),terminal.status!=="completed"){if(isDuplicate)return;if(record3.normalizedAgent==="coder"){if(record3.planTaskId){let expectedGeneration=record3.taskChangeContext?.workflowGeneration;if(expectedGeneration===void 0)warn(`[background] failed coder ${record3.correlationId} has no launch generation for task ${record3.planTaskId}`);else try{await transitionTaskWorkflowEvidence(directory,record3.planTaskId,{type:"dispatch_no_mutation",agentType:"coder",expectedGeneration,transitionId:`background-coder-terminal:${terminal.eventId}`})}catch(error93){warn(`[background] failed coder retry accounting was fenced for ${record3.planTaskId}: ${error93 instanceof Error?error93.message:String(error93)}`)}}try{await releaseCoderReservation(directory,record3,"recovered")}catch(error93){warn(`[background] failed coder reservation cleanup will be retried by admission reconciliation: ${error93 instanceof Error?error93.message:String(error93)}`)}if(record3.worktree){let descriptor=record3.worktree;if(!standardWorktreeByCallID.has(record3.callID))standardWorktreeByCallID.set(record3.callID,{callID:descriptor.callID,parentSessionID:descriptor.parentSessionId,taskId:descriptor.taskId,...descriptor.planTaskId?{planTaskId:descriptor.planTaskId}:{},handle:{worktreePath:descriptor.worktreePath,branchName:descriptor.branchName,purpose:"lane",id:descriptor.worktreeId,sessionId:descriptor.worktreeSessionId},mergeStrategy:descriptor.mergeStrategy,laneIndex:descriptor.laneIndex,...descriptor.worktreeDir?{worktree_dir:descriptor.worktreeDir}:{}});try{await abortStandardWorktreeDispatch(record3.callID,"cancelled",directory)}catch(error93){warn(`[background] failed coder worktree cleanup preserved the lane for manual recovery: ${error93 instanceof Error?error93.message:String(error93)}`)}}}discardScopeForRecord(record3),await publishAdvisory(directory,record3,terminal.eventId,terminal.status==="cancelled"?"cancelled":"failed");return}if(record3.normalizedAgent==="coder"){let settled=await settleCoder(directory,record3,terminal.eventId);if(record3=settled.record,!settled.ok){await publishAdvisory(directory,record3,terminal.eventId,settled.outcome);return}}else if(!isDuplicate&&isBackgroundGateBearingRecord(record3)){if(validateStageBWorkspace(directory,record3).stale){await appendDelegationTransition(directory,record3.correlationId,{status:"stale"}),discardScopeForRecord(record3),await publishAdvisory(directory,record3,terminal.eventId,"stale");return}}if(record3.normalizedAgent==="coder"||isBackgroundGateBearingRecord(record3)){let ingestion=await claimDelegationIngestion(directory,record3.correlationId,{claimantId:terminal.eventId});if(ingestion?.disposition==="claimed"||ingestion?.disposition==="retry"){let applied=await ingestBackgroundStageBCompletion({directory,record:ingestion.record,result:ingestion.record.result??result,reviewerReceiptOptions:opts.reviewerReceiptOptions}),claimToken=ingestion.record.ingestion?.claimToken;if(!claimToken){await publishAdvisory(directory,record3,terminal.eventId,"ingestion claim token missing");return}let ingestionCommit=await(opts.recordIngestionResult??recordDelegationIngestionResult)(directory,record3.correlationId,claimToken,applied.ok);if(!ingestionCommit){warn(`[background] ingestion claim for ${record3.correlationId} expired or was fenced before commit; retry remains pending`);return}if(applied.ok&&(ingestionCommit.status!=="consumed"||ingestionCommit.ingestion?.state!=="consumed"||ingestionCommit.ingestion.claimToken!==claimToken)){warn(`[background] ingestion commit for ${record3.correlationId} did not confirm the exact consumed claim; retry remains pending`);return}if(record3=ingestionCommit,record3=(await findDelegationForCompletion(directory,record3.correlationId))?.record??record3,!applied.ok){await publishAdvisory(directory,record3,terminal.eventId,applied.stale?"stale":"ingestion failed");return}}else if(ingestion?.disposition==="busy")return;else if(ingestion?.disposition!=="consumed"){await publishAdvisory(directory,record3,terminal.eventId,"ingestion pending");return}}if(record3.normalizedAgent==="docs")try{if(!await completeBackgroundPhaseParticipation({directory,record:record3,resultText:text}))warn(`[background] docs completion ${record3.correlationId} did not satisfy its durable phase-participation binding`)}catch(error93){warn(`[background] docs completion ${record3.correlationId} could not persist phase participation: ${error93 instanceof Error?error93.message:String(error93)}`)}if(record3.normalizedAgent==="reviewer")discardScopeForRecord(record3);if(record3.normalizedAgent==="coder")await releaseCoderReservation(directory,record3,"consumed");await publishAdvisory(directory,record3,terminal.eventId,record3.normalizedAgent==="coder"?"completed and settled":"completed"),log(`[background] trusted completion settled: agent=${record3.normalizedAgent} task=${taskLabel(record3)} parent=${record3.parentSessionId}`)}catch(err){warn(`[background] completion observer error: ${err instanceof Error?err.message:String(err)}`)}},prepareAdvisories:async(parentSessionId)=>{if(!config3.enabled||!parentSessionId)return null;let preparationId=`bg-prepare:${cryptoRandomId()}`,entries=await preparePendingBackgroundAdvisories(directory,parentSessionId,{preparationId});return entries.length===0?null:{preparationId,eventIds:entries.map((entry)=>entry.eventId),messages:entries.map((entry)=>entry.message)}},ackObservedAdvisories:(parentSessionId,observedTexts)=>acknowledgeObservedBackgroundAdvisories(directory,parentSessionId,observedTexts),releaseAdvisories:(parentSessionId,prepared)=>releasePreparedBackgroundAdvisories(directory,parentSessionId,prepared.preparationId,prepared.eventIds)}}async function releaseCoderReservation(directory,record3,reason){if(!record3.coderReservationId)return;let bound=await bindBackgroundCoderReservation(directory,{reservationId:record3.coderReservationId,parentSessionId:record3.parentSessionId,planTaskId:record3.planTaskId,callID:record3.callID,correlationId:record3.correlationId});if(!bound){warn(`[background] coder reservation ${record3.coderReservationId} could not be bound for ${record3.correlationId}; admission remains fail-closed`);return}if(!await releaseBackgroundCoderReservation(directory,{...bound,reason}))warn(`[background] coder reservation ${record3.coderReservationId} could not be released after ${reason}; the next admission will retry reconciliation`)}async function settleCoder(directory,record3,operationId){let context=record3.taskChangeContext;if(!context)return{ok:!1,record:record3,outcome:"stale: no coder baseline"};let claim=await claimCoderSettlement(directory,record3.correlationId,operationId);if(!claim)return{ok:!1,record:record3,outcome:"settlement claim failed"};if(claim.disposition==="settled")return{ok:!0,record:claim.record,outcome:"completed and settled"};if(claim.disposition==="preserved")return{ok:!1,record:claim.record,outcome:"settlement preserved"};if(record3=claim.record,!record3.worktree){let baseline=context.baseline,current=captureWorkspaceSnapshot(directory,{scope:baseline.scope,prHeadSha:baseline.prHeadSha,resolveCurrentPrHeadSha:baseline.prHeadSha!==null}),repositoryDelta=changedFilesSinceSnapshot(directory,baseline),declaredFiles=context.declaredFiles,observedFiles2=repositoryDelta&&declaredFiles&&declaredFiles.length>0?repositoryDelta.filter((file3)=>isInDeclaredScope(file3,declaredFiles,directory)):null,staleReason=path220.resolve(baseline.directory)!==path220.resolve(directory)?"shared-root directory identity changed":!baseline.gitHead||current.gitHead!==baseline.gitHead?"shared-root HEAD changed before coder completion":baseline.prHeadSha!==null&&current.prHeadSha!==baseline.prHeadSha?"shared-root PR head changed before coder completion":observedFiles2===null?"shared-root coder files could not be attributed to a non-empty declared scope":null;if(staleReason||observedFiles2===null){let preserved2=await updateCoderSettlement(directory,record3.correlationId,{operationId,state:"preserved",observedFiles:null,outcome:{kind:"shared-root",result:"failed",reason:staleReason??"coder attribution failed"}});return await appendDelegationTransition(directory,record3.correlationId,{status:"stale"}),{ok:!1,record:preserved2??record3,outcome:`stale: ${staleReason??"coder attribution failed"}`}}let settled=await updateCoderSettlement(directory,record3.correlationId,{operationId,state:"settled",observedFiles:observedFiles2,outcome:{kind:"shared-root",result:"ready"}});return settled?{ok:!0,record:settled,outcome:"completed and settled"}:{ok:!1,record:record3,outcome:"settlement persistence failed"}}let descriptor=record3.worktree;if(descriptor.callID!==record3.callID||descriptor.parentSessionId!==record3.parentSessionId||descriptor.planTaskId!==record3.planTaskId||path220.resolve(context.baseline.directory)!==path220.resolve(descriptor.worktreePath))return{ok:!1,record:await updateCoderSettlement(directory,record3.correlationId,{operationId,state:"preserved",observedFiles:null,outcome:{kind:"standard-worktree",result:"failed",reason:"worktree recovery identity does not match the dispatch"}})??record3,outcome:"worktree settlement preserved: identity mismatch"};let observedFiles=changedFilesSinceSnapshot(descriptor.worktreePath,context.baseline);if(observedFiles===null)return{ok:!1,record:await updateCoderSettlement(directory,record3.correlationId,{operationId,state:"preserved",observedFiles:null,outcome:{kind:"standard-worktree",result:"failed",reason:"worktree files could not be attributed to the clean baseline"}})??record3,outcome:"worktree settlement preserved: attribution failed"};let dispatch=standardWorktreeByCallID.get(record3.callID)??{callID:descriptor.callID,parentSessionID:descriptor.parentSessionId,taskId:descriptor.taskId,...descriptor.planTaskId?{planTaskId:descriptor.planTaskId}:{},handle:{worktreePath:descriptor.worktreePath,branchName:descriptor.branchName,purpose:"lane",id:descriptor.worktreeId,sessionId:descriptor.worktreeSessionId},mergeStrategy:descriptor.mergeStrategy,laneIndex:descriptor.laneIndex,...descriptor.worktreeDir?{worktree_dir:descriptor.worktreeDir}:{}};standardWorktreeByCallID.delete(record3.callID),awaitingMergeByCallID.set(record3.callID,{callID:record3.callID,parentSessionID:descriptor.parentSessionId,taskId:descriptor.taskId,...descriptor.planTaskId?{planTaskId:descriptor.planTaskId}:{},branch:descriptor.branchName,worktreePath:descriptor.worktreePath,mergeStrategy:descriptor.mergeStrategy,queuedAt:Date.now()});let resume=settlementResume(record3),mergeResult=await finishStandardWorktreeDispatch(directory,dispatch,void 0,record3.callID,{operationId,...resume?{resume}:{},onBeforeMerge:async(provenance)=>{let persisted=await updateCoderSettlement(directory,record3.correlationId,{operationId,state:"settling",sourceHeadAfterCommit:provenance.sourceHead,targetHeadBeforeMerge:provenance.targetHeadBefore,observedFiles});if(!persisted)throw Error("could not persist pre-merge provenance");record3=persisted},onMerged:async(merged)=>{let provenance=merged.provenance??resume,persisted=await updateCoderSettlement(directory,record3.correlationId,{operationId,state:"settled",observedFiles,...provenance?{sourceHeadAfterCommit:provenance.sourceHead,targetHeadBeforeMerge:provenance.targetHeadBefore}:{},outcome:{kind:"standard-worktree",result:provenance&&provenance.sourceHead!==provenance.targetHeadBefore?"merged":"unchanged",sourceHeadAfterCommit:provenance?.sourceHead??null,targetHeadBeforeMerge:provenance?.targetHeadBefore??null,targetHeadAfterMerge:resolveCurrentGitHead(directory)}});if(!persisted)throw Error("could not persist merged settlement");record3=persisted}});if(mergeResult.outcome==="merged")return{ok:!0,record:(await findDelegationForCompletion(directory,record3.correlationId))?.record??record3,outcome:"completed and merged"};if(mergeResult.outcome==="failed"&&mergeResult.stage==="settlement-persist")return{ok:!1,record:record3,outcome:"worktree settlement persistence pending retry"};return{ok:!1,record:await updateCoderSettlement(directory,record3.correlationId,{operationId,state:"preserved",observedFiles,...mergeResult.provenance?{sourceHeadAfterCommit:mergeResult.provenance.sourceHead,targetHeadBeforeMerge:mergeResult.provenance.targetHeadBefore}:{},outcome:{kind:"standard-worktree",result:mergeResult.outcome,reason:mergeResult.message,sourceHeadAfterCommit:mergeResult.provenance?.sourceHead??null,targetHeadBeforeMerge:mergeResult.provenance?.targetHeadBefore??null}})??record3,outcome:`worktree settlement preserved: ${mergeResult.message}`}}function settlementResume(record3){let{coderSettlement:settlement,worktree}=record3;if(settlement?.state!=="settling"||!settlement.operationId||!settlement.sourceHeadAfterCommit||!settlement.targetHeadBeforeMerge||!GIT_OBJECT_ID_PATTERN.test(settlement.sourceHeadAfterCommit)||!GIT_OBJECT_ID_PATTERN.test(settlement.targetHeadBeforeMerge)||!worktree)return;return{operationId:settlement.operationId,sourceHead:settlement.sourceHeadAfterCommit,targetHeadBefore:settlement.targetHeadBeforeMerge,branchName:worktree.branchName,strategy:worktree.mergeStrategy}}async function publishAdvisory(directory,record3,eventId,outcome){let message=`[BACKGROUND COMPLETION ${eventId}] ${record3.normalizedAgent} task ${taskLabel(record3)} ${outcome}.`,stored=await putPendingBackgroundAdvisory(directory,record3.correlationId,{eventId,parentSessionId:record3.parentSessionId,message});if(!stored)return;let session=swarmState.agentSessions.get(record3.parentSessionId);if(session)pushAdvisory(session,stored.message)}function taskLabel(record3){return record3.evidenceTaskId??record3.planTaskId??"unknown"}function discardScopeForRecord(record3){let taskId=record3.evidenceTaskId??record3.planTaskId;if(!taskId)return;if(record3.normalizedAgent==="reviewer")discardReviewerScopeGenerationClaim({parentSessionID:record3.parentSessionId,taskId,reviewerCallID:record3.callID});else if(record3.normalizedAgent==="coder")discardReviewerScopeGenerationForCoderCall({parentSessionID:record3.parentSessionId,taskId,coderCallID:record3.callID})}function digest2(text){return createHash58("sha256").update(text).digest("hex")}function cryptoRandomId(){return createHash58("sha256").update(`${Date.now()}:${Math.random()}`).digest("hex").slice(0,24)}init_pr_subscriptions();init_commands();init_registry2();init_config();init_agent_model();init_bundled_skills();init_constants();init_config();init_warning_buffer();init_constants();import*as fs117 from"node:fs";import*as path221 from"node:path";var STARTER_CONTENT=`{}
6323
+ `);return/(?:^|\n)\s*TASK:\s*(\d+\.\d+(?:\.\d+)*)\b/i.exec(text)?.[1]??null}function storePath3(directory){return validateSwarmPath(directory,PHASE_PARTICIPATION_FILE)}function readRawStore(directory){let filePath;try{filePath=storePath3(directory)}catch(error93){return{status:"unreadable",error:error93}}let descriptor,bytes;try{let pathStat=fs116.lstatSync(filePath);if(pathStat.isSymbolicLink()||!pathStat.isFile())return{status:"unreadable",error:Error("Participation projection is not a regular file")};if(pathStat.size>MAX_PHASE_PARTICIPATION_BYTES)return{status:"oversized",bytes:pathStat.size};descriptor=fs116.openSync(filePath,fs116.constants.O_RDONLY|(fs116.constants.O_NOFOLLOW??0));let openedStat=fs116.fstatSync(descriptor);if(!openedStat.isFile()||openedStat.dev!==pathStat.dev||openedStat.ino!==pathStat.ino)return{status:"unreadable",error:Error("Participation projection changed while it was being opened")};if(openedStat.size>MAX_PHASE_PARTICIPATION_BYTES)return{status:"oversized",bytes:openedStat.size};let bounded=Buffer.allocUnsafe(MAX_PHASE_PARTICIPATION_BYTES+1),offset=0;while(offset<bounded.byteLength){let read=fs116.readSync(descriptor,bounded,offset,bounded.byteLength-offset,null);if(read===0)break;offset+=read}if(offset>MAX_PHASE_PARTICIPATION_BYTES)return{status:"oversized",bytes:offset};bytes=bounded.subarray(0,offset)}catch(error93){if(error93.code==="ENOENT")return{status:"missing"};return{status:"unreadable",error:error93}}finally{if(descriptor!==void 0)try{fs116.closeSync(descriptor)}catch{}}try{return{status:"valid",store:StoreSchema.parse(JSON.parse(bytes.toString("utf8")))}}catch{return{status:"corrupt",bytes}}}async function atomicWriteBytes(filePath,bytes){await atomicWriteSwarmFile(filePath,bytes)}async function readBoundedRegularFile(filePath,maxBytes){let pathStat=await fs116.promises.lstat(filePath);if(pathStat.isSymbolicLink()||!pathStat.isFile()||pathStat.size>maxBytes)throw Error("bounded evidence artifact is not a permitted regular file");let handle=await fs116.promises.open(filePath,fs116.constants.O_RDONLY|(fs116.constants.O_NOFOLLOW??0));try{let openedStat=await handle.stat();if(!openedStat.isFile()||openedStat.dev!==pathStat.dev||openedStat.ino!==pathStat.ino||openedStat.size>maxBytes)throw Error("bounded evidence artifact changed while being opened");let bounded=Buffer.allocUnsafe(maxBytes+1),offset=0;while(offset<bounded.byteLength){let{bytesRead}=await handle.read(bounded,offset,bounded.byteLength-offset,null);if(bytesRead===0)break;offset+=bytesRead}if(offset>maxBytes)throw Error("bounded evidence artifact exceeds its byte limit");return bounded.subarray(0,offset)}finally{try{await handle.close()}catch{}}}function quarantineFullError(){return Error("PHASE_PARTICIPATION_QUARANTINE_FULL: preserved corrupt evidence reached its bounded retention limit; an operator must archive the quarantine before docs can be re-dispatched.")}async function quarantineCorruptBytes(directory,bytes){let digest2=sha2564(bytes),quarantineDir=validateSwarmPath(directory,PHASE_PARTICIPATION_QUARANTINE_DIR);await fs116.promises.mkdir(quarantineDir,{recursive:!0});let quarantineStat=await fs116.promises.lstat(quarantineDir);if(quarantineStat.isSymbolicLink()||!quarantineStat.isDirectory())throw Error("PHASE_PARTICIPATION_QUARANTINE_UNREADABLE: quarantine is not a regular directory.");let target=validateSwarmPath(directory,`${PHASE_PARTICIPATION_QUARANTINE_DIR}/${digest2}.bin`);try{if(!(await readBoundedRegularFile(target,MAX_PHASE_PARTICIPATION_BYTES)).equals(bytes))throw Error("hash-addressed quarantine content mismatch");return}catch(error93){if(error93.code!=="ENOENT")throw error93}let count=0,totalBytes=0,scanned=0,handle=await fs116.promises.opendir(quarantineDir,{bufferSize:16});try{for await(let entry of handle){if(scanned+=1,scanned>MAX_PHASE_PARTICIPATION_QUARANTINE_DIRECTORY_ENTRIES)throw quarantineFullError();if(!entry.isFile()||!/^[a-f0-9]{64}\.bin$/.test(entry.name))continue;count+=1;let candidate2=validateSwarmPath(directory,`${PHASE_PARTICIPATION_QUARANTINE_DIR}/${entry.name}`),candidateStat=await fs116.promises.lstat(candidate2);if(candidateStat.isSymbolicLink()||!candidateStat.isFile())throw Error("PHASE_PARTICIPATION_QUARANTINE_UNREADABLE: invalid quarantine artifact.");if(totalBytes+=candidateStat.size,count>=MAX_PHASE_PARTICIPATION_QUARANTINE_FILES||totalBytes+bytes.byteLength>MAX_PHASE_PARTICIPATION_QUARANTINE_BYTES)throw quarantineFullError()}}finally{try{await handle.close()}catch{}}await atomicWriteBytes(target,bytes)}async function loadWritableStoreUnderLock(directory){let read=readRawStore(directory);if(read.status==="missing")return emptyStore();if(read.status==="valid")return read.store;if(read.status==="corrupt")return await quarantineCorruptBytes(directory,read.bytes),emptyStore();if(read.status==="oversized")throw Error(`PHASE_PARTICIPATION_OVERSIZED: ${read.bytes} bytes exceeds ${MAX_PHASE_PARTICIPATION_BYTES}; operator action is required before docs can be re-dispatched.`);throw Error("PHASE_PARTICIPATION_UNREADABLE: operator action is required before docs can be re-dispatched.")}async function writeStore(directory,store){let validatedStore=StoreSchema.parse(store);validatedStore.pending.sort((left,right)=>left.capturedAt-right.capturedAt),validatedStore.receipts.sort((left,right)=>left.completedAt-right.completedAt);let serialized3=JSON.stringify(validatedStore,null,2);while(Buffer.byteLength(serialized3,"utf8")>MAX_PHASE_PARTICIPATION_BYTES){let pendingTime=validatedStore.pending[0]?.capturedAt??1/0,receiptTime=validatedStore.receipts[0]?.completedAt??1/0;if(pendingTime===1/0&&receiptTime===1/0)throw Error("PHASE_PARTICIPATION_WRITE_OVERSIZED: even an empty participation store exceeds its byte limit.");if(pendingTime<=receiptTime)validatedStore.pending.shift();else validatedStore.receipts.shift();validatedStore=StoreSchema.parse(validatedStore),serialized3=JSON.stringify(validatedStore,null,2)}await fs116.promises.mkdir(path219.dirname(storePath3(directory)),{recursive:!0}),await atomicWriteFile(storePath3(directory),serialized3)}function bindingMatchesPlan(binding,plan,phase){return binding.planId===derivePlanId(plan)&&binding.planIdentityHash===derivePlanIdentityHash(plan)&&binding.planStructureHash===computePlanStructureHash(plan)&&binding.phase===phase}function workspaceIdentityIsFresh(expected,current){return path219.resolve(expected.directory)===path219.resolve(current.directory)&&expected.gitHead===current.gitHead&&expected.prHeadSha===current.prHeadSha}function resultText(output){if(!output||typeof output!=="object")return{text:"",childSessionId:null};let record3=output,rawOutput=typeof record3.output==="string"?record3.output:"",envelope=parseTaskEnvelope(rawOutput);if(envelope?.state==="completed")return{text:envelope.resultText??"",childSessionId:envelope.sessionId};return{text:rawOutput,childSessionId:null}}function envelopeFromOutput(output){if(typeof output==="string")return parseTaskEnvelope(output);if(!output||typeof output!=="object")return null;let rawOutput=output.output;return typeof rawOutput==="string"?parseTaskEnvelope(rawOutput):null}function validateMetadata(output,parentSessionId,childSessionId){if(!output||typeof output!=="object")return{valid:!0,childSessionId};let metadata=output.metadata;if(!metadata||typeof metadata!=="object")return{valid:!0,childSessionId};let meta3=metadata;if(typeof meta3.parentSessionId==="string"&&meta3.parentSessionId!==parentSessionId)return{valid:!1,childSessionId:null};let metadataChild=typeof meta3.sessionId==="string"&&meta3.sessionId.length>0?meta3.sessionId:null;if(childSessionId&&metadataChild&&childSessionId!==metadataChild)return{valid:!1,childSessionId:null};return{valid:!0,childSessionId:childSessionId??metadataChild}}function addReceipt(store,pending,text,childIdentityAvailable){let receiptId=sha2564(stableCanonicalStringify({parentSessionId:pending.parentSessionId,callId:pending.callId,childSessionId:pending.childSessionId,planIdentityHash:pending.planIdentityHash,planStructureHash:pending.planStructureHash,phase:pending.phase,role:pending.role})),receipt={...pending,receiptId,resultDigest:sha2564(text),completedAt:Date.now(),childIdentityAvailable};store.receipts=store.receipts.filter((existing)=>existing.receiptId!==receiptId&&!(existing.planIdentityHash===receipt.planIdentityHash&&existing.planStructureHash===receipt.planStructureHash&&existing.phase===receipt.phase&&existing.role===receipt.role)),store.receipts.push(receipt),store.receipts=store.receipts.slice(-MAX_PHASE_PARTICIPATION_RECEIPTS)}async function reserveApprovedPhaseParticipation(input){if(input.tool.toLowerCase()!=="task")return;let rawRole=input.args.subagent_type;if(typeof rawRole!=="string"||stripKnownSwarmPrefix(rawRole)!=="docs")return;let plan=await loadPlan(input.directory);if(!plan)return;let binding=buildBinding({plan,phase:getCurrentPhase(plan),role:rawRole,parentSessionId:input.parentSessionId,callId:input.callId,taskId:extractPlanTaskId2(input.args),policy:input.policy,directory:input.directory});await withEvidenceLock(input.directory,PHASE_PARTICIPATION_FILE,"docs","phase-participation",async()=>{let store=await loadWritableStoreUnderLock(input.directory);await writeStore(input.directory,store)}),boundedPut(binding)}async function observePhaseParticipationToolResult(input){if(input.tool.toLowerCase()!=="task")return;let binding=takeBinding(input.parentSessionId,input.callId);if(!binding)return;let envelope=envelopeFromOutput(input.output);if(envelope?.state==="running"){let{subagentSessionId}=extractDispatchIds(input.output);if(!subagentSessionId||subagentSessionId!==envelope.sessionId)return;let pending2={...binding,childSessionId:subagentSessionId};await persistWithBindingRecovery(input.directory,binding,async()=>{let store=await loadWritableStoreUnderLock(input.directory);store.pending=store.pending.filter((existing)=>existing.childSessionId!==pending2.childSessionId&&!(existing.parentSessionId===pending2.parentSessionId&&existing.callId===pending2.callId)),store.pending.push(pending2),store.pending=store.pending.slice(-MAX_PHASE_PARTICIPATION_PENDING),await writeStore(input.directory,store)});return}if(envelope&&envelope.state!=="completed")return;if(classifyTaskResult(input.output)!=="success")return;let extracted=resultText(input.output),text=extracted.text.trim();if(!text)return;let metadata=validateMetadata(input.output,input.parentSessionId,extracted.childSessionId);if(!metadata.valid)return;let childSessionId=metadata.childSessionId,currentPlan=await loadPlan(input.directory);if(!currentPlan||!bindingMatchesPlan(binding,currentPlan,binding.phase))return;if(!workspaceIdentityIsFresh(binding.workspace,captureParticipationWorkspace(input.directory)))return;let pending={...binding,childSessionId:childSessionId??`unavailable:${sha2564(correlationKey(input.parentSessionId,input.callId))}`};await persistWithBindingRecovery(input.directory,binding,async()=>{let store=await loadWritableStoreUnderLock(input.directory);addReceipt(store,pending,text,childSessionId!==null),await writeStore(input.directory,store)})}async function completeBackgroundPhaseParticipation(input){if(stripKnownSwarmPrefix(input.record.normalizedAgent)!=="docs")return!1;let text=input.resultText.trim();if(!text)return!1;return withEvidenceLock(input.directory,PHASE_PARTICIPATION_FILE,"docs","phase-participation",async()=>{let store=await loadWritableStoreUnderLock(input.directory),currentPlan=await loadPlan(input.directory),existingReceipt=store.receipts.find((receipt)=>receipt.childSessionId===input.record.subagentSessionId&&receipt.parentSessionId===input.record.parentSessionId&&receipt.callId===input.record.callID&&receipt.role===input.record.normalizedAgent&&receipt.prefixedRole===input.record.swarmPrefixedAgent&&receipt.taskId===input.record.planTaskId);if(existingReceipt&&currentPlan&&bindingMatchesPlan(existingReceipt,currentPlan,existingReceipt.phase))return!0;let pending=store.pending.find((candidate2)=>candidate2.childSessionId===input.record.subagentSessionId&&candidate2.parentSessionId===input.record.parentSessionId&&candidate2.callId===input.record.callID&&candidate2.role===input.record.normalizedAgent&&candidate2.prefixedRole===input.record.swarmPrefixedAgent&&candidate2.taskId===input.record.planTaskId);if(!pending)return!1;let plan=currentPlan;if(!plan||!bindingMatchesPlan(pending,plan,pending.phase))return!1;if(!workspaceIdentityIsFresh(pending.workspace,captureParticipationWorkspace(input.directory)))return!1;if(pending.taskId!==null&&input.record.ingestion?.state!=="consumed")return!1;return addReceipt(store,pending,text,!0),store.pending=store.pending.filter((candidate2)=>candidate2.childSessionId!==pending.childSessionId),await writeStore(input.directory,store),!0})}function readPhaseParticipation(directory,plan,phase,role){let read=readRawStore(directory);if(read.status!=="valid")return{status:read.status,found:!1};let canonicalRole2=stripKnownSwarmPrefix(role),currentWorkspace=captureParticipationWorkspace(directory);return{status:"valid",found:read.store.receipts.some((receipt)=>receipt.role===canonicalRole2&&bindingMatchesPlan(receipt,plan,phase)&&workspaceIdentityIsFresh(receipt.workspace,currentWorkspace))}}init_gate_evidence();init_worktree_isolation();init_helpers();init_state2();init_logger();init_merge();init_pending_delegations();init_gate_evidence();init_gate_evidence_classification();init_review_receipt_collector();init_reviewer_scope_file_fingerprint();init_scope_binding();init_state2();init_logger();init_workspace_snapshot();var GATE_EVIDENCE_ROLES=new Set(["reviewer","test_engineer","docs","designer","critic","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","explorer","sme"]);function structuredStageBVerdict(role,text,taskId){let escapedTaskId=taskId.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),match=(role==="reviewer"?new RegExp(`^\\[REVIEWED\\]\\s*\\|\\s*(?:task-)?${escapedTaskId}\\s*\\|\\s*(APPROVED|REJECTED|CONCERNS)\\s*\\|`,"im"):new RegExp(`^\\[TESTED\\]\\s*\\|\\s*(?:task-)?${escapedTaskId}\\s*\\|\\s*(PASS|FAIL|SKIPPED)\\s*\\|`,"im")).exec(text);if(!match)return null;return match[1]==="APPROVED"||match[1]==="PASS"?"pass":"fail"}function normalizeAttributionPath(file3){let normalized=file3.trim().replaceAll("\\","/").replace(/^\.\/+/,""),hasControlCharacter5=[...normalized].some((character)=>{let code=character.charCodeAt(0);return code<=31||code===127});if(!normalized||normalized.startsWith("/")||/^[A-Za-z]:\//.test(normalized)||normalized===".."||normalized.startsWith("../")||normalized.split("/").includes("..")||hasControlCharacter5)return null;return normalized}function normalizedPathSet(files){if(!files)return null;let normalized=new Set;for(let file3 of files){let candidate2=normalizeAttributionPath(file3);if(!candidate2)return null;normalized.add(candidate2)}return normalized}function pathSetsEqual(left,right){return left.size===right.size&&[...left].every((file3)=>right.has(file3))}function hasDistinctBackgroundOwner(input){if(!Number.isFinite(input.candidateCreatedAt)||!Number.isFinite(input.candidateCompletedAt)||input.candidateCreatedAt>input.candidateCompletedAt)return!1;let liveOwners=[...(swarmState.agentSessions.get(input.parentSessionID)?.reviewerScopeGenerations??new Map).values()].filter((generation)=>{if(generation.background!==!0||generation.taskId===input.taskId&&generation.coderCallID===input.coderCallID)return!1;let declared=normalizedPathSet(generation.declaredFiles),routed=normalizedPathSet(generation.modifiedFiles),fingerprints=generation.modifiedFileFingerprints.filter((entry)=>normalizeAttributionPath(entry.file)===input.file),ownerCompletedAt=generation.readyAt??input.candidateCompletedAt;return Number.isFinite(generation.createdAt)&&Number.isFinite(ownerCompletedAt)&&generation.createdAt<=input.candidateCompletedAt&&input.candidateCreatedAt<=ownerCompletedAt&&declared?.has(input.file)===!0&&routed?.has(input.file)===!0&&fingerprints.length===1&&reviewerScopeFileFingerprintsEqual(fingerprints[0],input.fingerprint)}),historicalOwners=getReviewerScopeOwnershipHistory({parentSessionID:input.parentSessionID}).filter((owner)=>{if(owner.taskId===input.taskId&&owner.coderCallID===input.coderCallID)return!1;let declared=normalizedPathSet(owner.declaredFiles),routed=normalizedPathSet(owner.modifiedFiles),fingerprints=owner.modifiedFileFingerprints.filter((entry)=>normalizeAttributionPath(entry.file)===input.file);return owner.parentSessionID===input.parentSessionID&&owner.background===!0&&Number.isFinite(owner.createdAt)&&Number.isFinite(owner.readyAt)&&owner.createdAt<=input.candidateCompletedAt&&input.candidateCreatedAt<=owner.readyAt&&declared?.has(input.file)===!0&&routed?.has(input.file)===!0&&fingerprints.length===1&&reviewerScopeFileFingerprintsEqual(fingerprints[0],input.fingerprint)});return liveOwners.length+historicalOwners.length===1}function isBackgroundGateBearingRecord(record3){return record3.batchId===void 0&&record3.evidenceTaskId!==null&&GATE_EVIDENCE_ROLES.has(record3.normalizedAgent)}function validateStageBWorkspace(directory,record3){let actualWorkspace=captureWorkspaceSnapshot(directory,{scope:record3.workspace?.scope??null,prHeadSha:record3.workspace?.prHeadSha??null,resolveCurrentPrHeadSha:record3.workspace?.prHeadSha!==null}),check3=compareStageBWorkspace(record3,actualWorkspace);return{...check3,ok:!check3.stale}}function compareStageBWorkspace(record3,actualWorkspace){let expectedWorkspace=record3.normalizedAgent==="docs"&&record3.workspace?{...record3.workspace,dirtyHash:null}:record3.workspace;return compareWorkspaceSnapshots(expectedWorkspace,actualWorkspace)}async function ingestBackgroundStageBCompletion(args2){let taskId=args2.record.evidenceTaskId??args2.record.planTaskId;if(!taskId)return{ok:!0,consumed:!1};if(args2.record.normalizedAgent==="coder"){let taskChangeContext=args2.record.taskChangeContext,settledFiles=args2.record.coderSettlement?.state==="settled"?args2.record.coderSettlement.observedFiles:void 0,observedFiles=settledFiles!==void 0?settledFiles:taskChangeContext?changedFilesSinceSnapshot(taskChangeContext.baseline.directory,taskChangeContext.baseline):null;if(observedFiles===null)return{ok:!1,consumed:!1,stale:!0,reason:"background coder files could not be attributed to a clean immutable baseline"};try{let observedSet=normalizedPathSet(observedFiles),declaredSet=normalizedPathSet(taskChangeContext?.declaredFiles??null),completionTime=args2.record.completedAt??args2.record.updatedAt,attributedFiles=observedFiles??[];if(args2.reviewerReceiptOptions?.config?.enabled!==!0){if(observedSet&&declaredSet)attributedFiles=[...observedSet].filter((file3)=>declaredSet.has(file3))}if(args2.reviewerReceiptOptions?.config?.enabled===!0){if(!observedSet||!declaredSet)return{ok:!1,consumed:!1,reason:"background coder changed-file attribution could not be reconstructed exactly"};attributedFiles=[...observedSet].filter((file3)=>declaredSet.has(file3));let generation=getReviewerScopeGenerationForCoderCall({parentSessionID:args2.record.parentSessionId,taskId,coderCallID:args2.record.callID}),generationScope=normalizedPathSet(generation?.declaredFiles??null),routedFiles=normalizedPathSet(generation?.modifiedFiles??null),routedFingerprints=generation?.modifiedFileFingerprints??null;if(generation?.status==="collecting"&&generation.background===!0&&observedSet.size===0&&routedFiles?.size===0&&declaredSet){if(markReviewerScopeGenerationNoChange({parentSessionID:args2.record.parentSessionId,taskId,coderCallID:args2.record.callID}))return{ok:!0,consumed:!0}}let captureRoot=generation?.captureDirectory?.trim()||args2.directory,observedFingerprints=new Map;for(let file3 of observedSet){let captured=captureReviewerScopeFileFingerprint(captureRoot,file3);if(captured.kind==="capture_failed")return{ok:!1,consumed:!1,reason:`background coder post-write fingerprint could not be reconstructed exactly (${captured.code}${captured.retryable?" (retryable)":" (permanent)"} on ${captured.file})`};let fingerprint2=reviewerScopeCaptureToFingerprint(captured);if(!fingerprint2)return{ok:!1,consumed:!1,reason:"background coder post-write fingerprint returned an unusable result"};observedFingerprints.set(file3,fingerprint2)}let changedWithinDeclaredScope=new Set([...observedSet].filter((file3)=>declaredSet.has(file3)&&generationScope?.has(file3))),observedOutsideCurrentScope=[...observedSet].filter((file3)=>!generationScope?.has(file3));if(generation?.status!=="collecting"&&generation?.status!=="ready"||generation.background!==!0||!generationScope||!routedFiles||!routedFingerprints||routedFiles.size===0||!pathSetsEqual(declaredSet,generationScope)||!pathSetsEqual(routedFiles,changedWithinDeclaredScope)||reviewerScopeGenerationHasDeclaredOverlap({parentSessionID:args2.record.parentSessionId,taskId,coderCallID:args2.record.callID,declaredFiles:generation.declaredFiles})||observedOutsideCurrentScope.some((file3)=>!hasDistinctBackgroundOwner({parentSessionID:args2.record.parentSessionId,taskId,coderCallID:args2.record.callID,file:file3,fingerprint:observedFingerprints.get(file3),candidateCreatedAt:args2.record.createdAt,candidateCompletedAt:completionTime}))||[...routedFiles].some((file3)=>{let fingerprints=routedFingerprints.filter((entry)=>normalizeAttributionPath(entry.file)===file3),observedFingerprint=observedFingerprints.get(file3);return!observedSet.has(file3)||!declaredSet.has(file3)||!generationScope.has(file3)||fingerprints.length!==1||!observedFingerprint||!reviewerScopeFileFingerprintsEqual(fingerprints[0],observedFingerprint)}))return{ok:!1,consumed:!1,reason:"background coder scope handoff could not be reconstructed exactly"};attributedFiles=[...routedFiles];for(let file3 of routedFiles){let fingerprint2=observedFingerprints.get(file3);if(fingerprint2)recordReviewerScopeGenerationFileFingerprint({parentSessionID:args2.record.parentSessionId,taskId,coderCallID:args2.record.callID,fingerprint:fingerprint2})}}let parentSession=swarmState.agentSessions.get(args2.record.parentSessionId);if(parentSession){let state=getTaskState(parentSession,taskId);if(state!=="idle"&&state!=="coder_delegated"&&state!=="rework_required")return{ok:!1,consumed:!1,reason:`background coder completion is late for task ${taskId}: current state is ${state}`}}let accepted=attributedFiles.length>0,expectedGeneration=args2.record.taskChangeContext?.workflowGeneration??0,transitionId=`background-coder:${args2.record.correlationId}`,existingEvidence=await readTaskEvidence(args2.directory,taskId),existingWorkflow=getTaskWorkflowSnapshot(existingEvidence),updated=existingWorkflow.authoritative&&existingWorkflow.lastTransitionId===transitionId&&existingWorkflow.lastOutcome===(accepted?"accepted_mutation":"dispatch_no_mutation")&&existingWorkflow.generation===expectedGeneration+(accepted?1:0)?existingEvidence:await transitionTaskWorkflowEvidence(args2.directory,taskId,accepted?{type:"accepted_mutation",agentType:"coder",context:{testEngineerExempt:isMarkdownOnlyTaskChange(taskChangeContext?.declaredFiles,attributedFiles)},expectedGeneration,transitionId}:{type:"dispatch_no_mutation",agentType:"coder",expectedGeneration,transitionId});if(accepted){let workflow=getTaskWorkflowSnapshot(updated),parentSession2=swarmState.agentSessions.get(args2.record.parentSessionId);if(parentSession2){if(!recordModifiedFilesForTask(parentSession2,taskId,attributedFiles))warn(`[background] durable coder mutation for ${taskId} exceeded session file-attribution capacity`);parentSession2.taskWorkflowStates.set(taskId,"coder_delegated"),parentSession2.stageBCompletion?.delete(taskId),parentSession2.taskCouncilApproved?.delete(taskId),parentSession2.taskCouncilWorkflowGeneration?.delete(taskId),updateTaskWorkflowCache(parentSession2,taskId,workflow)}}if(args2.reviewerReceiptOptions?.config?.enabled===!0){let laneGeneration=getReviewerScopeGenerationForCoderCall({parentSessionID:args2.record.parentSessionId,taskId,coderCallID:args2.record.callID});if(laneGeneration!==null&&laneGeneration.workspaceIdentity!==canonicalWorkspaceIdentity(args2.directory))return markReviewerScopeGenerationMergebackPending({parentSessionID:args2.record.parentSessionId,taskId,coderCallID:args2.record.callID}),{ok:!0,consumed:!0}}if(args2.reviewerReceiptOptions?.config?.enabled===!0&&!markReviewerScopeGenerationReady({parentSessionID:args2.record.parentSessionId,taskId,coderCallID:args2.record.callID,primaryWorkspaceIdentity:canonicalWorkspaceIdentity(args2.directory)??void 0}))return{ok:!1,consumed:!1,reason:"background coder scope handoff could not be marked ready after evidence persisted"};return{ok:!0,consumed:!0}}catch(err){return{ok:!1,consumed:!1,reason:`background coder evidence ingestion failed: ${err instanceof Error?err.message:String(err)}`}}}if(!isBackgroundGateBearingRecord(args2.record))return{ok:!0,consumed:!1};let workspaceCheck=validateStageBWorkspace(args2.directory,args2.record);if(workspaceCheck.stale)return{ok:!1,consumed:!1,stale:!0,reason:workspaceCheck.reason??"workspace changed while gate was running"};try{if(args2.record.workflowGeneration===void 0)return{ok:!1,consumed:!1,reason:`stage-b ingestion failed: TASK_WORKFLOW_GENERATION_REQUIRED for ${taskId}`};let existingEvidence=await readTaskEvidence(args2.directory,taskId),stageBRole=args2.record.normalizedAgent==="reviewer"||args2.record.normalizedAgent==="test_engineer"?args2.record.normalizedAgent:null,verdict=stageBRole?structuredStageBVerdict(stageBRole,args2.result.text??"",taskId):null;if(stageBRole&&verdict!=="pass"){let rejected=await transitionTaskWorkflowEvidence(args2.directory,taskId,{type:"stage_b_failed",gate:stageBRole,expectedGeneration:args2.record.workflowGeneration,transitionId:`background-gate-failed:${args2.record.correlationId}`}),parentSession=swarmState.agentSessions.get(args2.record.parentSessionId);if(parentSession)parentSession.taskWorkflowStates.set(taskId,"rework_required"),parentSession.stageBCompletion?.delete(taskId),updateTaskWorkflowCache(parentSession,taskId,getTaskWorkflowSnapshot(rejected));return{ok:!1,consumed:!0,reason:verdict==="fail"?`background ${stageBRole} rejected task ${taskId}`:`background ${stageBRole} returned no valid structured verdict for task ${taskId}`}}if(await recordGateEvidence(args2.directory,taskId,args2.record.normalizedAgent,args2.record.subagentSessionId,hasActiveTurboMode(args2.record.parentSessionId),{expectedGeneration:args2.record.workflowGeneration,transitionId:`background-gate:${args2.record.correlationId}`,ensureDefaultStageB:existingEvidence?.test_engineer_exempt!==!0}),args2.record.normalizedAgent==="reviewer")await collectReviewerReceiptFromTranscript(args2.directory,{targetAgent:args2.record.swarmPrefixedAgent,prompt:args2.record.prompt?.text??"",transcript:args2.result.text??"",sessionID:args2.record.parentSessionId,taskId,reviewerCallID:args2.record.callID,consumeHandoff:!0},args2.reviewerReceiptOptions);if(args2.record.normalizedAgent==="reviewer"||args2.record.normalizedAgent==="test_engineer")applyStageBStateCompletion(taskId,args2.record.normalizedAgent,args2.record.parentSessionId,existingEvidence?.test_engineer_exempt===!0);return{ok:!0,consumed:!0}}catch(err){let message=err instanceof Error?err.message:String(err);return warn(`[background-stage-b] ingestion failed: ${message}`),{ok:!1,consumed:!1,reason:`stage-b ingestion failed: ${message}`}}}function candidateSessions(parentSessionId){let parent=swarmState.agentSessions.get(parentSessionId);return parent?[parent]:[]}function applyStageBStateCompletion(taskId,agent,parentSessionId,testEngineerExempt){for(let session of candidateSessions(parentSessionId)){recordStageBCompletion(session,taskId,agent);let state=getTaskState(session,taskId);if(state==="tests_run"||state==="complete")continue;if(hasBothStageBCompletions(session,taskId)||testEngineerExempt&&agent==="reviewer"){try{if(state==="coder_delegated"||state==="pre_check_passed")advanceTaskState(session,taskId,"reviewer_run",{telemetrySessionId:parentSessionId});if(getTaskState(session,taskId)==="reviewer_run")advanceTaskState(session,taskId,"tests_run",{telemetrySessionId:parentSessionId})}catch(err){warn(`[background-stage-b] could not advance ${taskId} after ${agent}: ${err instanceof Error?err.message:String(err)}`)}continue}if(agent==="reviewer"&&(state==="coder_delegated"||state==="pre_check_passed"))try{advanceTaskState(session,taskId,"reviewer_run",{telemetrySessionId:parentSessionId})}catch(err){warn(`[background-stage-b] could not advance ${taskId} to reviewer_run: ${err instanceof Error?err.message:String(err)}`)}else if(agent==="test_engineer"&&state==="reviewer_run")try{advanceTaskState(session,taskId,"tests_run",{telemetrySessionId:parentSessionId})}catch(err){warn(`[background-stage-b] could not advance ${taskId} to tests_run: ${err instanceof Error?err.message:String(err)}`)}}}init_task_envelope();init_workspace_snapshot();function createBackgroundCompletionObserver(opts){let{config:config3,directory}=opts;return{event:async(input)=>{if(!config3.enabled)return;try{let evt=input?.event;if(!evt||evt.type!=="message.part.updated")return;let part=evt.properties?.part;if(!part||part.type!=="text"||part.synthetic!==!0||typeof part.text!=="string")return;let envelope=parseTaskEnvelope(part.text);if(!envelope||envelope.state!=="completed"&&envelope.state!=="error"&&envelope.state!=="cancelled")return;let parentSessionId=typeof part.sessionID==="string"?part.sessionID:"",lookup=await findDelegationForCompletion(directory,envelope.sessionId);if(!lookup){log(`[background] trusted completion for ${envelope.sessionId} has no durable primary or fallback owner; ignored`);return}if(!parentSessionId||lookup.record.parentSessionId!==parentSessionId||lookup.record.subagentSessionId!==envelope.sessionId){warn(`[background] trusted completion identity mismatch for ${envelope.sessionId}; ignored`);return}let pending=lookup.record;if(lookup.source==="fallback"){let promoted=await promoteDelegationFallback(directory,envelope.sessionId);if(!promoted){warn(`[background] fallback promotion failed for ${envelope.sessionId}; terminal work remains preserved`);return}pending=promoted.record}let text=envelope.state==="error"||envelope.state==="cancelled"?envelope.errorText??"":envelope.resultText??"",result={...envelope.state==="error"?{error:text}:{text},chars:envelope.resultChars??text.length,truncated:envelope.resultTruncated??!1,digest:digest2(text)},terminal={eventId:buildBackgroundCompletionEventId({correlationId:pending.correlationId,jobId:pending.jobId,status:envelope.state,resultDigest:result.digest}),status:envelope.state,recordedAt:pending.terminalResult?.recordedAt??Date.now(),result},terminalClaim=await claimTerminalResult(directory,pending.correlationId,terminal);if(!terminalClaim){warn(`[background] terminal claim failed for ${pending.correlationId}; ignored`);return}let isDuplicate=terminalClaim.disposition==="duplicate",record3=terminalClaim.record;opts.onTerminalClaimed?.(record3);try{await maintainBackgroundDelegations(directory,{lockTimeoutMs:1000,reason:"trusted-terminal"})}catch{}if(terminal.status!=="completed"){if(isDuplicate)return;if(record3.normalizedAgent==="coder"){if(record3.planTaskId){let expectedGeneration=record3.taskChangeContext?.workflowGeneration;if(expectedGeneration===void 0)warn(`[background] failed coder ${record3.correlationId} has no launch generation for task ${record3.planTaskId}`);else try{await transitionTaskWorkflowEvidence(directory,record3.planTaskId,{type:"dispatch_no_mutation",agentType:"coder",expectedGeneration,transitionId:`background-coder-terminal:${terminal.eventId}`})}catch(error93){warn(`[background] failed coder retry accounting was fenced for ${record3.planTaskId}: ${error93 instanceof Error?error93.message:String(error93)}`)}}try{await releaseCoderReservation(directory,record3,"recovered")}catch(error93){warn(`[background] failed coder reservation cleanup will be retried by admission reconciliation: ${error93 instanceof Error?error93.message:String(error93)}`)}if(record3.worktree){let descriptor=record3.worktree;if(!standardWorktreeByCallID.has(record3.callID))standardWorktreeByCallID.set(record3.callID,{callID:descriptor.callID,parentSessionID:descriptor.parentSessionId,taskId:descriptor.taskId,...descriptor.planTaskId?{planTaskId:descriptor.planTaskId}:{},handle:{worktreePath:descriptor.worktreePath,branchName:descriptor.branchName,purpose:"lane",id:descriptor.worktreeId,sessionId:descriptor.worktreeSessionId},mergeStrategy:descriptor.mergeStrategy,laneIndex:descriptor.laneIndex,...descriptor.worktreeDir?{worktree_dir:descriptor.worktreeDir}:{}});try{await abortStandardWorktreeDispatch(record3.callID,"cancelled",directory)}catch(error93){warn(`[background] failed coder worktree cleanup preserved the lane for manual recovery: ${error93 instanceof Error?error93.message:String(error93)}`)}}}discardScopeForRecord(record3),await publishAdvisory(directory,record3,terminal.eventId,terminal.status==="cancelled"?"cancelled":"failed");return}if(record3.normalizedAgent==="coder"){let settled=await settleCoder(directory,record3,terminal.eventId);if(record3=settled.record,!settled.ok){await publishAdvisory(directory,record3,terminal.eventId,settled.outcome);return}}else if(!isDuplicate&&isBackgroundGateBearingRecord(record3)){if(validateStageBWorkspace(directory,record3).stale){await appendDelegationTransition(directory,record3.correlationId,{status:"stale"}),discardScopeForRecord(record3),await publishAdvisory(directory,record3,terminal.eventId,"stale");return}}if(record3.normalizedAgent==="coder"||isBackgroundGateBearingRecord(record3)){let ingestion=await claimDelegationIngestion(directory,record3.correlationId,{claimantId:terminal.eventId});if(ingestion?.disposition==="claimed"||ingestion?.disposition==="retry"){let applied=await ingestBackgroundStageBCompletion({directory,record:ingestion.record,result:ingestion.record.result??result,reviewerReceiptOptions:opts.reviewerReceiptOptions}),claimToken=ingestion.record.ingestion?.claimToken;if(!claimToken){await publishAdvisory(directory,record3,terminal.eventId,"ingestion claim token missing");return}let ingestionCommit=await(opts.recordIngestionResult??recordDelegationIngestionResult)(directory,record3.correlationId,claimToken,applied.ok);if(!ingestionCommit){warn(`[background] ingestion claim for ${record3.correlationId} expired or was fenced before commit; retry remains pending`);return}if(applied.ok&&(ingestionCommit.status!=="consumed"||ingestionCommit.ingestion?.state!=="consumed"||ingestionCommit.ingestion.claimToken!==claimToken)){warn(`[background] ingestion commit for ${record3.correlationId} did not confirm the exact consumed claim; retry remains pending`);return}if(record3=ingestionCommit,record3=(await findDelegationForCompletion(directory,record3.correlationId))?.record??record3,!applied.ok){await publishAdvisory(directory,record3,terminal.eventId,applied.stale?"stale":"ingestion failed");try{await maintainBackgroundDelegations(directory,{lockTimeoutMs:1000,reason:"ingestion-rejection"})}catch{}return}}else if(ingestion?.disposition==="busy")return;else if(ingestion?.disposition!=="consumed"){await publishAdvisory(directory,record3,terminal.eventId,"ingestion pending");return}}if(record3.normalizedAgent==="docs")try{if(!await completeBackgroundPhaseParticipation({directory,record:record3,resultText:text}))warn(`[background] docs completion ${record3.correlationId} did not satisfy its durable phase-participation binding`)}catch(error93){warn(`[background] docs completion ${record3.correlationId} could not persist phase participation: ${error93 instanceof Error?error93.message:String(error93)}`)}if(record3.normalizedAgent==="reviewer")discardScopeForRecord(record3);if(record3.normalizedAgent==="coder")await releaseCoderReservation(directory,record3,"consumed");await publishAdvisory(directory,record3,terminal.eventId,record3.normalizedAgent==="coder"?"completed and settled":"completed"),log(`[background] trusted completion settled: agent=${record3.normalizedAgent} task=${taskLabel(record3)} parent=${record3.parentSessionId}`)}catch(err){warn(`[background] completion observer error: ${err instanceof Error?err.message:String(err)}`)}},prepareAdvisories:async(parentSessionId)=>{if(!config3.enabled||!parentSessionId)return null;let preparationId=`bg-prepare:${cryptoRandomId()}`,entries=await preparePendingBackgroundAdvisories(directory,parentSessionId,{preparationId});return entries.length===0?null:{preparationId,eventIds:entries.map((entry)=>entry.eventId),messages:entries.map((entry)=>entry.message)}},ackObservedAdvisories:(parentSessionId,observedTexts)=>acknowledgeObservedBackgroundAdvisories(directory,parentSessionId,observedTexts),releaseAdvisories:(parentSessionId,prepared)=>releasePreparedBackgroundAdvisories(directory,parentSessionId,prepared.preparationId,prepared.eventIds)}}async function releaseCoderReservation(directory,record3,reason){if(!record3.coderReservationId)return;let bound=await bindBackgroundCoderReservation(directory,{reservationId:record3.coderReservationId,parentSessionId:record3.parentSessionId,planTaskId:record3.planTaskId,callID:record3.callID,correlationId:record3.correlationId});if(!bound){warn(`[background] coder reservation ${record3.coderReservationId} could not be bound for ${record3.correlationId}; admission remains fail-closed`);return}if(!await releaseBackgroundCoderReservation(directory,{...bound,generation:record3.generation??1,reason}))warn(`[background] coder reservation ${record3.coderReservationId} could not be released after ${reason}; the next admission will retry reconciliation`)}async function settleCoder(directory,record3,operationId){let context=record3.taskChangeContext;if(!context)return{ok:!1,record:record3,outcome:"stale: no coder baseline"};let claim=await claimCoderSettlement(directory,record3.correlationId,operationId);if(!claim)return{ok:!1,record:record3,outcome:"settlement claim failed"};if(claim.disposition==="settled")return{ok:!0,record:claim.record,outcome:"completed and settled"};if(claim.disposition==="preserved")return{ok:!1,record:claim.record,outcome:"settlement preserved"};if(record3=claim.record,!record3.worktree){let baseline=context.baseline,current=captureWorkspaceSnapshot(directory,{scope:baseline.scope,prHeadSha:baseline.prHeadSha,resolveCurrentPrHeadSha:baseline.prHeadSha!==null}),repositoryDelta=changedFilesSinceSnapshot(directory,baseline),declaredFiles=context.declaredFiles,observedFiles2=repositoryDelta&&declaredFiles&&declaredFiles.length>0?repositoryDelta.filter((file3)=>isInDeclaredScope(file3,declaredFiles,directory)):null,staleReason=path220.resolve(baseline.directory)!==path220.resolve(directory)?"shared-root directory identity changed":!baseline.gitHead||current.gitHead!==baseline.gitHead?"shared-root HEAD changed before coder completion":baseline.prHeadSha!==null&&current.prHeadSha!==baseline.prHeadSha?"shared-root PR head changed before coder completion":observedFiles2===null?"shared-root coder files could not be attributed to a non-empty declared scope":null;if(staleReason||observedFiles2===null){let preserved2=await updateCoderSettlement(directory,record3.correlationId,{operationId,state:"preserved",observedFiles:null,outcome:{kind:"shared-root",result:"failed",reason:staleReason??"coder attribution failed"}});return await appendDelegationTransition(directory,record3.correlationId,{status:"stale"}),{ok:!1,record:preserved2??record3,outcome:`stale: ${staleReason??"coder attribution failed"}`}}let settled=await updateCoderSettlement(directory,record3.correlationId,{operationId,state:"settled",observedFiles:observedFiles2,outcome:{kind:"shared-root",result:"ready"}});return settled?{ok:!0,record:settled,outcome:"completed and settled"}:{ok:!1,record:record3,outcome:"settlement persistence failed"}}let descriptor=record3.worktree;if(descriptor.callID!==record3.callID||descriptor.parentSessionId!==record3.parentSessionId||descriptor.planTaskId!==record3.planTaskId||path220.resolve(context.baseline.directory)!==path220.resolve(descriptor.worktreePath))return{ok:!1,record:await updateCoderSettlement(directory,record3.correlationId,{operationId,state:"preserved",observedFiles:null,outcome:{kind:"standard-worktree",result:"failed",reason:"worktree recovery identity does not match the dispatch"}})??record3,outcome:"worktree settlement preserved: identity mismatch"};let observedFiles=changedFilesSinceSnapshot(descriptor.worktreePath,context.baseline);if(observedFiles===null)return{ok:!1,record:await updateCoderSettlement(directory,record3.correlationId,{operationId,state:"preserved",observedFiles:null,outcome:{kind:"standard-worktree",result:"failed",reason:"worktree files could not be attributed to the clean baseline"}})??record3,outcome:"worktree settlement preserved: attribution failed"};let dispatch=standardWorktreeByCallID.get(record3.callID)??{callID:descriptor.callID,parentSessionID:descriptor.parentSessionId,taskId:descriptor.taskId,...descriptor.planTaskId?{planTaskId:descriptor.planTaskId}:{},handle:{worktreePath:descriptor.worktreePath,branchName:descriptor.branchName,purpose:"lane",id:descriptor.worktreeId,sessionId:descriptor.worktreeSessionId},mergeStrategy:descriptor.mergeStrategy,laneIndex:descriptor.laneIndex,...descriptor.worktreeDir?{worktree_dir:descriptor.worktreeDir}:{}};standardWorktreeByCallID.delete(record3.callID),awaitingMergeByCallID.set(record3.callID,{callID:record3.callID,parentSessionID:descriptor.parentSessionId,taskId:descriptor.taskId,...descriptor.planTaskId?{planTaskId:descriptor.planTaskId}:{},branch:descriptor.branchName,worktreePath:descriptor.worktreePath,mergeStrategy:descriptor.mergeStrategy,queuedAt:Date.now()});let resume=settlementResume(record3),mergeResult=await finishStandardWorktreeDispatch(directory,dispatch,void 0,record3.callID,{operationId,...resume?{resume}:{},onBeforeMerge:async(provenance)=>{let persisted=await updateCoderSettlement(directory,record3.correlationId,{operationId,state:"settling",sourceHeadAfterCommit:provenance.sourceHead,targetHeadBeforeMerge:provenance.targetHeadBefore,observedFiles});if(!persisted)throw Error("could not persist pre-merge provenance");record3=persisted},onMerged:async(merged)=>{let provenance=merged.provenance??resume,persisted=await updateCoderSettlement(directory,record3.correlationId,{operationId,state:"settled",observedFiles,...provenance?{sourceHeadAfterCommit:provenance.sourceHead,targetHeadBeforeMerge:provenance.targetHeadBefore}:{},outcome:{kind:"standard-worktree",result:provenance&&provenance.sourceHead!==provenance.targetHeadBefore?"merged":"unchanged",sourceHeadAfterCommit:provenance?.sourceHead??null,targetHeadBeforeMerge:provenance?.targetHeadBefore??null,targetHeadAfterMerge:resolveCurrentGitHead(directory)}});if(!persisted)throw Error("could not persist merged settlement");record3=persisted}});if(mergeResult.outcome==="merged")return{ok:!0,record:(await findDelegationForCompletion(directory,record3.correlationId))?.record??record3,outcome:"completed and merged"};if(mergeResult.outcome==="failed"&&mergeResult.stage==="settlement-persist")return{ok:!1,record:record3,outcome:"worktree settlement persistence pending retry"};return{ok:!1,record:await updateCoderSettlement(directory,record3.correlationId,{operationId,state:"preserved",observedFiles,...mergeResult.provenance?{sourceHeadAfterCommit:mergeResult.provenance.sourceHead,targetHeadBeforeMerge:mergeResult.provenance.targetHeadBefore}:{},outcome:{kind:"standard-worktree",result:mergeResult.outcome,reason:mergeResult.message,sourceHeadAfterCommit:mergeResult.provenance?.sourceHead??null,targetHeadBeforeMerge:mergeResult.provenance?.targetHeadBefore??null}})??record3,outcome:`worktree settlement preserved: ${mergeResult.message}`}}function settlementResume(record3){let{coderSettlement:settlement,worktree}=record3;if(settlement?.state!=="settling"||!settlement.operationId||!settlement.sourceHeadAfterCommit||!settlement.targetHeadBeforeMerge||!GIT_OBJECT_ID_PATTERN.test(settlement.sourceHeadAfterCommit)||!GIT_OBJECT_ID_PATTERN.test(settlement.targetHeadBeforeMerge)||!worktree)return;return{operationId:settlement.operationId,sourceHead:settlement.sourceHeadAfterCommit,targetHeadBefore:settlement.targetHeadBeforeMerge,branchName:worktree.branchName,strategy:worktree.mergeStrategy}}async function publishAdvisory(directory,record3,eventId,outcome){let message=`[BACKGROUND COMPLETION ${eventId}] ${record3.normalizedAgent} task ${taskLabel(record3)} ${outcome}.`,stored=await putPendingBackgroundAdvisory(directory,record3.correlationId,{eventId,parentSessionId:record3.parentSessionId,message});if(!stored)return;let session=swarmState.agentSessions.get(record3.parentSessionId);if(session)pushAdvisory(session,stored.message)}function taskLabel(record3){return record3.evidenceTaskId??record3.planTaskId??"unknown"}function discardScopeForRecord(record3){let taskId=record3.evidenceTaskId??record3.planTaskId;if(!taskId)return;if(record3.normalizedAgent==="reviewer")discardReviewerScopeGenerationClaim({parentSessionID:record3.parentSessionId,taskId,reviewerCallID:record3.callID});else if(record3.normalizedAgent==="coder")discardReviewerScopeGenerationForCoderCall({parentSessionID:record3.parentSessionId,taskId,coderCallID:record3.callID})}function digest2(text){return createHash58("sha256").update(text).digest("hex")}function cryptoRandomId(){return createHash58("sha256").update(`${Date.now()}:${Math.random()}`).digest("hex").slice(0,24)}init_pr_subscriptions();init_commands();init_registry2();init_config();init_agent_model();init_bundled_skills();init_constants();init_config();init_warning_buffer();init_constants();import*as fs117 from"node:fs";import*as path221 from"node:path";var STARTER_CONTENT=`{}
6323
6324
  `;function writeProjectConfigIfNew(directory,_quiet=!1){try{let opencodeDir=path221.join(directory,".opencode"),dest=path221.join(opencodeDir,"opencode-swarm.json"),normalizePathForCompare=(p)=>process.platform==="win32"?p.toLowerCase():p;try{if(fs117.lstatSync(opencodeDir).isSymbolicLink())return;let resolvedDir=fs117.realpathSync(opencodeDir),canonicalOpencode=path221.join(fs117.realpathSync(directory),".opencode");if(normalizePathForCompare(resolvedDir)!==normalizePathForCompare(canonicalOpencode))return}catch(err){if(err.code!=="ENOENT")return}if(!fs117.existsSync(opencodeDir))fs117.mkdirSync(opencodeDir,{recursive:!0});try{fs117.writeFileSync(dest,STARTER_CONTENT,{encoding:"utf-8",flag:"wx"}),advisoryWarn("[opencode-swarm] Created .opencode/opencode-swarm.json — "+"edit it to customize agent LLMs for this project, or commit it to share settings with your team")}catch(_writeErr){}}catch{}}function writeSwarmConfigExampleIfNew(projectDirectory){try{let swarmDir=path221.join(projectDirectory,".swarm"),dest=path221.join(swarmDir,"config.example.json");if(fs117.existsSync(dest))return;if(!fs117.existsSync(swarmDir))fs117.mkdirSync(swarmDir,{recursive:!0});let example={agents:Object.fromEntries(Object.entries(DEFAULT_MODELS).filter(([name])=>name!=="default").map(([name,model])=>[name,{model,fallback_models:["opencode/gpt-5-nano","opencode/big-pickle"]}])),max_iterations:5};fs117.writeFileSync(dest,`${JSON.stringify(example,null,2)}
6324
6325
  `,"utf-8")}catch{}}init_schema();init_schema();init_delegation_gate();init_utils();import*as fs118 from"node:fs";import*as path222 from"node:path";var FOR_TAG_PATTERN=/^\[FOR:\s*([^\]]+)\]/i;function containsPlanContent(text){if(!text)return!1;let lowerText=text.toLowerCase();return lowerText.includes(".swarm/plan")||lowerText.includes(".swarm/context")||lowerText.includes("swarm/plan.md")||lowerText.includes("swarm/context.md")}function containsKnowledgeContent(text){if(!text)return!1;let lowerText=text.toLowerCase();return lowerText.includes("knowledge")||lowerText.includes("lesson")||lowerText.includes(".swarm/knowledge")||lowerText.includes("swarm knowledge")}function parseForTag(content){let match=content.trim().match(FOR_TAG_PATTERN);if(!match)return null;let tagContent=match[1].trim();if(tagContent.toLowerCase()==="all")return["all"];return tagContent.split(",").map((agent)=>agent.trim().toLowerCase()).filter(Boolean)}function isTargetRoleAllowed(targetRole,allowedAgents){if(allowedAgents.includes("all"))return!0;let normalizedTarget=stripKnownSwarmPrefix(targetRole).toLowerCase();return allowedAgents.some((agent)=>{let normalizedAgent=stripKnownSwarmPrefix(agent).toLowerCase();return normalizedTarget===normalizedAgent})}function shouldNeverFilter(entry){if(entry.role==="system")return!0;if(entry.role==="user"){if(parseDelegationEnvelope(entry.content))return!0}if(entry.role==="assistant"){if(containsPlanContent(entry.content)||containsKnowledgeContent(entry.content))return!0}return!1}function logFilteringMetrics(directory,targetRole,totalEntries,includedEntries){try{let eventsPath=path222.join(directory,".swarm","events.jsonl"),event={event:"context_filtered",timestamp:new Date().toISOString(),agentName:targetRole,totalEntries,includedEntries,filteredEntries:totalEntries-includedEntries,estimatedTokensSaved:(totalEntries-includedEntries)*100},swarmDir=path222.dirname(eventsPath);if(!fs118.existsSync(swarmDir))fs118.mkdirSync(swarmDir,{recursive:!0});fs118.appendFileSync(eventsPath,`${JSON.stringify(event)}
6325
6326
  `,"utf-8")}catch(error93){log("[RoleFilter] event append failed",{error:error93 instanceof Error?error93.message:String(error93)})}}function filterByRole(entries,targetRole,directory,options={}){if(!entries||entries.length===0)return[];let filtered=[];for(let entry of entries){let allowedAgents=parseForTag(entry.content),canFilterTaggedSystem=entry.role==="system"&&options.filterTaggedSystem===!0&&allowedAgents!==null&&allowedAgents.length>0;if(shouldNeverFilter(entry)&&!canFilterTaggedSystem){filtered.push(entry);continue}if(allowedAgents===null){filtered.push(entry);continue}if(isTargetRoleAllowed(targetRole,allowedAgents))filtered.push(entry)}if(directory)logFilteringMetrics(directory,targetRole,entries.length,filtered.length);return filtered}function createRoleFilterSystemHook(getActiveAgentName){return{"experimental.chat.system.transform":async(input,output)=>{if(!input.sessionID||!Array.isArray(output.system))return;let targetRole=getActiveAgentName(input.sessionID);if(!targetRole)return;let entries=output.system.map((content)=>({role:"system",content})),kept=filterByRole(entries,targetRole,void 0,{filterTaggedSystem:!0}).map(({content})=>content);output.system.length=0;for(let content of kept)output.system.push(content)}}}import*as fs121 from"node:fs";import*as path225 from"node:path";import*as fs120 from"node:fs";import*as path224 from"node:path";import*as crypto13 from"node:crypto";import*as fs119 from"node:fs";import*as path223 from"node:path";var _internals171={readFileSync:fs119.readFileSync,writeFileSync:fs119.writeFileSync,mkdirSync:fs119.mkdirSync,renameSync:fs119.renameSync,existsSync:fs119.existsSync,statSync:fs119.statSync,createHash:crypto13.createHash.bind(crypto13)};function computeContentHash3(content){return _internals171.createHash("sha256").update(content,"utf-8").digest("hex")}function createEmptyContextMap(){return{schema_version:1,generated_at:new Date().toISOString(),repo_fingerprint:"",files:{},task_history:{},decisions:[]}}function loadContextMap(directory){let filePath=path223.join(directory,".swarm","context-map.json");try{if(!_internals171.existsSync(filePath))return null;let raw=_internals171.readFileSync(filePath,"utf-8"),parsed=JSON.parse(raw);if(typeof parsed!=="object"||parsed===null||parsed.schema_version!==1)return null;return parsed}catch{return null}}function saveContextMap(map3,directory){let swarmDir=path223.join(directory,".swarm"),tmpPath=path223.join(swarmDir,"context-map.tmp"),finalPath=path223.join(swarmDir,"context-map.json");_internals171.mkdirSync(swarmDir,{recursive:!0});let updated={...map3,generated_at:new Date().toISOString()},json3=JSON.stringify(updated,null,2);_internals171.writeFileSync(tmpPath,json3,"utf-8"),_internals171.renameSync(tmpPath,finalPath)}function appendTaskHistory(map3,summary){return{...map3,task_history:{...map3.task_history,[summary.task_id]:summary}}}function appendDecision(map3,decision){return{...map3,decisions:[...map3.decisions,decision]}}var EXTENSION_LANGUAGE_MAP={".ts":"typescript",".tsx":"typescript",".js":"javascript",".jsx":"javascript",".mjs":"javascript",".py":"python",".rs":"rust",".go":"go",".json":"json",".md":"markdown",".yaml":"yaml",".yml":"yaml",".css":"css",".scss":"scss",".html":"html",".sh":"shell",".bash":"shell",".ps1":"powershell"};function detectLanguage(filePath){let ext=path224.extname(filePath).toLowerCase();return EXTENSION_LANGUAGE_MAP[ext]}var RE_EXPORT_NAMED=/export\s+(?:function|class|interface|type|const|let|var|enum)\s+(\w+)/g,RE_EXPORT_BRACE=/export\s*\{\s*([\w,\s]+)\s*\}/g,RE_IMPORT_FROM=/import\s+.*?\s+from\s+['"](.+?)['"]/g,RE_IMPORT_REQUIRE=/require\(\s*['"](.+?)['"]\s*\)/g,RE_FIRST_COMMENT=/\/\*(.+?)\*\//s,MAX_KEY_SYMBOLS=10,MAX_PURPOSE_LENGTH=200;function extractFileSummary(filePath,content,absolutePath2,existingEntry){let contentHash=computeContentHash3(content),language=detectLanguage(filePath),exportsList=extractExports(content),importsList=extractImports5(content),purpose=extractPurpose(content),keySymbols=exportsList.slice(0,MAX_KEY_SYMBOLS),mtimeMs=0;if(absolutePath2)try{mtimeMs=fs120.statSync(absolutePath2).mtimeMs}catch{}let base={path:filePath,content_hash:contentHash,mtime_ms:mtimeMs,language,purpose,exports:exportsList.length>0?exportsList:void 0,imports:importsList.length>0?importsList:void 0,key_symbols:keySymbols.length>0?keySymbols:void 0,summary:purpose};if(existingEntry)return{...base,invariants:existingEntry.invariants,risks:existingEntry.risks,tests:existingEntry.tests,last_seen_task_ids:existingEntry.last_seen_task_ids};return base}function isFileStale(entry,currentContent){let currentHash=computeContentHash3(currentContent);return entry.content_hash!==currentHash}function extractExports(content){let symbols2=[],namedRe=new RegExp(RE_EXPORT_NAMED.source,"g"),match;match=namedRe.exec(content);while(match!==null)symbols2.push(match[1]),match=namedRe.exec(content);let braceRe=new RegExp(RE_EXPORT_BRACE.source,"g");match=braceRe.exec(content);while(match!==null){let list=match[1];for(let name of list.split(",")){let trimmed=name.trim();if(trimmed)symbols2.push(trimmed)}match=braceRe.exec(content)}return symbols2}function extractImports5(content){let specifiers=[],fromRe=new RegExp(RE_IMPORT_FROM.source,"g"),match;match=fromRe.exec(content);while(match!==null)specifiers.push(match[1]),match=fromRe.exec(content);let requireRe=new RegExp(RE_IMPORT_REQUIRE.source,"g");match=requireRe.exec(content);while(match!==null)specifiers.push(match[1]),match=requireRe.exec(content);return specifiers}function extractPurpose(content){let match=RE_FIRST_COMMENT.exec(content);if(!match)return"No summary available";let body=match[1].split(`
@@ -6957,8 +6958,8 @@ ${tailContent.join(`
6957
6958
  `)}
6958
6959
  ${footerLines.join(`
6959
6960
  `)}`}init_skill_propagation_gate();init_utils2();init_warning_buffer();init_cache_paths();import*as fs205 from"node:fs";import*as os28 from"node:os";import*as path327 from"node:path";import*as fs203 from"node:fs";import*as path325 from"node:path";var _internals253={realpathSyncNative:fs203.realpathSync.native};function hostWindowsPath(input){return input.replace(/^\/([a-zA-Z]):(?:[\\/]|$)/,(_m,d)=>`${d.toUpperCase()}:/`).replace(/^\/([a-zA-Z])(?:\/|$)/,(_m,d)=>`${d.toUpperCase()}:/`).replace(/^\/cygdrive\/([a-zA-Z])(?:\/|$)/,(_m,d)=>`${d.toUpperCase()}:/`).replace(/^\/mnt\/([a-zA-Z])(?:\/|$)/,(_m,d)=>`${d.toUpperCase()}:/`)}function hostNormalizePath(input){let resolved=path325.resolve(hostWindowsPath(input));try{return _internals253.realpathSyncNative(resolved)}catch{return resolved}}function hostNormalizePathPattern(pattern){if(pattern==="*")return pattern;let match=/^(.*)[\\/]\*$/.exec(pattern);if(!match)return hostNormalizePath(pattern);let dir=/^[A-Za-z]:$/.test(match[1])?`${match[1]}\\`:match[1];return path325.join(hostNormalizePath(dir),"*")}init_warning_buffer();init_swarm_branch();import*as fs204 from"node:fs";import*as path326 from"node:path";var MAX_CACHED_DIRECTORIES2=256,laneContextCache=new Map,_internals254={readFileSync:fs204.readFileSync,statSync:fs204.statSync,addDeferredWarning,clearCache:()=>{laneContextCache.clear()}},MAX_ANCESTOR_WALK_DEPTH=40,MAX_DETECTION_ATTEMPTS=3,DETECTION_RETRY_BACKOFF_MS=5;function sleepSync2(ms){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,ms)}catch{}}function remember(key,value,io){if(!io.failed)return cache5(key,value);try{_internals254.addDeferredWarning(`[swarm] Could not read git metadata for ${key} after ${MAX_DETECTION_ATTEMPTS} attempts; worktree-lane permission scoping was skipped for it. If this directory IS a swarm lane, external-directory prompts raised there cannot be answered and the lane may hang. Check filesystem permissions and open-file limits, then restart the session.`)}catch{}return null}function cache5(key,value){if(laneContextCache.size>=MAX_CACHED_DIRECTORIES2){let oldest=laneContextCache.keys().next();if(!oldest.done)laneContextCache.delete(oldest.value)}return laneContextCache.set(key,value),value}function isSwarmOwnedBranch(gitDir,io){let head2;try{head2=_internals254.readFileSync(path326.join(gitDir,"HEAD"),"utf-8")}catch(err2){if(err2?.code!=="ENOENT")io.failed=!0;return!1}let branch=/^\s*ref:\s*refs\/heads\/(.+?)\s*$/m.exec(head2)?.[1];if(!branch)return!1;return matchSwarmLaneBranch(branch)!==void 0}function readLinkedWorktreeGitDir(directory,io){let dotGit=path326.join(directory,".git"),stat21;try{stat21=_internals254.statSync(dotGit)}catch(err2){if(err2?.code!=="ENOENT")io.failed=!0;return}if(!stat21.isFile())return;let contents;try{contents=_internals254.readFileSync(dotGit,"utf-8")}catch(err2){if(err2?.code!=="ENOENT")io.failed=!0;return}let pointer=/^\s*gitdir:\s*(.+?)\s*$/m.exec(contents)?.[1];if(!pointer)return;return path326.resolve(directory,pointer)}function resolveMainWorktree(gitDir,io){let commonDir;try{let trimmed=_internals254.readFileSync(path326.join(gitDir,"commondir"),"utf-8").trim();if(trimmed)commonDir=path326.resolve(gitDir,trimmed)}catch(err2){if(err2?.code!=="ENOENT")io.failed=!0}if(commonDir){let parent2=path326.dirname(commonDir);return parent2&&parent2!==commonDir?parent2:void 0}let worktreesDir=path326.dirname(gitDir);if(path326.basename(worktreesDir)!=="worktrees")return;let sharedGitDir=path326.dirname(worktreesDir);if(path326.basename(sharedGitDir)!==".git")return;let parent=path326.dirname(sharedGitDir);return parent&&parent!==sharedGitDir?parent:void 0}function resolveLaneContext(directory){if(typeof directory!=="string"||directory.trim()==="")return null;let resolved;try{resolved=path326.resolve(directory)}catch{return null}let cached3=laneContextCache.get(resolved);if(cached3!==void 0)return cached3;let io={failed:!1},result=null;for(let attempt=1;attempt<=MAX_DETECTION_ATTEMPTS;attempt+=1){if(io={failed:!1},result=attemptDetection(resolved,io),result!==null||!io.failed)break;if(attempt<MAX_DETECTION_ATTEMPTS)sleepSync2(DETECTION_RETRY_BACKOFF_MS)}if(result!==null)return cache5(resolved,result);return remember(resolved,null,io)}function attemptDetection(resolved,io){try{let laneRoot,gitDir,current=resolved;for(let depth=0;depth<MAX_ANCESTOR_WALK_DEPTH;depth+=1){let candidate2=readLinkedWorktreeGitDir(current,io);if(candidate2){laneRoot=current,gitDir=candidate2;break}let parent=path326.dirname(current);if(parent===current)break;current=parent}if(!laneRoot||!gitDir)return null;if(!(isSwarmOwnedBranch(gitDir,io)||matchSwarmLanePath(laneRoot)!==void 0))return null;let parentProjectPath=resolveMainWorktree(gitDir,io);if(!parentProjectPath)return null;if(path326.resolve(parentProjectPath)===laneRoot)return null;return{lanePath:laneRoot,parentProjectPath:path326.resolve(parentProjectPath)}}catch{return io.failed=!0,null}}class LastWinsRuleMap{entries=new Map;set(pattern,action){this.entries.delete(pattern),this.entries.set(pattern,action)}toObject(){return Object.fromEntries(this.entries)}}var SKILL_DIR_NAMES=["skill","skills"],HOST_HOME_SKILL_MARKERS=[".claude",".agents"];function laneDirectoryPattern(dir){return hostNormalizePathPattern(path327.join(dir,"*"))}function isExpressibleDirectory(dir){return!dir.includes("*")&&!dir.includes("?")}function push(out,seen,dir,reason){if(!dir)return;let resolved;try{resolved=path327.resolve(dir)}catch{return}if(!isExpressibleDirectory(resolved))return;let key=process.platform==="win32"?resolved.toLowerCase():resolved;if(seen.has(key))return;seen.add(key),out.push({dir:resolved,pattern:laneDirectoryPattern(resolved),reason})}function buildLaneAllowlist(lane,configuredSkillPaths=[],configuredSkillUrls=[]){let out=[],seen=new Set;push(out,seen,lane.parentProjectPath,"parent project the lane is a git worktree of"),push(out,seen,lane.lanePath,"the lane worktree itself"),push(out,seen,getPluginConfigDir(),"OpenCode XDG config dir (host Global.Path.config)"),push(out,seen,getHostConfigDir(),"OpenCode config dir override (OPENCODE_CONFIG_DIR), when set");let tmpRoot=os28.tmpdir();if(push(out,seen,path327.join(tmpRoot,"opencode"),"OpenCode's own temp dir (host Global.Path.tmp)"),process.platform==="win32")push(out,seen,path327.join(tmpRoot,"swwt"),"shortened-worktree lane root (Windows path-budget fallback)");push(out,seen,path327.join(getHostDataDir(),"plans"),"OpenCode plan storage (host `plan` agent's native allow)");let home;try{home=os28.homedir()}catch{home=void 0}let projectRoots=[{base:lane.parentProjectPath,label:"parent project"},{base:lane.lanePath,label:"lane"}];for(let marker of HOST_HOME_SKILL_MARKERS){for(let{base,label}of projectRoots)push(out,seen,path327.resolve(base,marker,"skills"),`skill root (${label}): ${marker}/skills`);if(home)push(out,seen,path327.resolve(home,marker,"skills"),`skill root (user level): ~/${marker}/skills`)}let configSkillRoots=[{base:getPluginConfigDir(),label:"XDG config dir"},{base:getHostConfigDir(),label:"config dir override"},...projectRoots.map(({base,label})=>({base:path327.resolve(base,".opencode"),label:`${label} .opencode`})),...home?[{base:path327.join(home,".opencode"),label:"user-level .opencode"}]:[]];for(let{base,label}of configSkillRoots)for(let dirName of SKILL_DIR_NAMES)push(out,seen,path327.resolve(base,dirName),`skill root (${label}): ${dirName}/`);for(let relative78 of SKILL_SEARCH_ROOTS){for(let{base,label}of projectRoots)push(out,seen,path327.resolve(base,relative78),`skill root (${label}): ${relative78}`);if(home)push(out,seen,path327.resolve(home,relative78),`skill root (user level): ~/${relative78}`)}if((Array.isArray(configuredSkillUrls)?configuredSkillUrls:[]).some((u)=>typeof u==="string"&&u.trim()!==""))push(out,seen,getHostSkillCacheDir(),"URL-sourced skill cache (only because skills.urls is configured)");let skillPaths=Array.isArray(configuredSkillPaths)?configuredSkillPaths:[];for(let configured of skillPaths){if(typeof configured!=="string"||configured.trim()==="")continue;let expanded=configured.startsWith("~/")&&home?path327.join(home,configured.slice(2)):configured;push(out,seen,path327.isAbsolute(expanded)?expanded:path327.resolve(lane.lanePath,expanded),`configured skills.path: ${configured}`)}return out}function normalizeExisting(existing){if(typeof existing==="string")return{"*":existing};if(existing&&typeof existing==="object"&&!Array.isArray(existing))return{...existing};return}function buildLaneExternalDirectoryRules(mode,lane,existing,precomputedAllowlist){if(mode==="off")return null;let rules=new LastWinsRuleMap;if(rules.set("*","deny"),mode==="scoped_allow")for(let entry of precomputedAllowlist??buildLaneAllowlist(lane))rules.set(entry.pattern,"allow");let coercedAskPatterns=[],user=normalizeExisting(existing);if(user)for(let[pattern,action]of Object.entries(user)){if(action==="ask"){coercedAskPatterns.push(pattern),rules.set(pattern,"deny");continue}rules.set(pattern,action)}return{rules:rules.toObject(),coercedAskPatterns}}function renderLanePermissionAdvisory(mode,lane,allowlist,coercedAskPatterns=[]){let scope=mode==="deny"?"ALL external directory access is denied in this lane":`external directory access is limited to ${allowlist.length} justified path(s)`,parts=[`[swarm] Worktree-lane permissions active for ${lane.lanePath} (worktree of ${lane.parentProjectPath}).`,`Policy worktree.lane_permissions="${mode}": ${scope}; anything else is denied rather than left pending.`,'A lane instance has no TUI attached, so an "ask" there can never be answered and would hang the lane forever.'];if(coercedAskPatterns.length>0)parts.push(`Your configured external_directory "ask" rule(s) [${coercedAskPatterns.join(", ")}] were treated as "deny" here for that reason — change them to "allow" if the lane needs those paths.`);return parts.push("To widen the allowlist, add the directory to opencode.json:",' { "permission": { "external_directory": { "<absolute-dir>/*": "allow" } } }','To restore the previous (hanging) behaviour, set worktree.lane_permissions to "off".'),parts.join(" ")}var _internals255={resolveLaneContext,addDeferredWarning,appendFileSync:fs205.appendFileSync,mkdirSync:fs205.mkdirSync};function readConfiguredSkillList(opencodeConfig,key){let skills=opencodeConfig.skills;if(!skills||typeof skills!=="object"||Array.isArray(skills))return[];let value=skills[key];if(!Array.isArray(value))return[];return value.filter((v)=>typeof v==="string"&&v.trim()!=="")}function downgradeAgentAskRules(opencodeConfig){let coerced=[],agents=opencodeConfig.agent;if(!agents||typeof agents!=="object"||Array.isArray(agents))return coerced;for(let[agentName,rawAgent]of Object.entries(agents)){if(!rawAgent||typeof rawAgent!=="object"||Array.isArray(rawAgent))continue;let rawPermission=rawAgent.permission;if(!rawPermission||typeof rawPermission!=="object"||Array.isArray(rawPermission))continue;let agentPermission=rawPermission,external3=agentPermission.external_directory;if(external3==="ask"){agentPermission.external_directory="deny",coerced.push(`${agentName}.*`);continue}if(!external3||typeof external3!=="object"||Array.isArray(external3))continue;let map3=external3;for(let[pattern,action]of Object.entries(map3)){if(action!=="ask")continue;map3[pattern]="deny",coerced.push(`${agentName}.${pattern}`)}}return coerced}function recordLanePermissionEvent(directory,event){try{let eventsPath=validateSwarmPath(directory,"events.jsonl");_internals255.mkdirSync(path327.dirname(eventsPath),{recursive:!0}),_internals255.appendFileSync(eventsPath,`${JSON.stringify(event)}
6960
- `,"utf-8")}catch{}}function applyLanePermissions(opencodeConfig,directory,mode){let lane=_internals255.resolveLaneContext(directory);if(!lane)return{lane:!1};let eventRoot=lane.lanePath;if(mode==="off")return recordLanePermissionEvent(eventRoot,{event:"lane_permissions",timestamp:new Date().toISOString(),decision:"skipped",mode,lanePath:lane.lanePath,parentProjectPath:lane.parentProjectPath,reason:'worktree.lane_permissions is "off"; external_directory asks in this lane cannot be answered and will hang'}),{lane:!0,mode};let permission=(()=>{let current=opencodeConfig.permission;if(current&&typeof current==="object"&&!Array.isArray(current))return current;let created={};return opencodeConfig.permission=created,created})(),agentCoerced=downgradeAgentAskRules(opencodeConfig),allowlist=mode==="scoped_allow"?buildLaneAllowlist(lane,readConfiguredSkillList(opencodeConfig,"paths"),readConfiguredSkillList(opencodeConfig,"urls")):[],build=buildLaneExternalDirectoryRules(mode,lane,permission.external_directory,allowlist);if(!build)return{lane:!0,mode};let{rules,coercedAskPatterns:topLevelCoerced}=build;permission.external_directory=rules;let coercedAskPatterns=[...topLevelCoerced,...agentCoerced];return _internals255.addDeferredWarning(renderLanePermissionAdvisory(mode,lane,allowlist,coercedAskPatterns)),recordLanePermissionEvent(eventRoot,{event:"lane_permissions",timestamp:new Date().toISOString(),decision:"applied",mode,lanePath:lane.lanePath,parentProjectPath:lane.parentProjectPath,allowlist:allowlist.map((entry)=>({pattern:entry.pattern,reason:entry.reason})),rules,coercedAskPatterns,remedy:'Add { "permission": { "external_directory": { "<absolute-dir>/*": "allow" } } } to opencode.json to widen the allowlist.'}),{lane:!0,mode,rules}}init_warning_buffer();init_archive_sqlite();init_fixtures();init_gate_ground_truth();init_pr_review_recovery();init_public_api();var _heartbeatTimers=new Map,MAX_TRACKED_HEARTBEAT_SESSIONS=500;function capSessionMap(map3,max){while(map3.size>max){let oldest=map3.keys().next().value;if(oldest===void 0)break;map3.delete(oldest)}}var _delegationTelemetryByCallID=new Map,MAX_TRACKED_DELEGATION_TELEMETRY=500;function _resetDelegationTelemetryPairingForTesting(){_delegationTelemetryByCallID.clear()}var SWARM_COMMAND_SYSTEM_RULE_TAG="[opencode-swarm:swarm-command-rule]",PACKAGE_ROOT2=path329.resolve(path329.dirname(fileURLToPath7(import.meta.url)),".."),SYNC_BUNDLED_SKILLS_TIMEOUT_MS=2000,LOAD_PLUGIN_CONFIG_TIMEOUT_MS=2000;function createSwarmCommandSystemRuleHook(agentDefinitions,registeredAgents){return async(input,output)=>{let{sessionID}=input,activeAgentName=sessionID?swarmState.activeAgent.get(sessionID):void 0;if(!agentHasSwarmCommandTool(activeAgentName,agentDefinitions,registeredAgents))return;let system=Array.isArray(output.system)?output.system:[];if(system.some((entry)=>entry.includes(SWARM_COMMAND_SYSTEM_RULE_TAG))){output.system=system;return}system.push([SWARM_COMMAND_SYSTEM_RULE_TAG,"When a user asks for a supported /swarm command and the message instructs you to call the `swarm_command` tool, call that tool exactly once with the provided JSON arguments. After the tool returns, show the tool output verbatim and do not add extra swarm state, summaries, or invented command output."].join(`
6961
+ `,"utf-8")}catch{}}function applyLanePermissions(opencodeConfig,directory,mode){let lane=_internals255.resolveLaneContext(directory);if(!lane)return{lane:!1};let eventRoot=lane.lanePath;if(mode==="off")return recordLanePermissionEvent(eventRoot,{event:"lane_permissions",timestamp:new Date().toISOString(),decision:"skipped",mode,lanePath:lane.lanePath,parentProjectPath:lane.parentProjectPath,reason:'worktree.lane_permissions is "off"; external_directory asks in this lane cannot be answered and will hang'}),{lane:!0,mode};let permission=(()=>{let current=opencodeConfig.permission;if(current&&typeof current==="object"&&!Array.isArray(current))return current;let created={};return opencodeConfig.permission=created,created})(),agentCoerced=downgradeAgentAskRules(opencodeConfig),allowlist=mode==="scoped_allow"?buildLaneAllowlist(lane,readConfiguredSkillList(opencodeConfig,"paths"),readConfiguredSkillList(opencodeConfig,"urls")):[],build=buildLaneExternalDirectoryRules(mode,lane,permission.external_directory,allowlist);if(!build)return{lane:!0,mode};let{rules,coercedAskPatterns:topLevelCoerced}=build;permission.external_directory=rules;let coercedAskPatterns=[...topLevelCoerced,...agentCoerced];return _internals255.addDeferredWarning(renderLanePermissionAdvisory(mode,lane,allowlist,coercedAskPatterns)),recordLanePermissionEvent(eventRoot,{event:"lane_permissions",timestamp:new Date().toISOString(),decision:"applied",mode,lanePath:lane.lanePath,parentProjectPath:lane.parentProjectPath,allowlist:allowlist.map((entry)=>({pattern:entry.pattern,reason:entry.reason})),rules,coercedAskPatterns,remedy:'Add { "permission": { "external_directory": { "<absolute-dir>/*": "allow" } } } to opencode.json to widen the allowlist.'}),{lane:!0,mode,rules}}init_warning_buffer();init_archive_sqlite();init_fixtures();init_gate_ground_truth();init_pr_review_recovery();init_public_api();var _heartbeatTimers=new Map,MAX_TRACKED_HEARTBEAT_SESSIONS=500;function capSessionMap(map3,max){while(map3.size>max){let oldest=map3.keys().next().value;if(oldest===void 0)break;map3.delete(oldest)}}var _delegationTelemetryByCallID=new Map,MAX_TRACKED_DELEGATION_TELEMETRY=500;function _resetDelegationTelemetryPairingForTesting(){_delegationTelemetryByCallID.clear()}var SWARM_COMMAND_SYSTEM_RULE_TAG="[opencode-swarm:swarm-command-rule]",PACKAGE_ROOT2=path329.resolve(path329.dirname(fileURLToPath7(import.meta.url)),".."),SYNC_BUNDLED_SKILLS_TIMEOUT_MS=2000,BACKGROUND_MAINTENANCE_INIT_TIMEOUT_MS=1e4,LOAD_PLUGIN_CONFIG_TIMEOUT_MS=2000;function createSwarmCommandSystemRuleHook(agentDefinitions,registeredAgents){return async(input,output)=>{let{sessionID}=input,activeAgentName=sessionID?swarmState.activeAgent.get(sessionID):void 0;if(!agentHasSwarmCommandTool(activeAgentName,agentDefinitions,registeredAgents))return;let system=Array.isArray(output.system)?output.system:[];if(system.some((entry)=>entry.includes(SWARM_COMMAND_SYSTEM_RULE_TAG))){output.system=system;return}system.push([SWARM_COMMAND_SYSTEM_RULE_TAG,"When a user asks for a supported /swarm command and the message instructs you to call the `swarm_command` tool, call that tool exactly once with the provided JSON arguments. After the tool returns, show the tool output verbatim and do not add extra swarm state, summaries, or invented command output."].join(`
6961
6962
  `)),output.system=system}}function schedulePostResolutionTasks(tasks){if(tasks.length===0)return;let timer=setTimeout(()=>{for(let task2 of tasks)try{Promise.resolve(task2()).catch((err2)=>{log("post-resolution startup task failed (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})})}catch(err2){log("post-resolution startup task failed (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})}},0);if(typeof timer.unref==="function")timer.unref()}var createRepoGraphBuilderHookForInit=createRepoGraphBuilderHook,schedulePostResolutionTasksForInit=schedulePostResolutionTasks,loadPluginConfigWithMetaAsyncForInit=loadPluginConfigWithMetaAsync,loadSnapshotForInit=loadSnapshot,ensureSwarmGitExcludedForInit=ensureSwarmGitExcluded,resolveAutoReviewConfigForInit=resolveAutoReviewConfig,regenerateMemoryReflectionForInit=async(directory,config3)=>{let{regenerateMemoryReflection:regenerateMemoryReflection2}=await Promise.resolve().then(() => (init_reflection_service(),exports_reflection_service));return regenerateMemoryReflection2(directory,config3)};function overrideIndexInternalsForTest(overrides){let previousCreateRepoGraphBuilderHook=createRepoGraphBuilderHookForInit,previousSchedulePostResolutionTasks=schedulePostResolutionTasksForInit,previousLoadPluginConfigWithMetaAsync=loadPluginConfigWithMetaAsyncForInit,previousLoadSnapshot=loadSnapshotForInit,previousEnsureSwarmGitExcluded=ensureSwarmGitExcludedForInit,previousResolveAutoReviewConfig=resolveAutoReviewConfigForInit,previousRegenerateMemoryReflection=regenerateMemoryReflectionForInit;if(overrides.createRepoGraphBuilderHook)createRepoGraphBuilderHookForInit=overrides.createRepoGraphBuilderHook;if(overrides.schedulePostResolutionTasks)schedulePostResolutionTasksForInit=overrides.schedulePostResolutionTasks;if(overrides.loadPluginConfigWithMetaAsync)loadPluginConfigWithMetaAsyncForInit=overrides.loadPluginConfigWithMetaAsync;if(overrides.loadSnapshot)loadSnapshotForInit=overrides.loadSnapshot;if(overrides.ensureSwarmGitExcluded)ensureSwarmGitExcludedForInit=overrides.ensureSwarmGitExcluded;if(overrides.resolveAutoReviewConfig)resolveAutoReviewConfigForInit=overrides.resolveAutoReviewConfig;if(overrides.regenerateMemoryReflection)regenerateMemoryReflectionForInit=overrides.regenerateMemoryReflection;return()=>{createRepoGraphBuilderHookForInit=previousCreateRepoGraphBuilderHook,schedulePostResolutionTasksForInit=previousSchedulePostResolutionTasks,loadPluginConfigWithMetaAsyncForInit=previousLoadPluginConfigWithMetaAsync,loadSnapshotForInit=previousLoadSnapshot,ensureSwarmGitExcludedForInit=previousEnsureSwarmGitExcluded,resolveAutoReviewConfigForInit=previousResolveAutoReviewConfig,regenerateMemoryReflectionForInit=previousRegenerateMemoryReflection}}function schedulePostResolutionTasksForTest(tasks){schedulePostResolutionTasks(tasks)}function computeEffectiveTruncatableTools(defaultTools,configuredTools){let effective=configuredTools&&configuredTools.length>0?new Set(configuredTools):new Set(defaultTools);for(let exempt of SUMMARIZER_EXEMPT_TOOL_NAMES)effective.delete(exempt);return effective}var OpenCodeSwarm=async(ctx)=>{let postResolutionTasks=[];try{let hooks=await initializeOpenCodeSwarm(ctx,postResolutionTasks);return schedulePostResolutionTasksForInit(postResolutionTasks),hooks}catch(err2){let stack=err2 instanceof Error?err2.stack??err2.message:String(err2);throw console.error("[opencode-swarm] FATAL: plugin initialization failed. Plugin will not be available."),console.error(stack),err2}},MAX_TRACKED_ASSISTANT_USAGE_EVENTS=200,latestAssistantUsageBySession=new Map;function rememberAssistantUsageEvent(input){let event=isPlainRecord3(input)?input.event:void 0;if(!isPlainRecord3(event))return;if(event.type==="message.updated"){let properties=isPlainRecord3(event.properties)?event.properties:void 0,info=isPlainRecord3(properties?.info)?properties.info:void 0;if(info?.role==="assistant")rememberAssistantUsage(info.sessionID,info);return}if(event.type==="message.part.updated"){let properties=isPlainRecord3(event.properties)?event.properties:void 0,part=isPlainRecord3(properties?.part)?properties.part:void 0;if(part?.type==="step-finish")rememberAssistantUsage(part.sessionID,part)}}function rememberAssistantUsage(sessionID,raw){if(typeof sessionID!=="string"||sessionID.trim()==="")return;latestAssistantUsageBySession.set(sessionID,raw);while(latestAssistantUsageBySession.size>MAX_TRACKED_ASSISTANT_USAGE_EVENTS){let oldest=latestAssistantUsageBySession.keys().next().value;if(oldest===void 0)break;latestAssistantUsageBySession.delete(oldest)}}function consumeAssistantUsageForTask(parentSessionID,taskOutput){let sessionIDs=[parentSessionID,...collectSessionIDs(taskOutput)];for(let sessionID of sessionIDs){let usage=latestAssistantUsageBySession.get(sessionID);if(usage!==void 0)return latestAssistantUsageBySession.delete(sessionID),usage}return}function collectSessionIDs(raw){let found=[],seen=new Set,visit=(value,depth)=>{if(depth>3||!isPlainRecord3(value)||seen.has(value))return;seen.add(value);for(let key of["sessionID","sessionId","session_id"]){let candidate2=value[key];if(typeof candidate2==="string"&&candidate2.trim()!=="")found.push(candidate2)}for(let key of["metadata","data","info","message","response","output"])visit(value[key],depth+1)};return visit(raw,0),[...new Set(found)]}function isPlainRecord3(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}async function initializeOpenCodeSwarm(ctx,postResolutionTasks){console.warn(`[opencode-swarm] running v${package_default.version}`),clearDeferredWarnings();let __initIoStart=performance2.now(),configLoadP=withTimeout(loadPluginConfigWithMetaAsyncForInit(ctx.directory),LOAD_PLUGIN_CONFIG_TIMEOUT_MS,Error(`loadPluginConfigWithMetaAsync exceeded ${LOAD_PLUGIN_CONFIG_TIMEOUT_MS}ms budget; continuing with safe-default config`)).catch((err2)=>{let msg=err2 instanceof Error?err2.message:String(err2);return log("loadPluginConfig timed out or failed (non-fatal)",{error:msg}),advisoryWarn(`[opencode-swarm] Config load exceeded ${LOAD_PLUGIN_CONFIG_TIMEOUT_MS}ms budget; running with default configuration for this session.`),getSafeDefaultConfigLoadResult()}),snapshotP=withTimeout(loadSnapshotForInit(ctx.directory),5000,Error("loadSnapshot exceeded 5s budget; continuing without snapshot rehydration")).catch((err2)=>{let msg=err2 instanceof Error?err2.message:String(err2);log("loadSnapshot timed out or failed (non-fatal)",{error:msg})}),gitExcludeP=withTimeout(ensureSwarmGitExcludedForInit(ctx.directory),ENSURE_SWARM_GIT_EXCLUDED_OUTER_TIMEOUT_MS,Error(`ensureSwarmGitExcluded exceeded ${ENSURE_SWARM_GIT_EXCLUDED_OUTER_TIMEOUT_MS}ms budget; continuing without git-hygiene check`)).catch((err2)=>{let msg=err2 instanceof Error?err2.message:String(err2);log("ensureSwarmGitExcluded timed out or failed (non-fatal)",{error:msg})});await Promise.all([configLoadP,snapshotP,gitExcludeP]);let{config:config3,loadedFromFile}=await configLoadP;if(log(`init-path I/O completed in ${(performance2.now()-__initIoStart).toFixed(1)}ms (parallel: config+snapshot+git-exclude)`),setGitBinaryOverride(config3.git?.binary),config3.full_auto?.enabled===!0){let criticModel=config3.full_auto.critic_model??config3.agents?.critic?.model??DEFAULT_MODELS.critic,architectModel=config3.agents?.architect?.model??DEFAULT_MODELS.default;if(criticModel===architectModel)if(!config3.quiet)console.warn("[opencode-swarm] Full-auto mode warning: critic model matches architect model. Model validation is advisory-only; full-auto remains enabled. (Runtime architect model is determined by the orchestrator)");else addDeferredWarning("[opencode-swarm] Full-auto mode warning: critic model matches architect model. Model validation is advisory-only; full-auto remains enabled. (Runtime architect model is determined by the orchestrator)")}{let noFallback=[],hasNoFallback=(cfg)=>cfg.model&&(!cfg.fallback_models||cfg.fallback_models.length===0);if(config3.agents){for(let[name,cfg]of Object.entries(config3.agents))if(hasNoFallback(cfg))noFallback.push(`${name}(${cfg.model})`)}if(config3.swarms){for(let[swarmId,swarm]of Object.entries(config3.swarms))if(swarm.agents){for(let[name,cfg]of Object.entries(swarm.agents))if(hasNoFallback(cfg))noFallback.push(`${swarmId}/${name}(${cfg.model})`)}}if(noFallback.length>0){let msg=`[opencode-swarm] WARNING: ${noFallback.length} agent(s) use a custom model without fallback_models: `+noFallback.join(", ")+'. Add "fallback_models": ["model-a"] to each agent config for reliability.';if(!config3.quiet)console.warn(msg);else addDeferredWarning(msg)}}swarmState.fullAutoEnabledInConfig=config3.full_auto?.enabled===!0,swarmState.opencodeClient=ctx.client,initObservability({directory:ctx.directory,provenance:{pluginVersion:package_default.version,runtime:process.versions.bun===void 0?"node":"bun",runtimeVersion:process.versions.bun??process.versions.node,os:process.platform,arch:process.arch}}),initTelemetry(ctx.directory),startHeartbeatTracking();let repoGraphConfig=RepoGraphConfigSchema.parse(config3.repo_graph??{}),repoGraphHookFactory=createRepoGraphBuilderHookForInit,repoGraphHook=repoGraphConfig.enabled?repoGraphHookFactory(ctx.directory,void 0,{enabled:!0,initRefresh:repoGraphConfig.init_refresh,refreshCap:repoGraphConfig.refresh_cap,walkBudgetMs:repoGraphConfig.walk_budget_ms,maxFiles:repoGraphConfig.max_files,excludeDirs:repoGraphConfig.exclude_dirs}):null,repoGraphInitPromise;if(repoGraphHook)postResolutionTasks.push(()=>{let watchdog=setTimeout(()=>{log("[repo-graph] init exceeded 30s budget; scan will continue but is overdue")},30000);if(typeof watchdog.unref==="function")watchdog.unref();repoGraphInitPromise=repoGraphHook.init().catch(()=>{}).finally(()=>clearTimeout(watchdog))});if(postResolutionTasks.push(()=>{runModelPreflight(config3,swarmState.opencodeClient).then((result)=>{if(!result.catalogAvailable)return;let unresolved=result.resolutions.filter((resolution)=>resolution.status==="unresolved");if(unresolved.length===0)return;let lines=unresolved.map((resolution)=>` ${resolution.agent}: ${resolution.model} (${resolution.detail??"does not resolve"})`),msg=`[opencode-swarm] WARNING: ${unresolved.length} configured agent model(s) do not resolve against the provider catalog:
6962
6963
  ${lines.join(`
6963
6964
  `)}
6964
- Dispatching these agents will fail permanently ("Model not found"/"Forbidden"). Fix agents.<role>.model in opencode-swarm.json (or remove the override to fall back to the default).`;if(!config3.quiet)console.warn(msg);else addDeferredWarning(msg);for(let resolution of unresolved)telemetry.modelUnresolved(resolution.agent,resolution.model,resolution.detail??"does not resolve")}).catch(()=>{})}),postResolutionTasks.push(()=>{runInitOrphanRecovery(ctx.directory).catch((err2)=>{let msg=err2 instanceof Error?err2.message:String(err2);log("initOrphanRecovery failed (non-fatal)",{error:msg})})}),writeSwarmConfigExampleIfNew(ctx.directory),writeProjectConfigIfNew(ctx.directory,config3.quiet),postResolutionTasks.push(()=>{withTimeout(syncBundledProjectSkillsIfMissingAsync(ctx.directory,PACKAGE_ROOT2,config3.quiet),SYNC_BUNDLED_SKILLS_TIMEOUT_MS,Error(`syncBundledProjectSkillsIfMissingAsync exceeded ${SYNC_BUNDLED_SKILLS_TIMEOUT_MS}ms budget; continuing without skill materialization (command-path sync remains a backstop)`)).catch((err2)=>{let msg=err2 instanceof Error?err2.message:String(err2);log("bundled skill materialization timed out or failed (non-fatal)",{error:msg})})}),config3.version_check!==!1)postResolutionTasks.push(()=>{scheduleVersionCheck(package_default.version,(msg)=>{if(config3.quiet)addDeferredWarning(msg);else console.warn(msg)})});let projectContext=await withTimeout((async()=>{return(await Promise.resolve().then(() => (init_project_context(),exports_project_context))).buildProjectContext(ctx.directory)})(),300,Error("language-backend detection exceeded 300ms; continuing with unresolved sentinels")).catch((err2)=>{let msg=err2 instanceof Error?err2.message:String(err2);return log("language-backend detection timed out or failed (non-fatal)",{error:msg}),null}),autoReviewConfig;try{autoReviewConfig=resolveAutoReviewConfigForInit(config3.auto_review??{})}catch(error93){addDeferredWarning(`[swarm] Invalid auto_review configuration; auto-review is disabled until corrected: ${error93 instanceof Error?error93.message:String(error93)}`),autoReviewConfig=resolveAutoReviewConfigForInit({enabled:!1})}let configWithResolvedAutoReview={...config3,auto_review:autoReviewConfig},agents=getAgentConfigs(configWithResolvedAutoReview,ctx.directory,void 0,projectContext??void 0),largestArchitectChars=Object.entries(agents).reduce((max,[name,cfg])=>{if(!name.endsWith("_architect")&&name!=="architect")return max;let len=cfg.prompt?.length??0;return len>max?len:max},0);log("architect prompt size",{chars:largestArchitectChars});let agentDefinitions=createAgents(configWithResolvedAutoReview,projectContext??void 0),agentDefinitionMap=Object.fromEntries(agentDefinitions.map((agent)=>[agent.name,agent])),instanceGeneratedAgentNames=Object.freeze(Object.keys(agents));swarmState.curatorInitAgentNames=Object.keys(agents).filter((k)=>k==="curator_init"||k.endsWith("_curator_init")),swarmState.curatorPhaseAgentNames=Object.keys(agents).filter((k)=>k==="curator_phase"||k.endsWith("_curator_phase")),swarmState.curatorPostmortemAgentNames=Object.keys(agents).filter((k)=>k==="curator_postmortem"||k.endsWith("_curator_postmortem")),swarmState.curatorConsolidationAgentNames=Object.keys(agents).filter((k)=>k==="curator_consolidation"||k.endsWith("_curator_consolidation")),swarmState.skillImproverAgentNames=Object.keys(agents).filter((k)=>k==="skill_improver"||k.endsWith("_skill_improver")),swarmState.specWriterAgentNames=Object.keys(agents).filter((k)=>k==="spec_writer"||k.endsWith("_spec_writer")),swarmState.generatedAgentNames=[...instanceGeneratedAgentNames];let pipelineHook=createPipelineTrackerHook(config3,ctx.directory),systemEnhancerHook=createSystemEnhancerHook(config3,ctx.directory),contextCapsuleInjectHook=createContextCapsuleInjectHook(config3,ctx.directory),compactionHook=createCompactionCustomizerHook(config3,ctx.directory),resolveIncomingAgentModel=(agentName)=>resolveRuntimeAgentModel(config3,agents,agentName),resolveTaskRouteModelChain=(exactAgentName)=>{if(!exactAgentName)return null;let trimmedAgentName=exactAgentName.trim();if(!trimmedAgentName)return null;let role=stripKnownSwarmPrefix(trimmedAgentName),swarmAgents=getSwarmAgents(extractSwarmIdFromAgentName(trimmedAgentName));return{exactAgentName:trimmedAgentName,role,primaryModel:resolveRuntimeAgentModel(config3,agents,trimmedAgentName)??resolveRegisteredAgentModel(config3,trimmedAgentName),fallbackModels:swarmAgents?.[role]?.fallback_models??[]}},extractBoundedErrorSignal=(value,depth=0)=>{if(depth>4)return[];if(typeof value==="string"){let trimmed=value.trim();return trimmed?[trimmed.slice(0,512)]:[]}if(typeof value==="number"||typeof value==="boolean")return[String(value)];if(!value||typeof value!=="object")return[];if(value instanceof Error)return[...extractBoundedErrorSignal(value.name,depth+1),...extractBoundedErrorSignal(value.message,depth+1)];let record3=value,parts=[];for(let key of["message","reason","code","status","statusCode","error","cause","detail","details"])parts.push(...extractBoundedErrorSignal(record3[key],depth+1));return parts},extractSessionErrorSignal=(properties)=>{if(!properties)return"";return extractBoundedErrorSignal(properties).filter(Boolean).join(" ").slice(0,2048)},resolveTaskRouteForChildSession=(childSessionID)=>{let trimmedChildSessionID=childSessionID.trim();if(!trimmedChildSessionID)return;return getPendingTaskModelRouteSnapshot().find((route)=>route.childSessionID===trimmedChildSessionID)},lookupParentSessionIDForTaskRoute=async(childSessionID)=>{let sessionApi=ctx.client?.session;if(!sessionApi?.get)return;try{let result=await sessionApi.get({path:{id:childSessionID},query:{directory:ctx.directory}});return typeof result?.data?.parentID==="string"&&result.data.parentID.trim()!==""?result.data.parentID.trim():void 0}catch{return}};registerFullAutoRecoveryBlockerEvaluator(({sessionID})=>{let invocationID=getAgentSession(sessionID)?.activeInvocationId??0;if(invocationID<=0)return[];return[...new Set(listBlockingActionCircuitsForInvocation(sessionID,invocationID).map((entry)=>entry.circuitKind))]});let contextBudgetHandler=createContextBudgetHandler(config3,resolveIncomingAgentModel),evaluationModelDispatcher=createEvaluationModelDispatcher(ctx.client),reviewModelDispatcher=createReviewModelDispatcher(ctx.client),findingValidationScheduler=createFindingValidationScheduler(),reviewAgentModelRegistry=captureReviewAgentModelRegistry(config3,instanceGeneratedAgentNames),getActiveReviewAgentName=(sessionID)=>swarmState.activeAgent.get(sessionID)??swarmState.agentSessions.get(sessionID)?.agentName,roleFilterSystemHook=createRoleFilterSystemHook(getActiveReviewAgentName),commandHandler=createSwarmCommandHandler(ctx.directory,agentDefinitionMap,{getActiveAgentName:getActiveReviewAgentName,packageRoot:PACKAGE_ROOT2,registeredAgents:agents,evaluationModelDispatcher,reviewModelDispatcher,autoReviewConfig,reviewAgentModelRegistry}),swarmCommandSystemRuleHook=createSwarmCommandSystemRuleHook(agentDefinitionMap,agents),activityHooks=createAgentActivityHooks(config3,ctx.directory),learningConfig=LearningConfigSchema.parse(config3.learning??{}),prmHook=createPrmHook(config3.prm??PrmConfigSchema.parse({}),ctx.directory,resolvePrmPatternPersistenceOptions(learningConfig)),trajectoryLoggerHook=createTrajectoryLoggerHook({enabled:!0,max_lines:1000},ctx.directory),delegationGateHooks=createDelegationGateHook(configWithResolvedAutoReview,ctx.directory),advisoryInjector=(sessionId,message)=>{let session=swarmState.agentSessions.get(sessionId);if(session)pushAdvisory(session,message)},backgroundCompletionObserver=createBackgroundCompletionObserver({config:{enabled:config3.hooks?.background_subagents===!0},directory:ctx.directory,reviewerReceiptOptions:{dispatcher:reviewModelDispatcher,config:autoReviewConfig,generatedAgentNames:instanceGeneratedAgentNames,agentModelRegistry:reviewAgentModelRegistry,injectAdvisory:advisoryInjector,validationScheduler:findingValidationScheduler}}),delegationSanitizerHook=createDelegationSanitizerHook(ctx.directory),memoryLifecycleHooks=createMemoryLifecycleHooks({directory:ctx.directory,config:config3.memory,getActiveAgentName:(sessionID)=>sessionID?swarmState.activeAgent.get(sessionID):void 0,getActiveTaskId:(sessionID)=>sessionID?swarmState.agentSessions.get(sessionID)?.currentTaskId??void 0:void 0});if(config3.memory?.enabled===!0&&config3.memory.reflection?.enabled===!0){let reflectionConfig=config3.memory,regenerateMemoryReflectionTask=()=>withTimeout(repoGraphInitPromise??Promise.resolve(),5000,Error("repo graph refresh exceeded reflection wait budget")).catch(()=>{return}).then(()=>withTimeout(regenerateMemoryReflectionForInit(ctx.directory,reflectionConfig),15000,Error("memory reflection startup regeneration exceeded 15s"))).catch((err2)=>{log("memory reflection startup regeneration failed (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})}).then(()=>{return});postResolutionTasks.push(regenerateMemoryReflectionTask)}let guardrailsFallback=config3.guardrails?.enabled===!1?{...config3.guardrails,enabled:!1}:config3.guardrails??{},guardrailsConfig=GuardrailsConfigSchema.parse(guardrailsFallback);if(loadedFromFile&&guardrailsConfig.enabled===!1)warn(""),warn("══════════════════════════════════════════════════════════════"),warn("[opencode-swarm] \uD83D\uDD34 SECURITY WARNING: GUARDRAILS ARE DISABLED"),warn("══════════════════════════════════════════════════════════════"),warn("Guardrails have been explicitly disabled in user configuration."),warn("This disables safety measures including:"),warn(" - Tool call limits"),warn(" - Duration limits"),warn(" - Repetition detection"),warn(" - Error rate limits"),warn(" - Idle timeouts"),warn(""),warn("Only disable guardrails if you fully understand the security implications."),warn('To re-enable guardrails, set "guardrails.enabled" to true in your config.'),warn("══════════════════════════════════════════════════════════════"),warn("");let delegationHandler=createDelegationTrackerHook(config3,guardrailsConfig.enabled),authorityConfig=AuthorityConfigSchema.parse(config3.authority??{}),worktreeDirOverride=resolveWorktreeIsolationConfig(config3).worktree_dir,worktreeBaseDirOverrides=worktreeDirOverride?[worktreeDirOverride]:[],guardrailsHooks=createGuardrailsHooks(ctx.directory,void 0,guardrailsConfig,authorityConfig,worktreeBaseDirOverrides,resolveIncomingAgentModel),durableBackgroundAdvisoryMessagesTransform=async(input,output)=>{let mctx=resolveMessageTransformContext(output);if(!mctx.sessionID){await guardrailsHooks.messagesTransform(input,output);return}let observedTexts=(output.messages??[]).flatMap((message)=>(message.parts??[]).filter((part)=>part.type==="text"&&typeof part.text==="string").map((part)=>part.text));await backgroundCompletionObserver.ackObservedAdvisories(mctx.sessionID,observedTexts);let prepared=await backgroundCompletionObserver.prepareAdvisories(mctx.sessionID);if(!prepared){await guardrailsHooks.messagesTransform(input,output);return}let session=swarmState.agentSessions.get(mctx.sessionID),pendingBefore=session?[...session.pendingAdvisoryMessages??[]]:void 0,guardrailsSnapshot=session?{resumeModelAdvisoryDone:session.resumeModelAdvisoryDone,configModelAdvisoryDone:session.configModelAdvisoryDone,lastObservedModel:session.lastObservedModel,lastObservedProviderID:session.lastObservedProviderID,lastProviderRecoveryFingerprint:session.lastProviderRecoveryFingerprint,loopWarningPending:session.loopWarningPending}:void 0,messagesBefore=output.messages?structuredClone(output.messages):void 0;try{if(session)for(let message of prepared.messages)pushAdvisory(session,message);if(await guardrailsHooks.messagesTransform(input,output),!prepared.messages.every((message)=>(output.messages??[]).some((candidate2)=>(candidate2.parts??[]).some((part)=>part.type==="text"&&typeof part.text==="string"&&part.text.includes(message)))))throw Error("durable background advisory insertion failed")}catch(error93){if(session&&pendingBefore)session.pendingAdvisoryMessages=pendingBefore;if(session&&guardrailsSnapshot)session.resumeModelAdvisoryDone=guardrailsSnapshot.resumeModelAdvisoryDone,session.configModelAdvisoryDone=guardrailsSnapshot.configModelAdvisoryDone,session.lastObservedModel=guardrailsSnapshot.lastObservedModel,session.lastObservedProviderID=guardrailsSnapshot.lastObservedProviderID,session.lastProviderRecoveryFingerprint=guardrailsSnapshot.lastProviderRecoveryFingerprint,session.loopWarningPending=guardrailsSnapshot.loopWarningPending;if(Array.isArray(output.messages)&&messagesBefore){output.messages.length=0;for(let message of messagesBefore)output.messages.push(message)}else output.messages=messagesBefore;await backgroundCompletionObserver.releaseAdvisories(mctx.sessionID,prepared),warn(`[background] advisory injection rolled back for ${mctx.sessionID}: ${error93 instanceof Error?error93.message:String(error93)}`)}},fullAutoInterceptHook=createFullAutoInterceptHook(config3,ctx.directory),fullAutoPermissionHook=createFullAutoPermissionHook({config:config3,directory:ctx.directory}),fullAutoInputProbeHook=createFullAutoInputProbeHook({config:config3,directory:ctx.directory}),fullAutoDelegationHook=createFullAutoDelegationHook({config:config3,directory:ctx.directory}),ccCommandInterceptHook=createCcCommandInterceptHook({}),issueTraceHook=createIssueTraceHook(config3,ctx.directory),watchdogConfig=WatchdogConfigSchema.parse(config3.watchdog??{}),scopeGuardHook=createScopeGuardHook({enabled:watchdogConfig.scope_guard,skip_in_turbo:watchdogConfig.skip_in_turbo},ctx.directory,advisoryInjector),prWorkflowResponseGate=createPrWorkflowResponseGate({directory:ctx.directory,client:ctx.client}),prWorkflowSessionResolver=createPrWorkflowSessionResolver({directory:ctx.directory,client:ctx.client}),delegationLedgerHook=createDelegationLedgerHook({enabled:watchdogConfig.delegation_ledger},ctx.directory,advisoryInjector),initOrphanRecoveryAdvisoryHook=createInitOrphanRecoveryAdvisoryHook(ctx.directory),selfReviewConfig=SelfReviewConfigSchema.parse(config3.self_review??{}),selfReviewHook=createSelfReviewHook({enabled:selfReviewConfig.enabled,skip_in_turbo:selfReviewConfig.skip_in_turbo},advisoryInjector),autoReviewHook=createAutoReviewHook({config:autoReviewConfig,directory:ctx.directory,dispatcher:reviewModelDispatcher,generatedAgentNames:instanceGeneratedAgentNames,agentModelRegistry:reviewAgentModelRegistry,getActiveAgentName:getActiveReviewAgentName,injectAdvisory:advisoryInjector}),summaryConfig=SummaryConfigSchema.parse(config3.summaries??{}),toolSummarizerHook=createToolSummarizerHook(summaryConfig,ctx.directory),knowledgeConfigBase=config3.knowledge??{},knowledgeConfig=KnowledgeConfigSchema.parse(knowledgeConfigBase),skillImproverConfig=SkillImproverConfigSchema.parse(config3.skill_improver??{}),skillPropagationConfig=SkillPropagationConfigSchema.parse(config3.skillPropagation??{});if(skillImproverConfig.enabled&&skillImproverConfig.trigger==="scheduled")postResolutionTasks.push(()=>{return Promise.resolve().then(() => (init_skill_consolidation(),exports_skill_consolidation)).then(({runSkillConsolidationFireAndForget:runSkillConsolidationFireAndForget2})=>{runSkillConsolidationFireAndForget2({directory:ctx.directory,config:skillImproverConfig,source:"startup",enrichmentQuota:{maxCalls:knowledgeConfig.enrichment.max_calls_per_day,window:knowledgeConfig.enrichment.quota_window},evaluateDrafts:!0},void 0,(err2)=>{let msg=err2 instanceof Error?err2.message:String(err2);log("scheduled skill consolidation failed (non-fatal)",{error:msg})})}).catch((err2)=>{let msg=err2 instanceof Error?err2.message:String(err2);log("failed to schedule skill consolidation (non-fatal)",{error:msg})})});let knowledgeCuratorHook=knowledgeConfig.enabled?createKnowledgeCuratorHook(ctx.directory,knowledgeConfig,{llmDelegateFactory:(sessionID)=>createCuratorLLMDelegate(ctx.directory,"phase",sessionID),enrichmentQuota:{maxCalls:knowledgeConfig.enrichment.max_calls_per_day,window:knowledgeConfig.enrichment.quota_window}}):void 0,hivePromoterHook=knowledgeConfig.enabled&&knowledgeConfig.hive_enabled?createHivePromoterHook(ctx.directory,knowledgeConfig):void 0,knowledgeInjectorHook=knowledgeConfig.enabled?createKnowledgeInjectorHook(ctx.directory,knowledgeConfig,config3.context_budget?.model_limits??{},config3.context_budget?.unified_injection_tokens):void 0,steeringConsumedHook=createSteeringConsumedHook(ctx.directory),coChangeSuggesterHook=createCoChangeSuggesterHook(ctx.directory),darkMatterDetectorHook=createDarkMatterDetectorHook(ctx.directory),slopDetectorHook=config3.slop_detector?.enabled!==!1?createSlopDetectorHook(config3.slop_detector??{enabled:!0,classThreshold:3,commentStripThreshold:5,diffLineThreshold:200,importHygieneThreshold:2},ctx.directory,(sessionId,message)=>{let s=swarmState.agentSessions.get(sessionId);if(s)pushAdvisory(s,message)}):null,incrementalVerifyHook=config3.incremental_verify?.enabled!==!1?createIncrementalVerifyHook(config3.incremental_verify??{enabled:!0,command:null,timeoutMs:30000,triggerAgents:["coder"]},ctx.directory,(sessionId,message)=>{let s=swarmState.agentSessions.get(sessionId);if(s)pushAdvisory(s,message)}):null,compactionServiceHook=config3.compaction_service?.enabled!==!1?createCompactionService(config3.compaction_service??{enabled:!0,observationThreshold:40,reflectionThreshold:60,emergencyThreshold:80,preserveLastNTurns:5},ctx.directory,(sessionId,message)=>{let s=swarmState.agentSessions.get(sessionId);if(s)pushAdvisory(s,message)}):null,snapshotWriterHook=createSnapshotWriterHook(ctx.directory),automationConfig=AutomationConfigSchema.parse(config3.automation??{}),automationManager,preflightTriggerManager,statusArtifact,prMonitorWorker=null,planSyncWorker=null;if(automationConfig.mode!=="manual"){automationManager=createAutomationManager(automationConfig),automationManager.start();let{PreflightTriggerManager:PTM}=await Promise.resolve().then(() => (init_trigger(),exports_trigger));preflightTriggerManager=new PTM(automationConfig);let{AutomationStatusArtifact:ASA}=await Promise.resolve().then(() => (init_status_artifact(),exports_status_artifact)),swarmDir=path329.resolve(ctx.directory,".swarm");if(statusArtifact=new ASA(swarmDir),statusArtifact.updateConfig(automationConfig.mode,automationConfig.capabilities),automationConfig.capabilities?.evidence_auto_summaries===!0){let{createEvidenceSummaryIntegration:createEvidenceSummaryIntegration2}=await Promise.resolve().then(() => (init_evidence_summary_integration(),exports_evidence_summary_integration));createEvidenceSummaryIntegration2({automationConfig,directory:ctx.directory,projectDir:ctx.directory,summaryFilename:"evidence-summary.json"}),log("Evidence summary integration initialized",{directory:ctx.directory})}if(automationConfig.capabilities?.phase_preflight===!0){let{createPreflightIntegration:createPreflightIntegration2}=await Promise.resolve().then(() => (init_preflight_integration(),exports_preflight_integration));try{let{manager}=createPreflightIntegration2({automationConfig,directory:ctx.directory,swarmDir});preflightTriggerManager=manager,log("Preflight integration initialized",{directory:ctx.directory})}catch(err2){log("Preflight integration failed to initialize (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})}}if(automationConfig.capabilities?.plan_sync===!0)try{planSyncWorker=new PlanSyncWorker({directory:ctx.directory}),planSyncWorker.start(),log("PlanSyncWorker initialized",{directory:ctx.directory})}catch(err2){log("PlanSyncWorker failed to initialize (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})}log("Automation framework initialized",{mode:automationConfig.mode,enabled:automationManager?.isEnabled(),running:automationManager?.isActive(),preflightEnabled:preflightTriggerManager?.isEnabled()})}let prMonitorConfig=PrMonitorConfigSchema.parse(config3.pr_monitor??{});function ensurePrMonitorWorkerRunning(directory){try{if(!prMonitorConfig.enabled)return;if(!prMonitorWorker)prMonitorWorker=new PrMonitorWorker({directory,config:prMonitorConfig});if(!prMonitorWorker.isRunning())prMonitorWorker.start(),log("PR Monitor Worker started",{directory})}catch(err2){error48("[pr-monitor] Worker failed to start (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})}}setOnSubscriptionCreated((directory,_record3)=>{ensurePrMonitorWorkerRunning(directory)});let prEventCleanup=null,prEventDelivery=null;if(prMonitorConfig.enabled){try{let{registerPrEventSubscribers:registerPrEventSubscribers2}=await Promise.resolve().then(() => (init_pr_event_subscribers(),exports_pr_event_subscribers));prEventCleanup=registerPrEventSubscribers2({directory:ctx.directory,config:prMonitorConfig})}catch(err2){log("[pr-monitor] Failed to register PR event subscribers (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})}if(prMonitorConfig.event_delivery==="prompt")try{let deliveryModule=await Promise.resolve().then(() => (init_pr_event_delivery(),exports_pr_event_delivery));deliveryModule.registerPrEventDelivery({client:ctx.client,directory:ctx.directory,config:prMonitorConfig}),prEventDelivery={noteSessionIdle:deliveryModule.noteSessionIdle,unregisterPrEventDelivery:deliveryModule.unregisterPrEventDelivery}}catch(err2){log("[pr-monitor] Failed to register wake delivery (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})}}let prAutoSubscribeHook=createPrAutoSubscribeHook(ctx.directory,prMonitorConfig);if(prMonitorConfig.enabled)postResolutionTasks.push(()=>{listActive(ctx.directory).then((active)=>{if(active.length>0)ensurePrMonitorWorkerRunning(ctx.directory)}).catch((err2)=>{error48("[pr-monitor] Startup scan failed (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})})});let cleanupAutomation=()=>{automationManager?.stop(),prMonitorWorker?.stop(),planSyncWorker?.stop(),prEventCleanup?.(),prEventDelivery?.unregisterPrEventDelivery()};if(process.on("exit",cleanupAutomation),shouldRunOnStartup(automationConfig)){let enableAutofix=automationConfig.capabilities?.config_doctor_autofix===!0;postResolutionTasks.push(()=>{return Promise.resolve().then(() => (init_config_doctor(),exports_config_doctor)).then(({runConfigDoctorWithFixes:runConfigDoctorWithFixes2})=>{return runConfigDoctorWithFixes2(ctx.directory,config3,enableAutofix).then((doctorResult)=>{if(doctorResult.result.findings.length>0){log("Config Doctor ran on startup",{findings:doctorResult.result.findings.length,errors:doctorResult.result.summary.error,warnings:doctorResult.result.summary.warn,appliedFixes:doctorResult.appliedFixes.length,autofixEnabled:enableAutofix});try{let autoFixableCount=doctorResult.result.findings.filter((f)=>f.autoFixable).length,appliedCount=doctorResult.appliedFixes.length;if(!enableAutofix&&autoFixableCount>0){let msg=`[opencode-swarm] Config Doctor found ${autoFixableCount} auto-fixable issue(s). Run /swarm config doctor --fix to apply.`;if(!config3.quiet)console.warn(msg);else addDeferredWarning(msg)}else if(enableAutofix){let parts=[];if(appliedCount>0)parts.push(`applied ${appliedCount} fix(es) automatically`);let unapplied=Math.max(0,autoFixableCount-appliedCount);if(unapplied>0)parts.push(`${unapplied} auto-fixable issue(s) need explicit review — run /swarm config doctor --fix`);if(parts.length>0){let msg=`[opencode-swarm] Config Doctor: ${parts.join("; ")}.`;if(!config3.quiet)console.warn(msg);else addDeferredWarning(msg)}}}catch{}}}).catch((err2)=>{log("Config Doctor error (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})})})})}return log("Plugin initialized",{maxIterations:config3.max_iterations,agentCount:Object.keys(agents).length,hooks:{pipeline:!!pipelineHook["experimental.chat.messages.transform"],systemEnhancer:!!systemEnhancerHook["experimental.chat.system.transform"],compaction:!!compactionHook["experimental.session.compacting"],contextBudget:!!contextBudgetHandler,commands:!0,agentActivity:config3.hooks?.agent_activity!==!1,delegationTracker:config3.hooks?.delegation_tracker===!0,guardrails:guardrailsConfig.enabled,toolSummarizer:summaryConfig.enabled,knowledge:knowledgeConfig.enabled},automation:{mode:automationConfig.mode,capabilities:automationConfig.capabilities}}),{name:"opencode-swarm",agent:agents,tool:buildPluginToolObject(agentDefinitionMap,config3,evaluationModelDispatcher,reviewModelDispatcher,instanceGeneratedAgentNames,reviewAgentModelRegistry,getActiveReviewAgentName),event:async(input)=>{try{rememberAssistantUsageEvent(input);let lifecycleEvent=input.event;if(lifecycleEvent?.type==="message.part.updated"){let part=lifecycleEvent.properties?.part,metadata=part?.state?.metadata,partTool=typeof part?.tool==="string"?normalizeToolName(part.tool)?.toLowerCase():void 0,eventParentSessionID=typeof part?.sessionID==="string"&&part.sessionID.trim()!==""?part.sessionID:void 0,eventChildSessionID=typeof metadata?.sessionId==="string"&&metadata.sessionId.trim()!==""?metadata.sessionId:void 0;if(part?.type==="tool"&&partTool==="task"&&typeof part.callID==="string"&&part.callID.trim()!==""&&eventParentSessionID!==void 0&&eventChildSessionID!==void 0&&eventParentSessionID!==eventChildSessionID){await delegationGateHooks.taskMetadata({callID:part.callID,parentSessionID:eventParentSessionID,childSessionID:eventChildSessionID}),bindPendingTaskModelRouteChild({parentSessionID:eventParentSessionID,callID:part.callID,childSessionID:eventChildSessionID});let fullAutoRunState=loadFullAutoRunState(ctx.directory,eventParentSessionID);if(fullAutoRunState?.runGeneration!==void 0)bindFullAutoSevereChildSession({childSessionID:eventChildSessionID,parentSessionID:eventParentSessionID,parentCallID:part.callID,generation:fullAutoRunState.runGeneration})}}if(lifecycleEvent?.type==="session.error"){let properties=lifecycleEvent.properties,childSessionID=typeof properties?.sessionID==="string"?properties.sessionID:typeof properties?.sessionId==="string"?properties.sessionId:typeof properties?.info==="object"&&properties.info&&typeof properties.info.id==="string"?properties.info.id??"":"",route=childSessionID?resolveTaskRouteForChildSession(childSessionID):void 0,routeModel=resolveTaskRouteModelChain(route?swarmState.activeAgent.get(childSessionID)??swarmState.agentSessions.get(childSessionID)?.agentName??route.role:swarmState.activeAgent.get(childSessionID)??swarmState.agentSessions.get(childSessionID)?.agentName),errorSignal=extractSessionErrorSignal(properties);if(route&&routeModel&&errorSignal&&isRetryableProviderFailure(classifyProviderFailure(errorSignal)))advancePendingTaskModelRoute({childSessionID,role:route.role,actionDigest:route.actionDigest,primaryModel:routeModel.primaryModel,fallbackModels:routeModel.fallbackModels})}let lifecycleStatus=lifecycleEvent?.properties?.status;if(lifecycleEvent?.type==="session.deleted"||lifecycleEvent?.type==="session.removed"||lifecycleEvent?.type==="session.idle"||lifecycleEvent?.type==="session.error"||lifecycleEvent?.type==="session.status"&&(lifecycleStatus==="idle"||typeof lifecycleStatus==="object"&&(lifecycleStatus.type==="idle"||lifecycleStatus.type==="error"))){let properties=lifecycleEvent.properties,sessionID=properties?.sessionID??properties?.sessionId??properties?.info?.sessionID??properties?.info?.id??properties?.id;if(sessionID){if(delegationGateHooks.sessionEnded(sessionID,lifecycleEvent.type==="session.deleted"||lifecycleEvent.type==="session.removed"),lifecycleEvent.type==="session.deleted"||lifecycleEvent.type==="session.removed")clearPendingTaskModelRoutesForSession(sessionID),clearSessionActionCircuits(sessionID),clearFullAutoSevereSession(sessionID)}}if(prWorkflowSessionResolver.observeEvent(input),await prWorkflowResponseGate.event(input),prEventDelivery){let evt=input.event,idleSessionID=evt?.properties?.sessionID??evt?.data?.sessionID;if(evt?.type==="session.idle"&&typeof idleSessionID==="string")prEventDelivery.noteSessionIdle(idleSessionID)}await backgroundCompletionObserver.event(input)}catch(err2){warn(`[swarm] event hook error: ${err2 instanceof Error?err2.message:String(err2)}`)}},config:async(opencodeConfig)=>{let isObjectRecord=(value)=>typeof value==="object"&&value!==null,pluginConfig=opencodeConfig;if(!isObjectRecord(pluginConfig.agent))pluginConfig.agent={};let agentConfig=pluginConfig.agent;Object.assign(agentConfig,agents);try{applyLanePermissions(opencodeConfig,ctx.directory,config3?.worktree?.lane_permissions??"scoped_allow")}catch(err2){addDeferredWarning(`[swarm] lane permission scoping failed: ${err2 instanceof Error?err2.message:String(err2)}`)}let autoSelect=config3?.auto_select_architect;if(autoSelect)if(Object.keys(agents).some((name)=>stripKnownSwarmPrefix(name)==="architect")){for(let builtin of["build","plan"]){let existing=agentConfig[builtin];if(isObjectRecord(existing)&&existing.disable===!0)continue;agentConfig[builtin]={...isObjectRecord(existing)?existing:{},disable:!0}}if(autoSelect===!0){let primaryArchitects=Object.entries(agents).filter(([name,cfg])=>stripKnownSwarmPrefix(name)==="architect"&&isObjectRecord(cfg)&&cfg.mode==="primary");if(primaryArchitects.length>1){let names=primaryArchitects.map(([n])=>n).join(", ");addDeferredWarning(`[swarm] auto_select_architect is true but ${primaryArchitects.length} architect agents are primary (${names}). Consider setting auto_select_architect to a specific agent name.`)}}if(typeof autoSelect==="string"&&autoSelect!==""){let targetName=autoSelect;if(Object.hasOwn(agents,targetName)&&stripKnownSwarmPrefix(targetName)==="architect"){for(let[name,cfg]of Object.entries(agents))if(stripKnownSwarmPrefix(name)==="architect"&&name!==targetName)agentConfig[name]={...isObjectRecord(cfg)?cfg:{},mode:"subagent"};let targetExisting=agentConfig[targetName],targetAgent=agents[targetName];agentConfig[targetName]={...isObjectRecord(targetExisting)?targetExisting:{},...isObjectRecord(targetAgent)?targetAgent:{},mode:"primary"}}else addDeferredWarning(`[swarm] auto_select_architect is set to "${targetName}" but that is not a known architect agent. No architect demotion applied.`)}}else addDeferredWarning("[swarm] auto_select_architect is enabled but no architect agents were found in the generated set. The option has no effect.");let shortcutDescription=(cmd)=>{let entry=COMMAND_REGISTRY[cmd];if(!entry?.description)return`Use /swarm ${cmd}`;let desc=entry.description.charAt(0).toLowerCase()+entry.description.slice(1);return`Use /swarm ${cmd} to ${desc}`};opencodeConfig.command={...opencodeConfig.command||{},swarm:{template:"/swarm $ARGUMENTS",description:(()=>{return`Swarm management commands: /swarm [${VALID_COMMANDS.filter((cmd)=>{let entry=COMMAND_REGISTRY[cmd];return!entry.aliasOf&&!entry.deprecated&&!entry.subcommandOf}).join("|")}]`})()},"swarm-status":{template:"/swarm status",description:"Use /swarm status to show current swarm status and active phase"},"swarm-show-plan":{template:"/swarm show-plan $ARGUMENTS",description:"Use /swarm show-plan to view or filter the current execution plan"},"swarm-plan":{template:"/swarm plan $ARGUMENTS",description:"Deprecated alias for /swarm show-plan"},"swarm-agents":{template:"/swarm agents",description:"Use /swarm agents to list registered swarm agents"},"swarm-history":{template:"/swarm history",description:"Use /swarm history to show completed phases summary"},"swarm-config":{template:"/swarm config $ARGUMENTS",description:"Use /swarm config to show or validate configuration"},"swarm-evidence":{template:"/swarm evidence $ARGUMENTS",description:"Use /swarm evidence to view evidence bundles and summaries"},"swarm-handoff":{template:"/swarm handoff",description:"Use /swarm handoff to prepare handoff brief for switching models mid-task"},"swarm-archive":{template:"/swarm archive",description:"Use /swarm archive to archive old evidence bundles"},"swarm-diagnose":{template:"/swarm diagnose",description:"Use /swarm diagnose to run health checks on swarm state"},"swarm-diagnosis":{template:"/swarm diagnosis",description:"Use /swarm diagnosis to run health checks on swarm state"},"swarm-preflight":{template:"/swarm preflight",description:"Use /swarm preflight to run preflight automation checks"},"swarm-sync-plan":{template:"/swarm sync-plan",description:"Use /swarm sync-plan to sync plan.json with plan.md"},"swarm-benchmark":{template:"/swarm benchmark",description:"Use /swarm benchmark to show performance metrics"},"swarm-gate-audit":{template:"/swarm gate-audit $ARGUMENTS",description:"Use /swarm gate-audit to run the bounded Tier-1 production gate matrix"},"swarm-gate-stats":{template:"/swarm gate-stats $ARGUMENTS",description:"Use /swarm gate-stats to summarize stored gate-audit evidence"},"swarm-skill-opt":{template:"/swarm skill-opt $ARGUMENTS",description:"Use /swarm skill-opt to govern skill optimization (plan|run|status|diff|approve|reject|rollback|history)"},"swarm-costs":{template:"/swarm costs $ARGUMENTS",description:"Use /swarm costs to show per-agent, task, gate, and retry token/cost totals"},"swarm-export":{template:"/swarm export",description:"Use /swarm export to export plan and context as JSON"},"swarm-reset":{template:"/swarm reset --confirm",description:"Use /swarm reset --confirm to clear swarm state (requires --confirm)"},"swarm-rollback":{template:"/swarm rollback $ARGUMENTS",description:"Use /swarm rollback to restore swarm state to a checkpoint"},"swarm-retrieve":{template:"/swarm retrieve $ARGUMENTS",description:"Use /swarm retrieve to retrieve full output from summary"},"swarm-clarify":{template:"/swarm clarify $ARGUMENTS",description:"Use /swarm clarify to clarify and refine a feature specification"},"swarm-analyze":{template:"/swarm analyze",description:"Use /swarm analyze to analyze spec vs plan for coverage gaps"},"swarm-specify":{template:"/swarm specify $ARGUMENTS",description:"Use /swarm specify to generate or import a feature specification"},"swarm-brainstorm":{template:"/swarm brainstorm $ARGUMENTS",description:"Use /swarm brainstorm to enter the architect MODE: BRAINSTORM planning workflow"},"swarm-loop":{template:"/swarm loop $ARGUMENTS",description:"Use /swarm loop <objective> to run a compound-engineering loop: brainstorm → plan → build → review → improve, iterating until done [--max-cycles 1..5] [--autonomy checkpoint|auto] [--depth standard|exhaustive] [--resume]"},"swarm-council":{template:"/swarm council $ARGUMENTS",description:"Use /swarm council <question> to convene a multi-model General Council deliberation (generalist / skeptic / domain expert) [--spec-review]"},"swarm-pr-review":{template:"/swarm pr-review $ARGUMENTS",description:"Use /swarm pr-review to launch deep PR review with multi-lane analysis"},"swarm-review":{template:"/swarm review $ARGUMENTS",description:"Use /swarm review to run the bounded whole-diff review engine for the selected local scope"},"swarm-pr-feedback":{template:"/swarm pr-feedback $ARGUMENTS",description:"Use /swarm pr-feedback to ingest and close known PR feedback (review comments, CI failures, conflicts) without a fresh broad review"},"swarm-abort-pr-workflow":{template:"/swarm abort-pr-workflow $ARGUMENTS",description:"Use /swarm abort-pr-workflow to clear a stuck PR_REVIEW/PR_FEEDBACK mechanical gate and stop the auto-resume loop (human-only escape hatch)"},"swarm-approve-plan-critic":{template:"/swarm approve-plan-critic $ARGUMENTS",description:"Use /swarm approve-plan-critic to record a MANUAL plan-critic approval that unblocks the ratchet-tighter critic_pre_plan execution gate when the critic already returned APPROVED but the snapshot was not recorded (human-only escape hatch)"},"swarm-ci-monitor":{template:"/swarm ci-monitor $ARGUMENTS",description:"Use /swarm ci-monitor to drive an already-reviewed, approved PR to green and merged (monitor CI, fix, merge)"},"swarm-pr-subscribe":{template:"/swarm pr subscribe $ARGUMENTS",description:shortcutDescription("pr subscribe")},"swarm-pr-unsubscribe":{template:"/swarm pr unsubscribe $ARGUMENTS",description:shortcutDescription("pr unsubscribe")},"swarm-pr-status":{template:"/swarm pr status",description:shortcutDescription("pr status")},"swarm-ci-simulate":{template:"/swarm ci-simulate $ARGUMENTS",description:shortcutDescription("ci-simulate")},"swarm-learning":{template:"/swarm learning",description:shortcutDescription("learning")},"swarm-post-mortem":{template:"/swarm post-mortem $ARGUMENTS",description:shortcutDescription("post-mortem")},"swarm-deep-dive":{template:"/swarm deep-dive $ARGUMENTS",description:"Use /swarm deep-dive to launch a read-only deep audit with parallel explorer waves, dual reviewers, and critic challenge"},"swarm-deep-research":{template:"/swarm deep-research $ARGUMENTS",description:"Use /swarm deep-research <question> to run a multi-source, fact-checked deep research pass and synthesize a cited report [--depth standard|exhaustive] [--max-researchers 1..6] [--rounds 1..4] [--brief]"},"swarm-codebase-review":{template:"/swarm codebase-review $ARGUMENTS",description:"Use /swarm codebase-review to launch codebase-review-swarm for a quote-grounded full-repo or large-subsystem audit"},"swarm-design-docs":{template:"/swarm design-docs $ARGUMENTS",description:"Use /swarm design-docs to generate or sync language-agnostic design docs for the project under build"},"swarm-sdd":{template:"/swarm sdd $ARGUMENTS",description:"Use /swarm sdd to inspect OpenSpec-compatible SDD artifacts"},"swarm-sdd-status":{template:"/swarm sdd status",description:"Use /swarm sdd status to show effective spec and OpenSpec artifact status"},"swarm-sdd-validate":{template:"/swarm sdd validate $ARGUMENTS",description:"Use /swarm sdd validate to validate OpenSpec-compatible SDD artifacts"},"swarm-sdd-project":{template:"/swarm sdd project $ARGUMENTS",description:"Use /swarm sdd project to materialize OpenSpec artifacts into .swarm/spec.md"},"swarm-issue":{template:"/swarm issue $ARGUMENTS",description:"Use /swarm issue to ingest a GitHub issue into the swarm workflow"},"swarm-qa-gates":{template:"/swarm qa-gates $ARGUMENTS",description:"Use /swarm qa-gates to view or modify QA gate profile for the current plan"},"swarm-dark-matter":{template:"/swarm dark-matter",description:"Use /swarm dark-matter to detect hidden file couplings"},"swarm-knowledge":{template:"/swarm knowledge $ARGUMENTS",description:"Use /swarm knowledge for knowledge management (quarantine/restore/migrate)"},"swarm-memory":{template:"/swarm memory $ARGUMENTS",description:"Use /swarm memory for memory status, JSONL export/import, and SQLite migration"},"swarm-memory-status":{template:"/swarm memory status",description:"Use /swarm memory status to show provider and migration status"},"swarm-memory-export":{template:"/swarm memory export",description:"Use /swarm memory export to write current memory to JSONL"},"swarm-memory-import":{template:"/swarm memory import",description:"Use /swarm memory import to import legacy JSONL into SQLite"},"swarm-memory-migrate":{template:"/swarm memory migrate",description:"Use /swarm memory migrate to run the one-time SQLite migration"},"swarm-curate":{template:"/swarm curate",description:"Use /swarm curate to curate knowledge artifacts and entries"},"swarm-consolidate":{template:"/swarm consolidate $ARGUMENTS",description:"Use /swarm consolidate to run quota-bounded skill-improver consolidation"},"swarm-concurrency":{template:"/swarm concurrency $ARGUMENTS",description:"Use /swarm concurrency to manage runtime concurrency override for plan execution"},"swarm-turbo":{template:"/swarm turbo",description:"Use /swarm turbo to enable turbo mode for faster execution"},"swarm-epic":{template:"/swarm epic $ARGUMENTS",description:shortcutDescription("epic")},"swarm-coupling":{template:"/swarm coupling $ARGUMENTS",description:shortcutDescription("coupling")},"swarm-lanes":{template:"/swarm lanes",description:shortcutDescription("lanes")},"swarm-guardrail-explain":{template:"/swarm guardrail explain $ARGUMENTS",description:shortcutDescription("guardrail explain")},"swarm-guardrail-reset":{template:"/swarm guardrail reset $ARGUMENTS",description:shortcutDescription("guardrail reset")},"swarm-guardrail-log":{template:"/swarm guardrail-log $ARGUMENTS",description:shortcutDescription("guardrail-log")},"swarm-full-auto":{template:"/swarm full-auto $ARGUMENTS",description:"Toggle Full-Auto Mode for the active session [on|off]"},"swarm-auto-proceed":{template:"/swarm auto-proceed $ARGUMENTS",description:"Toggle auto-proceed mode for automatic phase advancement"},"swarm-write-retro":{template:"/swarm write-retro $ARGUMENTS",description:"Use /swarm write-retro to manually write a phase retrospective"},"swarm-reset-session":{template:"/swarm reset-session",description:"Use /swarm reset-session to clear session state and delegation chains"},"swarm-recover":{template:"/swarm recover $ARGUMENTS",description:"Use /swarm recover to settle wedged coder settlements [task_id] [--force]"},"swarm-simulate":{template:"/swarm simulate $ARGUMENTS",description:"Use /swarm simulate to run a simulated agent session"},"swarm-promote":{template:"/swarm promote $ARGUMENTS",description:"Use /swarm promote to promote knowledge entries to production"},"swarm-checkpoint":{template:"/swarm checkpoint $ARGUMENTS",description:"Use /swarm checkpoint to save or restore git checkpoints"},"swarm-config-doctor":{template:"/swarm config doctor",description:"Use /swarm config doctor to diagnose configuration issues"},"swarm-evidence-summary":{template:"/swarm evidence summary",description:"Use /swarm evidence summary to generate evidence summaries"},"swarm-finalize":{template:"/swarm finalize",description:"Use /swarm finalize to archive the swarm project and close active state"},"swarm-close":{template:"/swarm close",description:"Deprecated alias for /swarm finalize"},"swarm-acknowledge-spec-drift":{template:"/swarm acknowledge-spec-drift",description:"Use /swarm acknowledge-spec-drift to acknowledge spec drift and suppress further warnings"},"swarm-doctor-tools":{template:"/swarm doctor tools",description:"Use /swarm doctor tools to run tool registration coherence check"},"swarm-context-map-stats":{template:"/swarm context-map stats",description:shortcutDescription("context-map-stats")},"swarm-link":{template:"/swarm link $ARGUMENTS",description:"Use /swarm link to link this worktree to a shared knowledge store [name|status]"},"swarm-unlink":{template:"/swarm unlink $ARGUMENTS",description:"Use /swarm unlink to unlink this worktree from the shared knowledge store [--no-copy]"}},log("Config applied",{agents:Object.keys(agents),commands:["swarm"]})},"experimental.chat.messages.transform":composeHandlers(...[(_input,output)=>{if(process.env.DEBUG_SWARM)console.error("[DIAG] messagesTransform START");let mctx=resolveMessageTransformContext(output);if(mctx.sessionID){let archAgent=swarmState.activeAgent.get(mctx.sessionID),archSession=swarmState.agentSessions.get(mctx.sessionID),agentName=archAgent??archSession?.agentName??"";if(stripKnownSwarmPrefix(agentName)===ORCHESTRATOR_NAME)try{delegationLedgerHook.onArchitectResume(mctx.sessionID)}catch{}}return Promise.resolve()},pipelineHook["experimental.chat.messages.transform"],contextBudgetHandler,initOrphanRecoveryAdvisoryHook.messagesTransform,durableBackgroundAdvisoryMessagesTransform,fullAutoInterceptHook?.messagesTransform,ccCommandInterceptHook?.messagesTransform,delegationGateHooks.messagesTransform,issueTraceHook.messagesTransform,delegationSanitizerHook,memoryLifecycleHooks.messagesTransform,knowledgeInjectorHook,(_input,output)=>{try{let mctx=resolveMessageTransformContext(output);return knowledgeApplicationTransformScan(ctx.directory,output,mctx.sessionID)}catch{return Promise.resolve()}},(_input,output)=>{try{if(!skillPropagationConfig.enabled)return Promise.resolve();let mctx=resolveMessageTransformContext(output);return skillPropagationTransformScan(ctx.directory,output,mctx.sessionID,skillPropagationConfig)}catch{return Promise.resolve()}},(_input,output)=>{if(Array.isArray(output.messages))consolidateSystemMessagesInPlace(output.messages);if(process.env.DEBUG_SWARM)console.error("[DIAG] messagesTransform DONE");return Promise.resolve()}].filter((fn2)=>Boolean(fn2))),"experimental.text.complete":prWorkflowResponseGate.textComplete,"experimental.chat.system.transform":composeHandlers(...[async(_input,_output)=>{if(process.env.DEBUG_SWARM)console.error("[DIAG] systemTransform START")},systemEnhancerHook["experimental.chat.system.transform"],async(_input,_output)=>{if(process.env.DEBUG_SWARM)console.error("[DIAG] systemTransform enhancer DONE")},contextCapsuleInjectHook["experimental.chat.system.transform"],(input,_output)=>{try{let{sessionID}=input;if(!sessionID)return Promise.resolve();let lastTime=_heartbeatTimers.get(sessionID);if(Date.now()-(lastTime??0)>30000)_heartbeatTimers.set(sessionID,Date.now()),capSessionMap(_heartbeatTimers,MAX_TRACKED_HEARTBEAT_SESSIONS),telemetry.heartbeat(sessionID)}catch{}return Promise.resolve()},automationConfig.capabilities?.phase_preflight===!0&&preflightTriggerManager?createPhaseMonitorHook(ctx.directory,preflightTriggerManager,void 0,(sessionId)=>createCuratorLLMDelegate(ctx.directory,"init",sessionId)):knowledgeConfig.enabled?createPhaseMonitorHook(ctx.directory,void 0,void 0,(sessionId)=>createCuratorLLMDelegate(ctx.directory,"init",sessionId)):void 0,swarmCommandSystemRuleHook,roleFilterSystemHook["experimental.chat.system.transform"]].filter(Boolean)),"experimental.session.compacting":compactionHook["experimental.session.compacting"],"command.execute.before":safeHook(commandHandler),"tool.execute.before":async(input,output)=>{if(process.env.DEBUG_SWARM)console.error(`[DIAG] toolBefore tool=${normalizeToolName(input.tool)??input.tool} session=${input.sessionID}`);if(!swarmState.activeAgent.has(input.sessionID))swarmState.activeAgent.set(input.sessionID,ORCHESTRATOR_NAME);let session=swarmState.agentSessions.get(input.sessionID),activeAgent=swarmState.activeAgent.get(input.sessionID);if(session&&activeAgent&&activeAgent!==ORCHESTRATOR_NAME){if(stripKnownSwarmPrefix(activeAgent)!==ORCHESTRATOR_NAME){if(!session.delegationActive&&Date.now()-session.lastAgentEventTime>1e4)swarmState.activeAgent.set(input.sessionID,ORCHESTRATOR_NAME),ensureAgentSession(input.sessionID,ORCHESTRATOR_NAME)}}let failClosedRegionCompleted=!1;try{await guardrailsHooks.toolBefore(input,output),await scopeGuardHook.toolBefore(input,output);let prWorkflowControllerSessionID=await prWorkflowSessionResolver.resolve(input.sessionID),prWorkflowToolContext=resolveToolBeforeContext(input,output);await enforcePrWorkflowToolBefore(ctx.directory,prWorkflowControllerSessionID,normalizeToolName(input.tool)??input.tool,prWorkflowToolContext.args??void 0,instanceGeneratedAgentNames),await delegationGateHooks.toolBefore(input,output),await fullAutoDelegationHook.toolBefore(input,output),await fullAutoPermissionHook.toolBefore(input,output),await knowledgeApplicationGateBefore(ctx.directory,{tool:input.tool,agent:resolveToolBeforeContext(input,output).agent,sessionID:input.sessionID},KnowledgeApplicationConfigSchema.parse(config3.knowledge_application??{}));let skillResult=await skillPropagationGateBefore(ctx.directory,{tool:input.tool,agent:resolveToolBeforeContext(input,output).agent,sessionID:input.sessionID,args:resolveToolBeforeContext(input,output).args??void 0},skillPropagationConfig);if(skillResult.blocked)throw Error(skillResult.reason??"Blocked by skill propagation gate");if(skillResult.reason){let skillSession=ensureAgentSession(input.sessionID,swarmState.activeAgent.get(input.sessionID)??ORCHESTRATOR_NAME);pushAdvisory(skillSession,skillResult.reason)}let toolBeforeCtx=resolveToolBeforeContext(input,output),toolBeforeArgs=toolBeforeCtx.args??{};if(injectSkillsIntoDelegation(ctx.directory,toolBeforeArgs,skillResult.recommendedSkills,stripKnownSwarmPrefix(parseDelegationArgs(toolBeforeArgs)?.targetAgent??"")||toolBeforeCtx.agent,input.sessionID,{quiet:config3.quiet}),failClosedRegionCompleted=!0,knowledgeConfig.enabled)await injectDelegateDirectivesBefore(ctx.directory,{tool:input.tool,agent:toolBeforeCtx.agent,sessionID:input.sessionID,args:toolBeforeArgs},knowledgeConfig);setStoredInputArgs(input.callID,output.args);let pressurePct=getSessionBudgetPct(input.sessionID);if(pressurePct>=50){let pressureSession=ensureAgentSession(input.sessionID,swarmState.activeAgent.get(input.sessionID)??ORCHESTRATOR_NAME);if(!pressureSession.contextPressureWarningSent)pressureSession.contextPressureWarningSent=!0,pushAdvisory(pressureSession,`CONTEXT PRESSURE: ${pressurePct.toFixed(1)}% of context window used. Prioritize completing the current task before starting new work.`)}if(autoReviewConfig.enabled)await beginApprovedReviewerScopeLifecycle({directory:ctx.directory,tool:input.tool,args:toolBeforeArgs,parentSessionID:input.sessionID,callID:input.callID,maxBytes:autoReviewConfig.max_diff_kb*1024});if(await safeHook(activityHooks.toolBefore)(input,output),await reserveApprovedPhaseParticipation({directory:ctx.directory,tool:input.tool,parentSessionId:input.sessionID,callId:input.callID,args:toolBeforeArgs,policy:config3.phase_complete}),(normalizeToolName(input.tool)??input.tool)==="Task"&&typeof toolBeforeArgs.subagent_type==="string"&&toolBeforeArgs.subagent_type.trim()!==""){let actionIdentity2=createActionIdentity({tool:input.tool,args:toolBeforeArgs});registerPendingTaskModelRoute({parentSessionID:input.sessionID,invocationID:String(getAgentSession(input.sessionID)?.activeInvocationId??0),callID:input.callID,role:stripKnownSwarmPrefix(toolBeforeArgs.subagent_type),actionDigest:actionIdentity2.digest,swarmID:actionIdentity2.swarm??void 0})}resetGateDenialStreaks(input.sessionID,input.tool,toolBeforeArgs);{let beforeToolNormalized=normalizeToolName(input.tool)??input.tool;if(beforeToolNormalized==="Task"||beforeToolNormalized==="task"){let delegatedAgent=typeof toolBeforeArgs.subagent_type==="string"&&toolBeforeArgs.subagent_type.length>0?toolBeforeArgs.subagent_type:swarmState.activeAgent.get(input.sessionID)??"unknown",delegationTaskId=swarmState.agentSessions.get(input.sessionID)?.currentTaskId??"";_delegationTelemetryByCallID.set(input.callID,{agentName:delegatedAgent,taskId:delegationTaskId}),capSessionMap(_delegationTelemetryByCallID,MAX_TRACKED_DELEGATION_TELEMETRY),telemetry.delegationBegin(input.sessionID,delegatedAgent,delegationTaskId)}}}catch(err2){if(!failClosedRegionCompleted){let deniedMessage=err2&&typeof err2==="object"&&typeof err2.message==="string"?err2.message:null,deniedArgs;try{deniedArgs=resolveToolBeforeContext(input,output).args??void 0}catch{deniedArgs=void 0}if(deniedMessage!==null&&!isAbortLikeError(err2))try{await recordDeniedToolCall(input.sessionID,{tool:input.tool,callID:input.callID,args:deniedArgs},deniedMessage,ctx.directory,{maxLines:1000})}catch{}noteGateDenial(input.sessionID,input.tool,err2,{enabled:guardrailsConfig.enabled,warnThreshold:guardrailsConfig.gate_denial_warn_threshold,stopThreshold:guardrailsConfig.gate_denial_stop_threshold},deniedArgs)}if(normalizeToolName(input.tool)==="Task"||normalizeToolName(input.tool)==="task")try{await delegationGateHooks.abortDeniedSettlementForCall(input.callID)}catch{}throw err2}},"tool.execute.after":async(input,output)=>{let _dbg=!!process.env.DEBUG_SWARM,_toolName=normalizeToolName(input.tool)??input.tool;if(_dbg)console.error(`[DIAG] toolAfter START tool=${_toolName} session=${input.sessionID}`);let normalizedTool=normalizeToolName(input.tool),isTaskTool8=normalizedTool==="Task"||normalizedTool==="task",afterCtx=resolveToolAfterContext(input);if(autoReviewConfig.enabled&&isTaskTool8)await completeReviewerScopeLifecycle({directory:ctx.directory,tool:input.tool,args:afterCtx.args,output,parentSessionID:input.sessionID,callID:input.callID});let hookChain=async()=>{if(await activityHooks.toolAfter(input,output),_dbg)console.error(`[DIAG] toolAfter activity done tool=${_toolName}`);if(await safeHook(trajectoryLoggerHook.toolAfter)(input,output),_dbg)console.error(`[DIAG] toolAfter trajectoryLogger done tool=${_toolName}`);if(knowledgeConfig.enabled)await safeHook(()=>collectDelegateAcksAfter(ctx.directory,{tool:input.tool,sessionID:input.sessionID,args:afterCtx.args},output))(input,output),await safeHook(()=>collectReviewerVerdictsAfter(ctx.directory,{tool:input.tool,sessionID:input.sessionID,args:afterCtx.args},output))(input,output),await safeHook(()=>microReflectorAfter(ctx.directory,input,output,createCuratorLLMDelegate(ctx.directory,"phase",input.sessionID),{maxCalls:knowledgeConfig.enrichment.max_calls_per_day,window:knowledgeConfig.enrichment.quota_window},{enabled:learningConfig.realtime_admission.enabled,maxQueueSize:learningConfig.realtime_admission.max_queue_size}))(input,output);if(await safeHook(async()=>{let summary=await realtimeAdmissionAfter(ctx.directory,{tool:input.tool,sessionID:input.sessionID},learningConfig.realtime_admission,async()=>{let plan=await loadPlan(ctx.directory).catch(()=>null);return{knowledgeConfig,projectName:plan?.title??"unknown",phaseNumber:plan?.current_phase??1,sessionID:input.sessionID,llmDelegate:createCuratorLLMDelegate(ctx.directory,"phase",input.sessionID),onKnowledgeChanged:bumpKnowledgeGeneration}});if(summary)log("realtime admission drain",{sessionID:input.sessionID,...summary})})(input,output),await safeHook(async()=>{await collectReviewerReceiptAfter(ctx.directory,{tool:input.tool,sessionID:input.sessionID,callID:input.callID,args:afterCtx.args},output,{dispatcher:reviewModelDispatcher,config:autoReviewConfig,generatedAgentNames:instanceGeneratedAgentNames,agentModelRegistry:reviewAgentModelRegistry,injectAdvisory:advisoryInjector,validationScheduler:findingValidationScheduler})})(input,output),await safeHook(autoReviewHook.toolAfter)(input,afterCtx),await safeHook(prmHook.toolAfter)(input,output),await guardrailsHooks.toolAfter(input,output),_dbg)console.error(`[DIAG] toolAfter guardrails done tool=${_toolName}`);if(await safeHook(delegationLedgerHook.toolAfter)(input,output),_dbg)console.error(`[DIAG] toolAfter ledger done tool=${_toolName}`);if(await safeHook(selfReviewHook.toolAfter)(input,output),_dbg)console.error(`[DIAG] toolAfter selfReview done tool=${_toolName}`);if(await safeHook(memoryLifecycleHooks.toolAfter)(input,output),_dbg)console.error(`[DIAG] toolAfter memory done tool=${_toolName}`);if(await safeHook(delegationGateHooks.toolAfter)(input,output),await safeHook(async()=>{await observePhaseParticipationToolResult({directory:ctx.directory,tool:input.tool,parentSessionId:input.sessionID,callId:input.callID,output})})(input,output),_dbg)console.error(`[DIAG] toolAfter delegationGate done tool=${_toolName}`);if(await safeHook(fullAutoInputProbeHook.toolAfter)(input,output),await safeHook(fullAutoDelegationHook.toolAfter)(input,output),await safeHook(prAutoSubscribeHook.toolAfter)(input,output),isTaskTool8&&typeof output.output==="string")try{let adversarialMatches=detectAdversarialPatterns(output.output);if(adversarialMatches.length>0){let sessionId=input.sessionID,session=swarmState.agentSessions.get(sessionId);if(session)pushAdvisory(session,`ADVERSARIAL PATTERN DETECTED: ${adversarialMatches.map((p)=>p.pattern).join(", ")}. Review agent output for potential prompt injection or gate bypass.`);if("adversarialPatternDetected"in telemetry)telemetry.adversarialPatternDetected(input.sessionID,adversarialMatches)}}catch{}try{recordToolCall(normalizedTool,resolveToolAfterContext(input).args,input.sessionID)}catch{}try{let spiralMatch=await detectDebuggingSpiral(ctx.directory,input.sessionID);if(spiralMatch){let taskId=swarmState.agentSessions.get(input.sessionID)?.currentTaskId??`session-${input.sessionID.slice(0,12)}`,spiralResult=await handleDebuggingSpiral(spiralMatch,taskId,ctx.directory),session=swarmState.agentSessions.get(input.sessionID);if(session)pushAdvisory(session,spiralResult.message)}}catch{}if(knowledgeCuratorHook)await safeHook(knowledgeCuratorHook)(input,output);if(hivePromoterHook)await safeHook(hivePromoterHook)(input,output);if(_dbg)console.error(`[DIAG] toolAfter knowledge done tool=${_toolName}`);if(await safeHook(steeringConsumedHook)(input,output),await safeHook(coChangeSuggesterHook)(input,output),await safeHook(darkMatterDetectorHook)(input,output),_dbg)console.error(`[DIAG] toolAfter intelligence done tool=${_toolName}`);if(await snapshotWriterHook(input,output),await toolSummarizerHook?.(input,output),_dbg)console.error(`[DIAG] toolAfter snapshot+summarizer done tool=${_toolName}`);let execMode=config3.execution_mode??"balanced";if(execMode==="strict"){if(slopDetectorHook)await slopDetectorHook.toolAfter(input,output);if(incrementalVerifyHook)await incrementalVerifyHook.toolAfter(input,output)}if(execMode!=="fast"&&compactionServiceHook)await compactionServiceHook.toolAfter(input,output);if(repoGraphHook)await safeHook(repoGraphHook.toolAfter)(input,output);if(isTaskTool8&&config3.context_map?.enabled===!0&&input.sessionID)try{let contextMapTaskId=swarmState.agentSessions.get(input.sessionID)?.currentTaskId??null;if(contextMapTaskId){let agentOutput=typeof output.output==="string"?output.output:"";updateContextMapAfterAgent({task_id:contextMapTaskId,agent_role:swarmState.activeAgent.get(input.sessionID)??"unknown",files_touched:[],implementation_summary:agentOutput.slice(0,500),task_goal:"",final_status:"completed",directory:ctx.directory})}}catch{}let toolOutputConfig=config3.tool_output;if(toolOutputConfig&&toolOutputConfig.truncation_enabled!==!1&&typeof output.output==="string"){let defaultTruncatableTools=new Set(["diff","symbols","bash","shell","test_runner","lint","pre_check_batch","complexity_hotspots","pkg_audit","sbom_generate","schema_drift"]),configuredTools=toolOutputConfig.truncation_tools,truncatableTools=computeEffectiveTruncatableTools(defaultTruncatableTools,configuredTools),maxLines=toolOutputConfig.per_tool?.[input.tool]??toolOutputConfig.max_lines??150;if(truncatableTools.has(input.tool))output.output=truncateToolOutput(output.output,maxLines,input.tool,10)}};try{await hookChain()}catch(err2){let warning=`[swarm] toolAfter hook chain error tool=${_toolName}: ${err2 instanceof Error?err2.message:String(err2)}`;if(!config3.quiet)console.warn(warning);else addDeferredWarning(warning)}if(isTaskTool8){let backgroundResultIsRunning=outputLooksLikeBackgroundRunning(output),sessionId=input.sessionID,beganDelegation=_delegationTelemetryByCallID.get(input.callID),storedSubagentType=typeof afterCtx.args?.subagent_type==="string"?afterCtx.args.subagent_type:void 0,agentName=beganDelegation?.agentName||storedSubagentType||swarmState.activeAgent.get(sessionId)||"unknown",baseAgentName=stripKnownSwarmPrefix(agentName),preHandoffSession=swarmState.agentSessions.get(sessionId),activeWindow=getActiveWindow(sessionId),configuredModel=resolveRegisteredAgentModel(config3,agentName)??DEFAULT_MODELS[baseAgentName]??DEFAULT_MODELS.default,assistantUsage=consumeAssistantUsageForTask(sessionId,output),costFields=buildDelegationCostFields({raw:{metadata:output.metadata,output,assistant:assistantUsage},model:configuredModel,gate:preHandoffSession?.lastDelegationReason,retry_index:activeWindow?.transientRetryCount,pricing:config3.pricing});swarmState.activeAgent.set(sessionId,ORCHESTRATOR_NAME),ensureAgentSession(sessionId,ORCHESTRATOR_NAME);let taskSession=swarmState.agentSessions.get(sessionId);if(taskSession){if(taskSession.delegationActive=!1,taskSession.lastAgentEventTime=Date.now(),!backgroundResultIsRunning){if(_delegationTelemetryByCallID.delete(input.callID),telemetry.delegationEnd(sessionId,agentName,beganDelegation?.taskId||taskSession.currentTaskId||"","completed",costFields),baseAgentName==="reviewer"||baseAgentName==="test_engineer"||baseAgentName==="critic"||baseAgentName==="critic_sounding_board")pushAdvisory(taskSession,`[PIPELINE] ${baseAgentName} delegation complete for task ${taskSession.currentTaskId??"unknown"}. `+"Resume the QA gate pipeline — check your task pipeline steps for the next required action. "+"Do not stop here.");if(baseAgentName==="critic_sounding_board"){let rawResponse=typeof output.output==="string"?output.output:"",parsed=parseSoundingBoardResponse(rawResponse);if(parsed){let verdictMsg=`[SOUNDING_BOARD] Verdict: ${parsed.verdict}. ${parsed.reasoning}`;if(parsed.improvedQuestion)verdictMsg+=` Rephrase to: ${parsed.improvedQuestion}`;if(parsed.answer)verdictMsg+=` Answer: ${parsed.answer}`;if(parsed.warning)verdictMsg+=` WARNING: ${parsed.warning}`;pushAdvisory(taskSession,verdictMsg),taskSession.lastDelegationReason="critic_consultation"}else pushAdvisory(taskSession,`[SOUNDING_BOARD] WARNING: Could not parse a structured verdict from critic_sounding_board response (${rawResponse.length} chars). `+"Treat as REPHRASE — review the raw response before surfacing to user or escalating. "+"Do not silently accept as resolved.")}}}if(_dbg)console.error(`[DIAG] Task handoff DONE session=${sessionId} activeAgent=${swarmState.activeAgent.get(sessionId)}`)}if(deleteStoredInputArgs(input.callID),_dbg)console.error(`[DIAG] toolAfter COMPLETE tool=${_toolName}`)},"chat.message":async(input,output)=>{try{if(input?.sessionID&&typeof input?.agent==="string"){let routeModel=resolveTaskRouteModelChain(String(input.agent));if(routeModel){if((await resolveTaskChatModelOverride({childSessionID:String(input.sessionID),role:routeModel.role,primaryModel:routeModel.primaryModel,fallbackModels:routeModel.fallbackModels,lookupParentSessionID:lookupParentSessionIDForTaskRoute})).status==="exhausted"){let error93=Error(`MODEL_FALLBACK_EXHAUSTED: no configured model remains for ${routeModel.role}`);throw error93.name="TaskModelFallbackExhaustedError",error93}}}}catch(error93){if(error93 instanceof Error&&error93.name==="TaskModelFallbackExhaustedError")throw error93}await safeHook(async(input2,output2)=>{if(process.env.DEBUG_SWARM)console.error(`[DIAG] chat.message agent=${input2.agent??"none"} session=${input2.sessionID}`);if(input2?.sessionID&&typeof input2?.agent==="string"&&output2&&typeof output2==="object"&&typeof output2.message==="object"&&output2.message!==null){let routeModel=resolveTaskRouteModelChain(String(input2.agent));if(routeModel){let resolution=await resolveTaskChatModelOverride({childSessionID:String(input2.sessionID),role:routeModel.role,primaryModel:routeModel.primaryModel,fallbackModels:routeModel.fallbackModels,lookupParentSessionID:lookupParentSessionIDForTaskRoute});if(resolution.status==="override"&&resolution.model)output2.message.model=resolution.model}}if(await delegationHandler(input2,output2),input2?.sessionID)try{await cacheCohortIdAtMessage(ctx.directory,input2.sessionID)}catch{}try{if(input2?.sessionID&&input2?.agent){if(stripKnownSwarmPrefix(String(input2.agent))==="architect")tickAndMaybeDispatchCadence(ctx.directory,input2.sessionID,"architectTurns",config3,{activeAgent:String(input2.agent)})}}catch{}if(process.env.DEBUG_SWARM)console.error(`[DIAG] chat.message DONE agent=${input2.agent??"none"}`)})(input,output)},automation:automationManager}}var src_default={id:"opencode-swarm",server:OpenCodeSwarm};export{schedulePostResolutionTasksForTest,recordTestImpactGateGroundTruth,overrideIndexInternalsForTest,loadTier1EvaluationTasks,evaluationV1,evaluatePrReviewRecoveryV1,evaluateCandidateV1,src_default as default,computeEffectiveTruncatableTools,capSessionMap,archiveSqliteSnapshot,_resetDelegationTelemetryPairingForTesting};
6965
+ Dispatching these agents will fail permanently ("Model not found"/"Forbidden"). Fix agents.<role>.model in opencode-swarm.json (or remove the override to fall back to the default).`;if(!config3.quiet)console.warn(msg);else addDeferredWarning(msg);for(let resolution of unresolved)telemetry.modelUnresolved(resolution.agent,resolution.model,resolution.detail??"does not resolve")}).catch(()=>{})}),postResolutionTasks.push(()=>{runInitOrphanRecovery(ctx.directory).catch((err2)=>{let msg=err2 instanceof Error?err2.message:String(err2);log("initOrphanRecovery failed (non-fatal)",{error:msg})})}),config3.hooks?.background_subagents===!0)postResolutionTasks.push(()=>{withTimeout(Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations)).then((m)=>m.maintainBackgroundDelegations(ctx.directory,{lockTimeoutMs:5000,reason:"post-init"})),BACKGROUND_MAINTENANCE_INIT_TIMEOUT_MS,Error(`background maintenance exceeded ${BACKGROUND_MAINTENANCE_INIT_TIMEOUT_MS}ms post-init budget; continuing without it (other maintenance points remain)`)).catch((err2)=>{let msg=err2 instanceof Error?err2.message:String(err2);log("post-init background maintenance timed out or failed (non-fatal)",{error:msg})})});if(writeSwarmConfigExampleIfNew(ctx.directory),writeProjectConfigIfNew(ctx.directory,config3.quiet),postResolutionTasks.push(()=>{withTimeout(syncBundledProjectSkillsIfMissingAsync(ctx.directory,PACKAGE_ROOT2,config3.quiet),SYNC_BUNDLED_SKILLS_TIMEOUT_MS,Error(`syncBundledProjectSkillsIfMissingAsync exceeded ${SYNC_BUNDLED_SKILLS_TIMEOUT_MS}ms budget; continuing without skill materialization (command-path sync remains a backstop)`)).catch((err2)=>{let msg=err2 instanceof Error?err2.message:String(err2);log("bundled skill materialization timed out or failed (non-fatal)",{error:msg})})}),config3.version_check!==!1)postResolutionTasks.push(()=>{scheduleVersionCheck(package_default.version,(msg)=>{if(config3.quiet)addDeferredWarning(msg);else console.warn(msg)})});let projectContext=await withTimeout((async()=>{return(await Promise.resolve().then(() => (init_project_context(),exports_project_context))).buildProjectContext(ctx.directory)})(),300,Error("language-backend detection exceeded 300ms; continuing with unresolved sentinels")).catch((err2)=>{let msg=err2 instanceof Error?err2.message:String(err2);return log("language-backend detection timed out or failed (non-fatal)",{error:msg}),null}),autoReviewConfig;try{autoReviewConfig=resolveAutoReviewConfigForInit(config3.auto_review??{})}catch(error93){addDeferredWarning(`[swarm] Invalid auto_review configuration; auto-review is disabled until corrected: ${error93 instanceof Error?error93.message:String(error93)}`),autoReviewConfig=resolveAutoReviewConfigForInit({enabled:!1})}let configWithResolvedAutoReview={...config3,auto_review:autoReviewConfig},agents=getAgentConfigs(configWithResolvedAutoReview,ctx.directory,void 0,projectContext??void 0),largestArchitectChars=Object.entries(agents).reduce((max,[name,cfg])=>{if(!name.endsWith("_architect")&&name!=="architect")return max;let len=cfg.prompt?.length??0;return len>max?len:max},0);log("architect prompt size",{chars:largestArchitectChars});let agentDefinitions=createAgents(configWithResolvedAutoReview,projectContext??void 0),agentDefinitionMap=Object.fromEntries(agentDefinitions.map((agent)=>[agent.name,agent])),instanceGeneratedAgentNames=Object.freeze(Object.keys(agents));swarmState.curatorInitAgentNames=Object.keys(agents).filter((k)=>k==="curator_init"||k.endsWith("_curator_init")),swarmState.curatorPhaseAgentNames=Object.keys(agents).filter((k)=>k==="curator_phase"||k.endsWith("_curator_phase")),swarmState.curatorPostmortemAgentNames=Object.keys(agents).filter((k)=>k==="curator_postmortem"||k.endsWith("_curator_postmortem")),swarmState.curatorConsolidationAgentNames=Object.keys(agents).filter((k)=>k==="curator_consolidation"||k.endsWith("_curator_consolidation")),swarmState.skillImproverAgentNames=Object.keys(agents).filter((k)=>k==="skill_improver"||k.endsWith("_skill_improver")),swarmState.specWriterAgentNames=Object.keys(agents).filter((k)=>k==="spec_writer"||k.endsWith("_spec_writer")),swarmState.generatedAgentNames=[...instanceGeneratedAgentNames];let pipelineHook=createPipelineTrackerHook(config3,ctx.directory),systemEnhancerHook=createSystemEnhancerHook(config3,ctx.directory),contextCapsuleInjectHook=createContextCapsuleInjectHook(config3,ctx.directory),compactionHook=createCompactionCustomizerHook(config3,ctx.directory),resolveIncomingAgentModel=(agentName)=>resolveRuntimeAgentModel(config3,agents,agentName),resolveTaskRouteModelChain=(exactAgentName)=>{if(!exactAgentName)return null;let trimmedAgentName=exactAgentName.trim();if(!trimmedAgentName)return null;let role=stripKnownSwarmPrefix(trimmedAgentName),swarmAgents=getSwarmAgents(extractSwarmIdFromAgentName(trimmedAgentName));return{exactAgentName:trimmedAgentName,role,primaryModel:resolveRuntimeAgentModel(config3,agents,trimmedAgentName)??resolveRegisteredAgentModel(config3,trimmedAgentName),fallbackModels:swarmAgents?.[role]?.fallback_models??[]}},extractBoundedErrorSignal=(value,depth=0)=>{if(depth>4)return[];if(typeof value==="string"){let trimmed=value.trim();return trimmed?[trimmed.slice(0,512)]:[]}if(typeof value==="number"||typeof value==="boolean")return[String(value)];if(!value||typeof value!=="object")return[];if(value instanceof Error)return[...extractBoundedErrorSignal(value.name,depth+1),...extractBoundedErrorSignal(value.message,depth+1)];let record3=value,parts=[];for(let key of["message","reason","code","status","statusCode","error","cause","detail","details"])parts.push(...extractBoundedErrorSignal(record3[key],depth+1));return parts},extractSessionErrorSignal=(properties)=>{if(!properties)return"";return extractBoundedErrorSignal(properties).filter(Boolean).join(" ").slice(0,2048)},resolveTaskRouteForChildSession=(childSessionID)=>{let trimmedChildSessionID=childSessionID.trim();if(!trimmedChildSessionID)return;return getPendingTaskModelRouteSnapshot().find((route)=>route.childSessionID===trimmedChildSessionID)},lookupParentSessionIDForTaskRoute=async(childSessionID)=>{let sessionApi=ctx.client?.session;if(!sessionApi?.get)return;try{let result=await sessionApi.get({path:{id:childSessionID},query:{directory:ctx.directory}});return typeof result?.data?.parentID==="string"&&result.data.parentID.trim()!==""?result.data.parentID.trim():void 0}catch{return}};registerFullAutoRecoveryBlockerEvaluator(({sessionID})=>{let invocationID=getAgentSession(sessionID)?.activeInvocationId??0;if(invocationID<=0)return[];return[...new Set(listBlockingActionCircuitsForInvocation(sessionID,invocationID).map((entry)=>entry.circuitKind))]});let contextBudgetHandler=createContextBudgetHandler(config3,resolveIncomingAgentModel),evaluationModelDispatcher=createEvaluationModelDispatcher(ctx.client),reviewModelDispatcher=createReviewModelDispatcher(ctx.client),findingValidationScheduler=createFindingValidationScheduler(),reviewAgentModelRegistry=captureReviewAgentModelRegistry(config3,instanceGeneratedAgentNames),getActiveReviewAgentName=(sessionID)=>swarmState.activeAgent.get(sessionID)??swarmState.agentSessions.get(sessionID)?.agentName,roleFilterSystemHook=createRoleFilterSystemHook(getActiveReviewAgentName),commandHandler=createSwarmCommandHandler(ctx.directory,agentDefinitionMap,{getActiveAgentName:getActiveReviewAgentName,packageRoot:PACKAGE_ROOT2,registeredAgents:agents,evaluationModelDispatcher,reviewModelDispatcher,autoReviewConfig,reviewAgentModelRegistry}),swarmCommandSystemRuleHook=createSwarmCommandSystemRuleHook(agentDefinitionMap,agents),activityHooks=createAgentActivityHooks(config3,ctx.directory),learningConfig=LearningConfigSchema.parse(config3.learning??{}),prmHook=createPrmHook(config3.prm??PrmConfigSchema.parse({}),ctx.directory,resolvePrmPatternPersistenceOptions(learningConfig)),trajectoryLoggerHook=createTrajectoryLoggerHook({enabled:!0,max_lines:1000},ctx.directory),delegationGateHooks=createDelegationGateHook(configWithResolvedAutoReview,ctx.directory),advisoryInjector=(sessionId,message)=>{let session=swarmState.agentSessions.get(sessionId);if(session)pushAdvisory(session,message)},backgroundCompletionObserver=createBackgroundCompletionObserver({config:{enabled:config3.hooks?.background_subagents===!0},directory:ctx.directory,reviewerReceiptOptions:{dispatcher:reviewModelDispatcher,config:autoReviewConfig,generatedAgentNames:instanceGeneratedAgentNames,agentModelRegistry:reviewAgentModelRegistry,injectAdvisory:advisoryInjector,validationScheduler:findingValidationScheduler}}),backgroundSubagentsEnabled=config3.hooks?.background_subagents===!0,pendingDelegationsModulePromise=null,maintainBackgroundDelegationsOnSessionEvent=async()=>{let modulePromise=pendingDelegationsModulePromise;if(modulePromise===null)modulePromise=Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations)).catch((err2)=>{throw pendingDelegationsModulePromise=null,err2}),pendingDelegationsModulePromise=modulePromise;await(await modulePromise).maintainBackgroundDelegations(ctx.directory,{lockTimeoutMs:2000,reason:"session-close"})},delegationSanitizerHook=createDelegationSanitizerHook(ctx.directory),memoryLifecycleHooks=createMemoryLifecycleHooks({directory:ctx.directory,config:config3.memory,getActiveAgentName:(sessionID)=>sessionID?swarmState.activeAgent.get(sessionID):void 0,getActiveTaskId:(sessionID)=>sessionID?swarmState.agentSessions.get(sessionID)?.currentTaskId??void 0:void 0});if(config3.memory?.enabled===!0&&config3.memory.reflection?.enabled===!0){let reflectionConfig=config3.memory,regenerateMemoryReflectionTask=()=>withTimeout(repoGraphInitPromise??Promise.resolve(),5000,Error("repo graph refresh exceeded reflection wait budget")).catch(()=>{return}).then(()=>withTimeout(regenerateMemoryReflectionForInit(ctx.directory,reflectionConfig),15000,Error("memory reflection startup regeneration exceeded 15s"))).catch((err2)=>{log("memory reflection startup regeneration failed (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})}).then(()=>{return});postResolutionTasks.push(regenerateMemoryReflectionTask)}let guardrailsFallback=config3.guardrails?.enabled===!1?{...config3.guardrails,enabled:!1}:config3.guardrails??{},guardrailsConfig=GuardrailsConfigSchema.parse(guardrailsFallback);if(loadedFromFile&&guardrailsConfig.enabled===!1)warn(""),warn("══════════════════════════════════════════════════════════════"),warn("[opencode-swarm] \uD83D\uDD34 SECURITY WARNING: GUARDRAILS ARE DISABLED"),warn("══════════════════════════════════════════════════════════════"),warn("Guardrails have been explicitly disabled in user configuration."),warn("This disables safety measures including:"),warn(" - Tool call limits"),warn(" - Duration limits"),warn(" - Repetition detection"),warn(" - Error rate limits"),warn(" - Idle timeouts"),warn(""),warn("Only disable guardrails if you fully understand the security implications."),warn('To re-enable guardrails, set "guardrails.enabled" to true in your config.'),warn("══════════════════════════════════════════════════════════════"),warn("");let delegationHandler=createDelegationTrackerHook(config3,guardrailsConfig.enabled),authorityConfig=AuthorityConfigSchema.parse(config3.authority??{}),worktreeDirOverride=resolveWorktreeIsolationConfig(config3).worktree_dir,worktreeBaseDirOverrides=worktreeDirOverride?[worktreeDirOverride]:[],guardrailsHooks=createGuardrailsHooks(ctx.directory,void 0,guardrailsConfig,authorityConfig,worktreeBaseDirOverrides,resolveIncomingAgentModel),durableBackgroundAdvisoryMessagesTransform=async(input,output)=>{let mctx=resolveMessageTransformContext(output);if(!mctx.sessionID){await guardrailsHooks.messagesTransform(input,output);return}let observedTexts=(output.messages??[]).flatMap((message)=>(message.parts??[]).filter((part)=>part.type==="text"&&typeof part.text==="string").map((part)=>part.text));await backgroundCompletionObserver.ackObservedAdvisories(mctx.sessionID,observedTexts);let prepared=await backgroundCompletionObserver.prepareAdvisories(mctx.sessionID);if(!prepared){await guardrailsHooks.messagesTransform(input,output);return}let session=swarmState.agentSessions.get(mctx.sessionID),pendingBefore=session?[...session.pendingAdvisoryMessages??[]]:void 0,guardrailsSnapshot=session?{resumeModelAdvisoryDone:session.resumeModelAdvisoryDone,configModelAdvisoryDone:session.configModelAdvisoryDone,lastObservedModel:session.lastObservedModel,lastObservedProviderID:session.lastObservedProviderID,lastProviderRecoveryFingerprint:session.lastProviderRecoveryFingerprint,loopWarningPending:session.loopWarningPending}:void 0,messagesBefore=output.messages?structuredClone(output.messages):void 0;try{if(session)for(let message of prepared.messages)pushAdvisory(session,message);if(await guardrailsHooks.messagesTransform(input,output),!prepared.messages.every((message)=>(output.messages??[]).some((candidate2)=>(candidate2.parts??[]).some((part)=>part.type==="text"&&typeof part.text==="string"&&part.text.includes(message)))))throw Error("durable background advisory insertion failed")}catch(error93){if(session&&pendingBefore)session.pendingAdvisoryMessages=pendingBefore;if(session&&guardrailsSnapshot)session.resumeModelAdvisoryDone=guardrailsSnapshot.resumeModelAdvisoryDone,session.configModelAdvisoryDone=guardrailsSnapshot.configModelAdvisoryDone,session.lastObservedModel=guardrailsSnapshot.lastObservedModel,session.lastObservedProviderID=guardrailsSnapshot.lastObservedProviderID,session.lastProviderRecoveryFingerprint=guardrailsSnapshot.lastProviderRecoveryFingerprint,session.loopWarningPending=guardrailsSnapshot.loopWarningPending;if(Array.isArray(output.messages)&&messagesBefore){output.messages.length=0;for(let message of messagesBefore)output.messages.push(message)}else output.messages=messagesBefore;await backgroundCompletionObserver.releaseAdvisories(mctx.sessionID,prepared),warn(`[background] advisory injection rolled back for ${mctx.sessionID}: ${error93 instanceof Error?error93.message:String(error93)}`)}},fullAutoInterceptHook=createFullAutoInterceptHook(config3,ctx.directory),fullAutoPermissionHook=createFullAutoPermissionHook({config:config3,directory:ctx.directory}),fullAutoInputProbeHook=createFullAutoInputProbeHook({config:config3,directory:ctx.directory}),fullAutoDelegationHook=createFullAutoDelegationHook({config:config3,directory:ctx.directory}),ccCommandInterceptHook=createCcCommandInterceptHook({}),issueTraceHook=createIssueTraceHook(config3,ctx.directory),watchdogConfig=WatchdogConfigSchema.parse(config3.watchdog??{}),scopeGuardHook=createScopeGuardHook({enabled:watchdogConfig.scope_guard,skip_in_turbo:watchdogConfig.skip_in_turbo},ctx.directory,advisoryInjector),prWorkflowResponseGate=createPrWorkflowResponseGate({directory:ctx.directory,client:ctx.client}),prWorkflowSessionResolver=createPrWorkflowSessionResolver({directory:ctx.directory,client:ctx.client}),delegationLedgerHook=createDelegationLedgerHook({enabled:watchdogConfig.delegation_ledger},ctx.directory,advisoryInjector),initOrphanRecoveryAdvisoryHook=createInitOrphanRecoveryAdvisoryHook(ctx.directory),selfReviewConfig=SelfReviewConfigSchema.parse(config3.self_review??{}),selfReviewHook=createSelfReviewHook({enabled:selfReviewConfig.enabled,skip_in_turbo:selfReviewConfig.skip_in_turbo},advisoryInjector),autoReviewHook=createAutoReviewHook({config:autoReviewConfig,directory:ctx.directory,dispatcher:reviewModelDispatcher,generatedAgentNames:instanceGeneratedAgentNames,agentModelRegistry:reviewAgentModelRegistry,getActiveAgentName:getActiveReviewAgentName,injectAdvisory:advisoryInjector}),summaryConfig=SummaryConfigSchema.parse(config3.summaries??{}),toolSummarizerHook=createToolSummarizerHook(summaryConfig,ctx.directory),knowledgeConfigBase=config3.knowledge??{},knowledgeConfig=KnowledgeConfigSchema.parse(knowledgeConfigBase),skillImproverConfig=SkillImproverConfigSchema.parse(config3.skill_improver??{}),skillPropagationConfig=SkillPropagationConfigSchema.parse(config3.skillPropagation??{});if(skillImproverConfig.enabled&&skillImproverConfig.trigger==="scheduled")postResolutionTasks.push(()=>{return Promise.resolve().then(() => (init_skill_consolidation(),exports_skill_consolidation)).then(({runSkillConsolidationFireAndForget:runSkillConsolidationFireAndForget2})=>{runSkillConsolidationFireAndForget2({directory:ctx.directory,config:skillImproverConfig,source:"startup",enrichmentQuota:{maxCalls:knowledgeConfig.enrichment.max_calls_per_day,window:knowledgeConfig.enrichment.quota_window},evaluateDrafts:!0},void 0,(err2)=>{let msg=err2 instanceof Error?err2.message:String(err2);log("scheduled skill consolidation failed (non-fatal)",{error:msg})})}).catch((err2)=>{let msg=err2 instanceof Error?err2.message:String(err2);log("failed to schedule skill consolidation (non-fatal)",{error:msg})})});let knowledgeCuratorHook=knowledgeConfig.enabled?createKnowledgeCuratorHook(ctx.directory,knowledgeConfig,{llmDelegateFactory:(sessionID)=>createCuratorLLMDelegate(ctx.directory,"phase",sessionID),enrichmentQuota:{maxCalls:knowledgeConfig.enrichment.max_calls_per_day,window:knowledgeConfig.enrichment.quota_window}}):void 0,hivePromoterHook=knowledgeConfig.enabled&&knowledgeConfig.hive_enabled?createHivePromoterHook(ctx.directory,knowledgeConfig):void 0,knowledgeInjectorHook=knowledgeConfig.enabled?createKnowledgeInjectorHook(ctx.directory,knowledgeConfig,config3.context_budget?.model_limits??{},config3.context_budget?.unified_injection_tokens):void 0,steeringConsumedHook=createSteeringConsumedHook(ctx.directory),coChangeSuggesterHook=createCoChangeSuggesterHook(ctx.directory),darkMatterDetectorHook=createDarkMatterDetectorHook(ctx.directory),slopDetectorHook=config3.slop_detector?.enabled!==!1?createSlopDetectorHook(config3.slop_detector??{enabled:!0,classThreshold:3,commentStripThreshold:5,diffLineThreshold:200,importHygieneThreshold:2},ctx.directory,(sessionId,message)=>{let s=swarmState.agentSessions.get(sessionId);if(s)pushAdvisory(s,message)}):null,incrementalVerifyHook=config3.incremental_verify?.enabled!==!1?createIncrementalVerifyHook(config3.incremental_verify??{enabled:!0,command:null,timeoutMs:30000,triggerAgents:["coder"]},ctx.directory,(sessionId,message)=>{let s=swarmState.agentSessions.get(sessionId);if(s)pushAdvisory(s,message)}):null,compactionServiceHook=config3.compaction_service?.enabled!==!1?createCompactionService(config3.compaction_service??{enabled:!0,observationThreshold:40,reflectionThreshold:60,emergencyThreshold:80,preserveLastNTurns:5},ctx.directory,(sessionId,message)=>{let s=swarmState.agentSessions.get(sessionId);if(s)pushAdvisory(s,message)}):null,snapshotWriterHook=createSnapshotWriterHook(ctx.directory),automationConfig=AutomationConfigSchema.parse(config3.automation??{}),automationManager,preflightTriggerManager,statusArtifact,prMonitorWorker=null,planSyncWorker=null;if(automationConfig.mode!=="manual"){automationManager=createAutomationManager(automationConfig),automationManager.start();let{PreflightTriggerManager:PTM}=await Promise.resolve().then(() => (init_trigger(),exports_trigger));preflightTriggerManager=new PTM(automationConfig);let{AutomationStatusArtifact:ASA}=await Promise.resolve().then(() => (init_status_artifact(),exports_status_artifact)),swarmDir=path329.resolve(ctx.directory,".swarm");if(statusArtifact=new ASA(swarmDir),statusArtifact.updateConfig(automationConfig.mode,automationConfig.capabilities),automationConfig.capabilities?.evidence_auto_summaries===!0){let{createEvidenceSummaryIntegration:createEvidenceSummaryIntegration2}=await Promise.resolve().then(() => (init_evidence_summary_integration(),exports_evidence_summary_integration));createEvidenceSummaryIntegration2({automationConfig,directory:ctx.directory,projectDir:ctx.directory,summaryFilename:"evidence-summary.json"}),log("Evidence summary integration initialized",{directory:ctx.directory})}if(automationConfig.capabilities?.phase_preflight===!0){let{createPreflightIntegration:createPreflightIntegration2}=await Promise.resolve().then(() => (init_preflight_integration(),exports_preflight_integration));try{let{manager}=createPreflightIntegration2({automationConfig,directory:ctx.directory,swarmDir});preflightTriggerManager=manager,log("Preflight integration initialized",{directory:ctx.directory})}catch(err2){log("Preflight integration failed to initialize (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})}}if(automationConfig.capabilities?.plan_sync===!0)try{planSyncWorker=new PlanSyncWorker({directory:ctx.directory}),planSyncWorker.start(),log("PlanSyncWorker initialized",{directory:ctx.directory})}catch(err2){log("PlanSyncWorker failed to initialize (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})}log("Automation framework initialized",{mode:automationConfig.mode,enabled:automationManager?.isEnabled(),running:automationManager?.isActive(),preflightEnabled:preflightTriggerManager?.isEnabled()})}let prMonitorConfig=PrMonitorConfigSchema.parse(config3.pr_monitor??{});function ensurePrMonitorWorkerRunning(directory){try{if(!prMonitorConfig.enabled)return;if(!prMonitorWorker)prMonitorWorker=new PrMonitorWorker({directory,config:prMonitorConfig});if(!prMonitorWorker.isRunning())prMonitorWorker.start(),log("PR Monitor Worker started",{directory})}catch(err2){error48("[pr-monitor] Worker failed to start (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})}}setOnSubscriptionCreated((directory,_record3)=>{ensurePrMonitorWorkerRunning(directory)});let prEventCleanup=null,prEventDelivery=null;if(prMonitorConfig.enabled){try{let{registerPrEventSubscribers:registerPrEventSubscribers2}=await Promise.resolve().then(() => (init_pr_event_subscribers(),exports_pr_event_subscribers));prEventCleanup=registerPrEventSubscribers2({directory:ctx.directory,config:prMonitorConfig})}catch(err2){log("[pr-monitor] Failed to register PR event subscribers (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})}if(prMonitorConfig.event_delivery==="prompt")try{let deliveryModule=await Promise.resolve().then(() => (init_pr_event_delivery(),exports_pr_event_delivery));deliveryModule.registerPrEventDelivery({client:ctx.client,directory:ctx.directory,config:prMonitorConfig}),prEventDelivery={noteSessionIdle:deliveryModule.noteSessionIdle,unregisterPrEventDelivery:deliveryModule.unregisterPrEventDelivery}}catch(err2){log("[pr-monitor] Failed to register wake delivery (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})}}let prAutoSubscribeHook=createPrAutoSubscribeHook(ctx.directory,prMonitorConfig);if(prMonitorConfig.enabled)postResolutionTasks.push(()=>{listActive(ctx.directory).then((active)=>{if(active.length>0)ensurePrMonitorWorkerRunning(ctx.directory)}).catch((err2)=>{error48("[pr-monitor] Startup scan failed (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})})});let cleanupAutomation=()=>{automationManager?.stop(),prMonitorWorker?.stop(),planSyncWorker?.stop(),prEventCleanup?.(),prEventDelivery?.unregisterPrEventDelivery()};if(process.on("exit",cleanupAutomation),shouldRunOnStartup(automationConfig)){let enableAutofix=automationConfig.capabilities?.config_doctor_autofix===!0;postResolutionTasks.push(()=>{return Promise.resolve().then(() => (init_config_doctor(),exports_config_doctor)).then(({runConfigDoctorWithFixes:runConfigDoctorWithFixes2})=>{return runConfigDoctorWithFixes2(ctx.directory,config3,enableAutofix).then((doctorResult)=>{if(doctorResult.result.findings.length>0){log("Config Doctor ran on startup",{findings:doctorResult.result.findings.length,errors:doctorResult.result.summary.error,warnings:doctorResult.result.summary.warn,appliedFixes:doctorResult.appliedFixes.length,autofixEnabled:enableAutofix});try{let autoFixableCount=doctorResult.result.findings.filter((f)=>f.autoFixable).length,appliedCount=doctorResult.appliedFixes.length;if(!enableAutofix&&autoFixableCount>0){let msg=`[opencode-swarm] Config Doctor found ${autoFixableCount} auto-fixable issue(s). Run /swarm config doctor --fix to apply.`;if(!config3.quiet)console.warn(msg);else addDeferredWarning(msg)}else if(enableAutofix){let parts=[];if(appliedCount>0)parts.push(`applied ${appliedCount} fix(es) automatically`);let unapplied=Math.max(0,autoFixableCount-appliedCount);if(unapplied>0)parts.push(`${unapplied} auto-fixable issue(s) need explicit review — run /swarm config doctor --fix`);if(parts.length>0){let msg=`[opencode-swarm] Config Doctor: ${parts.join("; ")}.`;if(!config3.quiet)console.warn(msg);else addDeferredWarning(msg)}}}catch{}}}).catch((err2)=>{log("Config Doctor error (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})})})})}return log("Plugin initialized",{maxIterations:config3.max_iterations,agentCount:Object.keys(agents).length,hooks:{pipeline:!!pipelineHook["experimental.chat.messages.transform"],systemEnhancer:!!systemEnhancerHook["experimental.chat.system.transform"],compaction:!!compactionHook["experimental.session.compacting"],contextBudget:!!contextBudgetHandler,commands:!0,agentActivity:config3.hooks?.agent_activity!==!1,delegationTracker:config3.hooks?.delegation_tracker===!0,guardrails:guardrailsConfig.enabled,toolSummarizer:summaryConfig.enabled,knowledge:knowledgeConfig.enabled},automation:{mode:automationConfig.mode,capabilities:automationConfig.capabilities}}),{name:"opencode-swarm",agent:agents,tool:buildPluginToolObject(agentDefinitionMap,config3,evaluationModelDispatcher,reviewModelDispatcher,instanceGeneratedAgentNames,reviewAgentModelRegistry,getActiveReviewAgentName),event:async(input)=>{try{rememberAssistantUsageEvent(input);let lifecycleEvent=input.event;if(lifecycleEvent?.type==="message.part.updated"){let part=lifecycleEvent.properties?.part,metadata=part?.state?.metadata,partTool=typeof part?.tool==="string"?normalizeToolName(part.tool)?.toLowerCase():void 0,eventParentSessionID=typeof part?.sessionID==="string"&&part.sessionID.trim()!==""?part.sessionID:void 0,eventChildSessionID=typeof metadata?.sessionId==="string"&&metadata.sessionId.trim()!==""?metadata.sessionId:void 0;if(part?.type==="tool"&&partTool==="task"&&typeof part.callID==="string"&&part.callID.trim()!==""&&eventParentSessionID!==void 0&&eventChildSessionID!==void 0&&eventParentSessionID!==eventChildSessionID){await delegationGateHooks.taskMetadata({callID:part.callID,parentSessionID:eventParentSessionID,childSessionID:eventChildSessionID}),bindPendingTaskModelRouteChild({parentSessionID:eventParentSessionID,callID:part.callID,childSessionID:eventChildSessionID});let fullAutoRunState=loadFullAutoRunState(ctx.directory,eventParentSessionID);if(fullAutoRunState?.runGeneration!==void 0)bindFullAutoSevereChildSession({childSessionID:eventChildSessionID,parentSessionID:eventParentSessionID,parentCallID:part.callID,generation:fullAutoRunState.runGeneration})}}if(lifecycleEvent?.type==="session.error"){let properties=lifecycleEvent.properties,childSessionID=typeof properties?.sessionID==="string"?properties.sessionID:typeof properties?.sessionId==="string"?properties.sessionId:typeof properties?.info==="object"&&properties.info&&typeof properties.info.id==="string"?properties.info.id??"":"",route=childSessionID?resolveTaskRouteForChildSession(childSessionID):void 0,routeModel=resolveTaskRouteModelChain(route?swarmState.activeAgent.get(childSessionID)??swarmState.agentSessions.get(childSessionID)?.agentName??route.role:swarmState.activeAgent.get(childSessionID)??swarmState.agentSessions.get(childSessionID)?.agentName),errorSignal=extractSessionErrorSignal(properties);if(route&&routeModel&&errorSignal&&isRetryableProviderFailure(classifyProviderFailure(errorSignal)))advancePendingTaskModelRoute({childSessionID,role:route.role,actionDigest:route.actionDigest,primaryModel:routeModel.primaryModel,fallbackModels:routeModel.fallbackModels})}let lifecycleStatus=lifecycleEvent?.properties?.status;if(lifecycleEvent?.type==="session.deleted"||lifecycleEvent?.type==="session.removed"||lifecycleEvent?.type==="session.idle"||lifecycleEvent?.type==="session.error"||lifecycleEvent?.type==="session.status"&&(lifecycleStatus==="idle"||typeof lifecycleStatus==="object"&&(lifecycleStatus.type==="idle"||lifecycleStatus.type==="error"))){let properties=lifecycleEvent.properties,sessionID=properties?.sessionID??properties?.sessionId??properties?.info?.sessionID??properties?.info?.id??properties?.id;if(sessionID){if(delegationGateHooks.sessionEnded(sessionID,lifecycleEvent.type==="session.deleted"||lifecycleEvent.type==="session.removed"),lifecycleEvent.type==="session.deleted"||lifecycleEvent.type==="session.removed")clearPendingTaskModelRoutesForSession(sessionID),clearSessionActionCircuits(sessionID),clearFullAutoSevereSession(sessionID);if(backgroundSubagentsEnabled)try{await maintainBackgroundDelegationsOnSessionEvent()}catch{}}}if(prWorkflowSessionResolver.observeEvent(input),await prWorkflowResponseGate.event(input),prEventDelivery){let evt=input.event,idleSessionID=evt?.properties?.sessionID??evt?.data?.sessionID;if(evt?.type==="session.idle"&&typeof idleSessionID==="string")prEventDelivery.noteSessionIdle(idleSessionID)}await backgroundCompletionObserver.event(input)}catch(err2){warn(`[swarm] event hook error: ${err2 instanceof Error?err2.message:String(err2)}`)}},config:async(opencodeConfig)=>{let isObjectRecord=(value)=>typeof value==="object"&&value!==null,pluginConfig=opencodeConfig;if(!isObjectRecord(pluginConfig.agent))pluginConfig.agent={};let agentConfig=pluginConfig.agent;Object.assign(agentConfig,agents);try{applyLanePermissions(opencodeConfig,ctx.directory,config3?.worktree?.lane_permissions??"scoped_allow")}catch(err2){addDeferredWarning(`[swarm] lane permission scoping failed: ${err2 instanceof Error?err2.message:String(err2)}`)}let autoSelect=config3?.auto_select_architect;if(autoSelect)if(Object.keys(agents).some((name)=>stripKnownSwarmPrefix(name)==="architect")){for(let builtin of["build","plan"]){let existing=agentConfig[builtin];if(isObjectRecord(existing)&&existing.disable===!0)continue;agentConfig[builtin]={...isObjectRecord(existing)?existing:{},disable:!0}}if(autoSelect===!0){let primaryArchitects=Object.entries(agents).filter(([name,cfg])=>stripKnownSwarmPrefix(name)==="architect"&&isObjectRecord(cfg)&&cfg.mode==="primary");if(primaryArchitects.length>1){let names=primaryArchitects.map(([n])=>n).join(", ");addDeferredWarning(`[swarm] auto_select_architect is true but ${primaryArchitects.length} architect agents are primary (${names}). Consider setting auto_select_architect to a specific agent name.`)}}if(typeof autoSelect==="string"&&autoSelect!==""){let targetName=autoSelect;if(Object.hasOwn(agents,targetName)&&stripKnownSwarmPrefix(targetName)==="architect"){for(let[name,cfg]of Object.entries(agents))if(stripKnownSwarmPrefix(name)==="architect"&&name!==targetName)agentConfig[name]={...isObjectRecord(cfg)?cfg:{},mode:"subagent"};let targetExisting=agentConfig[targetName],targetAgent=agents[targetName];agentConfig[targetName]={...isObjectRecord(targetExisting)?targetExisting:{},...isObjectRecord(targetAgent)?targetAgent:{},mode:"primary"}}else addDeferredWarning(`[swarm] auto_select_architect is set to "${targetName}" but that is not a known architect agent. No architect demotion applied.`)}}else addDeferredWarning("[swarm] auto_select_architect is enabled but no architect agents were found in the generated set. The option has no effect.");let shortcutDescription=(cmd)=>{let entry=COMMAND_REGISTRY[cmd];if(!entry?.description)return`Use /swarm ${cmd}`;let desc=entry.description.charAt(0).toLowerCase()+entry.description.slice(1);return`Use /swarm ${cmd} to ${desc}`};opencodeConfig.command={...opencodeConfig.command||{},swarm:{template:"/swarm $ARGUMENTS",description:(()=>{return`Swarm management commands: /swarm [${VALID_COMMANDS.filter((cmd)=>{let entry=COMMAND_REGISTRY[cmd];return!entry.aliasOf&&!entry.deprecated&&!entry.subcommandOf}).join("|")}]`})()},"swarm-status":{template:"/swarm status",description:"Use /swarm status to show current swarm status and active phase"},"swarm-show-plan":{template:"/swarm show-plan $ARGUMENTS",description:"Use /swarm show-plan to view or filter the current execution plan"},"swarm-plan":{template:"/swarm plan $ARGUMENTS",description:"Deprecated alias for /swarm show-plan"},"swarm-agents":{template:"/swarm agents",description:"Use /swarm agents to list registered swarm agents"},"swarm-history":{template:"/swarm history",description:"Use /swarm history to show completed phases summary"},"swarm-config":{template:"/swarm config $ARGUMENTS",description:"Use /swarm config to show or validate configuration"},"swarm-evidence":{template:"/swarm evidence $ARGUMENTS",description:"Use /swarm evidence to view evidence bundles and summaries"},"swarm-handoff":{template:"/swarm handoff",description:"Use /swarm handoff to prepare handoff brief for switching models mid-task"},"swarm-archive":{template:"/swarm archive",description:"Use /swarm archive to archive old evidence bundles"},"swarm-diagnose":{template:"/swarm diagnose",description:"Use /swarm diagnose to run health checks on swarm state"},"swarm-diagnosis":{template:"/swarm diagnosis",description:"Use /swarm diagnosis to run health checks on swarm state"},"swarm-preflight":{template:"/swarm preflight",description:"Use /swarm preflight to run preflight automation checks"},"swarm-sync-plan":{template:"/swarm sync-plan",description:"Use /swarm sync-plan to sync plan.json with plan.md"},"swarm-benchmark":{template:"/swarm benchmark",description:"Use /swarm benchmark to show performance metrics"},"swarm-gate-audit":{template:"/swarm gate-audit $ARGUMENTS",description:"Use /swarm gate-audit to run the bounded Tier-1 production gate matrix"},"swarm-gate-stats":{template:"/swarm gate-stats $ARGUMENTS",description:"Use /swarm gate-stats to summarize stored gate-audit evidence"},"swarm-skill-opt":{template:"/swarm skill-opt $ARGUMENTS",description:"Use /swarm skill-opt to govern skill optimization (plan|run|status|diff|approve|reject|rollback|history)"},"swarm-costs":{template:"/swarm costs $ARGUMENTS",description:"Use /swarm costs to show per-agent, task, gate, and retry token/cost totals"},"swarm-export":{template:"/swarm export",description:"Use /swarm export to export plan and context as JSON"},"swarm-reset":{template:"/swarm reset --confirm",description:"Use /swarm reset --confirm to clear swarm state (requires --confirm)"},"swarm-rollback":{template:"/swarm rollback $ARGUMENTS",description:"Use /swarm rollback to restore swarm state to a checkpoint"},"swarm-retrieve":{template:"/swarm retrieve $ARGUMENTS",description:"Use /swarm retrieve to retrieve full output from summary"},"swarm-clarify":{template:"/swarm clarify $ARGUMENTS",description:"Use /swarm clarify to clarify and refine a feature specification"},"swarm-analyze":{template:"/swarm analyze",description:"Use /swarm analyze to analyze spec vs plan for coverage gaps"},"swarm-specify":{template:"/swarm specify $ARGUMENTS",description:"Use /swarm specify to generate or import a feature specification"},"swarm-brainstorm":{template:"/swarm brainstorm $ARGUMENTS",description:"Use /swarm brainstorm to enter the architect MODE: BRAINSTORM planning workflow"},"swarm-loop":{template:"/swarm loop $ARGUMENTS",description:"Use /swarm loop <objective> to run a compound-engineering loop: brainstorm → plan → build → review → improve, iterating until done [--max-cycles 1..5] [--autonomy checkpoint|auto] [--depth standard|exhaustive] [--resume]"},"swarm-council":{template:"/swarm council $ARGUMENTS",description:"Use /swarm council <question> to convene a multi-model General Council deliberation (generalist / skeptic / domain expert) [--spec-review]"},"swarm-pr-review":{template:"/swarm pr-review $ARGUMENTS",description:"Use /swarm pr-review to launch deep PR review with multi-lane analysis"},"swarm-review":{template:"/swarm review $ARGUMENTS",description:"Use /swarm review to run the bounded whole-diff review engine for the selected local scope"},"swarm-pr-feedback":{template:"/swarm pr-feedback $ARGUMENTS",description:"Use /swarm pr-feedback to ingest and close known PR feedback (review comments, CI failures, conflicts) without a fresh broad review"},"swarm-abort-pr-workflow":{template:"/swarm abort-pr-workflow $ARGUMENTS",description:"Use /swarm abort-pr-workflow to clear a stuck PR_REVIEW/PR_FEEDBACK mechanical gate and stop the auto-resume loop (human-only escape hatch)"},"swarm-approve-plan-critic":{template:"/swarm approve-plan-critic $ARGUMENTS",description:"Use /swarm approve-plan-critic to record a MANUAL plan-critic approval that unblocks the ratchet-tighter critic_pre_plan execution gate when the critic already returned APPROVED but the snapshot was not recorded (human-only escape hatch)"},"swarm-ci-monitor":{template:"/swarm ci-monitor $ARGUMENTS",description:"Use /swarm ci-monitor to drive an already-reviewed, approved PR to green and merged (monitor CI, fix, merge)"},"swarm-pr-subscribe":{template:"/swarm pr subscribe $ARGUMENTS",description:shortcutDescription("pr subscribe")},"swarm-pr-unsubscribe":{template:"/swarm pr unsubscribe $ARGUMENTS",description:shortcutDescription("pr unsubscribe")},"swarm-pr-status":{template:"/swarm pr status",description:shortcutDescription("pr status")},"swarm-ci-simulate":{template:"/swarm ci-simulate $ARGUMENTS",description:shortcutDescription("ci-simulate")},"swarm-learning":{template:"/swarm learning",description:shortcutDescription("learning")},"swarm-post-mortem":{template:"/swarm post-mortem $ARGUMENTS",description:shortcutDescription("post-mortem")},"swarm-deep-dive":{template:"/swarm deep-dive $ARGUMENTS",description:"Use /swarm deep-dive to launch a read-only deep audit with parallel explorer waves, dual reviewers, and critic challenge"},"swarm-deep-research":{template:"/swarm deep-research $ARGUMENTS",description:"Use /swarm deep-research <question> to run a multi-source, fact-checked deep research pass and synthesize a cited report [--depth standard|exhaustive] [--max-researchers 1..6] [--rounds 1..4] [--brief]"},"swarm-codebase-review":{template:"/swarm codebase-review $ARGUMENTS",description:"Use /swarm codebase-review to launch codebase-review-swarm for a quote-grounded full-repo or large-subsystem audit"},"swarm-design-docs":{template:"/swarm design-docs $ARGUMENTS",description:"Use /swarm design-docs to generate or sync language-agnostic design docs for the project under build"},"swarm-sdd":{template:"/swarm sdd $ARGUMENTS",description:"Use /swarm sdd to inspect OpenSpec-compatible SDD artifacts"},"swarm-sdd-status":{template:"/swarm sdd status",description:"Use /swarm sdd status to show effective spec and OpenSpec artifact status"},"swarm-sdd-validate":{template:"/swarm sdd validate $ARGUMENTS",description:"Use /swarm sdd validate to validate OpenSpec-compatible SDD artifacts"},"swarm-sdd-project":{template:"/swarm sdd project $ARGUMENTS",description:"Use /swarm sdd project to materialize OpenSpec artifacts into .swarm/spec.md"},"swarm-issue":{template:"/swarm issue $ARGUMENTS",description:"Use /swarm issue to ingest a GitHub issue into the swarm workflow"},"swarm-qa-gates":{template:"/swarm qa-gates $ARGUMENTS",description:"Use /swarm qa-gates to view or modify QA gate profile for the current plan"},"swarm-dark-matter":{template:"/swarm dark-matter",description:"Use /swarm dark-matter to detect hidden file couplings"},"swarm-knowledge":{template:"/swarm knowledge $ARGUMENTS",description:"Use /swarm knowledge for knowledge management (quarantine/restore/migrate)"},"swarm-memory":{template:"/swarm memory $ARGUMENTS",description:"Use /swarm memory for memory status, JSONL export/import, and SQLite migration"},"swarm-memory-status":{template:"/swarm memory status",description:"Use /swarm memory status to show provider and migration status"},"swarm-memory-export":{template:"/swarm memory export",description:"Use /swarm memory export to write current memory to JSONL"},"swarm-memory-import":{template:"/swarm memory import",description:"Use /swarm memory import to import legacy JSONL into SQLite"},"swarm-memory-migrate":{template:"/swarm memory migrate",description:"Use /swarm memory migrate to run the one-time SQLite migration"},"swarm-curate":{template:"/swarm curate",description:"Use /swarm curate to curate knowledge artifacts and entries"},"swarm-consolidate":{template:"/swarm consolidate $ARGUMENTS",description:"Use /swarm consolidate to run quota-bounded skill-improver consolidation"},"swarm-concurrency":{template:"/swarm concurrency $ARGUMENTS",description:"Use /swarm concurrency to manage runtime concurrency override for plan execution"},"swarm-turbo":{template:"/swarm turbo",description:"Use /swarm turbo to enable turbo mode for faster execution"},"swarm-epic":{template:"/swarm epic $ARGUMENTS",description:shortcutDescription("epic")},"swarm-coupling":{template:"/swarm coupling $ARGUMENTS",description:shortcutDescription("coupling")},"swarm-lanes":{template:"/swarm lanes",description:shortcutDescription("lanes")},"swarm-guardrail-explain":{template:"/swarm guardrail explain $ARGUMENTS",description:shortcutDescription("guardrail explain")},"swarm-guardrail-reset":{template:"/swarm guardrail reset $ARGUMENTS",description:shortcutDescription("guardrail reset")},"swarm-guardrail-log":{template:"/swarm guardrail-log $ARGUMENTS",description:shortcutDescription("guardrail-log")},"swarm-full-auto":{template:"/swarm full-auto $ARGUMENTS",description:"Toggle Full-Auto Mode for the active session [on|off]"},"swarm-auto-proceed":{template:"/swarm auto-proceed $ARGUMENTS",description:"Toggle auto-proceed mode for automatic phase advancement"},"swarm-write-retro":{template:"/swarm write-retro $ARGUMENTS",description:"Use /swarm write-retro to manually write a phase retrospective"},"swarm-reset-session":{template:"/swarm reset-session",description:"Use /swarm reset-session to clear session state and delegation chains"},"swarm-recover":{template:"/swarm recover $ARGUMENTS",description:"Use /swarm recover to settle wedged coder settlements [task_id] [--force]"},"swarm-simulate":{template:"/swarm simulate $ARGUMENTS",description:"Use /swarm simulate to run a simulated agent session"},"swarm-promote":{template:"/swarm promote $ARGUMENTS",description:"Use /swarm promote to promote knowledge entries to production"},"swarm-checkpoint":{template:"/swarm checkpoint $ARGUMENTS",description:"Use /swarm checkpoint to save or restore git checkpoints"},"swarm-config-doctor":{template:"/swarm config doctor",description:"Use /swarm config doctor to diagnose configuration issues"},"swarm-evidence-summary":{template:"/swarm evidence summary",description:"Use /swarm evidence summary to generate evidence summaries"},"swarm-finalize":{template:"/swarm finalize",description:"Use /swarm finalize to archive the swarm project and close active state"},"swarm-close":{template:"/swarm close",description:"Deprecated alias for /swarm finalize"},"swarm-acknowledge-spec-drift":{template:"/swarm acknowledge-spec-drift",description:"Use /swarm acknowledge-spec-drift to acknowledge spec drift and suppress further warnings"},"swarm-doctor-tools":{template:"/swarm doctor tools",description:"Use /swarm doctor tools to run tool registration coherence check"},"swarm-context-map-stats":{template:"/swarm context-map stats",description:shortcutDescription("context-map-stats")},"swarm-link":{template:"/swarm link $ARGUMENTS",description:"Use /swarm link to link this worktree to a shared knowledge store [name|status]"},"swarm-unlink":{template:"/swarm unlink $ARGUMENTS",description:"Use /swarm unlink to unlink this worktree from the shared knowledge store [--no-copy]"}},log("Config applied",{agents:Object.keys(agents),commands:["swarm"]})},"experimental.chat.messages.transform":composeHandlers(...[(_input,output)=>{if(process.env.DEBUG_SWARM)console.error("[DIAG] messagesTransform START");let mctx=resolveMessageTransformContext(output);if(mctx.sessionID){let archAgent=swarmState.activeAgent.get(mctx.sessionID),archSession=swarmState.agentSessions.get(mctx.sessionID),agentName=archAgent??archSession?.agentName??"";if(stripKnownSwarmPrefix(agentName)===ORCHESTRATOR_NAME)try{delegationLedgerHook.onArchitectResume(mctx.sessionID)}catch{}}return Promise.resolve()},pipelineHook["experimental.chat.messages.transform"],contextBudgetHandler,initOrphanRecoveryAdvisoryHook.messagesTransform,durableBackgroundAdvisoryMessagesTransform,fullAutoInterceptHook?.messagesTransform,ccCommandInterceptHook?.messagesTransform,delegationGateHooks.messagesTransform,issueTraceHook.messagesTransform,delegationSanitizerHook,memoryLifecycleHooks.messagesTransform,knowledgeInjectorHook,(_input,output)=>{try{let mctx=resolveMessageTransformContext(output);return knowledgeApplicationTransformScan(ctx.directory,output,mctx.sessionID)}catch{return Promise.resolve()}},(_input,output)=>{try{if(!skillPropagationConfig.enabled)return Promise.resolve();let mctx=resolveMessageTransformContext(output);return skillPropagationTransformScan(ctx.directory,output,mctx.sessionID,skillPropagationConfig)}catch{return Promise.resolve()}},(_input,output)=>{if(Array.isArray(output.messages))consolidateSystemMessagesInPlace(output.messages);if(process.env.DEBUG_SWARM)console.error("[DIAG] messagesTransform DONE");return Promise.resolve()}].filter((fn2)=>Boolean(fn2))),"experimental.text.complete":prWorkflowResponseGate.textComplete,"experimental.chat.system.transform":composeHandlers(...[async(_input,_output)=>{if(process.env.DEBUG_SWARM)console.error("[DIAG] systemTransform START")},systemEnhancerHook["experimental.chat.system.transform"],async(_input,_output)=>{if(process.env.DEBUG_SWARM)console.error("[DIAG] systemTransform enhancer DONE")},contextCapsuleInjectHook["experimental.chat.system.transform"],(input,_output)=>{try{let{sessionID}=input;if(!sessionID)return Promise.resolve();let lastTime=_heartbeatTimers.get(sessionID);if(Date.now()-(lastTime??0)>30000)_heartbeatTimers.set(sessionID,Date.now()),capSessionMap(_heartbeatTimers,MAX_TRACKED_HEARTBEAT_SESSIONS),telemetry.heartbeat(sessionID)}catch{}return Promise.resolve()},automationConfig.capabilities?.phase_preflight===!0&&preflightTriggerManager?createPhaseMonitorHook(ctx.directory,preflightTriggerManager,void 0,(sessionId)=>createCuratorLLMDelegate(ctx.directory,"init",sessionId)):knowledgeConfig.enabled?createPhaseMonitorHook(ctx.directory,void 0,void 0,(sessionId)=>createCuratorLLMDelegate(ctx.directory,"init",sessionId)):void 0,swarmCommandSystemRuleHook,roleFilterSystemHook["experimental.chat.system.transform"]].filter(Boolean)),"experimental.session.compacting":compactionHook["experimental.session.compacting"],"command.execute.before":safeHook(commandHandler),"tool.execute.before":async(input,output)=>{if(process.env.DEBUG_SWARM)console.error(`[DIAG] toolBefore tool=${normalizeToolName(input.tool)??input.tool} session=${input.sessionID}`);if(!swarmState.activeAgent.has(input.sessionID))swarmState.activeAgent.set(input.sessionID,ORCHESTRATOR_NAME);let session=swarmState.agentSessions.get(input.sessionID),activeAgent=swarmState.activeAgent.get(input.sessionID);if(session&&activeAgent&&activeAgent!==ORCHESTRATOR_NAME){if(stripKnownSwarmPrefix(activeAgent)!==ORCHESTRATOR_NAME){if(!session.delegationActive&&Date.now()-session.lastAgentEventTime>1e4)swarmState.activeAgent.set(input.sessionID,ORCHESTRATOR_NAME),ensureAgentSession(input.sessionID,ORCHESTRATOR_NAME)}}let failClosedRegionCompleted=!1;try{await guardrailsHooks.toolBefore(input,output),await scopeGuardHook.toolBefore(input,output);let prWorkflowControllerSessionID=await prWorkflowSessionResolver.resolve(input.sessionID),prWorkflowToolContext=resolveToolBeforeContext(input,output);await enforcePrWorkflowToolBefore(ctx.directory,prWorkflowControllerSessionID,normalizeToolName(input.tool)??input.tool,prWorkflowToolContext.args??void 0,instanceGeneratedAgentNames),await delegationGateHooks.toolBefore(input,output),await fullAutoDelegationHook.toolBefore(input,output),await fullAutoPermissionHook.toolBefore(input,output),await knowledgeApplicationGateBefore(ctx.directory,{tool:input.tool,agent:resolveToolBeforeContext(input,output).agent,sessionID:input.sessionID},KnowledgeApplicationConfigSchema.parse(config3.knowledge_application??{}));let skillResult=await skillPropagationGateBefore(ctx.directory,{tool:input.tool,agent:resolveToolBeforeContext(input,output).agent,sessionID:input.sessionID,args:resolveToolBeforeContext(input,output).args??void 0},skillPropagationConfig);if(skillResult.blocked)throw Error(skillResult.reason??"Blocked by skill propagation gate");if(skillResult.reason){let skillSession=ensureAgentSession(input.sessionID,swarmState.activeAgent.get(input.sessionID)??ORCHESTRATOR_NAME);pushAdvisory(skillSession,skillResult.reason)}let toolBeforeCtx=resolveToolBeforeContext(input,output),toolBeforeArgs=toolBeforeCtx.args??{};if(injectSkillsIntoDelegation(ctx.directory,toolBeforeArgs,skillResult.recommendedSkills,stripKnownSwarmPrefix(parseDelegationArgs(toolBeforeArgs)?.targetAgent??"")||toolBeforeCtx.agent,input.sessionID,{quiet:config3.quiet}),failClosedRegionCompleted=!0,knowledgeConfig.enabled)await injectDelegateDirectivesBefore(ctx.directory,{tool:input.tool,agent:toolBeforeCtx.agent,sessionID:input.sessionID,args:toolBeforeArgs},knowledgeConfig);setStoredInputArgs(input.callID,output.args);let pressurePct=getSessionBudgetPct(input.sessionID);if(pressurePct>=50){let pressureSession=ensureAgentSession(input.sessionID,swarmState.activeAgent.get(input.sessionID)??ORCHESTRATOR_NAME);if(!pressureSession.contextPressureWarningSent)pressureSession.contextPressureWarningSent=!0,pushAdvisory(pressureSession,`CONTEXT PRESSURE: ${pressurePct.toFixed(1)}% of context window used. Prioritize completing the current task before starting new work.`)}if(autoReviewConfig.enabled)await beginApprovedReviewerScopeLifecycle({directory:ctx.directory,tool:input.tool,args:toolBeforeArgs,parentSessionID:input.sessionID,callID:input.callID,maxBytes:autoReviewConfig.max_diff_kb*1024});if(await safeHook(activityHooks.toolBefore)(input,output),await reserveApprovedPhaseParticipation({directory:ctx.directory,tool:input.tool,parentSessionId:input.sessionID,callId:input.callID,args:toolBeforeArgs,policy:config3.phase_complete}),(normalizeToolName(input.tool)??input.tool)==="Task"&&typeof toolBeforeArgs.subagent_type==="string"&&toolBeforeArgs.subagent_type.trim()!==""){let actionIdentity2=createActionIdentity({tool:input.tool,args:toolBeforeArgs});registerPendingTaskModelRoute({parentSessionID:input.sessionID,invocationID:String(getAgentSession(input.sessionID)?.activeInvocationId??0),callID:input.callID,role:stripKnownSwarmPrefix(toolBeforeArgs.subagent_type),actionDigest:actionIdentity2.digest,swarmID:actionIdentity2.swarm??void 0})}resetGateDenialStreaks(input.sessionID,input.tool,toolBeforeArgs);{let beforeToolNormalized=normalizeToolName(input.tool)??input.tool;if(beforeToolNormalized==="Task"||beforeToolNormalized==="task"){let delegatedAgent=typeof toolBeforeArgs.subagent_type==="string"&&toolBeforeArgs.subagent_type.length>0?toolBeforeArgs.subagent_type:swarmState.activeAgent.get(input.sessionID)??"unknown",delegationTaskId=swarmState.agentSessions.get(input.sessionID)?.currentTaskId??"";_delegationTelemetryByCallID.set(input.callID,{agentName:delegatedAgent,taskId:delegationTaskId}),capSessionMap(_delegationTelemetryByCallID,MAX_TRACKED_DELEGATION_TELEMETRY),telemetry.delegationBegin(input.sessionID,delegatedAgent,delegationTaskId)}}}catch(err2){if(!failClosedRegionCompleted){let deniedMessage=err2&&typeof err2==="object"&&typeof err2.message==="string"?err2.message:null,deniedArgs;try{deniedArgs=resolveToolBeforeContext(input,output).args??void 0}catch{deniedArgs=void 0}if(deniedMessage!==null&&!isAbortLikeError(err2))try{await recordDeniedToolCall(input.sessionID,{tool:input.tool,callID:input.callID,args:deniedArgs},deniedMessage,ctx.directory,{maxLines:1000})}catch{}noteGateDenial(input.sessionID,input.tool,err2,{enabled:guardrailsConfig.enabled,warnThreshold:guardrailsConfig.gate_denial_warn_threshold,stopThreshold:guardrailsConfig.gate_denial_stop_threshold},deniedArgs)}if(normalizeToolName(input.tool)==="Task"||normalizeToolName(input.tool)==="task")try{await delegationGateHooks.abortDeniedSettlementForCall(input.callID)}catch{}throw err2}},"tool.execute.after":async(input,output)=>{let _dbg=!!process.env.DEBUG_SWARM,_toolName=normalizeToolName(input.tool)??input.tool;if(_dbg)console.error(`[DIAG] toolAfter START tool=${_toolName} session=${input.sessionID}`);let normalizedTool=normalizeToolName(input.tool),isTaskTool8=normalizedTool==="Task"||normalizedTool==="task",afterCtx=resolveToolAfterContext(input);if(autoReviewConfig.enabled&&isTaskTool8)await completeReviewerScopeLifecycle({directory:ctx.directory,tool:input.tool,args:afterCtx.args,output,parentSessionID:input.sessionID,callID:input.callID});let hookChain=async()=>{if(await activityHooks.toolAfter(input,output),_dbg)console.error(`[DIAG] toolAfter activity done tool=${_toolName}`);if(await safeHook(trajectoryLoggerHook.toolAfter)(input,output),_dbg)console.error(`[DIAG] toolAfter trajectoryLogger done tool=${_toolName}`);if(knowledgeConfig.enabled)await safeHook(()=>collectDelegateAcksAfter(ctx.directory,{tool:input.tool,sessionID:input.sessionID,args:afterCtx.args},output))(input,output),await safeHook(()=>collectReviewerVerdictsAfter(ctx.directory,{tool:input.tool,sessionID:input.sessionID,args:afterCtx.args},output))(input,output),await safeHook(()=>microReflectorAfter(ctx.directory,input,output,createCuratorLLMDelegate(ctx.directory,"phase",input.sessionID),{maxCalls:knowledgeConfig.enrichment.max_calls_per_day,window:knowledgeConfig.enrichment.quota_window},{enabled:learningConfig.realtime_admission.enabled,maxQueueSize:learningConfig.realtime_admission.max_queue_size}))(input,output);if(await safeHook(async()=>{let summary=await realtimeAdmissionAfter(ctx.directory,{tool:input.tool,sessionID:input.sessionID},learningConfig.realtime_admission,async()=>{let plan=await loadPlan(ctx.directory).catch(()=>null);return{knowledgeConfig,projectName:plan?.title??"unknown",phaseNumber:plan?.current_phase??1,sessionID:input.sessionID,llmDelegate:createCuratorLLMDelegate(ctx.directory,"phase",input.sessionID),onKnowledgeChanged:bumpKnowledgeGeneration}});if(summary)log("realtime admission drain",{sessionID:input.sessionID,...summary})})(input,output),await safeHook(async()=>{await collectReviewerReceiptAfter(ctx.directory,{tool:input.tool,sessionID:input.sessionID,callID:input.callID,args:afterCtx.args},output,{dispatcher:reviewModelDispatcher,config:autoReviewConfig,generatedAgentNames:instanceGeneratedAgentNames,agentModelRegistry:reviewAgentModelRegistry,injectAdvisory:advisoryInjector,validationScheduler:findingValidationScheduler})})(input,output),await safeHook(autoReviewHook.toolAfter)(input,afterCtx),await safeHook(prmHook.toolAfter)(input,output),await guardrailsHooks.toolAfter(input,output),_dbg)console.error(`[DIAG] toolAfter guardrails done tool=${_toolName}`);if(await safeHook(delegationLedgerHook.toolAfter)(input,output),_dbg)console.error(`[DIAG] toolAfter ledger done tool=${_toolName}`);if(await safeHook(selfReviewHook.toolAfter)(input,output),_dbg)console.error(`[DIAG] toolAfter selfReview done tool=${_toolName}`);if(await safeHook(memoryLifecycleHooks.toolAfter)(input,output),_dbg)console.error(`[DIAG] toolAfter memory done tool=${_toolName}`);if(await safeHook(delegationGateHooks.toolAfter)(input,output),await safeHook(async()=>{await observePhaseParticipationToolResult({directory:ctx.directory,tool:input.tool,parentSessionId:input.sessionID,callId:input.callID,output})})(input,output),_dbg)console.error(`[DIAG] toolAfter delegationGate done tool=${_toolName}`);if(await safeHook(fullAutoInputProbeHook.toolAfter)(input,output),await safeHook(fullAutoDelegationHook.toolAfter)(input,output),await safeHook(prAutoSubscribeHook.toolAfter)(input,output),isTaskTool8&&typeof output.output==="string")try{let adversarialMatches=detectAdversarialPatterns(output.output);if(adversarialMatches.length>0){let sessionId=input.sessionID,session=swarmState.agentSessions.get(sessionId);if(session)pushAdvisory(session,`ADVERSARIAL PATTERN DETECTED: ${adversarialMatches.map((p)=>p.pattern).join(", ")}. Review agent output for potential prompt injection or gate bypass.`);if("adversarialPatternDetected"in telemetry)telemetry.adversarialPatternDetected(input.sessionID,adversarialMatches)}}catch{}try{recordToolCall(normalizedTool,resolveToolAfterContext(input).args,input.sessionID)}catch{}try{let spiralMatch=await detectDebuggingSpiral(ctx.directory,input.sessionID);if(spiralMatch){let taskId=swarmState.agentSessions.get(input.sessionID)?.currentTaskId??`session-${input.sessionID.slice(0,12)}`,spiralResult=await handleDebuggingSpiral(spiralMatch,taskId,ctx.directory),session=swarmState.agentSessions.get(input.sessionID);if(session)pushAdvisory(session,spiralResult.message)}}catch{}if(knowledgeCuratorHook)await safeHook(knowledgeCuratorHook)(input,output);if(hivePromoterHook)await safeHook(hivePromoterHook)(input,output);if(_dbg)console.error(`[DIAG] toolAfter knowledge done tool=${_toolName}`);if(await safeHook(steeringConsumedHook)(input,output),await safeHook(coChangeSuggesterHook)(input,output),await safeHook(darkMatterDetectorHook)(input,output),_dbg)console.error(`[DIAG] toolAfter intelligence done tool=${_toolName}`);if(await snapshotWriterHook(input,output),await toolSummarizerHook?.(input,output),_dbg)console.error(`[DIAG] toolAfter snapshot+summarizer done tool=${_toolName}`);let execMode=config3.execution_mode??"balanced";if(execMode==="strict"){if(slopDetectorHook)await slopDetectorHook.toolAfter(input,output);if(incrementalVerifyHook)await incrementalVerifyHook.toolAfter(input,output)}if(execMode!=="fast"&&compactionServiceHook)await compactionServiceHook.toolAfter(input,output);if(repoGraphHook)await safeHook(repoGraphHook.toolAfter)(input,output);if(isTaskTool8&&config3.context_map?.enabled===!0&&input.sessionID)try{let contextMapTaskId=swarmState.agentSessions.get(input.sessionID)?.currentTaskId??null;if(contextMapTaskId){let agentOutput=typeof output.output==="string"?output.output:"";updateContextMapAfterAgent({task_id:contextMapTaskId,agent_role:swarmState.activeAgent.get(input.sessionID)??"unknown",files_touched:[],implementation_summary:agentOutput.slice(0,500),task_goal:"",final_status:"completed",directory:ctx.directory})}}catch{}let toolOutputConfig=config3.tool_output;if(toolOutputConfig&&toolOutputConfig.truncation_enabled!==!1&&typeof output.output==="string"){let defaultTruncatableTools=new Set(["diff","symbols","bash","shell","test_runner","lint","pre_check_batch","complexity_hotspots","pkg_audit","sbom_generate","schema_drift"]),configuredTools=toolOutputConfig.truncation_tools,truncatableTools=computeEffectiveTruncatableTools(defaultTruncatableTools,configuredTools),maxLines=toolOutputConfig.per_tool?.[input.tool]??toolOutputConfig.max_lines??150;if(truncatableTools.has(input.tool))output.output=truncateToolOutput(output.output,maxLines,input.tool,10)}};try{await hookChain()}catch(err2){let warning=`[swarm] toolAfter hook chain error tool=${_toolName}: ${err2 instanceof Error?err2.message:String(err2)}`;if(!config3.quiet)console.warn(warning);else addDeferredWarning(warning)}if(isTaskTool8){let backgroundResultIsRunning=outputLooksLikeBackgroundRunning(output),sessionId=input.sessionID,beganDelegation=_delegationTelemetryByCallID.get(input.callID),storedSubagentType=typeof afterCtx.args?.subagent_type==="string"?afterCtx.args.subagent_type:void 0,agentName=beganDelegation?.agentName||storedSubagentType||swarmState.activeAgent.get(sessionId)||"unknown",baseAgentName=stripKnownSwarmPrefix(agentName),preHandoffSession=swarmState.agentSessions.get(sessionId),activeWindow=getActiveWindow(sessionId),configuredModel=resolveRegisteredAgentModel(config3,agentName)??DEFAULT_MODELS[baseAgentName]??DEFAULT_MODELS.default,assistantUsage=consumeAssistantUsageForTask(sessionId,output),costFields=buildDelegationCostFields({raw:{metadata:output.metadata,output,assistant:assistantUsage},model:configuredModel,gate:preHandoffSession?.lastDelegationReason,retry_index:activeWindow?.transientRetryCount,pricing:config3.pricing});swarmState.activeAgent.set(sessionId,ORCHESTRATOR_NAME),ensureAgentSession(sessionId,ORCHESTRATOR_NAME);let taskSession=swarmState.agentSessions.get(sessionId);if(taskSession){if(taskSession.delegationActive=!1,taskSession.lastAgentEventTime=Date.now(),!backgroundResultIsRunning){if(_delegationTelemetryByCallID.delete(input.callID),telemetry.delegationEnd(sessionId,agentName,beganDelegation?.taskId||taskSession.currentTaskId||"","completed",costFields),baseAgentName==="reviewer"||baseAgentName==="test_engineer"||baseAgentName==="critic"||baseAgentName==="critic_sounding_board")pushAdvisory(taskSession,`[PIPELINE] ${baseAgentName} delegation complete for task ${taskSession.currentTaskId??"unknown"}. `+"Resume the QA gate pipeline — check your task pipeline steps for the next required action. "+"Do not stop here.");if(baseAgentName==="critic_sounding_board"){let rawResponse=typeof output.output==="string"?output.output:"",parsed=parseSoundingBoardResponse(rawResponse);if(parsed){let verdictMsg=`[SOUNDING_BOARD] Verdict: ${parsed.verdict}. ${parsed.reasoning}`;if(parsed.improvedQuestion)verdictMsg+=` Rephrase to: ${parsed.improvedQuestion}`;if(parsed.answer)verdictMsg+=` Answer: ${parsed.answer}`;if(parsed.warning)verdictMsg+=` WARNING: ${parsed.warning}`;pushAdvisory(taskSession,verdictMsg),taskSession.lastDelegationReason="critic_consultation"}else pushAdvisory(taskSession,`[SOUNDING_BOARD] WARNING: Could not parse a structured verdict from critic_sounding_board response (${rawResponse.length} chars). `+"Treat as REPHRASE — review the raw response before surfacing to user or escalating. "+"Do not silently accept as resolved.")}}}if(_dbg)console.error(`[DIAG] Task handoff DONE session=${sessionId} activeAgent=${swarmState.activeAgent.get(sessionId)}`)}if(deleteStoredInputArgs(input.callID),_dbg)console.error(`[DIAG] toolAfter COMPLETE tool=${_toolName}`)},"chat.message":async(input,output)=>{try{if(input?.sessionID&&typeof input?.agent==="string"){let routeModel=resolveTaskRouteModelChain(String(input.agent));if(routeModel){if((await resolveTaskChatModelOverride({childSessionID:String(input.sessionID),role:routeModel.role,primaryModel:routeModel.primaryModel,fallbackModels:routeModel.fallbackModels,lookupParentSessionID:lookupParentSessionIDForTaskRoute})).status==="exhausted"){let error93=Error(`MODEL_FALLBACK_EXHAUSTED: no configured model remains for ${routeModel.role}`);throw error93.name="TaskModelFallbackExhaustedError",error93}}}}catch(error93){if(error93 instanceof Error&&error93.name==="TaskModelFallbackExhaustedError")throw error93}await safeHook(async(input2,output2)=>{if(process.env.DEBUG_SWARM)console.error(`[DIAG] chat.message agent=${input2.agent??"none"} session=${input2.sessionID}`);if(input2?.sessionID&&typeof input2?.agent==="string"&&output2&&typeof output2==="object"&&typeof output2.message==="object"&&output2.message!==null){let routeModel=resolveTaskRouteModelChain(String(input2.agent));if(routeModel){let resolution=await resolveTaskChatModelOverride({childSessionID:String(input2.sessionID),role:routeModel.role,primaryModel:routeModel.primaryModel,fallbackModels:routeModel.fallbackModels,lookupParentSessionID:lookupParentSessionIDForTaskRoute});if(resolution.status==="override"&&resolution.model)output2.message.model=resolution.model}}if(await delegationHandler(input2,output2),input2?.sessionID)try{await cacheCohortIdAtMessage(ctx.directory,input2.sessionID)}catch{}try{if(input2?.sessionID&&input2?.agent){if(stripKnownSwarmPrefix(String(input2.agent))==="architect")tickAndMaybeDispatchCadence(ctx.directory,input2.sessionID,"architectTurns",config3,{activeAgent:String(input2.agent)})}}catch{}if(process.env.DEBUG_SWARM)console.error(`[DIAG] chat.message DONE agent=${input2.agent??"none"}`)})(input,output)},automation:automationManager}}var src_default={id:"opencode-swarm",server:OpenCodeSwarm};export{schedulePostResolutionTasksForTest,recordTestImpactGateGroundTruth,overrideIndexInternalsForTest,loadTier1EvaluationTasks,evaluationV1,evaluatePrReviewRecoveryV1,evaluateCandidateV1,src_default as default,computeEffectiveTruncatableTools,capSessionMap,archiveSqliteSnapshot,_resetDelegationTelemetryPairingForTesting};