opencode-swarm 7.176.1 → 7.176.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/binaries/win32-arm64/swarm-sandbox-runner.exe +0 -0
- package/binaries/win32-x64/swarm-sandbox-runner.exe +0 -0
- package/dist/cli/{coder-settlement-cctwqn8q.js → coder-settlement-q81p8cdw.js} +3 -3
- package/dist/cli/{config-doctor-f2j4t2qg.js → config-doctor-g8yj2ax5.js} +2 -2
- package/dist/cli/{core-j1wef1b1.js → core-qhsd6kh4.js} +1 -1
- package/dist/cli/{curator-9bkavyx7.js → curator-33h6tpkm.js} +19 -19
- package/dist/cli/{curator-llm-factory-rdmbyw36.js → curator-llm-factory-bvck3388.js} +19 -19
- package/dist/cli/{evidence-summary-service-vp1gnmw8.js → evidence-summary-service-h58msp28.js} +6 -6
- package/dist/cli/{gate-evidence-wfc2ypwe.js → gate-evidence-2mzqng35.js} +2 -2
- package/dist/cli/{guardrail-explain-271bxeve.js → guardrail-explain-vs575z3y.js} +20 -20
- package/dist/cli/{guardrail-log-cw6kst05.js → guardrail-log-8pm5hfaf.js} +3 -3
- package/dist/cli/{guardrail-reset-vs77rj7q.js → guardrail-reset-qygfp430.js} +19 -19
- package/dist/cli/{hive-promoter-f9zx73na.js → hive-promoter-1921z8af.js} +19 -19
- package/dist/cli/{index-zwvrrwwb.js → index-1d28c88a.js} +1 -1
- package/dist/cli/{index-wa6ryk62.js → index-30dx8h76.js} +1 -1
- package/dist/cli/{index-qr5ryazn.js → index-3gmfzg4w.js} +2 -2
- package/dist/cli/{index-9rpw0edg.js → index-6kn88mce.js} +2 -2
- package/dist/cli/{index-dzqarb47.js → index-7yms2y29.js} +3 -3
- package/dist/cli/{index-axzmpwsp.js → index-bsw3v6fa.js} +3 -3
- package/dist/cli/{index-39g9ktkw.js → index-d3mzw88v.js} +5 -5
- package/dist/cli/{index-faqr1jkr.js → index-dp0zm7mj.js} +2 -2
- package/dist/cli/{index-r7fz80tj.js → index-g364gm8a.js} +1 -1
- package/dist/cli/{index-cj66fbmz.js → index-gq1qbzsw.js} +4 -4
- package/dist/cli/{index-drdcsxdc.js → index-hc00tn5a.js} +2 -2
- package/dist/cli/{index-3ac47c51.js → index-kc9jbsxh.js} +52 -52
- package/dist/cli/{index-85qk65a0.js → index-mezy2tc7.js} +1 -1
- package/dist/cli/{index-3mrdcdsw.js → index-nmrcgs2v.js} +1 -1
- package/dist/cli/{index-bmzmxewc.js → index-pa9gk6qe.js} +19 -19
- package/dist/cli/{index-9kqtzj67.js → index-pedvpj59.js} +1 -1
- package/dist/cli/{index-sdcybkes.js → index-pgtrsc2t.js} +1 -1
- package/dist/cli/{index-8q6ax18j.js → index-psvgm17t.js} +1 -1
- package/dist/cli/{index-ekw3p6a9.js → index-tfvtf8z5.js} +3 -3
- package/dist/cli/{index-xj3j4v3r.js → index-vqhpemaw.js} +1 -1
- package/dist/cli/{index-9xp8cgh3.js → index-ycb3h9gp.js} +3 -3
- package/dist/cli/{index-af37hks1.js → index-yg3aqync.js} +3 -3
- package/dist/cli/{index-k4r7m6vz.js → index-ytg10jza.js} +21 -21
- package/dist/cli/{index-stz507bw.js → index-z7f3z7t0.js} +1 -1
- package/dist/cli/index.js +20 -20
- package/dist/cli/{knowledge-escalator-znzksqjb.js → knowledge-escalator-m88njezt.js} +6 -6
- package/dist/cli/{knowledge-events-n77sysfe.js → knowledge-events-ncwzpmne.js} +4 -4
- package/dist/cli/{knowledge-store-qv2n3q7j.js → knowledge-store-qsebf29s.js} +1 -1
- package/dist/cli/{knowledge-validator-ed7y0c3r.js → knowledge-validator-c345kv1x.js} +2 -2
- package/dist/cli/{mcp-xpxfwpjq.js → mcp-0wqnyca5.js} +1 -1
- package/dist/cli/{pending-delegations-d1m7ebsd.js → pending-delegations-fry2r78r.js} +2 -2
- package/dist/cli/{pr-subscriptions-8v66558d.js → pr-subscriptions-sd3fyt8p.js} +1 -1
- package/dist/cli/{pr-workflow-gate-bx7x5cyh.js → pr-workflow-gate-c84n5x8x.js} +19 -19
- package/dist/cli/{scan-cursor-9vp5c7dk.js → scan-cursor-ptg9wsmv.js} +2 -2
- package/dist/cli/{schema-e0b6nwh6.js → schema-dwxscxbv.js} +1 -1
- package/dist/cli/{scope-persistence-dd6cwhhc.js → scope-persistence-effvw96s.js} +5 -5
- package/dist/cli/{server-6xqhb2xr.js → server-91c44cv8.js} +19 -19
- package/dist/cli/{skill-generator-k9gvpdq5.js → skill-generator-kv7b5ync.js} +7 -7
- package/dist/cli/{snapshot-coordination-init-8a0cqgzy.js → snapshot-coordination-init-1kxmhy02.js} +19 -19
- package/dist/cli/{worktree-collision-ownership-msxze6pq.js → worktree-collision-ownership-esshj9p9.js} +2 -2
- package/dist/cli/{worktree-isolation-1fxsq65k.js → worktree-isolation-gvy7b6nq.js} +19 -19
- package/dist/evidence/phase-participation.d.ts +17 -0
- package/dist/index.js +3 -3
- package/dist/tools/phase-complete.d.ts +40 -0
- 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.176.1",description:"Architect-centric agentic swarm plugin for OpenCode - hub-and-spoke orchestration with SME consultation, code generation, and QA review",main:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",default:"./dist/index.js"},"./package.json":"./package.json"},bin:{"opencode-swarm":"./dist/cli/index.js"},type:"module",engines:{bun:">=1.3.13",node:">=22.13"},license:"MIT",repository:{type:"git",url:"https://github.com/ZaxbyHub/opencode-swarm.git"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},keywords:["opencode","opencode-plugin","ai","agents","orchestration","swarm","multi-agent","llm"],files:["dist","dist/lang/grammars","binaries","evaluation-fixtures",".opencode/skills/brainstorm",".opencode/skills/specify",".opencode/skills/clarify-spec",".opencode/skills/swarm-resume",".opencode/skills/clarify",".opencode/skills/discover",".opencode/skills/consult",".opencode/skills/pre-phase-briefing",".opencode/skills/council",".opencode/skills/deep-dive",".opencode/skills/deep-research",".opencode/skills/codebase-review-swarm",".opencode/skills/swarm-implement",".opencode/skills/design-docs",".opencode/skills/swarm-pr-review",".opencode/skills/swarm",".opencode/skills/swarm-pr-feedback",".opencode/skills/swarm-pr-subscribe",".opencode/skills/swarm-ci-monitor",".opencode/skills/issue-ingest",".opencode/skills/swarm-plan",".opencode/skills/critic-gate",".opencode/skills/execute",".opencode/skills/phase-wrap",".opencode/skills/loop",".opencode/skills/writing-tests",".opencode/skills/running-tests",".opencode/skills/engineering-conventions",".opencode/skills/commit-pr",".opencode/skills/ci-failure-batching",".opencode/skills/gate-attribution",".opencode/skills/merge-queue-readiness",".opencode/skills/skill-edit-validation",".opencode/skills/worktree-retry-cleanup",".opencode/skills/test-file-split",".opencode/skills/fork-pr-operations",".opencode/skills/parallel-work-check",".opencode/skills/ci-fix-monitor",".opencode/skills/issue-tracer",".opencode/skills/orchestrating-subagents",".opencode/skills/durable-session-state","tests/fixtures/memory-recall","tests/fixtures/memory-recall-heldout","opencode-swarm.schema.json","README.md","LICENSE"],scripts:{clean:`bun -e "require('fs').rmSync('dist',{recursive:true,force:true})"`,build:"bun run clean && bun run scripts/generate-config-schema.ts && bun run scripts/copy-grammars.ts && bun build src/index.ts --outdir dist --target node --format esm --external web-tree-sitter --minify-whitespace --minify-syntax && bun build src/cli/index.ts --outdir dist/cli --target bun --format esm --external bash-parser --splitting && bun run scripts/copy-grammars.ts --to-dist && tsc --emitDeclarationOnly",typecheck:"tsc --noEmit",test:"bun test",lint:"biome lint .","lint:ci":"biome ci .","test:unit:ci":"bun scripts/ci/run-unit-tests-local.ts","drift:check":"bun run scripts/drift-check.ts","check:pre-push":"bun run scripts/drift-check.ts --enforce --no-report && bun run check:registry-citations","schema:generate":"bun run scripts/generate-config-schema.ts","generate:commands-docs":"bun run scripts/generate-commands-docs.ts","check:runtime-src-refs":"bun run scripts/check-runtime-src-refs.ts","drift:fix":"bun run scripts/drift-check.ts --fix --confirm","skills:sync":"bun run scripts/sync-qa-gate-skills.ts",format:"biome format . --write",check:"biome check --write .",dev:"bun run build && opencode","package:smoke":"node scripts/package-smoke.mjs",prepare:"bun run build","repro:704":"node scripts/repro-704.mjs","repro:2669":"node scripts/repro-2669.mjs","repro:2670":"node scripts/repro-2670.mjs","repro:1144":"bun scripts/repro-1144.mjs","repro:1873":"bun build scripts/repro-1873-entry.ts --outdir dist-build-test/repro-1873 --target node --format esm && node scripts/repro-1873.mjs","repro:2487":"bun build scripts/repro-2487-parity-entry.ts --outdir dist-build-test/repro-2487 --target node --format esm && node scripts/repro-2487-parity.mjs","check:events":"bun run scripts/check-event-contract.ts","check:retention":"bun run scripts/check-retention-registry.ts","check:core-events":"bun run scripts/check-core-events-usage.ts","check:shell-audit":"bun run scripts/check-shell-audit-usage.ts","check:trajectory-store":"bun run scripts/check-trajectory-store-usage.ts","check:mock-cleanup":"bun run scripts/check-mock-cleanup.ts","check:invariants":"bun run scripts/check-invariants.ts","check:token-formula":"bun run scripts/check-token-formula.ts","check:cross-contamination":"bun run scripts/check-cross-contamination.ts","check:test-clock":"bun run scripts/check-test-clock.ts","check:test-file-cap":"bun run scripts/check-test-file-cap.ts","check:test-tmpdir":"bun run scripts/check-test-tmpdir.ts","check:bash-portability":"bun run scripts/check-bash-portability.ts","check:pending-fragment":"bun run scripts/check-pending-fragment.ts","check:gate-portability":"bun run scripts/check-gate-portability.ts","check:bare-spawn":"bun run scripts/check-bare-executable-spawn.ts","check:error-channel-discard":"bun run scripts/check-error-channel-discard.ts","check:path-identity":"bun run scripts/check-path-identity.ts","check:registry-citations":"bun run scripts/check-registry-citations.ts","check:memory-recall":"bun run scripts/memory-recall-regression.ts","check:retrieval-quality":"bun run scripts/retrieval-quality-regression.ts"},dependencies:{"@modelcontextprotocol/sdk":"^1.30.0","@opencode-ai/plugin":"^1.18.3","@opencode-ai/sdk":"^1.18.3","@vscode/tree-sitter-wasm":"^0.3.0","bash-parser":"^0.5.0","p-limit":"^7.3.0",picomatch:"^4.0.4","proper-lockfile":"^4.1.2","quick-lru":"^7.3.0","web-tree-sitter":"^0.25.0",zod:"4.3.6"},devDependencies:{"@biomejs/biome":"2.3.14","@types/picomatch":"^4.0.3","bun-types":"1.3.8","js-yaml":"^4.1.1",typescript:"^5.7.3"},peerDependencies:{"@xenova/transformers":"^2.17.2"},peerDependenciesMeta:{"@xenova/transformers":{optional:!0}}}});var QA_AGENTS,PIPELINE_AGENTS,ORCHESTRATOR_NAME="architect",ALL_SUBAGENT_NAMES,ALL_AGENT_NAMES;var init_agent_names=__esm(()=>{QA_AGENTS=["reviewer","critic","critic_oversight","critic_finding_validator"],PIPELINE_AGENTS=["explorer","coder","test_engineer"],ALL_SUBAGENT_NAMES=["sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","curator_postmortem","curator_consolidation","council_generalist","council_skeptic","council_domain_expert","skill_improver","spec_writer",...QA_AGENTS,...PIPELINE_AGENTS],ALL_AGENT_NAMES=["architect",...ALL_SUBAGENT_NAMES]});function getPrWorkflowToolCapability(toolName,mode){let metadata=TOOL_METADATA[toolName];if(!metadata?.prWorkflow?.modes.includes(mode))return null;return metadata.prWorkflow.capability}var TOOL_METADATA,TOOL_NAMES,TOOL_NAME_SET,TOOL_DESCRIPTIONS,AGENT_TOOL_MAP;var init_tool_metadata=__esm(()=>{init_agent_names();TOOL_METADATA={diff:{description:"structured git diff with contract change detection",agents:["architect","reviewer","critic_finding_validator","critic_oversight","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},diff_summary:{description:"filter classified AST changes by category, risk level, or file for reviewer drill-down",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},syntax_check:{description:"check syntax of source files using tree-sitter parsers across multiple languages, returning per-file errors",agents:["architect","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},placeholder_scan:{description:"todo and FIXME comment detection",agents:["architect","reviewer","critic_finding_validator"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},imports:{description:"find all consumers that import from a given file — use before refactoring shared modules to avoid breaking unseen dependents",agents:["architect","sme","researcher","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},lint:{description:"run project linter in check or fix mode; supports biome, eslint, ruff, clippy, and more, returns structured results",agents:["architect","reviewer","critic_finding_validator","coder"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},secretscan:{description:"scan for secrets (API keys, tokens, passwords) via regex and entropy; returns redacted previews, excludes common dirs",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},sast_scan:{description:"static analysis security scan",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},build_check:{description:"discover and run build, typecheck, and test commands for various project ecosystems in the working directory",agents:["architect","coder","test_engineer"]},pre_check_batch:{description:"parallel verification: lint:check + secretscan + sast_scan + quality_budget",agents:["architect","reviewer","critic_finding_validator"]},quality_budget:{description:"code quality budget check",agents:["architect"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},symbols:{description:"extract exported symbols (functions, classes, interfaces, types) from source files; supports TypeScript, JavaScript, 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"]},authorize_pr_review_reentry:{description:"issue a one-use, identity-bound reviewer/test_engineer re-entry authorization for the active PR_REVIEW workflow (issue #2383)",agents:["architect"]},submit_pr_review_result:{description:"submit one child-bound typed result for an active PR-review base or micro discovery lane",agents:[],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},approve_plan_critic:{description:"record a MANUAL plan_critic_gate approval snapshot to unblock the ratchet-tighter critic_pre_plan execution gate when the critic already returned APPROVED but the mechanical recorder failed to persist it (issue #2012), or as the sanctioned recovery for a bookkeeping-grade hashed-field repair under the critic-gate PLAN FREEZE rule (the reason must state which case applies)",agents:["architect"]},prepare_pr_workflow_checkout:{description:"prepare an auditable PR workflow checkout or restore its exact original branch/HEAD and preserved stash after terminal cleanup",agents:["architect"]},invalidate_pr_feedback_publication:{description:"invalidate the armed PR_FEEDBACK publication generation so approved content can change, superseding every content-dependent approval and reopening the exact scoped rework + fresh-review path (issue #2108)",agents:["architect"]},record_implementation_review:{description:"record fresh-context reviewer + critic APPROVE verdicts for the implementation diff so the /swarm issue --trace workflow can satisfy its review gate before commit-pr handoff",agents:["architect"]},record_issue_publication:{description:"record a publication receipt so the /swarm issue --trace workflow reaches its terminal published state after the PR is created/updated",agents:["architect"]},record_issue_reproduction:{description:"record the reproduction outcome for the current traced issue so the /swarm issue --trace workflow can satisfy its reproduction gate and transition to PLAN",agents:["architect"]},record_recurrence_sweep:{description:"record the recurrence sweep (defect class, predicates, hit dispositions, guardrail proof) 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 recoverable exact-task gate evidence, rebuild from durable requirements, recover receipt-backed legacy marker wedges or the exact sentinel-only historical reset, and refuse every other receipt-less reconstruction",agents:["architect"]},repair_knowledge_receipt_ledger:{description:"validate or repair authoritative knowledge receipts, preserve corrupt authority in bounded quarantine, 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 with provenance (modelLimitSource: host|override|provider_cap|native|fallback; modelLimitResolution: user_provider_model|user_model|user_default|live_model_limit|static_provider_cap|static_native|static_default; fallbackActive: true when the denominator came from a static table or the flat 128k default — treat headroom as uncertain), usage-percent, threshold-state (none/warn/critical), model name, and provider. Pure read-only: no state mutation, no warning injection. Works whether context_budget.enabled is true or false.",agents:["architect"]},search:{description:"Workspace-scoped ripgrep-style text search with structured JSON output. Supports literal and regex modes, glob filtering, and result limits. NOTE: This is text search, not structural AST search — use symbols and imports tools for structural queries.",agents:["architect","sme","docs","docs_design","designer","critic_hallucination_verifier","skill_improver","spec_writer","reviewer","critic_finding_validator","critic_oversight","explorer","coder","test_engineer","researcher"]},ast_grep:{description:"Read-only structural AST search using ast-grep patterns with optional language and glob filters. Use for syntax-aware code pattern searches; does not rewrite files.",agents:["architect","sme","docs","docs_design","critic_hallucination_verifier","spec_writer","explorer","coder","test_engineer","researcher"]},actionlint_scan:{description:"Run actionlint against GitHub Actions workflow YAML files with structured findings. Resolves actionlint lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},osv_scan:{description:"Run OSV-Scanner against a workspace path and return structured dependency vulnerability findings. Resolves osv-scanner lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},gh_evidence:{description:"Fetch bounded GitHub pull request or issue metadata through gh for review and CI evidence. Resolves gh lazily and is read-only.",agents:["architect","researcher"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},pr_workflow_status:{description:"Read-only architect observation of local git state (HEAD, branch, clean/dirty with a bounded changed-file list, remotes) plus a session-pinned PR workflow gate summary and the PR_FEEDBACK publication-generation section (state, attempts, invalidation reason, recovery guidance). Use to observe state under the fail-closed PR_REVIEW/PR_FEEDBACK gate. Never executes PR-controlled scripts and never reads another session gate.",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},batch_symbols:{description:"Batched symbol extraction across multiple files. Returns per-file symbol summaries with isolated error handling.",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","explorer"]},suggest_patch:{description:"Reviewer-safe structured patch suggestion tool. Produces context-anchored patch artifacts without file modification. Returns structured diagnostics on context mismatch.",agents:["architect","reviewer","critic_finding_validator"]},req_coverage:{description:"query requirement coverage status for tracked functional requirements",agents:["critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","critic","critic_oversight"]},get_approved_plan:{description:"retrieve the last critic-approved immutable plan snapshot for baseline drift comparison",agents:["critic_drift_verifier","critic","critic_oversight"]},repo_map:{description:"query the repo code graph: importers, dependencies, blast radius, localization, ontology facts, package boundaries, and heuristic preflight packets before refactoring; ontology findings are advisory, not formal proofs",agents:["architect","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},get_qa_gate_profile:{description:"retrieve the QA gate profile for the current or exact future plan identity: gates (reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council), lock state, 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; each lane agent must be a registered generated agent name (unregistered bare roles are refused on multi-swarm hosts); launch_timeout_ms is only a promptAsync acceptance budget, not a lane runtime timeout; poll incrementally with collect_lane_results (wait omitted), or join with wait: true for all results",agents:["architect"]},collect_lane_results:{description:"collect/poll a dispatch_lanes_async batch; a presumed-stale sweep runs on every call, settling lanes past the horizon: idle host to stale, unobservable host to a typed liveness error; cancel_pending cancels pending lanes; otherwise observe-only. Non-blocking poll (wait omitted or false) and blocking join (wait: true) supported. The wait budget bounds the observer call only — expiry never kills a lane nor proves it died; poll again or cancel explicitly, never abort. Unsettled lanes are reported in pending_lanes (batch_id, lane_id, status, output_ref) regardless of include_pending; busy/retry lanes never go stale for running long. Does not advance workflow gates. Settled-lane inline output is delivered once: later polls set output_omitted_repeat: true and omit output but keep output_ref for retrieval via retrieve_lane_output.",agents:["architect"]},summarize_work:{description:"emit a short structured summary of completed work (key decisions, assumptions, risks, constraints) at task completion; rolls up per phase for architecture-supervisor review. Advisory, never blocks.",agents:["architect","sme","researcher","docs","docs_design","designer","explorer","coder","test_engineer"]},write_architecture_supervisor_evidence:{description:"persist the architecture supervisor verdict for a phase (architect MUST dispatch critic_architecture_supervisor first and collect its JSON verdict; this tool persists only, it does not contact the supervisor)",agents:["architect"]},lean_turbo_plan_lanes:{description:"partition phase tasks into parallel lanes based on file-scope conflicts for Lean Turbo execution",agents:[]},lean_turbo_acquire_locks:{description:"acquire file locks for all files in a lane (all-or-nothing) before lane execution",agents:[]},lean_turbo_runner_status:{description:"read Lean Turbo run state from .swarm/turbo-state.json",agents:[]},lean_turbo_critic:{description:"dispatch a read-only critic agent to evaluate boundary conditions for a completed Lean Turbo phase (satisfies the turbo.lean.phase_critic gate)",agents:[]},lean_turbo_review:{description:"dispatch a read-only reviewer agent to evaluate a completed Lean Turbo phase",agents:[]},lean_turbo_run_phase:{description:"Execute a phase using Lean Turbo parallel lane execution. Plans lanes, acquires file locks, and dispatches coder agents concurrently. Use when Lean Turbo is active and you want to execute all tasks in a phase in parallel lanes.",agents:[]},lean_turbo_status:{description:"returns Lean Turbo configuration and active status for the current session",agents:[]},swarm_apply_patch:{description:"Apply a unified diff patch to workspace files with exact context matching, atomic writes, and path validation. Use standard unified diff format only — does NOT support *** Begin Patch / *** Update File payloads (use native apply_patch for those).",agents:["coder","test_engineer"]},external_skill_discover:{description:"Discover external skill candidates from configured sources. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_list:{description:"List external skill candidates in the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_inspect:{description:"Inspect a specific external skill candidate by ID. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_promote:{description:"Promote a validated external skill candidate to an active generated skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_reject:{description:"Reject an external skill candidate after evaluation. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_delete:{description:"Delete an external skill candidate from the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_revoke:{description:"Revoke a previously promoted external skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},epic_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 scanOverrideForDangerousKeys(value,path,depth){if(depth>=10)return;if(Array.isArray(value)){for(let i=0;i<value.length;i++)scanOverrideForDangerousKeys(value[i],`${path}[${i}]`,depth+1);return}if(typeof value!=="object"||value===null)return;for(let key of Object.keys(value)){if(DANGEROUS_MERGE_KEYS.has(key))throw new DangerousMergeKeyError(key,path);scanOverrideForDangerousKeys(value[key],`${path}.${key}`,depth+1)}}function deepMergeInternal(base,override,depth,path){if(depth>=10)throw Error("deepMerge exceeded maximum depth of 10");let result={...base};for(let key of Object.keys(override)){let baseVal=base[key],overrideVal=override[key];if(typeof baseVal==="object"&&baseVal!==null&&typeof overrideVal==="object"&&overrideVal!==null&&!Array.isArray(baseVal)&&!Array.isArray(overrideVal))result[key]=deepMergeInternal(baseVal,overrideVal,depth+1,`${path}.${key}`);else result[key]=overrideVal}return result}function deepMerge(base,override){if(!base)return override;if(!override)return base;return scanOverrideForDangerousKeys(override,"$",0),deepMergeInternal(base,override,0,"$")}var MAX_MERGE_DEPTH=10,DANGEROUS_MERGE_KEYS,DangerousMergeKeyError;var init_merge=__esm(()=>{DANGEROUS_MERGE_KEYS=new Set(["__proto__","constructor","prototype"]);DangerousMergeKeyError=class DangerousMergeKeyError extends Error{key;path;constructor(key,path){super(`deepMerge refused dangerous key "${key}" at "${path}": prototype-pollution carriers (__proto__/constructor/prototype) are never merged`);this.key=key;this.path=path;this.name="DangerousMergeKeyError"}}});function freezeSet(items,name="CLAUDE_CODE_NATIVE_COMMANDS"){let set=new Set(items),proxy=new Proxy(set,{get(target,prop){if(prop==="add"||prop==="delete"||prop==="clear")return()=>{throw TypeError(`${name} is readonly`)};if(prop==="forEach")return(callback,thisArg)=>{let wrapped=(v,k)=>callback.call(thisArg??void 0,v,k,proxy);return set.forEach(wrapped)};let value=Reflect.get(target,prop);return typeof value==="function"?value.bind(target):value},set(){throw TypeError(`${name} is readonly`)},deleteProperty(){throw TypeError(`${name} is readonly`)},defineProperty(){throw TypeError(`${name} is readonly`)},setPrototypeOf(){throw TypeError(`${name} is readonly`)}});return proxy}function isQAAgent(name){return QA_AGENTS.includes(name)}function isSubagent(name){return ALL_SUBAGENT_NAMES.includes(name)}function isLowCapabilityModel(modelId){let lower=(modelId||"").toLowerCase();return LOW_CAPABILITY_MODELS.some((substr)=>lower.includes(substr))}var OPENCODE_NATIVE_AGENTS,CLAUDE_CODE_NATIVE_COMMANDS,OPENCODE_NATIVE_COMMANDS,MEMORY_AGENT_TOOL_MAP,EXTERNAL_SKILL_TOOL_NAMES,EXTERNAL_SKILL_AGENT_TOOL_MAP,COUNCIL_TOOL_NAMES,COUNCIL_AGENT_TOOL_MAP,GENERAL_COUNCIL_TOOL_NAMES,GENERAL_COUNCIL_AGENT_TOOL_MAP,TURBO_TOOL_NAMES,TURBO_AGENT_TOOL_MAP,SKILL_TOOL_NAMES,SKILL_AGENT_TOOL_MAP,PR_REVIEW_CHILD_TOOL_NAMES,PR_REVIEW_CHILD_AGENT_TOOL_MAP,WRITE_TOOL_NAMES,SUMMARIZER_EXEMPT_TOOL_NAMES,DEFAULT_MODELS,DEFAULT_AGENT_CONFIGS,DEFAULT_SCORING_CONFIG,LOW_CAPABILITY_MODELS,TURBO_MODE_BANNER=`## \uD83D\uDE80 TURBO MODE ACTIVE
|
|
1
|
+
import{createRequire}from"node:module";var __create=Object.create;var{getPrototypeOf:__getProtoOf,defineProperty:__defProp,getOwnPropertyNames:__getOwnPropNames,getOwnPropertyDescriptor:__getOwnPropDesc}=Object,__hasOwnProp=Object.prototype.hasOwnProperty;function __accessProp(key){return this[key]}var __toESMCache_node,__toESMCache_esm,__toESM=(mod,isNodeMode,target)=>{var canCache=mod!=null&&typeof mod==="object";if(canCache){var cache=isNodeMode?__toESMCache_node??=new WeakMap:__toESMCache_esm??=new WeakMap,cached=cache.get(mod);if(cached)return cached}target=mod!=null?__create(__getProtoOf(mod)):{};let to=isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target;for(let key of __getOwnPropNames(mod))if(!__hasOwnProp.call(to,key))__defProp(to,key,{get:__accessProp.bind(mod,key),enumerable:!0});if(canCache)cache.set(mod,to);return to},__toCommonJS=(from)=>{var entry=(__moduleCache??=new WeakMap).get(from),desc;if(entry)return entry;if(entry=__defProp({},"__esModule",{value:!0}),from&&typeof from==="object"||typeof from==="function"){for(var key of __getOwnPropNames(from))if(!__hasOwnProp.call(entry,key))__defProp(entry,key,{get:__accessProp.bind(from,key),enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return __moduleCache.set(from,entry),entry},__moduleCache,__commonJS=(cb,mod)=>()=>(mod||cb((mod={exports:{}}).exports,mod),mod.exports);var __returnValue=(v)=>v;function __exportSetter(name,newValue){this[name]=__returnValue.bind(null,newValue)}var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0,configurable:!0,set:__exportSetter.bind(all,name)})};var __esm=(fn2,res)=>()=>(fn2&&(res=fn2(fn2=0)),res);var __require=createRequire(import.meta.url);var package_default;var init_package=__esm(()=>{package_default={name:"opencode-swarm",version:"7.176.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",node:">=22.13"},license:"MIT",repository:{type:"git",url:"https://github.com/ZaxbyHub/opencode-swarm.git"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},keywords:["opencode","opencode-plugin","ai","agents","orchestration","swarm","multi-agent","llm"],files:["dist","dist/lang/grammars","binaries","evaluation-fixtures",".opencode/skills/brainstorm",".opencode/skills/specify",".opencode/skills/clarify-spec",".opencode/skills/swarm-resume",".opencode/skills/clarify",".opencode/skills/discover",".opencode/skills/consult",".opencode/skills/pre-phase-briefing",".opencode/skills/council",".opencode/skills/deep-dive",".opencode/skills/deep-research",".opencode/skills/codebase-review-swarm",".opencode/skills/swarm-implement",".opencode/skills/design-docs",".opencode/skills/swarm-pr-review",".opencode/skills/swarm",".opencode/skills/swarm-pr-feedback",".opencode/skills/swarm-pr-subscribe",".opencode/skills/swarm-ci-monitor",".opencode/skills/issue-ingest",".opencode/skills/swarm-plan",".opencode/skills/critic-gate",".opencode/skills/execute",".opencode/skills/phase-wrap",".opencode/skills/loop",".opencode/skills/writing-tests",".opencode/skills/running-tests",".opencode/skills/engineering-conventions",".opencode/skills/commit-pr",".opencode/skills/ci-failure-batching",".opencode/skills/gate-attribution",".opencode/skills/merge-queue-readiness",".opencode/skills/skill-edit-validation",".opencode/skills/worktree-retry-cleanup",".opencode/skills/test-file-split",".opencode/skills/fork-pr-operations",".opencode/skills/parallel-work-check",".opencode/skills/ci-fix-monitor",".opencode/skills/issue-tracer",".opencode/skills/orchestrating-subagents",".opencode/skills/durable-session-state","tests/fixtures/memory-recall","tests/fixtures/memory-recall-heldout","opencode-swarm.schema.json","README.md","LICENSE"],scripts:{clean:`bun -e "require('fs').rmSync('dist',{recursive:true,force:true})"`,build:"bun run clean && bun run scripts/generate-config-schema.ts && bun run scripts/copy-grammars.ts && bun build src/index.ts --outdir dist --target node --format esm --external web-tree-sitter --minify-whitespace --minify-syntax && bun build src/cli/index.ts --outdir dist/cli --target bun --format esm --external bash-parser --splitting && bun run scripts/copy-grammars.ts --to-dist && tsc --emitDeclarationOnly",typecheck:"tsc --noEmit",test:"bun test",lint:"biome lint .","lint:ci":"biome ci .","test:unit:ci":"bun scripts/ci/run-unit-tests-local.ts","drift:check":"bun run scripts/drift-check.ts","check:pre-push":"bun run scripts/drift-check.ts --enforce --no-report && bun run check:registry-citations","schema:generate":"bun run scripts/generate-config-schema.ts","generate:commands-docs":"bun run scripts/generate-commands-docs.ts","check:runtime-src-refs":"bun run scripts/check-runtime-src-refs.ts","drift:fix":"bun run scripts/drift-check.ts --fix --confirm","skills:sync":"bun run scripts/sync-qa-gate-skills.ts",format:"biome format . --write",check:"biome check --write .",dev:"bun run build && opencode","package:smoke":"node scripts/package-smoke.mjs",prepare:"bun run build","repro:704":"node scripts/repro-704.mjs","repro:2669":"node scripts/repro-2669.mjs","repro:2670":"node scripts/repro-2670.mjs","repro:1144":"bun scripts/repro-1144.mjs","repro:1873":"bun build scripts/repro-1873-entry.ts --outdir dist-build-test/repro-1873 --target node --format esm && node scripts/repro-1873.mjs","repro:2487":"bun build scripts/repro-2487-parity-entry.ts --outdir dist-build-test/repro-2487 --target node --format esm && node scripts/repro-2487-parity.mjs","check:events":"bun run scripts/check-event-contract.ts","check:retention":"bun run scripts/check-retention-registry.ts","check:core-events":"bun run scripts/check-core-events-usage.ts","check:shell-audit":"bun run scripts/check-shell-audit-usage.ts","check:trajectory-store":"bun run scripts/check-trajectory-store-usage.ts","check:mock-cleanup":"bun run scripts/check-mock-cleanup.ts","check:invariants":"bun run scripts/check-invariants.ts","check:token-formula":"bun run scripts/check-token-formula.ts","check:cross-contamination":"bun run scripts/check-cross-contamination.ts","check:test-clock":"bun run scripts/check-test-clock.ts","check:test-file-cap":"bun run scripts/check-test-file-cap.ts","check:test-tmpdir":"bun run scripts/check-test-tmpdir.ts","check:bash-portability":"bun run scripts/check-bash-portability.ts","check:pending-fragment":"bun run scripts/check-pending-fragment.ts","check:gate-portability":"bun run scripts/check-gate-portability.ts","check:bare-spawn":"bun run scripts/check-bare-executable-spawn.ts","check:error-channel-discard":"bun run scripts/check-error-channel-discard.ts","check:path-identity":"bun run scripts/check-path-identity.ts","check:registry-citations":"bun run scripts/check-registry-citations.ts","check:memory-recall":"bun run scripts/memory-recall-regression.ts","check:retrieval-quality":"bun run scripts/retrieval-quality-regression.ts"},dependencies:{"@modelcontextprotocol/sdk":"^1.30.0","@opencode-ai/plugin":"^1.18.3","@opencode-ai/sdk":"^1.18.3","@vscode/tree-sitter-wasm":"^0.3.0","bash-parser":"^0.5.0","p-limit":"^7.3.0",picomatch:"^4.0.4","proper-lockfile":"^4.1.2","quick-lru":"^7.3.0","web-tree-sitter":"^0.25.0",zod:"4.3.6"},devDependencies:{"@biomejs/biome":"2.3.14","@types/picomatch":"^4.0.3","bun-types":"1.3.8","js-yaml":"^4.1.1",typescript:"^5.7.3"},peerDependencies:{"@xenova/transformers":"^2.17.2"},peerDependenciesMeta:{"@xenova/transformers":{optional:!0}}}});var QA_AGENTS,PIPELINE_AGENTS,ORCHESTRATOR_NAME="architect",ALL_SUBAGENT_NAMES,ALL_AGENT_NAMES;var init_agent_names=__esm(()=>{QA_AGENTS=["reviewer","critic","critic_oversight","critic_finding_validator"],PIPELINE_AGENTS=["explorer","coder","test_engineer"],ALL_SUBAGENT_NAMES=["sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","curator_postmortem","curator_consolidation","council_generalist","council_skeptic","council_domain_expert","skill_improver","spec_writer",...QA_AGENTS,...PIPELINE_AGENTS],ALL_AGENT_NAMES=["architect",...ALL_SUBAGENT_NAMES]});function getPrWorkflowToolCapability(toolName,mode){let metadata=TOOL_METADATA[toolName];if(!metadata?.prWorkflow?.modes.includes(mode))return null;return metadata.prWorkflow.capability}var TOOL_METADATA,TOOL_NAMES,TOOL_NAME_SET,TOOL_DESCRIPTIONS,AGENT_TOOL_MAP;var init_tool_metadata=__esm(()=>{init_agent_names();TOOL_METADATA={diff:{description:"structured git diff with contract change detection",agents:["architect","reviewer","critic_finding_validator","critic_oversight","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},diff_summary:{description:"filter classified AST changes by category, risk level, or file for reviewer drill-down",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},syntax_check:{description:"check syntax of source files using tree-sitter parsers across multiple languages, returning per-file errors",agents:["architect","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},placeholder_scan:{description:"todo and FIXME comment detection",agents:["architect","reviewer","critic_finding_validator"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},imports:{description:"find all consumers that import from a given file — use before refactoring shared modules to avoid breaking unseen dependents",agents:["architect","sme","researcher","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},lint:{description:"run project linter in check or fix mode; supports biome, eslint, ruff, clippy, and more, returns structured results",agents:["architect","reviewer","critic_finding_validator","coder"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},secretscan:{description:"scan for secrets (API keys, tokens, passwords) via regex and entropy; returns redacted previews, excludes common dirs",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},sast_scan:{description:"static analysis security scan",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},build_check:{description:"discover and run build, typecheck, and test commands for various project ecosystems in the working directory",agents:["architect","coder","test_engineer"]},pre_check_batch:{description:"parallel verification: lint:check + secretscan + sast_scan + quality_budget",agents:["architect","reviewer","critic_finding_validator"]},quality_budget:{description:"code quality budget check",agents:["architect"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},symbols:{description:"extract exported symbols (functions, classes, interfaces, types) from source files; supports TypeScript, JavaScript, 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"]},authorize_pr_review_reentry:{description:"issue a one-use, identity-bound reviewer/test_engineer re-entry authorization for the active PR_REVIEW workflow (issue #2383)",agents:["architect"]},submit_pr_review_result:{description:"submit one child-bound typed result for an active PR-review base or micro discovery lane",agents:[],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},approve_plan_critic:{description:"record a MANUAL plan_critic_gate approval snapshot to unblock the ratchet-tighter critic_pre_plan execution gate when the critic already returned APPROVED but the mechanical recorder failed to persist it (issue #2012), or as the sanctioned recovery for a bookkeeping-grade hashed-field repair under the critic-gate PLAN FREEZE rule (the reason must state which case applies)",agents:["architect"]},prepare_pr_workflow_checkout:{description:"prepare an auditable PR workflow checkout or restore its exact original branch/HEAD and preserved stash after terminal cleanup",agents:["architect"]},invalidate_pr_feedback_publication:{description:"invalidate the armed PR_FEEDBACK publication generation so approved content can change, superseding every content-dependent approval and reopening the exact scoped rework + fresh-review path (issue #2108)",agents:["architect"]},record_implementation_review:{description:"record fresh-context reviewer + critic APPROVE verdicts for the implementation diff so the /swarm issue --trace workflow can satisfy its review gate before commit-pr handoff",agents:["architect"]},record_issue_publication:{description:"record a publication receipt so the /swarm issue --trace workflow reaches its terminal published state after the PR is created/updated",agents:["architect"]},record_issue_reproduction:{description:"record the reproduction outcome for the current traced issue so the /swarm issue --trace workflow can satisfy its reproduction gate and transition to PLAN",agents:["architect"]},record_recurrence_sweep:{description:"record the recurrence sweep (defect class, predicates, hit dispositions, guardrail proof) 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 recoverable exact-task gate evidence, rebuild from durable requirements, recover receipt-backed legacy marker wedges or the exact sentinel-only historical reset, and refuse every other receipt-less reconstruction",agents:["architect"]},repair_knowledge_receipt_ledger:{description:"validate or repair authoritative knowledge receipts, preserve corrupt authority in bounded quarantine, 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 with provenance (modelLimitSource: host|override|provider_cap|native|fallback; modelLimitResolution: user_provider_model|user_model|user_default|live_model_limit|static_provider_cap|static_native|static_default; fallbackActive: true when the denominator came from a static table or the flat 128k default — treat headroom as uncertain), usage-percent, threshold-state (none/warn/critical), model name, and provider. Pure read-only: no state mutation, no warning injection. Works whether context_budget.enabled is true or false.",agents:["architect"]},search:{description:"Workspace-scoped ripgrep-style text search with structured JSON output. Supports literal and regex modes, glob filtering, and result limits. NOTE: This is text search, not structural AST search — use symbols and imports tools for structural queries.",agents:["architect","sme","docs","docs_design","designer","critic_hallucination_verifier","skill_improver","spec_writer","reviewer","critic_finding_validator","critic_oversight","explorer","coder","test_engineer","researcher"]},ast_grep:{description:"Read-only structural AST search using ast-grep patterns with optional language and glob filters. Use for syntax-aware code pattern searches; does not rewrite files.",agents:["architect","sme","docs","docs_design","critic_hallucination_verifier","spec_writer","explorer","coder","test_engineer","researcher"]},actionlint_scan:{description:"Run actionlint against GitHub Actions workflow YAML files with structured findings. Resolves actionlint lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},osv_scan:{description:"Run OSV-Scanner against a workspace path and return structured dependency vulnerability findings. Resolves osv-scanner lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},gh_evidence:{description:"Fetch bounded GitHub pull request or issue metadata through gh for review and CI evidence. Resolves gh lazily and is read-only.",agents:["architect","researcher"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},pr_workflow_status:{description:"Read-only architect observation of local git state (HEAD, branch, clean/dirty with a bounded changed-file list, remotes) plus a session-pinned PR workflow gate summary and the PR_FEEDBACK publication-generation section (state, attempts, invalidation reason, recovery guidance). Use to observe state under the fail-closed PR_REVIEW/PR_FEEDBACK gate. Never executes PR-controlled scripts and never reads another session gate.",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},batch_symbols:{description:"Batched symbol extraction across multiple files. Returns per-file symbol summaries with isolated error handling.",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","explorer"]},suggest_patch:{description:"Reviewer-safe structured patch suggestion tool. Produces context-anchored patch artifacts without file modification. Returns structured diagnostics on context mismatch.",agents:["architect","reviewer","critic_finding_validator"]},req_coverage:{description:"query requirement coverage status for tracked functional requirements",agents:["critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","critic","critic_oversight"]},get_approved_plan:{description:"retrieve the last critic-approved immutable plan snapshot for baseline drift comparison",agents:["critic_drift_verifier","critic","critic_oversight"]},repo_map:{description:"query the repo code graph: importers, dependencies, blast radius, localization, ontology facts, package boundaries, and heuristic preflight packets before refactoring; ontology findings are advisory, not formal proofs",agents:["architect","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},get_qa_gate_profile:{description:"retrieve the QA gate profile for the current or exact future plan identity: gates (reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council), lock state, 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; each lane agent must be a registered generated agent name (unregistered bare roles are refused on multi-swarm hosts); launch_timeout_ms is only a promptAsync acceptance budget, not a lane runtime timeout; poll incrementally with collect_lane_results (wait omitted), or join with wait: true for all results",agents:["architect"]},collect_lane_results:{description:"collect/poll a dispatch_lanes_async batch; a presumed-stale sweep runs on every call, settling lanes past the horizon: idle host to stale, unobservable host to a typed liveness error; cancel_pending cancels pending lanes; otherwise observe-only. Non-blocking poll (wait omitted or false) and blocking join (wait: true) supported. The wait budget bounds the observer call only — expiry never kills a lane nor proves it died; poll again or cancel explicitly, never abort. Unsettled lanes are reported in pending_lanes (batch_id, lane_id, status, output_ref) regardless of include_pending; busy/retry lanes never go stale for running long. Does not advance workflow gates. Settled-lane inline output is delivered once: later polls set output_omitted_repeat: true and omit output but keep output_ref for retrieval via retrieve_lane_output.",agents:["architect"]},summarize_work:{description:"emit a short structured summary of completed work (key decisions, assumptions, risks, constraints) at task completion; rolls up per phase for architecture-supervisor review. Advisory, never blocks.",agents:["architect","sme","researcher","docs","docs_design","designer","explorer","coder","test_engineer"]},write_architecture_supervisor_evidence:{description:"persist the architecture supervisor verdict for a phase (architect MUST dispatch critic_architecture_supervisor first and collect its JSON verdict; this tool persists only, it does not contact the supervisor)",agents:["architect"]},lean_turbo_plan_lanes:{description:"partition phase tasks into parallel lanes based on file-scope conflicts for Lean Turbo execution",agents:[]},lean_turbo_acquire_locks:{description:"acquire file locks for all files in a lane (all-or-nothing) before lane execution",agents:[]},lean_turbo_runner_status:{description:"read Lean Turbo run state from .swarm/turbo-state.json",agents:[]},lean_turbo_critic:{description:"dispatch a read-only critic agent to evaluate boundary conditions for a completed Lean Turbo phase (satisfies the turbo.lean.phase_critic gate)",agents:[]},lean_turbo_review:{description:"dispatch a read-only reviewer agent to evaluate a completed Lean Turbo phase",agents:[]},lean_turbo_run_phase:{description:"Execute a phase using Lean Turbo parallel lane execution. Plans lanes, acquires file locks, and dispatches coder agents concurrently. Use when Lean Turbo is active and you want to execute all tasks in a phase in parallel lanes.",agents:[]},lean_turbo_status:{description:"returns Lean Turbo configuration and active status for the current session",agents:[]},swarm_apply_patch:{description:"Apply a unified diff patch to workspace files with exact context matching, atomic writes, and path validation. Use standard unified diff format only — does NOT support *** Begin Patch / *** Update File payloads (use native apply_patch for those).",agents:["coder","test_engineer"]},external_skill_discover:{description:"Discover external skill candidates from configured sources. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_list:{description:"List external skill candidates in the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_inspect:{description:"Inspect a specific external skill candidate by ID. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_promote:{description:"Promote a validated external skill candidate to an active generated skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_reject:{description:"Reject an external skill candidate after evaluation. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_delete:{description:"Delete an external skill candidate from the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_revoke:{description:"Revoke a previously promoted external skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},epic_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 scanOverrideForDangerousKeys(value,path,depth){if(depth>=10)return;if(Array.isArray(value)){for(let i=0;i<value.length;i++)scanOverrideForDangerousKeys(value[i],`${path}[${i}]`,depth+1);return}if(typeof value!=="object"||value===null)return;for(let key of Object.keys(value)){if(DANGEROUS_MERGE_KEYS.has(key))throw new DangerousMergeKeyError(key,path);scanOverrideForDangerousKeys(value[key],`${path}.${key}`,depth+1)}}function deepMergeInternal(base,override,depth,path){if(depth>=10)throw Error("deepMerge exceeded maximum depth of 10");let result={...base};for(let key of Object.keys(override)){let baseVal=base[key],overrideVal=override[key];if(typeof baseVal==="object"&&baseVal!==null&&typeof overrideVal==="object"&&overrideVal!==null&&!Array.isArray(baseVal)&&!Array.isArray(overrideVal))result[key]=deepMergeInternal(baseVal,overrideVal,depth+1,`${path}.${key}`);else result[key]=overrideVal}return result}function deepMerge(base,override){if(!base)return override;if(!override)return base;return scanOverrideForDangerousKeys(override,"$",0),deepMergeInternal(base,override,0,"$")}var MAX_MERGE_DEPTH=10,DANGEROUS_MERGE_KEYS,DangerousMergeKeyError;var init_merge=__esm(()=>{DANGEROUS_MERGE_KEYS=new Set(["__proto__","constructor","prototype"]);DangerousMergeKeyError=class DangerousMergeKeyError extends Error{key;path;constructor(key,path){super(`deepMerge refused dangerous key "${key}" at "${path}": prototype-pollution carriers (__proto__/constructor/prototype) are never merged`);this.key=key;this.path=path;this.name="DangerousMergeKeyError"}}});function freezeSet(items,name="CLAUDE_CODE_NATIVE_COMMANDS"){let set=new Set(items),proxy=new Proxy(set,{get(target,prop){if(prop==="add"||prop==="delete"||prop==="clear")return()=>{throw TypeError(`${name} is readonly`)};if(prop==="forEach")return(callback,thisArg)=>{let wrapped=(v,k)=>callback.call(thisArg??void 0,v,k,proxy);return set.forEach(wrapped)};let value=Reflect.get(target,prop);return typeof value==="function"?value.bind(target):value},set(){throw TypeError(`${name} is readonly`)},deleteProperty(){throw TypeError(`${name} is readonly`)},defineProperty(){throw TypeError(`${name} is readonly`)},setPrototypeOf(){throw TypeError(`${name} is readonly`)}});return proxy}function isQAAgent(name){return QA_AGENTS.includes(name)}function isSubagent(name){return ALL_SUBAGENT_NAMES.includes(name)}function isLowCapabilityModel(modelId){let lower=(modelId||"").toLowerCase();return LOW_CAPABILITY_MODELS.some((substr)=>lower.includes(substr))}var OPENCODE_NATIVE_AGENTS,CLAUDE_CODE_NATIVE_COMMANDS,OPENCODE_NATIVE_COMMANDS,MEMORY_AGENT_TOOL_MAP,EXTERNAL_SKILL_TOOL_NAMES,EXTERNAL_SKILL_AGENT_TOOL_MAP,COUNCIL_TOOL_NAMES,COUNCIL_AGENT_TOOL_MAP,GENERAL_COUNCIL_TOOL_NAMES,GENERAL_COUNCIL_AGENT_TOOL_MAP,TURBO_TOOL_NAMES,TURBO_AGENT_TOOL_MAP,SKILL_TOOL_NAMES,SKILL_AGENT_TOOL_MAP,PR_REVIEW_CHILD_TOOL_NAMES,PR_REVIEW_CHILD_AGENT_TOOL_MAP,WRITE_TOOL_NAMES,SUMMARIZER_EXEMPT_TOOL_NAMES,DEFAULT_MODELS,DEFAULT_AGENT_CONFIGS,DEFAULT_SCORING_CONFIG,LOW_CAPABILITY_MODELS,TURBO_MODE_BANNER=`## \uD83D\uDE80 TURBO MODE ACTIVE
|
|
2
2
|
|
|
3
3
|
**Speed optimization enabled for this session.**
|
|
4
4
|
|
|
@@ -6901,7 +6901,7 @@ ${freshPreamble}`:`<curator_briefing>${truncatedBriefing}</curator_briefing>`}}c
|
|
|
6901
6901
|
`+rejected2.slice(-3).map((r)=>` ⚠️ REJECTED PATTERN: "${sanitizeLessonForContext(r.lesson).slice(0,80)}" — ${sanitizeLessonForContext(r.rejection_reason)}`).join(`
|
|
6902
6902
|
`);if(rejectedBlock.length<=remaining)parts.push(rejectedBlock)}}catch(err){warn(`[knowledge-injector] rejected pattern warnings unavailable: ${err instanceof Error?err.message:String(err)}`)}cachedInjectionText=parts.join(`
|
|
6903
6903
|
|
|
6904
|
-
`);let criticalIds=filteredEntries.filter((e)=>renderedDirectiveIdSet.has(e.id)).filter((e)=>e.directive_priority==="critical"&&isActiveStatus(e.status)).map((e)=>e.id);if(cachedShownIds.length>0){let byId=new Map(filteredEntries.map((entry)=>[entry.id,entry])),cohortId=await _internals225.ensureCohortIdCached(directory,sessionId),sourceLinkId=_internals225.readLinkPointer(directory)?.linkId,membership=await _internals225.commitDisplayedMembership(directory,{trace_id:search.trace_id,session_id:sessionId,exposure_kind:"architect_directive",phase:retrievalCtx.currentPhase,task_id:retrievalCtx.taskId,agent:"architect",cohort_id:cohortId,source_link_id:sourceLinkId,grace_days:config3.receipt_close_grace_days,entries:cachedShownIds.map((id,index)=>({entry_id:id,critical:criticalIds.includes(id),rank:index+1,score:byId.get(id)?.finalScore}))});if(!membership.ok||membership.memberships.some((item)=>item.terminal)){if(cachedInjectionText="",cachedShownIds=[],cachedCriticalIds=[],sessionId)clearCriticalShownIds(sessionId);recordInjectionSkip(directory,membership.ok?"terminal_trace_reuse":membership.code,{agent:agentName,sessionId,phase:currentPhase,extra:{trace_id:search.trace_id}});return}}injectKnowledgeMessage(output,cachedInjectionText,sessionId);let sessionID=sessionId;if(sessionID)if(cachedCriticalIds=criticalIds,criticalIds.length>0)setCriticalShownIds(sessionID,{ids:criticalIds,phase:`Phase ${currentPhase}`,generatedAt:Date.now()});else clearCriticalShownIds(sessionID);if(cachedShownIds.length>0){let phaseLabel=`Phase ${currentPhase}`,scoreById=new Map(filteredEntries.map((e)=>[e.id,e.finalScore])),ranks={},scores={};cachedShownIds.forEach((id,idx)=>{ranks[id]=idx+1,scores[id]=scoreById.get(id)??0}),await _internals225.recordKnowledgeEvent(directory,{type:"retrieved",trace_id:search.trace_id,session_id:sessionId,phase:retrievalCtx.currentPhase,task_id:retrievalCtx.taskId,agent:"architect",query:retrievalCtx.lastUserMessage??retrievalCtx.currentPhase??"",retrieval_mode:"auto_injection",result_ids:cachedShownIds,ranks,scores}),_internals225.recordKnowledgeShown(directory,cachedShownIds,{phase:phaseLabel,tool:retrievalCtx.currentTool,action:retrievalCtx.currentAction,targetAgent:retrievalCtx.targetAgent,taskId:retrievalCtx.taskId}).catch(()=>{}),_internals225.recordLessonsShown(directory,cachedShownIds,phaseLabel).catch(()=>{}),_internals225.confirmEntriesPhase(directory,cachedShownIds,currentPhase,projectName).catch(()=>{})}})}var INJECTION_SENTINEL,defaultSearchKnowledge,sanitizeLessonForContext,DELEGATE_DIRECTIVE_BLOCK_TAG="<delegate_knowledge_directives>",DELEGATE_INJECT_HARD_CHAR_CAP=2000,knowledgeGeneration=0,DELEGATED_AGENTS,DELEGATE_DEFAULT_TOOLS,DIRECTIVE_PRIORITY_RANK,_internals225;var init_knowledge_injector=__esm(()=>{init_reviewer_directive_compliance();init_schema();init_manager();init_injection_budget();init_run_memory();init_state2();init_logger();init_cohort_cache();init_curator_drift();init_extractors();init_host_boundary();init_knowledge_application();init_knowledge_escalator();init_knowledge_events();init_knowledge_link();init_knowledge_reader();init_knowledge_receipt_ledger();init_knowledge_store();init_knowledge_types();init_model_limits();init_phase_directives();init_search_knowledge();init_utils2();INJECTION_SENTINEL=`${String.fromCharCode(8204)}[[KNOWLEDGE-INJECTED]]`,defaultSearchKnowledge=searchKnowledge;sanitizeLessonForContext=sanitizeContextText;DELEGATED_AGENTS=new Set(["coder","reviewer","test_engineer","sme","docs","designer","critic","curator"]);DELEGATE_DEFAULT_TOOLS={coder:["edit","write","patch","bash"],reviewer:["read","grep","glob"],test_engineer:["edit","write","bash","read"],sme:["read","grep","glob","webfetch"],docs:["read","edit","write","grep"],designer:["read","write","edit"],critic:["read","grep","glob"],curator:["read","grep","glob"]};DIRECTIVE_PRIORITY_RANK={critical:0,high:1,medium:2,low:3};_internals225={searchKnowledge,recordKnowledgeEvent,recordKnowledgeShown,readRecentEscalations,buildEscalationBriefing,recordLessonsShown,confirmEntriesPhase,commitDisplayedMembership,commitEmptyRetrieval,queryLiveMemberships,ensureCohortIdCached,readLinkPointer}});function reject(reason,detail,rejected_items){return{ok:!1,rejected:!0,reason,detail,rejected_items}}async function validateReceipt(ctx){let{items,no_relevant_knowledge:noRelevant}=ctx;if(items.length===0&&!noRelevant)return reject("empty_receipt","no items and no_relevant_knowledge is false");if(noRelevant&&items.length>0)return reject("invalid_outcome","no_relevant_knowledge cannot be combined with items");for(let item of items)if(!VALID_OUTCOMES.has(item.outcome))return reject("invalid_outcome",`item ${item.id}: outcome ${item.outcome}`);let traceId=ctx.trace_id||NO_TRACE_SENTINEL;if(traceId===NO_TRACE_SENTINEL){if(items.length>0)return reject("trace_not_found","items filed against the none sentinel trace");let empty=await commitEmptyRetrieval(ctx.directory,{trace_id:traceId,session_id:ctx.session_id,phase:ctx.phase,task_id:ctx.task_id,agent:ctx.agent,grace_days:ctx.grace_days});if(!empty.ok)return reject(empty.code,empty.detail);return{ok:!0,accepted:[],idempotent_skips:[],trace:null,closes_no_relevant:!0,authoritative_event_ids:{},no_relevant_event_id:empty.terminal_event_id}}let committed=await validateAndCommitTerminalBatch(ctx.directory,{trace_id:traceId,session_id:ctx.session_id,phase:ctx.phase,task_id:ctx.task_id,agent:ctx.agent,cohort_id:ctx.cohort_id,source_link_id:ctx.source_link_id,grace_days:ctx.grace_days,items:items.map((item)=>({entry_id:item.id,outcome:item.outcome,reason:item.reason,source:ctx.source.trim()||"unknown"})),no_relevant_knowledge:noRelevant});if(!committed.ok)return reject(committed.code,committed.detail);let remainingItems=[...items],takeItem=(id,outcome)=>{let index=remainingItems.findIndex((item)=>item.id===id&&(outcome===void 0||item.outcome===outcome));if(index<0)return;return remainingItems.splice(index,1)[0]},accepted=committed.accepted.map((item)=>takeItem(item.entry_id,item.outcome)).filter((item)=>item!==void 0),idempotent_skips=committed.idempotent.map((id)=>takeItem(id)).filter((item)=>item!==void 0),rejected_items=committed.rejected.map((item)=>({item:takeItem(item.entry_id)??{id:item.entry_id,outcome:"ignored"},reason:item.reason}));if(rejected_items.length&&accepted.length===0&&idempotent_skips.length===0)return reject(rejected_items[0].reason,`${rejected_items[0].reason} for id ${rejected_items[0].item.id}`,rejected_items);let queried=await queryLiveMemberships(ctx.directory,{session_id:ctx.session_id,include_terminal:!0,grace_days:ctx.grace_days}),memberships=queried.ok?queried.memberships.filter((membership)=>membership.trace_id===traceId):[],trace=memberships.length?{type:"retrieved",event_id:memberships[0].membership_event_id,trace_id:traceId,timestamp:memberships[0].committed_at,session_id:ctx.session_id,phase:memberships[0].phase,task_id:memberships[0].task_id,agent:memberships[0].agent??ctx.agent,query:"",retrieval_mode:"manual",result_ids:memberships.map((membership)=>membership.entry_id),ranks:Object.fromEntries(memberships.map((membership,index)=>[membership.entry_id,membership.rank??index+1])),scores:Object.fromEntries(memberships.map((membership)=>[membership.entry_id,membership.score??0]))}:null;return{ok:!0,accepted,idempotent_skips,trace,closes_no_relevant:committed.closes_no_relevant,authoritative_event_ids:Object.fromEntries(committed.accepted.map((item)=>[item.entry_id,item.event_id])),...committed.terminal_event_id?{no_relevant_event_id:committed.terminal_event_id}:{},...rejected_items.length?{rejected_items}:{}}}var NO_TRACE_SENTINEL="none",VALID_OUTCOMES;var init_knowledge_receipt_validator=__esm(()=>{init_knowledge_receipt_ledger();VALID_OUTCOMES=RECEIPT_TERMINAL_OUTCOMES});function isTaskTool3(tool3){return tool3==="Task"||tool3==="task"}function resolveDelegateAckTaskId(args2,knownPlanTaskIds,planContextOverLimit=!1){let resolved=resolveDelegateAckTaskIdResult(args2,knownPlanTaskIds,planContextOverLimit);return resolved.status==="resolved"?resolved.taskId:void 0}function resolveDelegateAckTaskIdResult(args2,knownPlanTaskIds,planContextOverLimit=!1){return resolveTaskId(args2,{policy:"attribution",knownPlanTaskIds,planContextOverLimit})}async function appendUnacknowledgedCritical(directory,record3){let filePath=validateSwarmPath(directory,"unacknowledged-criticals.jsonl");await appendCappedJsonl(filePath,JSON.stringify(record3),{maxEntries:resolveRetentionCap("MAX_UNACKNOWLEDGED_CRITICALS",MAX_UNACKNOWLEDGED_CRITICALS),onPrune:(dropped)=>{warn(`unacknowledged-criticals audit at cap: dropped ${dropped} oldest ${dropped===1?"entry":"entries"} (FIFO bound MAX_UNACKNOWLEDGED_CRITICALS)`)}})}async function reconcileShownDirectives(params){let result={emitted:[],unacknowledgedCriticals:[],unacknowledgedNonCritical:[]};try{let shown=params.shown;if(shown.length===0)return result;let shownById=new Map(shown.map((d)=>[d.id,d])),criticalIds=shown.filter((d)=>d.priority==="critical").map((d)=>d.id),acks=parseAcknowledgments(params.transcript),ackedIds=new Set,violatedIds=new Set,sessionId=params.sessionId,taskId=params.taskId,traceId=params.traceId??"legacy-unverifiable",isLegacyPrompt=params.traceId===void 0,cohortId,linkId;try{cohortId=await ensureCohortIdCached(params.directory,sessionId),linkId=readLinkPointer(params.directory)?.linkId}catch{}let ackItems=[],ackByItemId=new Map;for(let ack of acks){if(!shownById.has(ack.id))continue;if(ackedIds.add(ack.id),!isLegacyPrompt&&ack.trace_id!==traceId)continue;if(ack.result==="applied"||ack.result==="ignored"||ack.result==="violated"||ack.result==="n_a"||ack.result==="contradicted")ackItems.push({id:ack.id,outcome:ack.result,reason:ack.reason}),ackByItemId.set(ack.id,ack)}let eventIdByKnowledgeId=new Map;if(isLegacyPrompt)for(let ack of acks){if(!shownById.has(ack.id))continue;if(!ackByItemId.has(ack.id))continue;ackedIds.add(ack.id)}else{let validation2=await validateReceipt({directory:params.directory,trace_id:traceId,session_id:sessionId,task_id:taskId,agent:params.agent,source:"delegate",cohort_id:cohortId,source_link_id:linkId,items:ackItems,no_relevant_knowledge:!1});if(validation2.ok){for(let item of validation2.accepted){let ack=ackByItemId.get(item.id);if(!ack)continue;ackedIds.add(item.id),await recordKnowledgeEvent(params.directory,{type:item.outcome,trace_id:traceId,knowledge_id:item.id,session_id:sessionId,task_id:taskId,agent:params.agent,source:"delegate",reason:ack.reason});let authoritativeEventId=validation2.authoritative_event_ids[item.id];if(authoritativeEventId)eventIdByKnowledgeId.set(item.id,authoritativeEventId);if(item.outcome==="violated")violatedIds.add(item.id);result.emitted.push({id:item.id,type:item.outcome})}for(let item of validation2.idempotent_skips)ackedIds.add(item.id);for(let rejected2 of validation2.rejected_items??[])ackedIds.add(rejected2.item.id)}if(!validation2.ok)for(let id of ackByItemId.keys())ackedIds.add(id)}try{let now2=new Date().toISOString(),evidenceRecords=[];for(let[kid,eid]of eventIdByKnowledgeId){let ack=ackByItemId.get(kid);if(!ack||!cohortId)continue;let outcome=ack.result;if(outcome!=="applied"&&outcome!=="violated"&&outcome!=="contradicted")continue;evidenceRecords.push({cohort_id:cohortId,source_link_id:linkId,entry_id:kid,retrieval_trace_id:traceId,receipt_outcome:outcome,receipt_source:"delegate",receipt_event_id:eid,phase:void 0,timestamp:now2})}await appendPromotionEvidence(params.directory,evidenceRecords)}catch{}let missingCriticalIds=criticalIds.filter((id)=>!ackedIds.has(id)),committedMissingCriticalIds=new Set;if(!isLegacyPrompt&&missingCriticalIds.length>0){let committed=await validateAndCommitTerminalBatch(params.directory,{trace_id:traceId,session_id:sessionId,task_id:taskId,agent:params.agent,cohort_id:cohortId,source_link_id:linkId,items:missingCriticalIds.map((entry_id)=>({entry_id,outcome:"violated",source:"delegate",reason:"unacknowledged"}))});if(committed.ok)committedMissingCriticalIds=new Set(committed.committed.map((item)=>item.entry_id))}for(let id of missingCriticalIds){if(!committedMissingCriticalIds.has(id))continue;result.unacknowledgedCriticals.push(id),await recordKnowledgeEvent(params.directory,{type:"violated",trace_id:traceId,knowledge_id:id,session_id:sessionId,task_id:taskId,agent:params.agent,source:"delegate",reason:"unacknowledged"}),violatedIds.add(id),result.emitted.push({id,type:"violated"});try{await appendUnacknowledgedCritical(params.directory,{timestamp:new Date().toISOString(),knowledge_id:id,agent:params.agent,session_id:sessionId,task_id:taskId,reason:"unacknowledged"})}catch{}}let silentEvents=[];for(let[id,directive]of shownById){if(directive.priority==="critical")continue;if(ackedIds.has(id))continue;if(params.replay===!0)continue;result.unacknowledgedNonCritical.push(id),silentEvents.push({type:"unacknowledged",trace_id:traceId,knowledge_id:id,session_id:sessionId,task_id:taskId,agent:params.agent,source:"delegate",reason:"no_ack_marker"}),result.emitted.push({id,type:"unacknowledged"})}if(silentEvents.length>0)await recordKnowledgeEventsBatch(params.directory,silentEvents);if(violatedIds.size>0)await escalateViolatedEntries(params.directory,[...violatedIds])}catch{}return result}async function collectDelegateAcks(params){let shown=parseDelegateDirectiveBlock(params.prompt);if(shown.length===0)return{emitted:[],unacknowledgedCriticals:[],unacknowledgedNonCritical:[]};let sessionId=params.sessionId;if(!sessionId)return{emitted:[],unacknowledgedCriticals:[],unacknowledgedNonCritical:[],unverifiable:{code:"missing_session_id",detail:"Delegate acknowledgments require a real host session id"}};let traceId=parseDelegateDirectiveTraceId(params.prompt)??void 0,taskId=params.taskIdResolution?params.taskIdResolution.status==="resolved"?params.taskIdResolution.taskId:void 0:params.taskId??resolveDelegateAckTaskId({prompt:params.prompt});return reconcileShownDirectives({directory:params.directory,shown,traceId,transcript:params.transcript,agent:params.agent,sessionId,taskId})}async function collectLaneDelegateAcks(params){let empty={emitted:[],unacknowledgedCriticals:[],unacknowledgedNonCritical:[],phases:[]};try{let memberships=await queryLiveMemberships(params.directory,{session_id:params.sessionId,exposure_kind:"delegate_directive",include_terminal:!0});if(!memberships.ok)return empty;let byTrace=new Map,phases=new Set;for(let membership of memberships.memberships){let group=byTrace.get(membership.trace_id)??[];if(group.push(membership),byTrace.set(membership.trace_id,group),membership.phase)phases.add(membership.phase)}let combined={emitted:[],unacknowledgedCriticals:[],unacknowledgedNonCritical:[]};for(let[traceId,group]of byTrace){let taskId=group.find((m)=>m.task_id)?.task_id,outcome=await reconcileShownDirectives({directory:params.directory,shown:group.map((m)=>({id:m.entry_id,priority:m.critical?"critical":"medium"})),traceId,transcript:params.transcript,agent:params.agent,sessionId:params.sessionId,taskId,replay:params.replay});if(combined.emitted.push(...outcome.emitted),combined.unacknowledgedCriticals.push(...outcome.unacknowledgedCriticals),combined.unacknowledgedNonCritical.push(...outcome.unacknowledgedNonCritical),outcome.unverifiable)combined.unverifiable=outcome.unverifiable}return{...combined,phases:[...phases]}}catch{return empty}}async function collectDelegateAcksAfter(directory,input,output){if(!isTaskTool3(input.tool))return;let argsRecord=input.args&&typeof input.args==="object"?input.args:null,prompt=argsRecord&&typeof argsRecord.prompt==="string"?argsRecord.prompt:"";if(!prompt)return;let transcript=typeof output.output==="string"?output.output:"";if(!transcript)return;let agent=parseDelegationArgs(input.args)?.targetAgent??"unknown",sessionId=typeof input.sessionID==="string"?input.sessionID:void 0,planTaskIdOptions=toTaskIdPlanContextOptions(await loadPlanTaskIdContext(directory)),taskIdResolution=resolveDelegateAckTaskIdResult(argsRecord??{prompt},planTaskIdOptions.knownPlanTaskIds,planTaskIdOptions.planContextOverLimit);await collectDelegateAcks({directory,prompt,transcript,agent,sessionId,taskIdResolution})}var MAX_UNACKNOWLEDGED_CRITICALS=500;var init_delegate_ack_collector=__esm(()=>{init_caps();init_jsonl_cap();init_logger();init_cohort_cache();init_knowledge_application();init_knowledge_escalator();init_knowledge_events();init_knowledge_injector();init_knowledge_link();init_knowledge_receipt_ledger();init_knowledge_receipt_validator();init_plan_task_id_context();init_promotion_evidence_store();init_skill_propagation_gate();init_task_id_resolver();init_utils2()});import{existsSync as existsSync149,readdirSync as readdirSync41,readFileSync as readFileSync118,statSync as statSync83}from"node:fs";import*as path282 from"node:path";function validateRepoRelativeGlob(directory,value){let v=value.trim();if(!v)return null;if(v.includes("\x00"))return null;if(v.startsWith("/")||/^[A-Za-z]:[\\/]/.test(v)||v.startsWith("\\"))return null;if(v.split(/[/\\]/).some((s)=>s===".."))return null;let globStart=v.search(/[*?{[]/),concrete=globStart===-1?v:v.slice(0,globStart);if(concrete){let baseDir=path282.resolve(directory),resolved=path282.resolve(baseDir,concrete),rel3=path282.relative(baseDir,resolved);if(rel3.startsWith("..")||path282.isAbsolute(rel3))return null}return v}function findBinaryInPath(binary){let candidates=process.platform==="win32"?[`${binary}.exe`,`${binary}.cmd`,`${binary}.bat`,binary]:[binary];for(let dir of(process.env.PATH??"").split(path282.delimiter)){if(!dir)continue;for(let name of candidates){let candidate2=path282.join(dir,name);if(existsSync149(candidate2))return candidate2}}return null}function safeChildEnv(){let env={};if(process.env.PATH)env.PATH=process.env.PATH;if(process.env.HOME)env.HOME=process.env.HOME;if(process.env.SystemRoot)env.SystemRoot=process.env.SystemRoot;if(process.env.TEMP)env.TEMP=process.env.TEMP;if(process.env.TMP)env.TMP=process.env.TMP;return env}async function runArgv(argv,cwd){let proc=bunSpawn(argv,{stdin:"ignore",stdout:"pipe",stderr:"pipe",cwd,env:safeChildEnv()}),finished=!1;try{let timeout=new Promise((resolve110)=>setTimeout(()=>resolve110("timeout"),PREDICATE_TIMEOUT_MS));if(await Promise.race([proc.exited,timeout])==="timeout")return{exitCode:null,stdout:"",stderr:"",timedOut:!0};let[stdout,stderr]=await Promise.all([proc.stdout.text().catch(()=>""),proc.stderr.text().catch(()=>"")]);return finished=!0,{exitCode:proc.exitCode,stdout,stderr,timedOut:!1}}finally{if(!finished)try{proc.kill()}catch{}}}async function runGrepPredicate(rest,directory){let lastColon=rest.lastIndexOf(":");if(lastColon<=0||lastColon===rest.length-1)return{result:"error",detail:"grep: expected <regex>:<path-glob>"};let regex=rest.slice(0,lastColon),rawGlob=rest.slice(lastColon+1),glob=validateRepoRelativeGlob(directory,rawGlob);if(glob===null)return{result:"error",detail:`grep: unsafe or empty path-glob "${rawGlob}"`};let pattern;try{pattern=new RegExp(regex,"m")}catch(err){return{result:"error",detail:`grep: invalid regex ${err instanceof Error?err.message:String(err)}`}}let matcher=import_picomatch2.default(glob,{dot:!0}),visited=0,matches=0,walk=(dir)=>{if(visited>=GREP_MAX_FILES)return;let entries2;try{entries2=readdirSync41(dir,{withFileTypes:!0})}catch{return}for(let entry of entries2){if(visited>=GREP_MAX_FILES)return;let fullPath=path282.join(dir,entry.name),relPath=path282.relative(directory,fullPath).replace(/\\/g,"/");if(entry.isDirectory()){if(!GREP_SKIP_DIRECTORIES.has(entry.name))walk(fullPath);continue}if(!entry.isFile())continue;if(visited++,!matcher(relPath))continue;try{if(statSync83(fullPath).size>GREP_MAX_BYTES_PER_FILE)continue;let found=readFileSync118(fullPath,"utf-8").match(pattern);if(found)matches+=found.length}catch{}}};if(walk(directory),visited>=GREP_MAX_FILES)return{result:"error",detail:`grep: file scan exceeded ${GREP_MAX_FILES} files`};if(matches===0)return{result:"pass",detail:"grep: zero matches"};return{result:"fail",detail:`grep: ${matches} match(es) found`}}async function runToolPredicate(rest,directory){let raw=rest.trim();if(!raw)return{result:"error",detail:"tool: empty command"};if(raw.includes("\x00"))return{result:"error",detail:"tool: null byte in command"};let argvParts=raw.split(/\s+/).filter((p)=>p.length>0);if(argvParts.length===0)return{result:"error",detail:"tool: empty command"};let binary=argvParts[0];if(binary.includes("/")||binary.includes("\\"))return{result:"error",detail:`tool: path-qualified binary "${binary}" is not allowed`};if(!TOOL_BINARY_ALLOWLIST.has(binary))return{result:"error",detail:`tool: binary "${binary}" is not on the allowlist`};let resolved=findBinaryInPath(binary);if(!resolved)return{result:"error",detail:`tool: binary "${binary}" not found`};let res=await runArgv([resolved,...argvParts.slice(1)],directory);if(res.timedOut)return{result:"error",detail:"tool: timed out"};if(res.exitCode===0)return{result:"pass",detail:"tool: exit 0"};return{result:"fail",detail:`tool: exit ${res.exitCode} ${res.stderr.slice(0,200)}`}}async function changedPaths(directory){let git2=findBinaryInPath("git");if(!git2)return null;let res=await runArgv([git2,"status","--porcelain","-z"],directory);if(res.timedOut||res.exitCode!==0)return null;let out=new Set;for(let entry of res.stdout.split("\x00")){if(entry.length<=3)continue;let p=entry.slice(3);if(p)out.add(path282.normalize(p))}return out}async function runFileModifiedPredicate(rest,directory,expectModified){let label=expectModified?"file_modified":"file_not_modified",safe2=validateRepoRelativeGlob(directory,rest);if(safe2===null)return{result:"error",detail:`${label}: unsafe or empty path "${rest}"`};let changed2=await changedPaths(directory);if(changed2===null)return{result:"error",detail:`${label}: git unavailable or failed`};let target=path282.normalize(safe2),isChanged=changed2.has(target);return{result:(expectModified?isChanged:!isChanged)?"pass":"fail",detail:`${label}: ${target} ${isChanged?"changed":"unchanged"}`}}async function runDirectivePredicate(predicate,directory){try{if(typeof predicate!=="string"||!predicate.trim())return{result:"error",detail:"predicate: empty"};let trimmed=predicate.trim(),firstColon=trimmed.indexOf(":");if(firstColon<=0)return{result:"error",detail:"predicate: missing handler prefix (expected <handler>:...)"};let handler=trimmed.slice(0,firstColon),rest=trimmed.slice(firstColon+1);switch(handler){case"grep":return await runGrepPredicate(rest,directory);case"tool":return await runToolPredicate(rest,directory);case"file_not_modified":return await runFileModifiedPredicate(rest,directory,!1);case"file_modified":return await runFileModifiedPredicate(rest,directory,!0);default:return{result:"error",detail:`predicate: unknown handler "${handler}"`}}}catch(err){return warn(`[directive-predicate-runner] unexpected error: ${err instanceof Error?err.message:String(err)}`),{result:"error",detail:"predicate: unexpected error (fail-closed)"}}}var import_picomatch2,PREDICATE_TIMEOUT_MS=15000,GREP_MAX_FILES=1e4,GREP_MAX_BYTES_PER_FILE=1e6,GREP_SKIP_DIRECTORIES,TOOL_BINARY_ALLOWLIST;var init_directive_predicate_runner=__esm(()=>{init_bun_compat();init_logger();import_picomatch2=__toESM(require_picomatch2(),1),GREP_SKIP_DIRECTORIES=new Set([".git",".swarm","node_modules","dist","coverage"]),TOOL_BINARY_ALLOWLIST=new Set(["rg","grep","git","biome","eslint","tsc","ruff"])});function parseReviewerDirectiveCompliance(text){if(!text||typeof text!=="string")return[];let out=[];for(let m of text.matchAll(VERDICT_PATTERN)){let verb=m[1].toUpperCase(),traceId=decodeDirectiveCorrelationId(m[2]),entryId=decodeDirectiveCorrelationId(m[3]);if(!traceId||!entryId)continue;let evidence2=m[4]?.trim().slice(0,280),verdict=verb==="VERIFIED"?"verified":verb==="VIOLATED"?"violated":"n_a";out.push({trace_id:traceId,entry_id:entryId,verdict,evidence:evidence2})}return out}function verdictToEventType(v){return v==="verified"?"applied":v==="violated"?"violated":"n_a"}function pairKey2(traceId,entryId){return JSON.stringify([traceId,entryId])}async function reconcileReviewerVerdicts(params){let result={emitted:[],omittedCriticals:[],uncertainties:[]},verifyByPair=new Map(params.directivesToVerify.map((d)=>[pairKey2(d.trace_id,d.entry_id),d]));if(verifyByPair.size===0)return result;let verdictsByPair=new Map;for(let verdict of parseReviewerDirectiveCompliance(params.transcript)){let key2=pairKey2(verdict.trace_id,verdict.entry_id);if(!verifyByPair.has(key2))continue;let existing=verdictsByPair.get(key2)??[];existing.push(verdict),verdictsByPair.set(key2,existing)}let pending=[];for(let[key2,directive]of verifyByPair){let matching=verdictsByPair.get(key2)??[];if(matching.length>1){result.uncertainties.push({trace_id:directive.trace_id,entry_id:directive.entry_id,code:"duplicate_verdict",uncertainty:"Reviewer emitted more than one verdict for the exact pair"});continue}if(matching.length===0){if(directive.priority!=="critical")continue;result.omittedCriticals.push({trace_id:directive.trace_id,entry_id:directive.entry_id}),pending.push({directive,type:"violated",reason:"reviewer_omitted"});continue}let verdict=matching[0];if(verdict.verdict==="verified"&&!verdict.evidence?.trim()){if(result.uncertainties.push({trace_id:directive.trace_id,entry_id:directive.entry_id,code:"reviewer_missing_evidence",uncertainty:"VERIFIED requires nonempty evidence"}),directive.priority==="critical")result.omittedCriticals.push({trace_id:directive.trace_id,entry_id:directive.entry_id}),pending.push({directive,type:"violated",reason:"reviewer_missing_evidence"});continue}let item={directive,type:verdictToEventType(verdict.verdict),reason:verdict.evidence};if(verdict.verdict==="violated"&&directive.verification_predicate)try{let outcome=await _internals232.runDirectivePredicate(directive.verification_predicate,params.directory);item.predicate_check={predicate:directive.verification_predicate,result:outcome.result,detail:outcome.detail}}catch(error93){item.predicate_check={predicate:directive.verification_predicate,result:"error",detail:error93 instanceof Error?error93.message:String(error93)}}pending.push(item)}let groups=new Map;for(let item of pending){let groupKey=JSON.stringify([item.directive.trace_id,item.directive.session_id,item.directive.cohort_id,item.directive.source_link_id,item.directive.prior_terminal_outcome,item.directive.prior_terminal_event_id]),group=groups.get(groupKey)??[];group.push(item),groups.set(groupKey,group)}let violatedIds=new Set,agent=params.agent??"reviewer";for(let group of groups.values()){let first=group[0].directive,remediationAuthorization=(first.prior_terminal_outcome==="violated"||first.prior_terminal_outcome==="contradicted")&&first.prior_terminal_event_id&&group.some((item)=>item.type!=="violated")?{actor:"reviewer-remediation",reason:"reviewer_verified_remediation",expected_event_id:first.prior_terminal_event_id,expected_outcome:first.prior_terminal_outcome}:void 0,committedEntries;try{let committed=await _internals232.validateAndCommitTerminalBatch(params.directory,{trace_id:first.trace_id,session_id:first.session_id,cohort_id:first.cohort_id,source_link_id:first.source_link_id,authorization:remediationAuthorization,items:group.map((item)=>({entry_id:item.directive.entry_id,outcome:item.type,source:"reviewer",reason:item.reason}))});if(!committed.ok){for(let item of group)result.uncertainties.push({trace_id:item.directive.trace_id,entry_id:item.directive.entry_id,code:committed.code,uncertainty:committed.detail});continue}committedEntries=new Set(committed.accepted.map((terminal)=>terminal.entry_id));for(let rejected2 of committed.rejected)result.uncertainties.push({trace_id:first.trace_id,entry_id:rejected2.entry_id||void 0,code:rejected2.reason,uncertainty:"Authoritative ledger rejected reviewer terminal"})}catch(error93){for(let item of group)result.uncertainties.push({trace_id:item.directive.trace_id,entry_id:item.directive.entry_id,code:"ledger_exception",uncertainty:error93 instanceof Error?error93.message:String(error93)});continue}for(let item of group){if(!committedEntries.has(item.directive.entry_id))continue;try{if(await _internals232.recordKnowledgeEvent(params.directory,{type:item.type,trace_id:item.directive.trace_id,knowledge_id:item.directive.entry_id,session_id:item.directive.session_id,task_id:params.taskId,phase:params.phase,agent,source:"reviewer",reason:item.reason,predicate_check:item.predicate_check}),result.emitted.push({trace_id:item.directive.trace_id,entry_id:item.directive.entry_id,id:item.directive.entry_id,type:item.type,source:"reviewer"}),item.type==="violated")violatedIds.add(item.directive.entry_id)}catch(error93){result.uncertainties.push({trace_id:item.directive.trace_id,entry_id:item.directive.entry_id,code:"diagnostic_event_failed",uncertainty:error93 instanceof Error?error93.message:String(error93)})}}}if(violatedIds.size>0)try{await _internals232.escalateViolatedEntries(params.directory,[...violatedIds])}catch(error93){result.uncertainties.push({trace_id:"",code:"escalation_failed",uncertainty:error93 instanceof Error?error93.message:String(error93)})}return result}function isTaskTool7(tool3){return tool3==="Task"||tool3==="task"}async function collectReviewerVerdictsAfter(directory,input,output){if(!isTaskTool7(input.tool))return;let parsedArgs=parseDelegationArgs(input.args);if(!parsedArgs)return;if(stripKnownSwarmPrefix(parsedArgs.targetAgent).toLowerCase()!=="reviewer")return;let argsRecord=input.args&&typeof input.args==="object"?input.args:null,prompt=argsRecord&&typeof argsRecord.prompt==="string"?argsRecord.prompt:"";if(!prompt)return;let transcript=typeof output.output==="string"?output.output:"";if(!transcript)return;let directivesToVerify=parseDirectivesToVerifyBlock(prompt);if(directivesToVerify.length===0)return;let sessionId=typeof input.sessionID==="string"?input.sessionID:void 0;await reconcileReviewerVerdicts({directory,transcript,directivesToVerify,sessionId,agent:"reviewer"})}var _internals232,VERDICT_PATTERN;var init_reviewer_verdict_parser=__esm(()=>{init_reviewer_directive_compliance();init_schema();init_directive_predicate_runner();init_knowledge_escalator();init_knowledge_events();init_knowledge_receipt_ledger();init_skill_propagation_gate();_internals232={validateAndCommitTerminalBatch,recordKnowledgeEvent,runDirectivePredicate,escalateViolatedEntries},VERDICT_PATTERN=/\b(VERIFIED|VIOLATED|N\/A)\s*:\s*([^:\s]{1,512})\s*:\s*([^:\s]{1,512})(?:\s+(?:evidence|reason)\s*=\s*([^\n\r]+?))?(?=$|[\n\r]|\s+(?:VERIFIED|VIOLATED|N\/A)\b)/gi});import{createHash as createHash95}from"node:crypto";function delegationCostRecordMaterial(record3){if(!record3.laneId)return`${record3.parentSessionId}\x00${record3.callID}`;return`${record3.parentSessionId}\x00${record3.callID}\x00lane:${record3.laneId}`}function buildDelegationTerminalIdentityFields(input){let material=delegationCostRecordMaterial(input.record);return{record_id:createHash95("sha256").update(`delegation-cost-id-v1\x00${material}`).digest("hex").slice(0,32),identity_fingerprint:createHash95("sha256").update(`delegation-cost-identity-v1\x00${material}\x00${input.record.swarmPrefixedAgent}\x00${input.model??""}`).digest("hex").slice(0,32),version:1,parent_session_digest:createHash95("sha256").update(`delegation-cost-parent-v1\x00${input.record.parentSessionId}`).digest("hex").slice(0,32),child_session_digest:createHash95("sha256").update(`delegation-cost-child-v1\x00${input.record.subagentSessionId}`).digest("hex").slice(0,32),...input.recovered?{recovered:!0}:{}}}var init_delegation_cost_identity=()=>{};var exports_delegation_lifecycle={};__export(exports_delegation_lifecycle,{settleDelegationTerminal:()=>settleDelegationTerminal,recoverTerminalLaneReceipts:()=>recoverTerminalLaneReceipts,isBenignSettleOutcome:()=>isBenignSettleOutcome,emitDelegationEventlessTerminalEnd:()=>emitDelegationEventlessTerminalEnd,emitDelegationBegin:()=>emitDelegationBegin,delegationCostRecordMaterial:()=>delegationCostRecordMaterial,buildDelegationTerminal:()=>buildDelegationTerminal,_internals:()=>_internals251,TERMINAL_LANE_RECEIPT_RECOVERY_DEADLINE_MS:()=>TERMINAL_LANE_RECEIPT_RECOVERY_DEADLINE_MS,MAX_TERMINAL_LANE_RECEIPT_RECOVERY:()=>MAX_TERMINAL_LANE_RECEIPT_RECOVERY});import*as fs177 from"node:fs";import*as path303 from"node:path";function isBenignSettleOutcome(kind){return kind==="duplicate"||kind==="conflict"||kind==="already_terminal_without_event"}function buildDelegationTerminal(record3,terminal,now2){return{eventId:buildBackgroundCompletionEventId({correlationId:record3.correlationId,jobId:record3.jobId,status:terminal.status,resultDigest:terminal.result.digest}),status:terminal.status,recordedAt:now2,result:terminal.result}}async function settleDelegationTerminal(directory,record3,terminal,observations={},now2=Date.now()){let claim=await _internals251.claimTerminalResult(directory,record3.correlationId,buildDelegationTerminal(record3,terminal,now2));if(claim){if(claim.disposition==="claimed")return await runDelegationTerminalObservations(directory,claim.record,terminal,observations,now2),{kind:"claimed",record:claim.record};if(claim.disposition==="duplicate"&&observations.transcript)await reconcileLaneKnowledgeReceipts(directory,claim.record,observations,!0);return{kind:"duplicate",record:claim.record}}let reread=_internals251.findByCorrelationIdDetailed(directory,record3.correlationId);if(reread.status==="uncertain")return{kind:"uncertain",reason:reread.reason};if(!reread.value)return{kind:"missing"};if(isTerminalDelegationStatus(reread.value.status)){if(reread.value.terminalResult)return{kind:"conflict",record:reread.value};return emitDelegationEventlessTerminalEnd(reread.value,reread.value.status),{kind:"already_terminal_without_event",record:reread.value}}return{kind:"not_open",record:reread.value}}function emitDelegationBegin(record3){try{_internals251.telemetry.delegationBegin(record3.parentSessionId,record3.swarmPrefixedAgent,record3.planTaskId??"")}catch{}}function emitDelegationCostObservation(record3,observations,terminalStatus,recovered=!1){try{let costFields=buildDelegationCostFields({raw:observations.costRaw,model:observations.model,pricing:observations.pricing});Object.assign(costFields,buildDelegationTerminalIdentityFields({record:record3,model:observations.model,recovered})),_internals251.telemetry.delegationEnd(record3.parentSessionId,record3.swarmPrefixedAgent,record3.planTaskId??"",terminalStatus,costFields)}catch(error93){log(`[delegation-lifecycle] cost observation skipped: ${error93 instanceof Error?error93.message:String(error93)}`)}}function emitDelegationEventlessTerminalEnd(record3,terminalStatus){emitDelegationCostObservation(record3,{},terminalStatus,!0)}async function appendDelegationTrajectoryObservation(directory,record3,terminalStatus,observations,now2){try{let lastStep=await getCurrentStep(record3.parentSessionId,directory);seedTrajectoryStepCounter(record3.parentSessionId,directory,lastStep);let entry={step:nextTrajectoryStep(record3.parentSessionId,directory),agent:record3.swarmPrefixedAgent,action:"delegate",target:record3.laneId??record3.correlationId,intent:`dispatch_lanes terminal ${terminalStatus}`,timestamp:new Date(now2).toISOString(),result:terminalStatus==="completed"?"success":"failure",tool:"dispatch_lanes",...observations.startedAt!==void 0?{elapsed_ms:Math.max(0,now2-observations.startedAt)}:{},...record3.batchId!==void 0?{batchId:record3.batchId}:{},laneId:record3.laneId??record3.correlationId,...record3.planTaskId?{taskId:record3.planTaskId}:{}};await appendTrajectoryEntry(record3.parentSessionId,entry,directory)}catch{}}async function reconcileLaneKnowledgeReceipts(directory,record3,observations,replay=!1){if(!observations.transcript)return;try{let ack=await collectLaneDelegateAcks({directory,sessionId:record3.subagentSessionId,agent:record3.swarmPrefixedAgent,transcript:observations.transcript,replay});if(record3.normalizedAgent!=="reviewer")return;let phase=ack.phases.find((value)=>Boolean(value));if(!phase)return;let directivesToVerify=await readPhaseDirectivesToVerify(directory,phase);if(directivesToVerify.length===0)return;await reconcileReviewerVerdicts({directory,transcript:observations.transcript,directivesToVerify,sessionId:record3.subagentSessionId,agent:"reviewer"})}catch{}}async function runDelegationTerminalObservations(directory,record3,terminal,observations,now2){emitDelegationCostObservation(record3,observations,terminal.status),await appendDelegationTrajectoryObservation(directory,record3,terminal.status,observations,now2),await reconcileLaneKnowledgeReceipts(directory,record3,observations)}function candidateAfter(record3,cursor){if(record3.updatedAt!==cursor.updatedAt)return record3.updatedAt>cursor.updatedAt;return record3.correlationId>cursor.correlationId}function readRecoveryCursor(directory){try{let filePath=path303.join(directory,".swarm",RECOVERY_CURSOR_FILE);if(!fs177.existsSync(filePath))return null;let parsed=JSON.parse(fs177.readFileSync(filePath,"utf-8"));if(typeof parsed.updatedAt==="number"&&Number.isFinite(parsed.updatedAt)&&typeof parsed.correlationId==="string"&&parsed.correlationId.length>0)return{updatedAt:parsed.updatedAt,correlationId:parsed.correlationId};return null}catch{return null}}function writeRecoveryCursor(directory,cursor){try{let swarmDir=path303.join(directory,".swarm");fs177.mkdirSync(swarmDir,{recursive:!0});let filePath=path303.join(swarmDir,RECOVERY_CURSOR_FILE);if(cursor===null)fs177.rmSync(filePath,{force:!0});else fs177.writeFileSync(filePath,JSON.stringify(cursor),"utf-8")}catch{}}function isRecoverableTerminalLaneRecord(record3){return Boolean(record3.laneId&&record3.terminalResult&&typeof record3.terminalResult.result.text==="string"&&record3.terminalResult.result.text.length>0)}async function recoverTerminalLaneReceipts(directory,records,options={}){let now2=options.now??Date.now,deadlineMs=options.deadlineMs??TERMINAL_LANE_RECEIPT_RECOVERY_DEADLINE_MS,deadline=now2()+deadlineMs;if(records!==void 0){let recovered2=0;for(let record3 of records){if(!isRecoverableTerminalLaneRecord(record3))continue;let transcript=record3.terminalResult?.result.text;if(!transcript)continue;if(now2()>=deadline)return{recovered:recovered2,exhaustedBudget:!0};try{await reconcileLaneKnowledgeReceipts(directory,record3,{transcript},!0),recovered2+=1}catch{}}return{recovered:recovered2,exhaustedBudget:!1}}let enumeration=readDelegationsDetailed(directory);if(enumeration.status==="uncertain")return warn(`[delegation-lifecycle] terminal-lane receipt recovery deferred: delegation store unreadable after ${enumeration.attempts} attempts (${enumeration.reason})`),{recovered:0,exhaustedBudget:!1};let candidates=enumeration.records.filter(isRecoverableTerminalLaneRecord).sort((left,right)=>{if(left.updatedAt!==right.updatedAt)return left.updatedAt-right.updatedAt;return left.correlationId<right.correlationId?-1:left.correlationId>right.correlationId?1:0});if(candidates.length===0)return{recovered:0,exhaustedBudget:!1};let cursor=readRecoveryCursor(directory),selected=cursor?candidates.filter((record3)=>candidateAfter(record3,cursor)):candidates,wrapped=!1;if(selected.length===0)selected=candidates,wrapped=!0;let recovered=0,lastProcessed=null;for(let record3 of selected){if(recovered>=MAX_TERMINAL_LANE_RECEIPT_RECOVERY)break;if(now2()>=deadline)break;let transcript=record3.terminalResult?.result.text;if(!transcript)continue;try{await reconcileLaneKnowledgeReceipts(directory,record3,{transcript},!0),recovered+=1,lastProcessed={updatedAt:record3.updatedAt,correlationId:record3.correlationId}}catch{lastProcessed={updatedAt:record3.updatedAt,correlationId:record3.correlationId}}}let lastCandidate=selected[selected.length-1],processedAll=selected.length>0&&lastProcessed!==null&&lastCandidate!==void 0&&lastProcessed.updatedAt===lastCandidate.updatedAt&&lastProcessed.correlationId===lastCandidate.correlationId,nextCursor=wrapped&&processedAll?null:lastProcessed??cursor??null;if(nextCursor?.correlationId!==cursor?.correlationId)writeRecoveryCursor(directory,nextCursor);return{recovered,exhaustedBudget:recovered<selected.length&&(now2()>=deadline||recovered>=MAX_TERMINAL_LANE_RECEIPT_RECOVERY)}}var MAX_TERMINAL_LANE_RECEIPT_RECOVERY=64,TERMINAL_LANE_RECEIPT_RECOVERY_DEADLINE_MS=5000,RECOVERY_CURSOR_FILE="lane-receipt-recovery-cursor.json",_internals251;var init_delegation_lifecycle=__esm(()=>{init_delegate_ack_collector();init_phase_directives();init_reviewer_verdict_parser();init_trajectory_step_state();init_trajectory_store();init_cost_accounting();init_telemetry();init_logger();init_delegation_cost_identity();init_pending_delegations();init_delegation_cost_identity();registerStaleSweepObserver((record3)=>{emitDelegationEventlessTerminalEnd(record3,"stale")});_internals251={claimTerminalResult,findByCorrelationId,findByCorrelationIdDetailed,telemetry}});var exports_design_doc_drift={};__export(exports_design_doc_drift,{runDesignDocDriftCheck:()=>runDesignDocDriftCheck,_internals:()=>_internals272});import*as fs198 from"node:fs";import*as path326 from"node:path";function mtimeMsOrNull(absPath){try{return fs198.statSync(absPath).mtimeMs}catch{return null}}function resolveAnchorWithin(directory,anchor){if(!anchor||typeof anchor!=="string")return null;let root=path326.resolve(directory),resolved=path326.resolve(root,anchor),rel3=path326.relative(root,resolved);if(rel3.startsWith("..")||path326.isAbsolute(rel3))return null;return resolved}async function runDesignDocDriftCheck(directory,phase,outDir){try{let root=path326.resolve(directory),outAbs=path326.resolve(root,outDir),outRel=path326.relative(root,outAbs);if(outRel.startsWith("..")||path326.isAbsolute(outRel))return null;let docMtimes=new Map,checkedDocs=[],missingDocs=[];for(let[docName,relFile]of Object.entries(DESIGN_DOC_FILES)){let abs=path326.join(outAbs,relFile),mtime=mtimeMsOrNull(abs);if(docMtimes.set(docName,mtime),mtime===null)missingDocs.push(path326.join(outDir,relFile));else checkedDocs.push(path326.join(outDir,relFile))}let traceabilityAbs=path326.join(outAbs,TRACEABILITY_REL),registry3=null;try{if((await fs198.promises.stat(traceabilityAbs)).size<=MAX_TRACEABILITY_BYTES){let raw=await fs198.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},locator=phaseReportLocator("design_doc_drift",phase);return await upsertPhaseReportDb(directory,"design_doc_drift",phase,JSON.stringify(report,null,2)),getGlobalEventBus().publish("curator.docdrift.completed",{phase,verdict,stale_count:staleSections.length,report_path:locator}),report}catch(err){try{getGlobalEventBus().publish("curator.error",{operation:"docdrift",phase,error:String(err)})}catch{}return warn(`[design-doc-drift] check failed for phase ${phase}: ${String(err)}`),null}}var MAX_TRACEABILITY_BYTES=1048576,DESIGN_DOC_FILES,TRACEABILITY_REL,_internals272;var init_design_doc_drift=__esm(()=>{init_event_bus();init_phase_report_store();init_effective_spec();init_logger();DESIGN_DOC_FILES={domain:"domain.md","technical-spec":"technical-spec.md","behavior-spec":"behavior-spec.md","reference-impl":path326.join("reference","reference-impl.md"),"idiom-notes":path326.join("reference","idiom-notes.md")},TRACEABILITY_REL=path326.join("reference","traceability.json");_internals272={mtimeMsOrNull,resolveAnchorWithin,DESIGN_DOC_FILES}});var exports_project_context={};__export(exports_project_context,{buildProjectContext:()=>buildProjectContext,_internals:()=>_internals304,LANG_BACKEND_DETECTION_TIMEOUT_MS:()=>LANG_BACKEND_DETECTION_TIMEOUT_MS});import*as fs228 from"node:fs";import*as path364 from"node:path";function detectFileExists2(directory,pattern){if(pattern.includes("*")||pattern.includes("?"))try{let files=fs228.readdirSync(directory),regex=new RegExp(`^${pattern.replace(/\./g,"\\.").replace(/\*/g,".*").replace(/\?/g,".")}$`);return files.some((f)=>regex.test(f))}catch{return!1}try{return fs228.accessSync(path364.join(directory,pattern)),!0}catch{return!1}}function selectTestCommandFromScriptsTest(backend,directory){let pkgRaw;try{pkgRaw=fs228.readFileSync(path364.join(directory,"package.json"),"utf-8")}catch{return null}let pkg;try{pkg=JSON.parse(pkgRaw)}catch{return null}let script=pkg.scripts?.test;if(!script)return null;let fwName=null;if(script.includes("vitest"))fwName="vitest";else if(script.includes("jest"))fwName="jest";else if(script.includes("mocha"))fwName="mocha";else if(script.includes("bun test"))fwName="bun:test";if(!fwName)return null;let fw=backend.test.frameworks.find((f)=>f.name===fwName);return fw?fw.cmd:null}function selectTestCommandFast(backend,directory){let fromScripts=selectTestCommandFromScriptsTest(backend,directory);if(fromScripts!==null)return fromScripts;let sorted2=[...backend.test.frameworks].sort((a,b)=>b.priority-a.priority);for(let fw of sorted2){if(!detectFileExists2(directory,fw.detect))continue;return fw.cmd}return null}function selectBuildCommandFast(backend,directory){let sorted2=[...backend.build.commands].sort((a,b)=>b.priority-a.priority);for(let cmd of sorted2){if(cmd.detectFile&&!detectFileExists2(directory,cmd.detectFile))continue;return cmd.cmd}return null}function selectLintCommand(backend,directory){let sorted2=[...backend.lint.linters].sort((a,b)=>b.priority-a.priority);for(let lint2 of sorted2){if(!detectFileExists2(directory,lint2.detect))continue;return lint2.cmd}return null}async function buildProjectContext(directory,signal2){let backend=await _internals304.pickBackend(directory,signal2);if(!backend)return null;let profiles=_internals304.pickedProfiles(directory),ctx=emptyProjectContext();ctx.PROJECT_LANGUAGE=backend.displayName;let buildCmd=selectBuildCommandFast(backend,directory);if(buildCmd)ctx.BUILD_CMD=buildCmd;let testCmd=selectTestCommandFast(backend,directory);if(testCmd)ctx.TEST_CMD=testCmd;let lintCmd=selectLintCommand(backend,directory);if(lintCmd)ctx.LINT_CMD=lintCmd;if(backend.id==="php"){let overlay=getLaravelCommandOverlay(directory);if(overlay){if(ctx.TEST_CMD=overlay.testCommand,overlay.lintCommand)ctx.LINT_CMD=overlay.lintCommand}}let[frameworkSel,entryPoints]=await Promise.all([backend.selectFramework?backend.selectFramework(directory).catch(()=>null):Promise.resolve(null),backend.selectEntryPoints?backend.selectEntryPoints(directory).catch(()=>[]):Promise.resolve([])]);if(frameworkSel)ctx.PROJECT_FRAMEWORK=frameworkSel.name;if(entryPoints.length>0)ctx.ENTRY_POINTS=entryPoints.join(", ");if(backend.prompts.coderConstraints.length>0)ctx.CODER_CONSTRAINTS=bulletList(backend.prompts.coderConstraints);if(backend.prompts.testConstraints&&backend.prompts.testConstraints.length>0)ctx.TEST_CONSTRAINTS=bulletList(backend.prompts.testConstraints);if(backend.prompts.reviewerChecklist.length>0)ctx.REVIEWER_CHECKLIST=bulletList(backend.prompts.reviewerChecklist);if(profiles.length>1)ctx.PROJECT_CONTEXT_SECONDARY_LANGUAGES=profiles.slice(1).map((p)=>p.id).join(", ");return ctx}var LANG_BACKEND_DETECTION_TIMEOUT_MS=300,_internals304;var init_project_context=__esm(()=>{init_dispatch();init_framework_detector();_internals304={pickBackend,pickedProfiles}});init_package();init_agents2();init_critic();import{createHash as createHash108}from"node:crypto";import*as path365 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_manager4();init_manager();init_utils();import*as fs143 from"node:fs";import*as path255 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 path255.resolve(this.directory,".swarm")}getPlanJsonPath(){return path255.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=fs143.statSync(this.getPlanJsonPath());this.lastStat={mtimeMs:stats2.mtimeMs,size:stats2.size}}catch{this.lastStat=null}}setupNativeWatcher(){let swarmDir=this.getSwarmDir();try{if(!fs143.existsSync(swarmDir))return log("[PlanSyncWorker] Swarm directory does not exist yet"),!1;return this.watcher=fs143.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(!fs143.existsSync(planPath)){if(this.lastStat!==null)this.lastStat=null,log("[PlanSyncWorker] plan.json deleted");return}let stats2=fs143.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(_internals51.loadPlanJsonOnly(this.directory),this.syncTimeoutMs,"Sync operation timed out");if(plan&&plan.phases.length>0)await _internals51.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=path255.join(swarmDir,"plan.json"),markerPath=path255.join(swarmDir,".plan-write-marker"),planStats=fs143.statSync(planJsonPath),planMtimeMs=Math.floor(planStats.mtimeMs),markerContent=fs143.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((resolve101,reject)=>{let timer=setTimeout(()=>{reject(Error(`${timeoutMessage2} (${ms}ms)`))},ms);promise3.then((result)=>{clearTimeout(timer),resolve101(result)}).catch((error93)=>{clearTimeout(timer),reject(error93)})})}}init_pr_event_subscribers();init_pr_monitor_worker();init_queue();init_status_artifact();init_trigger();init_worker();import{createHash as createHash89}from"node:crypto";init_zod();init_task_envelope();init_workspace_snapshot();init_plan_schema();init_schema();init_plan_task_id_context();init_task_id_resolver();init_task_result_classifier();init_utils2();init_ledger();init_manager();init_utils3();init_atomic_write();init_canonical_root();init_lock();init_task_file();import{createHash as createHash88}from"node:crypto";import*as fs145 from"node:fs";import*as path258 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 sha2569(value){return createHash88("sha256").update(value).digest("hex")}function policyDigest(policy){return sha2569(stableCanonicalStringify(policy??{}))}async function captureParticipationWorkspace(directory){let workspace=await captureWorkspaceSnapshotAsync(directory,{resolveCurrentPrHeadSha:!0});return{directory:workspace.directory,gitHead:workspace.gitHead,prHeadSha:workspace.prHeadSha}}function boundedPut(binding){let key2=correlationKey(binding.parentSessionId,binding.callId);foregroundReservations.delete(key2),foregroundReservations.set(key2,binding);while(foregroundReservations.size>MAX_PENDING_IN_MEMORY){let oldest=foregroundReservations.keys().next().value;if(!oldest)break;foregroundReservations.delete(oldest)}}function takeBinding(parentSessionId,callId){let key2=correlationKey(parentSessionId,callId),binding=foregroundReservations.get(key2)??null;return foregroundReservations.delete(key2),binding}async function persistWithBindingRecovery(directory,binding,operation){try{await withEvidenceLock(directory,PHASE_PARTICIPATION_FILE,"docs","phase-participation",operation)}catch(error93){throw boundedPut(binding),error93}}async function buildBinding(input){return{role:stripKnownSwarmPrefix(input.role),prefixedRole:input.role,planId:derivePlanId(input.plan),planIdentityHash:derivePlanIdentityHash(input.plan),planStructureHash:computePlanStructureHash(input.plan),phase:input.phase,taskId:input.taskId,parentSessionId:input.parentSessionId,callId:input.callId,policyDigest:policyDigest(input.policy),workspace:await captureParticipationWorkspace(input.directory),capturedAt:Date.now()}}function extractPlanTaskId2(args2,plan){let context=collectPlanTaskIdContextFromPhases(plan.phases),result=resolveTaskId(args2,{policy:"plan",...toTaskIdPlanContextOptions(context)});if(result.status!=="resolved")return null;if(context.status==="over_limit"&&!plan.phases.some((phase)=>phase?.tasks?.some((task2)=>task2?.id===result.taskId)))return null;return result.taskId}function storePath6(directory){return validateSwarmPath(directory,PHASE_PARTICIPATION_FILE)}function readRawStore(directory){let filePath;try{filePath=storePath6(directory)}catch(error93){return{status:"unreadable",error:error93}}let descriptor,bytes;try{let pathStat=fs145.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=fs145.openSync(filePath,fs145.constants.O_RDONLY|(fs145.constants.O_NOFOLLOW??0));let openedStat=fs145.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=fs145.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{fs145.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 fs145.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 fs145.promises.open(filePath,fs145.constants.O_RDONLY|(fs145.constants.O_NOFOLLOW??0));try{let openedStat=await handle.stat();if(!openedStat.isFile()||openedStat.dev!==pathStat.dev||openedStat.ino!==pathStat.ino||openedStat.size>maxBytes)throw Error("bounded evidence artifact changed while being opened");let bounded=Buffer.allocUnsafe(maxBytes+1),offset=0;while(offset<bounded.byteLength){let{bytesRead}=await handle.read(bounded,offset,bounded.byteLength-offset,null);if(bytesRead===0)break;offset+=bytesRead}if(offset>maxBytes)throw Error("bounded evidence artifact exceeds its byte limit");return bounded.subarray(0,offset)}finally{try{await handle.close()}catch{}}}function quarantineFullError(){return Error("PHASE_PARTICIPATION_QUARANTINE_FULL: preserved corrupt evidence reached its bounded retention limit; an operator must archive the quarantine before docs can be re-dispatched.")}async function quarantineCorruptBytes(directory,bytes){let digest4=sha2569(bytes),quarantineDir=validateSwarmPath(directory,PHASE_PARTICIPATION_QUARANTINE_DIR);await fs145.promises.mkdir(quarantineDir,{recursive:!0});let quarantineStat=await fs145.promises.lstat(quarantineDir);if(quarantineStat.isSymbolicLink()||!quarantineStat.isDirectory())throw Error("PHASE_PARTICIPATION_QUARANTINE_UNREADABLE: quarantine is not a regular directory.");let target=validateSwarmPath(directory,`${PHASE_PARTICIPATION_QUARANTINE_DIR}/${digest4}.bin`);try{if(!(await readBoundedRegularFile(target,MAX_PHASE_PARTICIPATION_BYTES)).equals(bytes))throw Error("hash-addressed quarantine content mismatch");return}catch(error93){if(error93.code!=="ENOENT")throw error93}let count=0,totalBytes=0,scanned=0,handle=await fs145.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 fs145.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 writeStore3(directory,store){let validatedStore=StoreSchema.parse(store);validatedStore.pending.sort((left,right)=>left.capturedAt-right.capturedAt),validatedStore.receipts.sort((left,right)=>left.completedAt-right.completedAt);let serialized3=JSON.stringify(validatedStore,null,2);while(Buffer.byteLength(serialized3,"utf8")>MAX_PHASE_PARTICIPATION_BYTES){let pendingTime=validatedStore.pending[0]?.capturedAt??1/0,receiptTime=validatedStore.receipts[0]?.completedAt??1/0;if(pendingTime===1/0&&receiptTime===1/0)throw Error("PHASE_PARTICIPATION_WRITE_OVERSIZED: even an empty participation store exceeds its byte limit.");if(pendingTime<=receiptTime)validatedStore.pending.shift();else validatedStore.receipts.shift();validatedStore=StoreSchema.parse(validatedStore),serialized3=JSON.stringify(validatedStore,null,2)}await fs145.promises.mkdir(path258.dirname(storePath6(directory)),{recursive:!0}),await atomicWriteFile(storePath6(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 sameProjectRoot(expected.directory,current.directory)&&expected.gitHead===current.gitHead&&expected.prHeadSha===current.prHeadSha}function resultText(output){if(!output||typeof output!=="object")return{text:"",childSessionId:null};let record3=output,rawOutput=typeof record3.output==="string"?record3.output:"",envelope=parseTaskEnvelope(rawOutput);if(envelope?.state==="completed")return{text:envelope.resultText??"",childSessionId:envelope.sessionId};return{text:rawOutput,childSessionId:null}}function envelopeFromOutput(output){if(typeof output==="string")return parseTaskEnvelope(output);if(!output||typeof output!=="object")return null;let rawOutput=output.output;return typeof rawOutput==="string"?parseTaskEnvelope(rawOutput):null}function validateMetadata(output,parentSessionId,childSessionId){if(!output||typeof output!=="object")return{valid:!0,childSessionId};let metadata=output.metadata;if(!metadata||typeof metadata!=="object")return{valid:!0,childSessionId};let meta3=metadata;if(typeof meta3.parentSessionId==="string"&&meta3.parentSessionId!==parentSessionId)return{valid:!1,childSessionId:null};let metadataChild=typeof meta3.sessionId==="string"&&meta3.sessionId.length>0?meta3.sessionId:null;if(childSessionId&&metadataChild&&childSessionId!==metadataChild)return{valid:!1,childSessionId:null};return{valid:!0,childSessionId:childSessionId??metadataChild}}function addReceipt(store,pending,text,childIdentityAvailable){let receiptId=sha2569(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:sha2569(text),completedAt:Date.now(),childIdentityAvailable};store.receipts=store.receipts.filter((existing)=>existing.receiptId!==receiptId&&!(existing.planIdentityHash===receipt.planIdentityHash&&existing.planStructureHash===receipt.planStructureHash&&existing.phase===receipt.phase&&existing.role===receipt.role)),store.receipts.push(receipt),store.receipts=store.receipts.slice(-MAX_PHASE_PARTICIPATION_RECEIPTS)}async function reserveApprovedPhaseParticipation(input){if(input.tool.toLowerCase()!=="task")return;let rawRole=input.args.subagent_type;if(typeof rawRole!=="string"||stripKnownSwarmPrefix(rawRole)!=="docs")return;let plan=await loadPlan(input.directory);if(!plan)return;let binding=await buildBinding({plan,phase:getCurrentPhase(plan),role:rawRole,parentSessionId:input.parentSessionId,callId:input.callId,taskId:extractPlanTaskId2(input.args,plan),policy:input.policy,directory:input.directory});await withEvidenceLock(input.directory,PHASE_PARTICIPATION_FILE,"docs","phase-participation",async()=>{let store=await loadWritableStoreUnderLock(input.directory);await writeStore3(input.directory,store)}),boundedPut(binding)}async function observePhaseParticipationToolResult(input){if(input.tool.toLowerCase()!=="task")return;let binding=takeBinding(input.parentSessionId,input.callId);if(!binding)return;let envelope=envelopeFromOutput(input.output);if(envelope?.state==="running"){let{subagentSessionId}=extractDispatchIds(input.output);if(!subagentSessionId||subagentSessionId!==envelope.sessionId)return;let pending2={...binding,childSessionId:subagentSessionId};await persistWithBindingRecovery(input.directory,binding,async()=>{let store=await loadWritableStoreUnderLock(input.directory);store.pending=store.pending.filter((existing)=>existing.childSessionId!==pending2.childSessionId&&!(existing.parentSessionId===pending2.parentSessionId&&existing.callId===pending2.callId)),store.pending.push(pending2),store.pending=store.pending.slice(-MAX_PHASE_PARTICIPATION_PENDING),await writeStore3(input.directory,store)});return}if(envelope&&envelope.state!=="completed")return;if(classifyTaskResult(input.output)!=="success")return;let extracted=resultText(input.output),text=extracted.text.trim();if(!text)return;let metadata=validateMetadata(input.output,input.parentSessionId,extracted.childSessionId);if(!metadata.valid)return;let childSessionId=metadata.childSessionId,currentPlan=await loadPlan(input.directory);if(!currentPlan||!bindingMatchesPlan(binding,currentPlan,binding.phase))return;if(!workspaceIdentityIsFresh(binding.workspace,await captureParticipationWorkspace(input.directory)))return;let pending={...binding,childSessionId:childSessionId??`unavailable:${sha2569(correlationKey(input.parentSessionId,input.callId))}`};await persistWithBindingRecovery(input.directory,binding,async()=>{let store=await loadWritableStoreUnderLock(input.directory);addReceipt(store,pending,text,childSessionId!==null),await writeStore3(input.directory,store)})}async function completeBackgroundPhaseParticipation(input){if(stripKnownSwarmPrefix(input.record.normalizedAgent)!=="docs")return!1;let text=input.resultText.trim();if(!text)return!1;return withEvidenceLock(input.directory,PHASE_PARTICIPATION_FILE,"docs","phase-participation",async()=>{let store=await loadWritableStoreUnderLock(input.directory),currentPlan=await loadPlan(input.directory),existingReceipt=store.receipts.find((receipt)=>receipt.childSessionId===input.record.subagentSessionId&&receipt.parentSessionId===input.record.parentSessionId&&receipt.callId===input.record.callID&&receipt.role===input.record.normalizedAgent&&receipt.prefixedRole===input.record.swarmPrefixedAgent&&receipt.taskId===input.record.planTaskId);if(existingReceipt&¤tPlan&&bindingMatchesPlan(existingReceipt,currentPlan,existingReceipt.phase))return!0;let pending=store.pending.find((candidate2)=>candidate2.childSessionId===input.record.subagentSessionId&&candidate2.parentSessionId===input.record.parentSessionId&&candidate2.callId===input.record.callID&&candidate2.role===input.record.normalizedAgent&&candidate2.prefixedRole===input.record.swarmPrefixedAgent&&candidate2.taskId===input.record.planTaskId);if(!pending)return!1;let plan=currentPlan;if(!plan||!bindingMatchesPlan(pending,plan,pending.phase))return!1;if(!workspaceIdentityIsFresh(pending.workspace,await captureParticipationWorkspace(input.directory)))return!1;if(pending.taskId!==null&&input.record.ingestion?.state!=="consumed")return!1;return addReceipt(store,pending,text,!0),store.pending=store.pending.filter((candidate2)=>candidate2.childSessionId!==pending.childSessionId),await writeStore3(input.directory,store),!0})}async function readPhaseParticipation(directory,plan,phase,role){let read=readRawStore(directory);if(read.status!=="valid")return{status:read.status,found:!1};let canonicalRole2=stripKnownSwarmPrefix(role),currentWorkspace=await captureParticipationWorkspace(directory);return{status:"valid",found:read.store.receipts.some((receipt)=>receipt.role===canonicalRole2&&bindingMatchesPlan(receipt,plan,phase)&&workspaceIdentityIsFresh(receipt.workspace,currentWorkspace))}}init_gate_evidence();init_worktree_isolation();init_helpers();init_state2();init_canonical_root();init_logger();init_coder_settlement();init_merge2();init_pending_delegations();init_loader();init_task_gate_requirements();init_gate_evidence();init_gate_evidence_classification();init_review_receipt_collector();init_reviewer_scope_file_fingerprint();init_routing_enforcement();init_scope_binding();init_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 state2=getTaskState(parentSession,taskId);if(state2!=="idle"&&state2!=="coder_delegated"&&state2!=="rework_required")return{ok:!1,consumed:!1,reason:`background coder completion is late for task ${taskId}: current state is ${state2}`}}let accepted=attributedFiles.length>0,expectedGeneration=args2.record.taskChangeContext?.workflowGeneration??0,transitionId=`background-coder:${args2.record.correlationId}`,existingEvidence=await readTaskEvidence(args2.directory,taskId),existingWorkflow=getTaskWorkflowSnapshot(existingEvidence),updated=existingWorkflow.authoritative&&existingWorkflow.lastTransitionId===transitionId&&existingWorkflow.lastOutcome===(accepted?"accepted_mutation":"dispatch_no_mutation")&&existingWorkflow.generation===expectedGeneration+(accepted?1:0)?existingEvidence:await transitionTaskWorkflowEvidence(args2.directory,taskId,accepted?{type:"accepted_mutation",agentType:"coder",context:{testEngineerExempt:isMarkdownOnlyTaskChange(taskChangeContext?.declaredFiles,attributedFiles)},expectedGeneration,transitionId}:{type:"dispatch_no_mutation",agentType:"coder",expectedGeneration,transitionId});if(accepted){let workflow=getTaskWorkflowSnapshot(updated),parentSession2=swarmState.agentSessions.get(args2.record.parentSessionId);if(parentSession2){if(!recordModifiedFilesForTask(parentSession2,taskId,attributedFiles))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 rejected2=await transitionTaskWorkflowEvidence(args2.directory,taskId,{type:"stage_b_failed",gate:stageBRole,expectedGeneration:args2.record.workflowGeneration,transitionId:`background-gate-failed:${args2.record.correlationId}`}),parentSession=swarmState.agentSessions.get(args2.record.parentSessionId);if(parentSession)parentSession.taskWorkflowStates.set(taskId,"rework_required"),parentSession.stageBCompletion?.delete(taskId),updateTaskWorkflowCache(parentSession,taskId,getTaskWorkflowSnapshot(rejected2));return{ok:!1,consumed:!0,reason:verdict==="fail"?`background ${stageBRole} rejected task ${taskId}`:`background ${stageBRole} returned no valid structured verdict for task ${taskId}`}}let preparedRoute,routeCompleteForPersistence;if(stageBRole){let parentSession=swarmState.agentSessions.get(args2.record.parentSessionId);if(parentSession){preparedRoute=resolveBackgroundStageBRoute({directory:args2.directory,taskId,parentSessionId:args2.record.parentSessionId,role:stageBRole,callId:args2.record.callID,childSessionId:args2.record.subagentSessionId,generation:args2.record.workflowGeneration,session:parentSession});let routeEnabled=(()=>{try{return loadPluginConfig(args2.directory).review_routing?.enforce_receipts??!0}catch{return!0}})(),routeDecision=enforcePersistedReviewRouteReceipt({projectRoot:args2.directory,sessionId:args2.record.parentSessionId,taskId,receipts:preparedRoute.prospective,enforcementEnabled:routeEnabled,legacyUnrouted:preparedRoute.legacyUnrouted,requireEvidenceBindings:!0,requireCompleteEvidence:!1,expectedDispatch:preparedRoute.binding?{role:preparedRoute.binding.role,identity:preparedRoute.binding.identity,callId:preparedRoute.binding.callId,childSessionId:preparedRoute.binding.childSessionId,generation:preparedRoute.binding.generation}:void 0});if(!routeDecision.canAdvance)return warn(`[background-stage-b] route receipt blocked before evidence publication for ${taskId}: ${routeDecision.reason??"unknown reason"}`),{ok:!1,consumed:!1,reason:`route receipt blocked before Stage-B evidence publication: ${routeDecision.reason??"unknown reason"}`};if(routeEnabled&&preparedRoute.route?.kind==="review_route_receipt")routeCompleteForPersistence=enforcePersistedReviewRouteReceipt({projectRoot:args2.directory,sessionId:args2.record.parentSessionId,taskId,receipts:preparedRoute.prospective,enforcementEnabled:!0,legacyUnrouted:preparedRoute.legacyUnrouted,requireEvidenceBindings:!0,requireCompleteEvidence:!0}).canAdvance}else{let route=readReviewRouteReceiptSync({projectRoot:args2.directory,sessionId:args2.record.parentSessionId,taskId});if(route?.kind!=="review_route_router_error"||route.sessionId!==args2.record.parentSessionId||route.taskId!==taskId)return{ok:!1,consumed:!1,reason:"route receipt blocked before Stage-B evidence publication: parent session is unavailable and recovery receipt is not identity-bound"}}}let routeEvidenceRollback=null;if(preparedRoute?.binding){let parentSession=swarmState.agentSessions.get(args2.record.parentSessionId);if(!parentSession)return warn(`[background-stage-b] route receipt blocked before evidence publication for ${taskId}: parent session unavailable`),{ok:!1,consumed:!1,reason:"route receipt blocked before Stage-B evidence publication: parent session unavailable"};if(routeEvidenceRollback=reserveStageBRouteEvidence(parentSession,taskId,preparedRoute.binding),!routeEvidenceRollback)return warn(`[background-stage-b] route receipt blocked before evidence publication for ${taskId}: bounded route evidence capacity exceeded`),{ok:!1,consumed:!1,reason:"route receipt blocked before Stage-B evidence publication: bounded route evidence capacity exceeded"}}try{await recordGateEvidence(args2.directory,taskId,args2.record.normalizedAgent,args2.record.subagentSessionId,hasActiveTurboMode(args2.record.parentSessionId),{expectedGeneration:args2.record.workflowGeneration,transitionId:`background-gate:${args2.record.correlationId}`,ensureDefaultStageB:existingEvidence?.test_engineer_exempt!==!0,routeBinding:preparedRoute?.binding,routeComplete:routeCompleteForPersistence})}catch(err){throw routeEvidenceRollback?.(),err}if(args2.record.normalizedAgent==="reviewer")await collectReviewerReceiptFromTranscript(args2.directory,{targetAgent:args2.record.swarmPrefixedAgent,prompt:args2.record.prompt?.text??"",transcript:args2.result.text??"",sessionID:args2.record.parentSessionId,taskId,reviewerCallID:args2.record.callID,consumeHandoff:!0},args2.reviewerReceiptOptions);if(args2.record.normalizedAgent==="reviewer"||args2.record.normalizedAgent==="test_engineer")applyStageBStateCompletion(taskId,args2.record.normalizedAgent,args2.record.parentSessionId,existingEvidence?.test_engineer_exempt===!0,args2.directory,args2.record.callID,args2.record.subagentSessionId,args2.record.workflowGeneration,preparedRoute);return{ok:!0,consumed:!0}}catch(err){let message=err instanceof Error?err.message:String(err);return warn(`[background-stage-b] ingestion failed: ${message}`),{ok:!1,consumed:!1,reason:`stage-b ingestion failed: ${message}`}}}function candidateSessions(parentSessionId){let parent=swarmState.agentSessions.get(parentSessionId);return parent?[parent]:[]}function routeDispatchKey(entry){if(!entry.callId||!entry.childSessionId||typeof entry.generation!=="number")return null;return[entry.role,entry.sessionId??"",entry.taskId??"",entry.callId,entry.childSessionId,String(entry.generation)].join("\x00")}function resolveBackgroundStageBRoute(input){let route=readReviewRouteReceiptSync({projectRoot:input.directory,sessionId:input.parentSessionId,taskId:input.taskId}),evidence2=getStageBRouteEvidence(input.session,input.taskId);if(evidence2.length===0)try{evidence2=routeEvidenceFromTaskGateRequirements(readTaskGateRequirementsReceiptsSync(input.directory,input.taskId))}catch{}let legacyUnrouted=route===null&&!isStageBRouteRequired(input.session,input.taskId)&&(()=>{try{let receipts=readTaskGateRequirementsReceiptsSync(input.directory,input.taskId);return receipts.length>0&&receipts.every((receipt)=>!receipt.routeBinding)}catch{return!1}})(),binding,prospective=evidence2;if(route?.kind==="review_route_receipt"){let identities=input.role==="reviewer"?route.identities.reviewers:route.identities.testEngineers,slots=input.role==="reviewer"?route.slots?.reviewers??identities:route.slots?.testEngineers??identities,dispatchKey2=[input.role,input.parentSessionId,input.taskId,input.callId,input.childSessionId,String(input.generation)].join("\x00"),retry=evidence2.find((entry)=>entry.role===input.role&&routeDispatchKey(entry)===dispatchKey2),usedSlots=new Set(evidence2.filter((entry)=>entry.role===input.role&&entry!==retry&&entry.slotId).map((entry)=>entry.slotId)),slotIndex=retry?slots.indexOf(retry.slotId??""):slots.findIndex((slot)=>!usedSlots.has(slot));if(slotIndex>=0&&slotIndex<identities.length){let slotId=slots[slotIndex],identity=identities[slotIndex];binding={role:input.role,identity,sessionId:input.parentSessionId,taskId:input.taskId,slotId,callId:input.callId,childSessionId:input.childSessionId,generation:input.generation},prospective=retry?evidence2.map((entry)=>entry===retry?binding:entry):[...evidence2,binding]}}return{route,binding,prospective,legacyUnrouted}}function applyStageBStateCompletion(taskId,agent,parentSessionId,testEngineerExempt,directory,callId,childSessionId,generation,preparedRoute){for(let session of candidateSessions(parentSessionId)){let resolvedRoute=preparedRoute??resolveBackgroundStageBRoute({directory,taskId,parentSessionId,role:agent,callId,childSessionId,generation:generation??-1,session}),{binding,prospective:routeEvidence,legacyUnrouted}=resolvedRoute,routeEnabled=(()=>{try{return loadPluginConfig(directory).review_routing?.enforce_receipts??!0}catch{return!0}})(),completionDecision=enforcePersistedReviewRouteReceipt({projectRoot:directory,sessionId:parentSessionId,taskId,receipts:routeEvidence,enforcementEnabled:routeEnabled,legacyUnrouted,requireEvidenceBindings:!0,requireCompleteEvidence:!1,expectedDispatch:binding?{role:binding.role,identity:binding.identity,callId:binding.callId,childSessionId:binding.childSessionId,generation:binding.generation}:void 0});if(!completionDecision.canAdvance){warn(`[background-stage-b] route receipt blocked ${taskId}: ${completionDecision.reason??"unknown reason"}`);continue}if(binding&&!recordStageBRouteEvidence(session,taskId,binding)){warn(`[background-stage-b] route receipt blocked before Stage-B evidence publication for ${taskId}: bounded route evidence capacity exceeded`);continue}recordStageBCompletion(session,taskId,agent);let state2=getTaskState(session,taskId);if(state2==="tests_run"||state2==="complete")continue;let routeComplete=enforcePersistedReviewRouteReceipt({projectRoot:directory,sessionId:parentSessionId,taskId,receipts:getStageBRouteEvidence(session,taskId),enforcementEnabled:routeEnabled,legacyUnrouted,requireEvidenceBindings:!0,requireCompleteEvidence:!0}).canAdvance;if(routeComplete&&(hasBothStageBCompletions(session,taskId)||testEngineerExempt&&agent==="reviewer")){try{if(state2==="coder_delegated"||state2==="pre_check_passed")advanceTaskState(session,taskId,"reviewer_run",{telemetrySessionId:parentSessionId});if(getTaskState(session,taskId)==="reviewer_run")advanceTaskState(session,taskId,"tests_run",{telemetrySessionId:parentSessionId})}catch(err){warn(`[background-stage-b] could not advance ${taskId} after ${agent}: ${err instanceof Error?err.message:String(err)}`)}continue}if(agent==="reviewer"&&(state2==="coder_delegated"||state2==="pre_check_passed"))try{advanceTaskState(session,taskId,"reviewer_run",{telemetrySessionId:parentSessionId})}catch(err){warn(`[background-stage-b] could not advance ${taskId} to reviewer_run: ${err instanceof Error?err.message:String(err)}`)}else if(routeComplete&&agent==="test_engineer"&&state2==="reviewer_run")try{advanceTaskState(session,taskId,"tests_run",{telemetrySessionId:parentSessionId})}catch(err){warn(`[background-stage-b] could not advance ${taskId} to tests_run: ${err instanceof Error?err.message:String(err)}`)}}}init_task_envelope();init_workspace_snapshot();var RETRYABLE_LEGACY_SETTLEMENT_TRANSFER_ERROR_CODES=new Set(["CODER_SETTLEMENT_LOCKED","EACCES","EBUSY","EIO","EPERM","ETIMEDOUT"]),observerInternals={transferCoderSettlementToBackground,markLegacyCoderSettlementTransferPending,sleep:(milliseconds)=>new Promise((resolve102)=>setTimeout(resolve102,milliseconds))};function createBackgroundCompletionObserver(opts){let{config:config3,directory}=opts,replayInProgress=!1,notifyLegacyCoderSettlementAdvisoryReplaced=(record3,replacement)=>{let session=swarmState.agentSessions.get(record3.parentSessionId);if(!session)return;if(removeQueuedLegacyTransferAdvisory(session.pendingAdvisoryMessages,replacement.advisory.eventId),replacement.replacedMessage)removeQueuedAdvisoryMessage(session.pendingAdvisoryMessages,[replacement.replacedMessage]);pushAdvisory(session,replacement.advisory.message)},event=async(input)=>{if(!config3.enabled)return;try{let pending,result,terminal,record3,text,isDuplicate=!1;if(input.trustedTerminal)pending=input.trustedTerminal.record,result=input.trustedTerminal.result,terminal=input.trustedTerminal.terminal,text=result.error??result.text??"",record3=pending,isDuplicate=!0;else{let evt=input?.event;if(!evt||evt.type!=="message.part.updated")return;let part=evt.properties?.part;if(!part||part.type!=="text"||part.synthetic!==!0||typeof part.text!=="string")return;let envelope=parseTaskEnvelope(part.text);if(!envelope||envelope.state!=="completed"&&envelope.state!=="error"&&envelope.state!=="cancelled")return;let parentSessionId=typeof part.sessionID==="string"?part.sessionID:"",lookup=await findDelegationForCompletion(directory,envelope.sessionId);if(lookup?.source==="uncertain"){warn(`[background] deferring terminal ingestion: delegation store unreadable for ${envelope.sessionId} (${lookup.uncertain})`);return}if(!lookup){log(`[background] trusted completion for ${envelope.sessionId} has no durable primary or fallback owner; ignored`);return}if(!parentSessionId||lookup.record.parentSessionId!==parentSessionId||lookup.record.subagentSessionId!==envelope.sessionId){warn(`[background] trusted completion identity mismatch for ${envelope.sessionId}; ignored`);return}if(pending=lookup.record,lookup.source==="fallback"){let promoted=await promoteDelegationFallback(directory,envelope.sessionId);if(!promoted){warn(`[background] fallback promotion failed for ${envelope.sessionId}; terminal work remains preserved`);return}pending=promoted.record}text=envelope.state==="error"||envelope.state==="cancelled"?envelope.errorText??"":envelope.resultText??"",result={...envelope.state==="error"?{error:text}:{text},chars:envelope.resultChars??text.length,truncated:envelope.resultTruncated??!1,digest:digest4(text)},terminal={eventId:buildBackgroundCompletionEventId({correlationId:pending.correlationId,jobId:pending.jobId,status:envelope.state,resultDigest:result.digest}),status:envelope.state,recordedAt:pending.terminalResult?.recordedAt??Date.now(),result};let terminalClaim=await claimTerminalResult(directory,pending.correlationId,terminal);if(!terminalClaim){warn(`[background] terminal claim failed for ${pending.correlationId}; ignored`);return}isDuplicate=terminalClaim.disposition==="duplicate",record3=terminalClaim.record}if(opts.onTerminalClaimed?.(record3),!input.trustedTerminal?.skipMaintenance)try{await maintainBackgroundDelegations(directory,{lockTimeoutMs:1000,reason:"trusted-terminal",onLegacyCoderSettlementReconciled:reconcilePending,onLegacyCoderSettlementAdvisoryReplaced:notifyLegacyCoderSettlementAdvisoryReplaced})}catch{}let legacyTransferPending=!1,legacyTransferRequiresManualRecovery=!1;if(terminal.status!=="completed"){if(isDuplicate&&record3.normalizedAgent!=="coder")return;if(record3.normalizedAgent==="coder"){let legacyTransfer=await transferLegacyCoderSettlement(directory,record3);if(legacyTransfer.disposition==="retry_pending")legacyTransferPending=!0;else if(legacyTransfer.disposition==="manual_recovery")legacyTransferRequiresManualRecovery=!0;if(record3.planTaskId){let expectedGeneration=record3.taskChangeContext?.workflowGeneration;if(expectedGeneration===void 0)warn(`[background] failed coder ${record3.correlationId} has no launch generation for task ${record3.planTaskId}`);else try{await transitionTaskWorkflowEvidence(directory,record3.planTaskId,{type:"dispatch_no_mutation",agentType:"coder",expectedGeneration,transitionId:`background-coder-terminal:${terminal.eventId}`})}catch(error93){warn(`[background] failed coder retry accounting was fenced for ${record3.planTaskId}: ${error93 instanceof Error?error93.message:String(error93)}`)}}try{await releaseCoderReservation(directory,record3,"recovered")}catch(error93){warn(`[background] failed coder reservation cleanup will be retried by admission reconciliation: ${error93 instanceof Error?error93.message:String(error93)}`)}if(record3.worktree){let descriptor=record3.worktree;if(!standardWorktreeByCallID.has(record3.callID))standardWorktreeByCallID.set(record3.callID,{callID:descriptor.callID,parentSessionID:descriptor.parentSessionId,taskId:descriptor.taskId,...descriptor.planTaskId?{planTaskId:descriptor.planTaskId}:{},handle:{worktreePath:descriptor.worktreePath,branchName:descriptor.branchName,purpose:"lane",id:descriptor.worktreeId,sessionId:descriptor.worktreeSessionId},mergeStrategy:descriptor.mergeStrategy,laneIndex:descriptor.laneIndex,...descriptor.worktreeDir?{worktree_dir:descriptor.worktreeDir}:{}});try{await abortStandardWorktreeDispatch(record3.callID,"cancelled",directory)}catch(error93){warn(`[background] failed coder worktree cleanup preserved the lane for manual recovery: ${error93 instanceof Error?error93.message:String(error93)}`)}}}if(discardScopeForRecord(record3),await publishAdvisory(directory,record3,terminal.eventId,legacyTransferPending?`${terminal.status==="cancelled"?"cancelled":"failed"}; legacy coder settlement transfer is pending; durable reconciliation will retry`:legacyTransferRequiresManualRecovery?`${terminal.status==="cancelled"?"cancelled":"failed"}; legacy coder settlement requires manual recovery; run /swarm recover for this task (or /swarm reset-session)`:terminal.status==="cancelled"?"cancelled":"failed"),!legacyTransferPending)await clearLegacyCoderSettlementTransferPending(directory,record3.correlationId);return}if(record3.normalizedAgent==="coder"){let settled=await settleCoder(directory,record3,terminal.eventId);if(record3=settled.record,!settled.ok){await publishAdvisory(directory,record3,terminal.eventId,settled.outcome);return}let legacyTransfer=await transferLegacyCoderSettlement(directory,record3);if(legacyTransfer.disposition==="retry_pending")legacyTransferPending=!0;else if(legacyTransfer.disposition==="manual_recovery")legacyTransferRequiresManualRecovery=!0}else if(!isDuplicate&&isBackgroundGateBearingRecord(record3)){if(validateStageBWorkspace(directory,record3).stale){await appendDelegationTransition(directory,record3.correlationId,{status:"stale"}),discardScopeForRecord(record3),await publishAdvisory(directory,record3,terminal.eventId,"stale");return}}if(record3.normalizedAgent==="coder"||isBackgroundGateBearingRecord(record3)){let ingestion=await claimDelegationIngestion(directory,record3.correlationId,{claimantId:terminal.eventId});if(ingestion?.disposition==="claimed"||ingestion?.disposition==="retry"){let applied2=await ingestBackgroundStageBCompletion({directory,record:ingestion.record,result:ingestion.record.result??result,reviewerReceiptOptions:opts.reviewerReceiptOptions}),claimToken=ingestion.record.ingestion?.claimToken;if(!claimToken){await publishAdvisory(directory,record3,terminal.eventId,"ingestion claim token missing");return}let ingestionCommit=await(opts.recordIngestionResult??recordDelegationIngestionResult)(directory,record3.correlationId,claimToken,applied2.ok);if(!ingestionCommit){warn(`[background] ingestion claim for ${record3.correlationId} expired or was fenced before commit; retry remains pending`);return}if(applied2.ok&&(ingestionCommit.status!=="consumed"||ingestionCommit.ingestion?.state!=="consumed"||ingestionCommit.ingestion.claimToken!==claimToken)){warn(`[background] ingestion commit for ${record3.correlationId} did not confirm the exact consumed claim; retry remains pending`);return}if(record3=ingestionCommit,record3=(await findDelegationForCompletion(directory,record3.correlationId))?.record??record3,!applied2.ok){await publishAdvisory(directory,record3,terminal.eventId,legacyTransferPending?"ingestion failed; legacy coder settlement transfer is pending; durable reconciliation will retry":legacyTransferRequiresManualRecovery?"ingestion failed; legacy coder settlement requires manual recovery; run /swarm recover for this task (or /swarm reset-session)":applied2.stale?"stale":"ingestion failed");try{await maintainBackgroundDelegations(directory,{lockTimeoutMs:1000,reason:"ingestion-rejection",skipLegacyCoderSettlementReconciliation:legacyTransferPending,onLegacyCoderSettlementAdvisoryReplaced:notifyLegacyCoderSettlementAdvisoryReplaced})}catch{}return}}else if(ingestion?.disposition==="busy")return;else if(ingestion?.disposition!=="consumed"){await publishAdvisory(directory,record3,terminal.eventId,"ingestion pending");return}}if(record3.normalizedAgent==="docs")try{if(!await completeBackgroundPhaseParticipation({directory,record:record3,resultText:text}))warn(`[background] docs completion ${record3.correlationId} did not satisfy its durable phase-participation binding`)}catch(error93){warn(`[background] docs completion ${record3.correlationId} could not persist phase participation: ${error93 instanceof Error?error93.message:String(error93)}`)}if(record3.normalizedAgent==="reviewer")discardScopeForRecord(record3);if(record3.normalizedAgent==="coder"){if(await releaseCoderReservation(directory,record3,"consumed"),!legacyTransferPending)await clearLegacyCoderSettlementTransferPending(directory,record3.correlationId)}await publishAdvisory(directory,record3,terminal.eventId,record3.normalizedAgent==="coder"?legacyTransferPending?"completed and settled; legacy coder settlement transfer is pending; durable reconciliation will retry":legacyTransferRequiresManualRecovery?"completed and settled; legacy coder settlement requires manual recovery; run /swarm recover for this task (or /swarm reset-session)":"completed and settled":"completed"),log(`[background] trusted completion settled: agent=${record3.normalizedAgent} task=${taskLabel(record3)} parent=${record3.parentSessionId}`)}catch(err){warn(`[background] completion observer error: ${err instanceof Error?err.message:String(err)}`)}},reconcilePending=async(record3)=>{if(replayInProgress)return!1;let terminal=record3.terminalResult;if(!terminal)return!1;replayInProgress=!0;try{await event({event:void 0,trustedTerminal:{record:record3,terminal,result:terminal.result,skipMaintenance:!0}});let refreshed=await findDelegationForCompletion(directory,record3.subagentSessionId);return refreshed?.record?refreshed.record.status==="consumed":!1}finally{replayInProgress=!1}};if(config3.enabled)registerLegacyCoderSettlementReconciler(directory,reconcilePending);return{event,reconcilePending,notifyLegacyCoderSettlementAdvisoryReplaced,prepareAdvisories:async(parentSessionId)=>{if(!config3.enabled||!parentSessionId)return null;let preparationId=`bg-prepare:${cryptoRandomId()}`,entries2=await preparePendingBackgroundAdvisories(directory,parentSessionId,{preparationId});return entries2.length===0?null:{preparationId,eventIds:entries2.map((entry)=>entry.eventId),messages:entries2.map((entry)=>entry.message)}},ackObservedAdvisories:(parentSessionId,observedTexts)=>acknowledgeObservedBackgroundAdvisories(directory,parentSessionId,observedTexts),releaseAdvisories:(parentSessionId,prepared)=>releasePreparedBackgroundAdvisories(directory,parentSessionId,prepared.preparationId,prepared.eventIds)}}async function transferLegacyCoderSettlement(directory,record3){if(!record3.planTaskId)return{disposition:"ok",outcome:"no task-scoped legacy settlement"};let transfer={taskId:record3.planTaskId,transitionId:`coder:${record3.callID}`},detail="unknown transfer failure",lastErrorCode=null;for(let attempt=0;attempt<3;attempt+=1)try{return{disposition:"ok",outcome:await observerInternals.transferCoderSettlementToBackground({directory,taskId:transfer.taskId,transitionId:transfer.transitionId})}}catch(error93){if(lastErrorCode=errorCode(error93),detail=error93 instanceof Error?error93.message:String(error93),attempt===2||!isRetryableLegacyTransferErrorCode(lastErrorCode))break;await observerInternals.sleep(50*(attempt+1))}if(warn(`[background] legacy coder settlement transfer failed for ${record3.planTaskId}: ${detail}`),!isRetryableLegacyTransferErrorCode(lastErrorCode))return{disposition:"manual_recovery",outcome:"legacy coder settlement requires manual recovery; run /swarm recover for this task (or /swarm reset-session)"};let pending=null;for(let markerAttempt=0;markerAttempt<3;markerAttempt+=1){try{pending=await observerInternals.markLegacyCoderSettlementTransferPending(directory,record3.correlationId,transfer)}catch{pending=null}if(hasExactPendingLegacyTransfer(pending,transfer))break;if(markerAttempt<2)await observerInternals.sleep(50*(markerAttempt+1))}if(hasExactPendingLegacyTransfer(pending,transfer))return{disposition:"retry_pending",outcome:"legacy coder settlement transfer is pending; retrying durable reconciliation"};return{disposition:"manual_recovery",outcome:"legacy coder settlement requires manual recovery; run /swarm recover for this task (or /swarm reset-session)"}}async function releaseCoderReservation(directory,record3,reason){if(!record3.coderReservationId)return;let bound=await bindBackgroundCoderReservation(directory,{reservationId:record3.coderReservationId,parentSessionId:record3.parentSessionId,planTaskId:record3.planTaskId,callID:record3.callID,correlationId:record3.correlationId});if(!bound){warn(`[background] coder reservation ${record3.coderReservationId} could not be bound for ${record3.correlationId}; admission remains fail-closed`);return}if(!await releaseBackgroundCoderReservation(directory,{...bound,generation:record3.generation??1,reason}))warn(`[background] coder reservation ${record3.coderReservationId} could not be released after ${reason}; the next admission will retry reconciliation`)}async function settleCoder(directory,record3,operationId){let context=record3.taskChangeContext;if(!context)return{ok:!1,record:record3,outcome:"stale: no coder baseline"};let claim=await claimCoderSettlement(directory,record3.correlationId,operationId);if(!claim)return{ok:!1,record:record3,outcome:"settlement claim failed"};if(claim.disposition==="settled")return{ok:!0,record:claim.record,outcome:"completed and settled"};if(claim.disposition==="preserved")return{ok:!1,record:claim.record,outcome:"settlement preserved"};if(record3=claim.record,!record3.worktree){let baseline=context.baseline,current=captureWorkspaceSnapshot(directory,{scope:baseline.scope,prHeadSha:baseline.prHeadSha,resolveCurrentPrHeadSha:baseline.prHeadSha!==null}),repositoryDelta=changedFilesSinceSnapshot(directory,baseline),declaredFiles=context.declaredFiles,observedFiles2=repositoryDelta&&declaredFiles&&declaredFiles.length>0?repositoryDelta.filter((file3)=>isInDeclaredScope(file3,declaredFiles,directory)):null,staleReason=!sameProjectRoot(baseline.directory,directory)?"shared-root directory identity changed":!baseline.gitHead||current.gitHead!==baseline.gitHead?"shared-root HEAD changed before coder completion":baseline.prHeadSha!==null&¤t.prHeadSha!==baseline.prHeadSha?"shared-root PR head changed before coder completion":observedFiles2===null?"shared-root coder files could not be attributed to a non-empty declared scope":null;if(staleReason||observedFiles2===null){let preserved2=await updateCoderSettlement(directory,record3.correlationId,{operationId,state:"preserved",observedFiles:null,outcome:{kind:"shared-root",result:"failed",reason:staleReason??"coder attribution failed"}});return await appendDelegationTransition(directory,record3.correlationId,{status:"stale"}),{ok:!1,record:preserved2??record3,outcome:`stale: ${staleReason??"coder attribution failed"}`}}let settled=await updateCoderSettlement(directory,record3.correlationId,{operationId,state:"settled",observedFiles:observedFiles2,outcome:{kind:"shared-root",result:"ready"}});return settled?{ok:!0,record:settled,outcome:"completed and settled"}:{ok:!1,record:record3,outcome:"settlement persistence failed"}}let descriptor=record3.worktree;if(descriptor.callID!==record3.callID||descriptor.parentSessionId!==record3.parentSessionId||descriptor.planTaskId!==record3.planTaskId||!sameProjectRoot(context.baseline.directory,descriptor.worktreePath))return{ok:!1,record:await updateCoderSettlement(directory,record3.correlationId,{operationId,state:"preserved",observedFiles:null,outcome:{kind:"standard-worktree",result:"failed",reason:"worktree recovery identity does not match the dispatch"}})??record3,outcome:"worktree settlement preserved: identity mismatch"};let observedFiles=changedFilesSinceSnapshot(descriptor.worktreePath,context.baseline);if(observedFiles===null)return{ok:!1,record:await updateCoderSettlement(directory,record3.correlationId,{operationId,state:"preserved",observedFiles:null,outcome:{kind:"standard-worktree",result:"failed",reason:"worktree files could not be attributed to the clean baseline"}})??record3,outcome:"worktree settlement preserved: attribution failed"};let dispatch=standardWorktreeByCallID.get(record3.callID)??{callID:descriptor.callID,parentSessionID:descriptor.parentSessionId,taskId:descriptor.taskId,...descriptor.planTaskId?{planTaskId:descriptor.planTaskId}:{},handle:{worktreePath:descriptor.worktreePath,branchName:descriptor.branchName,purpose:"lane",id:descriptor.worktreeId,sessionId:descriptor.worktreeSessionId},mergeStrategy:descriptor.mergeStrategy,laneIndex:descriptor.laneIndex,...descriptor.worktreeDir?{worktree_dir:descriptor.worktreeDir}:{}};standardWorktreeByCallID.delete(record3.callID),awaitingMergeByCallID.set(record3.callID,{callID:record3.callID,parentSessionID:descriptor.parentSessionId,taskId:descriptor.taskId,...descriptor.planTaskId?{planTaskId:descriptor.planTaskId}:{},branch:descriptor.branchName,worktreePath:descriptor.worktreePath,mergeStrategy:descriptor.mergeStrategy,queuedAt:Date.now()});let resume=settlementResume(record3),mergeResult=await finishStandardWorktreeDispatch(directory,dispatch,void 0,record3.callID,{operationId,...resume?{resume}:{},onBeforeMerge:async(provenance)=>{let persisted=await updateCoderSettlement(directory,record3.correlationId,{operationId,state:"settling",sourceHeadAfterCommit:provenance.sourceHead,targetHeadBeforeMerge:provenance.targetHeadBefore,observedFiles});if(!persisted)throw Error("could not persist pre-merge provenance");record3=persisted},onMerged:async(merged)=>{let provenance=merged.provenance??resume,persisted=await updateCoderSettlement(directory,record3.correlationId,{operationId,state:"settled",observedFiles,...provenance?{sourceHeadAfterCommit:provenance.sourceHead,targetHeadBeforeMerge:provenance.targetHeadBefore}:{},outcome:{kind:"standard-worktree",result:provenance&&provenance.sourceHead!==provenance.targetHeadBefore?"merged":"unchanged",sourceHeadAfterCommit:provenance?.sourceHead??null,targetHeadBeforeMerge:provenance?.targetHeadBefore??null,targetHeadAfterMerge:resolveCurrentGitHead(directory)}});if(!persisted)throw Error("could not persist merged settlement");record3=persisted}});if(mergeResult.outcome==="merged")return{ok:!0,record:(await findDelegationForCompletion(directory,record3.correlationId))?.record??record3,outcome:"completed and merged"};if(mergeResult.outcome==="failed"&&mergeResult.stage==="settlement-persist")return{ok:!1,record:record3,outcome:"worktree settlement persistence pending retry"};return{ok:!1,record:await updateCoderSettlement(directory,record3.correlationId,{operationId,state:"preserved",observedFiles,...mergeResult.provenance?{sourceHeadAfterCommit:mergeResult.provenance.sourceHead,targetHeadBeforeMerge:mergeResult.provenance.targetHeadBefore}:{},outcome:{kind:"standard-worktree",result:mergeResult.outcome,reason:mergeResult.message,sourceHeadAfterCommit:mergeResult.provenance?.sourceHead??null,targetHeadBeforeMerge:mergeResult.provenance?.targetHeadBefore??null}})??record3,outcome:`worktree settlement preserved: ${mergeResult.message}`}}function settlementResume(record3){let{coderSettlement:settlement,worktree}=record3;if(settlement?.state!=="settling"||!settlement.operationId||!settlement.sourceHeadAfterCommit||!settlement.targetHeadBeforeMerge||!GIT_OBJECT_ID_PATTERN.test(settlement.sourceHeadAfterCommit)||!GIT_OBJECT_ID_PATTERN.test(settlement.targetHeadBeforeMerge)||!worktree)return;return{operationId:settlement.operationId,sourceHead:settlement.sourceHeadAfterCommit,targetHeadBefore:settlement.targetHeadBeforeMerge,branchName:worktree.branchName,strategy:worktree.mergeStrategy}}async function publishAdvisory(directory,record3,eventId,outcome){let message=`[BACKGROUND COMPLETION ${eventId}] ${record3.normalizedAgent} task ${taskLabel(record3)} ${outcome}.`,input={eventId,parentSessionId:record3.parentSessionId,message},needsCorrection=!message.includes(LEGACY_CODER_SETTLEMENT_PENDING_ADVISORY_MARKER),replacement=(needsCorrection?await replacePendingBackgroundAdvisory(directory,record3.correlationId,input):null)??null,stored=replacement?.advisory??await putPendingBackgroundAdvisory(directory,record3.correlationId,input);if(!stored)return;let session=swarmState.agentSessions.get(record3.parentSessionId);if(session){if(needsCorrection){if(removeQueuedLegacyTransferAdvisory(session.pendingAdvisoryMessages,eventId),replacement?.replacedMessage)removeQueuedAdvisoryMessage(session.pendingAdvisoryMessages,[replacement.replacedMessage])}pushAdvisory(session,stored.message)}}function errorCode(error93){if(error93&&typeof error93==="object"&&"code"in error93&&typeof error93.code==="string")return error93.code??null;let detail=error93 instanceof Error?error93.message:String(error93);return/^([A-Z][A-Z0-9_]*)(?::|$)/.exec(detail.trim())?.[1]??null}function hasExactPendingLegacyTransfer(record3,transfer){return record3?.legacyCoderSettlementTransfer?.taskId===transfer.taskId&&record3.legacyCoderSettlementTransfer.transitionId===transfer.transitionId}function isRetryableLegacyTransferErrorCode(code){return code!==null&&RETRYABLE_LEGACY_SETTLEMENT_TRANSFER_ERROR_CODES.has(code)}function removeQueuedAdvisoryMessage(queue,messagesToRemove){if(!queue||queue.length===0||messagesToRemove.length===0)return;let remove=new Set(messagesToRemove);for(let index=queue.length-1;index>=0;index-=1)if(remove.has(queue[index]))queue.splice(index,1)}function removeQueuedLegacyTransferAdvisory(queue,eventId){if(!queue||queue.length===0)return;let prefix=`[BACKGROUND COMPLETION ${eventId}]`;for(let index=queue.length-1;index>=0;index-=1){let message=queue[index];if(message?.startsWith(prefix)&&message.includes(LEGACY_CODER_SETTLEMENT_PENDING_ADVISORY_MARKER))queue.splice(index,1)}}function taskLabel(record3){return record3.evidenceTaskId??record3.planTaskId??"unknown"}function discardScopeForRecord(record3){let taskId=record3.evidenceTaskId??record3.planTaskId;if(!taskId)return;if(record3.normalizedAgent==="reviewer")discardReviewerScopeGenerationClaim({parentSessionID:record3.parentSessionId,taskId,reviewerCallID:record3.callID});else if(record3.normalizedAgent==="coder")discardReviewerScopeGenerationForCoderCall({parentSessionID:record3.parentSessionId,taskId,coderCallID:record3.callID})}function digest4(text){return createHash89("sha256").update(text).digest("hex")}function cryptoRandomId(){return createHash89("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_package();init_constants();import*as fs146 from"node:fs";import*as path259 from"node:path";var CONFIG_SCHEMA_REF=`https://unpkg.com/opencode-swarm@${package_default.version}/opencode-swarm.schema.json`;function writeSwarmConfigExampleIfNew(projectDirectory){try{let swarmDir=path259.join(projectDirectory,".swarm"),dest=path259.join(swarmDir,"config.example.json");if(fs146.existsSync(dest))return;if(!fs146.existsSync(swarmDir))fs146.mkdirSync(swarmDir,{recursive:!0});let example={$schema:CONFIG_SCHEMA_REF,agents:Object.fromEntries(Object.entries(DEFAULT_MODELS).filter(([name])=>name!=="default").map(([name,model])=>[name,{model,fallback_models:["opencode/gpt-5-nano","opencode/big-pickle"]}])),max_iterations:5};fs146.writeFileSync(dest,`${JSON.stringify(example,null,2)}
|
|
6904
|
+
`);let criticalIds=filteredEntries.filter((e)=>renderedDirectiveIdSet.has(e.id)).filter((e)=>e.directive_priority==="critical"&&isActiveStatus(e.status)).map((e)=>e.id);if(cachedShownIds.length>0){let byId=new Map(filteredEntries.map((entry)=>[entry.id,entry])),cohortId=await _internals225.ensureCohortIdCached(directory,sessionId),sourceLinkId=_internals225.readLinkPointer(directory)?.linkId,membership=await _internals225.commitDisplayedMembership(directory,{trace_id:search.trace_id,session_id:sessionId,exposure_kind:"architect_directive",phase:retrievalCtx.currentPhase,task_id:retrievalCtx.taskId,agent:"architect",cohort_id:cohortId,source_link_id:sourceLinkId,grace_days:config3.receipt_close_grace_days,entries:cachedShownIds.map((id,index)=>({entry_id:id,critical:criticalIds.includes(id),rank:index+1,score:byId.get(id)?.finalScore}))});if(!membership.ok||membership.memberships.some((item)=>item.terminal)){if(cachedInjectionText="",cachedShownIds=[],cachedCriticalIds=[],sessionId)clearCriticalShownIds(sessionId);recordInjectionSkip(directory,membership.ok?"terminal_trace_reuse":membership.code,{agent:agentName,sessionId,phase:currentPhase,extra:{trace_id:search.trace_id}});return}}injectKnowledgeMessage(output,cachedInjectionText,sessionId);let sessionID=sessionId;if(sessionID)if(cachedCriticalIds=criticalIds,criticalIds.length>0)setCriticalShownIds(sessionID,{ids:criticalIds,phase:`Phase ${currentPhase}`,generatedAt:Date.now()});else clearCriticalShownIds(sessionID);if(cachedShownIds.length>0){let phaseLabel=`Phase ${currentPhase}`,scoreById=new Map(filteredEntries.map((e)=>[e.id,e.finalScore])),ranks={},scores={};cachedShownIds.forEach((id,idx)=>{ranks[id]=idx+1,scores[id]=scoreById.get(id)??0}),await _internals225.recordKnowledgeEvent(directory,{type:"retrieved",trace_id:search.trace_id,session_id:sessionId,phase:retrievalCtx.currentPhase,task_id:retrievalCtx.taskId,agent:"architect",query:retrievalCtx.lastUserMessage??retrievalCtx.currentPhase??"",retrieval_mode:"auto_injection",result_ids:cachedShownIds,ranks,scores}),_internals225.recordKnowledgeShown(directory,cachedShownIds,{phase:phaseLabel,tool:retrievalCtx.currentTool,action:retrievalCtx.currentAction,targetAgent:retrievalCtx.targetAgent,taskId:retrievalCtx.taskId}).catch(()=>{}),_internals225.recordLessonsShown(directory,cachedShownIds,phaseLabel).catch(()=>{}),_internals225.confirmEntriesPhase(directory,cachedShownIds,currentPhase,projectName).catch(()=>{})}})}var INJECTION_SENTINEL,defaultSearchKnowledge,sanitizeLessonForContext,DELEGATE_DIRECTIVE_BLOCK_TAG="<delegate_knowledge_directives>",DELEGATE_INJECT_HARD_CHAR_CAP=2000,knowledgeGeneration=0,DELEGATED_AGENTS,DELEGATE_DEFAULT_TOOLS,DIRECTIVE_PRIORITY_RANK,_internals225;var init_knowledge_injector=__esm(()=>{init_reviewer_directive_compliance();init_schema();init_manager();init_injection_budget();init_run_memory();init_state2();init_logger();init_cohort_cache();init_curator_drift();init_extractors();init_host_boundary();init_knowledge_application();init_knowledge_escalator();init_knowledge_events();init_knowledge_link();init_knowledge_reader();init_knowledge_receipt_ledger();init_knowledge_store();init_knowledge_types();init_model_limits();init_phase_directives();init_search_knowledge();init_utils2();INJECTION_SENTINEL=`${String.fromCharCode(8204)}[[KNOWLEDGE-INJECTED]]`,defaultSearchKnowledge=searchKnowledge;sanitizeLessonForContext=sanitizeContextText;DELEGATED_AGENTS=new Set(["coder","reviewer","test_engineer","sme","docs","designer","critic","curator"]);DELEGATE_DEFAULT_TOOLS={coder:["edit","write","patch","bash"],reviewer:["read","grep","glob"],test_engineer:["edit","write","bash","read"],sme:["read","grep","glob","webfetch"],docs:["read","edit","write","grep"],designer:["read","write","edit"],critic:["read","grep","glob"],curator:["read","grep","glob"]};DIRECTIVE_PRIORITY_RANK={critical:0,high:1,medium:2,low:3};_internals225={searchKnowledge,recordKnowledgeEvent,recordKnowledgeShown,readRecentEscalations,buildEscalationBriefing,recordLessonsShown,confirmEntriesPhase,commitDisplayedMembership,commitEmptyRetrieval,queryLiveMemberships,ensureCohortIdCached,readLinkPointer}});function reject(reason,detail,rejected_items){return{ok:!1,rejected:!0,reason,detail,rejected_items}}async function validateReceipt(ctx){let{items,no_relevant_knowledge:noRelevant}=ctx;if(items.length===0&&!noRelevant)return reject("empty_receipt","no items and no_relevant_knowledge is false");if(noRelevant&&items.length>0)return reject("invalid_outcome","no_relevant_knowledge cannot be combined with items");for(let item of items)if(!VALID_OUTCOMES.has(item.outcome))return reject("invalid_outcome",`item ${item.id}: outcome ${item.outcome}`);let traceId=ctx.trace_id||NO_TRACE_SENTINEL;if(traceId===NO_TRACE_SENTINEL){if(items.length>0)return reject("trace_not_found","items filed against the none sentinel trace");let empty=await commitEmptyRetrieval(ctx.directory,{trace_id:traceId,session_id:ctx.session_id,phase:ctx.phase,task_id:ctx.task_id,agent:ctx.agent,grace_days:ctx.grace_days});if(!empty.ok)return reject(empty.code,empty.detail);return{ok:!0,accepted:[],idempotent_skips:[],trace:null,closes_no_relevant:!0,authoritative_event_ids:{},no_relevant_event_id:empty.terminal_event_id}}let committed=await validateAndCommitTerminalBatch(ctx.directory,{trace_id:traceId,session_id:ctx.session_id,phase:ctx.phase,task_id:ctx.task_id,agent:ctx.agent,cohort_id:ctx.cohort_id,source_link_id:ctx.source_link_id,grace_days:ctx.grace_days,items:items.map((item)=>({entry_id:item.id,outcome:item.outcome,reason:item.reason,source:ctx.source.trim()||"unknown"})),no_relevant_knowledge:noRelevant});if(!committed.ok)return reject(committed.code,committed.detail);let remainingItems=[...items],takeItem=(id,outcome)=>{let index=remainingItems.findIndex((item)=>item.id===id&&(outcome===void 0||item.outcome===outcome));if(index<0)return;return remainingItems.splice(index,1)[0]},accepted=committed.accepted.map((item)=>takeItem(item.entry_id,item.outcome)).filter((item)=>item!==void 0),idempotent_skips=committed.idempotent.map((id)=>takeItem(id)).filter((item)=>item!==void 0),rejected_items=committed.rejected.map((item)=>({item:takeItem(item.entry_id)??{id:item.entry_id,outcome:"ignored"},reason:item.reason}));if(rejected_items.length&&accepted.length===0&&idempotent_skips.length===0)return reject(rejected_items[0].reason,`${rejected_items[0].reason} for id ${rejected_items[0].item.id}`,rejected_items);let queried=await queryLiveMemberships(ctx.directory,{session_id:ctx.session_id,include_terminal:!0,grace_days:ctx.grace_days}),memberships=queried.ok?queried.memberships.filter((membership)=>membership.trace_id===traceId):[],trace=memberships.length?{type:"retrieved",event_id:memberships[0].membership_event_id,trace_id:traceId,timestamp:memberships[0].committed_at,session_id:ctx.session_id,phase:memberships[0].phase,task_id:memberships[0].task_id,agent:memberships[0].agent??ctx.agent,query:"",retrieval_mode:"manual",result_ids:memberships.map((membership)=>membership.entry_id),ranks:Object.fromEntries(memberships.map((membership,index)=>[membership.entry_id,membership.rank??index+1])),scores:Object.fromEntries(memberships.map((membership)=>[membership.entry_id,membership.score??0]))}:null;return{ok:!0,accepted,idempotent_skips,trace,closes_no_relevant:committed.closes_no_relevant,authoritative_event_ids:Object.fromEntries(committed.accepted.map((item)=>[item.entry_id,item.event_id])),...committed.terminal_event_id?{no_relevant_event_id:committed.terminal_event_id}:{},...rejected_items.length?{rejected_items}:{}}}var NO_TRACE_SENTINEL="none",VALID_OUTCOMES;var init_knowledge_receipt_validator=__esm(()=>{init_knowledge_receipt_ledger();VALID_OUTCOMES=RECEIPT_TERMINAL_OUTCOMES});function isTaskTool3(tool3){return tool3==="Task"||tool3==="task"}function resolveDelegateAckTaskId(args2,knownPlanTaskIds,planContextOverLimit=!1){let resolved=resolveDelegateAckTaskIdResult(args2,knownPlanTaskIds,planContextOverLimit);return resolved.status==="resolved"?resolved.taskId:void 0}function resolveDelegateAckTaskIdResult(args2,knownPlanTaskIds,planContextOverLimit=!1){return resolveTaskId(args2,{policy:"attribution",knownPlanTaskIds,planContextOverLimit})}async function appendUnacknowledgedCritical(directory,record3){let filePath=validateSwarmPath(directory,"unacknowledged-criticals.jsonl");await appendCappedJsonl(filePath,JSON.stringify(record3),{maxEntries:resolveRetentionCap("MAX_UNACKNOWLEDGED_CRITICALS",MAX_UNACKNOWLEDGED_CRITICALS),onPrune:(dropped)=>{warn(`unacknowledged-criticals audit at cap: dropped ${dropped} oldest ${dropped===1?"entry":"entries"} (FIFO bound MAX_UNACKNOWLEDGED_CRITICALS)`)}})}async function reconcileShownDirectives(params){let result={emitted:[],unacknowledgedCriticals:[],unacknowledgedNonCritical:[]};try{let shown=params.shown;if(shown.length===0)return result;let shownById=new Map(shown.map((d)=>[d.id,d])),criticalIds=shown.filter((d)=>d.priority==="critical").map((d)=>d.id),acks=parseAcknowledgments(params.transcript),ackedIds=new Set,violatedIds=new Set,sessionId=params.sessionId,taskId=params.taskId,traceId=params.traceId??"legacy-unverifiable",isLegacyPrompt=params.traceId===void 0,cohortId,linkId;try{cohortId=await ensureCohortIdCached(params.directory,sessionId),linkId=readLinkPointer(params.directory)?.linkId}catch{}let ackItems=[],ackByItemId=new Map;for(let ack of acks){if(!shownById.has(ack.id))continue;if(ackedIds.add(ack.id),!isLegacyPrompt&&ack.trace_id!==traceId)continue;if(ack.result==="applied"||ack.result==="ignored"||ack.result==="violated"||ack.result==="n_a"||ack.result==="contradicted")ackItems.push({id:ack.id,outcome:ack.result,reason:ack.reason}),ackByItemId.set(ack.id,ack)}let eventIdByKnowledgeId=new Map;if(isLegacyPrompt)for(let ack of acks){if(!shownById.has(ack.id))continue;if(!ackByItemId.has(ack.id))continue;ackedIds.add(ack.id)}else{let validation2=await validateReceipt({directory:params.directory,trace_id:traceId,session_id:sessionId,task_id:taskId,agent:params.agent,source:"delegate",cohort_id:cohortId,source_link_id:linkId,items:ackItems,no_relevant_knowledge:!1});if(validation2.ok){for(let item of validation2.accepted){let ack=ackByItemId.get(item.id);if(!ack)continue;ackedIds.add(item.id),await recordKnowledgeEvent(params.directory,{type:item.outcome,trace_id:traceId,knowledge_id:item.id,session_id:sessionId,task_id:taskId,agent:params.agent,source:"delegate",reason:ack.reason});let authoritativeEventId=validation2.authoritative_event_ids[item.id];if(authoritativeEventId)eventIdByKnowledgeId.set(item.id,authoritativeEventId);if(item.outcome==="violated")violatedIds.add(item.id);result.emitted.push({id:item.id,type:item.outcome})}for(let item of validation2.idempotent_skips)ackedIds.add(item.id);for(let rejected2 of validation2.rejected_items??[])ackedIds.add(rejected2.item.id)}if(!validation2.ok)for(let id of ackByItemId.keys())ackedIds.add(id)}try{let now2=new Date().toISOString(),evidenceRecords=[];for(let[kid,eid]of eventIdByKnowledgeId){let ack=ackByItemId.get(kid);if(!ack||!cohortId)continue;let outcome=ack.result;if(outcome!=="applied"&&outcome!=="violated"&&outcome!=="contradicted")continue;evidenceRecords.push({cohort_id:cohortId,source_link_id:linkId,entry_id:kid,retrieval_trace_id:traceId,receipt_outcome:outcome,receipt_source:"delegate",receipt_event_id:eid,phase:void 0,timestamp:now2})}await appendPromotionEvidence(params.directory,evidenceRecords)}catch{}let missingCriticalIds=criticalIds.filter((id)=>!ackedIds.has(id)),committedMissingCriticalIds=new Set;if(!isLegacyPrompt&&missingCriticalIds.length>0){let committed=await validateAndCommitTerminalBatch(params.directory,{trace_id:traceId,session_id:sessionId,task_id:taskId,agent:params.agent,cohort_id:cohortId,source_link_id:linkId,items:missingCriticalIds.map((entry_id)=>({entry_id,outcome:"violated",source:"delegate",reason:"unacknowledged"}))});if(committed.ok)committedMissingCriticalIds=new Set(committed.committed.map((item)=>item.entry_id))}for(let id of missingCriticalIds){if(!committedMissingCriticalIds.has(id))continue;result.unacknowledgedCriticals.push(id),await recordKnowledgeEvent(params.directory,{type:"violated",trace_id:traceId,knowledge_id:id,session_id:sessionId,task_id:taskId,agent:params.agent,source:"delegate",reason:"unacknowledged"}),violatedIds.add(id),result.emitted.push({id,type:"violated"});try{await appendUnacknowledgedCritical(params.directory,{timestamp:new Date().toISOString(),knowledge_id:id,agent:params.agent,session_id:sessionId,task_id:taskId,reason:"unacknowledged"})}catch{}}let silentEvents=[];for(let[id,directive]of shownById){if(directive.priority==="critical")continue;if(ackedIds.has(id))continue;if(params.replay===!0)continue;result.unacknowledgedNonCritical.push(id),silentEvents.push({type:"unacknowledged",trace_id:traceId,knowledge_id:id,session_id:sessionId,task_id:taskId,agent:params.agent,source:"delegate",reason:"no_ack_marker"}),result.emitted.push({id,type:"unacknowledged"})}if(silentEvents.length>0)await recordKnowledgeEventsBatch(params.directory,silentEvents);if(violatedIds.size>0)await escalateViolatedEntries(params.directory,[...violatedIds])}catch{}return result}async function collectDelegateAcks(params){let shown=parseDelegateDirectiveBlock(params.prompt);if(shown.length===0)return{emitted:[],unacknowledgedCriticals:[],unacknowledgedNonCritical:[]};let sessionId=params.sessionId;if(!sessionId)return{emitted:[],unacknowledgedCriticals:[],unacknowledgedNonCritical:[],unverifiable:{code:"missing_session_id",detail:"Delegate acknowledgments require a real host session id"}};let traceId=parseDelegateDirectiveTraceId(params.prompt)??void 0,taskId=params.taskIdResolution?params.taskIdResolution.status==="resolved"?params.taskIdResolution.taskId:void 0:params.taskId??resolveDelegateAckTaskId({prompt:params.prompt});return reconcileShownDirectives({directory:params.directory,shown,traceId,transcript:params.transcript,agent:params.agent,sessionId,taskId})}async function collectLaneDelegateAcks(params){let empty={emitted:[],unacknowledgedCriticals:[],unacknowledgedNonCritical:[],phases:[]};try{let memberships=await queryLiveMemberships(params.directory,{session_id:params.sessionId,exposure_kind:"delegate_directive",include_terminal:!0});if(!memberships.ok)return empty;let byTrace=new Map,phases=new Set;for(let membership of memberships.memberships){let group=byTrace.get(membership.trace_id)??[];if(group.push(membership),byTrace.set(membership.trace_id,group),membership.phase)phases.add(membership.phase)}let combined={emitted:[],unacknowledgedCriticals:[],unacknowledgedNonCritical:[]};for(let[traceId,group]of byTrace){let taskId=group.find((m)=>m.task_id)?.task_id,outcome=await reconcileShownDirectives({directory:params.directory,shown:group.map((m)=>({id:m.entry_id,priority:m.critical?"critical":"medium"})),traceId,transcript:params.transcript,agent:params.agent,sessionId:params.sessionId,taskId,replay:params.replay});if(combined.emitted.push(...outcome.emitted),combined.unacknowledgedCriticals.push(...outcome.unacknowledgedCriticals),combined.unacknowledgedNonCritical.push(...outcome.unacknowledgedNonCritical),outcome.unverifiable)combined.unverifiable=outcome.unverifiable}return{...combined,phases:[...phases]}}catch{return empty}}async function collectDelegateAcksAfter(directory,input,output){if(!isTaskTool3(input.tool))return;let argsRecord=input.args&&typeof input.args==="object"?input.args:null,prompt=argsRecord&&typeof argsRecord.prompt==="string"?argsRecord.prompt:"";if(!prompt)return;let transcript=typeof output.output==="string"?output.output:"";if(!transcript)return;let agent=parseDelegationArgs(input.args)?.targetAgent??"unknown",sessionId=typeof input.sessionID==="string"?input.sessionID:void 0,planTaskIdOptions=toTaskIdPlanContextOptions(await loadPlanTaskIdContext(directory)),taskIdResolution=resolveDelegateAckTaskIdResult(argsRecord??{prompt},planTaskIdOptions.knownPlanTaskIds,planTaskIdOptions.planContextOverLimit);await collectDelegateAcks({directory,prompt,transcript,agent,sessionId,taskIdResolution})}var MAX_UNACKNOWLEDGED_CRITICALS=500;var init_delegate_ack_collector=__esm(()=>{init_caps();init_jsonl_cap();init_logger();init_cohort_cache();init_knowledge_application();init_knowledge_escalator();init_knowledge_events();init_knowledge_injector();init_knowledge_link();init_knowledge_receipt_ledger();init_knowledge_receipt_validator();init_plan_task_id_context();init_promotion_evidence_store();init_skill_propagation_gate();init_task_id_resolver();init_utils2()});import{existsSync as existsSync149,readdirSync as readdirSync41,readFileSync as readFileSync118,statSync as statSync83}from"node:fs";import*as path282 from"node:path";function validateRepoRelativeGlob(directory,value){let v=value.trim();if(!v)return null;if(v.includes("\x00"))return null;if(v.startsWith("/")||/^[A-Za-z]:[\\/]/.test(v)||v.startsWith("\\"))return null;if(v.split(/[/\\]/).some((s)=>s===".."))return null;let globStart=v.search(/[*?{[]/),concrete=globStart===-1?v:v.slice(0,globStart);if(concrete){let baseDir=path282.resolve(directory),resolved=path282.resolve(baseDir,concrete),rel3=path282.relative(baseDir,resolved);if(rel3.startsWith("..")||path282.isAbsolute(rel3))return null}return v}function findBinaryInPath(binary){let candidates=process.platform==="win32"?[`${binary}.exe`,`${binary}.cmd`,`${binary}.bat`,binary]:[binary];for(let dir of(process.env.PATH??"").split(path282.delimiter)){if(!dir)continue;for(let name of candidates){let candidate2=path282.join(dir,name);if(existsSync149(candidate2))return candidate2}}return null}function safeChildEnv(){let env={};if(process.env.PATH)env.PATH=process.env.PATH;if(process.env.HOME)env.HOME=process.env.HOME;if(process.env.SystemRoot)env.SystemRoot=process.env.SystemRoot;if(process.env.TEMP)env.TEMP=process.env.TEMP;if(process.env.TMP)env.TMP=process.env.TMP;return env}async function runArgv(argv,cwd){let proc=bunSpawn(argv,{stdin:"ignore",stdout:"pipe",stderr:"pipe",cwd,env:safeChildEnv()}),finished=!1;try{let timeout=new Promise((resolve110)=>setTimeout(()=>resolve110("timeout"),PREDICATE_TIMEOUT_MS));if(await Promise.race([proc.exited,timeout])==="timeout")return{exitCode:null,stdout:"",stderr:"",timedOut:!0};let[stdout,stderr]=await Promise.all([proc.stdout.text().catch(()=>""),proc.stderr.text().catch(()=>"")]);return finished=!0,{exitCode:proc.exitCode,stdout,stderr,timedOut:!1}}finally{if(!finished)try{proc.kill()}catch{}}}async function runGrepPredicate(rest,directory){let lastColon=rest.lastIndexOf(":");if(lastColon<=0||lastColon===rest.length-1)return{result:"error",detail:"grep: expected <regex>:<path-glob>"};let regex=rest.slice(0,lastColon),rawGlob=rest.slice(lastColon+1),glob=validateRepoRelativeGlob(directory,rawGlob);if(glob===null)return{result:"error",detail:`grep: unsafe or empty path-glob "${rawGlob}"`};let pattern;try{pattern=new RegExp(regex,"m")}catch(err){return{result:"error",detail:`grep: invalid regex ${err instanceof Error?err.message:String(err)}`}}let matcher=import_picomatch2.default(glob,{dot:!0}),visited=0,matches=0,walk=(dir)=>{if(visited>=GREP_MAX_FILES)return;let entries2;try{entries2=readdirSync41(dir,{withFileTypes:!0})}catch{return}for(let entry of entries2){if(visited>=GREP_MAX_FILES)return;let fullPath=path282.join(dir,entry.name),relPath=path282.relative(directory,fullPath).replace(/\\/g,"/");if(entry.isDirectory()){if(!GREP_SKIP_DIRECTORIES.has(entry.name))walk(fullPath);continue}if(!entry.isFile())continue;if(visited++,!matcher(relPath))continue;try{if(statSync83(fullPath).size>GREP_MAX_BYTES_PER_FILE)continue;let found=readFileSync118(fullPath,"utf-8").match(pattern);if(found)matches+=found.length}catch{}}};if(walk(directory),visited>=GREP_MAX_FILES)return{result:"error",detail:`grep: file scan exceeded ${GREP_MAX_FILES} files`};if(matches===0)return{result:"pass",detail:"grep: zero matches"};return{result:"fail",detail:`grep: ${matches} match(es) found`}}async function runToolPredicate(rest,directory){let raw=rest.trim();if(!raw)return{result:"error",detail:"tool: empty command"};if(raw.includes("\x00"))return{result:"error",detail:"tool: null byte in command"};let argvParts=raw.split(/\s+/).filter((p)=>p.length>0);if(argvParts.length===0)return{result:"error",detail:"tool: empty command"};let binary=argvParts[0];if(binary.includes("/")||binary.includes("\\"))return{result:"error",detail:`tool: path-qualified binary "${binary}" is not allowed`};if(!TOOL_BINARY_ALLOWLIST.has(binary))return{result:"error",detail:`tool: binary "${binary}" is not on the allowlist`};let resolved=findBinaryInPath(binary);if(!resolved)return{result:"error",detail:`tool: binary "${binary}" not found`};let res=await runArgv([resolved,...argvParts.slice(1)],directory);if(res.timedOut)return{result:"error",detail:"tool: timed out"};if(res.exitCode===0)return{result:"pass",detail:"tool: exit 0"};return{result:"fail",detail:`tool: exit ${res.exitCode} ${res.stderr.slice(0,200)}`}}async function changedPaths(directory){let git2=findBinaryInPath("git");if(!git2)return null;let res=await runArgv([git2,"status","--porcelain","-z"],directory);if(res.timedOut||res.exitCode!==0)return null;let out=new Set;for(let entry of res.stdout.split("\x00")){if(entry.length<=3)continue;let p=entry.slice(3);if(p)out.add(path282.normalize(p))}return out}async function runFileModifiedPredicate(rest,directory,expectModified){let label=expectModified?"file_modified":"file_not_modified",safe2=validateRepoRelativeGlob(directory,rest);if(safe2===null)return{result:"error",detail:`${label}: unsafe or empty path "${rest}"`};let changed2=await changedPaths(directory);if(changed2===null)return{result:"error",detail:`${label}: git unavailable or failed`};let target=path282.normalize(safe2),isChanged=changed2.has(target);return{result:(expectModified?isChanged:!isChanged)?"pass":"fail",detail:`${label}: ${target} ${isChanged?"changed":"unchanged"}`}}async function runDirectivePredicate(predicate,directory){try{if(typeof predicate!=="string"||!predicate.trim())return{result:"error",detail:"predicate: empty"};let trimmed=predicate.trim(),firstColon=trimmed.indexOf(":");if(firstColon<=0)return{result:"error",detail:"predicate: missing handler prefix (expected <handler>:...)"};let handler=trimmed.slice(0,firstColon),rest=trimmed.slice(firstColon+1);switch(handler){case"grep":return await runGrepPredicate(rest,directory);case"tool":return await runToolPredicate(rest,directory);case"file_not_modified":return await runFileModifiedPredicate(rest,directory,!1);case"file_modified":return await runFileModifiedPredicate(rest,directory,!0);default:return{result:"error",detail:`predicate: unknown handler "${handler}"`}}}catch(err){return warn(`[directive-predicate-runner] unexpected error: ${err instanceof Error?err.message:String(err)}`),{result:"error",detail:"predicate: unexpected error (fail-closed)"}}}var import_picomatch2,PREDICATE_TIMEOUT_MS=15000,GREP_MAX_FILES=1e4,GREP_MAX_BYTES_PER_FILE=1e6,GREP_SKIP_DIRECTORIES,TOOL_BINARY_ALLOWLIST;var init_directive_predicate_runner=__esm(()=>{init_bun_compat();init_logger();import_picomatch2=__toESM(require_picomatch2(),1),GREP_SKIP_DIRECTORIES=new Set([".git",".swarm","node_modules","dist","coverage"]),TOOL_BINARY_ALLOWLIST=new Set(["rg","grep","git","biome","eslint","tsc","ruff"])});function parseReviewerDirectiveCompliance(text){if(!text||typeof text!=="string")return[];let out=[];for(let m of text.matchAll(VERDICT_PATTERN)){let verb=m[1].toUpperCase(),traceId=decodeDirectiveCorrelationId(m[2]),entryId=decodeDirectiveCorrelationId(m[3]);if(!traceId||!entryId)continue;let evidence2=m[4]?.trim().slice(0,280),verdict=verb==="VERIFIED"?"verified":verb==="VIOLATED"?"violated":"n_a";out.push({trace_id:traceId,entry_id:entryId,verdict,evidence:evidence2})}return out}function verdictToEventType(v){return v==="verified"?"applied":v==="violated"?"violated":"n_a"}function pairKey2(traceId,entryId){return JSON.stringify([traceId,entryId])}async function reconcileReviewerVerdicts(params){let result={emitted:[],omittedCriticals:[],uncertainties:[]},verifyByPair=new Map(params.directivesToVerify.map((d)=>[pairKey2(d.trace_id,d.entry_id),d]));if(verifyByPair.size===0)return result;let verdictsByPair=new Map;for(let verdict of parseReviewerDirectiveCompliance(params.transcript)){let key2=pairKey2(verdict.trace_id,verdict.entry_id);if(!verifyByPair.has(key2))continue;let existing=verdictsByPair.get(key2)??[];existing.push(verdict),verdictsByPair.set(key2,existing)}let pending=[];for(let[key2,directive]of verifyByPair){let matching=verdictsByPair.get(key2)??[];if(matching.length>1){result.uncertainties.push({trace_id:directive.trace_id,entry_id:directive.entry_id,code:"duplicate_verdict",uncertainty:"Reviewer emitted more than one verdict for the exact pair"});continue}if(matching.length===0){if(directive.priority!=="critical")continue;result.omittedCriticals.push({trace_id:directive.trace_id,entry_id:directive.entry_id}),pending.push({directive,type:"violated",reason:"reviewer_omitted"});continue}let verdict=matching[0];if(verdict.verdict==="verified"&&!verdict.evidence?.trim()){if(result.uncertainties.push({trace_id:directive.trace_id,entry_id:directive.entry_id,code:"reviewer_missing_evidence",uncertainty:"VERIFIED requires nonempty evidence"}),directive.priority==="critical")result.omittedCriticals.push({trace_id:directive.trace_id,entry_id:directive.entry_id}),pending.push({directive,type:"violated",reason:"reviewer_missing_evidence"});continue}let item={directive,type:verdictToEventType(verdict.verdict),reason:verdict.evidence};if(verdict.verdict==="violated"&&directive.verification_predicate)try{let outcome=await _internals232.runDirectivePredicate(directive.verification_predicate,params.directory);item.predicate_check={predicate:directive.verification_predicate,result:outcome.result,detail:outcome.detail}}catch(error93){item.predicate_check={predicate:directive.verification_predicate,result:"error",detail:error93 instanceof Error?error93.message:String(error93)}}pending.push(item)}let groups=new Map;for(let item of pending){let groupKey=JSON.stringify([item.directive.trace_id,item.directive.session_id,item.directive.cohort_id,item.directive.source_link_id,item.directive.prior_terminal_outcome,item.directive.prior_terminal_event_id]),group=groups.get(groupKey)??[];group.push(item),groups.set(groupKey,group)}let violatedIds=new Set,agent=params.agent??"reviewer";for(let group of groups.values()){let first=group[0].directive,remediationAuthorization=(first.prior_terminal_outcome==="violated"||first.prior_terminal_outcome==="contradicted")&&first.prior_terminal_event_id&&group.some((item)=>item.type!=="violated")?{actor:"reviewer-remediation",reason:"reviewer_verified_remediation",expected_event_id:first.prior_terminal_event_id,expected_outcome:first.prior_terminal_outcome}:void 0,committedEntries;try{let committed=await _internals232.validateAndCommitTerminalBatch(params.directory,{trace_id:first.trace_id,session_id:first.session_id,cohort_id:first.cohort_id,source_link_id:first.source_link_id,authorization:remediationAuthorization,items:group.map((item)=>({entry_id:item.directive.entry_id,outcome:item.type,source:"reviewer",reason:item.reason}))});if(!committed.ok){for(let item of group)result.uncertainties.push({trace_id:item.directive.trace_id,entry_id:item.directive.entry_id,code:committed.code,uncertainty:committed.detail});continue}committedEntries=new Set(committed.accepted.map((terminal)=>terminal.entry_id));for(let rejected2 of committed.rejected)result.uncertainties.push({trace_id:first.trace_id,entry_id:rejected2.entry_id||void 0,code:rejected2.reason,uncertainty:"Authoritative ledger rejected reviewer terminal"})}catch(error93){for(let item of group)result.uncertainties.push({trace_id:item.directive.trace_id,entry_id:item.directive.entry_id,code:"ledger_exception",uncertainty:error93 instanceof Error?error93.message:String(error93)});continue}for(let item of group){if(!committedEntries.has(item.directive.entry_id))continue;try{if(await _internals232.recordKnowledgeEvent(params.directory,{type:item.type,trace_id:item.directive.trace_id,knowledge_id:item.directive.entry_id,session_id:item.directive.session_id,task_id:params.taskId,phase:params.phase,agent,source:"reviewer",reason:item.reason,predicate_check:item.predicate_check}),result.emitted.push({trace_id:item.directive.trace_id,entry_id:item.directive.entry_id,id:item.directive.entry_id,type:item.type,source:"reviewer"}),item.type==="violated")violatedIds.add(item.directive.entry_id)}catch(error93){result.uncertainties.push({trace_id:item.directive.trace_id,entry_id:item.directive.entry_id,code:"diagnostic_event_failed",uncertainty:error93 instanceof Error?error93.message:String(error93)})}}}if(violatedIds.size>0)try{await _internals232.escalateViolatedEntries(params.directory,[...violatedIds])}catch(error93){result.uncertainties.push({trace_id:"",code:"escalation_failed",uncertainty:error93 instanceof Error?error93.message:String(error93)})}return result}function isTaskTool7(tool3){return tool3==="Task"||tool3==="task"}async function collectReviewerVerdictsAfter(directory,input,output){if(!isTaskTool7(input.tool))return;let parsedArgs=parseDelegationArgs(input.args);if(!parsedArgs)return;if(stripKnownSwarmPrefix(parsedArgs.targetAgent).toLowerCase()!=="reviewer")return;let argsRecord=input.args&&typeof input.args==="object"?input.args:null,prompt=argsRecord&&typeof argsRecord.prompt==="string"?argsRecord.prompt:"";if(!prompt)return;let transcript=typeof output.output==="string"?output.output:"";if(!transcript)return;let directivesToVerify=parseDirectivesToVerifyBlock(prompt);if(directivesToVerify.length===0)return;let sessionId=typeof input.sessionID==="string"?input.sessionID:void 0;await reconcileReviewerVerdicts({directory,transcript,directivesToVerify,sessionId,agent:"reviewer"})}var _internals232,VERDICT_PATTERN;var init_reviewer_verdict_parser=__esm(()=>{init_reviewer_directive_compliance();init_schema();init_directive_predicate_runner();init_knowledge_escalator();init_knowledge_events();init_knowledge_receipt_ledger();init_skill_propagation_gate();_internals232={validateAndCommitTerminalBatch,recordKnowledgeEvent,runDirectivePredicate,escalateViolatedEntries},VERDICT_PATTERN=/\b(VERIFIED|VIOLATED|N\/A)\s*:\s*([^:\s]{1,512})\s*:\s*([^:\s]{1,512})(?:\s+(?:evidence|reason)\s*=\s*([^\n\r]+?))?(?=$|[\n\r]|\s+(?:VERIFIED|VIOLATED|N\/A)\b)/gi});import{createHash as createHash95}from"node:crypto";function delegationCostRecordMaterial(record3){if(!record3.laneId)return`${record3.parentSessionId}\x00${record3.callID}`;return`${record3.parentSessionId}\x00${record3.callID}\x00lane:${record3.laneId}`}function buildDelegationTerminalIdentityFields(input){let material=delegationCostRecordMaterial(input.record);return{record_id:createHash95("sha256").update(`delegation-cost-id-v1\x00${material}`).digest("hex").slice(0,32),identity_fingerprint:createHash95("sha256").update(`delegation-cost-identity-v1\x00${material}\x00${input.record.swarmPrefixedAgent}\x00${input.model??""}`).digest("hex").slice(0,32),version:1,parent_session_digest:createHash95("sha256").update(`delegation-cost-parent-v1\x00${input.record.parentSessionId}`).digest("hex").slice(0,32),child_session_digest:createHash95("sha256").update(`delegation-cost-child-v1\x00${input.record.subagentSessionId}`).digest("hex").slice(0,32),...input.recovered?{recovered:!0}:{}}}var init_delegation_cost_identity=()=>{};var exports_delegation_lifecycle={};__export(exports_delegation_lifecycle,{settleDelegationTerminal:()=>settleDelegationTerminal,recoverTerminalLaneReceipts:()=>recoverTerminalLaneReceipts,isBenignSettleOutcome:()=>isBenignSettleOutcome,emitDelegationEventlessTerminalEnd:()=>emitDelegationEventlessTerminalEnd,emitDelegationBegin:()=>emitDelegationBegin,delegationCostRecordMaterial:()=>delegationCostRecordMaterial,buildDelegationTerminal:()=>buildDelegationTerminal,_internals:()=>_internals251,TERMINAL_LANE_RECEIPT_RECOVERY_DEADLINE_MS:()=>TERMINAL_LANE_RECEIPT_RECOVERY_DEADLINE_MS,MAX_TERMINAL_LANE_RECEIPT_RECOVERY:()=>MAX_TERMINAL_LANE_RECEIPT_RECOVERY});import*as fs177 from"node:fs";import*as path303 from"node:path";function isBenignSettleOutcome(kind){return kind==="duplicate"||kind==="conflict"||kind==="already_terminal_without_event"}function buildDelegationTerminal(record3,terminal,now2){return{eventId:buildBackgroundCompletionEventId({correlationId:record3.correlationId,jobId:record3.jobId,status:terminal.status,resultDigest:terminal.result.digest}),status:terminal.status,recordedAt:now2,result:terminal.result}}async function settleDelegationTerminal(directory,record3,terminal,observations={},now2=Date.now()){let claim=await _internals251.claimTerminalResult(directory,record3.correlationId,buildDelegationTerminal(record3,terminal,now2));if(claim){if(claim.disposition==="claimed")return await runDelegationTerminalObservations(directory,claim.record,terminal,observations,now2),{kind:"claimed",record:claim.record};if(claim.disposition==="duplicate"&&observations.transcript)await reconcileLaneKnowledgeReceipts(directory,claim.record,observations,!0);return{kind:"duplicate",record:claim.record}}let reread=_internals251.findByCorrelationIdDetailed(directory,record3.correlationId);if(reread.status==="uncertain")return{kind:"uncertain",reason:reread.reason};if(!reread.value)return{kind:"missing"};if(isTerminalDelegationStatus(reread.value.status)){if(reread.value.terminalResult)return{kind:"conflict",record:reread.value};return emitDelegationEventlessTerminalEnd(reread.value,reread.value.status),{kind:"already_terminal_without_event",record:reread.value}}return{kind:"not_open",record:reread.value}}function emitDelegationBegin(record3){try{_internals251.telemetry.delegationBegin(record3.parentSessionId,record3.swarmPrefixedAgent,record3.planTaskId??"")}catch{}}function emitDelegationCostObservation(record3,observations,terminalStatus,recovered=!1){try{let costFields=buildDelegationCostFields({raw:observations.costRaw,model:observations.model,pricing:observations.pricing});Object.assign(costFields,buildDelegationTerminalIdentityFields({record:record3,model:observations.model,recovered})),_internals251.telemetry.delegationEnd(record3.parentSessionId,record3.swarmPrefixedAgent,record3.planTaskId??"",terminalStatus,costFields)}catch(error93){log(`[delegation-lifecycle] cost observation skipped: ${error93 instanceof Error?error93.message:String(error93)}`)}}function emitDelegationEventlessTerminalEnd(record3,terminalStatus){emitDelegationCostObservation(record3,{},terminalStatus,!0)}async function appendDelegationTrajectoryObservation(directory,record3,terminalStatus,observations,now2){try{let lastStep=await getCurrentStep(record3.parentSessionId,directory);seedTrajectoryStepCounter(record3.parentSessionId,directory,lastStep);let entry={step:nextTrajectoryStep(record3.parentSessionId,directory),agent:record3.swarmPrefixedAgent,action:"delegate",target:record3.laneId??record3.correlationId,intent:`dispatch_lanes terminal ${terminalStatus}`,timestamp:new Date(now2).toISOString(),result:terminalStatus==="completed"?"success":"failure",tool:"dispatch_lanes",...observations.startedAt!==void 0?{elapsed_ms:Math.max(0,now2-observations.startedAt)}:{},...record3.batchId!==void 0?{batchId:record3.batchId}:{},laneId:record3.laneId??record3.correlationId,...record3.planTaskId?{taskId:record3.planTaskId}:{}};await appendTrajectoryEntry(record3.parentSessionId,entry,directory)}catch{}}async function reconcileLaneKnowledgeReceipts(directory,record3,observations,replay=!1){if(!observations.transcript)return;try{let ack=await collectLaneDelegateAcks({directory,sessionId:record3.subagentSessionId,agent:record3.swarmPrefixedAgent,transcript:observations.transcript,replay});if(record3.normalizedAgent!=="reviewer")return;let phase=ack.phases.find((value)=>Boolean(value));if(!phase)return;let directivesToVerify=await readPhaseDirectivesToVerify(directory,phase);if(directivesToVerify.length===0)return;await reconcileReviewerVerdicts({directory,transcript:observations.transcript,directivesToVerify,sessionId:record3.subagentSessionId,agent:"reviewer"})}catch{}}async function runDelegationTerminalObservations(directory,record3,terminal,observations,now2){emitDelegationCostObservation(record3,observations,terminal.status),await appendDelegationTrajectoryObservation(directory,record3,terminal.status,observations,now2),await reconcileLaneKnowledgeReceipts(directory,record3,observations)}function candidateAfter(record3,cursor){if(record3.updatedAt!==cursor.updatedAt)return record3.updatedAt>cursor.updatedAt;return record3.correlationId>cursor.correlationId}function readRecoveryCursor(directory){try{let filePath=path303.join(directory,".swarm",RECOVERY_CURSOR_FILE);if(!fs177.existsSync(filePath))return null;let parsed=JSON.parse(fs177.readFileSync(filePath,"utf-8"));if(typeof parsed.updatedAt==="number"&&Number.isFinite(parsed.updatedAt)&&typeof parsed.correlationId==="string"&&parsed.correlationId.length>0)return{updatedAt:parsed.updatedAt,correlationId:parsed.correlationId};return null}catch{return null}}function writeRecoveryCursor(directory,cursor){try{let swarmDir=path303.join(directory,".swarm");fs177.mkdirSync(swarmDir,{recursive:!0});let filePath=path303.join(swarmDir,RECOVERY_CURSOR_FILE);if(cursor===null)fs177.rmSync(filePath,{force:!0});else fs177.writeFileSync(filePath,JSON.stringify(cursor),"utf-8")}catch{}}function isRecoverableTerminalLaneRecord(record3){return Boolean(record3.laneId&&record3.terminalResult&&typeof record3.terminalResult.result.text==="string"&&record3.terminalResult.result.text.length>0)}async function recoverTerminalLaneReceipts(directory,records,options={}){let now2=options.now??Date.now,deadlineMs=options.deadlineMs??TERMINAL_LANE_RECEIPT_RECOVERY_DEADLINE_MS,deadline=now2()+deadlineMs;if(records!==void 0){let recovered2=0;for(let record3 of records){if(!isRecoverableTerminalLaneRecord(record3))continue;let transcript=record3.terminalResult?.result.text;if(!transcript)continue;if(now2()>=deadline)return{recovered:recovered2,exhaustedBudget:!0};try{await reconcileLaneKnowledgeReceipts(directory,record3,{transcript},!0),recovered2+=1}catch{}}return{recovered:recovered2,exhaustedBudget:!1}}let enumeration=readDelegationsDetailed(directory);if(enumeration.status==="uncertain")return warn(`[delegation-lifecycle] terminal-lane receipt recovery deferred: delegation store unreadable after ${enumeration.attempts} attempts (${enumeration.reason})`),{recovered:0,exhaustedBudget:!1};let candidates=enumeration.records.filter(isRecoverableTerminalLaneRecord).sort((left,right)=>{if(left.updatedAt!==right.updatedAt)return left.updatedAt-right.updatedAt;return left.correlationId<right.correlationId?-1:left.correlationId>right.correlationId?1:0});if(candidates.length===0)return{recovered:0,exhaustedBudget:!1};let cursor=readRecoveryCursor(directory),selected=cursor?candidates.filter((record3)=>candidateAfter(record3,cursor)):candidates,wrapped=!1;if(selected.length===0)selected=candidates,wrapped=!0;let recovered=0,lastProcessed=null;for(let record3 of selected){if(recovered>=MAX_TERMINAL_LANE_RECEIPT_RECOVERY)break;if(now2()>=deadline)break;let transcript=record3.terminalResult?.result.text;if(!transcript)continue;try{await reconcileLaneKnowledgeReceipts(directory,record3,{transcript},!0),recovered+=1,lastProcessed={updatedAt:record3.updatedAt,correlationId:record3.correlationId}}catch{lastProcessed={updatedAt:record3.updatedAt,correlationId:record3.correlationId}}}let lastCandidate=selected[selected.length-1],processedAll=selected.length>0&&lastProcessed!==null&&lastCandidate!==void 0&&lastProcessed.updatedAt===lastCandidate.updatedAt&&lastProcessed.correlationId===lastCandidate.correlationId,nextCursor=wrapped&&processedAll?null:lastProcessed??cursor??null;if(nextCursor?.correlationId!==cursor?.correlationId)writeRecoveryCursor(directory,nextCursor);return{recovered,exhaustedBudget:recovered<selected.length&&(now2()>=deadline||recovered>=MAX_TERMINAL_LANE_RECEIPT_RECOVERY)}}var MAX_TERMINAL_LANE_RECEIPT_RECOVERY=64,TERMINAL_LANE_RECEIPT_RECOVERY_DEADLINE_MS=5000,RECOVERY_CURSOR_FILE="lane-receipt-recovery-cursor.json",_internals251;var init_delegation_lifecycle=__esm(()=>{init_delegate_ack_collector();init_phase_directives();init_reviewer_verdict_parser();init_trajectory_step_state();init_trajectory_store();init_cost_accounting();init_telemetry();init_logger();init_delegation_cost_identity();init_pending_delegations();init_delegation_cost_identity();registerStaleSweepObserver((record3)=>{emitDelegationEventlessTerminalEnd(record3,"stale")});_internals251={claimTerminalResult,findByCorrelationId,findByCorrelationIdDetailed,telemetry}});var exports_design_doc_drift={};__export(exports_design_doc_drift,{runDesignDocDriftCheck:()=>runDesignDocDriftCheck,_internals:()=>_internals272});import*as fs198 from"node:fs";import*as path326 from"node:path";function mtimeMsOrNull(absPath){try{return fs198.statSync(absPath).mtimeMs}catch{return null}}function resolveAnchorWithin(directory,anchor){if(!anchor||typeof anchor!=="string")return null;let root=path326.resolve(directory),resolved=path326.resolve(root,anchor),rel3=path326.relative(root,resolved);if(rel3.startsWith("..")||path326.isAbsolute(rel3))return null;return resolved}async function runDesignDocDriftCheck(directory,phase,outDir){try{let root=path326.resolve(directory),outAbs=path326.resolve(root,outDir),outRel=path326.relative(root,outAbs);if(outRel.startsWith("..")||path326.isAbsolute(outRel))return null;let docMtimes=new Map,checkedDocs=[],missingDocs=[];for(let[docName,relFile]of Object.entries(DESIGN_DOC_FILES)){let abs=path326.join(outAbs,relFile),mtime=mtimeMsOrNull(abs);if(docMtimes.set(docName,mtime),mtime===null)missingDocs.push(path326.join(outDir,relFile));else checkedDocs.push(path326.join(outDir,relFile))}let traceabilityAbs=path326.join(outAbs,TRACEABILITY_REL),registry3=null;try{if((await fs198.promises.stat(traceabilityAbs)).size<=MAX_TRACEABILITY_BYTES){let raw=await fs198.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},locator=phaseReportLocator("design_doc_drift",phase);return await upsertPhaseReportDb(directory,"design_doc_drift",phase,JSON.stringify(report,null,2)),getGlobalEventBus().publish("curator.docdrift.completed",{phase,verdict,stale_count:staleSections.length,report_path:locator}),report}catch(err){try{getGlobalEventBus().publish("curator.error",{operation:"docdrift",phase,error:String(err)})}catch{}return warn(`[design-doc-drift] check failed for phase ${phase}: ${String(err)}`),null}}var MAX_TRACEABILITY_BYTES=1048576,DESIGN_DOC_FILES,TRACEABILITY_REL,_internals272;var init_design_doc_drift=__esm(()=>{init_event_bus();init_phase_report_store();init_effective_spec();init_logger();DESIGN_DOC_FILES={domain:"domain.md","technical-spec":"technical-spec.md","behavior-spec":"behavior-spec.md","reference-impl":path326.join("reference","reference-impl.md"),"idiom-notes":path326.join("reference","idiom-notes.md")},TRACEABILITY_REL=path326.join("reference","traceability.json");_internals272={mtimeMsOrNull,resolveAnchorWithin,DESIGN_DOC_FILES}});var exports_project_context={};__export(exports_project_context,{buildProjectContext:()=>buildProjectContext,_internals:()=>_internals304,LANG_BACKEND_DETECTION_TIMEOUT_MS:()=>LANG_BACKEND_DETECTION_TIMEOUT_MS});import*as fs228 from"node:fs";import*as path364 from"node:path";function detectFileExists2(directory,pattern){if(pattern.includes("*")||pattern.includes("?"))try{let files=fs228.readdirSync(directory),regex=new RegExp(`^${pattern.replace(/\./g,"\\.").replace(/\*/g,".*").replace(/\?/g,".")}$`);return files.some((f)=>regex.test(f))}catch{return!1}try{return fs228.accessSync(path364.join(directory,pattern)),!0}catch{return!1}}function selectTestCommandFromScriptsTest(backend,directory){let pkgRaw;try{pkgRaw=fs228.readFileSync(path364.join(directory,"package.json"),"utf-8")}catch{return null}let pkg;try{pkg=JSON.parse(pkgRaw)}catch{return null}let script=pkg.scripts?.test;if(!script)return null;let fwName=null;if(script.includes("vitest"))fwName="vitest";else if(script.includes("jest"))fwName="jest";else if(script.includes("mocha"))fwName="mocha";else if(script.includes("bun test"))fwName="bun:test";if(!fwName)return null;let fw=backend.test.frameworks.find((f)=>f.name===fwName);return fw?fw.cmd:null}function selectTestCommandFast(backend,directory){let fromScripts=selectTestCommandFromScriptsTest(backend,directory);if(fromScripts!==null)return fromScripts;let sorted2=[...backend.test.frameworks].sort((a,b)=>b.priority-a.priority);for(let fw of sorted2){if(!detectFileExists2(directory,fw.detect))continue;return fw.cmd}return null}function selectBuildCommandFast(backend,directory){let sorted2=[...backend.build.commands].sort((a,b)=>b.priority-a.priority);for(let cmd of sorted2){if(cmd.detectFile&&!detectFileExists2(directory,cmd.detectFile))continue;return cmd.cmd}return null}function selectLintCommand(backend,directory){let sorted2=[...backend.lint.linters].sort((a,b)=>b.priority-a.priority);for(let lint2 of sorted2){if(!detectFileExists2(directory,lint2.detect))continue;return lint2.cmd}return null}async function buildProjectContext(directory,signal2){let backend=await _internals304.pickBackend(directory,signal2);if(!backend)return null;let profiles=_internals304.pickedProfiles(directory),ctx=emptyProjectContext();ctx.PROJECT_LANGUAGE=backend.displayName;let buildCmd=selectBuildCommandFast(backend,directory);if(buildCmd)ctx.BUILD_CMD=buildCmd;let testCmd=selectTestCommandFast(backend,directory);if(testCmd)ctx.TEST_CMD=testCmd;let lintCmd=selectLintCommand(backend,directory);if(lintCmd)ctx.LINT_CMD=lintCmd;if(backend.id==="php"){let overlay=getLaravelCommandOverlay(directory);if(overlay){if(ctx.TEST_CMD=overlay.testCommand,overlay.lintCommand)ctx.LINT_CMD=overlay.lintCommand}}let[frameworkSel,entryPoints]=await Promise.all([backend.selectFramework?backend.selectFramework(directory).catch(()=>null):Promise.resolve(null),backend.selectEntryPoints?backend.selectEntryPoints(directory).catch(()=>[]):Promise.resolve([])]);if(frameworkSel)ctx.PROJECT_FRAMEWORK=frameworkSel.name;if(entryPoints.length>0)ctx.ENTRY_POINTS=entryPoints.join(", ");if(backend.prompts.coderConstraints.length>0)ctx.CODER_CONSTRAINTS=bulletList(backend.prompts.coderConstraints);if(backend.prompts.testConstraints&&backend.prompts.testConstraints.length>0)ctx.TEST_CONSTRAINTS=bulletList(backend.prompts.testConstraints);if(backend.prompts.reviewerChecklist.length>0)ctx.REVIEWER_CHECKLIST=bulletList(backend.prompts.reviewerChecklist);if(profiles.length>1)ctx.PROJECT_CONTEXT_SECONDARY_LANGUAGES=profiles.slice(1).map((p)=>p.id).join(", ");return ctx}var LANG_BACKEND_DETECTION_TIMEOUT_MS=300,_internals304;var init_project_context=__esm(()=>{init_dispatch();init_framework_detector();_internals304={pickBackend,pickedProfiles}});init_package();init_agents2();init_critic();import{createHash as createHash108}from"node:crypto";import*as path365 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_manager4();init_manager();init_utils();import*as fs143 from"node:fs";import*as path255 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 path255.resolve(this.directory,".swarm")}getPlanJsonPath(){return path255.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=fs143.statSync(this.getPlanJsonPath());this.lastStat={mtimeMs:stats2.mtimeMs,size:stats2.size}}catch{this.lastStat=null}}setupNativeWatcher(){let swarmDir=this.getSwarmDir();try{if(!fs143.existsSync(swarmDir))return log("[PlanSyncWorker] Swarm directory does not exist yet"),!1;return this.watcher=fs143.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(!fs143.existsSync(planPath)){if(this.lastStat!==null)this.lastStat=null,log("[PlanSyncWorker] plan.json deleted");return}let stats2=fs143.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(_internals51.loadPlanJsonOnly(this.directory),this.syncTimeoutMs,"Sync operation timed out");if(plan&&plan.phases.length>0)await _internals51.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=path255.join(swarmDir,"plan.json"),markerPath=path255.join(swarmDir,".plan-write-marker"),planStats=fs143.statSync(planJsonPath),planMtimeMs=Math.floor(planStats.mtimeMs),markerContent=fs143.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((resolve101,reject)=>{let timer=setTimeout(()=>{reject(Error(`${timeoutMessage2} (${ms}ms)`))},ms);promise3.then((result)=>{clearTimeout(timer),resolve101(result)}).catch((error93)=>{clearTimeout(timer),reject(error93)})})}}init_pr_event_subscribers();init_pr_monitor_worker();init_queue();init_status_artifact();init_trigger();init_worker();import{createHash as createHash89}from"node:crypto";init_zod();init_task_envelope();init_workspace_snapshot();init_plan_schema();init_schema();init_plan_task_id_context();init_task_id_resolver();init_task_result_classifier();init_utils2();init_ledger();init_manager();init_utils3();init_atomic_write();init_canonical_root();init_lock();init_task_file();import{createHash as createHash88}from"node:crypto";import*as fs145 from"node:fs";import*as path258 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 sha2569(value){return createHash88("sha256").update(value).digest("hex")}function policyDigest(policy){return sha2569(stableCanonicalStringify(policy??{}))}async function captureParticipationWorkspace(directory){let workspace=await captureWorkspaceSnapshotAsync(directory,{resolveCurrentPrHeadSha:!0});return{directory:workspace.directory,gitHead:workspace.gitHead,prHeadSha:workspace.prHeadSha}}function boundedPut(binding){let key2=correlationKey(binding.parentSessionId,binding.callId);foregroundReservations.delete(key2),foregroundReservations.set(key2,binding);while(foregroundReservations.size>MAX_PENDING_IN_MEMORY){let oldest=foregroundReservations.keys().next().value;if(!oldest)break;foregroundReservations.delete(oldest)}}function takeBinding(parentSessionId,callId){let key2=correlationKey(parentSessionId,callId),binding=foregroundReservations.get(key2)??null;return foregroundReservations.delete(key2),binding}async function persistWithBindingRecovery(directory,binding,operation){try{await withEvidenceLock(directory,PHASE_PARTICIPATION_FILE,"docs","phase-participation",operation)}catch(error93){throw boundedPut(binding),error93}}async function buildBinding(input){return{role:stripKnownSwarmPrefix(input.role),prefixedRole:input.role,planId:derivePlanId(input.plan),planIdentityHash:derivePlanIdentityHash(input.plan),planStructureHash:computePlanStructureHash(input.plan),phase:input.phase,taskId:input.taskId,parentSessionId:input.parentSessionId,callId:input.callId,policyDigest:policyDigest(input.policy),workspace:await captureParticipationWorkspace(input.directory),capturedAt:Date.now()}}function extractPlanTaskId2(args2,plan){let context=collectPlanTaskIdContextFromPhases(plan.phases),result=resolveTaskId(args2,{policy:"plan",...toTaskIdPlanContextOptions(context)});if(result.status!=="resolved")return null;if(context.status==="over_limit"&&!plan.phases.some((phase)=>phase?.tasks?.some((task2)=>task2?.id===result.taskId)))return null;return result.taskId}function storePath6(directory){return validateSwarmPath(directory,PHASE_PARTICIPATION_FILE)}function readRawStore(directory){let filePath;try{filePath=storePath6(directory)}catch(error93){return{status:"unreadable",error:error93}}let descriptor,bytes;try{let pathStat=fs145.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=fs145.openSync(filePath,fs145.constants.O_RDONLY|(fs145.constants.O_NOFOLLOW??0));let openedStat=fs145.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=fs145.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{fs145.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 fs145.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 fs145.promises.open(filePath,fs145.constants.O_RDONLY|(fs145.constants.O_NOFOLLOW??0));try{let openedStat=await handle.stat();if(!openedStat.isFile()||openedStat.dev!==pathStat.dev||openedStat.ino!==pathStat.ino||openedStat.size>maxBytes)throw Error("bounded evidence artifact changed while being opened");let bounded=Buffer.allocUnsafe(maxBytes+1),offset=0;while(offset<bounded.byteLength){let{bytesRead}=await handle.read(bounded,offset,bounded.byteLength-offset,null);if(bytesRead===0)break;offset+=bytesRead}if(offset>maxBytes)throw Error("bounded evidence artifact exceeds its byte limit");return bounded.subarray(0,offset)}finally{try{await handle.close()}catch{}}}function quarantineFullError(){return Error("PHASE_PARTICIPATION_QUARANTINE_FULL: preserved corrupt evidence reached its bounded retention limit; an operator must archive the quarantine before docs can be re-dispatched.")}async function quarantineCorruptBytes(directory,bytes){let digest4=sha2569(bytes),quarantineDir=validateSwarmPath(directory,PHASE_PARTICIPATION_QUARANTINE_DIR);await fs145.promises.mkdir(quarantineDir,{recursive:!0});let quarantineStat=await fs145.promises.lstat(quarantineDir);if(quarantineStat.isSymbolicLink()||!quarantineStat.isDirectory())throw Error("PHASE_PARTICIPATION_QUARANTINE_UNREADABLE: quarantine is not a regular directory.");let target=validateSwarmPath(directory,`${PHASE_PARTICIPATION_QUARANTINE_DIR}/${digest4}.bin`);try{if(!(await readBoundedRegularFile(target,MAX_PHASE_PARTICIPATION_BYTES)).equals(bytes))throw Error("hash-addressed quarantine content mismatch");return}catch(error93){if(error93.code!=="ENOENT")throw error93}let count=0,totalBytes=0,scanned=0,handle=await fs145.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 fs145.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 writeStore3(directory,store){let validatedStore=StoreSchema.parse(store);validatedStore.pending.sort((left,right)=>left.capturedAt-right.capturedAt),validatedStore.receipts.sort((left,right)=>left.completedAt-right.completedAt);let serialized3=JSON.stringify(validatedStore,null,2);while(Buffer.byteLength(serialized3,"utf8")>MAX_PHASE_PARTICIPATION_BYTES){let pendingTime=validatedStore.pending[0]?.capturedAt??1/0,receiptTime=validatedStore.receipts[0]?.completedAt??1/0;if(pendingTime===1/0&&receiptTime===1/0)throw Error("PHASE_PARTICIPATION_WRITE_OVERSIZED: even an empty participation store exceeds its byte limit.");if(pendingTime<=receiptTime)validatedStore.pending.shift();else validatedStore.receipts.shift();validatedStore=StoreSchema.parse(validatedStore),serialized3=JSON.stringify(validatedStore,null,2)}await fs145.promises.mkdir(path258.dirname(storePath6(directory)),{recursive:!0}),await atomicWriteFile(storePath6(directory),serialized3)}function samePlanIdentity(binding,plan){return binding.planId===derivePlanId(plan)&&binding.planIdentityHash===derivePlanIdentityHash(plan)&&binding.planStructureHash===computePlanStructureHash(plan)}function bindingMatchesPlan(binding,plan,phase){return samePlanIdentity(binding,plan)&&binding.phase===phase}function workspaceIdentityIsFresh(expected,current){return sameProjectRoot(expected.directory,current.directory)&&expected.gitHead===current.gitHead&&expected.prHeadSha===current.prHeadSha}function resultText(output){if(!output||typeof output!=="object")return{text:"",childSessionId:null};let record3=output,rawOutput=typeof record3.output==="string"?record3.output:"",envelope=parseTaskEnvelope(rawOutput);if(envelope?.state==="completed")return{text:envelope.resultText??"",childSessionId:envelope.sessionId};return{text:rawOutput,childSessionId:null}}function envelopeFromOutput(output){if(typeof output==="string")return parseTaskEnvelope(output);if(!output||typeof output!=="object")return null;let rawOutput=output.output;return typeof rawOutput==="string"?parseTaskEnvelope(rawOutput):null}function validateMetadata(output,parentSessionId,childSessionId){if(!output||typeof output!=="object")return{valid:!0,childSessionId};let metadata=output.metadata;if(!metadata||typeof metadata!=="object")return{valid:!0,childSessionId};let meta3=metadata;if(typeof meta3.parentSessionId==="string"&&meta3.parentSessionId!==parentSessionId)return{valid:!1,childSessionId:null};let metadataChild=typeof meta3.sessionId==="string"&&meta3.sessionId.length>0?meta3.sessionId:null;if(childSessionId&&metadataChild&&childSessionId!==metadataChild)return{valid:!1,childSessionId:null};return{valid:!0,childSessionId:childSessionId??metadataChild}}function computeReceiptId(input){return sha2569(stableCanonicalStringify({parentSessionId:input.parentSessionId,callId:input.callId,childSessionId:input.childSessionId,planIdentityHash:input.planIdentityHash,planStructureHash:input.planStructureHash,phase:input.phase,role:input.role}))}function addReceipt(store,pending,text,childIdentityAvailable){let receiptId=computeReceiptId(pending),receipt={...pending,receiptId,resultDigest:sha2569(text),completedAt:Date.now(),childIdentityAvailable};store.receipts=store.receipts.filter((existing)=>existing.receiptId!==receiptId&&!(existing.planIdentityHash===receipt.planIdentityHash&&existing.planStructureHash===receipt.planStructureHash&&existing.phase===receipt.phase&&existing.role===receipt.role)),store.receipts.push(receipt),store.receipts=store.receipts.slice(-MAX_PHASE_PARTICIPATION_RECEIPTS)}async function reserveApprovedPhaseParticipation(input){if(input.tool.toLowerCase()!=="task")return;let rawRole=input.args.subagent_type;if(typeof rawRole!=="string"||stripKnownSwarmPrefix(rawRole)!=="docs")return;let plan=await loadPlan(input.directory);if(!plan)return;let binding=await buildBinding({plan,phase:getCurrentPhase(plan),role:rawRole,parentSessionId:input.parentSessionId,callId:input.callId,taskId:extractPlanTaskId2(input.args,plan),policy:input.policy,directory:input.directory});await withEvidenceLock(input.directory,PHASE_PARTICIPATION_FILE,"docs","phase-participation",async()=>{let store=await loadWritableStoreUnderLock(input.directory);await writeStore3(input.directory,store)}),boundedPut(binding)}async function observePhaseParticipationToolResult(input){if(input.tool.toLowerCase()!=="task")return;let binding=takeBinding(input.parentSessionId,input.callId);if(!binding)return;let envelope=envelopeFromOutput(input.output);if(envelope?.state==="running"){let{subagentSessionId}=extractDispatchIds(input.output);if(!subagentSessionId||subagentSessionId!==envelope.sessionId)return;let pending2={...binding,childSessionId:subagentSessionId};await persistWithBindingRecovery(input.directory,binding,async()=>{let store=await loadWritableStoreUnderLock(input.directory);store.pending=store.pending.filter((existing)=>existing.childSessionId!==pending2.childSessionId&&!(existing.parentSessionId===pending2.parentSessionId&&existing.callId===pending2.callId)),store.pending.push(pending2),store.pending=store.pending.slice(-MAX_PHASE_PARTICIPATION_PENDING),await writeStore3(input.directory,store)});return}if(envelope&&envelope.state!=="completed")return;if(classifyTaskResult(input.output)!=="success")return;let extracted=resultText(input.output),text=extracted.text.trim();if(!text)return;let metadata=validateMetadata(input.output,input.parentSessionId,extracted.childSessionId);if(!metadata.valid)return;let childSessionId=metadata.childSessionId,currentPlan=await loadPlan(input.directory);if(!currentPlan||!bindingMatchesPlan(binding,currentPlan,binding.phase))return;if(!workspaceIdentityIsFresh(binding.workspace,await captureParticipationWorkspace(input.directory)))return;let pending={...binding,childSessionId:childSessionId??`unavailable:${sha2569(correlationKey(input.parentSessionId,input.callId))}`};await persistWithBindingRecovery(input.directory,binding,async()=>{let store=await loadWritableStoreUnderLock(input.directory);addReceipt(store,pending,text,childSessionId!==null),await writeStore3(input.directory,store)})}async function completeBackgroundPhaseParticipation(input){if(stripKnownSwarmPrefix(input.record.normalizedAgent)!=="docs")return!1;let text=input.resultText.trim();if(!text)return!1;return withEvidenceLock(input.directory,PHASE_PARTICIPATION_FILE,"docs","phase-participation",async()=>{let store=await loadWritableStoreUnderLock(input.directory),currentPlan=await loadPlan(input.directory),existingReceipt=store.receipts.find((receipt)=>receipt.childSessionId===input.record.subagentSessionId&&receipt.parentSessionId===input.record.parentSessionId&&receipt.callId===input.record.callID&&receipt.role===input.record.normalizedAgent&&receipt.prefixedRole===input.record.swarmPrefixedAgent&&receipt.taskId===input.record.planTaskId);if(existingReceipt&¤tPlan&&bindingMatchesPlan(existingReceipt,currentPlan,existingReceipt.phase))return!0;let pending=store.pending.find((candidate2)=>candidate2.childSessionId===input.record.subagentSessionId&&candidate2.parentSessionId===input.record.parentSessionId&&candidate2.callId===input.record.callID&&candidate2.role===input.record.normalizedAgent&&candidate2.prefixedRole===input.record.swarmPrefixedAgent&&candidate2.taskId===input.record.planTaskId);if(!pending)return!1;let plan=currentPlan;if(!plan||!bindingMatchesPlan(pending,plan,pending.phase))return!1;if(!workspaceIdentityIsFresh(pending.workspace,await captureParticipationWorkspace(input.directory)))return!1;if(pending.taskId!==null&&input.record.ingestion?.state!=="consumed")return!1;return addReceipt(store,pending,text,!0),store.pending=store.pending.filter((candidate2)=>candidate2.childSessionId!==pending.childSessionId),await writeStore3(input.directory,store),!0})}async function readPhaseParticipation(directory,plan,phase,role){let read=readRawStore(directory);if(read.status!=="valid")return{status:read.status,found:!1};let canonicalRole2=stripKnownSwarmPrefix(role),currentWorkspace=await captureParticipationWorkspace(directory),cursorPhase=getCurrentPhase(plan);return{status:"valid",found:read.store.receipts.some((receipt)=>receipt.role===canonicalRole2&&samePlanIdentity(receipt,plan)&&workspaceIdentityIsFresh(receipt.workspace,currentWorkspace)&&(receipt.phase===phase||receipt.phase===cursorPhase&&cursorPhase<phase))}}async function rebindCursorTaggedReceipts(directory,plan,phase,role){let canonicalRole2=stripKnownSwarmPrefix(role),cursorPhase=getCurrentPhase(plan),peek=readRawStore(directory);if(!(peek.status==="valid"&&peek.store.receipts.some((receipt)=>receipt.role===canonicalRole2&&samePlanIdentity(receipt,plan)&&receipt.phase===cursorPhase&&cursorPhase<phase)))return{rebound:0};return withEvidenceLock(directory,PHASE_PARTICIPATION_FILE,"docs","phase-participation",async()=>{let store=await loadWritableStoreUnderLock(directory),rebound=0;for(let receipt of store.receipts)if(receipt.role===canonicalRole2&&samePlanIdentity(receipt,plan)&&receipt.phase===cursorPhase&&cursorPhase<phase)receipt.phase=phase,receipt.receiptId=computeReceiptId(receipt),rebound+=1;if(rebound>0){let newestByKey=new Map;for(let receipt of store.receipts.slice().sort((left,right)=>left.completedAt-right.completedAt))newestByKey.set(`${receipt.planIdentityHash}\x00${receipt.planStructureHash}\x00${receipt.phase}\x00${receipt.role}`,receipt);store.receipts=[...newestByKey.values()],await writeStore3(directory,store)}return{rebound}})}init_gate_evidence();init_worktree_isolation();init_helpers();init_state2();init_canonical_root();init_logger();init_coder_settlement();init_merge2();init_pending_delegations();init_loader();init_task_gate_requirements();init_gate_evidence();init_gate_evidence_classification();init_review_receipt_collector();init_reviewer_scope_file_fingerprint();init_routing_enforcement();init_scope_binding();init_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 state2=getTaskState(parentSession,taskId);if(state2!=="idle"&&state2!=="coder_delegated"&&state2!=="rework_required")return{ok:!1,consumed:!1,reason:`background coder completion is late for task ${taskId}: current state is ${state2}`}}let accepted=attributedFiles.length>0,expectedGeneration=args2.record.taskChangeContext?.workflowGeneration??0,transitionId=`background-coder:${args2.record.correlationId}`,existingEvidence=await readTaskEvidence(args2.directory,taskId),existingWorkflow=getTaskWorkflowSnapshot(existingEvidence),updated=existingWorkflow.authoritative&&existingWorkflow.lastTransitionId===transitionId&&existingWorkflow.lastOutcome===(accepted?"accepted_mutation":"dispatch_no_mutation")&&existingWorkflow.generation===expectedGeneration+(accepted?1:0)?existingEvidence:await transitionTaskWorkflowEvidence(args2.directory,taskId,accepted?{type:"accepted_mutation",agentType:"coder",context:{testEngineerExempt:isMarkdownOnlyTaskChange(taskChangeContext?.declaredFiles,attributedFiles)},expectedGeneration,transitionId}:{type:"dispatch_no_mutation",agentType:"coder",expectedGeneration,transitionId});if(accepted){let workflow=getTaskWorkflowSnapshot(updated),parentSession2=swarmState.agentSessions.get(args2.record.parentSessionId);if(parentSession2){if(!recordModifiedFilesForTask(parentSession2,taskId,attributedFiles))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 rejected2=await transitionTaskWorkflowEvidence(args2.directory,taskId,{type:"stage_b_failed",gate:stageBRole,expectedGeneration:args2.record.workflowGeneration,transitionId:`background-gate-failed:${args2.record.correlationId}`}),parentSession=swarmState.agentSessions.get(args2.record.parentSessionId);if(parentSession)parentSession.taskWorkflowStates.set(taskId,"rework_required"),parentSession.stageBCompletion?.delete(taskId),updateTaskWorkflowCache(parentSession,taskId,getTaskWorkflowSnapshot(rejected2));return{ok:!1,consumed:!0,reason:verdict==="fail"?`background ${stageBRole} rejected task ${taskId}`:`background ${stageBRole} returned no valid structured verdict for task ${taskId}`}}let preparedRoute,routeCompleteForPersistence;if(stageBRole){let parentSession=swarmState.agentSessions.get(args2.record.parentSessionId);if(parentSession){preparedRoute=resolveBackgroundStageBRoute({directory:args2.directory,taskId,parentSessionId:args2.record.parentSessionId,role:stageBRole,callId:args2.record.callID,childSessionId:args2.record.subagentSessionId,generation:args2.record.workflowGeneration,session:parentSession});let routeEnabled=(()=>{try{return loadPluginConfig(args2.directory).review_routing?.enforce_receipts??!0}catch{return!0}})(),routeDecision=enforcePersistedReviewRouteReceipt({projectRoot:args2.directory,sessionId:args2.record.parentSessionId,taskId,receipts:preparedRoute.prospective,enforcementEnabled:routeEnabled,legacyUnrouted:preparedRoute.legacyUnrouted,requireEvidenceBindings:!0,requireCompleteEvidence:!1,expectedDispatch:preparedRoute.binding?{role:preparedRoute.binding.role,identity:preparedRoute.binding.identity,callId:preparedRoute.binding.callId,childSessionId:preparedRoute.binding.childSessionId,generation:preparedRoute.binding.generation}:void 0});if(!routeDecision.canAdvance)return warn(`[background-stage-b] route receipt blocked before evidence publication for ${taskId}: ${routeDecision.reason??"unknown reason"}`),{ok:!1,consumed:!1,reason:`route receipt blocked before Stage-B evidence publication: ${routeDecision.reason??"unknown reason"}`};if(routeEnabled&&preparedRoute.route?.kind==="review_route_receipt")routeCompleteForPersistence=enforcePersistedReviewRouteReceipt({projectRoot:args2.directory,sessionId:args2.record.parentSessionId,taskId,receipts:preparedRoute.prospective,enforcementEnabled:!0,legacyUnrouted:preparedRoute.legacyUnrouted,requireEvidenceBindings:!0,requireCompleteEvidence:!0}).canAdvance}else{let route=readReviewRouteReceiptSync({projectRoot:args2.directory,sessionId:args2.record.parentSessionId,taskId});if(route?.kind!=="review_route_router_error"||route.sessionId!==args2.record.parentSessionId||route.taskId!==taskId)return{ok:!1,consumed:!1,reason:"route receipt blocked before Stage-B evidence publication: parent session is unavailable and recovery receipt is not identity-bound"}}}let routeEvidenceRollback=null;if(preparedRoute?.binding){let parentSession=swarmState.agentSessions.get(args2.record.parentSessionId);if(!parentSession)return warn(`[background-stage-b] route receipt blocked before evidence publication for ${taskId}: parent session unavailable`),{ok:!1,consumed:!1,reason:"route receipt blocked before Stage-B evidence publication: parent session unavailable"};if(routeEvidenceRollback=reserveStageBRouteEvidence(parentSession,taskId,preparedRoute.binding),!routeEvidenceRollback)return warn(`[background-stage-b] route receipt blocked before evidence publication for ${taskId}: bounded route evidence capacity exceeded`),{ok:!1,consumed:!1,reason:"route receipt blocked before Stage-B evidence publication: bounded route evidence capacity exceeded"}}try{await recordGateEvidence(args2.directory,taskId,args2.record.normalizedAgent,args2.record.subagentSessionId,hasActiveTurboMode(args2.record.parentSessionId),{expectedGeneration:args2.record.workflowGeneration,transitionId:`background-gate:${args2.record.correlationId}`,ensureDefaultStageB:existingEvidence?.test_engineer_exempt!==!0,routeBinding:preparedRoute?.binding,routeComplete:routeCompleteForPersistence})}catch(err){throw routeEvidenceRollback?.(),err}if(args2.record.normalizedAgent==="reviewer")await collectReviewerReceiptFromTranscript(args2.directory,{targetAgent:args2.record.swarmPrefixedAgent,prompt:args2.record.prompt?.text??"",transcript:args2.result.text??"",sessionID:args2.record.parentSessionId,taskId,reviewerCallID:args2.record.callID,consumeHandoff:!0},args2.reviewerReceiptOptions);if(args2.record.normalizedAgent==="reviewer"||args2.record.normalizedAgent==="test_engineer")applyStageBStateCompletion(taskId,args2.record.normalizedAgent,args2.record.parentSessionId,existingEvidence?.test_engineer_exempt===!0,args2.directory,args2.record.callID,args2.record.subagentSessionId,args2.record.workflowGeneration,preparedRoute);return{ok:!0,consumed:!0}}catch(err){let message=err instanceof Error?err.message:String(err);return warn(`[background-stage-b] ingestion failed: ${message}`),{ok:!1,consumed:!1,reason:`stage-b ingestion failed: ${message}`}}}function candidateSessions(parentSessionId){let parent=swarmState.agentSessions.get(parentSessionId);return parent?[parent]:[]}function routeDispatchKey(entry){if(!entry.callId||!entry.childSessionId||typeof entry.generation!=="number")return null;return[entry.role,entry.sessionId??"",entry.taskId??"",entry.callId,entry.childSessionId,String(entry.generation)].join("\x00")}function resolveBackgroundStageBRoute(input){let route=readReviewRouteReceiptSync({projectRoot:input.directory,sessionId:input.parentSessionId,taskId:input.taskId}),evidence2=getStageBRouteEvidence(input.session,input.taskId);if(evidence2.length===0)try{evidence2=routeEvidenceFromTaskGateRequirements(readTaskGateRequirementsReceiptsSync(input.directory,input.taskId))}catch{}let legacyUnrouted=route===null&&!isStageBRouteRequired(input.session,input.taskId)&&(()=>{try{let receipts=readTaskGateRequirementsReceiptsSync(input.directory,input.taskId);return receipts.length>0&&receipts.every((receipt)=>!receipt.routeBinding)}catch{return!1}})(),binding,prospective=evidence2;if(route?.kind==="review_route_receipt"){let identities=input.role==="reviewer"?route.identities.reviewers:route.identities.testEngineers,slots=input.role==="reviewer"?route.slots?.reviewers??identities:route.slots?.testEngineers??identities,dispatchKey2=[input.role,input.parentSessionId,input.taskId,input.callId,input.childSessionId,String(input.generation)].join("\x00"),retry=evidence2.find((entry)=>entry.role===input.role&&routeDispatchKey(entry)===dispatchKey2),usedSlots=new Set(evidence2.filter((entry)=>entry.role===input.role&&entry!==retry&&entry.slotId).map((entry)=>entry.slotId)),slotIndex=retry?slots.indexOf(retry.slotId??""):slots.findIndex((slot)=>!usedSlots.has(slot));if(slotIndex>=0&&slotIndex<identities.length){let slotId=slots[slotIndex],identity=identities[slotIndex];binding={role:input.role,identity,sessionId:input.parentSessionId,taskId:input.taskId,slotId,callId:input.callId,childSessionId:input.childSessionId,generation:input.generation},prospective=retry?evidence2.map((entry)=>entry===retry?binding:entry):[...evidence2,binding]}}return{route,binding,prospective,legacyUnrouted}}function applyStageBStateCompletion(taskId,agent,parentSessionId,testEngineerExempt,directory,callId,childSessionId,generation,preparedRoute){for(let session of candidateSessions(parentSessionId)){let resolvedRoute=preparedRoute??resolveBackgroundStageBRoute({directory,taskId,parentSessionId,role:agent,callId,childSessionId,generation:generation??-1,session}),{binding,prospective:routeEvidence,legacyUnrouted}=resolvedRoute,routeEnabled=(()=>{try{return loadPluginConfig(directory).review_routing?.enforce_receipts??!0}catch{return!0}})(),completionDecision=enforcePersistedReviewRouteReceipt({projectRoot:directory,sessionId:parentSessionId,taskId,receipts:routeEvidence,enforcementEnabled:routeEnabled,legacyUnrouted,requireEvidenceBindings:!0,requireCompleteEvidence:!1,expectedDispatch:binding?{role:binding.role,identity:binding.identity,callId:binding.callId,childSessionId:binding.childSessionId,generation:binding.generation}:void 0});if(!completionDecision.canAdvance){warn(`[background-stage-b] route receipt blocked ${taskId}: ${completionDecision.reason??"unknown reason"}`);continue}if(binding&&!recordStageBRouteEvidence(session,taskId,binding)){warn(`[background-stage-b] route receipt blocked before Stage-B evidence publication for ${taskId}: bounded route evidence capacity exceeded`);continue}recordStageBCompletion(session,taskId,agent);let state2=getTaskState(session,taskId);if(state2==="tests_run"||state2==="complete")continue;let routeComplete=enforcePersistedReviewRouteReceipt({projectRoot:directory,sessionId:parentSessionId,taskId,receipts:getStageBRouteEvidence(session,taskId),enforcementEnabled:routeEnabled,legacyUnrouted,requireEvidenceBindings:!0,requireCompleteEvidence:!0}).canAdvance;if(routeComplete&&(hasBothStageBCompletions(session,taskId)||testEngineerExempt&&agent==="reviewer")){try{if(state2==="coder_delegated"||state2==="pre_check_passed")advanceTaskState(session,taskId,"reviewer_run",{telemetrySessionId:parentSessionId});if(getTaskState(session,taskId)==="reviewer_run")advanceTaskState(session,taskId,"tests_run",{telemetrySessionId:parentSessionId})}catch(err){warn(`[background-stage-b] could not advance ${taskId} after ${agent}: ${err instanceof Error?err.message:String(err)}`)}continue}if(agent==="reviewer"&&(state2==="coder_delegated"||state2==="pre_check_passed"))try{advanceTaskState(session,taskId,"reviewer_run",{telemetrySessionId:parentSessionId})}catch(err){warn(`[background-stage-b] could not advance ${taskId} to reviewer_run: ${err instanceof Error?err.message:String(err)}`)}else if(routeComplete&&agent==="test_engineer"&&state2==="reviewer_run")try{advanceTaskState(session,taskId,"tests_run",{telemetrySessionId:parentSessionId})}catch(err){warn(`[background-stage-b] could not advance ${taskId} to tests_run: ${err instanceof Error?err.message:String(err)}`)}}}init_task_envelope();init_workspace_snapshot();var RETRYABLE_LEGACY_SETTLEMENT_TRANSFER_ERROR_CODES=new Set(["CODER_SETTLEMENT_LOCKED","EACCES","EBUSY","EIO","EPERM","ETIMEDOUT"]),observerInternals={transferCoderSettlementToBackground,markLegacyCoderSettlementTransferPending,sleep:(milliseconds)=>new Promise((resolve102)=>setTimeout(resolve102,milliseconds))};function createBackgroundCompletionObserver(opts){let{config:config3,directory}=opts,replayInProgress=!1,notifyLegacyCoderSettlementAdvisoryReplaced=(record3,replacement)=>{let session=swarmState.agentSessions.get(record3.parentSessionId);if(!session)return;if(removeQueuedLegacyTransferAdvisory(session.pendingAdvisoryMessages,replacement.advisory.eventId),replacement.replacedMessage)removeQueuedAdvisoryMessage(session.pendingAdvisoryMessages,[replacement.replacedMessage]);pushAdvisory(session,replacement.advisory.message)},event=async(input)=>{if(!config3.enabled)return;try{let pending,result,terminal,record3,text,isDuplicate=!1;if(input.trustedTerminal)pending=input.trustedTerminal.record,result=input.trustedTerminal.result,terminal=input.trustedTerminal.terminal,text=result.error??result.text??"",record3=pending,isDuplicate=!0;else{let evt=input?.event;if(!evt||evt.type!=="message.part.updated")return;let part=evt.properties?.part;if(!part||part.type!=="text"||part.synthetic!==!0||typeof part.text!=="string")return;let envelope=parseTaskEnvelope(part.text);if(!envelope||envelope.state!=="completed"&&envelope.state!=="error"&&envelope.state!=="cancelled")return;let parentSessionId=typeof part.sessionID==="string"?part.sessionID:"",lookup=await findDelegationForCompletion(directory,envelope.sessionId);if(lookup?.source==="uncertain"){warn(`[background] deferring terminal ingestion: delegation store unreadable for ${envelope.sessionId} (${lookup.uncertain})`);return}if(!lookup){log(`[background] trusted completion for ${envelope.sessionId} has no durable primary or fallback owner; ignored`);return}if(!parentSessionId||lookup.record.parentSessionId!==parentSessionId||lookup.record.subagentSessionId!==envelope.sessionId){warn(`[background] trusted completion identity mismatch for ${envelope.sessionId}; ignored`);return}if(pending=lookup.record,lookup.source==="fallback"){let promoted=await promoteDelegationFallback(directory,envelope.sessionId);if(!promoted){warn(`[background] fallback promotion failed for ${envelope.sessionId}; terminal work remains preserved`);return}pending=promoted.record}text=envelope.state==="error"||envelope.state==="cancelled"?envelope.errorText??"":envelope.resultText??"",result={...envelope.state==="error"?{error:text}:{text},chars:envelope.resultChars??text.length,truncated:envelope.resultTruncated??!1,digest:digest4(text)},terminal={eventId:buildBackgroundCompletionEventId({correlationId:pending.correlationId,jobId:pending.jobId,status:envelope.state,resultDigest:result.digest}),status:envelope.state,recordedAt:pending.terminalResult?.recordedAt??Date.now(),result};let terminalClaim=await claimTerminalResult(directory,pending.correlationId,terminal);if(!terminalClaim){warn(`[background] terminal claim failed for ${pending.correlationId}; ignored`);return}isDuplicate=terminalClaim.disposition==="duplicate",record3=terminalClaim.record}if(opts.onTerminalClaimed?.(record3),!input.trustedTerminal?.skipMaintenance)try{await maintainBackgroundDelegations(directory,{lockTimeoutMs:1000,reason:"trusted-terminal",onLegacyCoderSettlementReconciled:reconcilePending,onLegacyCoderSettlementAdvisoryReplaced:notifyLegacyCoderSettlementAdvisoryReplaced})}catch{}let legacyTransferPending=!1,legacyTransferRequiresManualRecovery=!1;if(terminal.status!=="completed"){if(isDuplicate&&record3.normalizedAgent!=="coder")return;if(record3.normalizedAgent==="coder"){let legacyTransfer=await transferLegacyCoderSettlement(directory,record3);if(legacyTransfer.disposition==="retry_pending")legacyTransferPending=!0;else if(legacyTransfer.disposition==="manual_recovery")legacyTransferRequiresManualRecovery=!0;if(record3.planTaskId){let expectedGeneration=record3.taskChangeContext?.workflowGeneration;if(expectedGeneration===void 0)warn(`[background] failed coder ${record3.correlationId} has no launch generation for task ${record3.planTaskId}`);else try{await transitionTaskWorkflowEvidence(directory,record3.planTaskId,{type:"dispatch_no_mutation",agentType:"coder",expectedGeneration,transitionId:`background-coder-terminal:${terminal.eventId}`})}catch(error93){warn(`[background] failed coder retry accounting was fenced for ${record3.planTaskId}: ${error93 instanceof Error?error93.message:String(error93)}`)}}try{await releaseCoderReservation(directory,record3,"recovered")}catch(error93){warn(`[background] failed coder reservation cleanup will be retried by admission reconciliation: ${error93 instanceof Error?error93.message:String(error93)}`)}if(record3.worktree){let descriptor=record3.worktree;if(!standardWorktreeByCallID.has(record3.callID))standardWorktreeByCallID.set(record3.callID,{callID:descriptor.callID,parentSessionID:descriptor.parentSessionId,taskId:descriptor.taskId,...descriptor.planTaskId?{planTaskId:descriptor.planTaskId}:{},handle:{worktreePath:descriptor.worktreePath,branchName:descriptor.branchName,purpose:"lane",id:descriptor.worktreeId,sessionId:descriptor.worktreeSessionId},mergeStrategy:descriptor.mergeStrategy,laneIndex:descriptor.laneIndex,...descriptor.worktreeDir?{worktree_dir:descriptor.worktreeDir}:{}});try{await abortStandardWorktreeDispatch(record3.callID,"cancelled",directory)}catch(error93){warn(`[background] failed coder worktree cleanup preserved the lane for manual recovery: ${error93 instanceof Error?error93.message:String(error93)}`)}}}if(discardScopeForRecord(record3),await publishAdvisory(directory,record3,terminal.eventId,legacyTransferPending?`${terminal.status==="cancelled"?"cancelled":"failed"}; legacy coder settlement transfer is pending; durable reconciliation will retry`:legacyTransferRequiresManualRecovery?`${terminal.status==="cancelled"?"cancelled":"failed"}; legacy coder settlement requires manual recovery; run /swarm recover for this task (or /swarm reset-session)`:terminal.status==="cancelled"?"cancelled":"failed"),!legacyTransferPending)await clearLegacyCoderSettlementTransferPending(directory,record3.correlationId);return}if(record3.normalizedAgent==="coder"){let settled=await settleCoder(directory,record3,terminal.eventId);if(record3=settled.record,!settled.ok){await publishAdvisory(directory,record3,terminal.eventId,settled.outcome);return}let legacyTransfer=await transferLegacyCoderSettlement(directory,record3);if(legacyTransfer.disposition==="retry_pending")legacyTransferPending=!0;else if(legacyTransfer.disposition==="manual_recovery")legacyTransferRequiresManualRecovery=!0}else if(!isDuplicate&&isBackgroundGateBearingRecord(record3)){if(validateStageBWorkspace(directory,record3).stale){await appendDelegationTransition(directory,record3.correlationId,{status:"stale"}),discardScopeForRecord(record3),await publishAdvisory(directory,record3,terminal.eventId,"stale");return}}if(record3.normalizedAgent==="coder"||isBackgroundGateBearingRecord(record3)){let ingestion=await claimDelegationIngestion(directory,record3.correlationId,{claimantId:terminal.eventId});if(ingestion?.disposition==="claimed"||ingestion?.disposition==="retry"){let applied2=await ingestBackgroundStageBCompletion({directory,record:ingestion.record,result:ingestion.record.result??result,reviewerReceiptOptions:opts.reviewerReceiptOptions}),claimToken=ingestion.record.ingestion?.claimToken;if(!claimToken){await publishAdvisory(directory,record3,terminal.eventId,"ingestion claim token missing");return}let ingestionCommit=await(opts.recordIngestionResult??recordDelegationIngestionResult)(directory,record3.correlationId,claimToken,applied2.ok);if(!ingestionCommit){warn(`[background] ingestion claim for ${record3.correlationId} expired or was fenced before commit; retry remains pending`);return}if(applied2.ok&&(ingestionCommit.status!=="consumed"||ingestionCommit.ingestion?.state!=="consumed"||ingestionCommit.ingestion.claimToken!==claimToken)){warn(`[background] ingestion commit for ${record3.correlationId} did not confirm the exact consumed claim; retry remains pending`);return}if(record3=ingestionCommit,record3=(await findDelegationForCompletion(directory,record3.correlationId))?.record??record3,!applied2.ok){await publishAdvisory(directory,record3,terminal.eventId,legacyTransferPending?"ingestion failed; legacy coder settlement transfer is pending; durable reconciliation will retry":legacyTransferRequiresManualRecovery?"ingestion failed; legacy coder settlement requires manual recovery; run /swarm recover for this task (or /swarm reset-session)":applied2.stale?"stale":"ingestion failed");try{await maintainBackgroundDelegations(directory,{lockTimeoutMs:1000,reason:"ingestion-rejection",skipLegacyCoderSettlementReconciliation:legacyTransferPending,onLegacyCoderSettlementAdvisoryReplaced:notifyLegacyCoderSettlementAdvisoryReplaced})}catch{}return}}else if(ingestion?.disposition==="busy")return;else if(ingestion?.disposition!=="consumed"){await publishAdvisory(directory,record3,terminal.eventId,"ingestion pending");return}}if(record3.normalizedAgent==="docs")try{if(!await completeBackgroundPhaseParticipation({directory,record:record3,resultText:text}))warn(`[background] docs completion ${record3.correlationId} did not satisfy its durable phase-participation binding`)}catch(error93){warn(`[background] docs completion ${record3.correlationId} could not persist phase participation: ${error93 instanceof Error?error93.message:String(error93)}`)}if(record3.normalizedAgent==="reviewer")discardScopeForRecord(record3);if(record3.normalizedAgent==="coder"){if(await releaseCoderReservation(directory,record3,"consumed"),!legacyTransferPending)await clearLegacyCoderSettlementTransferPending(directory,record3.correlationId)}await publishAdvisory(directory,record3,terminal.eventId,record3.normalizedAgent==="coder"?legacyTransferPending?"completed and settled; legacy coder settlement transfer is pending; durable reconciliation will retry":legacyTransferRequiresManualRecovery?"completed and settled; legacy coder settlement requires manual recovery; run /swarm recover for this task (or /swarm reset-session)":"completed and settled":"completed"),log(`[background] trusted completion settled: agent=${record3.normalizedAgent} task=${taskLabel(record3)} parent=${record3.parentSessionId}`)}catch(err){warn(`[background] completion observer error: ${err instanceof Error?err.message:String(err)}`)}},reconcilePending=async(record3)=>{if(replayInProgress)return!1;let terminal=record3.terminalResult;if(!terminal)return!1;replayInProgress=!0;try{await event({event:void 0,trustedTerminal:{record:record3,terminal,result:terminal.result,skipMaintenance:!0}});let refreshed=await findDelegationForCompletion(directory,record3.subagentSessionId);return refreshed?.record?refreshed.record.status==="consumed":!1}finally{replayInProgress=!1}};if(config3.enabled)registerLegacyCoderSettlementReconciler(directory,reconcilePending);return{event,reconcilePending,notifyLegacyCoderSettlementAdvisoryReplaced,prepareAdvisories:async(parentSessionId)=>{if(!config3.enabled||!parentSessionId)return null;let preparationId=`bg-prepare:${cryptoRandomId()}`,entries2=await preparePendingBackgroundAdvisories(directory,parentSessionId,{preparationId});return entries2.length===0?null:{preparationId,eventIds:entries2.map((entry)=>entry.eventId),messages:entries2.map((entry)=>entry.message)}},ackObservedAdvisories:(parentSessionId,observedTexts)=>acknowledgeObservedBackgroundAdvisories(directory,parentSessionId,observedTexts),releaseAdvisories:(parentSessionId,prepared)=>releasePreparedBackgroundAdvisories(directory,parentSessionId,prepared.preparationId,prepared.eventIds)}}async function transferLegacyCoderSettlement(directory,record3){if(!record3.planTaskId)return{disposition:"ok",outcome:"no task-scoped legacy settlement"};let transfer={taskId:record3.planTaskId,transitionId:`coder:${record3.callID}`},detail="unknown transfer failure",lastErrorCode=null;for(let attempt=0;attempt<3;attempt+=1)try{return{disposition:"ok",outcome:await observerInternals.transferCoderSettlementToBackground({directory,taskId:transfer.taskId,transitionId:transfer.transitionId})}}catch(error93){if(lastErrorCode=errorCode(error93),detail=error93 instanceof Error?error93.message:String(error93),attempt===2||!isRetryableLegacyTransferErrorCode(lastErrorCode))break;await observerInternals.sleep(50*(attempt+1))}if(warn(`[background] legacy coder settlement transfer failed for ${record3.planTaskId}: ${detail}`),!isRetryableLegacyTransferErrorCode(lastErrorCode))return{disposition:"manual_recovery",outcome:"legacy coder settlement requires manual recovery; run /swarm recover for this task (or /swarm reset-session)"};let pending=null;for(let markerAttempt=0;markerAttempt<3;markerAttempt+=1){try{pending=await observerInternals.markLegacyCoderSettlementTransferPending(directory,record3.correlationId,transfer)}catch{pending=null}if(hasExactPendingLegacyTransfer(pending,transfer))break;if(markerAttempt<2)await observerInternals.sleep(50*(markerAttempt+1))}if(hasExactPendingLegacyTransfer(pending,transfer))return{disposition:"retry_pending",outcome:"legacy coder settlement transfer is pending; retrying durable reconciliation"};return{disposition:"manual_recovery",outcome:"legacy coder settlement requires manual recovery; run /swarm recover for this task (or /swarm reset-session)"}}async function releaseCoderReservation(directory,record3,reason){if(!record3.coderReservationId)return;let bound=await bindBackgroundCoderReservation(directory,{reservationId:record3.coderReservationId,parentSessionId:record3.parentSessionId,planTaskId:record3.planTaskId,callID:record3.callID,correlationId:record3.correlationId});if(!bound){warn(`[background] coder reservation ${record3.coderReservationId} could not be bound for ${record3.correlationId}; admission remains fail-closed`);return}if(!await releaseBackgroundCoderReservation(directory,{...bound,generation:record3.generation??1,reason}))warn(`[background] coder reservation ${record3.coderReservationId} could not be released after ${reason}; the next admission will retry reconciliation`)}async function settleCoder(directory,record3,operationId){let context=record3.taskChangeContext;if(!context)return{ok:!1,record:record3,outcome:"stale: no coder baseline"};let claim=await claimCoderSettlement(directory,record3.correlationId,operationId);if(!claim)return{ok:!1,record:record3,outcome:"settlement claim failed"};if(claim.disposition==="settled")return{ok:!0,record:claim.record,outcome:"completed and settled"};if(claim.disposition==="preserved")return{ok:!1,record:claim.record,outcome:"settlement preserved"};if(record3=claim.record,!record3.worktree){let baseline=context.baseline,current=captureWorkspaceSnapshot(directory,{scope:baseline.scope,prHeadSha:baseline.prHeadSha,resolveCurrentPrHeadSha:baseline.prHeadSha!==null}),repositoryDelta=changedFilesSinceSnapshot(directory,baseline),declaredFiles=context.declaredFiles,observedFiles2=repositoryDelta&&declaredFiles&&declaredFiles.length>0?repositoryDelta.filter((file3)=>isInDeclaredScope(file3,declaredFiles,directory)):null,staleReason=!sameProjectRoot(baseline.directory,directory)?"shared-root directory identity changed":!baseline.gitHead||current.gitHead!==baseline.gitHead?"shared-root HEAD changed before coder completion":baseline.prHeadSha!==null&¤t.prHeadSha!==baseline.prHeadSha?"shared-root PR head changed before coder completion":observedFiles2===null?"shared-root coder files could not be attributed to a non-empty declared scope":null;if(staleReason||observedFiles2===null){let preserved2=await updateCoderSettlement(directory,record3.correlationId,{operationId,state:"preserved",observedFiles:null,outcome:{kind:"shared-root",result:"failed",reason:staleReason??"coder attribution failed"}});return await appendDelegationTransition(directory,record3.correlationId,{status:"stale"}),{ok:!1,record:preserved2??record3,outcome:`stale: ${staleReason??"coder attribution failed"}`}}let settled=await updateCoderSettlement(directory,record3.correlationId,{operationId,state:"settled",observedFiles:observedFiles2,outcome:{kind:"shared-root",result:"ready"}});return settled?{ok:!0,record:settled,outcome:"completed and settled"}:{ok:!1,record:record3,outcome:"settlement persistence failed"}}let descriptor=record3.worktree;if(descriptor.callID!==record3.callID||descriptor.parentSessionId!==record3.parentSessionId||descriptor.planTaskId!==record3.planTaskId||!sameProjectRoot(context.baseline.directory,descriptor.worktreePath))return{ok:!1,record:await updateCoderSettlement(directory,record3.correlationId,{operationId,state:"preserved",observedFiles:null,outcome:{kind:"standard-worktree",result:"failed",reason:"worktree recovery identity does not match the dispatch"}})??record3,outcome:"worktree settlement preserved: identity mismatch"};let observedFiles=changedFilesSinceSnapshot(descriptor.worktreePath,context.baseline);if(observedFiles===null)return{ok:!1,record:await updateCoderSettlement(directory,record3.correlationId,{operationId,state:"preserved",observedFiles:null,outcome:{kind:"standard-worktree",result:"failed",reason:"worktree files could not be attributed to the clean baseline"}})??record3,outcome:"worktree settlement preserved: attribution failed"};let dispatch=standardWorktreeByCallID.get(record3.callID)??{callID:descriptor.callID,parentSessionID:descriptor.parentSessionId,taskId:descriptor.taskId,...descriptor.planTaskId?{planTaskId:descriptor.planTaskId}:{},handle:{worktreePath:descriptor.worktreePath,branchName:descriptor.branchName,purpose:"lane",id:descriptor.worktreeId,sessionId:descriptor.worktreeSessionId},mergeStrategy:descriptor.mergeStrategy,laneIndex:descriptor.laneIndex,...descriptor.worktreeDir?{worktree_dir:descriptor.worktreeDir}:{}};standardWorktreeByCallID.delete(record3.callID),awaitingMergeByCallID.set(record3.callID,{callID:record3.callID,parentSessionID:descriptor.parentSessionId,taskId:descriptor.taskId,...descriptor.planTaskId?{planTaskId:descriptor.planTaskId}:{},branch:descriptor.branchName,worktreePath:descriptor.worktreePath,mergeStrategy:descriptor.mergeStrategy,queuedAt:Date.now()});let resume=settlementResume(record3),mergeResult=await finishStandardWorktreeDispatch(directory,dispatch,void 0,record3.callID,{operationId,...resume?{resume}:{},onBeforeMerge:async(provenance)=>{let persisted=await updateCoderSettlement(directory,record3.correlationId,{operationId,state:"settling",sourceHeadAfterCommit:provenance.sourceHead,targetHeadBeforeMerge:provenance.targetHeadBefore,observedFiles});if(!persisted)throw Error("could not persist pre-merge provenance");record3=persisted},onMerged:async(merged)=>{let provenance=merged.provenance??resume,persisted=await updateCoderSettlement(directory,record3.correlationId,{operationId,state:"settled",observedFiles,...provenance?{sourceHeadAfterCommit:provenance.sourceHead,targetHeadBeforeMerge:provenance.targetHeadBefore}:{},outcome:{kind:"standard-worktree",result:provenance&&provenance.sourceHead!==provenance.targetHeadBefore?"merged":"unchanged",sourceHeadAfterCommit:provenance?.sourceHead??null,targetHeadBeforeMerge:provenance?.targetHeadBefore??null,targetHeadAfterMerge:resolveCurrentGitHead(directory)}});if(!persisted)throw Error("could not persist merged settlement");record3=persisted}});if(mergeResult.outcome==="merged")return{ok:!0,record:(await findDelegationForCompletion(directory,record3.correlationId))?.record??record3,outcome:"completed and merged"};if(mergeResult.outcome==="failed"&&mergeResult.stage==="settlement-persist")return{ok:!1,record:record3,outcome:"worktree settlement persistence pending retry"};return{ok:!1,record:await updateCoderSettlement(directory,record3.correlationId,{operationId,state:"preserved",observedFiles,...mergeResult.provenance?{sourceHeadAfterCommit:mergeResult.provenance.sourceHead,targetHeadBeforeMerge:mergeResult.provenance.targetHeadBefore}:{},outcome:{kind:"standard-worktree",result:mergeResult.outcome,reason:mergeResult.message,sourceHeadAfterCommit:mergeResult.provenance?.sourceHead??null,targetHeadBeforeMerge:mergeResult.provenance?.targetHeadBefore??null}})??record3,outcome:`worktree settlement preserved: ${mergeResult.message}`}}function settlementResume(record3){let{coderSettlement:settlement,worktree}=record3;if(settlement?.state!=="settling"||!settlement.operationId||!settlement.sourceHeadAfterCommit||!settlement.targetHeadBeforeMerge||!GIT_OBJECT_ID_PATTERN.test(settlement.sourceHeadAfterCommit)||!GIT_OBJECT_ID_PATTERN.test(settlement.targetHeadBeforeMerge)||!worktree)return;return{operationId:settlement.operationId,sourceHead:settlement.sourceHeadAfterCommit,targetHeadBefore:settlement.targetHeadBeforeMerge,branchName:worktree.branchName,strategy:worktree.mergeStrategy}}async function publishAdvisory(directory,record3,eventId,outcome){let message=`[BACKGROUND COMPLETION ${eventId}] ${record3.normalizedAgent} task ${taskLabel(record3)} ${outcome}.`,input={eventId,parentSessionId:record3.parentSessionId,message},needsCorrection=!message.includes(LEGACY_CODER_SETTLEMENT_PENDING_ADVISORY_MARKER),replacement=(needsCorrection?await replacePendingBackgroundAdvisory(directory,record3.correlationId,input):null)??null,stored=replacement?.advisory??await putPendingBackgroundAdvisory(directory,record3.correlationId,input);if(!stored)return;let session=swarmState.agentSessions.get(record3.parentSessionId);if(session){if(needsCorrection){if(removeQueuedLegacyTransferAdvisory(session.pendingAdvisoryMessages,eventId),replacement?.replacedMessage)removeQueuedAdvisoryMessage(session.pendingAdvisoryMessages,[replacement.replacedMessage])}pushAdvisory(session,stored.message)}}function errorCode(error93){if(error93&&typeof error93==="object"&&"code"in error93&&typeof error93.code==="string")return error93.code??null;let detail=error93 instanceof Error?error93.message:String(error93);return/^([A-Z][A-Z0-9_]*)(?::|$)/.exec(detail.trim())?.[1]??null}function hasExactPendingLegacyTransfer(record3,transfer){return record3?.legacyCoderSettlementTransfer?.taskId===transfer.taskId&&record3.legacyCoderSettlementTransfer.transitionId===transfer.transitionId}function isRetryableLegacyTransferErrorCode(code){return code!==null&&RETRYABLE_LEGACY_SETTLEMENT_TRANSFER_ERROR_CODES.has(code)}function removeQueuedAdvisoryMessage(queue,messagesToRemove){if(!queue||queue.length===0||messagesToRemove.length===0)return;let remove=new Set(messagesToRemove);for(let index=queue.length-1;index>=0;index-=1)if(remove.has(queue[index]))queue.splice(index,1)}function removeQueuedLegacyTransferAdvisory(queue,eventId){if(!queue||queue.length===0)return;let prefix=`[BACKGROUND COMPLETION ${eventId}]`;for(let index=queue.length-1;index>=0;index-=1){let message=queue[index];if(message?.startsWith(prefix)&&message.includes(LEGACY_CODER_SETTLEMENT_PENDING_ADVISORY_MARKER))queue.splice(index,1)}}function taskLabel(record3){return record3.evidenceTaskId??record3.planTaskId??"unknown"}function discardScopeForRecord(record3){let taskId=record3.evidenceTaskId??record3.planTaskId;if(!taskId)return;if(record3.normalizedAgent==="reviewer")discardReviewerScopeGenerationClaim({parentSessionID:record3.parentSessionId,taskId,reviewerCallID:record3.callID});else if(record3.normalizedAgent==="coder")discardReviewerScopeGenerationForCoderCall({parentSessionID:record3.parentSessionId,taskId,coderCallID:record3.callID})}function digest4(text){return createHash89("sha256").update(text).digest("hex")}function cryptoRandomId(){return createHash89("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_package();init_constants();import*as fs146 from"node:fs";import*as path259 from"node:path";var CONFIG_SCHEMA_REF=`https://unpkg.com/opencode-swarm@${package_default.version}/opencode-swarm.schema.json`;function writeSwarmConfigExampleIfNew(projectDirectory){try{let swarmDir=path259.join(projectDirectory,".swarm"),dest=path259.join(swarmDir,"config.example.json");if(fs146.existsSync(dest))return;if(!fs146.existsSync(swarmDir))fs146.mkdirSync(swarmDir,{recursive:!0});let example={$schema:CONFIG_SCHEMA_REF,agents:Object.fromEntries(Object.entries(DEFAULT_MODELS).filter(([name])=>name!=="default").map(([name,model])=>[name,{model,fallback_models:["opencode/gpt-5-nano","opencode/big-pickle"]}])),max_iterations:5};fs146.writeFileSync(dest,`${JSON.stringify(example,null,2)}
|
|
6905
6905
|
`,"utf-8")}catch{}}init_schema();init_schema();init_core_events();init_delegation_gate();init_utils2();init_injection_budget();init_utils();var FOR_TAG_PATTERN=/^\[FOR:\s*([^\]]+)\]/i;function containsPlanContent(text){if(!text)return!1;let lowerText=text.toLowerCase();return lowerText.includes(".swarm/plan")||lowerText.includes(".swarm/context")||lowerText.includes("swarm/plan.md")||lowerText.includes("swarm/context.md")}function containsKnowledgeContent(text){if(!text)return!1;let lowerText=text.toLowerCase();return lowerText.includes("knowledge")||lowerText.includes("lesson")||lowerText.includes(".swarm/knowledge")||lowerText.includes("swarm knowledge")}function parseForTag(content){let match=content.trim().match(FOR_TAG_PATTERN);if(!match)return null;let tagContent=match[1].trim();if(tagContent.toLowerCase()==="all")return["all"];return tagContent.split(",").map((agent)=>agent.trim().toLowerCase()).filter(Boolean)}function isTargetRoleAllowed(targetRole,allowedAgents){if(allowedAgents.includes("all"))return!0;let normalizedTarget=stripKnownSwarmPrefix(targetRole).toLowerCase();return allowedAgents.some((agent)=>{let normalizedAgent=stripKnownSwarmPrefix(agent).toLowerCase();return normalizedTarget===normalizedAgent})}function shouldNeverFilter(entry){if(entry.role==="system")return!0;if(entry.role==="user"){if(parseDelegationEnvelope(entry.content))return!0}if(entry.role==="assistant"){if(containsPlanContent(entry.content)||containsKnowledgeContent(entry.content))return!0}return!1}function logFilteringMetrics(directory,targetRole,totalEntries,includedEntries){try{appendCoreEventSync(directory,{event:"context_filtered",timestamp:new Date().toISOString(),agentName:targetRole,totalEntries,includedEntries,filteredEntries:totalEntries-includedEntries,estimatedTokensSaved:(totalEntries-includedEntries)*100})}catch(error93){log("[RoleFilter] event append failed",{error:error93 instanceof Error?error93.message:String(error93)})}}function filterByRole(entries2,targetRole,directory,options={}){if(!entries2||entries2.length===0)return[];let filtered=[];for(let entry of entries2){let allowedAgents=parseForTag(entry.content),canFilterTaggedSystem=entry.role==="system"&&options.filterTaggedSystem===!0&&allowedAgents!==null&&allowedAgents.length>0;if(shouldNeverFilter(entry)&&!canFilterTaggedSystem){filtered.push(entry);continue}if(allowedAgents===null){filtered.push(entry);continue}if(isTargetRoleAllowed(targetRole,allowedAgents))filtered.push(entry)}if(directory)logFilteringMetrics(directory,targetRole,entries2.length,filtered.length);return filtered}function createRoleFilterSystemHook(getActiveAgentName){return{"experimental.chat.system.transform":async(input,output)=>{if(!input.sessionID||!Array.isArray(output.system))return;let targetRole=getActiveAgentName(input.sessionID);if(!targetRole)return;let entries2=output.system.map((content)=>({role:"system",content})),kept=filterByRole(entries2,targetRole,void 0,{filterTaggedSystem:!0}).map(({content})=>content),keptRemaining=new Map;for(let content of kept)keptRemaining.set(content,(keptRemaining.get(content)??0)+1);let removedTokens=0;for(let{content}of entries2){let remaining=keptRemaining.get(content)??0;if(remaining>0)keptRemaining.set(content,remaining-1);else removedTokens+=estimateTokens(content)}if(removedTokens>0)deductProducerEmission(input.sessionID,"system-enhancer",removedTokens);output.system.length=0;for(let content of kept)output.system.push(content)}}}import*as fs149 from"node:fs";import*as path262 from"node:path";import*as fs148 from"node:fs";import*as path261 from"node:path";import*as crypto13 from"node:crypto";import*as fs147 from"node:fs";import*as path260 from"node:path";var _internals209={readFileSync:fs147.readFileSync,writeFileSync:fs147.writeFileSync,mkdirSync:fs147.mkdirSync,renameSync:fs147.renameSync,existsSync:fs147.existsSync,statSync:fs147.statSync,createHash:crypto13.createHash.bind(crypto13)};function computeContentHash3(content){return _internals209.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=path260.join(directory,".swarm","context-map.json");try{if(!_internals209.existsSync(filePath))return null;let raw=_internals209.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=path260.join(directory,".swarm"),tmpPath=path260.join(swarmDir,"context-map.tmp"),finalPath=path260.join(swarmDir,"context-map.json");_internals209.mkdirSync(swarmDir,{recursive:!0});let updated={...map3,generated_at:new Date().toISOString()},json3=JSON.stringify(updated,null,2);_internals209.writeFileSync(tmpPath,json3,"utf-8"),_internals209.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=path261.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=fs148.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(`
|
|
6906
6906
|
`).map((line)=>line.replace(/^\s*\*\s?/,"").trim()).join(" ").replace(/\s+/g," ").trim();if(body.length>MAX_PURPOSE_LENGTH)body=`${body.substring(0,MAX_PURPOSE_LENGTH)}...`;return body||"No summary available"}var decisionCounter=0;function nextDecisionId(){return decisionCounter+=1,`A${decisionCounter}`}function deriveFinalStatus(params){if(params.rejection_reasons&¶ms.rejection_reasons.length>0)return"rejected";switch(params.final_status){case"completed":return"approved";case"failed":return"rejected";case"blocked":return"blocked";case"cancelled":return"rejected"}}function readFileContent(absolutePath2){try{if(!_internals210.existsSync(absolutePath2))return null;return _internals210.readFileSync(absolutePath2,"utf-8")}catch{return null}}function refreshFileEntry(relativePath2,absolutePath2,existingEntry){let content=readFileContent(absolutePath2);if(content===null)return null;return _internals210.extractFileSummary(relativePath2,content,absolutePath2,existingEntry)}var _internals210={loadContextMap,saveContextMap,createEmptyContextMap,extractFileSummary,existsSync:fs149.existsSync,readFileSync:fs149.readFileSync,readdirSync:fs149.readdirSync,realpathSync:fs149.realpathSync,appendTaskHistory,appendDecision};function extractEvidenceFindings(taskId,directory){let result={rejection_reasons:[],review_findings:[]};try{let evidenceDir=path262.join(directory,".swarm","evidence",taskId);if(!_internals210.existsSync(evidenceDir))return result;let evidenceFiles=_internals210.readdirSync(evidenceDir),targetFiles=["evidence.json","reviewer.json","test-engineer.json","test_engineer.json"];for(let fileName of evidenceFiles){if(!targetFiles.includes(fileName))continue;let filePath=path262.join(evidenceDir,fileName),content=readFileContent(filePath);if(content===null)continue;try{let parsed=JSON.parse(content);if(typeof parsed!=="object"||parsed===null||Array.isArray(parsed))continue;let obj=parsed;if(Array.isArray(obj.entries))for(let entry of obj.entries){if(typeof entry!=="object"||entry===null||Array.isArray(entry))continue;let entryObj=entry,entryType=String(entryObj.type??"").toLowerCase(),isActionable=entryType==="review"||entryType==="test"||entryType==="reviewer"||entryType==="test_engineer"||entryType==="test-engineer";if(isActionable&&typeof entryObj.verdict==="string"){let normalizedVerdict=String(entryObj.verdict).toLowerCase();if(normalizedVerdict==="rejected"||normalizedVerdict==="fail"||normalizedVerdict==="concerns")result.rejection_reasons.push(`[${fileName.replace(".json","")}] ${entryObj.verdict}`)}if(isActionable){let entryIssues=entryObj.issues||entryObj.findings||[];if(Array.isArray(entryIssues))for(let issue3 of entryIssues){let issueText=typeof issue3==="object"&&issue3!==null?String(issue3.message||issue3.detail||issue3.description||""):String(issue3);if(issueText)result.review_findings.push(issueText)}let entryFailures=entryObj.failures;if(Array.isArray(entryFailures))for(let failure of entryFailures){let failureText=typeof failure==="object"&&failure!==null?String(failure.message||failure.detail||String(failure)):String(failure);if(failureText)result.review_findings.push(failureText)}}}else{if(typeof obj.verdict==="string"){let normalizedVerdict=String(obj.verdict).toLowerCase();if(normalizedVerdict==="rejected"||normalizedVerdict==="fail"||normalizedVerdict==="concerns")result.rejection_reasons.push(`[${fileName.replace(".json","")}] ${obj.verdict}`)}if(Array.isArray(obj.issues))for(let issue3 of obj.issues){let issueText=typeof issue3==="object"&&issue3!==null?String(issue3.message||issue3.detail||issue3.description||""):String(issue3);if(issueText)result.review_findings.push(issueText)}if(Array.isArray(obj.findings)){for(let finding of obj.findings)if(typeof finding==="object"&&finding!==null){let findingText=String(finding.message||finding.detail||finding.description||"");if(findingText)result.review_findings.push(findingText)}}}}catch{}}}catch{}return result}function updateContextMapAfterAgent(params){try{let map3=_internals210.loadContextMap(params.directory);if(map3===null)map3=_internals210.createEmptyContextMap();let root=path262.resolve(params.directory),updatedFiles={...map3.files},validFiles=[],realRoot=_internals210.realpathSync(root);for(let filePath of params.files_touched)try{let resolved=path262.resolve(root,filePath),realResolved=_internals210.realpathSync(resolved),relative61=path262.relative(realRoot,realResolved);if(relative61.startsWith("..")||path262.isAbsolute(relative61))continue;let normalizedRelative=relative61.replace(/\\/g,"/"),existingEntry=map3.files[normalizedRelative],refreshed=refreshFileEntry(normalizedRelative,resolved,existingEntry);if(refreshed!==null)updatedFiles[normalizedRelative]=refreshed;validFiles.push(normalizedRelative)}catch{}map3={...map3,files:updatedFiles};let evidenceFindings=extractEvidenceFindings(params.task_id,params.directory),rejectionReasons=params.rejection_reasons??[],reviewFindings=params.review_findings??[],mergedRejectionReasons=[...rejectionReasons,...evidenceFindings.rejection_reasons.filter((r)=>!rejectionReasons.includes(r))],mergedReviewFindings=[...reviewFindings,...evidenceFindings.review_findings.filter((f)=>!reviewFindings.includes(f))],reviewerFindings=[...mergedRejectionReasons.map((r)=>`[rejection] ${r}`),...mergedReviewFindings],taskSummary={task_id:params.task_id,goal:params.task_goal,files_touched:validFiles,implementation_summary:params.implementation_summary,reviewer_findings:reviewerFindings.length>0?reviewerFindings:void 0,final_status:mergedRejectionReasons.length>0?"rejected":deriveFinalStatus(params)};if(map3=_internals210.appendTaskHistory(map3,taskSummary),params.decisions)for(let entry of params.decisions){let decision={id:nextDecisionId(),decision:entry.decision,rationale:entry.rationale,timestamp:new Date().toISOString(),task_id:params.task_id};map3=_internals210.appendDecision(map3,decision)}return _internals210.saveContextMap(map3,params.directory),map3}catch{try{return _internals210.loadContextMap(params.directory)??_internals210.createEmptyContextMap()}catch{return _internals210.createEmptyContextMap()}}}init_group_commit_writer();init_observability_event_store();init_project_db();init_spawn_circuit();init_coordination_store();init_logger();var TOKEN_BUCKET_NAMESPACE="dispatch.token-bucket",TOKEN_BUCKET_ENTITY_KEY="project",buckets=new Map;function refill(bucket,ratePerSecond,capacity,now2){if(now2<bucket.lastRefillMs)bucket.lastRefillMs=now2;let elapsedSeconds=(now2-bucket.lastRefillMs)/1000;if(elapsedSeconds>0&&ratePerSecond>0)bucket.level=Math.min(capacity,bucket.level+elapsedSeconds*ratePerSecond),bucket.lastRefillMs=now2}function persist(directory,bucket){try{let payload={level:bucket.level,lastRefillMs:bucket.lastRefillMs};transitionCoordinationState(directory,{namespace:TOKEN_BUCKET_NAMESPACE,entityKey:TOKEN_BUCKET_ENTITY_KEY,generation:1,status:"active",payload:JSON.stringify(payload)})}catch(err){_internals211.onPersistError(err)}}function hydrate(directory,capacity){let existing=buckets.get(directory);if(existing)return existing;let bucket={level:capacity,lastRefillMs:_internals211.now(),hydrated:!0};try{let row=_internals211.readState(directory);if(row){let parsed=JSON.parse(row.payload);if(typeof parsed.level==="number"&&Number.isFinite(parsed.level)){let nowMs3=_internals211.now();bucket={level:Math.min(capacity,Math.max(0,parsed.level)),lastRefillMs:typeof parsed.lastRefillMs==="number"&&Number.isFinite(parsed.lastRefillMs)?Math.min(parsed.lastRefillMs,nowMs3):nowMs3,hydrated:!0}}}}catch(err){_internals211.onPersistError(err)}return buckets.set(directory,bucket),bucket}async function acquireDispatchToken(input){let rate=input.ratePerSecond;if(!(rate>0))return;let capacity=Math.max(1,input.burstCapacity),bucket=hydrate(input.directory,capacity),waited=!1;for(;;){let now2=_internals211.now();if(refill(bucket,rate,capacity,now2),bucket.level>=1){if(bucket.level-=1,waited)persist(input.directory,bucket);return}waited=!0;let waitMs=Math.max(1,(1-bucket.level)/rate*1000);await _internals211.sleep(Math.min(waitMs,1000))}}var _internals211={now:()=>Date.now(),sleep:(ms)=>new Promise((resolve103)=>setTimeout(resolve103,ms)),readState:(directory)=>getCoordinationState(directory,TOKEN_BUCKET_NAMESPACE,TOKEN_BUCKET_ENTITY_KEY),onPersistError:(err)=>{if(process.env.DEBUG_SWARM)log("[dispatch.token-bucket] persist failed",err)}};init_model_dispatch_fallback();init_provider_error_classification();init_ephemeral_agent_dispatcher();function parseRequestedModel(modelId){if(modelId==="configured")return;let parsed=parseModelString2(modelId);if(!parsed)throw Error("explicit evaluation models must use provider/model syntax");return parsed}function resolveEvaluationAgentName(agents,logicalName,preferredSwarm){let names=agents.map((agent)=>agent.name);if(preferredSwarm){let preferred=`${preferredSwarm}_${logicalName}`;if(names.includes(preferred))return preferred;throw Error(`preferred swarm ${preferredSwarm} does not provide evaluation agent ${logicalName}`)}if(names.includes(logicalName))return logicalName;let prefixed=names.filter((name)=>name.endsWith(`_${logicalName}`)).sort((left,right)=>left.localeCompare(right));if(prefixed.length===1)return prefixed[0];if(prefixed.length>1)throw Error(`multiple swarms provide ${logicalName}; preferredSwarm is required`);throw Error(`evaluation agent ${logicalName} is not registered`)}var _internals212=Object.defineProperties({},{boundedAbort:{enumerable:!0,get:()=>_internals187.boundedAbort,set:(value)=>{_internals187.boundedAbort=value}},boundedDelete:{enumerable:!0,get:()=>_internals187.boundedDelete,set:(value)=>{_internals187.boundedDelete=value}},log:{enumerable:!0,get:()=>_internals187.log,set:(value)=>{_internals187.log=value}}});async function awaitWithAbort2(promise3,signal2){if(signal2.aborted)throw Error("evaluation dispatch aborted");return new Promise((resolve103,reject)=>{let onAbort=()=>reject(Error("evaluation dispatch aborted"));signal2.addEventListener("abort",onAbort,{once:!0}),promise3.then(resolve103,reject).finally(()=>{signal2.removeEventListener("abort",onAbort)})})}function createEvaluationModelDispatcher(client,pricing){return async(request)=>{let startedAt=Date.now();if(request.abortSignal?.aborted)return{status:"cancelled",modelId:request.modelId,text:"",durationMs:0};let resolvedAgentName,controller=new AbortController,timedOut=!1,abortListener=()=>controller.abort();request.abortSignal?.addEventListener("abort",abortListener,{once:!0});let timeoutHandle=setTimeout(()=>{timedOut=!0,controller.abort()},request.timeoutMs);try{let requestedModel=parseRequestedModel(request.modelId),agentsResult=await awaitWithAbort2(client.app.agents({query:{directory:request.sessionDirectory},signal:controller.signal}),controller.signal);if(!agentsResult.data)throw Error(`Failed to list registered evaluation agents: ${JSON.stringify(agentsResult.error)}`);resolvedAgentName=resolveEvaluationAgentName(agentsResult.data,request.agentName,request.preferredSwarm);let result=(await dispatchWithModelFallback({dispatch:async(_model,context)=>{let result2=await dispatchEphemeralAgent({client,directory:request.sessionDirectory,parentSessionId:request.parentSessionId,agentName:resolvedAgentName,model:requestedModel,...request.system===void 0?{}:{system:request.system},prompt:request.prompt,readOnlyTools:DEFAULT_READ_ONLY_TOOLS,title:`evaluation gate (${resolvedAgentName})`,timeoutMs:context.remainingMs??request.timeoutMs,abortSignal:controller.signal,pricing});if(result2.status==="completed")return result2;if(result2.status==="timeout")timedOut=!0;throw Error(result2.error??`evaluation dispatch ${result2.status}`)},classify:(error93)=>{let message=error93 instanceof Error?error93.message:String(error93);return isTransientProviderError(message)?"transient":"permanent"},maxTransientRetriesPerModel:2,backoffMs:()=>0,maxAttempts:3,deadlineAtMs:startedAt+request.timeoutMs})).result;return{status:"completed",modelId:result.modelId??request.modelId,agentName:resolvedAgentName,text:result.text,durationMs:Date.now()-startedAt,promptBytes:result.promptBytes,responseBytes:result.responseBytes,costFields:result.costFields}}catch(error93){let cancelled=request.abortSignal?.aborted===!0,msg=error93 instanceof Error?error93.message:String(error93),quotaMessage=isQuotaError(msg)?`${msg} (model quota/usage limit; retried the same model 2 time(s) — not substituted, to preserve benchmark attribution)`:msg;return{status:cancelled?"cancelled":timedOut?"timeout":"error",modelId:request.modelId,agentName:resolvedAgentName,text:"",durationMs:Date.now()-startedAt,error:quotaMessage}}finally{clearTimeout(timeoutHandle),request.abortSignal?.removeEventListener("abort",abortListener),controller.abort()}}}init_action_circuit();init_action_identity();init_invocation_failure();init_constants();init_schema();init_logger();init_oversight();init_state3();function configCadence(config3){let oversight=config3.full_auto?.oversight;return{everyToolCalls:oversight?.every_tool_calls??25,everyArchitectTurns:oversight?.every_architect_turns??5,everyMinutes:oversight?.every_minutes??20}}function denialLimits(config3){return{maxConsecutive:config3.full_auto?.denials?.max_consecutive??3,maxTotal:config3.full_auto?.denials?.max_total??20}}function evaluateFullAutoCadence(state2,config3,now2=Date.now()){let triggers=[],cadence=configCadence(config3),denials=denialLimits(config3);if(cadence.everyToolCalls>0&&state2.counters.toolCalls>0&&state2.counters.toolCalls%cadence.everyToolCalls===0)triggers.push({kind:"tool_calls",threshold:cadence.everyToolCalls});if(cadence.everyArchitectTurns>0&&state2.counters.architectTurns>0&&state2.counters.architectTurns%cadence.everyArchitectTurns===0)triggers.push({kind:"architect_turns",threshold:cadence.everyArchitectTurns});if(cadence.everyMinutes>0&&state2.lastOversightAt){let lastTs=Date.parse(state2.lastOversightAt);if(Number.isFinite(lastTs)){let elapsedMinutes=(now2-lastTs)/60000;if(elapsedMinutes>=cadence.everyMinutes)triggers.push({kind:"minutes",threshold:cadence.everyMinutes,elapsedMinutes})}}if(state2.counters.consecutiveNoProgressTurns>=3)triggers.push({kind:"consecutive_no_progress",threshold:3});if(denials.maxConsecutive>1&&state2.denialCounters.consecutive>=denials.maxConsecutive-1&&state2.denialCounters.consecutive<denials.maxConsecutive)triggers.push({kind:"denials_near_limit",consecutive:state2.denialCounters.consecutive,max:denials.maxConsecutive});return{shouldEscalate:triggers.length>0,triggers}}function tickAndEvaluate(directory,sessionID,counter,config3){let before=loadFullAutoRunState(directory,sessionID);if(!before||before.status!=="running")return;let updated=incrementFullAutoCounter(directory,sessionID,counter);if(!updated)return;return evaluateFullAutoCadence(updated,config3)}var cadenceDispatchInFlight=new Set;function resolveOversightAgentName(activeAgent){if(!activeAgent)return"critic_oversight";if(stripKnownSwarmPrefix(activeAgent)!==ORCHESTRATOR_NAME)return"critic_oversight";let lastIdx=activeAgent.toLowerCase().lastIndexOf("architect");if(lastIdx>0)return`${activeAgent.slice(0,lastIdx)}critic_oversight`;return"critic_oversight"}function tickAndMaybeDispatchCadence(directory,sessionID,counter,config3,options={}){let decision=tickAndEvaluate(directory,sessionID,counter,config3);if(!decision||!decision.shouldEscalate)return decision;if(cadenceDispatchInFlight.has(sessionID))return decision;let runState=loadFullAutoRunState(directory,sessionID);if(!runState||runState.status!=="running")return decision;let oversightAgentName=resolveOversightAgentName(options.activeAgent),criticModel=config3.full_auto?.critic_model??config3.agents?.critic?.model??"opencode/big-pickle";return cadenceDispatchInFlight.add(sessionID),(options.dispatch??dispatchFullAutoOversight)({directory,sessionID,trigger:`cadence:${decision.triggers.map((t)=>t.kind).join(",")}`,triggerSource:"cadence",phase:runState.currentPhase,taskID:runState.currentTaskID??void 0,planID:runState.planID,actionContext:{counters:runState.counters,denialCounters:runState.denialCounters,triggers:decision.triggers},criticModel,oversightAgentName,fullAutoConfig:{fail_closed:config3.full_auto?.fail_closed!==!1,max_dispatch_retries:config3.full_auto?.oversight?.max_dispatch_retries??2,max_consecutive_dispatch_failures:config3.full_auto?.oversight?.max_consecutive_dispatch_failures??3,total_timeout_ms:config3.full_auto?.oversight?.total_timeout_ms??120000}}).catch((err)=>{error48(`[full-auto/cadence] dispatch threw past dispatcher's own fail-closed branches: ${err instanceof Error?err.message:String(err)}`)}).finally(()=>{cadenceDispatchInFlight.delete(sessionID)}),decision}init_recovery2();init_severe_result();init_state3();init_task_file();init_invocation_failure();init_state2();init_utils();init_realtime_learning_nudge();init_utils2();import*as nodePath from"node:path";var MAX_TOOL_FAILURE_REASONS=5,MAX_TOOL_FAILURE_REASON_LENGTH=200;function extractFailureReason(error93){let raw;if(error93 instanceof Error)raw=error93.message;else if(typeof error93==="string")raw=error93;else if(error93&&typeof error93==="object"){let maybeMessage=error93.message;raw=typeof maybeMessage==="string"?maybeMessage:void 0}if(!raw)return;let trimmed=sanitizeFailureEvidenceDisplay(raw).trim();if(!trimmed)return;return trimmed.length>MAX_TOOL_FAILURE_REASON_LENGTH?`${trimmed.slice(0,MAX_TOOL_FAILURE_REASON_LENGTH)}...`:trimmed}function recordFailureReason(aggregate,reason){if(!aggregate.failureReasons)aggregate.failureReasons=[];if(aggregate.failureReasons.includes(reason))return;if(aggregate.failureReasons.length>=MAX_TOOL_FAILURE_REASONS)return;aggregate.failureReasons.push(reason)}function createAgentActivityHooks(config3,directory){if(config3.hooks?.agent_activity===!1)return{toolBefore:async()=>{},toolAfter:async()=>{}};return{toolBefore:async(input)=>{swarmState.activeToolCalls.set(input.callID,{tool:input.tool,sessionID:input.sessionID,callID:input.callID,startTime:Date.now()})},toolAfter:async(input,output)=>{let entry=swarmState.activeToolCalls.get(input.callID);if(!entry)return;swarmState.activeToolCalls.delete(input.callID);let duration5=Date.now()-entry.startTime,success3=!((typeof output.success==="boolean"?output.success:void 0)===!1||!!output.error),key2=entry.tool,existing=swarmState.toolAggregates.get(key2)??{tool:key2,count:0,successCount:0,failureCount:0,totalDuration:0};if(existing.count++,success3)existing.successCount++;else{existing.failureCount++;let reason=extractFailureReason(output.error);if(reason)recordFailureReason(existing,reason)}if(existing.totalDuration+=duration5,swarmState.toolAggregates.set(key2,existing),recordRealtimeLearningToolCall(entry.sessionID),swarmState.pendingEvents++,swarmState.pendingEvents>=20)flushActivityToFile(directory).catch((err)=>warn("Agent activity flush trigger failed:",err))}}}var flushPromise=null;async function flushActivityToFile(directory){if(flushPromise)return flushPromise=flushPromise.then(()=>doFlush(directory)).catch((err)=>{warn("Queued agent activity flush failed:",err)}),flushPromise;flushPromise=doFlush(directory);try{await flushPromise}finally{flushPromise=null}}async function doFlush(directory){try{let existing=await readSwarmFileAsync(directory,"context.md")??"",activitySection=renderActivitySection(),updated=replaceOrAppendSection(existing,"## Agent Activity",activitySection),flushedCount=swarmState.pendingEvents,path263=nodePath.join(directory,".swarm","context.md");await atomicWriteFile(path263,updated),swarmState.pendingEvents=Math.max(0,swarmState.pendingEvents-flushedCount)}catch(error93){warn("Agent activity flush failed:",error93)}}function renderActivitySection(){let lines=["## Agent Activity",""];if(swarmState.toolAggregates.size===0)return lines.push("No tool activity recorded yet."),lines.join(`
|
|
6907
6907
|
`);lines.push("| Tool | Calls | Success | Failed | Avg Duration |"),lines.push("|------|-------|---------|--------|--------------|");let sorted2=[...swarmState.toolAggregates.values()].sort((a,b)=>b.count-a.count);for(let agg of sorted2){let avgDuration=agg.count>0?Math.round(agg.totalDuration/agg.count):0;lines.push(`| ${agg.tool} | ${agg.count} | ${agg.successCount} | ${agg.failureCount} | ${avgDuration}ms |`)}return lines.join(`
|
|
@@ -7460,7 +7460,7 @@ Regenerated on: save_plan and phase_complete.
|
|
|
7460
7460
|
`)}function aggregateEvidence(cluster,phaseNumber){let refs=new Set;for(let p of cluster)for(let ref of p.evidenceRefs)refs.add(ref);let list=Array.from(refs).slice(0,19);return list.push(`consolidation:phase-${phaseNumber}`),list}async function runConsolidationPass(input,deps){let{phaseNumber,runId,config:config3}=input,consolidation=config3.consolidation,base={skipped:!0,phaseNumber,clusterCount:0,clustersDeferred:0,decisionsEmitted:0,added:0,superseded:0,contradictionsDetected:0,deduped:0,proposed:0,memoriesDecayed:0,errored:0};if(!config3.enabled||!consolidation.enabled||!deps.gateway.isEnabled())return{...base,skipReason:"disabled"};let priorLog=await deps.readLog();if(priorLog.some((r)=>r.phaseNumber===phaseNumber))return{...base,skipReason:"already_consolidated"};let processedBefore=new Set(priorLog.flatMap((r)=>r.processedProposalIds)),startedAt=deps.now().toISOString(),logKey=runId??"unknown";await deps.logEvent({event:"consolidation_started",runId:logKey,phaseNumber,timestamp:startedAt});let pendingProposals=(await deps.gateway.listProposals({status:"pending"})).filter((p)=>p.proposedBy?.agentRole!==CONSOLIDATION_AGENT_ROLE&&!processedBefore.has(p.id)).sort((a,b)=>a.id.localeCompare(b.id)),deadAnchorMemoryIds=deps.readDeadAnchorMemoryIds?.()??new Set,existingMemories=(await deps.gateway.listMemories({})).filter((memory)=>!deadAnchorMemoryIds.has(memory.id)),clusters=clusterByJaccard(pendingProposals,(p)=>p.proposedRecord?.text??p.rationale,consolidation.jaccardThreshold),processable=clusters.slice(0,consolidation.maxClustersPerPass),clustersDeferred=Math.max(0,clusters.length-processable.length);await deps.logEvent({event:"cluster_count",runId:logKey,phaseNumber,clusterCount:clusters.length});let result={...base,skipped:!1,clusterCount:clusters.length,clustersDeferred},processedProposalIds=new Set;if(!deps.llmDelegate){if(result.memoriesDecayed=await applyDecay(existingMemories,input,deps),deps.signal?.aborted)return{...result,skipped:!0,skipReason:"aborted"};return await finalize2(input,deps,result,startedAt,processedProposalIds),{...result,skipReason:"no_llm_delegate_decay_only"}}let seenFactTexts=new Set;for(let cluster of processable){if(deps.signal?.aborted)return{...result,skipped:!0,skipReason:"aborted"};for(let p of cluster)processedProposalIds.add(p.id);let raw;try{let prompt=buildDistillationPrompt(cluster,existingMemories);raw=await deps.llmDelegate("",prompt,deps.signal)}catch{result.errored++;continue}let facts=parseDistillationOutput(raw),evidenceRefs=aggregateEvidence(cluster,phaseNumber);for(let fact of facts){let normalized=fact.text.replace(/\s+/g," ").trim().toLowerCase();if(seenFactTexts.has(normalized))continue;seenFactTexts.add(normalized);let plan=deriveDecision(fact,existingMemories,{autoApplyMinConfidence:consolidation.autoApplyMinConfidence,jaccardThreshold:consolidation.jaccardThreshold});try{await executePlan(plan,evidenceRefs,input,deps,result)}catch{result.errored++}}}if(deps.signal?.aborted)return{...result,skipped:!0,skipReason:"aborted"};if(result.memoriesDecayed=await applyDecay(existingMemories,input,deps),deps.signal?.aborted)return{...result,skipped:!0,skipReason:"aborted"};return await finalize2(input,deps,result,startedAt,processedProposalIds),result}async function executePlan(plan,evidenceRefs,input,deps,result){let{phaseNumber}=input;if(plan.type==="skip")return;if(plan.type==="dedup"){result.deduped++;return}let newRecord={kind:plan.fact.kind,text:plan.fact.text,confidence:plan.fact.confidence,stability:"durable",source:sourceForDistilled(evidenceRefs,phaseNumber),metadata:{consolidatedFromPhase:phaseNumber}},rationale=`consolidation phase ${phaseNumber}`;if(((plan.type==="add"||plan.type==="supersede")&&EVIDENCE_REQUIRED_KINDS.has(plan.fact.kind)&&!hasRealEvidence(evidenceRefs)?"proposal":plan.type)==="proposal"){await deps.gateway.propose({operation:plan.type==="supersede"?"supersede":"add",kind:plan.fact.kind,text:plan.fact.text,rationale:plan.type==="proposal"?`${rationale}: ${plan.reason}`:`${rationale}: evidence-required kind lacks real evidence source`,evidenceRefs,...plan.type==="supersede"?{targetMemoryId:plan.oldMemoryId}:{}}),result.proposed++;return}if(plan.type==="supersede"){let proposal2=await deps.gateway.propose({operation:"supersede",kind:plan.fact.kind,text:plan.fact.text,targetMemoryId:plan.oldMemoryId,rationale,evidenceRefs});if(proposal2.status!=="pending"){result.proposed++;return}await deps.gateway.applyCuratorDecision({action:"supersede",proposalId:proposal2.id,oldMemoryId:plan.oldMemoryId,replacement:newRecord,reason:`contradiction superseded during phase ${phaseNumber} consolidation`}),result.superseded++,result.contradictionsDetected++,result.decisionsEmitted++;return}let proposal=await deps.gateway.propose({operation:"add",kind:plan.fact.kind,text:plan.fact.text,rationale,evidenceRefs});if(proposal.status!=="pending"){result.proposed++;return}await deps.gateway.applyCuratorDecision({action:"add",proposalId:proposal.id,memory:newRecord}),result.added++,result.decisionsEmitted++}async function applyDecay(memories,input,deps){let decayed=0,halfLives=input.config.consolidation.decayHalfLifeDays,now2=deps.now();for(let memory of memories){if(deps.signal?.aborted)break;if(memory.metadata.deleted===!0||memory.supersededBy)continue;if(isPastDecayHorizon(memory,halfLives,now2))continue;let nextExpiry=computeDecayExpiry(memory,halfLives,now2);if(!nextExpiry)continue;try{await deps.gateway.upsertCurated({...memory,expiresAt:nextExpiry}),decayed++}catch{}}return decayed}async function finalize2(input,deps,result,startedAt,processedProposalIds){let{phaseNumber,runId}=input,logKey=runId??"unknown",completedAt=deps.now().toISOString();await deps.logEvent({event:"decisions_emitted",runId:logKey,phaseNumber,decisionsEmitted:result.decisionsEmitted}),await deps.logEvent({event:"contradictions_detected",runId:logKey,phaseNumber,contradictionsDetected:result.contradictionsDetected}),await deps.logEvent({event:"memories_decayed",runId:logKey,phaseNumber,memoriesDecayed:result.memoriesDecayed}),await deps.logEvent({event:"consolidation_completed",runId:logKey,phaseNumber,clusterCount:result.clusterCount,decisionsEmitted:result.decisionsEmitted,contradictionsDetected:result.contradictionsDetected,memoriesDecayed:result.memoriesDecayed,timestamp:completedAt}),await deps.appendLog({phaseNumber,runId,startedAt,completedAt,clusterCount:result.clusterCount,clustersDeferred:result.clustersDeferred,decisionsEmitted:result.decisionsEmitted,added:result.added,superseded:result.superseded,contradictionsDetected:result.contradictionsDetected,deduped:result.deduped,proposed:result.proposed,memoriesDecayed:result.memoriesDecayed,errored:result.errored,processedProposalIds:Array.from(processedProposalIds)})}init_consolidation_log();init_gateway();init_reflection_service();init_run_log();init_storage_root();init_canonical_root();var CONSOLIDATION_TIMEOUT_MS=300000,runningByDirectory2=new Map;async function runMemoryConsolidation(req){let key2=canonicalRootKeyFresh(req.directory),existing=runningByDirectory2.get(key2);if(existing)return existing;let run=(async()=>{if(!req.config.enabled||!req.config.consolidation.enabled)return{started:!1,reason:"disabled"};let gateway=createMemoryGateway({directory:req.directory,sessionID:req.sessionId,runId:req.sessionId,agentRole:"curator_consolidation"},{config:req.config}),controller=new AbortController,timer=setTimeout(()=>controller.abort(),CONSOLIDATION_TIMEOUT_MS);timer.unref?.();try{if(!gateway.isEnabled())return{started:!1,reason:"disabled"};let llmDelegate=createCuratorLLMDelegate(req.directory,"consolidation",req.sessionId),result=await runConsolidationPass({directory:req.directory,phaseNumber:req.phase,runId:req.sessionId,config:req.config},{gateway,llmDelegate,now:()=>new Date,logEvent:(event)=>appendMemoryRunLog(req.directory,req.sessionId,event),readLog:()=>readConsolidationLog(resolveVettedMemoryRoot(req.directory,req.config)),appendLog:(record3)=>appendConsolidationLog(resolveVettedMemoryRoot(req.directory,req.config),record3),readDeadAnchorMemoryIds:()=>readDeadAnchorMemoryIds(req.directory),signal:controller.signal});return{started:!result.skipped,reason:result.skipReason,result}}finally{clearTimeout(timer),await gateway.dispose()}})();runningByDirectory2.set(key2,run);try{return await run}finally{if(runningByDirectory2.get(key2)===run)runningByDirectory2.delete(key2)}}function runMemoryConsolidationFireAndForget(req,onComplete,onError){queueMicrotask(()=>{runMemoryConsolidation(req).then(onComplete).catch(onError)})}init_skill_consolidation();init_snapshot_writer();init_state2();init_telemetry();init_state();init_file_locks();import*as fs191 from"node:fs";import*as path319 from"node:path";init_state4();var DEFAULT_CONFIG4={phase_reviewer:!0,phase_critic:!0,integrated_diff_required:!1};function defaultReadPlanJson(dir){try{let planPath=path319.join(dir,".swarm","plan.json");if(!fs191.existsSync(planPath))return null;let raw=fs191.readFileSync(planPath,"utf-8"),plan=JSON.parse(raw);if(typeof plan!=="object"||plan===null||!Array.isArray(plan.phases))return null;return plan}catch{return null}}function readReviewerEvidenceFromFile(directory,phase){try{let evidencePath=path319.join(directory,".swarm","evidence",String(phase),"lean-turbo-reviewer.json");if(!fs191.existsSync(evidencePath))return null;let raw=fs191.readFileSync(evidencePath,"utf-8"),parsed=JSON.parse(raw);if(typeof parsed!=="object"||parsed===null||typeof parsed.verdict!=="string")return null;let verdict=parsed.verdict;if(verdict!=="APPROVED"&&verdict!=="NEEDS_REVISION"&&verdict!=="REJECTED")return null;return parsed}catch{return null}}function readCriticEvidenceFromFile(directory,phase){try{let evidencePath=path319.join(directory,".swarm","evidence",String(phase),"lean-turbo-critic.json");if(!fs191.existsSync(evidencePath))return null;let raw=fs191.readFileSync(evidencePath,"utf-8"),parsed=JSON.parse(raw);if(typeof parsed!=="object"||parsed===null||typeof parsed.verdict!=="string")return null;let verdict=parsed.verdict;if(verdict!=="APPROVED"&&verdict!=="NEEDS_REVISION"&&verdict!=="REJECTED"&&verdict!=="ESCALATE_TO_HUMAN")return null;return parsed}catch{return null}}function listLaneEvidenceSync(directory,phase){let evidenceDir=path319.join(directory,".swarm","evidence",String(phase),"lean-turbo"),entries2;try{entries2=fs191.readdirSync(evidenceDir)}catch{return[]}entries2.sort();let laneIds=[];for(let entry of entries2){if(!entry.endsWith(".json")||entry==="lean-turbo-phase.json")continue;laneIds.push(entry.slice(0,-5))}return laneIds}var _internals270={listActiveLocks,readPersisted:readPersisted3,readPlanJson:defaultReadPlanJson,readReviewerEvidence:readReviewerEvidenceFromFile,readCriticEvidence:readCriticEvidenceFromFile,listLaneEvidence,listLaneEvidenceSync,verifyLeanTurboPhaseReady};function validatePersistedShape3(persisted){if(typeof persisted!=="object"||persisted===null)return!1;if(Array.isArray(persisted))return!1;if(typeof persisted.sessions!=="object")return!1;if(persisted.sessions===null)return!1;if(Array.isArray(persisted.sessions))return!1;return!0}function validateLanesArray(lanes){if(!Array.isArray(lanes))return!1;for(let lane of lanes){if(typeof lane!=="object"||lane===null)return!1;if(typeof lane.laneId!=="string")return!1;if(typeof lane.status!=="string")return!1}return!0}function validateDegradedTasksArray(degradedTasks){if(!Array.isArray(degradedTasks))return!1;for(let dt of degradedTasks){if(typeof dt!=="object"||dt===null)return!1;if(typeof dt.taskId!=="string")return!1}return!0}function verifyLeanTurboPhaseReady(directory,phase,sessionIDOrConfig,config3){let sessionID=typeof sessionIDOrConfig==="string"?sessionIDOrConfig:void 0,mergedConfig={...DEFAULT_CONFIG4,...typeof sessionIDOrConfig==="object"&&sessionIDOrConfig!==null?sessionIDOrConfig:config3??DEFAULT_CONFIG4},statePath2=path319.join(directory,".swarm","turbo-state.json");if(!fs191.existsSync(statePath2))return{ok:!1,reason:"Lean Turbo state unreadable or missing"};let persisted=_internals270.readPersisted(directory);if(!persisted)return{ok:!1,reason:"Lean Turbo state unreadable or missing"};if(!validatePersistedShape3(persisted))return{ok:!1,reason:"Lean Turbo state unreadable or missing"};let runState=null;for(let sessionState of Object.values(persisted.sessions))if(typeof sessionState==="object"&&sessionState!==null&&sessionState.status==="running"&&sessionState.phase===phase&&sessionState.strategy==="lean"&&sessionState.sessionID===sessionID){runState=sessionState;break}if(!runState&&sessionID===void 0){for(let sessionState of Object.values(persisted.sessions))if(typeof sessionState==="object"&&sessionState!==null&&sessionState.status==="running"&&sessionState.phase===phase&&sessionState.strategy==="lean"){runState=sessionState;break}}if(!runState)return{ok:!1,reason:sessionID?`No active Lean Turbo session for phase ${phase} and session ${sessionID}`:`No active Lean Turbo session for phase ${phase}`};if(!validateLanesArray(runState.lanes))return{ok:!1,reason:`No active Lean Turbo session for phase ${phase}`};if(!validateDegradedTasksArray(runState.degradedTasks))return{ok:!1,reason:`No active Lean Turbo session for phase ${phase}`};if(runState.lanes.length===0&&(!Array.isArray(runState.serializedTasks)||runState.serializedTasks.length===0)&&(!Array.isArray(runState.degradedTasks)||runState.degradedTasks.length===0))return{ok:!1,reason:`No lane plan or fallback tasks found for phase ${phase}`};let laneIds=runState.lanes.map((l)=>l.laneId);if(runState.lanes.length>0){for(let lane of runState.lanes)if(lane.status!=="completed"&&lane.status!=="failed")return{ok:!1,reason:`Lane ${lane.laneId} is not completed (status: ${lane.status})`}}if(runState.lanes.length>0){let evidenceLaneIds=new Set(_internals270.listLaneEvidenceSync(directory,phase));for(let lane of runState.lanes)if((lane.status==="completed"||lane.status==="failed")&&!evidenceLaneIds.has(lane.laneId))return{ok:!1,reason:`Lane ${lane.laneId} is ${lane.status} but lane evidence file is missing`}}let activeLocks=_internals270.listActiveLocks(directory),phaseLaneIds=new Set(laneIds);for(let lock of activeLocks)if(lock.laneId&&phaseLaneIds.has(lock.laneId))return{ok:!1,reason:`Active locks remain for lane ${lock.laneId}`};let laneTaskIds=new Set;for(let lane of runState.lanes)if(Array.isArray(lane.taskIds))for(let taskId of lane.taskIds)laneTaskIds.add(taskId);let serialDegradedTasks=runState.degradedTasks.filter((dt)=>!laneTaskIds.has(dt.taskId));if(serialDegradedTasks.length>0){let plan=_internals270.readPlanJson(directory);if(!plan)return{ok:!1,reason:"Cannot verify degraded task status: plan.json unreadable or malformed"};for(let dt of serialDegradedTasks){if(!Array.isArray(plan.phases))return{ok:!1,reason:`Cannot verify degraded task ${dt.taskId}: plan.json malformed (phases is not an array)`};let planPhase=plan.phases.find((p)=>p&&typeof p==="object"&&p!==null&&p.id===phase);if(!planPhase)return{ok:!1,reason:`Cannot verify degraded task ${dt.taskId}: phase ${phase} not found in plan.json`};if(!Array.isArray(planPhase.tasks))return{ok:!1,reason:`Cannot verify degraded task ${dt.taskId}: plan.json malformed (phase ${phase} tasks is not an array)`};let task2=planPhase.tasks.find((t)=>t&&typeof t==="object"&&t!==null&&t.id===dt.taskId);if(!task2)return{ok:!1,reason:`Degraded task ${dt.taskId} not found in plan`};if(task2.status!=="completed")return{ok:!1,reason:`Degraded task ${dt.taskId} not yet completed via standard flow`}}}let serializedTasks=runState.serializedTasks;if(Array.isArray(serializedTasks)&&serializedTasks.length>0){let plan=_internals270.readPlanJson(directory);if(!plan)return{ok:!1,reason:"Cannot verify serialized task status: plan.json unreadable or malformed"};if(!Array.isArray(plan.phases))return{ok:!1,reason:"Cannot verify serialized tasks: plan.json malformed (phases is not an array)"};let planPhase=plan.phases.find((p)=>p&&typeof p==="object"&&p!==null&&p.id===phase);if(!planPhase)return{ok:!1,reason:`Cannot verify serialized tasks: phase ${phase} not found in plan.json`};if(!Array.isArray(planPhase.tasks))return{ok:!1,reason:`Cannot verify serialized tasks: plan.json malformed (phase ${phase} tasks is not an array)`};for(let serTaskId of serializedTasks){let task2=planPhase.tasks.find((t)=>t&&typeof t==="object"&&t!==null&&t.id===serTaskId);if(!task2)return{ok:!1,reason:`Serialized task ${serTaskId} not found in plan`};if(task2.status!=="completed")return{ok:!1,reason:`Serialized task ${serTaskId} not yet completed (status: ${task2.status})`}}}if(mergedConfig.integrated_diff_required){let evidencePath=path319.join(directory,".swarm","evidence",String(phase),"lean-turbo","lean-turbo-phase.json"),hasDiff=!1;try{let content=fs191.readFileSync(evidencePath,"utf-8");hasDiff=!!JSON.parse(content).integratedDiffSummary}catch{}if(!hasDiff)return{ok:!1,reason:`Integrated diff summary is required but missing for phase ${phase}`}}let reviewerVerdict=runState.lastReviewerVerdict;if(!reviewerVerdict)reviewerVerdict=_internals270.readReviewerEvidence(directory,phase)?.verdict??void 0;if(mergedConfig.phase_reviewer){if(reviewerVerdict!=="APPROVED")return{ok:!1,reason:"Integrated reviewer approval missing or rejected"}}let criticVerdict=runState.lastCriticVerdict;if(!criticVerdict)criticVerdict=_internals270.readCriticEvidence(directory,phase)?.verdict??void 0;if(mergedConfig.phase_critic){if(criticVerdict!=="APPROVED")return{ok:!1,reason:"Integrated critic approval missing or rejected"}}return{ok:!0,reason:`Phase ${phase} is ready to advance`,evidence:{lanes:laneIds,degradedTasks:runState.degradedTasks.map((dt)=>dt.taskId),reviewerVerdict:reviewerVerdict??runState.lastReviewerVerdict,criticVerdict:criticVerdict??runState.lastCriticVerdict}}}init_logger();init_create_tool();function resolveCouncilFreshnessMaxAgeMs(config3){let hours=config3?.freshnessMaxAgeHours??24;if(!Number.isFinite(hours)||hours<1)return 86400000;return Math.min(hours,720)*60*60*1000}function evaluateCouncilFreshness(input){if(input.timestampMs===null||!Number.isFinite(input.timestampMs))return{ok:!1,reason:"invalid_timestamp",message:"evidence has a missing or invalid timestamp",recovery:"Re-run the council to generate fresh, timestamped evidence."};if(input.timestampMs>input.nowMs)return{ok:!1,reason:"future_timestamp",message:"evidence timestamp is in the future",recovery:"Re-run the council after the host clock is correct, then resubmit."};if(input.nowMs-input.timestampMs>input.maxAgeMs)return{ok:!1,reason:"stale_evidence",message:`evidence is older than the configured freshness window (${Math.round(input.maxAgeMs/3600000)} hours)`,recovery:"Re-run the council for fresh review."};if(input.mustPostdateMs!==void 0&&input.mustPostdateMs!==null&&Number.isFinite(input.mustPostdateMs)){if(input.mustPostdateMs>input.nowMs)return{ok:!1,reason:"invalid_required_input",message:"a later required input (e.g. the phase retrospective) is timestamped in the future — host clock skew suspected",recovery:"Correct the host clock / fix the skewed timestamp, then re-run the council."};if(input.timestampMs<input.mustPostdateMs)return{ok:!1,reason:"predates_required_input",message:"evidence predates a later required input (e.g. the phase retrospective)",recovery:"Re-run the council after the latest required evidence is available."}}return{ok:!0,message:"evidence is fresh",recovery:""}}function parseTimestampMs(value){if(typeof value!=="string")return null;let parsed=new Date(value).getTime();return Number.isNaN(parsed)?null:parsed}function latestRetroTimestampMsFromBundle(bundle,phase){if(!bundle||typeof bundle!=="object")return null;let raw=bundle,entries2=Array.isArray(raw.entries)?raw.entries:[],timestamps=[parseTimestampMs(raw.created_at),parseTimestampMs(raw.updated_at),...entries2.filter((entry)=>typeof entry==="object"&&entry!==null).filter((entry)=>entry.type==="retrospective"&&entry.phase_number===phase).map((entry)=>parseTimestampMs(entry.timestamp))].filter((timestamp)=>timestamp!==null);return timestamps.length>0?Math.max(...timestamps):null}init_store5();async function runArchitectureSupervisorGate(ctx){let{phase,dir,pluginConfig,agentsDispatched,safeWarn}=ctx,asConfig=pluginConfig.architectural_supervision,summarizeFindings=(findings)=>{if(!Array.isArray(findings)||findings.length===0)return"";let details=findings.map((f)=>f&&typeof f==="object"&&typeof f.description==="string"?f.description:void 0).filter((d)=>Boolean(d));return details.length>0?`
|
|
7461
7461
|
Findings: ${details.join("; ")}`:""},asBlocked=(reason,message)=>({blocked:!0,reason,message,agentsDispatched,agentsMissing:[],warnings:[]}),asEntry=null;try{asEntry=readSupervisorReportRaw(dir,phase)}catch(asError2){return asBlocked("ARCH_SUPERVISOR_ERROR",`Phase ${phase} cannot be completed: architecture supervisor gate encountered an error. Error: ${String(asError2)}`)}if(!asEntry)return asBlocked("ARCH_SUPERVISOR_REQUIRED",`Phase ${phase} cannot be completed: architectural_supervision gate mode is enabled and no architecture supervisor evidence was found at .swarm/evidence/${phase}/architecture-supervisor.json. Dispatch critic_architecture_supervisor with the phase + agent summaries, then call write_architecture_supervisor_evidence.`);let freshness=evaluateCouncilFreshness({nowMs:ctx.preflightNowMs,timestampMs:asEntry.timestamp?new Date(asEntry.timestamp).getTime():null,maxAgeMs:resolveCouncilFreshnessMaxAgeMs(ctx.pluginConfig.council)});if(!freshness.ok)return asBlocked({invalid_timestamp:"ARCH_SUPERVISOR_INVALID_TIMESTAMP",future_timestamp:"ARCH_SUPERVISOR_FUTURE_TIMESTAMP",stale_evidence:"ARCH_SUPERVISOR_STALE_EVIDENCE",predates_required_input:"ARCH_SUPERVISOR_STALE_EVIDENCE",invalid_required_input:"ARCH_SUPERVISOR_INVALID_REQUIRED_INPUT"}[freshness.reason??""]??"ARCH_SUPERVISOR_STALE_EVIDENCE",`Phase ${phase} cannot be completed: architecture supervisor ${freshness.message}. ${freshness.recovery}`);if(typeof asEntry.phase_number!=="number"||asEntry.phase_number!==phase)return asBlocked("ARCH_SUPERVISOR_PHASE_MISMATCH",`Phase ${phase} cannot be completed: architecture supervisor evidence is for phase ${String(asEntry.phase_number)}, not phase ${phase}.`);let gateWarnings=[];if(asConfig?.provenance_verify===!0){let provenance=asEntry.provenance;if(!provenance||!provenance.agent_name&&!provenance.session_id)return asBlocked("ARCH_SUPERVISOR_MISSING_PROVENANCE",`Phase ${phase} cannot be completed: architecture supervisor evidence lacks provenance (agent_name or session_id). Evidence provenance verification is enabled.`)}else if(!asEntry.provenance||!asEntry.provenance.agent_name&&!asEntry.provenance.session_id){let msg=`Architecture supervisor evidence lacks provenance for phase ${phase}. Enable 'provenance_verify' in architectural_supervision config to enforce provenance verification.`;gateWarnings.push(msg),safeWarn(`[phase_complete] ${msg}`,void 0)}let asVerdict=asEntry.verdict;if(asVerdict==="REJECT")return asBlocked("ARCH_SUPERVISOR_REJECTED",`Phase ${phase} cannot be completed: architecture supervisor returned verdict 'REJECT'. Address the system-level findings before completing the phase.${summarizeFindings(asEntry.findings)}`);if(asVerdict==="CONCERNS"){if(asConfig?.allow_concerns_to_complete===!1)return asBlocked("ARCH_SUPERVISOR_CONCERNS",`Phase ${phase} cannot be completed: architecture supervisor returned verdict 'CONCERNS' and allow_concerns_to_complete is disabled.${summarizeFindings(asEntry.findings)}`);safeWarn(`[phase_complete] Architecture supervisor returned CONCERNS for phase ${phase} — proceeding (allow_concerns_to_complete is enabled)`,void 0)}else if(asVerdict!=="APPROVE")return asBlocked("ARCH_SUPERVISOR_INVALID",`Phase ${phase} cannot be completed: architecture supervisor evidence contains unrecognized verdict '${String(asVerdict)}'. Expected one of: APPROVE, CONCERNS, REJECT.`);return{blocked:!1,agentsDispatched,agentsMissing:[],warnings:gateWarnings}}async function runCompletionVerifyGate(ctx){let{phase,dir,agentsDispatched}=ctx;try{let completionResultRaw=await executeCompletionVerify({phase,writeEvidence:!1},dir),completionResult=JSON.parse(completionResultRaw);if(completionResult.status==="blocked")return{blocked:!0,reason:"COMPLETION_INCOMPLETE",message:`Phase ${phase} cannot be completed: ${completionResult.reason}`,agentsDispatched,agentsMissing:[],warnings:completionResult.blockedTasks?[`Blocked tasks: ${completionResult.blockedTasks.map((t)=>t.task_id).join(", ")}`]:[]};return{blocked:!1,agentsDispatched,agentsMissing:[],warnings:[]}}catch(completionError){return{blocked:!0,reason:"COMPLETION_VERIFY_ERROR",message:`Phase ${phase} cannot be completed: completion verify gate encountered an error. Error: ${String(completionError)}`,agentsDispatched,agentsMissing:[],warnings:[`COMPLETION_VERIFY_ERROR: ${String(completionError)}`]}}}init_effective_spec();import*as fs192 from"node:fs";import*as path320 from"node:path";init_qa_gate_profile();init_ledger();init_manager();init_utils3();init_state2();async function resolveGatePreamble(dir,sessionID){let plan=await loadPlan(dir);if(!plan)return{resolved:!1};let planId=derivePlanId(plan),planHash=computePlanLedgerHash(plan),lookup=getProfileLookupForIdentity(dir,plan),overrides2=(sessionID?swarmState.agentSessions.get(sessionID):void 0)?.qaGateSessionOverrides??{};if(lookup.kind==="missing"){let hasOverrides=Object.keys(overrides2).length>0;return{resolved:hasOverrides,plan,planId,planHash,effectiveGates:hasOverrides?{...DEFAULT_QA_GATES,...overrides2}:void 0,identityBound:!0}}let profile=lookup.profile,effective=getEffectiveGates(profile,overrides2);return{resolved:!0,plan,planId,planHash,effectiveGates:effective,identityBound:lookup.kind==="bound"}}async function runDriftGate(ctx){let{phase,dir,sessionID,agentsDispatched,safeWarn}=ctx,gateWarnings=[],driftCheckEnabled=!0,driftHasEffectiveSpec=!1;try{driftHasEffectiveSpec=readEffectiveSpecSync(dir)!==null;let preamble=await resolveGatePreamble(dir,sessionID);if(preamble.resolved){if(preamble.identityBound===!1&&preamble.effectiveGates?.drift_check===!0)return{blocked:!0,reason:"DRIFT_VERIFICATION_IDENTITY_UNBOUND",message:`Phase ${phase} cannot be completed: drift_check is enabled but the QA gate profile is not exact-bound to the current raw swarm_id/plan_title. ${formatLegacyQaBindingRecovery({swarm:preamble.plan.swarm,title:preamble.plan.title},"retry completing the phase")}`,agentsDispatched,agentsMissing:[],warnings:[]};driftCheckEnabled=preamble.effectiveGates?.drift_check===!0}}catch(gateLoadError){safeWarn("[phase_complete] QA gate profile load error, drift_check defaults to enabled:",gateLoadError)}if(!driftCheckEnabled)return{blocked:!1,agentsDispatched,agentsMissing:[],warnings:[`drift_check gate is disabled. Drift verification was skipped for phase ${phase}.`]};let phaseType;try{let planPath=path320.join(dir,".swarm","plan.json");if(fs192.existsSync(planPath)){let planRaw=fs192.readFileSync(planPath,"utf-8");phaseType=JSON.parse(planRaw).phases?.find((p)=>p.id===phase)?.type}}catch{}if(phaseType==="non-code")return{blocked:!1,agentsDispatched,agentsMissing:[],warnings:[`Phase ${phase} is annotated as 'non-code'. Drift verification was skipped per phase type annotation.`]};try{let driftEvidencePath=path320.join(dir,".swarm","evidence",String(phase),"drift-verifier.json"),driftVerdictFound=!1,driftVerdictApproved=!1;try{let driftEvidenceContent=fs192.readFileSync(driftEvidencePath,"utf-8"),entries2=JSON.parse(driftEvidenceContent).entries??[];for(let entry of entries2)if(typeof entry.type==="string"&&entry.type.includes("drift")&&typeof entry.verdict==="string"){if(driftVerdictFound=!0,!entry.provenance||!entry.provenance.agent_name&&!entry.provenance.session_id){let msg=`Drift verification evidence lacks provenance for phase ${phase}. Evidence should include agent_name or session_id for verification.`;gateWarnings.push(msg),safeWarn(`[phase_complete] ${msg}`,void 0)}if(entry.verdict==="approved")driftVerdictApproved=!0;if(entry.verdict==="rejected"||typeof entry.summary==="string"&&entry.summary.includes("NEEDS_REVISION"))return{blocked:!0,reason:"DRIFT_VERIFICATION_REJECTED",message:`Phase ${phase} cannot be completed: drift verifier returned verdict '${entry.verdict}'. Address the drift issues before completing the phase.`,agentsDispatched,agentsMissing:[],warnings:[]}}}catch(readError){if(readError.code!=="ENOENT")safeWarn("[phase_complete] Drift verifier evidence unreadable:",readError);driftVerdictFound=!1}if(!driftVerdictFound)if(!driftHasEffectiveSpec){let incompleteTaskCount=0,planParseable=!1;try{let planPath=path320.join(dir,".swarm","plan.json");if(fs192.existsSync(planPath)){let planRaw=fs192.readFileSync(planPath,"utf-8"),plan=JSON.parse(planRaw);planParseable=!0;let planPhase=plan.phases?.find((p)=>p.id===phase);if(planPhase?.tasks)incompleteTaskCount=planPhase.tasks.filter((t)=>t.status!=="completed"&&t.status!=="closed").length}}catch{}if(!planParseable)return{blocked:!1,agentsDispatched,agentsMissing:[],warnings:["No effective spec found and drift verification evidence missing — consider running critic_drift_verifier before phase completion."]};else if(incompleteTaskCount>0)return{blocked:!1,agentsDispatched,agentsMissing:[],warnings:[`No effective spec found and drift verification evidence missing. Phase ${phase} has ${incompleteTaskCount} incomplete task(s) in plan.json — consider running critic_drift_verifier before phase completion.`]};else return{blocked:!1,agentsDispatched,agentsMissing:[],warnings:[`No effective spec found. Phase ${phase} tasks are all completed in plan.json. Drift verification was skipped.`]}}else return{blocked:!0,reason:"DRIFT_VERIFICATION_MISSING",message:`Phase ${phase} cannot be completed: drift_check is enabled and drift verifier evidence not found at .swarm/evidence/${phase}/drift-verifier.json. Run drift verification before completing the phase.`,agentsDispatched,agentsMissing:[],warnings:[]};if(!driftVerdictApproved&&driftVerdictFound)return{blocked:!0,reason:"DRIFT_VERIFICATION_REJECTED",message:`Phase ${phase} cannot be completed: drift verifier verdict is not approved.`,agentsDispatched,agentsMissing:[],warnings:[]};return{blocked:!1,agentsDispatched,agentsMissing:[],warnings:gateWarnings}}catch(driftError){return{blocked:!0,reason:"DRIFT_VERIFICATION_ERROR",message:`Phase ${phase} cannot be completed: drift verification encountered an error: ${driftError instanceof Error?driftError.message:String(driftError)}. This is a hard block — resolve the error before completing the phase.`,agentsDispatched,agentsMissing:[],warnings:[]}}}import*as fs193 from"node:fs";import*as path321 from"node:path";init_council_review_identity();init_types();init_qa_gate_profile();init_utils3();init_state2();function readLatestRetroTimestampMs(dir,phase){let baseDir=path321.normalize(path321.resolve(dir,".swarm")),retroPath=path321.normalize(path321.join(baseDir,"evidence",`retro-${phase}`,"evidence.json"));if(!(process.platform==="win32"?retroPath.toLowerCase().startsWith(baseDir.toLowerCase()+path321.sep)||retroPath.toLowerCase()===baseDir.toLowerCase():retroPath.startsWith(baseDir+path321.sep)||retroPath===baseDir))return null;try{let content=fs193.readFileSync(retroPath,"utf-8");return latestRetroTimestampMsFromBundle(JSON.parse(content),phase)}catch{return null}}function sessionHasEnabledFinalCouncil(sessionID){if(!sessionID)return!1;return swarmState.agentSessions.get(sessionID)?.qaGateSessionOverrides?.final_council===!0}async function runFinalCouncilGate(ctx){let{phase,dir,sessionID,agentsDispatched,safeWarn}=ctx,finalCouncilEnabled=!1,gateWarnings=[];try{let preamble=await resolveGatePreamble(dir,sessionID);if(!preamble.resolved||!preamble.plan){if(hasAnyProfileWithEnabledGate(dir,"final_council")||sessionHasEnabledFinalCouncil(sessionID))return{blocked:!0,reason:"FINAL_COUNCIL_PLAN_REQUIRED",message:`Phase ${phase} cannot be completed: final_council is enabled but plan.json is missing or invalid, so the final council gate cannot verify the current plan identity. Restore a valid .swarm/plan.json and re-run the final council.`,agentsDispatched,agentsMissing:[],warnings:[]};let warning="Final council gate: plan.json is missing and no enabled final_council profile was found. If final_council is required, the gate cannot be verified.";return gateWarnings.push(warning),safeWarn(`[phase_complete] ${warning}`,void 0),{blocked:!1,agentsDispatched,agentsMissing:[],warnings:[warning]}}if(preamble.resolved&&preamble.plan){let lastPhaseId=preamble.plan.phases[preamble.plan.phases.length-1]?.id;if(lastPhaseId!==void 0&&phase===lastPhaseId){if(preamble.effectiveGates?.final_council===!0){if(preamble.identityBound===!1)return{blocked:!0,reason:"FINAL_COUNCIL_IDENTITY_UNBOUND",message:`Phase ${phase} (last phase) cannot be completed: final_council is enabled but the QA gate profile is not exact-bound to the current raw swarm_id/plan_title. ${formatLegacyQaBindingRecovery({swarm:preamble.plan.swarm,title:preamble.plan.title},"retry completing the project")}`,agentsDispatched,agentsMissing:[],warnings:[]};finalCouncilEnabled=!0;let fcPath=path321.join(dir,".swarm","evidence","final-council.json"),fcVerdictFound=!1,_fcVerdict,identity=computeCouncilReviewIdentity({level:"final",scope:{kind:"final",final:!0},plan:preamble.plan,config:ctx.pluginConfig.council}),completionPolicy=resolveFinalCompletionPolicy(ctx.pluginConfig.council),maxAgeMs=resolveCouncilFreshnessMaxAgeMs(ctx.pluginConfig.council);try{let fcContent=fs193.readFileSync(fcPath,"utf-8"),fcBundle=JSON.parse(fcContent);for(let entry of fcBundle.entries??[])if(typeof entry.type==="string"&&entry.type==="final-council"&&typeof entry.verdict==="string"){fcVerdictFound=!0,_fcVerdict=entry.verdict;let fcTimeMs=parseTimestampMs(entry.timestamp),latestRetroTimestampMs=latestRetroTimestampMsFromBundle(ctx.loadedRetroBundle,phase)??readLatestRetroTimestampMs(dir,phase),freshness=evaluateCouncilFreshness({nowMs:ctx.preflightNowMs,timestampMs:fcTimeMs,maxAgeMs,mustPostdateMs:latestRetroTimestampMs});if(!freshness.ok)return{blocked:!0,reason:{invalid_timestamp:"FINAL_COUNCIL_TIMESTAMP_REQUIRED",future_timestamp:"FINAL_COUNCIL_FUTURE_TIMESTAMP",stale_evidence:"FINAL_COUNCIL_STALE_EVIDENCE",predates_required_input:"FINAL_COUNCIL_STALE_EVIDENCE",invalid_required_input:"FINAL_COUNCIL_INVALID_REQUIRED_INPUT"}[freshness.reason??""]??"FINAL_COUNCIL_STALE_EVIDENCE",message:`Phase ${phase} cannot be completed: final council ${freshness.message}. ${freshness.recovery}`,agentsDispatched,agentsMissing:[],warnings:[]};if(preamble.plan){let currentPlanId=preamble.planId;if(entry.plan_id&&entry.plan_id!==currentPlanId)return{blocked:!0,reason:"final_council_plan_mismatch",message:`Final council evidence belongs to a different plan (evidence: ${entry.plan_id}, current: ${currentPlanId}). Re-run the final council.`,agentsDispatched,agentsMissing:[],warnings:[]};if(!entry.plan_id)return{blocked:!0,reason:"FINAL_COUNCIL_PLAN_ID_REQUIRED",message:`Phase ${phase} (last phase) cannot be completed: final council evidence is missing plan_id binding. Re-run the final council to generate evidence with plan identity.`,agentsDispatched,agentsMissing:[],warnings:[]};let currentIdentityHash=derivePlanIdentityHash(preamble.plan);if(entry.plan_identity_hash!==currentIdentityHash)return{blocked:!0,reason:entry.plan_identity_hash?"FINAL_COUNCIL_PLAN_IDENTITY_MISMATCH":"FINAL_COUNCIL_PLAN_IDENTITY_REQUIRED",message:entry.plan_identity_hash?`Phase ${phase} cannot be completed: final council evidence belongs to a different raw plan identity. Re-run the final council.`:`Phase ${phase} cannot be completed: final council evidence is missing plan_identity_hash binding. Re-run the final council to generate collision-resistant plan identity evidence.`,agentsDispatched,agentsMissing:[],warnings:[]};if(entry.identity_version!==COUNCIL_REVIEW_IDENTITY_VERSION)return{blocked:!0,reason:entry.identity_version?"FINAL_COUNCIL_IDENTITY_MISMATCH":"FINAL_COUNCIL_IDENTITY_REQUIRED",message:entry.identity_version?`Phase ${phase} cannot be completed: final council evidence was produced under a different council identity schema version (${entry.identity_version}, expected ${COUNCIL_REVIEW_IDENTITY_VERSION}). Re-run the final council.`:`Phase ${phase} cannot be completed: final council evidence predates the council review identity cutover and carries no identity proof. Re-run the final council to generate identity-bound evidence.`,agentsDispatched,agentsMissing:[],warnings:[]};if(entry.review_hash!==identity.reviewHash||!isIdentityDigest(entry.identity_digest)||entry.identity_digest!==identity.identityDigest)return{blocked:!0,reason:entry.review_hash?"FINAL_COUNCIL_STALE_REVIEW_IDENTITY":"FINAL_COUNCIL_IDENTITY_REQUIRED",message:`Phase ${phase} cannot be completed: final council evidence does not match the current council review identity (review-relevant plan content or council policy changed since the review). Re-run the final council for the current plan and policy.`,agentsDispatched,agentsMissing:[],warnings:[]};if(entry.policy_digest!==identity.policyDigest)return{blocked:!0,reason:entry.policy_digest?"FINAL_COUNCIL_POLICY_MISMATCH":"FINAL_COUNCIL_IDENTITY_REQUIRED",message:`Phase ${phase} cannot be completed: final council evidence was produced under a different council policy. Re-run the final council under the current policy.`,agentsDispatched,agentsMissing:[],warnings:[]}}let requiredMembers=completionPolicy.mode==="quorum"?completionPolicy.minimumMembers:COUNCIL_MEMBER_ROLES.length,rawMembersVoted=Array.isArray(entry.membersVoted)?entry.membersVoted.filter((member)=>typeof member==="string"):[],distinctCanonicalVoted=new Set(rawMembersVoted.map((member)=>resolveCouncilMemberRole(member)).filter((role)=>Boolean(role))),membersAbsent=COUNCIL_MEMBER_ROLES.filter((role)=>!distinctCanonicalVoted.has(role)),strictAllMembersPresent=distinctCanonicalVoted.size===COUNCIL_MEMBER_ROLES.length,quorumSatisfied=completionPolicy.mode==="quorum"?distinctCanonicalVoted.size>=requiredMembers:strictAllMembersPresent&&membersAbsent.length===0;if(typeof entry.quorumSize!=="number"||!Number.isFinite(entry.quorumSize)||entry.quorumSize<requiredMembers||!quorumSatisfied)return{blocked:!0,reason:"FINAL_COUNCIL_MISSING_QUORUM",message:`Phase ${phase} (last phase) cannot be completed: final council evidence does not prove the required quorum (policy ${completionPolicy.mode}${completionPolicy.mode==="quorum"?`, minimumMembers: ${completionPolicy.minimumMembers}`:""}; recorded quorumSize: ${typeof entry.quorumSize==="number"?entry.quorumSize:"missing"}; distinct canonical members: ${distinctCanonicalVoted.size} of ${requiredMembers} required; absent: [${membersAbsent.join(", ")}]). Re-run the project-scoped final council and call write_final_council_evidence to generate quorumed evidence.`,agentsDispatched,agentsMissing:[],warnings:[]};if(entry.verdict==="rejected"||entry.verdict==="REJECTED")return{blocked:!0,reason:"FINAL_COUNCIL_REJECTED",message:`Phase ${phase} (last phase) cannot be completed: final council returned verdict 'REJECTED'. Address the required fixes before completing the project.`,agentsDispatched,agentsMissing:[],warnings:[]};if(entry.verdict==="concerns"||entry.verdict==="CONCERNS"){let advisoryNotes=Array.isArray(entry.advisoryNotes)?entry.advisoryNotes.filter((note)=>typeof note==="string"):[],warning=advisoryNotes.length>0?`Final council returned CONCERNS (non-blocking): ${advisoryNotes.join("; ")}`:"Final council returned CONCERNS (non-blocking).";gateWarnings.push(warning),safeWarn(`[phase_complete] ${warning}`,void 0)}if(entry.verdict!=="approved"&&entry.verdict!=="APPROVED"&&entry.verdict!=="concerns"&&entry.verdict!=="CONCERNS")return{blocked:!0,reason:"FINAL_COUNCIL_INVALID_VERDICT",message:`Phase ${phase} (last phase) cannot be completed: final council evidence contains unrecognized verdict '${entry.verdict}'. Expected one of: approved, concerns, rejected.`,agentsDispatched,agentsMissing:[],warnings:[]}}}catch(readErr){if(readErr.code!=="ENOENT")safeWarn("[phase_complete] Final council evidence unreadable:",readErr);fcVerdictFound=!1}if(!fcVerdictFound)return{blocked:!0,reason:"FINAL_COUNCIL_REQUIRED",final_council_required:!0,message:`Phase ${phase} (last phase) cannot be completed: final_council is enabled and final council evidence not found at .swarm/evidence/final-council.json. Dispatch critic, reviewer, sme, test_engineer, and explorer with project-scoped context, collect their CouncilMemberVerdict JSON, and call write_final_council_evidence before completing the project. Do not use convene_general_council for this gate.`,agentsDispatched,agentsMissing:[],warnings:["Final council required - dispatch the project-scoped council members, then call write_final_council_evidence to persist quorumed evidence."]}}}}}catch(fcError){if(finalCouncilEnabled)return{blocked:!0,reason:"FINAL_COUNCIL_ERROR",message:`Phase ${phase} (last phase) cannot be completed: final council gate encountered an error. Error: ${String(fcError)}`,agentsDispatched,agentsMissing:[],warnings:[`FINAL_COUNCIL_ERROR: ${String(fcError)}`]};else safeWarn("[phase_complete] Final council gate error (non-blocking):",fcError)}return{blocked:!1,agentsDispatched,agentsMissing:[],warnings:gateWarnings}}init_schema();init_manager();init_diff_source();init_evidence2();function pass(ctx,warnings=[]){return{blocked:!1,agentsDispatched:ctx.agentsDispatched,agentsMissing:[],warnings}}function block(ctx,reason,message,recovery={kind:"tool",action:"run_phase_review",args:{phase:ctx.phase,sessionID:ctx.sessionID}}){return{blocked:!0,reason,message,agentsDispatched:ctx.agentsDispatched,agentsMissing:[],warnings:[],recovery}}function evidenceStatusMatchesScope(evidenceStatus,scopeStatus){return scopeStatus==="clean"?evidenceStatus==="clean":evidenceStatus==="completed"}async function runFinalReviewGate(ctx){let config3;try{config3=resolveAutoReviewConfig(ctx.pluginConfig.auto_review??{})}catch(error93){return block(ctx,"FINAL_REVIEW_CONFIG_INVALID",`Phase ${ctx.phase} cannot be completed: ${error93 instanceof Error?error93.message:String(error93)}`,{kind:"tool",action:"swarm_command",args:{command:"doctor",args:["config"]}})}let finalPlanPhase=(await loadPlanJsonOnly(ctx.dir).catch(()=>null))?.phases.at(-1)?.id===ctx.phase,allowedTriggers=new Set;if(config3.final_review.on_phase_complete)allowedTriggers.add("phase_completion");if(finalPlanPhase&&config3.final_review.on_plan_complete)allowedTriggers.add("plan_completion");if(!config3.enabled||config3.final_review.mode!=="gate"||config3.trigger==="task_completion"||allowedTriggers.size===0)return pass(ctx);let evidence2=readAutoReviewEvidenceForPhase(ctx.dir,ctx.phase);if(!evidence2)return block(ctx,"FINAL_REVIEW_EVIDENCE_MISSING",`Phase ${ctx.phase} cannot be completed: .swarm/evidence/${ctx.phase}/auto-review.json is missing or malformed.`);if(evidence2.schema_version!==2||!evidence2.scope.manifest)return block(ctx,"FINAL_REVIEW_LEGACY_RERUN",`Phase ${ctx.phase} cannot be completed: final review evidence uses the legacy schema and must be rerun with run_phase_review before completion.`);if(evidence2.phase!==ctx.phase||!allowedTriggers.has(evidence2.trigger))return block(ctx,"FINAL_REVIEW_EVIDENCE_STALE",`Phase ${ctx.phase} cannot be completed: final review evidence does not match the current review scope.`);let currentScope=await _internals271.collectReviewDiff({directory:ctx.dir,maxBytes:config3.final_review.max_diff_bytes});if(currentScope.status==="error")return block(ctx,"FINAL_REVIEW_SCOPE_COLLECTION_FAILED",`Phase ${ctx.phase} cannot be completed: terminal final-review scope collection failed (${currentScope.reason}).`);let currentManifest=await materializeAutoReviewManifest(ctx.dir,currentScope.manifest,config3);if(currentManifest.hash!==evidence2.scope.manifest.hash||JSON.stringify(currentScope.selector)!==JSON.stringify(evidence2.scope.selector)||JSON.stringify(currentScope.completeness)!==JSON.stringify(evidence2.scope.completeness)||!evidenceStatusMatchesScope(evidence2.review.status,currentScope.status))return block(ctx,"FINAL_REVIEW_EVIDENCE_STALE",`Phase ${ctx.phase} cannot be completed: repository scope, plan requirements, or review policy changed after final review evidence was produced.`);if(evidence2.policy.mode!==config3.final_review.mode||evidence2.policy.min_confidence!==config3.min_confidence||evidence2.policy.structured_findings!==config3.structured_findings||evidence2.policy.validate_findings!==config3.validate_findings||evidence2.policy.digest!==currentManifest.review_policy_digest)return block(ctx,"FINAL_REVIEW_POLICY_STALE",`Phase ${ctx.phase} cannot be completed: final review evidence was produced under a different policy.`);let integrity=validateAutoReviewEvidenceIntegrity(ctx.dir,evidence2,{scopeHash:evidence2.scope.hash,phase:ctx.phase,trigger:evidence2.trigger,policy:{mode:evidence2.policy.mode,min_confidence:evidence2.policy.min_confidence,structured_findings:evidence2.policy.structured_findings,validate_findings:evidence2.policy.validate_findings},scopeContent:currentScope.canonicalText});if(!integrity.ok)return block(ctx,integrity.code==="receipt_missing"?"FINAL_REVIEW_RECEIPT_MISSING":"FINAL_REVIEW_EVIDENCE_INVALID",`Phase ${ctx.phase} cannot be completed: final review evidence integrity check failed (${integrity.reason}).`);if(evidence2.review.status==="error")return block(ctx,"FINAL_REVIEW_FAILED",`Phase ${ctx.phase} cannot be completed: final review dispatch or parsing failed.`);if(!evidence2.scope.completeness.complete)return block(ctx,"FINAL_REVIEW_SCOPE_INCOMPLETE",`Phase ${ctx.phase} cannot be completed: final review scope was truncated or incomplete.`);if(evidence2.review.status==="completed"&&evidence2.review.output_mode!=="structured")return block(ctx,"FINAL_REVIEW_STRUCTURED_EVIDENCE_REQUIRED",`Phase ${ctx.phase} cannot be completed: gate mode requires structured review evidence.`);if(!evidence2.validation_complete)return block(ctx,"FINAL_REVIEW_VALIDATION_INCOMPLETE",`Phase ${ctx.phase} cannot be completed: independent finding validation evidence is incomplete.`);let gateCandidates=evidence2.findings.filter((finding)=>finding.anchored&&(finding.effective_severity==="high"||finding.effective_severity==="critical"));if(gateCandidates.some((finding)=>!finding.validation||finding.validation.finding_id!==finding.finding_id))return block(ctx,"FINAL_REVIEW_VALIDATION_INCOMPLETE",`Phase ${ctx.phase} cannot be completed: gate-eligible findings lack exact-ID validation evidence.`);let confirmedIds=gateCandidates.filter((finding)=>finding.validation?.disposition==="CONFIRMED").map((finding)=>finding.finding_id).sort(),recordedBlockingIds=[...evidence2.blocking_finding_ids].sort();if(confirmedIds.length!==recordedBlockingIds.length||confirmedIds.some((id,index)=>id!==recordedBlockingIds[index]))return block(ctx,"FINAL_REVIEW_EVIDENCE_INVALID",`Phase ${ctx.phase} cannot be completed: blocking finding IDs do not match independently confirmed findings.`);if(evidence2.blocking_finding_ids.length>0)return block(ctx,"FINAL_REVIEW_CONFIRMED_FINDINGS",`Phase ${ctx.phase} cannot be completed: ${evidence2.blocking_finding_ids.length} anchored HIGH/CRITICAL finding(s) were independently CONFIRMED.`);return pass(ctx)}var _internals271={collectReviewDiff};import*as fs194 from"node:fs";import*as path322 from"node:path";async function runHallucinationGate(ctx){let{phase,dir,sessionID,agentsDispatched,safeWarn}=ctx,hallucinationGateEnabled=!1;try{let preamble=await resolveGatePreamble(dir,sessionID);if(preamble.resolved&&preamble.effectiveGates?.hallucination_guard===!0){if(hallucinationGateEnabled=!0,preamble.identityBound===!1)return{blocked:!0,reason:"HALLUCINATION_VERIFICATION_IDENTITY_UNBOUND",message:`Phase ${phase} cannot be completed: hallucination_guard is enabled but the QA gate profile is not exact-bound to the current raw swarm_id/plan_title. ${formatLegacyQaBindingRecovery({swarm:preamble.plan.swarm,title:preamble.plan.title},"retry completing the phase")}`,agentsDispatched,agentsMissing:[],warnings:[]};let hgPath=path322.join(dir,".swarm","evidence",String(phase),"hallucination-guard.json"),hgVerdictFound=!1,hgVerdictApproved=!1;try{let hgContent=fs194.readFileSync(hgPath,"utf-8"),hgBundle=JSON.parse(hgContent);for(let entry of hgBundle.entries??[])if(typeof entry.type==="string"&&entry.type.includes("hallucination")&&typeof entry.verdict==="string"){if(hgVerdictFound=!0,entry.verdict==="approved")hgVerdictApproved=!0;if(entry.verdict==="rejected"||typeof entry.summary==="string"&&entry.summary.includes("NEEDS_REVISION"))return{blocked:!0,reason:"HALLUCINATION_VERIFICATION_REJECTED",message:`Phase ${phase} cannot be completed: hallucination verifier returned verdict '${entry.verdict}'. Remove fabricated APIs/signatures and fix broken citations before completing the phase.`,agentsDispatched,agentsMissing:[],warnings:[]}}}catch(readErr){if(readErr.code!=="ENOENT")safeWarn("[phase_complete] Hallucination guard evidence unreadable:",readErr);hgVerdictFound=!1}if(!hgVerdictFound)return{blocked:!0,reason:"HALLUCINATION_VERIFICATION_MISSING",message:`Phase ${phase} cannot be completed: hallucination_guard is enabled and evidence not found at .swarm/evidence/${phase}/hallucination-guard.json. Delegate to critic_hallucination_verifier and call write_hallucination_evidence before completing the phase.`,agentsDispatched,agentsMissing:[],warnings:[]};if(!hgVerdictApproved)return{blocked:!0,reason:"HALLUCINATION_VERIFICATION_REJECTED",message:`Phase ${phase} cannot be completed: hallucination verifier verdict is not approved.`,agentsDispatched,agentsMissing:[],warnings:[]}}}catch(hgError){if(hallucinationGateEnabled)return{blocked:!0,reason:"HALLUCINATION_GATE_ERROR",message:`Phase ${phase} cannot be completed: hallucination guard gate encountered an error when hallucination_guard was enabled. Error: ${String(hgError)}`,agentsDispatched,agentsMissing:[],warnings:[`HALLUCINATION_GATE_ERROR: ${String(hgError)}`]};else safeWarn("[phase_complete] Hallucination guard error (non-blocking):",hgError)}return{blocked:!1,agentsDispatched,agentsMissing:[],warnings:[]}}import*as fs195 from"node:fs";import*as path323 from"node:path";async function runMutationGate(ctx){let{phase,dir,sessionID,agentsDispatched,safeWarn}=ctx,mutationGateEnabled=!1;try{let preamble=await resolveGatePreamble(dir,sessionID);if(preamble.resolved&&preamble.effectiveGates?.mutation_test===!0){if(mutationGateEnabled=!0,preamble.identityBound===!1)return{blocked:!0,reason:"MUTATION_GATE_IDENTITY_UNBOUND",message:`Phase ${phase} cannot be completed: mutation_test is enabled but the QA gate profile is not exact-bound to the current raw swarm_id/plan_title. ${formatLegacyQaBindingRecovery({swarm:preamble.plan.swarm,title:preamble.plan.title},"retry completing the phase")}`,agentsDispatched,agentsMissing:[],warnings:[]};let mgPath=path323.join(dir,".swarm","evidence",String(phase),"mutation-gate.json"),mgVerdictFound=!1,mgVerdict;try{let mgContent=fs195.readFileSync(mgPath,"utf-8"),mgBundle=JSON.parse(mgContent);for(let entry of mgBundle.entries??[])if(typeof entry.type==="string"&&entry.type==="mutation-gate"&&typeof entry.verdict==="string"){if(mgVerdictFound=!0,mgVerdict=entry.verdict,entry.verdict==="fail")return{blocked:!0,reason:"MUTATION_GATE_FAIL",message:`Phase ${phase} cannot be completed: mutation gate returned verdict 'fail'. Resolve surviving mutants or lower the kill-rate threshold before completing the phase.`,agentsDispatched,agentsMissing:[],warnings:[]};else if(!["pass","warn","skip"].includes(entry.verdict))return{blocked:!0,reason:"MUTATION_GATE_FAIL",message:`Phase ${phase} cannot be completed: mutation gate evidence contains unrecognized verdict '${entry.verdict}'. Expected one of: pass, warn, fail, skip.`,agentsDispatched,agentsMissing:[],warnings:[]}}}catch(readErr){if(readErr.code!=="ENOENT")safeWarn("[phase_complete] Mutation gate evidence unreadable:",readErr);mgVerdictFound=!1}if(!mgVerdictFound)return{blocked:!0,reason:"MUTATION_GATE_MISSING",message:`Phase ${phase} cannot be completed: mutation_test is enabled and evidence not found at .swarm/evidence/${phase}/mutation-gate.json. Run mutation_test, then call write_mutation_evidence before completing the phase.`,agentsDispatched,agentsMissing:[],warnings:[]};if(mgVerdict==="warn")safeWarn(`[phase_complete] Mutation gate verdict is 'warn' for phase ${phase} — proceeding with warning`,void 0)}}catch(mgError){if(mutationGateEnabled)return{blocked:!0,reason:"MUTATION_GATE_ERROR",message:`Phase ${phase} cannot be completed: mutation gate encountered an error when mutation_test was enabled. Error: ${String(mgError)}`,agentsDispatched,agentsMissing:[],warnings:[`MUTATION_GATE_ERROR: ${String(mgError)}`]};else safeWarn("[phase_complete] Mutation gate error (non-blocking):",mgError)}return{blocked:!1,agentsDispatched,agentsMissing:[],warnings:[]}}import*as fs196 from"node:fs";import*as path324 from"node:path";init_council_review_identity();function readLatestRetroTimestampMs2(dir,phase){let baseDir=path324.normalize(path324.resolve(dir,".swarm")),retroPath=path324.normalize(path324.join(baseDir,"evidence",`retro-${phase}`,"evidence.json"));if(!(process.platform==="win32"?retroPath.toLowerCase().startsWith(baseDir.toLowerCase()+path324.sep)||retroPath.toLowerCase()===baseDir.toLowerCase():retroPath.startsWith(baseDir+path324.sep)||retroPath===baseDir))return null;try{return latestRetroTimestampMsFromBundle(JSON.parse(fs196.readFileSync(retroPath,"utf-8")),phase)}catch{return null}}async function runPhaseCouncilGate(ctx){let{phase,dir,sessionID,pluginConfig,agentsDispatched,safeWarn}=ctx,gateWarnings=[],councilModeEnabled=!1;try{let preamble=await resolveGatePreamble(dir,sessionID);if(preamble.resolved&&preamble.effectiveGates?.phase_council===!0&&pluginConfig.council?.enabled===!0){if(preamble.identityBound===!1)return{blocked:!0,reason:"PHASE_COUNCIL_IDENTITY_UNBOUND",message:`Phase ${phase} cannot be completed: phase_council is enabled but the QA gate profile is not exact-bound to the current raw swarm_id/plan_title. ${formatLegacyQaBindingRecovery({swarm:preamble.plan.swarm,title:preamble.plan.title},"retry completing the phase")}`,agentsDispatched,agentsMissing:[],warnings:[]};councilModeEnabled=!0;let identity=computeCouncilReviewIdentity({level:"phase",scope:{kind:"phase",phaseNumber:phase},plan:preamble.plan??null,config:pluginConfig.council}),maxAgeMs=resolveCouncilFreshnessMaxAgeMs(pluginConfig.council),pcPath=path324.join(dir,".swarm","evidence",String(phase),"phase-council.json"),pcVerdictFound=!1,_pcVerdict,pcQuorumSize,pcPhaseNumber;try{let pcContent=fs196.readFileSync(pcPath,"utf-8"),pcBundle=JSON.parse(pcContent);for(let entry of pcBundle.entries??[])if(typeof entry.type==="string"&&entry.type==="phase-council"&&typeof entry.verdict==="string"){if(pcVerdictFound=!0,_pcVerdict=entry.verdict,pcQuorumSize=typeof entry.quorumSize==="number"?entry.quorumSize:void 0,pcPhaseNumber=typeof entry.phase_number==="number"?entry.phase_number:typeof entry.phase==="number"?entry.phase:void 0,pcPhaseNumber===void 0||typeof pcPhaseNumber!=="number")return{blocked:!0,reason:"PHASE_COUNCIL_MISSING_PHASE",message:`Phase ${phase} cannot be completed: phase council evidence is missing phase_number field.`,agentsDispatched,agentsMissing:[],warnings:[]};if(pcPhaseNumber!==phase)return{blocked:!0,reason:"PHASE_COUNCIL_PHASE_MISMATCH",message:`Phase ${phase} cannot be completed: phase council evidence is for phase ${pcPhaseNumber}, not phase ${phase}. Run council for the correct phase.`,agentsDispatched,agentsMissing:[],warnings:[]};let freshness=evaluateCouncilFreshness({nowMs:ctx.preflightNowMs,timestampMs:parseTimestampMs(entry.timestamp),maxAgeMs,mustPostdateMs:latestRetroTimestampMsFromBundle(ctx.loadedRetroBundle,phase)??readLatestRetroTimestampMs2(dir,phase)});if(!freshness.ok)return{blocked:!0,reason:{invalid_timestamp:"PHASE_COUNCIL_INVALID_TIMESTAMP",future_timestamp:"PHASE_COUNCIL_FUTURE_TIMESTAMP",stale_evidence:"PHASE_COUNCIL_STALE_EVIDENCE",predates_required_input:"PHASE_COUNCIL_STALE_EVIDENCE",invalid_required_input:"PHASE_COUNCIL_INVALID_REQUIRED_INPUT"}[freshness.reason??""]??"PHASE_COUNCIL_STALE_EVIDENCE",message:`Phase ${phase} cannot be completed: phase council ${freshness.message}. ${freshness.recovery}`,agentsDispatched,agentsMissing:[],warnings:[]};if(entry.identity_version!==COUNCIL_REVIEW_IDENTITY_VERSION)return{blocked:!0,reason:entry.identity_version?"PHASE_COUNCIL_IDENTITY_MISMATCH":"PHASE_COUNCIL_IDENTITY_REQUIRED",message:`Phase ${phase} cannot be completed: phase council evidence ${entry.identity_version?`was produced under a different council identity schema version (${entry.identity_version}, expected ${COUNCIL_REVIEW_IDENTITY_VERSION})`:"predates the council review identity cutover and carries no identity proof"}. Re-convene the phase council for the current plan and policy.`,agentsDispatched,agentsMissing:[],warnings:[]};if(entry.review_hash!==identity.reviewHash||!isIdentityDigest(entry.identity_digest)||entry.identity_digest!==identity.identityDigest)return{blocked:!0,reason:"PHASE_COUNCIL_STALE_REVIEW_IDENTITY",message:`Phase ${phase} cannot be completed: phase council evidence does not match the current council review identity (review-relevant plan content changed since the review). Re-convene the phase council.`,agentsDispatched,agentsMissing:[],warnings:[]};if(entry.policy_digest!==identity.policyDigest)return{blocked:!0,reason:entry.policy_digest?"PHASE_COUNCIL_POLICY_MISMATCH":"PHASE_COUNCIL_IDENTITY_REQUIRED",message:`Phase ${phase} cannot be completed: phase council evidence was produced under a different council policy. Re-convene the phase council under the current policy.`,agentsDispatched,agentsMissing:[],warnings:[]};if(!entry.provenance||!entry.provenance.agent_name&&!entry.provenance.session_id){let msg=`Phase council evidence lacks provenance for phase ${phase}. Evidence should include agent_name or session_id for verification.`;gateWarnings.push(msg),safeWarn(`[phase_complete] ${msg}`,void 0)}if(entry.verdict==="REJECT"||entry.verdict==="reject"){let requiredFixes=entry.requiredFixes??entry.required_fixes??[],fixesDetail=Array.isArray(requiredFixes)&&requiredFixes.length>0?`
|
|
7462
7462
|
Required fixes: ${requiredFixes.map((f)=>f.detail??JSON.stringify(f)).join("; ")}`:"";return{blocked:!0,reason:"PHASE_COUNCIL_REJECTED",message:`Phase ${phase} cannot be completed: phase council returned verdict 'REJECT'. Address the required fixes before completing the phase.${fixesDetail}`,agentsDispatched,agentsMissing:[],warnings:[]}}if(entry.verdict==="CONCERNS"||entry.verdict==="concerns"){if(!(pluginConfig.council?.phaseConcernsAllowComplete??!0)){let advisoryNotes=entry.advisoryNotes??entry.advisory_notes??[],notesDetail=Array.isArray(advisoryNotes)&&advisoryNotes.length>0?`
|
|
7463
|
-
Advisory notes: ${advisoryNotes.join("; ")}`:"";return{blocked:!0,reason:"PHASE_COUNCIL_CONCERNS",message:`Phase ${phase} cannot be completed: phase council returned verdict 'CONCERNS'.${notesDetail}`,agentsDispatched,agentsMissing:[],warnings:[]}}safeWarn(`[phase_complete] Phase council returned CONCERNS for phase ${phase} — proceeding (phaseConcernsAllowComplete is enabled)`,void 0)}if(entry.verdict!=="APPROVE"&&entry.verdict!=="approve"&&entry.verdict!=="CONCERNS"&&entry.verdict!=="concerns")return{blocked:!0,reason:"PHASE_COUNCIL_INVALID",message:`Phase ${phase} cannot be completed: phase council evidence contains unrecognized verdict '${entry.verdict}'. Expected one of: APPROVE, CONCERNS, REJECT.`,agentsDispatched,agentsMissing:[],warnings:[]}}}catch(readErr){if(readErr.code!=="ENOENT")safeWarn("[phase_complete] Phase council evidence unreadable:",readErr);pcVerdictFound=!1}if(!pcVerdictFound)return{blocked:!0,reason:"PHASE_COUNCIL_REQUIRED",phase_council_required:!0,message:`Phase ${phase} cannot be completed: phase_council is enabled and phase council evidence not found at .swarm/evidence/${phase}/phase-council.json. Convene a phase-level council (dispatch 5 members, collect verdicts, call submit_phase_council_verdicts) before completing the phase.`,agentsDispatched,agentsMissing:[],warnings:["Phase council required — convene 5 council members (critic, reviewer, sme, test_engineer, explorer) for holistic phase review. Call submit_phase_council_verdicts to synthesize verdicts and write phase-council.json evidence."]};let effectiveMinimum=pluginConfig.council.requireAllMembers?5:pluginConfig.council.minimumMembers??3;if(pcQuorumSize===void 0||typeof pcQuorumSize!=="number")return{blocked:!0,reason:"PHASE_COUNCIL_MISSING_QUORUM",message:`Phase ${phase} cannot be completed: phase council evidence is missing quorumSize field.`,agentsDispatched,agentsMissing:[],warnings:[]};if(pcQuorumSize<effectiveMinimum)return{blocked:!0,reason:"PHASE_COUNCIL_INSUFFICIENT_QUORUM",message:`Phase ${phase} cannot be completed: phase council quorum (${pcQuorumSize}) is below minimum (${effectiveMinimum}). Re-convene council with sufficient members.`,agentsDispatched,agentsMissing:[],warnings:[]}}}catch(pcError){if(councilModeEnabled)return{blocked:!0,reason:"PHASE_COUNCIL_ERROR",message:`Phase ${phase} cannot be completed: phase council gate encountered an error when phase_council was enabled. Error: ${String(pcError)}`,agentsDispatched,agentsMissing:[],warnings:[`PHASE_COUNCIL_ERROR: ${String(pcError)}`]};else safeWarn("[phase_complete] Phase council gate error (non-blocking):",pcError)}return{blocked:!1,agentsDispatched,agentsMissing:[],warnings:gateWarnings}}import{createHash as createHash100}from"node:crypto";var MAX_DETAIL_CHARS=1024,MAX_WARNINGS=32,MAX_ACTORS=64,DEFAULT_GATE_TIMEOUT_MS=1e4,MAX_GATE_TIMEOUT_MS=30000;async function runBoundedGate(check3){let timeoutMs=Math.min(MAX_GATE_TIMEOUT_MS,Math.max(1,check3.timeoutMs??DEFAULT_GATE_TIMEOUT_MS)),timer;try{return await Promise.race([check3.run(),new Promise((_,reject2)=>{timer=setTimeout(()=>reject2(Error(`${check3.id.toUpperCase()}_TIMEOUT: gate read exceeded ${timeoutMs}ms`)),timeoutMs)})])}finally{if(timer)clearTimeout(timer)}}function bounded(value,fallback=""){let text=typeof value==="string"?value:fallback;return text.length<=MAX_DETAIL_CHARS?text:`${text.slice(0,MAX_DETAIL_CHARS-1)}…`}function boundedStrings(value,limit=MAX_ACTORS){if(!Array.isArray(value))return[];return value.filter((item)=>typeof item==="string").slice(0,limit).map((item)=>bounded(item))}function recoveryFrom(result){let raw=result.recovery;if(!raw||typeof raw!=="object"||Array.isArray(raw))return;let candidate2=raw;if(!["tool","command","retry","user_action"].includes(String(candidate2.kind))||typeof candidate2.action!=="string"||candidate2.action.length===0)return;return{kind:candidate2.kind,action:bounded(candidate2.action),...candidate2.args&&typeof candidate2.args==="object"&&!Array.isArray(candidate2.args)?{args:candidate2.args}:{}}}function defaultBlockedRecovery(check3,result){let action2={critical_directives:"knowledge_receipt",retrospective:"write_retro",completion_verify:"completion_verify",drift:"write_drift_evidence",hallucination:"write_hallucination_evidence",mutation:"write_mutation_evidence",final_review:"run_phase_review",lean_turbo_readiness:"lean_turbo_review"}[check3.id];if(action2){if(check3.id==="lean_turbo_readiness"){let blockedOnCritic=/critic/i.test(`${result.message??""} ${result.reason??""}`);return{kind:"tool",action:action2,...blockedOnCritic?{args:{follow_up_tool:"lean_turbo_critic"}}:{}}}return{kind:"tool",action:action2}}if(check3.id==="phase_council"||check3.id==="final_council")return{kind:"user_action",action:"Task",args:{agents:["critic","reviewer","sme","test_engineer","explorer"],follow_up_tool:check3.id==="phase_council"?"submit_phase_council_verdicts":"write_final_council_evidence"}};if(check3.id==="architecture_supervisor")return{kind:"user_action",action:"Task",args:{agents:["critic_architecture_supervisor"],follow_up_tool:"write_architecture_supervisor_evidence"}};if(check3.id==="full_auto_approval")return{kind:"user_action",action:"Task",args:{agents:["critic_oversight"]}};if(check3.id==="required_agents")return{kind:"user_action",action:"Task",args:{agents:boundedStrings(result.agentsMissing)}};return{kind:"retry",action:"phase_complete"}}function retrospectiveGateFrom(result){let raw=result.retrospective_gate;if(!raw||typeof raw!=="object"||Array.isArray(raw))return;let candidate2=raw;if(typeof candidate2.schema_valid!=="boolean"||typeof candidate2.gate_pass!=="boolean")return;return{schema_valid:candidate2.schema_valid,gate_pass:candidate2.gate_pass,...candidate2.verdict==="pass"||candidate2.verdict==="fail"?{verdict:candidate2.verdict}:{}}}function stableReportHash(phase,entries2){return createHash100("sha256").update(JSON.stringify({schemaVersion:1,phase,entries:entries2})).digest("hex")}async function collectPhaseGateReport(input){let entries2=[];for(let check3 of input.checks){if(check3.applicable===!1){entries2.push({id:check3.id,code:"NOT_APPLICABLE",outcome:"not_applicable",detail:bounded(check3.notApplicableDetail,"gate not applicable"),evidenceRefs:[],responsibleActor:check3.responsibleActor,agentsDispatched:[],agentsMissing:[],warnings:[]});continue}try{let result=await runBoundedGate(check3),recovery=recoveryFrom(result)??(result.blocked?defaultBlockedRecovery(check3,result):void 0),retrospectiveGate=retrospectiveGateFrom(result);entries2.push({id:check3.id,code:typeof result.reason==="string"?bounded(result.reason):result.blocked?`${check3.id.toUpperCase()}_BLOCKED`:"PASS",outcome:result.blocked?"block":"pass",...typeof result.message==="string"?{detail:bounded(result.message)}:{},evidenceRefs:boundedStrings(result.evidenceRefs),responsibleActor:check3.responsibleActor,...recovery?{recovery,requiredRecoveryKind:recovery.kind}:{},...retrospectiveGate?{retrospective_gate:retrospectiveGate}:{},agentsDispatched:boundedStrings(result.agentsDispatched),agentsMissing:boundedStrings(result.agentsMissing),warnings:boundedStrings(result.warnings,MAX_WARNINGS),...typeof result.recovery_guidance==="string"?{recoveryGuidance:bounded(result.recovery_guidance)}:{},...result.phase_council_required===!0?{phase_council_required:!0}:{},...result.final_council_required===!0?{final_council_required:!0}:{}})}catch(error93){entries2.push({id:check3.id,code:error93 instanceof Error&&error93.message.startsWith(`${check3.id.toUpperCase()}_TIMEOUT:`)?`${check3.id.toUpperCase()}_TIMEOUT`:`${check3.id.toUpperCase()}_ERROR`,outcome:"error",detail:bounded(error93 instanceof Error?error93.message:String(error93),"unknown gate error"),evidenceRefs:[],responsibleActor:check3.responsibleActor,recovery:{kind:"retry",action:"phase_complete"},requiredRecoveryKind:"retry",agentsDispatched:[],agentsMissing:[],warnings:[]})}}let outcome=entries2.some((entry)=>entry.outcome==="block"||entry.outcome==="error")?"block":"pass";return{schemaVersion:1,phase:input.phase,outcome,reportHash:stableReportHash(input.phase,entries2),entries:entries2}}function formatPhaseGateCompatibility(report){let firstFailure=report.entries.find((entry)=>entry.outcome==="block"||entry.outcome==="error"),retrospectiveEntry=report.entries.find((entry)=>entry.id==="retrospective"&&entry.retrospective_gate),recoveryGuidance=report.entries.find((entry)=>entry.id==="required_agents"&&entry.recoveryGuidance)?.recoveryGuidance,requiredAgentsEntry=report.entries.find((entry)=>entry.id==="required_agents"),dispatched=new Set,missing=new Set,warnings=[];for(let entry of report.entries){for(let actor of entry.agentsDispatched)dispatched.add(actor);for(let actor of entry.agentsMissing)missing.add(actor);for(let warning of entry.warnings)if(warnings.length<MAX_WARNINGS&&!warnings.includes(warning))warnings.push(warning)}if(requiredAgentsEntry){dispatched.clear();for(let actor of requiredAgentsEntry.agentsDispatched)dispatched.add(actor)}return{success:report.outcome==="pass",phase:report.phase,status:report.outcome==="pass"?"success":firstFailure?.code==="REQUIRED_AGENTS_MISSING"?"incomplete":"blocked",...firstFailure?{reason:firstFailure.code,message:firstFailure.detail}:{},agentsDispatched:[...dispatched].sort(),agentsMissing:[...missing].sort(),warnings,gate_report:report,...recoveryGuidance?{recovery_guidance:recoveryGuidance}:{},...report.entries.some((entry)=>entry.phase_council_required)?{phase_council_required:!0}:{},...report.entries.some((entry)=>entry.final_council_required)?{final_council_required:!0}:{},...retrospectiveEntry?.retrospective_gate?{retrospective_gate:retrospectiveEntry.retrospective_gate}:{}}}import{createHash as createHash101}from"node:crypto";import*as fs197 from"node:fs";import*as path325 from"node:path";var MAX_SNAPSHOT_FILES=512,MAX_SNAPSHOT_ENTRIES=2048,MAX_SNAPSHOT_BYTES=16777216,INPUTS=[".swarm/evidence",".swarm/spec.md",".swarm/knowledge-receipts-v2.jsonl","specs","openspec/specs","openspec/changes"];function compareUtf8(left,right){return Buffer.compare(Buffer.from(left,"utf8"),Buffer.from(right,"utf8"))}function isContained3(root,candidate2){let relative82=path325.relative(root,candidate2);return relative82===""||relative82!==".."&&!relative82.startsWith(`..${path325.sep}`)&&!path325.isAbsolute(relative82)}function computePhaseEvidenceSnapshot(directory){let root=fs197.realpathSync(directory),entries2=[],totalBytes=0,visitedEntries=0,visit=(absolute)=>{if(!isContained3(root,absolute))throw Error("PHASE_SNAPSHOT_PATH_ESCAPE");let stat24;try{stat24=fs197.lstatSync(absolute)}catch(error93){if(error93.code==="ENOENT")return;throw error93}if(stat24.isSymbolicLink())throw Error(`PHASE_SNAPSHOT_UNSAFE_PATH: ${path325.relative(root,absolute)}`);if(stat24.isDirectory()){let names=[],handle=fs197.opendirSync(absolute);try{for(;;){let entry=handle.readSync();if(!entry)break;if(visitedEntries+=1,visitedEntries>MAX_SNAPSHOT_ENTRIES)throw Error("PHASE_SNAPSHOT_ENTRY_LIMIT");names.push(entry.name)}}finally{handle.closeSync()}for(let name of names.sort(compareUtf8))visit(path325.join(absolute,name));return}if(!stat24.isFile())throw Error(`PHASE_SNAPSHOT_NON_REGULAR: ${path325.relative(root,absolute)}`);if(entries2.length>=MAX_SNAPSHOT_FILES)throw Error("PHASE_SNAPSHOT_FILE_LIMIT");if(totalBytes+=stat24.size,totalBytes>MAX_SNAPSHOT_BYTES)throw Error("PHASE_SNAPSHOT_BYTE_LIMIT");let descriptor=fs197.openSync(absolute,fs197.constants.O_RDONLY|(fs197.constants.O_NOFOLLOW??0));try{let opened=fs197.fstatSync(descriptor);if(!opened.isFile()||opened.dev!==stat24.dev||opened.ino!==stat24.ino||opened.size!==stat24.size)throw Error("PHASE_SNAPSHOT_CONCURRENT_MUTATION");let bytes=fs197.readFileSync(descriptor),after=fs197.fstatSync(descriptor);if(after.size!==opened.size||after.mtimeMs!==opened.mtimeMs||after.ctimeMs!==opened.ctimeMs)throw Error("PHASE_SNAPSHOT_CONCURRENT_MUTATION");entries2.push({path:path325.relative(root,absolute).replaceAll("\\","/"),sha256:createHash101("sha256").update(bytes).digest("hex"),bytes:bytes.byteLength})}finally{fs197.closeSync(descriptor)}};for(let relative82 of INPUTS)visit(path325.join(root,...relative82.split("/")));return entries2.sort((left,right)=>compareUtf8(left.path,right.path)),createHash101("sha256").update(JSON.stringify({schemaVersion:1,entries:entries2})).digest("hex")}init_resolve_working_directory();var phaseCompleteReceiptInternals={recordPhaseCloseIntent,commitPhaseClosed},phaseCompleteCommitInternals={savePlan:(...args2)=>savePlan(...args2)},phaseCompletePreflightInternals={runCompletionVerifyGate,runDriftGate,runHallucinationGate,runMutationGate,runPhaseCouncilGate,runArchitectureSupervisorGate,runFinalReviewGate,runFinalCouncilGate};function buildMissingAgentRecoveryGuidance(input){if(input.missing.length===0)return;let steps=[`Dispatch the missing required role${input.missing.length===1?"":"s"} (${input.missing.join(", ")}) and retry phase_complete after each Task returns a successful, non-empty result.`];if(input.docsAddedByConfig&&input.missing.includes("docs"))steps.push("If this phase genuinely has no documentation obligation, set phase_complete.require_docs to false in opencode-swarm configuration; that setting is independent of the QA gate profile.");if(!input.docsPlanReadable&&input.missing.includes("docs"))steps.push("A readable plan is required to bind durable docs participation. Restore or rebuild .swarm/plan.json/.swarm/plan.md (or recover from .swarm/plan-export/) before re-dispatching docs, then retry phase_complete.");if(input.docsEvidenceStatus==="corrupt")steps.push("The readable docs-participation projection is corrupt; a genuine docs re-dispatch will quarantine the original bytes and rebuild it safely.");else if(input.docsEvidenceStatus==="unreadable"||input.docsEvidenceStatus==="oversized")steps.push("The docs-participation projection needs operator repair or archival before a re-dispatch can persist new proof.");if(input.missing.includes("docs")&&input.docsEvidenceStatus==="missing")steps.push("No prior durable docs-participation receipt was found (this can happen after a plugin upgrade or a cleared evidence store). A fresh docs Task dispatch writes a new durable completion receipt and is the canonical recovery path.");if(input.policy==="warn")steps.push("The configured warn policy allows closure with a warning, but it does not create participation proof.");else steps.push('Last resort: if the missing role obligation genuinely cannot be satisfied in this environment, set phase_complete.policy to "warn" in opencode-swarm configuration. This weakens enforcement for every missing role and does NOT create durable participation proof, so only use it when the obligation cannot be met.');return steps.join(" ")}function safeWarn(message,error93){try{warn(message,error93 instanceof Error?error93.message:String(error93))}catch{}}var MAX_OUTPUT_BYTES7=512000,TASK_GATE_INFERABLE_AGENTS=new Set(["coder","reviewer","test_engineer"]);function canInferMissingAgentsFromTaskGates(agentsMissing){return agentsMissing.every((agent)=>TASK_GATE_INFERABLE_AGENTS.has(agent))}async function allCompletedTasksHavePassedGateEvidence(directory,tasks){for(let task2 of tasks){if(task2.status!=="completed")return!1;if(!await hasPassedAllGates(directory,task2.id))return!1}return tasks.length>0}function collectCrossSessionDispatchedAgents(phaseReferenceTimestamp,callerSessionId){let agents=new Set,contributorSessionIds=[],callerSession=swarmState.agentSessions.get(callerSessionId);if(callerSession){if(contributorSessionIds.push(callerSessionId),callerSession.phaseAgentsDispatched)for(let agent of callerSession.phaseAgentsDispatched)agents.add(agent);for(let delegation of _getDelegationsSince(callerSessionId,phaseReferenceTimestamp))agents.add(stripKnownSwarmPrefix(delegation.from)),agents.add(stripKnownSwarmPrefix(delegation.to))}for(let[sessionId,session]of swarmState.agentSessions){if(sessionId===callerSessionId)continue;let hasRecentToolCalls=session.lastToolCallTime>=phaseReferenceTimestamp,hasRecentDelegations=swarmState.delegationChains.get(sessionId)?.some((d)=>d.timestamp>=phaseReferenceTimestamp)??!1,hasRestoredAgents=(session.phaseAgentsDispatched?.size??0)>0&&session.lastPhaseCompleteTimestamp===phaseReferenceTimestamp;if(hasRecentToolCalls||hasRecentDelegations||hasRestoredAgents){if(contributorSessionIds.push(sessionId),session.phaseAgentsDispatched)for(let agent of session.phaseAgentsDispatched)agents.add(agent);for(let delegation of _getDelegationsSince(sessionId,phaseReferenceTimestamp))agents.add(stripKnownSwarmPrefix(delegation.from)),agents.add(stripKnownSwarmPrefix(delegation.to))}}return{agents,contributorSessionIds}}function _getDelegationsSince(sessionID,sinceTimestamp){let chain=swarmState.delegationChains.get(sessionID);if(!chain)return[];if(sinceTimestamp===0)return chain;return chain.filter((entry)=>entry.timestamp>sinceTimestamp)}function isValidRetroEntry(entry,phase){return entry.type==="retrospective"&&"phase_number"in entry&&entry.phase_number===phase&&"verdict"in entry&&(entry.verdict==="pass"||entry.verdict==="fail")}async function executePhaseComplete(args2,workingDirectory,directory,_runtime={}){let phase=Number(args2.phase),summary=args2.summary,sessionID=args2.sessionID;if(Number.isNaN(phase)||phase<1||!Number.isFinite(phase)||!Number.isInteger(phase))return JSON.stringify({success:!1,phase,status:"blocked",message:"Invalid phase number",agentsDispatched:[],warnings:["Phase must be a positive number"]},null,2);if(!sessionID)return JSON.stringify({success:!1,phase,message:"Session ID is required",agentsDispatched:[],warnings:["sessionID parameter is required for phase completion tracking"]},null,2);let phaseReferenceTimestamp=ensureAgentSession(sessionID).lastPhaseCompleteTimestamp??0,warnings=[];if(hasActiveTurboMode(sessionID))warnings.push(`Turbo mode active — skipped completion-verify, drift-verifier, hallucination-guard, mutation-gate, and phase-council gates for phase ${phase}.`);let crossSessionResult=collectCrossSessionDispatchedAgents(phaseReferenceTimestamp,sessionID),agentsDispatched=Array.from(crossSessionResult.agents).sort(),dir=workingDirectory||directory,{config:config3}=loadPluginConfigWithMeta(dir),phaseCompleteConfig;try{phaseCompleteConfig=PhaseCompleteConfigSchema.parse(config3.phase_complete??{})}catch(parseError){return JSON.stringify({success:!1,phase,status:"incomplete",message:`Invalid phase_complete configuration: ${parseError instanceof Error?parseError.message:"Unknown error"}`,agentsDispatched,agentsMissing:[],warnings:["Configuration validation failed"]},null,2)}if(phaseCompleteConfig.enabled===!1){let disabledReport=await collectPhaseGateReport({phase,checks:["critical_directives","retrospective","completion_verify","drift","hallucination","mutation","phase_council","architecture_supervisor","final_review","final_council","full_auto_approval","lean_turbo_readiness","required_agents","snapshot_identity"].map((id)=>({id,responsibleActor:"architect",applicable:!1,notApplicableDetail:"phase completion enforcement is disabled",run:async()=>({blocked:!1,agentsDispatched:[],agentsMissing:[],warnings:[]})}))});return JSON.stringify({success:!0,phase,status:"disabled",message:`Phase ${phase} complete (enforcement disabled)`,agentsDispatched,agentsMissing:[],warnings:[],gate_report:disabledReport},null,2)}let receiptPlan=await loadPlan(dir).catch(()=>null),receiptPhaseLabel=receiptPlan?extractCurrentPhaseFromPlan(receiptPlan)??`Phase ${receiptPlan.current_phase??phase}`:`Phase ${phase}`,knowledgeEnabled=config3.knowledge?.enabled!==!1,retroFound=!1,retroEntry=null,invalidSchemaErrors=[],loadedRetroTaskId=null,loadedRetroBundle=null,retrospectiveGate={schema_valid:!1,gate_pass:!1},primaryRetroTaskId=`retro-${phase}`,preflightNowMs=Date.now(),gateCtx={phase,dir,sessionID,pluginConfig:config3,agentsDispatched,safeWarn,loadedRetroBundle,loadedRetroTaskId,preflightNowMs},passGate=(extra={})=>({blocked:!1,agentsDispatched,agentsMissing:[],warnings:[],...extra}),preflightChecks=[];preflightChecks.push({id:"critical_directives",responsibleActor:"architect",applicable:knowledgeEnabled,notApplicableDetail:"knowledge directives are disabled",run:async()=>{let requestedAccept=Array.isArray(args2.acceptViolations)?args2.acceptViolations.filter((value)=>typeof value==="string"&&value.length>0):[];if(requestedAccept.length>0){let callerAgent=args2.callerAgent??swarmState.activeAgent.get(sessionID)??"architect";if(stripKnownSwarmPrefix(callerAgent).toLowerCase()!=="architect")return{...passGate(),blocked:!0,reason:"OVERRIDE_DENIED_NON_ARCHITECT",message:"accept_violations is architect-only and cannot be committed by this caller."};let justification=typeof args2.acceptViolationsJustification==="string"?args2.acceptViolationsJustification.trim():"";return{...passGate(),blocked:!0,reason:justification.length>=10?"DIRECTIVE_OVERRIDE_SEPARATE_ACTION_REQUIRED":"OVERRIDE_REQUIRES_JUSTIFICATION",message:justification.length>=10?"Directive overrides are separate audited evidence writes. Record the override, then retry phase_complete without accept_violations.":"accept_violations requires at least 10 characters of substantive justification.",recovery:{kind:"tool",action:"record_directive_override",args:{directive_ids:requestedAccept,justification,phase}}}}let directiveGate=await evaluatePhaseCriticalDirectives({directory:dir,sessionId:sessionID,phaseLabel:receiptPhaseLabel});if(!directiveGate.blocked)return passGate();return{...passGate(),blocked:!0,reason:directiveGate.failedClosed?"DIRECTIVE_GATE_FAILED_CLOSED":"UNRESOLVED_CRITICAL_DIRECTIVES",message:directiveGate.failedClosed?"Critical-directive gate could not read authoritative receipt state; failing closed.":formatDirectiveBlockMessage(directiveGate.unresolved),unresolved_directives:directiveGate.unresolved,..."recovery"in directiveGate&&directiveGate.recovery&&typeof directiveGate.recovery==="object"?{recovery:directiveGate.recovery}:{}}}}),preflightChecks.push({id:"retrospective",responsibleActor:"architect",run:async()=>{let retroResult=await loadEvidence(dir,primaryRetroTaskId,{migrate:!1}),candidates=[];if(retroResult.status==="found")candidates.push({taskId:primaryRetroTaskId,bundle:retroResult.bundle});else if(retroResult.status==="invalid_schema")invalidSchemaErrors.push(...retroResult.errors);if(candidates.length===0){let taskIds=(await listEvidenceTaskIds(dir)).filter((id)=>/^retro-\d+$/.test(id)).sort();for(let taskId of taskIds){let candidate2=await loadEvidence(dir,taskId,{migrate:!1});if(candidate2.status==="found")candidates.push({taskId,bundle:candidate2.bundle});else if(candidate2.status==="invalid_schema")invalidSchemaErrors.push(...candidate2.errors)}}for(let candidate2 of candidates){let entry=candidate2.bundle.entries?.find((item)=>isValidRetroEntry(item,phase));if(!entry)continue;if(retroFound=!0,retroEntry=entry,loadedRetroTaskId=candidate2.taskId,loadedRetroBundle=candidate2.bundle,retrospectiveGate={schema_valid:!0,gate_pass:entry.verdict==="pass",verdict:entry.verdict},gateCtx.loadedRetroTaskId=candidate2.taskId,gateCtx.loadedRetroBundle=candidate2.bundle,entry.verdict==="fail")return{...passGate(),blocked:!0,reason:"RETROSPECTIVE_FAILED",message:'The retrospective is schema-valid and truthfully records verdict "fail". Resolve the phase findings and write a new explicit verdict before retrying.',retrospective_gate:retrospectiveGate,recovery:{kind:"tool",action:"write_retro"}};return passGate({retrospective_gate:retrospectiveGate})}let schemaDetail=invalidSchemaErrors.length>0?` Schema validation failed: ${invalidSchemaErrors.slice(0,8).join("; ")}.`:"";return{...passGate(),blocked:!0,reason:invalidSchemaErrors.length>0?"RETROSPECTIVE_SCHEMA_INVALID":"RETROSPECTIVE_MISSING",message:`Phase ${phase} cannot be completed without an explicit retrospective verdict.${schemaDetail}`,retrospective_gate:retrospectiveGate,recovery:{kind:"tool",action:"write_retro",args:{phase}}}}});let turboActive=hasActiveTurboMode(sessionID),standardGateSpecs=[{id:"completion_verify",actor:"test_engineer",run:()=>phaseCompletePreflightInternals.runCompletionVerifyGate(gateCtx)},{id:"drift",actor:"critic",run:()=>phaseCompletePreflightInternals.runDriftGate(gateCtx)},{id:"hallucination",actor:"reviewer",run:()=>phaseCompletePreflightInternals.runHallucinationGate(gateCtx)},{id:"mutation",actor:"test_engineer",run:()=>phaseCompletePreflightInternals.runMutationGate(gateCtx)},{id:"phase_council",actor:"architect",run:()=>phaseCompletePreflightInternals.runPhaseCouncilGate(gateCtx)}];for(let spec of standardGateSpecs)preflightChecks.push({id:spec.id,responsibleActor:spec.actor,applicable:!turboActive,notApplicableDetail:"standard gate bypassed by active Turbo policy",run:spec.run});preflightChecks.push({id:"architecture_supervisor",responsibleActor:"architecture_supervisor",applicable:config3.architectural_supervision?.enabled===!0&&config3.architectural_supervision.mode==="gate",notApplicableDetail:"architecture supervision gate is not enabled",run:()=>phaseCompletePreflightInternals.runArchitectureSupervisorGate(gateCtx)}),preflightChecks.push({id:"final_review",responsibleActor:"reviewer",run:()=>phaseCompletePreflightInternals.runFinalReviewGate(gateCtx)}),preflightChecks.push({id:"final_council",responsibleActor:"architect",run:()=>phaseCompletePreflightInternals.runFinalCouncilGate(gateCtx)}),preflightChecks.push({id:"full_auto_approval",responsibleActor:"critic",run:async()=>{let approval=verifyFullAutoPhaseApproval(dir,sessionID,phase,config3);return approval.ok?passGate():{...passGate(),blocked:!0,reason:"FULL_AUTO_APPROVAL_REQUIRED",message:`Phase ${phase} cannot be completed: ${approval.reason??"Full-Auto v2 approval missing"}`,recovery:{kind:"user_action",action:"Task",args:{subagent_type:"critic_oversight",trigger_source:"phase_boundary",phase}}}}});let epicActiveForProject=isEpicModeActiveForProject(dir);preflightChecks.push({id:"lean_turbo_readiness",responsibleActor:"architect",applicable:hasActiveLeanTurbo(sessionID)&&!epicActiveForProject,notApplicableDetail:"Lean Turbo is inactive or Epic Mode owns readiness",run:async()=>{let leanConfig=config3?.turbo?.lean,check3=_internals270.verifyLeanTurboPhaseReady(dir,phase,sessionID,leanConfig?{phase_reviewer:leanConfig.phase_reviewer,phase_critic:leanConfig.phase_critic,integrated_diff_required:leanConfig.integrated_diff_required}:void 0);return check3.ok?passGate():{...passGate(),blocked:!0,reason:"LEAN_TURBO_PHASE_NOT_READY",message:`Phase ${phase} cannot be completed: ${check3.reason}`}}}),preflightChecks.push({id:"required_agents",responsibleActor:"architect",run:async()=>{let participationPlan=null,phaseRequiredAgents;try{participationPlan=await loadPlan(dir),phaseRequiredAgents=participationPlan?.phases.find((item)=>item.id===phase)?.required_agents}catch{participationPlan=null}let configured=[...phaseRequiredAgents??phaseCompleteConfig.required_agents],required3=[...configured];if(phaseCompleteConfig.require_docs&&!required3.includes("docs"))required3.push("docs");let docsStatus=null,durableDocsFound=!1;if(required3.includes("docs")){if(crossSessionResult.agents.delete("docs"),participationPlan){let receipt=await readPhaseParticipation(dir,participationPlan,phase,"docs");if(docsStatus=receipt.status,receipt.found)durableDocsFound=!0,crossSessionResult.agents.add("docs")}}let missing=required3.filter((role)=>!crossSessionResult.agents.has(role)),inferredFromTaskGates=[];if(missing.length>0)try{let planRaw=fs199.readFileSync(validateSwarmPath(dir,"plan.json"),"utf8"),target=JSON.parse(planRaw).phases.find((item)=>item.id===phase);if(target&&target.tasks.length>0&&canInferMissingAgentsFromTaskGates(missing)&&await allCompletedTasksHavePassedGateEvidence(dir,target.tasks))inferredFromTaskGates=[...missing],missing=[]}catch{}let recoveryGuidance=buildMissingAgentRecoveryGuidance({missing,docsAddedByConfig:phaseCompleteConfig.require_docs&&!configured.includes("docs"),docsEvidenceStatus:docsStatus,docsPlanReadable:participationPlan!==null,policy:phaseCompleteConfig.policy}),authoritativeAgents=[...crossSessionResult.agents].sort();return missing.length>0&&phaseCompleteConfig.policy==="enforce"?{...passGate(),blocked:!0,reason:"REQUIRED_AGENTS_MISSING",message:`Phase ${phase} is missing required agents: ${missing.join(", ")}. ${recoveryGuidance}`,agentsMissing:missing,agentsDispatched:authoritativeAgents,recovery_guidance:recoveryGuidance,recovery:{kind:"user_action",action:"Task",args:{agents:missing}}}:passGate({agentsDispatched:durableDocsFound?[...new Set([...authoritativeAgents,"docs"])].sort():authoritativeAgents,recovery_guidance:recoveryGuidance,agentsMissing:missing,warnings:[...durableDocsFound?[`Recovered durable docs participation proof for phase ${phase}.`]:[],...inferredFromTaskGates.length>0?[`Agent dispatch fallback: all completed tasks in phase ${phase} have durable passing gate evidence. Clearing missing agents: ${inferredFromTaskGates.join(", ")}.`]:[],...missing.length>0?[`Warning: phase ${phase} missing required agents: ${missing.join(", ")} (advisory because phase_complete.policy=warn).`]:[]]})}}),preflightChecks.push({id:"snapshot_identity",responsibleActor:"architect",run:async()=>{let plan=await loadPlan(dir),structureHash=plan?computePlanStructureHash(plan):"plan:none",policyHash=createHash102("sha256").update(JSON.stringify(config3)).digest("hex"),evidenceHash=computePhaseEvidenceSnapshot(dir);return passGate({evidenceRefs:[`plan-structure:${structureHash}`,`policy:${policyHash}`,`phase-evidence:${evidenceHash}`]})}});let preflightReport=await collectPhaseGateReport({phase,checks:preflightChecks});if(preflightReport.outcome==="block")return JSON.stringify(formatPhaseGateCompatibility(preflightReport),null,2);for(let entry of preflightReport.entries)warnings.push(...entry.warnings);let acceptedRetro={found:retroFound,entry:retroEntry,taskId:loadedRetroTaskId,bundle:loadedRetroBundle},phaseRecoveryGuidance=preflightReport.entries.find((entry)=>entry.id==="required_agents"&&entry.recoveryGuidance)?.recoveryGuidance,phaseCommitAgent="phase-complete";for(let[,activeAgent]of swarmState.activeAgent){phaseCommitAgent=activeAgent;break}let planLockTaskId=`phase-complete-plan-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,phasePlanLock;try{phasePlanLock=await tryAcquireLock(dir,"plan.json",phaseCommitAgent,planLockTaskId)}catch(error93){let detail=error93 instanceof Error?error93.message:String(error93);return JSON.stringify({success:!1,phase,status:"incomplete",reason:"PHASE_COMMIT_LOCK_ERROR",message:`Failed to acquire the guarded phase commit lock: ${detail}`,agentsDispatched,agentsMissing:[],warnings,gate_report:preflightReport,errors:[`Phase commit lock acquisition failed: ${detail}`],recovery_guidance:"Resolve the filesystem or lock-directory error, then retry phase_complete. No phase transition or completion event was committed.",recovery:{kind:"retry",action:"phase_complete"}})}if(!phasePlanLock.acquired){let lockOwner=phasePlanLock.existing?.agent??"another agent";return JSON.stringify({success:!1,phase,status:"incomplete",reason:"PHASE_COMMIT_LOCKED",message:`Plan write is locked by ${lockOwner}.`,agentsDispatched,agentsMissing:[],warnings,gate_report:preflightReport,errors:[`Concurrent plan write detected; lock is held by ${lockOwner}.`],recovery_guidance:"Wait for the current plan writer to finish, then retry phase_complete. No phase transition or completion event was committed.",recovery:{kind:"retry",action:"phase_complete"}})}try{let lockedPreflight=await collectPhaseGateReport({phase,checks:preflightChecks});if(lockedPreflight.outcome!=="pass"||lockedPreflight.reportHash!==preflightReport.reportHash)return JSON.stringify({success:!1,phase,status:"blocked",reason:"PHASE_PREFLIGHT_STALE",message:"Phase evidence, plan identity, or policy changed after preflight. No phase transition or post-commit side effect was written.",agentsDispatched,agentsMissing:[],warnings,gate_report:lockedPreflight,recovery:{kind:"retry",action:"phase_complete"}});let plan=await loadPlan(dir);if(plan?._ledgerReplayStale===!0){let staleReason=plan._ledgerReplayStaleReason??"unknown reason";return JSON.stringify({success:!1,phase,status:"incomplete",reason:"PHASE_PLAN_STALE",message:`Plan write refused: plan.json is stale from a failed ledger replay (${staleReason}). Refusing to complete phase ${phase} against a known-stale plan.`,agentsDispatched,agentsMissing:[],warnings,gate_report:lockedPreflight,errors:[`Stale plan from failed ledger replay: ${staleReason}`],recovery_guidance:"The ledger replay failed and no critic-approved snapshot was available, so loadPlan fell back to a stale plan.json. Do NOT retry blindly. Recover first: re-verify the plan (re-run completion verification), reset the session, or restore from the latest checkpoint under .swarm/plan-export/, then retry phase_complete.",_ledgerReplayStaleReason:staleReason})}if(!plan&&await ledgerExists(dir))plan=await replayFromLedger(dir);let phaseObject=plan?plan.phases.find((candidate2)=>candidate2.id===phase):void 0;if(plan){if(!phaseObject)return JSON.stringify({success:!1,phase,status:"incomplete",reason:"PHASE_NOT_IN_PLAN",message:`Phase ${phase} is not present in the authoritative plan.`,agentsDispatched,agentsMissing:[],warnings,gate_report:lockedPreflight})}else if(fs199.existsSync(validateSwarmPath(dir,"plan.json")))return JSON.stringify({success:!1,phase,status:"incomplete",reason:"PHASE_PLAN_UNREADABLE",message:"Plan exists but could not be read or rebuilt from the ledger; no phase transition was committed.",agentsDispatched,agentsMissing:[],warnings,gate_report:lockedPreflight});if(knowledgeEnabled){let closeIntent=await phaseCompleteReceiptInternals.recordPhaseCloseIntent(dir,receiptPhaseLabel,sessionID);if(!closeIntent.ok)return JSON.stringify({success:!1,phase,status:"incomplete",reason:"PHASE_CLOSE_INTENT_FAILED",message:"Phase completion blocked: could not persist receipt phase-close intent.",agentsDispatched,agentsMissing:[],warnings,gate_report:lockedPreflight,errors:[closeIntent.detail],recovery:{kind:"retry",action:"phase_complete"}})}let commitPreflight=await collectPhaseGateReport({phase,checks:preflightChecks});if(commitPreflight.outcome!=="pass")return JSON.stringify({success:!1,phase,status:"blocked",reason:"PHASE_PREFLIGHT_STALE",message:"Phase evidence or policy changed before the authoritative transition. No plan transition or completion event was written.",agentsDispatched,agentsMissing:[],warnings,gate_report:commitPreflight,recovery:{kind:"retry",action:"phase_complete"}});let commitEvidenceRef=commitPreflight.entries.find((entry)=>entry.id==="snapshot_identity")?.evidenceRefs.find((reference)=>reference.startsWith("phase-evidence:")),commitPolicyRef=commitPreflight.entries.find((entry)=>entry.id==="snapshot_identity")?.evidenceRefs.find((reference)=>reference.startsWith("policy:")),expectedCommitEvidenceHash=commitEvidenceRef?.slice(15),expectedCommitPolicyHash=commitPolicyRef?.slice(7);if(!expectedCommitEvidenceHash||!expectedCommitPolicyHash)return JSON.stringify({success:!1,phase,status:"blocked",reason:"PHASE_PREFLIGHT_STALE",message:"The commit-boundary evidence identity was unavailable. No plan transition or completion event was written.",agentsDispatched,agentsMissing:[],warnings,gate_report:commitPreflight,recovery:{kind:"retry",action:"phase_complete"}});if(plan&&phaseObject&&!["complete","completed","closed"].includes(phaseObject.status)){phaseObject.status="complete";try{let saveDurability=await phaseCompleteCommitInternals.savePlan(dir,plan,{preserveCompletedStatuses:!0,planLockAlreadyHeld:!0,preCommitCheck:()=>{let currentPolicyHash=createHash102("sha256").update(JSON.stringify(loadPluginConfigWithMeta(dir).config)).digest("hex");if(computePhaseEvidenceSnapshot(dir)!==expectedCommitEvidenceHash||currentPolicyHash!==expectedCommitPolicyHash)throw Error("PHASE_PREFLIGHT_STALE: evidence changed at the authoritative transition boundary")}});if(saveDurability.durability==="incomplete")warnings.push(`Plan saved with incomplete durability; degraded surfaces: ${saveDurability.degraded_surfaces.join(", ")}`+(saveDurability.md_write_error?` (${saveDurability.md_write_error})`:""))}catch(error93){if(error93 instanceof Error&&error93.message.startsWith("PHASE_PREFLIGHT_STALE:"))return JSON.stringify({success:!1,phase,status:"blocked",reason:"PHASE_PREFLIGHT_STALE",message:"Phase evidence changed at the authoritative transition boundary. No plan transition or completion event was written.",agentsDispatched,agentsMissing:[],warnings,gate_report:commitPreflight,recovery:{kind:"retry",action:"phase_complete"}});throw error93}await takeSnapshotEvent(dir,plan).catch(()=>{return})}}finally{if(phasePlanLock.lock._release)await phasePlanLock.lock._release().catch((error93)=>{warn("[phase_complete] Plan lock release failed:",error93 instanceof Error?error93.message:String(error93))})}if(knowledgeEnabled){let receiptClose=await phaseCompleteReceiptInternals.commitPhaseClosed(dir,receiptPhaseLabel,sessionID);if(!receiptClose.ok)return JSON.stringify({success:!1,phase,status:"incomplete",reason:"PHASE_RECEIPT_CLOSE_PENDING",message:"Plan phase closed, but receipt lifecycle closure is pending reconciliation; retry phase_complete.",agentsDispatched,agentsMissing:[],warnings:[...warnings,receiptClose.detail],gate_report:preflightReport,recovery:{kind:"retry",action:"phase_complete"}})}let requiredAgentsEntry=preflightReport.entries.find((entry)=>entry.id==="required_agents");if(requiredAgentsEntry)agentsDispatched.splice(0,agentsDispatched.length,...requiredAgentsEntry.agentsDispatched);let knowledgeConfig;try{knowledgeConfig=KnowledgeConfigSchema.parse(config3.knowledge??{})}catch(parseErr){warnings.push(`Knowledge config validation failed: ${String(parseErr)}`),knowledgeConfig=KnowledgeConfigSchema.parse({})}if(acceptedRetro.found&&acceptedRetro.entry?.lessons_learned&&acceptedRetro.entry.lessons_learned.length>0)try{let projectName=path327.basename(dir),curationResult=await curateAndStoreSwarm(acceptedRetro.entry.lessons_learned,projectName,{phase_number:phase},dir,knowledgeConfig,{llmDelegate:createCuratorLLMDelegate(dir,"phase",sessionID),enrichmentQuota:{maxCalls:knowledgeConfig.enrichment.max_calls_per_day,window:knowledgeConfig.enrichment.quota_window}});if(curationResult&&curationResult.stored+curationResult.reinforced+curationResult.quarantined+curationResult.rejected>0){let sessionState=swarmState.agentSessions.get(sessionID);if(sessionState)pushAdvisory(sessionState,`[CURATOR] Knowledge curation: ${curationResult.stored} stored, ${curationResult.reinforced} reinforced, ${curationResult.skipped} skipped, ${curationResult.rejected} rejected, ${curationResult.quarantined} quarantined (unactionable).`)}}catch(error93){safeWarn("[phase_complete] Failed to curate lessons from retrospective:",error93)}let complianceWarnings=[];try{let curatorConfig=CuratorConfigSchema.parse(config3.curator??{});if(curatorConfig.enabled&&curatorConfig.phase_enabled){let llmDelegate=createCuratorLLMDelegate(dir,"phase",sessionID??void 0),curatorResult=await runCuratorPhase(dir,phase,agentsDispatched,curatorConfig,{},llmDelegate);{let scopeContent=curatorResult.digest?.summary??`Phase ${phase} curator analysis`,complianceWarnings2=curatorResult.compliance.filter((c)=>c.severity==="warning"),receipt=complianceWarnings2.length>0?buildRejectedReceipt({agent:"curator",scopeContent,scopeDescription:"phase-digest",blockingFindings:complianceWarnings2.map((c)=>({location:`phase-${c.phase}`,summary:c.description,severity:c.type==="missing_reviewer"?"high":"medium"})),evidenceReferences:[],passConditions:["resolve all compliance warnings before phase completion"]}):buildApprovedReceipt({agent:"curator",scopeContent,scopeDescription:"phase-digest",checkedAspects:["phase_compliance","knowledge_recommendations","phase_digest"],validatedClaims:[`phase: ${phase}`,`agents_dispatched: ${agentsDispatched.length}`,`knowledge_recommendations: ${curatorResult.knowledge_recommendations.length}`]});persistReviewReceipt(dir,receipt).catch(()=>{})}let knowledgeResult=await applyCuratorKnowledgeUpdates(dir,curatorResult.knowledge_recommendations,knowledgeConfig),driftAdvisoryPushedThisRun=!1;try{let{runDeterministicDriftCheck:runDeterministicDriftCheck2}=await Promise.resolve().then(() => (init_curator_drift(),exports_curator_drift));await runDeterministicDriftCheck2(dir,phase,curatorResult,curatorConfig,(message2)=>{let sessionState=swarmState.agentSessions.get(sessionID);if(sessionState)pushAdvisory(sessionState,message2),driftAdvisoryPushedThisRun=!0})}catch{}let callerSessionState=swarmState.agentSessions.get(sessionID);if(callerSessionState){let digestSummary=curatorResult.digest?.summary?curatorResult.digest.summary.slice(0,200):"Phase analysis complete",complianceNote=curatorResult.compliance.length>0?` (${curatorResult.compliance.length} compliance observation(s))`:"",analyzeHint=curatorResult.knowledge_recommendations.length>0?" Call curator_analyze with recommendations to apply knowledge updates from this phase.":"";if(digestSummary!=="Phase analysis complete")pushAdvisory(callerSessionState,`[CURATOR] Phase ${phase} digest: ${digestSummary}${complianceNote}. Knowledge: ${knowledgeResult.applied} applied, ${knowledgeResult.skipped} skipped.${analyzeHint}`);try{let{readPriorDriftReports:readPriorDriftReports2}=await Promise.resolve().then(() => (init_curator_drift(),exports_curator_drift)),phaseReport=(await readPriorDriftReports2(dir)).filter((r)=>r.phase===phase).pop();if(phaseReport&&phaseReport.drift_score>0&&!driftAdvisoryPushedThisRun)pushAdvisory(callerSessionState,`[CURATOR DRIFT DETECTED (phase ${phase}, score ${phaseReport.drift_score})]: Prior drift report found on disk. Consider running critic_drift_verifier before phase completion to get a proper drift review. Review drift report for phase ${phase} and address spec alignment if applicable.`)}catch{}}if(curatorResult.compliance.length>0&&!curatorConfig.suppress_warnings)complianceWarnings=curatorResult.compliance.map((obs)=>`[${obs.severity.toUpperCase()}] ${obs.description}`).slice(0,5)}}catch(curatorError){safeWarn("[phase_complete] Curator pipeline error (non-blocking):",curatorError)}try{if(config3.design_docs?.enabled===!0){let outDir=config3.design_docs.out_dir??"docs",{runDesignDocDriftCheck:runDesignDocDriftCheck2}=await Promise.resolve().then(() => (init_design_doc_drift(),exports_design_doc_drift)),docReport=await runDesignDocDriftCheck2(dir,phase,outDir);if(docReport?.verdict==="DOC_STALE"){let callerSessionState=swarmState.agentSessions.get(sessionID);if(callerSessionState){let staleIds=docReport.stale_sections.map((s)=>s.section_id).slice(0,8).join(", ");pushAdvisory(callerSessionState,`[DESIGN-DOC DRIFT (phase ${phase})]: ${docReport.stale_sections.length} design-doc section(s) are stale (${staleIds}). Run /swarm design-docs --update to sync ${outDir}/ and append a design-changelog entry. Advisory only — does not block completion.`)}}}}catch(docDriftError){safeWarn("[phase_complete] Design-doc drift check error (non-blocking):",docDriftError)}let floorOptions={floorAction:knowledgeConfig.confidence_floor_action,floorMinOutcomes:knowledgeConfig.confidence_floor_min_outcomes,floorSignalThreshold:knowledgeConfig.confidence_floor_signal_threshold};try{let feedbackResult=await applySkillUsageFeedback(dir,{floorOptions});if(feedbackResult.processed>0){let sessionState=swarmState.agentSessions.get(sessionID);if(sessionState)pushAdvisory(sessionState,`[FEEDBACK] Skill usage feedback: ${feedbackResult.processed} skills processed, ${feedbackResult.bumps} confidence updates applied.`)}}catch(skillUsageError){safeWarn("[phase_complete] Skill usage feedback error (non-blocking):",skillUsageError)}try{pruneSkillUsageLog(dir,500)}catch(skillPruneError){safeWarn("[phase_complete] Skill usage log pruning error (non-blocking):",skillPruneError)}try{let verdictMarkerPath=validateSwarmPath(dir,"verdict-feedback-last-processed.json"),verdictSinceTimestamp,verdictSinceEventId;try{let markerData=JSON.parse(fs199.readFileSync(verdictMarkerPath,"utf-8"));verdictSinceTimestamp=markerData.lastProcessedTimestamp,verdictSinceEventId=markerData.lastProcessedEventId}catch{}let{applyKnowledgeVerdictFeedback:applyKnowledgeVerdictFeedback2}=await Promise.resolve().then(() => (init_knowledge_events(),exports_knowledge_events)),verdictResult=await applyKnowledgeVerdictFeedback2(dir,{sinceTimestamp:verdictSinceTimestamp,sinceEventId:verdictSinceEventId,floorOptions});if(verdictResult.lastProcessedTimestamp)try{fs199.writeFileSync(verdictMarkerPath,JSON.stringify({lastProcessedTimestamp:verdictResult.lastProcessedTimestamp,lastProcessedEventId:verdictResult.lastProcessedEventId}),"utf-8")}catch{}if(verdictResult.bumps>0){let sessionState=swarmState.agentSessions.get(sessionID);if(sessionState)pushAdvisory(sessionState,`[FEEDBACK] Knowledge verdict feedback: ${verdictResult.processed} entries processed, ${verdictResult.bumps} confidence updates applied.`)}}catch(verdictError){safeWarn("[phase_complete] Knowledge verdict feedback error (non-blocking):",verdictError)}let agentsMissing=[...requiredAgentsEntry?.agentsMissing??[]],VALID_TASK_COMPLEXITY=["trivial","simple","moderate","complex"],firstEntry=acceptedRetro.bundle?.entries?.[0];if(acceptedRetro.taskId!==primaryRetroTaskId&&acceptedRetro.taskId?.startsWith("retro-")&&acceptedRetro.bundle?.schema_version==="1.0.0"&&firstEntry?.task_complexity&&VALID_TASK_COMPLEXITY.includes(firstEntry.task_complexity))warnings.push(`Retrospective data for phase ${phase} may have been automatically migrated to current schema format.`);let success3=!0,status2=agentsMissing.length>0?"warned":"success",safeSummary=summary?.trim().slice(0,500),message=safeSummary?`Phase ${phase} completed: ${safeSummary}`:`Phase ${phase} completed`,result={success:success3,phase,status:status2,message,agentsDispatched,agentsMissing,warnings,gate_report:preflightReport,...phaseRecoveryGuidance?{recovery_guidance:phaseRecoveryGuidance}:{}},hasPlan=!1;try{hasPlan=fs199.existsSync(validateSwarmPath(dir,"plan.json"))}catch{}if(!hasPlan&&!crossSessionResult.agents.has("reviewer")&&!crossSessionResult.agents.has("test_engineer"))warnings.push(`⚠️ Plan-free phase ${phase}: no independent reviewer or test_engineer dispatch detected. Code changes in plan-free sessions should have independent review. Consider dispatching reviewer + test_engineer before completing future plan-free phases.`);if(!hasPlan)warnings.push(`Warning: failed to update plan.json phase status because no authoritative plan was found; phase ${phase} completed in plan-free mode.`);if(acceptedRetro.found&&acceptedRetro.entry?.lessons_learned&&acceptedRetro.entry.lessons_learned.length>0)await updateRetrievalOutcome(dir,`Phase ${phase}`,success3).catch(()=>{});if(phaseCompleteConfig.regression_sweep?.enforce)try{let planPath=validateSwarmPath(dir,"plan.json"),planRaw=fs199.readFileSync(planPath,"utf-8"),targetPhase=JSON.parse(planRaw).phases.find((p)=>p.id===phase);if(targetPhase){let sweepFound=!1;for(let task2 of targetPhase.tasks){let taskEvidenceResult=await loadEvidence(dir,task2.id);if(taskEvidenceResult.status==="found"){let entries2=taskEvidenceResult.bundle.entries??[];for(let entry of entries2)if(entry.regression_sweep!==void 0){sweepFound=!0;break}}if(sweepFound)break}if(!sweepFound)warnings.push(`Warning: regression_sweep.enforce=true but no regression-sweep result found for any task in phase ${phase}. Run tests to populate regression-sweep results.`)}}catch{}let now2=Date.now(),durationMs=now2-phaseReferenceTimestamp,event={event:"phase_complete",phase,timestamp:new Date(now2).toISOString(),agents_dispatched:agentsDispatched,agents_missing:agentsMissing,status:status2,summary:safeSummary??null};try{appendCoreEventSync(dir,{...event})}catch(writeError){warnings.push(`Warning: failed to write phase complete event: ${writeError instanceof Error?writeError.message:String(writeError)}`)}if(success3){try{let skillConfig=SkillImproverConfigSchema.parse(config3.skill_improver??{});if(skillConfig.enabled&&skillConfig.trigger==="scheduled")runSkillConsolidationFireAndForget({directory:dir,config:skillConfig,source:"phase_complete",sessionId:sessionID,enrichmentQuota:{maxCalls:knowledgeConfig.enrichment.max_calls_per_day,window:knowledgeConfig.enrichment.quota_window},evaluateDrafts:!0},(consolidationResult)=>{if(!consolidationResult.started)return;let sessionState=swarmState.agentSessions.get(sessionID);if(!sessionState)return;let activatedSlugs=consolidationResult.result?.autoApply?.approved??[],activationSuffix=activatedSlugs.length>0?` and auto-activated ${activatedSlugs.length} skill(s): ${activatedSlugs.join(", ")}.`:" and auto-activated no skills.";pushAdvisory(sessionState,`[SKILL CONSOLIDATION] Scheduled skill_improver consolidation wrote ${consolidationResult.result?.proposalPath??"a proposal"}${activationSuffix}`)},(err)=>{safeWarn("[phase_complete] Scheduled skill consolidation error (non-blocking):",err)})}catch(skillConsolidationError){safeWarn("[phase_complete] Scheduled skill consolidation setup error (non-blocking):",skillConsolidationError)}try{let memoryConfig=config3.memory;if(memoryConfig?.enabled&&memoryConfig.consolidation?.enabled)runMemoryConsolidationFireAndForget({directory:dir,config:memoryConfig,phase,sessionId:sessionID},void 0,(err)=>{safeWarn("[phase_complete] Memory consolidation error (non-blocking):",err)})}catch(memoryConsolidationError){safeWarn("[phase_complete] Memory consolidation setup error (non-blocking):",memoryConsolidationError)}for(let contributorSessionId of crossSessionResult.contributorSessionIds){let contributorSession=swarmState.agentSessions.get(contributorSessionId);if(contributorSession){if(contributorSession.phaseAgentsDispatched.size>0)contributorSession.lastCompletedPhaseAgentsDispatched=new Set(contributorSession.phaseAgentsDispatched);contributorSession.phaseAgentsDispatched=new Set,contributorSession.fullAutoInteractionCount=0,contributorSession.fullAutoDeadlockCount=0,contributorSession.fullAutoLastQuestionHash=null,contributorSession.lastPhaseCompleteTimestamp=now2;let oldPhase=contributorSession.lastPhaseCompletePhase;contributorSession.lastPhaseCompletePhase=phase,telemetry.phaseChanged(contributorSessionId,oldPhase??0,phase)}}try{if(knowledgeConfig.sweep_enabled){let swarmPath3=resolveSwarmKnowledgePath(dir);if(await sweepAgedEntries(swarmPath3,knowledgeConfig.default_max_phases),await sweepStaleTodos(swarmPath3,knowledgeConfig.todo_max_phases),knowledgeConfig.hive_enabled){let hivePath=resolveHiveKnowledgePath2();await sweepAgedEntries(hivePath,knowledgeConfig.default_max_phases),await sweepStaleTodos(hivePath,knowledgeConfig.todo_max_phases)}}}catch(err){let detail=String(err);if(detail.includes("ELOCKED"))detail="lock timeout (stale lock detected)";else if(detail.includes("ENOSPC"))detail="disk full";else if(detail.includes("EACCES"))detail="permission denied";warnings.push(`Knowledge sweep failed for phase ${phase}: ${detail}`)}}if(complianceWarnings.length>0)warnings.push(`Curator compliance: ${complianceWarnings.join("; ")}`);await flushPendingSnapshot(dir),await writeCheckpoint(dir).catch(()=>{});try{let curatorCfg=CuratorConfigSchema.parse(config3.curator??{});if(curatorCfg.enabled&&curatorCfg.postmortem_enabled){let finalPlan=await loadPlan(dir);if(finalPlan?.phases?.length){if(finalPlan.phases.every((p)=>p.status==="complete")){let{runCuratorPostMortem:runCuratorPostMortem2}=await Promise.resolve().then(() => (init_curator_postmortem(),exports_curator_postmortem)),pmResult=await runCuratorPostMortem2(dir,{llmDelegate:createCuratorLLMDelegate(dir,"postmortem",sessionID),scope:"project",sessionID});if(pmResult.success&&pmResult.summary)warnings.push(`[POST-MORTEM] ${pmResult.summary}`);if(pmResult.warnings.length>0)for(let w of pmResult.warnings)warnings.push(`[POST-MORTEM] ${w}`)}}}}catch{}let outputData={...result,timestamp:event.timestamp,duration_ms:durationMs};return _buildOutputJson(outputData)}function _buildOutputJson(outputData){let json3=JSON.stringify(outputData,null,2);if(json3.length>MAX_OUTPUT_BYTES7){let truncated={_truncated:!0,_truncation_reason:`Output exceeded MAX_OUTPUT_BYTES (${MAX_OUTPUT_BYTES7}) limit`,phase:outputData.phase,success:outputData.success,status:outputData.status,message:outputData.message,agentsDispatched:outputData.agentsDispatched?.slice(0,10),agentsMissing:outputData.agentsMissing?.slice(0,10),warnings:["(output truncated — full output exceeded size limit)"],timestamp:outputData.timestamp,duration_ms:outputData.duration_ms};json3=JSON.stringify(truncated,null,2)}return json3}function createPhaseCompleteTool(runtime={}){return createSwarmTool({description:"Mark a phase as complete and track which agents were dispatched. Used for phase completion gating and tracking. Accepts phase number and optional summary. Returns list of agents that were dispatched.",args:{phase:exports_external.number().int().min(1).describe("The phase number being completed — a positive integer (e.g., 1, 2, 3)"),summary:exports_external.string().optional().describe("Optional summary of what was accomplished in this phase"),sessionID:exports_external.string().optional().describe("Session ID for tracking state (auto-provided by plugin context)"),working_directory:exports_external.string().optional().describe("Explicit project root directory. When provided, .swarm/ is resolved relative to this path instead of the plugin context directory. Use this when CWD differs from the actual project root."),accept_violations:exports_external.array(exports_external.string()).optional().describe("DEPRECATED COMPATIBILITY INPUT. phase_complete never records directive overrides. When supplied, it fails closed with recovery instructions for the architect-only record_directive_override action."),accept_violations_justification:exports_external.string().optional().describe("Written justification retained only for deprecated compatibility input; use it with record_directive_override instead.")},execute:async(args2,directory,ctx)=>{let phaseCompleteArgs,workingDirInput;try{phaseCompleteArgs={phase:Number(args2.phase),summary:args2.summary!==void 0?String(args2.summary):void 0,sessionID:ctx?.sessionID??(args2.sessionID!==void 0?String(args2.sessionID):void 0),acceptViolations:Array.isArray(args2.accept_violations)?args2.accept_violations.map((s)=>String(s)):void 0,acceptViolationsJustification:args2.accept_violations_justification!==void 0?String(args2.accept_violations_justification):void 0,callerAgent:ctx?.agent!==void 0?String(ctx.agent):void 0},workingDirInput=args2.working_directory!==void 0?String(args2.working_directory):void 0}catch{return JSON.stringify({success:!1,phase:0,message:"Invalid arguments",agentsDispatched:[],warnings:["Failed to parse arguments"]},null,2)}let dirResult=resolveWorkingDirectory(workingDirInput,directory);if(!dirResult.success)return JSON.stringify({success:!1,phase:phaseCompleteArgs.phase,message:dirResult.message,agentsDispatched:[],warnings:[dirResult.message]},null,2);return executePhaseComplete(phaseCompleteArgs,dirResult.directory,dirResult.directory,runtime)}})}var phase_complete=createPhaseCompleteTool();init_zod();init_discovery();init_utils();init_bun_compat();init_external_tool_runner();init_create_tool();import*as fs200 from"node:fs";import*as path328 from"node:path";var MAX_OUTPUT_BYTES8=52428800,AUDIT_TIMEOUT_MS=120000;function resolveAuditCommandDefault(name){if(process.platform!=="win32")return[name];let resolved=resolveExecutableFromPath([name]);if(!resolved)return[name];let lowered=resolved.toLowerCase();if(lowered.endsWith(".cmd")||lowered.endsWith(".bat")){if(/["&|<>^!%]/.test(resolved))return[name];return["cmd.exe","/d","/s","/c",`call "${resolved}"`]}return[resolved]}var _internals273={bunSpawn,resolveAuditCommand:resolveAuditCommandDefault};function isValidEcosystem(value){return typeof value==="string"&&["auto","npm","pip","cargo","go","dotnet","ruby","dart","composer"].includes(value)}function validateArgs3(args2){if(typeof args2!=="object"||args2===null)return!0;let obj=args2;if(obj.ecosystem!==void 0&&!isValidEcosystem(obj.ecosystem))return!1;return!0}function detectEcosystems(directory){let ecosystems=[],cwd=directory;if(fs200.existsSync(path328.join(cwd,"package.json")))ecosystems.push("npm");if(fs200.existsSync(path328.join(cwd,"pyproject.toml"))||fs200.existsSync(path328.join(cwd,"requirements.txt")))ecosystems.push("pip");if(fs200.existsSync(path328.join(cwd,"Cargo.toml")))ecosystems.push("cargo");if(fs200.existsSync(path328.join(cwd,"go.mod")))ecosystems.push("go");try{if(fs200.readdirSync(cwd).some((f)=>f.endsWith(".csproj")||f.endsWith(".sln")))ecosystems.push("dotnet")}catch{}if(fs200.existsSync(path328.join(cwd,"Gemfile"))||fs200.existsSync(path328.join(cwd,"Gemfile.lock")))ecosystems.push("ruby");if(fs200.existsSync(path328.join(cwd,"pubspec.yaml")))ecosystems.push("dart");if(fs200.existsSync(path328.join(cwd,"composer.lock")))ecosystems.push("composer");return ecosystems}function auditFailureResult(ecosystem,command,error93,isToolMissing,toolMissingNote,genericNotePrefix){let message=error93 instanceof Error?error93.message:"Unknown error",base={ecosystem,command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0};if(classifySpawnFailure(error93)==="cwd-missing")return{...base,note:`${genericNotePrefix}: ${message}`};if(isToolMissing(message))return{...base,note:toolMissingNote};return{...base,note:`${genericNotePrefix}: ${message}`}}function npmAuditFailure(command,error93){return auditFailureResult("npm",command,error93,(m)=>m.includes("audit")||m.includes("command not found")||m.includes("'npm' is not recognized"),"npm audit not available - npm may not be installed","Error running npm audit")}function cargoAuditFailure(command,error93){return auditFailureResult("cargo",command,error93,(m)=>m.includes("not found")||m.includes("not recognized")||m.includes("cargo-audit"),"cargo-audit not installed. Install with: cargo install cargo-audit","Error running cargo audit")}async function runNpmAudit(directory){let command=[..._internals273.resolveAuditCommand("npm"),"audit","--json"];try{let proc=_internals273.bunSpawn(command,{stdout:"pipe",stderr:"pipe",cwd:directory,...command[0]==="cmd.exe"?{windowsVerbatimArguments:!0,killProcessTree:!0}:{}}),timeoutPromise=new Promise((resolve131)=>setTimeout(()=>resolve131("timeout"),AUDIT_TIMEOUT_MS)),result=await Promise.race([Promise.all([proc.stdout.text(),proc.stderr.text()]).then(([stdout2,stderr2])=>({stdout:stdout2,stderr:stderr2})),timeoutPromise]);if(result==="timeout")return proc.kill(),{ecosystem:"npm",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:`npm audit timed out after ${AUDIT_TIMEOUT_MS/1000}s`};let{stdout,stderr}=result;if(stdout.length>MAX_OUTPUT_BYTES8)stdout=stdout.slice(0,MAX_OUTPUT_BYTES8);let exitCode=await proc.exited;if(proc.spawnError)return npmAuditFailure(command,proc.spawnError);if(exitCode===0)return{ecosystem:"npm",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0};let jsonOutput=stdout,jsonMatch=stdout.match(/\{[\s\S]*\}/)||stderr.match(/\{[\s\S]*\}/);if(jsonMatch)jsonOutput=jsonMatch[0];let response=JSON.parse(jsonOutput),findings=[];if(response.vulnerabilities)for(let[pkgName,vuln]of Object.entries(response.vulnerabilities)){let patchedVersion=null;if(vuln.fixAvailable&&typeof vuln.fixAvailable==="object")patchedVersion=vuln.fixAvailable.version;else if(vuln.fixAvailable===!0)patchedVersion="latest";let severity2=mapNpmSeverity(vuln.severity);findings.push({package:pkgName,installedVersion:vuln.range,patchedVersion,severity:severity2,title:vuln.title||`Vulnerability in ${pkgName}`,cve:vuln.cves&&vuln.cves.length>0?vuln.cves[0]:null,url:vuln.url||null})}let criticalCount=findings.filter((f)=>f.severity==="critical").length,highCount=findings.filter((f)=>f.severity==="high").length;return{ecosystem:"npm",command,findings,criticalCount,highCount,totalCount:findings.length,clean:findings.length===0}}catch(error93){return npmAuditFailure(command,error93)}}function mapNpmSeverity(severity2){switch(severity2.toLowerCase()){case"critical":return"critical";case"high":return"high";case"moderate":return"moderate";case"low":return"low";default:return"info"}}async function runPipAudit(directory){let command=["pip-audit","--format=json"];try{let proc=bunSpawn(command,{stdout:"pipe",stderr:"pipe",cwd:directory}),timeoutPromise=new Promise((resolve131)=>setTimeout(()=>resolve131("timeout"),AUDIT_TIMEOUT_MS)),result=await Promise.race([Promise.all([proc.stdout.text(),proc.stderr.text()]).then(([stdout2,stderr2])=>({stdout:stdout2,stderr:stderr2})),timeoutPromise]);if(result==="timeout")return proc.kill(),{ecosystem:"pip",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:`pip-audit timed out after ${AUDIT_TIMEOUT_MS/1000}s`};let{stdout,stderr}=result;if(stdout.length>MAX_OUTPUT_BYTES8)stdout=stdout.slice(0,MAX_OUTPUT_BYTES8);if(await proc.exited===0&&!stdout.trim())return{ecosystem:"pip",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0};let packages=[];try{let parsed=JSON.parse(stdout);if(Array.isArray(parsed))packages=parsed;else if(parsed.dependencies)packages=parsed.dependencies}catch{if(stderr.includes("not installed")||stdout.includes("not installed")||stderr.includes("command not found"))return{ecosystem:"pip",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:"pip-audit not installed. Install with: pip install pip-audit"};return{ecosystem:"pip",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:`pip-audit output could not be parsed: ${stdout.slice(0,200)}`}}let findings=[];for(let pkg of packages)if(pkg.vulns&&pkg.vulns.length>0)for(let vuln of pkg.vulns){let severity2=vuln.aliases&&vuln.aliases.length>0?"high":"moderate";findings.push({package:pkg.name,installedVersion:pkg.version,patchedVersion:vuln.fix_versions&&vuln.fix_versions.length>0?vuln.fix_versions[0]:null,severity:severity2,title:vuln.id,cve:vuln.aliases&&vuln.aliases.length>0?vuln.aliases[0]:null,url:vuln.id.startsWith("CVE-")?`https://nvd.nist.gov/vuln/detail/${vuln.id}`:null})}let criticalCount=findings.filter((f)=>f.severity==="critical").length,highCount=findings.filter((f)=>f.severity==="high").length;return{ecosystem:"pip",command,findings,criticalCount,highCount,totalCount:findings.length,clean:findings.length===0}}catch(error93){let errorMessage3=error93 instanceof Error?error93.message:"Unknown error";if(errorMessage3.includes("not found")||errorMessage3.includes("not recognized")||errorMessage3.includes("pip-audit"))return{ecosystem:"pip",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:"pip-audit not installed. Install with: pip install pip-audit"};return{ecosystem:"pip",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:`Error running pip-audit: ${errorMessage3}`}}}async function runCargoAudit(directory){let command=[..._internals273.resolveAuditCommand("cargo"),"audit","--json"];try{let proc=_internals273.bunSpawn(command,{stdout:"pipe",stderr:"pipe",cwd:directory,...command[0]==="cmd.exe"?{windowsVerbatimArguments:!0,killProcessTree:!0}:{}}),timeoutPromise=new Promise((resolve131)=>setTimeout(()=>resolve131("timeout"),AUDIT_TIMEOUT_MS)),result=await Promise.race([Promise.all([proc.stdout.text(),proc.stderr.text()]).then(([stdout2,stderr])=>({stdout:stdout2,stderr})),timeoutPromise]);if(result==="timeout")return proc.kill(),{ecosystem:"cargo",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:`cargo audit timed out after ${AUDIT_TIMEOUT_MS/1000}s`};let{stdout,stderr:_stderr}=result;if(stdout.length>MAX_OUTPUT_BYTES8)stdout=stdout.slice(0,MAX_OUTPUT_BYTES8);let exitCode=await proc.exited;if(proc.spawnError)return cargoAuditFailure(command,proc.spawnError);if(exitCode===0)return{ecosystem:"cargo",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0};let findings=[],lines=stdout.split(`
|
|
7463
|
+
Advisory notes: ${advisoryNotes.join("; ")}`:"";return{blocked:!0,reason:"PHASE_COUNCIL_CONCERNS",message:`Phase ${phase} cannot be completed: phase council returned verdict 'CONCERNS'.${notesDetail}`,agentsDispatched,agentsMissing:[],warnings:[]}}safeWarn(`[phase_complete] Phase council returned CONCERNS for phase ${phase} — proceeding (phaseConcernsAllowComplete is enabled)`,void 0)}if(entry.verdict!=="APPROVE"&&entry.verdict!=="approve"&&entry.verdict!=="CONCERNS"&&entry.verdict!=="concerns")return{blocked:!0,reason:"PHASE_COUNCIL_INVALID",message:`Phase ${phase} cannot be completed: phase council evidence contains unrecognized verdict '${entry.verdict}'. Expected one of: APPROVE, CONCERNS, REJECT.`,agentsDispatched,agentsMissing:[],warnings:[]}}}catch(readErr){if(readErr.code!=="ENOENT")safeWarn("[phase_complete] Phase council evidence unreadable:",readErr);pcVerdictFound=!1}if(!pcVerdictFound)return{blocked:!0,reason:"PHASE_COUNCIL_REQUIRED",phase_council_required:!0,message:`Phase ${phase} cannot be completed: phase_council is enabled and phase council evidence not found at .swarm/evidence/${phase}/phase-council.json. Convene a phase-level council (dispatch 5 members, collect verdicts, call submit_phase_council_verdicts) before completing the phase.`,agentsDispatched,agentsMissing:[],warnings:["Phase council required — convene 5 council members (critic, reviewer, sme, test_engineer, explorer) for holistic phase review. Call submit_phase_council_verdicts to synthesize verdicts and write phase-council.json evidence."]};let effectiveMinimum=pluginConfig.council.requireAllMembers?5:pluginConfig.council.minimumMembers??3;if(pcQuorumSize===void 0||typeof pcQuorumSize!=="number")return{blocked:!0,reason:"PHASE_COUNCIL_MISSING_QUORUM",message:`Phase ${phase} cannot be completed: phase council evidence is missing quorumSize field.`,agentsDispatched,agentsMissing:[],warnings:[]};if(pcQuorumSize<effectiveMinimum)return{blocked:!0,reason:"PHASE_COUNCIL_INSUFFICIENT_QUORUM",message:`Phase ${phase} cannot be completed: phase council quorum (${pcQuorumSize}) is below minimum (${effectiveMinimum}). Re-convene council with sufficient members.`,agentsDispatched,agentsMissing:[],warnings:[]}}}catch(pcError){if(councilModeEnabled)return{blocked:!0,reason:"PHASE_COUNCIL_ERROR",message:`Phase ${phase} cannot be completed: phase council gate encountered an error when phase_council was enabled. Error: ${String(pcError)}`,agentsDispatched,agentsMissing:[],warnings:[`PHASE_COUNCIL_ERROR: ${String(pcError)}`]};else safeWarn("[phase_complete] Phase council gate error (non-blocking):",pcError)}return{blocked:!1,agentsDispatched,agentsMissing:[],warnings:gateWarnings}}import{createHash as createHash100}from"node:crypto";var MAX_DETAIL_CHARS=1024,MAX_WARNINGS=32,MAX_ACTORS=64,DEFAULT_GATE_TIMEOUT_MS=1e4,MAX_GATE_TIMEOUT_MS=30000;async function runBoundedGate(check3){let timeoutMs=Math.min(MAX_GATE_TIMEOUT_MS,Math.max(1,check3.timeoutMs??DEFAULT_GATE_TIMEOUT_MS)),timer;try{return await Promise.race([check3.run(),new Promise((_,reject2)=>{timer=setTimeout(()=>reject2(Error(`${check3.id.toUpperCase()}_TIMEOUT: gate read exceeded ${timeoutMs}ms`)),timeoutMs)})])}finally{if(timer)clearTimeout(timer)}}function bounded(value,fallback=""){let text=typeof value==="string"?value:fallback;return text.length<=MAX_DETAIL_CHARS?text:`${text.slice(0,MAX_DETAIL_CHARS-1)}…`}function boundedStrings(value,limit=MAX_ACTORS){if(!Array.isArray(value))return[];return value.filter((item)=>typeof item==="string").slice(0,limit).map((item)=>bounded(item))}function recoveryFrom(result){let raw=result.recovery;if(!raw||typeof raw!=="object"||Array.isArray(raw))return;let candidate2=raw;if(!["tool","command","retry","user_action"].includes(String(candidate2.kind))||typeof candidate2.action!=="string"||candidate2.action.length===0)return;return{kind:candidate2.kind,action:bounded(candidate2.action),...candidate2.args&&typeof candidate2.args==="object"&&!Array.isArray(candidate2.args)?{args:candidate2.args}:{}}}function defaultBlockedRecovery(check3,result){let action2={critical_directives:"knowledge_receipt",retrospective:"write_retro",completion_verify:"completion_verify",drift:"write_drift_evidence",hallucination:"write_hallucination_evidence",mutation:"write_mutation_evidence",final_review:"run_phase_review",lean_turbo_readiness:"lean_turbo_review"}[check3.id];if(action2){if(check3.id==="lean_turbo_readiness"){let blockedOnCritic=/critic/i.test(`${result.message??""} ${result.reason??""}`);return{kind:"tool",action:action2,...blockedOnCritic?{args:{follow_up_tool:"lean_turbo_critic"}}:{}}}return{kind:"tool",action:action2}}if(check3.id==="phase_council"||check3.id==="final_council")return{kind:"user_action",action:"Task",args:{agents:["critic","reviewer","sme","test_engineer","explorer"],follow_up_tool:check3.id==="phase_council"?"submit_phase_council_verdicts":"write_final_council_evidence"}};if(check3.id==="architecture_supervisor")return{kind:"user_action",action:"Task",args:{agents:["critic_architecture_supervisor"],follow_up_tool:"write_architecture_supervisor_evidence"}};if(check3.id==="full_auto_approval")return{kind:"user_action",action:"Task",args:{agents:["critic_oversight"]}};if(check3.id==="required_agents")return{kind:"user_action",action:"Task",args:{agents:boundedStrings(result.agentsMissing)}};return{kind:"retry",action:"phase_complete"}}function retrospectiveGateFrom(result){let raw=result.retrospective_gate;if(!raw||typeof raw!=="object"||Array.isArray(raw))return;let candidate2=raw;if(typeof candidate2.schema_valid!=="boolean"||typeof candidate2.gate_pass!=="boolean")return;return{schema_valid:candidate2.schema_valid,gate_pass:candidate2.gate_pass,...candidate2.verdict==="pass"||candidate2.verdict==="fail"?{verdict:candidate2.verdict}:{}}}function stableReportHash(phase,entries2){return createHash100("sha256").update(JSON.stringify({schemaVersion:1,phase,entries:entries2})).digest("hex")}async function collectPhaseGateReport(input){let entries2=[];for(let check3 of input.checks){if(check3.applicable===!1){entries2.push({id:check3.id,code:"NOT_APPLICABLE",outcome:"not_applicable",detail:bounded(check3.notApplicableDetail,"gate not applicable"),evidenceRefs:[],responsibleActor:check3.responsibleActor,agentsDispatched:[],agentsMissing:[],warnings:[]});continue}try{let result=await runBoundedGate(check3),recovery=recoveryFrom(result)??(result.blocked?defaultBlockedRecovery(check3,result):void 0),retrospectiveGate=retrospectiveGateFrom(result);entries2.push({id:check3.id,code:typeof result.reason==="string"?bounded(result.reason):result.blocked?`${check3.id.toUpperCase()}_BLOCKED`:"PASS",outcome:result.blocked?"block":"pass",...typeof result.message==="string"?{detail:bounded(result.message)}:{},evidenceRefs:boundedStrings(result.evidenceRefs),responsibleActor:check3.responsibleActor,...recovery?{recovery,requiredRecoveryKind:recovery.kind}:{},...retrospectiveGate?{retrospective_gate:retrospectiveGate}:{},agentsDispatched:boundedStrings(result.agentsDispatched),agentsMissing:boundedStrings(result.agentsMissing),warnings:boundedStrings(result.warnings,MAX_WARNINGS),...typeof result.recovery_guidance==="string"?{recoveryGuidance:bounded(result.recovery_guidance)}:{},...result.phase_council_required===!0?{phase_council_required:!0}:{},...result.final_council_required===!0?{final_council_required:!0}:{}})}catch(error93){entries2.push({id:check3.id,code:error93 instanceof Error&&error93.message.startsWith(`${check3.id.toUpperCase()}_TIMEOUT:`)?`${check3.id.toUpperCase()}_TIMEOUT`:`${check3.id.toUpperCase()}_ERROR`,outcome:"error",detail:bounded(error93 instanceof Error?error93.message:String(error93),"unknown gate error"),evidenceRefs:[],responsibleActor:check3.responsibleActor,recovery:{kind:"retry",action:"phase_complete"},requiredRecoveryKind:"retry",agentsDispatched:[],agentsMissing:[],warnings:[]})}}let outcome=entries2.some((entry)=>entry.outcome==="block"||entry.outcome==="error")?"block":"pass";return{schemaVersion:1,phase:input.phase,outcome,reportHash:stableReportHash(input.phase,entries2),entries:entries2}}function formatPhaseGateCompatibility(report){let firstFailure=report.entries.find((entry)=>entry.outcome==="block"||entry.outcome==="error"),retrospectiveEntry=report.entries.find((entry)=>entry.id==="retrospective"&&entry.retrospective_gate),recoveryGuidance=report.entries.find((entry)=>entry.id==="required_agents"&&entry.recoveryGuidance)?.recoveryGuidance,requiredAgentsEntry=report.entries.find((entry)=>entry.id==="required_agents"),dispatched=new Set,missing=new Set,warnings=[];for(let entry of report.entries){for(let actor of entry.agentsDispatched)dispatched.add(actor);for(let actor of entry.agentsMissing)missing.add(actor);for(let warning of entry.warnings)if(warnings.length<MAX_WARNINGS&&!warnings.includes(warning))warnings.push(warning)}if(requiredAgentsEntry){dispatched.clear();for(let actor of requiredAgentsEntry.agentsDispatched)dispatched.add(actor)}return{success:report.outcome==="pass",phase:report.phase,status:report.outcome==="pass"?"success":firstFailure?.code==="REQUIRED_AGENTS_MISSING"?"incomplete":"blocked",...firstFailure?{reason:firstFailure.code,message:firstFailure.detail}:{},agentsDispatched:[...dispatched].sort(),agentsMissing:[...missing].sort(),warnings,gate_report:report,...recoveryGuidance?{recovery_guidance:recoveryGuidance}:{},...report.entries.some((entry)=>entry.phase_council_required)?{phase_council_required:!0}:{},...report.entries.some((entry)=>entry.final_council_required)?{final_council_required:!0}:{},...retrospectiveEntry?.retrospective_gate?{retrospective_gate:retrospectiveEntry.retrospective_gate}:{}}}import{createHash as createHash101}from"node:crypto";import*as fs197 from"node:fs";import*as path325 from"node:path";var MAX_SNAPSHOT_FILES=512,MAX_SNAPSHOT_ENTRIES=2048,MAX_SNAPSHOT_BYTES=16777216,INPUTS=[".swarm/evidence",".swarm/spec.md",".swarm/knowledge-receipts-v2.jsonl","specs","openspec/specs","openspec/changes"];function compareUtf8(left,right){return Buffer.compare(Buffer.from(left,"utf8"),Buffer.from(right,"utf8"))}function isContained3(root,candidate2){let relative82=path325.relative(root,candidate2);return relative82===""||relative82!==".."&&!relative82.startsWith(`..${path325.sep}`)&&!path325.isAbsolute(relative82)}function computePhaseEvidenceSnapshot(directory){let root=fs197.realpathSync(directory),entries2=[],totalBytes=0,visitedEntries=0,visit=(absolute)=>{if(!isContained3(root,absolute))throw Error("PHASE_SNAPSHOT_PATH_ESCAPE");let stat24;try{stat24=fs197.lstatSync(absolute)}catch(error93){if(error93.code==="ENOENT")return;throw error93}if(stat24.isSymbolicLink())throw Error(`PHASE_SNAPSHOT_UNSAFE_PATH: ${path325.relative(root,absolute)}`);if(stat24.isDirectory()){let names=[],handle=fs197.opendirSync(absolute);try{for(;;){let entry=handle.readSync();if(!entry)break;if(visitedEntries+=1,visitedEntries>MAX_SNAPSHOT_ENTRIES)throw Error("PHASE_SNAPSHOT_ENTRY_LIMIT");names.push(entry.name)}}finally{handle.closeSync()}for(let name of names.sort(compareUtf8))visit(path325.join(absolute,name));return}if(!stat24.isFile())throw Error(`PHASE_SNAPSHOT_NON_REGULAR: ${path325.relative(root,absolute)}`);if(entries2.length>=MAX_SNAPSHOT_FILES)throw Error("PHASE_SNAPSHOT_FILE_LIMIT");if(totalBytes+=stat24.size,totalBytes>MAX_SNAPSHOT_BYTES)throw Error("PHASE_SNAPSHOT_BYTE_LIMIT");let descriptor=fs197.openSync(absolute,fs197.constants.O_RDONLY|(fs197.constants.O_NOFOLLOW??0));try{let opened=fs197.fstatSync(descriptor);if(!opened.isFile()||opened.dev!==stat24.dev||opened.ino!==stat24.ino||opened.size!==stat24.size)throw Error("PHASE_SNAPSHOT_CONCURRENT_MUTATION");let bytes=fs197.readFileSync(descriptor),after=fs197.fstatSync(descriptor);if(after.size!==opened.size||after.mtimeMs!==opened.mtimeMs||after.ctimeMs!==opened.ctimeMs)throw Error("PHASE_SNAPSHOT_CONCURRENT_MUTATION");entries2.push({path:path325.relative(root,absolute).replaceAll("\\","/"),sha256:createHash101("sha256").update(bytes).digest("hex"),bytes:bytes.byteLength})}finally{fs197.closeSync(descriptor)}};for(let relative82 of INPUTS)visit(path325.join(root,...relative82.split("/")));return entries2.sort((left,right)=>compareUtf8(left.path,right.path)),createHash101("sha256").update(JSON.stringify({schemaVersion:1,entries:entries2})).digest("hex")}init_resolve_working_directory();var phaseCompleteReceiptInternals={recordPhaseCloseIntent,commitPhaseClosed,rebindCursorTaggedReceipts:(...args2)=>rebindCursorTaggedReceipts(...args2)},phaseCompleteCommitInternals={savePlan:(...args2)=>savePlan(...args2)},phaseCompletePreflightInternals={runCompletionVerifyGate,runDriftGate,runHallucinationGate,runMutationGate,runPhaseCouncilGate,runArchitectureSupervisorGate,runFinalReviewGate,runFinalCouncilGate};function buildMissingAgentRecoveryGuidance(input){if(input.missing.length===0)return;let steps=[`Dispatch the missing required role${input.missing.length===1?"":"s"} (${input.missing.join(", ")}) and retry phase_complete after each Task returns a successful, non-empty result.`];if(input.docsAddedByConfig&&input.missing.includes("docs"))steps.push("If this phase genuinely has no documentation obligation, set phase_complete.require_docs to false in opencode-swarm configuration; that setting is independent of the QA gate profile.");if(!input.docsPlanReadable&&input.missing.includes("docs"))steps.push("A readable plan is required to bind durable docs participation. Restore or rebuild .swarm/plan.json/.swarm/plan.md (or recover from .swarm/plan-export/) before re-dispatching docs, then retry phase_complete.");if(input.docsEvidenceStatus==="corrupt")steps.push("The readable docs-participation projection is corrupt; a genuine docs re-dispatch will quarantine the original bytes and rebuild it safely.");else if(input.docsEvidenceStatus==="unreadable"||input.docsEvidenceStatus==="oversized")steps.push("The docs-participation projection needs operator repair or archival before a re-dispatch can persist new proof.");if(input.missing.includes("docs")&&input.docsEvidenceStatus==="missing")steps.push("No prior durable docs-participation receipt was found (this can happen after a plugin upgrade or a cleared evidence store). A fresh docs Task dispatch writes a new durable completion receipt and is the canonical recovery path.");if(input.policy==="warn")steps.push("The configured warn policy allows closure with a warning, but it does not create participation proof.");else steps.push('Last resort: if the missing role obligation genuinely cannot be satisfied in this environment, set phase_complete.policy to "warn" in opencode-swarm configuration. This weakens enforcement for every missing role and does NOT create durable participation proof, so only use it when the obligation cannot be met.');return steps.join(" ")}function safeWarn(message,error93){try{warn(message,error93 instanceof Error?error93.message:String(error93))}catch{}}var MAX_OUTPUT_BYTES7=512000,TASK_GATE_INFERABLE_AGENTS=new Set(["coder","reviewer","test_engineer"]);function canInferMissingAgentsFromTaskGates(agentsMissing){return agentsMissing.every((agent)=>TASK_GATE_INFERABLE_AGENTS.has(agent))}async function allCompletedTasksHavePassedGateEvidence(directory,tasks){for(let task2 of tasks){if(task2.status!=="completed")return!1;if(!await hasPassedAllGates(directory,task2.id))return!1}return tasks.length>0}function collectCrossSessionDispatchedAgents(phaseReferenceTimestamp,callerSessionId){let agents=new Set,contributorSessionIds=[],callerSession=swarmState.agentSessions.get(callerSessionId);if(callerSession){if(contributorSessionIds.push(callerSessionId),callerSession.phaseAgentsDispatched)for(let agent of callerSession.phaseAgentsDispatched)agents.add(agent);for(let delegation of _getDelegationsSince(callerSessionId,phaseReferenceTimestamp))agents.add(stripKnownSwarmPrefix(delegation.from)),agents.add(stripKnownSwarmPrefix(delegation.to))}for(let[sessionId,session]of swarmState.agentSessions){if(sessionId===callerSessionId)continue;let hasRecentToolCalls=session.lastToolCallTime>=phaseReferenceTimestamp,hasRecentDelegations=swarmState.delegationChains.get(sessionId)?.some((d)=>d.timestamp>=phaseReferenceTimestamp)??!1,hasRestoredAgents=(session.phaseAgentsDispatched?.size??0)>0&&session.lastPhaseCompleteTimestamp===phaseReferenceTimestamp;if(hasRecentToolCalls||hasRecentDelegations||hasRestoredAgents){if(contributorSessionIds.push(sessionId),session.phaseAgentsDispatched)for(let agent of session.phaseAgentsDispatched)agents.add(agent);for(let delegation of _getDelegationsSince(sessionId,phaseReferenceTimestamp))agents.add(stripKnownSwarmPrefix(delegation.from)),agents.add(stripKnownSwarmPrefix(delegation.to))}}return{agents,contributorSessionIds}}function _getDelegationsSince(sessionID,sinceTimestamp){let chain=swarmState.delegationChains.get(sessionID);if(!chain)return[];if(sinceTimestamp===0)return chain;return chain.filter((entry)=>entry.timestamp>sinceTimestamp)}function isValidRetroEntry(entry,phase){return entry.type==="retrospective"&&"phase_number"in entry&&entry.phase_number===phase&&"verdict"in entry&&(entry.verdict==="pass"||entry.verdict==="fail")}async function executePhaseComplete(args2,workingDirectory,directory,_runtime={}){let phase=Number(args2.phase),summary=args2.summary,sessionID=args2.sessionID;if(Number.isNaN(phase)||phase<1||!Number.isFinite(phase)||!Number.isInteger(phase))return JSON.stringify({success:!1,phase,status:"blocked",message:"Invalid phase number",agentsDispatched:[],warnings:["Phase must be a positive number"]},null,2);if(!sessionID)return JSON.stringify({success:!1,phase,message:"Session ID is required",agentsDispatched:[],warnings:["sessionID parameter is required for phase completion tracking"]},null,2);let phaseReferenceTimestamp=ensureAgentSession(sessionID).lastPhaseCompleteTimestamp??0,warnings=[];if(hasActiveTurboMode(sessionID))warnings.push(`Turbo mode active — skipped completion-verify, drift-verifier, hallucination-guard, mutation-gate, and phase-council gates for phase ${phase}.`);let crossSessionResult=collectCrossSessionDispatchedAgents(phaseReferenceTimestamp,sessionID),agentsDispatched=Array.from(crossSessionResult.agents).sort(),dir=workingDirectory||directory,{config:config3}=loadPluginConfigWithMeta(dir),phaseCompleteConfig;try{phaseCompleteConfig=PhaseCompleteConfigSchema.parse(config3.phase_complete??{})}catch(parseError){return JSON.stringify({success:!1,phase,status:"incomplete",message:`Invalid phase_complete configuration: ${parseError instanceof Error?parseError.message:"Unknown error"}`,agentsDispatched,agentsMissing:[],warnings:["Configuration validation failed"]},null,2)}if(phaseCompleteConfig.enabled===!1){let disabledReport=await collectPhaseGateReport({phase,checks:["critical_directives","retrospective","completion_verify","drift","hallucination","mutation","phase_council","architecture_supervisor","final_review","final_council","full_auto_approval","lean_turbo_readiness","required_agents","snapshot_identity"].map((id)=>({id,responsibleActor:"architect",applicable:!1,notApplicableDetail:"phase completion enforcement is disabled",run:async()=>({blocked:!1,agentsDispatched:[],agentsMissing:[],warnings:[]})}))});return JSON.stringify({success:!0,phase,status:"disabled",message:`Phase ${phase} complete (enforcement disabled)`,agentsDispatched,agentsMissing:[],warnings:[],gate_report:disabledReport},null,2)}let receiptPlan=await loadPlan(dir).catch(()=>null),receiptPhaseLabel=receiptPlan?extractCurrentPhaseFromPlan(receiptPlan)??`Phase ${receiptPlan.current_phase??phase}`:`Phase ${phase}`,knowledgeEnabled=config3.knowledge?.enabled!==!1,retroFound=!1,retroEntry=null,invalidSchemaErrors=[],loadedRetroTaskId=null,loadedRetroBundle=null,retrospectiveGate={schema_valid:!1,gate_pass:!1},primaryRetroTaskId=`retro-${phase}`,preflightNowMs=Date.now(),gateCtx={phase,dir,sessionID,pluginConfig:config3,agentsDispatched,safeWarn,loadedRetroBundle,loadedRetroTaskId,preflightNowMs},passGate=(extra={})=>({blocked:!1,agentsDispatched,agentsMissing:[],warnings:[],...extra}),preflightChecks=[];preflightChecks.push({id:"critical_directives",responsibleActor:"architect",applicable:knowledgeEnabled,notApplicableDetail:"knowledge directives are disabled",run:async()=>{let requestedAccept=Array.isArray(args2.acceptViolations)?args2.acceptViolations.filter((value)=>typeof value==="string"&&value.length>0):[];if(requestedAccept.length>0){let callerAgent=args2.callerAgent??swarmState.activeAgent.get(sessionID)??"architect";if(stripKnownSwarmPrefix(callerAgent).toLowerCase()!=="architect")return{...passGate(),blocked:!0,reason:"OVERRIDE_DENIED_NON_ARCHITECT",message:"accept_violations is architect-only and cannot be committed by this caller."};let justification=typeof args2.acceptViolationsJustification==="string"?args2.acceptViolationsJustification.trim():"";return{...passGate(),blocked:!0,reason:justification.length>=10?"DIRECTIVE_OVERRIDE_SEPARATE_ACTION_REQUIRED":"OVERRIDE_REQUIRES_JUSTIFICATION",message:justification.length>=10?"Directive overrides are separate audited evidence writes. Record the override, then retry phase_complete without accept_violations.":"accept_violations requires at least 10 characters of substantive justification.",recovery:{kind:"tool",action:"record_directive_override",args:{directive_ids:requestedAccept,justification,phase}}}}let directiveGate=await evaluatePhaseCriticalDirectives({directory:dir,sessionId:sessionID,phaseLabel:receiptPhaseLabel});if(!directiveGate.blocked)return passGate();return{...passGate(),blocked:!0,reason:directiveGate.failedClosed?"DIRECTIVE_GATE_FAILED_CLOSED":"UNRESOLVED_CRITICAL_DIRECTIVES",message:directiveGate.failedClosed?"Critical-directive gate could not read authoritative receipt state; failing closed.":formatDirectiveBlockMessage(directiveGate.unresolved),unresolved_directives:directiveGate.unresolved,..."recovery"in directiveGate&&directiveGate.recovery&&typeof directiveGate.recovery==="object"?{recovery:directiveGate.recovery}:{}}}}),preflightChecks.push({id:"retrospective",responsibleActor:"architect",run:async()=>{let retroResult=await loadEvidence(dir,primaryRetroTaskId,{migrate:!1}),candidates=[];if(retroResult.status==="found")candidates.push({taskId:primaryRetroTaskId,bundle:retroResult.bundle});else if(retroResult.status==="invalid_schema")invalidSchemaErrors.push(...retroResult.errors);if(candidates.length===0){let taskIds=(await listEvidenceTaskIds(dir)).filter((id)=>/^retro-\d+$/.test(id)).sort();for(let taskId of taskIds){let candidate2=await loadEvidence(dir,taskId,{migrate:!1});if(candidate2.status==="found")candidates.push({taskId,bundle:candidate2.bundle});else if(candidate2.status==="invalid_schema")invalidSchemaErrors.push(...candidate2.errors)}}for(let candidate2 of candidates){let entry=candidate2.bundle.entries?.find((item)=>isValidRetroEntry(item,phase));if(!entry)continue;if(retroFound=!0,retroEntry=entry,loadedRetroTaskId=candidate2.taskId,loadedRetroBundle=candidate2.bundle,retrospectiveGate={schema_valid:!0,gate_pass:entry.verdict==="pass",verdict:entry.verdict},gateCtx.loadedRetroTaskId=candidate2.taskId,gateCtx.loadedRetroBundle=candidate2.bundle,entry.verdict==="fail")return{...passGate(),blocked:!0,reason:"RETROSPECTIVE_FAILED",message:'The retrospective is schema-valid and truthfully records verdict "fail". Resolve the phase findings and write a new explicit verdict before retrying.',retrospective_gate:retrospectiveGate,recovery:{kind:"tool",action:"write_retro"}};return passGate({retrospective_gate:retrospectiveGate})}let schemaDetail=invalidSchemaErrors.length>0?` Schema validation failed: ${invalidSchemaErrors.slice(0,8).join("; ")}.`:"";return{...passGate(),blocked:!0,reason:invalidSchemaErrors.length>0?"RETROSPECTIVE_SCHEMA_INVALID":"RETROSPECTIVE_MISSING",message:`Phase ${phase} cannot be completed without an explicit retrospective verdict.${schemaDetail}`,retrospective_gate:retrospectiveGate,recovery:{kind:"tool",action:"write_retro",args:{phase}}}}});let turboActive=hasActiveTurboMode(sessionID),standardGateSpecs=[{id:"completion_verify",actor:"test_engineer",run:()=>phaseCompletePreflightInternals.runCompletionVerifyGate(gateCtx)},{id:"drift",actor:"critic",run:()=>phaseCompletePreflightInternals.runDriftGate(gateCtx)},{id:"hallucination",actor:"reviewer",run:()=>phaseCompletePreflightInternals.runHallucinationGate(gateCtx)},{id:"mutation",actor:"test_engineer",run:()=>phaseCompletePreflightInternals.runMutationGate(gateCtx)},{id:"phase_council",actor:"architect",run:()=>phaseCompletePreflightInternals.runPhaseCouncilGate(gateCtx)}];for(let spec of standardGateSpecs)preflightChecks.push({id:spec.id,responsibleActor:spec.actor,applicable:!turboActive,notApplicableDetail:"standard gate bypassed by active Turbo policy",run:spec.run});preflightChecks.push({id:"architecture_supervisor",responsibleActor:"architecture_supervisor",applicable:config3.architectural_supervision?.enabled===!0&&config3.architectural_supervision.mode==="gate",notApplicableDetail:"architecture supervision gate is not enabled",run:()=>phaseCompletePreflightInternals.runArchitectureSupervisorGate(gateCtx)}),preflightChecks.push({id:"final_review",responsibleActor:"reviewer",run:()=>phaseCompletePreflightInternals.runFinalReviewGate(gateCtx)}),preflightChecks.push({id:"final_council",responsibleActor:"architect",run:()=>phaseCompletePreflightInternals.runFinalCouncilGate(gateCtx)}),preflightChecks.push({id:"full_auto_approval",responsibleActor:"critic",run:async()=>{let approval=verifyFullAutoPhaseApproval(dir,sessionID,phase,config3);return approval.ok?passGate():{...passGate(),blocked:!0,reason:"FULL_AUTO_APPROVAL_REQUIRED",message:`Phase ${phase} cannot be completed: ${approval.reason??"Full-Auto v2 approval missing"}`,recovery:{kind:"user_action",action:"Task",args:{subagent_type:"critic_oversight",trigger_source:"phase_boundary",phase}}}}});let epicActiveForProject=isEpicModeActiveForProject(dir);preflightChecks.push({id:"lean_turbo_readiness",responsibleActor:"architect",applicable:hasActiveLeanTurbo(sessionID)&&!epicActiveForProject,notApplicableDetail:"Lean Turbo is inactive or Epic Mode owns readiness",run:async()=>{let leanConfig=config3?.turbo?.lean,check3=_internals270.verifyLeanTurboPhaseReady(dir,phase,sessionID,leanConfig?{phase_reviewer:leanConfig.phase_reviewer,phase_critic:leanConfig.phase_critic,integrated_diff_required:leanConfig.integrated_diff_required}:void 0);return check3.ok?passGate():{...passGate(),blocked:!0,reason:"LEAN_TURBO_PHASE_NOT_READY",message:`Phase ${phase} cannot be completed: ${check3.reason}`}}}),preflightChecks.push({id:"required_agents",responsibleActor:"architect",run:async()=>{let participationPlan=null,phaseRequiredAgents;try{participationPlan=await loadPlan(dir),phaseRequiredAgents=participationPlan?.phases.find((item)=>item.id===phase)?.required_agents}catch{participationPlan=null}let configured=[...phaseRequiredAgents??phaseCompleteConfig.required_agents],required3=[...configured];if(phaseCompleteConfig.require_docs&&!required3.includes("docs"))required3.push("docs");let docsStatus=null,durableDocsFound=!1;if(required3.includes("docs")){if(crossSessionResult.agents.delete("docs"),participationPlan){let receipt=await readPhaseParticipation(dir,participationPlan,phase,"docs");if(docsStatus=receipt.status,receipt.found)durableDocsFound=!0,crossSessionResult.agents.add("docs")}}let missing=required3.filter((role)=>!crossSessionResult.agents.has(role)),inferredFromTaskGates=[];if(missing.length>0)try{let planRaw=fs199.readFileSync(validateSwarmPath(dir,"plan.json"),"utf8"),target=JSON.parse(planRaw).phases.find((item)=>item.id===phase);if(target&&target.tasks.length>0&&canInferMissingAgentsFromTaskGates(missing)&&await allCompletedTasksHavePassedGateEvidence(dir,target.tasks))inferredFromTaskGates=[...missing],missing=[]}catch{}let recoveryGuidance=buildMissingAgentRecoveryGuidance({missing,docsAddedByConfig:phaseCompleteConfig.require_docs&&!configured.includes("docs"),docsEvidenceStatus:docsStatus,docsPlanReadable:participationPlan!==null,policy:phaseCompleteConfig.policy}),authoritativeAgents=[...crossSessionResult.agents].sort();return missing.length>0&&phaseCompleteConfig.policy==="enforce"?{...passGate(),blocked:!0,reason:"REQUIRED_AGENTS_MISSING",message:`Phase ${phase} is missing required agents: ${missing.join(", ")}. ${recoveryGuidance}`,agentsMissing:missing,agentsDispatched:authoritativeAgents,recovery_guidance:recoveryGuidance,recovery:{kind:"user_action",action:"Task",args:{agents:missing}}}:passGate({agentsDispatched:durableDocsFound?[...new Set([...authoritativeAgents,"docs"])].sort():authoritativeAgents,recovery_guidance:recoveryGuidance,agentsMissing:missing,warnings:[...durableDocsFound?[`Recovered durable docs participation proof for phase ${phase}.`]:[],...inferredFromTaskGates.length>0?[`Agent dispatch fallback: all completed tasks in phase ${phase} have durable passing gate evidence. Clearing missing agents: ${inferredFromTaskGates.join(", ")}.`]:[],...missing.length>0?[`Warning: phase ${phase} missing required agents: ${missing.join(", ")} (advisory because phase_complete.policy=warn).`]:[]]})}}),preflightChecks.push({id:"snapshot_identity",responsibleActor:"architect",run:async()=>{let plan=await loadPlan(dir),structureHash=plan?computePlanStructureHash(plan):"plan:none",policyHash=createHash102("sha256").update(JSON.stringify(config3)).digest("hex"),evidenceHash=computePhaseEvidenceSnapshot(dir);return passGate({evidenceRefs:[`plan-structure:${structureHash}`,`policy:${policyHash}`,`phase-evidence:${evidenceHash}`]})}});let preflightReport=await collectPhaseGateReport({phase,checks:preflightChecks});if(preflightReport.outcome==="block")return JSON.stringify(formatPhaseGateCompatibility(preflightReport),null,2);for(let entry of preflightReport.entries)warnings.push(...entry.warnings);let acceptedRetro={found:retroFound,entry:retroEntry,taskId:loadedRetroTaskId,bundle:loadedRetroBundle},phaseRecoveryGuidance=preflightReport.entries.find((entry)=>entry.id==="required_agents"&&entry.recoveryGuidance)?.recoveryGuidance,phaseCommitAgent="phase-complete";for(let[,activeAgent]of swarmState.activeAgent){phaseCommitAgent=activeAgent;break}let planLockTaskId=`phase-complete-plan-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,phasePlanLock;try{phasePlanLock=await tryAcquireLock(dir,"plan.json",phaseCommitAgent,planLockTaskId)}catch(error93){let detail=error93 instanceof Error?error93.message:String(error93);return JSON.stringify({success:!1,phase,status:"incomplete",reason:"PHASE_COMMIT_LOCK_ERROR",message:`Failed to acquire the guarded phase commit lock: ${detail}`,agentsDispatched,agentsMissing:[],warnings,gate_report:preflightReport,errors:[`Phase commit lock acquisition failed: ${detail}`],recovery_guidance:"Resolve the filesystem or lock-directory error, then retry phase_complete. No phase transition or completion event was committed.",recovery:{kind:"retry",action:"phase_complete"}})}if(!phasePlanLock.acquired){let lockOwner=phasePlanLock.existing?.agent??"another agent";return JSON.stringify({success:!1,phase,status:"incomplete",reason:"PHASE_COMMIT_LOCKED",message:`Plan write is locked by ${lockOwner}.`,agentsDispatched,agentsMissing:[],warnings,gate_report:preflightReport,errors:[`Concurrent plan write detected; lock is held by ${lockOwner}.`],recovery_guidance:"Wait for the current plan writer to finish, then retry phase_complete. No phase transition or completion event was committed.",recovery:{kind:"retry",action:"phase_complete"}})}try{let lockedPreflight=await collectPhaseGateReport({phase,checks:preflightChecks});if(lockedPreflight.outcome!=="pass"||lockedPreflight.reportHash!==preflightReport.reportHash)return JSON.stringify({success:!1,phase,status:"blocked",reason:"PHASE_PREFLIGHT_STALE",message:"Phase evidence, plan identity, or policy changed after preflight. No phase transition or post-commit side effect was written.",agentsDispatched,agentsMissing:[],warnings,gate_report:lockedPreflight,recovery:{kind:"retry",action:"phase_complete"}});let plan=await loadPlan(dir);if(plan?._ledgerReplayStale===!0){let staleReason=plan._ledgerReplayStaleReason??"unknown reason";return JSON.stringify({success:!1,phase,status:"incomplete",reason:"PHASE_PLAN_STALE",message:`Plan write refused: plan.json is stale from a failed ledger replay (${staleReason}). Refusing to complete phase ${phase} against a known-stale plan.`,agentsDispatched,agentsMissing:[],warnings,gate_report:lockedPreflight,errors:[`Stale plan from failed ledger replay: ${staleReason}`],recovery_guidance:"The ledger replay failed and no critic-approved snapshot was available, so loadPlan fell back to a stale plan.json. Do NOT retry blindly. Recover first: re-verify the plan (re-run completion verification), reset the session, or restore from the latest checkpoint under .swarm/plan-export/, then retry phase_complete.",_ledgerReplayStaleReason:staleReason})}if(!plan&&await ledgerExists(dir))plan=await replayFromLedger(dir);let phaseObject=plan?plan.phases.find((candidate2)=>candidate2.id===phase):void 0;if(plan){if(!phaseObject)return JSON.stringify({success:!1,phase,status:"incomplete",reason:"PHASE_NOT_IN_PLAN",message:`Phase ${phase} is not present in the authoritative plan.`,agentsDispatched,agentsMissing:[],warnings,gate_report:lockedPreflight})}else if(fs199.existsSync(validateSwarmPath(dir,"plan.json")))return JSON.stringify({success:!1,phase,status:"incomplete",reason:"PHASE_PLAN_UNREADABLE",message:"Plan exists but could not be read or rebuilt from the ledger; no phase transition was committed.",agentsDispatched,agentsMissing:[],warnings,gate_report:lockedPreflight});if(knowledgeEnabled){let closeIntent=await phaseCompleteReceiptInternals.recordPhaseCloseIntent(dir,receiptPhaseLabel,sessionID);if(!closeIntent.ok)return JSON.stringify({success:!1,phase,status:"incomplete",reason:"PHASE_CLOSE_INTENT_FAILED",message:"Phase completion blocked: could not persist receipt phase-close intent.",agentsDispatched,agentsMissing:[],warnings,gate_report:lockedPreflight,errors:[closeIntent.detail],recovery:{kind:"retry",action:"phase_complete"}})}let commitPreflight=await collectPhaseGateReport({phase,checks:preflightChecks});if(commitPreflight.outcome!=="pass")return JSON.stringify({success:!1,phase,status:"blocked",reason:"PHASE_PREFLIGHT_STALE",message:"Phase evidence or policy changed before the authoritative transition. No plan transition or completion event was written.",agentsDispatched,agentsMissing:[],warnings,gate_report:commitPreflight,recovery:{kind:"retry",action:"phase_complete"}});let commitEvidenceRef=commitPreflight.entries.find((entry)=>entry.id==="snapshot_identity")?.evidenceRefs.find((reference)=>reference.startsWith("phase-evidence:")),commitPolicyRef=commitPreflight.entries.find((entry)=>entry.id==="snapshot_identity")?.evidenceRefs.find((reference)=>reference.startsWith("policy:")),expectedCommitEvidenceHash=commitEvidenceRef?.slice(15),expectedCommitPolicyHash=commitPolicyRef?.slice(7);if(!expectedCommitEvidenceHash||!expectedCommitPolicyHash)return JSON.stringify({success:!1,phase,status:"blocked",reason:"PHASE_PREFLIGHT_STALE",message:"The commit-boundary evidence identity was unavailable. No plan transition or completion event was written.",agentsDispatched,agentsMissing:[],warnings,gate_report:commitPreflight,recovery:{kind:"retry",action:"phase_complete"}});if(plan&&phaseObject&&!["complete","completed","closed"].includes(phaseObject.status)){phaseObject.status="complete";try{let saveDurability=await phaseCompleteCommitInternals.savePlan(dir,plan,{preserveCompletedStatuses:!0,planLockAlreadyHeld:!0,preCommitCheck:()=>{let currentPolicyHash=createHash102("sha256").update(JSON.stringify(loadPluginConfigWithMeta(dir).config)).digest("hex");if(computePhaseEvidenceSnapshot(dir)!==expectedCommitEvidenceHash||currentPolicyHash!==expectedCommitPolicyHash)throw Error("PHASE_PREFLIGHT_STALE: evidence changed at the authoritative transition boundary")}});if(saveDurability.durability==="incomplete")warnings.push(`Plan saved with incomplete durability; degraded surfaces: ${saveDurability.degraded_surfaces.join(", ")}`+(saveDurability.md_write_error?` (${saveDurability.md_write_error})`:""))}catch(error93){if(error93 instanceof Error&&error93.message.startsWith("PHASE_PREFLIGHT_STALE:"))return JSON.stringify({success:!1,phase,status:"blocked",reason:"PHASE_PREFLIGHT_STALE",message:"Phase evidence changed at the authoritative transition boundary. No plan transition or completion event was written.",agentsDispatched,agentsMissing:[],warnings,gate_report:commitPreflight,recovery:{kind:"retry",action:"phase_complete"}});throw error93}await takeSnapshotEvent(dir,plan).catch(()=>{return})}}finally{if(phasePlanLock.lock._release)await phasePlanLock.lock._release().catch((error93)=>{warn("[phase_complete] Plan lock release failed:",error93 instanceof Error?error93.message:String(error93))})}try{let normalizedPlan=await loadPlan(dir).catch(()=>null);if(normalizedPlan){let{rebound}=await phaseCompleteReceiptInternals.rebindCursorTaggedReceipts(dir,normalizedPlan,phase,"docs");if(rebound>0)warnings.push(`Re-stamped ${rebound} docs participation receipt(s) from the plan's stale current_phase cursor to phase ${phase}.`)}}catch(error93){warnings.push(`Docs participation receipt normalization failed: ${error93 instanceof Error?error93.message:String(error93)}.`)}if(knowledgeEnabled){let receiptClose=await phaseCompleteReceiptInternals.commitPhaseClosed(dir,receiptPhaseLabel,sessionID);if(!receiptClose.ok)return JSON.stringify({success:!1,phase,status:"incomplete",reason:"PHASE_RECEIPT_CLOSE_PENDING",message:"Plan phase closed, but receipt lifecycle closure is pending reconciliation; retry phase_complete.",agentsDispatched,agentsMissing:[],warnings:[...warnings,receiptClose.detail],gate_report:preflightReport,recovery:{kind:"retry",action:"phase_complete"}})}let requiredAgentsEntry=preflightReport.entries.find((entry)=>entry.id==="required_agents");if(requiredAgentsEntry)agentsDispatched.splice(0,agentsDispatched.length,...requiredAgentsEntry.agentsDispatched);let knowledgeConfig;try{knowledgeConfig=KnowledgeConfigSchema.parse(config3.knowledge??{})}catch(parseErr){warnings.push(`Knowledge config validation failed: ${String(parseErr)}`),knowledgeConfig=KnowledgeConfigSchema.parse({})}if(acceptedRetro.found&&acceptedRetro.entry?.lessons_learned&&acceptedRetro.entry.lessons_learned.length>0)try{let projectName=path327.basename(dir),curationResult=await curateAndStoreSwarm(acceptedRetro.entry.lessons_learned,projectName,{phase_number:phase},dir,knowledgeConfig,{llmDelegate:createCuratorLLMDelegate(dir,"phase",sessionID),enrichmentQuota:{maxCalls:knowledgeConfig.enrichment.max_calls_per_day,window:knowledgeConfig.enrichment.quota_window}});if(curationResult&&curationResult.stored+curationResult.reinforced+curationResult.quarantined+curationResult.rejected>0){let sessionState=swarmState.agentSessions.get(sessionID);if(sessionState)pushAdvisory(sessionState,`[CURATOR] Knowledge curation: ${curationResult.stored} stored, ${curationResult.reinforced} reinforced, ${curationResult.skipped} skipped, ${curationResult.rejected} rejected, ${curationResult.quarantined} quarantined (unactionable).`)}}catch(error93){safeWarn("[phase_complete] Failed to curate lessons from retrospective:",error93)}let complianceWarnings=[];try{let curatorConfig=CuratorConfigSchema.parse(config3.curator??{});if(curatorConfig.enabled&&curatorConfig.phase_enabled){let llmDelegate=createCuratorLLMDelegate(dir,"phase",sessionID??void 0),curatorResult=await runCuratorPhase(dir,phase,agentsDispatched,curatorConfig,{},llmDelegate);{let scopeContent=curatorResult.digest?.summary??`Phase ${phase} curator analysis`,complianceWarnings2=curatorResult.compliance.filter((c)=>c.severity==="warning"),receipt=complianceWarnings2.length>0?buildRejectedReceipt({agent:"curator",scopeContent,scopeDescription:"phase-digest",blockingFindings:complianceWarnings2.map((c)=>({location:`phase-${c.phase}`,summary:c.description,severity:c.type==="missing_reviewer"?"high":"medium"})),evidenceReferences:[],passConditions:["resolve all compliance warnings before phase completion"]}):buildApprovedReceipt({agent:"curator",scopeContent,scopeDescription:"phase-digest",checkedAspects:["phase_compliance","knowledge_recommendations","phase_digest"],validatedClaims:[`phase: ${phase}`,`agents_dispatched: ${agentsDispatched.length}`,`knowledge_recommendations: ${curatorResult.knowledge_recommendations.length}`]});persistReviewReceipt(dir,receipt).catch(()=>{})}let knowledgeResult=await applyCuratorKnowledgeUpdates(dir,curatorResult.knowledge_recommendations,knowledgeConfig),driftAdvisoryPushedThisRun=!1;try{let{runDeterministicDriftCheck:runDeterministicDriftCheck2}=await Promise.resolve().then(() => (init_curator_drift(),exports_curator_drift));await runDeterministicDriftCheck2(dir,phase,curatorResult,curatorConfig,(message2)=>{let sessionState=swarmState.agentSessions.get(sessionID);if(sessionState)pushAdvisory(sessionState,message2),driftAdvisoryPushedThisRun=!0})}catch{}let callerSessionState=swarmState.agentSessions.get(sessionID);if(callerSessionState){let digestSummary=curatorResult.digest?.summary?curatorResult.digest.summary.slice(0,200):"Phase analysis complete",complianceNote=curatorResult.compliance.length>0?` (${curatorResult.compliance.length} compliance observation(s))`:"",analyzeHint=curatorResult.knowledge_recommendations.length>0?" Call curator_analyze with recommendations to apply knowledge updates from this phase.":"";if(digestSummary!=="Phase analysis complete")pushAdvisory(callerSessionState,`[CURATOR] Phase ${phase} digest: ${digestSummary}${complianceNote}. Knowledge: ${knowledgeResult.applied} applied, ${knowledgeResult.skipped} skipped.${analyzeHint}`);try{let{readPriorDriftReports:readPriorDriftReports2}=await Promise.resolve().then(() => (init_curator_drift(),exports_curator_drift)),phaseReport=(await readPriorDriftReports2(dir)).filter((r)=>r.phase===phase).pop();if(phaseReport&&phaseReport.drift_score>0&&!driftAdvisoryPushedThisRun)pushAdvisory(callerSessionState,`[CURATOR DRIFT DETECTED (phase ${phase}, score ${phaseReport.drift_score})]: Prior drift report found on disk. Consider running critic_drift_verifier before phase completion to get a proper drift review. Review drift report for phase ${phase} and address spec alignment if applicable.`)}catch{}}if(curatorResult.compliance.length>0&&!curatorConfig.suppress_warnings)complianceWarnings=curatorResult.compliance.map((obs)=>`[${obs.severity.toUpperCase()}] ${obs.description}`).slice(0,5)}}catch(curatorError){safeWarn("[phase_complete] Curator pipeline error (non-blocking):",curatorError)}try{if(config3.design_docs?.enabled===!0){let outDir=config3.design_docs.out_dir??"docs",{runDesignDocDriftCheck:runDesignDocDriftCheck2}=await Promise.resolve().then(() => (init_design_doc_drift(),exports_design_doc_drift)),docReport=await runDesignDocDriftCheck2(dir,phase,outDir);if(docReport?.verdict==="DOC_STALE"){let callerSessionState=swarmState.agentSessions.get(sessionID);if(callerSessionState){let staleIds=docReport.stale_sections.map((s)=>s.section_id).slice(0,8).join(", ");pushAdvisory(callerSessionState,`[DESIGN-DOC DRIFT (phase ${phase})]: ${docReport.stale_sections.length} design-doc section(s) are stale (${staleIds}). Run /swarm design-docs --update to sync ${outDir}/ and append a design-changelog entry. Advisory only — does not block completion.`)}}}}catch(docDriftError){safeWarn("[phase_complete] Design-doc drift check error (non-blocking):",docDriftError)}let floorOptions={floorAction:knowledgeConfig.confidence_floor_action,floorMinOutcomes:knowledgeConfig.confidence_floor_min_outcomes,floorSignalThreshold:knowledgeConfig.confidence_floor_signal_threshold};try{let feedbackResult=await applySkillUsageFeedback(dir,{floorOptions});if(feedbackResult.processed>0){let sessionState=swarmState.agentSessions.get(sessionID);if(sessionState)pushAdvisory(sessionState,`[FEEDBACK] Skill usage feedback: ${feedbackResult.processed} skills processed, ${feedbackResult.bumps} confidence updates applied.`)}}catch(skillUsageError){safeWarn("[phase_complete] Skill usage feedback error (non-blocking):",skillUsageError)}try{pruneSkillUsageLog(dir,500)}catch(skillPruneError){safeWarn("[phase_complete] Skill usage log pruning error (non-blocking):",skillPruneError)}try{let verdictMarkerPath=validateSwarmPath(dir,"verdict-feedback-last-processed.json"),verdictSinceTimestamp,verdictSinceEventId;try{let markerData=JSON.parse(fs199.readFileSync(verdictMarkerPath,"utf-8"));verdictSinceTimestamp=markerData.lastProcessedTimestamp,verdictSinceEventId=markerData.lastProcessedEventId}catch{}let{applyKnowledgeVerdictFeedback:applyKnowledgeVerdictFeedback2}=await Promise.resolve().then(() => (init_knowledge_events(),exports_knowledge_events)),verdictResult=await applyKnowledgeVerdictFeedback2(dir,{sinceTimestamp:verdictSinceTimestamp,sinceEventId:verdictSinceEventId,floorOptions});if(verdictResult.lastProcessedTimestamp)try{fs199.writeFileSync(verdictMarkerPath,JSON.stringify({lastProcessedTimestamp:verdictResult.lastProcessedTimestamp,lastProcessedEventId:verdictResult.lastProcessedEventId}),"utf-8")}catch{}if(verdictResult.bumps>0){let sessionState=swarmState.agentSessions.get(sessionID);if(sessionState)pushAdvisory(sessionState,`[FEEDBACK] Knowledge verdict feedback: ${verdictResult.processed} entries processed, ${verdictResult.bumps} confidence updates applied.`)}}catch(verdictError){safeWarn("[phase_complete] Knowledge verdict feedback error (non-blocking):",verdictError)}let agentsMissing=[...requiredAgentsEntry?.agentsMissing??[]],VALID_TASK_COMPLEXITY=["trivial","simple","moderate","complex"],firstEntry=acceptedRetro.bundle?.entries?.[0];if(acceptedRetro.taskId!==primaryRetroTaskId&&acceptedRetro.taskId?.startsWith("retro-")&&acceptedRetro.bundle?.schema_version==="1.0.0"&&firstEntry?.task_complexity&&VALID_TASK_COMPLEXITY.includes(firstEntry.task_complexity))warnings.push(`Retrospective data for phase ${phase} may have been automatically migrated to current schema format.`);let success3=!0,status2=agentsMissing.length>0?"warned":"success",safeSummary=summary?.trim().slice(0,500),message=safeSummary?`Phase ${phase} completed: ${safeSummary}`:`Phase ${phase} completed`,result={success:success3,phase,status:status2,message,agentsDispatched,agentsMissing,warnings,gate_report:preflightReport,...phaseRecoveryGuidance?{recovery_guidance:phaseRecoveryGuidance}:{}},hasPlan=!1;try{hasPlan=fs199.existsSync(validateSwarmPath(dir,"plan.json"))}catch{}if(!hasPlan&&!crossSessionResult.agents.has("reviewer")&&!crossSessionResult.agents.has("test_engineer"))warnings.push(`⚠️ Plan-free phase ${phase}: no independent reviewer or test_engineer dispatch detected. Code changes in plan-free sessions should have independent review. Consider dispatching reviewer + test_engineer before completing future plan-free phases.`);if(!hasPlan)warnings.push(`Warning: failed to update plan.json phase status because no authoritative plan was found; phase ${phase} completed in plan-free mode.`);if(acceptedRetro.found&&acceptedRetro.entry?.lessons_learned&&acceptedRetro.entry.lessons_learned.length>0)await updateRetrievalOutcome(dir,`Phase ${phase}`,success3).catch(()=>{});if(phaseCompleteConfig.regression_sweep?.enforce)try{let planPath=validateSwarmPath(dir,"plan.json"),planRaw=fs199.readFileSync(planPath,"utf-8"),targetPhase=JSON.parse(planRaw).phases.find((p)=>p.id===phase);if(targetPhase){let sweepFound=!1;for(let task2 of targetPhase.tasks){let taskEvidenceResult=await loadEvidence(dir,task2.id);if(taskEvidenceResult.status==="found"){let entries2=taskEvidenceResult.bundle.entries??[];for(let entry of entries2)if(entry.regression_sweep!==void 0){sweepFound=!0;break}}if(sweepFound)break}if(!sweepFound)warnings.push(`Warning: regression_sweep.enforce=true but no regression-sweep result found for any task in phase ${phase}. Run tests to populate regression-sweep results.`)}}catch{}let now2=Date.now(),durationMs=now2-phaseReferenceTimestamp,event={event:"phase_complete",phase,timestamp:new Date(now2).toISOString(),agents_dispatched:agentsDispatched,agents_missing:agentsMissing,status:status2,summary:safeSummary??null};try{appendCoreEventSync(dir,{...event})}catch(writeError){warnings.push(`Warning: failed to write phase complete event: ${writeError instanceof Error?writeError.message:String(writeError)}`)}if(success3){try{let skillConfig=SkillImproverConfigSchema.parse(config3.skill_improver??{});if(skillConfig.enabled&&skillConfig.trigger==="scheduled")runSkillConsolidationFireAndForget({directory:dir,config:skillConfig,source:"phase_complete",sessionId:sessionID,enrichmentQuota:{maxCalls:knowledgeConfig.enrichment.max_calls_per_day,window:knowledgeConfig.enrichment.quota_window},evaluateDrafts:!0},(consolidationResult)=>{if(!consolidationResult.started)return;let sessionState=swarmState.agentSessions.get(sessionID);if(!sessionState)return;let activatedSlugs=consolidationResult.result?.autoApply?.approved??[],activationSuffix=activatedSlugs.length>0?` and auto-activated ${activatedSlugs.length} skill(s): ${activatedSlugs.join(", ")}.`:" and auto-activated no skills.";pushAdvisory(sessionState,`[SKILL CONSOLIDATION] Scheduled skill_improver consolidation wrote ${consolidationResult.result?.proposalPath??"a proposal"}${activationSuffix}`)},(err)=>{safeWarn("[phase_complete] Scheduled skill consolidation error (non-blocking):",err)})}catch(skillConsolidationError){safeWarn("[phase_complete] Scheduled skill consolidation setup error (non-blocking):",skillConsolidationError)}try{let memoryConfig=config3.memory;if(memoryConfig?.enabled&&memoryConfig.consolidation?.enabled)runMemoryConsolidationFireAndForget({directory:dir,config:memoryConfig,phase,sessionId:sessionID},void 0,(err)=>{safeWarn("[phase_complete] Memory consolidation error (non-blocking):",err)})}catch(memoryConsolidationError){safeWarn("[phase_complete] Memory consolidation setup error (non-blocking):",memoryConsolidationError)}for(let contributorSessionId of crossSessionResult.contributorSessionIds){let contributorSession=swarmState.agentSessions.get(contributorSessionId);if(contributorSession){if(contributorSession.phaseAgentsDispatched.size>0)contributorSession.lastCompletedPhaseAgentsDispatched=new Set(contributorSession.phaseAgentsDispatched);contributorSession.phaseAgentsDispatched=new Set,contributorSession.fullAutoInteractionCount=0,contributorSession.fullAutoDeadlockCount=0,contributorSession.fullAutoLastQuestionHash=null,contributorSession.lastPhaseCompleteTimestamp=now2;let oldPhase=contributorSession.lastPhaseCompletePhase;contributorSession.lastPhaseCompletePhase=phase,telemetry.phaseChanged(contributorSessionId,oldPhase??0,phase)}}try{if(knowledgeConfig.sweep_enabled){let swarmPath3=resolveSwarmKnowledgePath(dir);if(await sweepAgedEntries(swarmPath3,knowledgeConfig.default_max_phases),await sweepStaleTodos(swarmPath3,knowledgeConfig.todo_max_phases),knowledgeConfig.hive_enabled){let hivePath=resolveHiveKnowledgePath2();await sweepAgedEntries(hivePath,knowledgeConfig.default_max_phases),await sweepStaleTodos(hivePath,knowledgeConfig.todo_max_phases)}}}catch(err){let detail=String(err);if(detail.includes("ELOCKED"))detail="lock timeout (stale lock detected)";else if(detail.includes("ENOSPC"))detail="disk full";else if(detail.includes("EACCES"))detail="permission denied";warnings.push(`Knowledge sweep failed for phase ${phase}: ${detail}`)}}if(complianceWarnings.length>0)warnings.push(`Curator compliance: ${complianceWarnings.join("; ")}`);await flushPendingSnapshot(dir),await writeCheckpoint(dir).catch(()=>{});try{let curatorCfg=CuratorConfigSchema.parse(config3.curator??{});if(curatorCfg.enabled&&curatorCfg.postmortem_enabled){let finalPlan=await loadPlan(dir);if(finalPlan?.phases?.length){if(finalPlan.phases.every((p)=>p.status==="complete")){let{runCuratorPostMortem:runCuratorPostMortem2}=await Promise.resolve().then(() => (init_curator_postmortem(),exports_curator_postmortem)),pmResult=await runCuratorPostMortem2(dir,{llmDelegate:createCuratorLLMDelegate(dir,"postmortem",sessionID),scope:"project",sessionID});if(pmResult.success&&pmResult.summary)warnings.push(`[POST-MORTEM] ${pmResult.summary}`);if(pmResult.warnings.length>0)for(let w of pmResult.warnings)warnings.push(`[POST-MORTEM] ${w}`)}}}}catch{}let outputData={...result,timestamp:event.timestamp,duration_ms:durationMs};return _buildOutputJson(outputData)}function _buildOutputJson(outputData){let json3=JSON.stringify(outputData,null,2);if(json3.length>MAX_OUTPUT_BYTES7){let truncated={_truncated:!0,_truncation_reason:`Output exceeded MAX_OUTPUT_BYTES (${MAX_OUTPUT_BYTES7}) limit`,phase:outputData.phase,success:outputData.success,status:outputData.status,message:outputData.message,agentsDispatched:outputData.agentsDispatched?.slice(0,10),agentsMissing:outputData.agentsMissing?.slice(0,10),warnings:["(output truncated — full output exceeded size limit)"],timestamp:outputData.timestamp,duration_ms:outputData.duration_ms};json3=JSON.stringify(truncated,null,2)}return json3}function createPhaseCompleteTool(runtime={}){return createSwarmTool({description:"Mark a phase as complete and track which agents were dispatched. Used for phase completion gating and tracking. Accepts phase number and optional summary. Returns list of agents that were dispatched.",args:{phase:exports_external.number().int().min(1).describe("The phase number being completed — a positive integer (e.g., 1, 2, 3)"),summary:exports_external.string().optional().describe("Optional summary of what was accomplished in this phase"),sessionID:exports_external.string().optional().describe("Session ID for tracking state (auto-provided by plugin context)"),working_directory:exports_external.string().optional().describe("Explicit project root directory. When provided, .swarm/ is resolved relative to this path instead of the plugin context directory. Use this when CWD differs from the actual project root."),accept_violations:exports_external.array(exports_external.string()).optional().describe("DEPRECATED COMPATIBILITY INPUT. phase_complete never records directive overrides. When supplied, it fails closed with recovery instructions for the architect-only record_directive_override action."),accept_violations_justification:exports_external.string().optional().describe("Written justification retained only for deprecated compatibility input; use it with record_directive_override instead.")},execute:async(args2,directory,ctx)=>{let phaseCompleteArgs,workingDirInput;try{phaseCompleteArgs={phase:Number(args2.phase),summary:args2.summary!==void 0?String(args2.summary):void 0,sessionID:ctx?.sessionID??(args2.sessionID!==void 0?String(args2.sessionID):void 0),acceptViolations:Array.isArray(args2.accept_violations)?args2.accept_violations.map((s)=>String(s)):void 0,acceptViolationsJustification:args2.accept_violations_justification!==void 0?String(args2.accept_violations_justification):void 0,callerAgent:ctx?.agent!==void 0?String(ctx.agent):void 0},workingDirInput=args2.working_directory!==void 0?String(args2.working_directory):void 0}catch{return JSON.stringify({success:!1,phase:0,message:"Invalid arguments",agentsDispatched:[],warnings:["Failed to parse arguments"]},null,2)}let dirResult=resolveWorkingDirectory(workingDirInput,directory);if(!dirResult.success)return JSON.stringify({success:!1,phase:phaseCompleteArgs.phase,message:dirResult.message,agentsDispatched:[],warnings:[dirResult.message]},null,2);return executePhaseComplete(phaseCompleteArgs,dirResult.directory,dirResult.directory,runtime)}})}var phase_complete=createPhaseCompleteTool();init_zod();init_discovery();init_utils();init_bun_compat();init_external_tool_runner();init_create_tool();import*as fs200 from"node:fs";import*as path328 from"node:path";var MAX_OUTPUT_BYTES8=52428800,AUDIT_TIMEOUT_MS=120000;function resolveAuditCommandDefault(name){if(process.platform!=="win32")return[name];let resolved=resolveExecutableFromPath([name]);if(!resolved)return[name];let lowered=resolved.toLowerCase();if(lowered.endsWith(".cmd")||lowered.endsWith(".bat")){if(/["&|<>^!%]/.test(resolved))return[name];return["cmd.exe","/d","/s","/c",`call "${resolved}"`]}return[resolved]}var _internals273={bunSpawn,resolveAuditCommand:resolveAuditCommandDefault};function isValidEcosystem(value){return typeof value==="string"&&["auto","npm","pip","cargo","go","dotnet","ruby","dart","composer"].includes(value)}function validateArgs3(args2){if(typeof args2!=="object"||args2===null)return!0;let obj=args2;if(obj.ecosystem!==void 0&&!isValidEcosystem(obj.ecosystem))return!1;return!0}function detectEcosystems(directory){let ecosystems=[],cwd=directory;if(fs200.existsSync(path328.join(cwd,"package.json")))ecosystems.push("npm");if(fs200.existsSync(path328.join(cwd,"pyproject.toml"))||fs200.existsSync(path328.join(cwd,"requirements.txt")))ecosystems.push("pip");if(fs200.existsSync(path328.join(cwd,"Cargo.toml")))ecosystems.push("cargo");if(fs200.existsSync(path328.join(cwd,"go.mod")))ecosystems.push("go");try{if(fs200.readdirSync(cwd).some((f)=>f.endsWith(".csproj")||f.endsWith(".sln")))ecosystems.push("dotnet")}catch{}if(fs200.existsSync(path328.join(cwd,"Gemfile"))||fs200.existsSync(path328.join(cwd,"Gemfile.lock")))ecosystems.push("ruby");if(fs200.existsSync(path328.join(cwd,"pubspec.yaml")))ecosystems.push("dart");if(fs200.existsSync(path328.join(cwd,"composer.lock")))ecosystems.push("composer");return ecosystems}function auditFailureResult(ecosystem,command,error93,isToolMissing,toolMissingNote,genericNotePrefix){let message=error93 instanceof Error?error93.message:"Unknown error",base={ecosystem,command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0};if(classifySpawnFailure(error93)==="cwd-missing")return{...base,note:`${genericNotePrefix}: ${message}`};if(isToolMissing(message))return{...base,note:toolMissingNote};return{...base,note:`${genericNotePrefix}: ${message}`}}function npmAuditFailure(command,error93){return auditFailureResult("npm",command,error93,(m)=>m.includes("audit")||m.includes("command not found")||m.includes("'npm' is not recognized"),"npm audit not available - npm may not be installed","Error running npm audit")}function cargoAuditFailure(command,error93){return auditFailureResult("cargo",command,error93,(m)=>m.includes("not found")||m.includes("not recognized")||m.includes("cargo-audit"),"cargo-audit not installed. Install with: cargo install cargo-audit","Error running cargo audit")}async function runNpmAudit(directory){let command=[..._internals273.resolveAuditCommand("npm"),"audit","--json"];try{let proc=_internals273.bunSpawn(command,{stdout:"pipe",stderr:"pipe",cwd:directory,...command[0]==="cmd.exe"?{windowsVerbatimArguments:!0,killProcessTree:!0}:{}}),timeoutPromise=new Promise((resolve131)=>setTimeout(()=>resolve131("timeout"),AUDIT_TIMEOUT_MS)),result=await Promise.race([Promise.all([proc.stdout.text(),proc.stderr.text()]).then(([stdout2,stderr2])=>({stdout:stdout2,stderr:stderr2})),timeoutPromise]);if(result==="timeout")return proc.kill(),{ecosystem:"npm",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:`npm audit timed out after ${AUDIT_TIMEOUT_MS/1000}s`};let{stdout,stderr}=result;if(stdout.length>MAX_OUTPUT_BYTES8)stdout=stdout.slice(0,MAX_OUTPUT_BYTES8);let exitCode=await proc.exited;if(proc.spawnError)return npmAuditFailure(command,proc.spawnError);if(exitCode===0)return{ecosystem:"npm",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0};let jsonOutput=stdout,jsonMatch=stdout.match(/\{[\s\S]*\}/)||stderr.match(/\{[\s\S]*\}/);if(jsonMatch)jsonOutput=jsonMatch[0];let response=JSON.parse(jsonOutput),findings=[];if(response.vulnerabilities)for(let[pkgName,vuln]of Object.entries(response.vulnerabilities)){let patchedVersion=null;if(vuln.fixAvailable&&typeof vuln.fixAvailable==="object")patchedVersion=vuln.fixAvailable.version;else if(vuln.fixAvailable===!0)patchedVersion="latest";let severity2=mapNpmSeverity(vuln.severity);findings.push({package:pkgName,installedVersion:vuln.range,patchedVersion,severity:severity2,title:vuln.title||`Vulnerability in ${pkgName}`,cve:vuln.cves&&vuln.cves.length>0?vuln.cves[0]:null,url:vuln.url||null})}let criticalCount=findings.filter((f)=>f.severity==="critical").length,highCount=findings.filter((f)=>f.severity==="high").length;return{ecosystem:"npm",command,findings,criticalCount,highCount,totalCount:findings.length,clean:findings.length===0}}catch(error93){return npmAuditFailure(command,error93)}}function mapNpmSeverity(severity2){switch(severity2.toLowerCase()){case"critical":return"critical";case"high":return"high";case"moderate":return"moderate";case"low":return"low";default:return"info"}}async function runPipAudit(directory){let command=["pip-audit","--format=json"];try{let proc=bunSpawn(command,{stdout:"pipe",stderr:"pipe",cwd:directory}),timeoutPromise=new Promise((resolve131)=>setTimeout(()=>resolve131("timeout"),AUDIT_TIMEOUT_MS)),result=await Promise.race([Promise.all([proc.stdout.text(),proc.stderr.text()]).then(([stdout2,stderr2])=>({stdout:stdout2,stderr:stderr2})),timeoutPromise]);if(result==="timeout")return proc.kill(),{ecosystem:"pip",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:`pip-audit timed out after ${AUDIT_TIMEOUT_MS/1000}s`};let{stdout,stderr}=result;if(stdout.length>MAX_OUTPUT_BYTES8)stdout=stdout.slice(0,MAX_OUTPUT_BYTES8);if(await proc.exited===0&&!stdout.trim())return{ecosystem:"pip",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0};let packages=[];try{let parsed=JSON.parse(stdout);if(Array.isArray(parsed))packages=parsed;else if(parsed.dependencies)packages=parsed.dependencies}catch{if(stderr.includes("not installed")||stdout.includes("not installed")||stderr.includes("command not found"))return{ecosystem:"pip",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:"pip-audit not installed. Install with: pip install pip-audit"};return{ecosystem:"pip",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:`pip-audit output could not be parsed: ${stdout.slice(0,200)}`}}let findings=[];for(let pkg of packages)if(pkg.vulns&&pkg.vulns.length>0)for(let vuln of pkg.vulns){let severity2=vuln.aliases&&vuln.aliases.length>0?"high":"moderate";findings.push({package:pkg.name,installedVersion:pkg.version,patchedVersion:vuln.fix_versions&&vuln.fix_versions.length>0?vuln.fix_versions[0]:null,severity:severity2,title:vuln.id,cve:vuln.aliases&&vuln.aliases.length>0?vuln.aliases[0]:null,url:vuln.id.startsWith("CVE-")?`https://nvd.nist.gov/vuln/detail/${vuln.id}`:null})}let criticalCount=findings.filter((f)=>f.severity==="critical").length,highCount=findings.filter((f)=>f.severity==="high").length;return{ecosystem:"pip",command,findings,criticalCount,highCount,totalCount:findings.length,clean:findings.length===0}}catch(error93){let errorMessage3=error93 instanceof Error?error93.message:"Unknown error";if(errorMessage3.includes("not found")||errorMessage3.includes("not recognized")||errorMessage3.includes("pip-audit"))return{ecosystem:"pip",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:"pip-audit not installed. Install with: pip install pip-audit"};return{ecosystem:"pip",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:`Error running pip-audit: ${errorMessage3}`}}}async function runCargoAudit(directory){let command=[..._internals273.resolveAuditCommand("cargo"),"audit","--json"];try{let proc=_internals273.bunSpawn(command,{stdout:"pipe",stderr:"pipe",cwd:directory,...command[0]==="cmd.exe"?{windowsVerbatimArguments:!0,killProcessTree:!0}:{}}),timeoutPromise=new Promise((resolve131)=>setTimeout(()=>resolve131("timeout"),AUDIT_TIMEOUT_MS)),result=await Promise.race([Promise.all([proc.stdout.text(),proc.stderr.text()]).then(([stdout2,stderr])=>({stdout:stdout2,stderr})),timeoutPromise]);if(result==="timeout")return proc.kill(),{ecosystem:"cargo",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:`cargo audit timed out after ${AUDIT_TIMEOUT_MS/1000}s`};let{stdout,stderr:_stderr}=result;if(stdout.length>MAX_OUTPUT_BYTES8)stdout=stdout.slice(0,MAX_OUTPUT_BYTES8);let exitCode=await proc.exited;if(proc.spawnError)return cargoAuditFailure(command,proc.spawnError);if(exitCode===0)return{ecosystem:"cargo",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0};let findings=[],lines=stdout.split(`
|
|
7464
7464
|
`).filter((line)=>line.trim());for(let line of lines)try{let obj=JSON.parse(line);if(obj.vulnerabilities?.list)for(let item of obj.vulnerabilities.list){let cvss=item.advisory.cvss||0,severity2=mapCargoSeverity(cvss);findings.push({package:item.advisory.package,installedVersion:item.package.version,patchedVersion:item.versions.patched&&item.versions.patched.length>0?item.versions.patched[0]:null,severity:severity2,title:item.advisory.title,cve:item.advisory.aliases&&item.advisory.aliases.length>0?item.advisory.aliases[0]:item.advisory.id?item.advisory.id:null,url:item.advisory.url||null})}}catch{}let criticalCount=findings.filter((f)=>f.severity==="critical").length,highCount=findings.filter((f)=>f.severity==="high").length;return{ecosystem:"cargo",command,findings,criticalCount,highCount,totalCount:findings.length,clean:findings.length===0}}catch(error93){return cargoAuditFailure(command,error93)}}function mapCargoSeverity(cvss){if(cvss>=9)return"critical";if(cvss>=7)return"high";if(cvss>=4)return"moderate";return"low"}async function runGoAudit(directory){let command=["govulncheck","-json","./..."];if(!isCommandAvailable("govulncheck"))return warn("[pkg-audit] govulncheck not found, skipping Go audit"),{ecosystem:"go",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:"govulncheck not installed. Install with: go install golang.org/x/vuln/cmd/govulncheck@latest"};try{let proc=bunSpawn(command,{stdout:"pipe",stderr:"pipe",cwd:directory}),timeoutPromise=new Promise((resolve131)=>setTimeout(()=>resolve131("timeout"),AUDIT_TIMEOUT_MS)),result=await Promise.race([Promise.all([proc.stdout.text(),proc.stderr.text()]).then(([stdout2,stderr])=>({stdout:stdout2,stderr})),timeoutPromise]);if(result==="timeout")return proc.kill(),{ecosystem:"go",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:`govulncheck timed out after ${AUDIT_TIMEOUT_MS/1000}s`};let{stdout}=result;if(stdout.length>MAX_OUTPUT_BYTES8)stdout=stdout.slice(0,MAX_OUTPUT_BYTES8);let exitCode=await proc.exited;if(exitCode!==0&&exitCode!==3)return{ecosystem:"go",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:`govulncheck exited with code ${exitCode}`};if(exitCode===0)return{ecosystem:"go",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0};let osvMap=new Map,goFindings=[],lines=stdout.split(`
|
|
7465
7465
|
`).filter((line)=>line.trim());for(let line of lines)try{let obj=JSON.parse(line);if(obj.osv)osvMap.set(obj.osv.id,obj.osv);if(obj.finding)goFindings.push(obj.finding)}catch{}let findings=[];for(let finding of goFindings){let osv=osvMap.get(finding.osv),severity2=osv?.aliases?.some((a)=>a.startsWith("CVE-"))??!1?"high":"moderate",cve=osv?.aliases?.find((a)=>a.startsWith("CVE-"))??null,url3=osv?.references?.find((r)=>r.type==="WEB")?.url??`https://pkg.go.dev/vuln/${finding.osv}`,trace0=finding.trace[0],pkgName=trace0?.module??finding.osv,installedVersion=trace0?.version??"unknown";findings.push({package:pkgName,installedVersion,patchedVersion:finding.fixed_by??null,severity:severity2,title:osv?.summary??finding.osv,cve,url:url3})}let criticalCount=findings.filter((f)=>f.severity==="critical").length,highCount=findings.filter((f)=>f.severity==="high").length;return{ecosystem:"go",command,findings,criticalCount,highCount,totalCount:findings.length,clean:findings.length===0}}catch(error93){let errorMessage3=error93 instanceof Error?error93.message:"Unknown error";return{ecosystem:"go",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:`Error running govulncheck: ${errorMessage3}`}}}async function runDotnetAudit(directory){let command=["dotnet","list","package","--vulnerable","--include-transitive"];if(!isCommandAvailable("dotnet"))return warn("[pkg-audit] dotnet not found, skipping .NET audit"),{ecosystem:"dotnet",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:"dotnet CLI not installed. Install from: https://dotnet.microsoft.com/download"};try{let proc=bunSpawn(command,{stdout:"pipe",stderr:"pipe",cwd:directory}),timeoutPromise=new Promise((resolve131)=>setTimeout(()=>resolve131("timeout"),AUDIT_TIMEOUT_MS)),result=await Promise.race([Promise.all([proc.stdout.text(),proc.stderr.text()]).then(([stdout2,stderr])=>({stdout:stdout2,stderr})),timeoutPromise]);if(result==="timeout")return proc.kill(),{ecosystem:"dotnet",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:`dotnet list package timed out after ${AUDIT_TIMEOUT_MS/1000}s`};let{stdout}=result;if(stdout.length>MAX_OUTPUT_BYTES8)stdout=stdout.slice(0,MAX_OUTPUT_BYTES8);let exitCode=await proc.exited;if(exitCode!==0&&!stdout.includes("has the following vulnerable packages"))return{ecosystem:"dotnet",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:`dotnet list package exited with code ${exitCode}`};let vulnLinePattern=/^\s*>\s+(\S+)\s+\S+\s+(\S+)\s+(Critical|High|Moderate|Low)\s+(\S+)/i,findings=[],lines=stdout.split(`
|
|
7466
7466
|
`);for(let line of lines){let match=line.match(vulnLinePattern);if(match){let[,pkgName,resolvedVersion,severityStr,url3]=match,severity2=mapDotnetSeverity(severityStr);findings.push({package:pkgName,installedVersion:resolvedVersion,patchedVersion:null,severity:severity2,title:`Vulnerable package: ${pkgName}`,cve:null,url:url3})}}let criticalCount=findings.filter((f)=>f.severity==="critical").length,highCount=findings.filter((f)=>f.severity==="high").length;return{ecosystem:"dotnet",command,findings,criticalCount,highCount,totalCount:findings.length,clean:findings.length===0}}catch(error93){let errorMessage3=error93 instanceof Error?error93.message:"Unknown error";return{ecosystem:"dotnet",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:`Error running dotnet list package: ${errorMessage3}`}}}function mapDotnetSeverity(severity2){switch(severity2.toLowerCase()){case"critical":return"critical";case"high":return"high";case"moderate":return"moderate";case"low":return"low";default:return"info"}}async function runBundleAudit(directory){let useBundleExec=!isCommandAvailable("bundle-audit")&&isCommandAvailable("bundle");if(!isCommandAvailable("bundle-audit")&&!isCommandAvailable("bundle"))return warn("[pkg-audit] bundle-audit not found, skipping Ruby audit"),{ecosystem:"ruby",command:["bundle-audit","check","--format","json"],findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:"bundle-audit not installed. Install with: gem install bundler-audit"};let command=useBundleExec?["bundle","exec","bundle-audit","check","--format","json"]:["bundle-audit","check","--format","json"];try{let proc=bunSpawn(command,{stdout:"pipe",stderr:"pipe",cwd:directory}),timeoutPromise=new Promise((resolve131)=>setTimeout(()=>resolve131("timeout"),AUDIT_TIMEOUT_MS)),result=await Promise.race([Promise.all([proc.stdout.text(),proc.stderr.text()]).then(([stdout2,stderr])=>({stdout:stdout2,stderr})),timeoutPromise]);if(result==="timeout")return proc.kill(),{ecosystem:"ruby",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:`bundle-audit timed out after ${AUDIT_TIMEOUT_MS/1000}s`};let{stdout}=result;if(stdout.length>MAX_OUTPUT_BYTES8)stdout=stdout.slice(0,MAX_OUTPUT_BYTES8);let exitCode=await proc.exited;if(exitCode!==0&&exitCode!==1)return{ecosystem:"ruby",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:`bundle-audit failed with exit code ${exitCode}`};if(exitCode===0)return{ecosystem:"ruby",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0};let response;try{response=JSON.parse(stdout)}catch{return{ecosystem:"ruby",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:"bundle-audit JSON output could not be parsed"}}let findings=[];for(let item of response.results??[]){let adv=item.advisory,severity2=mapBundleSeverity(adv);findings.push({package:item.gem.name,installedVersion:item.gem.version,patchedVersion:adv.patched_versions?.[0]??null,severity:severity2,title:adv.title,cve:adv.cve??null,url:adv.url})}let criticalCount=findings.filter((f)=>f.severity==="critical").length,highCount=findings.filter((f)=>f.severity==="high").length;return{ecosystem:"ruby",command,findings,criticalCount,highCount,totalCount:findings.length,clean:findings.length===0}}catch(error93){let errorMessage3=error93 instanceof Error?error93.message:"Unknown error",isNotInstalled=errorMessage3.includes("not recognized")||errorMessage3.includes("not found")||errorMessage3.includes("No such file")||errorMessage3.includes("ENOENT");return{ecosystem:"ruby",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:isNotInstalled?"bundle-audit not installed. Install with: gem install bundler-audit":`Error running bundle-audit: ${errorMessage3}`}}}function mapBundleSeverity(adv){if(adv.criticality)switch(adv.criticality.toLowerCase()){case"critical":return"critical";case"high":return"high";case"medium":return"moderate";case"low":return"low"}let cvss=adv.cvss_v3??adv.cvss_v2??0;if(cvss>=9)return"critical";if(cvss>=7)return"high";if(cvss>=4)return"moderate";return"low"}async function runDartAudit(directory){let dartBin=isCommandAvailable("dart")?"dart":isCommandAvailable("flutter")?"flutter":null;if(!dartBin)return warn("[pkg-audit] dart/flutter not found, skipping Dart audit"),{ecosystem:"dart",command:["dart","pub","outdated","--json"],findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:"dart or flutter not installed. Install from: https://dart.dev/get-dart"};let command=[dartBin,"pub","outdated","--json"];try{let proc=bunSpawn(command,{stdout:"pipe",stderr:"pipe",cwd:directory}),timeoutPromise=new Promise((resolve131)=>setTimeout(()=>resolve131("timeout"),AUDIT_TIMEOUT_MS)),result=await Promise.race([Promise.all([proc.stdout.text(),proc.stderr.text()]).then(([stdout2,stderr])=>({stdout:stdout2,stderr})),timeoutPromise]);if(result==="timeout")return proc.kill(),{ecosystem:"dart",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:`dart pub outdated timed out after ${AUDIT_TIMEOUT_MS/1000}s`};let{stdout}=result;if(stdout.length>MAX_OUTPUT_BYTES8)stdout=stdout.slice(0,MAX_OUTPUT_BYTES8);let exitCode=await proc.exited;if(exitCode!==0)return{ecosystem:"dart",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:`dart pub outdated exited with code ${exitCode}`};let response;try{response=JSON.parse(stdout)}catch{return{ecosystem:"dart",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:"dart pub outdated JSON output could not be parsed"}}let findings=[];for(let pkg of response.packages??[]){let current=pkg.current?.version,latest=pkg.latest?.version;if(!current||!latest||current===latest)continue;if(!pkg.upgradable)continue;findings.push({package:pkg.package,installedVersion:current,patchedVersion:pkg.upgradable.version,severity:"info",title:`Outdated package: ${pkg.package} (${current} → ${latest})`,cve:null,url:`https://pub.dev/packages/${pkg.package}`})}return{ecosystem:"dart",command,findings,criticalCount:0,highCount:0,totalCount:findings.length,clean:findings.length===0,note:"dart pub outdated reports outdated packages, not security vulnerabilities"}}catch(error93){let errorMessage3=error93 instanceof Error?error93.message:"Unknown error";return{ecosystem:"dart",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:`Error running dart pub outdated: ${errorMessage3}`}}}async function runComposerAudit(directory){let command=["composer","audit","--locked","--format=json"];if(!isCommandAvailable("composer"))return warn("[pkg-audit] composer not found, skipping Composer audit"),{ecosystem:"composer",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:"composer not installed or not on PATH"};try{let proc=bunSpawn(command,{stdout:"pipe",stderr:"pipe",cwd:directory}),timeoutPromise=new Promise((resolve131)=>setTimeout(()=>resolve131("timeout"),AUDIT_TIMEOUT_MS)),result=await Promise.race([Promise.all([proc.stdout.text(),proc.stderr.text()]).then(([stdout2,stderr])=>({stdout:stdout2,stderr})),timeoutPromise]);if(result==="timeout")return proc.kill(),{ecosystem:"composer",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:`composer audit timed out after ${AUDIT_TIMEOUT_MS/1000}s`};let{stdout}=result;if(stdout.length>MAX_OUTPUT_BYTES8)stdout=stdout.slice(0,MAX_OUTPUT_BYTES8);let exitCode=await proc.exited,hasVulnerabilities=(exitCode&1)!==0,hasAbandoned=(exitCode&2)!==0;if(exitCode===0)return{ecosystem:"composer",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0};if(hasVulnerabilities&&!stdout.trim())return{ecosystem:"composer",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!1,incomplete:!0,note:`composer audit returned exit code ${exitCode} indicating vulnerabilities but produced no output`};let parsed;try{parsed=JSON.parse(stdout||"{}")}catch{return{ecosystem:"composer",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!hasVulnerabilities,incomplete:!0,note:`composer audit returned exit code ${exitCode} but output was not valid JSON`}}if(!hasVulnerabilities&&hasAbandoned){let abandonedList=Object.keys(parsed.abandoned??{});return{ecosystem:"composer",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,note:abandonedList.length>0?`Abandoned packages detected: ${abandonedList.join(", ")}`:"composer audit exit 2 (abandoned packages)"}}let findings=[];for(let advisories of Object.values(parsed.advisories??{}))for(let advisory of advisories){let hasCve=Boolean(advisory.cve?.trim());findings.push({package:advisory.packageName,installedVersion:"see composer.lock",patchedVersion:null,severity:hasCve?"high":"moderate",title:advisory.title,cve:advisory.cve||null,url:advisory.link||null})}let criticalCount=findings.filter((f)=>f.severity==="critical").length,highCount=findings.filter((f)=>f.severity==="high").length,abandonedNote=hasAbandoned&&Object.keys(parsed.abandoned??{}).length>0?` Also abandoned: ${Object.keys(parsed.abandoned).join(", ")}`:"";return{ecosystem:"composer",command,findings,criticalCount,highCount,totalCount:findings.length,clean:!1,...abandonedNote?{note:abandonedNote.trim()}:{}}}catch(error93){return{ecosystem:"composer",command,findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0,incomplete:!0,note:`composer audit error: ${error93 instanceof Error?error93.message:String(error93)}`}}}async function runAutoAudit(directory){let ecosystems=detectEcosystems(directory);if(ecosystems.length===0)return{ecosystems:[],findings:[],criticalCount:0,highCount:0,totalCount:0,clean:!0};let results=[];for(let eco of ecosystems)switch(eco){case"npm":results.push(await runNpmAudit(directory));break;case"pip":results.push(await runPipAudit(directory));break;case"cargo":results.push(await runCargoAudit(directory));break;case"go":results.push(await runGoAudit(directory));break;case"dotnet":results.push(await runDotnetAudit(directory));break;case"ruby":results.push(await runBundleAudit(directory));break;case"dart":results.push(await runDartAudit(directory));break;case"composer":results.push(await runComposerAudit(directory));break}let allFindings=[],totalCritical=0,totalHigh=0,notes=[],ecosystemsIncomplete=[],anyIncomplete=!1;for(let result of results){if(allFindings.push(...result.findings),totalCritical+=result.criticalCount,totalHigh+=result.highCount,result.note)notes.push(result.note);if(result.incomplete)anyIncomplete=!0,ecosystemsIncomplete.push(result.ecosystem)}return{ecosystems,findings:allFindings,criticalCount:totalCritical,highCount:totalHigh,totalCount:allFindings.length,clean:allFindings.length===0&&!anyIncomplete,notes,ecosystemsIncomplete}}var pkg_audit=createSwarmTool({description:'Run package manager security audit (npm, pip, cargo, go, dotnet, ruby, dart) and return structured CVE data. Use ecosystem to specify which package manager, or "auto" to detect from project files.',args:{ecosystem:exports_external.enum(["auto","npm","pip","cargo","go","dotnet","ruby","dart","composer"]).default("auto").describe('Package ecosystem to audit: "auto" (detect from project files), "npm", "pip", "cargo", "go" (govulncheck), "dotnet" (dotnet list package), "ruby" (bundle-audit), "dart" (dart pub outdated), or "composer" (Composer/PHP)')},async execute(args2,directory){if(!validateArgs3(args2))return JSON.stringify({error:'Invalid arguments: ecosystem must be "auto", "npm", "pip", "cargo", "go", "dotnet", "ruby", "dart", or "composer"'},null,2);if(!directory||typeof directory!=="string"||directory.trim()==="")return JSON.stringify({error:"project directory is required but was not provided"},null,2);let ecosystem=args2.ecosystem||"auto",result;switch(ecosystem){case"auto":result=await runAutoAudit(directory);break;case"npm":result=await runNpmAudit(directory);break;case"pip":result=await runPipAudit(directory);break;case"cargo":result=await runCargoAudit(directory);break;case"go":result=await runGoAudit(directory);break;case"dotnet":result=await runDotnetAudit(directory);break;case"ruby":result=await runBundleAudit(directory);break;case"dart":result=await runDartAudit(directory);break;case"composer":result=await runComposerAudit(directory);break}return JSON.stringify(result,null,2)}});init_zod();init_config();init_manager2();init_registry();init_utils();init_path_security();init_create_tool();import*as fs201 from"node:fs";import*as path329 from"node:path";var MAX_FILE_SIZE=1048576,DEFAULT_SENTINEL_ALLOWLIST=["SC-PLACEHOLDER"],DEFAULT_COMMENT_PATTERNS=[{pattern:/\bTODO\b/i,rule_id:"placeholder/comment-todo"},{pattern:/\bFIXME\b/i,rule_id:"placeholder/comment-fixme"},{pattern:/\bTBD\b/i,rule_id:"placeholder/comment-other"},{pattern:/\bXXX\b/,rule_id:"placeholder/comment-other"},{pattern:/\bHACK\b/i,rule_id:"placeholder/comment-other"}],DEFAULT_STRING_PATTERNS=[{pattern:/"[^"]*\bplaceholder\b[^"]*"/i,rule_id:"placeholder/text-placeholder"},{pattern:/"[^"]*\bstub\b[^"]*"/i,rule_id:"placeholder/text-placeholder"},{pattern:/"[^"]*\bwip\b[^"]*"/i,rule_id:"placeholder/text-placeholder"},{pattern:/"[^"]*\bnot implemented\b[^"]*"/i,rule_id:"placeholder/text-placeholder"},{pattern:/'[^']*\bplaceholder\b[^']*'/i,rule_id:"placeholder/text-placeholder"},{pattern:/'[^']*\bstub\b[^']*'/i,rule_id:"placeholder/text-placeholder"},{pattern:/'[^']*\bwip\b[^']*'/i,rule_id:"placeholder/text-placeholder"},{pattern:/`[^`]*\bplaceholder\b[^`]*`/i,rule_id:"placeholder/text-placeholder"},{pattern:/`[^`]*\bstub\b[^`]*`/i,rule_id:"placeholder/text-placeholder"}],FILE_ALLOWLIST=["src/tools/declare-scope.ts","src/tools/placeholder-scan.ts"],DEFAULT_CODE_PATTERNS=[{pattern:/throw\s+new\s+Error\s*\(\s*["'][^"']*\bTODO\b[^"']*["']\s*\)/i,rule_id:"placeholder/code-throw-todo"},{pattern:/throw\s+new\s+Error\s*\(\s*["'][^"']*\bFIXME\b[^"']*["']\s*\)/i,rule_id:"placeholder/code-throw-todo"},{pattern:/return\s+null\s*;/,rule_id:"placeholder/code-stub-return"},{pattern:/return\s+undefined\s*;/,rule_id:"placeholder/code-stub-return"},{pattern:/return\s+None\s*$/m,rule_id:"placeholder/code-stub-return"},{pattern:/return\s+0\s*;/,rule_id:"placeholder/code-stub-return"},{pattern:/return\s+false\s*;/i,rule_id:"placeholder/code-stub-return"},{pattern:/return\s+true\s*;/i,rule_id:"placeholder/code-stub-return"},{pattern:/return\s+""\s*;/,rule_id:"placeholder/code-stub-return"},{pattern:/return\s+\[\]\s*;/,rule_id:"placeholder/code-stub-return"},{pattern:/return\s+\{\}\s*;/,rule_id:"placeholder/code-stub-return"},{pattern:/return\s+nil\s*;/,rule_id:"placeholder/code-stub-return"}],PLAN_PLACEHOLDER_PATTERNS=[{pattern:/\[task\]/gi,rule_id:"placeholder/plan-bracket-task"},{pattern:/\[Project\]/g,rule_id:"placeholder/plan-bracket-project"},{pattern:/\[date\]/g,rule_id:"placeholder/plan-bracket-date"},{pattern:/\[reason\]/g,rule_id:"placeholder/plan-bracket-reason"},{pattern:/\[description\]/gi,rule_id:"placeholder/plan-bracket-description"}],TEST_PATH_PATTERNS=[/\.test\./,/\.spec\./,/\btests?\//,/\b__tests?__\//,/\bmocks?\//,/\b__mocks?__\//,/\bspecs?\//,/\b__specs?__\//],SCAFFOLD_PATH_PATTERNS=[/\bgenerated\//,/\bscaffold\//,/\btemplates?\//,/\b__generated__\//,/\b__scaffold__\//],SCAFFOLD_FILENAME_PATTERNS=[/^gen-/,/^scaffold-/,/^template-/,/\.gen\./,/\.scaffold\./,/\.template\./],SUPPORTED_PARSER_EXTENSIONS=new Set([".js",".jsx",".ts",".tsx",".py",".go",".rs",".java",".c",".cpp",".h",".hpp",".cs",".php",".blade.php",".rb"]);function isTestFile2(filePath){let normalizedPath=filePath.toLowerCase().replace(/\\/g,"/");return TEST_PATH_PATTERNS.some((pattern)=>pattern.test(normalizedPath))}function isScaffoldFile(filePath){let normalizedPath=filePath.toLowerCase().replace(/\\/g,"/");if(SCAFFOLD_PATH_PATTERNS.some((pattern)=>pattern.test(normalizedPath)))return!0;let filename=path329.basename(filePath);if(SCAFFOLD_FILENAME_PATTERNS.some((pattern)=>pattern.test(filename)))return!0;return!1}function isAllowedByGlobs(filePath,allowGlobs){if(!allowGlobs||allowGlobs.length===0)return!1;let normalizedPath=filePath.toLowerCase().replace(/\\/g,"/");for(let glob of allowGlobs)try{let regexPattern=glob.replace(/\*\*/g,"<<<DBL>>>").replace(/\*/g,"([^/]+)").replace(/<<<DBL>>>/g,"(.*)");if(new RegExp(`^${regexPattern}`,"i").test(normalizedPath))return!0;let filename=path329.basename(filePath);if(new RegExp(`^${regexPattern}$`,"i").test(filename))return!0}catch{}return!1}function isParserSupported(filePath){let ext=path329.extname(filePath).toLowerCase();return SUPPORTED_PARSER_EXTENSIONS.has(ext)}var BODY_SHAPE_SUPPORTED_EXTENSIONS=new Set([".js",".jsx",".ts",".tsx",".py"]);function isBodyShapeSupported(filePath){return BODY_SHAPE_SUPPORTED_EXTENSIONS.has(path329.extname(filePath).toLowerCase())}function isPlanFile(filePath){let normalizedPath=filePath.toLowerCase().replace(/\\/g,"/");return normalizedPath.endsWith(".swarm/plan.md")||normalizedPath.includes("/.swarm/plan.md")}function scanPlanFileForPlaceholders(content,filePath,addedLines){let findings=[],lines=content.split(`
|