opencode-swarm 7.184.9 → 7.184.10
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-wv26kvbq.js → coder-settlement-b47vmcm9.js} +11 -11
- package/dist/cli/{config-doctor-0v3a8gwd.js → config-doctor-3j3m2ccc.js} +3 -3
- package/dist/cli/{core-sw3g54fw.js → core-td5kj2w8.js} +4 -4
- package/dist/cli/{curation-policy-734npcqk.js → curation-policy-xe77n9zj.js} +4 -4
- package/dist/cli/{curator-1ffd62zb.js → curator-c7we2apv.js} +38 -38
- package/dist/cli/{curator-drift-hbpphpph.js → curator-drift-wxyhgz7y.js} +9 -9
- package/dist/cli/curator-llm-factory-1260n9ty.js +75 -0
- package/dist/cli/{evidence-summary-service-yynh7bqj.js → evidence-summary-service-2t1ttdgj.js} +17 -17
- package/dist/cli/{gate-evidence-72cmq7sq.js → gate-evidence-5w2q1h5w.js} +8 -6
- package/dist/cli/guardrail-explain-qeywnmza.js +76 -0
- package/dist/cli/{guardrail-log-7202nsc9.js → guardrail-log-5zwqdhaf.js} +7 -7
- package/dist/cli/{guardrail-reset-nwyhnz98.js → guardrail-reset-qnq1swzf.js} +38 -38
- package/dist/cli/{hive-promoter-0b8ht2g0.js → hive-promoter-c3c6tz3b.js} +38 -38
- package/dist/cli/{index-d5vkn5eg.js → index-07fqfseh.js} +2 -2
- package/dist/cli/{index-955e0wpp.js → index-0ajyhjht.js} +1 -1
- package/dist/cli/{index-snzz0yvz.js → index-0d7e94zg.js} +7 -7
- package/dist/cli/{index-1r22v0js.js → index-0mj7hc2z.js} +1 -1
- package/dist/cli/{index-tdtqm702.js → index-19e61hgv.js} +12 -12
- package/dist/cli/{index-0hzr6vdh.js → index-1g2bm6ht.js} +2 -2
- package/dist/cli/{index-gj0121y5.js → index-260174fq.js} +4 -4
- package/dist/cli/{index-g2jbpm6g.js → index-35cdceqf.js} +1 -1
- package/dist/cli/{index-zvz722td.js → index-3rfc2v1d.js} +3 -3
- package/dist/cli/{index-cbwmx38c.js → index-3wgvpxmv.js} +76 -76
- package/dist/cli/{index-hkbs7pcd.js → index-45h58v8d.js} +7 -7
- package/dist/cli/{index-ezagem2g.js → index-48jvqqfa.js} +2 -2
- package/dist/cli/{index-et6gxgbn.js → index-4szb7qpv.js} +37 -6
- package/dist/cli/{index-na3qxeha.js → index-54f1payv.js} +2 -2
- package/dist/cli/{index-s9pq2q6h.js → index-5m1b70z3.js} +1 -1
- package/dist/cli/{index-z5nqpnem.js → index-7849gy4s.js} +5 -5
- package/dist/cli/{index-yn0nsxwv.js → index-8n2dh26k.js} +1 -1
- package/dist/cli/{index-tps93cp3.js → index-95vytkv6.js} +4 -4
- package/dist/cli/{index-vx1dt9x3.js → index-9jz73x8x.js} +38 -38
- package/dist/cli/{index-5egfk9c6.js → index-aae38s4x.js} +1 -1
- package/dist/cli/{index-tkk06smw.js → index-b6saxkqj.js} +2 -2
- package/dist/cli/{index-zygpw9qb.js → index-be5h97z8.js} +1 -1
- package/dist/cli/{index-hp5xyqxs.js → index-bhj3zx43.js} +1 -1
- package/dist/cli/{index-kf8gkdtq.js → index-bt1k1ek3.js} +1 -1
- package/dist/cli/{index-cq1gpknp.js → index-cjh92zm9.js} +40 -40
- package/dist/cli/{index-f2xrc6r5.js → index-djnxehe7.js} +6 -6
- package/dist/cli/{index-7wth46ez.js → index-dqpq8m9w.js} +2 -2
- package/dist/cli/{index-mk9kd5wr.js → index-f336fv53.js} +4 -4
- package/dist/cli/{index-cvrtpb52.js → index-fn1y9jpv.js} +3 -3
- package/dist/cli/{index-jnts5d04.js → index-fxtgxe04.js} +7 -7
- package/dist/cli/{index-fx0kf5jt.js → index-gnryhmak.js} +1 -1
- package/dist/cli/{index-kjetx4xq.js → index-hk0eh9qb.js} +1 -1
- package/dist/cli/{index-fanhmwk3.js → index-hs26e3k6.js} +2 -2
- package/dist/cli/{index-hq9fezjc.js → index-j4efx148.js} +2 -2
- package/dist/cli/{index-7e1ecg26.js → index-kg2mb1m5.js} +1 -1
- package/dist/cli/{index-g4ft1r0z.js → index-nh5fxxc9.js} +1 -1
- package/dist/cli/{index-v5r7w16s.js → index-pj877ads.js} +5 -5
- package/dist/cli/{index-2ebf550v.js → index-q7q00ppx.js} +6 -6
- package/dist/cli/{index-48ceyvpc.js → index-ta2kp4xy.js} +5 -5
- package/dist/cli/{index-qjs6cgb9.js → index-thcyqqdq.js} +2 -2
- package/dist/cli/{index-zg40ap5c.js → index-tzyppdv7.js} +3 -3
- package/dist/cli/{index-22qpvevn.js → index-x119gdak.js} +1 -1
- package/dist/cli/{index-rgrae86w.js → index-yyvkeev1.js} +4 -4
- package/dist/cli/index.js +39 -39
- package/dist/cli/{knowledge-escalator-a9h29ayc.js → knowledge-escalator-912nwxb4.js} +12 -12
- package/dist/cli/{knowledge-events-sjdhtwm2.js → knowledge-events-hvzj872f.js} +10 -10
- package/dist/cli/{knowledge-link-6kxpc4x5.js → knowledge-link-8tetyje0.js} +3 -3
- package/dist/cli/{knowledge-store-g3h4gqe7.js → knowledge-store-sqx0axb6.js} +4 -4
- package/dist/cli/{knowledge-validator-br05bd3x.js → knowledge-validator-d8m7p2vg.js} +6 -6
- package/dist/cli/{mcp-167c0dnd.js → mcp-nxxy0dq0.js} +1 -1
- package/dist/cli/{model-preflight-dxm5dcej.js → model-preflight-2mmep72y.js} +38 -38
- package/dist/cli/{pending-delegations-q9n8bry1.js → pending-delegations-fat9r7w1.js} +10 -10
- package/dist/cli/{pr-subscriptions-qs9fhjpk.js → pr-subscriptions-8xv7gaeb.js} +10 -10
- package/dist/cli/{pr-workflow-gate-nfbbc2c0.js → pr-workflow-gate-g9exsspv.js} +38 -38
- package/dist/cli/{runner-wfd9dys9.js → runner-ff0bj9w0.js} +4 -4
- package/dist/cli/{scan-cursor-z59x53tn.js → scan-cursor-h9tza4z6.js} +5 -5
- package/dist/cli/{schema-y3rs9evj.js → schema-1p9cw863.js} +2 -2
- package/dist/cli/{scope-persistence-54g2j63h.js → scope-persistence-xv6b7daq.js} +14 -14
- package/dist/cli/{server-gwgsy9t3.js → server-z5401cje.js} +40 -38
- package/dist/cli/{skill-generator-qc4bfp4z.js → skill-generator-72n07p92.js} +14 -14
- package/dist/cli/{snapshot-coordination-init-0pytgxbn.js → snapshot-coordination-init-xjyv8kxx.js} +38 -38
- package/dist/cli/{speckit-checkoff-d14y1jnc.js → speckit-checkoff-828xrjfd.js} +5 -5
- package/dist/cli/{workspace-snapshot-bvnyzzr2.js → workspace-snapshot-nrbvjh1c.js} +3 -3
- package/dist/cli/{worktree-collision-ownership-9gmtsqmf.js → worktree-collision-ownership-cr6vv3xk.js} +11 -11
- package/dist/cli/{worktree-isolation-22dntk4t.js → worktree-isolation-6yycqkc6.js} +38 -38
- package/dist/gate-evidence.d.ts +34 -0
- package/dist/index.js +19 -13
- package/dist/todo/todo-gate.d.ts +37 -0
- package/dist/tools/build-check.d.ts +6 -2
- package/dist/tools/phase-complete/gates/index.d.ts +1 -0
- package/dist/tools/phase-complete/gates/todo-gate.d.ts +14 -0
- package/dist/tools/phase-complete.d.ts +2 -1
- package/dist/tools/tool-metadata.d.ts +1 -1
- package/package.json +1 -1
- package/dist/cli/curator-llm-factory-0n05cgjf.js +0 -75
- package/dist/cli/guardrail-explain-sadek1sk.js +0 -76
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.184.9",description:"Architect-centric agentic swarm plugin for OpenCode - hub-and-spoke orchestration with SME consultation, code generation, and QA review",main:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",default:"./dist/index.js"},"./package.json":"./package.json"},bin:{"opencode-swarm":"./dist/cli/index.js"},type:"module",engines:{bun:">=1.3.13",node:">=22.13"},license:"MIT",repository:{type:"git",url:"https://github.com/ZaxbyHub/opencode-swarm.git"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},keywords:["opencode","opencode-plugin","ai","agents","orchestration","swarm","multi-agent","llm"],files:["dist","dist/lang/grammars","binaries","evaluation-fixtures",".opencode/skills/brainstorm",".opencode/skills/specify",".opencode/skills/clarify-spec",".opencode/skills/swarm-resume",".opencode/skills/clarify",".opencode/skills/discover",".opencode/skills/consult",".opencode/skills/pre-phase-briefing",".opencode/skills/council",".opencode/skills/deep-dive",".opencode/skills/deep-research",".opencode/skills/codebase-review-swarm",".opencode/skills/swarm-implement",".opencode/skills/design-docs",".opencode/skills/swarm-pr-review",".opencode/skills/swarm",".opencode/skills/swarm-pr-feedback",".opencode/skills/swarm-pr-subscribe",".opencode/skills/swarm-ci-monitor",".opencode/skills/issue-ingest",".opencode/skills/swarm-plan",".opencode/skills/critic-gate",".opencode/skills/execute",".opencode/skills/phase-wrap",".opencode/skills/loop",".opencode/skills/writing-tests",".opencode/skills/running-tests",".opencode/skills/engineering-conventions",".opencode/skills/commit-pr",".opencode/skills/ci-failure-batching",".opencode/skills/gate-attribution",".opencode/skills/merge-queue-readiness",".opencode/skills/skill-edit-validation",".opencode/skills/worktree-retry-cleanup",".opencode/skills/test-file-split",".opencode/skills/fork-pr-operations",".opencode/skills/parallel-work-check",".opencode/skills/ci-fix-monitor",".opencode/skills/issue-tracer",".opencode/skills/orchestrating-subagents",".opencode/skills/durable-session-state","tests/fixtures/memory-recall","tests/fixtures/memory-recall-heldout","opencode-swarm.schema.json","README.md","LICENSE"],scripts:{clean:`bun -e "require('fs').rmSync('dist',{recursive:true,force:true})"`,build:"bun run clean && bun run scripts/generate-config-schema.ts && bun run scripts/copy-grammars.ts && bun build src/index.ts --outdir dist --target node --format esm --external web-tree-sitter --minify-whitespace --minify-syntax && bun build src/cli/index.ts --outdir dist/cli --target bun --format esm --external bash-parser --splitting && bun run scripts/copy-grammars.ts --to-dist && tsc --emitDeclarationOnly",typecheck:"tsc --noEmit",test:"bun test",lint:"biome lint .","lint:ci":"biome ci .","test:unit:ci":"bun scripts/ci/run-unit-tests-local.ts","validate:repo":"bun scripts/ci/repository-validation.ts","drift:check":"bun run scripts/drift-check.ts","check:pre-push":"bun run scripts/drift-check.ts --enforce --no-report && bun run check:registry-citations","schema:generate":"bun run scripts/generate-config-schema.ts","generate:commands-docs":"bun run scripts/generate-commands-docs.ts","check:runtime-src-refs":"bun run scripts/check-runtime-src-refs.ts","drift:fix":"bun run scripts/drift-check.ts --fix --confirm","skills:sync":"bun run scripts/sync-qa-gate-skills.ts",format:"biome format . --write",check:"biome check --write .",dev:"bun run build && opencode","package:smoke":"node scripts/package-smoke.mjs",prepare:"bun run build","repro:704":"node scripts/repro-704.mjs","repro:2669":"node scripts/repro-2669.mjs","repro:2670":"node scripts/repro-2670.mjs","repro:1144":"bun scripts/repro-1144.mjs","repro:1873":"bun build scripts/repro-1873-entry.ts --outdir dist-build-test/repro-1873 --target node --format esm && node scripts/repro-1873.mjs","repro:2487":"bun build scripts/repro-2487-parity-entry.ts --outdir dist-build-test/repro-2487 --target node --format esm && node scripts/repro-2487-parity.mjs","check:events":"bun run scripts/check-event-contract.ts","check:retention":"bun run scripts/check-retention-registry.ts","check:core-events":"bun run scripts/check-core-events-usage.ts","check:shell-audit":"bun run scripts/check-shell-audit-usage.ts","check:trajectory-store":"bun run scripts/check-trajectory-store-usage.ts","check:mock-cleanup":"bun run scripts/check-mock-cleanup.ts","check:invariants":"bun run scripts/check-invariants.ts","check:token-formula":"bun run scripts/check-token-formula.ts","check:cross-contamination":"bun run scripts/check-cross-contamination.ts","check:test-clock":"bun run scripts/check-test-clock.ts","check:test-file-cap":"bun run scripts/check-test-file-cap.ts","check:test-tmpdir":"bun run scripts/check-test-tmpdir.ts","check:bash-portability":"bun run scripts/check-bash-portability.ts","check:pending-fragment":"bun run scripts/check-pending-fragment.ts","check:gate-portability":"bun run scripts/check-gate-portability.ts","check:bare-spawn":"bun run scripts/check-bare-executable-spawn.ts","check:error-channel-discard":"bun run scripts/check-error-channel-discard.ts","check:path-identity":"bun run scripts/check-path-identity.ts","check:registry-citations":"bun run scripts/check-registry-citations.ts","check:memory-recall":"bun run scripts/memory-recall-regression.ts","check:retrieval-quality":"bun run scripts/retrieval-quality-regression.ts"},dependencies:{"@modelcontextprotocol/sdk":"^1.30.0","@opencode-ai/plugin":"^1.18.3","@opencode-ai/sdk":"^1.18.3","@vscode/tree-sitter-wasm":"^0.3.0","bash-parser":"^0.5.0","p-limit":"^7.3.0",picomatch:"^4.0.4","proper-lockfile":"^4.1.2","quick-lru":"^7.3.0","web-tree-sitter":"^0.25.0",zod:"4.3.6"},devDependencies:{"@biomejs/biome":"2.3.14","@types/picomatch":"^4.0.3","bun-types":"1.3.8","js-yaml":"^4.1.1",typescript:"^5.7.3"},peerDependencies:{"@xenova/transformers":"^2.17.2"},peerDependenciesMeta:{"@xenova/transformers":{optional:!0}}}});var QA_AGENTS,PIPELINE_AGENTS,ORCHESTRATOR_NAME="architect",ALL_SUBAGENT_NAMES,ALL_AGENT_NAMES;var init_agent_names=__esm(()=>{QA_AGENTS=["reviewer","critic","critic_oversight","critic_finding_validator"],PIPELINE_AGENTS=["explorer","coder","test_engineer"],ALL_SUBAGENT_NAMES=["sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","curator_postmortem","curator_consolidation","council_generalist","council_skeptic","council_domain_expert","skill_improver","spec_writer",...QA_AGENTS,...PIPELINE_AGENTS],ALL_AGENT_NAMES=["architect",...ALL_SUBAGENT_NAMES]});function getPrWorkflowToolCapability(toolName,mode){let metadata=TOOL_METADATA[toolName];if(!metadata?.prWorkflow?.modes.includes(mode))return null;return metadata.prWorkflow.capability}var TOOL_METADATA,TOOL_NAMES,TOOL_NAME_SET,TOOL_DESCRIPTIONS,AGENT_TOOL_MAP;var init_tool_metadata=__esm(()=>{init_agent_names();TOOL_METADATA={diff:{description:"structured git diff with contract change detection",agents:["architect","reviewer","critic_finding_validator","critic_oversight","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},diff_summary:{description:"filter classified AST changes by category, risk level, or file for reviewer drill-down",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},syntax_check:{description:"check syntax of source files using tree-sitter parsers across multiple languages, returning per-file errors",agents:["architect","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},placeholder_scan:{description:"todo and FIXME comment detection",agents:["architect","reviewer","critic_finding_validator"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},imports:{description:"find all consumers that import from a given file — use before refactoring shared modules to avoid breaking unseen dependents",agents:["architect","sme","researcher","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},lint:{description:"run project linter in check or fix mode; supports biome, eslint, ruff, clippy, and more, returns structured results",agents:["architect","reviewer","critic_finding_validator","coder"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},secretscan:{description:"scan for secrets (API keys, tokens, passwords) via regex and entropy; returns redacted previews, excludes common dirs",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},sast_scan:{description:"static analysis security scan",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},build_check:{description:"discover and run build, typecheck, and test commands for various project ecosystems in the working directory",agents:["architect","coder","test_engineer"]},pre_check_batch:{description:"parallel verification: lint:check + secretscan + sast_scan + quality_budget",agents:["architect","reviewer","critic_finding_validator"]},quality_budget:{description:"code quality budget check",agents:["architect"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},symbols:{description:"extract exported symbols (functions, classes, interfaces, types) from source files; supports TypeScript, JavaScript, 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"]},approve_retry_sounding_board:{description:"record a MANUAL critic_sounding_board gate entry to unblock the coder retry circuit-breaker gate when the sounding board returned APPROVED but the mechanical recorder missed it (issue #2703)",agents:["architect"]},recover_rework_task:{description:"recover a task wedged at rework_required when the reviewer/test_engineer verdict did not require a code change: write a supervised stage_a_passed so those gates can be re-dispatched without re-running the coder (issue #2755)",agents:["architect"]},recover_stage_a_task:{description:"recover a task wedged in the settlement-backed Stage A deadlock — workflow at idle/blocked while a COMMITTED accepted coder settlement and green post-settlement pre-check proof justify Stage A: write a settlement-backed stage_a_passed so reviewer/test_engineer can be dispatched, without re-running the coder (issue #2828)",agents:["architect"]},prepare_pr_workflow_checkout:{description:"prepare an auditable PR workflow checkout or restore its exact original branch/HEAD and preserved stash after terminal cleanup",agents:["architect"]},invalidate_pr_feedback_publication:{description:"invalidate the armed PR_FEEDBACK publication generation so approved content can change, superseding every content-dependent approval and reopening the exact scoped rework + fresh-review path (issue #2108)",agents:["architect"]},record_implementation_review:{description:"record fresh-context reviewer + critic APPROVE verdicts for the implementation diff so the /swarm issue --trace workflow can satisfy its review gate before commit-pr handoff",agents:["architect"]},record_issue_publication:{description:"record a publication receipt so the /swarm issue --trace workflow reaches its terminal published state after the PR is created/updated",agents:["architect"]},record_issue_reproduction:{description:"record the reproduction outcome for the current traced issue so the /swarm issue --trace workflow can satisfy its reproduction gate and transition to PLAN",agents:["architect"]},record_recurrence_sweep:{description:"record the recurrence sweep (defect class, predicates, hit dispositions, guardrail proof, related-problems results) so the /swarm issue --trace workflow can satisfy its recurrence gate before commit-pr handoff",agents:["architect"]},record_branch_freshness:{description:"record the Phase 0 branch-freshness outcome (synced / behind:<n> / fetch-failed:<reason> plus optional user override) so the /swarm issue --trace workflow can pass its freshness gate before transitioning to PLAN (issue #2564)",agents:["architect"]},record_trace_validation:{description:"record one per-phase trace-check.sh validator outcome (phase, pass/fail, reviewedCommit, treeId) so the /swarm issue --trace workflow can satisfy its validator-receipt gate before commit-pr handoff (issue #2564)",agents:["architect"]},record_merge_approval:{description:"record the human merge approval bound to the exact PR head SHA so the /swarm issue --trace workflow reaches its terminal merge_approval_recorded state — recorded for audit only, never certified or driven by the plugin (issue #2564)",agents:["architect"]},rebind_pr_feedback_head:{description:"rebind a PR_FEEDBACK workflow to a new verified remote PR head after merge/rebase/conflict repair, invalidating ancestry-bound receipts so the mechanical ladder re-runs",agents:["architect"]},run_pr_feedback_stage_a:{description:"execute and persist mandatory PR-feedback Stage A checks on a content-bound revision",agents:["architect"]},submit_council_verdicts:{description:"submit pre-collected council member verdicts for synthesis (architect MUST dispatch critic/reviewer/sme/test_engineer/explorer as Agent tasks first; this tool synthesizes only, it does not contact members)",agents:[]},submit_phase_council_verdicts:{description:"submit pre-collected phase-level council member verdicts for holistic phase synthesis (architect MUST dispatch all 5 council members with phase-scoped context first; this tool synthesizes only, it does not contact members)",agents:[]},declare_council_criteria:{description:"pre-declare acceptance criteria for a task before the coder starts work; criteria are read back during council evaluation",agents:[]},sbom_generate:{description:"SBOM generation for dependency inventory",agents:["architect"]},checkpoint:{description:"create named git checkpoints for save, restore, and delete — use before risky operations to enable rollback",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; test selection comes from explicit files (override) or source_files derived via the impact analyzer with a typed bounded fallback",agents:["architect","test_engineer"]},generate_mutants:{description:"generate LLM-based mutation testing patches for source files; returns MutationPatch[] for direct consumption by the mutation_test tool",agents:["architect"]},detect_domains:{description:"detect which SME domains are relevant for a given text",agents:["architect","sme","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic","critic_oversight","explorer"]},git_blame:{description:"per-line git blame metadata: sha, author, date, summary for each line in a file",agents:["reviewer","critic_finding_validator","explorer","architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},gitingest:{description:"fetch a GitHub repository full content via gitingest.com",agents:["architect","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_summary:{description:"retrieve the full content of a stored tool output summary",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_lane_output:{description:"retrieve paged full dispatch lane output by output_ref; use before consuming truncated lane previews or routing candidates from lane results",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},extract_code_blocks:{description:"extract code blocks from text content and save them to files",agents:["docs","docs_design","designer","spec_writer","coder","test_engineer"]},phase_complete:{description:"preflight every applicable phase gate, report all blockers, and atomically commit a current passing snapshot",agents:["architect"]},run_phase_review:{description:"run the bounded phase-final review engine and persist complete content-addressed review evidence",agents:["architect"]},repair_gate_evidence:{description:"quarantine recoverable exact-task gate evidence, rebuild from durable requirements, recover receipt-backed legacy marker wedges or the exact sentinel-only historical reset, and refuse every other receipt-less reconstruction",agents:["architect"]},repair_knowledge_receipt_ledger:{description:"validate or repair authoritative knowledge receipts, preserve corrupt authority in bounded quarantine, 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"]},scope_validate:{description:"validate shell writes against an inline file scope",agents:["architect"]},knowledge_query:{description:"query swarm or hive knowledge with optional filters",agents:["architect","skill_improver","spec_writer"]},doc_scan:{description:"scan project documentation files and build an index manifest",agents:["architect","docs_design","skill_improver","spec_writer","explorer"]},doc_extract:{description:"extract actionable constraints from project documentation",agents:["architect","docs_design","skill_improver","spec_writer"]},curator_analyze:{description:"run curator phase analysis and optionally apply knowledge recommendations",agents:["architect"]},consensus_mine:{description:"mine cross-run consensus from existing .swarm evidence into an immutable proposals-only report; also deletes its own reports past consensus.report_retention, appends to the shared recommendation dedup ledger (in the shared cohort root, outside this project, when a knowledge link is active), and mirrors proposals into pending swarm-memory proposals when memory is enabled",agents:["architect","curator_phase","curator_postmortem"]},knowledge_add:{description:"store a new lesson in the knowledge base",agents:["architect","coder"]},knowledge_recall:{description:"search the knowledge base for relevant past decisions",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"]},knowledge_remove:{description:"delete an outdated swarm knowledge entry by ID (swarm tier only)",agents:["architect"]},co_change_analyzer:{description:"detect hidden couplings by analyzing git history",agents:["architect"]},context_status:{description:"report current context-window headroom for the active session — returns tokens-used, usageSource (provider|estimated), model-limit with provenance (modelLimitSource: host|override|provider_cap|native|fallback; modelLimitResolution: user_provider_model|user_model|user_default|live_model_limit|static_provider_cap|static_native|static_default; fallbackActive: true when the denominator came from a static table or the flat 128k default — treat headroom as uncertain), usage-percent, threshold-state (none/warn/critical), model name, and provider. Pure read-only: no state mutation, no warning injection. Works whether context_budget.enabled is true or false.",agents:["architect"]},search:{description:"Workspace-scoped ripgrep-style text search with structured JSON output. Supports literal and regex modes, glob filtering, and result limits. NOTE: This is text search, not structural AST search — use symbols and imports tools for structural queries.",agents:["architect","sme","docs","docs_design","designer","critic_hallucination_verifier","skill_improver","spec_writer","reviewer","critic_finding_validator","critic_oversight","explorer","coder","test_engineer","researcher"]},ast_grep:{description:"Read-only structural AST search using ast-grep patterns with optional language and glob filters. Use for syntax-aware code pattern searches; does not rewrite files.",agents:["architect","sme","docs","docs_design","critic_hallucination_verifier","spec_writer","explorer","coder","test_engineer","researcher"]},actionlint_scan:{description:"Run actionlint against GitHub Actions workflow YAML files with structured findings. Resolves actionlint lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},osv_scan:{description:"Run OSV-Scanner against a workspace path and return structured dependency vulnerability findings. Resolves osv-scanner lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},gh_evidence:{description:"Fetch bounded GitHub pull request or issue metadata through gh for review and CI evidence. Resolves gh lazily and is read-only.",agents:["architect","researcher"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},pr_workflow_status:{description:"Read-only architect observation of local git state (HEAD, branch, clean/dirty with a bounded changed-file list, remotes) plus a session-pinned PR workflow gate summary and the PR_FEEDBACK publication-generation section (state, attempts, invalidation reason, recovery guidance). Use to observe state under the fail-closed PR_REVIEW/PR_FEEDBACK gate. Never executes PR-controlled scripts and never reads another session gate.",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},batch_symbols:{description:"Batched symbol extraction across multiple files. Returns per-file symbol summaries with isolated error handling.",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","explorer"]},suggest_patch:{description:"Reviewer-safe structured patch suggestion tool. Produces context-anchored patch artifacts without file modification. Returns structured diagnostics on context mismatch.",agents:["architect","reviewer","critic_finding_validator"]},req_coverage:{description:"query requirement coverage status for tracked functional requirements",agents:["critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","critic","critic_oversight"]},get_approved_plan:{description:"retrieve the last critic-approved immutable plan snapshot for baseline drift comparison",agents:["critic_drift_verifier","critic","critic_oversight"]},repo_map:{description:"query the repo code graph: importers, dependencies, blast radius, localization, ontology facts, package boundaries, and heuristic preflight packets before refactoring; ontology findings are advisory, not formal proofs",agents:["architect","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},get_qa_gate_profile:{description:"retrieve the QA gate profile for the current or exact future plan identity: gates (reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council), lock state, profile hash, the calling session’s ratchet-tighter overrides, and the EFFECTIVE gates (profile merged with those overrides; durable across restart). Read-only and never creates state.",agents:["architect"]},set_qa_gates:{description:"configure the QA gate profile for the current plan or bootstrap an exact future plan with swarm_id and plan_title. Architect-only. The initial selection may set explicit true/false values over defaults; later changes are ratchet-tighter and rejected once locked after critic approval. Supports: reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council, plus adopt_legacy_binding_only for exact-binding recovery without mutating gates.",agents:["architect"]},web_search:{description:"External web search (Tavily or Brave) for architect-driven council research, SME domain research, researcher auto-research, and skill-improver research. Returns titled results with snippets, URLs, normalized query metadata, temporal intent, freshness, and removed stale years. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides. Requires a search API key. Used by the architect in MODE: COUNCIL to gather a RESEARCH CONTEXT before dispatching council agents, by SME for opt-in external skill/source evaluation, and by the researcher agent for multi-source auto-research.",agents:["sme","researcher","skill_improver"]},web_fetch:{description:"Fetch the readable text of a single http(s) URL (architect-only). Returns decoded page text, document title, final URL after redirects, and an evidence reference. Reads primary sources that web_search only surfaces as snippets. Config-gated on council.general.enabled. Blocks private/loopback/link-local/metadata addresses (re-validated and re-pinned across redirects); enforces timeout and body size cap.",agents:[]},convene_general_council:{description:"Synthesize responses from a multi-model General Council. Accepts parallel member responses (Round 1, optionally Round 2), detects disagreements, and returns consensus points, persisting disagreements, and a structured synthesis. Architect-only. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides.",agents:[]},write_final_council_evidence:{description:"Persist project-scoped final council evidence to .swarm/evidence/final-council.json. PREREQUISITE: dispatch critic, reviewer, sme, test_engineer, and explorer as project-scoped Agent tasks and collect their CouncilMemberVerdict JSON — this tool synthesizes only. Rejects on insufficient quorum or CONCERNS with unresolved requiredFixes; normalizes verdicts to approved/concerns/rejected. Architect-only.",agents:[]},skill_generate:{description:"compile knowledge entries into a structured SKILL.md draft",agents:["skill_improver"]},skill_list:{description:"list generated skill files and their status",agents:["skill_improver"]},skill_apply:{description:"activate a draft skill proposal",agents:[]},skill_inspect:{description:"inspect the content and source entries of a skill file",agents:["skill_improver"]},run_stale_reconciliation:{description:"reconcile skills against the knowledge store: mark skills stale when source knowledge is archived or deleted, or clear stale markers",agents:["architect"]},skill_regenerate:{description:"regenerate an active skill by re-clustering its source knowledge entries and updating the SKILL.md in place",agents:[]},skill_retire:{description:"retire a generated skill by adding a retired.marker file; retired skills are excluded from scoring and injection",agents:[]},skill_improve:{description:"run the skill_improver agent to review and refine skills",agents:["skill_improver"]},spec_write:{description:"author or update .swarm/spec.md for the current project",agents:["spec_writer"]},knowledge_receipt:{description:"file a receipt for retrieved knowledge (applied/ignored/contradicted + new lessons), recorded as immutable knowledge events",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},knowledge_receipt_status:{description:"receipt status",agents:["architect"]},knowledge_archive:{description:"archive (default), quarantine, or purge a swarm or hive knowledge entry by ID with an immutable audit tombstone; purge requires an admin flag",agents:["architect"]},swarm_memory_recall:{description:"recall scoped Swarm memory for the current repository as untrusted background",agents:[]},swarm_memory_propose:{description:"create a pending Swarm memory proposal; does not write durable memory directly",agents:[]},swarm_memory_outcome:{description:"record useful, dead-end, or corrected outcomes and, when enabled, synchronously refresh deterministic memory lessons",agents:[]},swarm_command:{description:"run supported /swarm commands through the canonical command registry",agents:["architect","sme","researcher","docs","docs_design","designer","reviewer","critic_finding_validator","critic","explorer","coder","test_engineer"]},dispatch_lanes:{description:"dispatch read-only exploration/review lanes concurrently and BLOCK until all finish; prefer dispatch_lanes_async for non-blocking dispatch, use this only when promptAsync is unavailable",agents:["architect"]},dispatch_lanes_async:{description:"launch read-only advisory lanes non-blockingly and return a batch id plus lane session handles immediately; each lane agent must be a registered generated agent name (unregistered bare roles are refused on multi-swarm hosts); launch_timeout_ms is only a promptAsync acceptance budget, not a lane runtime timeout; poll incrementally with collect_lane_results (wait omitted), or join with wait: true for all results",agents:["architect"]},collect_lane_results:{description:"collect/poll a dispatch_lanes_async batch; 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.184.10",description:"Architect-centric agentic swarm plugin for OpenCode - hub-and-spoke orchestration with SME consultation, code generation, and QA review",main:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",default:"./dist/index.js"},"./package.json":"./package.json"},bin:{"opencode-swarm":"./dist/cli/index.js"},type:"module",engines:{bun:">=1.3.13",node:">=22.13"},license:"MIT",repository:{type:"git",url:"https://github.com/ZaxbyHub/opencode-swarm.git"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},keywords:["opencode","opencode-plugin","ai","agents","orchestration","swarm","multi-agent","llm"],files:["dist","dist/lang/grammars","binaries","evaluation-fixtures",".opencode/skills/brainstorm",".opencode/skills/specify",".opencode/skills/clarify-spec",".opencode/skills/swarm-resume",".opencode/skills/clarify",".opencode/skills/discover",".opencode/skills/consult",".opencode/skills/pre-phase-briefing",".opencode/skills/council",".opencode/skills/deep-dive",".opencode/skills/deep-research",".opencode/skills/codebase-review-swarm",".opencode/skills/swarm-implement",".opencode/skills/design-docs",".opencode/skills/swarm-pr-review",".opencode/skills/swarm",".opencode/skills/swarm-pr-feedback",".opencode/skills/swarm-pr-subscribe",".opencode/skills/swarm-ci-monitor",".opencode/skills/issue-ingest",".opencode/skills/swarm-plan",".opencode/skills/critic-gate",".opencode/skills/execute",".opencode/skills/phase-wrap",".opencode/skills/loop",".opencode/skills/writing-tests",".opencode/skills/running-tests",".opencode/skills/engineering-conventions",".opencode/skills/commit-pr",".opencode/skills/ci-failure-batching",".opencode/skills/gate-attribution",".opencode/skills/merge-queue-readiness",".opencode/skills/skill-edit-validation",".opencode/skills/worktree-retry-cleanup",".opencode/skills/test-file-split",".opencode/skills/fork-pr-operations",".opencode/skills/parallel-work-check",".opencode/skills/ci-fix-monitor",".opencode/skills/issue-tracer",".opencode/skills/orchestrating-subagents",".opencode/skills/durable-session-state","tests/fixtures/memory-recall","tests/fixtures/memory-recall-heldout","opencode-swarm.schema.json","README.md","LICENSE"],scripts:{clean:`bun -e "require('fs').rmSync('dist',{recursive:true,force:true})"`,build:"bun run clean && bun run scripts/generate-config-schema.ts && bun run scripts/copy-grammars.ts && bun build src/index.ts --outdir dist --target node --format esm --external web-tree-sitter --minify-whitespace --minify-syntax && bun build src/cli/index.ts --outdir dist/cli --target bun --format esm --external bash-parser --splitting && bun run scripts/copy-grammars.ts --to-dist && tsc --emitDeclarationOnly",typecheck:"tsc --noEmit",test:"bun test",lint:"biome lint .","lint:ci":"biome ci .","test:unit:ci":"bun scripts/ci/run-unit-tests-local.ts","validate:repo":"bun scripts/ci/repository-validation.ts","drift:check":"bun run scripts/drift-check.ts","check:pre-push":"bun run scripts/drift-check.ts --enforce --no-report && bun run check:registry-citations","schema:generate":"bun run scripts/generate-config-schema.ts","generate:commands-docs":"bun run scripts/generate-commands-docs.ts","check:runtime-src-refs":"bun run scripts/check-runtime-src-refs.ts","drift:fix":"bun run scripts/drift-check.ts --fix --confirm","skills:sync":"bun run scripts/sync-qa-gate-skills.ts",format:"biome format . --write",check:"biome check --write .",dev:"bun run build && opencode","package:smoke":"node scripts/package-smoke.mjs",prepare:"bun run build","repro:704":"node scripts/repro-704.mjs","repro:2669":"node scripts/repro-2669.mjs","repro:2670":"node scripts/repro-2670.mjs","repro:1144":"bun scripts/repro-1144.mjs","repro:1873":"bun build scripts/repro-1873-entry.ts --outdir dist-build-test/repro-1873 --target node --format esm && node scripts/repro-1873.mjs","repro:2487":"bun build scripts/repro-2487-parity-entry.ts --outdir dist-build-test/repro-2487 --target node --format esm && node scripts/repro-2487-parity.mjs","check:events":"bun run scripts/check-event-contract.ts","check:retention":"bun run scripts/check-retention-registry.ts","check:core-events":"bun run scripts/check-core-events-usage.ts","check:shell-audit":"bun run scripts/check-shell-audit-usage.ts","check:trajectory-store":"bun run scripts/check-trajectory-store-usage.ts","check:mock-cleanup":"bun run scripts/check-mock-cleanup.ts","check:invariants":"bun run scripts/check-invariants.ts","check:token-formula":"bun run scripts/check-token-formula.ts","check:cross-contamination":"bun run scripts/check-cross-contamination.ts","check:test-clock":"bun run scripts/check-test-clock.ts","check:test-file-cap":"bun run scripts/check-test-file-cap.ts","check:test-tmpdir":"bun run scripts/check-test-tmpdir.ts","check:bash-portability":"bun run scripts/check-bash-portability.ts","check:pending-fragment":"bun run scripts/check-pending-fragment.ts","check:gate-portability":"bun run scripts/check-gate-portability.ts","check:bare-spawn":"bun run scripts/check-bare-executable-spawn.ts","check:error-channel-discard":"bun run scripts/check-error-channel-discard.ts","check:path-identity":"bun run scripts/check-path-identity.ts","check:registry-citations":"bun run scripts/check-registry-citations.ts","check:memory-recall":"bun run scripts/memory-recall-regression.ts","check:retrieval-quality":"bun run scripts/retrieval-quality-regression.ts"},dependencies:{"@modelcontextprotocol/sdk":"^1.30.0","@opencode-ai/plugin":"^1.18.3","@opencode-ai/sdk":"^1.18.3","@vscode/tree-sitter-wasm":"^0.3.0","bash-parser":"^0.5.0","p-limit":"^7.3.0",picomatch:"^4.0.4","proper-lockfile":"^4.1.2","quick-lru":"^7.3.0","web-tree-sitter":"^0.25.0",zod:"4.3.6"},devDependencies:{"@biomejs/biome":"2.3.14","@types/picomatch":"^4.0.3","bun-types":"1.3.8","js-yaml":"^4.1.1",typescript:"^5.7.3"},peerDependencies:{"@xenova/transformers":"^2.17.2"},peerDependenciesMeta:{"@xenova/transformers":{optional:!0}}}});var QA_AGENTS,PIPELINE_AGENTS,ORCHESTRATOR_NAME="architect",ALL_SUBAGENT_NAMES,ALL_AGENT_NAMES;var init_agent_names=__esm(()=>{QA_AGENTS=["reviewer","critic","critic_oversight","critic_finding_validator"],PIPELINE_AGENTS=["explorer","coder","test_engineer"],ALL_SUBAGENT_NAMES=["sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","curator_postmortem","curator_consolidation","council_generalist","council_skeptic","council_domain_expert","skill_improver","spec_writer",...QA_AGENTS,...PIPELINE_AGENTS],ALL_AGENT_NAMES=["architect",...ALL_SUBAGENT_NAMES]});function getPrWorkflowToolCapability(toolName,mode){let metadata=TOOL_METADATA[toolName];if(!metadata?.prWorkflow?.modes.includes(mode))return null;return metadata.prWorkflow.capability}var TOOL_METADATA,TOOL_NAMES,TOOL_NAME_SET,TOOL_DESCRIPTIONS,AGENT_TOOL_MAP;var init_tool_metadata=__esm(()=>{init_agent_names();TOOL_METADATA={diff:{description:"structured git diff with contract change detection",agents:["architect","reviewer","critic_finding_validator","critic_oversight","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},diff_summary:{description:"filter classified AST changes by category, risk level, or file for reviewer drill-down",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},syntax_check:{description:"check syntax of source files using tree-sitter parsers across multiple languages, returning per-file errors",agents:["architect","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},placeholder_scan:{description:"todo and FIXME comment detection",agents:["architect","reviewer","critic_finding_validator"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},imports:{description:"find all consumers that import from a given file — use before refactoring shared modules to avoid breaking unseen dependents",agents:["architect","sme","researcher","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},lint:{description:"run project linter in check or fix mode; supports biome, eslint, ruff, clippy, and more, returns structured results",agents:["architect","reviewer","critic_finding_validator","coder"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},secretscan:{description:"scan for secrets (API keys, tokens, passwords) via regex and entropy; returns redacted previews, excludes common dirs",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},sast_scan:{description:"static analysis security scan",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},build_check:{description:"discover and run build, typecheck, and test commands for various project ecosystems in the working directory",agents:["architect","coder","test_engineer"]},pre_check_batch:{description:"parallel verification: lint:check + secretscan + sast_scan + quality_budget",agents:["architect","reviewer","critic_finding_validator"]},quality_budget:{description:"code quality budget check",agents:["architect"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},symbols:{description:"extract exported symbols (functions, classes, interfaces, types) from source files; supports TypeScript, JavaScript, 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; with task_id, records the high-priority count as todo_scan gate evidence",agents:["architect","researcher","docs","explorer","coder"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},evidence_check:{description:"verify task evidence completeness",agents:["architect","critic_oversight"]},check_gate_status:{description:"check the gate status of a specific task",agents:["architect","critic_oversight"]},completion_verify:{description:"verify completed tasks have required evidence",agents:["architect","critic_oversight"]},complete_pr_workflow:{description:"validate terminal PR workflow evidence and clear its durable session gate",agents:["architect"]},abort_pr_workflow:{description:"abort an unrecoverable PR_REVIEW/PR_FEEDBACK mechanical gate and clear its durable session state",agents:["architect"]},authorize_pr_review_reentry:{description:"issue a one-use, identity-bound reviewer/test_engineer re-entry authorization for the active PR_REVIEW workflow (issue #2383)",agents:["architect"]},submit_pr_review_result:{description:"submit one child-bound typed result for an active PR-review base or micro discovery lane",agents:[],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},approve_plan_critic:{description:"record a MANUAL plan_critic_gate approval snapshot to unblock the ratchet-tighter critic_pre_plan execution gate when the critic already returned APPROVED but the mechanical recorder failed to persist it (issue #2012), or as the sanctioned recovery for a bookkeeping-grade hashed-field repair under the critic-gate PLAN FREEZE rule (the reason must state which case applies)",agents:["architect"]},approve_retry_sounding_board:{description:"record a MANUAL critic_sounding_board gate entry to unblock the coder retry circuit-breaker gate when the sounding board returned APPROVED but the mechanical recorder missed it (issue #2703)",agents:["architect"]},recover_rework_task:{description:"recover a task wedged at rework_required when the reviewer/test_engineer verdict did not require a code change: write a supervised stage_a_passed so those gates can be re-dispatched without re-running the coder (issue #2755)",agents:["architect"]},recover_stage_a_task:{description:"recover a task wedged in the settlement-backed Stage A deadlock — workflow at idle/blocked while a COMMITTED accepted coder settlement and green post-settlement pre-check proof justify Stage A: write a settlement-backed stage_a_passed so reviewer/test_engineer can be dispatched, without re-running the coder (issue #2828)",agents:["architect"]},prepare_pr_workflow_checkout:{description:"prepare an auditable PR workflow checkout or restore its exact original branch/HEAD and preserved stash after terminal cleanup",agents:["architect"]},invalidate_pr_feedback_publication:{description:"invalidate the armed PR_FEEDBACK publication generation so approved content can change, superseding every content-dependent approval and reopening the exact scoped rework + fresh-review path (issue #2108)",agents:["architect"]},record_implementation_review:{description:"record fresh-context reviewer + critic APPROVE verdicts for the implementation diff so the /swarm issue --trace workflow can satisfy its review gate before commit-pr handoff",agents:["architect"]},record_issue_publication:{description:"record a publication receipt so the /swarm issue --trace workflow reaches its terminal published state after the PR is created/updated",agents:["architect"]},record_issue_reproduction:{description:"record the reproduction outcome for the current traced issue so the /swarm issue --trace workflow can satisfy its reproduction gate and transition to PLAN",agents:["architect"]},record_recurrence_sweep:{description:"record the recurrence sweep (defect class, predicates, hit dispositions, guardrail proof, related-problems results) so the /swarm issue --trace workflow can satisfy its recurrence gate before commit-pr handoff",agents:["architect"]},record_branch_freshness:{description:"record the Phase 0 branch-freshness outcome (synced / behind:<n> / fetch-failed:<reason> plus optional user override) so the /swarm issue --trace workflow can pass its freshness gate before transitioning to PLAN (issue #2564)",agents:["architect"]},record_trace_validation:{description:"record one per-phase trace-check.sh validator outcome (phase, pass/fail, reviewedCommit, treeId) so the /swarm issue --trace workflow can satisfy its validator-receipt gate before commit-pr handoff (issue #2564)",agents:["architect"]},record_merge_approval:{description:"record the human merge approval bound to the exact PR head SHA so the /swarm issue --trace workflow reaches its terminal merge_approval_recorded state — recorded for audit only, never certified or driven by the plugin (issue #2564)",agents:["architect"]},rebind_pr_feedback_head:{description:"rebind a PR_FEEDBACK workflow to a new verified remote PR head after merge/rebase/conflict repair, invalidating ancestry-bound receipts so the mechanical ladder re-runs",agents:["architect"]},run_pr_feedback_stage_a:{description:"execute and persist mandatory PR-feedback Stage A checks on a content-bound revision",agents:["architect"]},submit_council_verdicts:{description:"submit pre-collected council member verdicts for synthesis (architect MUST dispatch critic/reviewer/sme/test_engineer/explorer as Agent tasks first; this tool synthesizes only, it does not contact members)",agents:[]},submit_phase_council_verdicts:{description:"submit pre-collected phase-level council member verdicts for holistic phase synthesis (architect MUST dispatch all 5 council members with phase-scoped context first; this tool synthesizes only, it does not contact members)",agents:[]},declare_council_criteria:{description:"pre-declare acceptance criteria for a task before the coder starts work; criteria are read back during council evaluation",agents:[]},sbom_generate:{description:"SBOM generation for dependency inventory",agents:["architect"]},checkpoint:{description:"create named git checkpoints for save, restore, and delete — use before risky operations to enable rollback",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; test selection comes from explicit files (override) or source_files derived via the impact analyzer with a typed bounded fallback",agents:["architect","test_engineer"]},generate_mutants:{description:"generate LLM-based mutation testing patches for source files; returns MutationPatch[] for direct consumption by the mutation_test tool",agents:["architect"]},detect_domains:{description:"detect which SME domains are relevant for a given text",agents:["architect","sme","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic","critic_oversight","explorer"]},git_blame:{description:"per-line git blame metadata: sha, author, date, summary for each line in a file",agents:["reviewer","critic_finding_validator","explorer","architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},gitingest:{description:"fetch a GitHub repository full content via gitingest.com",agents:["architect","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_summary:{description:"retrieve the full content of a stored tool output summary",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_lane_output:{description:"retrieve paged full dispatch lane output by output_ref; use before consuming truncated lane previews or routing candidates from lane results",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},extract_code_blocks:{description:"extract code blocks from text content and save them to files",agents:["docs","docs_design","designer","spec_writer","coder","test_engineer"]},phase_complete:{description:"preflight every applicable phase gate, report all blockers, and atomically commit a current passing snapshot",agents:["architect"]},run_phase_review:{description:"run the bounded phase-final review engine and persist complete content-addressed review evidence",agents:["architect"]},repair_gate_evidence:{description:"quarantine recoverable exact-task gate evidence, rebuild from durable requirements, recover receipt-backed legacy marker wedges or the exact sentinel-only historical reset, and refuse every other receipt-less reconstruction",agents:["architect"]},repair_knowledge_receipt_ledger:{description:"validate or repair authoritative knowledge receipts, preserve corrupt authority in bounded quarantine, 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"]},scope_validate:{description:"validate shell writes against an inline file scope",agents:["architect"]},knowledge_query:{description:"query swarm or hive knowledge with optional filters",agents:["architect","skill_improver","spec_writer"]},doc_scan:{description:"scan project documentation files and build an index manifest",agents:["architect","docs_design","skill_improver","spec_writer","explorer"]},doc_extract:{description:"extract actionable constraints from project documentation",agents:["architect","docs_design","skill_improver","spec_writer"]},curator_analyze:{description:"run curator phase analysis and optionally apply knowledge recommendations",agents:["architect"]},consensus_mine:{description:"mine cross-run consensus from existing .swarm evidence into an immutable proposals-only report; also deletes its own reports past consensus.report_retention, appends to the shared recommendation dedup ledger (in the shared cohort root, outside this project, when a knowledge link is active), and mirrors proposals into pending swarm-memory proposals when memory is enabled",agents:["architect","curator_phase","curator_postmortem"]},knowledge_add:{description:"store a new lesson in the knowledge base",agents:["architect","coder"]},knowledge_recall:{description:"search the knowledge base for relevant past decisions",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"]},knowledge_remove:{description:"delete an outdated swarm knowledge entry by ID (swarm tier only)",agents:["architect"]},co_change_analyzer:{description:"detect hidden couplings by analyzing git history",agents:["architect"]},context_status:{description:"report current context-window headroom for the active session — returns tokens-used, usageSource (provider|estimated), model-limit with provenance (modelLimitSource: host|override|provider_cap|native|fallback; modelLimitResolution: user_provider_model|user_model|user_default|live_model_limit|static_provider_cap|static_native|static_default; fallbackActive: true when the denominator came from a static table or the flat 128k default — treat headroom as uncertain), usage-percent, threshold-state (none/warn/critical), model name, and provider. Pure read-only: no state mutation, no warning injection. Works whether context_budget.enabled is true or false.",agents:["architect"]},search:{description:"Workspace-scoped ripgrep-style text search with structured JSON output. Supports literal and regex modes, glob filtering, and result limits. NOTE: This is text search, not structural AST search — use symbols and imports tools for structural queries.",agents:["architect","sme","docs","docs_design","designer","critic_hallucination_verifier","skill_improver","spec_writer","reviewer","critic_finding_validator","critic_oversight","explorer","coder","test_engineer","researcher"]},ast_grep:{description:"Read-only structural AST search using ast-grep patterns with optional language and glob filters. Use for syntax-aware code pattern searches; does not rewrite files.",agents:["architect","sme","docs","docs_design","critic_hallucination_verifier","spec_writer","explorer","coder","test_engineer","researcher"]},actionlint_scan:{description:"Run actionlint against GitHub Actions workflow YAML files with structured findings. Resolves actionlint lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},osv_scan:{description:"Run OSV-Scanner against a workspace path and return structured dependency vulnerability findings. Resolves osv-scanner lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},gh_evidence:{description:"Fetch bounded GitHub pull request or issue metadata through gh for review and CI evidence. Resolves gh lazily and is read-only.",agents:["architect","researcher"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},pr_workflow_status:{description:"Read-only architect observation of local git state (HEAD, branch, clean/dirty with a bounded changed-file list, remotes) plus a session-pinned PR workflow gate summary and the PR_FEEDBACK publication-generation section (state, attempts, invalidation reason, recovery guidance). Use to observe state under the fail-closed PR_REVIEW/PR_FEEDBACK gate. Never executes PR-controlled scripts and never reads another session gate.",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},batch_symbols:{description:"Batched symbol extraction across multiple files. Returns per-file symbol summaries with isolated error handling.",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","explorer"]},suggest_patch:{description:"Reviewer-safe structured patch suggestion tool. Produces context-anchored patch artifacts without file modification. Returns structured diagnostics on context mismatch.",agents:["architect","reviewer","critic_finding_validator"]},req_coverage:{description:"query requirement coverage status for tracked functional requirements",agents:["critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","critic","critic_oversight"]},get_approved_plan:{description:"retrieve the last critic-approved immutable plan snapshot for baseline drift comparison",agents:["critic_drift_verifier","critic","critic_oversight"]},repo_map:{description:"query the repo code graph: importers, dependencies, blast radius, localization, ontology facts, package boundaries, and heuristic preflight packets before refactoring; ontology findings are advisory, not formal proofs",agents:["architect","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},get_qa_gate_profile:{description:"retrieve the QA gate profile for the current or exact future plan identity: gates (reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council), lock state, profile hash, the calling session’s ratchet-tighter overrides, and the EFFECTIVE gates (profile merged with those overrides; durable across restart). Read-only and never creates state.",agents:["architect"]},set_qa_gates:{description:"configure the QA gate profile for the current plan or bootstrap an exact future plan with swarm_id and plan_title. Architect-only. The initial selection may set explicit true/false values over defaults; later changes are ratchet-tighter and rejected once locked after critic approval. Supports: reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council, plus adopt_legacy_binding_only for exact-binding recovery without mutating gates.",agents:["architect"]},web_search:{description:"External web search (Tavily or Brave) for architect-driven council research, SME domain research, researcher auto-research, and skill-improver research. Returns titled results with snippets, URLs, normalized query metadata, temporal intent, freshness, and removed stale years. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides. Requires a search API key. Used by the architect in MODE: COUNCIL to gather a RESEARCH CONTEXT before dispatching council agents, by SME for opt-in external skill/source evaluation, and by the researcher agent for multi-source auto-research.",agents:["sme","researcher","skill_improver"]},web_fetch:{description:"Fetch the readable text of a single http(s) URL (architect-only). Returns decoded page text, document title, final URL after redirects, and an evidence reference. Reads primary sources that web_search only surfaces as snippets. Config-gated on council.general.enabled. Blocks private/loopback/link-local/metadata addresses (re-validated and re-pinned across redirects); enforces timeout and body size cap.",agents:[]},convene_general_council:{description:"Synthesize responses from a multi-model General Council. Accepts parallel member responses (Round 1, optionally Round 2), detects disagreements, and returns consensus points, persisting disagreements, and a structured synthesis. Architect-only. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides.",agents:[]},write_final_council_evidence:{description:"Persist project-scoped final council evidence to .swarm/evidence/final-council.json. PREREQUISITE: dispatch critic, reviewer, sme, test_engineer, and explorer as project-scoped Agent tasks and collect their CouncilMemberVerdict JSON — this tool synthesizes only. Rejects on insufficient quorum or CONCERNS with unresolved requiredFixes; normalizes verdicts to approved/concerns/rejected. Architect-only.",agents:[]},skill_generate:{description:"compile knowledge entries into a structured SKILL.md draft",agents:["skill_improver"]},skill_list:{description:"list generated skill files and their status",agents:["skill_improver"]},skill_apply:{description:"activate a draft skill proposal",agents:[]},skill_inspect:{description:"inspect the content and source entries of a skill file",agents:["skill_improver"]},run_stale_reconciliation:{description:"reconcile skills against the knowledge store: mark skills stale when source knowledge is archived or deleted, or clear stale markers",agents:["architect"]},skill_regenerate:{description:"regenerate an active skill by re-clustering its source knowledge entries and updating the SKILL.md in place",agents:[]},skill_retire:{description:"retire a generated skill by adding a retired.marker file; retired skills are excluded from scoring and injection",agents:[]},skill_improve:{description:"run the skill_improver agent to review and refine skills",agents:["skill_improver"]},spec_write:{description:"author or update .swarm/spec.md for the current project",agents:["spec_writer"]},knowledge_receipt:{description:"file a receipt for retrieved knowledge (applied/ignored/contradicted + new lessons), recorded as immutable knowledge events",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},knowledge_receipt_status:{description:"receipt status",agents:["architect"]},knowledge_archive:{description:"archive (default), quarantine, or purge a swarm or hive knowledge entry by ID with an immutable audit tombstone; purge requires an admin flag",agents:["architect"]},swarm_memory_recall:{description:"recall scoped Swarm memory for the current repository as untrusted background",agents:[]},swarm_memory_propose:{description:"create a pending Swarm memory proposal; does not write durable memory directly",agents:[]},swarm_memory_outcome:{description:"record useful, dead-end, or corrected outcomes and, when enabled, synchronously refresh deterministic memory lessons",agents:[]},swarm_command:{description:"run supported /swarm commands through the canonical command registry",agents:["architect","sme","researcher","docs","docs_design","designer","reviewer","critic_finding_validator","critic","explorer","coder","test_engineer"]},dispatch_lanes:{description:"dispatch read-only exploration/review lanes concurrently and BLOCK until all finish; prefer dispatch_lanes_async for non-blocking dispatch, use this only when promptAsync is unavailable",agents:["architect"]},dispatch_lanes_async:{description:"launch read-only advisory lanes non-blockingly and return a batch id plus lane session handles immediately; each lane agent must be a registered generated agent name (unregistered bare roles are refused on multi-swarm hosts); launch_timeout_ms is only a promptAsync acceptance budget, not a lane runtime timeout; poll incrementally with collect_lane_results (wait omitted), or join with wait: true for all results",agents:["architect"]},collect_lane_results:{description:"collect/poll a dispatch_lanes_async batch; 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
|
|
|
@@ -176,7 +176,7 @@ line break`,"required change with\rcarriage return"]),discardedReviewer=encodePr
|
|
|
176
176
|
`);return outside?`${outside}
|
|
177
177
|
${protocol}`:protocol}function declaredCanonicalFamilies(source){let families=[];for(let line of source.split(/\r?\n/)){let family=candidateHeaderFamily(splitPipeFields(line).map((field)=>field.trim()));if(family&&!families.includes(family))families.push(family)}return families}function normalizeCandidateArtifact(rawText,fallbackFamily){let repairKinds=[],summaryDrop=dropNonContractMarkerRows(rawText);if(summaryDrop.dropped)repairKinds.push("summary-row-dropped");let recoveredFence=recoverTerminalProtocolFence(summaryDrop.text,fallbackFamily);if(recoveredFence!==null)repairKinds.push("terminal-protocol-fence");let cleanRepair=repairRedundantCleanConfidence(recoveredFence??removeCandidateCodeFences(summaryDrop.text),fallbackFamily);if(cleanRepair.repaired)repairKinds.push("redundant-clean-confidence");let pipeRepair=repairCleanEvidencePipes(cleanRepair.text);if(pipeRepair.repaired)repairKinds.push("clean-evidence-pipe-tail-merge");let candidatePipeRepair=repairCandidateEvidencePipes(pipeRepair.text,fallbackFamily);if(candidatePipeRepair.repaired)repairKinds.push("candidate-evidence-pipe-recovery-lossy");let lateHeaderRepair=resynchronizeLateCanonicalHeader(candidatePipeRepair.text,fallbackFamily);if(lateHeaderRepair.repaired)repairKinds.push("late-canonical-header-resynchronized");let duplicateHeaderDrop=dropDuplicateHeaderRows(lateHeaderRepair.text);if(duplicateHeaderDrop.dropped)repairKinds.push("duplicate-header-row-dropped");let text=duplicateHeaderDrop.text,header=selectCandidateHeader(text.split(/\r?\n/));if(header?.markerBearing&&header.family!==null)return{text,synthesizedHeader:!1,repairKinds};if(declaredCanonicalFamilies(text).length>0)return{text,synthesizedHeader:!1,repairKinds};if(declaredCanonicalFamilies(summaryDrop.text).some((family)=>family!==fallbackFamily))return{text,synthesizedHeader:!1,repairKinds};let lines=text.split(/\r?\n/);if(!lines.some((line)=>{if(analyzeCandidateLine(line,fallbackFamily)?.valid===!0)return!0;let fields=splitPipeFields(line).map((field)=>field.trim());if(fields[0]!==CLEAN_MARKER)return!1;return analyzeCleanFields(fields,fallbackFamily).valid}))return{text,synthesizedHeader:!1,repairKinds};let firstSalvageableIndex=lines.findIndex((line)=>{let marker=splitPipeFields(line)[0]?.trim();return marker===CANDIDATE_MARKER||marker===CLEAN_MARKER});return repairKinds.push("synthesized-header"),{text:[...lines.slice(0,firstSalvageableIndex),CANDIDATE_HEADERS[fallbackFamily],...lines.slice(firstSalvageableIndex)].join(`
|
|
178
178
|
`),synthesizedHeader:!0,repairKinds}}function candidateArtifactCacheKey(rawText,fallbackFamily){return createHash2("sha256").update(`${rawText}\x00${fallbackFamily}`).digest("hex")}function normalizeCandidateArtifactCached(rawText,fallbackFamily){let key=candidateArtifactCacheKey(rawText,fallbackFamily),hit=candidateArtifactCache.get(key);if(hit!==void 0)return candidateArtifactCacheHits++,hit;candidateArtifactCacheMisses++;let result=normalizeCandidateArtifact(rawText,fallbackFamily);if(candidateArtifactCache.size>=CANDIDATE_ARTIFACT_CACHE_CAPACITY){let oldest=candidateArtifactCache.keys().next().value;if(oldest!==void 0)candidateArtifactCache.delete(oldest)}return candidateArtifactCache.set(key,result),result}function analyzeCandidateLaneContext(context){let issues=[],baseBound=Boolean(context.expected_lane||context.expected_lanes),microBound=Boolean(context.expected_micro_lane||context.expected_micro_lanes);if(context.expected_lanes){if(!context.expected_lane)issues.push({field:"expected_lane",message:"expected_lane is required when expected_lanes is supplied"});if(new Set(context.expected_lanes).size!==context.expected_lanes.length)issues.push({field:"expected_lanes",message:"expected_lanes must contain unique lane identities"});if(context.expected_lane&&!context.expected_lanes.includes(context.expected_lane))issues.push({field:"expected_lanes",message:"expected_lanes must contain expected_lane"})}if(context.expected_micro_lanes){if(!context.expected_micro_lane)issues.push({field:"expected_micro_lane",message:"expected_micro_lane is required when expected_micro_lanes is supplied"});if(new Set(context.expected_micro_lanes).size!==context.expected_micro_lanes.length)issues.push({field:"expected_micro_lanes",message:"expected_micro_lanes must contain unique lane identities"});if(context.expected_micro_lane&&!context.expected_micro_lanes.includes(context.expected_micro_lane))issues.push({field:"expected_micro_lanes",message:"expected_micro_lanes must contain expected_micro_lane"})}if(!context.expected_family&&baseBound&µBound)issues.push({field:"expected_family",message:"base and micro ownership fields cannot be combined without one expected_family"});else if(context.expected_family==="base_explorer"&µBound)issues.push({field:"expected_family",message:"base_explorer ownership cannot include expected_micro_lane fields"});else if(context.expected_family==="micro_lane"&&baseBound)issues.push({field:"expected_family",message:"micro_lane ownership cannot include expected_lane fields"});else if(!context.expected_family&&baseBound)issues.push({field:"expected_family",message:"base ownership fields require expected_family base_explorer"});else if(!context.expected_family&µBound)issues.push({field:"expected_family",message:"micro ownership fields require expected_family micro_lane"});return issues}function splitPipeFields(line){let fields=[],current="";for(let index=0;index<line.length;index++){let char=line[index];if(char==="\\"&&index+1<line.length&&line[index+1]==="|"){current+="|",index++;continue}if(char==="|"){fields.push(current),current="";continue}current+=char}return fields.push(current),fields}function candidateDiagnosticPreview(value){let normalized=value.replace(/[\r\n\t]+/g," ").trim();if(normalized.length<=CANDIDATE_DIAGNOSTIC_PREVIEW_CHARS)return normalized;return`${normalized.slice(0,CANDIDATE_DIAGNOSTIC_PREVIEW_CHARS)}...`}function isCandidateSeverity(value){return value!==null&&value!==void 0&&CANDIDATE_SEVERITIES.includes(value)}function isCandidateConfidence(value){return value!==null&&value!==void 0&&CANDIDATE_CONFIDENCES.includes(value)}function isCandidateLookingShortRow(fields,_context,explicitCandidateMarker=!1){if(explicitCandidateMarker||fields[0]?.trim()==="[CANDIDATE]")return!0;return fields.length>=2}function analyzeCandidateFields(fields,family){let names=CANDIDATE_FIELDS[family],trimmed=fields.map((field)=>field.trim()),values={},issues=[];if(trimmed.length!==CANDIDATE_FIELD_COUNT)issues.push({field:"row",message:`Expected exactly ${CANDIDATE_FIELD_COUNT} candidate fields, received ${trimmed.length}`});for(let index=0;index<names.length;index++){let name=names[index],value=trimmed[index]?.trim()||null;if(values[name]=value,value===null&&name!=="risk_impact"&&name!=="risk_tags")issues.push({field:name,message:`Missing required field: ${name}`})}let severity=values.severity;if(severity!==null&&!isCandidateSeverity(severity))issues.push({field:"severity",message:`Invalid severity: ${candidateDiagnosticPreview(severity)}; expected ${CANDIDATE_SEVERITIES.join("|")}`});let confidence=values.confidence;if(confidence!==null&&!isCandidateConfidence(confidence))issues.push({field:"confidence",message:`Invalid confidence: ${candidateDiagnosticPreview(confidence)}; expected ${CANDIDATE_CONFIDENCES.join("|")}`});let riskImpact=values.risk_impact;if(riskImpact!==null&&!PR_REVIEW_RISK_IMPACTS.includes(riskImpact))issues.push({field:"risk_impact",message:`Invalid risk_impact: ${candidateDiagnosticPreview(riskImpact)}; expected ${PR_REVIEW_RISK_IMPACTS.join("|")}`});let riskTags=values.risk_tags;if(riskTags!==null){let parsedTags=parsePrReviewRiskTagsField(riskTags),known=new Set(PR_REVIEW_RISK_TAGS);if(riskTags!==""&&(parsedTags.length===0||parsedTags.some((tag)=>!known.has(tag))))issues.push({field:"risk_tags",message:`Invalid risk_tags: ${candidateDiagnosticPreview(riskTags)}; expected a comma-separated subset of ${PR_REVIEW_RISK_TAGS.join("|")}, or empty`})}return{valid:issues.length===0,issues,values,candidateId:values.candidate_id,workflowLane:family==="base_explorer"?values.lane:values.micro_lane}}function analyzeCleanFields(fields,family,expectedLane){let trimmed=fields.map((field)=>field.trim()),issues=[],laneField=family==="base_explorer"?"lane":"micro_lane";if(trimmed.length!==CLEAN_FIELD_COUNT)issues.push({field:"row",message:`Expected exactly ${CLEAN_FIELD_COUNT-1} CLEAN fields after [CLEAN], received ${Math.max(0,trimmed.length-1)}`});if(trimmed[0]!=="[CLEAN]")issues.push({field:"row",message:"CLEAN row must begin with [CLEAN]"});let lane=trimmed[1]||null,coverageScope=trimmed[2]||null,evidence=trimmed[3]||null;if(lane===null)issues.push({field:laneField,message:`Missing required field: ${laneField}`});else if(expectedLane!==void 0&&lane!==expectedLane)issues.push({field:laneField,message:`Expected ${laneField} ${candidateDiagnosticPreview(expectedLane)}, received ${candidateDiagnosticPreview(lane)}`});if(coverageScope===null)issues.push({field:"coverage_scope",message:"Missing required field: coverage_scope"});else if(coverageScope.length<CLEAN_COVERAGE_SCOPE_MIN_CHARS)issues.push({field:"coverage_scope",message:`coverage_scope must contain at least ${CLEAN_COVERAGE_SCOPE_MIN_CHARS} characters`});if(evidence===null)issues.push({field:"evidence",message:"Missing required field: evidence"});else if(evidence.length<CLEAN_EVIDENCE_MIN_CHARS)issues.push({field:"evidence",message:`evidence must contain at least ${CLEAN_EVIDENCE_MIN_CHARS} characters`});return{valid:issues.length===0,issues,lane,coverageScope,evidence}}function analyzeCandidateLine(line,family){let fields=splitPipeFields(line).map((field)=>field.trim());if(fields[0]!=="[CANDIDATE]")return null;return analyzeCandidateFields(fields.slice(1),family)}var CANDIDATE_SEVERITIES,FINDINGS_SEVERITIES,CANDIDATE_CONFIDENCES,CANDIDATE_FIELD_COUNT=11,CANDIDATE_LEGACY_FIELD_COUNT=9,CLEAN_FIELD_COUNT=4,CLEAN_COVERAGE_SCOPE_MIN_CHARS=12,CLEAN_EVIDENCE_MIN_CHARS=20,CANDIDATE_DIAGNOSTIC_PREVIEW_CHARS=160,CANDIDATE_FIELDS,CANDIDATE_REQUIRED_FIELDS,CANDIDATE_MARKER="[CANDIDATE]",CLEAN_MARKER="[CLEAN]",CANDIDATE_HEADERS,CLEAN_TEMPLATES,NON_CONTRACT_MARKER_LINE,CANDIDATE_ARTIFACT_CACHE_CAPACITY=512,candidateArtifactCache,candidateArtifactCacheHits=0,candidateArtifactCacheMisses=0;var init_candidate_contract=__esm(()=>{init_pr_review_contract();init_pr_review_contract();CANDIDATE_SEVERITIES=["INFO","LOW","MEDIUM","HIGH","CRITICAL"],FINDINGS_SEVERITIES=[...CANDIDATE_SEVERITIES,"NONE"],CANDIDATE_CONFIDENCES=["HIGH","MEDIUM","LOW"],CANDIDATE_FIELDS={base_explorer:["candidate_id","lane","severity","category","file_line","claim","evidence_summary","impact_context","confidence","risk_impact","risk_tags"],micro_lane:["candidate_id","micro_lane","severity","category","file_line","claim","invariant_violated","evidence_summary","confidence","risk_impact","risk_tags"]},CANDIDATE_REQUIRED_FIELDS={base_explorer:CANDIDATE_FIELDS.base_explorer.filter((field)=>field!=="risk_impact"&&field!=="risk_tags"),micro_lane:CANDIDATE_FIELDS.micro_lane.filter((field)=>field!=="risk_impact"&&field!=="risk_tags")};CANDIDATE_HEADERS={base_explorer:formatCandidateHeader("base_explorer"),micro_lane:formatCandidateHeader("micro_lane")},CLEAN_TEMPLATES={base_explorer:formatCleanTemplate("base_explorer"),micro_lane:formatCleanTemplate("micro_lane")};NON_CONTRACT_MARKER_LINE=/^\[(?!(?:CANDIDATE|CLEAN)\])[A-Z][A-Z0-9_-]*\]/;candidateArtifactCache=new Map});var require_polyfills=__commonJS((exports,module)=>{var constants=__require("constants"),origCwd=process.cwd,cwd=null,platform=process.env.GRACEFUL_FS_PLATFORM||process.platform;process.cwd=function(){if(!cwd)cwd=origCwd.call(process);return cwd};try{process.cwd()}catch(er){}if(typeof process.chdir==="function"){if(chdir=process.chdir,process.chdir=function(d){cwd=null,chdir.call(process,d)},Object.setPrototypeOf)Object.setPrototypeOf(process.chdir,chdir)}var chdir;module.exports=patch;function patch(fs4){if(constants.hasOwnProperty("O_SYMLINK")&&process.version.match(/^v0\.6\.[0-2]|^v0\.5\./))patchLchmod(fs4);if(!fs4.lutimes)patchLutimes(fs4);if(fs4.chown=chownFix(fs4.chown),fs4.fchown=chownFix(fs4.fchown),fs4.lchown=chownFix(fs4.lchown),fs4.chmod=chmodFix(fs4.chmod),fs4.fchmod=chmodFix(fs4.fchmod),fs4.lchmod=chmodFix(fs4.lchmod),fs4.chownSync=chownFixSync(fs4.chownSync),fs4.fchownSync=chownFixSync(fs4.fchownSync),fs4.lchownSync=chownFixSync(fs4.lchownSync),fs4.chmodSync=chmodFixSync(fs4.chmodSync),fs4.fchmodSync=chmodFixSync(fs4.fchmodSync),fs4.lchmodSync=chmodFixSync(fs4.lchmodSync),fs4.stat=statFix(fs4.stat),fs4.fstat=statFix(fs4.fstat),fs4.lstat=statFix(fs4.lstat),fs4.statSync=statFixSync(fs4.statSync),fs4.fstatSync=statFixSync(fs4.fstatSync),fs4.lstatSync=statFixSync(fs4.lstatSync),fs4.chmod&&!fs4.lchmod)fs4.lchmod=function(path6,mode,cb){if(cb)process.nextTick(cb)},fs4.lchmodSync=function(){};if(fs4.chown&&!fs4.lchown)fs4.lchown=function(path6,uid,gid,cb){if(cb)process.nextTick(cb)},fs4.lchownSync=function(){};if(platform==="win32")fs4.rename=typeof fs4.rename!=="function"?fs4.rename:function(fs$rename){function rename2(from,to,cb){var start=Date.now(),backoff=0;fs$rename(from,to,function CB(er){if(er&&(er.code==="EACCES"||er.code==="EPERM"||er.code==="EBUSY")&&Date.now()-start<60000){if(setTimeout(function(){fs4.stat(to,function(stater,st){if(stater&&stater.code==="ENOENT")fs$rename(from,to,CB);else cb(er)})},backoff),backoff<100)backoff+=10;return}if(cb)cb(er)})}if(Object.setPrototypeOf)Object.setPrototypeOf(rename2,fs$rename);return rename2}(fs4.rename);fs4.read=typeof fs4.read!=="function"?fs4.read:function(fs$read){function read(fd,buffer,offset,length,position,callback_){var callback;if(callback_&&typeof callback_==="function"){var eagCounter=0;callback=function(er,_,__){if(er&&er.code==="EAGAIN"&&eagCounter<10)return eagCounter++,fs$read.call(fs4,fd,buffer,offset,length,position,callback);callback_.apply(this,arguments)}}return fs$read.call(fs4,fd,buffer,offset,length,position,callback)}if(Object.setPrototypeOf)Object.setPrototypeOf(read,fs$read);return read}(fs4.read),fs4.readSync=typeof fs4.readSync!=="function"?fs4.readSync:function(fs$readSync){return function(fd,buffer,offset,length,position){var eagCounter=0;while(!0)try{return fs$readSync.call(fs4,fd,buffer,offset,length,position)}catch(er){if(er.code==="EAGAIN"&&eagCounter<10){eagCounter++;continue}throw er}}}(fs4.readSync);function patchLchmod(fs5){fs5.lchmod=function(path6,mode,callback){fs5.open(path6,constants.O_WRONLY|constants.O_SYMLINK,mode,function(err,fd){if(err){if(callback)callback(err);return}fs5.fchmod(fd,mode,function(err2){fs5.close(fd,function(err22){if(callback)callback(err2||err22)})})})},fs5.lchmodSync=function(path6,mode){var fd=fs5.openSync(path6,constants.O_WRONLY|constants.O_SYMLINK,mode),threw=!0,ret;try{ret=fs5.fchmodSync(fd,mode),threw=!1}finally{if(threw)try{fs5.closeSync(fd)}catch(er){}else fs5.closeSync(fd)}return ret}}function patchLutimes(fs5){if(constants.hasOwnProperty("O_SYMLINK")&&fs5.futimes)fs5.lutimes=function(path6,at,mt,cb){fs5.open(path6,constants.O_SYMLINK,function(er,fd){if(er){if(cb)cb(er);return}fs5.futimes(fd,at,mt,function(er2){fs5.close(fd,function(er22){if(cb)cb(er2||er22)})})})},fs5.lutimesSync=function(path6,at,mt){var fd=fs5.openSync(path6,constants.O_SYMLINK),ret,threw=!0;try{ret=fs5.futimesSync(fd,at,mt),threw=!1}finally{if(threw)try{fs5.closeSync(fd)}catch(er){}else fs5.closeSync(fd)}return ret};else if(fs5.futimes)fs5.lutimes=function(_a2,_b,_c,cb){if(cb)process.nextTick(cb)},fs5.lutimesSync=function(){}}function chmodFix(orig){if(!orig)return orig;return function(target,mode,cb){return orig.call(fs4,target,mode,function(er){if(chownErOk(er))er=null;if(cb)cb.apply(this,arguments)})}}function chmodFixSync(orig){if(!orig)return orig;return function(target,mode){try{return orig.call(fs4,target,mode)}catch(er){if(!chownErOk(er))throw er}}}function chownFix(orig){if(!orig)return orig;return function(target,uid,gid,cb){return orig.call(fs4,target,uid,gid,function(er){if(chownErOk(er))er=null;if(cb)cb.apply(this,arguments)})}}function chownFixSync(orig){if(!orig)return orig;return function(target,uid,gid){try{return orig.call(fs4,target,uid,gid)}catch(er){if(!chownErOk(er))throw er}}}function statFix(orig){if(!orig)return orig;return function(target,options,cb){if(typeof options==="function")cb=options,options=null;function callback(er,stats2){if(stats2){if(stats2.uid<0)stats2.uid+=4294967296;if(stats2.gid<0)stats2.gid+=4294967296}if(cb)cb.apply(this,arguments)}return options?orig.call(fs4,target,options,callback):orig.call(fs4,target,callback)}}function statFixSync(orig){if(!orig)return orig;return function(target,options){var stats2=options?orig.call(fs4,target,options):orig.call(fs4,target);if(stats2){if(stats2.uid<0)stats2.uid+=4294967296;if(stats2.gid<0)stats2.gid+=4294967296}return stats2}}function chownErOk(er){if(!er)return!0;if(er.code==="ENOSYS")return!0;var nonroot=!process.getuid||process.getuid()!==0;if(nonroot){if(er.code==="EINVAL"||er.code==="EPERM")return!0}return!1}}});var require_legacy_streams=__commonJS((exports,module)=>{var Stream=__require("stream").Stream;module.exports=legacy;function legacy(fs4){return{ReadStream,WriteStream};function ReadStream(path6,options){if(!(this instanceof ReadStream))return new ReadStream(path6,options);Stream.call(this);var self=this;this.path=path6,this.fd=null,this.readable=!0,this.paused=!1,this.flags="r",this.mode=438,this.bufferSize=65536,options=options||{};var keys=Object.keys(options);for(var index=0,length=keys.length;index<length;index++){var key=keys[index];this[key]=options[key]}if(this.encoding)this.setEncoding(this.encoding);if(this.start!==void 0){if(typeof this.start!=="number")throw TypeError("start must be a Number");if(this.end===void 0)this.end=1/0;else if(typeof this.end!=="number")throw TypeError("end must be a Number");if(this.start>this.end)throw Error("start must be <= end");this.pos=this.start}if(this.fd!==null){process.nextTick(function(){self._read()});return}fs4.open(this.path,this.flags,this.mode,function(err,fd){if(err){self.emit("error",err),self.readable=!1;return}self.fd=fd,self.emit("open",fd),self._read()})}function WriteStream(path6,options){if(!(this instanceof WriteStream))return new WriteStream(path6,options);Stream.call(this),this.path=path6,this.fd=null,this.writable=!0,this.flags="w",this.encoding="binary",this.mode=438,this.bytesWritten=0,options=options||{};var keys=Object.keys(options);for(var index=0,length=keys.length;index<length;index++){var key=keys[index];this[key]=options[key]}if(this.start!==void 0){if(typeof this.start!=="number")throw TypeError("start must be a Number");if(this.start<0)throw Error("start must be >= zero");this.pos=this.start}if(this.busy=!1,this._queue=[],this.fd===null)this._open=fs4.open,this._queue.push([this._open,this.path,this.flags,this.mode,void 0]),this.flush()}}});var require_clone=__commonJS((exports,module)=>{module.exports=clone2;var getPrototypeOf=Object.getPrototypeOf||function(obj){return obj.__proto__};function clone2(obj){if(obj===null||typeof obj!=="object")return obj;if(obj instanceof Object)var copy={__proto__:getPrototypeOf(obj)};else var copy=Object.create(null);return Object.getOwnPropertyNames(obj).forEach(function(key){Object.defineProperty(copy,key,Object.getOwnPropertyDescriptor(obj,key))}),copy}});var require_graceful_fs=__commonJS((exports,module)=>{var fs4=__require("fs"),polyfills=require_polyfills(),legacy=require_legacy_streams(),clone2=require_clone(),util=__require("util"),gracefulQueue,previousSymbol;if(typeof Symbol==="function"&&typeof Symbol.for==="function")gracefulQueue=Symbol.for("graceful-fs.queue"),previousSymbol=Symbol.for("graceful-fs.previous");else gracefulQueue="___graceful-fs.queue",previousSymbol="___graceful-fs.previous";function noop(){}function publishQueue(context,queue2){Object.defineProperty(context,gracefulQueue,{get:function(){return queue2}})}var debug=noop;if(util.debuglog)debug=util.debuglog("gfs4");else if(/\bgfs4\b/i.test(process.env.NODE_DEBUG||""))debug=function(){var m=util.format.apply(util,arguments);m="GFS4: "+m.split(/\n/).join(`
|
|
179
|
-
GFS4: `),console.error(m)};if(!fs4[gracefulQueue]){if(queue=global[gracefulQueue]||[],publishQueue(fs4,queue),fs4.close=function(fs$close){function close(fd,cb){return fs$close.call(fs4,fd,function(err){if(!err)resetQueue();if(typeof cb==="function")cb.apply(this,arguments)})}return Object.defineProperty(close,previousSymbol,{value:fs$close}),close}(fs4.close),fs4.closeSync=function(fs$closeSync){function closeSync(fd){fs$closeSync.apply(fs4,arguments),resetQueue()}return Object.defineProperty(closeSync,previousSymbol,{value:fs$closeSync}),closeSync}(fs4.closeSync),/\bgfs4\b/i.test(process.env.NODE_DEBUG||""))process.on("exit",function(){debug(fs4[gracefulQueue]),__require("assert").equal(fs4[gracefulQueue].length,0)})}var queue;if(!global[gracefulQueue])publishQueue(global,fs4[gracefulQueue]);module.exports=patch(clone2(fs4));if(process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH&&!fs4.__patched)module.exports=patch(fs4),fs4.__patched=!0;function patch(fs5){polyfills(fs5),fs5.gracefulify=patch,fs5.createReadStream=createReadStream,fs5.createWriteStream=createWriteStream;var fs$readFile=fs5.readFile;fs5.readFile=readFile3;function readFile3(path6,options,cb){if(typeof options==="function")cb=options,options=null;return go$readFile(path6,options,cb);function go$readFile(path7,options2,cb2,startTime){return fs$readFile(path7,options2,function(err){if(err&&(err.code==="EMFILE"||err.code==="ENFILE"))enqueue([go$readFile,[path7,options2,cb2],err,startTime||Date.now(),Date.now()]);else if(typeof cb2==="function")cb2.apply(this,arguments)})}}var fs$writeFile=fs5.writeFile;fs5.writeFile=writeFile2;function writeFile2(path6,data,options,cb){if(typeof options==="function")cb=options,options=null;return go$writeFile(path6,data,options,cb);function go$writeFile(path7,data2,options2,cb2,startTime){return fs$writeFile(path7,data2,options2,function(err){if(err&&(err.code==="EMFILE"||err.code==="ENFILE"))enqueue([go$writeFile,[path7,data2,options2,cb2],err,startTime||Date.now(),Date.now()]);else if(typeof cb2==="function")cb2.apply(this,arguments)})}}var fs$appendFile=fs5.appendFile;if(fs$appendFile)fs5.appendFile=appendFile;function appendFile(path6,data,options,cb){if(typeof options==="function")cb=options,options=null;return go$appendFile(path6,data,options,cb);function go$appendFile(path7,data2,options2,cb2,startTime){return fs$appendFile(path7,data2,options2,function(err){if(err&&(err.code==="EMFILE"||err.code==="ENFILE"))enqueue([go$appendFile,[path7,data2,options2,cb2],err,startTime||Date.now(),Date.now()]);else if(typeof cb2==="function")cb2.apply(this,arguments)})}}var fs$copyFile=fs5.copyFile;if(fs$copyFile)fs5.copyFile=copyFile2;function copyFile2(src,dest,flags,cb){if(typeof flags==="function")cb=flags,flags=0;return go$copyFile(src,dest,flags,cb);function go$copyFile(src2,dest2,flags2,cb2,startTime){return fs$copyFile(src2,dest2,flags2,function(err){if(err&&(err.code==="EMFILE"||err.code==="ENFILE"))enqueue([go$copyFile,[src2,dest2,flags2,cb2],err,startTime||Date.now(),Date.now()]);else if(typeof cb2==="function")cb2.apply(this,arguments)})}}var fs$readdir=fs5.readdir;fs5.readdir=readdir2;var noReaddirOptionVersions=/^v[0-5]\./;function readdir2(path6,options,cb){if(typeof options==="function")cb=options,options=null;var go$readdir=noReaddirOptionVersions.test(process.version)?function(path7,options2,cb2,startTime){return fs$readdir(path7,fs$readdirCallback(path7,options2,cb2,startTime))}:function(path7,options2,cb2,startTime){return fs$readdir(path7,options2,fs$readdirCallback(path7,options2,cb2,startTime))};return go$readdir(path6,options,cb);function fs$readdirCallback(path7,options2,cb2,startTime){return function(err,files){if(err&&(err.code==="EMFILE"||err.code==="ENFILE"))enqueue([go$readdir,[path7,options2,cb2],err,startTime||Date.now(),Date.now()]);else{if(files&&files.sort)files.sort();if(typeof cb2==="function")cb2.call(this,err,files)}}}}if(process.version.substr(0,4)==="v0.8"){var legStreams=legacy(fs5);ReadStream=legStreams.ReadStream,WriteStream=legStreams.WriteStream}var fs$ReadStream=fs5.ReadStream;if(fs$ReadStream)ReadStream.prototype=Object.create(fs$ReadStream.prototype),ReadStream.prototype.open=ReadStream$open;var fs$WriteStream=fs5.WriteStream;if(fs$WriteStream)WriteStream.prototype=Object.create(fs$WriteStream.prototype),WriteStream.prototype.open=WriteStream$open;Object.defineProperty(fs5,"ReadStream",{get:function(){return ReadStream},set:function(val){ReadStream=val},enumerable:!0,configurable:!0}),Object.defineProperty(fs5,"WriteStream",{get:function(){return WriteStream},set:function(val){WriteStream=val},enumerable:!0,configurable:!0});var FileReadStream=ReadStream;Object.defineProperty(fs5,"FileReadStream",{get:function(){return FileReadStream},set:function(val){FileReadStream=val},enumerable:!0,configurable:!0});var FileWriteStream=WriteStream;Object.defineProperty(fs5,"FileWriteStream",{get:function(){return FileWriteStream},set:function(val){FileWriteStream=val},enumerable:!0,configurable:!0});function ReadStream(path6,options){if(this instanceof ReadStream)return fs$ReadStream.apply(this,arguments),this;else return ReadStream.apply(Object.create(ReadStream.prototype),arguments)}function ReadStream$open(){var that=this;open(that.path,that.flags,that.mode,function(err,fd){if(err){if(that.autoClose)that.destroy();that.emit("error",err)}else that.fd=fd,that.emit("open",fd),that.read()})}function WriteStream(path6,options){if(this instanceof WriteStream)return fs$WriteStream.apply(this,arguments),this;else return WriteStream.apply(Object.create(WriteStream.prototype),arguments)}function WriteStream$open(){var that=this;open(that.path,that.flags,that.mode,function(err,fd){if(err)that.destroy(),that.emit("error",err);else that.fd=fd,that.emit("open",fd)})}function createReadStream(path6,options){return new fs5.ReadStream(path6,options)}function createWriteStream(path6,options){return new fs5.WriteStream(path6,options)}var fs$open=fs5.open;fs5.open=open;function open(path6,flags,mode,cb){if(typeof mode==="function")cb=mode,mode=null;return go$open(path6,flags,mode,cb);function go$open(path7,flags2,mode2,cb2,startTime){return fs$open(path7,flags2,mode2,function(err,fd){if(err&&(err.code==="EMFILE"||err.code==="ENFILE"))enqueue([go$open,[path7,flags2,mode2,cb2],err,startTime||Date.now(),Date.now()]);else if(typeof cb2==="function")cb2.apply(this,arguments)})}}return fs5}function enqueue(elem){debug("ENQUEUE",elem[0].name,elem[1]),fs4[gracefulQueue].push(elem),retry()}var retryTimer;function resetQueue(){var now=Date.now();for(var i=0;i<fs4[gracefulQueue].length;++i)if(fs4[gracefulQueue][i].length>2)fs4[gracefulQueue][i][3]=now,fs4[gracefulQueue][i][4]=now;retry()}function retry(){if(clearTimeout(retryTimer),retryTimer=void 0,fs4[gracefulQueue].length===0)return;var elem=fs4[gracefulQueue].shift(),fn2=elem[0],args2=elem[1],err=elem[2],startTime=elem[3],lastTime=elem[4];if(startTime===void 0)debug("RETRY",fn2.name,args2),fn2.apply(null,args2);else if(Date.now()-startTime>=60000){debug("TIMEOUT",fn2.name,args2);var cb=args2.pop();if(typeof cb==="function")cb.call(null,err)}else{var sinceAttempt=Date.now()-lastTime,sinceStart=Math.max(lastTime-startTime,1),desiredDelay=Math.min(sinceStart*1.2,100);if(sinceAttempt>=desiredDelay)debug("RETRY",fn2.name,args2),fn2.apply(null,args2.concat([startTime]));else fs4[gracefulQueue].push(elem)}if(retryTimer===void 0)retryTimer=setTimeout(retry,0)}});var require_retry_operation=__commonJS((exports,module)=>{function RetryOperation(timeouts,options){if(typeof options==="boolean")options={forever:options};if(this._originalTimeouts=JSON.parse(JSON.stringify(timeouts)),this._timeouts=timeouts,this._options=options||{},this._maxRetryTime=options&&options.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._options.forever)this._cachedTimeouts=this._timeouts.slice(0)}module.exports=RetryOperation;RetryOperation.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts};RetryOperation.prototype.stop=function(){if(this._timeout)clearTimeout(this._timeout);this._timeouts=[],this._cachedTimeouts=null};RetryOperation.prototype.retry=function(err){if(this._timeout)clearTimeout(this._timeout);if(!err)return!1;var currentTime=new Date().getTime();if(err&¤tTime-this._operationStart>=this._maxRetryTime)return this._errors.unshift(Error("RetryOperation timeout occurred")),!1;this._errors.push(err);var timeout=this._timeouts.shift();if(timeout===void 0)if(this._cachedTimeouts)this._errors.splice(this._errors.length-1,this._errors.length),this._timeouts=this._cachedTimeouts.slice(0),timeout=this._timeouts.shift();else return!1;var self=this,timer=setTimeout(function(){if(self._attempts++,self._operationTimeoutCb){if(self._timeout=setTimeout(function(){self._operationTimeoutCb(self._attempts)},self._operationTimeout),self._options.unref)self._timeout.unref()}self._fn(self._attempts)},timeout);if(this._options.unref)timer.unref();return!0};RetryOperation.prototype.attempt=function(fn2,timeoutOps){if(this._fn=fn2,timeoutOps){if(timeoutOps.timeout)this._operationTimeout=timeoutOps.timeout;if(timeoutOps.cb)this._operationTimeoutCb=timeoutOps.cb}var self=this;if(this._operationTimeoutCb)this._timeout=setTimeout(function(){self._operationTimeoutCb()},self._operationTimeout);this._operationStart=new Date().getTime(),this._fn(this._attempts)};RetryOperation.prototype.try=function(fn2){console.log("Using RetryOperation.try() is deprecated"),this.attempt(fn2)};RetryOperation.prototype.start=function(fn2){console.log("Using RetryOperation.start() is deprecated"),this.attempt(fn2)};RetryOperation.prototype.start=RetryOperation.prototype.try;RetryOperation.prototype.errors=function(){return this._errors};RetryOperation.prototype.attempts=function(){return this._attempts};RetryOperation.prototype.mainError=function(){if(this._errors.length===0)return null;var counts={},mainError=null,mainErrorCount=0;for(var i=0;i<this._errors.length;i++){var error49=this._errors[i],message=error49.message,count=(counts[message]||0)+1;if(counts[message]=count,count>=mainErrorCount)mainError=error49,mainErrorCount=count}return mainError}});var require_retry=__commonJS((exports)=>{var RetryOperation=require_retry_operation();exports.operation=function(options){var timeouts=exports.timeouts(options);return new RetryOperation(timeouts,{forever:options&&options.forever,unref:options&&options.unref,maxRetryTime:options&&options.maxRetryTime})};exports.timeouts=function(options){if(options instanceof Array)return[].concat(options);var opts={retries:10,factor:2,minTimeout:1000,maxTimeout:1/0,randomize:!1};for(var key in options)opts[key]=options[key];if(opts.minTimeout>opts.maxTimeout)throw Error("minTimeout is greater than maxTimeout");var timeouts=[];for(var i=0;i<opts.retries;i++)timeouts.push(this.createTimeout(i,opts));if(options&&options.forever&&!timeouts.length)timeouts.push(this.createTimeout(i,opts));return timeouts.sort(function(a,b){return a-b}),timeouts};exports.createTimeout=function(attempt,opts){var random=opts.randomize?Math.random()+1:1,timeout=Math.round(random*opts.minTimeout*Math.pow(opts.factor,attempt));return timeout=Math.min(timeout,opts.maxTimeout),timeout};exports.wrap=function(obj,options,methods){if(options instanceof Array)methods=options,options=null;if(!methods){methods=[];for(var key in obj)if(typeof obj[key]==="function")methods.push(key)}for(var i=0;i<methods.length;i++){var method=methods[i],original=obj[method];obj[method]=function(original2){var op=exports.operation(options),args2=Array.prototype.slice.call(arguments,1),callback=args2.pop();args2.push(function(err){if(op.retry(err))return;if(err)arguments[0]=op.mainError();callback.apply(this,arguments)}),op.attempt(function(){original2.apply(obj,args2)})}.bind(obj,original),obj[method].options=options}}});var require_signals=__commonJS((exports,module)=>{module.exports=["SIGABRT","SIGALRM","SIGHUP","SIGINT","SIGTERM"];if(process.platform!=="win32")module.exports.push("SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");if(process.platform==="linux")module.exports.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT","SIGUNUSED")});var require_signal_exit=__commonJS((exports,module)=>{var process3=global.process,processOk=function(process4){return process4&&typeof process4==="object"&&typeof process4.removeListener==="function"&&typeof process4.emit==="function"&&typeof process4.reallyExit==="function"&&typeof process4.listeners==="function"&&typeof process4.kill==="function"&&typeof process4.pid==="number"&&typeof process4.on==="function"};if(!processOk(process3))module.exports=function(){return function(){}};else{if(assert2=__require("assert"),signals=require_signals(),isWin=/^win/i.test(process3.platform),EE=__require("events"),typeof EE!=="function")EE=EE.EventEmitter;if(process3.__signal_exit_emitter__)emitter=process3.__signal_exit_emitter__;else emitter=process3.__signal_exit_emitter__=new EE,emitter.count=0,emitter.emitted={};if(!emitter.infinite)emitter.setMaxListeners(1/0),emitter.infinite=!0;module.exports=function(cb,opts){if(!processOk(global.process))return function(){};if(assert2.equal(typeof cb,"function","a callback must be provided for exit handler"),loaded===!1)load();var ev="exit";if(opts&&opts.alwaysLast)ev="afterexit";var remove=function(){if(emitter.removeListener(ev,cb),emitter.listeners("exit").length===0&&emitter.listeners("afterexit").length===0)unload()};return emitter.on(ev,cb),remove},unload=function(){if(!loaded||!processOk(global.process))return;loaded=!1,signals.forEach(function(sig){try{process3.removeListener(sig,sigListeners[sig])}catch(er){}}),process3.emit=originalProcessEmit,process3.reallyExit=originalProcessReallyExit,emitter.count-=1},module.exports.unload=unload,emit=function(event,code,signal){if(emitter.emitted[event])return;emitter.emitted[event]=!0,emitter.emit(event,code,signal)},sigListeners={},signals.forEach(function(sig){sigListeners[sig]=function(){if(!processOk(global.process))return;var listeners=process3.listeners(sig);if(listeners.length===emitter.count){if(unload(),emit("exit",null,sig),emit("afterexit",null,sig),isWin&&sig==="SIGHUP")sig="SIGINT";process3.kill(process3.pid,sig)}}}),module.exports.signals=function(){return signals},loaded=!1,load=function(){if(loaded||!processOk(global.process))return;loaded=!0,emitter.count+=1,signals=signals.filter(function(sig){try{return process3.on(sig,sigListeners[sig]),!0}catch(er){return!1}}),process3.emit=processEmit,process3.reallyExit=processReallyExit},module.exports.load=load,originalProcessReallyExit=process3.reallyExit,processReallyExit=function(code){if(!processOk(global.process))return;process3.exitCode=code||0,emit("exit",process3.exitCode,null),emit("afterexit",process3.exitCode,null),originalProcessReallyExit.call(process3,process3.exitCode)},originalProcessEmit=process3.emit,processEmit=function(ev,arg){if(ev==="exit"&&processOk(global.process)){if(arg!==void 0)process3.exitCode=arg;var ret=originalProcessEmit.apply(this,arguments);return emit("exit",process3.exitCode,null),emit("afterexit",process3.exitCode,null),ret}else return originalProcessEmit.apply(this,arguments)}}var assert2,signals,isWin,EE,emitter,unload,emit,sigListeners,loaded,load,originalProcessReallyExit,processReallyExit,originalProcessEmit,processEmit});var require_mtime_precision=__commonJS((exports,module)=>{var cacheSymbol=Symbol();function probe(file2,fs4,callback){let cachedPrecision=fs4[cacheSymbol];if(cachedPrecision)return fs4.stat(file2,(err,stat4)=>{if(err)return callback(err);callback(null,stat4.mtime,cachedPrecision)});let mtime=new Date(Math.ceil(Date.now()/1000)*1000+5);fs4.utimes(file2,mtime,mtime,(err)=>{if(err)return callback(err);fs4.stat(file2,(err2,stat4)=>{if(err2)return callback(err2);let precision=stat4.mtime.getTime()%1000===0?"s":"ms";Object.defineProperty(fs4,cacheSymbol,{value:precision}),callback(null,stat4.mtime,precision)})})}function getMtime(precision){let now=Date.now();if(precision==="s")now=Math.ceil(now/1000)*1000;return new Date(now)}exports.probe=probe;exports.getMtime=getMtime});var require_lockfile=__commonJS((exports,module)=>{var path6=__require("path"),fs4=require_graceful_fs(),retry=require_retry(),onExit=require_signal_exit(),mtimePrecision=require_mtime_precision(),locks={};function getLockFile(file2,options){return options.lockfilePath||`${file2}.lock`}function resolveCanonicalPath(file2,options,callback){if(!options.realpath)return callback(null,path6.resolve(file2));options.fs.realpath(file2,callback)}function acquireLock(file2,options,callback){let lockfilePath=getLockFile(file2,options);options.fs.mkdir(lockfilePath,(err)=>{if(!err)return mtimePrecision.probe(lockfilePath,options.fs,(err2,mtime,mtimePrecision2)=>{if(err2)return options.fs.rmdir(lockfilePath,()=>{}),callback(err2);callback(null,mtime,mtimePrecision2)});if(err.code!=="EEXIST")return callback(err);if(options.stale<=0)return callback(Object.assign(Error("Lock file is already being held"),{code:"ELOCKED",file:file2}));options.fs.stat(lockfilePath,(err2,stat4)=>{if(err2){if(err2.code==="ENOENT")return acquireLock(file2,{...options,stale:0},callback);return callback(err2)}if(!isLockStale(stat4,options))return callback(Object.assign(Error("Lock file is already being held"),{code:"ELOCKED",file:file2}));removeLock(file2,options,(err3)=>{if(err3)return callback(err3);acquireLock(file2,{...options,stale:0},callback)})})})}function isLockStale(stat4,options){return stat4.mtime.getTime()<Date.now()-options.stale}function removeLock(file2,options,callback){options.fs.rmdir(getLockFile(file2,options),(err)=>{if(err&&err.code!=="ENOENT")return callback(err);callback()})}function updateLock(file2,options){let lock2=locks[file2];if(lock2.updateTimeout)return;if(lock2.updateDelay=lock2.updateDelay||options.update,lock2.updateTimeout=setTimeout(()=>{lock2.updateTimeout=null,options.fs.stat(lock2.lockfilePath,(err,stat4)=>{let isOverThreshold=lock2.lastUpdate+options.stale<Date.now();if(err){if(err.code==="ENOENT"||isOverThreshold)return setLockAsCompromised(file2,lock2,Object.assign(err,{code:"ECOMPROMISED"}));return lock2.updateDelay=1000,updateLock(file2,options)}if(lock2.mtime.getTime()!==stat4.mtime.getTime())return setLockAsCompromised(file2,lock2,Object.assign(Error("Unable to update lock within the stale threshold"),{code:"ECOMPROMISED"}));let mtime=mtimePrecision.getMtime(lock2.mtimePrecision);options.fs.utimes(lock2.lockfilePath,mtime,mtime,(err2)=>{let isOverThreshold2=lock2.lastUpdate+options.stale<Date.now();if(lock2.released)return;if(err2){if(err2.code==="ENOENT"||isOverThreshold2)return setLockAsCompromised(file2,lock2,Object.assign(err2,{code:"ECOMPROMISED"}));return lock2.updateDelay=1000,updateLock(file2,options)}lock2.mtime=mtime,lock2.lastUpdate=Date.now(),lock2.updateDelay=null,updateLock(file2,options)})})},lock2.updateDelay),lock2.updateTimeout.unref)lock2.updateTimeout.unref()}function setLockAsCompromised(file2,lock2,err){if(lock2.released=!0,lock2.updateTimeout)clearTimeout(lock2.updateTimeout);if(locks[file2]===lock2)delete locks[file2];lock2.options.onCompromised(err)}function lock(file2,options,callback){options={stale:1e4,update:null,realpath:!0,retries:0,fs:fs4,onCompromised:(err)=>{throw err},...options},options.retries=options.retries||0,options.retries=typeof options.retries==="number"?{retries:options.retries}:options.retries,options.stale=Math.max(options.stale||0,2000),options.update=options.update==null?options.stale/2:options.update||0,options.update=Math.max(Math.min(options.update,options.stale/2),1000),resolveCanonicalPath(file2,options,(err,file3)=>{if(err)return callback(err);let operation=retry.operation(options.retries);operation.attempt(()=>{acquireLock(file3,options,(err2,mtime,mtimePrecision2)=>{if(operation.retry(err2))return;if(err2)return callback(operation.mainError());let lock2=locks[file3]={lockfilePath:getLockFile(file3,options),mtime,mtimePrecision:mtimePrecision2,options,lastUpdate:Date.now()};updateLock(file3,options),callback(null,(releasedCallback)=>{if(lock2.released)return releasedCallback&&releasedCallback(Object.assign(Error("Lock is already released"),{code:"ERELEASED"}));unlock(file3,{...options,realpath:!1},releasedCallback)})})})})}function unlock(file2,options,callback){options={fs:fs4,realpath:!0,...options},resolveCanonicalPath(file2,options,(err,file3)=>{if(err)return callback(err);let lock2=locks[file3];if(!lock2)return callback(Object.assign(Error("Lock is not acquired/owned by you"),{code:"ENOTACQUIRED"}));lock2.updateTimeout&&clearTimeout(lock2.updateTimeout),lock2.released=!0,delete locks[file3],removeLock(file3,options,callback)})}function check2(file2,options,callback){options={stale:1e4,realpath:!0,fs:fs4,...options},options.stale=Math.max(options.stale||0,2000),resolveCanonicalPath(file2,options,(err,file3)=>{if(err)return callback(err);options.fs.stat(getLockFile(file3,options),(err2,stat4)=>{if(err2)return err2.code==="ENOENT"?callback(null,!1):callback(err2);return callback(null,!isLockStale(stat4,options))})})}function getLocks(){return locks}onExit(()=>{for(let file2 in locks){let options=locks[file2].options;try{options.fs.rmdirSync(getLockFile(file2,options))}catch(e){}}});exports.lock=lock;exports.unlock=unlock;exports.check=check2;exports.getLocks=getLocks});var require_adapter=__commonJS((exports,module)=>{var fs4=require_graceful_fs();function createSyncFs(fs5){let methods=["mkdir","realpath","stat","rmdir","utimes"],newFs={...fs5};return methods.forEach((method)=>{newFs[method]=(...args2)=>{let callback=args2.pop(),ret;try{ret=fs5[`${method}Sync`](...args2)}catch(err){return callback(err)}callback(null,ret)}}),newFs}function toPromise(method){return(...args2)=>new Promise((resolve4,reject)=>{args2.push((err,result)=>{if(err)reject(err);else resolve4(result)}),method(...args2)})}function toSync(method){return(...args2)=>{let err,result;if(args2.push((_err,_result)=>{err=_err,result=_result}),method(...args2),err)throw err;return result}}function toSyncOptions(options){if(options={...options},options.fs=createSyncFs(options.fs||fs4),typeof options.retries==="number"&&options.retries>0||options.retries&&typeof options.retries.retries==="number"&&options.retries.retries>0)throw Object.assign(Error("Cannot use retries with the sync api"),{code:"ESYNC"});return options}module.exports={toPromise,toSync,toSyncOptions}});var require_proper_lockfile=__commonJS((exports,module)=>{var lockfile=require_lockfile(),{toPromise,toSync,toSyncOptions}=require_adapter();async function lock(file2,options){let release=await toPromise(lockfile.lock)(file2,options);return toPromise(release)}function lockSync(file2,options){let release=toSync(lockfile.lock)(file2,toSyncOptions(options));return toSync(release)}function unlock(file2,options){return toPromise(lockfile.unlock)(file2,options)}function unlockSync(file2,options){return toSync(lockfile.unlock)(file2,toSyncOptions(options))}function check2(file2,options){return toPromise(lockfile.check)(file2,options)}function checkSync(file2,options){return toSync(lockfile.check)(file2,toSyncOptions(options))}module.exports=lock;module.exports.lock=lock;module.exports.unlock=unlock;module.exports.lockSync=lockSync;module.exports.unlockSync=unlockSync;module.exports.check=check2;module.exports.checkSync=checkSync});var SwarmError;var init_errors3=__esm(()=>{SwarmError=class SwarmError extends Error{code;guidance;constructor(message,code,guidance){super(message);this.name="SwarmError",this.code=code,this.guidance=guidance}}});function escapeRegex2(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function simpleGlobToRegex(pattern,flags="i"){let escaped=pattern.split("*").map((starSegment)=>starSegment.split("?").map(escapeRegex2).join(".")).join(".*");return new RegExp(`^${escaped}$`,flags)}var init_utils=__esm(()=>{init_errors3();init_logger();init_merge()});import{randomBytes}from"node:crypto";import*as fs4 from"node:fs";import*as path6 from"node:path";function matchTempGrammar(basename2){return SWARM_TEMP_GRAMMARS.find((g)=>g.match.test(basename2))}function parseTargetBasename(basename2){for(let g of SWARM_TEMP_GRAMMARS){if(!g.parsesTarget)continue;let m=g.match.exec(basename2);if(m?.[1])return m[1]}return null}function assertWellFormedTargetPath(targetPath){if(!path6.isAbsolute(targetPath))throw Error(`atomic-write target must be absolute: ${targetPath}`);if(/[\0-\x1f\x7f]/.test(targetPath))throw Error("atomic-write target contains control characters");if(/[*?]/.test(targetPath)||/(^|[/\\])\{[^}]*\}([/\\]|$)/.test(targetPath))throw Error(`atomic-write target contains glob metacharacters: ${targetPath}`);if(/(^|[/\\])~([/\\]|$)/.test(targetPath))throw Error("atomic-write target contains unresolved home-dir marker (~)");if(/\$\{?[A-Za-z_][A-Za-z0-9_]*\}?/.test(targetPath)||/%[^/\\%]+%/.test(targetPath))throw Error("atomic-write target contains unresolved environment-variable form")}function lstatNotSymlink(p,what){if(fs4.lstatSync(p).isSymbolicLink())throw Error(`${what} is a symlink/reparse point: ${p}`)}function assertSwarmContainedTarget(targetPath){assertWellFormedTargetPath(targetPath);let resolved=path6.normalize(path6.resolve(targetPath)),segments=resolved.split(path6.sep),swarmIdx=-1;for(let i=segments.length-2;i>=1;i--)if(segments[i]===".swarm"){swarmIdx=i;break}if(swarmIdx===-1)throw Error(`atomic-write target is not under a project .swarm root: ${targetPath}`);let swarmRoot=segments.slice(0,swarmIdx+1).join(path6.sep);try{let st=fs4.lstatSync(swarmRoot);if(!st.isDirectory()||st.isSymbolicLink())throw Error(`.swarm root is not a real directory (symlink/reparse or non-dir): ${swarmRoot}`)}catch(err){if(err?.code!=="ENOENT")throw err}let rel=path6.relative(swarmRoot,resolved);if(!rel||rel.startsWith("..")||path6.isAbsolute(rel))throw Error(`atomic-write target escapes .swarm root: ${targetPath}`);let probe=swarmRoot;for(let seg of rel.split(path6.sep)){if(probe=path6.join(probe,seg),!fs4.existsSync(probe))break;lstatNotSymlink(probe,"path segment under .swarm")}return{projectRoot:path6.dirname(swarmRoot),swarmRoot}}function noteRecentWriteActivity(resolvedTarget){recentWriteActivity.delete(resolvedTarget),recentWriteActivity.set(resolvedTarget,Date.now());while(recentWriteActivity.size>MAX_RECENT_WRITE_TRACKED_PATHS){let oldest=recentWriteActivity.keys().next().value;if(oldest===void 0)break;recentWriteActivity.delete(oldest)}}function clearRecentWriteActivity(targetPath){return recentWriteActivity.delete(path6.resolve(targetPath))}function wasRecentlyWrittenByThisProcess(targetPath,withinMs=RECENT_WRITE_WINDOW_MS){let last=recentWriteActivity.get(path6.resolve(targetPath));if(last===void 0)return!1;return Date.now()-last<=withinMs}function toBuffer(content){if(typeof content==="string")return Buffer.from(content,"utf-8");return content}function syncSleep(ms){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,ms)}catch{let start=Date.now();while(Date.now()-start<ms);}}function renameWithRetry(tempPath,targetPath){let lastError;for(let attempt=0;attempt<=RENAME_RETRY_DELAYS_MS.length;attempt++)try{_internals8.renameSync(tempPath,targetPath);return}catch(err){lastError=err;let code=err?.code;if(!code||!RETRYABLE_RENAME_CODES.has(code))throw err;if(attempt<RENAME_RETRY_DELAYS_MS.length)syncSleep(RENAME_RETRY_DELAYS_MS[attempt])}throw lastError}function writeAtomicSync(targetPath,content,options){if(options?.contained!==!1)assertSwarmContainedTarget(targetPath);else assertWellFormedTargetPath(targetPath);let resolvedTarget=path6.resolve(targetPath);noteRecentWriteActivity(resolvedTarget);let buffer=toBuffer(content),maxBytes=options?.maxBytes??MAX_ATOMIC_WRITE_BYTES;if(buffer.byteLength>maxBytes)throw Error(`atomic write exceeds ${maxBytes} byte bound: ${buffer.byteLength}`);let tempPath=`${resolvedTarget}.${_internals8.randomSuffix()}.tmp`;fs4.mkdirSync(path6.dirname(tempPath),{recursive:!0});try{try{let fd=fs4.openSync(tempPath,"wx",options?.mode);try{let written=0;while(written<buffer.byteLength)written+=_internals8.writeSync(fd,buffer,written,buffer.byteLength-written);if(options?.skipFsync!==!0)try{_internals8.fsyncSync(fd)}catch{}}finally{fs4.closeSync(fd)}renameWithRetry(tempPath,resolvedTarget)}finally{try{_internals8.unlinkSync(tempPath)}catch{}}}catch(error49){throw clearRecentWriteActivity(resolvedTarget),error49}try{let dirFd=fs4.openSync(path6.dirname(resolvedTarget),"r");try{fs4.fsyncSync(dirFd)}finally{fs4.closeSync(dirFd)}}catch{}invalidateCachedArtifact(resolvedTarget),noteRecentWriteActivity(resolvedTarget)}async function atomicWriteSwarmFile(targetPath,content,options){await new Promise((resolve5)=>setImmediate(resolve5)),writeAtomicSync(targetPath,content,options)}function atomicWriteSwarmFileSync(targetPath,content,options){writeAtomicSync(targetPath,content,options)}async function atomicWriteFileAnyRoot(targetPath,content,options){await new Promise((resolve5)=>setImmediate(resolve5)),writeAtomicSync(targetPath,content,{...options,contained:!1})}var UUID_RE="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",SWARM_TEMP_GRAMMARS,WRITER_CLASSIFICATION,MAX_ATOMIC_WRITE_BYTES=268435456,RENAME_RETRY_DELAYS_MS,RETRYABLE_RENAME_CODES,MAX_RECENT_WRITE_TRACKED_PATHS=256,RECENT_WRITE_WINDOW_MS=500,recentWriteActivity,_internals8;var init_atomic_write=__esm(()=>{init_swarm_artifact_cache();SWARM_TEMP_GRAMMARS=[{id:"canonical-v1",era:"canonical",match:/^(.+)\.[0-9a-f]{32}\.tmp$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/utils/atomic-write.ts:atomicWriteSwarmFile","src/utils/atomic-write.ts:atomicWriteFileAnyRoot"]},{id:"target-suffix-tmp-uuid",era:"current",match:new RegExp(`^(.+)\\.tmp\\.${UUID_RE}$`),token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/commands/handoff.ts (pre-#2035; site=handoff.md; migrated-to=src/commands/handoff.ts:handleHandoffCommand)","src/commands/handoff.ts (pre-#2035; site=handoff-prompt.md; migrated-to=src/commands/handoff.ts:handleHandoffCommand)","src/memory/local-jsonl-provider.ts:1288","src/config/bundled-skills.ts:259"]},{id:"target-suffix-tmp-pid-uuid",era:"current",match:new RegExp(`^(.+)\\.tmp\\.\\d+\\.${UUID_RE}$`),token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/hooks/pr-workflow-gate.ts (pre-#2385; migrated-to=src/pr-review/persistence.ts:writeAtomicJson)"],note:"pre/post-rename file-identity verification (assertOpened/ClosedSwarmFileIdentity, pr-workflow-gate.ts:17880-17980) is writer-specific and load-bearing"},{id:"target-suffix-tmp-num-num-json",era:"current",match:/^(.+)\.tmp\.\d+\.\d+\.json$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/hooks/issue-trace-state.ts:447"],note:"the .json terminator keeps this shape distinct from the bare two-token family — declared before it so first-match wins"},{id:"target-suffix-tmp-num-alnum",era:"current",match:/^(.+)\.tmp\.\d+\.[0-9a-z]+$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/evidence/task-file.ts (pre-#2035; migrated-to=src/evidence/task-file.ts:atomicWriteFile)","src/scope/scope-persistence.ts (pre-#2035; migrated-to=src/scope/scope-persistence.ts:atomicWrite)","src/scope/scope-persistence.ts (pre-#2035; migrated-to=src/scope/scope-persistence.ts:atomicWriteSync)","src/plan/manager.ts:683","src/plan/manager.ts:2110","src/plan/manager.ts:2170","src/review/evidence.ts:175","src/turbo/lean/evidence.ts:182","src/summaries/manager.ts:163","src/evidence/manager.ts:288","src/evidence/manager.ts:456","src/tools/sast-baseline.ts:199","src/tools/repo-graph/storage.ts:543","src/memory/reflection-service.ts (pre-#2035; migrated-to=src/memory/reflection-service.ts:atomicWrite)","src/hooks/review-receipt.ts:609","src/hooks/review-receipt.ts:675","src/hooks/review-receipt.ts:894","src/knowledge/identity.ts:230","src/evidence/phase-participation.ts (pre-#2035; migrated-to=src/evidence/phase-participation.ts:atomicWriteBytes)","src/turbo/lean/integration.ts:428","src/turbo/lean/reviewer.ts:403","src/plan/ledger.ts:1471","src/services/synonym-map.ts:389","src/services/skill-optimizer/store.ts:340","src/services/skill-optimizer/store.ts:503","src/turbo/epic/calibration.ts:234","src/commands/archive-sqlite.ts:318","src/memory/jsonl-migration.ts:161"],note:"fsync-discipline / lock-scoped fd writers whose temp naming is pinned by their own durability test suites (plan-durability invariant 5, #2034 crash matrix); grammars registered here so their residue stays discoverable"},{id:"target-suffix-tmp-token",era:"current",match:/^(.+)\.tmp\.[0-9a-z-]{6,}$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/turbo/lean/state.ts:129","src/turbo/lean/recovery.ts:175","src/hooks/delegation-gate/worktree-merge-status.ts:110","src/plan/ledger.ts:606"]},{id:"target-suffix-tmp-dash",era:"current",match:/^(.+)\.tmp-\d+-[0-9a-z-]+$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/services/skill-evaluator.ts (pre-#2035; migrated-to=src/services/skill-evaluator.ts:atomicWrite)","src/services/skill-improver.ts (pre-#2035; migrated-to=src/services/skill-improver.ts:atomicWrite)","src/services/skill-consolidation.ts (pre-#2035; migrated-to=src/services/skill-consolidation.ts:atomicWrite)","src/services/skill-generator.ts (pre-#2035; migrated-to=src/services/skill-generator.ts:atomicWrite)","src/tools/spec-write.ts:98","src/sdd/effective-spec.ts:1377","src/background/lane-output-store.ts:353","src/background/pending-delegations.ts:1501","src/background/delegation-health.ts:391","src/tools/submit-phase-council-verdicts.ts:458","src/summaries/store.ts (pre-#2035; migrated-to=src/summaries/store.ts:writeRawSidecar)","src/retention/jsonl-cap.ts:213","src/services/skill-changelog.ts:58","src/turbo/epic/divergence-recorder.ts:108"],note:"background lane/delegation stores keep bounded-retry rename semantics wired into their callers (#2034/#2276 delivery contracts); migration candidates for a follow-up but grammars registered"},{id:"target-suffix-tmp-dash-num",era:"current",match:/^(.+)\.tmp-\d+$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/services/skill-improver-quota.ts:114"]},{id:"target-dot-pid-uuid-tmp",era:"current",match:new RegExp(`^(.+)\\.\\d+\\.${UUID_RE}\\.tmp$`),token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/hooks/knowledge-receipt-ledger-storage.ts:591"],note:"pre/post-rename file-identity verification (existingFileIdentity checks, knowledge-receipt-ledger-storage.ts:544-591) is writer-specific and load-bearing"},{id:"dot-numeric-instance-tmp",era:"current",match:/^\..+(?:\.\d+){2,4}\.[0-9a-z]+\.tmp$/,token:"instance",quarantineEligible:!0,parsesTarget:!1,producers:["src/utils/bun-compat.ts:138","src/tools/repo-graph/freshness.ts:171"],note:"bunWrite Node-fallback internal temp and the repo-graph fingerprint temp (2-4 numeric token groups); leading-dot temps are standalone, target not parsed"},{id:"dot-uuid-instance-tmp",era:"current",match:new RegExp(`^\\..+\\.${UUID_RE}\\.tmp$`),token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/tools/write-pr-review-artifact.ts:154","src/tools/write-pr-review-artifact.ts:174","src/tools/write-pr-review-trigger-eval.ts:96"],note:"bundled-skills writes outside .swarm (project skill roots) and keeps its own contained-directory logic (invariant 4 bundled-skill ownership)"},{id:"tmp-prefix-named",era:"legacy",match:/^\.tmp-.+-\d+-\d+$/,token:"instance",quarantineEligible:!0,parsesTarget:!1,producers:["src/commands/issue.ts (pre-#2035; migrated-to=src/commands/issue.ts:atomicWriteFileSync)"],note:"prefix form embeds the filename; target not reliably parseable (dashes), so eligibility relies on the age/tracked/symlink/lock gates"},{id:"target-rebuild-close",era:"current",match:/^(.+)\.(?:rebuild|close)\.\d+\.[0-9a-z]+$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/plan/manager.ts:2369","src/plan/manager.ts:2431"],note:"plan-durability (invariant 5) fd-write paths; grammars registered, writers unchanged in this PR"},{id:"target-migration-pid",era:"current",match:/^(.+)\.migration-\d+$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/scope/scope-persistence.ts (pre-#2035; migrated-to=src/scope/scope-persistence.ts:atomicWriteSync)"]},{id:"dot-tmp-prefix-legacy",era:"legacy",match:/^\.tmp\..+$/,token:"constant",quarantineEligible:!0,parsesTarget:!1,producers:["pre-7.x writers (pre-#2035; scanner=src/services/swarm-residue.ts:collectCandidates)"],note:"legacy prefix grammar: issue #2035 req 7 preserves its handling — stale instances are quarantined (formerly unlinked) under the same eligibility gates"},{id:"dot-constant-tmp",era:"current",match:/^\..+\.tmp$/,token:"constant",quarantineEligible:!1,parsesTarget:!1,producers:["src/tools/write-drift-evidence.ts:275","src/tools/write-mutation-evidence.ts:169","src/tools/write-hallucination-evidence.ts:121","src/tools/write-final-council-evidence.ts:403"],note:"constant-name temps: no per-invocation token — reported when stale, never auto-quarantined (may be an in-flight writer of any process)"},{id:"target-constant-tmp",era:"current",match:/^(.+)\.tmp$/,token:"constant",quarantineEligible:!1,parsesTarget:!1,producers:["src/tools/checkpoint.ts:195","src/full-auto/state.ts:636","src/context-map/persistence.ts:119","src/context-map/capsule-persistence.ts:111","src/test-impact/history-store.ts:297","src/test-impact/history-store.ts:302","src/test-impact/history-store.ts:429","src/test-impact/history-store.ts:435","src/hooks/promotion-evidence-store.ts:112","src/hooks/skill-usage-log.ts:1165","src/hooks/skill-usage-log.ts:1675","src/hooks/skill-usage-pending.ts:817","src/parallel/file-locks.ts:113","src/plan/ledger.ts:607","src/plan/ledger.ts:1793"],note:"constant-name temps: reported when stale, never auto-quarantined. file-locks meta sidecars live under the scanner-skipped .swarm/locks/ subtree; the ledger reconcile temp embeds instance tokens but its .tmp-suffix shape maps here (conservatively report-only)"}];WRITER_CLASSIFICATION=Object.freeze({"src/commands/close.ts":"migrated","src/commands/close/context.ts":"reader-only","src/commands/close/clean-stage.ts":"reader-only","src/commands/handoff.ts":"migrated","src/commands/simulate.ts":"migrated","src/commands/coupling.ts":"migrated","src/commands/issue.ts":"migrated","src/evidence/task-file.ts":"migrated","src/evidence/phase-participation.ts":"migrated","src/memory/reflection-service.ts":"migrated","src/scope/scope-persistence.ts":"migrated","src/services/skill-consolidation.ts":"migrated","src/services/skill-evaluator.ts":"migrated","src/services/skill-generator.ts":"migrated","src/services/skill-improver.ts":"migrated","src/summaries/store.ts":"migrated","src/prm/trajectory-store.ts":"migrated","src/observability/otlp-exporter.ts":"registered-bespoke","src/retention/jsonl-cap.ts":"registered-bespoke","src/services/skill-changelog.ts":"registered-bespoke","src/turbo/epic/divergence-recorder.ts":"registered-bespoke","src/background/delegation-health.ts":"registered-bespoke","src/background/lane-output-store.ts":"registered-bespoke","src/background/pending-delegations.ts":"registered-bespoke","src/commands/archive-sqlite.ts":"registered-bespoke","src/context-map/capsule-persistence.ts":"registered-bespoke","src/context-map/persistence.ts":"registered-bespoke","src/context-map/telemetry.ts":"registered-bespoke","src/events/core-events.ts":"registered-bespoke","src/hooks/guardrails/shell-audit-store.ts":"registered-bespoke","src/evidence/documents-retention.ts":"registered-bespoke","src/evidence/manager.ts":"registered-bespoke","src/full-auto/state.ts":"registered-bespoke","src/hooks/delegation-gate/worktree-merge-status.ts":"registered-bespoke","src/hooks/delegation-gate/worktree-provisioning-owner.ts":"migrated","src/hooks/issue-trace-state.ts":"registered-bespoke","src/hooks/knowledge-receipt-ledger-storage.ts":"registered-bespoke","src/hooks/pr-workflow-gate.ts":"registered-bespoke","src/pr-review/authorization.ts":"registered-bespoke","src/pr-review/persistence.ts":"registered-bespoke","src/hooks/promotion-evidence-store.ts":"registered-bespoke","src/hooks/review-receipt.ts":"registered-bespoke","src/hooks/skill-usage-log.ts":"registered-bespoke","src/hooks/skill-usage-pending.ts":"registered-bespoke","src/knowledge/identity.ts":"registered-bespoke","src/memory/jsonl-migration.ts":"external","src/memory/local-jsonl-provider.ts":"registered-bespoke","src/plan/ledger.ts":"registered-bespoke","src/plan/manager.ts":"registered-bespoke","src/review/evidence.ts":"registered-bespoke","src/sdd/effective-spec.ts":"registered-bespoke","src/services/skill-improver-quota.ts":"registered-bespoke","src/services/skill-optimizer/activation.ts":"external","src/services/skill-optimizer/store.ts":"registered-bespoke","src/services/skill-reviser.ts":"external","src/services/synonym-map.ts":"registered-bespoke","src/session/snapshot-writer.ts":"registered-bespoke","src/summaries/manager.ts":"registered-bespoke","src/test-impact/history-store.ts":"registered-bespoke","src/turbo/epic/calibration.ts":"registered-bespoke","src/turbo/epic/state.ts":"registered-bespoke","src/turbo/lean/evidence.ts":"registered-bespoke","src/turbo/lean/integration.ts":"registered-bespoke","src/turbo/lean/recovery.ts":"registered-bespoke","src/turbo/lean/reviewer.ts":"registered-bespoke","src/turbo/lean/state.ts":"registered-bespoke","src/tools/apply-patch.ts":"external","src/tools/checkpoint.ts":"registered-bespoke","src/tools/record-implementation-review.ts":"migrated","src/tools/record-issue-publication.ts":"migrated","src/tools/record-issue-reproduction.ts":"migrated","src/tools/record-recurrence-sweep.ts":"migrated","src/tools/record-branch-freshness.ts":"migrated","src/tools/record-trace-validation.ts":"migrated","src/tools/record-merge-approval.ts":"migrated","src/tools/repo-graph/freshness.ts":"registered-bespoke","src/tools/repo-graph/storage.ts":"registered-bespoke","src/tools/sast-baseline.ts":"registered-bespoke","src/tools/spec-write.ts":"registered-bespoke","src/tools/submit-phase-council-verdicts.ts":"registered-bespoke","src/tools/write-drift-evidence.ts":"registered-bespoke","src/tools/write-final-council-evidence.ts":"registered-bespoke","src/tools/write-hallucination-evidence.ts":"registered-bespoke","src/tools/write-mutation-evidence.ts":"registered-bespoke","src/tools/write-pr-review-artifact.ts":"registered-bespoke","src/tools/write-pr-review-trigger-eval.ts":"registered-bespoke","src/config/bundled-skills.ts":"external","src/services/config-doctor.ts":"external","src/parallel/file-locks.ts":"registered-bespoke","src/utils/bun-compat.ts":"registered-bespoke","src/background/plan-sync-worker.ts":"reader-only","src/config/lane-permissions.ts":"reader-only","src/environment/profile.ts":"reader-only","src/worktree/core.ts":"reader-only"});RENAME_RETRY_DELAYS_MS=[10,25,50,100,200],RETRYABLE_RENAME_CODES=new Set(["EPERM","EBUSY","EACCES","EEXIST"]),recentWriteActivity=new Map;_internals8={randomSuffix:()=>randomBytes(16).toString("hex"),writeSync:(fd,buffer,offset,length)=>fs4.writeSync(fd,buffer,offset,length),renameSync:(from,to)=>fs4.renameSync(from,to),unlinkSync:(p)=>fs4.unlinkSync(p),fsyncSync:(fd)=>fs4.fsyncSync(fd)}});import{spawn as nodeSpawn,spawnSync as nodeSpawnSync}from"node:child_process";import*as fsSync3 from"node:fs";import*as fsPromises2 from"node:fs/promises";import*as path7 from"node:path";function getBun(){return globalThis.Bun}function bunFile(filePath){let bun=getBun();if(bun?.file)return bun.file(filePath);let cachedSize;return{async text(){return fsPromises2.readFile(filePath,"utf-8")},async arrayBuffer(){let buf=await fsPromises2.readFile(filePath),ab=new ArrayBuffer(buf.byteLength);return new Uint8Array(ab).set(buf),ab},async exists(){try{return await fsPromises2.access(filePath,fsSync3.constants.F_OK),!0}catch{return!1}},get size(){if(cachedSize!==void 0)return cachedSize;try{cachedSize=fsSync3.statSync(filePath).size}catch{cachedSize=0}return cachedSize}}}async function bunWrite(filePath,data){let bun=getBun();if(bun?.write)return bun.write(filePath,data);let dir=path7.dirname(filePath),tempName=`.${path7.basename(filePath)}.${process.pid}.${Date.now()}.${tempCounter++}.${Math.random().toString(36).slice(2,10)}.tmp`,tempPath=path7.join(dir,tempName),buffer;if(typeof data==="string")buffer=data;else if(data instanceof ArrayBuffer)buffer=new Uint8Array(data);else if(ArrayBuffer.isView(data))buffer=new Uint8Array(data.buffer,data.byteOffset,data.byteLength);else buffer=new Uint8Array(0);try{await fsPromises2.mkdir(dir,{recursive:!0})}catch{}await fsPromises2.writeFile(tempPath,buffer);let lastError;for(let attempt=0;attempt<WINDOWS_RENAME_MAX_RETRIES;attempt++)try{await fsPromises2.rename(tempPath,filePath),lastError=void 0;break}catch(err){lastError=err;let code=err.code;if(code!=="EEXIST"&&code!=="EBUSY"&&code!=="EPERM")break;await new Promise((r)=>setTimeout(r,WINDOWS_RENAME_RETRY_DELAY_MS))}if(lastError){try{await fsPromises2.unlink(tempPath)}catch{}throw lastError}try{let dirFd=await fsPromises2.open(dir,"r");try{await dirFd.sync()}finally{await dirFd.close()}}catch{}return(await fsPromises2.stat(filePath)).size}function sleep(ms){let bun=getBun();if(bun?.sleep)return bun.sleep(ms);return new Promise((resolve5)=>setTimeout(resolve5,ms))}function collectGarbageBestEffort(){let bun=getBun();try{bun?.gc?.(!0)}catch{}}function bunHash(input){let bun=getBun();if(bun?.hash){let r=bun.hash(input);return typeof r==="bigint"?r:BigInt(r)}let bytes;if(typeof input==="string")bytes=new TextEncoder().encode(input);else if(input instanceof ArrayBuffer)bytes=new Uint8Array(input);else bytes=new Uint8Array(input.buffer,input.byteOffset,input.byteLength);let hash2=5381n;for(let b of bytes)hash2=hash2*33n+BigInt(b)&0xffffffffffffffffn;return hash2}async function killProcessTreeImpl(pid,signal,directKill,wasDetached){if(typeof pid!=="number"||pid<=0){directKill(signal);return}if(_internals9.platform()==="win32"){let taskkill;try{if(taskkill=_internals9.spawnTaskkill(["/PID",String(pid),"/T","/F"],{cwd:_internals9.cwd(),stdio:["ignore","ignore","ignore"],timeout:5000,killSignal:"SIGKILL",windowsHide:!0}),await new Promise((resolve5)=>{let settled=!1,finish=(value)=>{if(settled)return;settled=!0,resolve5(value)};taskkill?.once("error",()=>finish(!1)),taskkill?.once("exit",(code)=>finish(code===0))}))return}catch{}finally{try{taskkill?.kill("SIGKILL")}catch{}}throw directKill(signal),Error("Windows process-tree termination could not be confirmed")}if(wasDetached)try{process.kill(-pid,signal??"SIGKILL");return}catch{}directKill(signal)}function createProcessTreeKiller(pid,directKill,wasDetached){return(signal)=>killProcessTreeImpl(pid,signal,directKill,wasDetached)}function inspectSpawnCwd(cwd){try{return _internals9.statSync(cwd).isDirectory()?"directory":"not-directory"}catch(err){let code=typeof err==="object"&&err!==null&&"code"in err?err.code:void 0;if(code==="ENOENT"||code==="ENOTDIR")return"missing";if(code==="EACCES"||code==="EPERM")return"unreadable";return"unknown"}}function describeSpawnCwdFailure(cwd,executable,cause){let state2=inspectSpawnCwd(cwd);if(state2==="missing")return new SpawnCwdMissingError(cwd,"missing",executable,{cause});if(state2==="not-directory")return new SpawnCwdMissingError(cwd,"not-directory",executable,{cause});return null}function spawnErrorCode(err){if(typeof err!=="object"||err===null||!("code"in err))return;let code=err.code;return typeof code==="string"?code:void 0}function classifySpawnFailure(err,cwd){if(err instanceof SpawnCwdMissingError)return"cwd-missing";let code=spawnErrorCode(err);if(code===void 0||!AMBIGUOUS_SPAWN_CODES.has(code))return"other";if(cwd===void 0||cwd==="")return code==="ENOENT"?"binary-missing":"other";switch(inspectSpawnCwd(cwd)){case"missing":case"not-directory":return"cwd-missing";case"unreadable":case"unknown":return"cwd-unreadable";default:return code==="ENOENT"?"binary-missing":"other"}}function wrapSpawnFailure(error49,cwd,executable){let err=asError(error49);if(err instanceof SpawnCwdMissingError)return err;if(cwd===void 0||cwd==="")return err;if(classifySpawnFailure(err,cwd)!=="cwd-missing")return err;return describeSpawnCwdFailure(cwd,executable,err)??err}function normalizedMaxBuffer(value){return typeof value==="number"&&Number.isSafeInteger(value)&&value>0?value:DEFAULT_BUN_SPAWN_MAX_BUFFER_BYTES}function createOutputOverflowController(limit,requestKill){let error49,killRequested=!1,resolveCompleted,completed=new Promise((resolve5)=>{resolveCompleted=resolve5});return{get error(){return error49},completed,overflow(captured,total){if(error49)return;if(error49=new BunCompatOutputLimitError(limit,captured,total),killRequested)return;killRequested=!0;try{requestKill()}catch{}},complete(){resolveCompleted()}}}function streamFromNode(pipe2,limit,controller){if(!pipe2)return staticStream("");let mode,collected,collect=()=>{if(mode==="reader")return Promise.reject(TypeError("Subprocess output is already consumed by a reader"));if(mode="buffered",collected)return collected;return collected=new Promise((resolve5)=>{if(!pipe2){resolve5(Buffer.alloc(0));return}let chunks=[],captured=0,total=0,finished=!1,finish=()=>{if(finished)return;finished=!0,resolve5(Buffer.concat(chunks))};pipe2.on("data",(chunk)=>{let bytes=typeof chunk==="string"?Buffer.from(chunk):chunk;if(total+=bytes.byteLength,controller?.error||limit===void 0)return;let remaining=limit-captured;if(remaining>0){let retained=Buffer.from(bytes.subarray(0,remaining));chunks.push(retained),captured+=retained.byteLength}if(bytes.byteLength>remaining)controller?.overflow(captured,total)}),pipe2.on("end",finish),pipe2.on("close",finish),pipe2.on("error",finish)}).then(async(bytes)=>{if(await controller?.completed,controller?.error)throw controller.error;return bytes}),collected},toWebReadable=()=>{if(!pipe2)return new ReadableStream({start(controller2){controller2.close()}});let r=pipe2;if(typeof r.toWeb==="function")return r.toWeb();return new ReadableStream({start(controller2){pipe2.on("data",(chunk)=>{controller2.enqueue(typeof chunk==="string"?new TextEncoder().encode(chunk):new Uint8Array(chunk.buffer,chunk.byteOffset,chunk.byteLength))}),pipe2.on("end",()=>controller2.close()),pipe2.on("error",(err)=>controller2.error(err))},cancel(){let destroyable=pipe2;if(typeof destroyable.destroy==="function")try{destroyable.destroy()}catch{}}})},result={async text(){return(await collect()).toString("utf-8")},async bytes(){let b=await collect();return new Uint8Array(b.buffer,b.byteOffset,b.byteLength)},getReader(){if(mode!==void 0)throw TypeError("Subprocess output is already consumed");return mode="reader",toWebReadable().getReader()}};if(pipe2&&controller&&limit!==void 0)queueMicrotask(()=>{if(mode===void 0)collect().catch(()=>{return})});return result}function mapStdio(v){return v??"pipe"}function streamFromBun(stream,limit,controller){if(!stream||typeof stream!=="object")return{async text(){return""},async bytes(){return new Uint8Array(0)},getReader(){return new ReadableStream({start(controller2){controller2.close()}}).getReader()}};let candidate=stream,mode,collected,collect=()=>{if(mode==="reader")return Promise.reject(TypeError("Subprocess output is already consumed by a reader"));return mode="buffered",collected??=(async()=>{if(typeof candidate.getReader!=="function")return new Uint8Array(0);let reader=candidate.getReader(),chunks=[],captured=0,total=0;try{for(;;){let{done,value}=await reader.read();if(done)break;if(!value)continue;if(total+=value.byteLength,controller?.error||limit===void 0)continue;let remaining=limit-captured;if(remaining>0){let retained=value.slice(0,remaining);chunks.push(retained),captured+=retained.byteLength}if(value.byteLength>remaining)controller?.overflow(captured,total)}}finally{reader.releaseLock()}if(await controller?.completed,controller?.error)throw controller.error;let out=new Uint8Array(captured),offset=0;for(let chunk of chunks)out.set(chunk,offset),offset+=chunk.byteLength;return out})(),collected},result={async text(){return new TextDecoder().decode(await collect())},bytes:collect,getReader(){if(mode!==void 0)throw TypeError("Subprocess output is already consumed");return mode="reader",typeof candidate.getReader==="function"?candidate.getReader():new ReadableStream({start(streamController){streamController.close()}}).getReader()}};if(typeof candidate.getReader==="function"&&controller&&limit!==void 0)queueMicrotask(()=>{if(mode===void 0)collect().catch(()=>{return})});return result}function mergeEnvForChild(baseEnv,envOverrides){let hasExplicitBaseEnv=baseEnv!==void 0,baseSource=baseEnv??process.env,merged={};for(let[key,value]of Object.entries(baseSource))if(typeof value==="string")merged[key]=value;if(envOverrides)for(let[key,value]of Object.entries(envOverrides))if(value===null)delete merged[key];else merged[key]=value;if(Object.keys(merged).length===0)return hasExplicitBaseEnv?{}:void 0;return merged}function asError(value){return value instanceof Error?value:Error(String(value))}function staticStream(text){let bytes=new TextEncoder().encode(text);return{async text(){return text},async bytes(){return bytes},getReader(){return new ReadableStream({start(controller){if(bytes.byteLength>0)controller.enqueue(bytes);controller.close()}}).getReader()}}}function spawnCreationFailure(error49){return{stdout:streamFromBun(void 0),stderr:staticStream(error49.message),exited:Promise.resolve(SPAWN_CREATION_FAILURE_EXIT_CODE),exitCode:null,signalCode:null,spawnError:error49,kill(){},killTree:()=>Promise.resolve()}}function bunSpawn(cmd,options){let maxBuffer=normalizedMaxBuffer(options?.maxBuffer),bun=getBun();if(bun?.spawn){let mergedEnv2=mergeEnvForChild(options?.env,options?.envOverrides),spawnOpts={...options};if(delete spawnOpts.killProcessTree,delete spawnOpts.maxBuffer,mergedEnv2!==void 0)spawnOpts.env=mergedEnv2;if(options?.timeout&&options.timeout>0&&options.killProcessTree!==!0)spawnOpts.killSignal="SIGKILL";if(options?.killProcessTree===!0)delete spawnOpts.timeout,delete spawnOpts.killSignal,spawnOpts.detached=!0;let spawned;try{spawned=bun.spawn(cmd,spawnOpts)}catch(error49){return spawnCreationFailure(wrapSpawnFailure(error49,options?.cwd,cmd[0]??""))}let proc2=spawned,killBunTree=createProcessTreeKiller(proc2.pid,(sig)=>proc2.kill(sig),!0),killBunProcess=(sig)=>options?.killProcessTree?killBunTree(sig):Promise.resolve(proc2.kill(sig)),outputController2=createOutputOverflowController(maxBuffer,()=>{killBunProcess("SIGKILL").catch(()=>{return})}),timeoutHandle2;if(options?.killProcessTree===!0&&options.timeout&&options.timeout>0){if(timeoutHandle2=setTimeout(()=>{try{killBunProcess("SIGKILL").catch(()=>{return})}catch{}},options.timeout),typeof timeoutHandle2.unref==="function")timeoutHandle2.unref()}let exited2=proc2.exited.finally(()=>{if(timeoutHandle2!==void 0)clearTimeout(timeoutHandle2);outputController2.complete()});return{stdout:streamFromBun(proc2.stdout,maxBuffer,outputController2),stderr:streamFromBun(proc2.stderr,maxBuffer,outputController2),exited:exited2,get exitCode(){return proc2.exitCode},get signalCode(){return proc2.signalCode},kill(sig){killBunProcess(sig).catch(()=>{return})},killTree:killBunProcess}}let[file2,...args2]=cmd,detached=options?.killProcessTree===!0,mergedEnv=mergeEnvForChild(options?.env,options?.envOverrides),proc;try{proc=nodeSpawn(file2,args2,{cwd:options?.cwd,env:mergedEnv,detached,windowsHide:!0,windowsVerbatimArguments:options?.windowsVerbatimArguments,stdio:[mapStdio(options?.stdin),mapStdio(options?.stdout),mapStdio(options?.stderr)]})}catch(error49){return spawnCreationFailure(wrapSpawnFailure(error49,options?.cwd,file2))}let killChildTree=createProcessTreeKiller(proc.pid,(signal)=>proc.kill(signal),!0),killChild=(signal)=>{if(detached)return killChildTree(signal);return proc.kill(signal),Promise.resolve()},outputController=createOutputOverflowController(maxBuffer,()=>{killChild("SIGKILL").catch(()=>{return})}),timeoutHandle,observedSignal=null,observedSpawnError=null,exited=new Promise((resolve5)=>{if(proc.on("exit",(code,signal)=>{observedSignal=signal,resolve5(code??-1)}),proc.on("error",(error49)=>{observedSpawnError=wrapSpawnFailure(error49,options?.cwd,file2),resolve5(1)}),options?.timeout&&options.timeout>0){if(timeoutHandle=setTimeout(()=>{try{killChild("SIGKILL").catch(()=>{return})}catch{}},options.timeout),typeof timeoutHandle.unref==="function")timeoutHandle.unref()}}).finally(()=>{if(timeoutHandle!==void 0)clearTimeout(timeoutHandle);outputController.complete()});return{stdout:streamFromNode(proc.stdout,maxBuffer,outputController),stderr:streamFromNode(proc.stderr,maxBuffer,outputController),exited,get exitCode(){return observedSpawnError?null:proc.exitCode},get signalCode(){return observedSignal??proc.signalCode},get spawnError(){return observedSpawnError},kill(signal){killChild(signal).catch(()=>{return})},killTree:killChild}}function syncSpawnCreationFailure(error49){return{stdout:new Uint8Array(0),stderr:new TextEncoder().encode(error49.message),exitCode:SPAWN_CREATION_FAILURE_EXIT_CODE,success:!1}}function bunSpawnSync(cmd,options){let requestedCwd=Array.isArray(cmd)?options?.cwd:options?.cwd??cmd.cwd,executable=(Array.isArray(cmd)?cmd[0]:cmd.cmd[0])??"",bun=getBun();if(bun?.spawnSync){let mergedEnv2=mergeEnvForChild(options?.env,options?.envOverrides),spawnOpts={...options};if(delete spawnOpts.maxBuffer,mergedEnv2!==void 0)spawnOpts.env=mergedEnv2;try{return bun.spawnSync(cmd,spawnOpts)}catch(error49){return syncSpawnCreationFailure(wrapSpawnFailure(error49,requestedCwd,executable))}}let argv,mergedOptions;if(Array.isArray(cmd))argv=cmd,mergedOptions={...options??{}};else if(argv=cmd.cmd,mergedOptions={cwd:cmd.cwd,env:cmd.env,stdin:"pipe",timeout:cmd.timeout,...options??{}},cmd.stdin!==void 0)mergedOptions.stdin=cmd.stdin;let[file2,...args2]=argv,mergedEnv=mergeEnvForChild(mergedOptions.env,options?.envOverrides),result;try{result=nodeSpawnSync(file2,args2,{cwd:mergedOptions.cwd,env:mergedEnv,input:mergedOptions.stdin instanceof Uint8Array||typeof mergedOptions.stdin==="string"?mergedOptions.stdin:void 0,timeout:mergedOptions.timeout,windowsHide:!0})}catch(error49){return syncSpawnCreationFailure(wrapSpawnFailure(error49,mergedOptions.cwd,file2))}if(result.error){let wrapped=wrapSpawnFailure(result.error,mergedOptions.cwd,file2);if(wrapped instanceof SpawnCwdMissingError)return syncSpawnCreationFailure(wrapped)}let stdout=result.stdout instanceof Buffer?new Uint8Array(result.stdout.buffer,result.stdout.byteOffset,result.stdout.byteLength):typeof result.stdout==="string"?new TextEncoder().encode(result.stdout):new Uint8Array(0),stderr=result.stderr instanceof Buffer?new Uint8Array(result.stderr.buffer,result.stderr.byteOffset,result.stderr.byteLength):typeof result.stderr==="string"?new TextEncoder().encode(result.stderr):new Uint8Array(0),exitCode=result.status??(result.signal?128:1);return{stdout,stderr,exitCode,success:exitCode===0&&!result.error}}var WINDOWS_RENAME_MAX_RETRIES=3,WINDOWS_RENAME_RETRY_DELAY_MS=50,tempCounter=0,DEFAULT_BUN_SPAWN_MAX_BUFFER_BYTES=5242880,BunCompatOutputLimitError,_internals9,SpawnCwdMissingError,AMBIGUOUS_SPAWN_CODES,SPAWN_CREATION_FAILURE_EXIT_CODE=1;var init_bun_compat=__esm(()=>{BunCompatOutputLimitError=class BunCompatOutputLimitError extends Error{limit;captured;total;constructor(limit,captured,total){super(`Subprocess output exceeded the ${limit}-byte buffer limit after capturing ${captured} bytes (${total} bytes observed)`);this.name="BunCompatOutputLimitError",this.limit=limit,this.captured=captured,this.total=total}};_internals9={platform:()=>process.platform,cwd:()=>process.cwd(),spawnTaskkill:(args2,options)=>nodeSpawn("taskkill",args2,options),createProcessTreeKiller,statSync:(target)=>fsSync3.statSync(target)};SpawnCwdMissingError=class SpawnCwdMissingError extends Error{name="SpawnCwdMissingError";code="ENOENT";cwd;reason;executable;constructor(cwd,reason,executable,options){super(reason==="missing"?`cannot start "${executable}": working directory no longer exists: ${cwd}`:`cannot start "${executable}": working directory is not a directory: ${cwd}`,options);this.cwd=cwd,this.reason=reason,this.executable=executable}};AMBIGUOUS_SPAWN_CODES=new Set(["ENOENT","ENOTDIR","EACCES","EPERM"])});import*as fs5 from"node:fs";import*as path8 from"node:path";function isFailClosedHandler(value){return typeof value==="function"&&Object.hasOwn(value,"__failClosed")&&value.__failClosed===!0}function safeHook(fn2){return async(input,output)=>{try{await fn2(input,output)}catch(_error){let functionName=fn2.name||"unknown";if(_error instanceof SwarmError)warn(`Hook '${functionName}' failed: ${_error.message}
|
|
179
|
+
GFS4: `),console.error(m)};if(!fs4[gracefulQueue]){if(queue=global[gracefulQueue]||[],publishQueue(fs4,queue),fs4.close=function(fs$close){function close(fd,cb){return fs$close.call(fs4,fd,function(err){if(!err)resetQueue();if(typeof cb==="function")cb.apply(this,arguments)})}return Object.defineProperty(close,previousSymbol,{value:fs$close}),close}(fs4.close),fs4.closeSync=function(fs$closeSync){function closeSync(fd){fs$closeSync.apply(fs4,arguments),resetQueue()}return Object.defineProperty(closeSync,previousSymbol,{value:fs$closeSync}),closeSync}(fs4.closeSync),/\bgfs4\b/i.test(process.env.NODE_DEBUG||""))process.on("exit",function(){debug(fs4[gracefulQueue]),__require("assert").equal(fs4[gracefulQueue].length,0)})}var queue;if(!global[gracefulQueue])publishQueue(global,fs4[gracefulQueue]);module.exports=patch(clone2(fs4));if(process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH&&!fs4.__patched)module.exports=patch(fs4),fs4.__patched=!0;function patch(fs5){polyfills(fs5),fs5.gracefulify=patch,fs5.createReadStream=createReadStream,fs5.createWriteStream=createWriteStream;var fs$readFile=fs5.readFile;fs5.readFile=readFile3;function readFile3(path6,options,cb){if(typeof options==="function")cb=options,options=null;return go$readFile(path6,options,cb);function go$readFile(path7,options2,cb2,startTime){return fs$readFile(path7,options2,function(err){if(err&&(err.code==="EMFILE"||err.code==="ENFILE"))enqueue([go$readFile,[path7,options2,cb2],err,startTime||Date.now(),Date.now()]);else if(typeof cb2==="function")cb2.apply(this,arguments)})}}var fs$writeFile=fs5.writeFile;fs5.writeFile=writeFile2;function writeFile2(path6,data,options,cb){if(typeof options==="function")cb=options,options=null;return go$writeFile(path6,data,options,cb);function go$writeFile(path7,data2,options2,cb2,startTime){return fs$writeFile(path7,data2,options2,function(err){if(err&&(err.code==="EMFILE"||err.code==="ENFILE"))enqueue([go$writeFile,[path7,data2,options2,cb2],err,startTime||Date.now(),Date.now()]);else if(typeof cb2==="function")cb2.apply(this,arguments)})}}var fs$appendFile=fs5.appendFile;if(fs$appendFile)fs5.appendFile=appendFile;function appendFile(path6,data,options,cb){if(typeof options==="function")cb=options,options=null;return go$appendFile(path6,data,options,cb);function go$appendFile(path7,data2,options2,cb2,startTime){return fs$appendFile(path7,data2,options2,function(err){if(err&&(err.code==="EMFILE"||err.code==="ENFILE"))enqueue([go$appendFile,[path7,data2,options2,cb2],err,startTime||Date.now(),Date.now()]);else if(typeof cb2==="function")cb2.apply(this,arguments)})}}var fs$copyFile=fs5.copyFile;if(fs$copyFile)fs5.copyFile=copyFile2;function copyFile2(src,dest,flags,cb){if(typeof flags==="function")cb=flags,flags=0;return go$copyFile(src,dest,flags,cb);function go$copyFile(src2,dest2,flags2,cb2,startTime){return fs$copyFile(src2,dest2,flags2,function(err){if(err&&(err.code==="EMFILE"||err.code==="ENFILE"))enqueue([go$copyFile,[src2,dest2,flags2,cb2],err,startTime||Date.now(),Date.now()]);else if(typeof cb2==="function")cb2.apply(this,arguments)})}}var fs$readdir=fs5.readdir;fs5.readdir=readdir2;var noReaddirOptionVersions=/^v[0-5]\./;function readdir2(path6,options,cb){if(typeof options==="function")cb=options,options=null;var go$readdir=noReaddirOptionVersions.test(process.version)?function(path7,options2,cb2,startTime){return fs$readdir(path7,fs$readdirCallback(path7,options2,cb2,startTime))}:function(path7,options2,cb2,startTime){return fs$readdir(path7,options2,fs$readdirCallback(path7,options2,cb2,startTime))};return go$readdir(path6,options,cb);function fs$readdirCallback(path7,options2,cb2,startTime){return function(err,files){if(err&&(err.code==="EMFILE"||err.code==="ENFILE"))enqueue([go$readdir,[path7,options2,cb2],err,startTime||Date.now(),Date.now()]);else{if(files&&files.sort)files.sort();if(typeof cb2==="function")cb2.call(this,err,files)}}}}if(process.version.substr(0,4)==="v0.8"){var legStreams=legacy(fs5);ReadStream=legStreams.ReadStream,WriteStream=legStreams.WriteStream}var fs$ReadStream=fs5.ReadStream;if(fs$ReadStream)ReadStream.prototype=Object.create(fs$ReadStream.prototype),ReadStream.prototype.open=ReadStream$open;var fs$WriteStream=fs5.WriteStream;if(fs$WriteStream)WriteStream.prototype=Object.create(fs$WriteStream.prototype),WriteStream.prototype.open=WriteStream$open;Object.defineProperty(fs5,"ReadStream",{get:function(){return ReadStream},set:function(val){ReadStream=val},enumerable:!0,configurable:!0}),Object.defineProperty(fs5,"WriteStream",{get:function(){return WriteStream},set:function(val){WriteStream=val},enumerable:!0,configurable:!0});var FileReadStream=ReadStream;Object.defineProperty(fs5,"FileReadStream",{get:function(){return FileReadStream},set:function(val){FileReadStream=val},enumerable:!0,configurable:!0});var FileWriteStream=WriteStream;Object.defineProperty(fs5,"FileWriteStream",{get:function(){return FileWriteStream},set:function(val){FileWriteStream=val},enumerable:!0,configurable:!0});function ReadStream(path6,options){if(this instanceof ReadStream)return fs$ReadStream.apply(this,arguments),this;else return ReadStream.apply(Object.create(ReadStream.prototype),arguments)}function ReadStream$open(){var that=this;open(that.path,that.flags,that.mode,function(err,fd){if(err){if(that.autoClose)that.destroy();that.emit("error",err)}else that.fd=fd,that.emit("open",fd),that.read()})}function WriteStream(path6,options){if(this instanceof WriteStream)return fs$WriteStream.apply(this,arguments),this;else return WriteStream.apply(Object.create(WriteStream.prototype),arguments)}function WriteStream$open(){var that=this;open(that.path,that.flags,that.mode,function(err,fd){if(err)that.destroy(),that.emit("error",err);else that.fd=fd,that.emit("open",fd)})}function createReadStream(path6,options){return new fs5.ReadStream(path6,options)}function createWriteStream(path6,options){return new fs5.WriteStream(path6,options)}var fs$open=fs5.open;fs5.open=open;function open(path6,flags,mode,cb){if(typeof mode==="function")cb=mode,mode=null;return go$open(path6,flags,mode,cb);function go$open(path7,flags2,mode2,cb2,startTime){return fs$open(path7,flags2,mode2,function(err,fd){if(err&&(err.code==="EMFILE"||err.code==="ENFILE"))enqueue([go$open,[path7,flags2,mode2,cb2],err,startTime||Date.now(),Date.now()]);else if(typeof cb2==="function")cb2.apply(this,arguments)})}}return fs5}function enqueue(elem){debug("ENQUEUE",elem[0].name,elem[1]),fs4[gracefulQueue].push(elem),retry()}var retryTimer;function resetQueue(){var now=Date.now();for(var i=0;i<fs4[gracefulQueue].length;++i)if(fs4[gracefulQueue][i].length>2)fs4[gracefulQueue][i][3]=now,fs4[gracefulQueue][i][4]=now;retry()}function retry(){if(clearTimeout(retryTimer),retryTimer=void 0,fs4[gracefulQueue].length===0)return;var elem=fs4[gracefulQueue].shift(),fn2=elem[0],args2=elem[1],err=elem[2],startTime=elem[3],lastTime=elem[4];if(startTime===void 0)debug("RETRY",fn2.name,args2),fn2.apply(null,args2);else if(Date.now()-startTime>=60000){debug("TIMEOUT",fn2.name,args2);var cb=args2.pop();if(typeof cb==="function")cb.call(null,err)}else{var sinceAttempt=Date.now()-lastTime,sinceStart=Math.max(lastTime-startTime,1),desiredDelay=Math.min(sinceStart*1.2,100);if(sinceAttempt>=desiredDelay)debug("RETRY",fn2.name,args2),fn2.apply(null,args2.concat([startTime]));else fs4[gracefulQueue].push(elem)}if(retryTimer===void 0)retryTimer=setTimeout(retry,0)}});var require_retry_operation=__commonJS((exports,module)=>{function RetryOperation(timeouts,options){if(typeof options==="boolean")options={forever:options};if(this._originalTimeouts=JSON.parse(JSON.stringify(timeouts)),this._timeouts=timeouts,this._options=options||{},this._maxRetryTime=options&&options.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._options.forever)this._cachedTimeouts=this._timeouts.slice(0)}module.exports=RetryOperation;RetryOperation.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts};RetryOperation.prototype.stop=function(){if(this._timeout)clearTimeout(this._timeout);this._timeouts=[],this._cachedTimeouts=null};RetryOperation.prototype.retry=function(err){if(this._timeout)clearTimeout(this._timeout);if(!err)return!1;var currentTime=new Date().getTime();if(err&¤tTime-this._operationStart>=this._maxRetryTime)return this._errors.unshift(Error("RetryOperation timeout occurred")),!1;this._errors.push(err);var timeout=this._timeouts.shift();if(timeout===void 0)if(this._cachedTimeouts)this._errors.splice(this._errors.length-1,this._errors.length),this._timeouts=this._cachedTimeouts.slice(0),timeout=this._timeouts.shift();else return!1;var self=this,timer=setTimeout(function(){if(self._attempts++,self._operationTimeoutCb){if(self._timeout=setTimeout(function(){self._operationTimeoutCb(self._attempts)},self._operationTimeout),self._options.unref)self._timeout.unref()}self._fn(self._attempts)},timeout);if(this._options.unref)timer.unref();return!0};RetryOperation.prototype.attempt=function(fn2,timeoutOps){if(this._fn=fn2,timeoutOps){if(timeoutOps.timeout)this._operationTimeout=timeoutOps.timeout;if(timeoutOps.cb)this._operationTimeoutCb=timeoutOps.cb}var self=this;if(this._operationTimeoutCb)this._timeout=setTimeout(function(){self._operationTimeoutCb()},self._operationTimeout);this._operationStart=new Date().getTime(),this._fn(this._attempts)};RetryOperation.prototype.try=function(fn2){console.log("Using RetryOperation.try() is deprecated"),this.attempt(fn2)};RetryOperation.prototype.start=function(fn2){console.log("Using RetryOperation.start() is deprecated"),this.attempt(fn2)};RetryOperation.prototype.start=RetryOperation.prototype.try;RetryOperation.prototype.errors=function(){return this._errors};RetryOperation.prototype.attempts=function(){return this._attempts};RetryOperation.prototype.mainError=function(){if(this._errors.length===0)return null;var counts={},mainError=null,mainErrorCount=0;for(var i=0;i<this._errors.length;i++){var error49=this._errors[i],message=error49.message,count=(counts[message]||0)+1;if(counts[message]=count,count>=mainErrorCount)mainError=error49,mainErrorCount=count}return mainError}});var require_retry=__commonJS((exports)=>{var RetryOperation=require_retry_operation();exports.operation=function(options){var timeouts=exports.timeouts(options);return new RetryOperation(timeouts,{forever:options&&options.forever,unref:options&&options.unref,maxRetryTime:options&&options.maxRetryTime})};exports.timeouts=function(options){if(options instanceof Array)return[].concat(options);var opts={retries:10,factor:2,minTimeout:1000,maxTimeout:1/0,randomize:!1};for(var key in options)opts[key]=options[key];if(opts.minTimeout>opts.maxTimeout)throw Error("minTimeout is greater than maxTimeout");var timeouts=[];for(var i=0;i<opts.retries;i++)timeouts.push(this.createTimeout(i,opts));if(options&&options.forever&&!timeouts.length)timeouts.push(this.createTimeout(i,opts));return timeouts.sort(function(a,b){return a-b}),timeouts};exports.createTimeout=function(attempt,opts){var random=opts.randomize?Math.random()+1:1,timeout=Math.round(random*opts.minTimeout*Math.pow(opts.factor,attempt));return timeout=Math.min(timeout,opts.maxTimeout),timeout};exports.wrap=function(obj,options,methods){if(options instanceof Array)methods=options,options=null;if(!methods){methods=[];for(var key in obj)if(typeof obj[key]==="function")methods.push(key)}for(var i=0;i<methods.length;i++){var method=methods[i],original=obj[method];obj[method]=function(original2){var op=exports.operation(options),args2=Array.prototype.slice.call(arguments,1),callback=args2.pop();args2.push(function(err){if(op.retry(err))return;if(err)arguments[0]=op.mainError();callback.apply(this,arguments)}),op.attempt(function(){original2.apply(obj,args2)})}.bind(obj,original),obj[method].options=options}}});var require_signals=__commonJS((exports,module)=>{module.exports=["SIGABRT","SIGALRM","SIGHUP","SIGINT","SIGTERM"];if(process.platform!=="win32")module.exports.push("SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");if(process.platform==="linux")module.exports.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT","SIGUNUSED")});var require_signal_exit=__commonJS((exports,module)=>{var process3=global.process,processOk=function(process4){return process4&&typeof process4==="object"&&typeof process4.removeListener==="function"&&typeof process4.emit==="function"&&typeof process4.reallyExit==="function"&&typeof process4.listeners==="function"&&typeof process4.kill==="function"&&typeof process4.pid==="number"&&typeof process4.on==="function"};if(!processOk(process3))module.exports=function(){return function(){}};else{if(assert2=__require("assert"),signals=require_signals(),isWin=/^win/i.test(process3.platform),EE=__require("events"),typeof EE!=="function")EE=EE.EventEmitter;if(process3.__signal_exit_emitter__)emitter=process3.__signal_exit_emitter__;else emitter=process3.__signal_exit_emitter__=new EE,emitter.count=0,emitter.emitted={};if(!emitter.infinite)emitter.setMaxListeners(1/0),emitter.infinite=!0;module.exports=function(cb,opts){if(!processOk(global.process))return function(){};if(assert2.equal(typeof cb,"function","a callback must be provided for exit handler"),loaded===!1)load();var ev="exit";if(opts&&opts.alwaysLast)ev="afterexit";var remove=function(){if(emitter.removeListener(ev,cb),emitter.listeners("exit").length===0&&emitter.listeners("afterexit").length===0)unload()};return emitter.on(ev,cb),remove},unload=function(){if(!loaded||!processOk(global.process))return;loaded=!1,signals.forEach(function(sig){try{process3.removeListener(sig,sigListeners[sig])}catch(er){}}),process3.emit=originalProcessEmit,process3.reallyExit=originalProcessReallyExit,emitter.count-=1},module.exports.unload=unload,emit=function(event,code,signal){if(emitter.emitted[event])return;emitter.emitted[event]=!0,emitter.emit(event,code,signal)},sigListeners={},signals.forEach(function(sig){sigListeners[sig]=function(){if(!processOk(global.process))return;var listeners=process3.listeners(sig);if(listeners.length===emitter.count){if(unload(),emit("exit",null,sig),emit("afterexit",null,sig),isWin&&sig==="SIGHUP")sig="SIGINT";process3.kill(process3.pid,sig)}}}),module.exports.signals=function(){return signals},loaded=!1,load=function(){if(loaded||!processOk(global.process))return;loaded=!0,emitter.count+=1,signals=signals.filter(function(sig){try{return process3.on(sig,sigListeners[sig]),!0}catch(er){return!1}}),process3.emit=processEmit,process3.reallyExit=processReallyExit},module.exports.load=load,originalProcessReallyExit=process3.reallyExit,processReallyExit=function(code){if(!processOk(global.process))return;process3.exitCode=code||0,emit("exit",process3.exitCode,null),emit("afterexit",process3.exitCode,null),originalProcessReallyExit.call(process3,process3.exitCode)},originalProcessEmit=process3.emit,processEmit=function(ev,arg){if(ev==="exit"&&processOk(global.process)){if(arg!==void 0)process3.exitCode=arg;var ret=originalProcessEmit.apply(this,arguments);return emit("exit",process3.exitCode,null),emit("afterexit",process3.exitCode,null),ret}else return originalProcessEmit.apply(this,arguments)}}var assert2,signals,isWin,EE,emitter,unload,emit,sigListeners,loaded,load,originalProcessReallyExit,processReallyExit,originalProcessEmit,processEmit});var require_mtime_precision=__commonJS((exports,module)=>{var cacheSymbol=Symbol();function probe(file2,fs4,callback){let cachedPrecision=fs4[cacheSymbol];if(cachedPrecision)return fs4.stat(file2,(err,stat4)=>{if(err)return callback(err);callback(null,stat4.mtime,cachedPrecision)});let mtime=new Date(Math.ceil(Date.now()/1000)*1000+5);fs4.utimes(file2,mtime,mtime,(err)=>{if(err)return callback(err);fs4.stat(file2,(err2,stat4)=>{if(err2)return callback(err2);let precision=stat4.mtime.getTime()%1000===0?"s":"ms";Object.defineProperty(fs4,cacheSymbol,{value:precision}),callback(null,stat4.mtime,precision)})})}function getMtime(precision){let now=Date.now();if(precision==="s")now=Math.ceil(now/1000)*1000;return new Date(now)}exports.probe=probe;exports.getMtime=getMtime});var require_lockfile=__commonJS((exports,module)=>{var path6=__require("path"),fs4=require_graceful_fs(),retry=require_retry(),onExit=require_signal_exit(),mtimePrecision=require_mtime_precision(),locks={};function getLockFile(file2,options){return options.lockfilePath||`${file2}.lock`}function resolveCanonicalPath(file2,options,callback){if(!options.realpath)return callback(null,path6.resolve(file2));options.fs.realpath(file2,callback)}function acquireLock(file2,options,callback){let lockfilePath=getLockFile(file2,options);options.fs.mkdir(lockfilePath,(err)=>{if(!err)return mtimePrecision.probe(lockfilePath,options.fs,(err2,mtime,mtimePrecision2)=>{if(err2)return options.fs.rmdir(lockfilePath,()=>{}),callback(err2);callback(null,mtime,mtimePrecision2)});if(err.code!=="EEXIST")return callback(err);if(options.stale<=0)return callback(Object.assign(Error("Lock file is already being held"),{code:"ELOCKED",file:file2}));options.fs.stat(lockfilePath,(err2,stat4)=>{if(err2){if(err2.code==="ENOENT")return acquireLock(file2,{...options,stale:0},callback);return callback(err2)}if(!isLockStale(stat4,options))return callback(Object.assign(Error("Lock file is already being held"),{code:"ELOCKED",file:file2}));removeLock(file2,options,(err3)=>{if(err3)return callback(err3);acquireLock(file2,{...options,stale:0},callback)})})})}function isLockStale(stat4,options){return stat4.mtime.getTime()<Date.now()-options.stale}function removeLock(file2,options,callback){options.fs.rmdir(getLockFile(file2,options),(err)=>{if(err&&err.code!=="ENOENT")return callback(err);callback()})}function updateLock(file2,options){let lock2=locks[file2];if(lock2.updateTimeout)return;if(lock2.updateDelay=lock2.updateDelay||options.update,lock2.updateTimeout=setTimeout(()=>{lock2.updateTimeout=null,options.fs.stat(lock2.lockfilePath,(err,stat4)=>{let isOverThreshold=lock2.lastUpdate+options.stale<Date.now();if(err){if(err.code==="ENOENT"||isOverThreshold)return setLockAsCompromised(file2,lock2,Object.assign(err,{code:"ECOMPROMISED"}));return lock2.updateDelay=1000,updateLock(file2,options)}if(lock2.mtime.getTime()!==stat4.mtime.getTime())return setLockAsCompromised(file2,lock2,Object.assign(Error("Unable to update lock within the stale threshold"),{code:"ECOMPROMISED"}));let mtime=mtimePrecision.getMtime(lock2.mtimePrecision);options.fs.utimes(lock2.lockfilePath,mtime,mtime,(err2)=>{let isOverThreshold2=lock2.lastUpdate+options.stale<Date.now();if(lock2.released)return;if(err2){if(err2.code==="ENOENT"||isOverThreshold2)return setLockAsCompromised(file2,lock2,Object.assign(err2,{code:"ECOMPROMISED"}));return lock2.updateDelay=1000,updateLock(file2,options)}lock2.mtime=mtime,lock2.lastUpdate=Date.now(),lock2.updateDelay=null,updateLock(file2,options)})})},lock2.updateDelay),lock2.updateTimeout.unref)lock2.updateTimeout.unref()}function setLockAsCompromised(file2,lock2,err){if(lock2.released=!0,lock2.updateTimeout)clearTimeout(lock2.updateTimeout);if(locks[file2]===lock2)delete locks[file2];lock2.options.onCompromised(err)}function lock(file2,options,callback){options={stale:1e4,update:null,realpath:!0,retries:0,fs:fs4,onCompromised:(err)=>{throw err},...options},options.retries=options.retries||0,options.retries=typeof options.retries==="number"?{retries:options.retries}:options.retries,options.stale=Math.max(options.stale||0,2000),options.update=options.update==null?options.stale/2:options.update||0,options.update=Math.max(Math.min(options.update,options.stale/2),1000),resolveCanonicalPath(file2,options,(err,file3)=>{if(err)return callback(err);let operation=retry.operation(options.retries);operation.attempt(()=>{acquireLock(file3,options,(err2,mtime,mtimePrecision2)=>{if(operation.retry(err2))return;if(err2)return callback(operation.mainError());let lock2=locks[file3]={lockfilePath:getLockFile(file3,options),mtime,mtimePrecision:mtimePrecision2,options,lastUpdate:Date.now()};updateLock(file3,options),callback(null,(releasedCallback)=>{if(lock2.released)return releasedCallback&&releasedCallback(Object.assign(Error("Lock is already released"),{code:"ERELEASED"}));unlock(file3,{...options,realpath:!1},releasedCallback)})})})})}function unlock(file2,options,callback){options={fs:fs4,realpath:!0,...options},resolveCanonicalPath(file2,options,(err,file3)=>{if(err)return callback(err);let lock2=locks[file3];if(!lock2)return callback(Object.assign(Error("Lock is not acquired/owned by you"),{code:"ENOTACQUIRED"}));lock2.updateTimeout&&clearTimeout(lock2.updateTimeout),lock2.released=!0,delete locks[file3],removeLock(file3,options,callback)})}function check2(file2,options,callback){options={stale:1e4,realpath:!0,fs:fs4,...options},options.stale=Math.max(options.stale||0,2000),resolveCanonicalPath(file2,options,(err,file3)=>{if(err)return callback(err);options.fs.stat(getLockFile(file3,options),(err2,stat4)=>{if(err2)return err2.code==="ENOENT"?callback(null,!1):callback(err2);return callback(null,!isLockStale(stat4,options))})})}function getLocks(){return locks}onExit(()=>{for(let file2 in locks){let options=locks[file2].options;try{options.fs.rmdirSync(getLockFile(file2,options))}catch(e){}}});exports.lock=lock;exports.unlock=unlock;exports.check=check2;exports.getLocks=getLocks});var require_adapter=__commonJS((exports,module)=>{var fs4=require_graceful_fs();function createSyncFs(fs5){let methods=["mkdir","realpath","stat","rmdir","utimes"],newFs={...fs5};return methods.forEach((method)=>{newFs[method]=(...args2)=>{let callback=args2.pop(),ret;try{ret=fs5[`${method}Sync`](...args2)}catch(err){return callback(err)}callback(null,ret)}}),newFs}function toPromise(method){return(...args2)=>new Promise((resolve4,reject)=>{args2.push((err,result)=>{if(err)reject(err);else resolve4(result)}),method(...args2)})}function toSync(method){return(...args2)=>{let err,result;if(args2.push((_err,_result)=>{err=_err,result=_result}),method(...args2),err)throw err;return result}}function toSyncOptions(options){if(options={...options},options.fs=createSyncFs(options.fs||fs4),typeof options.retries==="number"&&options.retries>0||options.retries&&typeof options.retries.retries==="number"&&options.retries.retries>0)throw Object.assign(Error("Cannot use retries with the sync api"),{code:"ESYNC"});return options}module.exports={toPromise,toSync,toSyncOptions}});var require_proper_lockfile=__commonJS((exports,module)=>{var lockfile=require_lockfile(),{toPromise,toSync,toSyncOptions}=require_adapter();async function lock(file2,options){let release=await toPromise(lockfile.lock)(file2,options);return toPromise(release)}function lockSync(file2,options){let release=toSync(lockfile.lock)(file2,toSyncOptions(options));return toSync(release)}function unlock(file2,options){return toPromise(lockfile.unlock)(file2,options)}function unlockSync(file2,options){return toSync(lockfile.unlock)(file2,toSyncOptions(options))}function check2(file2,options){return toPromise(lockfile.check)(file2,options)}function checkSync(file2,options){return toSync(lockfile.check)(file2,toSyncOptions(options))}module.exports=lock;module.exports.lock=lock;module.exports.unlock=unlock;module.exports.lockSync=lockSync;module.exports.unlockSync=unlockSync;module.exports.check=check2;module.exports.checkSync=checkSync});var SwarmError;var init_errors3=__esm(()=>{SwarmError=class SwarmError extends Error{code;guidance;constructor(message,code,guidance){super(message);this.name="SwarmError",this.code=code,this.guidance=guidance}}});function escapeRegex2(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function simpleGlobToRegex(pattern,flags="i"){let escaped=pattern.split("*").map((starSegment)=>starSegment.split("?").map(escapeRegex2).join(".")).join(".*");return new RegExp(`^${escaped}$`,flags)}var init_utils=__esm(()=>{init_errors3();init_logger();init_merge()});import{randomBytes}from"node:crypto";import*as fs4 from"node:fs";import*as path6 from"node:path";function matchTempGrammar(basename2){return SWARM_TEMP_GRAMMARS.find((g)=>g.match.test(basename2))}function parseTargetBasename(basename2){for(let g of SWARM_TEMP_GRAMMARS){if(!g.parsesTarget)continue;let m=g.match.exec(basename2);if(m?.[1])return m[1]}return null}function assertWellFormedTargetPath(targetPath){if(!path6.isAbsolute(targetPath))throw Error(`atomic-write target must be absolute: ${targetPath}`);if(/[\0-\x1f\x7f]/.test(targetPath))throw Error("atomic-write target contains control characters");if(/[*?]/.test(targetPath)||/(^|[/\\])\{[^}]*\}([/\\]|$)/.test(targetPath))throw Error(`atomic-write target contains glob metacharacters: ${targetPath}`);if(/(^|[/\\])~([/\\]|$)/.test(targetPath))throw Error("atomic-write target contains unresolved home-dir marker (~)");if(/\$\{?[A-Za-z_][A-Za-z0-9_]*\}?/.test(targetPath)||/%[^/\\%]+%/.test(targetPath))throw Error("atomic-write target contains unresolved environment-variable form")}function lstatNotSymlink(p,what){if(fs4.lstatSync(p).isSymbolicLink())throw Error(`${what} is a symlink/reparse point: ${p}`)}function assertSwarmContainedTarget(targetPath){assertWellFormedTargetPath(targetPath);let resolved=path6.normalize(path6.resolve(targetPath)),segments=resolved.split(path6.sep),swarmIdx=-1;for(let i=segments.length-2;i>=1;i--)if(segments[i]===".swarm"){swarmIdx=i;break}if(swarmIdx===-1)throw Error(`atomic-write target is not under a project .swarm root: ${targetPath}`);let swarmRoot=segments.slice(0,swarmIdx+1).join(path6.sep);try{let st=fs4.lstatSync(swarmRoot);if(!st.isDirectory()||st.isSymbolicLink())throw Error(`.swarm root is not a real directory (symlink/reparse or non-dir): ${swarmRoot}`)}catch(err){if(err?.code!=="ENOENT")throw err}let rel=path6.relative(swarmRoot,resolved);if(!rel||rel.startsWith("..")||path6.isAbsolute(rel))throw Error(`atomic-write target escapes .swarm root: ${targetPath}`);let probe=swarmRoot;for(let seg of rel.split(path6.sep)){if(probe=path6.join(probe,seg),!fs4.existsSync(probe))break;lstatNotSymlink(probe,"path segment under .swarm")}return{projectRoot:path6.dirname(swarmRoot),swarmRoot}}function noteRecentWriteActivity(resolvedTarget){recentWriteActivity.delete(resolvedTarget),recentWriteActivity.set(resolvedTarget,Date.now());while(recentWriteActivity.size>MAX_RECENT_WRITE_TRACKED_PATHS){let oldest=recentWriteActivity.keys().next().value;if(oldest===void 0)break;recentWriteActivity.delete(oldest)}}function clearRecentWriteActivity(targetPath){return recentWriteActivity.delete(path6.resolve(targetPath))}function wasRecentlyWrittenByThisProcess(targetPath,withinMs=RECENT_WRITE_WINDOW_MS){let last=recentWriteActivity.get(path6.resolve(targetPath));if(last===void 0)return!1;return Date.now()-last<=withinMs}function toBuffer(content){if(typeof content==="string")return Buffer.from(content,"utf-8");return content}function syncSleep(ms){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,ms)}catch{let start=Date.now();while(Date.now()-start<ms);}}function renameWithRetry(tempPath,targetPath){let lastError;for(let attempt=0;attempt<=RENAME_RETRY_DELAYS_MS.length;attempt++)try{_internals8.renameSync(tempPath,targetPath);return}catch(err){lastError=err;let code=err?.code;if(!code||!RETRYABLE_RENAME_CODES.has(code))throw err;if(attempt<RENAME_RETRY_DELAYS_MS.length)syncSleep(RENAME_RETRY_DELAYS_MS[attempt])}throw lastError}function writeAtomicSync(targetPath,content,options){if(options?.contained!==!1)assertSwarmContainedTarget(targetPath);else assertWellFormedTargetPath(targetPath);let resolvedTarget=path6.resolve(targetPath);noteRecentWriteActivity(resolvedTarget);let buffer=toBuffer(content),maxBytes=options?.maxBytes??MAX_ATOMIC_WRITE_BYTES;if(buffer.byteLength>maxBytes)throw Error(`atomic write exceeds ${maxBytes} byte bound: ${buffer.byteLength}`);let tempPath=`${resolvedTarget}.${_internals8.randomSuffix()}.tmp`;fs4.mkdirSync(path6.dirname(tempPath),{recursive:!0});try{try{let fd=fs4.openSync(tempPath,"wx",options?.mode);try{let written=0;while(written<buffer.byteLength)written+=_internals8.writeSync(fd,buffer,written,buffer.byteLength-written);if(options?.skipFsync!==!0)try{_internals8.fsyncSync(fd)}catch{}}finally{fs4.closeSync(fd)}renameWithRetry(tempPath,resolvedTarget)}finally{try{_internals8.unlinkSync(tempPath)}catch{}}}catch(error49){throw clearRecentWriteActivity(resolvedTarget),error49}try{let dirFd=fs4.openSync(path6.dirname(resolvedTarget),"r");try{fs4.fsyncSync(dirFd)}finally{fs4.closeSync(dirFd)}}catch{}invalidateCachedArtifact(resolvedTarget),noteRecentWriteActivity(resolvedTarget)}async function atomicWriteSwarmFile(targetPath,content,options){await new Promise((resolve5)=>setImmediate(resolve5)),writeAtomicSync(targetPath,content,options)}function atomicWriteSwarmFileSync(targetPath,content,options){writeAtomicSync(targetPath,content,options)}async function atomicWriteFileAnyRoot(targetPath,content,options){await new Promise((resolve5)=>setImmediate(resolve5)),writeAtomicSync(targetPath,content,{...options,contained:!1})}var UUID_RE="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",SWARM_TEMP_GRAMMARS,WRITER_CLASSIFICATION,MAX_ATOMIC_WRITE_BYTES=268435456,RENAME_RETRY_DELAYS_MS,RETRYABLE_RENAME_CODES,MAX_RECENT_WRITE_TRACKED_PATHS=256,RECENT_WRITE_WINDOW_MS=500,recentWriteActivity,_internals8;var init_atomic_write=__esm(()=>{init_swarm_artifact_cache();SWARM_TEMP_GRAMMARS=[{id:"canonical-v1",era:"canonical",match:/^(.+)\.[0-9a-f]{32}\.tmp$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/utils/atomic-write.ts:atomicWriteSwarmFile","src/utils/atomic-write.ts:atomicWriteFileAnyRoot"]},{id:"target-suffix-tmp-uuid",era:"current",match:new RegExp(`^(.+)\\.tmp\\.${UUID_RE}$`),token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/commands/handoff.ts (pre-#2035; site=handoff.md; migrated-to=src/commands/handoff.ts:handleHandoffCommand)","src/commands/handoff.ts (pre-#2035; site=handoff-prompt.md; migrated-to=src/commands/handoff.ts:handleHandoffCommand)","src/memory/local-jsonl-provider.ts:1288","src/config/bundled-skills.ts:259"]},{id:"target-suffix-tmp-pid-uuid",era:"current",match:new RegExp(`^(.+)\\.tmp\\.\\d+\\.${UUID_RE}$`),token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/hooks/pr-workflow-gate.ts (pre-#2385; migrated-to=src/pr-review/persistence.ts:writeAtomicJson)"],note:"pre/post-rename file-identity verification (assertOpened/ClosedSwarmFileIdentity, pr-workflow-gate.ts:17880-17980) is writer-specific and load-bearing"},{id:"target-suffix-tmp-num-num-json",era:"current",match:/^(.+)\.tmp\.\d+\.\d+\.json$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/hooks/issue-trace-state.ts:447"],note:"the .json terminator keeps this shape distinct from the bare two-token family — declared before it so first-match wins"},{id:"target-suffix-tmp-num-alnum",era:"current",match:/^(.+)\.tmp\.\d+\.[0-9a-z]+$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/evidence/task-file.ts (pre-#2035; migrated-to=src/evidence/task-file.ts:atomicWriteFile)","src/scope/scope-persistence.ts (pre-#2035; migrated-to=src/scope/scope-persistence.ts:atomicWrite)","src/scope/scope-persistence.ts (pre-#2035; migrated-to=src/scope/scope-persistence.ts:atomicWriteSync)","src/plan/manager.ts:683","src/plan/manager.ts:2110","src/plan/manager.ts:2170","src/review/evidence.ts:175","src/turbo/lean/evidence.ts:182","src/summaries/manager.ts:163","src/evidence/manager.ts:288","src/evidence/manager.ts:456","src/tools/sast-baseline.ts:199","src/tools/repo-graph/storage.ts:543","src/memory/reflection-service.ts (pre-#2035; migrated-to=src/memory/reflection-service.ts:atomicWrite)","src/hooks/review-receipt.ts:609","src/hooks/review-receipt.ts:675","src/hooks/review-receipt.ts:894","src/knowledge/identity.ts:234","src/evidence/phase-participation.ts (pre-#2035; migrated-to=src/evidence/phase-participation.ts:atomicWriteBytes)","src/turbo/lean/integration.ts:428","src/turbo/lean/reviewer.ts:403","src/plan/ledger.ts:1471","src/services/synonym-map.ts:389","src/services/skill-optimizer/store.ts:340","src/services/skill-optimizer/store.ts:503","src/turbo/epic/calibration.ts:234","src/commands/archive-sqlite.ts:318","src/memory/jsonl-migration.ts:161"],note:"fsync-discipline / lock-scoped fd writers whose temp naming is pinned by their own durability test suites (plan-durability invariant 5, #2034 crash matrix); grammars registered here so their residue stays discoverable"},{id:"target-suffix-tmp-token",era:"current",match:/^(.+)\.tmp\.[0-9a-z-]{6,}$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/turbo/lean/state.ts:129","src/turbo/lean/recovery.ts:175","src/hooks/delegation-gate/worktree-merge-status.ts:110","src/plan/ledger.ts:606"]},{id:"target-suffix-tmp-dash",era:"current",match:/^(.+)\.tmp-\d+-[0-9a-z-]+$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/services/skill-evaluator.ts (pre-#2035; migrated-to=src/services/skill-evaluator.ts:atomicWrite)","src/services/skill-improver.ts (pre-#2035; migrated-to=src/services/skill-improver.ts:atomicWrite)","src/services/skill-consolidation.ts (pre-#2035; migrated-to=src/services/skill-consolidation.ts:atomicWrite)","src/services/skill-generator.ts (pre-#2035; migrated-to=src/services/skill-generator.ts:atomicWrite)","src/tools/spec-write.ts:98","src/sdd/effective-spec.ts:1377","src/background/lane-output-store.ts:353","src/background/pending-delegations.ts:1501","src/background/delegation-health.ts:391","src/tools/submit-phase-council-verdicts.ts:458","src/summaries/store.ts (pre-#2035; migrated-to=src/summaries/store.ts:writeRawSidecar)","src/retention/jsonl-cap.ts:213","src/services/skill-changelog.ts:58","src/turbo/epic/divergence-recorder.ts:108"],note:"background lane/delegation stores keep bounded-retry rename semantics wired into their callers (#2034/#2276 delivery contracts); migration candidates for a follow-up but grammars registered"},{id:"target-suffix-tmp-dash-num",era:"current",match:/^(.+)\.tmp-\d+$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/services/skill-improver-quota.ts:114"]},{id:"target-dot-pid-uuid-tmp",era:"current",match:new RegExp(`^(.+)\\.\\d+\\.${UUID_RE}\\.tmp$`),token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/hooks/knowledge-receipt-ledger-storage.ts:591"],note:"pre/post-rename file-identity verification (existingFileIdentity checks, knowledge-receipt-ledger-storage.ts:544-591) is writer-specific and load-bearing"},{id:"dot-numeric-instance-tmp",era:"current",match:/^\..+(?:\.\d+){2,4}\.[0-9a-z]+\.tmp$/,token:"instance",quarantineEligible:!0,parsesTarget:!1,producers:["src/utils/bun-compat.ts:138","src/tools/repo-graph/freshness.ts:171"],note:"bunWrite Node-fallback internal temp and the repo-graph fingerprint temp (2-4 numeric token groups); leading-dot temps are standalone, target not parsed"},{id:"dot-uuid-instance-tmp",era:"current",match:new RegExp(`^\\..+\\.${UUID_RE}\\.tmp$`),token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/tools/write-pr-review-artifact.ts:154","src/tools/write-pr-review-artifact.ts:174","src/tools/write-pr-review-trigger-eval.ts:96"],note:"bundled-skills writes outside .swarm (project skill roots) and keeps its own contained-directory logic (invariant 4 bundled-skill ownership)"},{id:"tmp-prefix-named",era:"legacy",match:/^\.tmp-.+-\d+-\d+$/,token:"instance",quarantineEligible:!0,parsesTarget:!1,producers:["src/commands/issue.ts (pre-#2035; migrated-to=src/commands/issue.ts:atomicWriteFileSync)"],note:"prefix form embeds the filename; target not reliably parseable (dashes), so eligibility relies on the age/tracked/symlink/lock gates"},{id:"target-rebuild-close",era:"current",match:/^(.+)\.(?:rebuild|close)\.\d+\.[0-9a-z]+$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/plan/manager.ts:2369","src/plan/manager.ts:2431"],note:"plan-durability (invariant 5) fd-write paths; grammars registered, writers unchanged in this PR"},{id:"target-migration-pid",era:"current",match:/^(.+)\.migration-\d+$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/scope/scope-persistence.ts (pre-#2035; migrated-to=src/scope/scope-persistence.ts:atomicWriteSync)"]},{id:"dot-tmp-prefix-legacy",era:"legacy",match:/^\.tmp\..+$/,token:"constant",quarantineEligible:!0,parsesTarget:!1,producers:["pre-7.x writers (pre-#2035; scanner=src/services/swarm-residue.ts:collectCandidates)"],note:"legacy prefix grammar: issue #2035 req 7 preserves its handling — stale instances are quarantined (formerly unlinked) under the same eligibility gates"},{id:"dot-constant-tmp",era:"current",match:/^\..+\.tmp$/,token:"constant",quarantineEligible:!1,parsesTarget:!1,producers:["src/tools/write-drift-evidence.ts:275","src/tools/write-mutation-evidence.ts:169","src/tools/write-hallucination-evidence.ts:121","src/tools/write-final-council-evidence.ts:403"],note:"constant-name temps: no per-invocation token — reported when stale, never auto-quarantined (may be an in-flight writer of any process)"},{id:"target-constant-tmp",era:"current",match:/^(.+)\.tmp$/,token:"constant",quarantineEligible:!1,parsesTarget:!1,producers:["src/tools/checkpoint.ts:195","src/full-auto/state.ts:636","src/context-map/persistence.ts:119","src/context-map/capsule-persistence.ts:111","src/test-impact/history-store.ts:297","src/test-impact/history-store.ts:302","src/test-impact/history-store.ts:429","src/test-impact/history-store.ts:435","src/hooks/promotion-evidence-store.ts:112","src/hooks/skill-usage-log.ts:1165","src/hooks/skill-usage-log.ts:1675","src/hooks/skill-usage-pending.ts:817","src/parallel/file-locks.ts:113","src/plan/ledger.ts:607","src/plan/ledger.ts:1793"],note:"constant-name temps: reported when stale, never auto-quarantined. file-locks meta sidecars live under the scanner-skipped .swarm/locks/ subtree; the ledger reconcile temp embeds instance tokens but its .tmp-suffix shape maps here (conservatively report-only)"}];WRITER_CLASSIFICATION=Object.freeze({"src/commands/close.ts":"migrated","src/commands/close/context.ts":"reader-only","src/commands/close/clean-stage.ts":"reader-only","src/commands/handoff.ts":"migrated","src/commands/simulate.ts":"migrated","src/commands/coupling.ts":"migrated","src/commands/issue.ts":"migrated","src/evidence/task-file.ts":"migrated","src/evidence/phase-participation.ts":"migrated","src/memory/reflection-service.ts":"migrated","src/scope/scope-persistence.ts":"migrated","src/services/skill-consolidation.ts":"migrated","src/services/skill-evaluator.ts":"migrated","src/services/skill-generator.ts":"migrated","src/services/skill-improver.ts":"migrated","src/summaries/store.ts":"migrated","src/prm/trajectory-store.ts":"migrated","src/observability/otlp-exporter.ts":"registered-bespoke","src/retention/jsonl-cap.ts":"registered-bespoke","src/services/skill-changelog.ts":"registered-bespoke","src/turbo/epic/divergence-recorder.ts":"registered-bespoke","src/background/delegation-health.ts":"registered-bespoke","src/background/lane-output-store.ts":"registered-bespoke","src/background/pending-delegations.ts":"registered-bespoke","src/commands/archive-sqlite.ts":"registered-bespoke","src/context-map/capsule-persistence.ts":"registered-bespoke","src/context-map/persistence.ts":"registered-bespoke","src/context-map/telemetry.ts":"registered-bespoke","src/events/core-events.ts":"registered-bespoke","src/hooks/guardrails/shell-audit-store.ts":"registered-bespoke","src/evidence/documents-retention.ts":"registered-bespoke","src/evidence/manager.ts":"registered-bespoke","src/full-auto/state.ts":"registered-bespoke","src/hooks/delegation-gate/worktree-merge-status.ts":"registered-bespoke","src/hooks/delegation-gate/worktree-provisioning-owner.ts":"migrated","src/hooks/issue-trace-state.ts":"registered-bespoke","src/hooks/knowledge-receipt-ledger-storage.ts":"registered-bespoke","src/hooks/pr-workflow-gate.ts":"registered-bespoke","src/pr-review/authorization.ts":"registered-bespoke","src/pr-review/persistence.ts":"registered-bespoke","src/hooks/promotion-evidence-store.ts":"registered-bespoke","src/hooks/review-receipt.ts":"registered-bespoke","src/hooks/skill-usage-log.ts":"registered-bespoke","src/hooks/skill-usage-pending.ts":"registered-bespoke","src/knowledge/identity.ts":"registered-bespoke","src/memory/jsonl-migration.ts":"external","src/memory/local-jsonl-provider.ts":"registered-bespoke","src/plan/ledger.ts":"registered-bespoke","src/plan/manager.ts":"registered-bespoke","src/review/evidence.ts":"registered-bespoke","src/sdd/effective-spec.ts":"registered-bespoke","src/services/skill-improver-quota.ts":"registered-bespoke","src/services/skill-optimizer/activation.ts":"external","src/services/skill-optimizer/store.ts":"registered-bespoke","src/services/skill-reviser.ts":"external","src/services/synonym-map.ts":"registered-bespoke","src/session/snapshot-writer.ts":"registered-bespoke","src/summaries/manager.ts":"registered-bespoke","src/test-impact/history-store.ts":"registered-bespoke","src/turbo/epic/calibration.ts":"registered-bespoke","src/turbo/epic/state.ts":"registered-bespoke","src/turbo/lean/evidence.ts":"registered-bespoke","src/turbo/lean/integration.ts":"registered-bespoke","src/turbo/lean/recovery.ts":"registered-bespoke","src/turbo/lean/reviewer.ts":"registered-bespoke","src/turbo/lean/state.ts":"registered-bespoke","src/tools/apply-patch.ts":"external","src/tools/checkpoint.ts":"registered-bespoke","src/tools/record-implementation-review.ts":"migrated","src/tools/record-issue-publication.ts":"migrated","src/tools/record-issue-reproduction.ts":"migrated","src/tools/record-recurrence-sweep.ts":"migrated","src/tools/record-branch-freshness.ts":"migrated","src/tools/record-trace-validation.ts":"migrated","src/tools/record-merge-approval.ts":"migrated","src/tools/repo-graph/freshness.ts":"registered-bespoke","src/tools/repo-graph/storage.ts":"registered-bespoke","src/tools/sast-baseline.ts":"registered-bespoke","src/tools/spec-write.ts":"registered-bespoke","src/tools/submit-phase-council-verdicts.ts":"registered-bespoke","src/tools/write-drift-evidence.ts":"registered-bespoke","src/tools/write-final-council-evidence.ts":"registered-bespoke","src/tools/write-hallucination-evidence.ts":"registered-bespoke","src/tools/write-mutation-evidence.ts":"registered-bespoke","src/tools/write-pr-review-artifact.ts":"registered-bespoke","src/tools/write-pr-review-trigger-eval.ts":"registered-bespoke","src/config/bundled-skills.ts":"external","src/services/config-doctor.ts":"external","src/parallel/file-locks.ts":"registered-bespoke","src/utils/bun-compat.ts":"registered-bespoke","src/background/plan-sync-worker.ts":"reader-only","src/config/lane-permissions.ts":"reader-only","src/environment/profile.ts":"reader-only","src/worktree/core.ts":"reader-only"});RENAME_RETRY_DELAYS_MS=[10,25,50,100,200],RETRYABLE_RENAME_CODES=new Set(["EPERM","EBUSY","EACCES","EEXIST"]),recentWriteActivity=new Map;_internals8={randomSuffix:()=>randomBytes(16).toString("hex"),writeSync:(fd,buffer,offset,length)=>fs4.writeSync(fd,buffer,offset,length),renameSync:(from,to)=>fs4.renameSync(from,to),unlinkSync:(p)=>fs4.unlinkSync(p),fsyncSync:(fd)=>fs4.fsyncSync(fd)}});import{spawn as nodeSpawn,spawnSync as nodeSpawnSync}from"node:child_process";import*as fsSync3 from"node:fs";import*as fsPromises2 from"node:fs/promises";import*as path7 from"node:path";function getBun(){return globalThis.Bun}function bunFile(filePath){let bun=getBun();if(bun?.file)return bun.file(filePath);let cachedSize;return{async text(){return fsPromises2.readFile(filePath,"utf-8")},async arrayBuffer(){let buf=await fsPromises2.readFile(filePath),ab=new ArrayBuffer(buf.byteLength);return new Uint8Array(ab).set(buf),ab},async exists(){try{return await fsPromises2.access(filePath,fsSync3.constants.F_OK),!0}catch{return!1}},get size(){if(cachedSize!==void 0)return cachedSize;try{cachedSize=fsSync3.statSync(filePath).size}catch{cachedSize=0}return cachedSize}}}async function bunWrite(filePath,data){let bun=getBun();if(bun?.write)return bun.write(filePath,data);let dir=path7.dirname(filePath),tempName=`.${path7.basename(filePath)}.${process.pid}.${Date.now()}.${tempCounter++}.${Math.random().toString(36).slice(2,10)}.tmp`,tempPath=path7.join(dir,tempName),buffer;if(typeof data==="string")buffer=data;else if(data instanceof ArrayBuffer)buffer=new Uint8Array(data);else if(ArrayBuffer.isView(data))buffer=new Uint8Array(data.buffer,data.byteOffset,data.byteLength);else buffer=new Uint8Array(0);try{await fsPromises2.mkdir(dir,{recursive:!0})}catch{}await fsPromises2.writeFile(tempPath,buffer);let lastError;for(let attempt=0;attempt<WINDOWS_RENAME_MAX_RETRIES;attempt++)try{await fsPromises2.rename(tempPath,filePath),lastError=void 0;break}catch(err){lastError=err;let code=err.code;if(code!=="EEXIST"&&code!=="EBUSY"&&code!=="EPERM")break;await new Promise((r)=>setTimeout(r,WINDOWS_RENAME_RETRY_DELAY_MS))}if(lastError){try{await fsPromises2.unlink(tempPath)}catch{}throw lastError}try{let dirFd=await fsPromises2.open(dir,"r");try{await dirFd.sync()}finally{await dirFd.close()}}catch{}return(await fsPromises2.stat(filePath)).size}function sleep(ms){let bun=getBun();if(bun?.sleep)return bun.sleep(ms);return new Promise((resolve5)=>setTimeout(resolve5,ms))}function collectGarbageBestEffort(){let bun=getBun();try{bun?.gc?.(!0)}catch{}}function bunHash(input){let bun=getBun();if(bun?.hash){let r=bun.hash(input);return typeof r==="bigint"?r:BigInt(r)}let bytes;if(typeof input==="string")bytes=new TextEncoder().encode(input);else if(input instanceof ArrayBuffer)bytes=new Uint8Array(input);else bytes=new Uint8Array(input.buffer,input.byteOffset,input.byteLength);let hash2=5381n;for(let b of bytes)hash2=hash2*33n+BigInt(b)&0xffffffffffffffffn;return hash2}async function killProcessTreeImpl(pid,signal,directKill,wasDetached){if(typeof pid!=="number"||pid<=0){directKill(signal);return}if(_internals9.platform()==="win32"){let taskkill;try{if(taskkill=_internals9.spawnTaskkill(["/PID",String(pid),"/T","/F"],{cwd:_internals9.cwd(),stdio:["ignore","ignore","ignore"],timeout:5000,killSignal:"SIGKILL",windowsHide:!0}),await new Promise((resolve5)=>{let settled=!1,finish=(value)=>{if(settled)return;settled=!0,resolve5(value)};taskkill?.once("error",()=>finish(!1)),taskkill?.once("exit",(code)=>finish(code===0))}))return}catch{}finally{try{taskkill?.kill("SIGKILL")}catch{}}throw directKill(signal),Error("Windows process-tree termination could not be confirmed")}if(wasDetached)try{process.kill(-pid,signal??"SIGKILL");return}catch{}directKill(signal)}function createProcessTreeKiller(pid,directKill,wasDetached){return(signal)=>killProcessTreeImpl(pid,signal,directKill,wasDetached)}function inspectSpawnCwd(cwd){try{return _internals9.statSync(cwd).isDirectory()?"directory":"not-directory"}catch(err){let code=typeof err==="object"&&err!==null&&"code"in err?err.code:void 0;if(code==="ENOENT"||code==="ENOTDIR")return"missing";if(code==="EACCES"||code==="EPERM")return"unreadable";return"unknown"}}function describeSpawnCwdFailure(cwd,executable,cause){let state2=inspectSpawnCwd(cwd);if(state2==="missing")return new SpawnCwdMissingError(cwd,"missing",executable,{cause});if(state2==="not-directory")return new SpawnCwdMissingError(cwd,"not-directory",executable,{cause});return null}function spawnErrorCode(err){if(typeof err!=="object"||err===null||!("code"in err))return;let code=err.code;return typeof code==="string"?code:void 0}function classifySpawnFailure(err,cwd){if(err instanceof SpawnCwdMissingError)return"cwd-missing";let code=spawnErrorCode(err);if(code===void 0||!AMBIGUOUS_SPAWN_CODES.has(code))return"other";if(cwd===void 0||cwd==="")return code==="ENOENT"?"binary-missing":"other";switch(inspectSpawnCwd(cwd)){case"missing":case"not-directory":return"cwd-missing";case"unreadable":case"unknown":return"cwd-unreadable";default:return code==="ENOENT"?"binary-missing":"other"}}function wrapSpawnFailure(error49,cwd,executable){let err=asError(error49);if(err instanceof SpawnCwdMissingError)return err;if(cwd===void 0||cwd==="")return err;if(classifySpawnFailure(err,cwd)!=="cwd-missing")return err;return describeSpawnCwdFailure(cwd,executable,err)??err}function normalizedMaxBuffer(value){return typeof value==="number"&&Number.isSafeInteger(value)&&value>0?value:DEFAULT_BUN_SPAWN_MAX_BUFFER_BYTES}function createOutputOverflowController(limit,requestKill){let error49,killRequested=!1,resolveCompleted,completed=new Promise((resolve5)=>{resolveCompleted=resolve5});return{get error(){return error49},completed,overflow(captured,total){if(error49)return;if(error49=new BunCompatOutputLimitError(limit,captured,total),killRequested)return;killRequested=!0;try{requestKill()}catch{}},complete(){resolveCompleted()}}}function streamFromNode(pipe2,limit,controller){if(!pipe2)return staticStream("");let mode,collected,collect=()=>{if(mode==="reader")return Promise.reject(TypeError("Subprocess output is already consumed by a reader"));if(mode="buffered",collected)return collected;return collected=new Promise((resolve5)=>{if(!pipe2){resolve5(Buffer.alloc(0));return}let chunks=[],captured=0,total=0,finished=!1,finish=()=>{if(finished)return;finished=!0,resolve5(Buffer.concat(chunks))};pipe2.on("data",(chunk)=>{let bytes=typeof chunk==="string"?Buffer.from(chunk):chunk;if(total+=bytes.byteLength,controller?.error||limit===void 0)return;let remaining=limit-captured;if(remaining>0){let retained=Buffer.from(bytes.subarray(0,remaining));chunks.push(retained),captured+=retained.byteLength}if(bytes.byteLength>remaining)controller?.overflow(captured,total)}),pipe2.on("end",finish),pipe2.on("close",finish),pipe2.on("error",finish)}).then(async(bytes)=>{if(await controller?.completed,controller?.error)throw controller.error;return bytes}),collected},toWebReadable=()=>{if(!pipe2)return new ReadableStream({start(controller2){controller2.close()}});let r=pipe2;if(typeof r.toWeb==="function")return r.toWeb();return new ReadableStream({start(controller2){pipe2.on("data",(chunk)=>{controller2.enqueue(typeof chunk==="string"?new TextEncoder().encode(chunk):new Uint8Array(chunk.buffer,chunk.byteOffset,chunk.byteLength))}),pipe2.on("end",()=>controller2.close()),pipe2.on("error",(err)=>controller2.error(err))},cancel(){let destroyable=pipe2;if(typeof destroyable.destroy==="function")try{destroyable.destroy()}catch{}}})},result={async text(){return(await collect()).toString("utf-8")},async bytes(){let b=await collect();return new Uint8Array(b.buffer,b.byteOffset,b.byteLength)},getReader(){if(mode!==void 0)throw TypeError("Subprocess output is already consumed");return mode="reader",toWebReadable().getReader()}};if(pipe2&&controller&&limit!==void 0)queueMicrotask(()=>{if(mode===void 0)collect().catch(()=>{return})});return result}function mapStdio(v){return v??"pipe"}function streamFromBun(stream,limit,controller){if(!stream||typeof stream!=="object")return{async text(){return""},async bytes(){return new Uint8Array(0)},getReader(){return new ReadableStream({start(controller2){controller2.close()}}).getReader()}};let candidate=stream,mode,collected,collect=()=>{if(mode==="reader")return Promise.reject(TypeError("Subprocess output is already consumed by a reader"));return mode="buffered",collected??=(async()=>{if(typeof candidate.getReader!=="function")return new Uint8Array(0);let reader=candidate.getReader(),chunks=[],captured=0,total=0;try{for(;;){let{done,value}=await reader.read();if(done)break;if(!value)continue;if(total+=value.byteLength,controller?.error||limit===void 0)continue;let remaining=limit-captured;if(remaining>0){let retained=value.slice(0,remaining);chunks.push(retained),captured+=retained.byteLength}if(value.byteLength>remaining)controller?.overflow(captured,total)}}finally{reader.releaseLock()}if(await controller?.completed,controller?.error)throw controller.error;let out=new Uint8Array(captured),offset=0;for(let chunk of chunks)out.set(chunk,offset),offset+=chunk.byteLength;return out})(),collected},result={async text(){return new TextDecoder().decode(await collect())},bytes:collect,getReader(){if(mode!==void 0)throw TypeError("Subprocess output is already consumed");return mode="reader",typeof candidate.getReader==="function"?candidate.getReader():new ReadableStream({start(streamController){streamController.close()}}).getReader()}};if(typeof candidate.getReader==="function"&&controller&&limit!==void 0)queueMicrotask(()=>{if(mode===void 0)collect().catch(()=>{return})});return result}function mergeEnvForChild(baseEnv,envOverrides){let hasExplicitBaseEnv=baseEnv!==void 0,baseSource=baseEnv??process.env,merged={};for(let[key,value]of Object.entries(baseSource))if(typeof value==="string")merged[key]=value;if(envOverrides)for(let[key,value]of Object.entries(envOverrides))if(value===null)delete merged[key];else merged[key]=value;if(Object.keys(merged).length===0)return hasExplicitBaseEnv?{}:void 0;return merged}function asError(value){return value instanceof Error?value:Error(String(value))}function staticStream(text){let bytes=new TextEncoder().encode(text);return{async text(){return text},async bytes(){return bytes},getReader(){return new ReadableStream({start(controller){if(bytes.byteLength>0)controller.enqueue(bytes);controller.close()}}).getReader()}}}function spawnCreationFailure(error49){return{stdout:streamFromBun(void 0),stderr:staticStream(error49.message),exited:Promise.resolve(SPAWN_CREATION_FAILURE_EXIT_CODE),exitCode:null,signalCode:null,spawnError:error49,kill(){},killTree:()=>Promise.resolve()}}function bunSpawn(cmd,options){let maxBuffer=normalizedMaxBuffer(options?.maxBuffer),bun=getBun();if(bun?.spawn){let mergedEnv2=mergeEnvForChild(options?.env,options?.envOverrides),spawnOpts={...options};if(delete spawnOpts.killProcessTree,delete spawnOpts.maxBuffer,mergedEnv2!==void 0)spawnOpts.env=mergedEnv2;if(options?.timeout&&options.timeout>0&&options.killProcessTree!==!0)spawnOpts.killSignal="SIGKILL";if(options?.killProcessTree===!0)delete spawnOpts.timeout,delete spawnOpts.killSignal,spawnOpts.detached=!0;let spawned;try{spawned=bun.spawn(cmd,spawnOpts)}catch(error49){return spawnCreationFailure(wrapSpawnFailure(error49,options?.cwd,cmd[0]??""))}let proc2=spawned,killBunTree=createProcessTreeKiller(proc2.pid,(sig)=>proc2.kill(sig),!0),killBunProcess=(sig)=>options?.killProcessTree?killBunTree(sig):Promise.resolve(proc2.kill(sig)),outputController2=createOutputOverflowController(maxBuffer,()=>{killBunProcess("SIGKILL").catch(()=>{return})}),timeoutHandle2;if(options?.killProcessTree===!0&&options.timeout&&options.timeout>0){if(timeoutHandle2=setTimeout(()=>{try{killBunProcess("SIGKILL").catch(()=>{return})}catch{}},options.timeout),typeof timeoutHandle2.unref==="function")timeoutHandle2.unref()}let exited2=proc2.exited.finally(()=>{if(timeoutHandle2!==void 0)clearTimeout(timeoutHandle2);outputController2.complete()});return{stdout:streamFromBun(proc2.stdout,maxBuffer,outputController2),stderr:streamFromBun(proc2.stderr,maxBuffer,outputController2),exited:exited2,get exitCode(){return proc2.exitCode},get signalCode(){return proc2.signalCode},kill(sig){killBunProcess(sig).catch(()=>{return})},killTree:killBunProcess}}let[file2,...args2]=cmd,detached=options?.killProcessTree===!0,mergedEnv=mergeEnvForChild(options?.env,options?.envOverrides),proc;try{proc=nodeSpawn(file2,args2,{cwd:options?.cwd,env:mergedEnv,detached,windowsHide:!0,windowsVerbatimArguments:options?.windowsVerbatimArguments,stdio:[mapStdio(options?.stdin),mapStdio(options?.stdout),mapStdio(options?.stderr)]})}catch(error49){return spawnCreationFailure(wrapSpawnFailure(error49,options?.cwd,file2))}let killChildTree=createProcessTreeKiller(proc.pid,(signal)=>proc.kill(signal),!0),killChild=(signal)=>{if(detached)return killChildTree(signal);return proc.kill(signal),Promise.resolve()},outputController=createOutputOverflowController(maxBuffer,()=>{killChild("SIGKILL").catch(()=>{return})}),timeoutHandle,observedSignal=null,observedSpawnError=null,exited=new Promise((resolve5)=>{if(proc.on("exit",(code,signal)=>{observedSignal=signal,resolve5(code??-1)}),proc.on("error",(error49)=>{observedSpawnError=wrapSpawnFailure(error49,options?.cwd,file2),resolve5(1)}),options?.timeout&&options.timeout>0){if(timeoutHandle=setTimeout(()=>{try{killChild("SIGKILL").catch(()=>{return})}catch{}},options.timeout),typeof timeoutHandle.unref==="function")timeoutHandle.unref()}}).finally(()=>{if(timeoutHandle!==void 0)clearTimeout(timeoutHandle);outputController.complete()});return{stdout:streamFromNode(proc.stdout,maxBuffer,outputController),stderr:streamFromNode(proc.stderr,maxBuffer,outputController),exited,get exitCode(){return observedSpawnError?null:proc.exitCode},get signalCode(){return observedSignal??proc.signalCode},get spawnError(){return observedSpawnError},kill(signal){killChild(signal).catch(()=>{return})},killTree:killChild}}function syncSpawnCreationFailure(error49){return{stdout:new Uint8Array(0),stderr:new TextEncoder().encode(error49.message),exitCode:SPAWN_CREATION_FAILURE_EXIT_CODE,success:!1}}function bunSpawnSync(cmd,options){let requestedCwd=Array.isArray(cmd)?options?.cwd:options?.cwd??cmd.cwd,executable=(Array.isArray(cmd)?cmd[0]:cmd.cmd[0])??"",bun=getBun();if(bun?.spawnSync){let mergedEnv2=mergeEnvForChild(options?.env,options?.envOverrides),spawnOpts={...options};if(delete spawnOpts.maxBuffer,mergedEnv2!==void 0)spawnOpts.env=mergedEnv2;try{return bun.spawnSync(cmd,spawnOpts)}catch(error49){return syncSpawnCreationFailure(wrapSpawnFailure(error49,requestedCwd,executable))}}let argv,mergedOptions;if(Array.isArray(cmd))argv=cmd,mergedOptions={...options??{}};else if(argv=cmd.cmd,mergedOptions={cwd:cmd.cwd,env:cmd.env,stdin:"pipe",timeout:cmd.timeout,...options??{}},cmd.stdin!==void 0)mergedOptions.stdin=cmd.stdin;let[file2,...args2]=argv,mergedEnv=mergeEnvForChild(mergedOptions.env,options?.envOverrides),result;try{result=nodeSpawnSync(file2,args2,{cwd:mergedOptions.cwd,env:mergedEnv,input:mergedOptions.stdin instanceof Uint8Array||typeof mergedOptions.stdin==="string"?mergedOptions.stdin:void 0,timeout:mergedOptions.timeout,windowsHide:!0})}catch(error49){return syncSpawnCreationFailure(wrapSpawnFailure(error49,mergedOptions.cwd,file2))}if(result.error){let wrapped=wrapSpawnFailure(result.error,mergedOptions.cwd,file2);if(wrapped instanceof SpawnCwdMissingError)return syncSpawnCreationFailure(wrapped)}let stdout=result.stdout instanceof Buffer?new Uint8Array(result.stdout.buffer,result.stdout.byteOffset,result.stdout.byteLength):typeof result.stdout==="string"?new TextEncoder().encode(result.stdout):new Uint8Array(0),stderr=result.stderr instanceof Buffer?new Uint8Array(result.stderr.buffer,result.stderr.byteOffset,result.stderr.byteLength):typeof result.stderr==="string"?new TextEncoder().encode(result.stderr):new Uint8Array(0),exitCode=result.status??(result.signal?128:1);return{stdout,stderr,exitCode,success:exitCode===0&&!result.error}}var WINDOWS_RENAME_MAX_RETRIES=3,WINDOWS_RENAME_RETRY_DELAY_MS=50,tempCounter=0,DEFAULT_BUN_SPAWN_MAX_BUFFER_BYTES=5242880,BunCompatOutputLimitError,_internals9,SpawnCwdMissingError,AMBIGUOUS_SPAWN_CODES,SPAWN_CREATION_FAILURE_EXIT_CODE=1;var init_bun_compat=__esm(()=>{BunCompatOutputLimitError=class BunCompatOutputLimitError extends Error{limit;captured;total;constructor(limit,captured,total){super(`Subprocess output exceeded the ${limit}-byte buffer limit after capturing ${captured} bytes (${total} bytes observed)`);this.name="BunCompatOutputLimitError",this.limit=limit,this.captured=captured,this.total=total}};_internals9={platform:()=>process.platform,cwd:()=>process.cwd(),spawnTaskkill:(args2,options)=>nodeSpawn("taskkill",args2,options),createProcessTreeKiller,statSync:(target)=>fsSync3.statSync(target)};SpawnCwdMissingError=class SpawnCwdMissingError extends Error{name="SpawnCwdMissingError";code="ENOENT";cwd;reason;executable;constructor(cwd,reason,executable,options){super(reason==="missing"?`cannot start "${executable}": working directory no longer exists: ${cwd}`:`cannot start "${executable}": working directory is not a directory: ${cwd}`,options);this.cwd=cwd,this.reason=reason,this.executable=executable}};AMBIGUOUS_SPAWN_CODES=new Set(["ENOENT","ENOTDIR","EACCES","EPERM"])});import*as fs5 from"node:fs";import*as path8 from"node:path";function isFailClosedHandler(value){return typeof value==="function"&&Object.hasOwn(value,"__failClosed")&&value.__failClosed===!0}function safeHook(fn2){return async(input,output)=>{try{await fn2(input,output)}catch(_error){let functionName=fn2.name||"unknown";if(_error instanceof SwarmError)warn(`Hook '${functionName}' failed: ${_error.message}
|
|
180
180
|
→ ${_error.guidance}`);else warn(`Hook function '${functionName}' failed:`,_error)}}}function composeHandlers(...fns){if(fns.length===0)return async()=>{};for(let fn2 of fns)if(isFailClosedHandler(fn2))throw Error("composeHandlers cannot wrap fail-closed handlers; use composeBlockingHandlers or await them directly");return async(input,output)=>{for(let fn2 of fns)await _internals10.safeHook(fn2)(input,output)}}function validateSwarmPath(directory,filename){if(/[\0]/.test(filename))throw Error("Invalid filename: contains null bytes");if(/\.\.[/\\]/.test(filename))throw Error("Invalid filename: path traversal detected");if(/^[A-Za-z]:[\\/]/.test(filename))throw Error("Invalid filename: path escapes .swarm directory");if(filename.startsWith("/"))throw Error("Invalid filename: path escapes .swarm directory");let baseDir=path8.normalize(path8.resolve(directory,".swarm")),resolved=path8.normalize(path8.resolve(baseDir,filename));if(process.platform==="win32"){if(!resolved.toLowerCase().startsWith((baseDir+path8.sep).toLowerCase()))throw Error("Invalid filename: path escapes .swarm directory")}else if(!resolved.startsWith(baseDir+path8.sep))throw Error("Invalid filename: path escapes .swarm directory");let realBaseDir;try{if(fs5.lstatSync(baseDir).isSymbolicLink())throw Error("Invalid filename: path escapes .swarm directory");realBaseDir=fs5.realpathSync(baseDir)}catch(error49){if(error49 instanceof Error&&error49.message==="Invalid filename: path escapes .swarm directory")throw error49;if(error49.code==="ENOENT")return resolved;throw Error("Invalid filename: failed to resolve .swarm directory")}let existingPath=resolved;while(!fs5.existsSync(existingPath)){let parent=path8.dirname(existingPath);if(parent===existingPath||!isPathWithin(parent,baseDir)){existingPath=baseDir;break}existingPath=parent}let realExistingPath;try{realExistingPath=fs5.realpathSync(existingPath)}catch(error49){if(error49.code==="ENOENT")realExistingPath=realBaseDir;else throw Error("Invalid filename: failed to resolve path")}if(!isPathWithin(realExistingPath,realBaseDir))throw Error("Invalid filename: path escapes .swarm directory");return resolved}function isPathWithin(candidate,base){let normalizedCandidate=path8.normalize(candidate),normalizedBase=path8.normalize(base);if(process.platform==="win32"){let candidateLower=normalizedCandidate.toLowerCase(),baseLower=normalizedBase.toLowerCase();return candidateLower===baseLower||candidateLower.startsWith(`${baseLower}${path8.sep}`)}return normalizedCandidate===normalizedBase||normalizedCandidate.startsWith(`${normalizedBase}${path8.sep}`)}async function readSwarmFileAsync(directory,filename,cache2,reader,useArtifactCache=!0){if(cache2!==void 0&&useArtifactCache){let key=`${directory}::${filename}`,cached2=cache2.get(key);if(cached2!==void 0)return cached2;let promise2=readSwarmFileAsync(directory,filename,void 0,reader,useArtifactCache);return cache2.set(key,promise2),promise2}let ENOENT_MAX_ATTEMPTS=5,ENOENT_RETRY_DELAY_MS=10,maxAttempts=6;for(let attempt=0;attempt<maxAttempts;attempt++){let resolvedPath="";try{resolvedPath=_internals10.validateSwarmPath(directory,filename);let read=async()=>{if(reader!==void 0)return reader(resolvedPath);return await bunFile(resolvedPath).text()};return useArtifactCache?await _internals10.readCachedTextFile(resolvedPath,read):await read()}catch(err){let code=err?.code;if(reader!==void 0&&(code===void 0||code==="ERR_ENCODING_INVALID_ENCODED_DATA"))throw err;if(code==="ENOENT"){if(!(resolvedPath!==""&&(wasRecentlyWrittenByThisProcess(resolvedPath,RECENT_WRITE_WINDOW_MS)||wasObservedToExist(resolvedPath))))return null;if(attempt>=ENOENT_MAX_ATTEMPTS-1)return null;await new Promise((resolve6)=>setTimeout(resolve6,ENOENT_RETRY_DELAY_MS));continue}if(!(code==="EBUSY"||code==="EPERM"||code==="EACCES")||attempt===maxAttempts-1)return null;let retryDelayMs=10*2**attempt;await new Promise((resolve6)=>setTimeout(resolve6,retryDelayMs))}}return null}function estimateTokensFromCharCount(chars){if(chars<=0)return 0;return Math.ceil(chars*TOKENS_PER_CHAR)}function estimateCharsForTokens(tokens){if(tokens<=0)return 0;return Math.floor(tokens/TOKENS_PER_CHAR)}function estimateTokens(text){if(!text)return 0;return estimateTokensFromCharCount(text.length)}var _internals10,TOKENS_PER_CHAR=0.33;var init_utils2=__esm(()=>{init_utils();init_atomic_write();init_bun_compat();init_swarm_artifact_cache();_internals10={safeHook,composeHandlers,validateSwarmPath,readSwarmFileAsync,readCachedTextFile}});import{createHash as createHash3}from"node:crypto";import{appendFileSync,mkdirSync as mkdirSync2}from"node:fs";import*as path9 from"node:path";function isBidiCodePoint(code){for(let i=0;i<BIDI_RANGES.length;i++){let[lo,hi]=BIDI_RANGES[i];if(code>=lo&&code<=hi)return!0}return!1}function sanitizeString(value){let result="";for(let i=0;i<value.length;i++){let code=value.codePointAt(i)??0;if(code>65535)result+=value[i],i++,result+=value[i];else if(code===0)result+="\\u0000";else if(code===27){if(i+1<value.length&&value[i+1]==="["){i++;while(i+1<value.length){let next=value.charCodeAt(i+1);if(next>=48&&next<=63)i++;else if(next>=32&&next<=47)i++;else if(next>=64&&next<=126){i++;break}else break}}else if(i+1<value.length&&value[i+1]==="]"){i++;while(i+1<value.length){let next=value.charCodeAt(i+1);if(next===7){i++;break}else if(next===27&&i+2<value.length&&value[i+2]==="\\"){i+=2;break}else i++}}else if(i+1<value.length){let next=value.charCodeAt(i+1);if(next>=32&&next<=47){i++;while(i+1<value.length){let b=value.charCodeAt(i+1);if(b>=48&&b<=126){i++;break}else if(b>=32&&b<=47)i++;else break}}else if(next>=48&&next<=126)i++}}else if(isBidiCodePoint(code));else result+=value[i]}return result}function sanitizeRecord(record2){for(let key of Object.keys(record2)){let value=record2[key];if(typeof value==="string")record2[key]=sanitizeString(value);else if(value!==null&&typeof value==="object")if(Array.isArray(value))for(let i=0;i<value.length;i++){let element=value[i];if(typeof element==="string")value[i]=sanitizeString(element);else if(element!==null&&typeof element==="object")sanitizeRecord(element)}else sanitizeRecord(value)}return record2}function computeBatchDigest(batchId){return createHash3(BATCH_DIGEST_ALGORITHM).update(batchId).digest("hex")}function sidecarRelativePath(batchDigest){return path9.join("lane-results",batchDigest,"candidates.jsonl")}function validateRecord(record2,schema,label){let result=schema.safeParse(record2);if(!result.success)throw Error(`Sidecar ${label} schema validation failed: ${result.error.issues.map((i)=>`${i.path.join(".")}: ${i.message}`).join("; ")}`)}function withLockfile(lockDir,write){let lockPath=path9.join(lockDir,".lock"),release=import_proper_lockfile.default.lockSync(lockPath,{realpath:!1});try{return write()}finally{release()}}function appendToSidecar(options,batchId,envelope,candidates,cleanAttestation){let batchDigest=options.batchDigest??computeBatchDigest(batchId),relPath=sidecarRelativePath(batchDigest),absPath=validateSwarmPath(options.projectRoot,relPath);validateRecord(envelope,SidecarEnvelopeSchema,"envelope");for(let i=0;i<candidates.length;i++)validateRecord(candidates[i],SidecarCandidateSchema,`candidate[${i}]`);if(cleanAttestation!==void 0)validateRecord(cleanAttestation,SidecarCleanAttestationSchema,"clean_attestation");mkdirSync2(path9.dirname(absPath),{recursive:!0});let sanitizedEnvelope=sanitizeRecord(structuredClone(envelope)),sanitizedCandidates=candidates.map((c)=>sanitizeRecord(structuredClone(c))),sanitizedCleanAttestation=cleanAttestation===void 0?void 0:sanitizeRecord(structuredClone(cleanAttestation)),lines=[JSON.stringify(sanitizedEnvelope)];if(sanitizedCleanAttestation)lines.push(JSON.stringify(sanitizedCleanAttestation));for(let candidate of sanitizedCandidates)lines.push(JSON.stringify(candidate));let payload=`${lines.join(`
|
|
181
181
|
`)}
|
|
182
182
|
`,doWrite=()=>{appendFileSync(absPath,payload,"utf-8")};if(options.useLockfile)withLockfile(path9.dirname(absPath),doWrite);else doWrite()}var import_proper_lockfile,BATCH_DIGEST_ALGORITHM="sha256",SidecarEnvelopeSchema,SidecarCleanAttestationSchema,SidecarCandidateCommon,SidecarCandidateSchema,BIDI_RANGES;var init_candidate_sidecar_store=__esm(()=>{init_zod();init_utils2();init_candidate_contract();import_proper_lockfile=__toESM(require_proper_lockfile(),1),SidecarEnvelopeSchema=exports_external.object({record_type:exports_external.literal("invocation"),source_output_ref:exports_external.string().min(1),source_batch_id:exports_external.string().min(1),source_lane_id:exports_external.string().min(1),source_agent:exports_external.string().min(1),source_digest:exports_external.string().regex(/^[a-f0-9]{64}$/),row_format_version:exports_external.number().int().nonnegative(),producer:exports_external.string().optional(),produced_at:exports_external.string().min(1),record_version:exports_external.object({major:exports_external.number().int().nonnegative(),minor:exports_external.number().int().nonnegative()}),sessionId:exports_external.string().min(1).optional(),parentSessionId:exports_external.string().min(1).optional(),format_families_detected:exports_external.array(exports_external.string()),candidate_count:exports_external.number().int().nonnegative(),parse_errors:exports_external.number().int().nonnegative(),malformed_rows:exports_external.number().int().nonnegative(),clean_attestation_count:exports_external.number().int().nonnegative().optional()}).strict(),SidecarCleanAttestationSchema=exports_external.discriminatedUnion("row_format_family",[exports_external.object({record_type:exports_external.literal("clean_attestation"),row_format_family:exports_external.literal("base_explorer"),row_format_version:exports_external.number().int().nonnegative(),record_version:exports_external.object({major:exports_external.number().int().nonnegative(),minor:exports_external.number().int().nonnegative()}),source_output_ref:exports_external.string().min(1),source_batch_id:exports_external.string().min(1),source_lane_id:exports_external.string().min(1),source_agent:exports_external.string().min(1),source_digest:exports_external.string().regex(/^[a-f0-9]{64}$/),extracted_from_partial_source:exports_external.literal(!1),sessionId:exports_external.string().min(1).optional(),parentSessionId:exports_external.string().min(1).optional(),producer:exports_external.string().optional(),lane:exports_external.string().min(1),coverage_scope:exports_external.string().min(CLEAN_COVERAGE_SCOPE_MIN_CHARS),evidence:exports_external.string().min(CLEAN_EVIDENCE_MIN_CHARS)}).strict(),exports_external.object({record_type:exports_external.literal("clean_attestation"),row_format_family:exports_external.literal("micro_lane"),row_format_version:exports_external.number().int().nonnegative(),record_version:exports_external.object({major:exports_external.number().int().nonnegative(),minor:exports_external.number().int().nonnegative()}),source_output_ref:exports_external.string().min(1),source_batch_id:exports_external.string().min(1),source_lane_id:exports_external.string().min(1),source_agent:exports_external.string().min(1),source_digest:exports_external.string().regex(/^[a-f0-9]{64}$/),extracted_from_partial_source:exports_external.literal(!1),sessionId:exports_external.string().min(1).optional(),parentSessionId:exports_external.string().min(1).optional(),producer:exports_external.string().optional(),micro_lane:exports_external.string().min(1),coverage_scope:exports_external.string().min(CLEAN_COVERAGE_SCOPE_MIN_CHARS),evidence:exports_external.string().min(CLEAN_EVIDENCE_MIN_CHARS)}).strict()]),SidecarCandidateCommon={record_type:exports_external.literal("candidate"),row_format_version:exports_external.number().int().nonnegative(),record_version:exports_external.object({major:exports_external.number().int().nonnegative(),minor:exports_external.number().int().nonnegative()}),source_output_ref:exports_external.string().min(1),source_batch_id:exports_external.string().min(1),source_lane_id:exports_external.string().min(1),source_agent:exports_external.string().min(1),source_digest:exports_external.string().regex(/^[a-f0-9]{64}$/),sessionId:exports_external.string().min(1).optional(),parentSessionId:exports_external.string().min(1).optional(),producer:exports_external.string().optional(),extracted_from_partial_source:exports_external.boolean(),candidate_id:exports_external.string().min(1),severity:exports_external.enum(CANDIDATE_SEVERITIES),category:exports_external.string().min(1),file_line:exports_external.string().min(1),claim:exports_external.string().min(1),evidence_summary:exports_external.string().min(1),confidence:exports_external.enum(CANDIDATE_CONFIDENCES),risk_impact:exports_external.enum(PR_REVIEW_RISK_IMPACTS).optional(),risk_tags:exports_external.array(exports_external.enum(PR_REVIEW_RISK_TAGS)).optional()},SidecarCandidateSchema=exports_external.discriminatedUnion("row_format_family",[exports_external.object({...SidecarCandidateCommon,row_format_family:exports_external.literal("base_explorer"),lane:exports_external.string().min(1),micro_lane:exports_external.null(),impact_context:exports_external.string().min(1),invariant_violated:exports_external.null()}).strict(),exports_external.object({...SidecarCandidateCommon,row_format_family:exports_external.literal("micro_lane"),lane:exports_external.null(),micro_lane:exports_external.string().min(1),impact_context:exports_external.null(),invariant_violated:exports_external.string().min(1)}).strict()]),BIDI_RANGES=[[8234,8238],[8294,8297]]});function detectRowFormatFamily(rowFields){let trimmed=rowFields.map((f)=>f.trim()),hasImpactContext=trimmed.length>7&&trimmed[7]!=="",hasInvariantViolated=trimmed.length>6&&trimmed[6]!=="";if(hasImpactContext&&!hasInvariantViolated)return"base_explorer";if(hasInvariantViolated&&!hasImpactContext)return"micro_lane";if(hasImpactContext&&hasInvariantViolated)return"base_explorer";throw new UnknownFormatFamilyError}function mapFields(fields,family){let trimmed=fields.map((f)=>f.trim()),names=CANDIDATE_FIELDS[family],result={};for(let i=0;i<names.length;i++)result[names[i]]=i<trimmed.length&&trimmed[i]!==""?trimmed[i]:null;if(family==="base_explorer")result.micro_lane=null,result.invariant_violated=null;else result.lane=null,result.impact_context=null;return result}function getRequiredFields(family){return CANDIDATE_REQUIRED_FIELDS[family]}function assertNonNullCandidateId(value){if(value===null||value==="")throw Error("Invariant violation: null/empty candidate_id reached candidate builder")}function buildInvocationEnvelope(input,flags,formatFamiliesDetected,candidateCount,parseErrors,malformedRows,cleanAttestationCount=0){return{record_type:"invocation",source_output_ref:input.output_ref,source_batch_id:input.batchId,source_lane_id:input.laneId,source_agent:input.agent,source_digest:input.digest,row_format_version:flags.row_format_version,sessionId:input.sessionId,parentSessionId:input.parentSessionId,...flags.producer?{producer:flags.producer}:{},produced_at:input.produced_at,record_version:RECORD_VERSION,format_families_detected:formatFamiliesDetected,candidate_count:candidateCount,parse_errors:parseErrors,malformed_rows:malformedRows,clean_attestation_count:cleanAttestationCount}}function buildEmptyDiagnostics(input,flags){return{candidate_count:0,parse_errors:0,parse_error_details:[],malformed_rows:0,duplicate_id_count:0,duplicate_id_warnings:[],degraded_source_count:flags.degraded?1:0,incomplete_source_count:input.transcriptIncomplete?1:0,format_families_detected:[],clean_attestation_count:0}}function refusalResult(errorCode,errorMessage,input,flags){let envelope=buildInvocationEnvelope(input,flags,[],0,0,0);return{error:errorMessage,error_code:errorCode,candidates:[],invocation_envelope:envelope,diagnostics:buildEmptyDiagnostics(input,flags)}}function detectFormatMismatchHint(text){if(text.trim()==="")return;let severityPattern=/\b(CRITICAL|HIGH|MEDIUM|LOW|INFO)\b/,fileLinePattern=/\b\S+\.[a-z]{1,4}:\d+\b/,hasSeverity=severityPattern.test(text),textForFileLine=text.replace(/\b\w+:\/\/\S*/g,""),hasFileLine=fileLinePattern.test(textForFileLine);if(hasSeverity&&hasFileLine)return"Lane output contains severity keywords and file:line references but no parseable [CANDIDATE] rows. The explorer may have emitted findings in prose format instead of pipe-delimited candidate rows.";if(hasSeverity)return"Lane output contains severity keywords but no parseable [CANDIDATE] rows. The explorer may have emitted findings in an unstructured format.";return}function emptyTextResult(input,flags){let envelope=buildInvocationEnvelope(input,flags,[],0,0,0),diagnostics=buildEmptyDiagnostics(input,flags),hint=detectFormatMismatchHint(input.text);if(hint)diagnostics.format_mismatch_hint=hint;return{candidates:[],invocation_envelope:envelope,diagnostics}}function parseCandidates(input,flags){let inputParse=ArtifactInputSchema.safeParse(input);if(!inputParse.success)throw Error(`Invalid ArtifactInput: ${inputParse.error.issues.map((issue2)=>issue2.message).join(", ")}`);let flagsParse=ParseFlagsSchema.safeParse(flags);if(!flagsParse.success)throw Error(`Invalid ParseFlags: ${flagsParse.error.issues.map((issue2)=>issue2.message).join(", ")}`);let validatedInput=inputParse.data,validatedFlags=flagsParse.data;if(validatedInput.artifact_status==="ref-not-found")return refusalResult("ref-not-found","Artifact reference not found in store",validatedInput,validatedFlags);if(validatedInput.artifact_status==="artifact-corrupted")return refusalResult("artifact-corrupted","Artifact data is corrupted",validatedInput,validatedFlags);if(validatedFlags.degraded&&!validatedFlags.accept_degraded)return refusalResult("degraded-source-refused","Degraded source refused by caller",validatedInput,validatedFlags);if(validatedInput.transcriptIncomplete===!0&&!validatedFlags.accept_partial)return refusalResult("partial-source-refused","Partial transcript refused by caller",validatedInput,validatedFlags);if(validatedInput.text.trim()==="")return emptyTextResult(validatedInput,validatedFlags);return parseText(validatedInput,validatedFlags)}function parseText(input,flags){let lines=removeCandidateCodeFences(input.text).split(`
|
|
@@ -632,7 +632,7 @@ ${squashResult.stdout}`,restore=await runGit3(["checkout","-q","HEAD","--",...in
|
|
|
632
632
|
`.split(`
|
|
633
633
|
`)){let line=rawLine.endsWith("\r")?rawLine.slice(0,-1):rawLine;if(line.startsWith("worktree ")){worktreePath=line.slice(9);continue}if(!line.startsWith("branch ")||!worktreePath)continue;try{fs21.statSync(worktreePath)}catch(error49){let code=error49.code;if(code==="ENOENT"||code==="ENOTDIR")continue;return{status:"uncertain",reason:`registered worktree path "${worktreePath}" is unreadable: ${error49 instanceof Error?error49.message:String(error49)}`}}let branch=line.slice(7);liveBranches.push(branch.startsWith("refs/heads/")?branch.slice(11):branch)}return{status:"ok",liveBranches}}async function readLaneBranchHead(branchName,primaryDir){return runGit3(["rev-parse","--verify","--quiet",`refs/heads/${branchName}`],primaryDir)}async function captureLaneSourceHead(worktreePath,branchName,primaryDir,knownMissing){if(!knownMissing){let fromWorktree=await runGit3(["rev-parse","HEAD"],worktreePath);if(fromWorktree.spawnFailure?.kind!=="cwd-missing")return{result:fromWorktree,sourceWorktreeMissing:!1}}return{result:await readLaneBranchHead(branchName,primaryDir),sourceWorktreeMissing:!0}}async function handleSourceWorktreeGone(branchHead,worktreePath,branchName,primaryDir,provenance){if(!(branchHead.spawnFailure===void 0&&branchHead.exitCode===0&&branchHead.stdout.trim().length>0)){let definitelyAbsent=branchHead.spawnFailure===void 0&&branchHead.exitCode===1;return{failed:!0,stage:definitelyAbsent?SOURCE_WORKTREE_GONE_STAGE:SOURCE_WORKTREE_UNCERTAIN_STAGE,message:definitelyAbsent?`Lane worktree "${worktreePath}" is gone and branch "${branchName}" no longer exists; nothing is recoverable`:`Lane worktree "${worktreePath}" is gone and branch "${branchName}" existence could not be determined: ${branchHead.stderr.trim()||`git exited ${branchHead.exitCode}`}`,...provenance?{provenance}:{}}}let prune=await runGit3(["worktree","prune"],primaryDir);if(prune.exitCode!==0)log(`[worktree] attemptMergeBackFromDirty: worktree prune failed for "${worktreePath}": ${prune.stderr.trim()||prune.stdout.trim()}`);return advisoryWarn(`STALE_LANE_WORKTREE_DETECTED: lane worktree "${worktreePath}" no longer exists. Its stale git registration was pruned, and the merge-back for branch "${branchName}" is being taken from "${primaryDir}" instead. Any uncommitted work in that worktree is unrecoverable; every commit on the branch is preserved.`),null}async function attemptMergeBackFromDirty(worktreePath,branchName,primaryDir,strategy,options={}){let autoCommitted=!1,cleaned=!1,autoCommitFailed=!1,cleanFailed=!1,provenance=options.resume,sourceWorktreeMissing=!1;if(provenance){if(provenance.branchName!==branchName||provenance.strategy!==strategy||options.operationId!==void 0&&provenance.operationId!==options.operationId)return{failed:!0,stage:"reconciliation",message:"Stored merge operation identity does not match this dispatch",provenance};let reconciliation=await reconcileLandedMerge(primaryDir,provenance);if("error"in reconciliation&&reconciliation.error)return{failed:!0,stage:"reconciliation",message:`Unable to reconcile prior merge-back: ${reconciliation.error}`,provenance};if(reconciliation.landed)return{merged:!0,strategy:reconciliation.method==="worktree-match"?"squash-unstaged":strategy,autoCommitted:!1,cleaned:!1,reconciled:!0,provenance};let source=await captureLaneSourceHead(worktreePath,branchName,primaryDir,!1);if(source.sourceWorktreeMissing){let unrecoverable=await handleSourceWorktreeGone(source.result,worktreePath,branchName,primaryDir,provenance);if(unrecoverable)return unrecoverable;sourceWorktreeMissing=!0}let sourceHead=source.result,targetHead=await runGit3(["rev-parse","HEAD"],primaryDir);if(sourceHead.exitCode!==0||targetHead.exitCode!==0||sourceHead.stdout.trim()!==provenance.sourceHead||targetHead.stdout.trim()!==provenance.targetHeadBefore)return{failed:!0,stage:"reconciliation",message:"Stored merge operation did not land and its source or target HEAD has changed",provenance}}if(!provenance&&!sourceWorktreeMissing){let commitResult=await autoCommitDirty(worktreePath);if(commitResult.committed)autoCommitted=!0;else if(commitResult.reason!=="Nothing to commit")autoCommitFailed=!0,log(`[worktree] attemptMergeBackFromDirty: auto-commit failed for worktree "${worktreePath}" branch "${branchName}": ${commitResult.reason}`)}if(!sourceWorktreeMissing){let cleanResult=await cleanUntrackedFiles(worktreePath);if(cleanResult.cleaned)cleaned=!0;else cleanFailed=!0,log(`[worktree] attemptMergeBackFromDirty: clean untracked failed for worktree "${worktreePath}" branch "${branchName}": ${cleanResult.error}`)}if(autoCommitFailed&&cleanFailed)if((await runGit3(["rev-parse","--git-dir"],worktreePath)).spawnFailure?.kind==="cwd-missing"){let unrecoverable=await handleSourceWorktreeGone(await readLaneBranchHead(branchName,primaryDir),worktreePath,branchName,primaryDir,provenance);if(unrecoverable)return unrecoverable;sourceWorktreeMissing=!0,autoCommitFailed=!1,cleanFailed=!1,cleaned=!1}else return{failed:!0,stage:"cleanup",message:"Auto-commit and clean both failed; abandoning worktree",...provenance?{provenance}:{}};let initialOverlapSnapshot=await _internals35.captureMergeOverlapSnapshot(primaryDir,branchName);if("error"in initialOverlapSnapshot)return{failed:!0,stage:"pre-merge",message:initialOverlapSnapshot.error,...provenance?{provenance}:{}};if(!provenance&&(options.operationId||options.onBeforeMerge)){if(!options.operationId)return{failed:!0,stage:"pre-merge",message:"A pre-merge callback requires a stable operationId"};if(provenance={operationId:options.operationId,sourceHead:initialOverlapSnapshot.snapshot.laneHead,targetHeadBefore:initialOverlapSnapshot.snapshot.targetHead,branchName,strategy},options.onBeforeMerge)try{await options.onBeforeMerge(provenance)}catch(error49){return{failed:!0,stage:"pre-merge",message:`Unable to persist merge operation provenance: ${String(error49)}`,provenance}}}let finalOverlapSnapshot=await _internals35.captureMergeOverlapSnapshot(primaryDir,branchName);if("error"in finalOverlapSnapshot)return{failed:!0,stage:"pre-merge",message:finalOverlapSnapshot.error,...provenance?{provenance}:{}};if(finalOverlapSnapshot.snapshot.overlapPaths.length>0)return{partial:!0,stage:"pre-merge-overlap",autoCommitted,cleaned,message:`Primary checkout has overlapping dirty paths with incoming lane changes: ${finalOverlapSnapshot.snapshot.overlapPaths.join(", ")}`,conflictFiles:finalOverlapSnapshot.snapshot.overlapPaths,code:"SETTLEMENT_OVERLAP_BLOCKED",recoveryHint:`ACTION: commit or stash your local changes to the overlapping paths (or run /swarm recover for the preserved lane), then re-dispatch the lane. Overlapping paths: ${finalOverlapSnapshot.snapshot.overlapPaths.join(", ")}`,...provenance?{provenance}:{}};if(!sameOverlapSnapshot(initialOverlapSnapshot.snapshot,finalOverlapSnapshot.snapshot))return{failed:!0,stage:"pre-merge",message:"Primary or lane state changed during overlap preflight; refusing merge-back",...provenance?{provenance}:{}};let landingStrategy=strategy==="merge"&&!options.commitLanding?"squash-unstaged":strategy,mergeResult=await mergeLaneBranch(primaryDir,branchName,landingStrategy);if("merged"in mergeResult&&mergeResult.merged)return{merged:!0,strategy:landingStrategy,autoCommitted,cleaned,...provenance?{reconciled:!1,provenance}:{}};if("conflict"in mergeResult)return{partial:!0,stage:"merge",autoCommitted,cleaned,message:mergeResult.message,conflictFiles:mergeResult.files,...provenance?{provenance}:{}};if("error"in mergeResult)return{failed:!0,stage:"merge",message:mergeResult.error,...provenance?{provenance}:{}};return{failed:!0,stage:"merge",message:"Merge failed with unexpected result",...provenance?{provenance}:{}}}function extractSessionId(branchName){let segments=branchName.trim().split("/");if(segments.length>=3&&segments[0]==="swarm-lane")return segments[1];if(segments.length>=4&&segments[0]==="swarm"&&segments[1]==="lane")return segments[2];return null}async function listLaneBranches(directory){let branches=new Set,result=await runGit3(["branch","--format=%(refname:short)"],directory);if(result.exitCode===0)for(let line of result.stdout.split(`
|
|
634
634
|
`)){let branch=line.trim();if(branch.length>0&&(branch.startsWith("swarm-lane/")||branch.startsWith("swarm/lane/")))branches.add(branch)}return[...branches]}async function cleanupOrphanedBranches(directory,activeSessionIds=[],options={}){let removed=[],skipped=[],skippedRecoveryBranches=[],errors3=[];if(recoveryReadErrored(directory)){log("[worktree] cleanupOrphanedBranches: .swarm/recovery/ read error — skipping all "+"lane-branch deletions this pass (fail-safe for preserved recovery branches).");let branches2=await listLaneBranches(directory);return{removed,skipped:branches2,skippedRecoveryBranches,errors:errors3,recoveryReadError:!0}}let branches=await listLaneBranches(directory);await runGit3(["worktree","prune"],directory);for(let branch of branches){let sessionId=extractSessionId(branch);if(sessionId!==null&&activeSessionIds.includes(sessionId)){skipped.push(branch);continue}if(hasRecoveryRecordForBranch(directory,branch)){skippedRecoveryBranches.push(branch);continue}let deleteResult=await runGit3(["branch",options.preserveUnmerged?"-d":"-D",branch],directory);if(deleteResult.exitCode===0)removed.push(branch);else errors3.push({branch,error:deleteResult.stderr.trim()||deleteResult.stdout.trim()})}return{removed,skipped,skippedRecoveryBranches,errors:errors3}}async function startupOrphanRecovery(directory,activeSessionIds=[]){let warnings=[],pruneResult=await runGit3(["worktree","prune"],directory);if(pruneResult.exitCode!==0)warnings.push(`git worktree prune failed: ${pruneResult.stderr.trim()||pruneResult.stdout.trim()}`);let allBranches=await listLaneBranches(directory),orphanBranches=[];for(let branch of allBranches){let sessionId=extractSessionId(branch);if(sessionId===null||!activeSessionIds.includes(sessionId))orphanBranches.push(branch),warnings.push(`Orphaned swarm-lane branch "${branch}" detected in "${directory}"`)}for(let warning of warnings)log(warning);return{prunedWorktrees:pruneResult.exitCode===0,remainingBranches:orphanBranches,warnings}}var _internals35,MERGE_TIMEOUT_MS=30000,GIT_SPAWN_FAILURE_EXIT_CODE2=1,SOURCE_WORKTREE_GONE_STAGE="source-worktree-gone",SOURCE_WORKTREE_UNCERTAIN_STAGE="source-worktree-uncertain",GIT_OBJECT_ID_PATTERN;var init_merge2=__esm(()=>{init_warning_buffer();init_recovery();init_utils();init_bun_compat();init_git_binary_missing_error();init_git_executable();init_core3();_internals35={bunSpawn,platform:process.platform,sleep:(ms)=>new Promise((resolve21)=>setTimeout(resolve21,ms)),cleanupOrphanedBranches,startupOrphanRecovery,captureMergeOverlapSnapshot,extractSessionId,resolveGitExecutable};GIT_OBJECT_ID_PATTERN=/^[0-9a-f]{40}$|^[0-9a-f]{64}$/});function isSafeGitBranchName(value){if(typeof value!=="string"||!BRANCH_NAME_PATTERN.test(value))return!1;if(value.includes("..")||value.endsWith("/")||value.endsWith("."))return!1;return!value.split("/").some((segment)=>segment.length===0||segment.startsWith(".")||segment.endsWith(".lock"))}function isSafeWorktreePath(value){return typeof value==="string"&&value.length>0&&value.length<=4096&&!value.startsWith("-")&&unsafePathTextReason(value)===null}function formatUnreadableMessage(code,filePath,detail,remediation){throw Error(`${code}: ${filePath} ${detail}. ${remediation}`)}function parseWalObject(raw,filePath,code,remediation){let parsed;try{parsed=JSON.parse(raw)}catch(error49){formatUnreadableMessage(code,filePath,`is not valid JSON (${error49 instanceof Error?error49.message:String(error49)})`,remediation)}if(typeof parsed!=="object"||parsed===null||Array.isArray(parsed))formatUnreadableMessage(code,filePath,"is not a JSON object",remediation);return parsed}function parseCoderSettlementWal(raw,filePath,expectedTaskId){let parsed=parseWalObject(raw,filePath,"CODER_SETTLEMENT_WAL_UNREADABLE","Preserve this file, reconcile the task lane, and only then move it aside."),context=parsed.context,baseline=context?.baseline,worktree=parsed.worktree,provenance=parsed.mergeProvenance;if(parsed.version!==1||!["ABORTED","COMMITTED","DISPATCHED","PREPARED"].includes(String(parsed.state))||typeof parsed.taskId!=="string"||!TASK_ID_PATTERN.test(parsed.taskId)||typeof parsed.transitionId!=="string"||parsed.transitionId.length===0||parsed.transitionId.length>512||typeof parsed.actor!=="string"||parsed.actor.length===0||parsed.actor.length>512||!Number.isInteger(parsed.processId)||(parsed.processId??0)<=0||typeof parsed.runtimeId!=="string"||parsed.runtimeId.length===0||!Number.isInteger(parsed.expectedGeneration)||(parsed.expectedGeneration??-1)<0||!context||!baseline||typeof baseline.directory!=="string"||baseline.directory.length===0||baseline.directory.length>4096||typeof baseline.gitHead!=="string"&&baseline.gitHead!==null||typeof baseline.dirtyHash!=="string"&&baseline.dirtyHash!==null||typeof baseline.prHeadSha!=="string"&&baseline.prHeadSha!==null||typeof baseline.scope!=="string"&&baseline.scope!==null||!Array.isArray(baseline.changedFiles)&&baseline.changedFiles!==null&&baseline.changedFiles!==void 0||Array.isArray(baseline.changedFiles)&&(baseline.changedFiles.length>50000||baseline.changedFiles.some((candidatePath)=>typeof candidatePath!=="string"||candidatePath.length>4096))||!Array.isArray(context.declaredFiles)&&context.declaredFiles!==null||Array.isArray(context.declaredFiles)&&(context.declaredFiles.length>50000||context.declaredFiles.some((candidatePath)=>typeof candidatePath!=="string"||candidatePath.length>4096))||parsed.observedFiles!==void 0&&(!Array.isArray(parsed.observedFiles)||parsed.observedFiles.length>50000||parsed.observedFiles.some((candidatePath)=>typeof candidatePath!=="string"||candidatePath.length>4096||Array.isArray(context.declaredFiles)&&context.declaredFiles.length>0&&!isPathWithinDeclaredScope(candidatePath,context.declaredFiles,baseline.directory)))||worktree!==void 0&&(typeof worktree.callID!=="string"||typeof worktree.parentSessionId!=="string"||typeof worktree.taskId!=="string"||worktree.taskId!==parsed.taskId||!isSafeWorktreePath(worktree.worktreePath)||!isSafeGitBranchName(worktree.branchName)||typeof worktree.worktreeId!=="string"||typeof worktree.worktreeSessionId!=="string"||!["merge","rebase","cherry-pick"].includes(String(worktree.mergeStrategy))||!Number.isInteger(worktree.laneIndex))||provenance!==void 0&&(typeof provenance.operationId!=="string"||provenance.operationId!==parsed.transitionId||typeof provenance.sourceHead!=="string"||!GIT_OBJECT_ID_PATTERN.test(provenance.sourceHead)||typeof provenance.targetHeadBefore!=="string"||!GIT_OBJECT_ID_PATTERN.test(provenance.targetHeadBefore)||!isSafeGitBranchName(provenance.branchName)||worktree!==void 0&&(provenance.branchName!==worktree.branchName||provenance.strategy!==worktree.mergeStrategy)||!["merge","rebase","cherry-pick"].includes(String(provenance.strategy)))||typeof parsed.recordedAt!=="string"||parsed.state==="PREPARED"&&typeof parsed.accepted!=="boolean"||parsed.cleanupComplete!==void 0&&typeof parsed.cleanupComplete!=="boolean"||parsed.settlementFailed!==void 0&&typeof parsed.settlementFailed!=="boolean"||parsed.abortReason!==void 0&&(typeof parsed.abortReason!=="string"||parsed.abortReason.length===0||parsed.abortReason.length>512))formatUnreadableMessage("CODER_SETTLEMENT_WAL_UNREADABLE",filePath,"is not a valid v1 coder-settlement WAL","Preserve this file, reconcile the task lane, and only then move it aside.");if(expectedTaskId&&parsed.taskId!==expectedTaskId)formatUnreadableMessage("CODER_SETTLEMENT_WAL_TASK_MISMATCH",filePath,`records task ${parsed.taskId} but was read for task ${expectedTaskId}`,"Preserve this file, reconcile the task lane, and only then move it aside.");return parsed}function parseTaskRepairWal(raw,filePath,expectedTaskId){let parsed=parseWalObject(raw,filePath,"TASK_REPAIR_WAL_UNREADABLE","Preserve this file, reconcile the repair transition, and only then move it aside.");if(parsed.version!==1||parsed.state!=="PREPARED"&&parsed.state!=="COMMITTED"&&parsed.state!=="ABORTED"||typeof parsed.taskId!=="string"||!TASK_ID_PATTERN.test(parsed.taskId)||typeof parsed.transitionId!=="string"||parsed.transitionId.length===0||parsed.transitionId.length>512||typeof parsed.reason!=="string"||parsed.reason.length===0||parsed.reason.length>4096||typeof parsed.actor!=="string"||parsed.actor.length===0||parsed.actor.length>512||typeof parsed.oldPlanStatus!=="string"||parsed.oldPlanStatus.length===0||parsed.oldPlanStatus.length>128||parsed.newPlanStatus!=="in_progress"||typeof parsed.oldWorkflowState!=="string"||!WORKFLOW_STATES.has(parsed.oldWorkflowState)||parsed.newWorkflowState!=="idle"||!Number.isInteger(parsed.generation)||(parsed.generation??-1)<0||!Number.isInteger(parsed.oldGeneration)||(parsed.oldGeneration??-1)<0||parsed.generation!==(parsed.oldGeneration??-1)+1||typeof parsed.recordedAt!=="string"||!Number.isFinite(Date.parse(parsed.recordedAt)))formatUnreadableMessage("TASK_REPAIR_WAL_UNREADABLE",filePath,"is not a valid v1 repair WAL (unexpected shape or version)","Preserve this file, reconcile the repair transition, and only then move it aside.");if(expectedTaskId&&parsed.taskId!==expectedTaskId)formatUnreadableMessage("TASK_REPAIR_WAL_TASK_MISMATCH",filePath,`records task ${parsed.taskId} but was read for task ${expectedTaskId}`,"Preserve this file, reconcile the repair transition, and only then move it aside.");return parsed}function parseTaskTerminalWal(raw,filePath,expectedTaskId){let parsed=parseWalObject(raw,filePath,"TASK_TERMINAL_WAL_UNREADABLE","Preserve this file and reconcile the task terminal transition before moving it aside.");if(parsed.version!==1&&parsed.version!==2||parsed.state!=="PREPARED"&&parsed.state!=="COMMITTED"&&parsed.state!=="ABORTED"||typeof parsed.taskId!=="string"||!TASK_ID_PATTERN.test(parsed.taskId)||typeof parsed.transitionId!=="string"||parsed.transitionId.length===0||parsed.transitionId.length>512||typeof parsed.actor!=="string"||parsed.actor.length===0||parsed.actor.length>512||typeof parsed.oldPlanStatus!=="string"||parsed.oldPlanStatus.length===0||parsed.oldPlanStatus.length>128||parsed.newPlanStatus!=="completed"&&parsed.newPlanStatus!=="blocked"&&parsed.newPlanStatus!=="closed"||typeof parsed.oldWorkflowState!=="string"||!WORKFLOW_STATES.has(parsed.oldWorkflowState)||parsed.newWorkflowState!=="complete"&&parsed.newWorkflowState!=="blocked"&&parsed.newWorkflowState!=="closed"||!Number.isInteger(parsed.generation)||(parsed.generation??-1)<0||typeof parsed.qaExempt!=="boolean"||parsed.readOnlyNoMutation!==void 0&&typeof parsed.readOnlyNoMutation!=="boolean"||typeof parsed.recordedAt!=="string"||!Number.isFinite(Date.parse(parsed.recordedAt)))formatUnreadableMessage("TASK_TERMINAL_WAL_UNREADABLE",filePath,"is not a valid terminal WAL","Preserve this file and reconcile the task terminal transition before moving it aside.");if(parsed.version===2&&(typeof parsed.planIdentityHash!=="string"||!SHA256_PATTERN.test(parsed.planIdentityHash)||typeof parsed.planEpoch!=="string"||!UUID_PATTERN.test(parsed.planEpoch)))formatUnreadableMessage("TASK_TERMINAL_WAL_UNREADABLE",filePath,"is missing the v2 plan identity fields","Preserve this file and reconcile the task terminal transition before moving it aside.");if(parsed.version===1&&(parsed.newPlanStatus==="closed"||parsed.newWorkflowState==="closed"))formatUnreadableMessage("TASK_TERMINAL_WAL_UNREADABLE",filePath,"claims a closed transition in a legacy v1 terminal WAL","Preserve this file and reconcile the task terminal transition before moving it aside.");if(parsed.readOnlyNoMutation===!0&&(parsed.newPlanStatus!=="completed"||parsed.newWorkflowState!=="complete"||parsed.generation!==0||parsed.qaExempt!==!1))throw Error(`TASK_TERMINAL_WAL_STATE_MISMATCH: ${filePath} claims read-only no-mutation completion outside generation 0`);if(!(parsed.newPlanStatus==="completed"&&parsed.newWorkflowState==="complete"||parsed.newPlanStatus==="blocked"&&parsed.newWorkflowState==="blocked"||parsed.newPlanStatus==="closed"&&parsed.newWorkflowState==="closed"))throw Error(`TASK_TERMINAL_WAL_STATE_MISMATCH: ${filePath} encodes ${String(parsed.newPlanStatus)} -> ${String(parsed.newWorkflowState)}`);if(expectedTaskId&&parsed.taskId!==expectedTaskId)formatUnreadableMessage("TASK_TERMINAL_WAL_TASK_MISMATCH",filePath,`records task ${parsed.taskId} but was read for task ${expectedTaskId}`,"Preserve this file and reconcile the task terminal transition before moving it aside.");return parsed}var TASK_ID_PATTERN,SHA256_PATTERN,BRANCH_NAME_PATTERN,UUID_PATTERN,WORKFLOW_STATES;var init_workflow_wal_schema=__esm(()=>{init_path_identity();init_merge2();TASK_ID_PATTERN=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,SHA256_PATTERN=/^[0-9a-f]{64}$/,BRANCH_NAME_PATTERN=/^[A-Za-z0-9_][A-Za-z0-9._/-]{0,1023}$/;UUID_PATTERN=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,WORKFLOW_STATES=new Set(["idle","coder_delegated","pre_check_passed","reviewer_run","tests_run","rework_required","complete","blocked","closed"])});import*as fs22 from"node:fs";import{mkdir as mkdir8,open as open3}from"node:fs/promises";import{dirname as dirname18}from"node:path";function maxBytesFor(kind){return kind==="coder-settlement"?CODER_SETTLEMENT_MAX_BYTES:SMALL_WORKFLOW_WAL_MAX_BYTES}function remediationFor(kind){switch(kind){case"coder-settlement":return"Preserve this file, reconcile the task lane, and only then move it aside.";case"task-repair":return"Preserve this file, reconcile the repair transition, and only then move it aside.";case"task-terminal":return"Preserve this file and reconcile the task terminal transition before moving it aside."}}function unreadableCode(kind){switch(kind){case"coder-settlement":return"CODER_SETTLEMENT_WAL_UNREADABLE";case"task-repair":return"TASK_REPAIR_WAL_UNREADABLE";case"task-terminal":return"TASK_TERMINAL_WAL_UNREADABLE"}}function walIoError(kind,filePath,action,error49){let detail=error49 instanceof Error?error49.message:String(error49);return Error(`${unreadableCode(kind)}: could not ${action} ${filePath} (${detail}). ${remediationFor(kind)}`,{cause:error49})}function oversizeCode(kind){switch(kind){case"coder-settlement":return"CODER_SETTLEMENT_WAL_OVERSIZE";case"task-repair":return"TASK_REPAIR_WAL_OVERSIZE";case"task-terminal":return"TASK_TERMINAL_WAL_OVERSIZE"}}function oversizeMessage(kind,filePath,maxBytes){if(kind==="coder-settlement")throw Error(`${oversizeCode(kind)}: ${filePath} exceeds the 64 MiB safety limit. Preserve this file, reconcile the lane, reduce or partition the declared scope, and only then move the WAL aside.`);throw Error(`${oversizeCode(kind)}: ${filePath} exceeds the ${maxBytes} byte safety limit. ${remediationFor(kind)}`)}function decodeUtf8(kind,filePath,bytes){try{return UTF8_FATAL_DECODER.decode(bytes)}catch(error49){throw Error(`${unreadableCode(kind)}: ${filePath} is not valid UTF-8 (${error49 instanceof Error?error49.message:String(error49)}). ${remediationFor(kind)}`)}}function validateWal(kind,raw,filePath,expectedTaskId){switch(kind){case"coder-settlement":return parseCoderSettlementWal(raw,filePath,expectedTaskId);case"task-repair":return parseTaskRepairWal(raw,filePath,expectedTaskId);case"task-terminal":return parseTaskTerminalWal(raw,filePath,expectedTaskId)}}async function readBoundedBytes(kind,filePath,maxBytes){let handle;try{handle=await _internals36.openFile(filePath,"r")}catch(error49){if(error49.code==="ENOENT")return null;throw walIoError(kind,filePath,"open",error49)}let result=new Uint8Array,failure=null;try{let limit=maxBytes+1,chunks=[],total=0;while(!0){let remaining=limit-total;if(remaining<=0)break;let buffer=Buffer.alloc(Math.min(CHUNK_BYTES,remaining)),{bytesRead}=await handle.read(buffer,0,buffer.length,null);if(bytesRead===0)break;if(total+=bytesRead,chunks.push(buffer.subarray(0,bytesRead)),total>maxBytes)break}result=Buffer.concat(chunks,total)}catch(error49){failure=walIoError(kind,filePath,"read",error49)}try{await handle.close()}catch(error49){failure??=walIoError(kind,filePath,"close",error49)}if(failure)throw failure;return result}function readBoundedBytesSync(kind,filePath,maxBytes){let fd;try{fd=_internals36.openFileSync(filePath,"r")}catch(error49){if(error49.code==="ENOENT")return null;throw walIoError(kind,filePath,"open",error49)}let result=new Uint8Array,failure=null;try{let limit=maxBytes+1,chunks=[],total=0;while(!0){let remaining=limit-total;if(remaining<=0)break;let buffer=Buffer.alloc(Math.min(CHUNK_BYTES,remaining)),bytesRead=_internals36.readFileSync(fd,buffer,0,buffer.length,null);if(bytesRead===0)break;if(total+=bytesRead,chunks.push(buffer.subarray(0,bytesRead)),total>maxBytes)break}result=Buffer.concat(chunks,total)}catch(error49){failure=walIoError(kind,filePath,"read",error49)}try{_internals36.closeFileSync(fd)}catch(error49){failure??=walIoError(kind,filePath,"close",error49)}if(failure)throw failure;return result}async function readWorkflowWalFile(kind,filePath,expectedTaskId){let maxBytes=maxBytesFor(kind),bytes=await readBoundedBytes(kind,filePath,maxBytes);if(bytes===null)return null;if(bytes.length===0)throw Error(`${unreadableCode(kind)}: ${filePath} is empty. ${remediationFor(kind)}`);if(bytes.length>maxBytes)oversizeMessage(kind,filePath,maxBytes);return validateWal(kind,decodeUtf8(kind,filePath,bytes),filePath,expectedTaskId)}function readWorkflowWalFileSync(kind,filePath,expectedTaskId){let maxBytes=maxBytesFor(kind),bytes=readBoundedBytesSync(kind,filePath,maxBytes);if(bytes===null)return null;if(bytes.length===0)throw Error(`${unreadableCode(kind)}: ${filePath} is empty. ${remediationFor(kind)}`);if(bytes.length>maxBytes)oversizeMessage(kind,filePath,maxBytes);return validateWal(kind,decodeUtf8(kind,filePath,bytes),filePath,expectedTaskId)}async function writeWorkflowWalFile(kind,filePath,wal){let serialized=`${JSON.stringify(wal,null,2)}
|
|
635
|
-
`,maxBytes=maxBytesFor(kind);if(Buffer.byteLength(serialized,"utf8")>maxBytes)oversizeMessage(kind,filePath,maxBytes);validateWal(kind,serialized,filePath,wal.taskId),await mkdir8(dirname18(filePath),{recursive:!0}),await atomicWriteFile(filePath,serialized)}var UTF8_FATAL_DECODER,CODER_SETTLEMENT_MAX_BYTES=67108864,SMALL_WORKFLOW_WAL_MAX_BYTES=1048576,CHUNK_BYTES=65536,_internals36;var init_workflow_wal_file=__esm(()=>{init_task_file();init_workflow_wal_schema();UTF8_FATAL_DECODER=new TextDecoder("utf-8",{fatal:!0}),_internals36={openFile:open3,openFileSync:fs22.openSync,readFileSync:fs22.readSync,closeFileSync:fs22.closeSync}});var exports_gate_evidence={};__export(exports_gate_evidence,{withTaskEvidenceTransaction:()=>withTaskEvidenceTransaction,transitionTaskWorkflowEvidenceWithStatus:()=>transitionTaskWorkflowEvidenceWithStatus,transitionTaskWorkflowEvidence:()=>transitionTaskWorkflowEvidence,reduceTaskWorkflowSnapshot:()=>reduceTaskWorkflowSnapshot,recordGateEvidence:()=>recordGateEvidence,recordAgentDispatch:()=>recordAgentDispatch,readTaskEvidenceState:()=>readTaskEvidenceState,readTaskEvidenceRaw:()=>readTaskEvidenceRaw,readTaskEvidence:()=>readTaskEvidence,readCurrentTaskDeclaredFiles:()=>readCurrentTaskDeclaredFiles,parseTaskEvidence:()=>parseTaskEvidence,isValidTaskId:()=>isValidTaskId,isReadOnlyNoMutationEligible:()=>isReadOnlyNoMutationEligible,hasPassedAllGates:()=>hasPassedAllGates,getTaskWorkflowSnapshot:()=>getTaskWorkflowSnapshot,expandRequiredGates:()=>expandRequiredGates,ensureTaskGateRequirementsReceiptForSettledTransition:()=>ensureTaskGateRequirementsReceiptForSettledTransition,deriveRequiredGates:()=>deriveRequiredGates,deriveApplicableGateSet:()=>deriveApplicableGateSet,compareTaskWorkflowStateRank:()=>compareTaskWorkflowStateRank,assertTaskEvidenceWriteAllowed:()=>assertTaskEvidenceWriteAllowed,_internals:()=>_internals37,TASK_WORKFLOW_SCHEMA_MARKER:()=>TASK_WORKFLOW_SCHEMA_MARKER,TASK_GATE_REQUIREMENTS_RECONSTRUCTION_SENTINEL:()=>TASK_GATE_REQUIREMENTS_RECONSTRUCTION_SENTINEL,DEFAULT_REQUIRED_GATES:()=>DEFAULT_REQUIRED_GATES});import{mkdirSync as mkdirSync15,readFileSync as readFileSync13,realpathSync as realpathSync9,statSync as statSync13}from"node:fs";import*as path38 from"node:path";function readCurrentTaskDeclaredFiles(directory,taskId){try{let planPath=validateSwarmPath(directory,"plan.json"),stat7=statSync13(planPath);if(!stat7.isFile()||stat7.size>MAX_PLAN_SCOPE_INSPECTION_BYTES)return null;let parsed=JSON.parse(readFileSync13(planPath,"utf8"));if(!Array.isArray(parsed.phases))return null;let declaredFiles=null;for(let phase of parsed.phases){if(!phase||typeof phase!=="object")return null;let tasks=phase.tasks;if(!Array.isArray(tasks))return null;for(let task of tasks){if(!task||typeof task!=="object")return null;let record2=task;if(record2.id!==taskId)continue;if(!Array.isArray(record2.files_touched)||!record2.files_touched.every((file2)=>typeof file2==="string"))return null;if(declaredFiles!==null)return null;declaredFiles=[...record2.files_touched]}}return declaredFiles}catch{return null}}function assertTaskEvidenceWriteAllowed(directory,taskId,event){assertValidTaskId(taskId);let coderWalPath=validateSwarmPath(directory,`coder-settlements/${taskId}.json`),coderWal=readWorkflowWalFileSync("coder-settlement",coderWalPath,taskId);if((coderWal?.state==="DISPATCHED"||coderWal?.state==="PREPARED")&&!(event!=null&&event.transitionId===coderWal.transitionId&&(event.type==="dispatch_attempted"||event.type==="dispatch_no_mutation"||event.type==="accepted_mutation")))throw Error(`CODER_SETTLEMENT_IN_PROGRESS: transition ${String(coderWal.transitionId)} owns evidence for task ${taskId}. Wait for the owning transition to settle or run /swarm recover ${taskId} (or /swarm reset-session), then retry; do not remove the WAL by hand.`);let terminalWalPath=validateSwarmPath(directory,`task-terminals/${taskId}.json`),terminalWal=readWorkflowWalFileSync("task-terminal",terminalWalPath,taskId);if(terminalWal?.state==="PREPARED"){if(!(event!=null&&event.transitionId===terminalWal.transitionId&&(event.type==="task_completed"&&terminalWal.newPlanStatus==="completed"||event.type==="task_blocked"&&terminalWal.newPlanStatus==="blocked"||event.type==="task_closed"&&terminalWal.newPlanStatus==="closed")))throw Error(`TASK_TERMINAL_PREPARED: transition ${String(terminalWal.transitionId)} owns evidence for task ${taskId}`)}let repairWalPath=validateSwarmPath(directory,`task-repairs/${taskId}.json`),repairWal=readWorkflowWalFileSync("task-repair",repairWalPath,taskId);if(repairWal?.state==="PREPARED"&&!(event?.type==="repair_idle"&&event.transitionId===repairWal.transitionId))throw Error(`TASK_REPAIR_PREPARED: transition ${String(repairWal.transitionId)} owns evidence for task ${taskId}`)}function parseTaskEvidence(raw,expectedTaskId){let parsed=TaskEvidenceSchema.parse(JSON.parse(raw));if(parsed.taskId!==expectedTaskId)throw Error(`TASK_EVIDENCE_IDENTITY_MISMATCH: expected ${expectedTaskId}, found ${parsed.taskId}`);return parsed}function isValidTaskId(taskId){return isStrictTaskId(taskId)}function assertValidTaskId(taskId){assertStrictTaskId(taskId)}function createDefaultWorkflowMetadata(nowIso2){return{schema:TASK_WORKFLOW_SCHEMA_MARKER,generation:0,state:DEFAULT_WORKFLOW_STATE,retryCount:0,retryHistory:[],retryEpoch:0,lastOutcome:"none",lastTransitionId:null,updatedAt:nowIso2}}function getEventOutcome(event){switch(event.type){case"dispatch_attempted":return"dispatch_attempted";case"dispatch_no_mutation":return"dispatch_no_mutation";case"accepted_mutation":return event.context?.settlementFailed===!0?"accepted_mutation_failed":"accepted_mutation";case"stage_a_passed":return"stage_a_passed";case"stage_a_failed":return"stage_a_failed";case"stage_b_completed":return"stage_b_completed";case"stage_b_failed":return"stage_b_failed";case"gate_recorded":return"gate_recorded";case"task_completed":return"task_completed";case"task_blocked":return"task_blocked";case"task_closed":return"task_closed";case"repair_idle":return"repair_idle"}}function isAuthoritativeWorkflowMetadata(workflow){return workflow?.schema===TASK_WORKFLOW_SCHEMA_MARKER}function getTaskWorkflowSnapshot(evidence){if(isAuthoritativeWorkflowMetadata(evidence?.workflow))return{...evidence.workflow,authoritative:!0};return{...createDefaultWorkflowMetadata(""),authoritative:!1}}function maybeExpandRequiredGates(existing,event){if(event.type==="accepted_mutation"){let agentType=event.agentType;if(typeof agentType==="string"&&agentType.trim()!=="")return existing?expandRequiredGates(existing.required_gates.filter((gate)=>gate!==TASK_GATE_REQUIREMENTS_RECONSTRUCTION_SENTINEL),agentType,event.context??{}):deriveRequiredGates(agentType,event.context??{})}if(event.type==="stage_b_completed"&&event.ensureDefaultStageB===!0)return expandRequiredGates(existing?.required_gates??[],"coder",{testEngineerExempt:!1});if(event.type==="stage_b_completed"||event.type==="gate_recorded")return existing?expandRequiredGates(existing.required_gates,event.gate):deriveRequiredGates(event.gate);return existing?.required_gates??[]}function hasAllRequiredGatesPassed(requiredGates,gates){return requiredGates.length>0&&requiredGates.every((gate)=>gates[gate]!=null)}function shouldTreatGateAsStageB(gate){return gate==="reviewer"||gate==="test_engineer"}function clearWorkflowGateProof(gates){let retained={...gates};return delete retained.pre_check,delete retained.reviewer,delete retained.test_engineer,delete retained.council,delete retained.critic,delete retained.critic_sounding_board,retained}function assertExpectedGeneration(snapshot,event){if(typeof event.expectedGeneration==="number"&&event.expectedGeneration!==snapshot.generation)throw Error(`TASK_WORKFLOW_GENERATION_MISMATCH: expected ${event.expectedGeneration}, current ${snapshot.generation}`)}function isDuplicateTransition(snapshot,event){if(event.type==="dispatch_no_mutation"&&event.context?.declaredFiles?.length===0&&event.context.settlementTransitionId===event.transitionId&&!snapshot.noMutationSettlement)return!1;return snapshot.authoritative&&typeof event.transitionId==="string"&&event.transitionId.length>0&&snapshot.lastTransitionId===event.transitionId&&snapshot.lastOutcome===getEventOutcome(event)}function isNoMutationSettlementMetadata(workflow){let settlement=workflow.noMutationSettlement;if(!workflow.authoritative||workflow.generation!==0||settlement?.generation!==0||typeof settlement.transitionId!=="string"||settlement.transitionId.length===0||!Array.isArray(settlement.declaredFiles)||settlement.declaredFiles.length!==0)return!1;return workflow.state==="idle"||workflow.state==="complete"}function deriveApplicableGateSet(evidence,options){if(!evidence)return{requiredGates:["pre_check"],satisfiedGates:[],missingGates:["pre_check"],readOnlyNoMutation:!1};let workflow=getTaskWorkflowSnapshot(evidence),readOnlyNoMutation=isNoMutationSettlementMetadata(workflow)&&(options?.currentDeclaredFiles===void 0?!0:options.currentDeclaredFiles!==null&&options.currentDeclaredFiles.length===0),requiredGates=[...new Set(evidence.required_gates??[])];if(!readOnlyNoMutation&&!requiredGates.includes("pre_check"))requiredGates.unshift("pre_check");let satisfiedGates=requiredGates.filter((gate)=>evidence.gates?.[gate]!=null);return{requiredGates,satisfiedGates,missingGates:requiredGates.filter((gate)=>evidence.gates?.[gate]==null),readOnlyNoMutation}}function isReadOnlyNoMutationEligible(evidence,options){return deriveApplicableGateSet(evidence,options).readOnlyNoMutation}function reduceTaskWorkflowSnapshot(current,event,context){if((current.state==="complete"||current.state==="blocked"||current.state==="closed")&&event.type!=="repair_idle"&&!(current.state==="complete"&&event.type==="task_completed"||current.state==="blocked"&&event.type==="task_blocked"||current.state==="blocked"&&event.type==="task_closed"||current.state==="blocked"&&event.type==="stage_a_passed"&&event.settlementRecovery===!0))throw Error(`TASK_WORKFLOW_TERMINAL: cannot apply ${event.type} from ${current.state}`);let outcome=getEventOutcome(event),base={schema:TASK_WORKFLOW_SCHEMA_MARKER,generation:current.generation,state:current.state,retryCount:current.retryCount,retryHistory:current.retryHistory,retryEpoch:current.retryEpoch,lastOutcome:outcome,lastTransitionId:event.transitionId??current.lastTransitionId,updatedAt:context.nowIso,...current.forcedCompletion===!0?{forcedCompletion:!0}:{},...current.supervisedRecovery===!0?{supervisedRecovery:!0}:{},...current.settlementRecovery===!0?{settlementRecovery:!0}:{},...current.noMutationSettlement?{noMutationSettlement:current.noMutationSettlement}:{}};switch(event.type){case"dispatch_attempted":{let{noMutationSettlement:_clearedSettlement,...withoutSettlement}=base;return withoutSettlement}case"dispatch_no_mutation":{let{noMutationSettlement:_clearedSettlement,...withoutSettlement}=base;return{...withoutSettlement,retryCount:Math.min(current.retryCount+1,3),retryHistory:[...current.retryHistory,outcome].slice(-3),retryEpoch:current.retryEpoch||current.generation+1,...current.generation===0&&event.transitionId&&Array.isArray(event.context?.declaredFiles)&&event.context.declaredFiles.length===0&&event.context.settlementTransitionId===event.transitionId?{noMutationSettlement:{generation:0,transitionId:event.transitionId,declaredFiles:[]}}:{}}}case"stage_b_failed":if(current.state!=="pre_check_passed"&¤t.state!=="reviewer_run"&¤t.state!=="tests_run"&¤t.state!=="rework_required")throw Error(`TASK_WORKFLOW_STAGE_A_REQUIRED: cannot reject ${event.gate} from ${current.state}`);return{...base,state:"rework_required",retryCount:Math.min(current.retryCount+1,3),retryHistory:[...current.retryHistory,outcome].slice(-3),retryEpoch:current.retryEpoch||current.generation+1};case"accepted_mutation":{let{noMutationSettlement:_clearedSettlement,...withoutSettlement}=base;if(event.context?.settlementFailed===!0)return{...withoutSettlement,generation:current.generation+1,state:"rework_required",retryCount:Math.min(current.retryCount+1,3),retryHistory:[...current.retryHistory,outcome].slice(-3),retryEpoch:current.retryEpoch||current.generation+1,supervisedRecovery:void 0,settlementRecovery:void 0};return{...withoutSettlement,generation:current.generation+1,state:"coder_delegated",supervisedRecovery:void 0,settlementRecovery:void 0}}case"stage_a_passed":if(current.state!=="coder_delegated"&¤t.state!=="pre_check_passed"&&!(current.state==="rework_required"&&event.supervisedRecovery===!0)&&!(event.settlementRecovery===!0&&(current.state==="idle"||current.state==="blocked")))throw Error(`TASK_WORKFLOW_CODER_MUTATION_REQUIRED: cannot pass Stage A from ${current.state}`);return{...base,...event.supervisedRecovery===!0?{supervisedRecovery:!0}:{},...event.settlementRecovery===!0?{settlementRecovery:!0}:{},state:"pre_check_passed"};case"stage_a_failed":if(current.state!=="coder_delegated"&¤t.state!=="pre_check_passed"&¤t.state!=="rework_required")throw Error(`TASK_WORKFLOW_CODER_MUTATION_REQUIRED: cannot fail Stage A from ${current.state}`);return{...base,state:"rework_required",retryCount:Math.min(current.retryCount+1,3),retryHistory:[...current.retryHistory,outcome].slice(-3),retryEpoch:current.retryEpoch||current.generation+1};case"stage_b_completed":if(current.state!=="pre_check_passed"&¤t.state!=="reviewer_run"&¤t.state!=="tests_run")throw Error(`TASK_WORKFLOW_STAGE_A_REQUIRED: cannot record ${event.gate} from ${current.state}`);if(event.routeComplete===!1)return{...base,state:event.gate==="reviewer"||current.state==="reviewer_run"?"reviewer_run":current.state};if(event.routeComplete===!0)return{...base,state:"tests_run"};return{...base,state:hasAllRequiredGatesPassed(context.requiredGates,context.gates)?"tests_run":"reviewer_run"};case"gate_recorded":return{...base,state:current.state};case"task_completed":{let readOnlyNoMutation=event.readOnlyNoMutation===!0&¤t.state==="idle"&¤t.generation===0&&isNoMutationSettlementMetadata(current)&&context.requiredGates.every((gate)=>context.gates[gate]!=null);if(event.qaExempt!==!0&¤t.state!=="tests_run"&¤t.state!=="complete"&&!(current.state==="pre_check_passed"&&context.gates.council!=null)&&!readOnlyNoMutation)throw Error(`TASK_WORKFLOW_QA_REQUIRED: cannot complete from ${current.state}`);return{...base,state:"complete",...event.qaExempt===!0?{forcedCompletion:!0}:{}}}case"task_blocked":return{...base,state:"blocked"};case"task_closed":return{...base,state:"closed"};case"repair_idle":{let{forcedCompletion:_cleared,supervisedRecovery:_clearedMarker,settlementRecovery:_clearedSettlementMarker,noMutationSettlement:_clearedSettlement,...withoutForced}=base;return{...withoutForced,generation:current.generation+1,state:"idle",retryCount:0,retryHistory:[],retryEpoch:0}}}}function getEvidenceDir(directory){let swarmDir=path38.resolve(directory,".swarm"),evidenceDir=path38.join(swarmDir,"evidence");mkdirSync15(evidenceDir,{recursive:!0});let resolvedSwarmDir,resolvedEvidenceDir;try{resolvedSwarmDir=path38.normalize(realpathSync9(swarmDir)),resolvedEvidenceDir=path38.normalize(realpathSync9(evidenceDir))}catch(error49){throw Error(`Unable to resolve evidence directory: ${error49.message}`)}let swarmPrefix=`${resolvedSwarmDir}${path38.sep}`;if(!(process.platform==="win32"?resolvedEvidenceDir.toLowerCase().startsWith(swarmPrefix.toLowerCase()):resolvedEvidenceDir.startsWith(swarmPrefix)))throw Error(`Evidence path escapes .swarm boundary: ${resolvedEvidenceDir}`);return resolvedEvidenceDir}function getEvidencePath(directory,taskId){return assertValidTaskId(taskId),taskEvidencePath(directory,taskId)}function bindTrustedNoMutationSettlement(directory,taskId,event){if(event.type!=="dispatch_no_mutation")return event;let context=event.context;if(!context||event.transitionId===void 0)return{...event,context:void 0};try{let wal=readWorkflowWalFileSync("coder-settlement",validateSwarmPath(directory,`coder-settlements/${taskId}.json`),taskId),declaredFiles=wal?.context?.declaredFiles,trusted=wal!==null&&(wal.state==="PREPARED"||wal.state==="COMMITTED")&&wal.accepted===!1&&wal.transitionId===event.transitionId&&Array.isArray(declaredFiles)&&declaredFiles.length===0&&Array.isArray(context.declaredFiles)&&context.declaredFiles.length===0;return{...event,context:trusted?{...context,declaredFiles,settlementTransitionId:wal.transitionId}:{...context,settlementTransitionId:void 0}}}catch{return{...event,context:{...context,settlementTransitionId:void 0}}}}function readExisting(evidencePath,taskId){try{let raw=readFileSync13(evidencePath,"utf-8");return parseTaskEvidence(raw,taskId)}catch(error49){if(error49.code==="ENOENT")return null;throw telemetry.gateParseError(taskId,error49),error49}}function deriveRequiredGates(agentType,context={}){switch(agentType){case"coder":return context.testEngineerExempt===!0?["reviewer"]:["reviewer","test_engineer"];case"docs":return["docs"];case"designer":return["designer","reviewer","test_engineer"];case"explorer":return["explorer"];case"sme":return["sme"];case"reviewer":return["reviewer"];case"test_engineer":return["test_engineer"];case"critic":return["critic"];case"critic_sounding_board":return["critic_sounding_board"];case"critic_drift_verifier":return["critic_drift_verifier"];case"critic_hallucination_verifier":return["critic_hallucination_verifier"];case"critic_architecture_supervisor":return["critic_architecture_supervisor"];default:return["reviewer","test_engineer"]}}function expandRequiredGates(existingGates,newAgentType,context={}){let newGates=deriveRequiredGates(newAgentType,context);return[...new Set([...existingGates??[],...newGates])].sort()}function updateEvidenceForTransition(existing,event){let nowIso2=new Date().toISOString(),requiredGates=maybeExpandRequiredGates(existing,event),gates={...existing?.gates??{}};if(event.type==="accepted_mutation"||event.type==="repair_idle")gates=clearWorkflowGateProof(gates);if(event.type==="stage_a_passed")gates={...gates,pre_check:{sessionId:"system",timestamp:nowIso2,agent:"pre_check"}};if(event.type==="stage_a_failed")delete gates.pre_check;if(event.type==="stage_b_failed")delete gates.reviewer,delete gates.test_engineer;if(event.type==="stage_b_completed"||event.type==="gate_recorded")gates={...gates,[event.gate]:{sessionId:event.sessionId,timestamp:nowIso2,agent:event.gate}};let snapshot=getTaskWorkflowSnapshot(existing);if(assertExpectedGeneration(snapshot,event),isDuplicateTransition(snapshot,event)&&existing)return existing;let workflow=reduceTaskWorkflowSnapshot(snapshot,event,{requiredGates,gates,nowIso:nowIso2});return{taskId:existing?.taskId??"",required_gates:requiredGates,gates,turbo:"turbo"in event&&event.turbo===!0?!0:("turbo"in event)&&event.turbo===!1?existing?.turbo:existing?.turbo,test_engineer_exempt:(event.type==="dispatch_attempted"||event.type==="dispatch_no_mutation"||event.type==="accepted_mutation")&&event.agentType==="coder"?event.context?.testEngineerExempt===!0&&!requiredGates.includes("test_engineer"):existing?.test_engineer_exempt,workflow}}async function transitionTaskWorkflowEvidence(directory,taskId,event){let{evidence}=await transitionTaskWorkflowEvidenceWithStatus(directory,taskId,event);return evidence}async function transitionTaskWorkflowEvidenceWithStatus(directory,taskId,event){assertValidTaskId(taskId);let updatedEvidence=null,duplicated=!1;return await withTaskEvidenceTransaction(directory,taskId,event.type,async(transaction)=>{if(transaction.transitionWithStatus){let result=await transaction.transitionWithStatus(event);updatedEvidence=result.evidence,duplicated=result.duplicated;return}updatedEvidence=await transaction.transition(event)}),{evidence:updatedEvidence??{taskId,required_gates:[],gates:{},workflow:createDefaultWorkflowMetadata(new Date().toISOString())},duplicated}}async function withTaskEvidenceTransaction(directory,taskId,agent,callback){return assertValidTaskId(taskId),withTaskEvidenceLock(directory,taskId,agent,async()=>{let resolvedEvidenceDir=getEvidenceDir(directory),evidencePath=path38.join(resolvedEvidenceDir,`${taskId}.json`),current=null;try{current=readExisting(evidencePath,taskId)}catch(error49){throw telemetry.gateParseError(taskId,error49),error49}let persist=async(nextEvidence,event)=>{let validated=TaskEvidenceSchema.parse({...nextEvidence,taskId});if(await atomicWriteFile(evidencePath,JSON.stringify(validated,null,2)),event)await _internals37.appendTaskGateRequirementsReceiptIfNeeded(directory,taskId,current,validated,event);return current=validated,validated},transitionWithStatusImpl=async(event)=>{let boundEvent=bindTrustedNoMutationSettlement(directory,taskId,event);assertTaskEvidenceWriteAllowed(directory,taskId,boundEvent);let nextEvidence=updateEvidenceForTransition(current,boundEvent),duplicated=nextEvidence===current;return nextEvidence.taskId=taskId,{evidence:await persist(nextEvidence,boundEvent),duplicated}};return callback({taskId,read:()=>current,transition:async(event)=>{let{evidence}=await transitionWithStatusImpl(event);return evidence},transitionWithStatus:transitionWithStatusImpl})})}async function ensureTaskGateRequirementsReceiptForSettledTransition(directory,taskId,evidence,event){assertValidTaskId(taskId);let validated=TaskEvidenceSchema.parse({...evidence,taskId});await _internals37.appendTaskGateRequirementsReceiptIfNeeded(directory,taskId,null,validated,event)}async function recordGateEvidence(directory,taskId,gate,sessionId,turbo,options={}){if(assertValidTaskId(taskId),shouldTreatGateAsStageB(gate)&&typeof options.expectedGeneration!=="number")throw Error(`TASK_WORKFLOW_GENERATION_REQUIRED: ${gate} for task ${taskId} must be bound at dispatch`);await transitionTaskWorkflowEvidence(directory,taskId,shouldTreatGateAsStageB(gate)?{type:"stage_b_completed",gate,sessionId,routeBinding:options.routeBinding,routeComplete:options.routeComplete,turbo,ensureDefaultStageB:options.ensureDefaultStageB,expectedGeneration:options.expectedGeneration,transitionId:options.transitionId}:{type:"gate_recorded",gate,sessionId,turbo,expectedGeneration:options.expectedGeneration,transitionId:options.transitionId}),telemetry.gatePassed(sessionId,gate,taskId)}async function recordAgentDispatch(directory,taskId,agentType,turbo,context={}){assertValidTaskId(taskId);let expectedGeneration=getTaskWorkflowSnapshot(await readTaskEvidence(directory,taskId)).generation;await transitionTaskWorkflowEvidence(directory,taskId,agentType==="coder"?{type:"accepted_mutation",agentType,turbo,context,expectedGeneration}:{type:"dispatch_attempted",agentType,turbo,context,expectedGeneration})}async function readTaskEvidence(directory,taskId){let state2=await readTaskEvidenceState(directory,taskId);return state2.kind==="ok"?state2.evidence:null}async function readTaskEvidenceState(directory,taskId){try{assertValidTaskId(taskId)}catch{return{kind:"missing"}}try{let evidencePath=getEvidencePath(directory,taskId),raw=readFileSync13(evidencePath,"utf-8");return{kind:"ok",evidence:parseTaskEvidence(raw,taskId)}}catch(error49){let evidencePath=getEvidencePathSafe(directory,taskId),code=error49.code;if(code==="ENOENT"||code==="ENAMETOOLONG")return{kind:"missing"};return telemetry.gateParseError(taskId,error49),{kind:"unparseable",evidencePath,error:error49}}}function getEvidencePathSafe(directory,taskId){try{return getEvidencePath(directory,taskId)}catch{return`${directory}/.swarm/evidence/${taskId}.json`}}function readTaskEvidenceRaw(directory,taskId){assertValidTaskId(taskId);let evidencePath=getEvidencePath(directory,taskId);try{let raw=readFileSync13(evidencePath,"utf-8");return parseTaskEvidence(raw,taskId)}catch(error49){let code=error49.code;if(code==="ENOENT"||code==="ENAMETOOLONG")return null;throw error49}}async function hasPassedAllGates(directory,taskId,currentDeclaredFiles){let evidence=await readTaskEvidence(directory,taskId);if(!evidence)return!1;if(!Array.isArray(evidence.required_gates))return!1;if(currentDeclaredFiles===void 0){if(deriveApplicableGateSet(evidence).readOnlyNoMutation)return!1;return hasAllRequiredGatesPassed(evidence.required_gates,evidence.gates)}return deriveApplicableGateSet(evidence,{currentDeclaredFiles}).missingGates.length===0}function compareTaskWorkflowStateRank(left,right){return WORKFLOW_STATE_RANK[left]-WORKFLOW_STATE_RANK[right]}var _internals37,TASK_WORKFLOW_SCHEMA_MARKER="exact-task-v1",TASK_WORKFLOW_STATES,TASK_WORKFLOW_OUTCOMES,MAX_PLAN_SCOPE_INSPECTION_BYTES=4194304,TASK_GATE_REQUIREMENTS_RECONSTRUCTION_SENTINEL="requirements_reconstruction",GateEvidenceSchema,TaskWorkflowMetadataSchema,TaskEvidenceSchema,DEFAULT_REQUIRED_GATES,DEFAULT_WORKFLOW_STATE="idle",WORKFLOW_STATE_RANK;var init_gate_evidence=__esm(()=>{init_zod();init_task_file();init_task_gate_requirements();init_utils2();init_telemetry();init_task_id();init_workflow_wal_file();_internals37={appendTaskGateRequirementsReceiptIfNeeded},TASK_WORKFLOW_STATES=["idle","coder_delegated","pre_check_passed","reviewer_run","tests_run","rework_required","complete","blocked","closed"],TASK_WORKFLOW_OUTCOMES=["none","dispatch_attempted","dispatch_no_mutation","accepted_mutation","accepted_mutation_failed","stage_a_passed","stage_a_failed","stage_b_completed","stage_b_failed","gate_recorded","task_completed","task_blocked","task_closed","repair_idle"];GateEvidenceSchema=exports_external.object({sessionId:exports_external.string(),timestamp:exports_external.string(),agent:exports_external.string()}).passthrough(),TaskWorkflowMetadataSchema=exports_external.object({schema:exports_external.literal(TASK_WORKFLOW_SCHEMA_MARKER),generation:exports_external.number().int().min(0),state:exports_external.enum(TASK_WORKFLOW_STATES),retryCount:exports_external.number().int().min(0).default(0),retryHistory:exports_external.array(exports_external.enum(TASK_WORKFLOW_OUTCOMES)).max(3).default([]),retryEpoch:exports_external.number().int().min(0).default(0),lastOutcome:exports_external.enum(TASK_WORKFLOW_OUTCOMES).default("none"),lastTransitionId:exports_external.string().min(1).nullable().optional().default(null),updatedAt:exports_external.string(),forcedCompletion:exports_external.boolean().optional(),supervisedRecovery:exports_external.boolean().optional(),settlementRecovery:exports_external.boolean().optional(),noMutationSettlement:exports_external.object({generation:exports_external.literal(0),transitionId:exports_external.string().min(1).max(512),declaredFiles:exports_external.array(exports_external.string()).length(0)}).optional()}),TaskEvidenceSchema=exports_external.object({taskId:exports_external.string(),required_gates:exports_external.array(exports_external.string()).default([]),gates:exports_external.record(exports_external.string(),GateEvidenceSchema),turbo:exports_external.boolean().optional(),requirements_state:exports_external.enum(["known","unknown"]).optional(),test_engineer_exempt:exports_external.boolean().optional(),workflow:TaskWorkflowMetadataSchema.optional(),repair_provenance:exports_external.object({source_sha256:exports_external.string().regex(/^[a-f0-9]{64}$/).nullable(),source_generation:exports_external.number().int().min(0).nullable(),requirements_receipt_hash:exports_external.string().regex(/^[a-f0-9]{64}$/).nullable()}).optional()});DEFAULT_REQUIRED_GATES=["reviewer","test_engineer"],WORKFLOW_STATE_RANK={idle:0,coder_delegated:1,pre_check_passed:2,reviewer_run:3,tests_run:4,rework_required:5,blocked:6,closed:7,complete:8}});import*as path39 from"node:path";function normalizeCandidate(value){if(typeof value!=="string"||value.length===0)return null;if([...value].some((character)=>{let codePoint=character.codePointAt(0)??0;return codePoint<=31||codePoint===127}))return null;if(path39.win32.isAbsolute(value)||path39.posix.isAbsolute(value))return null;let normalized=value.replace(/\\/g,"/");if(normalized.split("/").some((segment)=>segment===""||segment==="."||segment===".."))return null;return normalized}function isExactMarkdownPath(value){let normalized=normalizeCandidate(value);return normalized!==null&&path39.posix.extname(normalized)===".md"}function isMarkdownOnlyDeclaredScope(value){return Array.isArray(value)&&value.length>0&&value.every(isExactMarkdownPath)}function isMarkdownOnlyTaskChange(declaredFiles,observedFiles){if(!Array.isArray(declaredFiles)||!Array.isArray(observedFiles))return!1;if(!isMarkdownOnlyDeclaredScope(declaredFiles)||observedFiles.length===0)return!1;if(!observedFiles.every(isExactMarkdownPath))return!1;let declared=new Set(declaredFiles.map(normalizeCandidate).filter((value)=>value!==null));return observedFiles.every((value)=>{let normalized=normalizeCandidate(value);return normalized!==null&&declared.has(normalized)})}var init_gate_evidence_classification=()=>{};import{createHash as createHash20}from"node:crypto";import*as fs23 from"node:fs";import*as path40 from"node:path";function ownerDirectory(directory){return path40.dirname(validateSwarmPath(directory,path40.join(PROVISIONING_OWNER_DIR,".containment-anchor")))}function ownerPath(directory,callID){let digest2=createHash20("sha256").update(callID).digest("hex");return validateSwarmPath(directory,path40.join(PROVISIONING_OWNER_DIR,`${digest2}.json`))}function journalPath(directory){return validateSwarmPath(directory,PROVISIONING_JOURNAL_PATH)}function isOwner(value){if(!value||typeof value!=="object"||Array.isArray(value))return!1;let candidate=value,schemaVersion=candidate.schemaVersion,validTaskIdentity=schemaVersion===1?candidate.taskId===void 0&&candidate.reservationId===void 0&&candidate.generation===void 0&&candidate.branchName===void 0:schemaVersion===2&&typeof candidate.taskId==="string"&&candidate.taskId.length>0&&candidate.taskId.length<=512&&candidate.reservationId===void 0&&candidate.generation===void 0&&candidate.branchName===void 0,validV3Identity=schemaVersion===3&&typeof candidate.taskId==="string"&&candidate.taskId.length>0&&candidate.taskId.length<=512&&typeof candidate.reservationId==="string"&&candidate.reservationId.length>0&&candidate.reservationId.length<=512&&typeof candidate.generation==="number"&&Number.isInteger(candidate.generation)&&candidate.generation>0&&typeof candidate.branchName==="string"&&candidate.branchName.length>0&&candidate.branchName.length<=1024;return(schemaVersion===1||schemaVersion===2||schemaVersion===3)&&(validTaskIdentity||validV3Identity)&&typeof candidate.callID==="string"&&candidate.callID.length>0&&candidate.callID.length<=512&&typeof candidate.parentSessionId==="string"&&candidate.parentSessionId.length>0&&candidate.parentSessionId.length<=512&&typeof candidate.worktreeSessionId==="string"&&candidate.worktreeSessionId.length>0&&candidate.worktreeSessionId.length<=512&&typeof candidate.createdAt==="number"&&Number.isFinite(candidate.createdAt)&&candidate.createdAt>=0}function isLifecycleEntry(value){if(!value||typeof value!=="object"||Array.isArray(value))return!1;let candidate=value,validState=WORKTREE_PROVISIONING_LIFECYCLE_STATES.includes(candidate.state);return candidate.schemaVersion===1&&validState&&typeof candidate.callID==="string"&&candidate.callID.length>0&&candidate.callID.length<=512&&typeof candidate.parentSessionId==="string"&&candidate.parentSessionId.length>0&&candidate.parentSessionId.length<=512&&typeof candidate.worktreeSessionId==="string"&&candidate.worktreeSessionId.length>0&&candidate.worktreeSessionId.length<=512&&(candidate.taskId===void 0||typeof candidate.taskId==="string"&&candidate.taskId.length>0&&candidate.taskId.length<=512)&&(candidate.reservationId===void 0||typeof candidate.reservationId==="string"&&candidate.reservationId.length>0&&candidate.reservationId.length<=512)&&(candidate.generation===void 0||typeof candidate.generation==="number"&&Number.isInteger(candidate.generation)&&candidate.generation>0)&&(candidate.branchName===void 0||typeof candidate.branchName==="string"&&candidate.branchName.length>0&&candidate.branchName.length<=1024)&&typeof candidate.recordedAt==="number"&&Number.isFinite(candidate.recordedAt)&&candidate.recordedAt>=0}function readBoundedJsonFile(filePath,maxBytes){try{if(fs23.statSync(filePath).size>maxBytes)return{ok:!1,reason:`${path40.basename(filePath)} exceeds the ${maxBytes}-byte safety bound`};let raw=fs23.readFileSync(filePath,"utf8");if(Buffer.byteLength(raw,"utf8")>maxBytes)return{ok:!1,reason:`${path40.basename(filePath)} changed beyond the ${maxBytes}-byte safety bound`};return{ok:!0,value:JSON.parse(raw)}}catch(error49){if(error49.code==="ENOENT")return{ok:!0,value:void 0};return{ok:!1,reason:`${path40.basename(filePath)} is unreadable or malformed: ${error49 instanceof Error?error49.message:String(error49)}`}}}function readOwner(directory,callID){let absolutePath=ownerPath(directory,callID),loaded=readBoundedJsonFile(absolutePath,MAX_PROVISIONING_OWNER_BYTES);if(!loaded.ok||loaded.value===void 0)return null;return isOwner(loaded.value)?loaded.value:null}function loadLifecycleJournal(directory){let loaded=readBoundedJsonFile(journalPath(directory),MAX_PROVISIONING_JOURNAL_BYTES);if(!loaded.ok)return{status:"uncertain",reason:loaded.reason};if(loaded.value===void 0)return{status:"ok",entries:[]};let parsed=loaded.value;if(parsed.schemaVersion!==1||!Array.isArray(parsed.entries))return{status:"uncertain",reason:"worktree provisioning lifecycle journal is malformed"};if(parsed.entries.length>MAX_PROVISIONING_JOURNAL_ENTRIES)return{status:"uncertain",reason:`worktree provisioning lifecycle journal exceeds the ${MAX_PROVISIONING_JOURNAL_ENTRIES}-entry safety bound`};let entries=[];for(let entry of parsed.entries){if(!isLifecycleEntry(entry))return{status:"uncertain",reason:"worktree provisioning lifecycle journal contains an invalid entry"};entries.push(entry)}return{status:"ok",entries}}function appendLifecycleEntry(directory,owner,state2){let loaded=loadLifecycleJournal(directory);if(loaded.status==="uncertain")throw Error(loaded.reason);let journal={schemaVersion:1,entries:[...loaded.entries,{schemaVersion:1,state:state2,callID:owner.callID,parentSessionId:owner.parentSessionId,worktreeSessionId:owner.worktreeSessionId,...owner.taskId?{taskId:owner.taskId}:{},...owner.reservationId?{reservationId:owner.reservationId}:{},...owner.generation!==void 0?{generation:owner.generation}:{},...owner.branchName?{branchName:owner.branchName}:{},recordedAt:Date.now()}].slice(-MAX_PROVISIONING_JOURNAL_ENTRIES)};atomicWriteSwarmFileSync(journalPath(directory),JSON.stringify(journal,null,2))}function recordWorktreeProvisioningOwner(directory,input){let wantsV3=input.reservationId!==void 0||input.generation!==void 0||input.branchName!==void 0;if(wantsV3&&(!input.taskId||!input.reservationId||input.generation===void 0||!input.branchName))throw Error("worktree provisioning owner v3 requires taskId, reservationId, generation, and branchName");let owner={schemaVersion:wantsV3?3:input.taskId?2:1,callID:input.callID,parentSessionId:input.parentSessionId,worktreeSessionId:input.worktreeSessionId,...input.taskId?{taskId:input.taskId}:{},...input.reservationId?{reservationId:input.reservationId}:{},...input.generation!==void 0?{generation:input.generation}:{},...input.branchName?{branchName:input.branchName}:{},createdAt:Date.now()};if(!isOwner(owner))throw Error("invalid worktree provisioning owner");let absolutePath=ownerPath(directory,input.callID);return fs23.mkdirSync(path40.dirname(absolutePath),{recursive:!0}),atomicWriteSwarmFileSync(absolutePath,`${JSON.stringify(owner)}
|
|
635
|
+
`,maxBytes=maxBytesFor(kind);if(Buffer.byteLength(serialized,"utf8")>maxBytes)oversizeMessage(kind,filePath,maxBytes);validateWal(kind,serialized,filePath,wal.taskId),await mkdir8(dirname18(filePath),{recursive:!0}),await atomicWriteFile(filePath,serialized)}var UTF8_FATAL_DECODER,CODER_SETTLEMENT_MAX_BYTES=67108864,SMALL_WORKFLOW_WAL_MAX_BYTES=1048576,CHUNK_BYTES=65536,_internals36;var init_workflow_wal_file=__esm(()=>{init_task_file();init_workflow_wal_schema();UTF8_FATAL_DECODER=new TextDecoder("utf-8",{fatal:!0}),_internals36={openFile:open3,openFileSync:fs22.openSync,readFileSync:fs22.readSync,closeFileSync:fs22.closeSync}});var exports_gate_evidence={};__export(exports_gate_evidence,{withTaskEvidenceTransaction:()=>withTaskEvidenceTransaction,transitionTaskWorkflowEvidenceWithStatus:()=>transitionTaskWorkflowEvidenceWithStatus,transitionTaskWorkflowEvidence:()=>transitionTaskWorkflowEvidence,reduceTaskWorkflowSnapshot:()=>reduceTaskWorkflowSnapshot,recordTodoScanEvidence:()=>recordTodoScanEvidence,recordGateEvidence:()=>recordGateEvidence,recordAgentDispatch:()=>recordAgentDispatch,readTaskEvidenceState:()=>readTaskEvidenceState,readTaskEvidenceRaw:()=>readTaskEvidenceRaw,readTaskEvidence:()=>readTaskEvidence,readCurrentTaskDeclaredFiles:()=>readCurrentTaskDeclaredFiles,parseTaskEvidence:()=>parseTaskEvidence,isValidTaskId:()=>isValidTaskId,isReadOnlyNoMutationEligible:()=>isReadOnlyNoMutationEligible,hasPassedAllGates:()=>hasPassedAllGates,getTaskWorkflowSnapshot:()=>getTaskWorkflowSnapshot,expandRequiredGates:()=>expandRequiredGates,ensureTaskGateRequirementsReceiptForSettledTransition:()=>ensureTaskGateRequirementsReceiptForSettledTransition,deriveRequiredGates:()=>deriveRequiredGates,deriveApplicableGateSet:()=>deriveApplicableGateSet,compareTaskWorkflowStateRank:()=>compareTaskWorkflowStateRank,assertTaskEvidenceWriteAllowed:()=>assertTaskEvidenceWriteAllowed,_internals:()=>_internals37,TASK_WORKFLOW_SCHEMA_MARKER:()=>TASK_WORKFLOW_SCHEMA_MARKER,TASK_GATE_REQUIREMENTS_RECONSTRUCTION_SENTINEL:()=>TASK_GATE_REQUIREMENTS_RECONSTRUCTION_SENTINEL,DEFAULT_REQUIRED_GATES:()=>DEFAULT_REQUIRED_GATES});import{mkdirSync as mkdirSync15,readFileSync as readFileSync13,realpathSync as realpathSync9,statSync as statSync13}from"node:fs";import*as path38 from"node:path";function readCurrentTaskDeclaredFiles(directory,taskId){try{let planPath=validateSwarmPath(directory,"plan.json"),stat7=statSync13(planPath);if(!stat7.isFile()||stat7.size>MAX_PLAN_SCOPE_INSPECTION_BYTES)return null;let parsed=JSON.parse(readFileSync13(planPath,"utf8"));if(!Array.isArray(parsed.phases))return null;let declaredFiles=null;for(let phase of parsed.phases){if(!phase||typeof phase!=="object")return null;let tasks=phase.tasks;if(!Array.isArray(tasks))return null;for(let task of tasks){if(!task||typeof task!=="object")return null;let record2=task;if(record2.id!==taskId)continue;if(!Array.isArray(record2.files_touched)||!record2.files_touched.every((file2)=>typeof file2==="string"))return null;if(declaredFiles!==null)return null;declaredFiles=[...record2.files_touched]}}return declaredFiles}catch{return null}}function assertTaskEvidenceWriteAllowed(directory,taskId,event){assertValidTaskId(taskId);let coderWalPath=validateSwarmPath(directory,`coder-settlements/${taskId}.json`),coderWal=readWorkflowWalFileSync("coder-settlement",coderWalPath,taskId);if((coderWal?.state==="DISPATCHED"||coderWal?.state==="PREPARED")&&!(event!=null&&event.transitionId===coderWal.transitionId&&(event.type==="dispatch_attempted"||event.type==="dispatch_no_mutation"||event.type==="accepted_mutation")))throw Error(`CODER_SETTLEMENT_IN_PROGRESS: transition ${String(coderWal.transitionId)} owns evidence for task ${taskId}. Wait for the owning transition to settle or run /swarm recover ${taskId} (or /swarm reset-session), then retry; do not remove the WAL by hand.`);let terminalWalPath=validateSwarmPath(directory,`task-terminals/${taskId}.json`),terminalWal=readWorkflowWalFileSync("task-terminal",terminalWalPath,taskId);if(terminalWal?.state==="PREPARED"){if(!(event!=null&&event.transitionId===terminalWal.transitionId&&(event.type==="task_completed"&&terminalWal.newPlanStatus==="completed"||event.type==="task_blocked"&&terminalWal.newPlanStatus==="blocked"||event.type==="task_closed"&&terminalWal.newPlanStatus==="closed")))throw Error(`TASK_TERMINAL_PREPARED: transition ${String(terminalWal.transitionId)} owns evidence for task ${taskId}`)}let repairWalPath=validateSwarmPath(directory,`task-repairs/${taskId}.json`),repairWal=readWorkflowWalFileSync("task-repair",repairWalPath,taskId);if(repairWal?.state==="PREPARED"&&!(event?.type==="repair_idle"&&event.transitionId===repairWal.transitionId))throw Error(`TASK_REPAIR_PREPARED: transition ${String(repairWal.transitionId)} owns evidence for task ${taskId}`)}function parseTaskEvidence(raw,expectedTaskId){let parsed=TaskEvidenceSchema.parse(JSON.parse(raw));if(parsed.taskId!==expectedTaskId)throw Error(`TASK_EVIDENCE_IDENTITY_MISMATCH: expected ${expectedTaskId}, found ${parsed.taskId}`);return parsed}function isValidTaskId(taskId){return isStrictTaskId(taskId)}function assertValidTaskId(taskId){assertStrictTaskId(taskId)}function createDefaultWorkflowMetadata(nowIso2){return{schema:TASK_WORKFLOW_SCHEMA_MARKER,generation:0,state:DEFAULT_WORKFLOW_STATE,retryCount:0,retryHistory:[],retryEpoch:0,lastOutcome:"none",lastTransitionId:null,updatedAt:nowIso2}}function getEventOutcome(event){switch(event.type){case"dispatch_attempted":return"dispatch_attempted";case"dispatch_no_mutation":return"dispatch_no_mutation";case"accepted_mutation":return event.context?.settlementFailed===!0?"accepted_mutation_failed":"accepted_mutation";case"stage_a_passed":return"stage_a_passed";case"stage_a_failed":return"stage_a_failed";case"stage_b_completed":return"stage_b_completed";case"stage_b_failed":return"stage_b_failed";case"gate_recorded":return"gate_recorded";case"task_completed":return"task_completed";case"task_blocked":return"task_blocked";case"task_closed":return"task_closed";case"repair_idle":return"repair_idle"}}function isAuthoritativeWorkflowMetadata(workflow){return workflow?.schema===TASK_WORKFLOW_SCHEMA_MARKER}function getTaskWorkflowSnapshot(evidence){if(isAuthoritativeWorkflowMetadata(evidence?.workflow))return{...evidence.workflow,authoritative:!0};return{...createDefaultWorkflowMetadata(""),authoritative:!1}}function maybeExpandRequiredGates(existing,event){if(event.type==="accepted_mutation"){let agentType=event.agentType;if(typeof agentType==="string"&&agentType.trim()!=="")return existing?expandRequiredGates(existing.required_gates.filter((gate)=>gate!==TASK_GATE_REQUIREMENTS_RECONSTRUCTION_SENTINEL),agentType,event.context??{}):deriveRequiredGates(agentType,event.context??{})}if(event.type==="stage_b_completed"&&event.ensureDefaultStageB===!0)return expandRequiredGates(existing?.required_gates??[],"coder",{testEngineerExempt:!1});if(event.type==="stage_b_completed"||event.type==="gate_recorded")return existing?expandRequiredGates(existing.required_gates,event.gate):deriveRequiredGates(event.gate);return existing?.required_gates??[]}function hasAllRequiredGatesPassed(requiredGates,gates){return requiredGates.length>0&&requiredGates.every((gate)=>gates[gate]!=null)}function shouldTreatGateAsStageB(gate){return gate==="reviewer"||gate==="test_engineer"}function clearWorkflowGateProof(gates){let retained={...gates};return delete retained.pre_check,delete retained.reviewer,delete retained.test_engineer,delete retained.council,delete retained.critic,delete retained.critic_sounding_board,retained}function assertExpectedGeneration(snapshot,event){if(typeof event.expectedGeneration==="number"&&event.expectedGeneration!==snapshot.generation)throw Error(`TASK_WORKFLOW_GENERATION_MISMATCH: expected ${event.expectedGeneration}, current ${snapshot.generation}`)}function isDuplicateTransition(snapshot,event){if(event.type==="dispatch_no_mutation"&&event.context?.declaredFiles?.length===0&&event.context.settlementTransitionId===event.transitionId&&!snapshot.noMutationSettlement)return!1;return snapshot.authoritative&&typeof event.transitionId==="string"&&event.transitionId.length>0&&snapshot.lastTransitionId===event.transitionId&&snapshot.lastOutcome===getEventOutcome(event)}function isNoMutationSettlementMetadata(workflow){let settlement=workflow.noMutationSettlement;if(!workflow.authoritative||workflow.generation!==0||settlement?.generation!==0||typeof settlement.transitionId!=="string"||settlement.transitionId.length===0||!Array.isArray(settlement.declaredFiles)||settlement.declaredFiles.length!==0)return!1;return workflow.state==="idle"||workflow.state==="complete"}function deriveApplicableGateSet(evidence,options){if(!evidence)return{requiredGates:["pre_check"],satisfiedGates:[],missingGates:["pre_check"],readOnlyNoMutation:!1};let workflow=getTaskWorkflowSnapshot(evidence),readOnlyNoMutation=isNoMutationSettlementMetadata(workflow)&&(options?.currentDeclaredFiles===void 0?!0:options.currentDeclaredFiles!==null&&options.currentDeclaredFiles.length===0),requiredGates=[...new Set(evidence.required_gates??[])];if(!readOnlyNoMutation&&!requiredGates.includes("pre_check"))requiredGates.unshift("pre_check");let satisfiedGates=requiredGates.filter((gate)=>evidence.gates?.[gate]!=null);return{requiredGates,satisfiedGates,missingGates:requiredGates.filter((gate)=>evidence.gates?.[gate]==null),readOnlyNoMutation}}function isReadOnlyNoMutationEligible(evidence,options){return deriveApplicableGateSet(evidence,options).readOnlyNoMutation}function reduceTaskWorkflowSnapshot(current,event,context){if((current.state==="complete"||current.state==="blocked"||current.state==="closed")&&event.type!=="repair_idle"&&!(current.state==="complete"&&event.type==="task_completed"||current.state==="blocked"&&event.type==="task_blocked"||current.state==="blocked"&&event.type==="task_closed"||current.state==="blocked"&&event.type==="stage_a_passed"&&event.settlementRecovery===!0))throw Error(`TASK_WORKFLOW_TERMINAL: cannot apply ${event.type} from ${current.state}`);let outcome=getEventOutcome(event),base={schema:TASK_WORKFLOW_SCHEMA_MARKER,generation:current.generation,state:current.state,retryCount:current.retryCount,retryHistory:current.retryHistory,retryEpoch:current.retryEpoch,lastOutcome:outcome,lastTransitionId:event.transitionId??current.lastTransitionId,updatedAt:context.nowIso,...current.forcedCompletion===!0?{forcedCompletion:!0}:{},...current.supervisedRecovery===!0?{supervisedRecovery:!0}:{},...current.settlementRecovery===!0?{settlementRecovery:!0}:{},...current.noMutationSettlement?{noMutationSettlement:current.noMutationSettlement}:{}};switch(event.type){case"dispatch_attempted":{let{noMutationSettlement:_clearedSettlement,...withoutSettlement}=base;return withoutSettlement}case"dispatch_no_mutation":{let{noMutationSettlement:_clearedSettlement,...withoutSettlement}=base;return{...withoutSettlement,retryCount:Math.min(current.retryCount+1,3),retryHistory:[...current.retryHistory,outcome].slice(-3),retryEpoch:current.retryEpoch||current.generation+1,...current.generation===0&&event.transitionId&&Array.isArray(event.context?.declaredFiles)&&event.context.declaredFiles.length===0&&event.context.settlementTransitionId===event.transitionId?{noMutationSettlement:{generation:0,transitionId:event.transitionId,declaredFiles:[]}}:{}}}case"stage_b_failed":if(current.state!=="pre_check_passed"&¤t.state!=="reviewer_run"&¤t.state!=="tests_run"&¤t.state!=="rework_required")throw Error(`TASK_WORKFLOW_STAGE_A_REQUIRED: cannot reject ${event.gate} from ${current.state}`);return{...base,state:"rework_required",retryCount:Math.min(current.retryCount+1,3),retryHistory:[...current.retryHistory,outcome].slice(-3),retryEpoch:current.retryEpoch||current.generation+1};case"accepted_mutation":{let{noMutationSettlement:_clearedSettlement,...withoutSettlement}=base;if(event.context?.settlementFailed===!0)return{...withoutSettlement,generation:current.generation+1,state:"rework_required",retryCount:Math.min(current.retryCount+1,3),retryHistory:[...current.retryHistory,outcome].slice(-3),retryEpoch:current.retryEpoch||current.generation+1,supervisedRecovery:void 0,settlementRecovery:void 0};return{...withoutSettlement,generation:current.generation+1,state:"coder_delegated",supervisedRecovery:void 0,settlementRecovery:void 0}}case"stage_a_passed":if(current.state!=="coder_delegated"&¤t.state!=="pre_check_passed"&&!(current.state==="rework_required"&&event.supervisedRecovery===!0)&&!(event.settlementRecovery===!0&&(current.state==="idle"||current.state==="blocked")))throw Error(`TASK_WORKFLOW_CODER_MUTATION_REQUIRED: cannot pass Stage A from ${current.state}`);return{...base,...event.supervisedRecovery===!0?{supervisedRecovery:!0}:{},...event.settlementRecovery===!0?{settlementRecovery:!0}:{},state:"pre_check_passed"};case"stage_a_failed":if(current.state!=="coder_delegated"&¤t.state!=="pre_check_passed"&¤t.state!=="rework_required")throw Error(`TASK_WORKFLOW_CODER_MUTATION_REQUIRED: cannot fail Stage A from ${current.state}`);return{...base,state:"rework_required",retryCount:Math.min(current.retryCount+1,3),retryHistory:[...current.retryHistory,outcome].slice(-3),retryEpoch:current.retryEpoch||current.generation+1};case"stage_b_completed":if(current.state!=="pre_check_passed"&¤t.state!=="reviewer_run"&¤t.state!=="tests_run")throw Error(`TASK_WORKFLOW_STAGE_A_REQUIRED: cannot record ${event.gate} from ${current.state}`);if(event.routeComplete===!1)return{...base,state:event.gate==="reviewer"||current.state==="reviewer_run"?"reviewer_run":current.state};if(event.routeComplete===!0)return{...base,state:"tests_run"};return{...base,state:hasAllRequiredGatesPassed(context.requiredGates,context.gates)?"tests_run":"reviewer_run"};case"gate_recorded":return{...base,state:current.state};case"task_completed":{let readOnlyNoMutation=event.readOnlyNoMutation===!0&¤t.state==="idle"&¤t.generation===0&&isNoMutationSettlementMetadata(current)&&context.requiredGates.every((gate)=>context.gates[gate]!=null);if(event.qaExempt!==!0&¤t.state!=="tests_run"&¤t.state!=="complete"&&!(current.state==="pre_check_passed"&&context.gates.council!=null)&&!readOnlyNoMutation)throw Error(`TASK_WORKFLOW_QA_REQUIRED: cannot complete from ${current.state}`);return{...base,state:"complete",...event.qaExempt===!0?{forcedCompletion:!0}:{}}}case"task_blocked":return{...base,state:"blocked"};case"task_closed":return{...base,state:"closed"};case"repair_idle":{let{forcedCompletion:_cleared,supervisedRecovery:_clearedMarker,settlementRecovery:_clearedSettlementMarker,noMutationSettlement:_clearedSettlement,...withoutForced}=base;return{...withoutForced,generation:current.generation+1,state:"idle",retryCount:0,retryHistory:[],retryEpoch:0}}}}function getEvidenceDir(directory){let swarmDir=path38.resolve(directory,".swarm"),evidenceDir=path38.join(swarmDir,"evidence");mkdirSync15(evidenceDir,{recursive:!0});let resolvedSwarmDir,resolvedEvidenceDir;try{resolvedSwarmDir=path38.normalize(realpathSync9(swarmDir)),resolvedEvidenceDir=path38.normalize(realpathSync9(evidenceDir))}catch(error49){throw Error(`Unable to resolve evidence directory: ${error49.message}`)}let swarmPrefix=`${resolvedSwarmDir}${path38.sep}`;if(!(process.platform==="win32"?resolvedEvidenceDir.toLowerCase().startsWith(swarmPrefix.toLowerCase()):resolvedEvidenceDir.startsWith(swarmPrefix)))throw Error(`Evidence path escapes .swarm boundary: ${resolvedEvidenceDir}`);return resolvedEvidenceDir}function getEvidencePath(directory,taskId){return assertValidTaskId(taskId),taskEvidencePath(directory,taskId)}function bindTrustedNoMutationSettlement(directory,taskId,event){if(event.type!=="dispatch_no_mutation")return event;let context=event.context;if(!context||event.transitionId===void 0)return{...event,context:void 0};try{let wal=readWorkflowWalFileSync("coder-settlement",validateSwarmPath(directory,`coder-settlements/${taskId}.json`),taskId),declaredFiles=wal?.context?.declaredFiles,trusted=wal!==null&&(wal.state==="PREPARED"||wal.state==="COMMITTED")&&wal.accepted===!1&&wal.transitionId===event.transitionId&&Array.isArray(declaredFiles)&&declaredFiles.length===0&&Array.isArray(context.declaredFiles)&&context.declaredFiles.length===0;return{...event,context:trusted?{...context,declaredFiles,settlementTransitionId:wal.transitionId}:{...context,settlementTransitionId:void 0}}}catch{return{...event,context:{...context,settlementTransitionId:void 0}}}}function readExisting(evidencePath,taskId){try{let raw=readFileSync13(evidencePath,"utf-8");return parseTaskEvidence(raw,taskId)}catch(error49){if(error49.code==="ENOENT")return null;throw telemetry.gateParseError(taskId,error49),error49}}function deriveRequiredGates(agentType,context={}){switch(agentType){case"coder":return context.testEngineerExempt===!0?["reviewer"]:["reviewer","test_engineer"];case"docs":return["docs"];case"designer":return["designer","reviewer","test_engineer"];case"explorer":return["explorer"];case"sme":return["sme"];case"reviewer":return["reviewer"];case"test_engineer":return["test_engineer"];case"critic":return["critic"];case"critic_sounding_board":return["critic_sounding_board"];case"critic_drift_verifier":return["critic_drift_verifier"];case"critic_hallucination_verifier":return["critic_hallucination_verifier"];case"critic_architecture_supervisor":return["critic_architecture_supervisor"];default:return["reviewer","test_engineer"]}}function expandRequiredGates(existingGates,newAgentType,context={}){let newGates=deriveRequiredGates(newAgentType,context);return[...new Set([...existingGates??[],...newGates])].sort()}function updateEvidenceForTransition(existing,event){let nowIso2=new Date().toISOString(),requiredGates=maybeExpandRequiredGates(existing,event),gates={...existing?.gates??{}};if(event.type==="accepted_mutation"||event.type==="repair_idle")gates=clearWorkflowGateProof(gates);if(event.type==="stage_a_passed")gates={...gates,pre_check:{sessionId:"system",timestamp:nowIso2,agent:"pre_check"}};if(event.type==="stage_a_failed")delete gates.pre_check;if(event.type==="stage_b_failed")delete gates.reviewer,delete gates.test_engineer;if(event.type==="stage_b_completed"||event.type==="gate_recorded")gates={...gates,[event.gate]:{sessionId:event.sessionId,timestamp:nowIso2,agent:event.gate}};let snapshot=getTaskWorkflowSnapshot(existing);if(assertExpectedGeneration(snapshot,event),isDuplicateTransition(snapshot,event)&&existing)return existing;let workflow=reduceTaskWorkflowSnapshot(snapshot,event,{requiredGates,gates,nowIso:nowIso2});return{taskId:existing?.taskId??"",required_gates:requiredGates,gates,turbo:"turbo"in event&&event.turbo===!0?!0:("turbo"in event)&&event.turbo===!1?existing?.turbo:existing?.turbo,test_engineer_exempt:(event.type==="dispatch_attempted"||event.type==="dispatch_no_mutation"||event.type==="accepted_mutation")&&event.agentType==="coder"?event.context?.testEngineerExempt===!0&&!requiredGates.includes("test_engineer"):existing?.test_engineer_exempt,workflow,requirements_state:existing?.requirements_state,...existing?.repair_provenance?{repair_provenance:existing.repair_provenance}:{},...existing?.todo_scan?{todo_scan:existing.todo_scan}:{}}}async function transitionTaskWorkflowEvidence(directory,taskId,event){let{evidence}=await transitionTaskWorkflowEvidenceWithStatus(directory,taskId,event);return evidence}async function transitionTaskWorkflowEvidenceWithStatus(directory,taskId,event){assertValidTaskId(taskId);let updatedEvidence=null,duplicated=!1;return await withTaskEvidenceTransaction(directory,taskId,event.type,async(transaction)=>{if(transaction.transitionWithStatus){let result=await transaction.transitionWithStatus(event);updatedEvidence=result.evidence,duplicated=result.duplicated;return}updatedEvidence=await transaction.transition(event)}),{evidence:updatedEvidence??{taskId,required_gates:[],gates:{},workflow:createDefaultWorkflowMetadata(new Date().toISOString())},duplicated}}async function withTaskEvidenceTransaction(directory,taskId,agent,callback){return assertValidTaskId(taskId),withTaskEvidenceLock(directory,taskId,agent,async()=>{let resolvedEvidenceDir=getEvidenceDir(directory),evidencePath=path38.join(resolvedEvidenceDir,`${taskId}.json`),current=null;try{current=readExisting(evidencePath,taskId)}catch(error49){throw telemetry.gateParseError(taskId,error49),error49}let persist=async(nextEvidence,event)=>{let validated=TaskEvidenceSchema.parse({...nextEvidence,taskId});if(await atomicWriteFile(evidencePath,JSON.stringify(validated,null,2)),event)await _internals37.appendTaskGateRequirementsReceiptIfNeeded(directory,taskId,current,validated,event);return current=validated,validated},transitionWithStatusImpl=async(event)=>{let boundEvent=bindTrustedNoMutationSettlement(directory,taskId,event);assertTaskEvidenceWriteAllowed(directory,taskId,boundEvent);let nextEvidence=updateEvidenceForTransition(current,boundEvent),duplicated=nextEvidence===current;return nextEvidence.taskId=taskId,{evidence:await persist(nextEvidence,boundEvent),duplicated}};return callback({taskId,read:()=>current,transition:async(event)=>{let{evidence}=await transitionWithStatusImpl(event);return evidence},transitionWithStatus:transitionWithStatusImpl,save:async(nextEvidence)=>{return assertTaskEvidenceWriteAllowed(directory,taskId,void 0),nextEvidence.taskId=taskId,persist(nextEvidence)}})})}async function ensureTaskGateRequirementsReceiptForSettledTransition(directory,taskId,evidence,event){assertValidTaskId(taskId);let validated=TaskEvidenceSchema.parse({...evidence,taskId});await _internals37.appendTaskGateRequirementsReceiptIfNeeded(directory,taskId,null,validated,event)}async function recordGateEvidence(directory,taskId,gate,sessionId,turbo,options={}){if(assertValidTaskId(taskId),shouldTreatGateAsStageB(gate)&&typeof options.expectedGeneration!=="number")throw Error(`TASK_WORKFLOW_GENERATION_REQUIRED: ${gate} for task ${taskId} must be bound at dispatch`);await transitionTaskWorkflowEvidence(directory,taskId,shouldTreatGateAsStageB(gate)?{type:"stage_b_completed",gate,sessionId,routeBinding:options.routeBinding,routeComplete:options.routeComplete,turbo,ensureDefaultStageB:options.ensureDefaultStageB,expectedGeneration:options.expectedGeneration,transitionId:options.transitionId}:{type:"gate_recorded",gate,sessionId,turbo,expectedGeneration:options.expectedGeneration,transitionId:options.transitionId}),telemetry.gatePassed(sessionId,gate,taskId)}async function recordTodoScanEvidence(directory,taskId,scan){assertValidTaskId(taskId),await withTaskEvidenceTransaction(directory,taskId,"todo_scan_recorded",async(transaction)=>{let base=transaction.read()??{taskId,required_gates:[],gates:{},workflow:createDefaultWorkflowMetadata(new Date().toISOString())};if(!transaction.save)throw Error(`TASK_EVIDENCE_SAVE_UNAVAILABLE: transaction for task ${taskId} does not support supplementary writes`);await transaction.save({...base,todo_scan:scan})})}async function recordAgentDispatch(directory,taskId,agentType,turbo,context={}){assertValidTaskId(taskId);let expectedGeneration=getTaskWorkflowSnapshot(await readTaskEvidence(directory,taskId)).generation;await transitionTaskWorkflowEvidence(directory,taskId,agentType==="coder"?{type:"accepted_mutation",agentType,turbo,context,expectedGeneration}:{type:"dispatch_attempted",agentType,turbo,context,expectedGeneration})}async function readTaskEvidence(directory,taskId){let state2=await readTaskEvidenceState(directory,taskId);return state2.kind==="ok"?state2.evidence:null}async function readTaskEvidenceState(directory,taskId){try{assertValidTaskId(taskId)}catch{return{kind:"missing"}}try{let evidencePath=getEvidencePath(directory,taskId),raw=readFileSync13(evidencePath,"utf-8");return{kind:"ok",evidence:parseTaskEvidence(raw,taskId)}}catch(error49){let evidencePath=getEvidencePathSafe(directory,taskId),code=error49.code;if(code==="ENOENT"||code==="ENAMETOOLONG")return{kind:"missing"};return telemetry.gateParseError(taskId,error49),{kind:"unparseable",evidencePath,error:error49}}}function getEvidencePathSafe(directory,taskId){try{return getEvidencePath(directory,taskId)}catch{return`${directory}/.swarm/evidence/${taskId}.json`}}function readTaskEvidenceRaw(directory,taskId){assertValidTaskId(taskId);let evidencePath=getEvidencePath(directory,taskId);try{let raw=readFileSync13(evidencePath,"utf-8");return parseTaskEvidence(raw,taskId)}catch(error49){let code=error49.code;if(code==="ENOENT"||code==="ENAMETOOLONG")return null;throw error49}}async function hasPassedAllGates(directory,taskId,currentDeclaredFiles){let evidence=await readTaskEvidence(directory,taskId);if(!evidence)return!1;if(!Array.isArray(evidence.required_gates))return!1;if(currentDeclaredFiles===void 0){if(deriveApplicableGateSet(evidence).readOnlyNoMutation)return!1;return hasAllRequiredGatesPassed(evidence.required_gates,evidence.gates)}return deriveApplicableGateSet(evidence,{currentDeclaredFiles}).missingGates.length===0}function compareTaskWorkflowStateRank(left,right){return WORKFLOW_STATE_RANK[left]-WORKFLOW_STATE_RANK[right]}var _internals37,TASK_WORKFLOW_SCHEMA_MARKER="exact-task-v1",TASK_WORKFLOW_STATES,TASK_WORKFLOW_OUTCOMES,MAX_PLAN_SCOPE_INSPECTION_BYTES=4194304,TASK_GATE_REQUIREMENTS_RECONSTRUCTION_SENTINEL="requirements_reconstruction",GateEvidenceSchema,TaskWorkflowMetadataSchema,TaskEvidenceSchema,DEFAULT_REQUIRED_GATES,DEFAULT_WORKFLOW_STATE="idle",WORKFLOW_STATE_RANK;var init_gate_evidence=__esm(()=>{init_zod();init_task_file();init_task_gate_requirements();init_utils2();init_telemetry();init_task_id();init_workflow_wal_file();_internals37={appendTaskGateRequirementsReceiptIfNeeded},TASK_WORKFLOW_STATES=["idle","coder_delegated","pre_check_passed","reviewer_run","tests_run","rework_required","complete","blocked","closed"],TASK_WORKFLOW_OUTCOMES=["none","dispatch_attempted","dispatch_no_mutation","accepted_mutation","accepted_mutation_failed","stage_a_passed","stage_a_failed","stage_b_completed","stage_b_failed","gate_recorded","task_completed","task_blocked","task_closed","repair_idle"];GateEvidenceSchema=exports_external.object({sessionId:exports_external.string(),timestamp:exports_external.string(),agent:exports_external.string()}).passthrough(),TaskWorkflowMetadataSchema=exports_external.object({schema:exports_external.literal(TASK_WORKFLOW_SCHEMA_MARKER),generation:exports_external.number().int().min(0),state:exports_external.enum(TASK_WORKFLOW_STATES),retryCount:exports_external.number().int().min(0).default(0),retryHistory:exports_external.array(exports_external.enum(TASK_WORKFLOW_OUTCOMES)).max(3).default([]),retryEpoch:exports_external.number().int().min(0).default(0),lastOutcome:exports_external.enum(TASK_WORKFLOW_OUTCOMES).default("none"),lastTransitionId:exports_external.string().min(1).nullable().optional().default(null),updatedAt:exports_external.string(),forcedCompletion:exports_external.boolean().optional(),supervisedRecovery:exports_external.boolean().optional(),settlementRecovery:exports_external.boolean().optional(),noMutationSettlement:exports_external.object({generation:exports_external.literal(0),transitionId:exports_external.string().min(1).max(512),declaredFiles:exports_external.array(exports_external.string()).length(0)}).optional()}),TaskEvidenceSchema=exports_external.object({taskId:exports_external.string(),required_gates:exports_external.array(exports_external.string()).default([]),gates:exports_external.record(exports_external.string(),GateEvidenceSchema),turbo:exports_external.boolean().optional(),requirements_state:exports_external.enum(["known","unknown"]).optional(),test_engineer_exempt:exports_external.boolean().optional(),workflow:TaskWorkflowMetadataSchema.optional(),repair_provenance:exports_external.object({source_sha256:exports_external.string().regex(/^[a-f0-9]{64}$/).nullable(),source_generation:exports_external.number().int().min(0).nullable(),requirements_receipt_hash:exports_external.string().regex(/^[a-f0-9]{64}$/).nullable()}).optional(),todo_scan:exports_external.object({priority:exports_external.string(),count:exports_external.number().int().min(0),details:exports_external.array(exports_external.string()).max(200).optional(),recorded_at:exports_external.string().optional()}).optional()});DEFAULT_REQUIRED_GATES=["reviewer","test_engineer"],WORKFLOW_STATE_RANK={idle:0,coder_delegated:1,pre_check_passed:2,reviewer_run:3,tests_run:4,rework_required:5,blocked:6,closed:7,complete:8}});import*as path39 from"node:path";function normalizeCandidate(value){if(typeof value!=="string"||value.length===0)return null;if([...value].some((character)=>{let codePoint=character.codePointAt(0)??0;return codePoint<=31||codePoint===127}))return null;if(path39.win32.isAbsolute(value)||path39.posix.isAbsolute(value))return null;let normalized=value.replace(/\\/g,"/");if(normalized.split("/").some((segment)=>segment===""||segment==="."||segment===".."))return null;return normalized}function isExactMarkdownPath(value){let normalized=normalizeCandidate(value);return normalized!==null&&path39.posix.extname(normalized)===".md"}function isMarkdownOnlyDeclaredScope(value){return Array.isArray(value)&&value.length>0&&value.every(isExactMarkdownPath)}function isMarkdownOnlyTaskChange(declaredFiles,observedFiles){if(!Array.isArray(declaredFiles)||!Array.isArray(observedFiles))return!1;if(!isMarkdownOnlyDeclaredScope(declaredFiles)||observedFiles.length===0)return!1;if(!observedFiles.every(isExactMarkdownPath))return!1;let declared=new Set(declaredFiles.map(normalizeCandidate).filter((value)=>value!==null));return observedFiles.every((value)=>{let normalized=normalizeCandidate(value);return normalized!==null&&declared.has(normalized)})}var init_gate_evidence_classification=()=>{};import{createHash as createHash20}from"node:crypto";import*as fs23 from"node:fs";import*as path40 from"node:path";function ownerDirectory(directory){return path40.dirname(validateSwarmPath(directory,path40.join(PROVISIONING_OWNER_DIR,".containment-anchor")))}function ownerPath(directory,callID){let digest2=createHash20("sha256").update(callID).digest("hex");return validateSwarmPath(directory,path40.join(PROVISIONING_OWNER_DIR,`${digest2}.json`))}function journalPath(directory){return validateSwarmPath(directory,PROVISIONING_JOURNAL_PATH)}function isOwner(value){if(!value||typeof value!=="object"||Array.isArray(value))return!1;let candidate=value,schemaVersion=candidate.schemaVersion,validTaskIdentity=schemaVersion===1?candidate.taskId===void 0&&candidate.reservationId===void 0&&candidate.generation===void 0&&candidate.branchName===void 0:schemaVersion===2&&typeof candidate.taskId==="string"&&candidate.taskId.length>0&&candidate.taskId.length<=512&&candidate.reservationId===void 0&&candidate.generation===void 0&&candidate.branchName===void 0,validV3Identity=schemaVersion===3&&typeof candidate.taskId==="string"&&candidate.taskId.length>0&&candidate.taskId.length<=512&&typeof candidate.reservationId==="string"&&candidate.reservationId.length>0&&candidate.reservationId.length<=512&&typeof candidate.generation==="number"&&Number.isInteger(candidate.generation)&&candidate.generation>0&&typeof candidate.branchName==="string"&&candidate.branchName.length>0&&candidate.branchName.length<=1024;return(schemaVersion===1||schemaVersion===2||schemaVersion===3)&&(validTaskIdentity||validV3Identity)&&typeof candidate.callID==="string"&&candidate.callID.length>0&&candidate.callID.length<=512&&typeof candidate.parentSessionId==="string"&&candidate.parentSessionId.length>0&&candidate.parentSessionId.length<=512&&typeof candidate.worktreeSessionId==="string"&&candidate.worktreeSessionId.length>0&&candidate.worktreeSessionId.length<=512&&typeof candidate.createdAt==="number"&&Number.isFinite(candidate.createdAt)&&candidate.createdAt>=0}function isLifecycleEntry(value){if(!value||typeof value!=="object"||Array.isArray(value))return!1;let candidate=value,validState=WORKTREE_PROVISIONING_LIFECYCLE_STATES.includes(candidate.state);return candidate.schemaVersion===1&&validState&&typeof candidate.callID==="string"&&candidate.callID.length>0&&candidate.callID.length<=512&&typeof candidate.parentSessionId==="string"&&candidate.parentSessionId.length>0&&candidate.parentSessionId.length<=512&&typeof candidate.worktreeSessionId==="string"&&candidate.worktreeSessionId.length>0&&candidate.worktreeSessionId.length<=512&&(candidate.taskId===void 0||typeof candidate.taskId==="string"&&candidate.taskId.length>0&&candidate.taskId.length<=512)&&(candidate.reservationId===void 0||typeof candidate.reservationId==="string"&&candidate.reservationId.length>0&&candidate.reservationId.length<=512)&&(candidate.generation===void 0||typeof candidate.generation==="number"&&Number.isInteger(candidate.generation)&&candidate.generation>0)&&(candidate.branchName===void 0||typeof candidate.branchName==="string"&&candidate.branchName.length>0&&candidate.branchName.length<=1024)&&typeof candidate.recordedAt==="number"&&Number.isFinite(candidate.recordedAt)&&candidate.recordedAt>=0}function readBoundedJsonFile(filePath,maxBytes){try{if(fs23.statSync(filePath).size>maxBytes)return{ok:!1,reason:`${path40.basename(filePath)} exceeds the ${maxBytes}-byte safety bound`};let raw=fs23.readFileSync(filePath,"utf8");if(Buffer.byteLength(raw,"utf8")>maxBytes)return{ok:!1,reason:`${path40.basename(filePath)} changed beyond the ${maxBytes}-byte safety bound`};return{ok:!0,value:JSON.parse(raw)}}catch(error49){if(error49.code==="ENOENT")return{ok:!0,value:void 0};return{ok:!1,reason:`${path40.basename(filePath)} is unreadable or malformed: ${error49 instanceof Error?error49.message:String(error49)}`}}}function readOwner(directory,callID){let absolutePath=ownerPath(directory,callID),loaded=readBoundedJsonFile(absolutePath,MAX_PROVISIONING_OWNER_BYTES);if(!loaded.ok||loaded.value===void 0)return null;return isOwner(loaded.value)?loaded.value:null}function loadLifecycleJournal(directory){let loaded=readBoundedJsonFile(journalPath(directory),MAX_PROVISIONING_JOURNAL_BYTES);if(!loaded.ok)return{status:"uncertain",reason:loaded.reason};if(loaded.value===void 0)return{status:"ok",entries:[]};let parsed=loaded.value;if(parsed.schemaVersion!==1||!Array.isArray(parsed.entries))return{status:"uncertain",reason:"worktree provisioning lifecycle journal is malformed"};if(parsed.entries.length>MAX_PROVISIONING_JOURNAL_ENTRIES)return{status:"uncertain",reason:`worktree provisioning lifecycle journal exceeds the ${MAX_PROVISIONING_JOURNAL_ENTRIES}-entry safety bound`};let entries=[];for(let entry of parsed.entries){if(!isLifecycleEntry(entry))return{status:"uncertain",reason:"worktree provisioning lifecycle journal contains an invalid entry"};entries.push(entry)}return{status:"ok",entries}}function appendLifecycleEntry(directory,owner,state2){let loaded=loadLifecycleJournal(directory);if(loaded.status==="uncertain")throw Error(loaded.reason);let journal={schemaVersion:1,entries:[...loaded.entries,{schemaVersion:1,state:state2,callID:owner.callID,parentSessionId:owner.parentSessionId,worktreeSessionId:owner.worktreeSessionId,...owner.taskId?{taskId:owner.taskId}:{},...owner.reservationId?{reservationId:owner.reservationId}:{},...owner.generation!==void 0?{generation:owner.generation}:{},...owner.branchName?{branchName:owner.branchName}:{},recordedAt:Date.now()}].slice(-MAX_PROVISIONING_JOURNAL_ENTRIES)};atomicWriteSwarmFileSync(journalPath(directory),JSON.stringify(journal,null,2))}function recordWorktreeProvisioningOwner(directory,input){let wantsV3=input.reservationId!==void 0||input.generation!==void 0||input.branchName!==void 0;if(wantsV3&&(!input.taskId||!input.reservationId||input.generation===void 0||!input.branchName))throw Error("worktree provisioning owner v3 requires taskId, reservationId, generation, and branchName");let owner={schemaVersion:wantsV3?3:input.taskId?2:1,callID:input.callID,parentSessionId:input.parentSessionId,worktreeSessionId:input.worktreeSessionId,...input.taskId?{taskId:input.taskId}:{},...input.reservationId?{reservationId:input.reservationId}:{},...input.generation!==void 0?{generation:input.generation}:{},...input.branchName?{branchName:input.branchName}:{},createdAt:Date.now()};if(!isOwner(owner))throw Error("invalid worktree provisioning owner");let absolutePath=ownerPath(directory,input.callID);return fs23.mkdirSync(path40.dirname(absolutePath),{recursive:!0}),atomicWriteSwarmFileSync(absolutePath,`${JSON.stringify(owner)}
|
|
636
636
|
`),appendLifecycleEntry(directory,owner,"OWNER_PUBLISHED"),owner}function removeWorktreeProvisioningOwner(directory,callID,expected){try{let owner=readOwner(directory,callID);if(owner?.schemaVersion===3&&(!expected||expected.reservationId!==owner.reservationId||expected.generation!==owner.generation||expected.branchName!==owner.branchName))return!1;if(fs23.unlinkSync(ownerPath(directory,callID)),owner)appendLifecycleEntry(directory,owner,"OWNER_REMOVED");return!0}catch(error49){return error49.code==="ENOENT"}}function scanWorktreeProvisioningOwnersForRecovery(directory){let directoryPath,entries;try{directoryPath=ownerDirectory(directory),entries=fs23.readdirSync(directoryPath,{withFileTypes:!0}).filter((entry)=>entry.isFile()&&entry.name.endsWith(".json"))}catch(error49){if(error49.code==="ENOENT")return{status:"ok",owners:[]};return{status:"uncertain",reason:`worktree provisioning-owner directory is unreadable: ${error49 instanceof Error?error49.message:String(error49)}`}}if(entries.length>MAX_PROVISIONING_OWNERS)return{status:"uncertain",reason:`worktree provisioning-owner count exceeds the ${MAX_PROVISIONING_OWNERS}-marker safety bound`};let owners=[];for(let entry of entries){let absolutePath=path40.join(directoryPath,entry.name);try{if(fs23.statSync(absolutePath).size>MAX_PROVISIONING_OWNER_BYTES)return{status:"uncertain",reason:`worktree provisioning owner "${entry.name}" exceeds the recovery size bound`};let raw=fs23.readFileSync(absolutePath,"utf8");if(Buffer.byteLength(raw,"utf8")>MAX_PROVISIONING_OWNER_BYTES)return{status:"uncertain",reason:`worktree provisioning owner "${entry.name}" changed beyond the recovery size bound`};let parsed=JSON.parse(raw);if(!isOwner(parsed))return{status:"uncertain",reason:`worktree provisioning owner "${entry.name}" is invalid`};owners.push(parsed)}catch(error49){return{status:"uncertain",reason:`worktree provisioning owner "${entry.name}" is unreadable or malformed: ${error49 instanceof Error?error49.message:String(error49)}`}}}return{status:"ok",owners}}function scanWorktreeProvisioningLifecycleJournalForRecovery(directory){return loadLifecycleJournal(directory)}var PROVISIONING_OWNER_DIR="worktree-provisioning-owners",MAX_PROVISIONING_OWNERS=512,MAX_PROVISIONING_OWNER_BYTES=16384,PROVISIONING_JOURNAL_PATH,MAX_PROVISIONING_JOURNAL_BYTES=262144,MAX_PROVISIONING_JOURNAL_ENTRIES=512,WORKTREE_PROVISIONING_OWNER_LEASE_MS=300000,WORKTREE_LIFECYCLE_LOCK_FILE=".swarm/locks/init-orphan-recovery.lock",WORKTREE_PROVISIONING_LIFECYCLE_STATES;var init_worktree_provisioning_owner=__esm(()=>{init_atomic_write();init_utils2();PROVISIONING_JOURNAL_PATH=path40.join(".swarm","worktree-provisioning-lifecycle.json"),WORKTREE_PROVISIONING_LIFECYCLE_STATES=["OWNER_PUBLISHED","OWNER_REMOVED"]});import{spawnSync as spawnSync3}from"node:child_process";import{existsSync as existsSync21}from"node:fs";function resolveBwrapBinary(){try{if(existsSync21(BWRAP_ABSOLUTE))return BWRAP_ABSOLUTE}catch{}return"bwrap"}function probeBwrap(){try{let binary=_internals38.resolveBwrapBinary(),result=spawnSync3(binary,["--version"],{windowsHide:!0,encoding:"utf-8",timeout:5000,stdio:["ignore","pipe","ignore"]});if(result.error){let code=result.error.code;if(code&&BWRAP_UNAVAILABLE_CODES.has(code))return warn(`Sandbox disabled: bwrap error (${code}). Falling through to tool-layer enforcement.`),!1;return warn(`Sandbox disabled: bwrap spawn error (${result.error.message}). Falling through to tool-layer enforcement.`),!1}return result.status===BWRAP_VERSION_EXIT&&result.stdout.trim().length>0}catch(err){let message=err instanceof Error?err.message:String(err);return warn(`Sandbox disabled: probe threw (${message}). Falling through to tool-layer enforcement.`),!1}}function shellEscape(s){return s.replace(/'/g,"'\\''")}class BubblewrapSandboxExecutor{mechanism="Bubblewrap";_scopePaths;_tempDir;_available;_disabledReason;constructor(scopePaths=[],tempDir){this._scopePaths=scopePaths,this._tempDir=tempDir,this._available=!1,this._disabledReason=null;try{if(!_internals38.probeBwrap())this._disabledReason="bwrap not available or not functional",warn(`Sandbox disabled: ${this._disabledReason}. Falling through to tool-layer enforcement.`);else this._available=!0}catch(err){let message=err instanceof Error?err.message:String(err);this._disabledReason=`constructor threw: ${message}`,this._available=!1,warn(`Sandbox disabled: ${this._disabledReason}. Falling through to tool-layer enforcement.`)}}isAvailable(){return this._available}disable(reason){this._available=!1,this._disabledReason=reason,warn(`Sandbox disabled: ${reason}. Falling through to tool-layer enforcement.`)}wrapCommand(command,scopePaths,tempDir,envOverrides,policy){if(!this._available)throw new SandboxError("Sandbox not available","SANDBOX_UNAVAILABLE");let temp=tempDir??this._tempDir??"/tmp",bindArgs=[...this._scopePaths,...scopePaths].flatMap((p)=>["--bind",`'${shellEscape(p)}'`,`'${shellEscape(p)}'`]),envArgs=[];if(envOverrides)for(let[key,value]of Object.entries(envOverrides)){if(!isValidEnvKey(key))continue;if(value===null)envArgs.push("--unsetenv",key);else envArgs.push("--setenv",key,`'${shellEscape(value)}'`)}let args2=["--unshare-user","--unshare-ipc","--die-with-parent","--new-session","--cap-drop","ALL",...bindArgs,"--dev","/dev","--size",String(TMPFS_SIZE_BYTES),"--tmpfs",`'${shellEscape(temp)}'`,"--ro-bind","/etc","/etc","--ro-bind","/usr","/usr","--ro-bind","/lib","/lib","--ro-bind","/lib64","/lib64","--proc","/proc","--unshare-pid",...envArgs,"--","bash","-c",`'${shellEscape(command)}'`];if((policy?.network_mode??"off")==="off")args2.splice(1,0,"--unshare-net");return`${_internals38.resolveBwrapBinary()} ${args2.join(" ")}`}getEnvOverrides(){return{}}}var BWRAP_VERSION_EXIT=0,BWRAP_UNAVAILABLE_CODES,BWRAP_ABSOLUTE="/usr/bin/bwrap",TMPFS_SIZE_BYTES=524288000,_internals38;var init_bubblewrap_executor=__esm(()=>{init_logger();init_executor();BWRAP_UNAVAILABLE_CODES=new Set(["ENOENT","EACCES","ENOSPC"]);_internals38={probeBwrap,resolveBwrapBinary}});import{spawnSync as spawnSync4}from"node:child_process";import{existsSync as existsSync22,mkdtempSync,writeFileSync as writeFileSync9}from"node:fs";import*as os9 from"node:os";import*as path41 from"node:path";function resolveBinary(absolutePath,bareName){try{if(_internals39.exists(absolutePath))return absolutePath}catch{}return bareName}function resolveSandboxExecBinary(){return resolveBinary(SANDBOX_EXEC_ABSOLUTE,"sandbox-exec")}function resolveProbeTargetBinary(){return resolveBinary(TRUE_ABSOLUTE,"true")}function buildProbeProfile(tempDir){return`(version 1)
|
|
637
637
|
(allow default)
|
|
638
638
|
(deny file-write*)
|
|
@@ -7527,9 +7527,15 @@ ${hint}`}]}return{file:targetPath,status:"error",hunks:hunksTotal,hunksApplied:0
|
|
|
7527
7527
|
`?resultContent.replace(/\n/g,`\r
|
|
7528
7528
|
`):resultContent;finalContent=ensureFinalNewline(withLineEnding,originalEndsWithNewline)}if(finalContent===content)return{file:targetPath,status:"no-changes",hunks:hunksTotal,hunksApplied:hunksTotal,hunksFailed:0};if(!dryRun)atomicWriteFileSync3(fullPath,finalContent);return{file:targetPath,status:"applied",hunks:hunksTotal,hunksApplied:hunksTotal,hunksFailed:0}}function buildErrorResult(message){return{success:!1,files:[{file:"",status:"error",hunks:0,hunksApplied:0,hunksFailed:0,errors:[{hunkIndex:0,type:"context-mismatch",message}]}],summary:{totalFiles:0,applied:0,failed:1,totalHunks:0}}}function isUnsupportedPatchFormat(patchText){let trimmed=patchText.trimStart();return trimmed.startsWith("*** Begin Patch")||trimmed.startsWith("*** Update File")||trimmed.startsWith("*** Add File")||trimmed.startsWith("*** Delete File")||trimmed.startsWith("*** End Patch")}var swarmApplyPatch2=createSwarmTool({description:"Apply a unified diff patch to workspace files. Validates paths, matches context exactly, and writes atomically. Coder-scoped write tool. Use standard unified diff format (--- a/file / +++ b/file / @@ hunks). Indented patches (e.g. inside a fenced markdown/YAML block) are automatically dedented to column 0 before parsing — the diff body itself may be indented. Does NOT support *** Begin Patch / *** Update File payloads — use the native apply_patch tool for those. Accepts the payload as `patch` (canonical) or any of the aliases `patchText`, `patch_text`, `patchPayload` (#2206); the resolver picks the first non-empty one.",args:{patch:exports_external.string().optional().describe("Unified diff text to parse and apply (optional when an alias below carries the payload)"),patchText:exports_external.string().optional().describe("Alias for patch — unified diff payload; accepted because models frequently hallucinate alternative argument names (#2206)"),patch_text:exports_external.string().optional().describe("Alias for patch — unified diff payload; accepted because models frequently hallucinate alternative argument names (#2206)"),patchPayload:exports_external.string().optional().describe("Alias for patch — unified diff payload; accepted because models frequently hallucinate alternative argument names (#2206)"),files:exports_external.array(exports_external.string()).min(1).describe("Array of target file paths the patch is expected to touch. Every parsed target must appear in this list."),dryRun:exports_external.boolean().optional().default(!1).describe("Validate without writing files (default: false)"),allowCreates:exports_external.boolean().optional().default(!1).describe("Allow creating new files from patches with --- /dev/null (default: false)"),allowDeletes:exports_external.boolean().optional().default(!1).describe("Allow deleting files from patches with +++ /dev/null (default: false)")},execute:async(args2,directory)=>{if(!args2||typeof args2!=="object")return JSON.stringify(buildErrorResult("Could not parse swarm_apply_patch arguments"),null,2);let obj=args2,patchText=[obj.patch,obj.patchText,obj.patch_text,obj.patchPayload].find((value)=>typeof value==="string"&&value.length>0)??"",files=obj.files??[],dryRun=obj.dryRun??!1,allowCreates=obj.allowCreates??!1,allowDeletes=obj.allowDeletes??!1,{config:config3}=_internals249.loadPluginConfigWithMeta(directory),fuzzyMatch=config3.apply_patch?.fuzzy_match===!0,fuzzyMatchContextAware=config3.apply_patch?.fuzzy_match_context_aware===!0,hunkOptions=fuzzyMatch||fuzzyMatchContextAware?{fuzzyMatch,fuzzyMatchContextAware}:void 0;if(!existsSync158(directory))return JSON.stringify(buildErrorResult("Workspace directory does not exist"),null,2);if(files.length===0)return JSON.stringify(buildErrorResult("files array cannot be empty"),null,2);if(!patchText||patchText.trim()==="")return JSON.stringify(buildErrorResult("patch text cannot be empty"),null,2);if(isUnsupportedPatchFormat(patchText))return JSON.stringify(buildErrorResult("Unsupported patch format: *** Begin Patch / *** Update File style payloads are not supported by swarm_apply_patch. Use the native apply_patch tool for this format, or provide a standard unified diff (--- a/file / +++ b/file / @@ hunks)."),null,2);for(let filePath of files){let validationError=validatePatchTargetPath(filePath,directory);if(validationError)return JSON.stringify(buildErrorResult(validationError),null,2)}let{files:parsedFiles,error:parseError}=parseUnifiedDiff2(patchText);if(parseError)return JSON.stringify(buildErrorResult(parseError),null,2);if(parsedFiles.length===0)return JSON.stringify({success:!0,dryRun,files:[],summary:{totalFiles:0,applied:0,failed:0,totalHunks:0}},null,2);let declaredFileSet=new Set(files),undeclaredTargets=[];for(let fileDiff of parsedFiles){let targetPath=fileDiff.isDelete?fileDiff.oldPath:fileDiff.newPath;if(targetPath&&targetPath!=="/dev/null"&&!declaredFileSet.has(targetPath))undeclaredTargets.push(targetPath)}if(undeclaredTargets.length>0)return JSON.stringify(buildErrorResult(`Patch targets files not in the declared files array: ${undeclaredTargets.join(", ")}`),null,2);let parsedTargetSet=new Set(parsedFiles.map((fd)=>fd.isDelete?fd.oldPath:fd.newPath).filter(Boolean)),extraFiles=files.filter((f)=>!parsedTargetSet.has(f)),fileResults=[],totalApplied=0,totalFailed=0,totalHunks=0;for(let fileDiff of parsedFiles){let targetPath=fileDiff.isDelete?fileDiff.oldPath:fileDiff.newPath,fullPath=path305.resolve(directory,targetPath);totalHunks+=fileDiff.hunks.length;let result=processFileDiff(fileDiff,targetPath,fullPath,directory,dryRun,allowCreates,allowDeletes,hunkOptions);if(fileResults.push(result),result.status==="applied"||result.status==="created")totalApplied++;else if(result.status==="error")totalFailed++}let output={success:totalFailed===0,dryRun,files:fileResults,summary:{totalFiles:fileResults.length,applied:totalApplied,failed:totalFailed,totalHunks}};if(extraFiles.length>0)return JSON.stringify({...output,warnings:[`files[] contains entries not targeted by the patch: ${extraFiles.join(", ")}`]},null,2);return JSON.stringify(output,null,2)}});init_zod();init_delegation_gate();init_create_tool();var ApprovePlanCriticArgsSchema=exports_external.object({reason:exports_external.string().trim().min(1).max(500).describe('Why a manual approval is being recorded (e.g. "critic returned APPROVED but the verdict format did not match the mechanical recorder"). Audited to .swarm/events.jsonl.')}).strict();async function executeApprovePlanCritic(args2,directory,context={}){let parsed=ApprovePlanCriticArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,message:`Invalid approve_plan_critic call: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`});if(!context.sessionID?.trim())return JSON.stringify({success:!1,message:"approve_plan_critic requires an active sessionID"});try{let summary=await forceRecordPlanCriticApproval(directory,context.sessionID,{reason:parsed.data.reason,userConfirmed:!1});return JSON.stringify({success:!0,plan_id:summary.planId,recorded_at:summary.recordedAt,method:"manual_override",user_confirmed:!1,message:"Recorded a manual plan_critic_gate approval snapshot. The critic_pre_plan execution gate will now allow coder delegation. An audit event was appended to .swarm/events.jsonl."})}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:String(error93)})}}var approve_plan_critic=createSwarmTool({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 snapshot recorder failed to persist it (verdict-format mismatch, dispatch-signal miss, or a plan.json read race — issue #2012). The snapshot carries a distinct method: "manual_override" audit marker. Architect-only: the active session must be the architect. Prefer re-running MODE: CRITIC-GATE first; use this only as an escape hatch when a legitimate APPROVED was lost, or as the sanctioned recovery for a bookkeeping-grade hashed-field repair under the critic-gate PLAN FREEZE rule (e.g. a files_touched-only scope reconciliation) — the reason must state which case applies. A reason is required and audited to .swarm/events.jsonl. The human-confirmed variant is /swarm approve-plan-critic.',args:{reason:ApprovePlanCriticArgsSchema.shape.reason},execute:executeApprovePlanCritic});init_zod();init_delegation_gate();init_create_tool();var ApproveRetrySoundingBoardArgsSchema=exports_external.object({task_id:exports_external.string().trim().min(1).describe('Exact plan task id of the wedged task (e.g. "2.1"). Must exist in the current plan and already have a durable sounding_board_consultation escalation.'),reason:exports_external.string().trim().min(1).max(500).describe('Why a manual approval is being recorded (e.g. "sounding board returned APPROVED but the verdict format did not match the mechanical recorder"). Audited to .swarm/events.jsonl.')}).strict();async function executeApproveRetrySoundingBoard(args2,directory,context={}){let parsed=ApproveRetrySoundingBoardArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,message:`Invalid approve_retry_sounding_board call: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`});if(!context.sessionID?.trim())return JSON.stringify({success:!1,message:"approve_retry_sounding_board requires an active sessionID"});try{let summary=await forceRecordRetrySoundingBoardApproval(directory,context.sessionID,{taskId:parsed.data.task_id,reason:parsed.data.reason});return JSON.stringify({success:!0,task_id:summary.taskId,generation:summary.generation,retry_epoch:summary.retryEpoch,recorded_at:summary.recordedAt,audit_event_recorded:summary.auditEventRecorded,method:"manual_override",user_confirmed:!1,message:summary.auditEventRecorded?"Recorded a manual critic_sounding_board gate entry for the coder retry circuit breaker. The next coder dispatch for this task passes the TASK_RETRY_CRITIC_REQUIRED critic check (one bounded simplified retry). An audit event (action sounding_board_manual_approval) was appended to .swarm/events.jsonl.":"Recorded a manual critic_sounding_board gate entry for the coder retry circuit breaker. The next coder dispatch for this task passes the TASK_RETRY_CRITIC_REQUIRED critic check (one bounded simplified retry). WARNING: the audit event could NOT be appended to .swarm/events.jsonl (see the plugin log); the gate evidence itself records the override via the retry-sb-manual transition id."})}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:String(error93)})}}var approve_retry_sounding_board=createSwarmTool({description:"Record a MANUAL critic_sounding_board gate entry to unblock the coder retry circuit-breaker gate (TASK_RETRY_CRITIC_REQUIRED) when the sounding board already returned APPROVED but the mechanical recorder failed to persist it — verdict-format miss (the sounding board echoed its enumerated RESPONSE FORMAT line), dispatch-task attribution miss, launch-generation binding miss, or a failed/error output state (issue #2703). Scoped to the exact plan task id, which must already carry a durable sounding_board_consultation escalation for the current retry epoch; the audit event (action sounding_board_manual_approval) distinguishes the override from a mechanical recording. Architect-only: the active session must be the architect. Prefer re-dispatching the sounding board first; use this only as an escape hatch when a legitimate APPROVED verdict was lost. A reason is required and audited to .swarm/events.jsonl.",args:{task_id:ApproveRetrySoundingBoardArgsSchema.shape.task_id,reason:ApproveRetrySoundingBoardArgsSchema.shape.reason},execute:executeApproveRetrySoundingBoard});init_zod();init_external_tool_runner();init_path_security();init_create_tool();import*as fs174 from"node:fs";import*as path306 from"node:path";var AST_GREP_TIMEOUT_MS=1e4,AST_GREP_MAX_STDOUT_BYTES=8388608,AST_GREP_MAX_STDERR_BYTES=65536,DEFAULT_MAX_RESULTS2=100,HARD_CAP_RESULTS2=1e4,MAX_PATTERN_LENGTH=20000;function splitGlobPatterns(value){return value?value.split(",").map((p)=>p.trim()).filter(Boolean):[]}function resolveAstGrepBinary(){return _internals250.resolveExecutableFromPath(["ast-grep","sg"])}function toWorkspaceRelativePath(filePath,workspace){try{let resolved=path306.resolve(workspace,filePath),realWorkspace=fs174.realpathSync(workspace),realResolved=fs174.realpathSync(resolved),relative75=path306.relative(realWorkspace,realResolved);if(!relative75||relative75.startsWith("..")||path306.isAbsolute(relative75))return null;return relative75.split(path306.sep).join("/")}catch{return null}}function parseAstGrepStream(stdout,workspace,maxResults){let matches=[],total=0;for(let line of stdout.split(`
|
|
7529
7529
|
`)){if(!line.trim())continue;try{let entry=JSON.parse(line),relativePath2=typeof entry.file==="string"?toWorkspaceRelativePath(entry.file,workspace):null;if(!relativePath2)continue;if(total++,matches.length>=maxResults)continue;let start=entry.range?.start??{},end=entry.range?.end??{};matches.push({file:relativePath2,lineNumber:typeof start.line==="number"?start.line+1:1,column:typeof start.column==="number"?start.column+1:1,endLineNumber:typeof end.line==="number"?end.line+1:1,endColumn:typeof end.column==="number"?end.column+1:1,text:typeof entry.text==="string"?entry.text:"",lines:typeof entry.lines==="string"?entry.lines.trimEnd():"",language:typeof entry.language==="string"?entry.language:void 0,metaVariables:entry.metaVariables&&typeof entry.metaVariables==="object"?entry.metaVariables:void 0})}catch{}}return{matches,total}}function validateGlobArg(kind,value){if(!value)return null;if(containsControlChars(value))return{error:!0,type:"path-escape",message:`${kind} pattern contains invalid control characters`};if(containsPathTraversal(value))return{error:!0,type:"path-escape",message:`${kind} pattern contains path traversal sequence`};return null}var ast_grep=createSwarmTool({description:"Read-only structural AST search using ast-grep. Searches code patterns with optional language and glob filters; does not rewrite files.",args:{pattern:exports_external.string().describe("ast-grep pattern to search for"),language:exports_external.string().optional().describe("Optional ast-grep language, e.g. ts, tsx, js, py, rust"),include:exports_external.string().optional().describe("Comma-separated include globs, passed to ast-grep --globs"),exclude:exports_external.string().optional().describe("Comma-separated exclude globs, passed to ast-grep as !glob"),max_results:exports_external.number().default(DEFAULT_MAX_RESULTS2).describe("Maximum number of matches to return")},execute:async(args2,directory)=>{let pattern,language,include,exclude,maxResults=DEFAULT_MAX_RESULTS2;try{let obj=args2;pattern=typeof obj.pattern==="string"?obj.pattern:"",language=typeof obj.language==="string"?obj.language:void 0,include=typeof obj.include==="string"?obj.include:void 0,exclude=typeof obj.exclude==="string"?obj.exclude:void 0;let rawMaxResults=typeof obj.max_results==="number"?obj.max_results:DEFAULT_MAX_RESULTS2,sanitizedMaxResults=Number.isFinite(rawMaxResults)?rawMaxResults:DEFAULT_MAX_RESULTS2;maxResults=Math.min(Math.max(0,sanitizedMaxResults),HARD_CAP_RESULTS2)}catch{return JSON.stringify({error:!0,type:"invalid-pattern",message:"Could not parse ast_grep arguments"},null,2)}if(!pattern||pattern.trim()==="")return JSON.stringify({error:!0,type:"invalid-pattern",message:"Pattern cannot be empty"},null,2);if(pattern.length>MAX_PATTERN_LENGTH||containsControlChars(pattern))return JSON.stringify({error:!0,type:"invalid-pattern",message:`Pattern is invalid or exceeds ${MAX_PATTERN_LENGTH} characters`},null,2);if(language&&!/^[A-Za-z0-9_-]+$/.test(language))return JSON.stringify({error:!0,type:"invalid-pattern",message:"Language must contain only letters, numbers, _ or -"},null,2);let includeError=validateGlobArg("Include",include);if(includeError)return JSON.stringify(includeError,null,2);let excludeError=validateGlobArg("Exclude",exclude);if(excludeError)return JSON.stringify(excludeError,null,2);if(!fs174.existsSync(directory))return JSON.stringify({error:!0,type:"unknown",message:"Workspace directory does not exist"},null,2);let executable=_internals250.resolveAstGrepBinary();if(!executable)return JSON.stringify({error:!0,type:"ast-grep-not-found",message:"ast-grep executable not found. Install ast-grep and ensure ast-grep or sg is on PATH."},null,2);let sgArgs=["run","--pattern",pattern,"--json=stream","--color","never"];if(language)sgArgs.push("--lang",language);for(let glob of splitGlobPatterns(include))sgArgs.push("--globs",glob);for(let glob of splitGlobPatterns(exclude))sgArgs.push("--globs",`!${glob}`);sgArgs.push(".");let run=await _internals250.runExternalTool({executable,args:sgArgs,cwd:directory,timeoutMs:AST_GREP_TIMEOUT_MS,maxStdoutBytes:AST_GREP_MAX_STDOUT_BYTES,maxStderrBytes:AST_GREP_MAX_STDERR_BYTES});if(run.status==="timeout")return JSON.stringify({error:!0,type:"timeout",message:`ast-grep timed out after ${AST_GREP_TIMEOUT_MS}ms`},null,2);if(run.status==="spawn-error")return JSON.stringify({error:!0,type:"unknown",message:run.message??"ast-grep failed to start"},null,2);if(run.exitCode!==0&&run.stderr)return JSON.stringify({error:!0,type:"invalid-pattern",message:run.stderr.split(`
|
|
7530
|
-
`)[0]},null,2);let{matches,total}=parseAstGrepStream(run.stdout,directory,maxResults);return JSON.stringify({matches,truncated:total>maxResults||run.stdoutTruncated||run.stderrTruncated,total,pattern,language,maxResults,outputTruncated:run.stdoutTruncated||run.stderrTruncated},null,2)}}),_internals250={resolveExecutableFromPath,resolveAstGrepBinary,runExternalTool,parseAstGrepStream};init_zod();init_authorization();init_create_tool();var AuthorizePrReviewReentryArgsSchema=exports_external.object({run_id:exports_external.string().regex(/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/).optional(),pr_head_sha:exports_external.string().trim().regex(/^[0-9a-f]{6,64}$/i),role:exports_external.enum(["reviewer","test_engineer"])}).strict();async function executeAuthorizePrReviewReentry(args2,directory,context={}){let parsed=AuthorizePrReviewReentryArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,message:`Invalid PR-review re-entry authorization: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`});if(!context.sessionID?.trim())return JSON.stringify({success:!1,message:"PR-review re-entry authorization requires an active sessionID"});try{let record3=await issuePrReviewReentryAuthorization(directory,context.sessionID,{...parsed.data.run_id?{runId:parsed.data.run_id}:{},prHeadSha:parsed.data.pr_head_sha,role:parsed.data.role});return JSON.stringify({success:!0,authorization_id:record3.authorizationId,role:record3.role,pr_head_sha:record3.prHeadSha,run_id:record3.runId,generation:record3.generation,revision_digest:record3.revisionDigest,expires_at:record3.expiresAt,instructions:`Immediately dispatch exactly one direct subagent_type Task call with role "${record3.role}" for this PR-review re-entry; if a plan or task workflow state exists, include the exact task_id (or task identifier in the prompt). A taskless dispatch is allowed only for a plan-free standalone review and does not advance plan-task gate state. The PR workflow controller admits and reserves this authorization once, and the delegation gate verifies the same call-bound reservation; a later unrelated gate rejection still burns it. Any other dispatch falls back to normal gating.`},null,2)}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:String(error93)})}}var authorize_pr_review_reentry=createSwarmTool({description:"Issue a one-use, identity-bound reviewer/test_engineer re-entry authorization for the active PR_REVIEW workflow (issue #2383). The authorization is reserved atomically by the PR workflow controller for the very next direct subagent_type Task dispatch of the declared role (admitting that one dispatch past the PR_REVIEW read-only restriction), then verified for that same call by the delegation gate, which bypasses ONLY the generic Stage-A task-workflow requirement; all other delegation gates remain authoritative. If a plan or task workflow state exists, the dispatch must include an exact task_id or task identifier; taskless dispatch is standalone-only and never guesses from plan/session state. Bound to the exact session, workflow, run, PR head SHA, worktree revision digest, role, and gate generation; replay, cross-session use, wrong role, expiry (10 minutes), or workflow progress since issuance fails closed. A dispatch the delegation gate later rejects for another reason still burns the authorization. Requires an active head-bound PR_REVIEW gate. Issue immediately before the Task dispatch; unconsumed same-role authorizations at the same generation are refused.",args:{run_id:AuthorizePrReviewReentryArgsSchema.shape.run_id,pr_head_sha:AuthorizePrReviewReentryArgsSchema.shape.pr_head_sha,role:AuthorizePrReviewReentryArgsSchema.shape.role},execute:executeAuthorizePrReviewReentry});init_dist();init_create_tool();init_symbols();init_path_security();import*as fs175 from"node:fs";import*as path307 from"node:path";var WINDOWS_RESERVED_NAMES4=/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\.|:|$)/i;function containsWindowsAttacks3(str){if(/:[^\\/]/.test(str))return!0;let parts=str.split(/[/\\]/);for(let part of parts)if(WINDOWS_RESERVED_NAMES4.test(part))return!0;return!1}function isPathInWorkspace2(filePath,workspace){try{let resolvedPath=path307.resolve(workspace,filePath);if(!fs175.existsSync(resolvedPath))return!0;let realWorkspace=fs175.realpathSync(workspace),realResolvedPath=fs175.realpathSync(resolvedPath),relativePath2=path307.relative(realWorkspace,realResolvedPath);if(relativePath2.startsWith("..")||path307.isAbsolute(relativePath2))return!1;return!0}catch{return!1}}function processFile(file3,cwd,exportedOnly){let ext=path307.extname(file3);if(containsControlChars(file3))return{file:file3,success:!1,error:"Path contains invalid control characters",errorType:"invalid-path"};if(containsPathTraversal(file3))return{file:file3,success:!1,error:"Path contains path traversal sequence",errorType:"path-traversal"};if(containsWindowsAttacks3(file3))return{file:file3,success:!1,error:"Path contains invalid Windows-specific sequence",errorType:"invalid-path"};if(!isPathInWorkspace2(file3,cwd))return{file:file3,success:!1,error:"Path is outside workspace",errorType:"path-outside-workspace"};let fullPath=path307.join(cwd,file3);if(!fs175.existsSync(fullPath))return{file:file3,success:!1,error:`File not found: ${file3}`,errorType:"file-not-found"};let syms;switch(ext){case".ts":case".tsx":case".js":case".jsx":case".mjs":case".cjs":syms=extractTSSymbols(file3,cwd);break;case".py":case".pyw":syms=extractPythonSymbols(file3,cwd);break;case".rs":syms=extractRustSymbols(file3,cwd);break;case".go":syms=extractGoSymbols(file3,cwd);break;default:return{file:file3,success:!1,error:`Unsupported file extension: ${ext}. Supported: .ts, .tsx, .js, .jsx, .mjs, .cjs, .py, .pyw, .rs, .go`,errorType:"unsupported-language"}}let isEmptyFile=!1;try{if(fs175.statSync(fullPath).size===0)isEmptyFile=!0}catch{}if(syms.length===0)try{if(fs175.readFileSync(fullPath,"utf-8").trim().length===0)isEmptyFile=!0}catch{}if(isEmptyFile)return{file:file3,success:!0,symbols:[],error:"empty-file",errorType:"empty-file"};if(exportedOnly)syms=syms.filter((s)=>s.exported);return{file:file3,success:!0,symbols:syms}}var batch_symbols=createSwarmTool({description:"Extract symbols from multiple files in a single batch call. Accepts an array of file paths and returns per-file symbol summaries. One bad file does not crash the batch. Use for surveying a module when you need symbol information from multiple files at once.",args:{files:tool.schema.array(tool.schema.string()).describe("Array of file paths to extract symbols from"),exported_only:tool.schema.boolean().default(!0).describe("If true, only return exported/public symbols. If false, include all top-level symbols.")},execute:async(args2,directory)=>{let files,exportedOnly=!0;try{let obj=args2;if(!Array.isArray(obj.files))return JSON.stringify({results:[],totalFiles:0,successCount:0,failureCount:0,error:"Invalid arguments: files must be an array"},null,2);files=obj.files.map((f)=>String(f)),exportedOnly=obj.exported_only!==!1}catch{return JSON.stringify({results:[],totalFiles:0,successCount:0,failureCount:0,error:"Invalid arguments: could not extract files array"},null,2)}let cwd=directory,results=[];for(let file3 of files){let result=processFile(file3,cwd,exportedOnly);results.push(result)}let successCount=results.filter((r)=>r.success).length,failureCount=results.filter((r)=>!r.success).length,batchResult={results,totalFiles:files.length,successCount,failureCount};return JSON.stringify(batchResult,null,2)}});init_zod();init_discovery();init_config();init_manager2();init_bun_compat();init_logger();init_create_tool();var _internals251={loadGateOverrides},DEFAULT_TIMEOUT_MS4=300000,MAX_OUTPUT_BYTES6=10240,MAX_OUTPUT_LINES=100,NO_BUILD_FILES_DISCOVERED_REASON="No build commands discovered (no supported build files found)";function truncateOutput(output,maxLines=MAX_OUTPUT_LINES,maxBytes=MAX_OUTPUT_BYTES6){if(!output)return"";let truncated=output;if(truncated.length>maxBytes)truncated=truncated.slice(-maxBytes);let lines=truncated.split(`
|
|
7530
|
+
`)[0]},null,2);let{matches,total}=parseAstGrepStream(run.stdout,directory,maxResults);return JSON.stringify({matches,truncated:total>maxResults||run.stdoutTruncated||run.stderrTruncated,total,pattern,language,maxResults,outputTruncated:run.stdoutTruncated||run.stderrTruncated},null,2)}}),_internals250={resolveExecutableFromPath,resolveAstGrepBinary,runExternalTool,parseAstGrepStream};init_zod();init_authorization();init_create_tool();var AuthorizePrReviewReentryArgsSchema=exports_external.object({run_id:exports_external.string().regex(/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/).optional(),pr_head_sha:exports_external.string().trim().regex(/^[0-9a-f]{6,64}$/i),role:exports_external.enum(["reviewer","test_engineer"])}).strict();async function executeAuthorizePrReviewReentry(args2,directory,context={}){let parsed=AuthorizePrReviewReentryArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,message:`Invalid PR-review re-entry authorization: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`});if(!context.sessionID?.trim())return JSON.stringify({success:!1,message:"PR-review re-entry authorization requires an active sessionID"});try{let record3=await issuePrReviewReentryAuthorization(directory,context.sessionID,{...parsed.data.run_id?{runId:parsed.data.run_id}:{},prHeadSha:parsed.data.pr_head_sha,role:parsed.data.role});return JSON.stringify({success:!0,authorization_id:record3.authorizationId,role:record3.role,pr_head_sha:record3.prHeadSha,run_id:record3.runId,generation:record3.generation,revision_digest:record3.revisionDigest,expires_at:record3.expiresAt,instructions:`Immediately dispatch exactly one direct subagent_type Task call with role "${record3.role}" for this PR-review re-entry; if a plan or task workflow state exists, include the exact task_id (or task identifier in the prompt). A taskless dispatch is allowed only for a plan-free standalone review and does not advance plan-task gate state. The PR workflow controller admits and reserves this authorization once, and the delegation gate verifies the same call-bound reservation; a later unrelated gate rejection still burns it. Any other dispatch falls back to normal gating.`},null,2)}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:String(error93)})}}var authorize_pr_review_reentry=createSwarmTool({description:"Issue a one-use, identity-bound reviewer/test_engineer re-entry authorization for the active PR_REVIEW workflow (issue #2383). The authorization is reserved atomically by the PR workflow controller for the very next direct subagent_type Task dispatch of the declared role (admitting that one dispatch past the PR_REVIEW read-only restriction), then verified for that same call by the delegation gate, which bypasses ONLY the generic Stage-A task-workflow requirement; all other delegation gates remain authoritative. If a plan or task workflow state exists, the dispatch must include an exact task_id or task identifier; taskless dispatch is standalone-only and never guesses from plan/session state. Bound to the exact session, workflow, run, PR head SHA, worktree revision digest, role, and gate generation; replay, cross-session use, wrong role, expiry (10 minutes), or workflow progress since issuance fails closed. A dispatch the delegation gate later rejects for another reason still burns the authorization. Requires an active head-bound PR_REVIEW gate. Issue immediately before the Task dispatch; unconsumed same-role authorizations at the same generation are refused.",args:{run_id:AuthorizePrReviewReentryArgsSchema.shape.run_id,pr_head_sha:AuthorizePrReviewReentryArgsSchema.shape.pr_head_sha,role:AuthorizePrReviewReentryArgsSchema.shape.role},execute:executeAuthorizePrReviewReentry});init_dist();init_create_tool();init_symbols();init_path_security();import*as fs175 from"node:fs";import*as path307 from"node:path";var WINDOWS_RESERVED_NAMES4=/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\.|:|$)/i;function containsWindowsAttacks3(str){if(/:[^\\/]/.test(str))return!0;let parts=str.split(/[/\\]/);for(let part of parts)if(WINDOWS_RESERVED_NAMES4.test(part))return!0;return!1}function isPathInWorkspace2(filePath,workspace){try{let resolvedPath=path307.resolve(workspace,filePath);if(!fs175.existsSync(resolvedPath))return!0;let realWorkspace=fs175.realpathSync(workspace),realResolvedPath=fs175.realpathSync(resolvedPath),relativePath2=path307.relative(realWorkspace,realResolvedPath);if(relativePath2.startsWith("..")||path307.isAbsolute(relativePath2))return!1;return!0}catch{return!1}}function processFile(file3,cwd,exportedOnly){let ext=path307.extname(file3);if(containsControlChars(file3))return{file:file3,success:!1,error:"Path contains invalid control characters",errorType:"invalid-path"};if(containsPathTraversal(file3))return{file:file3,success:!1,error:"Path contains path traversal sequence",errorType:"path-traversal"};if(containsWindowsAttacks3(file3))return{file:file3,success:!1,error:"Path contains invalid Windows-specific sequence",errorType:"invalid-path"};if(!isPathInWorkspace2(file3,cwd))return{file:file3,success:!1,error:"Path is outside workspace",errorType:"path-outside-workspace"};let fullPath=path307.join(cwd,file3);if(!fs175.existsSync(fullPath))return{file:file3,success:!1,error:`File not found: ${file3}`,errorType:"file-not-found"};let syms;switch(ext){case".ts":case".tsx":case".js":case".jsx":case".mjs":case".cjs":syms=extractTSSymbols(file3,cwd);break;case".py":case".pyw":syms=extractPythonSymbols(file3,cwd);break;case".rs":syms=extractRustSymbols(file3,cwd);break;case".go":syms=extractGoSymbols(file3,cwd);break;default:return{file:file3,success:!1,error:`Unsupported file extension: ${ext}. Supported: .ts, .tsx, .js, .jsx, .mjs, .cjs, .py, .pyw, .rs, .go`,errorType:"unsupported-language"}}let isEmptyFile=!1;try{if(fs175.statSync(fullPath).size===0)isEmptyFile=!0}catch{}if(syms.length===0)try{if(fs175.readFileSync(fullPath,"utf-8").trim().length===0)isEmptyFile=!0}catch{}if(isEmptyFile)return{file:file3,success:!0,symbols:[],error:"empty-file",errorType:"empty-file"};if(exportedOnly)syms=syms.filter((s)=>s.exported);return{file:file3,success:!0,symbols:syms}}var batch_symbols=createSwarmTool({description:"Extract symbols from multiple files in a single batch call. Accepts an array of file paths and returns per-file symbol summaries. One bad file does not crash the batch. Use for surveying a module when you need symbol information from multiple files at once.",args:{files:tool.schema.array(tool.schema.string()).describe("Array of file paths to extract symbols from"),exported_only:tool.schema.boolean().default(!0).describe("If true, only return exported/public symbols. If false, include all top-level symbols.")},execute:async(args2,directory)=>{let files,exportedOnly=!0;try{let obj=args2;if(!Array.isArray(obj.files))return JSON.stringify({results:[],totalFiles:0,successCount:0,failureCount:0,error:"Invalid arguments: files must be an array"},null,2);files=obj.files.map((f)=>String(f)),exportedOnly=obj.exported_only!==!1}catch{return JSON.stringify({results:[],totalFiles:0,successCount:0,failureCount:0,error:"Invalid arguments: could not extract files array"},null,2)}let cwd=directory,results=[];for(let file3 of files){let result=processFile(file3,cwd,exportedOnly);results.push(result)}let successCount=results.filter((r)=>r.success).length,failureCount=results.filter((r)=>!r.success).length,batchResult={results,totalFiles:files.length,successCount,failureCount};return JSON.stringify(batchResult,null,2)}});init_zod();init_discovery();init_config();init_manager2();init_bun_compat();init_logger();init_create_tool();var _internals251={loadGateOverrides,bunSpawn},DEFAULT_TIMEOUT_MS4=300000,MAX_OUTPUT_BYTES6=10240,MAX_OUTPUT_LINES=100,NO_BUILD_FILES_DISCOVERED_REASON="No build commands discovered (no supported build files found)";function truncateOutput(output,maxLines=MAX_OUTPUT_LINES,maxBytes=MAX_OUTPUT_BYTES6){if(!output)return"";let truncated=output;if(truncated.length>maxBytes)truncated=truncated.slice(-maxBytes);let lines=truncated.split(`
|
|
7531
7531
|
`);if(lines.length>maxLines)return lines.slice(-maxLines).join(`
|
|
7532
|
-
`);return truncated}function getCommandKind(command){let lower=command.toLowerCase();if(lower.includes("typecheck")||lower.includes("check")||lower.includes("analyze")||lower.includes("lint"))return"typecheck";if(lower.includes("test")||lower.includes("spec")||lower.includes("jest")||lower.includes("vitest")||lower.includes("mocha")||lower.includes("pytest"))return"test";return"build"}function filterByMode(commands,mode){if(mode==="both")return commands;return commands.filter((cmd)=>getCommandKind(cmd.command)===mode)}async function executeCommand(command){let startTime=Date.now(),kind=getCommandKind(command.command),isWindows=process.platform==="win32",cmd,args2;if(isWindows&&!command.command.includes(" "))cmd=[command.command],args2=[];else if(isWindows)cmd=["cmd","/c",command.command],args2=[];else cmd=["/bin/sh"],args2=["-c",command.command];let result=bunSpawn([...cmd,...args2],{cwd:command.cwd,stdout:"pipe",stderr:"pipe",timeout:DEFAULT_TIMEOUT_MS4}),[exitCode,stdout,stderr]=await Promise.all([result.exited,result.stdout.text(),result.stderr.text()]),duration_ms=Date.now()-startTime;return{kind,command:command.command,cwd:command.cwd,exit_code:exitCode??-1,duration_ms,stdout_tail:truncateOutput(stdout),stderr_tail:truncateOutput(stderr)}}async function runBuildCheck(workingDir,input){let scope=input.scope??"all",mode=input.mode??"both",changedFiles=input.changed_files??[],discoveryResult=await discoverBuildCommands(workingDir,{scope,changedFiles}),commands=filterByMode(discoveryResult.commands,mode),runs=[],failedCount=0;for(let cmd of commands)try{let run=await executeCommand(cmd);if(runs.push(run),run.exit_code!==0)failedCount++}catch(error93){runs.push({kind:getCommandKind(cmd.command),command:cmd.command,cwd:cmd.cwd,exit_code:-1,duration_ms:0,stdout_tail:"",stderr_tail:error93 instanceof Error?error93.message:"Unknown error"}),failedCount++}let verdict,skipped_reason,environmentUnavailable=discoveryResult.skipped.filter((skip)=>skip.code==="environment_unavailable");if(runs.length===0)if(verdict=environmentUnavailable.length>0?"skip":"info",discoveryResult.skipped.length>0)skipped_reason=discoveryResult.skipped.map((s)=>`${s.ecosystem}: ${s.reason}`).join("; ");else skipped_reason=NO_BUILD_FILES_DISCOVERED_REASON;else if(failedCount>0)verdict="fail";else verdict="pass";return{verdict,runs,summary:{files_scanned:changedFiles.length,runs_count:runs.length,failed_count:failedCount,skipped_reason,environment_unavailable:environmentUnavailable.length>0?environmentUnavailable:void 0}}}var build_check=createSwarmTool({allowWorkingDirectoryOverride:!0,description:"Discover and run build commands for various ecosystems in a project directory. Supports build, typecheck, and test commands.",args:{scope:exports_external.enum(["changed","all"]).describe('Scope of detection: "all" for all build files, "changed" for only changed files'),changed_files:exports_external.array(exports_external.string()).optional().describe('List of changed files when scope is "changed"'),mode:exports_external.enum(["build","typecheck","both"]).optional().describe('Mode: "build" for build commands, "typecheck" for type checking, "both" for all (default: both)')},async execute(args2,directory){if(_internals251.loadGateOverrides(directory)?.build_check?.enabled===!1)return JSON.stringify({verdict:"skip",runs:[],summary:{files_scanned:0,runs_count:0,failed_count:0,skipped_reason:"build_check disabled by configuration"}},null,2);let obj=args2,scope=obj.scope??"all",changedFiles=obj.changed_files??[],mode=obj.mode??"both",workingDir=directory,result=await runBuildCheck(workingDir,{scope,changed_files:changedFiles,mode}),evidence2={task_id:"build",type:"build",timestamp:new Date().toISOString(),agent:"build_check",verdict:result.verdict,summary:`${result.runs.length} build command(s) executed, ${result.summary.failed_count} failed`,runs:result.runs,files_scanned:result.summary.files_scanned,runs_count:result.summary.runs_count,failed_count:result.summary.failed_count,skipped_reason:result.summary.skipped_reason,environment_unavailable:result.summary.environment_unavailable};try{await saveEvidence(workingDir,"build",evidence2)}catch(error93){log("Failed to save build evidence:",error93 instanceof Error?error93.message:String(error93))}return JSON.stringify(result,null,2)}});init_zod();init_manager2();init_gate_evidence();init_task_id();init_create_tool();init_resolve_working_directory();import*as fs176 from"node:fs";import*as path308 from"node:path";var EVIDENCE_DIR=".swarm/evidence";function isValidTaskId4(taskId){return isStrictTaskId(taskId)}function isPathWithinSwarm(filePath,workspaceRoot){let normalizedWorkspace=path308.resolve(workspaceRoot),swarmPath3=path308.join(normalizedWorkspace,".swarm","evidence");return path308.resolve(filePath).startsWith(swarmPath3)}function readEvidenceFile(evidencePath){if(!fs176.existsSync(evidencePath))return null;let content;try{content=fs176.readFileSync(evidencePath,"utf-8")}catch{return null}let parsed;try{parsed=JSON.parse(content)}catch{return null}if(parsed&&typeof parsed==="object"&&Array.isArray(parsed.required_gates)&&typeof parsed.gates==="object"&&parsed.gates!==null)return parsed;return null}var check_gate_status=createSwarmTool({description:"Read-only tool to check the gate status of a specific task. Reads .swarm/evidence/{taskId}.json and returns structured JSON describing required, passed, and missing gates.",args:{task_id:exports_external.string().min(1).regex(/^\d+\.\d+(\.\d+)*$/,'Task ID must be in N.M or N.M.P format (e.g., "1.1", "1.2.3", "1.2.3.4")').describe('The task ID to check gate status for (e.g., "1.1", "2.3.1")'),working_directory:exports_external.string().optional().describe("Explicit project root directory. When provided, .swarm/evidence/ is resolved relative to this path instead of the plugin context directory. Use this when CWD differs from the actual project root.")},async execute(args2,directory){let taskIdInput,workingDirInput;try{if(args2&&typeof args2==="object"){let obj=args2;taskIdInput=typeof obj.task_id==="string"?obj.task_id:void 0,workingDirInput=typeof obj.working_directory==="string"?obj.working_directory:void 0}}catch{}let dirResult=resolveWorkingDirectory(workingDirInput,directory);if(!dirResult.success){let errorResult={taskId:taskIdInput??"",status:"no_evidence",required_gates:[],passed_gates:[],missing_gates:[],gates:{},message:dirResult.message,todo_scan:null};return JSON.stringify(errorResult,null,2)}if(directory=dirResult.directory,!taskIdInput)return JSON.stringify({taskId:"",status:"no_evidence",required_gates:[],passed_gates:[],missing_gates:[],gates:{},message:"Invalid task_id: task_id is required",todo_scan:null},null,2);if(!isValidTaskId4(taskIdInput)){let errorResult={taskId:taskIdInput,status:"no_evidence",required_gates:[],passed_gates:[],missing_gates:[],gates:{},message:`Invalid task_id format: "${taskIdInput}". Must match N.M or N.M.P (e.g. "1.1", "1.2.3", "1.2.3.4")`,todo_scan:null};return JSON.stringify(errorResult,null,2)}let evidencePath=path308.join(directory,EVIDENCE_DIR,`${taskIdInput}.json`);if(!isPathWithinSwarm(evidencePath,directory))return JSON.stringify({taskId:taskIdInput,status:"no_evidence",required_gates:[],passed_gates:[],missing_gates:[],gates:{},message:"Invalid path: evidence path validation failed",todo_scan:null},null,2);let evidenceData=readEvidenceFile(evidencePath);if(!evidenceData){let errorResult={taskId:taskIdInput,status:"no_evidence",required_gates:[],passed_gates:[],missing_gates:[],gates:{},message:`No evidence file found for task "${taskIdInput}" at ${evidencePath}. Evidence file may be missing or invalid.`,todo_scan:null};return JSON.stringify(errorResult,null,2)}let gatesMap=evidenceData.gates||{},authoritativeWorkflow=evidenceData.workflow?.schema===TASK_WORKFLOW_SCHEMA_MARKER,derivedGates=deriveApplicableGateSet(evidenceData,authoritativeWorkflow?{currentDeclaredFiles:readCurrentTaskDeclaredFiles(directory,taskIdInput)}:void 0),requiredGates=derivedGates.requiredGates,passedGates=derivedGates.satisfiedGates,missingGates=derivedGates.missingGates,readOnlyNoMutation=derivedGates.readOnlyNoMutation,status2=missingGates.length===0&&(readOnlyNoMutation||evidenceData.workflow?.state==="tests_run"||evidenceData.workflow?.state==="complete")?"all_passed":"incomplete",message;if(status2==="all_passed")message=`All required gates have passed for task "${taskIdInput}".`;else if(requiredGates.length===0)message=`Task "${taskIdInput}" is incomplete. No required gates are configured for this task generation.`;else message=`Task "${taskIdInput}" is incomplete. Missing gates: ${missingGates.join(", ")}.`;let secretscanVerdict="not_run";try{let evidenceResult=await loadEvidence(directory,taskIdInput);if(evidenceResult.status==="found"){let secretscanEntries=evidenceResult.bundle.entries.filter((entry)=>entry.type==="secretscan");if(secretscanEntries.length>0){let lastSecretscan=secretscanEntries[secretscanEntries.length-1];if(isSecretscanEvidence(lastSecretscan)){let{incomplete_files:incompleteFiles,incomplete_paths:incompletePaths}=lastSecretscan,findingsCount=lastSecretscan.findings_count??0,hasIncompleteCoverage=incompleteFiles>0||incompletePaths.length>0,hasFindings=findingsCount>0,hasZeroCoverage=lastSecretscan.files_scanned===0;if(hasIncompleteCoverage||hasFindings||hasZeroCoverage||lastSecretscan.verdict==="fail"||lastSecretscan.verdict==="rejected")if(secretscanVerdict="fail",hasIncompleteCoverage&&!hasFindings){if(missingGates.push("secretscan (BLOCKED — incomplete coverage)"),status2==="all_passed")status2="incomplete";message=`BLOCKED: Secretscan incomplete coverage in prior scan. ${message}`}else if(hasFindings&&hasIncompleteCoverage){if(missingGates.push("secretscan (BLOCKED — secrets detected; incomplete coverage)"),status2==="all_passed")status2="incomplete";message=`BLOCKED: Secretscan found secrets and incomplete coverage in prior scan. ${message}`}else if(hasFindings){if(missingGates.push("secretscan (BLOCKED — secrets detected)"),status2==="all_passed")status2="incomplete";message=`BLOCKED: Secretscan found secrets in prior scan. ${message}`}else{if(missingGates.push("secretscan (BLOCKED — zero coverage)"),status2==="all_passed")status2="incomplete";message=`BLOCKED: Secretscan scanned zero files in prior scan. ${message}`}else if(lastSecretscan.verdict==="pass"||lastSecretscan.verdict==="approved"||lastSecretscan.verdict==="info")secretscanVerdict="pass"}}else message+=" Advisory: No secretscan evidence found for this task. Consider running secretscan."}else if(evidenceResult.status==="invalid_schema")secretscanVerdict="fail",missingGates.push("secretscan (BLOCKED — invalid evidence)"),status2="incomplete",message=`BLOCKED: Secretscan evidence is invalid and cannot prove complete coverage. ${message}`}catch{}let todoScan=evidenceData.todo_scan,workflowMeta=evidenceData.workflow&&typeof evidenceData.workflow==="object"&&typeof evidenceData.workflow.state==="string"?{state:evidenceData.workflow.state,generation:typeof evidenceData.workflow.generation==="number"?evidenceData.workflow.generation:0}:null,workflowAttributionHint;if(status2==="incomplete"&&workflowMeta?.state==="coder_delegated"&&!gatesMap.pre_check)workflowAttributionHint="Task is settled at coder_delegated but Stage A (pre_check_batch) was never attributed — "+`reviewer/test_engineer dispatches will be denied with TASK_WORKFLOW_STAGE_A_REQUIRED. Run pre_check_batch on the task's changed files; if it passes without advancing this task, run /swarm recover ${taskIdInput}.`,message+=` ${workflowAttributionHint}`;let result={taskId:taskIdInput,status:status2,required_gates:requiredGates,passed_gates:passedGates,missing_gates:missingGates,gates:gatesMap,message,todo_scan:todoScan??null,secretscan_verdict:secretscanVerdict,workflow:workflowMeta,...workflowAttributionHint?{workflow_attribution_hint:workflowAttributionHint}:{}};return JSON.stringify(result,null,2)}});init_checkpoint();init_co_change_analyzer();init_zod();init_loader();init_pr_workflow_gate();init_create_tool();var CompletePrWorkflowArgsSchema=exports_external.object({mode:exports_external.enum(["PR_REVIEW","PR_FEEDBACK"]),pr_head_sha:exports_external.string().trim().min(1).max(80),report_verdict:exports_external.enum(["APPROVE","REQUEST_CHANGES","INCOMPLETE"]).optional()}).strict().superRefine((value,ctx)=>{if(value.mode==="PR_REVIEW"&&value.report_verdict===void 0)ctx.addIssue({code:"custom",path:["report_verdict"],message:"is required for PR_REVIEW completion (issue #2383 terminal report)"})});async function executeCompletePrWorkflow(args2,directory,context={}){let parsed=CompletePrWorkflowArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,message:`Invalid PR workflow completion: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`});if(!context.sessionID?.trim())return JSON.stringify({success:!1,message:"PR workflow completion requires an active sessionID"});let staleDisclosure={},laneLiveness;try{let config3=loadPluginConfig(directory),hooks2=config3.hooks;laneLiveness={laneLivenessWatchdog:config3.lane_liveness_watchdog,backgroundPendingTimeoutMs:hooks2?.background_pending_timeout_minutes!==void 0?hooks2.background_pending_timeout_minutes*60000:void 0}}catch{}try{let settlement=await _internals252.settlePresumedStalePrWorkflowLanes(directory,context.sessionID,laneLiveness);if(settlement.presumedStaleLaneIds.length>0)staleDisclosure={presumed_stale_lanes:settlement.presumedStaleLaneIds,presumed_stale_disclosure:settlement.disclosure};if(settlement.probedAliveLaneIds?.length)staleDisclosure.probe_retained_lanes=settlement.probedAliveLaneIds;if(settlement.probeDegradedReason)staleDisclosure.probe_status=settlement.probeDegradedReason;if(settlement.horizonConflictNote)staleDisclosure.horizon_conflict=settlement.horizonConflictNote}catch{}let amendmentDisclosure={};try{let gateState=await _internals252.readPrWorkflowGateState(directory,context.sessionID);if(gateState?.prFeedbackInventoryAmendments?.length)amendmentDisclosure={inventory_amendments:gateState.prFeedbackInventoryAmendments}}catch{}try{let terminalReport;if(parsed.data.mode==="PR_REVIEW"){let coverage=null;try{coverage=await _internals252.readPrReviewTerminalCoverageForReport(directory,context.sessionID)}catch{}if(coverage){let findingPolicy;try{findingPolicy=await _internals252.readPrReviewFinalFindingPolicyForReport(directory,context.sessionID)}catch{}terminalReport={kind:coverage.kind,covered_dimensions:coverage.coveredDimensions,unresolved_dimensions:coverage.unresolvedDimensions,live_dimensions:coverage.liveDimensions,allowed_verdicts:findingPolicy?.permittedVerdicts??coverage.allowedVerdicts,...findingPolicy?{finding_policy_version:findingPolicy.policyVersion,blocking_finding_ids:findingPolicy.blockingFindingIds}:{},report_verdict:parsed.data.report_verdict}}}let status2=await _internals252.completePrWorkflow(directory,context.sessionID,parsed.data.mode,parsed.data.pr_head_sha,parsed.data.mode==="PR_REVIEW"?{reportVerdict:parsed.data.report_verdict,...laneLiveness?{laneLiveness}:{}}:laneLiveness?{laneLiveness}:void 0),checkoutRestoreRequired=!1,checkoutRestoreReceipts=[];if(status2==="completed")try{checkoutRestoreReceipts=await _internals252.listPendingPrWorkflowCheckoutRestores(directory,context.sessionID),checkoutRestoreRequired=checkoutRestoreReceipts.length>0}catch{checkoutRestoreRequired=!0}return JSON.stringify({success:!0,mode:parsed.data.mode,pr_head_sha:parsed.data.pr_head_sha,status:status2,ready_to_publish:status2==="ready-to-publish",verified_no_change:status2==="verified-no-change",gate_cleared:status2==="completed"||status2==="verified-no-change",checkout_restore_required:checkoutRestoreRequired,checkout_restore_receipts:checkoutRestoreReceipts,...terminalReport?{terminal_report:terminalReport}:{},...staleDisclosure,...amendmentDisclosure})}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:String(error93),...staleDisclosure,...amendmentDisclosure})}}var complete_pr_workflow=createSwarmTool({description:"Validate terminal PR workflow coverage. After the ordered PR_FEEDBACK gates permit one standalone commit, the first call requires a clean tree and a non-merge direct child of intake HEAD, then binds its structured upstream target; the second clears only after both the local tracking ref and an actual-remote query point to that exact commit. A cleared result reports checkout_restore_required when preserved pre-workflow changes must be restored.",args:{mode:CompletePrWorkflowArgsSchema.shape.mode,pr_head_sha:CompletePrWorkflowArgsSchema.shape.pr_head_sha,report_verdict:CompletePrWorkflowArgsSchema.shape.report_verdict},execute:executeCompletePrWorkflow}),_internals252={completePrWorkflow,listPendingPrWorkflowCheckoutRestores,readPrWorkflowGateState,readPrReviewTerminalCoverageForReport,readPrReviewFinalFindingPolicyForReport,settlePresumedStalePrWorkflowLanes};init_zod();init_utils2();init_state2();init_swarm_artifact_cache();init_create_tool();init_resolve_working_directory();import*as fs177 from"node:fs";import*as path309 from"node:path";function extractMatches(regex,text){return Array.from(text.matchAll(regex))}function parseIdentifiers(description){let identifiers=new Set,backtickRegex=/`([^`]+)`/g;for(let match of extractMatches(backtickRegex,description))identifiers.add(match[1]);let camelCaseRegex=/\b([a-z][a-zA-Z0-9]{2,})\b/g;for(let match of extractMatches(camelCaseRegex,description)){let word=match[1];if(word==="the"||word==="and"||word==="for"||word==="have"||word==="this"||word==="with"||word==="from"||word==="they"||word==="been"||word==="will"||word==="your"||word==="also")continue;identifiers.add(word)}let pascalCaseRegex=/\b([A-Z][a-zA-Z0-9]{2,})\b/g;for(let match of extractMatches(pascalCaseRegex,description))identifiers.add(match[1]);let configKeyRegex=/\b([a-z][a-zA-Z0-9]*(?:\.[a-z][a-zA-Z0-9]*)+)\b/g;for(let match of extractMatches(configKeyRegex,description))identifiers.add(match[1]);let quotedPathRegex=/['"](\.{0,3}(?:src|lib|test)[/\\][^'"]+)['"]/g;for(let match of extractMatches(quotedPathRegex,description))identifiers.add(match[1]);return Array.from(identifiers)}function parseFilePaths(description,filesTouched){if(filesTouched&&Array.isArray(filesTouched)&&filesTouched.length>0)return filesTouched;let filePaths=[],srcPathRegex=/\b(?:src|lib|test|app|packages?)[/\\][a-zA-Z0-9_./-]+\.(?:ts|tsx|js|jsx|mjs|cjs)\b/g;for(let match of extractMatches(srcPathRegex,description))filePaths.push(match[0]);let genericPathRegex=/\b[a-zA-Z0-9_./-]+[/\\][a-zA-Z0-9_./-]+\.[a-zA-Z0-9]+(?=\s|$|[.,;])/g;for(let match of extractMatches(genericPathRegex,description)){let pathStr=match[0];if(pathStr.includes("src/")||pathStr.includes("src\\")||pathStr.includes("lib/")||pathStr.includes("lib\\")||pathStr.includes("test/")||pathStr.includes("test\\"))filePaths.push(pathStr)}return filePaths}function buildVerifySummary(tasksChecked,tasksSkipped,tasksBlocked){if(tasksBlocked>0)return`Blocked: ${tasksBlocked} task(s) with missing identifiers`;let verified=tasksChecked-tasksSkipped;if(tasksSkipped===tasksChecked)return`All ${tasksChecked} completed task(s) skipped — research/inventory tasks`;if(tasksSkipped>0)return`${verified} task(s) verified, ${tasksSkipped} skipped (research tasks)`;return`All ${tasksChecked} completed tasks verified successfully`}async function executeCompletionVerify(args2,directory){let phase=Number(args2.phase);if(Number.isNaN(phase)||phase<1||!Number.isFinite(phase))return JSON.stringify({success:!1,phase,status:"blocked",reason:"Invalid phase number",tasksChecked:0,tasksSkipped:0,tasksBlocked:0,blockedTasks:[]},null,2);if(hasActiveTurboMode(args2.sessionID))return JSON.stringify({success:!0,phase,status:"passed",reason:"Turbo Mode active — completion verification bypassed",tasksChecked:0,tasksSkipped:0,tasksBlocked:0,blockedTasks:[]},null,2);let plan;try{let planPath=validateSwarmPath(directory,"plan.json"),planRaw=fs177.readFileSync(planPath,"utf-8");plan=JSON.parse(planRaw)}catch{return JSON.stringify({success:!0,phase,status:"passed",reason:"Cannot verify without plan.json",tasksChecked:0,tasksSkipped:0,tasksBlocked:0,blockedTasks:[]},null,2)}let targetPhase=plan.phases.find((p)=>p.id===phase);if(!targetPhase){let result2={success:!1,phase,status:"blocked",reason:`Phase ${phase} not found in plan.json`,tasksChecked:0,tasksSkipped:0,tasksBlocked:0,blockedTasks:[]};return JSON.stringify(result2,null,2)}let tasksChecked=0,tasksSkipped=0,tasksBlocked=0,blockedTasks=[];for(let task2 of targetPhase.tasks){if(task2.status!=="completed")continue;tasksChecked++;let fileTargets=parseFilePaths(task2.description,task2.files_touched),identifiers=parseIdentifiers(task2.description);if(fileTargets.length===0){tasksSkipped++;continue}if(identifiers.length===0){blockedTasks.push({task_id:task2.id,identifier:"",file_path:"",reason:"No identifiers — cannot verify completion without identifiers"}),tasksBlocked++;continue}let foundIdentifiers=new Set,hasFileReadFailure=!1;for(let filePath of fileTargets){let normalizedPath=filePath.replace(/\\/g,"/"),resolvedPath=path309.resolve(directory,normalizedPath),projectRoot=path309.resolve(directory),relative77=path309.relative(projectRoot,resolvedPath);if(!(relative77===""||!relative77.startsWith("..")&&!path309.isAbsolute(relative77))){blockedTasks.push({task_id:task2.id,identifier:"",file_path:filePath,reason:`File path '${filePath}' escapes the project directory — cannot verify completion`}),hasFileReadFailure=!0;continue}let fileContent;try{fileContent=fs177.readFileSync(resolvedPath,"utf-8")}catch{blockedTasks.push({task_id:task2.id,identifier:"",file_path:filePath,reason:`File '${filePath}' not found — cannot verify completion`}),hasFileReadFailure=!0;continue}for(let identifier of identifiers)if(fileContent.includes(identifier))foundIdentifiers.add(identifier)}let foundCount=foundIdentifiers.size;if(hasFileReadFailure||foundCount===0){if(!hasFileReadFailure)blockedTasks.push({task_id:task2.id,identifier:"",file_path:"",reason:"No identifiers found in target files"});tasksBlocked++}}let now2=new Date().toISOString(),result={success:tasksBlocked===0,phase,status:tasksBlocked===0?"passed":"blocked",reason:tasksBlocked>0?`COMPLETION_INCOMPLETE: ${tasksBlocked} task(s) blocked — missing identifiers or target files`:void 0,tasksChecked,tasksSkipped,tasksBlocked,blockedTasks};if(args2.writeEvidence!==!1)try{let evidenceDir=path309.join(directory,".swarm","evidence",`${phase}`),evidencePath=path309.join(evidenceDir,"completion-verify.json");fs177.mkdirSync(evidenceDir,{recursive:!0});let evidenceBundle={schema_version:"1.0.0",task_id:"completion-verify",created_at:now2,entries:[{task_id:"completion-verify",type:"completion_verify",timestamp:now2,agent:"completion_verify",verdict:tasksBlocked===0?"pass":"fail",summary:buildVerifySummary(tasksChecked,tasksSkipped,tasksBlocked),phase,tasks_checked:tasksChecked,tasks_skipped:tasksSkipped,tasks_blocked:tasksBlocked,blocked_tasks:blockedTasks}]};fs177.writeFileSync(evidencePath,JSON.stringify(evidenceBundle,null,2),"utf-8"),invalidateCachedArtifact(evidencePath)}catch{}return JSON.stringify(result,null,2)}var completion_verify=createSwarmTool({description:"Deterministic pre-check verifying that plan task identifiers exist in their target source files before phase completion. Blocks if obviously incomplete.",args:{phase:exports_external.number().describe("The phase number to check"),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.")},execute:async(args2,directory)=>{let parsedArgs;try{if(args2&&typeof args2==="object"){let obj=args2;parsedArgs={phase:typeof obj.phase==="number"?obj.phase:typeof obj.phase==="string"?Number(obj.phase):0,sessionID:typeof obj.sessionID==="string"?obj.sessionID:void 0,working_directory:typeof obj.working_directory==="string"?obj.working_directory:void 0}}else parsedArgs={phase:0}}catch{return JSON.stringify({success:!1,phase:0,status:"blocked",reason:"Invalid arguments",tasksChecked:0,tasksSkipped:0,tasksBlocked:0,blockedTasks:[]},null,2)}let dirResult=resolveWorkingDirectory(parsedArgs.working_directory,directory);if(!dirResult.success)return JSON.stringify({success:!1,phase:parsedArgs.phase,status:"blocked",reason:dirResult.message,tasksChecked:0,tasksSkipped:0,tasksBlocked:0,blockedTasks:[]},null,2);return executeCompletionVerify(parsedArgs,dirResult.directory)}});init_zod();init_metrics();init_bun_compat();init_git_executable();init_create_tool();init_path_security();import{Buffer as Buffer4}from"node:buffer";import*as fs178 from"node:fs";import*as path310 from"node:path";var MAX_FILE_SIZE_BYTES5=262144,DEFAULT_DAYS=90,DEFAULT_TOP_N2=20,DEFAULT_EXTENSIONS="ts,tsx,js,jsx,py,rs,ps1",SHELL_METACHAR_REGEX=/[;&|%$`\\]/;function validateDays(days){if(typeof days>"u")return{valid:!0,value:DEFAULT_DAYS,error:null};if(typeof days!=="number"||!Number.isInteger(days))return{valid:!1,value:0,error:"days must be an integer"};if(days<1||days>365)return{valid:!1,value:0,error:"days must be between 1 and 365"};return{valid:!0,value:days,error:null}}function validateTopN(topN){if(typeof topN>"u")return{valid:!0,value:DEFAULT_TOP_N2,error:null};if(typeof topN!=="number"||!Number.isInteger(topN))return{valid:!1,value:0,error:"top_n must be an integer"};if(topN<1||topN>100)return{valid:!1,value:0,error:"top_n must be between 1 and 100"};return{valid:!0,value:topN,error:null}}function validateExtensions(extensions){if(typeof extensions>"u")return{valid:!0,value:DEFAULT_EXTENSIONS,error:null};if(typeof extensions!=="string")return{valid:!1,value:"",error:"extensions must be a string"};if(containsControlChars(extensions))return{valid:!1,value:"",error:"extensions contains control characters"};if(SHELL_METACHAR_REGEX.test(extensions))return{valid:!1,value:"",error:"extensions contains shell metacharacters (;|&%$`\\)"};if(!/^[a-zA-Z0-9,.]+$/.test(extensions))return{valid:!1,value:"",error:"extensions contains invalid characters (only alphanumeric, commas, dots allowed)"};return{valid:!0,value:extensions,error:null}}var _internals253={bunSpawn,resolveGitExecutable},GIT_CHURN_TIMEOUT_MS=1e4,GIT_CHURN_MAX_BUFFER_BYTES=5242880;async function getGitChurn(days,directory){let churnMap=new Map,proc=_internals253.bunSpawn([_internals253.resolveGitExecutable(),"log",`--since=${days} days ago`,"--name-only","--pretty=format:"],{stdout:"pipe",stderr:"pipe",stdin:"ignore",cwd:directory,timeout:GIT_CHURN_TIMEOUT_MS,maxBuffer:GIT_CHURN_MAX_BUFFER_BYTES,killProcessTree:!0,env:{...process.env,GIT_TERMINAL_PROMPT:"0"}}),churnTimeout;try{let[stdout,outcome]=await Promise.race([Promise.all([proc.stdout.text(),proc.exited]).then((churnOutput)=>churnOutput),new Promise((resolve125)=>{churnTimeout=setTimeout(()=>resolve125([null,"timeout"]),GIT_CHURN_TIMEOUT_MS)})]);if(typeof churnTimeout<"u")clearTimeout(churnTimeout);if(outcome==="timeout")throw Error(`git churn analysis failed: git log did not finish within ${GIT_CHURN_TIMEOUT_MS} ms (bounded; child tree killed)`);if(proc.spawnError)throw Error(`git churn analysis failed: ${proc.spawnError.message}`);if(proc.signalCode)throw Error(`git churn analysis failed: git log was killed by ${proc.signalCode} after exceeding the ${GIT_CHURN_TIMEOUT_MS} ms / ${GIT_CHURN_MAX_BUFFER_BYTES}-byte bound`);if(Buffer4.byteLength(stdout)>=GIT_CHURN_MAX_BUFFER_BYTES)throw Error(`git churn analysis failed: git log output reached the ${GIT_CHURN_MAX_BUFFER_BYTES}-byte buffer limit`);let lines=stdout.split(/\r?\n/);for(let line of lines){let normalizedPath=line.replace(/\\/g,"/");if(!normalizedPath||normalizedPath.trim()==="")continue;if(normalizedPath.includes("node_modules")||normalizedPath.includes("/.git/")||normalizedPath.includes("/dist/")||normalizedPath.includes("/build/")||normalizedPath.includes("__tests__"))continue;if(normalizedPath.includes(".test.")||normalizedPath.includes(".spec."))continue;churnMap.set(normalizedPath,(churnMap.get(normalizedPath)||0)+1)}}finally{if(typeof churnTimeout<"u")clearTimeout(churnTimeout);try{proc.kill()}catch{}}return churnMap}function getComplexityForFile2(filePath){try{if(fs178.statSync(filePath).size>MAX_FILE_SIZE_BYTES5)return null;let content=fs178.readFileSync(filePath,"utf-8");return estimateCyclomaticComplexity(content)}catch{return null}}async function analyzeHotspots(days,topN,extensions,directory){let churnMap=await getGitChurn(days,directory),extSet=new Set(extensions.map((e)=>e.startsWith(".")?e:`.${e}`)),filteredChurn=new Map;for(let[file3,count]of churnMap){let ext=path310.extname(file3).toLowerCase();if(extSet.has(ext))filteredChurn.set(file3,count)}let hotspots=[],cwd=directory,analyzedFiles=0;for(let[file3,churnCount]of filteredChurn){let fullPath=file3;if(!fs178.existsSync(fullPath))fullPath=path310.join(cwd,file3);let complexity=getComplexityForFile2(fullPath);if(complexity!==null){analyzedFiles++;let riskScore=Math.round(churnCount*Math.log2(Math.max(complexity,1))*10)/10,recommendation;if(riskScore>=50)recommendation="full_gates";else if(riskScore>=30)recommendation="security_review";else if(riskScore>=15)recommendation="enhanced_review";else recommendation="standard";hotspots.push({file:file3,churnCount,complexity,riskScore,recommendation})}}hotspots.sort((a,b)=>b.riskScore-a.riskScore);let topHotspots=hotspots.slice(0,topN),summary={fullGates:topHotspots.filter((h)=>h.recommendation==="full_gates").length,securityReview:topHotspots.filter((h)=>h.recommendation==="security_review").length,enhancedReview:topHotspots.filter((h)=>h.recommendation==="enhanced_review").length,standard:topHotspots.filter((h)=>h.recommendation==="standard").length};return{analyzedFiles,period:`${days} days`,hotspots:topHotspots,summary}}var complexity_hotspots=createSwarmTool({description:"Identify high-risk code hotspots by combining git churn frequency with cyclomatic complexity estimates. Returns files with their churn count, complexity score, risk score, and recommended review level.",args:{days:exports_external.number().optional().describe("Number of days of git history to analyze (default: 90, valid range: 1-365)"),top_n:exports_external.number().optional().describe("Number of top hotspots to return (default: 20, valid range: 1-100)"),extensions:exports_external.string().optional().describe('Comma-separated extensions to include (default: "ts,tsx,js,jsx,py,rs,ps1")')},async execute(args2,directory){if(!directory||typeof directory!=="string"||directory.trim()==="")return JSON.stringify({error:"project directory is required but was not provided",analyzedFiles:0,period:"0 days",hotspots:[],summary:{fullGates:0,securityReview:0,enhancedReview:0,standard:0}},null,2);let daysInput,topNInput,extensionsInput;try{if(args2&&typeof args2==="object"){let obj=args2;daysInput=typeof obj.days==="number"?obj.days:void 0,topNInput=typeof obj.top_n==="number"?obj.top_n:void 0,extensionsInput=typeof obj.extensions==="string"?obj.extensions:void 0}}catch{}let daysValidation=validateDays(daysInput);if(!daysValidation.valid){let errorResult={error:`invalid days: ${daysValidation.error}`,analyzedFiles:0,period:"0 days",hotspots:[],summary:{fullGates:0,securityReview:0,enhancedReview:0,standard:0}};return JSON.stringify(errorResult,null,2)}let topNValidation=validateTopN(topNInput);if(!topNValidation.valid){let errorResult={error:`invalid top_n: ${topNValidation.error}`,analyzedFiles:0,period:"0 days",hotspots:[],summary:{fullGates:0,securityReview:0,enhancedReview:0,standard:0}};return JSON.stringify(errorResult,null,2)}let extensionsValidation=validateExtensions(extensionsInput);if(!extensionsValidation.valid){let errorResult={error:`invalid extensions: ${extensionsValidation.error}`,analyzedFiles:0,period:"0 days",hotspots:[],summary:{fullGates:0,securityReview:0,enhancedReview:0,standard:0}};return JSON.stringify(errorResult,null,2)}let days=daysValidation.value,topN=topNValidation.value,extensions=extensionsValidation.value.split(",").map((e)=>e.trim());try{let result=await analyzeHotspots(days,topN,extensions,directory);return JSON.stringify(result,null,2)}catch(e){let errorResult={error:e instanceof Error?`analysis failed: ${e.message}`:"analysis failed: unknown error",analyzedFiles:0,period:`${days} days`,hotspots:[],summary:{fullGates:0,securityReview:0,enhancedReview:0,standard:0}};return JSON.stringify(errorResult,null,2)}}});init_zod();init_config();init_schema();init_miner();init_miner();init_store4();async function mineAndStoreConsensusV1(options){let priorFingerprints=options.deps.priorFingerprints??await listConsensusProposalFingerprints(options.directory),result=await mineConsensus(options.directory,options.request,{...options.deps,priorFingerprints}),report=await writeConsensusReport(options.directory,result.report);return{...result,report}}init_store4();init_memory();init_recommendation_ledger();init_state2();init_logger();init_create_tool();var MAX_FILTER_ENTRIES=200,FilterListSchema=exports_external.array(exports_external.string().min(1).max(512)).max(MAX_FILTER_ENTRIES),MAX_INLINE_ATTRIBUTES=25;function countSummaries(attributes,inlineLimit){let total=0,shown=0;for(let[index,attribute]of attributes.entries()){if(attribute.llmSummary===void 0)continue;if(total+=1,index<inlineLimit)shown+=1}return{total,hidden:total-shown}}function buildMinerRecommendationCandidates(report,sessionId){return report.proposals.map((proposal)=>({kind:"miner",target:proposal.target,statement:proposal.intent,scopeKeys:[],provenance:{mechanism:"consensus_mine",sourceEvidenceRefs:proposal.evidenceRefs,sourceRunIds:proposal.provenance.sourceRunIds,sourceModelIds:proposal.provenance.sourceModelIds,sourceTaskIds:proposal.provenance.sourceTaskIds},origin:{agentRole:"consensus_mine",...sessionId?{sessionId}:{},producedAt:report.generatedAt}}))}var MIRRORED_PROPOSAL_KIND="todo";async function mirrorProposalsToMemory(options){if(options.memoryConfig?.enabled!==!0)return{enabled:!1,attempted:0,proposed:0,rejected:0,failed:0};let proposals=options.report.proposals;if(proposals.length===0)return{enabled:!0,attempted:0,proposed:0,rejected:0,failed:0};let gateway;try{gateway=_internals254.createMemoryGateway({directory:options.directory,...options.sessionId?{sessionID:options.sessionId,runId:options.sessionId}:{},agentRole:"consensus_mine"},{config:options.memoryConfig})}catch(err){let message=err instanceof Error?err.message:String(err);return warn(`[consensus_mine] memory mirror unavailable (fail-open): ${message}`),{enabled:!0,attempted:proposals.length,proposed:0,rejected:0,failed:proposals.length,error:message}}let proposed=0,rejected2=0,failed=0,error93;try{for(let proposal of proposals)try{if((await gateway.propose({operation:"add",kind:MIRRORED_PROPOSAL_KIND,text:proposal.intent,rationale:`consensus_mine proposal from report ${options.report.reportId}, attribute ${proposal.sourceAttributeId} (target ${proposal.target}, confidence ${proposal.confidence})`,evidenceRefs:proposal.evidenceRefs})).status==="rejected")rejected2+=1;else proposed+=1}catch(err){failed+=1,error93??=err instanceof Error?err.message:String(err)}}finally{try{await gateway.dispose()}catch(err){warn(`[consensus_mine] memory gateway dispose failed: ${err instanceof Error?err.message:String(err)}`)}}if(error93!==void 0)warn(`[consensus_mine] memory mirror partially failed: ${error93}`);return{enabled:!0,attempted:proposals.length,proposed,rejected:rejected2,failed,...error93?{error:error93}:{}}}var _internals254={createMemoryGateway};var consensus_mine=createSwarmTool({description:"Mine cross-run consensus from existing .swarm evidence — evaluation runs, gate audits, gate "+"ground truth, task trajectories, PRM sessions, skill usage, knowledge outcomes, evidence "+"bundles, and curated failures (nine sources) — and persist an immutable report of "+`agreed-upon attributes plus proposals-only recommendations. It never activates a skill, writes a knowledge entry, admits a durable memory record, edits a project file, or mutates any evidence it reads. It is NOT otherwise write-minimal, so plan for these effects: it DELETES its own older reports past consensus.report_retention (default 50) on every run; it rewrites the shared recommendation dedup ledger whole, with FIFO eviction that can drop another producer's oldest entries; it leaves one never-removed lock sentinel per report id under .swarm/locks/; when memory.enabled is true it mirrors each proposal into a PENDING swarm-memory proposal (curator review still required); and when consensus.llm_summarization_enabled is true (the default) it issues up to ${MAX_LLM_SUMMARIES} session.create plus session.prompt calls. Under a knowledge or memory link the ledger and the memory store resolve to the shared cohort root, outside this project's .swarm/.`,args:{run_ids:FilterListSchema.optional().describe("Restrict mining to these run ids (raw or namespaced). Omit for all runs."),task_categories:FilterListSchema.optional().describe("Restrict to these evaluation task categories. Omit for all categories."),agent_roles:FilterListSchema.optional().describe("Restrict to these agent roles. Omit for all roles."),model_ids:FilterListSchema.optional().describe("Restrict to these model ids. Omit for all models."),min_support:exports_external.number().int().min(1).max(1e4).optional().describe("Distinct runs required to emit an attribute. Defaults to consensus.default_min_support."),min_successful_runs:exports_external.number().int().min(0).max(1e4).optional().describe("Successful runs required. Defaults to consensus.default_min_successful_runs."),max_evidence_items:exports_external.number().int().min(1).max(1e4).optional().describe("Cap on corpus observations read. Defaults to consensus.default_max_evidence_items.")},execute:async(args2,directory,ctx)=>{let input=args2??{},loaded=loadPluginConfigWithMeta(directory),config3=ConsensusConfigSchema.parse(loaded.config.consensus??{});if(!config3.enabled)return JSON.stringify({success:!1,disabled:!0,message:"Consensus mining is disabled (consensus.enabled = false). No report was written."},null,2);let request={...input.run_ids?{runIds:input.run_ids}:{},...input.task_categories?{taskCategories:input.task_categories}:{},...input.agent_roles?{agentRoles:input.agent_roles}:{},...input.model_ids?{modelIds:input.model_ids}:{},minSupport:input.min_support??config3.default_min_support,minSuccessfulRuns:input.min_successful_runs??config3.default_min_successful_runs,maxEvidenceItems:input.max_evidence_items??config3.default_max_evidence_items},client=swarmState.opencodeClient,dispatcher=config3.llm_summarization_enabled&&client?createEvaluationModelDispatcher(client):void 0,result=await mineAndStoreConsensusV1({directory,request,deps:{config:config3,...dispatcher?{dispatcher}:{},...ctx?.sessionID?{sessionId:ctx.sessionID}:{},agentRole:"consensus_mine"}}),report=result.report,ledger=await recordEmittedRecommendations(directory,buildMinerRecommendationCandidates(report,ctx?.sessionID),{producedAt:report.generatedAt});if(ledger.degraded)warn("[consensus_mine] recommendation ledger write degraded; proposals were not recorded for cross-producer dedup");let memoryMirror=await mirrorProposalsToMemory({directory,memoryConfig:loaded.config.memory,report,...ctx?.sessionID?{sessionId:ctx.sessionID}:{}}),pruned=await pruneConsensusReports(directory,config3.report_retention),pruningEnabled=config3.report_retention>0,summaries=countSummaries(report.attributes,MAX_INLINE_ATTRIBUTES);return JSON.stringify({success:!0,report_id:report.reportId,report_path:`.swarm/evolution/consensus/${report.reportId}.json`,generated_at:report.generatedAt,integrity_hash:report.integrityHash,config_hash:report.configHash,redaction_policy_version:report.redactionPolicyVersion,thresholds:{min_support:request.minSupport,min_successful_runs:request.minSuccessfulRuns,max_evidence_items:request.maxEvidenceItems,min_task_diversity:MIN_TASK_DIVERSITY_FOR_PROPOSAL,min_support_for_proposal:MIN_SUPPORT_FOR_PROPOSAL},input_run_count:report.inputIds.length,corpus:report.corpusHashes.map((entry)=>({source:entry.source,observations:entry.observations})),corpus_truncated:result.truncated,truncation:{corpus:report.truncation.corpus,observations_tallied:report.truncation.observations,input_ids_truncated:report.truncation.inputIds,total_input_ids:report.truncation.totalInputIds,attributes_dropped:report.truncation.attributesDropped},unreadable_sources:result.unreadableSources,attribute_count:report.attributes.length,investigation_note_count:result.investigationNoteCount,proposal_count:report.proposals.length,deduped_proposal_count:result.dedupedProposalCount,recommendation_ledger:{recorded:ledger.recorded,duplicate_recommendation_count:ledger.suppressed,evicted:ledger.evicted,degraded:ledger.degraded},memory_mirror:memoryMirror,summarized_count:summaries.total,summarized_but_not_shown:summaries.hidden,restatements_accepted_this_run:result.summarizedCount,...result.summarizationSkippedReason?{summarization_skipped_reason:result.summarizationSkippedReason}:{},attributes:report.attributes.slice(0,MAX_INLINE_ATTRIBUTES).map((attribute)=>({id:attribute.id,statement:attribute.statement,...attribute.llmSummary?{llm_summary:attribute.llmSummary}:{},support:attribute.support,success_support:attribute.successSupport,failure_support:attribute.failureSupport,task_diversity:attribute.taskDiversity,model_diversity:attribute.modelDiversity,confidence:attribute.confidence,proposed_target:attribute.proposedTarget,counterexample_count:attribute.counterexampleRefs.length})),attributes_truncated:report.attributes.length>MAX_INLINE_ATTRIBUTES,retention:pruningEnabled?{configured:config3.report_retention,pruning_enabled:!0,deleted:pruned.deleted.length,retained:pruned.retained.length,failed:pruned.failed.length,corrupt:pruned.corrupt.length}:{configured:config3.report_retention,pruning_enabled:!1,deleted:0,failed:0},guarantees:["proposals only — no skill activation, no knowledge write, no durable memory record, and no mutation of any evidence read",'model_diversity 0 means "not measurable from this corpus", never "measured as none"',`attributes below task diversity ${MIN_TASK_DIVERSITY_FOR_PROPOSAL} or below support ${MIN_SUPPORT_FOR_PROPOSAL} are investigation notes, never proposals`,"an attribute counting failing runs always carries counterexample refs (schema-enforced)","truncation is not biased toward successes, but it is still a cut: it balances per source, and drops whole sources once the budget is spent","statement is deterministic; llm_summary is an optional restatement excluded from integrity_hash","reproducible: identical corpus, request, config_hash, and prior proposals yield the same integrity_hash and report_id; model wording never moves it",'truncation is declared on the report; read failure_support 0 on a truncated report as "none survived the cut"']},null,2)}});init_config();init_model_limits();init_state2();init_create_tool();var _internals255={loadPluginConfig,fetchSessionMessages:async(sessionID,directory,limit=100)=>{if(!swarmState.opencodeClient?.session)return null;try{return(await swarmState.opencodeClient.session.messages({path:{id:sessionID},query:{directory,limit}})).data??null}catch{return null}}};function computeContextHeadroom(messages,warnThreshold=0.7,criticalThreshold=0.9,modelLimitsConfig={},liveContextLimit,modelIdentity,directory){let{modelID,providerID}=modelIdentity??extractModelInfo(messages),modelLimitResolution=resolveModelLimit(modelID,providerID,modelLimitsConfig,liveContextLimit,directory),modelLimit=modelLimitResolution.limit,usage=computeContextUsage(messages),usagePercent=usage.tokensUsed/modelLimit,thresholdCrossed="none";if(usagePercent>criticalThreshold)thresholdCrossed="critical";else if(usagePercent>warnThreshold)thresholdCrossed="warn";return{tokensUsed:usage.tokensUsed,usageSource:usage.source,modelLimit,modelLimitSource:modelLimitResolution.source,modelLimitResolution:modelLimitResolution.resolution,fallbackActive:modelLimitResolution.source==="provider_cap"||modelLimitResolution.source==="native"||modelLimitResolution.source==="fallback",usagePercent,thresholdCrossed,modelId:modelID??null,provider:providerID??null}}var context_status=createSwarmTool({allowWorkingDirectoryOverride:!0,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.",args:{},async execute(_args,directory,ctx){let config3=_internals255.loadPluginConfig(directory),warnThreshold=config3.context_budget?.warn_threshold??0.7,criticalThreshold=config3.context_budget?.critical_threshold??0.9,modelLimitsConfig=config3.context_budget?.model_limits??{},messages=[];if(ctx?.sessionID){let sessionMessages=await _internals255.fetchSessionMessages(ctx.sessionID,directory);if(sessionMessages)messages=sessionMessages}let{modelID,providerID}=getLiveContextModelIdentity(ctx?.sessionID)??extractModelInfo(messages),headroom=computeContextHeadroom(messages,warnThreshold,criticalThreshold,modelLimitsConfig,getLiveContextWindow(ctx?.sessionID,{modelID,providerID}),{modelID,providerID},directory);return JSON.stringify(headroom,null,2)}});init_zod();init_loader();function pushCouncilAdvisory(session,synthesis){let dedupKey=`council:${synthesis.taskId}:${synthesis.roundNumber}`;if(synthesis.overallVerdict==="APPROVE"&&synthesis.advisoryFindings.length===0)return;if(session.pendingAdvisoryMessages??=[],session.pendingAdvisoryMessages.some((m)=>m.includes(dedupKey)))return;let blocking=synthesis.overallVerdict==="REJECT",header=`[${dedupKey}] (priority=HIGH, blocking=${blocking})`,body=synthesis.unifiedFeedbackMd;pushAdvisory(session,`${header}
|
|
7532
|
+
`);return truncated}function getCommandKind(command){let lower=command.toLowerCase();if(lower.includes("typecheck")||lower.includes("check")||lower.includes("analyze")||lower.includes("lint"))return"typecheck";if(lower.includes("test")||lower.includes("spec")||lower.includes("jest")||lower.includes("vitest")||lower.includes("mocha")||lower.includes("pytest"))return"test";return"build"}function filterByMode(commands,mode){if(mode==="both")return commands;return commands.filter((cmd)=>getCommandKind(cmd.command)===mode)}async function executeCommand(command){let startTime=Date.now(),kind=getCommandKind(command.command),isWindows=process.platform==="win32",cmd,args2;if(isWindows&&!command.command.includes(" "))cmd=[command.command],args2=[];else if(isWindows)cmd=["cmd","/c",command.command],args2=[];else cmd=["/bin/sh"],args2=["-c",command.command];let proc=_internals251.bunSpawn([...cmd,...args2],{cwd:command.cwd,stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:DEFAULT_TIMEOUT_MS4,maxBuffer:DEFAULT_BUN_SPAWN_MAX_BUFFER_BYTES});try{let[exitCode,stdout,stderr]=await Promise.all([proc.exited,proc.stdout.text(),proc.stderr.text()]),duration_ms=Date.now()-startTime;return{kind,command:command.command,cwd:command.cwd,exit_code:exitCode??-1,duration_ms,stdout_tail:truncateOutput(stdout),stderr_tail:truncateOutput(stderr)}}finally{try{proc.kill()}catch{}}}async function runBuildCheck(workingDir,input){let scope=input.scope??"all",mode=input.mode??"both",changedFiles=input.changed_files??[],discoveryResult=await discoverBuildCommands(workingDir,{scope,changedFiles}),commands=filterByMode(discoveryResult.commands,mode),runs=[],failedCount=0;for(let cmd of commands)try{let run=await executeCommand(cmd);if(runs.push(run),run.exit_code!==0)failedCount++}catch(error93){runs.push({kind:getCommandKind(cmd.command),command:cmd.command,cwd:cmd.cwd,exit_code:-1,duration_ms:0,stdout_tail:"",stderr_tail:error93 instanceof Error?error93.message:"Unknown error"}),failedCount++}let verdict,skipped_reason,environmentUnavailable=discoveryResult.skipped.filter((skip)=>skip.code==="environment_unavailable");if(runs.length===0)if(verdict=environmentUnavailable.length>0?"skip":"info",discoveryResult.skipped.length>0)skipped_reason=discoveryResult.skipped.map((s)=>`${s.ecosystem}: ${s.reason}`).join("; ");else skipped_reason=NO_BUILD_FILES_DISCOVERED_REASON;else if(failedCount>0)verdict="fail";else verdict="pass";return{verdict,runs,summary:{files_scanned:changedFiles.length,runs_count:runs.length,failed_count:failedCount,skipped_reason,environment_unavailable:environmentUnavailable.length>0?environmentUnavailable:void 0}}}var build_check=createSwarmTool({allowWorkingDirectoryOverride:!0,description:"Discover and run build commands for various ecosystems in a project directory. Supports build, typecheck, and test commands.",args:{scope:exports_external.enum(["changed","all"]).describe('Scope of detection: "all" for all build files, "changed" for only changed files'),changed_files:exports_external.array(exports_external.string()).optional().describe('List of changed files when scope is "changed"'),mode:exports_external.enum(["build","typecheck","both"]).optional().describe('Mode: "build" for build commands, "typecheck" for type checking, "both" for all (default: both)')},async execute(args2,directory){if(_internals251.loadGateOverrides(directory)?.build_check?.enabled===!1)return JSON.stringify({verdict:"skip",runs:[],summary:{files_scanned:0,runs_count:0,failed_count:0,skipped_reason:"build_check disabled by configuration"}},null,2);let obj=args2,scope=obj.scope??"all",changedFiles=obj.changed_files??[],mode=obj.mode??"both",workingDir=directory,result=await runBuildCheck(workingDir,{scope,changed_files:changedFiles,mode}),evidence2={task_id:"build",type:"build",timestamp:new Date().toISOString(),agent:"build_check",verdict:result.verdict,summary:`${result.runs.length} build command(s) executed, ${result.summary.failed_count} failed`,runs:result.runs,files_scanned:result.summary.files_scanned,runs_count:result.summary.runs_count,failed_count:result.summary.failed_count,skipped_reason:result.summary.skipped_reason,environment_unavailable:result.summary.environment_unavailable};try{await saveEvidence(workingDir,"build",evidence2)}catch(error93){log("Failed to save build evidence:",error93 instanceof Error?error93.message:String(error93))}return JSON.stringify(result,null,2)}});init_zod();init_config();init_manager2();init_gate_evidence();import*as fs176 from"node:fs";import*as path308 from"node:path";var TODO_GATE_DEFAULTS={enabled:!0,max_high_priority:0,block_on_threshold:!1};function formatDetails(details,count){if(!details||details.length===0)return"";let lines=details.map((line)=>` - ${line}`).join(`
|
|
7533
|
+
`);return details.length<count?`${lines}
|
|
7534
|
+
(showing first ${details.length} of ${count})`:lines}function repairStep(){return"Repair: resolve or remove the high-priority TODO comments listed above, or adjust the todo_gate config (raise max_high_priority / set enabled: false), then re-run todo_extract with the same task_id to refresh the recorded evidence."}function isTodoThresholdExceeded(count,maxHighPriority){return maxHighPriority>=0&&count>maxHighPriority}function evaluateTodoGate(todoScan,todoGate){let enabled=todoGate?.enabled??TODO_GATE_DEFAULTS.enabled,max=todoGate?.max_high_priority??TODO_GATE_DEFAULTS.max_high_priority,blockOnThreshold=todoGate?.block_on_threshold??TODO_GATE_DEFAULTS.block_on_threshold;if(enabled===!1)return{status:"disabled",blocked:!1,advisory:!1,count:0,max};if(!todoScan)return{status:"no-evidence",blocked:!1,advisory:!1,count:0,max};let count=todoScan.count;if(!isTodoThresholdExceeded(count,max))return{status:"pass",blocked:!1,advisory:!1,count,max};let evidence2=formatDetails(todoScan.details,count),summary=`todo_gate: ${count} high-priority TODOs (FIXME/HACK/XXX) exceed max_high_priority=${max}.${evidence2?`
|
|
7535
|
+
Evidence:
|
|
7536
|
+
${evidence2}`:""}`;if(blockOnThreshold)return{status:"exceeded",blocked:!0,advisory:!1,count,max,message:`${summary}
|
|
7537
|
+
${repairStep()}`};return{status:"exceeded",blocked:!1,advisory:!0,count,max,message:`${summary}
|
|
7538
|
+
${repairStep()}`}}init_logger();init_task_id();init_create_tool();init_resolve_working_directory();var EVIDENCE_DIR=".swarm/evidence";function isValidTaskId4(taskId){return isStrictTaskId(taskId)}function isPathWithinSwarm(filePath,workspaceRoot){let normalizedWorkspace=path308.resolve(workspaceRoot),swarmPath3=path308.join(normalizedWorkspace,".swarm","evidence");return path308.resolve(filePath).startsWith(swarmPath3)}function readEvidenceFile(evidencePath){if(!fs176.existsSync(evidencePath))return null;let content;try{content=fs176.readFileSync(evidencePath,"utf-8")}catch{return null}let parsed;try{parsed=JSON.parse(content)}catch{return null}if(parsed&&typeof parsed==="object"&&Array.isArray(parsed.required_gates)&&typeof parsed.gates==="object"&&parsed.gates!==null)return parsed;return null}var check_gate_status=createSwarmTool({description:"Read-only tool to check the gate status of a specific task. Reads .swarm/evidence/{taskId}.json and returns structured JSON describing required, passed, and missing gates.",args:{task_id:exports_external.string().min(1).regex(/^\d+\.\d+(\.\d+)*$/,'Task ID must be in N.M or N.M.P format (e.g., "1.1", "1.2.3", "1.2.3.4")').describe('The task ID to check gate status for (e.g., "1.1", "2.3.1")'),working_directory:exports_external.string().optional().describe("Explicit project root directory. When provided, .swarm/evidence/ is resolved relative to this path instead of the plugin context directory. Use this when CWD differs from the actual project root.")},async execute(args2,directory){let taskIdInput,workingDirInput;try{if(args2&&typeof args2==="object"){let obj=args2;taskIdInput=typeof obj.task_id==="string"?obj.task_id:void 0,workingDirInput=typeof obj.working_directory==="string"?obj.working_directory:void 0}}catch{}let dirResult=resolveWorkingDirectory(workingDirInput,directory);if(!dirResult.success){let errorResult={taskId:taskIdInput??"",status:"no_evidence",required_gates:[],passed_gates:[],missing_gates:[],gates:{},message:dirResult.message,todo_scan:null};return JSON.stringify(errorResult,null,2)}directory=dirResult.directory;let todoGateConfig;try{todoGateConfig=loadPluginConfigWithMeta(directory).config.todo_gate}catch(configError){log("check_gate_status: todo_gate config load threw; TODO gate evaluation skipped",configError)}if(!taskIdInput)return JSON.stringify({taskId:"",status:"no_evidence",required_gates:[],passed_gates:[],missing_gates:[],gates:{},message:"Invalid task_id: task_id is required",todo_scan:null},null,2);if(!isValidTaskId4(taskIdInput)){let errorResult={taskId:taskIdInput,status:"no_evidence",required_gates:[],passed_gates:[],missing_gates:[],gates:{},message:`Invalid task_id format: "${taskIdInput}". Must match N.M or N.M.P (e.g. "1.1", "1.2.3", "1.2.3.4")`,todo_scan:null};return JSON.stringify(errorResult,null,2)}let evidencePath=path308.join(directory,EVIDENCE_DIR,`${taskIdInput}.json`);if(!isPathWithinSwarm(evidencePath,directory))return JSON.stringify({taskId:taskIdInput,status:"no_evidence",required_gates:[],passed_gates:[],missing_gates:[],gates:{},message:"Invalid path: evidence path validation failed",todo_scan:null},null,2);let evidenceData=readEvidenceFile(evidencePath);if(!evidenceData){let errorResult={taskId:taskIdInput,status:"no_evidence",required_gates:[],passed_gates:[],missing_gates:[],gates:{},message:`No evidence file found for task "${taskIdInput}" at ${evidencePath}. Evidence file may be missing or invalid.`,todo_scan:null};return JSON.stringify(errorResult,null,2)}let gatesMap=evidenceData.gates||{},authoritativeWorkflow=evidenceData.workflow?.schema===TASK_WORKFLOW_SCHEMA_MARKER,derivedGates=deriveApplicableGateSet(evidenceData,authoritativeWorkflow?{currentDeclaredFiles:readCurrentTaskDeclaredFiles(directory,taskIdInput)}:void 0),requiredGates=derivedGates.requiredGates,passedGates=derivedGates.satisfiedGates,missingGates=derivedGates.missingGates,readOnlyNoMutation=derivedGates.readOnlyNoMutation,status2=missingGates.length===0&&(readOnlyNoMutation||evidenceData.workflow?.state==="tests_run"||evidenceData.workflow?.state==="complete")?"all_passed":"incomplete",message;if(status2==="all_passed")message=`All required gates have passed for task "${taskIdInput}".`;else if(requiredGates.length===0)message=`Task "${taskIdInput}" is incomplete. No required gates are configured for this task generation.`;else message=`Task "${taskIdInput}" is incomplete. Missing gates: ${missingGates.join(", ")}.`;let secretscanVerdict="not_run";try{let evidenceResult=await loadEvidence(directory,taskIdInput);if(evidenceResult.status==="found"){let secretscanEntries=evidenceResult.bundle.entries.filter((entry)=>entry.type==="secretscan");if(secretscanEntries.length>0){let lastSecretscan=secretscanEntries[secretscanEntries.length-1];if(isSecretscanEvidence(lastSecretscan)){let{incomplete_files:incompleteFiles,incomplete_paths:incompletePaths}=lastSecretscan,findingsCount=lastSecretscan.findings_count??0,hasIncompleteCoverage=incompleteFiles>0||incompletePaths.length>0,hasFindings=findingsCount>0,hasZeroCoverage=lastSecretscan.files_scanned===0;if(hasIncompleteCoverage||hasFindings||hasZeroCoverage||lastSecretscan.verdict==="fail"||lastSecretscan.verdict==="rejected")if(secretscanVerdict="fail",hasIncompleteCoverage&&!hasFindings){if(missingGates.push("secretscan (BLOCKED — incomplete coverage)"),status2==="all_passed")status2="incomplete";message=`BLOCKED: Secretscan incomplete coverage in prior scan. ${message}`}else if(hasFindings&&hasIncompleteCoverage){if(missingGates.push("secretscan (BLOCKED — secrets detected; incomplete coverage)"),status2==="all_passed")status2="incomplete";message=`BLOCKED: Secretscan found secrets and incomplete coverage in prior scan. ${message}`}else if(hasFindings){if(missingGates.push("secretscan (BLOCKED — secrets detected)"),status2==="all_passed")status2="incomplete";message=`BLOCKED: Secretscan found secrets in prior scan. ${message}`}else{if(missingGates.push("secretscan (BLOCKED — zero coverage)"),status2==="all_passed")status2="incomplete";message=`BLOCKED: Secretscan scanned zero files in prior scan. ${message}`}else if(lastSecretscan.verdict==="pass"||lastSecretscan.verdict==="approved"||lastSecretscan.verdict==="info")secretscanVerdict="pass"}}else message+=" Advisory: No secretscan evidence found for this task. Consider running secretscan."}else if(evidenceResult.status==="invalid_schema")secretscanVerdict="fail",missingGates.push("secretscan (BLOCKED — invalid evidence)"),status2="incomplete",message=`BLOCKED: Secretscan evidence is invalid and cannot prove complete coverage. ${message}`}catch{}let todoScan=evidenceData.todo_scan,todoVerdict=evaluateTodoGate(todoScan,todoGateConfig);if(todoVerdict.status==="exceeded")if(todoVerdict.blocked){if(missingGates.push(`todo_gate (BLOCKED — ${todoVerdict.count} high-priority TODOs exceed max ${todoVerdict.max})`),status2==="all_passed")status2="incomplete";message=`BLOCKED: TODO gate threshold exceeded. ${todoVerdict.message} ${message}`}else message+=` Advisory: todo_gate threshold exceeded — ${todoVerdict.count} high-priority TODOs (FIXME/HACK/XXX) exceed max_high_priority=${todoVerdict.max}.`;let workflowMeta=evidenceData.workflow&&typeof evidenceData.workflow==="object"&&typeof evidenceData.workflow.state==="string"?{state:evidenceData.workflow.state,generation:typeof evidenceData.workflow.generation==="number"?evidenceData.workflow.generation:0}:null,workflowAttributionHint;if(status2==="incomplete"&&workflowMeta?.state==="coder_delegated"&&!gatesMap.pre_check)workflowAttributionHint="Task is settled at coder_delegated but Stage A (pre_check_batch) was never attributed — "+`reviewer/test_engineer dispatches will be denied with TASK_WORKFLOW_STAGE_A_REQUIRED. Run pre_check_batch on the task's changed files; if it passes without advancing this task, run /swarm recover ${taskIdInput}.`,message+=` ${workflowAttributionHint}`;let result={taskId:taskIdInput,status:status2,required_gates:requiredGates,passed_gates:passedGates,missing_gates:missingGates,gates:gatesMap,message,todo_scan:todoScan??null,secretscan_verdict:secretscanVerdict,workflow:workflowMeta,...workflowAttributionHint?{workflow_attribution_hint:workflowAttributionHint}:{}};return JSON.stringify(result,null,2)}});init_checkpoint();init_co_change_analyzer();init_zod();init_loader();init_pr_workflow_gate();init_create_tool();var CompletePrWorkflowArgsSchema=exports_external.object({mode:exports_external.enum(["PR_REVIEW","PR_FEEDBACK"]),pr_head_sha:exports_external.string().trim().min(1).max(80),report_verdict:exports_external.enum(["APPROVE","REQUEST_CHANGES","INCOMPLETE"]).optional()}).strict().superRefine((value,ctx)=>{if(value.mode==="PR_REVIEW"&&value.report_verdict===void 0)ctx.addIssue({code:"custom",path:["report_verdict"],message:"is required for PR_REVIEW completion (issue #2383 terminal report)"})});async function executeCompletePrWorkflow(args2,directory,context={}){let parsed=CompletePrWorkflowArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,message:`Invalid PR workflow completion: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`});if(!context.sessionID?.trim())return JSON.stringify({success:!1,message:"PR workflow completion requires an active sessionID"});let staleDisclosure={},laneLiveness;try{let config3=loadPluginConfig(directory),hooks2=config3.hooks;laneLiveness={laneLivenessWatchdog:config3.lane_liveness_watchdog,backgroundPendingTimeoutMs:hooks2?.background_pending_timeout_minutes!==void 0?hooks2.background_pending_timeout_minutes*60000:void 0}}catch{}try{let settlement=await _internals252.settlePresumedStalePrWorkflowLanes(directory,context.sessionID,laneLiveness);if(settlement.presumedStaleLaneIds.length>0)staleDisclosure={presumed_stale_lanes:settlement.presumedStaleLaneIds,presumed_stale_disclosure:settlement.disclosure};if(settlement.probedAliveLaneIds?.length)staleDisclosure.probe_retained_lanes=settlement.probedAliveLaneIds;if(settlement.probeDegradedReason)staleDisclosure.probe_status=settlement.probeDegradedReason;if(settlement.horizonConflictNote)staleDisclosure.horizon_conflict=settlement.horizonConflictNote}catch{}let amendmentDisclosure={};try{let gateState=await _internals252.readPrWorkflowGateState(directory,context.sessionID);if(gateState?.prFeedbackInventoryAmendments?.length)amendmentDisclosure={inventory_amendments:gateState.prFeedbackInventoryAmendments}}catch{}try{let terminalReport;if(parsed.data.mode==="PR_REVIEW"){let coverage=null;try{coverage=await _internals252.readPrReviewTerminalCoverageForReport(directory,context.sessionID)}catch{}if(coverage){let findingPolicy;try{findingPolicy=await _internals252.readPrReviewFinalFindingPolicyForReport(directory,context.sessionID)}catch{}terminalReport={kind:coverage.kind,covered_dimensions:coverage.coveredDimensions,unresolved_dimensions:coverage.unresolvedDimensions,live_dimensions:coverage.liveDimensions,allowed_verdicts:findingPolicy?.permittedVerdicts??coverage.allowedVerdicts,...findingPolicy?{finding_policy_version:findingPolicy.policyVersion,blocking_finding_ids:findingPolicy.blockingFindingIds}:{},report_verdict:parsed.data.report_verdict}}}let status2=await _internals252.completePrWorkflow(directory,context.sessionID,parsed.data.mode,parsed.data.pr_head_sha,parsed.data.mode==="PR_REVIEW"?{reportVerdict:parsed.data.report_verdict,...laneLiveness?{laneLiveness}:{}}:laneLiveness?{laneLiveness}:void 0),checkoutRestoreRequired=!1,checkoutRestoreReceipts=[];if(status2==="completed")try{checkoutRestoreReceipts=await _internals252.listPendingPrWorkflowCheckoutRestores(directory,context.sessionID),checkoutRestoreRequired=checkoutRestoreReceipts.length>0}catch{checkoutRestoreRequired=!0}return JSON.stringify({success:!0,mode:parsed.data.mode,pr_head_sha:parsed.data.pr_head_sha,status:status2,ready_to_publish:status2==="ready-to-publish",verified_no_change:status2==="verified-no-change",gate_cleared:status2==="completed"||status2==="verified-no-change",checkout_restore_required:checkoutRestoreRequired,checkout_restore_receipts:checkoutRestoreReceipts,...terminalReport?{terminal_report:terminalReport}:{},...staleDisclosure,...amendmentDisclosure})}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:String(error93),...staleDisclosure,...amendmentDisclosure})}}var complete_pr_workflow=createSwarmTool({description:"Validate terminal PR workflow coverage. After the ordered PR_FEEDBACK gates permit one standalone commit, the first call requires a clean tree and a non-merge direct child of intake HEAD, then binds its structured upstream target; the second clears only after both the local tracking ref and an actual-remote query point to that exact commit. A cleared result reports checkout_restore_required when preserved pre-workflow changes must be restored.",args:{mode:CompletePrWorkflowArgsSchema.shape.mode,pr_head_sha:CompletePrWorkflowArgsSchema.shape.pr_head_sha,report_verdict:CompletePrWorkflowArgsSchema.shape.report_verdict},execute:executeCompletePrWorkflow}),_internals252={completePrWorkflow,listPendingPrWorkflowCheckoutRestores,readPrWorkflowGateState,readPrReviewTerminalCoverageForReport,readPrReviewFinalFindingPolicyForReport,settlePresumedStalePrWorkflowLanes};init_zod();init_utils2();init_state2();init_swarm_artifact_cache();init_create_tool();init_resolve_working_directory();import*as fs177 from"node:fs";import*as path309 from"node:path";function extractMatches(regex,text){return Array.from(text.matchAll(regex))}function parseIdentifiers(description){let identifiers=new Set,backtickRegex=/`([^`]+)`/g;for(let match of extractMatches(backtickRegex,description))identifiers.add(match[1]);let camelCaseRegex=/\b([a-z][a-zA-Z0-9]{2,})\b/g;for(let match of extractMatches(camelCaseRegex,description)){let word=match[1];if(word==="the"||word==="and"||word==="for"||word==="have"||word==="this"||word==="with"||word==="from"||word==="they"||word==="been"||word==="will"||word==="your"||word==="also")continue;identifiers.add(word)}let pascalCaseRegex=/\b([A-Z][a-zA-Z0-9]{2,})\b/g;for(let match of extractMatches(pascalCaseRegex,description))identifiers.add(match[1]);let configKeyRegex=/\b([a-z][a-zA-Z0-9]*(?:\.[a-z][a-zA-Z0-9]*)+)\b/g;for(let match of extractMatches(configKeyRegex,description))identifiers.add(match[1]);let quotedPathRegex=/['"](\.{0,3}(?:src|lib|test)[/\\][^'"]+)['"]/g;for(let match of extractMatches(quotedPathRegex,description))identifiers.add(match[1]);return Array.from(identifiers)}function parseFilePaths(description,filesTouched){if(filesTouched&&Array.isArray(filesTouched)&&filesTouched.length>0)return filesTouched;let filePaths=[],srcPathRegex=/\b(?:src|lib|test|app|packages?)[/\\][a-zA-Z0-9_./-]+\.(?:ts|tsx|js|jsx|mjs|cjs)\b/g;for(let match of extractMatches(srcPathRegex,description))filePaths.push(match[0]);let genericPathRegex=/\b[a-zA-Z0-9_./-]+[/\\][a-zA-Z0-9_./-]+\.[a-zA-Z0-9]+(?=\s|$|[.,;])/g;for(let match of extractMatches(genericPathRegex,description)){let pathStr=match[0];if(pathStr.includes("src/")||pathStr.includes("src\\")||pathStr.includes("lib/")||pathStr.includes("lib\\")||pathStr.includes("test/")||pathStr.includes("test\\"))filePaths.push(pathStr)}return filePaths}function buildVerifySummary(tasksChecked,tasksSkipped,tasksBlocked){if(tasksBlocked>0)return`Blocked: ${tasksBlocked} task(s) with missing identifiers`;let verified=tasksChecked-tasksSkipped;if(tasksSkipped===tasksChecked)return`All ${tasksChecked} completed task(s) skipped — research/inventory tasks`;if(tasksSkipped>0)return`${verified} task(s) verified, ${tasksSkipped} skipped (research tasks)`;return`All ${tasksChecked} completed tasks verified successfully`}async function executeCompletionVerify(args2,directory){let phase=Number(args2.phase);if(Number.isNaN(phase)||phase<1||!Number.isFinite(phase))return JSON.stringify({success:!1,phase,status:"blocked",reason:"Invalid phase number",tasksChecked:0,tasksSkipped:0,tasksBlocked:0,blockedTasks:[]},null,2);if(hasActiveTurboMode(args2.sessionID))return JSON.stringify({success:!0,phase,status:"passed",reason:"Turbo Mode active — completion verification bypassed",tasksChecked:0,tasksSkipped:0,tasksBlocked:0,blockedTasks:[]},null,2);let plan;try{let planPath=validateSwarmPath(directory,"plan.json"),planRaw=fs177.readFileSync(planPath,"utf-8");plan=JSON.parse(planRaw)}catch{return JSON.stringify({success:!0,phase,status:"passed",reason:"Cannot verify without plan.json",tasksChecked:0,tasksSkipped:0,tasksBlocked:0,blockedTasks:[]},null,2)}let targetPhase=plan.phases.find((p)=>p.id===phase);if(!targetPhase){let result2={success:!1,phase,status:"blocked",reason:`Phase ${phase} not found in plan.json`,tasksChecked:0,tasksSkipped:0,tasksBlocked:0,blockedTasks:[]};return JSON.stringify(result2,null,2)}let tasksChecked=0,tasksSkipped=0,tasksBlocked=0,blockedTasks=[];for(let task2 of targetPhase.tasks){if(task2.status!=="completed")continue;tasksChecked++;let fileTargets=parseFilePaths(task2.description,task2.files_touched),identifiers=parseIdentifiers(task2.description);if(fileTargets.length===0){tasksSkipped++;continue}if(identifiers.length===0){blockedTasks.push({task_id:task2.id,identifier:"",file_path:"",reason:"No identifiers — cannot verify completion without identifiers"}),tasksBlocked++;continue}let foundIdentifiers=new Set,hasFileReadFailure=!1;for(let filePath of fileTargets){let normalizedPath=filePath.replace(/\\/g,"/"),resolvedPath=path309.resolve(directory,normalizedPath),projectRoot=path309.resolve(directory),relative77=path309.relative(projectRoot,resolvedPath);if(!(relative77===""||!relative77.startsWith("..")&&!path309.isAbsolute(relative77))){blockedTasks.push({task_id:task2.id,identifier:"",file_path:filePath,reason:`File path '${filePath}' escapes the project directory — cannot verify completion`}),hasFileReadFailure=!0;continue}let fileContent;try{fileContent=fs177.readFileSync(resolvedPath,"utf-8")}catch{blockedTasks.push({task_id:task2.id,identifier:"",file_path:filePath,reason:`File '${filePath}' not found — cannot verify completion`}),hasFileReadFailure=!0;continue}for(let identifier of identifiers)if(fileContent.includes(identifier))foundIdentifiers.add(identifier)}let foundCount=foundIdentifiers.size;if(hasFileReadFailure||foundCount===0){if(!hasFileReadFailure)blockedTasks.push({task_id:task2.id,identifier:"",file_path:"",reason:"No identifiers found in target files"});tasksBlocked++}}let now2=new Date().toISOString(),result={success:tasksBlocked===0,phase,status:tasksBlocked===0?"passed":"blocked",reason:tasksBlocked>0?`COMPLETION_INCOMPLETE: ${tasksBlocked} task(s) blocked — missing identifiers or target files`:void 0,tasksChecked,tasksSkipped,tasksBlocked,blockedTasks};if(args2.writeEvidence!==!1)try{let evidenceDir=path309.join(directory,".swarm","evidence",`${phase}`),evidencePath=path309.join(evidenceDir,"completion-verify.json");fs177.mkdirSync(evidenceDir,{recursive:!0});let evidenceBundle={schema_version:"1.0.0",task_id:"completion-verify",created_at:now2,entries:[{task_id:"completion-verify",type:"completion_verify",timestamp:now2,agent:"completion_verify",verdict:tasksBlocked===0?"pass":"fail",summary:buildVerifySummary(tasksChecked,tasksSkipped,tasksBlocked),phase,tasks_checked:tasksChecked,tasks_skipped:tasksSkipped,tasks_blocked:tasksBlocked,blocked_tasks:blockedTasks}]};fs177.writeFileSync(evidencePath,JSON.stringify(evidenceBundle,null,2),"utf-8"),invalidateCachedArtifact(evidencePath)}catch{}return JSON.stringify(result,null,2)}var completion_verify=createSwarmTool({description:"Deterministic pre-check verifying that plan task identifiers exist in their target source files before phase completion. Blocks if obviously incomplete.",args:{phase:exports_external.number().describe("The phase number to check"),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.")},execute:async(args2,directory)=>{let parsedArgs;try{if(args2&&typeof args2==="object"){let obj=args2;parsedArgs={phase:typeof obj.phase==="number"?obj.phase:typeof obj.phase==="string"?Number(obj.phase):0,sessionID:typeof obj.sessionID==="string"?obj.sessionID:void 0,working_directory:typeof obj.working_directory==="string"?obj.working_directory:void 0}}else parsedArgs={phase:0}}catch{return JSON.stringify({success:!1,phase:0,status:"blocked",reason:"Invalid arguments",tasksChecked:0,tasksSkipped:0,tasksBlocked:0,blockedTasks:[]},null,2)}let dirResult=resolveWorkingDirectory(parsedArgs.working_directory,directory);if(!dirResult.success)return JSON.stringify({success:!1,phase:parsedArgs.phase,status:"blocked",reason:dirResult.message,tasksChecked:0,tasksSkipped:0,tasksBlocked:0,blockedTasks:[]},null,2);return executeCompletionVerify(parsedArgs,dirResult.directory)}});init_zod();init_metrics();init_bun_compat();init_git_executable();init_create_tool();init_path_security();import{Buffer as Buffer4}from"node:buffer";import*as fs178 from"node:fs";import*as path310 from"node:path";var MAX_FILE_SIZE_BYTES5=262144,DEFAULT_DAYS=90,DEFAULT_TOP_N2=20,DEFAULT_EXTENSIONS="ts,tsx,js,jsx,py,rs,ps1",SHELL_METACHAR_REGEX=/[;&|%$`\\]/;function validateDays(days){if(typeof days>"u")return{valid:!0,value:DEFAULT_DAYS,error:null};if(typeof days!=="number"||!Number.isInteger(days))return{valid:!1,value:0,error:"days must be an integer"};if(days<1||days>365)return{valid:!1,value:0,error:"days must be between 1 and 365"};return{valid:!0,value:days,error:null}}function validateTopN(topN){if(typeof topN>"u")return{valid:!0,value:DEFAULT_TOP_N2,error:null};if(typeof topN!=="number"||!Number.isInteger(topN))return{valid:!1,value:0,error:"top_n must be an integer"};if(topN<1||topN>100)return{valid:!1,value:0,error:"top_n must be between 1 and 100"};return{valid:!0,value:topN,error:null}}function validateExtensions(extensions){if(typeof extensions>"u")return{valid:!0,value:DEFAULT_EXTENSIONS,error:null};if(typeof extensions!=="string")return{valid:!1,value:"",error:"extensions must be a string"};if(containsControlChars(extensions))return{valid:!1,value:"",error:"extensions contains control characters"};if(SHELL_METACHAR_REGEX.test(extensions))return{valid:!1,value:"",error:"extensions contains shell metacharacters (;|&%$`\\)"};if(!/^[a-zA-Z0-9,.]+$/.test(extensions))return{valid:!1,value:"",error:"extensions contains invalid characters (only alphanumeric, commas, dots allowed)"};return{valid:!0,value:extensions,error:null}}var _internals253={bunSpawn,resolveGitExecutable},GIT_CHURN_TIMEOUT_MS=1e4,GIT_CHURN_MAX_BUFFER_BYTES=5242880;async function getGitChurn(days,directory,abortSignal){let churnMap=new Map,proc=_internals253.bunSpawn([_internals253.resolveGitExecutable(),"log",`--since=${days} days ago`,"--name-only","--pretty=format:"],{stdout:"pipe",stderr:"pipe",stdin:"ignore",cwd:directory,timeout:GIT_CHURN_TIMEOUT_MS,maxBuffer:GIT_CHURN_MAX_BUFFER_BYTES,killProcessTree:!0,env:{...process.env,GIT_TERMINAL_PROMPT:"0"}}),churnTimeout,churnAbortCleanup,racers=[Promise.all([proc.stdout.text(),proc.exited]).then((churnOutput)=>churnOutput),new Promise((resolve125)=>{churnTimeout=setTimeout(()=>resolve125([null,"timeout"]),GIT_CHURN_TIMEOUT_MS)})];if(abortSignal!==void 0)racers.push(new Promise((resolve125)=>{let settle2=()=>resolve125([null,"aborted"]);if(abortSignal.aborted){settle2();return}let onAbort=()=>settle2();abortSignal.addEventListener("abort",onAbort,{once:!0}),churnAbortCleanup=()=>{abortSignal.removeEventListener("abort",onAbort)}}));try{let[stdout,outcome]=await Promise.race(racers);if(typeof churnTimeout<"u")clearTimeout(churnTimeout);if(outcome==="timeout")throw Error(`git churn analysis failed: git log did not finish within ${GIT_CHURN_TIMEOUT_MS} ms (bounded; child tree killed)`);if(outcome==="aborted")throw Error(`git churn analysis failed: aborted by host cancellation (ctx.abort fired before the ${GIT_CHURN_TIMEOUT_MS} ms deadline; child tree killed)`);if(proc.spawnError)throw Error(`git churn analysis failed: ${proc.spawnError.message}`);if(proc.signalCode)throw Error(`git churn analysis failed: git log was killed by ${proc.signalCode} after exceeding the ${GIT_CHURN_TIMEOUT_MS} ms / ${GIT_CHURN_MAX_BUFFER_BYTES}-byte bound`);if(Buffer4.byteLength(stdout)>=GIT_CHURN_MAX_BUFFER_BYTES)throw Error(`git churn analysis failed: git log output reached the ${GIT_CHURN_MAX_BUFFER_BYTES}-byte buffer limit`);let lines=stdout.split(/\r?\n/);for(let line of lines){let normalizedPath=line.replace(/\\/g,"/");if(!normalizedPath||normalizedPath.trim()==="")continue;if(normalizedPath.includes("node_modules")||normalizedPath.includes("/.git/")||normalizedPath.includes("/dist/")||normalizedPath.includes("/build/")||normalizedPath.includes("__tests__"))continue;if(normalizedPath.includes(".test.")||normalizedPath.includes(".spec."))continue;churnMap.set(normalizedPath,(churnMap.get(normalizedPath)||0)+1)}}finally{if(typeof churnTimeout<"u")clearTimeout(churnTimeout);churnAbortCleanup?.();try{proc.kill()}catch{}}return churnMap}function getComplexityForFile2(filePath){try{if(fs178.statSync(filePath).size>MAX_FILE_SIZE_BYTES5)return null;let content=fs178.readFileSync(filePath,"utf-8");return estimateCyclomaticComplexity(content)}catch{return null}}async function analyzeHotspots(days,topN,extensions,directory,abortSignal){let churnMap=await getGitChurn(days,directory,abortSignal),extSet=new Set(extensions.map((e)=>e.startsWith(".")?e:`.${e}`)),filteredChurn=new Map;for(let[file3,count]of churnMap){let ext=path310.extname(file3).toLowerCase();if(extSet.has(ext))filteredChurn.set(file3,count)}let hotspots=[],cwd=directory,analyzedFiles=0;for(let[file3,churnCount]of filteredChurn){let fullPath=file3;if(!fs178.existsSync(fullPath))fullPath=path310.join(cwd,file3);let complexity=getComplexityForFile2(fullPath);if(complexity!==null){analyzedFiles++;let riskScore=Math.round(churnCount*Math.log2(Math.max(complexity,1))*10)/10,recommendation;if(riskScore>=50)recommendation="full_gates";else if(riskScore>=30)recommendation="security_review";else if(riskScore>=15)recommendation="enhanced_review";else recommendation="standard";hotspots.push({file:file3,churnCount,complexity,riskScore,recommendation})}}hotspots.sort((a,b)=>b.riskScore-a.riskScore);let topHotspots=hotspots.slice(0,topN),summary={fullGates:topHotspots.filter((h)=>h.recommendation==="full_gates").length,securityReview:topHotspots.filter((h)=>h.recommendation==="security_review").length,enhancedReview:topHotspots.filter((h)=>h.recommendation==="enhanced_review").length,standard:topHotspots.filter((h)=>h.recommendation==="standard").length};return{analyzedFiles,period:`${days} days`,hotspots:topHotspots,summary}}var complexity_hotspots=createSwarmTool({description:"Identify high-risk code hotspots by combining git churn frequency with cyclomatic complexity estimates. Returns files with their churn count, complexity score, risk score, and recommended review level.",args:{days:exports_external.number().optional().describe("Number of days of git history to analyze (default: 90, valid range: 1-365)"),top_n:exports_external.number().optional().describe("Number of top hotspots to return (default: 20, valid range: 1-100)"),extensions:exports_external.string().optional().describe('Comma-separated extensions to include (default: "ts,tsx,js,jsx,py,rs,ps1")')},async execute(args2,directory,ctx){if(!directory||typeof directory!=="string"||directory.trim()==="")return JSON.stringify({error:"project directory is required but was not provided",analyzedFiles:0,period:"0 days",hotspots:[],summary:{fullGates:0,securityReview:0,enhancedReview:0,standard:0}},null,2);let daysInput,topNInput,extensionsInput;try{if(args2&&typeof args2==="object"){let obj=args2;daysInput=typeof obj.days==="number"?obj.days:void 0,topNInput=typeof obj.top_n==="number"?obj.top_n:void 0,extensionsInput=typeof obj.extensions==="string"?obj.extensions:void 0}}catch{}let daysValidation=validateDays(daysInput);if(!daysValidation.valid){let errorResult={error:`invalid days: ${daysValidation.error}`,analyzedFiles:0,period:"0 days",hotspots:[],summary:{fullGates:0,securityReview:0,enhancedReview:0,standard:0}};return JSON.stringify(errorResult,null,2)}let topNValidation=validateTopN(topNInput);if(!topNValidation.valid){let errorResult={error:`invalid top_n: ${topNValidation.error}`,analyzedFiles:0,period:"0 days",hotspots:[],summary:{fullGates:0,securityReview:0,enhancedReview:0,standard:0}};return JSON.stringify(errorResult,null,2)}let extensionsValidation=validateExtensions(extensionsInput);if(!extensionsValidation.valid){let errorResult={error:`invalid extensions: ${extensionsValidation.error}`,analyzedFiles:0,period:"0 days",hotspots:[],summary:{fullGates:0,securityReview:0,enhancedReview:0,standard:0}};return JSON.stringify(errorResult,null,2)}let days=daysValidation.value,topN=topNValidation.value,extensions=extensionsValidation.value.split(",").map((e)=>e.trim());try{let result=await analyzeHotspots(days,topN,extensions,directory,ctx?.abort);return JSON.stringify(result,null,2)}catch(e){let errorResult={error:e instanceof Error?`analysis failed: ${e.message}`:"analysis failed: unknown error",analyzedFiles:0,period:`${days} days`,hotspots:[],summary:{fullGates:0,securityReview:0,enhancedReview:0,standard:0}};return JSON.stringify(errorResult,null,2)}}});init_zod();init_config();init_schema();init_miner();init_miner();init_store4();async function mineAndStoreConsensusV1(options){let priorFingerprints=options.deps.priorFingerprints??await listConsensusProposalFingerprints(options.directory),result=await mineConsensus(options.directory,options.request,{...options.deps,priorFingerprints}),report=await writeConsensusReport(options.directory,result.report);return{...result,report}}init_store4();init_memory();init_recommendation_ledger();init_state2();init_logger();init_create_tool();var MAX_FILTER_ENTRIES=200,FilterListSchema=exports_external.array(exports_external.string().min(1).max(512)).max(MAX_FILTER_ENTRIES),MAX_INLINE_ATTRIBUTES=25;function countSummaries(attributes,inlineLimit){let total=0,shown=0;for(let[index,attribute]of attributes.entries()){if(attribute.llmSummary===void 0)continue;if(total+=1,index<inlineLimit)shown+=1}return{total,hidden:total-shown}}function buildMinerRecommendationCandidates(report,sessionId){return report.proposals.map((proposal)=>({kind:"miner",target:proposal.target,statement:proposal.intent,scopeKeys:[],provenance:{mechanism:"consensus_mine",sourceEvidenceRefs:proposal.evidenceRefs,sourceRunIds:proposal.provenance.sourceRunIds,sourceModelIds:proposal.provenance.sourceModelIds,sourceTaskIds:proposal.provenance.sourceTaskIds},origin:{agentRole:"consensus_mine",...sessionId?{sessionId}:{},producedAt:report.generatedAt}}))}var MIRRORED_PROPOSAL_KIND="todo";async function mirrorProposalsToMemory(options){if(options.memoryConfig?.enabled!==!0)return{enabled:!1,attempted:0,proposed:0,rejected:0,failed:0};let proposals=options.report.proposals;if(proposals.length===0)return{enabled:!0,attempted:0,proposed:0,rejected:0,failed:0};let gateway;try{gateway=_internals254.createMemoryGateway({directory:options.directory,...options.sessionId?{sessionID:options.sessionId,runId:options.sessionId}:{},agentRole:"consensus_mine"},{config:options.memoryConfig})}catch(err){let message=err instanceof Error?err.message:String(err);return warn(`[consensus_mine] memory mirror unavailable (fail-open): ${message}`),{enabled:!0,attempted:proposals.length,proposed:0,rejected:0,failed:proposals.length,error:message}}let proposed=0,rejected2=0,failed=0,error93;try{for(let proposal of proposals)try{if((await gateway.propose({operation:"add",kind:MIRRORED_PROPOSAL_KIND,text:proposal.intent,rationale:`consensus_mine proposal from report ${options.report.reportId}, attribute ${proposal.sourceAttributeId} (target ${proposal.target}, confidence ${proposal.confidence})`,evidenceRefs:proposal.evidenceRefs})).status==="rejected")rejected2+=1;else proposed+=1}catch(err){failed+=1,error93??=err instanceof Error?err.message:String(err)}}finally{try{await gateway.dispose()}catch(err){warn(`[consensus_mine] memory gateway dispose failed: ${err instanceof Error?err.message:String(err)}`)}}if(error93!==void 0)warn(`[consensus_mine] memory mirror partially failed: ${error93}`);return{enabled:!0,attempted:proposals.length,proposed,rejected:rejected2,failed,...error93?{error:error93}:{}}}var _internals254={createMemoryGateway};var consensus_mine=createSwarmTool({description:"Mine cross-run consensus from existing .swarm evidence — evaluation runs, gate audits, gate "+"ground truth, task trajectories, PRM sessions, skill usage, knowledge outcomes, evidence "+"bundles, and curated failures (nine sources) — and persist an immutable report of "+`agreed-upon attributes plus proposals-only recommendations. It never activates a skill, writes a knowledge entry, admits a durable memory record, edits a project file, or mutates any evidence it reads. It is NOT otherwise write-minimal, so plan for these effects: it DELETES its own older reports past consensus.report_retention (default 50) on every run; it rewrites the shared recommendation dedup ledger whole, with FIFO eviction that can drop another producer's oldest entries; it leaves one never-removed lock sentinel per report id under .swarm/locks/; when memory.enabled is true it mirrors each proposal into a PENDING swarm-memory proposal (curator review still required); and when consensus.llm_summarization_enabled is true (the default) it issues up to ${MAX_LLM_SUMMARIES} session.create plus session.prompt calls. Under a knowledge or memory link the ledger and the memory store resolve to the shared cohort root, outside this project's .swarm/.`,args:{run_ids:FilterListSchema.optional().describe("Restrict mining to these run ids (raw or namespaced). Omit for all runs."),task_categories:FilterListSchema.optional().describe("Restrict to these evaluation task categories. Omit for all categories."),agent_roles:FilterListSchema.optional().describe("Restrict to these agent roles. Omit for all roles."),model_ids:FilterListSchema.optional().describe("Restrict to these model ids. Omit for all models."),min_support:exports_external.number().int().min(1).max(1e4).optional().describe("Distinct runs required to emit an attribute. Defaults to consensus.default_min_support."),min_successful_runs:exports_external.number().int().min(0).max(1e4).optional().describe("Successful runs required. Defaults to consensus.default_min_successful_runs."),max_evidence_items:exports_external.number().int().min(1).max(1e4).optional().describe("Cap on corpus observations read. Defaults to consensus.default_max_evidence_items.")},execute:async(args2,directory,ctx)=>{let input=args2??{},loaded=loadPluginConfigWithMeta(directory),config3=ConsensusConfigSchema.parse(loaded.config.consensus??{});if(!config3.enabled)return JSON.stringify({success:!1,disabled:!0,message:"Consensus mining is disabled (consensus.enabled = false). No report was written."},null,2);let request={...input.run_ids?{runIds:input.run_ids}:{},...input.task_categories?{taskCategories:input.task_categories}:{},...input.agent_roles?{agentRoles:input.agent_roles}:{},...input.model_ids?{modelIds:input.model_ids}:{},minSupport:input.min_support??config3.default_min_support,minSuccessfulRuns:input.min_successful_runs??config3.default_min_successful_runs,maxEvidenceItems:input.max_evidence_items??config3.default_max_evidence_items},client=swarmState.opencodeClient,dispatcher=config3.llm_summarization_enabled&&client?createEvaluationModelDispatcher(client):void 0,result=await mineAndStoreConsensusV1({directory,request,deps:{config:config3,...dispatcher?{dispatcher}:{},...ctx?.sessionID?{sessionId:ctx.sessionID}:{},agentRole:"consensus_mine"}}),report=result.report,ledger=await recordEmittedRecommendations(directory,buildMinerRecommendationCandidates(report,ctx?.sessionID),{producedAt:report.generatedAt});if(ledger.degraded)warn("[consensus_mine] recommendation ledger write degraded; proposals were not recorded for cross-producer dedup");let memoryMirror=await mirrorProposalsToMemory({directory,memoryConfig:loaded.config.memory,report,...ctx?.sessionID?{sessionId:ctx.sessionID}:{}}),pruned=await pruneConsensusReports(directory,config3.report_retention),pruningEnabled=config3.report_retention>0,summaries=countSummaries(report.attributes,MAX_INLINE_ATTRIBUTES);return JSON.stringify({success:!0,report_id:report.reportId,report_path:`.swarm/evolution/consensus/${report.reportId}.json`,generated_at:report.generatedAt,integrity_hash:report.integrityHash,config_hash:report.configHash,redaction_policy_version:report.redactionPolicyVersion,thresholds:{min_support:request.minSupport,min_successful_runs:request.minSuccessfulRuns,max_evidence_items:request.maxEvidenceItems,min_task_diversity:MIN_TASK_DIVERSITY_FOR_PROPOSAL,min_support_for_proposal:MIN_SUPPORT_FOR_PROPOSAL},input_run_count:report.inputIds.length,corpus:report.corpusHashes.map((entry)=>({source:entry.source,observations:entry.observations})),corpus_truncated:result.truncated,truncation:{corpus:report.truncation.corpus,observations_tallied:report.truncation.observations,input_ids_truncated:report.truncation.inputIds,total_input_ids:report.truncation.totalInputIds,attributes_dropped:report.truncation.attributesDropped},unreadable_sources:result.unreadableSources,attribute_count:report.attributes.length,investigation_note_count:result.investigationNoteCount,proposal_count:report.proposals.length,deduped_proposal_count:result.dedupedProposalCount,recommendation_ledger:{recorded:ledger.recorded,duplicate_recommendation_count:ledger.suppressed,evicted:ledger.evicted,degraded:ledger.degraded},memory_mirror:memoryMirror,summarized_count:summaries.total,summarized_but_not_shown:summaries.hidden,restatements_accepted_this_run:result.summarizedCount,...result.summarizationSkippedReason?{summarization_skipped_reason:result.summarizationSkippedReason}:{},attributes:report.attributes.slice(0,MAX_INLINE_ATTRIBUTES).map((attribute)=>({id:attribute.id,statement:attribute.statement,...attribute.llmSummary?{llm_summary:attribute.llmSummary}:{},support:attribute.support,success_support:attribute.successSupport,failure_support:attribute.failureSupport,task_diversity:attribute.taskDiversity,model_diversity:attribute.modelDiversity,confidence:attribute.confidence,proposed_target:attribute.proposedTarget,counterexample_count:attribute.counterexampleRefs.length})),attributes_truncated:report.attributes.length>MAX_INLINE_ATTRIBUTES,retention:pruningEnabled?{configured:config3.report_retention,pruning_enabled:!0,deleted:pruned.deleted.length,retained:pruned.retained.length,failed:pruned.failed.length,corrupt:pruned.corrupt.length}:{configured:config3.report_retention,pruning_enabled:!1,deleted:0,failed:0},guarantees:["proposals only — no skill activation, no knowledge write, no durable memory record, and no mutation of any evidence read",'model_diversity 0 means "not measurable from this corpus", never "measured as none"',`attributes below task diversity ${MIN_TASK_DIVERSITY_FOR_PROPOSAL} or below support ${MIN_SUPPORT_FOR_PROPOSAL} are investigation notes, never proposals`,"an attribute counting failing runs always carries counterexample refs (schema-enforced)","truncation is not biased toward successes, but it is still a cut: it balances per source, and drops whole sources once the budget is spent","statement is deterministic; llm_summary is an optional restatement excluded from integrity_hash","reproducible: identical corpus, request, config_hash, and prior proposals yield the same integrity_hash and report_id; model wording never moves it",'truncation is declared on the report; read failure_support 0 on a truncated report as "none survived the cut"']},null,2)}});init_config();init_model_limits();init_state2();init_create_tool();var _internals255={loadPluginConfig,fetchSessionMessages:async(sessionID,directory,limit=100)=>{if(!swarmState.opencodeClient?.session)return null;try{return(await swarmState.opencodeClient.session.messages({path:{id:sessionID},query:{directory,limit}})).data??null}catch{return null}}};function computeContextHeadroom(messages,warnThreshold=0.7,criticalThreshold=0.9,modelLimitsConfig={},liveContextLimit,modelIdentity,directory){let{modelID,providerID}=modelIdentity??extractModelInfo(messages),modelLimitResolution=resolveModelLimit(modelID,providerID,modelLimitsConfig,liveContextLimit,directory),modelLimit=modelLimitResolution.limit,usage=computeContextUsage(messages),usagePercent=usage.tokensUsed/modelLimit,thresholdCrossed="none";if(usagePercent>criticalThreshold)thresholdCrossed="critical";else if(usagePercent>warnThreshold)thresholdCrossed="warn";return{tokensUsed:usage.tokensUsed,usageSource:usage.source,modelLimit,modelLimitSource:modelLimitResolution.source,modelLimitResolution:modelLimitResolution.resolution,fallbackActive:modelLimitResolution.source==="provider_cap"||modelLimitResolution.source==="native"||modelLimitResolution.source==="fallback",usagePercent,thresholdCrossed,modelId:modelID??null,provider:providerID??null}}var context_status=createSwarmTool({allowWorkingDirectoryOverride:!0,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.",args:{},async execute(_args,directory,ctx){let config3=_internals255.loadPluginConfig(directory),warnThreshold=config3.context_budget?.warn_threshold??0.7,criticalThreshold=config3.context_budget?.critical_threshold??0.9,modelLimitsConfig=config3.context_budget?.model_limits??{},messages=[];if(ctx?.sessionID){let sessionMessages=await _internals255.fetchSessionMessages(ctx.sessionID,directory);if(sessionMessages)messages=sessionMessages}let{modelID,providerID}=getLiveContextModelIdentity(ctx?.sessionID)??extractModelInfo(messages),headroom=computeContextHeadroom(messages,warnThreshold,criticalThreshold,modelLimitsConfig,getLiveContextWindow(ctx?.sessionID,{modelID,providerID}),{modelID,providerID},directory);return JSON.stringify(headroom,null,2)}});init_zod();init_loader();function pushCouncilAdvisory(session,synthesis){let dedupKey=`council:${synthesis.taskId}:${synthesis.roundNumber}`;if(synthesis.overallVerdict==="APPROVE"&&synthesis.advisoryFindings.length===0)return;if(session.pendingAdvisoryMessages??=[],session.pendingAdvisoryMessages.some((m)=>m.includes(dedupKey)))return;let blocking=synthesis.overallVerdict==="REJECT",header=`[${dedupKey}] (priority=HIGH, blocking=${blocking})`,body=synthesis.unifiedFeedbackMd;pushAdvisory(session,`${header}
|
|
7533
7539
|
${body}`,{dedupeKey:dedupKey})}init_zod();init_task_file();init_gate_evidence();init_project_boundary();init_council_review_identity();import{existsSync as existsSync163,mkdirSync as mkdirSync90,readFileSync as readFileSync135}from"node:fs";import{join as join247}from"node:path";var EVIDENCE_DIR2=".swarm/evidence",VALID_TASK_ID=/^\d+\.\d+(\.\d+)*$/,COUNCIL_GATE_NAME="council",COUNCIL_AGENT_ID="architect",EvidenceFileSchema=exports_external.record(exports_external.string(),exports_external.unknown()),_internals256={withTaskEvidenceLock},FORBIDDEN_KEYS=new Set(["__proto__","constructor","prototype"]);function safeAssignOwnProps(target,source){for(let key2 of Object.keys(source)){if(FORBIDDEN_KEYS.has(key2))continue;let value=source[key2];if(value!==null&&typeof value==="object"&&!Array.isArray(value)){let nested=Object.create(null);safeAssignOwnProps(nested,value),target[key2]=nested}else if(Array.isArray(value))target[key2]=value.map((item)=>{if(item!==null&&typeof item==="object"&&!Array.isArray(item)){let nested=Object.create(null);return safeAssignOwnProps(nested,item),nested}return item});else target[key2]=value}return target}async function writeCouncilEvidence(workingDir,synthesis,attemptId,expectedGeneration,identity){if(!VALID_TASK_ID.test(synthesis.taskId))throw Error(`writeCouncilEvidence: invalid taskId "${synthesis.taskId}" — must match N.M or N.M.P format`);let dir=join247(workingDir,EVIDENCE_DIR2);assertProjectRoot(workingDir),mkdirSync90(dir,{recursive:!0});let filePath=taskEvidencePath(workingDir,synthesis.taskId);await _internals256.withTaskEvidenceLock(workingDir,synthesis.taskId,COUNCIL_AGENT_ID,async()=>{assertTaskEvidenceWriteAllowed(workingDir,synthesis.taskId);let existingRoot=Object.create(null);if(existsSync163(filePath))try{let raw=readFileSync135(filePath,"utf-8");if(expectedGeneration!==void 0){let exactEvidence=parseTaskEvidence(raw,synthesis.taskId),workflow=getTaskWorkflowSnapshot(exactEvidence);if(!workflow.authoritative||workflow.generation!==expectedGeneration||workflow.state!=="pre_check_passed")throw Error(`TASK_COUNCIL_GENERATION_MISMATCH: expected pre_check_passed@${expectedGeneration}, found ${workflow.state}@${workflow.generation}`)}let parsed=EvidenceFileSchema.parse(JSON.parse(raw));safeAssignOwnProps(existingRoot,parsed)}catch(error93){if(expectedGeneration!==void 0)throw error93}else if(expectedGeneration!==void 0)throw Error(`TASK_COUNCIL_GENERATION_MISMATCH: no exact evidence exists for generation ${expectedGeneration}`);let existingGatesRaw=existingRoot.gates,mergedGates=Object.create(null);if(existingGatesRaw&&typeof existingGatesRaw==="object"&&!Array.isArray(existingGatesRaw))safeAssignOwnProps(mergedGates,existingGatesRaw);mergedGates[COUNCIL_GATE_NAME]={sessionId:synthesis.swarmId,timestamp:synthesis.timestamp,agent:COUNCIL_AGENT_ID,verdict:synthesis.overallVerdict,vetoedBy:synthesis.vetoedBy,roundNumber:synthesis.roundNumber,allCriteriaMet:synthesis.allCriteriaMet,quorumSize:synthesis.quorumSize,...identity?councilIdentityEvidenceFields(identity):{},...expectedGeneration!==void 0?{workflowGeneration:expectedGeneration}:{},...attemptId?{attemptId}:{}};let updated=Object.create(null);if(safeAssignOwnProps(updated,existingRoot),updated.gates=mergedGates,!updated.taskId)updated.taskId=synthesis.taskId;if(!Array.isArray(updated.required_gates))updated.required_gates=[];await atomicWriteFile(filePath,JSON.stringify(updated,null,2))})}function hasCouncilEvidenceAttempt(workingDir,taskId,attemptId,roundNumber){if(!VALID_TASK_ID.test(taskId))return!1;try{let council=EvidenceFileSchema.parse(JSON.parse(readFileSync135(taskEvidencePath(workingDir,taskId),"utf-8"))).gates?.[COUNCIL_GATE_NAME];return council?.attemptId===attemptId&&council.roundNumber===roundNumber}catch{return!1}}init_council_review_identity();init_lock();init_task_file();import{createHash as createHash100,randomUUID as randomUUID42}from"node:crypto";import{closeSync as closeSync38,existsSync as existsSync164,fsyncSync as fsyncSync11,mkdirSync as mkdirSync91,openSync as openSync38,readFileSync as readFileSync136,readSync as readSync26,statSync as statSync92,writeSync as writeSync7}from"node:fs";import{dirname as dirname115,join as join248}from"node:path";init_telemetry();function scopeIdentityPayload(scope){return{level:scope.kind,...scope.kind==="task"&&scope.taskId!==void 0?{taskId:scope.taskId}:{},...scope.kind==="phase"&&scope.phaseNumber!==void 0?{phase:scope.phaseNumber}:{},identityDigest:scope.identityDigest}}function observeCouncilAuditAppend(scope,sessionID,councilRoundId,record3){try{emit("council_attempt",{...sessionID!==void 0?{sessionId:sessionID}:{},councilRoundId,...scopeIdentityPayload(scope),stage:record3.event,attemptId:record3.attemptId,disposition:record3.disposition,authoritativeRound:record3.authoritativeRound,...record3.clientRound!==void 0?{clientRound:record3.clientRound}:{},verdictCount:record3.verdictCount,memberCount:record3.members.length,...record3.quorumSize!==void 0?{quorumSize:record3.quorumSize}:{},...record3.verdict!==void 0?{verdict:record3.verdict}:{},...record3.transition!==void 0?{transition:record3.transition}:{},...record3.gateEffect!==void 0?{gateEffect:record3.gateEffect}:{}});let next=record3.nextState;if(record3.event!=="received"&&(record3.transition==="advance"||record3.transition==="close")&&next!==void 0)emit("council_round_transition",{...sessionID!==void 0?{sessionId:sessionID}:{},councilRoundId,...scopeIdentityPayload(scope),attemptId:record3.attemptId,transition:record3.transition,gateEffect:record3.gateEffect,round:record3.authoritativeRound,nextRound:next.currentRound,roundStatus:next.status,maxRoundsExhausted:next.maxRoundsExhausted,...record3.verdict!==void 0?{verdict:record3.verdict}:{},...record3.quorumSize!==void 0?{quorumSize:record3.quorumSize}:{}})}catch{}}function emitUnscopedCouncilAttemptObservation(sessionID,level,disposition,fingerprint2,attemptId){try{emit("council_attempt_unscoped",{...sessionID!==void 0?{sessionId:sessionID}:{},level,disposition,fingerprint:fingerprint2,attemptId})}catch{}}init_council_review_identity();var VERSION=2,MAX_ROUND=10,MAX_AUDIT_TAIL=262144,STATE_AGENT="council-round-state",EXHAUSTION_EVENT_RELATIVE_PATH="council/events/max-rounds-exhaustion.jsonl";class CouncilRoundStateUncertainError extends Error{constructor(message){super(message);this.name="CouncilRoundStateUncertainError"}}function sha25611(value){return createHash100("sha256").update(value).digest("hex")}var UUID_PATTERN2=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,DIGEST_PATTERN2=/^[a-f0-9]{64}$/;function isUuid2(value){return typeof value==="string"&&UUID_PATTERN2.test(value)}function isDigest(value){return typeof value==="string"&&DIGEST_PATTERN2.test(value)}function isRound(value){return Number.isInteger(value)&&Number(value)>=1&&Number(value)<=MAX_ROUND}function isDisposition(value){return typeof value==="string"&&value.length>0&&value.length<=80}function isEvidenceRef(value){return typeof value==="string"&&value.length>0&&value.length<=240&&value.startsWith(".swarm/")&&!value.includes("..")}function scopeToken(scope){if(scope.kind==="task"){if(!/^\d+\.\d+(\.\d+)*$/.test(scope.taskId))throw Error("invalid task council scope");if(!isIdentityDigest(scope.identityDigest))throw Error("invalid task council scope identity");return`task-${sha25611(JSON.stringify({k:"task",taskId:scope.taskId,id:scope.identityDigest}))}`}if(scope.kind==="phase"){if(!Number.isInteger(scope.phaseNumber)||scope.phaseNumber<1||scope.phaseNumber>1000)throw Error("invalid phase council scope");if(!isIdentityDigest(scope.identityDigest))throw Error("invalid phase council scope identity");return`phase-${sha25611(JSON.stringify({k:"phase",phaseNumber:scope.phaseNumber,id:scope.identityDigest}))}`}if(!isIdentityDigest(scope.identityDigest))throw Error("invalid final council scope identity");return`final-${sha25611(JSON.stringify({k:"final",id:scope.identityDigest}))}`}function auditScope(scope){if(scopeToken(scope),scope.kind==="task")return{kind:"task",scopeHash:sha25611(scope.taskId),identityDigest:scope.identityDigest};if(scope.kind==="phase")return{kind:"phase",phaseNumber:scope.phaseNumber,identityDigest:scope.identityDigest};return{kind:"final",scopeHash:sha25611(scope.identityDigest),identityDigest:scope.identityDigest}}function sameAuditScope(left,right){if(left.kind!==right.kind)return!1;if(left.identityDigest!==right.identityDigest)return!1;if(left.kind==="phase"&&right.kind==="phase")return left.phaseNumber===right.phaseNumber;if(left.kind!=="phase"&&right.kind!=="phase")return left.scopeHash===right.scopeHash;return!1}function councilRoundStatePaths(directory,scope){let token=scopeToken(scope);return{state:join248(directory,".swarm","council","round-state",`${token}.json`),audit:join248(directory,".swarm","council","attempts",`${token}.jsonl`),lock:join248("council","round-state",`${token}.json`)}}function canonicalize3(value){if(Array.isArray(value))return value.map(canonicalize3);if(value&&typeof value==="object"){let result=Object.create(null);for(let key2 of Object.keys(value).sort()){if(key2==="working_directory"||key2==="roundNumber"||key2==="provenanceAgentName"||key2==="provenanceSessionId")continue;result[key2]=canonicalize3(value[key2])}return result}return value}function councilRequestDigest(request,round){return sha25611(JSON.stringify({round,request:canonicalize3(request)}))}function isSnapshot(value){if(!value||typeof value!=="object")return!1;let state2=value;return state2.version===VERSION&&isIdentityDigest(state2.identityDigest)&&isRound(state2.currentRound)&&(state2.status==="open"||state2.status==="closed")&&typeof state2.maxRoundsExhausted==="boolean"&&(state2.lastAttemptId===void 0||isUuid2(state2.lastAttemptId))&&(state2.lastDigest===void 0||isDigest(state2.lastDigest))&&state2.lastAttemptId===void 0===(state2.lastDigest===void 0)}function isTransition(value){return value==="stay"||value==="advance"||value==="close"}function isGateEffect(value){return value==="none"||value==="blocked"||value==="allowed"}function isVerdict(value){return value==="APPROVE"||value==="CONCERNS"||value==="REJECT"}function auditTransitionIsConsistent(record3){if(!record3.nextState||!record3.transition)return!1;if(record3.transition==="close")return record3.nextState.status==="closed"&&record3.nextState.currentRound===record3.authoritativeRound;if(record3.transition==="stay"){if(record3.nextState.status==="closed"&&!["duplicate_submission","council_round_closed","council_round_mismatch"].includes(record3.disposition))return!1;return(record3.nextState.status==="open"||record3.nextState.status==="closed")&&record3.nextState.currentRound===record3.authoritativeRound}return record3.nextState.status==="open"&&(record3.nextState.currentRound===record3.authoritativeRound+1&&record3.nextState.maxRoundsExhausted===!1||record3.nextState.currentRound===record3.authoritativeRound&&record3.nextState.maxRoundsExhausted===!0)}function recoverAuditHistory(tail2,identityDigest){let current=tail2.truncated?void 0:initialState(identityDigest),awaiting,sawTransition=!1;for(let record3 of tail2.records){if(record3.event==="received"){if(awaiting)throw new CouncilRoundStateUncertainError("council audit contains overlapping attempts");if(current&&record3.authoritativeRound!==current.currentRound||!current&&!tail2.truncated&&record3.authoritativeRound!==1)throw new CouncilRoundStateUncertainError("council audit round history is not monotonic");awaiting=record3;continue}if(!record3.nextState||!record3.transition)throw new CouncilRoundStateUncertainError("council audit transition is incomplete");if(awaiting){if(awaiting.attemptId!==record3.attemptId||awaiting.digest!==record3.digest||awaiting.authoritativeRound!==record3.authoritativeRound)throw new CouncilRoundStateUncertainError("council audit attempt pairing is inconsistent");awaiting=void 0}else if(!tail2.truncated||sawTransition)throw new CouncilRoundStateUncertainError("council audit transition has no matching received record");if(current){if(record3.authoritativeRound!==current.currentRound)throw new CouncilRoundStateUncertainError("council audit transition regresses the authoritative round");if(record3.transition==="stay"&&record3.nextState.status!==current.status)throw new CouncilRoundStateUncertainError("council audit stay transition changes scope status");if((record3.transition==="stay"||record3.transition==="close")&&record3.nextState.maxRoundsExhausted!==current.maxRoundsExhausted)throw new CouncilRoundStateUncertainError("council audit changes exhaustion without advancing");if(current.status==="closed"&&(record3.transition!=="stay"||record3.nextState.status!=="closed"))throw new CouncilRoundStateUncertainError("council audit reopens a closed scope")}current=record3.nextState,sawTransition=!0}if(awaiting)throw new CouncilRoundStateUncertainError("council audit ends with an unresolved received attempt");return current}function pendingMatchesParent(state2,pending){if(state2.status!=="open"||pending.round!==state2.currentRound)return!1;if(pending.nextState.lastAttemptId!==pending.attemptId||pending.nextState.lastDigest!==pending.digest)return!1;if(pending.transition==="stay")return pending.nextState.status==="open"&&pending.nextState.currentRound===state2.currentRound&&pending.nextState.maxRoundsExhausted===state2.maxRoundsExhausted;if(pending.transition==="close")return pending.nextState.status==="closed"&&pending.nextState.currentRound===state2.currentRound&&pending.nextState.maxRoundsExhausted===state2.maxRoundsExhausted;return pending.nextState.status==="open"&&(pending.nextState.currentRound===state2.currentRound+1&&pending.nextState.maxRoundsExhausted===!1||pending.nextState.currentRound===state2.currentRound&&pending.nextState.maxRoundsExhausted===!0)}function parseState(raw,expectedIdentityDigest){let value;try{value=JSON.parse(raw)}catch{throw new CouncilRoundStateUncertainError("council round state is corrupt")}if(!isSnapshot(value))throw new CouncilRoundStateUncertainError("council round state is invalid");let state2=value;if(state2.identityDigest!==expectedIdentityDigest)throw new CouncilRoundStateUncertainError("council round state identity does not match the request scope");if(state2.pending){let pending=state2.pending;if(!isUuid2(pending.attemptId)||!isDigest(pending.digest)||!isRound(pending.round)||!isSnapshot(pending.nextState)||!isTransition(pending.transition)||!isDisposition(pending.disposition)||!isGateEffect(pending.gateEffect)||typeof pending.evidenceExpected!=="boolean"||pending.evidenceExpected!==(pending.evidenceRef!==void 0)||pending.evidenceRef!==void 0&&!isEvidenceRef(pending.evidenceRef)||pending.verdict!==void 0&&!isVerdict(pending.verdict)||pending.quorumSize!==void 0&&(!Number.isInteger(pending.quorumSize)||pending.quorumSize<0||pending.quorumSize>5)||pending.verdict===void 0!==(pending.quorumSize===void 0)||!pendingMatchesParent(state2,pending))throw new CouncilRoundStateUncertainError("pending council state is invalid")}return state2}function parseAuditRecord(line,expectedScope){try{let record3=JSON.parse(line);if(record3.version!==VERSION||!["received","finalized","recovered"].includes(record3.event)||!isUuid2(record3.attemptId)||typeof record3.timestamp!=="string"||record3.timestamp.length>40||!Number.isFinite(Date.parse(record3.timestamp))||!sameAuditScope(record3.scope,expectedScope)||record3.clientRound!==void 0&&!isRound(record3.clientRound)||!isRound(record3.authoritativeRound)||!isDigest(record3.digest)||record3.sessionHash!==void 0&&!isDigest(record3.sessionHash)||!isDisposition(record3.disposition)||!Number.isInteger(record3.verdictCount)||record3.verdictCount<0||record3.verdictCount>5||!Array.isArray(record3.members)||record3.members.length>5||record3.members.some((member)=>typeof member!=="string"||member.length===0||member.length>32)||new Set(record3.members).size!==record3.members.length)throw Error("invalid");if(record3.event==="received"){if(record3.disposition!=="received"||record3.transition!==void 0||record3.gateEffect!==void 0||record3.nextState!==void 0||record3.evidenceRef!==void 0)throw Error("invalid")}else if(!isTransition(record3.transition)||!isGateEffect(record3.gateEffect)||!isSnapshot(record3.nextState)||record3.nextState.lastAttemptId!==record3.attemptId||record3.nextState.lastDigest!==record3.digest||!auditTransitionIsConsistent(record3))throw Error("invalid");if(record3.verdict!==void 0&&!isVerdict(record3.verdict))throw Error("invalid");if(record3.quorumSize!==void 0&&(!Number.isInteger(record3.quorumSize)||record3.quorumSize<0||record3.quorumSize>5))throw Error("invalid");if(record3.verdict===void 0!==(record3.quorumSize===void 0))throw Error("invalid");if(record3.evidenceRef!==void 0&&!isEvidenceRef(record3.evidenceRef))throw Error("invalid");return record3}catch{throw new CouncilRoundStateUncertainError("council attempt audit is corrupt")}}function appendAudit2(path311,record3){mkdirSync91(dirname115(path311),{recursive:!0});let descriptor=openSync38(path311,"a");try{writeSync7(descriptor,`${JSON.stringify(record3)}
|
|
7534
7540
|
`,void 0,"utf8"),fsyncSync11(descriptor)}finally{closeSync38(descriptor)}}function appendAuditAndObserve(input,paths,councilRoundId,record3){_internals257.appendAudit(paths.audit,record3),observeCouncilAuditAppend(input.scope,input.sessionID,councilRoundId,record3)}function readAuditTail(path311,scope){if(!existsSync164(path311))return{records:[],truncated:!1};let size=statSync92(path311).size;if(size===0)return{records:[],truncated:!1};let offset=Math.max(0,size-MAX_AUDIT_TAIL),length=size-offset,descriptor=openSync38(path311,"r"),buffer=Buffer.alloc(length);try{readSync26(descriptor,buffer,0,length,offset)}finally{closeSync38(descriptor)}let text=buffer.toString("utf8");if(!text.endsWith(`
|
|
7535
7541
|
`))throw new CouncilRoundStateUncertainError("council attempt audit has a partial tail");if(offset>0){let firstNewline=text.indexOf(`
|
|
@@ -7549,7 +7555,7 @@ ${body}`)}function renderAdvisoryBody(result){return result.synthesis.trim()}var
|
|
|
7549
7555
|
`):"_No persisting disagreements after deliberation._",sourcesBlock=allSources.length>0?allSources.map((s)=>`- [${s.title||s.url}](${s.url})`).join(`
|
|
7550
7556
|
`):"_No sources cited._";return["## General Council Synthesis","",`**Question:** ${question}`,`**Mode:** ${mode}`,`**Members:**
|
|
7551
7557
|
${memberLines}`,`**Rounds:** ${roundsCompleted}`,"","### Consensus",consensusBlock,"","### Persistent Disagreements",disagreementsBlock,"","### Sources",sourcesBlock].join(`
|
|
7552
|
-
`)}function synthesizeGeneralCouncil(question,mode,round1Responses,round2Responses){let safeRound1=Array.isArray(round1Responses)?round1Responses:[],safeRound2=Array.isArray(round2Responses)?round2Responses:[],disagreements=detectDisagreements(safeRound1),consensusPoints=buildConsensusClusters(safeRound1,disagreements),persistingDisagreements=computePersistingDisagreements(disagreements,safeRound2),allSources=dedupeSources(safeRound1,safeRound2),roundsCompleted=safeRound2.length>0?2:1,synthesis=renderSynthesisMarkdown(question,mode,roundsCompleted,safeRound1,consensusPoints,persistingDisagreements,allSources);return{question,mode,round1Responses:safeRound1,disagreements,round2Responses:safeRound2,synthesis,consensusPoints,persistingDisagreements:persistingDisagreements.map((d)=>d.topic),allSources,timestamp:new Date().toISOString()}}init_state2();init_logger();init_create_tool();init_resolve_working_directory();var WebSearchResultSchema=exports_external.object({title:exports_external.string(),url:exports_external.string(),snippet:exports_external.string(),query:exports_external.string()}),ClaimSchema=exports_external.object({subject:exports_external.string().min(1).max(120),statement:exports_external.string().min(1).max(600),stance:exports_external.enum(["support","oppose","neutral","concern","alternative"]),confidence:exports_external.number().min(0).max(1),evidence:exports_external.array(exports_external.string().max(240)).max(4).optional()}),MemberClaimsSchema=exports_external.array(ClaimSchema).max(8).optional().catch(void 0),MemberRoleEnum=exports_external.enum(["generalist","skeptic","domain_expert","devil_advocate","synthesizer"]),Round1ResponseSchema=exports_external.object({memberId:exports_external.string().min(1),model:exports_external.string().min(1),role:MemberRoleEnum,response:exports_external.string(),sources:exports_external.array(WebSearchResultSchema).default([]),searchQueries:exports_external.array(exports_external.string()).default([]),confidence:exports_external.number().min(0).max(1),areasOfUncertainty:exports_external.array(exports_external.string()).default([]),durationMs:exports_external.number().nonnegative().default(0),claims:MemberClaimsSchema}),Round2ResponseSchema=Round1ResponseSchema.extend({disagreementTopics:exports_external.array(exports_external.string()).default([])}),ArgsSchema2=exports_external.object({question:exports_external.string().min(1).max(8000),mode:exports_external.enum(["general","spec_review"]).default("general"),members:exports_external.array(exports_external.string()).default([]),round1Responses:exports_external.array(Round1ResponseSchema).min(1),round2Responses:exports_external.array(Round2ResponseSchema).optional(),working_directory:exports_external.string().optional()}),convene_general_council=createSwarmTool({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.",args:{question:exports_external.string().min(1).max(8000).describe("The question put to the council, or the spec text to review."),mode:exports_external.enum(["general","spec_review"]).optional().describe('"general" for /swarm council or pre-save PLAN advisory; "spec_review" for manual /swarm council --spec-review.'),members:exports_external.array(exports_external.string()).optional().describe("Optional list of member IDs convened (for evidence/audit)."),round1Responses:exports_external.array(exports_external.object({memberId:exports_external.string().min(1),model:exports_external.string().min(1),role:exports_external.enum(["generalist","skeptic","domain_expert","devil_advocate","synthesizer"]),response:exports_external.string(),sources:exports_external.array(exports_external.object({title:exports_external.string(),url:exports_external.string(),snippet:exports_external.string(),query:exports_external.string()})).optional(),searchQueries:exports_external.array(exports_external.string()).optional(),confidence:exports_external.number().min(0).max(1),areasOfUncertainty:exports_external.array(exports_external.string()).optional(),durationMs:exports_external.number().nonnegative().optional(),claims:MemberClaimsSchema})).describe("Round 1 member responses (one per council member)."),round2Responses:exports_external.array(exports_external.object({memberId:exports_external.string().min(1),model:exports_external.string().min(1),role:exports_external.enum(["generalist","skeptic","domain_expert","devil_advocate","synthesizer"]),response:exports_external.string(),sources:exports_external.array(exports_external.object({title:exports_external.string(),url:exports_external.string(),snippet:exports_external.string(),query:exports_external.string()})).optional(),searchQueries:exports_external.array(exports_external.string()).optional(),confidence:exports_external.number().min(0).max(1),areasOfUncertainty:exports_external.array(exports_external.string()).optional(),durationMs:exports_external.number().nonnegative().optional(),disagreementTopics:exports_external.array(exports_external.string()).optional(),claims:MemberClaimsSchema})).optional().describe("Round 2 deliberation responses (omit when no deliberation has occurred)."),working_directory:exports_external.string().optional().describe("Project root for config + evidence path resolution.")},execute:async(args2,directory,ctx)=>{let parsed=ArgsSchema2.safeParse(args2);if(!parsed.success){let fail2={success:!1,reason:"invalid_args",message:parsed.error.issues.map((i)=>`${i.path.join(".")}: ${i.message}`).join("; ")};return JSON.stringify(fail2,null,2)}let input=parsed.data,dirResult=resolveWorkingDirectory(input.working_directory,directory);if(!dirResult.success){let fail2={success:!1,reason:"invalid_working_directory",message:dirResult.message};return JSON.stringify(fail2,null,2)}let workingDir=dirResult.directory,generalConfig=loadPluginConfig(workingDir).council?.general;if(!generalConfig||generalConfig.enabled!==!0)return JSON.stringify({success:!1,reason:"council_general_disabled",message:"convene_general_council requires council.general.enabled: true in the resolved config: global ~/.config/opencode/opencode-swarm.json or project .opencode/opencode-swarm.json."},null,2);let round1=input.round1Responses,round2=input.round2Responses??[],result=synthesizeGeneralCouncil(input.question,input.mode,round1,round2),evidenceDir=path311.join(workingDir,".swarm","council","general"),evidenceFile=`${result.timestamp.replace(/[:.]/g,"-")}-${input.mode}.json`,evidencePath=path311.join(evidenceDir,evidenceFile);try{await fs179.promises.mkdir(evidenceDir,{recursive:!0}),await fs179.promises.writeFile(evidencePath,JSON.stringify(result,null,2))}catch(err){let message=err instanceof Error?err.message:String(err);log(`[convene_general_council] Failed to write evidence to ${evidencePath}: ${message}`)}try{let sessionID=ctx?.sessionID;if(sessionID){let session=getAgentSession(sessionID);if(session)pushGeneralCouncilAdvisory(session,result)}}catch{}let ok={success:!0,question:input.question,mode:input.mode,roundsCompleted:round2.length>0?2:1,consensusPoints:result.consensusPoints,disagreementsCount:result.disagreements.length,persistingDisagreements:result.persistingDisagreements,allSourcesCount:result.allSources.length,synthesis:result.synthesis,evidencePath};return JSON.stringify(ok,null,2)}});init_zod();init_config();init_schema();init_core_events();init_curator();init_curator();init_curator_llm_factory();init_review_receipt();init_create_tool();var curator_analyze=createSwarmTool({description:"Run curator phase analysis and optionally apply knowledge recommendations. Call this after reviewing a phase to apply knowledge updates. If recommendations is provided, applies them via applyCuratorKnowledgeUpdates.",args:{phase:exports_external.number().int().min(1).describe("Phase number to analyze"),recommendations:exports_external.array(exports_external.object({action:exports_external.enum(["promote","archive","flag_contradiction","rewrite"]),entry_id:exports_external.string().optional(),lesson:exports_external.string(),reason:exports_external.string(),category:exports_external.enum(["process","architecture","tooling","security","testing","debugging","performance","integration","other"]).optional(),confidence:exports_external.number().min(0).max(1).optional()})).optional().describe("Knowledge recommendations to apply. If omitted, only collects digest data.")},execute:async(args2,directory,ctx)=>{let typedArgs=args2;try{if(!Number.isInteger(typedArgs.phase)||typedArgs.phase<1)return JSON.stringify({error:"phase must be a positive integer >= 1"},null,2);if(typedArgs.recommendations){let validActions=["promote","archive","flag_contradiction","rewrite"];for(let rec of typedArgs.recommendations)if(!validActions.includes(rec.action))return JSON.stringify({error:`Invalid recommendation action: ${rec.action}`},null,2)}if(typedArgs.recommendations){let UUID_V42=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;for(let rec of typedArgs.recommendations)if(rec.entry_id!==void 0&&!UUID_V42.test(rec.entry_id))return JSON.stringify({error:`Invalid entry_id '${rec.entry_id}': must be a UUID v4 or omitted. Use undefined/omit entry_id to create a new entry.`},null,2)}let{config:config3}=loadPluginConfigWithMeta(directory),curatorConfig=CuratorConfigSchema.parse(config3.curator??{}),knowledgeConfig=KnowledgeConfigSchema.parse(config3.knowledge??{}),agentsDispatched=[];try{let eventsWindow=readCoreEvents(directory);if(eventsWindow.text.length>0){let phaseEvents=filterPhaseEvents(eventsWindow.text,typedArgs.phase),agentSet=new Set;for(let evt of phaseEvents){let record3=evt;if(typeof record3.agent==="string"&&record3.agent.length>0)agentSet.add(record3.agent);if(Array.isArray(record3.agents_dispatched)){for(let a of record3.agents_dispatched)if(typeof a==="string")agentSet.add(a)}}agentsDispatched=Array.from(agentSet).sort()}}catch{}let llmDelegate=createCuratorLLMDelegate(directory,"phase",ctx?.sessionID),curatorResult=await runCuratorPhase(directory,typedArgs.phase,agentsDispatched,curatorConfig,{},llmDelegate);{let scopeContent=curatorResult.digest?.summary??`Phase ${typedArgs.phase} curator analysis`,complianceWarnings=curatorResult.compliance.filter((c)=>c.severity==="warning"),receipt=complianceWarnings.length>0?buildRejectedReceipt({agent:"curator",scopeContent,scopeDescription:"phase-digest",blockingFindings:complianceWarnings.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: ${typedArgs.phase}`,`knowledge_recommendations: ${curatorResult.knowledge_recommendations.length}`]});persistReviewReceipt(directory,receipt).catch(()=>{})}let applied2=0,skipped=0;if(typedArgs.recommendations&&typedArgs.recommendations.length>0){let result=await applyCuratorKnowledgeUpdates(directory,typedArgs.recommendations,knowledgeConfig);applied2=result.applied,skipped=result.skipped}return JSON.stringify({phase_digest:curatorResult.digest,compliance_count:curatorResult.compliance.length,applied:applied2,skipped},null,2)}catch(error93){return JSON.stringify({error:error93 instanceof Error?error93.message:String(error93),phase:typedArgs.phase},null,2)}}});init_zod();init_loader();init_create_tool();init_resolve_working_directory();var CriteriaItemSchema=exports_external.object({id:exports_external.string().min(1).max(20).regex(/^C\d+$/,'Criterion id must match C\\d+ (e.g. "C1", "C12")'),description:exports_external.string().min(10).max(500),mandatory:exports_external.boolean()}),ArgsSchema3=exports_external.object({taskId:exports_external.string().min(1).regex(/^\d+\.\d+(\.\d+)*$/,"Task ID must be in N.M or N.M.P format"),criteria:exports_external.array(CriteriaItemSchema).min(1).max(20),working_directory:exports_external.string().optional()}),declare_council_criteria=createSwarmTool({description:"Pre-declare acceptance criteria for a task before the coder starts work. Criteria are persisted under .swarm/council/ and read back during council evaluation so reviewers assess a stable, pre-committed contract. Architect-only. Config-gated via council.enabled.",args:{taskId:exports_external.string().min(1).regex(/^\d+\.\d+(\.\d+)*$/,"Task ID must be in N.M or N.M.P format").describe('Task ID for which criteria are declared, e.g. "1.1", "1.2.3"'),criteria:exports_external.array(exports_external.object({id:exports_external.string().min(1).max(20).regex(/^C\d+$/,"Criterion id must match C\\d+").describe('Criterion identifier, e.g. "C1", "C12"'),description:exports_external.string().min(10).max(500).describe("Human-readable description of the criterion"),mandatory:exports_external.boolean().describe("Whether the criterion is mandatory. Mandatory criteria block APPROVE when unmet.")})).min(1).max(20).describe("Array of acceptance criteria items. Must contain between 1 and 20 entries with unique ids."),working_directory:exports_external.string().optional().describe("Explicit project root directory. When provided, .swarm/council/ is resolved relative to this path instead of the plugin context directory.")},async execute(args2,directory){let parsed=ArgsSchema3.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,reason:"invalid arguments",errors:parsed.error.issues.map((i)=>({path:i.path.join("."),message:i.message}))},null,2);let input=parsed.data,dirResult=resolveWorkingDirectory(input.working_directory,directory);if(!dirResult.success)return JSON.stringify({success:!1,reason:dirResult.message},null,2);let workingDir=dirResult.directory;if(!loadPluginConfig(workingDir).council?.enabled)return JSON.stringify({success:!1,reason:"council feature is disabled — set council.enabled: true in .opencode/opencode-swarm.json to enable"},null,2);let ids=input.criteria.map((c)=>c.id);if(new Set(ids).size<ids.length){let seen=new Set,duplicates=[];for(let id of ids){if(seen.has(id)&&!duplicates.includes(id))duplicates.push(id);seen.add(id)}return JSON.stringify({success:!1,reason:"duplicate criterion ids",errors:duplicates},null,2)}let replaced=readCriteria(workingDir,input.taskId)!==null;return await writeCriteria(workingDir,input.taskId,input.criteria),JSON.stringify({success:!0,taskId:input.taskId,criteriaCount:input.criteria.length,mandatoryCount:input.criteria.filter((c)=>c.mandatory).length,declaredAt:new Date().toISOString(),replaced},null,2)}});init_zod();init_config();init_plan_schema();init_file_authority();init_path_identity();init_scope_binding();init_scope_persistence();init_state2();init_project_boundary();init_task_id();init_create_tool();import*as fs180 from"node:fs";import*as path312 from"node:path";function validateTaskIdFormat2(taskId){return validateTaskIdFormat(taskId)}function validateFiles(files){let errors5=[],totalBytes=0;for(let file3 of files){if(file3.includes("\x00")){errors5.push(`Invalid file "${file3}": null bytes are not allowed`);continue}let unsafeReason=unsafePathTextReason(file3);if(unsafeReason){errors5.push(`Invalid file path: ${unsafeReason}`);continue}if(file3.replace(/\\/g,"/").split("/").includes(".."))errors5.push(`Invalid file "${file3}": path traversal sequences (..) are not allowed`);let bytes=Buffer.byteLength(file3,"utf8");if(totalBytes+=bytes,bytes>MAX_SCOPE_PATH_BYTES)errors5.push(`Invalid file "${file3}": path exceeds maximum length of ${MAX_SCOPE_PATH_BYTES} UTF-8 bytes`)}if(totalBytes>MAX_SCOPE_FILES_BYTES)errors5.push(`Invalid scope: file paths exceed the aggregate limit of ${MAX_SCOPE_FILES_BYTES} UTF-8 bytes`);return errors5}async function executeDeclareScope(args2,fallbackDir,owner,authorityConfig){let taskIdError=validateTaskIdFormat2(args2.taskId);if(taskIdError)return{success:!1,message:"Validation failed",errors:[taskIdError]};if(!Array.isArray(args2.files)||args2.files.length===0)return{success:!1,message:"Validation failed",errors:["files must be a non-empty array"]};let fileErrors=validateFiles(args2.files);if(fileErrors.length>0)return{success:!1,message:"Validation failed",errors:fileErrors};if(args2.whitelist){let whitelistErrors=validateFiles(args2.whitelist);if(whitelistErrors.length>0)return{success:!1,message:"Validation failed",errors:whitelistErrors}}let normalizedDir;if(args2.working_directory!=null&&args2.working_directory.trim()!==""){if(args2.working_directory.includes("\x00"))return{success:!1,message:"Invalid working_directory: null bytes are not allowed",errors:["Invalid working_directory: null bytes are not allowed"]};if(/^\\\\|^(NUL|CON|AUX|COM[1-9]|LPT[1-9])(\..*)?$/i.test(args2.working_directory))return{success:!1,message:"Invalid working_directory: Windows device paths are not allowed",errors:["Invalid working_directory: Windows device paths are not allowed"]};if(normalizedDir=path312.normalize(args2.working_directory),normalizedDir.split(path312.sep).includes(".."))return{success:!1,message:"Invalid working_directory: path traversal sequences (..) are not allowed",errors:["Invalid working_directory: path traversal sequences (..) are not allowed"]};let resolvedDir=path312.resolve(normalizedDir);try{let realPath=fs180.realpathSync(resolvedDir),planPath2=path312.join(realPath,".swarm","plan.json");if(!fs180.existsSync(planPath2))return{success:!1,message:`Invalid working_directory: plan not found in "${realPath}"`,errors:[`Invalid working_directory: plan not found in "${realPath}"`]}}catch{return{success:!1,message:`Invalid working_directory: path "${resolvedDir}" does not exist or is inaccessible`,errors:[`Invalid working_directory: path "${resolvedDir}" does not exist or is inaccessible`]}}if(normalizedDir&&fallbackDir)try{let canonicalWorkingDir=fs180.realpathSync(path312.resolve(normalizedDir)),canonicalProjectRoot=fs180.realpathSync(path312.resolve(fallbackDir));if(isStrictPathDescendant(canonicalWorkingDir,canonicalProjectRoot)&&!hasExplicitProjectBoundary(canonicalWorkingDir))return{success:!1,message:`working_directory "${normalizedDir}" is a subdirectory of the project root. Use the project root "${fallbackDir}" instead.`,errors:[`Subdirectory working_directory not allowed — use project root "${fallbackDir}"`]}}catch{}}if(!normalizedDir&&!fallbackDir)return{success:!1,message:"Cannot resolve project directory",errors:["Provide working_directory or ensure the tool is invoked from a project root"]};let directory=normalizedDir||fallbackDir,planPath=path312.resolve(directory,".swarm","plan.json");if(!fs180.existsSync(planPath))return{success:!1,message:"No plan found",errors:["plan.json not found"]};let rawPlanContent;try{rawPlanContent=JSON.parse(fs180.readFileSync(planPath,"utf-8"))}catch{return{success:!1,message:"Failed to parse plan.json",errors:["plan.json is not valid JSON"]}}let parsedPlan=PlanSchema.safeParse(rawPlanContent);if(!parsedPlan.success)return{success:!1,message:"Failed to validate plan.json",errors:["plan.json does not match the supported plan schema"]};let planContent=parsedPlan.data,allTasks=planContent.phases?.flatMap((p)=>p.tasks??[])??[];if(!allTasks.some((t)=>t.id===args2.taskId))return{success:!1,message:`Task ${args2.taskId} not found in plan`,errors:[`Task ${args2.taskId} does not exist in plan.json`]};let taskInPlan=allTasks.find((t)=>t.id===args2.taskId);if(taskInPlan&&taskInPlan.status==="completed")return{success:!1,message:`Task ${args2.taskId} is already completed`,errors:[`Cannot declare scope for completed task ${args2.taskId}`]};let rawMergedFiles=[...args2.files,...args2.whitelist??[]],warnings=[],normalizeErrors=[],dir=directory,mergedFiles=rawMergedFiles.map((file3)=>{if(path312.isAbsolute(file3)){let relativePath2=path312.relative(dir,file3).replace(/\\/g,"/");if(relativePath2.startsWith(".."))return normalizeErrors.push(`Path '${file3}' resolves outside the project directory`),file3;return warnings.push(`Absolute path normalized to relative: '${relativePath2}' (was '${file3}')`),relativePath2}return file3});if(normalizeErrors.length>0)return{success:!1,message:"Validation failed",errors:normalizeErrors};let lstatErrors=[];for(let file3 of mergedFiles){let block=checkWriteTargetForSymlink(file3,dir);if(block)lstatErrors.push(block)}if(lstatErrors.length>0)return{success:!1,message:"Scope contains symlink-backed paths",errors:lstatErrors};let authorityErrors=[];for(let file3 of mergedFiles){let decision=checkFileAuthority("coder",file3,dir,authorityConfig,{declaredScope:[file3]});if(!decision.allowed)authorityErrors.push(decision.reason)}if(authorityErrors.length>0)return{success:!1,message:"Scope denied by effective coder authority",errors:authorityErrors};if(owner?.sessionID&&owner.messageID){let binding=createScopeBinding({directory:dir,plan:planContent,taskId:args2.taskId,files:mergedFiles,ownerSessionId:owner.sessionID,ownerMessageId:owner.messageID,source:"declare_scope"});if(!binding)return{success:!1,message:"Failed to bind scope to the calling session",errors:["Scope identity could not be validated"]};let persistence=await replaceExistingScopeDeclaration({directory:dir,binding,replaceExisting:args2.replace_existing??!1});if(!persistence.ok)return{success:!1,message:"Failed to persist scope declaration",errors:[`${persistence.code}: ${persistence.message}`]};let session=ensureAgentSession(owner.sessionID,owner.agentName??"architect",dir);session.declaredCoderScope=mergedFiles,session.lastScopeViolation=null}return warnings.push("SCOPE ENFORCEMENT: This declaration is bound to the caller session and current plan. Direct writes and statically detected shell/interpreter writes must stay inside the active Task-correlated scope; missing or unverifiable coder write authority fails closed with SCOPE_NOT_DECLARED or SCOPE_VIOLATION."),{success:!0,message:"Scope declared successfully",taskId:args2.taskId,fileCount:mergedFiles.length,warnings}}var declare_scope=createSwarmTool({description:"Declare the file scope for the next coder delegation. Sets the list of files the coder is permitted to modify for a specific task. Must be called before delegating to coder to enable scope containment checking.",args:{taskId:exports_external.string().min(1).regex(/^\d+\.\d+(\.\d+)*$/,"Task ID must be in N.M or N.M.P format").describe('Task ID for which scope is being declared, e.g. "1.1", "1.2.3"'),files:exports_external.array(exports_external.string().min(1).max(4096)).min(1).describe("Array of file paths the coder is permitted to modify"),whitelist:exports_external.array(exports_external.string().min(1).max(4096)).optional().describe("Additional file paths to whitelist (merged with files)"),replace_existing:exports_external.boolean().optional().describe("Set true to atomically revoke and replace this session's existing live declaration for the same task"),working_directory:exports_external.string().optional().describe("Working directory where the plan is located")},execute:async(args2,_directory2,ctx)=>{let{config:config3}=loadPluginConfigWithMeta(_directory2);return JSON.stringify(await executeDeclareScope(args2,_directory2,{sessionID:ctx?.sessionID??"",messageID:ctx?.messageID??"",agentName:ctx?.agent},config3.authority),null,2)}});init_zod();init_ast_diff();init_semantic_classifier();import*as child_process13 from"node:child_process";import*as fs181 from"node:fs";import*as path313 from"node:path";init_git_executable();init_create_tool();var MAX_DIFF_LINES=500,DIFF_TIMEOUT_MS=30000,MAX_BUFFER_BYTES=5242880,MAX_AST_FILES=50,CONTRACT_PATTERNS=[/^[+-]\s*export\s+(function|const|class|interface|type|enum|default)\b/,/^[+-]\s*(interface|type)\s+\w+/,/^[+-]\s*public\s+/,/^[+-]\s*(async\s+)?function\s+\w+\s*\(/],SAFE_REF_PATTERN=/^[a-zA-Z0-9._\-/~^@{}]+$/,MAX_REF_LENGTH2=256,MAX_PATH_LENGTH=500,SHELL_METACHARACTERS3=/[;|&$`(){}<>!'"]/,CONTROL_CHAR_PATTERN2=/[\u0000-\u001F\u007F]/;function validateBase(base){if(base.length>MAX_REF_LENGTH2)return`base ref exceeds maximum length of ${MAX_REF_LENGTH2}`;if(base.startsWith("-"))return"base ref must not begin with a dash";if(!SAFE_REF_PATTERN.test(base))return"base contains invalid characters for git ref";return null}function validatePaths(paths){if(!paths)return null;for(let path314 of paths){if(!path314||path314.length===0)return"empty path not allowed";if(path314.length>MAX_PATH_LENGTH)return`path exceeds maximum length of ${MAX_PATH_LENGTH}`;if(SHELL_METACHARACTERS3.test(path314))return"path contains shell metacharacters";if(path314.startsWith("-"))return'path cannot start with "-" (option-like arguments not allowed)';if(CONTROL_CHAR_PATTERN2.test(path314))return"path contains control characters"}return null}var diff=createSwarmTool({description:"Analyze git diff for changed files, exports, interfaces, and function signatures. Returns structured output with contract change detection.",args:{base:exports_external.string().optional().describe('Base ref to diff against (default: HEAD). Use "staged" for staged changes, "unstaged" for working tree changes.'),paths:exports_external.array(exports_external.string()).optional().describe("Optional file paths to restrict diff scope."),summaryOnly:exports_external.boolean().optional().describe("When true, return only file list with additions/deletions counts and hasContractChanges. No hunk content or AST diff. Default false.")},async execute(args2,directory,_ctx){let typedArgs=args2,summaryOnly=typedArgs.summaryOnly===!0;try{let fileExistsInRef=function(refPath){try{return child_process13.execFileSync(gitExecutable,["cat-file","-e",refPath],{encoding:"utf-8",timeout:3000,cwd:directory,stdio:["ignore","pipe","pipe"]}),!0}catch(e){if(e&&typeof e==="object"&&"code"in e){if(e.code==="ENOENT")throw e}return!1}},getContentFromRef=function(refPath){return child_process13.execFileSync(gitExecutable,["show",refPath],{encoding:"utf-8",timeout:15000,cwd:directory,stdio:["ignore","pipe","pipe"]})};if(!directory||typeof directory!=="string"||directory.trim()==="")return JSON.stringify({error:"project directory is required but was not provided",files:[],contractChanges:[],hasContractChanges:!1},null,2);let base=typedArgs.base??"HEAD",baseValidationError=validateBase(base);if(baseValidationError){let errorResult={error:`invalid base: ${baseValidationError}`,files:[],contractChanges:[],hasContractChanges:!1};return JSON.stringify(errorResult,null,2)}let pathsValidationError=validatePaths(typedArgs.paths);if(pathsValidationError){let errorResult={error:`invalid paths: ${pathsValidationError}`,files:[],contractChanges:[],hasContractChanges:!1};return JSON.stringify(errorResult,null,2)}let gitExecutable=await resolveGitExecutableAsync(),gitArgs;if(base==="staged")gitArgs=["--no-pager","diff","--cached"];else if(base==="unstaged")gitArgs=["--no-pager","diff"];else gitArgs=["--no-pager","diff",base];let numstatArgs=[...gitArgs,"--numstat"],fullDiffArgs=[...gitArgs,"-U3"];if(typedArgs.paths?.length)numstatArgs.push("--",...typedArgs.paths),fullDiffArgs.push("--",...typedArgs.paths);let numstatOutput=child_process13.execFileSync(gitExecutable,numstatArgs,{encoding:"utf-8",timeout:DIFF_TIMEOUT_MS,maxBuffer:MAX_BUFFER_BYTES,cwd:directory,stdio:["ignore","pipe","pipe"]}),files=[],numstatLines=numstatOutput.split(`
|
|
7558
|
+
`)}function synthesizeGeneralCouncil(question,mode,round1Responses,round2Responses){let safeRound1=Array.isArray(round1Responses)?round1Responses:[],safeRound2=Array.isArray(round2Responses)?round2Responses:[],disagreements=detectDisagreements(safeRound1),consensusPoints=buildConsensusClusters(safeRound1,disagreements),persistingDisagreements=computePersistingDisagreements(disagreements,safeRound2),allSources=dedupeSources(safeRound1,safeRound2),roundsCompleted=safeRound2.length>0?2:1,synthesis=renderSynthesisMarkdown(question,mode,roundsCompleted,safeRound1,consensusPoints,persistingDisagreements,allSources);return{question,mode,round1Responses:safeRound1,disagreements,round2Responses:safeRound2,synthesis,consensusPoints,persistingDisagreements:persistingDisagreements.map((d)=>d.topic),allSources,timestamp:new Date().toISOString()}}init_state2();init_logger();init_create_tool();init_resolve_working_directory();var WebSearchResultSchema=exports_external.object({title:exports_external.string(),url:exports_external.string(),snippet:exports_external.string(),query:exports_external.string()}),ClaimSchema=exports_external.object({subject:exports_external.string().min(1).max(120),statement:exports_external.string().min(1).max(600),stance:exports_external.enum(["support","oppose","neutral","concern","alternative"]),confidence:exports_external.number().min(0).max(1),evidence:exports_external.array(exports_external.string().max(240)).max(4).optional()}),MemberClaimsSchema=exports_external.array(ClaimSchema).max(8).optional().catch(void 0),MemberRoleEnum=exports_external.enum(["generalist","skeptic","domain_expert","devil_advocate","synthesizer"]),Round1ResponseSchema=exports_external.object({memberId:exports_external.string().min(1),model:exports_external.string().min(1),role:MemberRoleEnum,response:exports_external.string(),sources:exports_external.array(WebSearchResultSchema).default([]),searchQueries:exports_external.array(exports_external.string()).default([]),confidence:exports_external.number().min(0).max(1),areasOfUncertainty:exports_external.array(exports_external.string()).default([]),durationMs:exports_external.number().nonnegative().default(0),claims:MemberClaimsSchema}),Round2ResponseSchema=Round1ResponseSchema.extend({disagreementTopics:exports_external.array(exports_external.string()).default([])}),ArgsSchema2=exports_external.object({question:exports_external.string().min(1).max(8000),mode:exports_external.enum(["general","spec_review"]).default("general"),members:exports_external.array(exports_external.string()).default([]),round1Responses:exports_external.array(Round1ResponseSchema).min(1),round2Responses:exports_external.array(Round2ResponseSchema).optional(),working_directory:exports_external.string().optional()}),convene_general_council=createSwarmTool({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.",args:{question:exports_external.string().min(1).max(8000).describe("The question put to the council, or the spec text to review."),mode:exports_external.enum(["general","spec_review"]).optional().describe('"general" for /swarm council or pre-save PLAN advisory; "spec_review" for manual /swarm council --spec-review.'),members:exports_external.array(exports_external.string()).optional().describe("Optional list of member IDs convened (for evidence/audit)."),round1Responses:exports_external.array(exports_external.object({memberId:exports_external.string().min(1),model:exports_external.string().min(1),role:exports_external.enum(["generalist","skeptic","domain_expert","devil_advocate","synthesizer"]),response:exports_external.string(),sources:exports_external.array(exports_external.object({title:exports_external.string(),url:exports_external.string(),snippet:exports_external.string(),query:exports_external.string()})).optional(),searchQueries:exports_external.array(exports_external.string()).optional(),confidence:exports_external.number().min(0).max(1),areasOfUncertainty:exports_external.array(exports_external.string()).optional(),durationMs:exports_external.number().nonnegative().optional(),claims:MemberClaimsSchema})).describe("Round 1 member responses (one per council member)."),round2Responses:exports_external.array(exports_external.object({memberId:exports_external.string().min(1),model:exports_external.string().min(1),role:exports_external.enum(["generalist","skeptic","domain_expert","devil_advocate","synthesizer"]),response:exports_external.string(),sources:exports_external.array(exports_external.object({title:exports_external.string(),url:exports_external.string(),snippet:exports_external.string(),query:exports_external.string()})).optional(),searchQueries:exports_external.array(exports_external.string()).optional(),confidence:exports_external.number().min(0).max(1),areasOfUncertainty:exports_external.array(exports_external.string()).optional(),durationMs:exports_external.number().nonnegative().optional(),disagreementTopics:exports_external.array(exports_external.string()).optional(),claims:MemberClaimsSchema})).optional().describe("Round 2 deliberation responses (omit when no deliberation has occurred)."),working_directory:exports_external.string().optional().describe("Project root for config + evidence path resolution.")},execute:async(args2,directory,ctx)=>{let parsed=ArgsSchema2.safeParse(args2);if(!parsed.success){let fail2={success:!1,reason:"invalid_args",message:parsed.error.issues.map((i)=>`${i.path.join(".")}: ${i.message}`).join("; ")};return JSON.stringify(fail2,null,2)}let input=parsed.data,dirResult=resolveWorkingDirectory(input.working_directory,directory);if(!dirResult.success){let fail2={success:!1,reason:"invalid_working_directory",message:dirResult.message};return JSON.stringify(fail2,null,2)}let workingDir=dirResult.directory,generalConfig=loadPluginConfig(workingDir).council?.general;if(!generalConfig||generalConfig.enabled!==!0)return JSON.stringify({success:!1,reason:"council_general_disabled",message:"convene_general_council requires council.general.enabled: true in the resolved config: global ~/.config/opencode/opencode-swarm.json or project .opencode/opencode-swarm.json."},null,2);let round1=input.round1Responses,round2=input.round2Responses??[],result=synthesizeGeneralCouncil(input.question,input.mode,round1,round2),evidenceDir=path311.join(workingDir,".swarm","council","general"),evidenceFile=`${result.timestamp.replace(/[:.]/g,"-")}-${input.mode}.json`,evidencePath=path311.join(evidenceDir,evidenceFile);try{await fs179.promises.mkdir(evidenceDir,{recursive:!0}),await fs179.promises.writeFile(evidencePath,JSON.stringify(result,null,2))}catch(err){let message=err instanceof Error?err.message:String(err);log(`[convene_general_council] Failed to write evidence to ${evidencePath}: ${message}`)}try{let sessionID=ctx?.sessionID;if(sessionID){let session=getAgentSession(sessionID);if(session)pushGeneralCouncilAdvisory(session,result)}}catch{}let ok={success:!0,question:input.question,mode:input.mode,roundsCompleted:round2.length>0?2:1,consensusPoints:result.consensusPoints,disagreementsCount:result.disagreements.length,persistingDisagreements:result.persistingDisagreements,allSourcesCount:result.allSources.length,synthesis:result.synthesis,evidencePath};return JSON.stringify(ok,null,2)}});init_zod();init_config();init_schema();init_core_events();init_curator();init_curator();init_curator_llm_factory();init_review_receipt();init_create_tool();var curator_analyze=createSwarmTool({description:"Run curator phase analysis and optionally apply knowledge recommendations. Call this after reviewing a phase to apply knowledge updates. If recommendations is provided, applies them via applyCuratorKnowledgeUpdates.",args:{phase:exports_external.number().int().min(1).describe("Phase number to analyze"),recommendations:exports_external.array(exports_external.object({action:exports_external.enum(["promote","archive","flag_contradiction","rewrite"]),entry_id:exports_external.string().optional(),lesson:exports_external.string(),reason:exports_external.string(),category:exports_external.enum(["process","architecture","tooling","security","testing","debugging","performance","integration","other"]).optional(),confidence:exports_external.number().min(0).max(1).optional()})).optional().describe("Knowledge recommendations to apply. If omitted, only collects digest data.")},execute:async(args2,directory,ctx)=>{let typedArgs=args2;try{if(!Number.isInteger(typedArgs.phase)||typedArgs.phase<1)return JSON.stringify({error:"phase must be a positive integer >= 1"},null,2);if(typedArgs.recommendations){let validActions=["promote","archive","flag_contradiction","rewrite"];for(let rec of typedArgs.recommendations)if(!validActions.includes(rec.action))return JSON.stringify({error:`Invalid recommendation action: ${rec.action}`},null,2)}if(typedArgs.recommendations){let UUID_V42=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;for(let rec of typedArgs.recommendations)if(rec.entry_id!==void 0&&!UUID_V42.test(rec.entry_id))return JSON.stringify({error:`Invalid entry_id '${rec.entry_id}': must be a UUID v4 or omitted. Use undefined/omit entry_id to create a new entry.`},null,2)}let{config:config3}=loadPluginConfigWithMeta(directory),curatorConfig=CuratorConfigSchema.parse(config3.curator??{}),knowledgeConfig=KnowledgeConfigSchema.parse(config3.knowledge??{}),agentsDispatched=[];try{let eventsWindow=readCoreEvents(directory);if(eventsWindow.text.length>0){let phaseEvents=filterPhaseEvents(eventsWindow.text,typedArgs.phase),agentSet=new Set;for(let evt of phaseEvents){let record3=evt;if(typeof record3.agent==="string"&&record3.agent.length>0)agentSet.add(record3.agent);if(Array.isArray(record3.agents_dispatched)){for(let a of record3.agents_dispatched)if(typeof a==="string")agentSet.add(a)}}agentsDispatched=Array.from(agentSet).sort()}}catch{}let llmDelegate=createCuratorLLMDelegate(directory,"phase",ctx?.sessionID),curatorResult=await runCuratorPhase(directory,typedArgs.phase,agentsDispatched,curatorConfig,{},llmDelegate);{let scopeContent=curatorResult.digest?.summary??`Phase ${typedArgs.phase} curator analysis`,complianceWarnings=curatorResult.compliance.filter((c)=>c.severity==="warning"),receipt=complianceWarnings.length>0?buildRejectedReceipt({agent:"curator",scopeContent,scopeDescription:"phase-digest",blockingFindings:complianceWarnings.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: ${typedArgs.phase}`,`knowledge_recommendations: ${curatorResult.knowledge_recommendations.length}`]});persistReviewReceipt(directory,receipt).catch(()=>{})}let applied2=0,skipped=0;if(typedArgs.recommendations&&typedArgs.recommendations.length>0){let result=await applyCuratorKnowledgeUpdates(directory,typedArgs.recommendations,knowledgeConfig);applied2=result.applied,skipped=result.skipped}return JSON.stringify({phase_digest:curatorResult.digest,compliance_count:curatorResult.compliance.length,applied:applied2,skipped},null,2)}catch(error93){return JSON.stringify({error:error93 instanceof Error?error93.message:String(error93),phase:typedArgs.phase},null,2)}}});init_zod();init_loader();init_create_tool();init_resolve_working_directory();var CriteriaItemSchema=exports_external.object({id:exports_external.string().min(1).max(20).regex(/^C\d+$/,'Criterion id must match C\\d+ (e.g. "C1", "C12")'),description:exports_external.string().min(10).max(500),mandatory:exports_external.boolean()}),ArgsSchema3=exports_external.object({taskId:exports_external.string().min(1).regex(/^\d+\.\d+(\.\d+)*$/,"Task ID must be in N.M or N.M.P format"),criteria:exports_external.array(CriteriaItemSchema).min(1).max(20),working_directory:exports_external.string().optional()}),declare_council_criteria=createSwarmTool({description:"Pre-declare acceptance criteria for a task before the coder starts work. Criteria are persisted under .swarm/council/ and read back during council evaluation so reviewers assess a stable, pre-committed contract. Architect-only. Config-gated via council.enabled.",args:{taskId:exports_external.string().min(1).regex(/^\d+\.\d+(\.\d+)*$/,"Task ID must be in N.M or N.M.P format").describe('Task ID for which criteria are declared, e.g. "1.1", "1.2.3"'),criteria:exports_external.array(exports_external.object({id:exports_external.string().min(1).max(20).regex(/^C\d+$/,"Criterion id must match C\\d+").describe('Criterion identifier, e.g. "C1", "C12"'),description:exports_external.string().min(10).max(500).describe("Human-readable description of the criterion"),mandatory:exports_external.boolean().describe("Whether the criterion is mandatory. Mandatory criteria block APPROVE when unmet.")})).min(1).max(20).describe("Array of acceptance criteria items. Must contain between 1 and 20 entries with unique ids."),working_directory:exports_external.string().optional().describe("Explicit project root directory. When provided, .swarm/council/ is resolved relative to this path instead of the plugin context directory.")},async execute(args2,directory){let parsed=ArgsSchema3.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,reason:"invalid arguments",errors:parsed.error.issues.map((i)=>({path:i.path.join("."),message:i.message}))},null,2);let input=parsed.data,dirResult=resolveWorkingDirectory(input.working_directory,directory);if(!dirResult.success)return JSON.stringify({success:!1,reason:dirResult.message},null,2);let workingDir=dirResult.directory;if(!loadPluginConfig(workingDir).council?.enabled)return JSON.stringify({success:!1,reason:"council feature is disabled — set council.enabled: true in .opencode/opencode-swarm.json to enable"},null,2);let ids=input.criteria.map((c)=>c.id);if(new Set(ids).size<ids.length){let seen=new Set,duplicates=[];for(let id of ids){if(seen.has(id)&&!duplicates.includes(id))duplicates.push(id);seen.add(id)}return JSON.stringify({success:!1,reason:"duplicate criterion ids",errors:duplicates},null,2)}let replaced=readCriteria(workingDir,input.taskId)!==null;return await writeCriteria(workingDir,input.taskId,input.criteria),JSON.stringify({success:!0,taskId:input.taskId,criteriaCount:input.criteria.length,mandatoryCount:input.criteria.filter((c)=>c.mandatory).length,declaredAt:new Date().toISOString(),replaced},null,2)}});init_zod();init_config();init_plan_schema();init_file_authority();init_path_identity();init_scope_binding();init_scope_persistence();init_state2();init_project_boundary();init_task_id();init_create_tool();import*as fs180 from"node:fs";import*as path312 from"node:path";function validateTaskIdFormat2(taskId){return validateTaskIdFormat(taskId)}function validateFiles(files){let errors5=[],totalBytes=0;for(let file3 of files){if(file3.includes("\x00")){errors5.push(`Invalid file "${file3}": null bytes are not allowed`);continue}let unsafeReason=unsafePathTextReason(file3);if(unsafeReason){errors5.push(`Invalid file path: ${unsafeReason}`);continue}if(file3.replace(/\\/g,"/").split("/").includes(".."))errors5.push(`Invalid file "${file3}": path traversal sequences (..) are not allowed`);let bytes=Buffer.byteLength(file3,"utf8");if(totalBytes+=bytes,bytes>MAX_SCOPE_PATH_BYTES)errors5.push(`Invalid file "${file3}": path exceeds maximum length of ${MAX_SCOPE_PATH_BYTES} UTF-8 bytes`)}if(totalBytes>MAX_SCOPE_FILES_BYTES)errors5.push(`Invalid scope: file paths exceed the aggregate limit of ${MAX_SCOPE_FILES_BYTES} UTF-8 bytes`);return errors5}async function executeDeclareScope(args2,fallbackDir,owner,authorityConfig){let taskIdError=validateTaskIdFormat2(args2.taskId);if(taskIdError)return{success:!1,message:"Validation failed",errors:[taskIdError]};if(!Array.isArray(args2.files)||args2.files.length===0)return{success:!1,message:"Validation failed",errors:["files must be a non-empty array"]};let fileErrors=validateFiles(args2.files);if(fileErrors.length>0)return{success:!1,message:"Validation failed",errors:fileErrors};if(args2.whitelist){let whitelistErrors=validateFiles(args2.whitelist);if(whitelistErrors.length>0)return{success:!1,message:"Validation failed",errors:whitelistErrors}}let normalizedDir;if(args2.working_directory!=null&&args2.working_directory.trim()!==""){if(args2.working_directory.includes("\x00"))return{success:!1,message:"Invalid working_directory: null bytes are not allowed",errors:["Invalid working_directory: null bytes are not allowed"]};if(/^\\\\|^(NUL|CON|AUX|COM[1-9]|LPT[1-9])(\..*)?$/i.test(args2.working_directory))return{success:!1,message:"Invalid working_directory: Windows device paths are not allowed",errors:["Invalid working_directory: Windows device paths are not allowed"]};if(normalizedDir=path312.normalize(args2.working_directory),normalizedDir.split(path312.sep).includes(".."))return{success:!1,message:"Invalid working_directory: path traversal sequences (..) are not allowed",errors:["Invalid working_directory: path traversal sequences (..) are not allowed"]};let resolvedDir=path312.resolve(normalizedDir);try{let realPath=fs180.realpathSync(resolvedDir),planPath2=path312.join(realPath,".swarm","plan.json");if(!fs180.existsSync(planPath2))return{success:!1,message:`Invalid working_directory: plan not found in "${realPath}"`,errors:[`Invalid working_directory: plan not found in "${realPath}"`]}}catch{return{success:!1,message:`Invalid working_directory: path "${resolvedDir}" does not exist or is inaccessible`,errors:[`Invalid working_directory: path "${resolvedDir}" does not exist or is inaccessible`]}}if(normalizedDir&&fallbackDir)try{let canonicalWorkingDir=fs180.realpathSync(path312.resolve(normalizedDir)),canonicalProjectRoot=fs180.realpathSync(path312.resolve(fallbackDir));if(isStrictPathDescendant(canonicalWorkingDir,canonicalProjectRoot)&&!hasExplicitProjectBoundary(canonicalWorkingDir))return{success:!1,message:`working_directory "${normalizedDir}" is a subdirectory of the project root. Use the project root "${fallbackDir}" instead.`,errors:[`Subdirectory working_directory not allowed — use project root "${fallbackDir}"`]}}catch{}}if(!normalizedDir&&!fallbackDir)return{success:!1,message:"Cannot resolve project directory",errors:["Provide working_directory or ensure the tool is invoked from a project root"]};let directory=normalizedDir||fallbackDir,planPath=path312.resolve(directory,".swarm","plan.json");if(!fs180.existsSync(planPath))return{success:!1,message:"No plan found",errors:["plan.json not found"]};let rawPlanContent;try{rawPlanContent=JSON.parse(fs180.readFileSync(planPath,"utf-8"))}catch{return{success:!1,message:"Failed to parse plan.json",errors:["plan.json is not valid JSON"]}}let parsedPlan=PlanSchema.safeParse(rawPlanContent);if(!parsedPlan.success)return{success:!1,message:"Failed to validate plan.json",errors:["plan.json does not match the supported plan schema"]};let planContent=parsedPlan.data,allTasks=planContent.phases?.flatMap((p)=>p.tasks??[])??[];if(!allTasks.some((t)=>t.id===args2.taskId))return{success:!1,message:`Task ${args2.taskId} not found in plan`,errors:[`Task ${args2.taskId} does not exist in plan.json`]};let taskInPlan=allTasks.find((t)=>t.id===args2.taskId);if(taskInPlan&&taskInPlan.status==="completed")return{success:!1,message:`Task ${args2.taskId} is already completed`,errors:[`Cannot declare scope for completed task ${args2.taskId}`]};let rawMergedFiles=[...args2.files,...args2.whitelist??[]],warnings=[],normalizeErrors=[],dir=directory,mergedFiles=rawMergedFiles.map((file3)=>{if(path312.isAbsolute(file3)){let relativePath2=path312.relative(dir,file3).replace(/\\/g,"/");if(relativePath2.startsWith(".."))return normalizeErrors.push(`Path '${file3}' resolves outside the project directory`),file3;return warnings.push(`Absolute path normalized to relative: '${relativePath2}' (was '${file3}')`),relativePath2}return file3});if(normalizeErrors.length>0)return{success:!1,message:"Validation failed",errors:normalizeErrors};let lstatErrors=[];for(let file3 of mergedFiles){let block=checkWriteTargetForSymlink(file3,dir);if(block)lstatErrors.push(block)}if(lstatErrors.length>0)return{success:!1,message:"Scope contains symlink-backed paths",errors:lstatErrors};let authorityErrors=[];for(let file3 of mergedFiles){let decision=checkFileAuthority("coder",file3,dir,authorityConfig,{declaredScope:[file3]});if(!decision.allowed)authorityErrors.push(decision.reason)}if(authorityErrors.length>0)return{success:!1,message:"Scope denied by effective coder authority",errors:authorityErrors};if(owner?.sessionID&&owner.messageID){let binding=createScopeBinding({directory:dir,plan:planContent,taskId:args2.taskId,files:mergedFiles,ownerSessionId:owner.sessionID,ownerMessageId:owner.messageID,source:"declare_scope"});if(!binding)return{success:!1,message:"Failed to bind scope to the calling session",errors:["Scope identity could not be validated"]};let persistence=await replaceExistingScopeDeclaration({directory:dir,binding,replaceExisting:args2.replace_existing??!1});if(!persistence.ok)return{success:!1,message:"Failed to persist scope declaration",errors:[`${persistence.code}: ${persistence.message}`]};let session=ensureAgentSession(owner.sessionID,owner.agentName??"architect",dir);session.declaredCoderScope=mergedFiles,session.lastScopeViolation=null}return warnings.push("SCOPE ENFORCEMENT: This declaration is bound to the caller session and current plan. Direct writes and statically detected shell/interpreter writes must stay inside the active Task-correlated scope; missing or unverifiable coder write authority fails closed with SCOPE_NOT_DECLARED or SCOPE_VIOLATION."),{success:!0,message:"Scope declared successfully",taskId:args2.taskId,fileCount:mergedFiles.length,warnings}}var declare_scope=createSwarmTool({description:"Declare the file scope for the next coder delegation. Sets the list of files the coder is permitted to modify for a specific task. Must be called before delegating to coder to enable scope containment checking.",args:{taskId:exports_external.string().min(1).regex(/^\d+\.\d+(\.\d+)*$/,"Task ID must be in N.M or N.M.P format").describe('Task ID for which scope is being declared, e.g. "1.1", "1.2.3"'),files:exports_external.array(exports_external.string().min(1).max(4096)).min(1).describe("Array of file paths the coder is permitted to modify"),whitelist:exports_external.array(exports_external.string().min(1).max(4096)).optional().describe("Additional file paths to whitelist (merged with files)"),replace_existing:exports_external.boolean().optional().describe("Set true to atomically revoke and replace this session's existing live declaration for the same task"),working_directory:exports_external.string().optional().describe("Working directory where the plan is located")},execute:async(args2,_directory2,ctx)=>{let{config:config3}=loadPluginConfigWithMeta(_directory2);return JSON.stringify(await executeDeclareScope(args2,_directory2,{sessionID:ctx?.sessionID??"",messageID:ctx?.messageID??"",agentName:ctx?.agent},config3.authority),null,2)}});init_zod();init_ast_diff();init_semantic_classifier();import*as child_process13 from"node:child_process";import*as fs181 from"node:fs";import*as path313 from"node:path";init_git_executable();init_create_tool();var MAX_DIFF_LINES=500,DIFF_TIMEOUT_MS=30000,MAX_BUFFER_BYTES=5242880,MAX_AST_FILES=50,CONTRACT_PATTERNS=[/^[+-]\s*export\s+(function|const|class|interface|type|enum|default)\b/,/^[+-]\s*(interface|type)\s+\w+/,/^[+-]\s*public\s+/,/^[+-]\s*(async\s+)?function\s+\w+\s*\(/],SAFE_REF_PATTERN=/^[a-zA-Z0-9._\-/~^@{}]+$/,MAX_REF_LENGTH2=256,MAX_PATH_LENGTH=500,SHELL_METACHARACTERS3=/[;|&$`(){}<>!'"]/,CONTROL_CHAR_PATTERN2=/[\u0000-\u001F\u007F]/;function validateBase(base){if(base.length>MAX_REF_LENGTH2)return`base ref exceeds maximum length of ${MAX_REF_LENGTH2}`;if(base.startsWith("-"))return"base ref must not begin with a dash";if(!SAFE_REF_PATTERN.test(base))return"base contains invalid characters for git ref";return null}function validatePaths(paths){if(!paths)return null;for(let path314 of paths){if(!path314||path314.length===0)return"empty path not allowed";if(path314.length>MAX_PATH_LENGTH)return`path exceeds maximum length of ${MAX_PATH_LENGTH}`;if(SHELL_METACHARACTERS3.test(path314))return"path contains shell metacharacters";if(path314.startsWith("-"))return'path cannot start with "-" (option-like arguments not allowed)';if(CONTROL_CHAR_PATTERN2.test(path314))return"path contains control characters"}return null}var diff=createSwarmTool({description:"Analyze git diff for changed files, exports, interfaces, and function signatures. Returns structured output with contract change detection.",args:{base:exports_external.string().optional().describe('Base ref to diff against (default: HEAD). Use "staged" for staged changes, "unstaged" for working tree changes.'),paths:exports_external.array(exports_external.string()).optional().describe("Optional file paths to restrict diff scope."),summaryOnly:exports_external.boolean().optional().describe("When true, return only file list with additions/deletions counts and hasContractChanges. No hunk content or AST diff. Default false.")},async execute(args2,directory,_ctx){let typedArgs=args2,summaryOnly=typedArgs.summaryOnly===!0;try{let fileExistsInRef=function(refPath){try{return child_process13.execFileSync(gitExecutable,["cat-file","-e",refPath],{encoding:"utf-8",timeout:3000,maxBuffer:MAX_BUFFER_BYTES,cwd:directory,stdio:["ignore","pipe","pipe"]}),!0}catch(e){if(e&&typeof e==="object"&&"code"in e){if(e.code==="ENOENT")throw e}return!1}},getContentFromRef=function(refPath){return child_process13.execFileSync(gitExecutable,["show",refPath],{encoding:"utf-8",timeout:15000,maxBuffer:MAX_BUFFER_BYTES,cwd:directory,stdio:["ignore","pipe","pipe"]})};if(!directory||typeof directory!=="string"||directory.trim()==="")return JSON.stringify({error:"project directory is required but was not provided",files:[],contractChanges:[],hasContractChanges:!1},null,2);let base=typedArgs.base??"HEAD",baseValidationError=validateBase(base);if(baseValidationError){let errorResult={error:`invalid base: ${baseValidationError}`,files:[],contractChanges:[],hasContractChanges:!1};return JSON.stringify(errorResult,null,2)}let pathsValidationError=validatePaths(typedArgs.paths);if(pathsValidationError){let errorResult={error:`invalid paths: ${pathsValidationError}`,files:[],contractChanges:[],hasContractChanges:!1};return JSON.stringify(errorResult,null,2)}let gitExecutable=await resolveGitExecutableAsync(),gitArgs;if(base==="staged")gitArgs=["--no-pager","diff","--cached"];else if(base==="unstaged")gitArgs=["--no-pager","diff"];else gitArgs=["--no-pager","diff",base];let numstatArgs=[...gitArgs,"--numstat"],fullDiffArgs=[...gitArgs,"-U3"];if(typedArgs.paths?.length)numstatArgs.push("--",...typedArgs.paths),fullDiffArgs.push("--",...typedArgs.paths);let numstatOutput=child_process13.execFileSync(gitExecutable,numstatArgs,{encoding:"utf-8",timeout:DIFF_TIMEOUT_MS,maxBuffer:MAX_BUFFER_BYTES,cwd:directory,stdio:["ignore","pipe","pipe"]}),files=[],numstatLines=numstatOutput.split(`
|
|
7553
7559
|
`);for(let line of numstatLines){if(!line.trim())continue;let parts=line.split("\t");if(parts.length>=3){let additions=parseInt(parts[0],10)||0,deletions=parseInt(parts[1],10)||0,path314=parts[2];files.push({path:path314,additions,deletions})}}if(summaryOnly){let hasContractChanges2=!1;try{let contractDiffArgs=[...gitArgs,"-U0"];if(typedArgs.paths?.length)contractDiffArgs.push("--",...typedArgs.paths);let contractDiffLines=child_process13.execFileSync(gitExecutable,contractDiffArgs,{encoding:"utf-8",timeout:DIFF_TIMEOUT_MS,maxBuffer:MAX_BUFFER_BYTES,cwd:directory,stdio:["ignore","pipe","pipe"]}).split(`
|
|
7554
7560
|
`);for(let line of contractDiffLines){for(let pattern of CONTRACT_PATTERNS)if(pattern.test(line)){hasContractChanges2=!0;break}if(hasContractChanges2)break}}catch{hasContractChanges2=!0}let result2={files,contractChanges:[],hasContractChanges:hasContractChanges2,summary:`${files.length} files changed (summary only)`};return JSON.stringify(result2,null,2)}let fullDiffOutput=child_process13.execFileSync(gitExecutable,fullDiffArgs,{encoding:"utf-8",timeout:DIFF_TIMEOUT_MS,maxBuffer:MAX_BUFFER_BYTES,cwd:directory,stdio:["ignore","pipe","pipe"]}),contractChanges=[],diffLines=fullDiffOutput.split(`
|
|
7555
7561
|
`),currentFile="";for(let line of diffLines){let gitLineMatch=line.match(/^diff --git.* b\/(.+)$/);if(gitLineMatch)currentFile=gitLineMatch[1];for(let pattern of CONTRACT_PATTERNS)if(pattern.test(line)){let trimmed=line.trim();if(currentFile)contractChanges.push(`[${currentFile}] ${trimmed}`);else contractChanges.push(trimmed);break}}let hasContractChanges=contractChanges.length>0,fileCount=files.length,astDiffs=[],filesForAST=files.slice(0,MAX_AST_FILES);for(let file3 of filesForAST)try{let oldContent,newContent;if(base==="staged"){let oldRef=`HEAD:${file3.path}`;oldContent=fileExistsInRef(oldRef)?getContentFromRef(oldRef):"",newContent=getContentFromRef(`:${file3.path}`)}else if(base==="unstaged"){let oldRef=`:${file3.path}`;oldContent=fileExistsInRef(oldRef)?getContentFromRef(oldRef):"",newContent=fs181.readFileSync(path313.join(directory,file3.path),"utf-8")}else{let oldRef=`${base}:${file3.path}`;oldContent=fileExistsInRef(oldRef)?getContentFromRef(oldRef):"",newContent=getContentFromRef(`HEAD:${file3.path}`)}let astResult=await computeASTDiff(file3.path,oldContent,newContent);if(astResult&&(astResult.changes.length>0||astResult.error))astDiffs.push(astResult)}catch(e){if(e&&typeof e==="object"&&"code"in e){if(e.code==="ENOENT")throw e}astDiffs.push({filePath:file3.path,language:null,changes:[{type:"modified",category:"other",name:"(parse failed)",lineStart:0,lineEnd:0}],durationMs:0,usedAST:!1,error:"AST parse unavailable — tree-sitter analysis failed for this file"})}let semanticSummary;if(astDiffs.length>0)try{let classifiedChanges=classifyChanges(astDiffs);semanticSummary=generateSummary(classifiedChanges)}catch{}let markdownSummary;if(semanticSummary)try{markdownSummary=generateSummaryMarkdown(semanticSummary)}catch{}let astSkippedCount=files.length>MAX_AST_FILES?files.length-MAX_AST_FILES:0,summary=diffLines.length>MAX_DIFF_LINES?`${fileCount} files changed. Contract changes: ${hasContractChanges?"YES":"NO"}. (truncated to ${MAX_DIFF_LINES} lines)`:`${fileCount} files changed. Contract changes: ${hasContractChanges?"YES":"NO"}`,result={files,contractChanges,hasContractChanges,summary,...astDiffs.length>0?{astDiffs}:{},...semanticSummary?{semanticSummary}:{},...markdownSummary?{markdownSummary}:{},...astSkippedCount>0?{astSkippedCount}:{}};return JSON.stringify(result,null,2)}catch(e){let errorResult={error:e instanceof Error?`git diff failed: ${e.message}`:"git diff failed: unknown error",files:[],contractChanges:[],hasContractChanges:!1};return JSON.stringify(errorResult,null,2)}}});init_zod();init_ast_diff();init_semantic_classifier();import*as child_process14 from"node:child_process";import*as fs182 from"node:fs";import*as path314 from"node:path";init_git_binary_missing_error();init_git_executable();init_create_tool();init_resolve_working_directory();var _internals258={execFile:child_process14.execFile,resolveGitExecutableAsync,execGit:execGit2};async function execGit2(workingDir,args2,options){try{let gitExecutable=await _internals258.resolveGitExecutableAsync();return await new Promise((resolve126,reject2)=>{let execOpts={encoding:"utf-8",cwd:workingDir,timeout:options?.timeout,maxBuffer:options?.maxBuffer,stdio:["ignore","pipe","pipe"]};_internals258.execFile(gitExecutable,args2,execOpts,(error93,output,_stderr)=>{if(error93){reject2(error93);return}resolve126(output??"")})})}catch(err){if(isSpawnCwdMissing(err,workingDir))throw new GitSpawnCwdError(workingDir,"missing",{cause:err});if(isSpawnCwdUnreadable(err,workingDir))throw new GitSpawnCwdError(workingDir,"unreadable",{cause:err});if(isGitBinaryMissing(err,workingDir))throw new GitBinaryMissingError(`git executable is not available on PATH (working directory ${workingDir} exists)`,{cause:err});throw err}}var diff_summary=createSwarmTool({description:"Generate a filtered semantic diff summary from AST analysis. Returns SemanticDiffSummary with optional filtering by classification or riskLevel.",args:{files:exports_external.array(exports_external.string()).describe("Array of file paths to analyze"),classification:exports_external.string().optional().describe("Filter results to only this ChangeCategory"),riskLevel:exports_external.string().optional().describe("Filter results to only this RiskLevel")},async execute(args2,directory,_ctx){let typedArgs=args2;try{if(!typedArgs.files||!Array.isArray(typedArgs.files)||typedArgs.files.length===0)return JSON.stringify({error:"files must be a non-empty array of file paths",success:!1},null,2);let resolved=resolveWorkingDirectory(void 0,directory);if(!resolved.success)return JSON.stringify({success:!1,error:resolved.message},null,2);let workingDir=resolved.directory,astDiffs=[];for(let filePath of typedArgs.files){let astResult=null,fileExistsInHead=!1;try{await execGit2(workingDir,["cat-file","-e",`HEAD:${filePath}`],{timeout:3000}),fileExistsInHead=!0}catch(e){if(e instanceof GitUnavailableError)throw e}try{let oldContent,newContent=await fs182.promises.readFile(path314.join(workingDir,filePath),"utf-8");if(fileExistsInHead)oldContent=await execGit2(workingDir,["show",`HEAD:${filePath}`],{timeout:5000,maxBuffer:5242880});else oldContent="";astResult=await computeASTDiff(filePath,oldContent,newContent)}catch(e){if(e instanceof GitUnavailableError)throw e;astResult=null}if(astResult&&(astResult.changes.length>0||astResult.error!==void 0))astDiffs.push(astResult)}let filteredChanges=classifyChanges(astDiffs);if(typedArgs.classification)filteredChanges=filteredChanges.filter((change)=>change.category===typedArgs.classification);if(typedArgs.riskLevel)filteredChanges=filteredChanges.filter((change)=>change.riskLevel===typedArgs.riskLevel);let summary=generateSummary(filteredChanges);return JSON.stringify(summary,null,2)}catch(e){let errorResult={error:e instanceof Error?`diff_summary failed: ${e.message}`:"diff_summary failed: unknown error",success:!1};return JSON.stringify(errorResult,null,2)}}});init_p_limit();init_zod();init_agents2();init_candidate_contract();init_delegation_lifecycle();import{createHash as createHash102}from"node:crypto";init_canonical_root();init_lane_output_store();import*as fs184 from"node:fs";import*as path316 from"node:path";var LANE_DELIVERY_CACHE_FILENAME="lane-delivery-cache.json",MAX_DELIVERED_LANE_OUTPUT_KEYS=1024,MAX_TRACKED_SESSIONS11=16,MAX_TRACKED_DIRECTORIES2=16,CORRUPT_SUFFIX=".corrupt",directoryBuckets=new Map;function bucketKey(directory){return directory?canonicalRootKeyFresh(directory):""}function emptyBucket(){return{order:[],sessions:new Map,total:0}}function cacheFilePath(directory){return path316.join(directory,".swarm",LANE_DELIVERY_CACHE_FILENAME)}function isValidCacheFile(value){if(!value||typeof value!=="object"||value.version!==1)return!1;let{order,sessions}=value;if(!Array.isArray(order)||order.some((id)=>typeof id!=="string"))return!1;if(!sessions||typeof sessions!=="object")return!1;return Object.values(sessions).every((keys)=>Array.isArray(keys)&&keys.every((key2)=>typeof key2==="string"))}function loadBucketFromDisk(directory){let file3=cacheFilePath(directory),raw;try{raw=fs184.readFileSync(file3,"utf-8")}catch{return emptyBucket()}let parsed;try{parsed=JSON.parse(raw)}catch{parsed=null}if(!isValidCacheFile(parsed)){try{let corruptPath=`${file3}${CORRUPT_SUFFIX}`,lastRenameError;for(let attempt=0;attempt<3;attempt++)try{fs184.renameSync(file3,corruptPath),lastRenameError=void 0;break}catch(err){lastRenameError=err;let code=err.code;if(code!=="EEXIST"&&code!=="EBUSY"&&code!=="EPERM")break}if(lastRenameError)throw lastRenameError}catch{}return emptyBucket()}let bucket=emptyBucket(),seen=new Set;for(let sessionID of parsed.order){if(seen.has(sessionID))continue;let keys=parsed.sessions[sessionID];if(!keys||keys.length===0)continue;seen.add(sessionID),bucket.order.push(sessionID),bucket.sessions.set(sessionID,[...keys]),bucket.total+=keys.length}return bucket}function persistBucket(directory,bucket){let file3={version:1,order:bucket.order,sessions:Object.fromEntries(bucket.sessions)};try{writeAtomicJson(cacheFilePath(directory),file3)}catch{}}function evictOverflow(bucket){while(bucket.total>MAX_DELIVERED_LANE_OUTPUT_KEYS){let evicted=!1;for(let sessionID of bucket.order){let keys=bucket.sessions.get(sessionID);if(!keys||keys.length===0)continue;if(keys.shift(),bucket.total-=1,keys.length===0)bucket.sessions.delete(sessionID),bucket.order=bucket.order.filter((id)=>id!==sessionID);evicted=!0;break}if(!evicted)break}}function bucketFor(directory){let key2=bucketKey(directory),existing=directoryBuckets.get(key2);if(existing)return existing;while(directoryBuckets.size>=MAX_TRACKED_DIRECTORIES2){let oldestDirectory=directoryBuckets.keys().next().value;if(oldestDirectory===void 0)break;directoryBuckets.delete(oldestDirectory)}let bucket=directory?loadBucketFromDisk(directory):emptyBucket();return directoryBuckets.set(key2,bucket),bucket}function sessionKeys(bucket,sessionID){let key2=sessionID??"",keys=bucket.sessions.get(key2);if(!keys){while(bucket.order.length>=MAX_TRACKED_SESSIONS11){let oldest=bucket.order.shift();if(oldest===void 0)break;let oldestKeys=bucket.sessions.get(oldest);bucket.sessions.delete(oldest),bucket.total-=oldestKeys?.length??0}keys=[],bucket.sessions.set(key2,keys),bucket.order.push(key2)}return keys}function hasLaneOutputBeenDelivered(directory,sessionID,key2){if(!key2)return!1;return bucketFor(directory).sessions.get(sessionID??"")?.includes(key2)??!1}function markLaneOutputDelivered(directory,sessionID,key2){if(!key2)return;let bucket=bucketFor(directory),keys=sessionKeys(bucket,sessionID);if(keys.includes(key2))return;if(keys.push(key2),bucket.total+=1,evictOverflow(bucket),directory)persistBucket(directory,bucket)}init_lane_output_store();init_pending_delegations();init_pr_review_collection_receipt();init_pr_review_contract();init_pr_review_trigger_contract();init_workspace_snapshot();init_constants();init_loader();init_schema();init_invocation_failure();init_pr_workflow_gate();init_p_limit();function createParallelDispatcher(config3){let limit=pLimit(config3.maxConcurrentTasks),activeSlots=new Map,slotCounter=0,shutdownCalled=!1;return{config:config3,dispatch(taskId){if(!config3.enabled)return{action:"reject",reason:"dispatcher_disabled"};if(shutdownCalled)return{action:"reject",reason:"dispatcher_shutdown"};if(activeSlots.size>=config3.maxConcurrentTasks)return{action:"defer",reason:"max_concurrent_tasks_reached"};let slotId=`slot-${++slotCounter}`,runId=`run-${taskId}-${slotId}`,slot={slotId,taskId,runId,startedAt:Date.now()};return activeSlots.set(slotId,slot),limit(async()=>{}),{action:"dispatch",reason:"slot_available",slot}},handles(){return[...activeSlots.values()].map((slot)=>({slotId:slot.slotId,taskId:slot.taskId,runId:slot.runId,cancel:()=>{activeSlots.delete(slot.slotId)}}))},releaseSlot(slotId){activeSlots.delete(slotId)},shutdown(){shutdownCalled=!0,activeSlots.clear(),limit.clearQueue()}}}init_circuit();init_persistence();init_reducer();init_state2();init_canonical_root();init_ephemeral_session_teardown();init_logger();init_model_dispatch_fallback();init_provider_error_classification();init_create_tool();var MAX_LANES=8,MAX_PROMPT_CHARS=80000,COMMON_PROMPT_SEPARATOR=`
|
|
@@ -7713,10 +7719,10 @@ Regenerated on: save_plan and phase_complete.
|
|
|
7713
7719
|
`)}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 fs197 from"node:fs";import*as path332 from"node:path";init_state4();var DEFAULT_CONFIG4={phase_reviewer:!0,phase_critic:!0,integrated_diff_required:!1};function defaultReadPlanJson(dir){try{let planPath=path332.join(dir,".swarm","plan.json");if(!fs197.existsSync(planPath))return null;let raw=fs197.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=path332.join(directory,".swarm","evidence",String(phase),"lean-turbo-reviewer.json");if(!fs197.existsSync(evidencePath))return null;let raw=fs197.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=path332.join(directory,".swarm","evidence",String(phase),"lean-turbo-critic.json");if(!fs197.existsSync(evidencePath))return null;let raw=fs197.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=path332.join(directory,".swarm","evidence",String(phase),"lean-turbo"),entries2;try{entries2=fs197.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 _internals279={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},statePath3=path332.join(directory,".swarm","turbo-state.json");if(!fs197.existsSync(statePath3))return{ok:!1,reason:"Lean Turbo state unreadable or missing"};let persisted=_internals279.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(_internals279.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=_internals279.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=_internals279.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=_internals279.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=path332.join(directory,".swarm","evidence",String(phase),"lean-turbo","lean-turbo-phase.json"),hasDiff=!1;try{let content=fs197.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=_internals279.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=_internals279.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?`
|
|
7714
7720
|
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 fs198 from"node:fs";import*as path333 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=path333.join(dir,".swarm","plan.json");if(fs198.existsSync(planPath)){let planRaw=fs198.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=path333.join(dir,".swarm","evidence",String(phase),"drift-verifier.json"),driftVerdictFound=!1,driftVerdictApproved=!1;try{let driftEvidenceContent=fs198.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=path333.join(dir,".swarm","plan.json");if(fs198.existsSync(planPath)){let planRaw=fs198.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 fs199 from"node:fs";import*as path334 from"node:path";init_council_review_identity();init_types();init_qa_gate_profile();init_utils3();init_state2();function readLatestRetroTimestampMs(dir,phase){let baseDir=path334.normalize(path334.resolve(dir,".swarm")),retroPath=path334.normalize(path334.join(baseDir,"evidence",`retro-${phase}`,"evidence.json"));if(!(process.platform==="win32"?retroPath.toLowerCase().startsWith(baseDir.toLowerCase()+path334.sep)||retroPath.toLowerCase()===baseDir.toLowerCase():retroPath.startsWith(baseDir+path334.sep)||retroPath===baseDir))return null;try{let content=fs199.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=path334.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=fs199.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??{},{preset:ctx.pluginConfig.preset})}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 _internals280.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 _internals280={collectReviewDiff};import*as fs200 from"node:fs";import*as path335 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=path335.join(dir,".swarm","evidence",String(phase),"hallucination-guard.json"),hgVerdictFound=!1,hgVerdictApproved=!1;try{let hgContent=fs200.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 fs201 from"node:fs";import*as path336 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=path336.join(dir,".swarm","evidence",String(phase),"mutation-gate.json"),mgVerdictFound=!1,mgVerdict;try{let mgContent=fs201.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 fs202 from"node:fs";import*as path337 from"node:path";init_council_review_identity();function readLatestRetroTimestampMs2(dir,phase){let baseDir=path337.normalize(path337.resolve(dir,".swarm")),retroPath=path337.normalize(path337.join(baseDir,"evidence",`retro-${phase}`,"evidence.json"));if(!(process.platform==="win32"?retroPath.toLowerCase().startsWith(baseDir.toLowerCase()+path337.sep)||retroPath.toLowerCase()===baseDir.toLowerCase():retroPath.startsWith(baseDir+path337.sep)||retroPath===baseDir))return null;try{return latestRetroTimestampMsFromBundle(JSON.parse(fs202.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=path337.join(dir,".swarm","evidence",String(phase),"phase-council.json"),pcVerdictFound=!1,_pcVerdict,pcQuorumSize,pcPhaseNumber;try{let pcContent=fs202.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?`
|
|
7715
7721
|
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?`
|
|
7716
|
-
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 createHash108}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 createHash108("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 createHash109}from"node:crypto";import*as fs203 from"node:fs";import*as path338 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 relative84=path338.relative(root,candidate2);return relative84===""||relative84!==".."&&!relative84.startsWith(`..${path338.sep}`)&&!path338.isAbsolute(relative84)}function computePhaseEvidenceSnapshot(directory){let root=fs203.realpathSync(directory),entries2=[],totalBytes=0,visitedEntries=0,visit=(absolute)=>{if(!isContained3(root,absolute))throw Error("PHASE_SNAPSHOT_PATH_ESCAPE");let stat25;try{stat25=fs203.lstatSync(absolute)}catch(error93){if(error93.code==="ENOENT")return;throw error93}if(stat25.isSymbolicLink())throw Error(`PHASE_SNAPSHOT_UNSAFE_PATH: ${path338.relative(root,absolute)}`);if(stat25.isDirectory()){let names=[],handle=fs203.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(path338.join(absolute,name));return}if(!stat25.isFile())throw Error(`PHASE_SNAPSHOT_NON_REGULAR: ${path338.relative(root,absolute)}`);if(entries2.length>=MAX_SNAPSHOT_FILES)throw Error("PHASE_SNAPSHOT_FILE_LIMIT");if(totalBytes+=stat25.size,totalBytes>MAX_SNAPSHOT_BYTES)throw Error("PHASE_SNAPSHOT_BYTE_LIMIT");let descriptor=fs203.openSync(absolute,fs203.constants.O_RDONLY|(fs203.constants.O_NOFOLLOW??0));try{let opened=fs203.fstatSync(descriptor);if(!opened.isFile()||opened.dev!==stat25.dev||opened.ino!==stat25.ino||opened.size!==stat25.size)throw Error("PHASE_SNAPSHOT_CONCURRENT_MUTATION");let bytes=fs203.readFileSync(descriptor),after=fs203.fstatSync(descriptor);if(after.size!==opened.size||after.mtimeMs!==opened.mtimeMs||after.ctimeMs!==opened.ctimeMs)throw Error("PHASE_SNAPSHOT_CONCURRENT_MUTATION");entries2.push({path:path338.relative(root,absolute).replaceAll("\\","/"),sha256:createHash109("sha256").update(bytes).digest("hex"),bytes:bytes.byteLength})}finally{fs203.closeSync(descriptor)}};for(let relative84 of INPUTS)visit(path338.join(root,...relative84.split("/")));return entries2.sort((left,right)=>compareUtf8(left.path,right.path)),createHash109("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,task2.files_touched??null))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=_internals279.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 target=participationPlan?.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=createHash110("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(fs205.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=createHash110("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=path340.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(fs205.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{fs205.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=fs205.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=fs205.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 fs206 from"node:fs";import*as path341 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 _internals282={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(fs206.existsSync(path341.join(cwd,"package.json")))ecosystems.push("npm");if(fs206.existsSync(path341.join(cwd,"pyproject.toml"))||fs206.existsSync(path341.join(cwd,"requirements.txt")))ecosystems.push("pip");if(fs206.existsSync(path341.join(cwd,"Cargo.toml")))ecosystems.push("cargo");if(fs206.existsSync(path341.join(cwd,"go.mod")))ecosystems.push("go");try{if(fs206.readdirSync(cwd).some((f)=>f.endsWith(".csproj")||f.endsWith(".sln")))ecosystems.push("dotnet")}catch{}if(fs206.existsSync(path341.join(cwd,"Gemfile"))||fs206.existsSync(path341.join(cwd,"Gemfile.lock")))ecosystems.push("ruby");if(fs206.existsSync(path341.join(cwd,"pubspec.yaml")))ecosystems.push("dart");if(fs206.existsSync(path341.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=[..._internals282.resolveAuditCommand("npm"),"audit","--json"];try{let proc=_internals282.bunSpawn(command,{stdout:"pipe",stderr:"pipe",cwd:directory,...command[0]==="cmd.exe"?{windowsVerbatimArguments:!0,killProcessTree:!0}:{}}),timeoutPromise=new Promise((resolve135)=>setTimeout(()=>resolve135("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((resolve135)=>setTimeout(()=>resolve135("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=[..._internals282.resolveAuditCommand("cargo"),"audit","--json"];try{let proc=_internals282.bunSpawn(command,{stdout:"pipe",stderr:"pipe",cwd:directory,...command[0]==="cmd.exe"?{windowsVerbatimArguments:!0,killProcessTree:!0}:{}}),timeoutPromise=new Promise((resolve135)=>setTimeout(()=>resolve135("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(`
|
|
7717
|
-
`).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((resolve135)=>setTimeout(()=>resolve135("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(`
|
|
7718
|
-
`).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((resolve135)=>setTimeout(()=>resolve135("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(`
|
|
7719
|
-
`);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((resolve135)=>setTimeout(()=>resolve135("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((resolve135)=>setTimeout(()=>resolve135("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((resolve135)=>setTimeout(()=>resolve135("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 fs207 from"node:fs";import*as path342 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=path342.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=path342.basename(filePath);if(new RegExp(`^${regexPattern}$`,"i").test(filename))return!0}catch{}return!1}function isParserSupported(filePath){let ext=path342.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(path342.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(`
|
|
7722
|
+
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}}init_gate_evidence();init_manager();async function runTodoGateGate(ctx){let{phase,dir,agentsDispatched,pluginConfig,safeWarn}=ctx,pass2=()=>({blocked:!1,agentsDispatched,agentsMissing:[],warnings:[]});if(pluginConfig.todo_gate?.enabled===!1)return pass2();let taskIds;try{let phaseRecord=(await loadPlan(dir))?.phases.find((p)=>p.id===phase);if(!phaseRecord)return safeWarn(`todo_gate: no plan phase ${phase} found; gate passed without evidence`,void 0),pass2();taskIds=phaseRecord.tasks.map((task2)=>task2.id)}catch(planError){return safeWarn("todo_gate: plan load failed; gate passed without evidence",planError),pass2()}let warnings=[];for(let taskId of taskIds){let evidence2=null;try{evidence2=await readTaskEvidence(dir,taskId)}catch(evidenceError){safeWarn(`todo_gate: task ${taskId} evidence unreadable; skipped`,evidenceError);continue}let verdict=evaluateTodoGate(evidence2?.todo_scan,pluginConfig.todo_gate);if(verdict.status!=="exceeded")continue;if(verdict.blocked)return{blocked:!0,reason:"TODO_GATE_THRESHOLD_EXCEEDED",message:`Phase ${phase} cannot be completed: task ${taskId} todo_gate threshold exceeded. ${verdict.message??""}`,agentsDispatched,agentsMissing:[],warnings:[`todo_gate: task ${taskId} has ${verdict.count} high-priority TODOs (max ${verdict.max})`],recovery:{kind:"tool",action:"todo_extract",args:{task_id:taskId}},recoveryGuidance:"Resolve or remove the high-priority TODO comments listed in the gate message, or adjust the todo_gate config (raise max_high_priority / set enabled: false), then re-run todo_extract with the same task_id to refresh the recorded evidence."};warnings.push(`todo_gate advisory: task ${taskId} — ${verdict.count} high-priority TODOs (FIXME/HACK/XXX) exceed max_high_priority=${verdict.max}. ${verdict.message??""}`)}return{blocked:!1,agentsDispatched,agentsMissing:[],warnings}}import{createHash as createHash108}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 createHash108("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 createHash109}from"node:crypto";import*as fs203 from"node:fs";import*as path338 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 relative84=path338.relative(root,candidate2);return relative84===""||relative84!==".."&&!relative84.startsWith(`..${path338.sep}`)&&!path338.isAbsolute(relative84)}function computePhaseEvidenceSnapshot(directory){let root=fs203.realpathSync(directory),entries2=[],totalBytes=0,visitedEntries=0,visit=(absolute)=>{if(!isContained3(root,absolute))throw Error("PHASE_SNAPSHOT_PATH_ESCAPE");let stat25;try{stat25=fs203.lstatSync(absolute)}catch(error93){if(error93.code==="ENOENT")return;throw error93}if(stat25.isSymbolicLink())throw Error(`PHASE_SNAPSHOT_UNSAFE_PATH: ${path338.relative(root,absolute)}`);if(stat25.isDirectory()){let names=[],handle=fs203.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(path338.join(absolute,name));return}if(!stat25.isFile())throw Error(`PHASE_SNAPSHOT_NON_REGULAR: ${path338.relative(root,absolute)}`);if(entries2.length>=MAX_SNAPSHOT_FILES)throw Error("PHASE_SNAPSHOT_FILE_LIMIT");if(totalBytes+=stat25.size,totalBytes>MAX_SNAPSHOT_BYTES)throw Error("PHASE_SNAPSHOT_BYTE_LIMIT");let descriptor=fs203.openSync(absolute,fs203.constants.O_RDONLY|(fs203.constants.O_NOFOLLOW??0));try{let opened=fs203.fstatSync(descriptor);if(!opened.isFile()||opened.dev!==stat25.dev||opened.ino!==stat25.ino||opened.size!==stat25.size)throw Error("PHASE_SNAPSHOT_CONCURRENT_MUTATION");let bytes=fs203.readFileSync(descriptor),after=fs203.fstatSync(descriptor);if(after.size!==opened.size||after.mtimeMs!==opened.mtimeMs||after.ctimeMs!==opened.ctimeMs)throw Error("PHASE_SNAPSHOT_CONCURRENT_MUTATION");entries2.push({path:path338.relative(root,absolute).replaceAll("\\","/"),sha256:createHash109("sha256").update(bytes).digest("hex"),bytes:bytes.byteLength})}finally{fs203.closeSync(descriptor)}};for(let relative84 of INPUTS)visit(path338.join(root,...relative84.split("/")));return entries2.sort((left,right)=>compareUtf8(left.path,right.path)),createHash109("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,runTodoGateGate};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,task2.files_touched??null))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","todo_gate","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)},{id:"todo_gate",actor:"coder",run:()=>phaseCompletePreflightInternals.runTodoGateGate(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=_internals279.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 target=participationPlan?.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=createHash110("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(fs205.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=createHash110("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=path340.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(fs205.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{fs205.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=fs205.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=fs205.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 fs206 from"node:fs";import*as path341 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 _internals282={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(fs206.existsSync(path341.join(cwd,"package.json")))ecosystems.push("npm");if(fs206.existsSync(path341.join(cwd,"pyproject.toml"))||fs206.existsSync(path341.join(cwd,"requirements.txt")))ecosystems.push("pip");if(fs206.existsSync(path341.join(cwd,"Cargo.toml")))ecosystems.push("cargo");if(fs206.existsSync(path341.join(cwd,"go.mod")))ecosystems.push("go");try{if(fs206.readdirSync(cwd).some((f)=>f.endsWith(".csproj")||f.endsWith(".sln")))ecosystems.push("dotnet")}catch{}if(fs206.existsSync(path341.join(cwd,"Gemfile"))||fs206.existsSync(path341.join(cwd,"Gemfile.lock")))ecosystems.push("ruby");if(fs206.existsSync(path341.join(cwd,"pubspec.yaml")))ecosystems.push("dart");if(fs206.existsSync(path341.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=[..._internals282.resolveAuditCommand("npm"),"audit","--json"];try{let proc=_internals282.bunSpawn(command,{stdin:"ignore",stdout:"pipe",stderr:"pipe",cwd:directory,...command[0]==="cmd.exe"?{windowsVerbatimArguments:!0,killProcessTree:!0}:{}}),timeoutPromise=new Promise((resolve135)=>setTimeout(()=>resolve135("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,{stdin:"ignore",stdout:"pipe",stderr:"pipe",cwd:directory}),timeoutPromise=new Promise((resolve135)=>setTimeout(()=>resolve135("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=[..._internals282.resolveAuditCommand("cargo"),"audit","--json"];try{let proc=_internals282.bunSpawn(command,{stdin:"ignore",stdout:"pipe",stderr:"pipe",cwd:directory,...command[0]==="cmd.exe"?{windowsVerbatimArguments:!0,killProcessTree:!0}:{}}),timeoutPromise=new Promise((resolve135)=>setTimeout(()=>resolve135("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(`
|
|
7723
|
+
`).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,{stdin:"ignore",stdout:"pipe",stderr:"pipe",cwd:directory}),timeoutPromise=new Promise((resolve135)=>setTimeout(()=>resolve135("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(`
|
|
7724
|
+
`).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,{stdin:"ignore",stdout:"pipe",stderr:"pipe",cwd:directory}),timeoutPromise=new Promise((resolve135)=>setTimeout(()=>resolve135("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(`
|
|
7725
|
+
`);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,{stdin:"ignore",stdout:"pipe",stderr:"pipe",cwd:directory}),timeoutPromise=new Promise((resolve135)=>setTimeout(()=>resolve135("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,{stdin:"ignore",stdout:"pipe",stderr:"pipe",cwd:directory}),timeoutPromise=new Promise((resolve135)=>setTimeout(()=>resolve135("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,{stdin:"ignore",stdout:"pipe",stderr:"pipe",cwd:directory}),timeoutPromise=new Promise((resolve135)=>setTimeout(()=>resolve135("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 fs207 from"node:fs";import*as path342 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=path342.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=path342.basename(filePath);if(new RegExp(`^${regexPattern}$`,"i").test(filename))return!0}catch{}return!1}function isParserSupported(filePath){let ext=path342.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(path342.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(`
|
|
7720
7726
|
`);for(let i=0;i<lines.length;i++){let line=lines[i],lineNumber=i+1;if(addedLines&&!addedLines.has(lineNumber))continue;for(let{pattern,rule_id}of PLAN_PLACEHOLDER_PATTERNS){if(pattern.test(line))findings.push({path:filePath,line:lineNumber,kind:"other",excerpt:line.substring(0,100),rule_id});pattern.lastIndex=0}}return findings}function normalizeAddedLines(value){if(value instanceof Set)return value;if(Array.isArray(value))return new Set(value);return}function isValidationPattern(lines,currentLineIdx){let currentLine=lines[currentLineIdx];if(!/return\s+undefined\s*;/.test(currentLine))return!1;let MAX_SEARCH_LINES=50,jsdocContent="",_foundFunction=!1,functionKeywords=/^(?:export\s+)?(?:async\s+)?function\s+\w+|^(?:export\s+)?(?:async\s+)?(?:\w+\s+)?\w+\s*\([^)]*\)\s*(?::\s*\w+\s*)?(?:\{|$)/;for(let i=currentLineIdx-1;i>=0&&i>=currentLineIdx-MAX_SEARCH_LINES;i--){let line=lines[i].trim();if(line.startsWith("*")||line.startsWith("*/"))jsdocContent=`${line.replace(/^\*?\s?/,"").replace(/^\*\//,"")}
|
|
7721
7727
|
${jsdocContent}`;else if(line.includes("*/"))break;else if(functionKeywords.test(line)||line.startsWith("function ")){_foundFunction=!0;break}else if(line.length>0&&!line.startsWith("//")&&!line.startsWith("*"))break}if(jsdocContent){if(/@returns\s*(?:\{[^}]*\})?\s*(?:undefined|[A-Za-z_]\w*)/i.test(jsdocContent))return!0}let braceCount=0,inFunction=!1;for(let i=currentLineIdx;i>=0;i--){let line=lines[i];for(let char of line)if(char==="{")braceCount++,inFunction=!0;else if(char==="}")braceCount--;if(inFunction&&braceCount===0&&i<currentLineIdx)break}let errorReturnPattern=/return\s+["'`][[:ascii:]]*["'`]\s*;/;for(let i=currentLineIdx-1;i>=0&&i>=currentLineIdx-MAX_SEARCH_LINES;i--){let line=lines[i].trim();if(functionKeywords.test(line)||line.startsWith("function "))break;if(errorReturnPattern.test(line))return!0}return!1}function scanWithRegex(content,filePath,denyPatterns,addedLines){let findings=[],lines=content.split(`
|
|
7722
7728
|
`),filterByAddedLines=addedLines!==void 0;for(let i=0;i<lines.length;i++){let line=lines[i],lineNumber=i+1;if(filterByAddedLines&&!addedLines.has(lineNumber))continue;let lineCommentMatch=line.match(/(?:\/\/|#|<!--)\s*(.*)$/);if(lineCommentMatch){let commentText=lineCommentMatch[1];for(let{pattern,rule_id}of denyPatterns.comment)if(pattern.test(commentText)){findings.push({path:filePath,line:lineNumber,kind:"comment",excerpt:line.substring(0,100),rule_id});break}}let blockCommentMatch=line.match(/\/\*([\s\S]*?)\*\//);if(blockCommentMatch){let commentText=blockCommentMatch[1];for(let{pattern,rule_id}of denyPatterns.comment)if(pattern.test(commentText)){findings.push({path:filePath,line:lineNumber,kind:"comment",excerpt:line.substring(0,100),rule_id});break}}let stringMatches=line.match(/(["'`])(?:(?!\1)[^\\]|\\.)*\1/g);if(stringMatches){for(let stringContent of stringMatches)for(let{pattern,rule_id}of denyPatterns.string)if(pattern.test(stringContent)){findings.push({path:filePath,line:lineNumber,kind:"string",excerpt:line.substring(0,100),rule_id});break}}for(let{pattern,rule_id}of denyPatterns.code)if(!(line.includes("describe(")||line.includes("it(")||line.includes("test(")||line.includes("expect("))&&pattern.test(line)){if(rule_id==="placeholder/code-stub-return"&&/return\s+undefined\s*;/.test(line)){if(isValidationPattern(lines,i))continue}findings.push({path:filePath,line:lineNumber,kind:"function_body",excerpt:line.substring(0,100),rule_id})}}return findings}async function scanWithParser(content,filePath,denyPatterns,addedLines){let findings=[],regexFindings=scanWithRegex(content,filePath,denyPatterns,addedLines);findings.push(...regexFindings);let parser=await getParserForFile(filePath);if(!parser)return findings;try{let walkNode=function(node){let{type:nodeType,text:nodeText}=node,lineNum=node.startPosition.row+1;if(filterByAddedLines?addedLines.has(lineNum):!0){if(nodeType==="comment"||nodeType==="line_comment"||nodeType==="block_comment"||nodeType==="documentation_comment"||nodeType==="doc_comment")for(let{pattern,rule_id}of denyPatterns.comment){let key2=`${lineNum}:${rule_id}`;if(!seenKeys.has(key2)&&pattern.test(nodeText))seenKeys.add(key2),findings.push({path:filePath,line:lineNum,kind:"comment",excerpt:nodeText.substring(0,100),rule_id})}if(nodeType==="string"||nodeType==="template_string"||nodeType==="string_literal"||nodeType==="string_fragment")for(let{pattern,rule_id}of denyPatterns.string){let key2=`${lineNum}:${rule_id}`;if(!seenKeys.has(key2)&&pattern.test(nodeText))seenKeys.add(key2),findings.push({path:filePath,line:lineNum,kind:"string",excerpt:nodeText.substring(0,100),rule_id})}}if(node.children)for(let child of node.children)walkNode(child)},tree=parser.parse(content);if(!tree||!tree.rootNode)return findings;let seenKeys=new Set;for(let f of findings)seenKeys.add(`${f.line}:${f.rule_id}`);let filterByAddedLines=addedLines!==void 0;if(walkNode(tree.rootNode),isBodyShapeSupported(filePath))try{let nonStubBodyLines=collectNonStubBodyLines(tree.rootNode);if(nonStubBodyLines.size>0)for(let i=findings.length-1;i>=0;i--){let f=findings[i];if(f.rule_id==="placeholder/code-stub-return"&&nonStubBodyLines.has(f.line))findings.splice(i,1)}}catch{}tree.delete()}catch{}return findings}function isConstantLiteralNode(node){if(!node)return!1;let t=node.type;if(t==="null"||t==="true"||t==="false"||t==="number"||t==="string"||t==="array"||t==="object"||t==="identifier"||t==="none"||t==="integer"||t==="float"||t==="list"||t==="dictionary"||t==="tuple")return!0;if(t==="unary_expression"&&Array.isArray(node.children)&&node.children.length>=2&&node.children[0]?.type==="-"&&node.children[1]?.type==="number")return!0;if(t==="template_string")return!(Array.isArray(node.children)&&node.children.some((child)=>child&&child.type==="template_substitution"));return!1}function isStubSkeletonFunction(fnNode){if(!fnNode||typeof fnNode.type!=="string")return!1;let commentTypes=new Set(["comment","line_comment","block_comment","documentation_comment","doc_comment"]),skipPunctuation=new Set(["{","}",":",";",","]),bodyNode=null,isArrow=fnNode.type==="arrow_function";if(isArrow)bodyNode=fnNode.childForFieldName("body");else if(Array.isArray(fnNode.children)){for(let child of fnNode.children)if(child&&(child.type==="statement_block"||child.type==="block"||child.type==="suite")){bodyNode=child;break}}if(!bodyNode)return!1;if(isArrow&&bodyNode.type!=="statement_block")return isConstantLiteralNode(bodyNode);let effectiveStatements=[];if(Array.isArray(bodyNode.children))for(let child of bodyNode.children){if(!child||typeof child.type!=="string")continue;if(commentTypes.has(child.type))continue;if(skipPunctuation.has(child.type))continue;effectiveStatements.push(child)}if(effectiveStatements.length!==1)return!1;let stmt=effectiveStatements[0];if(!stmt)return!1;if(stmt.type==="return_statement"){let exprChild=Array.isArray(stmt.children)?stmt.children.find((c)=>c&&typeof c.type==="string"&&c.type!=="return"&&c.type!==";"&&!commentTypes.has(c.type)):null;if(!exprChild)return!1;return isConstantLiteralNode(exprChild)}return isConstantLiteralNode(stmt)}function collectNonStubBodyLines(rootNode){let result=new Set,stubSkeletonRanges=[],functionNodeTypes=new Set(["function_declaration","generator_function_declaration","method_definition","arrow_function","function_definition","function_expression","generator_function"]);function findBodyNode(fnNode){if(fnNode.type==="arrow_function")return fnNode.childForFieldName("body");if(Array.isArray(fnNode.children)){for(let child of fnNode.children)if(child&&(child.type==="statement_block"||child.type==="block"||child.type==="suite"))return child}return null}function walk(node){if(!node||typeof node.type!=="string")return;if(functionNodeTypes.has(node.type)){let bodyNode=findBodyNode(node),isStub=isStubSkeletonFunction(node);if(isStub&&bodyNode){let startLine=bodyNode.startPosition.row+1,endLine=bodyNode.endPosition.row+1;stubSkeletonRanges.push([startLine,endLine])}else if(!isStub&&bodyNode){let startLine=bodyNode.startPosition.row+1,endLine=bodyNode.endPosition.row+1;for(let line=startLine;line<=endLine;line++)result.add(line)}}if(Array.isArray(node.children))for(let child of node.children)walk(child)}walk(rootNode);for(let[start,end]of stubSkeletonRanges)for(let line=start;line<=end;line++)result.delete(line);return result}async function placeholderScan(input,directory,gateOverrides){return computePlaceholderScan(input,directory,gateOverrides,{persistEvidence:!0})}async function computePlaceholderScan(input,directory,gateOverrides,options){if(gateOverrides?.enabled===!1)return{verdict:"pass",findings:[],summary:{files_scanned:0,findings_count:0,files_with_findings:0,disabled_reason:"placeholder_scan disabled by configuration"}};let{changed_files,allow_globs:allowGlobsInput,deny_patterns:denyPatternsInput,added_lines,sentinel_allowlist:sentinelAllowlistInput,allow_sentinels:allowSentinelsInput}=input,allow_globs=allowGlobsInput??gateOverrides?.allow_globs,deny_patterns=denyPatternsInput??gateOverrides?.deny_patterns,sentinel_allowlist=sentinelAllowlistInput??allowSentinelsInput??gateOverrides?.sentinel_allowlist,max_allowed_findings=gateOverrides?.max_allowed_findings??0,sentinelPatterns=[...DEFAULT_SENTINEL_ALLOWLIST,...sentinel_allowlist??[]].map((sentinel)=>new RegExp(escapeRegex2(sentinel),"i"));function isSentinelAllowed(excerpt){for(let pattern of sentinelPatterns)if(pattern.test(excerpt))return!0;return!1}let commentPatterns=DEFAULT_COMMENT_PATTERNS,stringPatterns=DEFAULT_STRING_PATTERNS,codePatterns=DEFAULT_CODE_PATTERNS;if(deny_patterns&&deny_patterns.length>0)commentPatterns=deny_patterns.map((p)=>({pattern:new RegExp(`\\b${escapeRegex2(p)}\\b`,"i"),rule_id:`placeholder/custom-${p.toLowerCase()}`})),stringPatterns=[],codePatterns=[];let denyPatterns={comment:commentPatterns,string:stringPatterns,code:codePatterns},findings=[],filesScanned=0,filesWithFindings=new Set;for(let filePath of changed_files){let fullPath=path342.resolve(directory,filePath);if(!isCanonicalPathWithinRoot(fullPath,directory))continue;if(!fs207.existsSync(fullPath))continue;if(isAllowedByGlobs(filePath,allow_globs))continue;let relativeFilePath=path342.relative(directory,fullPath).replace(/\\/g,"/");if(FILE_ALLOWLIST.some((allowed)=>relativeFilePath.endsWith(allowed)))continue;let content;try{if(fs207.statSync(fullPath).size>MAX_FILE_SIZE)continue;content=fs207.readFileSync(fullPath,"utf-8")}catch{continue}if(content.includes("\x00"))continue;let isScaffold=isScaffoldFile(filePath);if(isTestFile2(filePath)&&!isScaffold)continue;filesScanned++;let addedLinesForFile=normalizeAddedLines(added_lines?.[relativeFilePath]??added_lines?.[filePath]),fileFindings;if(isPlanFile(filePath))fileFindings=scanPlanFileForPlaceholders(content,filePath,addedLinesForFile);else if(isParserSupported(filePath))fileFindings=await scanWithParser(content,filePath,denyPatterns,addedLinesForFile);else fileFindings=scanWithRegex(content,filePath,denyPatterns,addedLinesForFile);let filteredFindings=sentinelPatterns.length>0?fileFindings.filter((f)=>!isSentinelAllowed(f.excerpt)):fileFindings;if(filteredFindings.length>0)findings.push(...filteredFindings),filesWithFindings.add(filePath)}let verdict=findings.length>max_allowed_findings?"fail":"pass",addedLinesValues=Object.values(added_lines??{}),diffScoped=addedLinesValues.length>0,addedLinesFiles=addedLinesValues.filter((lines)=>(lines instanceof Set?lines.size:lines.length)>0).length,addedLinesTotal=addedLinesValues.reduce((sum,lines)=>sum+(lines instanceof Set?lines.size:lines.length),0);if(options?.persistEvidence===!0)await _internals283.saveEvidence(directory,"placeholder_scan",{task_id:"placeholder_scan",type:"placeholder",timestamp:new Date().toISOString(),agent:"placeholder_scan",verdict,summary:`Scanned ${filesScanned} files, found ${findings.length} placeholder(s)`,files_scanned:filesScanned,findings_count:findings.length,files_with_findings:filesWithFindings.size,findings,...diffScoped&&{diff_scoped:!0,added_lines_files:addedLinesFiles,added_lines_total:addedLinesTotal}});return{verdict,findings,summary:{files_scanned:filesScanned,findings_count:findings.length,files_with_findings:filesWithFindings.size}}}var placeholder_scan=createSwarmTool({allowWorkingDirectoryOverride:!0,description:"Scan source files for placeholder content (TODO/FIXME comments, stub implementations, unimplemented functions). Returns JSON with findings grouped by file and rule.",args:{changed_files:exports_external.array(exports_external.string()).describe("Files to scan for placeholders"),allow_globs:exports_external.array(exports_external.string()).optional().describe("Globs to allow (skip scanning)"),deny_patterns:exports_external.array(exports_external.string()).optional().describe("Custom deny patterns to search for"),added_lines:exports_external.record(exports_external.string(),exports_external.array(exports_external.number().int().positive())).optional().describe("Optional map of file path to PR-added line numbers"),sentinel_allowlist:exports_external.array(exports_external.string()).optional().describe("Intentional sentinel strings that suppress matching findings"),allow_sentinels:exports_external.array(exports_external.string()).optional().describe("Deprecated alias for sentinel_allowlist")},async execute(args2,directory){let result=await placeholderScan(args2,directory,_internals283.loadGateOverrides(directory)?.placeholder_scan);return JSON.stringify(result)}}),_internals283={collectNonStubBodyLines,isStubSkeletonFunction,isConstantLiteralNode,saveEvidence,loadGateOverrides};init_zod();init_manager();init_parallel_verdict();init_cochange_source();init_create_tool();var plan_conflict_check_args={task_ids:exports_external.array(exports_external.string().min(1)).min(2,"plan_conflict_check requires at least 2 task ids to compare").max(MAX_PARALLEL_VERDICT_TASKS,`plan_conflict_check accepts at most ${MAX_PARALLEL_VERDICT_TASKS} task ids`).describe('The N proposed parallel task group ids (e.g. ["4.1","4.2","4.3"]). '+"Minimum 2 — fewer than 2 tasks cannot conflict."),use_cochange:exports_external.boolean().optional().describe("When true, fold git co-change signal (from `git log`) into the verdict. "+'Off by default — the path-only verdict is sufficient for the v8 "provably '+'disjoint" gate. Opt in for richer signal on tightly-coupled codebases.'),phase_id:exports_external.string().optional().describe("Optional: scope the check to a phase. Currently informational — task_ids "+"are checked as-is regardless of phase. Reserved for future validation.")};async function executePlanConflictCheck(args2,directory){let useCochange=args2.use_cochange===!0,planLoaded=!1,loadedPlan=null,knownTaskIds=new Set;try{if(loadedPlan=await loadPlanJsonOnly(directory),loadedPlan){planLoaded=!0;for(let phase of loadedPlan.phases)for(let task2 of phase.tasks)knownTaskIds.add(task2.id)}}catch{planLoaded=!1}let requestedIds=args2.task_ids,unknownToPlan=planLoaded?requestedIds.filter((id)=>!knownTaskIds.has(id)):[],cochangePairs;if(useCochange)try{cochangePairs=await getCoChangePairs(directory)}catch{cochangePairs=void 0}let verdict=computeParallelVerdict(directory,requestedIds,{useCochange,cochangePairs,plan:loadedPlan??void 0});return{verdict:verdict.verdict,pairs:verdict.pairs,suggested_serial_order:verdict.suggestedSerialOrder,unknown_scope_tasks:verdict.unknownScopeTasks,used_cochange:useCochange&&cochangePairs!==void 0&&cochangePairs.length>0,plan_loaded:planLoaded,...unknownToPlan.length>0?{unknown_to_plan:unknownToPlan}:{}}}var plan_conflict_check=createSwarmTool({allowWorkingDirectoryOverride:!0,description:"Read-only advisory check (#1656): compute a pairwise file-conflict matrix for N proposed parallel task groups using the currently declared v2 scope bindings (the same authority declare_scope writes, #2532) and optional git co-change signal. 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. Use this BEFORE attempting parallel dispatch to confirm disjointness.",args:plan_conflict_check_args,execute:async(args2,directory)=>{let result=await executePlanConflictCheck(args2,directory);return JSON.stringify(result,null,2)}});init_pending_delegations();init_workspace_snapshot();init_pr_workflow_state();init_pr_workflow_auto_wake();init_pr_workflow_gate();import*as fsp12 from"node:fs/promises";import*as path343 from"node:path";init_utils2();init_bun_compat();init_git_executable();init_create_tool();var GIT_TIMEOUT_MS11=5000,GIT_MAX_STDOUT_BYTES=524288,MAX_DIRTY_FILES=50,MAX_REMOTES=20,MAX_REMOTE_URL_LEN=200,MAX_FIELD_LEN=240,MAX_RECOVERY_REASON_CODE_LEN=120,RECEIPT_DIR2="pr-workflow-checkouts",utf8Encoder=new TextEncoder,utf8Decoder=new TextDecoder("utf-8",{fatal:!1});function truncateToByteBudget(value,maxBytes){let encoded=utf8Encoder.encode(value);if(encoded.length<=maxBytes)return value;return utf8Decoder.decode(encoded.subarray(0,maxBytes))}function boundUntrusted(value,maxLen){let cleaned=value.replace(/[\p{Cc}]/gu," ").replace(/[`<>]/g," ").replace(/\s+/g," ").trim();return cleaned.length>maxLen?`${cleaned.slice(0,maxLen)}…`:cleaned}async function runGitCapture2(directory,args2){let gitExecutable;try{gitExecutable=await resolveGitExecutableAsync()}catch{return null}let proc=bunSpawn([gitExecutable,...args2],{cwd:directory,stdin:"ignore",stdout:"pipe",stderr:"ignore",timeout:GIT_TIMEOUT_MS11});try{let[exitCode,stdout]=await Promise.all([proc.exited,proc.stdout.text()]);if(exitCode!==0)return null;return truncateToByteBudget(stdout,GIT_MAX_STDOUT_BYTES)}catch{return null}finally{try{proc.kill()}catch{}}}async function resolveBranch(directory){let raw=await _internals284.runGitCapture(directory,["rev-parse","--abbrev-ref","HEAD"]);if(raw===null)return{branch:null,detached:null};let value=raw.trim();if(!value||value==="HEAD")return{branch:null,detached:!0};return{branch:boundUntrusted(value,MAX_FIELD_LEN),detached:!1}}function parseDirtyFiles(porcelain){if(!porcelain)return{dirtyFiles:[],dirtyFileCount:0,dirtyFilesTruncated:!1};let lines=porcelain.split(`
|
|
@@ -7786,8 +7792,8 @@ ${content}
|
|
|
7786
7792
|
`),diff2+=`
|
|
7787
7793
|
`,diff2}function validateOldContent(lines,contextMatch,oldContent){if(!oldContent)return{valid:!0};let expectedLines=splitDiffLines(oldContent),removalStartIdx=contextMatch.startLineIndex+contextMatch.matchedBefore.length,actualLines=lines.slice(removalStartIdx,removalStartIdx+expectedLines.length);if(!arraysEqual2(actualLines,expectedLines))return{valid:!1,expected:expectedLines.join(`
|
|
7788
7794
|
`),actual:actualLines.join(`
|
|
7789
|
-
`)};return{valid:!0}}var suggestPatch=createSwarmTool({description:'Suggest a structured patch for specified files without modifying them. Returns context-based patch proposals with anchors for reviewer use. When format="unified", also produces a unified diff string consumable by apply_patch. '+"This is a read-only tool — it does not modify any files.",args:{targetFiles:exports_external.array(exports_external.string()).describe("Array of file paths to patch").min(1),changes:exports_external.array(exports_external.object({file:exports_external.string().describe("Path to the file this change applies to"),contextBefore:exports_external.array(exports_external.string()).optional().describe("Lines before the change region (anchor)"),contextAfter:exports_external.array(exports_external.string()).optional().describe("Lines after the change region (anchor)"),oldContent:exports_external.string().optional().describe("Current content to be replaced"),newContent:exports_external.string().describe("New content to replace with")})).describe("Array of change descriptions with context anchors").min(1),format:exports_external.enum(["json","unified"]).optional().default("json").describe('Output format: "json" (default, existing structured output) or "unified" (unified diff string for apply_patch)')},execute:async(args2,directory)=>{if(!args2||typeof args2!=="object")return JSON.stringify({success:!1,error:!0,type:"parse-error",message:"Could not parse suggest-patch arguments"},null,2);let obj=args2,targetFiles=obj.targetFiles??[],changes=obj.changes??[],format=obj.format??"json";if(!targetFiles||targetFiles.length===0)return JSON.stringify({success:!1,error:!0,type:"parse-error",message:"targetFiles cannot be empty"},null,2);if(!changes||changes.length===0)return JSON.stringify({success:!1,error:!0,type:"parse-error",message:"changes cannot be empty"},null,2);if(!fs217.existsSync(directory))return JSON.stringify({success:!1,error:!0,type:"file-not-found",message:"Workspace directory does not exist"},null,2);let patches=[],filesModifiedSet=new Set,errors5=[],unifiedDiffEntries=[],targetFileSet=new Set(targetFiles),skippedBinaryFiles=new Set;if(format==="unified"){for(let change of changes)if(isBinaryFile4(change.file))errors5.push({success:!1,error:!0,type:"parse-error",message:`Binary files are not supported in unified diff mode: ${change.file}`,details:{location:change.file}}),skippedBinaryFiles.add(change.file)}for(let changeIndex=0;changeIndex<changes.length;changeIndex++){let change=changes[changeIndex];if(format==="unified"&&skippedBinaryFiles.has(change.file))continue;if(!targetFileSet.has(change.file)){errors5.push({success:!1,error:!0,type:"parse-error",message:`File "${change.file}" is not in targetFiles`,details:{location:change.file}});continue}if(!validateFilePath2(change.file,directory)){errors5.push({success:!1,error:!0,type:"parse-error",message:`Invalid file path: ${change.file}`,details:{location:change.file}});continue}let fullPath=path357.resolve(directory,change.file);if(!fs217.existsSync(fullPath)){errors5.push({success:!1,error:!0,type:"file-not-found",message:`File not found: ${change.file}`,details:{location:change.file}});continue}let content;try{content=fs217.readFileSync(fullPath,"utf-8")}catch(err2){errors5.push({success:!1,error:!0,type:"unknown",message:`Could not read file: ${err2 instanceof Error?err2.message:String(err2)}`,details:{location:`${change.file}:0`}});continue}let contextMatch=findContextMatch(content,change.contextBefore,change.contextAfter,change.oldContent);if(!contextMatch){errors5.push({success:!1,error:!0,type:"context-mismatch",message:`Could not find context anchor in ${change.file}. Provide contextBefore/contextAfter lines to locate the change region.`,details:{location:change.file}});continue}let lines=splitDiffLines(content),oldContentValidation=validateOldContent(lines,contextMatch,change.oldContent);if(!oldContentValidation.valid){errors5.push({success:!1,error:!0,type:"context-mismatch",message:"Content at the specified location does not match oldContent",details:{expected:oldContentValidation.expected,actual:oldContentValidation.actual,location:`${change.file}:${contextMatch.startLineIndex+1}-${contextMatch.endLineIndex+1}`}});continue}let originalContext=[...contextMatch.matchedBefore,...contextMatch.matchedAfter.length>0?["..."]:[],...contextMatch.matchedAfter];if(patches.push({file:change.file,originalContext,newContent:change.newContent,hunkIndex:changeIndex}),filesModifiedSet.add(change.file),format==="unified")unifiedDiffEntries.push({file:change.file,contextMatch,oldContent:change.oldContent,newContent:change.newContent})}if(patches.length>0){let baseResult={success:!0,patches,filesModified:Array.from(filesModifiedSet),...errors5.length>0&&{errors:errors5}};if(format==="unified"){let fileGroups=new Map;for(let entry of unifiedDiffEntries){let group=fileGroups.get(entry.file)??[];group.push(entry),fileGroups.set(entry.file,group)}let unifiedParts=[];for(let[file3,entries2]of fileGroups){entries2.sort((a,b)=>a.contextMatch.startLineIndex-b.contextMatch.startLineIndex);let entryFullPath=path357.resolve(directory,file3),entryContent;try{entryContent=fs217.readFileSync(entryFullPath,"utf-8")}catch{continue}unifiedParts.push(generateFileHeader(file3));for(let entry of entries2)unifiedParts.push(generateHunk(entryContent,entry.contextMatch,entry.oldContent,entry.newContent))}let unifiedPatch=unifiedParts.join("");return JSON.stringify({...baseResult,unifiedPatch},null,2)}return JSON.stringify(baseResult,null,2)}if(errors5.length===1)return JSON.stringify(errors5[0],null,2);return JSON.stringify({success:!1,error:!0,type:"context-mismatch",message:`All ${errors5.length} patch suggestions failed`,errors:errors5},null,2)}});init_zod();init_loader();init_schema3();init_store5();init_create_tool();init_resolve_working_directory();function getContextAgent2(ctx){if(!ctx||typeof ctx!=="object")return;let value=ctx.agent;return typeof value==="string"?value:void 0}var ArgsSchema5=exports_external.object({phase:exports_external.number().int().min(0).max(999),summary:exports_external.string().min(1),task_id:exports_external.string().min(1).optional(),parent_agent:exports_external.string().min(1).optional(),key_decisions:exports_external.array(exports_external.string().min(1)).optional(),constraints_observed:exports_external.array(exports_external.string().min(1)).optional(),constraints_violated:exports_external.array(exports_external.string().min(1)).optional(),assumptions:exports_external.array(exports_external.string().min(1)).optional(),risks:exports_external.array(exports_external.string().min(1)).optional(),files_touched:exports_external.array(exports_external.string().min(1)).optional(),evidence_refs:exports_external.array(exports_external.string().min(1)).optional(),working_directory:exports_external.string().optional()}),summarize_work=createSwarmTool({description:`Emit a short structured summary of the work you just completed (key decisions, assumptions, risks, constraints observed/violated). Call this once at task completion. Keep the summary under ${MAX_AGENT_SUMMARY_WORDS} words and each list to ${MAX_LIST_ITEMS} items — longer content is truncated, not rejected. These `+"summaries roll up per phase and are reviewed by the architecture supervisor to catch cross-task contradictions, drift, and repeated failure loops. Advisory only.",args:{phase:exports_external.number().int().min(0).max(999).describe("Phase number this work belongs to."),summary:exports_external.string().min(1).describe(`One-paragraph summary of what you did (<= ${MAX_AGENT_SUMMARY_WORDS} words).`),task_id:exports_external.string().min(1).optional().describe('Task ID this summary covers (e.g. "1.2").'),parent_agent:exports_external.string().min(1).optional().describe("The agent that delegated this task, if any."),key_decisions:exports_external.array(exports_external.string().min(1)).optional(),constraints_observed:exports_external.array(exports_external.string().min(1)).optional(),constraints_violated:exports_external.array(exports_external.string().min(1)).optional(),assumptions:exports_external.array(exports_external.string().min(1)).optional(),risks:exports_external.array(exports_external.string().min(1)).optional(),files_touched:exports_external.array(exports_external.string().min(1)).optional(),evidence_refs:exports_external.array(exports_external.string().min(1)).optional(),working_directory:exports_external.string().optional()},execute:async(rawArgs,directory,ctx)=>{let parsed=ArgsSchema5.safeParse(rawArgs);if(!parsed.success)return JSON.stringify({success:!1,reason:"invalid arguments",errors:parsed.error.issues.map((i)=>({path:i.path.join("."),message:i.message}))},null,2);let args2=parsed.data,dirResult=resolveWorkingDirectory(args2.working_directory,directory);if(!dirResult.success)return JSON.stringify({success:!1,reason:dirResult.message},null,2);let workingDir=dirResult.directory,sessionId=ctx?.sessionID??"unknown-session",agent=getContextAgent2(ctx)??"unknown-agent",maxWords=MAX_AGENT_SUMMARY_WORDS;try{maxWords=loadPluginConfig(workingDir).architectural_supervision?.max_agent_summary_words??maxWords}catch{}let summary=normalizeAgentWorkSummary({phase:args2.phase,task_id:args2.task_id,session_id:sessionId,agent,parent_agent:args2.parent_agent,summary:args2.summary,key_decisions:args2.key_decisions,constraints_observed:args2.constraints_observed,constraints_violated:args2.constraints_violated,assumptions:args2.assumptions,risks:args2.risks,files_touched:args2.files_touched,evidence_refs:args2.evidence_refs},maxWords),storedTaskId=await writeAgentSummary(workingDir,summary);return JSON.stringify({success:!0,stored_task_id:storedTaskId,phase:summary.phase,agent:summary.agent,truncated:summary.truncated??!1},null,2)}});init_zod();init_command_dispatch();init_tool_policy();init_create_tool();function createSwarmCommandTool(agents,evaluationModelDispatcher,reviewModelDispatcher,autoReviewConfig,reviewAgentModelRegistry,getActiveAgentName){return createSwarmTool({description:"Run supported /swarm commands through the canonical opencode-swarm command registry. Return the tool output verbatim to the user.",args:{command:exports_external.enum(SWARM_COMMAND_TOOL_COMMANDS).describe("The /swarm subcommand to run, without the /swarm prefix."),args:exports_external.array(exports_external.string()).default([]).describe("Additional command arguments as separate tokens.")},async execute(rawArgs,directory,ctx){let args2=rawArgs;return(await executeSwarmCommand({directory,agents,sessionID:ctx?.sessionID??"",tokens:[args2.command,...args2.args??[]],policy:classifySwarmCommandToolUse,evaluationModelDispatcher,reviewModelDispatcher,autoReviewConfig,reviewAgentModelRegistry,activeAgentName:getActiveAgentName?.(ctx?.sessionID??"")})).text}})}var swarm_command=createSwarmCommandTool({});init_zod();init_config();init_memory();init_state2();init_create_tool();import{createHash as createHash112}from"node:crypto";var OutcomeArgsSchema=exports_external.object({memory_id:exports_external.string().regex(/^mem_[a-f0-9]{16}$/).optional(),question:exports_external.string().trim().min(1).max(2000).optional(),outcome:exports_external.enum(["useful","dead_end","corrected"]),anchors:exports_external.array(MemoryAnchorSchema).max(20).optional(),correction:exports_external.string().trim().min(1).max(4000).optional()}).strict().superRefine((value,context)=>{if(Boolean(value.memory_id)===Boolean(value.question))context.addIssue({code:"custom",message:"exactly one of memory_id or question is required"});if(value.outcome==="corrected"&&!value.correction)context.addIssue({code:"custom",message:"corrected outcomes require correction text"})}),swarm_memory_outcome=createSwarmTool({description:"Record whether recalled memory or a graph answer was useful, a dead end, or corrected; when reflection is enabled, synchronously refresh deterministic reflection artifacts.",args:{memory_id:exports_external.string().regex(/^mem_[a-f0-9]{16}$/).optional().describe("Existing memory id to update"),question:exports_external.string().trim().min(1).max(2000).optional().describe("Question for a lightweight result memory when no id is known"),outcome:exports_external.enum(["useful","dead_end","corrected"]).describe("Observed result"),anchors:exports_external.array(MemoryAnchorSchema).max(20).optional().describe("Repository-relative file and optional symbol anchors"),correction:exports_external.string().trim().min(1).max(4000).optional().describe("Required corrected claim text for corrected outcomes")},execute:async(args2,directory,ctx)=>{let{config:config3}=_internals294.loadPluginConfigWithMeta(directory);if(config3.memory?.enabled!==!0)return JSON.stringify({success:!1,disabled:!0,message:"Swarm memory is disabled. Set swarm.memory.enabled=true."});let parsed=OutcomeArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,error:parsed.error.issues.map((issue3)=>issue3.message).join("; ")});let agent=typeof ctx?.agent==="string"?ctx.agent:void 0,taskId=ctx?.sessionID?_internals294.getAgentSession(ctx.sessionID)?.currentTaskId??void 0:void 0,gateway=_internals294.createMemoryGateway({directory,sessionID:ctx?.sessionID,agentRole:agent,agentId:agent,runId:ctx?.sessionID,unitId:taskId},{config:config3.memory}),eventId=ctx?.sessionID&&ctx.messageID?`tool-${createHash112("sha256").update(JSON.stringify({sessionID:ctx.sessionID,messageID:ctx.messageID,args:parsed.data})).digest("hex").slice(0,32)}`:void 0;try{let result=await _internals294.recordOutcomeWithReflection(directory,config3.memory,gateway,{memoryId:parsed.data.memory_id,question:parsed.data.question,outcome:parsed.data.outcome,anchors:parsed.data.anchors,correction:parsed.data.correction,eventId}),reflectionUpdated=result.reflectionUpdated,reflectionAttempted=result.reflectionAttempted,partial3=result.reflectionEnabled===!0&&reflectionAttempted&&!reflectionUpdated,reflectionError="error"in result?result.error:void 0;return JSON.stringify({success:!0,status:partial3?"partial":"complete",partial:partial3,outcome_recorded:result.outcomeRecorded,event_id:result.eventId,memory_id:result.record.id,outcome:parsed.data.outcome,outcomes:result.record.outcomes?.length??0,reflection_enabled:result.reflectionEnabled,reflection_attempted:reflectionAttempted,reflection_updated:reflectionUpdated,reflection_entries:reflectionUpdated?result.digest.generatedFrom.entries:void 0,error:partial3?reflectionError:void 0,reflection_error:partial3?reflectionError:void 0},null,2)}finally{await gateway.dispose()}}}),_internals294={loadPluginConfigWithMeta,createMemoryGateway,getAgentSession,recordOutcomeWithReflection};init_zod();init_config();init_memory();init_create_tool();var MEMORY_KINDS=["user_preference","project_fact","architecture_decision","repo_convention","api_finding","code_pattern","test_pattern","failure_pattern","security_note","evidence","todo","scratch"],ProposalArgsSchema=exports_external.object({operation:exports_external.enum(["add","update","delete","ignore","merge","supersede"]),kind:exports_external.enum(MEMORY_KINDS).optional(),text:exports_external.string().min(1).max(2000).optional(),targetMemoryId:exports_external.string().optional(),relatedMemoryIds:exports_external.array(exports_external.string()).optional(),rationale:exports_external.string().min(1).max(2000),evidenceRefs:exports_external.array(exports_external.string().min(1).max(500)).max(20).optional()}),swarm_memory_propose=createSwarmTool({description:"Create a pending Swarm memory proposal. This never writes durable memory directly; curator review is required.",args:{operation:exports_external.enum(["add","update","delete","ignore","merge","supersede"]).describe("Proposal operation"),kind:exports_external.enum(MEMORY_KINDS).optional().describe("Memory kind for add/update/supersede proposals"),text:exports_external.string().min(1).max(2000).optional().describe("Canonical fact text for add/update/supersede proposals"),targetMemoryId:exports_external.string().optional().describe("Target memory ID for update/delete/supersede proposals"),relatedMemoryIds:exports_external.array(exports_external.string()).optional().describe("For merge, 2-8 distinct memory IDs in one scope; also accepted as provenance for supersede proposals"),rationale:exports_external.string().min(1).max(2000).describe("Why this proposal matters"),evidenceRefs:exports_external.array(exports_external.string().min(1).max(500)).max(20).optional().describe("Evidence refs such as files, commits, test outputs, or URLs")},execute:async(args2,directory,ctx)=>{let{config:config3}=_internals295.loadPluginConfigWithMeta(directory);if(config3.memory?.enabled!==!0)return JSON.stringify({success:!1,disabled:!0,message:"Swarm memory is disabled. Set swarm.memory.enabled=true."});let parsed=ProposalArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,error:parsed.error.issues.map((issue3)=>issue3.message).join("; ")});let agent=getContextAgent3(ctx),gateway=_internals295.createMemoryGateway({directory,sessionID:ctx?.sessionID,agentRole:agent,agentId:agent,runId:ctx?.sessionID},{config:config3.memory});try{let proposal=await gateway.propose(parsed.data);return JSON.stringify({success:proposal.status!=="rejected",proposal_id:proposal.id,status:proposal.status,operation:proposal.operation,memory_id:proposal.proposedRecord?.id,rejection_reason:proposal.rejectionReason,message:proposal.status==="pending"?"Memory proposal created. Durable memory was not written.":"Memory proposal was captured with policy rejection metadata."},null,2)}finally{await gateway.dispose()}}}),_internals295={loadPluginConfigWithMeta,createMemoryGateway};function getContextAgent3(ctx){if(!ctx||typeof ctx!=="object")return;let value=ctx.agent;return typeof value==="string"?value:void 0}init_zod();init_config();init_memory();init_state2();init_create_tool();var MEMORY_KINDS2=["user_preference","project_fact","architecture_decision","repo_convention","api_finding","code_pattern","test_pattern","failure_pattern","security_note","evidence","todo","scratch"],swarm_memory_recall=createSwarmTool({description:"Recall scoped Swarm memory for the current repository. Read-only; retrieved memory is untrusted background.",args:{query:exports_external.string().min(3).describe("Natural language recall query"),kinds:exports_external.array(exports_external.enum(MEMORY_KINDS2)).optional().describe("Optional memory kinds to include"),maxItems:exports_external.number().int().min(1).max(20).optional().describe("Maximum memories to return")},execute:async(args2,directory,ctx)=>computeSwarmMemoryRecall(args2,directory,ctx)});async function computeSwarmMemoryRecall(args2,directory,ctx,options){let{config:config3}=_internals296.loadPluginConfigWithMeta(directory);if(config3.memory?.enabled!==!0)return JSON.stringify({success:!1,disabled:!0,message:"Swarm memory is disabled. Set swarm.memory.enabled=true."});let parsed=RecallArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,error:parsed.error.issues.map((issue3)=>issue3.message).join("; ")});let agent=getContextAgent4(ctx),unitId=ctx?.sessionID?_internals296.getAgentSession(ctx.sessionID)?.currentTaskId??void 0:void 0,gateway=_internals296.createMemoryGateway({directory,sessionID:ctx?.sessionID,agentRole:agent,agentId:agent,runId:ctx?.sessionID,unitId},{config:config3.memory});try{let bundle=await gateway.recall(parsed.data,{recordUsage:options?.recordUsage!==!1});return JSON.stringify({success:!0,bundle_id:bundle.id,memory_ids:bundle.items.map((item)=>item.record.id),total:bundle.items.length,token_estimate:bundle.tokenEstimate,signals:bundle.items.map((item)=>({memory_id:item.record.id,relation:item.relation,...item.signals})),prompt_block:bundle.promptBlock},null,2)}finally{await gateway.dispose()}}var RecallArgsSchema=exports_external.object({query:exports_external.string().min(3),kinds:exports_external.array(exports_external.enum(MEMORY_KINDS2)).optional(),maxItems:exports_external.number().int().min(1).max(20).optional()}),_internals296={loadPluginConfigWithMeta,createMemoryGateway,getAgentSession};function getContextAgent4(ctx){if(!ctx||typeof ctx!=="object")return;let value=ctx.agent;return typeof value==="string"?value:void 0}init_symbols();init_p_limit();init_zod();init_config();init_manager2();init_detector();init_registry();init_create_tool();import*as fs218 from"node:fs";import*as path358 from"node:path";var _internals297={loadGateOverrides},MAX_FILE_SIZE2=2097152,BINARY_CHECK_BYTES=8192,BINARY_NULL_THRESHOLD3=0.1,SYNTAX_CHECK_CONCURRENCY=8;function isBinaryContent2(content){let sample=content.slice(0,BINARY_CHECK_BYTES),nullCount=0;for(let i=0;i<sample.length;i++)if(sample.charCodeAt(i)===0)nullCount++;return nullCount/sample.length>BINARY_NULL_THRESHOLD3}function extractSyntaxErrors(parser,content){let tree=parser.parse(content);if(!tree)return[];let errors5=[],stack=[tree.rootNode];while(stack.length>0){let node=stack.pop();if(node.type==="ERROR")errors5.push({line:node.startPosition.row+1,column:node.startPosition.column,message:"Syntax error"});else if(node.isMissing)errors5.push({line:node.startPosition.row+1,column:node.startPosition.column,message:`Missing '${node.type}'`});let children=node.children;for(let i=children.length-1;i>=0;i--)stack.push(children[i])}if(errors5.length===0&&tree.rootNode.hasError)errors5.push({line:1,column:0,message:"Syntax error detected (tree has errors)"});return tree.delete(),errors5}async function syntaxCheck(input,directory,gates){return computeSyntaxCheck(input,directory,gates,{persistEvidence:!0})}async function computeSyntaxCheck(input,directory,gates,options){if(gates?.syntax_check?.enabled===!1)return{verdict:"pass",files:[],summary:"syntax_check disabled by configuration"};let{changed_files,mode="changed",languages}=input,filesToCheck=changed_files;if(mode==="changed")filesToCheck=filesToCheck.filter((f)=>f.additions>0);if(languages?.length){let lowerLangs=languages.map((l)=>l.toLowerCase());filesToCheck=filesToCheck.filter((file3)=>{let ext=path358.extname(file3.path).toLowerCase(),langDef=getLanguageForExtension(ext),langId=getProfileForFile(file3.path)?.id||langDef?.id;return langId?lowerLangs.includes(langId.toLowerCase()):!1})}let{loadGrammar:loadGrammar2}=await Promise.resolve().then(() => (init_runtime(),exports_runtime));async function checkOneFile(fileInfo){let{path:filePath}=fileInfo,fullPath=path358.isAbsolute(filePath)?filePath:path358.join(directory,filePath),result={path:filePath,language:"",ok:!1,errors:[]};try{let profile=getProfileForFile(filePath),grammarId=profile?.treeSitter?.grammarId,parser=null;if(grammarId)try{parser=await loadGrammar2(grammarId)}catch{parser=null}if(!parser)parser=await getParserForFile(filePath);if(!parser)return result.skipped_reason="unsupported_language",{result,counted:!1,failed:!1,skipped:!0};try{if(fs218.statSync(fullPath).size>=MAX_FILE_SIZE2)return result.skipped_reason="file_too_large",{result,counted:!1,failed:!1,skipped:!0}}catch{}let content;try{content=fs218.readFileSync(fullPath,"utf8")}catch{return result.skipped_reason="file_read_error",{result,counted:!1,failed:!1,skipped:!0}}if(content.length>=MAX_FILE_SIZE2)return result.skipped_reason="file_too_large",{result,counted:!1,failed:!1,skipped:!0};if(isBinaryContent2(content))return result.skipped_reason="binary_file",{result,counted:!1,failed:!1,skipped:!0};let ext=path358.extname(filePath).toLowerCase(),langDef=getLanguageForExtension(ext);result.language=profile?.id||langDef?.id||"unknown";let errors5=extractSyntaxErrors(parser,content);if(errors5.length>0)return result.ok=!1,result.errors=errors5,{result,counted:!0,failed:!0,skipped:!1};return result.ok=!0,{result,counted:!0,failed:!1,skipped:!1}}catch(error93){return result.skipped_reason=error93 instanceof Error?error93.message:"unknown_error",{result,counted:!0,failed:!1,skipped:!0}}}let limit=pLimit(SYNTAX_CHECK_CONCURRENCY),outcomes=await Promise.all(filesToCheck.map((fileInfo)=>limit(()=>checkOneFile(fileInfo)))),results=[],filesChecked=0,filesFailed=0,skippedCount=0;for(let outcome of outcomes){if(results.push(outcome.result),outcome.counted)filesChecked++;if(outcome.failed)filesFailed++;if(outcome.skipped)skippedCount++}let emptyCheckReasons=[];if(changed_files.length===0)emptyCheckReasons.push("no files were supplied in changed_files");else{if(mode==="changed")emptyCheckReasons.push("mode='changed' dropped files with additions === 0 (deletion-only or pure-rename entries); pass mode='all' to include them");if(languages?.length)emptyCheckReasons.push(`the languages filter [${languages.join(", ")}] matched no supplied file`);if(emptyCheckReasons.length===0)emptyCheckReasons.push("every supplied file was skipped as unsupported, unreadable, too large, or binary")}let verdict=filesFailed>0?"fail":filesChecked===0?"skip":"pass",summary=filesFailed>0?`Syntax errors found in ${filesFailed} of ${filesChecked} files`:filesChecked===0?`No files were checked — ${emptyCheckReasons.join("; ")}. This is NOT a passing syntax check.`:`All ${filesChecked} files passed syntax check`;if(options?.persistEvidence===!0)await _internals58.saveEvidence(directory,"syntax_check",{task_id:"syntax_check",type:"syntax",timestamp:new Date().toISOString(),agent:"syntax_check",verdict,summary,files_checked:filesChecked,files_failed:filesFailed,skipped_count:skippedCount,files:results});return{verdict,files:results,summary}}var syntax_check=createSwarmTool({allowWorkingDirectoryOverride:!0,description:"Check syntax of source files using tree-sitter parsers. Supports JS/TS, Python, Go, Rust, Java, C/C++, C#, PHP, Ruby. Returns JSON with syntax errors found per file.",args:{changed_files:exports_external.array(exports_external.object({path:exports_external.string(),additions:exports_external.number()})).describe("Files to check (from diff gate)"),mode:exports_external.enum(["changed","all"]).optional().describe("Check mode over the supplied changed_files. 'changed' (default) checks only entries with additions > 0, so deletion-only and pure-rename entries are excluded; 'all' checks every supplied entry. Neither mode enumerates the repository — this tool only ever inspects the files you pass in changed_files. If the filters leave nothing to check the verdict is 'skip', never 'pass'."),languages:exports_external.array(exports_external.string()).optional().describe("Optional: restrict to specific languages")},async execute(args2,directory){let gates=_internals297.loadGateOverrides(directory),result=await syntaxCheck(args2,directory,gates);return JSON.stringify(result)}});init_zod();init_analyzer();init_create_tool();init_resolve_working_directory();var test_impact=createSwarmTool({description:"Analyze which test files are impacted by changes to the given source files. Returns TestImpactResult with impactedTests, untestedFiles, and the full impact map.",args:{changedFiles:exports_external.array(exports_external.string()).describe("Array of source file paths to analyze for test impact"),working_directory:exports_external.string().optional().describe("Project root directory. Defaults to current working directory.")},async execute(args2,directory,_ctx){let typedArgs=args2;try{if(!typedArgs.changedFiles||!Array.isArray(typedArgs.changedFiles)||typedArgs.changedFiles.length===0)return JSON.stringify({error:"changedFiles must be a non-empty array of file paths",success:!1},null,2);let resolved=resolveWorkingDirectory(typedArgs.working_directory,directory);if(!resolved.success)return JSON.stringify({error:resolved.message,success:!1},null,2);let cwd=resolved.directory,result=await analyzeImpact(typedArgs.changedFiles,cwd);return JSON.stringify(result,null,2)}catch(e){return JSON.stringify({error:e instanceof Error?`test_impact failed: ${e.message}`:"test_impact failed: unknown error",success:!1},null,2)}}});init_test_runner();init_zod();init_utils();init_create_tool();init_path_security();import*as fs219 from"node:fs";import*as path359 from"node:path";var MAX_TEXT_LENGTH=200,MAX_FILE_SIZE_BYTES10=1048576,SUPPORTED_EXTENSIONS3=new Set([".ts",".tsx",".js",".jsx",".py",".rs",".ps1",".go",".java",".c",".cpp",".h",".cs",".rb",".php",".blade.php",".swift",".kt"]),SKIP_DIRECTORIES5=new Set(["node_modules","dist","build",".git",".swarm","coverage"]),PRIORITY_MAP={FIXME:"high",HACK:"high",XXX:"high",TODO:"medium",WARN:"medium",NOTE:"low"},SHELL_METACHAR_REGEX3=/[;&|%$`\\]/;function validateTagsInput(tags){if(!tags||tags.length===0)return"tags cannot be empty";if(containsControlChars(tags))return"tags contains control characters";if(SHELL_METACHAR_REGEX3.test(tags))return"tags contains shell metacharacters (;|&$`\\)";if(!/^[a-zA-Z0-9,\s]+$/.test(tags))return"tags contains invalid characters (only alphanumeric, commas, spaces allowed)";return null}function validatePathsInput(paths,cwd){if(!paths||paths.length===0)return{error:null,resolvedPath:cwd};if(containsControlChars(paths))return{error:"paths contains control characters",resolvedPath:null};if(containsPathTraversal(paths))return{error:"paths contains path traversal",resolvedPath:null};try{let resolvedPath=path359.resolve(paths),normalizedCwd=path359.resolve(cwd);if(!path359.resolve(resolvedPath).startsWith(normalizedCwd))return{error:"paths must be within the current working directory",resolvedPath:null};return{error:null,resolvedPath}}catch(e){return{error:e instanceof Error?e.message:"invalid paths",resolvedPath:null}}}function isSupportedExtension(filePath){let ext=path359.extname(filePath).toLowerCase();return SUPPORTED_EXTENSIONS3.has(ext)}function findSourceFiles3(dir,files=[]){let entries2;try{entries2=fs219.readdirSync(dir)}catch{return files}entries2.sort((a,b)=>a.toLowerCase().localeCompare(b.toLowerCase()));for(let entry of entries2){if(SKIP_DIRECTORIES5.has(entry))continue;let fullPath=path359.join(dir,entry),stat25;try{stat25=fs219.statSync(fullPath)}catch{continue}if(stat25.isDirectory())findSourceFiles3(fullPath,files);else if(stat25.isFile()){if(isSupportedExtension(fullPath))files.push(fullPath)}}return files}function parseTodoComments(content,filePath,tagsSet){let entries2=[],lines=content.split(`
|
|
7790
|
-
`),tagPattern=Array.from(tagsSet).map(escapeRegex2).join("|"),regex=new RegExp(`\\b(${tagPattern})\\b[:\\s]?`,"i");for(let i=0;i<lines.length;i++){let line=lines[i],match=regex.exec(line);if(match){let tag=match[1].toUpperCase(),priority=PRIORITY_MAP[tag]||"medium",text=line.substring(match.index+match[0].length).trim();if(text=text.replace(/^[/*\-\s]+/,""),text.length>MAX_TEXT_LENGTH)text=`${text.substring(0,MAX_TEXT_LENGTH-3)}...`;entries2.push({file:filePath,line:i+1,tag,text,priority})}}return entries2}var todo_extract=createSwarmTool({description:"Scan the codebase for TODO/FIXME/HACK/XXX/WARN/NOTE comments. Returns JSON with count by priority and sorted entries. Useful for identifying pending tasks and code issues.",args:{paths:exports_external.string().optional().describe("Directory or file to scan (default: entire project/cwd)"),tags:exports_external.string().optional().describe("Comma-separated tags to search for (default: TODO,FIXME,HACK,XXX,WARN,NOTE)")},async execute(args2,directory){let paths,tags;try{if(args2&&typeof args2==="object"){let obj=args2;paths=typeof obj.paths==="string"?obj.paths:void 0,tags=typeof obj.tags==="string"?obj.tags:void 0}}catch{}let cwd=directory,tagsInput=tags||"TODO,FIXME,HACK,XXX,WARN,NOTE",tagsValidationError=validateTagsInput(tagsInput);if(tagsValidationError){let errorResult={error:`invalid tags: ${tagsValidationError}`,total:0,byPriority:{high:0,medium:0,low:0},entries:[]};return JSON.stringify(errorResult,null,2)}let tagsList=tagsInput.split(",").map((t)=>t.trim().toUpperCase()).filter((t)=>t.length>0),tagsSet=new Set(tagsList);if(tagsSet.size===0)return JSON.stringify({error:"invalid tags: no valid tags provided",total:0,byPriority:{high:0,medium:0,low:0},entries:[]},null,2);let pathsInput=paths||cwd,{error:pathsError,resolvedPath}=validatePathsInput(pathsInput,cwd);if(pathsError){let errorResult={error:`invalid paths: ${pathsError}`,total:0,byPriority:{high:0,medium:0,low:0},entries:[]};return JSON.stringify(errorResult,null,2)}let scanPath=resolvedPath;if(!fs219.existsSync(scanPath)){let errorResult={error:`path not found: ${pathsInput}`,total:0,byPriority:{high:0,medium:0,low:0},entries:[]};return JSON.stringify(errorResult,null,2)}let filesToScan=[];if(fs219.statSync(scanPath).isFile())if(isSupportedExtension(scanPath))filesToScan.push(scanPath);else{let errorResult={error:`unsupported file extension: ${path359.extname(scanPath)}`,total:0,byPriority:{high:0,medium:0,low:0},entries:[]};return JSON.stringify(errorResult,null,2)}else findSourceFiles3(scanPath,filesToScan);let allEntries=[];for(let filePath of filesToScan)try{if(fs219.statSync(filePath).size>MAX_FILE_SIZE_BYTES10)continue;let content=fs219.readFileSync(filePath,"utf-8"),entries2=parseTodoComments(content,filePath,tagsSet);allEntries.push(...entries2)}catch{}allEntries.sort((a,b)=>{let priorityOrder={high:0,medium:1,low:2},priorityDiff=priorityOrder[a.priority]-priorityOrder[b.priority];if(priorityDiff!==0)return priorityDiff;return a.file.toLowerCase().localeCompare(b.file.toLowerCase())});let byPriority={high:allEntries.filter((e)=>e.priority==="high").length,medium:allEntries.filter((e)=>e.priority==="medium").length,low:allEntries.filter((e)=>e.priority==="low").length},result={total:allEntries.length,byPriority,entries:allEntries};return JSON.stringify(result,null,2)}});init_zod();init_loader();init_schema();init_qa_gate_profile();init_task_gate_requirements();init_gate_evidence();import*as fs223 from"node:fs";import*as path363 from"node:path";init_bun_compat();init_git_executable();import*as fs221 from"node:fs";import*as path361 from"node:path";init_warning_buffer();init_bun_compat();init_git_executable();import*as fs220 from"node:fs";import*as path360 from"node:path";var _internals298={bunSpawn,resolveGitExecutableAsync};var _swarmGitExcludedChecked=!1;function fileCoversIgnorePatterns(content,patterns){for(let rawLine of content.split(`
|
|
7795
|
+
`)};return{valid:!0}}var suggestPatch=createSwarmTool({description:'Suggest a structured patch for specified files without modifying them. Returns context-based patch proposals with anchors for reviewer use. When format="unified", also produces a unified diff string consumable by apply_patch. '+"This is a read-only tool — it does not modify any files.",args:{targetFiles:exports_external.array(exports_external.string()).describe("Array of file paths to patch").min(1),changes:exports_external.array(exports_external.object({file:exports_external.string().describe("Path to the file this change applies to"),contextBefore:exports_external.array(exports_external.string()).optional().describe("Lines before the change region (anchor)"),contextAfter:exports_external.array(exports_external.string()).optional().describe("Lines after the change region (anchor)"),oldContent:exports_external.string().optional().describe("Current content to be replaced"),newContent:exports_external.string().describe("New content to replace with")})).describe("Array of change descriptions with context anchors").min(1),format:exports_external.enum(["json","unified"]).optional().default("json").describe('Output format: "json" (default, existing structured output) or "unified" (unified diff string for apply_patch)')},execute:async(args2,directory)=>{if(!args2||typeof args2!=="object")return JSON.stringify({success:!1,error:!0,type:"parse-error",message:"Could not parse suggest-patch arguments"},null,2);let obj=args2,targetFiles=obj.targetFiles??[],changes=obj.changes??[],format=obj.format??"json";if(!targetFiles||targetFiles.length===0)return JSON.stringify({success:!1,error:!0,type:"parse-error",message:"targetFiles cannot be empty"},null,2);if(!changes||changes.length===0)return JSON.stringify({success:!1,error:!0,type:"parse-error",message:"changes cannot be empty"},null,2);if(!fs217.existsSync(directory))return JSON.stringify({success:!1,error:!0,type:"file-not-found",message:"Workspace directory does not exist"},null,2);let patches=[],filesModifiedSet=new Set,errors5=[],unifiedDiffEntries=[],targetFileSet=new Set(targetFiles),skippedBinaryFiles=new Set;if(format==="unified"){for(let change of changes)if(isBinaryFile4(change.file))errors5.push({success:!1,error:!0,type:"parse-error",message:`Binary files are not supported in unified diff mode: ${change.file}`,details:{location:change.file}}),skippedBinaryFiles.add(change.file)}for(let changeIndex=0;changeIndex<changes.length;changeIndex++){let change=changes[changeIndex];if(format==="unified"&&skippedBinaryFiles.has(change.file))continue;if(!targetFileSet.has(change.file)){errors5.push({success:!1,error:!0,type:"parse-error",message:`File "${change.file}" is not in targetFiles`,details:{location:change.file}});continue}if(!validateFilePath2(change.file,directory)){errors5.push({success:!1,error:!0,type:"parse-error",message:`Invalid file path: ${change.file}`,details:{location:change.file}});continue}let fullPath=path357.resolve(directory,change.file);if(!fs217.existsSync(fullPath)){errors5.push({success:!1,error:!0,type:"file-not-found",message:`File not found: ${change.file}`,details:{location:change.file}});continue}let content;try{content=fs217.readFileSync(fullPath,"utf-8")}catch(err2){errors5.push({success:!1,error:!0,type:"unknown",message:`Could not read file: ${err2 instanceof Error?err2.message:String(err2)}`,details:{location:`${change.file}:0`}});continue}let contextMatch=findContextMatch(content,change.contextBefore,change.contextAfter,change.oldContent);if(!contextMatch){errors5.push({success:!1,error:!0,type:"context-mismatch",message:`Could not find context anchor in ${change.file}. Provide contextBefore/contextAfter lines to locate the change region.`,details:{location:change.file}});continue}let lines=splitDiffLines(content),oldContentValidation=validateOldContent(lines,contextMatch,change.oldContent);if(!oldContentValidation.valid){errors5.push({success:!1,error:!0,type:"context-mismatch",message:"Content at the specified location does not match oldContent",details:{expected:oldContentValidation.expected,actual:oldContentValidation.actual,location:`${change.file}:${contextMatch.startLineIndex+1}-${contextMatch.endLineIndex+1}`}});continue}let originalContext=[...contextMatch.matchedBefore,...contextMatch.matchedAfter.length>0?["..."]:[],...contextMatch.matchedAfter];if(patches.push({file:change.file,originalContext,newContent:change.newContent,hunkIndex:changeIndex}),filesModifiedSet.add(change.file),format==="unified")unifiedDiffEntries.push({file:change.file,contextMatch,oldContent:change.oldContent,newContent:change.newContent})}if(patches.length>0){let baseResult={success:!0,patches,filesModified:Array.from(filesModifiedSet),...errors5.length>0&&{errors:errors5}};if(format==="unified"){let fileGroups=new Map;for(let entry of unifiedDiffEntries){let group=fileGroups.get(entry.file)??[];group.push(entry),fileGroups.set(entry.file,group)}let unifiedParts=[];for(let[file3,entries2]of fileGroups){entries2.sort((a,b)=>a.contextMatch.startLineIndex-b.contextMatch.startLineIndex);let entryFullPath=path357.resolve(directory,file3),entryContent;try{entryContent=fs217.readFileSync(entryFullPath,"utf-8")}catch{continue}unifiedParts.push(generateFileHeader(file3));for(let entry of entries2)unifiedParts.push(generateHunk(entryContent,entry.contextMatch,entry.oldContent,entry.newContent))}let unifiedPatch=unifiedParts.join("");return JSON.stringify({...baseResult,unifiedPatch},null,2)}return JSON.stringify(baseResult,null,2)}if(errors5.length===1)return JSON.stringify(errors5[0],null,2);return JSON.stringify({success:!1,error:!0,type:"context-mismatch",message:`All ${errors5.length} patch suggestions failed`,errors:errors5},null,2)}});init_zod();init_loader();init_schema3();init_store5();init_create_tool();init_resolve_working_directory();function getContextAgent2(ctx){if(!ctx||typeof ctx!=="object")return;let value=ctx.agent;return typeof value==="string"?value:void 0}var ArgsSchema5=exports_external.object({phase:exports_external.number().int().min(0).max(999),summary:exports_external.string().min(1),task_id:exports_external.string().min(1).optional(),parent_agent:exports_external.string().min(1).optional(),key_decisions:exports_external.array(exports_external.string().min(1)).optional(),constraints_observed:exports_external.array(exports_external.string().min(1)).optional(),constraints_violated:exports_external.array(exports_external.string().min(1)).optional(),assumptions:exports_external.array(exports_external.string().min(1)).optional(),risks:exports_external.array(exports_external.string().min(1)).optional(),files_touched:exports_external.array(exports_external.string().min(1)).optional(),evidence_refs:exports_external.array(exports_external.string().min(1)).optional(),working_directory:exports_external.string().optional()}),summarize_work=createSwarmTool({description:`Emit a short structured summary of the work you just completed (key decisions, assumptions, risks, constraints observed/violated). Call this once at task completion. Keep the summary under ${MAX_AGENT_SUMMARY_WORDS} words and each list to ${MAX_LIST_ITEMS} items — longer content is truncated, not rejected. These `+"summaries roll up per phase and are reviewed by the architecture supervisor to catch cross-task contradictions, drift, and repeated failure loops. Advisory only.",args:{phase:exports_external.number().int().min(0).max(999).describe("Phase number this work belongs to."),summary:exports_external.string().min(1).describe(`One-paragraph summary of what you did (<= ${MAX_AGENT_SUMMARY_WORDS} words).`),task_id:exports_external.string().min(1).optional().describe('Task ID this summary covers (e.g. "1.2").'),parent_agent:exports_external.string().min(1).optional().describe("The agent that delegated this task, if any."),key_decisions:exports_external.array(exports_external.string().min(1)).optional(),constraints_observed:exports_external.array(exports_external.string().min(1)).optional(),constraints_violated:exports_external.array(exports_external.string().min(1)).optional(),assumptions:exports_external.array(exports_external.string().min(1)).optional(),risks:exports_external.array(exports_external.string().min(1)).optional(),files_touched:exports_external.array(exports_external.string().min(1)).optional(),evidence_refs:exports_external.array(exports_external.string().min(1)).optional(),working_directory:exports_external.string().optional()},execute:async(rawArgs,directory,ctx)=>{let parsed=ArgsSchema5.safeParse(rawArgs);if(!parsed.success)return JSON.stringify({success:!1,reason:"invalid arguments",errors:parsed.error.issues.map((i)=>({path:i.path.join("."),message:i.message}))},null,2);let args2=parsed.data,dirResult=resolveWorkingDirectory(args2.working_directory,directory);if(!dirResult.success)return JSON.stringify({success:!1,reason:dirResult.message},null,2);let workingDir=dirResult.directory,sessionId=ctx?.sessionID??"unknown-session",agent=getContextAgent2(ctx)??"unknown-agent",maxWords=MAX_AGENT_SUMMARY_WORDS;try{maxWords=loadPluginConfig(workingDir).architectural_supervision?.max_agent_summary_words??maxWords}catch{}let summary=normalizeAgentWorkSummary({phase:args2.phase,task_id:args2.task_id,session_id:sessionId,agent,parent_agent:args2.parent_agent,summary:args2.summary,key_decisions:args2.key_decisions,constraints_observed:args2.constraints_observed,constraints_violated:args2.constraints_violated,assumptions:args2.assumptions,risks:args2.risks,files_touched:args2.files_touched,evidence_refs:args2.evidence_refs},maxWords),storedTaskId=await writeAgentSummary(workingDir,summary);return JSON.stringify({success:!0,stored_task_id:storedTaskId,phase:summary.phase,agent:summary.agent,truncated:summary.truncated??!1},null,2)}});init_zod();init_command_dispatch();init_tool_policy();init_create_tool();function createSwarmCommandTool(agents,evaluationModelDispatcher,reviewModelDispatcher,autoReviewConfig,reviewAgentModelRegistry,getActiveAgentName){return createSwarmTool({description:"Run supported /swarm commands through the canonical opencode-swarm command registry. Return the tool output verbatim to the user.",args:{command:exports_external.enum(SWARM_COMMAND_TOOL_COMMANDS).describe("The /swarm subcommand to run, without the /swarm prefix."),args:exports_external.array(exports_external.string()).default([]).describe("Additional command arguments as separate tokens.")},async execute(rawArgs,directory,ctx){let args2=rawArgs;return(await executeSwarmCommand({directory,agents,sessionID:ctx?.sessionID??"",tokens:[args2.command,...args2.args??[]],policy:classifySwarmCommandToolUse,evaluationModelDispatcher,reviewModelDispatcher,autoReviewConfig,reviewAgentModelRegistry,activeAgentName:getActiveAgentName?.(ctx?.sessionID??"")})).text}})}var swarm_command=createSwarmCommandTool({});init_zod();init_config();init_memory();init_state2();init_create_tool();import{createHash as createHash112}from"node:crypto";var OutcomeArgsSchema=exports_external.object({memory_id:exports_external.string().regex(/^mem_[a-f0-9]{16}$/).optional(),question:exports_external.string().trim().min(1).max(2000).optional(),outcome:exports_external.enum(["useful","dead_end","corrected"]),anchors:exports_external.array(MemoryAnchorSchema).max(20).optional(),correction:exports_external.string().trim().min(1).max(4000).optional()}).strict().superRefine((value,context)=>{if(Boolean(value.memory_id)===Boolean(value.question))context.addIssue({code:"custom",message:"exactly one of memory_id or question is required"});if(value.outcome==="corrected"&&!value.correction)context.addIssue({code:"custom",message:"corrected outcomes require correction text"})}),swarm_memory_outcome=createSwarmTool({description:"Record whether recalled memory or a graph answer was useful, a dead end, or corrected; when reflection is enabled, synchronously refresh deterministic reflection artifacts.",args:{memory_id:exports_external.string().regex(/^mem_[a-f0-9]{16}$/).optional().describe("Existing memory id to update"),question:exports_external.string().trim().min(1).max(2000).optional().describe("Question for a lightweight result memory when no id is known"),outcome:exports_external.enum(["useful","dead_end","corrected"]).describe("Observed result"),anchors:exports_external.array(MemoryAnchorSchema).max(20).optional().describe("Repository-relative file and optional symbol anchors"),correction:exports_external.string().trim().min(1).max(4000).optional().describe("Required corrected claim text for corrected outcomes")},execute:async(args2,directory,ctx)=>{let{config:config3}=_internals294.loadPluginConfigWithMeta(directory);if(config3.memory?.enabled!==!0)return JSON.stringify({success:!1,disabled:!0,message:"Swarm memory is disabled. Set swarm.memory.enabled=true."});let parsed=OutcomeArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,error:parsed.error.issues.map((issue3)=>issue3.message).join("; ")});let agent=typeof ctx?.agent==="string"?ctx.agent:void 0,taskId=ctx?.sessionID?_internals294.getAgentSession(ctx.sessionID)?.currentTaskId??void 0:void 0,gateway=_internals294.createMemoryGateway({directory,sessionID:ctx?.sessionID,agentRole:agent,agentId:agent,runId:ctx?.sessionID,unitId:taskId},{config:config3.memory}),eventId=ctx?.sessionID&&ctx.messageID?`tool-${createHash112("sha256").update(JSON.stringify({sessionID:ctx.sessionID,messageID:ctx.messageID,args:parsed.data})).digest("hex").slice(0,32)}`:void 0;try{let result=await _internals294.recordOutcomeWithReflection(directory,config3.memory,gateway,{memoryId:parsed.data.memory_id,question:parsed.data.question,outcome:parsed.data.outcome,anchors:parsed.data.anchors,correction:parsed.data.correction,eventId}),reflectionUpdated=result.reflectionUpdated,reflectionAttempted=result.reflectionAttempted,partial3=result.reflectionEnabled===!0&&reflectionAttempted&&!reflectionUpdated,reflectionError="error"in result?result.error:void 0;return JSON.stringify({success:!0,status:partial3?"partial":"complete",partial:partial3,outcome_recorded:result.outcomeRecorded,event_id:result.eventId,memory_id:result.record.id,outcome:parsed.data.outcome,outcomes:result.record.outcomes?.length??0,reflection_enabled:result.reflectionEnabled,reflection_attempted:reflectionAttempted,reflection_updated:reflectionUpdated,reflection_entries:reflectionUpdated?result.digest.generatedFrom.entries:void 0,error:partial3?reflectionError:void 0,reflection_error:partial3?reflectionError:void 0},null,2)}finally{await gateway.dispose()}}}),_internals294={loadPluginConfigWithMeta,createMemoryGateway,getAgentSession,recordOutcomeWithReflection};init_zod();init_config();init_memory();init_create_tool();var MEMORY_KINDS=["user_preference","project_fact","architecture_decision","repo_convention","api_finding","code_pattern","test_pattern","failure_pattern","security_note","evidence","todo","scratch"],ProposalArgsSchema=exports_external.object({operation:exports_external.enum(["add","update","delete","ignore","merge","supersede"]),kind:exports_external.enum(MEMORY_KINDS).optional(),text:exports_external.string().min(1).max(2000).optional(),targetMemoryId:exports_external.string().optional(),relatedMemoryIds:exports_external.array(exports_external.string()).optional(),rationale:exports_external.string().min(1).max(2000),evidenceRefs:exports_external.array(exports_external.string().min(1).max(500)).max(20).optional()}),swarm_memory_propose=createSwarmTool({description:"Create a pending Swarm memory proposal. This never writes durable memory directly; curator review is required.",args:{operation:exports_external.enum(["add","update","delete","ignore","merge","supersede"]).describe("Proposal operation"),kind:exports_external.enum(MEMORY_KINDS).optional().describe("Memory kind for add/update/supersede proposals"),text:exports_external.string().min(1).max(2000).optional().describe("Canonical fact text for add/update/supersede proposals"),targetMemoryId:exports_external.string().optional().describe("Target memory ID for update/delete/supersede proposals"),relatedMemoryIds:exports_external.array(exports_external.string()).optional().describe("For merge, 2-8 distinct memory IDs in one scope; also accepted as provenance for supersede proposals"),rationale:exports_external.string().min(1).max(2000).describe("Why this proposal matters"),evidenceRefs:exports_external.array(exports_external.string().min(1).max(500)).max(20).optional().describe("Evidence refs such as files, commits, test outputs, or URLs")},execute:async(args2,directory,ctx)=>{let{config:config3}=_internals295.loadPluginConfigWithMeta(directory);if(config3.memory?.enabled!==!0)return JSON.stringify({success:!1,disabled:!0,message:"Swarm memory is disabled. Set swarm.memory.enabled=true."});let parsed=ProposalArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,error:parsed.error.issues.map((issue3)=>issue3.message).join("; ")});let agent=getContextAgent3(ctx),gateway=_internals295.createMemoryGateway({directory,sessionID:ctx?.sessionID,agentRole:agent,agentId:agent,runId:ctx?.sessionID},{config:config3.memory});try{let proposal=await gateway.propose(parsed.data);return JSON.stringify({success:proposal.status!=="rejected",proposal_id:proposal.id,status:proposal.status,operation:proposal.operation,memory_id:proposal.proposedRecord?.id,rejection_reason:proposal.rejectionReason,message:proposal.status==="pending"?"Memory proposal created. Durable memory was not written.":"Memory proposal was captured with policy rejection metadata."},null,2)}finally{await gateway.dispose()}}}),_internals295={loadPluginConfigWithMeta,createMemoryGateway};function getContextAgent3(ctx){if(!ctx||typeof ctx!=="object")return;let value=ctx.agent;return typeof value==="string"?value:void 0}init_zod();init_config();init_memory();init_state2();init_create_tool();var MEMORY_KINDS2=["user_preference","project_fact","architecture_decision","repo_convention","api_finding","code_pattern","test_pattern","failure_pattern","security_note","evidence","todo","scratch"],swarm_memory_recall=createSwarmTool({description:"Recall scoped Swarm memory for the current repository. Read-only; retrieved memory is untrusted background.",args:{query:exports_external.string().min(3).describe("Natural language recall query"),kinds:exports_external.array(exports_external.enum(MEMORY_KINDS2)).optional().describe("Optional memory kinds to include"),maxItems:exports_external.number().int().min(1).max(20).optional().describe("Maximum memories to return")},execute:async(args2,directory,ctx)=>computeSwarmMemoryRecall(args2,directory,ctx)});async function computeSwarmMemoryRecall(args2,directory,ctx,options){let{config:config3}=_internals296.loadPluginConfigWithMeta(directory);if(config3.memory?.enabled!==!0)return JSON.stringify({success:!1,disabled:!0,message:"Swarm memory is disabled. Set swarm.memory.enabled=true."});let parsed=RecallArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,error:parsed.error.issues.map((issue3)=>issue3.message).join("; ")});let agent=getContextAgent4(ctx),unitId=ctx?.sessionID?_internals296.getAgentSession(ctx.sessionID)?.currentTaskId??void 0:void 0,gateway=_internals296.createMemoryGateway({directory,sessionID:ctx?.sessionID,agentRole:agent,agentId:agent,runId:ctx?.sessionID,unitId},{config:config3.memory});try{let bundle=await gateway.recall(parsed.data,{recordUsage:options?.recordUsage!==!1});return JSON.stringify({success:!0,bundle_id:bundle.id,memory_ids:bundle.items.map((item)=>item.record.id),total:bundle.items.length,token_estimate:bundle.tokenEstimate,signals:bundle.items.map((item)=>({memory_id:item.record.id,relation:item.relation,...item.signals})),prompt_block:bundle.promptBlock},null,2)}finally{await gateway.dispose()}}var RecallArgsSchema=exports_external.object({query:exports_external.string().min(3),kinds:exports_external.array(exports_external.enum(MEMORY_KINDS2)).optional(),maxItems:exports_external.number().int().min(1).max(20).optional()}),_internals296={loadPluginConfigWithMeta,createMemoryGateway,getAgentSession};function getContextAgent4(ctx){if(!ctx||typeof ctx!=="object")return;let value=ctx.agent;return typeof value==="string"?value:void 0}init_symbols();init_p_limit();init_zod();init_config();init_manager2();init_detector();init_registry();init_create_tool();import*as fs218 from"node:fs";import*as path358 from"node:path";var _internals297={loadGateOverrides},MAX_FILE_SIZE2=2097152,BINARY_CHECK_BYTES=8192,BINARY_NULL_THRESHOLD3=0.1,SYNTAX_CHECK_CONCURRENCY=8;function isBinaryContent2(content){let sample=content.slice(0,BINARY_CHECK_BYTES),nullCount=0;for(let i=0;i<sample.length;i++)if(sample.charCodeAt(i)===0)nullCount++;return nullCount/sample.length>BINARY_NULL_THRESHOLD3}function extractSyntaxErrors(parser,content){let tree=parser.parse(content);if(!tree)return[];let errors5=[],stack=[tree.rootNode];while(stack.length>0){let node=stack.pop();if(node.type==="ERROR")errors5.push({line:node.startPosition.row+1,column:node.startPosition.column,message:"Syntax error"});else if(node.isMissing)errors5.push({line:node.startPosition.row+1,column:node.startPosition.column,message:`Missing '${node.type}'`});let children=node.children;for(let i=children.length-1;i>=0;i--)stack.push(children[i])}if(errors5.length===0&&tree.rootNode.hasError)errors5.push({line:1,column:0,message:"Syntax error detected (tree has errors)"});return tree.delete(),errors5}async function syntaxCheck(input,directory,gates){return computeSyntaxCheck(input,directory,gates,{persistEvidence:!0})}async function computeSyntaxCheck(input,directory,gates,options){if(gates?.syntax_check?.enabled===!1)return{verdict:"pass",files:[],summary:"syntax_check disabled by configuration"};let{changed_files,mode="changed",languages}=input,filesToCheck=changed_files;if(mode==="changed")filesToCheck=filesToCheck.filter((f)=>f.additions>0);if(languages?.length){let lowerLangs=languages.map((l)=>l.toLowerCase());filesToCheck=filesToCheck.filter((file3)=>{let ext=path358.extname(file3.path).toLowerCase(),langDef=getLanguageForExtension(ext),langId=getProfileForFile(file3.path)?.id||langDef?.id;return langId?lowerLangs.includes(langId.toLowerCase()):!1})}let{loadGrammar:loadGrammar2}=await Promise.resolve().then(() => (init_runtime(),exports_runtime));async function checkOneFile(fileInfo){let{path:filePath}=fileInfo,fullPath=path358.isAbsolute(filePath)?filePath:path358.join(directory,filePath),result={path:filePath,language:"",ok:!1,errors:[]};try{let profile=getProfileForFile(filePath),grammarId=profile?.treeSitter?.grammarId,parser=null;if(grammarId)try{parser=await loadGrammar2(grammarId)}catch{parser=null}if(!parser)parser=await getParserForFile(filePath);if(!parser)return result.skipped_reason="unsupported_language",{result,counted:!1,failed:!1,skipped:!0};try{if(fs218.statSync(fullPath).size>=MAX_FILE_SIZE2)return result.skipped_reason="file_too_large",{result,counted:!1,failed:!1,skipped:!0}}catch{}let content;try{content=fs218.readFileSync(fullPath,"utf8")}catch{return result.skipped_reason="file_read_error",{result,counted:!1,failed:!1,skipped:!0}}if(content.length>=MAX_FILE_SIZE2)return result.skipped_reason="file_too_large",{result,counted:!1,failed:!1,skipped:!0};if(isBinaryContent2(content))return result.skipped_reason="binary_file",{result,counted:!1,failed:!1,skipped:!0};let ext=path358.extname(filePath).toLowerCase(),langDef=getLanguageForExtension(ext);result.language=profile?.id||langDef?.id||"unknown";let errors5=extractSyntaxErrors(parser,content);if(errors5.length>0)return result.ok=!1,result.errors=errors5,{result,counted:!0,failed:!0,skipped:!1};return result.ok=!0,{result,counted:!0,failed:!1,skipped:!1}}catch(error93){return result.skipped_reason=error93 instanceof Error?error93.message:"unknown_error",{result,counted:!0,failed:!1,skipped:!0}}}let limit=pLimit(SYNTAX_CHECK_CONCURRENCY),outcomes=await Promise.all(filesToCheck.map((fileInfo)=>limit(()=>checkOneFile(fileInfo)))),results=[],filesChecked=0,filesFailed=0,skippedCount=0;for(let outcome of outcomes){if(results.push(outcome.result),outcome.counted)filesChecked++;if(outcome.failed)filesFailed++;if(outcome.skipped)skippedCount++}let emptyCheckReasons=[];if(changed_files.length===0)emptyCheckReasons.push("no files were supplied in changed_files");else{if(mode==="changed")emptyCheckReasons.push("mode='changed' dropped files with additions === 0 (deletion-only or pure-rename entries); pass mode='all' to include them");if(languages?.length)emptyCheckReasons.push(`the languages filter [${languages.join(", ")}] matched no supplied file`);if(emptyCheckReasons.length===0)emptyCheckReasons.push("every supplied file was skipped as unsupported, unreadable, too large, or binary")}let verdict=filesFailed>0?"fail":filesChecked===0?"skip":"pass",summary=filesFailed>0?`Syntax errors found in ${filesFailed} of ${filesChecked} files`:filesChecked===0?`No files were checked — ${emptyCheckReasons.join("; ")}. This is NOT a passing syntax check.`:`All ${filesChecked} files passed syntax check`;if(options?.persistEvidence===!0)await _internals58.saveEvidence(directory,"syntax_check",{task_id:"syntax_check",type:"syntax",timestamp:new Date().toISOString(),agent:"syntax_check",verdict,summary,files_checked:filesChecked,files_failed:filesFailed,skipped_count:skippedCount,files:results});return{verdict,files:results,summary}}var syntax_check=createSwarmTool({allowWorkingDirectoryOverride:!0,description:"Check syntax of source files using tree-sitter parsers. Supports JS/TS, Python, Go, Rust, Java, C/C++, C#, PHP, Ruby. Returns JSON with syntax errors found per file.",args:{changed_files:exports_external.array(exports_external.object({path:exports_external.string(),additions:exports_external.number()})).describe("Files to check (from diff gate)"),mode:exports_external.enum(["changed","all"]).optional().describe("Check mode over the supplied changed_files. 'changed' (default) checks only entries with additions > 0, so deletion-only and pure-rename entries are excluded; 'all' checks every supplied entry. Neither mode enumerates the repository — this tool only ever inspects the files you pass in changed_files. If the filters leave nothing to check the verdict is 'skip', never 'pass'."),languages:exports_external.array(exports_external.string()).optional().describe("Optional: restrict to specific languages")},async execute(args2,directory){let gates=_internals297.loadGateOverrides(directory),result=await syntaxCheck(args2,directory,gates);return JSON.stringify(result)}});init_zod();init_analyzer();init_create_tool();init_resolve_working_directory();var test_impact=createSwarmTool({description:"Analyze which test files are impacted by changes to the given source files. Returns TestImpactResult with impactedTests, untestedFiles, and the full impact map.",args:{changedFiles:exports_external.array(exports_external.string()).describe("Array of source file paths to analyze for test impact"),working_directory:exports_external.string().optional().describe("Project root directory. Defaults to current working directory.")},async execute(args2,directory,_ctx){let typedArgs=args2;try{if(!typedArgs.changedFiles||!Array.isArray(typedArgs.changedFiles)||typedArgs.changedFiles.length===0)return JSON.stringify({error:"changedFiles must be a non-empty array of file paths",success:!1},null,2);let resolved=resolveWorkingDirectory(typedArgs.working_directory,directory);if(!resolved.success)return JSON.stringify({error:resolved.message,success:!1},null,2);let cwd=resolved.directory,result=await analyzeImpact(typedArgs.changedFiles,cwd);return JSON.stringify(result,null,2)}catch(e){return JSON.stringify({error:e instanceof Error?`test_impact failed: ${e.message}`:"test_impact failed: unknown error",success:!1},null,2)}}});init_test_runner();init_zod();init_config();init_gate_evidence();init_utils();init_logger();init_task_id();init_create_tool();init_path_security();import*as fs219 from"node:fs";import*as path359 from"node:path";var MAX_TEXT_LENGTH=200,MAX_FILE_SIZE_BYTES10=1048576,MAX_RECORDED_DETAILS=50,SUPPORTED_EXTENSIONS3=new Set([".ts",".tsx",".js",".jsx",".py",".rs",".ps1",".go",".java",".c",".cpp",".h",".cs",".rb",".php",".blade.php",".swift",".kt"]),SKIP_DIRECTORIES5=new Set(["node_modules","dist","build",".git",".swarm","coverage"]),PRIORITY_MAP={FIXME:"high",HACK:"high",XXX:"high",TODO:"medium",WARN:"medium",NOTE:"low"},SHELL_METACHAR_REGEX3=/[;&|%$`\\]/;function validateTagsInput(tags){if(!tags||tags.length===0)return"tags cannot be empty";if(containsControlChars(tags))return"tags contains control characters";if(SHELL_METACHAR_REGEX3.test(tags))return"tags contains shell metacharacters (;|&$`\\)";if(!/^[a-zA-Z0-9,\s]+$/.test(tags))return"tags contains invalid characters (only alphanumeric, commas, spaces allowed)";return null}function validatePathsInput(paths,cwd){if(!paths||paths.length===0)return{error:null,resolvedPath:cwd};if(containsControlChars(paths))return{error:"paths contains control characters",resolvedPath:null};if(containsPathTraversal(paths))return{error:"paths contains path traversal",resolvedPath:null};try{let resolvedPath=path359.resolve(paths),normalizedCwd=path359.resolve(cwd);if(!path359.resolve(resolvedPath).startsWith(normalizedCwd))return{error:"paths must be within the current working directory",resolvedPath:null};return{error:null,resolvedPath}}catch(e){return{error:e instanceof Error?e.message:"invalid paths",resolvedPath:null}}}function isSupportedExtension(filePath){let ext=path359.extname(filePath).toLowerCase();return SUPPORTED_EXTENSIONS3.has(ext)}function findSourceFiles3(dir,files=[]){let entries2;try{entries2=fs219.readdirSync(dir)}catch{return files}entries2.sort((a,b)=>a.toLowerCase().localeCompare(b.toLowerCase()));for(let entry of entries2){if(SKIP_DIRECTORIES5.has(entry))continue;let fullPath=path359.join(dir,entry),stat25;try{stat25=fs219.statSync(fullPath)}catch{continue}if(stat25.isDirectory())findSourceFiles3(fullPath,files);else if(stat25.isFile()){if(isSupportedExtension(fullPath))files.push(fullPath)}}return files}function parseTodoComments(content,filePath,tagsSet){let entries2=[],lines=content.split(`
|
|
7796
|
+
`),tagPattern=Array.from(tagsSet).map(escapeRegex2).join("|"),regex=new RegExp(`\\b(${tagPattern})\\b[:\\s]?`,"i");for(let i=0;i<lines.length;i++){let line=lines[i],match=regex.exec(line);if(match){let tag=match[1].toUpperCase(),priority=PRIORITY_MAP[tag]||"medium",text=line.substring(match.index+match[0].length).trim();if(text=text.replace(/^[/*\-\s]+/,""),text.length>MAX_TEXT_LENGTH)text=`${text.substring(0,MAX_TEXT_LENGTH-3)}...`;entries2.push({file:filePath,line:i+1,tag,text,priority})}}return entries2}var todo_extract=createSwarmTool({description:"Scan the codebase for TODO/FIXME/HACK/XXX/WARN/NOTE comments. Returns JSON with count by priority and sorted entries. Useful for identifying pending tasks and code issues. When task_id is provided and the todo_gate config is enabled (default), the high-priority scan is also recorded as todo_scan gate evidence for that task, consumed by check_gate_status and the phase-complete todo_gate gate.",args:{paths:exports_external.string().optional().describe("Directory or file to scan (default: entire project/cwd)"),tags:exports_external.string().optional().describe("Comma-separated tags to search for (default: TODO,FIXME,HACK,XXX,WARN,NOTE)"),task_id:exports_external.string().regex(/^\d+\.\d+(\.\d+)*$/,'Task ID must be in N.M or N.M.P format (e.g., "1.1", "2.3.1")').optional().describe("Optional task ID (N.M format). When provided and todo_gate is enabled, the high-priority (FIXME/HACK/XXX) count is recorded as todo_scan gate evidence in .swarm/evidence/{task_id}.json")},async execute(args2,directory){let paths,tags,taskId;try{if(args2&&typeof args2==="object"){let obj=args2;paths=typeof obj.paths==="string"?obj.paths:void 0,tags=typeof obj.tags==="string"?obj.tags:void 0,taskId=typeof obj.task_id==="string"?obj.task_id:void 0}}catch{}let cwd=directory,tagsInput=tags||"TODO,FIXME,HACK,XXX,WARN,NOTE",tagsValidationError=validateTagsInput(tagsInput);if(tagsValidationError){let errorResult={error:`invalid tags: ${tagsValidationError}`,total:0,byPriority:{high:0,medium:0,low:0},entries:[]};return JSON.stringify(errorResult,null,2)}let tagsList=tagsInput.split(",").map((t)=>t.trim().toUpperCase()).filter((t)=>t.length>0),tagsSet=new Set(tagsList);if(tagsSet.size===0)return JSON.stringify({error:"invalid tags: no valid tags provided",total:0,byPriority:{high:0,medium:0,low:0},entries:[]},null,2);let pathsInput=paths||cwd,{error:pathsError,resolvedPath}=validatePathsInput(pathsInput,cwd);if(pathsError){let errorResult={error:`invalid paths: ${pathsError}`,total:0,byPriority:{high:0,medium:0,low:0},entries:[]};return JSON.stringify(errorResult,null,2)}let scanPath=resolvedPath;if(!fs219.existsSync(scanPath)){let errorResult={error:`path not found: ${pathsInput}`,total:0,byPriority:{high:0,medium:0,low:0},entries:[]};return JSON.stringify(errorResult,null,2)}let filesToScan=[];if(fs219.statSync(scanPath).isFile())if(isSupportedExtension(scanPath))filesToScan.push(scanPath);else{let errorResult={error:`unsupported file extension: ${path359.extname(scanPath)}`,total:0,byPriority:{high:0,medium:0,low:0},entries:[]};return JSON.stringify(errorResult,null,2)}else findSourceFiles3(scanPath,filesToScan);let allEntries=[];for(let filePath of filesToScan)try{if(fs219.statSync(filePath).size>MAX_FILE_SIZE_BYTES10)continue;let content=fs219.readFileSync(filePath,"utf-8"),entries2=parseTodoComments(content,filePath,tagsSet);allEntries.push(...entries2)}catch{}allEntries.sort((a,b)=>{let priorityOrder={high:0,medium:1,low:2},priorityDiff=priorityOrder[a.priority]-priorityOrder[b.priority];if(priorityDiff!==0)return priorityDiff;return a.file.toLowerCase().localeCompare(b.file.toLowerCase())});let byPriority={high:allEntries.filter((e)=>e.priority==="high").length,medium:allEntries.filter((e)=>e.priority==="medium").length,low:allEntries.filter((e)=>e.priority==="low").length},result={total:allEntries.length,byPriority,entries:allEntries},coversHighPriorityClass=["FIXME","HACK","XXX"].every((tag)=>tagsSet.has(tag));if(taskId&&isStrictTaskId(taskId))if(!coversHighPriorityClass)log("todo_extract: todo_scan evidence recording skipped — custom tags omit the FIXME/HACK/XXX high-priority class");else try{let{config:config3}=loadPluginConfigWithMeta(directory);if(config3.todo_gate?.enabled!==!1){let detailLines=allEntries.filter((entry)=>entry.priority==="high").slice(0,MAX_RECORDED_DETAILS).map((entry)=>{return`${path359.relative(directory,entry.file)}:${entry.line} ${entry.tag} ${entry.text}`});await recordTodoScanEvidence(directory,taskId,{priority:"high",count:byPriority.high,details:detailLines,recorded_at:new Date().toISOString()})}}catch(recordError){log("todo_extract: todo_scan evidence recording skipped",recordError)}return JSON.stringify(result,null,2)}});init_zod();init_loader();init_schema();init_qa_gate_profile();init_task_gate_requirements();init_gate_evidence();import*as fs223 from"node:fs";import*as path363 from"node:path";init_bun_compat();init_git_executable();import*as fs221 from"node:fs";import*as path361 from"node:path";init_warning_buffer();init_bun_compat();init_git_executable();import*as fs220 from"node:fs";import*as path360 from"node:path";var _internals298={bunSpawn,resolveGitExecutableAsync};var _swarmGitExcludedChecked=!1;function fileCoversIgnorePatterns(content,patterns){for(let rawLine of content.split(`
|
|
7791
7797
|
`)){let line=rawLine.trim();if(line.startsWith("#")||line.length===0)continue;if(patterns.includes(line))return!0}return!1}function fileCoversSwarm(content){return fileCoversIgnorePatterns(content,[".swarm",".swarm/"])}function fileCoversSwarmWorktrees(content){return fileCoversIgnorePatterns(content,[".swarm-worktrees",".swarm-worktrees/"])}var ENSURE_SWARM_GIT_EXCLUDED_OUTER_TIMEOUT_MS=3000,ENSURE_SWARM_GIT_EXCLUDED_PER_CALL_TIMEOUT_MS=1500,GIT_SPAWN_OPTIONS={timeout:ENSURE_SWARM_GIT_EXCLUDED_PER_CALL_TIMEOUT_MS,stdin:"ignore",stdout:"pipe",stderr:"pipe"};async function ensureSwarmGitExcluded(directory,options={}){if(_swarmGitExcludedChecked)return;_swarmGitExcludedChecked=!0;let{quiet:_quiet=!1}=options;try{let gitExecutable=await _internals298.resolveGitExecutableAsync(),[[gitRootExitCode,gitRootOutput],[excludePathExitCode,excludePathRaw],checkIgnoreExitCode,checkIgnoreWorktreesExitCode]=await Promise.all([(async()=>{let proc=_internals298.bunSpawn([gitExecutable,"-C",directory,"rev-parse","--show-toplevel"],GIT_SPAWN_OPTIONS);try{return await Promise.all([proc.exited,proc.stdout.text()])}finally{try{proc.kill()}catch{}}})(),(async()=>{let proc=_internals298.bunSpawn([gitExecutable,"-C",directory,"rev-parse","--git-path","info/exclude"],GIT_SPAWN_OPTIONS);try{return await Promise.all([proc.exited,proc.stdout.text()])}finally{try{proc.kill()}catch{}}})(),(async()=>{let proc=_internals298.bunSpawn([gitExecutable,"-C",directory,"check-ignore","-q",".swarm/.gitkeep"],GIT_SPAWN_OPTIONS);try{return await proc.exited}finally{try{proc.kill()}catch{}}})(),(async()=>{let proc=_internals298.bunSpawn([gitExecutable,"-C",directory,"check-ignore","-q",".swarm-worktrees/.gitkeep"],GIT_SPAWN_OPTIONS);try{return await proc.exited}finally{try{proc.kill()}catch{}}})()]);if(gitRootExitCode!==0)return;if(!gitRootOutput.trim())return;if(excludePathExitCode!==0)return;let excludeRelPath=excludePathRaw.trim();if(!excludeRelPath)return;let excludePath=path360.isAbsolute(excludeRelPath)?excludeRelPath:path360.join(directory,excludeRelPath),swarmIgnored=checkIgnoreExitCode===0,worktreesIgnored=checkIgnoreWorktreesExitCode===0;if(!swarmIgnored||!worktreesIgnored)try{fs220.mkdirSync(path360.dirname(excludePath),{recursive:!0});let existing="";try{existing=fs220.readFileSync(excludePath,"utf8")}catch{}let needSwarm=!swarmIgnored&&!fileCoversSwarm(existing),needWorktrees=!worktreesIgnored&&!fileCoversSwarmWorktrees(existing),added=[];if(needSwarm)added.push(".swarm/");if(needWorktrees)added.push(".swarm-worktrees/");if(added.length>0)fs220.appendFileSync(excludePath,`
|
|
7792
7798
|
# opencode-swarm local runtime state (incl. worktree lanes, #2527)
|
|
7793
7799
|
${added.join(`
|
|
@@ -7821,7 +7827,7 @@ ${outputSummary}`,sessionId,"tool")}catch{}}}}init_utils();init_git_executable()
|
|
|
7821
7827
|
${tailContent.join(`
|
|
7822
7828
|
`)}
|
|
7823
7829
|
${footerLines.join(`
|
|
7824
|
-
`)}`}init_core_events();init_skill_propagation_gate();init_warning_buffer();init_canonical_root();init_cache_paths();import*as fs231 from"node:fs";import*as os30 from"node:os";import*as path373 from"node:path";import*as fs230 from"node:fs";import*as path372 from"node:path";var _internals311={realpathSyncNative:fs230.realpathSync.native};function hostWindowsPath(input){return input.replace(/^\/([a-zA-Z]):(?:[\\/]|$)/,(_m,d)=>`${d.toUpperCase()}:/`).replace(/^\/([a-zA-Z])(?:\/|$)/,(_m,d)=>`${d.toUpperCase()}:/`).replace(/^\/cygdrive\/([a-zA-Z])(?:\/|$)/,(_m,d)=>`${d.toUpperCase()}:/`).replace(/^\/mnt\/([a-zA-Z])(?:\/|$)/,(_m,d)=>`${d.toUpperCase()}:/`)}function hostNormalizePath(input){let resolved=path372.resolve(hostWindowsPath(input));try{return _internals311.realpathSyncNative(resolved)}catch{return resolved}}function hostNormalizePathPattern(pattern){if(pattern==="*")return pattern;let match=/^(.*)[\\/]\*$/.exec(pattern);if(!match)return hostNormalizePath(pattern);let dir=/^[A-Za-z]:$/.test(match[1])?`${match[1]}\\`:match[1];return path372.join(hostNormalizePath(dir),"*")}init_lane_context();class LastWinsRuleMap{entries=new Map;set(pattern,action2){this.entries.delete(pattern),this.entries.set(pattern,action2)}toObject(){return Object.fromEntries(this.entries)}}var SKILL_DIR_NAMES=["skill","skills"],HOST_HOME_SKILL_MARKERS=[".claude",".agents"];function laneDirectoryPattern(dir){return hostNormalizePathPattern(path373.join(dir,"*"))}function isExpressibleDirectory(dir){return!dir.includes("*")&&!dir.includes("?")}function push(out,seen,dir,reason){if(!dir)return;let resolved;try{resolved=path373.resolve(dir)}catch{return}if(!isExpressibleDirectory(resolved))return;let key2=canonicalRootKeyFresh(resolved);if(seen.has(key2))return;seen.add(key2),out.push({dir:resolved,pattern:laneDirectoryPattern(resolved),reason})}function buildLaneAllowlist(lane,configuredSkillPaths=[],configuredSkillUrls=[]){let out=[],seen=new Set;push(out,seen,lane.parentProjectPath,"parent project the lane is a git worktree of"),push(out,seen,lane.lanePath,"the lane worktree itself"),push(out,seen,getPluginConfigDir(),"OpenCode XDG config dir (host Global.Path.config)"),push(out,seen,getHostConfigDir(),"OpenCode config dir override (OPENCODE_CONFIG_DIR), when set");let tmpRoot=os30.tmpdir();if(push(out,seen,path373.join(tmpRoot,"opencode"),"OpenCode's own temp dir (host Global.Path.tmp)"),process.platform==="win32")push(out,seen,path373.join(tmpRoot,"swwt"),"shortened-worktree lane root (Windows path-budget fallback)");push(out,seen,path373.join(getHostDataDir(),"plans"),"OpenCode plan storage (host `plan` agent's native allow)");let home;try{home=os30.homedir()}catch{home=void 0}let projectRoots=[{base:lane.parentProjectPath,label:"parent project"},{base:lane.lanePath,label:"lane"}];for(let marker of HOST_HOME_SKILL_MARKERS){for(let{base,label}of projectRoots)push(out,seen,path373.resolve(base,marker,"skills"),`skill root (${label}): ${marker}/skills`);if(home)push(out,seen,path373.resolve(home,marker,"skills"),`skill root (user level): ~/${marker}/skills`)}let configSkillRoots=[{base:getPluginConfigDir(),label:"XDG config dir"},{base:getHostConfigDir(),label:"config dir override"},...projectRoots.map(({base,label})=>({base:path373.resolve(base,".opencode"),label:`${label} .opencode`})),...home?[{base:path373.join(home,".opencode"),label:"user-level .opencode"}]:[]];for(let{base,label}of configSkillRoots)for(let dirName of SKILL_DIR_NAMES)push(out,seen,path373.resolve(base,dirName),`skill root (${label}): ${dirName}/`);for(let relative91 of SKILL_SEARCH_ROOTS){for(let{base,label}of projectRoots)push(out,seen,path373.resolve(base,relative91),`skill root (${label}): ${relative91}`);if(home)push(out,seen,path373.resolve(home,relative91),`skill root (user level): ~/${relative91}`)}if((Array.isArray(configuredSkillUrls)?configuredSkillUrls:[]).some((u)=>typeof u==="string"&&u.trim()!==""))push(out,seen,getHostSkillCacheDir(),"URL-sourced skill cache (only because skills.urls is configured)");let skillPaths=Array.isArray(configuredSkillPaths)?configuredSkillPaths:[];for(let configured of skillPaths){if(typeof configured!=="string"||configured.trim()==="")continue;let expanded=configured.startsWith("~/")&&home?path373.join(home,configured.slice(2)):configured;push(out,seen,path373.isAbsolute(expanded)?expanded:path373.resolve(lane.lanePath,expanded),`configured skills.path: ${configured}`)}return out}function normalizeExisting(existing){if(typeof existing==="string")return{"*":existing};if(existing&&typeof existing==="object"&&!Array.isArray(existing))return{...existing};return}function buildLaneExternalDirectoryRules(mode,lane,existing,precomputedAllowlist){if(mode==="off")return null;let rules=new LastWinsRuleMap;if(rules.set("*","deny"),mode==="scoped_allow")for(let entry of precomputedAllowlist??buildLaneAllowlist(lane))rules.set(entry.pattern,"allow");let coercedAskPatterns=[],user=normalizeExisting(existing);if(user)for(let[pattern,action2]of Object.entries(user)){if(action2==="ask"){coercedAskPatterns.push(pattern),rules.set(pattern,"deny");continue}rules.set(pattern,action2)}return{rules:rules.toObject(),coercedAskPatterns}}function renderLanePermissionAdvisory(mode,lane,allowlist,coercedAskPatterns=[]){let scope=mode==="deny"?"ALL external directory access is denied in this lane":`external directory access is limited to ${allowlist.length} justified path(s)`,parts=[`[swarm] Worktree-lane permissions active for ${lane.lanePath} (worktree of ${lane.parentProjectPath}).`,`Policy worktree.lane_permissions="${mode}": ${scope}; anything else is denied rather than left pending.`,'A lane instance has no TUI attached, so an "ask" there can never be answered and would hang the lane forever.'];if(coercedAskPatterns.length>0)parts.push(`Your configured external_directory "ask" rule(s) [${coercedAskPatterns.join(", ")}] were treated as "deny" here for that reason — change them to "allow" if the lane needs those paths.`);return parts.push("To widen the allowlist, add the directory to opencode.json:",' { "permission": { "external_directory": { "<absolute-dir>/*": "allow" } } }','To restore the previous (hanging) behaviour, set worktree.lane_permissions to "off".'),parts.join(" ")}var _internals312={resolveLaneContext,addDeferredWarning,appendFileSync:fs231.appendFileSync,mkdirSync:fs231.mkdirSync};function readConfiguredSkillList(opencodeConfig,key2){let skills=opencodeConfig.skills;if(!skills||typeof skills!=="object"||Array.isArray(skills))return[];let value=skills[key2];if(!Array.isArray(value))return[];return value.filter((v)=>typeof v==="string"&&v.trim()!=="")}function downgradeAgentAskRules(opencodeConfig){let coerced=[],agents=opencodeConfig.agent;if(!agents||typeof agents!=="object"||Array.isArray(agents))return coerced;for(let[agentName,rawAgent]of Object.entries(agents)){if(!rawAgent||typeof rawAgent!=="object"||Array.isArray(rawAgent))continue;let rawPermission=rawAgent.permission;if(!rawPermission||typeof rawPermission!=="object"||Array.isArray(rawPermission))continue;let agentPermission=rawPermission,external3=agentPermission.external_directory;if(external3==="ask"){agentPermission.external_directory="deny",coerced.push(`${agentName}.*`);continue}if(!external3||typeof external3!=="object"||Array.isArray(external3))continue;let map3=external3;for(let[pattern,action2]of Object.entries(map3)){if(action2!=="ask")continue;map3[pattern]="deny",coerced.push(`${agentName}.${pattern}`)}}return coerced}function recordLanePermissionEvent(directory,event){try{appendCoreEventSync(directory,event)}catch{}}function applyLanePermissions(opencodeConfig,directory,mode){let lane=_internals312.resolveLaneContext(directory);if(!lane)return{lane:!1};let eventRoot=lane.lanePath;if(mode==="off")return recordLanePermissionEvent(eventRoot,{event:"lane_permissions",timestamp:new Date().toISOString(),decision:"skipped",mode,lanePath:lane.lanePath,parentProjectPath:lane.parentProjectPath,reason:'worktree.lane_permissions is "off"; external_directory asks in this lane cannot be answered and will hang'}),{lane:!0,mode};let permission=(()=>{let current=opencodeConfig.permission;if(current&&typeof current==="object"&&!Array.isArray(current))return current;let created={};return opencodeConfig.permission=created,created})(),agentCoerced=downgradeAgentAskRules(opencodeConfig),allowlist=mode==="scoped_allow"?buildLaneAllowlist(lane,readConfiguredSkillList(opencodeConfig,"paths"),readConfiguredSkillList(opencodeConfig,"urls")):[],build=buildLaneExternalDirectoryRules(mode,lane,permission.external_directory,allowlist);if(!build)return{lane:!0,mode};let{rules,coercedAskPatterns:topLevelCoerced}=build;permission.external_directory=rules;let coercedAskPatterns=[...topLevelCoerced,...agentCoerced];return _internals312.addDeferredWarning(renderLanePermissionAdvisory(mode,lane,allowlist,coercedAskPatterns)),recordLanePermissionEvent(eventRoot,{event:"lane_permissions",timestamp:new Date().toISOString(),decision:"applied",mode,lanePath:lane.lanePath,parentProjectPath:lane.parentProjectPath,allowlist:allowlist.map((entry)=>({pattern:entry.pattern,reason:entry.reason})),rules,coercedAskPatterns,remedy:'Add { "permission": { "external_directory": { "<absolute-dir>/*": "allow" } } } to opencode.json to widen the allowlist.'}),{lane:!0,mode,rules}}init_warning_buffer();init_archive_sqlite();init_fixtures();init_gate_ground_truth();init_pr_review_recovery();init_public_api();init_contracts2();init_factory();init_hash();init_patch();init_protected_path_policy();init_git_executable();init_path_security();init_project_boundary();init_contracts2();init_hash();import{spawn as spawn6}from"node:child_process";import{createHash as createHash115}from"node:crypto";import{existsSync as existsSync197,lstatSync as lstatSync44}from"node:fs";import*as path374 from"node:path";var SHA_RE=/^[a-f0-9]{40,64}$/,RECORD_VERSION2=1,GIT_TIMEOUT_MS13=3000,MAX_GIT_OUTPUT_BYTES3=32768,TEXT_DECODER=new TextDecoder("utf-8",{fatal:!0});function normalizeRelativePath2(value){return value.replace(/\\/g,"/").replace(/^\.\/+/,"")}function decodeQuotedGitPathToken(value){if(!value.startsWith('"')||!value.endsWith('"'))return null;let decoded="";for(let index=1;index<value.length-1;index++){let current=value[index];if(current!=="\\"){decoded+=current;continue}let next=value[index+1];if(!next)return null;if(/[0-7]/.test(next)){let octal=next,cursor=index+2;while(cursor<value.length-1&&octal.length<3){let digit=value[cursor];if(!/[0-7]/.test(digit))break;octal+=digit,cursor++}decoded+=String.fromCharCode(Number.parseInt(octal,8)),index+=octal.length;continue}decoded+=next==="t"?"\t":next==="n"?`
|
|
7830
|
+
`)}`}init_core_events();init_skill_propagation_gate();init_warning_buffer();init_canonical_root();init_cache_paths();import*as fs231 from"node:fs";import*as os30 from"node:os";import*as path373 from"node:path";import*as fs230 from"node:fs";import*as path372 from"node:path";var _internals311={realpathSyncNative:fs230.realpathSync.native};function hostWindowsPath(input){return input.replace(/^\/([a-zA-Z]):(?:[\\/]|$)/,(_m,d)=>`${d.toUpperCase()}:/`).replace(/^\/([a-zA-Z])(?:\/|$)/,(_m,d)=>`${d.toUpperCase()}:/`).replace(/^\/cygdrive\/([a-zA-Z])(?:\/|$)/,(_m,d)=>`${d.toUpperCase()}:/`).replace(/^\/mnt\/([a-zA-Z])(?:\/|$)/,(_m,d)=>`${d.toUpperCase()}:/`)}function hostNormalizePath(input){let resolved=path372.resolve(hostWindowsPath(input));try{return _internals311.realpathSyncNative(resolved)}catch{return resolved}}function hostNormalizePathPattern(pattern){if(pattern==="*")return pattern;let match=/^(.*)[\\/]\*$/.exec(pattern);if(!match)return hostNormalizePath(pattern);let dir=/^[A-Za-z]:$/.test(match[1])?`${match[1]}\\`:match[1];return path372.join(hostNormalizePath(dir),"*")}init_lane_context();class LastWinsRuleMap{entries=new Map;set(pattern,action2){this.entries.delete(pattern),this.entries.set(pattern,action2)}toObject(){return Object.fromEntries(this.entries)}}var SKILL_DIR_NAMES=["skill","skills"],HOST_HOME_SKILL_MARKERS=[".claude",".agents"];function laneDirectoryPattern(dir){return hostNormalizePathPattern(path373.join(dir,"*"))}function isExpressibleDirectory(dir){return!dir.includes("*")&&!dir.includes("?")}function push(out,seen,dir,reason){if(!dir)return;let resolved;try{resolved=path373.resolve(dir)}catch{return}if(!isExpressibleDirectory(resolved))return;let key2=canonicalRootKeyFresh(resolved);if(seen.has(key2))return;seen.add(key2),out.push({dir:resolved,pattern:laneDirectoryPattern(resolved),reason})}function buildLaneAllowlist(lane,configuredSkillPaths=[],configuredSkillUrls=[]){let out=[],seen=new Set;push(out,seen,lane.parentProjectPath,"parent project the lane is a git worktree of"),push(out,seen,lane.lanePath,"the lane worktree itself"),push(out,seen,getPluginConfigDir(),"OpenCode XDG config dir (host Global.Path.config)"),push(out,seen,getHostConfigDir(),"OpenCode config dir override (OPENCODE_CONFIG_DIR), when set");let tmpRoot=os30.tmpdir();if(push(out,seen,path373.join(tmpRoot,"opencode"),"OpenCode's own temp dir (host Global.Path.tmp)"),process.platform==="win32")push(out,seen,path373.join(tmpRoot,"swwt"),"shortened-worktree lane root (Windows path-budget fallback)");push(out,seen,path373.join(getHostDataDir(),"plans"),"OpenCode plan storage (host `plan` agent's native allow)");let home;try{home=os30.homedir()}catch{home=void 0}let projectRoots=[{base:lane.parentProjectPath,label:"parent project"},{base:lane.lanePath,label:"lane"}];for(let marker of HOST_HOME_SKILL_MARKERS){for(let{base,label}of projectRoots)push(out,seen,path373.resolve(base,marker,"skills"),`skill root (${label}): ${marker}/skills`);if(home)push(out,seen,path373.resolve(home,marker,"skills"),`skill root (user level): ~/${marker}/skills`)}let configSkillRoots=[{base:getPluginConfigDir(),label:"XDG config dir"},{base:getHostConfigDir(),label:"config dir override"},...projectRoots.map(({base,label})=>({base:path373.resolve(base,".opencode"),label:`${label} .opencode`})),...home?[{base:path373.join(home,".opencode"),label:"user-level .opencode"}]:[]];for(let{base,label}of configSkillRoots)for(let dirName of SKILL_DIR_NAMES)push(out,seen,path373.resolve(base,dirName),`skill root (${label}): ${dirName}/`);for(let relative92 of SKILL_SEARCH_ROOTS){for(let{base,label}of projectRoots)push(out,seen,path373.resolve(base,relative92),`skill root (${label}): ${relative92}`);if(home)push(out,seen,path373.resolve(home,relative92),`skill root (user level): ~/${relative92}`)}if((Array.isArray(configuredSkillUrls)?configuredSkillUrls:[]).some((u)=>typeof u==="string"&&u.trim()!==""))push(out,seen,getHostSkillCacheDir(),"URL-sourced skill cache (only because skills.urls is configured)");let skillPaths=Array.isArray(configuredSkillPaths)?configuredSkillPaths:[];for(let configured of skillPaths){if(typeof configured!=="string"||configured.trim()==="")continue;let expanded=configured.startsWith("~/")&&home?path373.join(home,configured.slice(2)):configured;push(out,seen,path373.isAbsolute(expanded)?expanded:path373.resolve(lane.lanePath,expanded),`configured skills.path: ${configured}`)}return out}function normalizeExisting(existing){if(typeof existing==="string")return{"*":existing};if(existing&&typeof existing==="object"&&!Array.isArray(existing))return{...existing};return}function buildLaneExternalDirectoryRules(mode,lane,existing,precomputedAllowlist){if(mode==="off")return null;let rules=new LastWinsRuleMap;if(rules.set("*","deny"),mode==="scoped_allow")for(let entry of precomputedAllowlist??buildLaneAllowlist(lane))rules.set(entry.pattern,"allow");let coercedAskPatterns=[],user=normalizeExisting(existing);if(user)for(let[pattern,action2]of Object.entries(user)){if(action2==="ask"){coercedAskPatterns.push(pattern),rules.set(pattern,"deny");continue}rules.set(pattern,action2)}return{rules:rules.toObject(),coercedAskPatterns}}function renderLanePermissionAdvisory(mode,lane,allowlist,coercedAskPatterns=[]){let scope=mode==="deny"?"ALL external directory access is denied in this lane":`external directory access is limited to ${allowlist.length} justified path(s)`,parts=[`[swarm] Worktree-lane permissions active for ${lane.lanePath} (worktree of ${lane.parentProjectPath}).`,`Policy worktree.lane_permissions="${mode}": ${scope}; anything else is denied rather than left pending.`,'A lane instance has no TUI attached, so an "ask" there can never be answered and would hang the lane forever.'];if(coercedAskPatterns.length>0)parts.push(`Your configured external_directory "ask" rule(s) [${coercedAskPatterns.join(", ")}] were treated as "deny" here for that reason — change them to "allow" if the lane needs those paths.`);return parts.push("To widen the allowlist, add the directory to opencode.json:",' { "permission": { "external_directory": { "<absolute-dir>/*": "allow" } } }','To restore the previous (hanging) behaviour, set worktree.lane_permissions to "off".'),parts.join(" ")}var _internals312={resolveLaneContext,addDeferredWarning,appendFileSync:fs231.appendFileSync,mkdirSync:fs231.mkdirSync};function readConfiguredSkillList(opencodeConfig,key2){let skills=opencodeConfig.skills;if(!skills||typeof skills!=="object"||Array.isArray(skills))return[];let value=skills[key2];if(!Array.isArray(value))return[];return value.filter((v)=>typeof v==="string"&&v.trim()!=="")}function downgradeAgentAskRules(opencodeConfig){let coerced=[],agents=opencodeConfig.agent;if(!agents||typeof agents!=="object"||Array.isArray(agents))return coerced;for(let[agentName,rawAgent]of Object.entries(agents)){if(!rawAgent||typeof rawAgent!=="object"||Array.isArray(rawAgent))continue;let rawPermission=rawAgent.permission;if(!rawPermission||typeof rawPermission!=="object"||Array.isArray(rawPermission))continue;let agentPermission=rawPermission,external3=agentPermission.external_directory;if(external3==="ask"){agentPermission.external_directory="deny",coerced.push(`${agentName}.*`);continue}if(!external3||typeof external3!=="object"||Array.isArray(external3))continue;let map3=external3;for(let[pattern,action2]of Object.entries(map3)){if(action2!=="ask")continue;map3[pattern]="deny",coerced.push(`${agentName}.${pattern}`)}}return coerced}function recordLanePermissionEvent(directory,event){try{appendCoreEventSync(directory,event)}catch{}}function applyLanePermissions(opencodeConfig,directory,mode){let lane=_internals312.resolveLaneContext(directory);if(!lane)return{lane:!1};let eventRoot=lane.lanePath;if(mode==="off")return recordLanePermissionEvent(eventRoot,{event:"lane_permissions",timestamp:new Date().toISOString(),decision:"skipped",mode,lanePath:lane.lanePath,parentProjectPath:lane.parentProjectPath,reason:'worktree.lane_permissions is "off"; external_directory asks in this lane cannot be answered and will hang'}),{lane:!0,mode};let permission=(()=>{let current=opencodeConfig.permission;if(current&&typeof current==="object"&&!Array.isArray(current))return current;let created={};return opencodeConfig.permission=created,created})(),agentCoerced=downgradeAgentAskRules(opencodeConfig),allowlist=mode==="scoped_allow"?buildLaneAllowlist(lane,readConfiguredSkillList(opencodeConfig,"paths"),readConfiguredSkillList(opencodeConfig,"urls")):[],build=buildLaneExternalDirectoryRules(mode,lane,permission.external_directory,allowlist);if(!build)return{lane:!0,mode};let{rules,coercedAskPatterns:topLevelCoerced}=build;permission.external_directory=rules;let coercedAskPatterns=[...topLevelCoerced,...agentCoerced];return _internals312.addDeferredWarning(renderLanePermissionAdvisory(mode,lane,allowlist,coercedAskPatterns)),recordLanePermissionEvent(eventRoot,{event:"lane_permissions",timestamp:new Date().toISOString(),decision:"applied",mode,lanePath:lane.lanePath,parentProjectPath:lane.parentProjectPath,allowlist:allowlist.map((entry)=>({pattern:entry.pattern,reason:entry.reason})),rules,coercedAskPatterns,remedy:'Add { "permission": { "external_directory": { "<absolute-dir>/*": "allow" } } } to opencode.json to widen the allowlist.'}),{lane:!0,mode,rules}}init_warning_buffer();init_archive_sqlite();init_fixtures();init_gate_ground_truth();init_pr_review_recovery();init_public_api();init_contracts2();init_factory();init_hash();init_patch();init_protected_path_policy();init_git_executable();init_path_security();init_project_boundary();init_contracts2();init_hash();import{spawn as spawn6}from"node:child_process";import{createHash as createHash115}from"node:crypto";import{existsSync as existsSync197,lstatSync as lstatSync44}from"node:fs";import*as path374 from"node:path";var SHA_RE=/^[a-f0-9]{40,64}$/,RECORD_VERSION2=1,GIT_TIMEOUT_MS13=3000,MAX_GIT_OUTPUT_BYTES3=32768,TEXT_DECODER=new TextDecoder("utf-8",{fatal:!0});function normalizeRelativePath2(value){return value.replace(/\\/g,"/").replace(/^\.\/+/,"")}function decodeQuotedGitPathToken(value){if(!value.startsWith('"')||!value.endsWith('"'))return null;let decoded="";for(let index=1;index<value.length-1;index++){let current=value[index];if(current!=="\\"){decoded+=current;continue}let next=value[index+1];if(!next)return null;if(/[0-7]/.test(next)){let octal=next,cursor=index+2;while(cursor<value.length-1&&octal.length<3){let digit=value[cursor];if(!/[0-7]/.test(digit))break;octal+=digit,cursor++}decoded+=String.fromCharCode(Number.parseInt(octal,8)),index+=octal.length;continue}decoded+=next==="t"?"\t":next==="n"?`
|
|
7825
7831
|
`:next==="r"?"\r":next==="b"?"\b":next==="f"?"\f":next,index++}return decoded}function parseGitPathToken(value,startIndex=0){if(startIndex>=value.length)return null;if(value[startIndex]==='"'){let index2=startIndex+1;while(index2<value.length){let current=value[index2];if(current==="\\"){index2+=2;continue}if(current==='"')return{token:value.slice(startIndex,index2+1),nextIndex:index2+1};index2++}return null}let index=startIndex;while(index<value.length&&value[index]!==" ")index++;return{token:value.slice(startIndex,index),nextIndex:index}}function parseGitPathValue(value,expectedPrefix){let trimmed=value.trim(),parsed=parseGitPathToken(trimmed);if(!parsed||parsed.nextIndex!==value.trim().length)return null;let decoded=parsed.token.startsWith('"')?decodeQuotedGitPathToken(parsed.token):parsed.token;if(!decoded)return null;if(decoded==="/dev/null")return decoded;if(expectedPrefix&&!decoded.startsWith(expectedPrefix))return null;return normalizeRelativePath2(expectedPrefix?decoded.slice(expectedPrefix.length):decoded)}function parseGitHeaderPath(line,headerPrefix,expectedPathPrefix){if(!line.startsWith(headerPrefix))return null;return parseGitPathValue(line.slice(headerPrefix.length),expectedPathPrefix)}function parseDiffGitLine(line){if(!line.startsWith("diff --git "))return null;let body=line.slice(11),oldToken=parseGitPathToken(body);if(!oldToken)return null;let cursor=oldToken.nextIndex;while(cursor<body.length&&body[cursor]===" ")cursor++;let newToken=parseGitPathToken(body,cursor);if(!newToken)return null;cursor=newToken.nextIndex;while(cursor<body.length&&body[cursor]===" ")cursor++;if(cursor!==body.length)return null;let oldDecoded=parseGitPathValue(oldToken.token,"a/"),newDecoded=parseGitPathValue(newToken.token,"b/");if(!oldDecoded||!newDecoded)return null;return{oldPath:oldDecoded,newPath:newDecoded}}function isWithinPrefix(relativePath2,prefix){return relativePath2===prefix||relativePath2.startsWith(`${prefix}/`)}function isAllowlisted(relativePath2,allowlist){return allowlist.some((prefix)=>isWithinPrefix(relativePath2,normalizeRelativePath2(prefix)))}function isProtectedPath4(relativePath2,extraProtectedPaths){return isPolicyProtectedPath(relativePath2,{additional:[".opencode",".claude",".agents","dist","evaluation-fixtures","src/services/skill-improver","src/services/skill-optimizer","src/evidence","scripts",...extraProtectedPaths]})}function parseCount(token){if(!token)return 1;let parsed=Number.parseInt(token,10);return Number.isFinite(parsed)&&parsed>=0?parsed:-1}function validateParsedHunk(hunk){if(hunk.oldCount<0||hunk.newCount<0)return!1;if(hunk.oldCount===0?hunk.oldStart<0:hunk.oldStart<1)return!1;if(hunk.newCount===0?hunk.newStart<0:hunk.newStart<1)return!1;let oldSeen=0,newSeen=0,previousWasContent=!1;for(let line of hunk.lines){if(line==="\"){if(!previousWasContent)return!1;previousWasContent=!1;continue}let marker=line[0];if(marker===" ")oldSeen++,newSeen++;else if(marker==="-")oldSeen++;else if(marker==="+")newSeen++;else return!1;previousWasContent=!0}return oldSeen===hunk.oldCount&&newSeen===hunk.newCount}function validateHunkOrdering(hunks){let nextOldAnchor=0,nextNewAnchor=0;for(let hunk of hunks){let oldAnchor=hunk.oldCount===0?hunk.oldStart:hunk.oldStart-1,newAnchor=hunk.newCount===0?hunk.newStart:hunk.newStart-1;if(oldAnchor<nextOldAnchor||newAnchor<nextNewAnchor)return!1;nextOldAnchor=oldAnchor+hunk.oldCount,nextNewAnchor=newAnchor+hunk.newCount}return!0}function parsePatch(patch2){let lines=patch2.replace(/\r\n/g,`
|
|
7826
7832
|
`).split(`
|
|
7827
7833
|
`),files=[],index=0;while(index<lines.length){let line=lines[index];if(!line){index++;continue}let diffLine=parseDiffGitLine(line);if(!diffLine)return null;let{oldPath,newPath}=diffLine;index++;let operation=oldPath===newPath?"modify":"rename",declaredOldPath=oldPath,declaredNewPath=newPath,oldMode,newMode,oldObjectId,newObjectId;while(index<lines.length){let header=lines[index];if(!header){index++;continue}if(parseDiffGitLine(header))break;if(header.startsWith("new file mode ")){operation="add",newMode=header.slice(14),index++;continue}if(header.startsWith("deleted file mode ")){operation="delete",oldMode=header.slice(18),index++;continue}if(header.startsWith("rename from ")){operation="rename";let parsedPath=parseGitPathValue(header.slice(12));if(!parsedPath||parsedPath==="/dev/null")return null;declaredOldPath=parsedPath,index++;continue}if(header.startsWith("rename to ")){let parsedPath=parseGitPathValue(header.slice(10));if(!parsedPath||parsedPath==="/dev/null")return null;declaredNewPath=parsedPath,index++;continue}if(header.startsWith("copy from ")){operation="copy";let parsedPath=parseGitPathValue(header.slice(10));if(!parsedPath||parsedPath==="/dev/null")return null;declaredOldPath=parsedPath,index++;continue}if(header.startsWith("copy to ")){let parsedPath=parseGitPathValue(header.slice(8));if(!parsedPath||parsedPath==="/dev/null")return null;declaredNewPath=parsedPath,index++;continue}if(header.startsWith("old mode ")){operation="mode",oldMode=header.slice(9),index++;continue}if(header.startsWith("new mode ")){newMode=header.slice(9),index++;continue}if(header.startsWith("similarity index ")||header.startsWith("dissimilarity index ")){index++;continue}if(header==="GIT binary patch"||header.startsWith("Binary files "))return null;if(header.startsWith("index ")){let objectMatch=/^index ([a-f0-9]{7,64})\.\.([a-f0-9]{7,64})(?: [0-7]{6})?$/.exec(header);if(!objectMatch)return null;oldObjectId=objectMatch[1],newObjectId=objectMatch[2],index++;continue}let parsedOldHeader=parseGitHeaderPath(header,"--- ",operation==="add"?void 0:"a/"),parsedNewHeader=parseGitHeaderPath(String(lines[index+1]??""),"+++ ",operation==="delete"?void 0:"b/"),expectedOld=operation==="add"?"/dev/null":declaredOldPath,expectedNew=operation==="delete"?"/dev/null":declaredNewPath;if(parsedOldHeader!==expectedOld)return null;if(parsedNewHeader!==expectedNew)return null;index+=2;break}let hunks=[];while(index<lines.length){let hunkHeader=lines[index];if(!hunkHeader){index++;continue}if(parseDiffGitLine(hunkHeader))break;let hunkMatch=/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/.exec(hunkHeader);if(!hunkMatch)return null;index++;let hunkLines=[];while(index<lines.length){let hunkLine=lines[index];if(hunkLine===""){index++;continue}if(hunkLine.startsWith("@@ -")||parseDiffGitLine(hunkLine))break;if(hunkLine.startsWith(" ")||hunkLine.startsWith("+")||hunkLine.startsWith("-")||hunkLine==="\"){hunkLines.push(hunkLine),index++;continue}return null}if(hunks.push({oldStart:Number.parseInt(hunkMatch[1],10),oldCount:parseCount(hunkMatch[2]),newStart:Number.parseInt(hunkMatch[3],10),newCount:parseCount(hunkMatch[4]),lines:hunkLines}),!validateParsedHunk(hunks[hunks.length-1]))return null}if(hunks.length===0&&operation!=="mode"&&operation!=="rename"&&operation!=="copy")return null;if(!validateHunkOrdering(hunks))return null;files.push({oldRelativePath:operation==="add"?null:declaredOldPath,relativePath:operation==="delete"?declaredOldPath:declaredNewPath,operation,oldMode,newMode,oldObjectId,newObjectId,hunks})}return files.length>0?{files}:null}function splitTextLines(text){let normalized=text.replace(/\r\n/g,`
|