opencode-swarm 7.184.8 → 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/.opencode/skills/issue-ingest/SKILL.md +1 -1
- package/README.md +6 -3
- 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-r66d0hrv.js → coder-settlement-b47vmcm9.js} +11 -11
- package/dist/cli/{config-doctor-4283xkfv.js → config-doctor-3j3m2ccc.js} +3 -3
- package/dist/cli/{core-mz92tdmh.js → core-td5kj2w8.js} +4 -4
- package/dist/cli/{curation-policy-k43q6b91.js → curation-policy-xe77n9zj.js} +4 -4
- package/dist/cli/{curator-x826phy6.js → curator-c7we2apv.js} +38 -38
- package/dist/cli/{curator-drift-apjkb9ef.js → curator-drift-wxyhgz7y.js} +9 -9
- package/dist/cli/curator-llm-factory-1260n9ty.js +75 -0
- package/dist/cli/{evidence-summary-service-5tbqybse.js → evidence-summary-service-2t1ttdgj.js} +17 -17
- package/dist/cli/{gate-evidence-v6g6bwm5.js → gate-evidence-5w2q1h5w.js} +8 -6
- package/dist/cli/guardrail-explain-qeywnmza.js +76 -0
- package/dist/cli/{guardrail-log-nqg3kd9m.js → guardrail-log-5zwqdhaf.js} +7 -7
- package/dist/cli/{guardrail-reset-vyn98as6.js → guardrail-reset-qnq1swzf.js} +38 -38
- package/dist/cli/{hive-promoter-y7ddjf37.js → hive-promoter-c3c6tz3b.js} +38 -38
- package/dist/cli/{index-b1v0zxnh.js → index-07fqfseh.js} +2 -2
- package/dist/cli/{index-qeqn241m.js → index-0ajyhjht.js} +1 -1
- package/dist/cli/{index-4hrc0gmy.js → index-0d7e94zg.js} +7 -7
- package/dist/cli/{index-2t4zv1ag.js → index-0mj7hc2z.js} +2 -2
- package/dist/cli/{index-h5y74yhy.js → index-19e61hgv.js} +12 -12
- package/dist/cli/{index-zce97jmt.js → index-1g2bm6ht.js} +2 -2
- package/dist/cli/{index-n2md4hfb.js → index-260174fq.js} +4 -4
- package/dist/cli/{index-e1zrgvqg.js → index-35cdceqf.js} +1 -1
- package/dist/cli/{index-65xbb93y.js → index-3rfc2v1d.js} +3 -3
- package/dist/cli/{index-gkrsy2vy.js → index-3wgvpxmv.js} +96 -90
- package/dist/cli/{index-5rpg65jz.js → index-45h58v8d.js} +7 -7
- package/dist/cli/{index-ezagem2g.js → index-48jvqqfa.js} +2 -2
- package/dist/cli/{index-239r2znx.js → index-4szb7qpv.js} +37 -6
- package/dist/cli/{index-z9b6abs8.js → index-54f1payv.js} +2 -2
- package/dist/cli/{index-t0mb5a9p.js → index-5m1b70z3.js} +1 -1
- package/dist/cli/{index-tr83fkh2.js → index-7849gy4s.js} +5 -5
- package/dist/cli/{index-zcka2cmb.js → index-8n2dh26k.js} +1 -1
- package/dist/cli/{index-q858w0wz.js → index-95vytkv6.js} +4 -4
- package/dist/cli/{index-qat6caah.js → index-9jz73x8x.js} +38 -38
- package/dist/cli/{index-rmspt7xm.js → index-aae38s4x.js} +1 -1
- package/dist/cli/{index-bn604f1g.js → index-b6saxkqj.js} +2 -2
- package/dist/cli/{index-q39ecyaq.js → index-be5h97z8.js} +1 -1
- package/dist/cli/{index-cq0ft5wb.js → index-bhj3zx43.js} +1 -1
- package/dist/cli/{index-pv82gzpy.js → index-bt1k1ek3.js} +1 -1
- package/dist/cli/{index-w9517q25.js → index-cjh92zm9.js} +40 -40
- package/dist/cli/{index-rdsrbanf.js → index-djnxehe7.js} +6 -6
- package/dist/cli/{index-7xv2hvr6.js → index-dqpq8m9w.js} +2 -2
- package/dist/cli/{index-0nzrz0a7.js → index-f336fv53.js} +4 -4
- package/dist/cli/{index-psdt9tg0.js → index-fn1y9jpv.js} +3 -3
- package/dist/cli/{index-6grdzhtz.js → index-fxtgxe04.js} +7 -7
- package/dist/cli/{index-98a0rxby.js → index-gnryhmak.js} +1 -1
- package/dist/cli/{index-g2r6t7by.js → index-hk0eh9qb.js} +1 -1
- package/dist/cli/{index-6wtf98v6.js → index-hs26e3k6.js} +2 -2
- package/dist/cli/{index-xqxqepsy.js → index-j4efx148.js} +2 -2
- package/dist/cli/{index-s95ghsy1.js → index-kg2mb1m5.js} +1 -1
- package/dist/cli/{index-1t2ctwkd.js → index-nh5fxxc9.js} +1 -1
- package/dist/cli/{index-6d2fdc4g.js → index-pj877ads.js} +5 -5
- package/dist/cli/{index-14j1jkyy.js → index-q7q00ppx.js} +6 -6
- package/dist/cli/{index-cnm1e97z.js → index-ta2kp4xy.js} +5 -5
- package/dist/cli/{index-dqb9528c.js → index-thcyqqdq.js} +2 -2
- package/dist/cli/{index-qntx5f14.js → index-tzyppdv7.js} +3 -3
- package/dist/cli/{index-fr6x6vn2.js → index-x119gdak.js} +1 -1
- package/dist/cli/{index-kdkp3zds.js → index-yyvkeev1.js} +4 -4
- package/dist/cli/index.js +39 -39
- package/dist/cli/{knowledge-escalator-2f5kkezr.js → knowledge-escalator-912nwxb4.js} +12 -12
- package/dist/cli/{knowledge-events-4qewgabr.js → knowledge-events-hvzj872f.js} +10 -10
- package/dist/cli/{knowledge-link-xw6vsbx3.js → knowledge-link-8tetyje0.js} +3 -3
- package/dist/cli/{knowledge-store-04jxzbz5.js → knowledge-store-sqx0axb6.js} +4 -4
- package/dist/cli/{knowledge-validator-x9g76cgh.js → knowledge-validator-d8m7p2vg.js} +6 -6
- package/dist/cli/{mcp-zcmpnd9g.js → mcp-nxxy0dq0.js} +1 -1
- package/dist/cli/{model-preflight-y2wvmkmw.js → model-preflight-2mmep72y.js} +38 -38
- package/dist/cli/{pending-delegations-44cwy210.js → pending-delegations-fat9r7w1.js} +10 -10
- package/dist/cli/{pr-subscriptions-hmca4kyq.js → pr-subscriptions-8xv7gaeb.js} +10 -10
- package/dist/cli/{pr-workflow-gate-anzvkr87.js → pr-workflow-gate-g9exsspv.js} +38 -38
- package/dist/cli/{runner-pvdhxh74.js → runner-ff0bj9w0.js} +4 -4
- package/dist/cli/{scan-cursor-t020wayb.js → scan-cursor-h9tza4z6.js} +5 -5
- package/dist/cli/{schema-q5xjg4ww.js → schema-1p9cw863.js} +2 -2
- package/dist/cli/{scope-persistence-yk8bhh58.js → scope-persistence-xv6b7daq.js} +14 -14
- package/dist/cli/{server-z5r7yyg7.js → server-z5401cje.js} +40 -38
- package/dist/cli/{skill-generator-gma98zj6.js → skill-generator-72n07p92.js} +14 -14
- package/dist/cli/{snapshot-coordination-init-5hgtne5d.js → snapshot-coordination-init-xjyv8kxx.js} +38 -38
- package/dist/cli/{speckit-checkoff-5p71mpy2.js → speckit-checkoff-828xrjfd.js} +5 -5
- package/dist/cli/{workspace-snapshot-553c6cd3.js → workspace-snapshot-nrbvjh1c.js} +3 -3
- package/dist/cli/{worktree-collision-ownership-z4hg58zq.js → worktree-collision-ownership-cr6vv3xk.js} +11 -11
- package/dist/cli/{worktree-isolation-505j9dhm.js → worktree-isolation-6yycqkc6.js} +38 -38
- package/dist/gate-evidence.d.ts +34 -0
- package/dist/hooks/issue-trace-reducer.d.ts +20 -2
- package/dist/hooks/issue-trace-state.d.ts +6 -2
- package/dist/hooks/issue-trace.d.ts +2 -0
- package/dist/index.js +28 -21
- 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-79ee75n4.js +0 -75
- package/dist/cli/guardrail-explain-xdztayqz.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.8",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:442"],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*)
|
|
@@ -994,15 +994,16 @@ ${line}`:line,"utf-8");let sinceCheck=(appendCheckCounters.get(key)??0)+1;if(sin
|
|
|
994
994
|
`}}if(!tasksText.trim())return null;let trimmed=tasksText.trim();if(trimmed.length<=maxChars)return trimmed;return`${trimmed.slice(0,maxChars)}...`}function extractPatterns(contextContent,maxChars=500){if(!contextContent)return null;let lines=contextContent.split(`
|
|
995
995
|
`),patternsText="",inPatternsSection=!1;for(let line of lines){if(line.trim()==="## Patterns"){inPatternsSection=!0;continue}if(inPatternsSection){if(line.startsWith("## "))break;if(line.startsWith("- "))patternsText+=`${line}
|
|
996
996
|
`}}if(!patternsText.trim())return null;let trimmed=patternsText.trim();if(trimmed.length<=maxChars)return trimmed;return`${trimmed.slice(0,maxChars)}...`}function extractCurrentPhaseFromPlan(plan){let phaseId=resolveActivePhaseId(plan),phase=plan.phases.find((p)=>p.id===phaseId);if(!phase)return null;let statusText={pending:"PENDING",in_progress:"IN PROGRESS",complete:"COMPLETE",blocked:"BLOCKED"}[phase.status]||"PENDING";return`Phase ${phase.id}: ${phase.name} [${statusText}]`}function extractCurrentTaskFromPlan(plan){let phase=plan.phases.find((p)=>p.id===resolveActivePhaseId(plan));if(!phase)return null;let inProgress=phase.tasks.find((t)=>t.status==="in_progress");if(inProgress){let deps=inProgress.depends.length>0?` (depends: ${inProgress.depends.join(", ")})`:"";return`- [ ] ${inProgress.id}: ${inProgress.description} [${inProgress.size.toUpperCase()}]${deps} ← CURRENT`}let pending=phase.tasks.find((t)=>t.status==="pending");if(pending){let deps=pending.depends.length>0?` (depends: ${pending.depends.join(", ")})`:"";return`- [ ] ${pending.id}: ${pending.description} [${pending.size.toUpperCase()}]${deps}`}return null}function extractIncompleteTasksFromPlan(plan,maxChars=500){let phase=plan.phases.find((p)=>p.id===resolveActivePhaseId(plan));if(!phase)return null;let incomplete=phase.tasks.filter((t)=>t.status==="pending"||t.status==="in_progress");if(incomplete.length===0)return null;let text=incomplete.map((t)=>{let deps=t.depends.length>0?` (depends: ${t.depends.join(", ")})`:"",marker=t.status==="in_progress"?" ← CURRENT":"";return`- [ ] ${t.id}: ${t.description} [${t.size.toUpperCase()}]${deps}${marker}`}).join(`
|
|
997
|
-
`);if(text.length<=maxChars)return text;return`${text.slice(0,maxChars)}...`}function extractPlanCursor(planContent,options){let maxTokens=options?.maxTokens??1500,maxChars=estimateCharsForTokens(maxTokens),lookaheadCount=options?.lookaheadTasks??2;if(!planContent||typeof planContent!=="string")return`[SWARM PLAN CURSOR]
|
|
997
|
+
`);if(text.length<=maxChars)return text;return`${text.slice(0,maxChars)}...`}function extractPlanCursor(planContent,options){let maxTokens=options?.maxTokens??1500,maxChars=estimateCharsForTokens(maxTokens),lookaheadCount=options?.lookaheadTasks??2;if(planContent&&typeof planContent==="string")planContent=sanitizeContextText(planContent);if(!planContent||typeof planContent!=="string")return`[SWARM PLAN CURSOR]
|
|
998
998
|
No plan content available. Start by creating a .swarm/plan.md file.
|
|
999
999
|
[/SWARM PLAN CURSOR]`;let lines=planContent.split(`
|
|
1000
1000
|
`),result=[];result.push("[SWARM PLAN CURSOR]");let phases=[],currentPhase=null,inPhase=!1;for(let i=0;i<lines.length;i++){let line=lines[i],trimmed=line.trim(),phaseMatch=trimmed.match(/^## Phase (\d+):?\s*(.*?)\s*\[(COMPLETE|IN PROGRESS|PENDING|BLOCKED)\]/i);if(phaseMatch){if(currentPhase)phases.push(currentPhase);let phaseNum=parseInt(phaseMatch[1],10),phaseTitle=phaseMatch[2]?.trim()||"",status=phaseMatch[3].toUpperCase();currentPhase={number:phaseNum,title:phaseTitle,status,contentLines:[]},inPhase=!0;continue}if(inPhase&&(line.startsWith("## ")||trimmed==="---")){if(currentPhase)phases.push(currentPhase);currentPhase=null,inPhase=!1;continue}if(currentPhase&&inPhase&&trimmed)currentPhase.contentLines.push(line)}if(currentPhase)phases.push(currentPhase);if(phases.length===0)return result.push("No phases found in plan."),result.push("[/SWARM PLAN CURSOR]"),result.join(`
|
|
1001
1001
|
`);let inProgressPhase=phases.find((p)=>p.status==="IN PROGRESS"),completePhases=phases.filter((p)=>p.status==="COMPLETE"),pendingPhases=phases.filter((p)=>p.status==="PENDING");if(completePhases.length>0){let recentComplete=completePhases.slice(-5);if(completePhases.length>5)result.push(""),result.push(`## Earlier Phases (${completePhases.length-5} more)`),result.push(`- Phase 1-${completePhases.length-5}: Complete`);result.push(""),result.push("## Completed Phases");for(let phase of recentComplete){let taskLines=phase.contentLines.filter((l)=>l.trim().startsWith("- [")).map((l)=>l.replace(/^- \[[ xX]\]\s*/,"").replace(/\s*\[.*?\]/g,"").trim()).slice(0,3),taskSummary=taskLines.length>0?taskLines.join(", "):"All tasks complete";result.push(`- Phase ${phase.number}: ${phase.title}`),result.push(` - ${taskSummary}`)}}let incompleteTasks=inProgressPhase?inProgressPhase.contentLines.filter((l)=>l.trim().startsWith("- [ ]")).map((l)=>l.trim()):[];if(inProgressPhase)if(result.push(""),result.push(`## Phase ${inProgressPhase.number} [IN PROGRESS]`),result.push(`- ${inProgressPhase.title}`),incompleteTasks.length>0){let currentTask=incompleteTasks[0];result.push(""),result.push(`- Current: ${currentTask.replace("- [ ] ","")}`);let lookahead=incompleteTasks.slice(1,1+lookaheadCount);for(let i=0;i<lookahead.length;i++)result.push(`- Next: ${lookahead[i].replace("- [ ] ","")}`)}else result.push("- (No pending tasks)");let nextPending=pendingPhases[0];if(nextPending)result.push(""),result.push(`## Phase ${nextPending.number} [PENDING]`),result.push(`- ${nextPending.title}`);let output=result.join(`
|
|
1002
1002
|
`);if(output+=`
|
|
1003
1003
|
[/SWARM PLAN CURSOR]`,output.length>maxChars){let compactResult=[];if(compactResult.push("[SWARM PLAN CURSOR]"),completePhases.length>0){compactResult.push("## Completed Phases");let recentCompact=completePhases.slice(-3);for(let phase of recentCompact){let taskLines=phase.contentLines.filter((l)=>l.trim().startsWith("- [")).map((l)=>l.replace(/^- \[[ xX]\]\s*/,"").replace(/\s*\[.*?\]/g,"").trim()).slice(0,1),taskSummary=taskLines.length>0?taskLines[0]:"Complete";compactResult.push(`- Phase ${phase.number}: ${taskSummary}`)}if(completePhases.length>3)compactResult.push(`- Earlier: Phase 1-${completePhases.length-3} complete`)}if(inProgressPhase)if(compactResult.push(""),compactResult.push(`## Phase ${inProgressPhase.number} [IN PROGRESS]`),compactResult.push(`- ${inProgressPhase.title}`),incompleteTasks.length>0){let truncateTask=(task)=>{let text=task.replace("- [ ] ","");return text.length>60?`${text.slice(0,57)}...`:text};compactResult.push(`- Current: ${truncateTask(incompleteTasks[0])}`);let lookahead=incompleteTasks.slice(1,1+Math.min(lookaheadCount,1));for(let task of lookahead)compactResult.push(`- Next: ${truncateTask(task)}`)}else compactResult.push("- (No pending tasks)");if(nextPending)compactResult.push(""),compactResult.push(`## Phase ${nextPending.number} [PENDING]`),compactResult.push(`- ${nextPending.title}`);compactResult.push("[/SWARM PLAN CURSOR]"),output=compactResult.join(`
|
|
1004
|
-
`)}if(output.length>maxChars){let cap=Math.max(0,maxChars-21-4)
|
|
1005
|
-
[/SWARM PLAN CURSOR]`}return output}function resolvePlanCursorControls(planCursor){let maxTokens=planCursor?.max_tokens??1500,lookaheadTasks=planCursor?.lookahead_tasks??2;return{enabled:planCursor?.enabled??!0,maxTokens:Math.min(4000,Math.max(500,Math.round(maxTokens))),lookaheadTasks:Math.min(5,Math.max(0,Math.round(lookaheadTasks)))}}var init_extractors=__esm(()=>{init_plan_schema();init_utils2()});import{createHash as createHash34}from"node:crypto";import*as fs48 from"node:fs";import*as path75 from"node:path";function hasControlCharacter(value){for(let index=0;index<value.length;index+=1){let code=value.charCodeAt(index);if(code<=31||code===127)return!0}return!1}function normalizedProjectFile(directory,file2){if(file2.includes("\x00")||hasControlCharacter(file2))return null;let root=path75.resolve(directory),absolute=path75.resolve(root,file2),relative18=path75.relative(root,absolute).replaceAll("\\","/");if(!relative18||relative18===".."||relative18.startsWith("../")||path75.isAbsolute(relative18))return null;return relative18}function isWithinRoot2(root,candidate){let relative18=path75.relative(root,candidate);return relative18===""||relative18!==".."&&!relative18.startsWith(`..${path75.sep}`)&&!path75.isAbsolute(relative18)}function deletedPathIsContained(canonicalRoot,absolute){let current=path75.dirname(absolute);for(;;){try{let canonical=_internals69.realpathSync(current);return canonicalRoot===canonical||isWithinRoot2(canonicalRoot,canonical)}catch(error49){if(error49.code!=="ENOENT")return!1}let parent=path75.dirname(current);if(parent===current)return!1;current=parent}}function sameSnapshot(left,right){return(!((left.dev!==0n||left.ino!==0n)&&(right.dev!==0n||right.ino!==0n))||left.dev===right.dev&&left.ino===right.ino)&&left.size===right.size&&left.mtimeNs===right.mtimeNs&&left.ctimeNs===right.ctimeNs}function captureReviewerScopeFileFingerprint(directory,file2,options={}){if(typeof directory!=="string"||typeof file2!=="string")return{kind:"capture_failed",file:typeof file2==="string"?file2:"",code:"invalid_request",retryable:!1};if(file2.includes("\x00")||hasControlCharacter(file2))return{kind:"capture_failed",file:file2,code:"invalid_request",retryable:!1};let normalized=normalizedProjectFile(directory,file2);if(!normalized)return{kind:"capture_failed",file:file2,code:"outside_workspace",retryable:!1};let canonicalRoot,canonicalParent,absolute=path75.resolve(directory,normalized);try{canonicalRoot=_internals69.realpathSync(path75.resolve(directory))}catch{return{kind:"capture_failed",file:normalized,code:"outside_workspace",retryable:!1}}try{canonicalParent=_internals69.realpathSync(path75.dirname(absolute))}catch(error49){if(error49.code==="ENOENT"){let secondObservation=null,secondFailed=!1;try{secondObservation=_internals69.realpathSync(path75.dirname(absolute))}catch(secondError){if(secondError.code!=="ENOENT")return{kind:"capture_failed",file:normalized,code:"unreadable",retryable:!1,detail:secondError.code};secondFailed=!0}if(!secondFailed)canonicalParent=secondObservation;else{try{return _internals69.lstat(absolute),{kind:"capture_failed",file:normalized,code:"file_changed_during_capture",retryable:!0,detail:"parent enoent unstable"}}catch(fileError){if(fileError.code!=="ENOENT")return{kind:"capture_failed",file:normalized,code:"unreadable",retryable:!1,detail:fileError.code}}return deletedPathIsContained(canonicalRoot,absolute)?{kind:"captured_deleted",file:normalized}:{kind:"capture_failed",file:normalized,code:"outside_workspace",retryable:!1}}}else return{kind:"capture_failed",file:normalized,code:"unreadable",retryable:!1,detail:error49.code}}if(!isWithinRoot2(canonicalRoot,canonicalParent))return{kind:"capture_failed",file:normalized,code:"outside_workspace",retryable:!1};let before;try{before=_internals69.lstat(absolute)}catch(error49){if(error49.code==="ENOENT")return deletedPathIsContained(canonicalRoot,absolute)?{kind:"captured_deleted",file:normalized}:{kind:"capture_failed",file:normalized,code:"outside_workspace",retryable:!1};return{kind:"capture_failed",file:normalized,code:"unreadable",retryable:!1,detail:error49.code}}if(before.isSymbolicLink())return{kind:"capture_failed",file:normalized,code:"symlink_or_reparse",retryable:!1};try{let canonicalTarget=_internals69.realpathSync(absolute);if(!isWithinRoot2(canonicalRoot,canonicalTarget)||path75.dirname(canonicalTarget)!==canonicalParent)return{kind:"capture_failed",file:normalized,code:"outside_workspace",retryable:!1}}catch{return{kind:"capture_failed",file:normalized,code:"unreadable",retryable:!1}}if(!before.isFile()||!Number.isSafeInteger(before.size)||before.size<0)return{kind:"capture_failed",file:normalized,code:"non_regular",retryable:!1};let openFlags=fs48.constants.O_RDONLY|(process.platform==="win32"?0:fs48.constants.O_NOFOLLOW),beforeBigInt;try{beforeBigInt=_internals69.lstat(absolute,{bigint:!0})}catch{return{kind:"capture_failed",file:normalized,code:"file_changed_during_capture",retryable:!0}}let fd;try{fd=_internals69.open(absolute,openFlags)}catch(error49){let code=error49.code;if(code==="ENOENT"||code==="ELOOP")return{kind:"capture_failed",file:normalized,code:"file_changed_during_capture",retryable:!0,detail:code};if(code==="EMFILE"||code==="ENFILE")return{kind:"capture_failed",file:normalized,code:"capture_deadline",retryable:!0,detail:code};return{kind:"capture_failed",file:normalized,code:"unreadable",retryable:!1,detail:code}}try{let openedBefore=_internals69.fstat(fd,{bigint:!0});if(!openedBefore.isFile())return{kind:"capture_failed",file:normalized,code:"non_regular",retryable:!1};if(!sameSnapshot(beforeBigInt,openedBefore))return{kind:"capture_failed",file:normalized,code:"file_changed_during_capture",retryable:!0};let hash3=createHash34("sha256"),chunk=Buffer.alloc(REVIEWER_SCOPE_CAPTURE_CHUNK_BYTES),totalBytes=0;for(;;){if(options.deadlineAt!==void 0&&_internals69.now()>options.deadlineAt)return{kind:"capture_failed",file:normalized,code:"capture_deadline",retryable:!0};let bytesRead;try{bytesRead=_internals69.read(fd,chunk,0,chunk.byteLength,null)}catch(error49){let code=error49.code;return{kind:"capture_failed",file:normalized,code:"unreadable",retryable:!1,detail:code}}if(bytesRead===0)break;totalBytes+=bytesRead,hash3.update(bytesRead===chunk.byteLength?chunk:chunk.subarray(0,bytesRead))}let openedAfter=_internals69.fstat(fd,{bigint:!0});if(!sameSnapshot(openedBefore,openedAfter))return{kind:"capture_failed",file:normalized,code:"file_changed_during_capture",retryable:!0};if(totalBytes!==Number(openedBefore.size))return{kind:"capture_failed",file:normalized,code:"file_changed_during_capture",retryable:!0};let pathAfter;try{pathAfter=_internals69.stat(absolute,{bigint:!0})}catch{return{kind:"capture_failed",file:normalized,code:"file_changed_during_capture",retryable:!0}}if(!pathAfter.isFile()||!sameSnapshot(openedBefore,pathAfter))return{kind:"capture_failed",file:normalized,code:"file_changed_during_capture",retryable:!0};let canonicalAfterRead;try{canonicalAfterRead=_internals69.realpathSync(absolute)}catch{return{kind:"capture_failed",file:normalized,code:"file_changed_during_capture",retryable:!0}}if(!isWithinRoot2(canonicalRoot,canonicalAfterRead)||path75.dirname(canonicalAfterRead)!==canonicalParent)return{kind:"capture_failed",file:normalized,code:"file_changed_during_capture",retryable:!0};return{kind:"captured_file",file:normalized,size:totalBytes,hash:hash3.digest("hex")}}finally{if(fd!==void 0)try{_internals69.close(fd)}catch{}}}function reviewerScopeCaptureToFingerprint(result){if(result.kind==="captured_file")return{file:result.file,kind:"file",size:result.size,hash:result.hash};if(result.kind==="captured_deleted")return{file:result.file,kind:"deleted"};return null}function reviewerScopeFileFingerprintsEqual(left,right){return left.file===right.file&&left.kind===right.kind&&(left.kind==="deleted"||right.kind==="file"&&left.size===right.size&&left.hash===right.hash)}var REVIEWER_SCOPE_CAPTURE_CHUNK_BYTES=262144,REVIEWER_SCOPE_CAPTURE_ATTEMPTS=3,REVIEWER_SCOPE_CAPTURE_BATCH_DEADLINE_MS=1e4,_internals69;var init_reviewer_scope_file_fingerprint=__esm(()=>{_internals69={open:fs48.openSync,fstat:(fd,options)=>fs48.fstatSync(fd,options),read:fs48.readSync,close:fs48.closeSync,lstat:fs48.lstatSync,stat:(path76,options)=>fs48.statSync(path76,options),realpathSync:fs48.realpathSync,now:Date.now}});function classifyTaskResult(output){if(!output||typeof output!=="object")return"non_success";let record2=output,nestedRecords=[record2.metadata,record2.result].filter((candidate)=>typeof candidate==="object"&&candidate!==null),records=[record2,...nestedRecords],states=records.flatMap((candidate)=>[candidate.state,candidate.status]).filter((candidate)=>typeof candidate==="string").map((candidate)=>candidate.trim().toLowerCase());if(records.some((candidate)=>candidate.error!==void 0&&candidate.error!==null||Array.isArray(candidate.errors)&&candidate.errors.length>0)||states.some((state2)=>NON_SUCCESS_STATES.has(state2)))return"non_success";let knownStates=new Set([...SUCCESS_STATES,...RUNNING_STATES,...NON_SUCCESS_STATES]);if(states.some((state2)=>!knownStates.has(state2)))return"non_success";let metadata=nestedRecords[0];if(states.some((state2)=>RUNNING_STATES.has(state2))||metadata?.background===!0)return"running";if(states.some((state2)=>SUCCESS_STATES.has(state2)))return"success";if(typeof record2.output==="string")return"success";return Object.keys(record2).length===0?"success":"non_success"}var SUCCESS_STATES,RUNNING_STATES,NON_SUCCESS_STATES;var init_task_result_classifier=__esm(()=>{SUCCESS_STATES=new Set(["completed","complete","success","succeeded"]),RUNNING_STATES=new Set(["running","pending","queued","in_progress"]),NON_SUCCESS_STATES=new Set(["error","failed","failure","cancelled","canceled","stale","timeout","timed_out","aborted"])});function isExecutionEpisodeArmed(sessionID){return swarmState.agentSessions.get(sessionID)?.executionEpisodeArmed===!0}function setExecutionEpisodeArmed(sessionID,armed){let session=swarmState.agentSessions.get(sessionID);if(!session)return!1;return session.executionEpisodeArmed=armed,!0}var init_execution_episode=__esm(()=>{init_state2()});import*as fs49 from"node:fs";import*as path76 from"node:path";function newState(now){return{armed:!1,nonProgressCalls:0,lastToolCallAt:now,warnIssued:!1,denyTelemetryIssued:!1,workspaceBaseline:null,needsWorkspaceBaseline:!1,callsSinceWorkspaceProbe:0}}function touchState(sessionID,now){let state2=stallStates.get(sessionID)??newState(now);stallStates.delete(sessionID),stallStates.set(sessionID,state2);while(stallStates.size>MAX_TRACKED_STALL_SESSIONS){let stalest=stallStates.keys().next().value;if(stalest===void 0||stalest===sessionID)break;stallStates.delete(stalest)}return state2}function clearStreak(state2){state2.nonProgressCalls=0,state2.warnIssued=!1,state2.denyTelemetryIssued=!1,state2.callsSinceWorkspaceProbe=0}function disarmEpisode(sessionID,state2){state2.armed=!1,state2.workspaceBaseline=null,state2.needsWorkspaceBaseline=!1,clearStreak(state2),setExecutionEpisodeArmed(sessionID,!1)}function armEpisode(sessionID,state2){if(!state2.armed)state2.armed=!0,state2.needsWorkspaceBaseline=!0,clearStreak(state2);_internals70.ensureArchitectSession(sessionID),setExecutionEpisodeArmed(sessionID,!0)}function isArchitectStallSession(sessionID){let activeAgent=swarmState.activeAgent.get(sessionID);if(activeAgent)return stripKnownSwarmPrefix(activeAgent)===ORCHESTRATOR_NAME;let session=swarmState.agentSessions.get(sessionID);if(session)return stripKnownSwarmPrefix(session.agentName)===ORCHESTRATOR_NAME;return!1}function ensureArchitectSession(sessionID){try{if(swarmState.agentSessions.has(sessionID))return;let agentName=swarmState.activeAgent.get(sessionID)??ORCHESTRATOR_NAME;ensureAgentSession(sessionID,agentName)}catch{}}function canonicalDispatchRole(tool,args2){if(!isTaskToolId(tool??""))return null;let subagentType=args2?.subagent_type;if(typeof subagentType!=="string"||subagentType.length===0)return null;let stripped=stripKnownSwarmPrefix(subagentType).toLowerCase();if(isKnownCanonicalRole(stripped))return stripped;let resolved=getCanonicalAgentRole(subagentType).toLowerCase();if(isKnownCanonicalRole(resolved))return resolved;return subagentType.toLowerCase()}function rememberDispatchRole(callID,role){if(!callID)return;pendingDispatchRoles.delete(callID),pendingDispatchRoles.set(callID,role);while(pendingDispatchRoles.size>MAX_PENDING_DISPATCH_ROLES){let oldest=pendingDispatchRoles.keys().next().value;if(oldest===void 0)break;pendingDispatchRoles.delete(oldest)}}function takeDispatchRole(callID){if(!callID)return null;let role=pendingDispatchRoles.get(callID);if(role===void 0)return null;return pendingDispatchRoles.delete(callID),role}function readPlanOpenTaskState(directory){try{if(typeof directory!=="string"||directory.trim().length===0)return"unknown";let raw=fs49.readFileSync(path76.join(directory,".swarm","plan.json"),"utf-8"),plan=JSON.parse(raw);if(!Array.isArray(plan?.phases))return"unknown";for(let phase of plan.phases){if(!Array.isArray(phase?.tasks))continue;for(let task of phase.tasks)if(task?.status==="in_progress")return"open"}return"none"}catch{return"unknown"}}function isWriteToolName(normalizedTool){return WRITE_TOOL_NAMES.includes(normalizedTool)}function positiveInt(value,fallback){if(typeof value!=="number"||!Number.isFinite(value)||value<1)return fallback;return Math.floor(value)}function executionStallAdvisoryText(count){return`EXECUTION STALL: ${count} tool calls with no delegation completion, no file changes, and no status update. STOP investigating; delegate the work or report BLOCKED to the user.`}function executionStallDenialText(count,normalizedTool){return`EXECUTION_STALL: ${count} tool calls in this execution episode with no delegation completion, no file changes, and no task-status update. Direct investigation with \`${normalizedTool}\` is blocked. Productive avenues remain OPEN and are the way out: DELEGATE the work or the verification with `+"`Task` (coder / reviewer / test_engineer) — a completed dispatch clears this block and is how you "+"run builds and tests from here — or call `update_task_status`, or report the blocker to the user "+"with what you have already tried. Do NOT retry this call."}function observeExecutionStallToolCall(params){let{sessionID,tool,args:args2,callID,options}=params;try{if(options?.enabled===!1)return;if(!isArchitectStallSession(sessionID))return;let now=_internals70.now(),state2=touchState(sessionID,now),episodeMs=positiveInt(options?.episodeMinutes,DEFAULT_EXECUTION_STALL_EPISODE_MINUTES)*60000;if(state2.armed&&now-state2.lastToolCallAt>=episodeMs)disarmEpisode(sessionID,state2);state2.lastToolCallAt=now;let role=canonicalDispatchRole(tool,args2);if(role){if(rememberDispatchRole(callID,role),MUTATING_DELEGATION_ROLES.has(role))armEpisode(sessionID,state2)}if(!state2.armed)return;state2.nonProgressCalls+=1,state2.callsSinceWorkspaceProbe+=1;let warnCalls=positiveInt(options?.warnCalls,DEFAULT_EXECUTION_STALL_WARN_CALLS);if(state2.nonProgressCalls>=warnCalls&&!state2.warnIssued){state2.warnIssued=!0;let session=swarmState.agentSessions.get(sessionID);if(session)pushAdvisory(session,executionStallAdvisoryText(state2.nonProgressCalls));telemetry.executionStallWarning(sessionID,state2.nonProgressCalls,warnCalls)}}catch{}}function enforceExecutionStallDenial(params){let{sessionID,tool,options}=params,denial=null;try{if(options?.enabled===!1)return;let state2=stallStates.get(sessionID);if(!state2?.armed)return;if(!isArchitectStallSession(sessionID))return;let stopCalls=positiveInt(options?.stopCalls,DEFAULT_EXECUTION_STALL_STOP_CALLS);if(state2.nonProgressCalls<stopCalls)return;let normalizedTool=normalizeToolNameLowerCase(tool??"");if(!EXECUTION_STALL_DENIED_TOOLS.has(normalizedTool))return;if(!state2.denyTelemetryIssued){state2.denyTelemetryIssued=!0;try{telemetry.executionStallDenied(sessionID,normalizedTool,state2.nonProgressCalls,stopCalls)}catch{}}denial=executionStallDenialText(state2.nonProgressCalls,normalizedTool)}catch{return}if(denial)throw Error(denial)}async function probeWorkspaceProgress(directory,baseline){try{let authoritative=baseline?await _internals70.changedFilesSinceSnapshotAsync(directory,baseline):null,current=await _internals70.captureWorkspaceSnapshotAsync(directory);if(!baseline)return{progress:!1,next:current};if(authoritative!==null)return{progress:authoritative.length>0,next:current};if(baseline.gitHead&¤t?.gitHead&&baseline.gitHead!==current.gitHead)return{progress:!0,next:current};let before=new Set(baseline.changedFiles??[]);return{progress:(current?.changedFiles??[]).some((entry)=>!before.has(entry)),next:current}}catch{return{progress:!1,next:baseline}}}async function recordExecutionStallToolAfter(params){let{sessionID,tool,callID,args:args2,output,directory,options}=params;try{let dispatchRole=takeDispatchRole(callID);if(options?.enabled===!1)return;if(!isArchitectStallSession(sessionID))return;let normalizedTool=normalizeToolNameLowerCase(tool??""),succeeded=classifyTaskResult(output)==="success",progress=!1,armOnStatus=!1,taskSettled=!1;if(normalizedTool==="update_task_status"){let status=readUpdateTaskStatusOutcome(output,args2);if(status.ok)progress=!0,armOnStatus=status.value==="in_progress",taskSettled=!armOnStatus}else if(dispatchRole!==null)progress=succeeded&&MUTATING_DELEGATION_ROLES.has(dispatchRole);else if(isWriteToolName(normalizedTool))progress=succeeded;let now=_internals70.now(),existing=stallStates.get(sessionID);if(!existing&&!armOnStatus)return;let state2=existing??touchState(sessionID,now);if(armOnStatus)armEpisode(sessionID,state2);if(!state2.armed)return;if(taskSettled&&_internals70.readPlanOpenTaskState(directory)==="none"){disarmEpisode(sessionID,state2);return}if(progress){clearStreak(state2),state2.needsWorkspaceBaseline=!0;return}if(state2.needsWorkspaceBaseline){state2.needsWorkspaceBaseline=!1,state2.callsSinceWorkspaceProbe=0;try{state2.workspaceBaseline=await _internals70.captureWorkspaceSnapshotAsync(directory)}catch{state2.workspaceBaseline=null}return}if(state2.callsSinceWorkspaceProbe<WORKSPACE_PROBE_EVERY_CALLS)return;if(state2.callsSinceWorkspaceProbe=0,_internals70.readPlanOpenTaskState(directory)==="none"){disarmEpisode(sessionID,state2);return}let probe2=await probeWorkspaceProgress(directory,state2.workspaceBaseline);if(state2.workspaceBaseline=probe2.next,probe2.progress)clearStreak(state2)}catch{}}function readUpdateTaskStatusOutcome(output,args2){let text=output&&typeof output==="object"?output.output:void 0;if(typeof text!=="string")return{ok:!1,value:null};try{let parsed=JSON.parse(text);if(parsed?.success!==!0)return{ok:!1,value:null};let fromOutput=typeof parsed.new_status==="string"?parsed.new_status:null,fromArgs=typeof args2?.status==="string"?args2.status:null;return{ok:!0,value:(fromOutput??fromArgs)?.toLowerCase()??null}}catch{return{ok:!1,value:null}}}var DEFAULT_EXECUTION_STALL_WARN_CALLS=30,DEFAULT_EXECUTION_STALL_STOP_CALLS=60,DEFAULT_EXECUTION_STALL_EPISODE_MINUTES=30,MUTATING_DELEGATION_ROLES,EXECUTION_STALL_DENIED_TOOLS,WORKSPACE_PROBE_EVERY_CALLS=10,MAX_TRACKED_STALL_SESSIONS=200,MAX_PENDING_DISPATCH_ROLES=256,stallStates,pendingDispatchRoles,_internals70;var init_execution_stall=__esm(()=>{init_workspace_snapshot();init_constants();init_schema();init_state2();init_telemetry();init_normalize_tool_name();init_task_result_classifier();init_execution_episode();MUTATING_DELEGATION_ROLES=new Set(["coder","reviewer","test_engineer","security_reviewer"]),EXECUTION_STALL_DENIED_TOOLS=new Set(["read","glob","grep","bash","shell"]),stallStates=new Map,pendingDispatchRoles=new Map;_internals70={now:()=>Date.now(),captureWorkspaceSnapshotAsync,changedFilesSinceSnapshotAsync,ensureArchitectSession,readPlanOpenTaskState}});import*as path77 from"node:path";function isConfigFilePath(filePath,cwd,extraGlobs){let normalized=path77.relative(path77.resolve(cwd),path77.resolve(cwd,filePath)).replace(/\\/g,"/"),{zone}=classifyFile(normalized);if(zone==="config")return!0;let allGlobs=extraGlobs&&extraGlobs.length>0?[...KNOWN_VERIFIER_CONFIG_GLOBS,...extraGlobs]:KNOWN_VERIFIER_CONFIG_GLOBS;for(let glob of allGlobs)if(getGlobMatcher(glob)(normalized))return!0;return!1}function isWriteTool(toolName){let normalized=normalizeToolName(toolName);return WRITE_TOOL_NAMES.includes(normalized)}function isOutsideSwarmDir(filePath,directory){if(!filePath)return!1;let swarmDir=path77.resolve(directory,".swarm"),resolved=path77.resolve(directory,filePath),relative19=path77.relative(swarmDir,resolved);return relative19.startsWith("..")||path77.isAbsolute(relative19)}function isSourceCodePath(filePath){if(!filePath)return!1;let normalized=filePath.replace(/\\/g,"/");return![/^README(\..+)?$/i,/\/README(\..+)?$/i,/^CHANGELOG(\..+)?$/i,/\/CHANGELOG(\..+)?$/i,/^package\.json$/,/\/package\.json$/,/^\.github\//,/\/\.github\//,/^docs\//,/\/docs\//,/^\.swarm\//,/\/\.swarm\//].some((pattern)=>pattern.test(normalized))}function hasTraversalSegments(filePath){if(!filePath)return!1;let normalized=filePath.replace(/\\/g,"/");return normalized.startsWith("..")||normalized.includes("/../")||normalized.endsWith("/..")}function isInDeclaredScope(filePath,scopeEntries,cwd){return isPathWithinDeclaredScope(filePath,scopeEntries,cwd)}function redactShellCommand(cmd){if(typeof cmd!=="string")return"";let out=cmd.replace(/\/home\/[^/\s"']+/g,"~").replace(/[A-Za-z]:\\Users\\[^\\\s"']+/gi,"~").replace(/\/Users\/[^/\s"']+/g,"~").replace(/\\\\[^\\\s"']+\\[^\\\s"']+\\[^\\\s"']+(?:\\[^\s"']*)?/g,"~");out=out.replace(/([a-zA-Z][a-zA-Z0-9+.-]{0,32}:\/\/[^\s"'@/]+):([^@\s"'/]+)@/g,"$1:[REDACTED]@");let VALUE=String.raw`(?:"[^"]*"|'[^']*'|\S+)`;return out=out.replace(new RegExp(String.raw`\b([A-Z_]{0,64}(?:TOKEN|SECRET|PASSWORD|PASSWD|API[_]?KEY|APIKEY|AUTH|CREDENTIAL|PRIVATE[_]?KEY|ACCESS[_]?KEY|_KEY)[A-Z_0-9]{0,64})\s*=\s*`+VALUE,"gi"),"$1=[REDACTED]"),out=out.replace(new RegExp(String.raw`(\$env:[A-Za-z_][A-Za-z_0-9]{0,64}(?:TOKEN|SECRET|PASSWORD|PASSWD|API[_]?KEY|APIKEY|AUTH|CREDENTIAL|PRIVATE[_]?KEY|ACCESS[_]?KEY|_KEY)[A-Za-z_0-9]{0,64})(\s*=\s*)`+VALUE,"gi"),"$1=[REDACTED]"),out=out.replace(new RegExp(String.raw`\b(set|SET)(\s+"?)([A-Za-z_][A-Za-z_0-9]{0,64}(?:TOKEN|SECRET|PASSWORD|PASSWD|API[_]?KEY|APIKEY|AUTH|CREDENTIAL|PRIVATE[_]?KEY|ACCESS[_]?KEY|_KEY)[A-Za-z_0-9]{0,64})(=?)(\s+)`+VALUE,"gi"),"$1$2$3=[REDACTED]"),out=out.replace(/--([a-zA-Z-]*(?:token|secret|password|passwd|api[_-]?key|apikey|auth|credential|private[_-]?key|access[_-]?key)[a-zA-Z-]*)=(\S+)/gi,"--$1=[REDACTED]"),out=out.replace(/(--[a-zA-Z-]*(?:token|secret|password|passwd|api[_-]?key|apikey|auth|credential|private[_-]?key|access[_-]?key)[a-zA-Z-]*)(\s+)(?!--)(\S+)/gi,"$1$2[REDACTED]"),out=out.replace(/\b(Bearer|Basic)\s+[A-Za-z0-9+/=._-]{4,}/gi,"$1 [REDACTED]"),out=out.replace(/(-H\s+['"]?(?:Authorization|X-API-Key|X-Auth-Token|[A-Za-z][A-Za-z-]*-(?:key|token|secret|auth|credential)):\s*)([^'">\s][^'">\n]*)(['"]?)/gi,"$1[REDACTED]$3"),out=out.replace(/\bsk-[A-Za-z0-9_-]{20,}/g,"[REDACTED:openai]").replace(/\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{20,}/g,"[REDACTED:github]").replace(/\bgithub_pat_[A-Za-z0-9_]{22,}/g,"[REDACTED:github]").replace(/\bAKIA[0-9A-Z]{16}\b/g,"[REDACTED:aws]").replace(/\bxox[baprs]-[A-Za-z0-9-]{10,}/g,"[REDACTED:slack]").replace(/\bAIza[A-Za-z0-9_-]{30,}/g,"[REDACTED:google]"),out=out.replace(/[A-Za-z0-9+/]{80,}={0,2}/g,(run)=>/[A-Z]/.test(run)&&/[a-z]/.test(run)&&/[0-9]/.test(run)?"[REDACTED:base64]":run),out}var KNOWN_VERIFIER_CONFIG_GLOBS;var init_helpers=__esm(()=>{init_constants();init_path_identity();init_normalize_tool_name();init_file_authority();KNOWN_VERIFIER_CONFIG_GLOBS=["**/oxlintrc*","**/.oxlintrc*","**/.eslintrc*","**/eslint.config.*","**/.prettierrc*","**/prettier.config.*","**/biome.jsonc","**/.secretscanignore","**/.golangci*"]});function charsToTokens(chars){return estimateTokensFromCharCount(chars)}function allocateInjectionBudget(systemEnhancerDemandTokens,knowledgeInjectorDemandChars,config2){let budget=config2.totalBudgetTokens,seDemand=Math.max(0,systemEnhancerDemandTokens),kiChars=Math.max(0,knowledgeInjectorDemandChars),ceiling=Math.max(0,budget),kiDemand=charsToTokens(kiChars);if(seDemand+kiDemand<=ceiling)return{systemEnhancerTokens:seDemand,knowledgeInjectorTokens:kiDemand,totalTokens:seDemand+kiDemand};if(seDemand>=ceiling)return{systemEnhancerTokens:ceiling,knowledgeInjectorTokens:0,totalTokens:ceiling};if(kiDemand>=ceiling)return{systemEnhancerTokens:0,knowledgeInjectorTokens:ceiling,totalTokens:ceiling};let totalDemand=seDemand+kiDemand,seShare=Math.floor(seDemand/totalDemand*ceiling),kiShare=ceiling-seShare;return{systemEnhancerTokens:seShare,knowledgeInjectorTokens:kiShare,totalTokens:ceiling}}function evictTurnLedgers(){while(turnLedgers.size>MAX_TRACKED_SESSIONS){let firstKey=turnLedgers.keys().next().value;if(firstKey===void 0)break;turnLedgers.delete(firstKey)}}function getOrCreateAccounting(ledger,producer,surface){let accounting=ledger.producers.get(producer);if(!accounting)accounting={requested:0,granted:0,emitted:0,truncated:0,surface},ledger.producers.set(producer,accounting);return accounting.surface=surface,accounting}function makeInjectionBudgetReceipt(data){let receipt=Object.freeze({});return injectionBudgetReceipts.set(receipt,{...data,state:"pending"}),receipt}function settleInjectionBudgetReceipt(receipt,action){let data=injectionBudgetReceipts.get(receipt);if(!data||data.state!=="pending")return!1;let ledger=turnLedgers.get(data.sessionID);if(!ledger||ledger.generation!==data.generation)return data.state="stale",!1;let accounting=ledger.producers.get(data.producer);if(!accounting||accounting!==data.accounting||accounting.surface!==data.surface)return data.state="stale",!1;if(action==="commit")return data.state="committed",!0;if(accounting.requested=Math.max(0,accounting.requested-data.requestedTokens),accounting.granted=Math.max(0,accounting.granted-data.grantedTokens),data.retractEmissionOnRefund){let retracted=Math.min(accounting.emitted,data.emittedTokensOnRefund);accounting.emitted-=retracted,accounting.truncated+=retracted}if(accounting.requested===0&&accounting.granted===0&&accounting.emitted===0&&accounting.truncated===0)ledger.producers.delete(data.producer);return ledger.used=Math.max(0,ledger.used-data.chargedTokens),data.state="refunded",!0}function beginTurnLedger(sessionID,totalBudget,ceilingActive){let generation=++turnGenerationCounter;return turnLedgers.set(sessionID,{generation,totalBudget:Math.max(0,totalBudget),ceilingActive,used:0,producers:new Map}),evictTurnLedgers(),generation}function applyTurnBudgetClaim(sessionID,producer,requestedTokens,opts){let requested=Math.max(0,requestedTokens),localMax=opts?.localMaxTokens===void 0?requested:Math.max(0,opts.localMaxTokens),surface=opts?.surface??"system",ledger=turnLedgers.get(sessionID);if(!ledger)return{result:{granted:Math.min(requested,localMax),ledgerPresent:!1,ceilingActive:!1}};let accounting=getOrCreateAccounting(ledger,producer,surface);accounting.requested+=requested;let granted,charged=0;if(!ledger.ceilingActive)granted=Math.min(requested,localMax);else{let remaining=Math.max(0,ledger.totalBudget-ledger.used);granted=Math.min(requested,localMax,remaining),charged=granted,ledger.used+=charged}return accounting.granted+=granted,{result:{granted,ledgerPresent:!0,ceilingActive:ledger.ceilingActive},receiptData:{sessionID,generation:ledger.generation,producer,surface,accounting,requestedTokens:requested,grantedTokens:granted,chargedTokens:charged,emittedTokensOnRefund:0,retractEmissionOnRefund:!1}}}function claimTurnBudget(sessionID,producer,requestedTokens,opts){return applyTurnBudgetClaim(sessionID,producer,requestedTokens,opts).result}function claimTurnBudgetWithReceipt(sessionID,producer,requestedTokens,opts){let mutation=applyTurnBudgetClaim(sessionID,producer,requestedTokens,opts);return{...mutation.result,receipt:mutation.receiptData?makeInjectionBudgetReceipt(mutation.receiptData):void 0}}function recordProducerGrant(sessionID,producer,requestedTokens,grantedTokens,surface){applyProducerGrant(sessionID,producer,requestedTokens,grantedTokens,surface)}function applyProducerGrant(sessionID,producer,requestedTokens,grantedTokens,surface,expectedGeneration){let ledger=turnLedgers.get(sessionID);if(!ledger||expectedGeneration!==void 0&&ledger.generation!==expectedGeneration)return;let accounting=getOrCreateAccounting(ledger,producer,surface),requested=Math.max(0,requestedTokens);accounting.requested+=requested;let granted=Math.max(0,grantedTokens);accounting.granted+=granted;let charged=0;if(ledger.ceilingActive)charged=Math.min(granted,Math.max(0,ledger.totalBudget-ledger.used)),ledger.used+=charged;return{data:{sessionID,generation:ledger.generation,producer,surface,accounting,requestedTokens:requested,grantedTokens:granted,chargedTokens:charged,emittedTokensOnRefund:0,retractEmissionOnRefund:!1}}}function recordProducerGrantWithReceipt(sessionID,producer,requestedTokens,grantedTokens,surface,options={}){let mutation=applyProducerGrant(sessionID,producer,requestedTokens,grantedTokens,surface,options.expectedGeneration);if(!mutation)return;return makeInjectionBudgetReceipt({...mutation.data,retractEmissionOnRefund:options.retractEmissionOnRefund===!0,emittedTokensOnRefund:Math.max(0,options.emittedTokensOnRefund??0)})}function recordProducerEmission(sessionID,producer,emittedTokens,truncatedTokens,surface,options){applyProducerEmission(sessionID,producer,emittedTokens,truncatedTokens,surface,options?.expectedGeneration)}function applyProducerEmission(sessionID,producer,emittedTokens,truncatedTokens,surface,expectedGeneration){let ledger=turnLedgers.get(sessionID);if(!ledger||expectedGeneration!==void 0&&ledger.generation!==expectedGeneration)return;let accounting=getOrCreateAccounting(ledger,producer,surface),emitted=Math.max(0,emittedTokens);return accounting.emitted+=emitted,accounting.truncated+=Math.max(0,truncatedTokens),{sessionID,generation:ledger.generation,producer,surface,accounting,requestedTokens:0,grantedTokens:0,chargedTokens:0,emittedTokensOnRefund:emitted,retractEmissionOnRefund:!0}}function recordProducerEmissionWithReceipt(sessionID,producer,emittedTokens,surface,options){let receiptData=applyProducerEmission(sessionID,producer,emittedTokens,0,surface,options?.expectedGeneration);return receiptData?makeInjectionBudgetReceipt(receiptData):void 0}function deductProducerEmission(sessionID,producer,removedTokens,options){let ledger=turnLedgers.get(sessionID);if(!ledger||options?.expectedGeneration!==void 0&&ledger.generation!==options.expectedGeneration)return;let accounting=ledger.producers.get(producer);if(!accounting)return;accounting.emitted=Math.max(0,accounting.emitted-Math.max(0,removedTokens))}function getTurnLedgerSummary(sessionID){let ledger=turnLedgers.get(sessionID);if(!ledger)return null;return{generation:ledger.generation,totalBudget:ledger.totalBudget,ceilingActive:ledger.ceilingActive,used:ledger.used,producers:Array.from(ledger.producers.entries()).map(([producer,accounting])=>({producer,requested:accounting.requested,granted:accounting.granted,emitted:accounting.emitted,truncated:accounting.truncated,surface:accounting.surface}))}}function getProducerEmission(sessionID,producer){return turnLedgers.get(sessionID)?.producers.get(producer)?.emitted??0}function commitInjectionBudgetReceipt(receipt){return settleInjectionBudgetReceipt(receipt,"commit")}function refundInjectionBudgetReceipt(receipt){return settleInjectionBudgetReceipt(receipt,"refund")}function advanceTurnGeneration(sessionID){turnLedgers.delete(sessionID)}function clearAllTurnLedgers(){turnLedgers.clear()}var injectionBudgetReceipts,turnLedgers,MAX_TRACKED_SESSIONS=256,turnGenerationCounter=0;var init_injection_budget=__esm(()=>{init_utils2();injectionBudgetReceipts=new WeakMap,turnLedgers=new Map});function extractStatusCode(errorMsg){let match=errorMsg.match(/\b(408|429|500|502|503|504|529)\b/);if(match)return parseInt(match[1],10);return null}function isTransientProviderError(signal){if(!signal)return!1;if(TRANSIENT_MODEL_ERROR_PATTERN.test(signal))return!0;if(QUOTA_ERROR_PATTERN.test(signal))return!0;let status=extractStatusCode(signal);return status!==null&&TRANSIENT_STATUS_CODES.has(status)}function isQuotaError(signal){return signal.length>0&"A_ERROR_PATTERN.test(signal)}var TRANSIENT_STATUS_CODES,TRANSIENT_MODEL_ERROR_PATTERN,QUOTA_ERROR_PATTERN,REQUEST_SHAPE_REJECTION_PATTERN;var init_provider_error_classification=__esm(()=>{TRANSIENT_STATUS_CODES=new Set([408,429,500,502,503,504,529]);TRANSIENT_MODEL_ERROR_PATTERN=/rate.?limit|429|500|502|503|504|529|timeout|overloaded|model.?not.?found|temporarily.?unavailable|provider[_\s-]?unavailable|server.?error|network.?connection.?lost|connection.?(refused|reset|timeout|lost)|bad.?gateway|gateway.?timeout|internal.?server.?error|service.?unavailable|ECONNRESET|ECONNREFUSED|ETIMEDOUT|EPIPE|ENOTFOUND|broken.?pipe|dns(?:[\s_-]+(?:resolution)?)?[\s_-]+fail|name.?not.?resolved|EAI_AGAIN/i,QUOTA_ERROR_PATTERN=/quota|usage.?limit|insufficient.?(?:quota|credits?)|\b402\b|payment.?required|credit.?balance|out of credits|billing.?(?:hard.?)?limit/i,REQUEST_SHAPE_REJECTION_PATTERN=/\b(?:single|one|only|exactly)[^.]{0,48}?\bsystem\s+messages?\b|\bmultiple\s+system\s+messages?\b|\bsystem\s+messages?\s+(?:are\s+)?not\s+supported\b/i});function extractModelInfo(messages){if(!messages||messages.length===0)return{};for(let i=messages.length-1;i>=0;i--){let message=messages[i];if(!message?.info)continue;if(message.info.role==="assistant"){let modelID=message.info.modelID,providerID=message.info.providerID;if(modelID||providerID)return{...modelID?{modelID}:{},...providerID?{providerID}:{}}}}return{}}function extractSessionId2(messages){if(!messages||messages.length===0)return;for(let i=messages.length-1;i>=0;i--){let sessionID=messages[i]?.info?.sessionID;if(typeof sessionID==="string"&&sessionID.length>0)return sessionID}return}function rememberBoundedModelIdentity(set2,key){if(set2.has(key))return!1;while(set2.size>=MAX_TRACKED_MODEL_IDENTITIES){let oldest=set2.values().next().value;if(oldest===void 0)break;set2.delete(oldest)}return set2.add(key),!0}function classifyModelLimitSource(resolution){return SOURCE_CLASS_BY_RESOLUTION[resolution]}function lookupStaticModelLimit(modelID,providerID){if(providerID&&PROVIDER_CAPS[providerID]!==void 0)return{tokens:PROVIDER_CAPS[providerID],table:"provider_cap"};if(modelID){let native=findNativeLimit(modelID);if(native!==void 0)return{tokens:native,table:"native"}}return}function resolveModelLimit(modelID,providerID,configOverrides={},liveContextLimit,directory){let invalidOverride=recordInvalidOverrides(modelID,providerID,configOverrides);warnNormalizedKeyCollisions(configOverrides);let resolution=resolveContextWindow({userLimits:configOverrides,modelID,providerID,liveContextLimit,fallbackLookup:lookupStaticModelLimit});return logFirstCall(modelID??"",providerID??"",resolution.source,resolution.tokens),maybeWarnUndersizedDefault(modelID,providerID,resolution.source,resolution.tokens,liveContextLimit),_internals71.observeResolution({modelID,providerID,directory,resolution:resolution.source,aliasKeyClass:resolution.source==="user_provider_model"?"compound":resolution.source==="user_model"?"model":resolution.source==="user_default"?"default":void 0,invalidOverride}),{limit:resolution.tokens,source:classifyModelLimitSource(resolution.source),resolution:resolution.source}}function recordInvalidOverrides(modelID,providerID,configOverrides){if(!configOverrides||typeof configOverrides!=="object")return!1;let normalizedModel=modelID?.trim().toLowerCase(),normalizedCompound=`${providerID??""}/${modelID??""}`.trim().toLowerCase(),relevantInvalid=!1;for(let[key,value]of Object.entries(configOverrides)){if(isUsableConfiguredWindow(value))continue;let keyClass=key==="default"?"default":key.includes("/")?"compound":"model",normalizedKey=key.trim().toLowerCase();if(keyClass==="default"||keyClass==="model"&&normalizedModel!==void 0&&normalizedKey===normalizedModel||keyClass==="compound"&&normalizedKey===normalizedCompound)relevantInvalid=!0;let identity=`${modelID||"unknown"}::${providerID||"unknown"}::${keyClass}::${String(value)}`;if(rememberBoundedModelIdentity(invalidOverrideReports,identity))warn(`[model-limits] context_budget.model_limits.${key}=${String(value)} for ${modelID||"(no model)"}@${providerID||"(no provider)"} is not a usable limit (finite number ≥ 1); skipping it — not coercing.`,{modelID,providerID,keyClass,value})}return relevantInvalid}function warnNormalizedKeyCollisions(configOverrides){let byNormalized=new Map;for(let key of Object.keys(configOverrides)){let normalized=key.trim().toLowerCase();byNormalized.set(normalized,[...byNormalized.get(normalized)??[],key])}for(let[normalized,keys]of byNormalized){if(keys.length<2)continue;let identity=`collision::${normalized}`;if(!rememberBoundedModelIdentity(invalidOverrideReports,identity))continue;warn(`[model-limits] context_budget.model_limits has ${keys.length} keys that normalize identically (${keys.join(", ")}); only the last one in config order takes effect under normalized matching.`,{keys})}}function findNativeLimit(modelID){if(NATIVE_MODEL_LIMITS[modelID]!==void 0)return NATIVE_MODEL_LIMITS[modelID];let bestMatch;for(let key of Object.keys(NATIVE_MODEL_LIMITS))if(modelID.startsWith(key)){if(!bestMatch||key.length>bestMatch.length)bestMatch=key}return bestMatch?NATIVE_MODEL_LIMITS[bestMatch]:void 0}function logFirstCall(modelID,providerID,source,limit){let key=`${modelID||"unknown"}::${providerID||"unknown"}`;if(rememberBoundedModelIdentity(loggedFirstCalls,key))log(`[model-limits] Resolved limit for ${modelID||"(no model)"}@${providerID||"(no provider)"}: ${limit} (source: ${source})`)}function maybeWarnUndersizedDefault(modelID,providerID,source,resolvedTokens,liveContextLimit){if(source!=="user_default")return;if(!isUsableContextWindow(liveContextLimit))return;let liveTokens=Math.floor(liveContextLimit);if(liveTokens<=resolvedTokens)return;let key=`${modelID||"unknown"}::${providerID||"unknown"}`;if(!rememberBoundedModelIdentity(warnedUndersizedDefaults,key))return;warn(`[model-limits] context_budget.model_limits.default=${resolvedTokens} is below live model window ${liveTokens} for ${modelID||"(no model)"}@${providerID||"(no provider)"}; keeping the configured default.`,{modelID,providerID,resolvedTokens,liveTokens,source})}var NATIVE_MODEL_LIMITS,PROVIDER_CAPS,MAX_TRACKED_MODEL_IDENTITIES=256,loggedFirstCalls,warnedUndersizedDefaults,SOURCE_CLASS_BY_RESOLUTION,_internals71,invalidOverrideReports;var init_model_limits=__esm(()=>{init_learning_health();init_utils();NATIVE_MODEL_LIMITS={"claude-sonnet-4":200000,"claude-opus-4":200000,"claude-haiku-4":200000,"gpt-5":400000,"gpt-5.1-codex":400000,"gpt-5.1":264000,"gpt-4.1":1047576,"gemini-2.5-pro":1048576,"gemini-2.5-flash":1048576,o3:200000,"o4-mini":200000,"deepseek-r1":163840,"deepseek-chat":163840,"qwen3.5":131072,"MiniMax-M3":1e6,"MiniMax-M2.7":204800},PROVIDER_CAPS={copilot:128000,"github-copilot":128000};loggedFirstCalls=new Set,warnedUndersizedDefaults=new Set;SOURCE_CLASS_BY_RESOLUTION={user_provider_model:"override",user_model:"override",user_default:"override",live_model_limit:"host",static_provider_cap:"provider_cap",static_native:"native",static_default:"fallback"};_internals71={observeResolution:observeModelLimitResolution};invalidOverrideReports=new Set});function rememberCountedAssistantMsg(map2,sessionId,messageId){map2.delete(sessionId),map2.set(sessionId,messageId);while(map2.size>MAX_TRACKED_COUNTED_ASSISTANT_MSGS){let stalest=map2.keys().next().value;if(stalest===void 0)break;map2.delete(stalest)}}function boundAdvisoryBytes(advisories,maxBytes){let kept=[...advisories],sizeOf=(arr)=>arr.reduce((n,m)=>n+m.length+5,0);while(sizeOf(kept)>maxBytes&&kept.length>1)kept.shift();return{kept,truncated:kept.length<advisories.length}}function getMessageText(message){if(!message?.parts)return"";return message.parts.filter((part)=>part?.type==="text"&&typeof part.text==="string").map((part)=>part.text).join(`
|
|
1004
|
+
`)}if(output.length>maxChars){let cap=Math.max(0,maxChars-21-4),trimmed=output.slice(0,cap),lastNewline=trimmed.lastIndexOf(`
|
|
1005
|
+
`);if(lastNewline>0)trimmed=trimmed.slice(0,lastNewline);output=`${trimmed}
|
|
1006
|
+
[/SWARM PLAN CURSOR]`}return output}function resolvePlanCursorControls(planCursor){let rawMaxTokens=Number(planCursor?.max_tokens??1500),rawLookahead=Number(planCursor?.lookahead_tasks??2);return{enabled:planCursor?.enabled===void 0?!0:Boolean(planCursor.enabled),maxTokens:Number.isFinite(rawMaxTokens)?Math.min(4000,Math.max(500,Math.round(rawMaxTokens))):1500,lookaheadTasks:Number.isFinite(rawLookahead)?Math.min(5,Math.max(0,Math.round(rawLookahead))):2}}var init_extractors=__esm(()=>{init_plan_schema();init_utils2()});import{createHash as createHash34}from"node:crypto";import*as fs48 from"node:fs";import*as path75 from"node:path";function hasControlCharacter(value){for(let index=0;index<value.length;index+=1){let code=value.charCodeAt(index);if(code<=31||code===127)return!0}return!1}function normalizedProjectFile(directory,file2){if(file2.includes("\x00")||hasControlCharacter(file2))return null;let root=path75.resolve(directory),absolute=path75.resolve(root,file2),relative18=path75.relative(root,absolute).replaceAll("\\","/");if(!relative18||relative18===".."||relative18.startsWith("../")||path75.isAbsolute(relative18))return null;return relative18}function isWithinRoot2(root,candidate){let relative18=path75.relative(root,candidate);return relative18===""||relative18!==".."&&!relative18.startsWith(`..${path75.sep}`)&&!path75.isAbsolute(relative18)}function deletedPathIsContained(canonicalRoot,absolute){let current=path75.dirname(absolute);for(;;){try{let canonical=_internals69.realpathSync(current);return canonicalRoot===canonical||isWithinRoot2(canonicalRoot,canonical)}catch(error49){if(error49.code!=="ENOENT")return!1}let parent=path75.dirname(current);if(parent===current)return!1;current=parent}}function sameSnapshot(left,right){return(!((left.dev!==0n||left.ino!==0n)&&(right.dev!==0n||right.ino!==0n))||left.dev===right.dev&&left.ino===right.ino)&&left.size===right.size&&left.mtimeNs===right.mtimeNs&&left.ctimeNs===right.ctimeNs}function captureReviewerScopeFileFingerprint(directory,file2,options={}){if(typeof directory!=="string"||typeof file2!=="string")return{kind:"capture_failed",file:typeof file2==="string"?file2:"",code:"invalid_request",retryable:!1};if(file2.includes("\x00")||hasControlCharacter(file2))return{kind:"capture_failed",file:file2,code:"invalid_request",retryable:!1};let normalized=normalizedProjectFile(directory,file2);if(!normalized)return{kind:"capture_failed",file:file2,code:"outside_workspace",retryable:!1};let canonicalRoot,canonicalParent,absolute=path75.resolve(directory,normalized);try{canonicalRoot=_internals69.realpathSync(path75.resolve(directory))}catch{return{kind:"capture_failed",file:normalized,code:"outside_workspace",retryable:!1}}try{canonicalParent=_internals69.realpathSync(path75.dirname(absolute))}catch(error49){if(error49.code==="ENOENT"){let secondObservation=null,secondFailed=!1;try{secondObservation=_internals69.realpathSync(path75.dirname(absolute))}catch(secondError){if(secondError.code!=="ENOENT")return{kind:"capture_failed",file:normalized,code:"unreadable",retryable:!1,detail:secondError.code};secondFailed=!0}if(!secondFailed)canonicalParent=secondObservation;else{try{return _internals69.lstat(absolute),{kind:"capture_failed",file:normalized,code:"file_changed_during_capture",retryable:!0,detail:"parent enoent unstable"}}catch(fileError){if(fileError.code!=="ENOENT")return{kind:"capture_failed",file:normalized,code:"unreadable",retryable:!1,detail:fileError.code}}return deletedPathIsContained(canonicalRoot,absolute)?{kind:"captured_deleted",file:normalized}:{kind:"capture_failed",file:normalized,code:"outside_workspace",retryable:!1}}}else return{kind:"capture_failed",file:normalized,code:"unreadable",retryable:!1,detail:error49.code}}if(!isWithinRoot2(canonicalRoot,canonicalParent))return{kind:"capture_failed",file:normalized,code:"outside_workspace",retryable:!1};let before;try{before=_internals69.lstat(absolute)}catch(error49){if(error49.code==="ENOENT")return deletedPathIsContained(canonicalRoot,absolute)?{kind:"captured_deleted",file:normalized}:{kind:"capture_failed",file:normalized,code:"outside_workspace",retryable:!1};return{kind:"capture_failed",file:normalized,code:"unreadable",retryable:!1,detail:error49.code}}if(before.isSymbolicLink())return{kind:"capture_failed",file:normalized,code:"symlink_or_reparse",retryable:!1};try{let canonicalTarget=_internals69.realpathSync(absolute);if(!isWithinRoot2(canonicalRoot,canonicalTarget)||path75.dirname(canonicalTarget)!==canonicalParent)return{kind:"capture_failed",file:normalized,code:"outside_workspace",retryable:!1}}catch{return{kind:"capture_failed",file:normalized,code:"unreadable",retryable:!1}}if(!before.isFile()||!Number.isSafeInteger(before.size)||before.size<0)return{kind:"capture_failed",file:normalized,code:"non_regular",retryable:!1};let openFlags=fs48.constants.O_RDONLY|(process.platform==="win32"?0:fs48.constants.O_NOFOLLOW),beforeBigInt;try{beforeBigInt=_internals69.lstat(absolute,{bigint:!0})}catch{return{kind:"capture_failed",file:normalized,code:"file_changed_during_capture",retryable:!0}}let fd;try{fd=_internals69.open(absolute,openFlags)}catch(error49){let code=error49.code;if(code==="ENOENT"||code==="ELOOP")return{kind:"capture_failed",file:normalized,code:"file_changed_during_capture",retryable:!0,detail:code};if(code==="EMFILE"||code==="ENFILE")return{kind:"capture_failed",file:normalized,code:"capture_deadline",retryable:!0,detail:code};return{kind:"capture_failed",file:normalized,code:"unreadable",retryable:!1,detail:code}}try{let openedBefore=_internals69.fstat(fd,{bigint:!0});if(!openedBefore.isFile())return{kind:"capture_failed",file:normalized,code:"non_regular",retryable:!1};if(!sameSnapshot(beforeBigInt,openedBefore))return{kind:"capture_failed",file:normalized,code:"file_changed_during_capture",retryable:!0};let hash3=createHash34("sha256"),chunk=Buffer.alloc(REVIEWER_SCOPE_CAPTURE_CHUNK_BYTES),totalBytes=0;for(;;){if(options.deadlineAt!==void 0&&_internals69.now()>options.deadlineAt)return{kind:"capture_failed",file:normalized,code:"capture_deadline",retryable:!0};let bytesRead;try{bytesRead=_internals69.read(fd,chunk,0,chunk.byteLength,null)}catch(error49){let code=error49.code;return{kind:"capture_failed",file:normalized,code:"unreadable",retryable:!1,detail:code}}if(bytesRead===0)break;totalBytes+=bytesRead,hash3.update(bytesRead===chunk.byteLength?chunk:chunk.subarray(0,bytesRead))}let openedAfter=_internals69.fstat(fd,{bigint:!0});if(!sameSnapshot(openedBefore,openedAfter))return{kind:"capture_failed",file:normalized,code:"file_changed_during_capture",retryable:!0};if(totalBytes!==Number(openedBefore.size))return{kind:"capture_failed",file:normalized,code:"file_changed_during_capture",retryable:!0};let pathAfter;try{pathAfter=_internals69.stat(absolute,{bigint:!0})}catch{return{kind:"capture_failed",file:normalized,code:"file_changed_during_capture",retryable:!0}}if(!pathAfter.isFile()||!sameSnapshot(openedBefore,pathAfter))return{kind:"capture_failed",file:normalized,code:"file_changed_during_capture",retryable:!0};let canonicalAfterRead;try{canonicalAfterRead=_internals69.realpathSync(absolute)}catch{return{kind:"capture_failed",file:normalized,code:"file_changed_during_capture",retryable:!0}}if(!isWithinRoot2(canonicalRoot,canonicalAfterRead)||path75.dirname(canonicalAfterRead)!==canonicalParent)return{kind:"capture_failed",file:normalized,code:"file_changed_during_capture",retryable:!0};return{kind:"captured_file",file:normalized,size:totalBytes,hash:hash3.digest("hex")}}finally{if(fd!==void 0)try{_internals69.close(fd)}catch{}}}function reviewerScopeCaptureToFingerprint(result){if(result.kind==="captured_file")return{file:result.file,kind:"file",size:result.size,hash:result.hash};if(result.kind==="captured_deleted")return{file:result.file,kind:"deleted"};return null}function reviewerScopeFileFingerprintsEqual(left,right){return left.file===right.file&&left.kind===right.kind&&(left.kind==="deleted"||right.kind==="file"&&left.size===right.size&&left.hash===right.hash)}var REVIEWER_SCOPE_CAPTURE_CHUNK_BYTES=262144,REVIEWER_SCOPE_CAPTURE_ATTEMPTS=3,REVIEWER_SCOPE_CAPTURE_BATCH_DEADLINE_MS=1e4,_internals69;var init_reviewer_scope_file_fingerprint=__esm(()=>{_internals69={open:fs48.openSync,fstat:(fd,options)=>fs48.fstatSync(fd,options),read:fs48.readSync,close:fs48.closeSync,lstat:fs48.lstatSync,stat:(path76,options)=>fs48.statSync(path76,options),realpathSync:fs48.realpathSync,now:Date.now}});function classifyTaskResult(output){if(!output||typeof output!=="object")return"non_success";let record2=output,nestedRecords=[record2.metadata,record2.result].filter((candidate)=>typeof candidate==="object"&&candidate!==null),records=[record2,...nestedRecords],states=records.flatMap((candidate)=>[candidate.state,candidate.status]).filter((candidate)=>typeof candidate==="string").map((candidate)=>candidate.trim().toLowerCase());if(records.some((candidate)=>candidate.error!==void 0&&candidate.error!==null||Array.isArray(candidate.errors)&&candidate.errors.length>0)||states.some((state2)=>NON_SUCCESS_STATES.has(state2)))return"non_success";let knownStates=new Set([...SUCCESS_STATES,...RUNNING_STATES,...NON_SUCCESS_STATES]);if(states.some((state2)=>!knownStates.has(state2)))return"non_success";let metadata=nestedRecords[0];if(states.some((state2)=>RUNNING_STATES.has(state2))||metadata?.background===!0)return"running";if(states.some((state2)=>SUCCESS_STATES.has(state2)))return"success";if(typeof record2.output==="string")return"success";return Object.keys(record2).length===0?"success":"non_success"}var SUCCESS_STATES,RUNNING_STATES,NON_SUCCESS_STATES;var init_task_result_classifier=__esm(()=>{SUCCESS_STATES=new Set(["completed","complete","success","succeeded"]),RUNNING_STATES=new Set(["running","pending","queued","in_progress"]),NON_SUCCESS_STATES=new Set(["error","failed","failure","cancelled","canceled","stale","timeout","timed_out","aborted"])});function isExecutionEpisodeArmed(sessionID){return swarmState.agentSessions.get(sessionID)?.executionEpisodeArmed===!0}function setExecutionEpisodeArmed(sessionID,armed){let session=swarmState.agentSessions.get(sessionID);if(!session)return!1;return session.executionEpisodeArmed=armed,!0}var init_execution_episode=__esm(()=>{init_state2()});import*as fs49 from"node:fs";import*as path76 from"node:path";function newState(now){return{armed:!1,nonProgressCalls:0,lastToolCallAt:now,warnIssued:!1,denyTelemetryIssued:!1,workspaceBaseline:null,needsWorkspaceBaseline:!1,callsSinceWorkspaceProbe:0}}function touchState(sessionID,now){let state2=stallStates.get(sessionID)??newState(now);stallStates.delete(sessionID),stallStates.set(sessionID,state2);while(stallStates.size>MAX_TRACKED_STALL_SESSIONS){let stalest=stallStates.keys().next().value;if(stalest===void 0||stalest===sessionID)break;stallStates.delete(stalest)}return state2}function clearStreak(state2){state2.nonProgressCalls=0,state2.warnIssued=!1,state2.denyTelemetryIssued=!1,state2.callsSinceWorkspaceProbe=0}function disarmEpisode(sessionID,state2){state2.armed=!1,state2.workspaceBaseline=null,state2.needsWorkspaceBaseline=!1,clearStreak(state2),setExecutionEpisodeArmed(sessionID,!1)}function armEpisode(sessionID,state2){if(!state2.armed)state2.armed=!0,state2.needsWorkspaceBaseline=!0,clearStreak(state2);_internals70.ensureArchitectSession(sessionID),setExecutionEpisodeArmed(sessionID,!0)}function isArchitectStallSession(sessionID){let activeAgent=swarmState.activeAgent.get(sessionID);if(activeAgent)return stripKnownSwarmPrefix(activeAgent)===ORCHESTRATOR_NAME;let session=swarmState.agentSessions.get(sessionID);if(session)return stripKnownSwarmPrefix(session.agentName)===ORCHESTRATOR_NAME;return!1}function ensureArchitectSession(sessionID){try{if(swarmState.agentSessions.has(sessionID))return;let agentName=swarmState.activeAgent.get(sessionID)??ORCHESTRATOR_NAME;ensureAgentSession(sessionID,agentName)}catch{}}function canonicalDispatchRole(tool,args2){if(!isTaskToolId(tool??""))return null;let subagentType=args2?.subagent_type;if(typeof subagentType!=="string"||subagentType.length===0)return null;let stripped=stripKnownSwarmPrefix(subagentType).toLowerCase();if(isKnownCanonicalRole(stripped))return stripped;let resolved=getCanonicalAgentRole(subagentType).toLowerCase();if(isKnownCanonicalRole(resolved))return resolved;return subagentType.toLowerCase()}function rememberDispatchRole(callID,role){if(!callID)return;pendingDispatchRoles.delete(callID),pendingDispatchRoles.set(callID,role);while(pendingDispatchRoles.size>MAX_PENDING_DISPATCH_ROLES){let oldest=pendingDispatchRoles.keys().next().value;if(oldest===void 0)break;pendingDispatchRoles.delete(oldest)}}function takeDispatchRole(callID){if(!callID)return null;let role=pendingDispatchRoles.get(callID);if(role===void 0)return null;return pendingDispatchRoles.delete(callID),role}function readPlanOpenTaskState(directory){try{if(typeof directory!=="string"||directory.trim().length===0)return"unknown";let raw=fs49.readFileSync(path76.join(directory,".swarm","plan.json"),"utf-8"),plan=JSON.parse(raw);if(!Array.isArray(plan?.phases))return"unknown";for(let phase of plan.phases){if(!Array.isArray(phase?.tasks))continue;for(let task of phase.tasks)if(task?.status==="in_progress")return"open"}return"none"}catch{return"unknown"}}function isWriteToolName(normalizedTool){return WRITE_TOOL_NAMES.includes(normalizedTool)}function positiveInt(value,fallback){if(typeof value!=="number"||!Number.isFinite(value)||value<1)return fallback;return Math.floor(value)}function executionStallAdvisoryText(count){return`EXECUTION STALL: ${count} tool calls with no delegation completion, no file changes, and no status update. STOP investigating; delegate the work or report BLOCKED to the user.`}function executionStallDenialText(count,normalizedTool){return`EXECUTION_STALL: ${count} tool calls in this execution episode with no delegation completion, no file changes, and no task-status update. Direct investigation with \`${normalizedTool}\` is blocked. Productive avenues remain OPEN and are the way out: DELEGATE the work or the verification with `+"`Task` (coder / reviewer / test_engineer) — a completed dispatch clears this block and is how you "+"run builds and tests from here — or call `update_task_status`, or report the blocker to the user "+"with what you have already tried. Do NOT retry this call."}function observeExecutionStallToolCall(params){let{sessionID,tool,args:args2,callID,options}=params;try{if(options?.enabled===!1)return;if(!isArchitectStallSession(sessionID))return;let now=_internals70.now(),state2=touchState(sessionID,now),episodeMs=positiveInt(options?.episodeMinutes,DEFAULT_EXECUTION_STALL_EPISODE_MINUTES)*60000;if(state2.armed&&now-state2.lastToolCallAt>=episodeMs)disarmEpisode(sessionID,state2);state2.lastToolCallAt=now;let role=canonicalDispatchRole(tool,args2);if(role){if(rememberDispatchRole(callID,role),MUTATING_DELEGATION_ROLES.has(role))armEpisode(sessionID,state2)}if(!state2.armed)return;state2.nonProgressCalls+=1,state2.callsSinceWorkspaceProbe+=1;let warnCalls=positiveInt(options?.warnCalls,DEFAULT_EXECUTION_STALL_WARN_CALLS);if(state2.nonProgressCalls>=warnCalls&&!state2.warnIssued){state2.warnIssued=!0;let session=swarmState.agentSessions.get(sessionID);if(session)pushAdvisory(session,executionStallAdvisoryText(state2.nonProgressCalls));telemetry.executionStallWarning(sessionID,state2.nonProgressCalls,warnCalls)}}catch{}}function enforceExecutionStallDenial(params){let{sessionID,tool,options}=params,denial=null;try{if(options?.enabled===!1)return;let state2=stallStates.get(sessionID);if(!state2?.armed)return;if(!isArchitectStallSession(sessionID))return;let stopCalls=positiveInt(options?.stopCalls,DEFAULT_EXECUTION_STALL_STOP_CALLS);if(state2.nonProgressCalls<stopCalls)return;let normalizedTool=normalizeToolNameLowerCase(tool??"");if(!EXECUTION_STALL_DENIED_TOOLS.has(normalizedTool))return;if(!state2.denyTelemetryIssued){state2.denyTelemetryIssued=!0;try{telemetry.executionStallDenied(sessionID,normalizedTool,state2.nonProgressCalls,stopCalls)}catch{}}denial=executionStallDenialText(state2.nonProgressCalls,normalizedTool)}catch{return}if(denial)throw Error(denial)}async function probeWorkspaceProgress(directory,baseline){try{let authoritative=baseline?await _internals70.changedFilesSinceSnapshotAsync(directory,baseline):null,current=await _internals70.captureWorkspaceSnapshotAsync(directory);if(!baseline)return{progress:!1,next:current};if(authoritative!==null)return{progress:authoritative.length>0,next:current};if(baseline.gitHead&¤t?.gitHead&&baseline.gitHead!==current.gitHead)return{progress:!0,next:current};let before=new Set(baseline.changedFiles??[]);return{progress:(current?.changedFiles??[]).some((entry)=>!before.has(entry)),next:current}}catch{return{progress:!1,next:baseline}}}async function recordExecutionStallToolAfter(params){let{sessionID,tool,callID,args:args2,output,directory,options}=params;try{let dispatchRole=takeDispatchRole(callID);if(options?.enabled===!1)return;if(!isArchitectStallSession(sessionID))return;let normalizedTool=normalizeToolNameLowerCase(tool??""),succeeded=classifyTaskResult(output)==="success",progress=!1,armOnStatus=!1,taskSettled=!1;if(normalizedTool==="update_task_status"){let status=readUpdateTaskStatusOutcome(output,args2);if(status.ok)progress=!0,armOnStatus=status.value==="in_progress",taskSettled=!armOnStatus}else if(dispatchRole!==null)progress=succeeded&&MUTATING_DELEGATION_ROLES.has(dispatchRole);else if(isWriteToolName(normalizedTool))progress=succeeded;let now=_internals70.now(),existing=stallStates.get(sessionID);if(!existing&&!armOnStatus)return;let state2=existing??touchState(sessionID,now);if(armOnStatus)armEpisode(sessionID,state2);if(!state2.armed)return;if(taskSettled&&_internals70.readPlanOpenTaskState(directory)==="none"){disarmEpisode(sessionID,state2);return}if(progress){clearStreak(state2),state2.needsWorkspaceBaseline=!0;return}if(state2.needsWorkspaceBaseline){state2.needsWorkspaceBaseline=!1,state2.callsSinceWorkspaceProbe=0;try{state2.workspaceBaseline=await _internals70.captureWorkspaceSnapshotAsync(directory)}catch{state2.workspaceBaseline=null}return}if(state2.callsSinceWorkspaceProbe<WORKSPACE_PROBE_EVERY_CALLS)return;if(state2.callsSinceWorkspaceProbe=0,_internals70.readPlanOpenTaskState(directory)==="none"){disarmEpisode(sessionID,state2);return}let probe2=await probeWorkspaceProgress(directory,state2.workspaceBaseline);if(state2.workspaceBaseline=probe2.next,probe2.progress)clearStreak(state2)}catch{}}function readUpdateTaskStatusOutcome(output,args2){let text=output&&typeof output==="object"?output.output:void 0;if(typeof text!=="string")return{ok:!1,value:null};try{let parsed=JSON.parse(text);if(parsed?.success!==!0)return{ok:!1,value:null};let fromOutput=typeof parsed.new_status==="string"?parsed.new_status:null,fromArgs=typeof args2?.status==="string"?args2.status:null;return{ok:!0,value:(fromOutput??fromArgs)?.toLowerCase()??null}}catch{return{ok:!1,value:null}}}var DEFAULT_EXECUTION_STALL_WARN_CALLS=30,DEFAULT_EXECUTION_STALL_STOP_CALLS=60,DEFAULT_EXECUTION_STALL_EPISODE_MINUTES=30,MUTATING_DELEGATION_ROLES,EXECUTION_STALL_DENIED_TOOLS,WORKSPACE_PROBE_EVERY_CALLS=10,MAX_TRACKED_STALL_SESSIONS=200,MAX_PENDING_DISPATCH_ROLES=256,stallStates,pendingDispatchRoles,_internals70;var init_execution_stall=__esm(()=>{init_workspace_snapshot();init_constants();init_schema();init_state2();init_telemetry();init_normalize_tool_name();init_task_result_classifier();init_execution_episode();MUTATING_DELEGATION_ROLES=new Set(["coder","reviewer","test_engineer","security_reviewer"]),EXECUTION_STALL_DENIED_TOOLS=new Set(["read","glob","grep","bash","shell"]),stallStates=new Map,pendingDispatchRoles=new Map;_internals70={now:()=>Date.now(),captureWorkspaceSnapshotAsync,changedFilesSinceSnapshotAsync,ensureArchitectSession,readPlanOpenTaskState}});import*as path77 from"node:path";function isConfigFilePath(filePath,cwd,extraGlobs){let normalized=path77.relative(path77.resolve(cwd),path77.resolve(cwd,filePath)).replace(/\\/g,"/"),{zone}=classifyFile(normalized);if(zone==="config")return!0;let allGlobs=extraGlobs&&extraGlobs.length>0?[...KNOWN_VERIFIER_CONFIG_GLOBS,...extraGlobs]:KNOWN_VERIFIER_CONFIG_GLOBS;for(let glob of allGlobs)if(getGlobMatcher(glob)(normalized))return!0;return!1}function isWriteTool(toolName){let normalized=normalizeToolName(toolName);return WRITE_TOOL_NAMES.includes(normalized)}function isOutsideSwarmDir(filePath,directory){if(!filePath)return!1;let swarmDir=path77.resolve(directory,".swarm"),resolved=path77.resolve(directory,filePath),relative19=path77.relative(swarmDir,resolved);return relative19.startsWith("..")||path77.isAbsolute(relative19)}function isSourceCodePath(filePath){if(!filePath)return!1;let normalized=filePath.replace(/\\/g,"/");return![/^README(\..+)?$/i,/\/README(\..+)?$/i,/^CHANGELOG(\..+)?$/i,/\/CHANGELOG(\..+)?$/i,/^package\.json$/,/\/package\.json$/,/^\.github\//,/\/\.github\//,/^docs\//,/\/docs\//,/^\.swarm\//,/\/\.swarm\//].some((pattern)=>pattern.test(normalized))}function hasTraversalSegments(filePath){if(!filePath)return!1;let normalized=filePath.replace(/\\/g,"/");return normalized.startsWith("..")||normalized.includes("/../")||normalized.endsWith("/..")}function isInDeclaredScope(filePath,scopeEntries,cwd){return isPathWithinDeclaredScope(filePath,scopeEntries,cwd)}function redactShellCommand(cmd){if(typeof cmd!=="string")return"";let out=cmd.replace(/\/home\/[^/\s"']+/g,"~").replace(/[A-Za-z]:\\Users\\[^\\\s"']+/gi,"~").replace(/\/Users\/[^/\s"']+/g,"~").replace(/\\\\[^\\\s"']+\\[^\\\s"']+\\[^\\\s"']+(?:\\[^\s"']*)?/g,"~");out=out.replace(/([a-zA-Z][a-zA-Z0-9+.-]{0,32}:\/\/[^\s"'@/]+):([^@\s"'/]+)@/g,"$1:[REDACTED]@");let VALUE=String.raw`(?:"[^"]*"|'[^']*'|\S+)`;return out=out.replace(new RegExp(String.raw`\b([A-Z_]{0,64}(?:TOKEN|SECRET|PASSWORD|PASSWD|API[_]?KEY|APIKEY|AUTH|CREDENTIAL|PRIVATE[_]?KEY|ACCESS[_]?KEY|_KEY)[A-Z_0-9]{0,64})\s*=\s*`+VALUE,"gi"),"$1=[REDACTED]"),out=out.replace(new RegExp(String.raw`(\$env:[A-Za-z_][A-Za-z_0-9]{0,64}(?:TOKEN|SECRET|PASSWORD|PASSWD|API[_]?KEY|APIKEY|AUTH|CREDENTIAL|PRIVATE[_]?KEY|ACCESS[_]?KEY|_KEY)[A-Za-z_0-9]{0,64})(\s*=\s*)`+VALUE,"gi"),"$1=[REDACTED]"),out=out.replace(new RegExp(String.raw`\b(set|SET)(\s+"?)([A-Za-z_][A-Za-z_0-9]{0,64}(?:TOKEN|SECRET|PASSWORD|PASSWD|API[_]?KEY|APIKEY|AUTH|CREDENTIAL|PRIVATE[_]?KEY|ACCESS[_]?KEY|_KEY)[A-Za-z_0-9]{0,64})(=?)(\s+)`+VALUE,"gi"),"$1$2$3=[REDACTED]"),out=out.replace(/--([a-zA-Z-]*(?:token|secret|password|passwd|api[_-]?key|apikey|auth|credential|private[_-]?key|access[_-]?key)[a-zA-Z-]*)=(\S+)/gi,"--$1=[REDACTED]"),out=out.replace(/(--[a-zA-Z-]*(?:token|secret|password|passwd|api[_-]?key|apikey|auth|credential|private[_-]?key|access[_-]?key)[a-zA-Z-]*)(\s+)(?!--)(\S+)/gi,"$1$2[REDACTED]"),out=out.replace(/\b(Bearer|Basic)\s+[A-Za-z0-9+/=._-]{4,}/gi,"$1 [REDACTED]"),out=out.replace(/(-H\s+['"]?(?:Authorization|X-API-Key|X-Auth-Token|[A-Za-z][A-Za-z-]*-(?:key|token|secret|auth|credential)):\s*)([^'">\s][^'">\n]*)(['"]?)/gi,"$1[REDACTED]$3"),out=out.replace(/\bsk-[A-Za-z0-9_-]{20,}/g,"[REDACTED:openai]").replace(/\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{20,}/g,"[REDACTED:github]").replace(/\bgithub_pat_[A-Za-z0-9_]{22,}/g,"[REDACTED:github]").replace(/\bAKIA[0-9A-Z]{16}\b/g,"[REDACTED:aws]").replace(/\bxox[baprs]-[A-Za-z0-9-]{10,}/g,"[REDACTED:slack]").replace(/\bAIza[A-Za-z0-9_-]{30,}/g,"[REDACTED:google]"),out=out.replace(/[A-Za-z0-9+/]{80,}={0,2}/g,(run)=>/[A-Z]/.test(run)&&/[a-z]/.test(run)&&/[0-9]/.test(run)?"[REDACTED:base64]":run),out}var KNOWN_VERIFIER_CONFIG_GLOBS;var init_helpers=__esm(()=>{init_constants();init_path_identity();init_normalize_tool_name();init_file_authority();KNOWN_VERIFIER_CONFIG_GLOBS=["**/oxlintrc*","**/.oxlintrc*","**/.eslintrc*","**/eslint.config.*","**/.prettierrc*","**/prettier.config.*","**/biome.jsonc","**/.secretscanignore","**/.golangci*"]});function charsToTokens(chars){return estimateTokensFromCharCount(chars)}function allocateInjectionBudget(systemEnhancerDemandTokens,knowledgeInjectorDemandChars,config2){let budget=config2.totalBudgetTokens,seDemand=Math.max(0,systemEnhancerDemandTokens),kiChars=Math.max(0,knowledgeInjectorDemandChars),ceiling=Math.max(0,budget),kiDemand=charsToTokens(kiChars);if(seDemand+kiDemand<=ceiling)return{systemEnhancerTokens:seDemand,knowledgeInjectorTokens:kiDemand,totalTokens:seDemand+kiDemand};if(seDemand>=ceiling)return{systemEnhancerTokens:ceiling,knowledgeInjectorTokens:0,totalTokens:ceiling};if(kiDemand>=ceiling)return{systemEnhancerTokens:0,knowledgeInjectorTokens:ceiling,totalTokens:ceiling};let totalDemand=seDemand+kiDemand,seShare=Math.floor(seDemand/totalDemand*ceiling),kiShare=ceiling-seShare;return{systemEnhancerTokens:seShare,knowledgeInjectorTokens:kiShare,totalTokens:ceiling}}function evictTurnLedgers(){while(turnLedgers.size>MAX_TRACKED_SESSIONS){let firstKey=turnLedgers.keys().next().value;if(firstKey===void 0)break;turnLedgers.delete(firstKey)}}function getOrCreateAccounting(ledger,producer,surface){let accounting=ledger.producers.get(producer);if(!accounting)accounting={requested:0,granted:0,emitted:0,truncated:0,surface},ledger.producers.set(producer,accounting);return accounting.surface=surface,accounting}function makeInjectionBudgetReceipt(data){let receipt=Object.freeze({});return injectionBudgetReceipts.set(receipt,{...data,state:"pending"}),receipt}function settleInjectionBudgetReceipt(receipt,action){let data=injectionBudgetReceipts.get(receipt);if(!data||data.state!=="pending")return!1;let ledger=turnLedgers.get(data.sessionID);if(!ledger||ledger.generation!==data.generation)return data.state="stale",!1;let accounting=ledger.producers.get(data.producer);if(!accounting||accounting!==data.accounting||accounting.surface!==data.surface)return data.state="stale",!1;if(action==="commit")return data.state="committed",!0;if(accounting.requested=Math.max(0,accounting.requested-data.requestedTokens),accounting.granted=Math.max(0,accounting.granted-data.grantedTokens),data.retractEmissionOnRefund){let retracted=Math.min(accounting.emitted,data.emittedTokensOnRefund);accounting.emitted-=retracted,accounting.truncated+=retracted}if(accounting.requested===0&&accounting.granted===0&&accounting.emitted===0&&accounting.truncated===0)ledger.producers.delete(data.producer);return ledger.used=Math.max(0,ledger.used-data.chargedTokens),data.state="refunded",!0}function beginTurnLedger(sessionID,totalBudget,ceilingActive){let generation=++turnGenerationCounter;return turnLedgers.set(sessionID,{generation,totalBudget:Math.max(0,totalBudget),ceilingActive,used:0,producers:new Map}),evictTurnLedgers(),generation}function applyTurnBudgetClaim(sessionID,producer,requestedTokens,opts){let requested=Math.max(0,requestedTokens),localMax=opts?.localMaxTokens===void 0?requested:Math.max(0,opts.localMaxTokens),surface=opts?.surface??"system",ledger=turnLedgers.get(sessionID);if(!ledger)return{result:{granted:Math.min(requested,localMax),ledgerPresent:!1,ceilingActive:!1}};let accounting=getOrCreateAccounting(ledger,producer,surface);accounting.requested+=requested;let granted,charged=0;if(!ledger.ceilingActive)granted=Math.min(requested,localMax);else{let remaining=Math.max(0,ledger.totalBudget-ledger.used);granted=Math.min(requested,localMax,remaining),charged=granted,ledger.used+=charged}return accounting.granted+=granted,{result:{granted,ledgerPresent:!0,ceilingActive:ledger.ceilingActive},receiptData:{sessionID,generation:ledger.generation,producer,surface,accounting,requestedTokens:requested,grantedTokens:granted,chargedTokens:charged,emittedTokensOnRefund:0,retractEmissionOnRefund:!1}}}function claimTurnBudget(sessionID,producer,requestedTokens,opts){return applyTurnBudgetClaim(sessionID,producer,requestedTokens,opts).result}function claimTurnBudgetWithReceipt(sessionID,producer,requestedTokens,opts){let mutation=applyTurnBudgetClaim(sessionID,producer,requestedTokens,opts);return{...mutation.result,receipt:mutation.receiptData?makeInjectionBudgetReceipt(mutation.receiptData):void 0}}function recordProducerGrant(sessionID,producer,requestedTokens,grantedTokens,surface){applyProducerGrant(sessionID,producer,requestedTokens,grantedTokens,surface)}function applyProducerGrant(sessionID,producer,requestedTokens,grantedTokens,surface,expectedGeneration){let ledger=turnLedgers.get(sessionID);if(!ledger||expectedGeneration!==void 0&&ledger.generation!==expectedGeneration)return;let accounting=getOrCreateAccounting(ledger,producer,surface),requested=Math.max(0,requestedTokens);accounting.requested+=requested;let granted=Math.max(0,grantedTokens);accounting.granted+=granted;let charged=0;if(ledger.ceilingActive)charged=Math.min(granted,Math.max(0,ledger.totalBudget-ledger.used)),ledger.used+=charged;return{data:{sessionID,generation:ledger.generation,producer,surface,accounting,requestedTokens:requested,grantedTokens:granted,chargedTokens:charged,emittedTokensOnRefund:0,retractEmissionOnRefund:!1}}}function recordProducerGrantWithReceipt(sessionID,producer,requestedTokens,grantedTokens,surface,options={}){let mutation=applyProducerGrant(sessionID,producer,requestedTokens,grantedTokens,surface,options.expectedGeneration);if(!mutation)return;return makeInjectionBudgetReceipt({...mutation.data,retractEmissionOnRefund:options.retractEmissionOnRefund===!0,emittedTokensOnRefund:Math.max(0,options.emittedTokensOnRefund??0)})}function recordProducerEmission(sessionID,producer,emittedTokens,truncatedTokens,surface,options){applyProducerEmission(sessionID,producer,emittedTokens,truncatedTokens,surface,options?.expectedGeneration)}function applyProducerEmission(sessionID,producer,emittedTokens,truncatedTokens,surface,expectedGeneration){let ledger=turnLedgers.get(sessionID);if(!ledger||expectedGeneration!==void 0&&ledger.generation!==expectedGeneration)return;let accounting=getOrCreateAccounting(ledger,producer,surface),emitted=Math.max(0,emittedTokens);return accounting.emitted+=emitted,accounting.truncated+=Math.max(0,truncatedTokens),{sessionID,generation:ledger.generation,producer,surface,accounting,requestedTokens:0,grantedTokens:0,chargedTokens:0,emittedTokensOnRefund:emitted,retractEmissionOnRefund:!0}}function recordProducerEmissionWithReceipt(sessionID,producer,emittedTokens,surface,options){let receiptData=applyProducerEmission(sessionID,producer,emittedTokens,0,surface,options?.expectedGeneration);return receiptData?makeInjectionBudgetReceipt(receiptData):void 0}function deductProducerEmission(sessionID,producer,removedTokens,options){let ledger=turnLedgers.get(sessionID);if(!ledger||options?.expectedGeneration!==void 0&&ledger.generation!==options.expectedGeneration)return;let accounting=ledger.producers.get(producer);if(!accounting)return;accounting.emitted=Math.max(0,accounting.emitted-Math.max(0,removedTokens))}function getTurnLedgerSummary(sessionID){let ledger=turnLedgers.get(sessionID);if(!ledger)return null;return{generation:ledger.generation,totalBudget:ledger.totalBudget,ceilingActive:ledger.ceilingActive,used:ledger.used,producers:Array.from(ledger.producers.entries()).map(([producer,accounting])=>({producer,requested:accounting.requested,granted:accounting.granted,emitted:accounting.emitted,truncated:accounting.truncated,surface:accounting.surface}))}}function getProducerEmission(sessionID,producer){return turnLedgers.get(sessionID)?.producers.get(producer)?.emitted??0}function commitInjectionBudgetReceipt(receipt){return settleInjectionBudgetReceipt(receipt,"commit")}function refundInjectionBudgetReceipt(receipt){return settleInjectionBudgetReceipt(receipt,"refund")}function advanceTurnGeneration(sessionID){turnLedgers.delete(sessionID)}function clearAllTurnLedgers(){turnLedgers.clear()}var injectionBudgetReceipts,turnLedgers,MAX_TRACKED_SESSIONS=256,turnGenerationCounter=0;var init_injection_budget=__esm(()=>{init_utils2();injectionBudgetReceipts=new WeakMap,turnLedgers=new Map});function extractStatusCode(errorMsg){let match=errorMsg.match(/\b(408|429|500|502|503|504|529)\b/);if(match)return parseInt(match[1],10);return null}function isTransientProviderError(signal){if(!signal)return!1;if(TRANSIENT_MODEL_ERROR_PATTERN.test(signal))return!0;if(QUOTA_ERROR_PATTERN.test(signal))return!0;let status=extractStatusCode(signal);return status!==null&&TRANSIENT_STATUS_CODES.has(status)}function isQuotaError(signal){return signal.length>0&"A_ERROR_PATTERN.test(signal)}var TRANSIENT_STATUS_CODES,TRANSIENT_MODEL_ERROR_PATTERN,QUOTA_ERROR_PATTERN,REQUEST_SHAPE_REJECTION_PATTERN;var init_provider_error_classification=__esm(()=>{TRANSIENT_STATUS_CODES=new Set([408,429,500,502,503,504,529]);TRANSIENT_MODEL_ERROR_PATTERN=/rate.?limit|429|500|502|503|504|529|timeout|overloaded|model.?not.?found|temporarily.?unavailable|provider[_\s-]?unavailable|server.?error|network.?connection.?lost|connection.?(refused|reset|timeout|lost)|bad.?gateway|gateway.?timeout|internal.?server.?error|service.?unavailable|ECONNRESET|ECONNREFUSED|ETIMEDOUT|EPIPE|ENOTFOUND|broken.?pipe|dns(?:[\s_-]+(?:resolution)?)?[\s_-]+fail|name.?not.?resolved|EAI_AGAIN/i,QUOTA_ERROR_PATTERN=/quota|usage.?limit|insufficient.?(?:quota|credits?)|\b402\b|payment.?required|credit.?balance|out of credits|billing.?(?:hard.?)?limit/i,REQUEST_SHAPE_REJECTION_PATTERN=/\b(?:single|one|only|exactly)[^.]{0,48}?\bsystem\s+messages?\b|\bmultiple\s+system\s+messages?\b|\bsystem\s+messages?\s+(?:are\s+)?not\s+supported\b/i});function extractModelInfo(messages){if(!messages||messages.length===0)return{};for(let i=messages.length-1;i>=0;i--){let message=messages[i];if(!message?.info)continue;if(message.info.role==="assistant"){let modelID=message.info.modelID,providerID=message.info.providerID;if(modelID||providerID)return{...modelID?{modelID}:{},...providerID?{providerID}:{}}}}return{}}function extractSessionId2(messages){if(!messages||messages.length===0)return;for(let i=messages.length-1;i>=0;i--){let sessionID=messages[i]?.info?.sessionID;if(typeof sessionID==="string"&&sessionID.length>0)return sessionID}return}function rememberBoundedModelIdentity(set2,key){if(set2.has(key))return!1;while(set2.size>=MAX_TRACKED_MODEL_IDENTITIES){let oldest=set2.values().next().value;if(oldest===void 0)break;set2.delete(oldest)}return set2.add(key),!0}function classifyModelLimitSource(resolution){return SOURCE_CLASS_BY_RESOLUTION[resolution]}function lookupStaticModelLimit(modelID,providerID){if(providerID&&PROVIDER_CAPS[providerID]!==void 0)return{tokens:PROVIDER_CAPS[providerID],table:"provider_cap"};if(modelID){let native=findNativeLimit(modelID);if(native!==void 0)return{tokens:native,table:"native"}}return}function resolveModelLimit(modelID,providerID,configOverrides={},liveContextLimit,directory){let invalidOverride=recordInvalidOverrides(modelID,providerID,configOverrides);warnNormalizedKeyCollisions(configOverrides);let resolution=resolveContextWindow({userLimits:configOverrides,modelID,providerID,liveContextLimit,fallbackLookup:lookupStaticModelLimit});return logFirstCall(modelID??"",providerID??"",resolution.source,resolution.tokens),maybeWarnUndersizedDefault(modelID,providerID,resolution.source,resolution.tokens,liveContextLimit),_internals71.observeResolution({modelID,providerID,directory,resolution:resolution.source,aliasKeyClass:resolution.source==="user_provider_model"?"compound":resolution.source==="user_model"?"model":resolution.source==="user_default"?"default":void 0,invalidOverride}),{limit:resolution.tokens,source:classifyModelLimitSource(resolution.source),resolution:resolution.source}}function recordInvalidOverrides(modelID,providerID,configOverrides){if(!configOverrides||typeof configOverrides!=="object")return!1;let normalizedModel=modelID?.trim().toLowerCase(),normalizedCompound=`${providerID??""}/${modelID??""}`.trim().toLowerCase(),relevantInvalid=!1;for(let[key,value]of Object.entries(configOverrides)){if(isUsableConfiguredWindow(value))continue;let keyClass=key==="default"?"default":key.includes("/")?"compound":"model",normalizedKey=key.trim().toLowerCase();if(keyClass==="default"||keyClass==="model"&&normalizedModel!==void 0&&normalizedKey===normalizedModel||keyClass==="compound"&&normalizedKey===normalizedCompound)relevantInvalid=!0;let identity=`${modelID||"unknown"}::${providerID||"unknown"}::${keyClass}::${String(value)}`;if(rememberBoundedModelIdentity(invalidOverrideReports,identity))warn(`[model-limits] context_budget.model_limits.${key}=${String(value)} for ${modelID||"(no model)"}@${providerID||"(no provider)"} is not a usable limit (finite number ≥ 1); skipping it — not coercing.`,{modelID,providerID,keyClass,value})}return relevantInvalid}function warnNormalizedKeyCollisions(configOverrides){let byNormalized=new Map;for(let key of Object.keys(configOverrides)){let normalized=key.trim().toLowerCase();byNormalized.set(normalized,[...byNormalized.get(normalized)??[],key])}for(let[normalized,keys]of byNormalized){if(keys.length<2)continue;let identity=`collision::${normalized}`;if(!rememberBoundedModelIdentity(invalidOverrideReports,identity))continue;warn(`[model-limits] context_budget.model_limits has ${keys.length} keys that normalize identically (${keys.join(", ")}); only the last one in config order takes effect under normalized matching.`,{keys})}}function findNativeLimit(modelID){if(NATIVE_MODEL_LIMITS[modelID]!==void 0)return NATIVE_MODEL_LIMITS[modelID];let bestMatch;for(let key of Object.keys(NATIVE_MODEL_LIMITS))if(modelID.startsWith(key)){if(!bestMatch||key.length>bestMatch.length)bestMatch=key}return bestMatch?NATIVE_MODEL_LIMITS[bestMatch]:void 0}function logFirstCall(modelID,providerID,source,limit){let key=`${modelID||"unknown"}::${providerID||"unknown"}`;if(rememberBoundedModelIdentity(loggedFirstCalls,key))log(`[model-limits] Resolved limit for ${modelID||"(no model)"}@${providerID||"(no provider)"}: ${limit} (source: ${source})`)}function maybeWarnUndersizedDefault(modelID,providerID,source,resolvedTokens,liveContextLimit){if(source!=="user_default")return;if(!isUsableContextWindow(liveContextLimit))return;let liveTokens=Math.floor(liveContextLimit);if(liveTokens<=resolvedTokens)return;let key=`${modelID||"unknown"}::${providerID||"unknown"}`;if(!rememberBoundedModelIdentity(warnedUndersizedDefaults,key))return;warn(`[model-limits] context_budget.model_limits.default=${resolvedTokens} is below live model window ${liveTokens} for ${modelID||"(no model)"}@${providerID||"(no provider)"}; keeping the configured default.`,{modelID,providerID,resolvedTokens,liveTokens,source})}var NATIVE_MODEL_LIMITS,PROVIDER_CAPS,MAX_TRACKED_MODEL_IDENTITIES=256,loggedFirstCalls,warnedUndersizedDefaults,SOURCE_CLASS_BY_RESOLUTION,_internals71,invalidOverrideReports;var init_model_limits=__esm(()=>{init_learning_health();init_utils();NATIVE_MODEL_LIMITS={"claude-sonnet-4":200000,"claude-opus-4":200000,"claude-haiku-4":200000,"gpt-5":400000,"gpt-5.1-codex":400000,"gpt-5.1":264000,"gpt-4.1":1047576,"gemini-2.5-pro":1048576,"gemini-2.5-flash":1048576,o3:200000,"o4-mini":200000,"deepseek-r1":163840,"deepseek-chat":163840,"qwen3.5":131072,"MiniMax-M3":1e6,"MiniMax-M2.7":204800},PROVIDER_CAPS={copilot:128000,"github-copilot":128000};loggedFirstCalls=new Set,warnedUndersizedDefaults=new Set;SOURCE_CLASS_BY_RESOLUTION={user_provider_model:"override",user_model:"override",user_default:"override",live_model_limit:"host",static_provider_cap:"provider_cap",static_native:"native",static_default:"fallback"};_internals71={observeResolution:observeModelLimitResolution};invalidOverrideReports=new Set});function rememberCountedAssistantMsg(map2,sessionId,messageId){map2.delete(sessionId),map2.set(sessionId,messageId);while(map2.size>MAX_TRACKED_COUNTED_ASSISTANT_MSGS){let stalest=map2.keys().next().value;if(stalest===void 0)break;map2.delete(stalest)}}function boundAdvisoryBytes(advisories,maxBytes){let kept=[...advisories],sizeOf=(arr)=>arr.reduce((n,m)=>n+m.length+5,0);while(sizeOf(kept)>maxBytes&&kept.length>1)kept.shift();return{kept,truncated:kept.length<advisories.length}}function getMessageText(message){if(!message?.parts)return"";return message.parts.filter((part)=>part?.type==="text"&&typeof part.text==="string").map((part)=>part.text).join(`
|
|
1006
1007
|
`)}function getMostRecentAssistantText(messages){for(let i=messages.length-1;i>=0;i--)if(messages[i]?.info?.role==="assistant")return getMessageText(messages[i]);return""}function isTransientProviderFailureText(text){if(!text.trim())return!1;if(!/provider[_\s-]?unavailable|network\s+connection\s+lost|ECONNRESET|ECONNREFUSED|ETIMEDOUT|EPIPE|ENOTFOUND|broken.?pipe|dns(?:[\s_-]+(?:resolution)?)?[\s_-]+fail|name.?not.?resolved|EAI_AGAIN|connection\s+reset|connection\s+refused/i.test(text))return!1;let status=extractStatusCode(text);return status!==null&&TRANSIENT_STATUS_CODES.has(status)||TRANSIENT_MODEL_ERROR_PATTERN.test(text)}function getProviderFailureFingerprint(text){return String(hashArgs({providerFailure:text.slice(-4000)}))}function createMessagesTransformHandler(ctx){let{effectiveDirectory,cfg,requiredQaGates,requireReviewerAndTestEngineer,consecutiveNoToolTurns,lastCountedAssistantMsgId}=ctx;return async(_input,output)=>{let messages=output.messages;if(!messages||messages.length===0)return;let lastMessage=messages[messages.length-1],sessionId=lastMessage.info?.sessionID;if(!sessionId)return;let session=swarmState.agentSessions.get(sessionId),activeAgent=swarmState.activeAgent.get(sessionId)??session?.agentName,targetAgent=[...messages].reverse().find((message)=>message.info?.role==="user"&&typeof message.info.agent==="string"&&message.info.agent.length>0)?.info.agent;{let configuredModel=targetAgent?ctx.resolveAgentModel?.(targetAgent):void 0,targetModel=configuredModel?parseAgentModel(configuredModel):void 0,{modelID}=targetModel??extractModelInfo(messages);if(modelID&&isLowCapabilityModel(modelID))for(let msg of messages){if(msg.info?.role!=="system")continue;for(let part of msg.parts)try{if(part==null)continue;if(part.type!=="text"||typeof part.text!=="string")continue;if(!part.text.includes("<!-- BEHAVIORAL_GUIDANCE_START -->"))continue;part.text=part.text.replace(/<!--\s*BEHAVIORAL_GUIDANCE_START\s*-->[\s\S]*?<!--\s*BEHAVIORAL_GUIDANCE_END\s*-->/g,"[Enforcement: programmatic gates active]")}catch(error49){log("[Guardrails] behavioral guidance replacement failed",{error:error49 instanceof Error?error49.message:String(error49)})}}}let isArchitectSession=activeAgent?stripKnownSwarmPrefix(activeAgent)===ORCHESTRATOR_NAME:session?stripKnownSwarmPrefix(session.agentName)===ORCHESTRATOR_NAME:!1;if(isArchitectSession&&session){let{modelID,providerID}=extractModelInfo(messages);if(modelID){let observedFull=providerID?`${providerID}/${modelID}`:modelID,previousObserved=session.lastObservedModel;if(session.sessionRehydratedAt>0&&session.model_fallback_index===0&&previousObserved&&previousObserved!==observedFull&&!session.resumeModelAdvisoryDone)pushAdvisory(session,`MODEL CHANGED ACROSS RESUME: this run previously observed model "${previousObserved}"; the active model is now "${observedFull}". If this switch was unintended, re-select the intended model (or use /swarm handoff) before continuing.`),session.resumeModelAdvisoryDone=!0;if(!session.configModelAdvisoryDone&&session.model_fallback_index===0){let configuredArchitect=getSwarmAgents()?.architect?.model;if(configuredArchitect&&configuredArchitect!==observedFull&&configuredArchitect!==modelID)pushAdvisory(session,`MODEL CONFIG NOTE: your config pins the architect to "${configuredArchitect}", but the UI has "${observedFull}" active. The UI selection wins for the primary/architect role (its configured model is intentionally not applied), so this difference is expected — switch the UI model if you meant to run "${configuredArchitect}".`),session.configModelAdvisoryDone=!0}session.lastObservedModel=observedFull,session.lastObservedProviderID=providerID}}let guidanceCarriers=findGuidanceCarriers(messages);if(isArchitectSession&&session){let lastAssistantText=getMostRecentAssistantText(messages);if(isTransientProviderFailureText(lastAssistantText)){let fingerprint2=getProviderFailureFingerprint(lastAssistantText),alreadyPending=session.pendingAdvisoryMessages?.some((message)=>message.startsWith(TRANSIENT_PROVIDER_RECOVERY_TAG)),alreadyInjected=guidanceCarriers.some((message)=>getMessageText(message).includes(TRANSIENT_PROVIDER_RECOVERY_TAG));if(session.lastProviderRecoveryFingerprint!==fingerprint2&&!alreadyPending&&!alreadyInjected)pushAdvisory(session,`${TRANSIENT_PROVIDER_RECOVERY_TAG}: The previous Architect response appears to have been interrupted by a transient provider/network error. On this turn, continue from the last stable step, inspect current repo or plan state if needed, and keep working instead of treating the interrupted response as task completion.`),session.lastProviderRecoveryFingerprint=fingerprint2}else session.lastProviderRecoveryFingerprint=void 0}if(isArchitectSession){let countedMsgId=lastCountedAssistantMsgId.get(sessionId);if(countedMsgId!==void 0){let countedIdx=messages.findIndex((m)=>m.info?.id===countedMsgId);if(countedIdx<0)lastCountedAssistantMsgId.delete(sessionId);else if(messages.slice(countedIdx+1).some((m)=>m.info?.role==="user"))consecutiveNoToolTurns.set(sessionId,0),lastCountedAssistantMsgId.delete(sessionId)}let lastAssistantMsg;for(let i=messages.length-1;i>=0;i--)if(messages[i].info?.role==="assistant"){lastAssistantMsg=messages[i];break}if(lastAssistantMsg)if(lastAssistantMsg.parts?.some((part)=>part.type==="tool_use"))consecutiveNoToolTurns.set(sessionId,0);else{let textLen=lastAssistantMsg.parts?.filter((p)=>p.type==="text"&&typeof p.text==="string").reduce((sum,p)=>sum+p.text.length,0)??0,lastAssistantMsgId=lastAssistantMsg.info?.id,countsAsMedium=textLen>=RUNAWAY_MEDIUM_MIN&&textLen<=4000&&typeof lastAssistantMsgId==="string"&&lastAssistantMsgId.length>0&&isExecutionEpisodeArmed(sessionId);if(countsAsMedium&&lastAssistantMsgId)rememberCountedAssistantMsg(lastCountedAssistantMsgId,sessionId,lastAssistantMsgId);if(textLen>4000||countsAsMedium){let count=(consecutiveNoToolTurns.get(sessionId)??0)+1;consecutiveNoToolTurns.set(sessionId,count);let maxTurns=cfg.runaway_output_max_turns;if(count>=maxTurns){let stopCarrier=ensureGuidanceCarrier(messages,"guardrails");if(!messageTextOf(stopCarrier).includes("RUNAWAY OUTPUT STOP"))prependGuidanceText(stopCarrier,"guardrails",`[RUNAWAY OUTPUT STOP]
|
|
1007
1008
|
You have produced ${count} consecutive responses without using any tools. You MUST call a tool in your next response.
|
|
1008
1009
|
[/RUNAWAY OUTPUT STOP]
|
|
@@ -3541,7 +3542,7 @@ ${USAGE9}`;let issueUrl=`https://github.com/${issueInfo.owner}/${issueInfo.repo}
|
|
|
3541
3542
|
|
|
3542
3543
|
${USAGE9}`;try{assertProjectRoot(directory)}catch(error93){return`Error: Failed to persist issue reference durably: ${error93 instanceof Error?error93.message:String(error93)}
|
|
3543
3544
|
|
|
3544
|
-
${USAGE9}`}let swarmDir=path201.join(directory,".swarm"),issueReference={url:result.sanitized,owner:issueInfo.owner,repo:issueInfo.repo,number:issueInfo.number,timestamp:new Date().toISOString(),flags:{...parsed.plan&&{plan:!0},...parsed.trace&&{trace:!0},...parsed.noRepro&&{noRepro:!0}}};if(parsed.noRepro)issueReference.noReproWaiver={waived:!0,reason:"--no-repro flag",timestamp:new Date().toISOString()};let traceState={issueNumber:issueInfo.number,lastTransition:null,status:"in_progress"},oldTraceState=null;try{oldTraceState=_internals158.readFileSync(path201.join(swarmDir,"issue-trace-state.json"),"utf-8")}catch{}try{_internals158.mkdirSync(swarmDir,{recursive:!0}),atomicWriteFileSync2(swarmDir,"issue-trace-state.json",JSON.stringify(traceState,null,2))
|
|
3545
|
+
${USAGE9}`}let swarmDir=path201.join(directory,".swarm"),issueReference={url:result.sanitized,owner:issueInfo.owner,repo:issueInfo.repo,number:issueInfo.number,timestamp:new Date().toISOString(),flags:{...parsed.plan&&{plan:!0},...parsed.trace&&{trace:!0},...parsed.noRepro&&{noRepro:!0}}};if(parsed.noRepro)issueReference.noReproWaiver={waived:!0,reason:"--no-repro flag",timestamp:new Date().toISOString()};let traceState=parsed.trace?{issueNumber:issueInfo.number,lastTransition:null,status:"in_progress"}:null,oldTraceState=null;if(traceState)try{oldTraceState=_internals158.readFileSync(path201.join(swarmDir,"issue-trace-state.json"),"utf-8")}catch{}try{if(_internals158.mkdirSync(swarmDir,{recursive:!0}),traceState)atomicWriteFileSync2(swarmDir,"issue-trace-state.json",JSON.stringify(traceState,null,2));atomicWriteFileSync2(swarmDir,"issue-reference.json",JSON.stringify(issueReference,null,2))}catch(e){if(traceState)if(oldTraceState!==null)try{atomicWriteFileSync2(swarmDir,"issue-trace-state.json",oldTraceState)}catch{}else try{_internals158.unlinkSync(path201.join(swarmDir,"issue-trace-state.json"))}catch{}try{_internals158.unlinkSync(path201.join(swarmDir,"issue-reference.json"))}catch{}return`Error: Failed to persist issue reference durably: ${e instanceof Error?e.message:String(e)}
|
|
3545
3546
|
|
|
3546
3547
|
${USAGE9}`}let flags=[];if(parsed.plan)flags.push("plan=true");if(parsed.trace)flags.push("trace=true");if(parsed.noRepro)flags.push("noRepro=true");let flagsStr=flags.length>0?` ${flags.join(" ")}`:"";return`[MODE: ISSUE_INGEST issue="${result.sanitized}"${flagsStr}]`}var USAGE9,_internals158;var init_issue=__esm(()=>{init_atomic_write();init_project_boundary();init_url_security();USAGE9=["Usage: /swarm issue <url|owner/repo#N|N> [--plan] [--trace] [--no-repro]","","Ingest a GitHub issue into the swarm workflow."," /swarm issue https://github.com/owner/repo/issues/42"," /swarm issue owner/repo#42"," /swarm issue 42 --plan"," /swarm issue 42 --trace --no-repro","","Flags:"," --plan Transition to plan creation after spec generation"," --trace Run the fix workflow end-to-end (implies --plan); compose commit-pr to publish."," --no-repro Skip reproduction step"].join(`
|
|
3547
3548
|
`);_internals158={writeFileSync:fs112.writeFileSync,mkdirSync:fs112.mkdirSync,renameSync:fs112.renameSync,unlinkSync:fs112.unlinkSync,readFileSync:fs112.readFileSync,existsSync:fs112.existsSync}});import{randomUUID as randomUUID33}from"node:crypto";import{existsSync as existsSync105,readFileSync as readFileSync86}from"node:fs";import{mkdir as mkdir32,readFile as readFile43,writeFile as writeFile19}from"node:fs/promises";import*as os26 from"node:os";import*as path202 from"node:path";async function migrateKnowledgeToExternal(_directory2,_config2){let externalSentinelPath=path202.join(_directory2,".swarm",".knowledge-external-migrated"),contextPath=path202.join(_directory2,".swarm","context.md");if(_internals159.existsSync(externalSentinelPath))return{migrated:!1,entriesMigrated:0,entriesDropped:0,entriesTotal:0,skippedReason:"external-sentinel-exists"};if(!_internals159.existsSync(contextPath))return{migrated:!1,entriesMigrated:0,entriesDropped:0,entriesTotal:0,skippedReason:"no-context-file"};let contextContent=await _internals159.readFile(contextPath,"utf-8");if(contextContent.trim().length===0)return{migrated:!1,entriesMigrated:0,entriesDropped:0,entriesTotal:0,skippedReason:"empty-context"};let lines=contextContent.split(`
|
|
@@ -7325,7 +7326,7 @@ ${lines.join(`
|
|
|
7325
7326
|
- source: ${source}
|
|
7326
7327
|
- nudge: ${sessionAutoProceed.autoProceedNudgeDone?"true":"false"}`;tryInject(banner)}}try{let currentPhaseNum=plan2?.current_phase??1,retroText=await buildRetroInjection(directory,currentPhaseNum,plan2?.title??void 0);if(retroText)if(retroText.length<=1600)tryInject(retroText);else tryInject(`${retroText.substring(0,1600)}...`)}catch{}if(mode!=="DISCOVER"&&config3.knowledge?.enabled!==!1&&sessionId_retro){let sessionToolCalls=getRealtimeLearningToolCallCount(sessionId_retro);if(shouldInjectRealtimeLearningNudge({sessionID:sessionId_retro,config:config3.knowledge?.realtime_learning_nudge,realtimeAdmission})){let learningNudge=buildRealtimeLearningNudge({currentPhase:plan2?.current_phase??1,toolCallCount:sessionToolCalls});if(tryInject(learningNudge))commitRealtimeLearningNudge(sessionId_retro)}}if(mode!=="DISCOVER"){let compactionConfig=config3.compaction_advisory;if(compactionConfig?.enabled!==!1&&sessionId_retro){let session=swarmState.agentSessions.get(sessionId_retro);if(session){let totalToolCalls=getTotalAggregateToolCallCount(),thresholds=compactionConfig?.thresholds??[50,75,100,125,150],lastHint=session.lastCompactionHint||0;for(let threshold of thresholds)if(totalToolCalls>=threshold&&lastHint<threshold){let totalToolCallsPlaceholder="${totalToolCalls}",message=(compactionConfig?.message??`[SWARM HINT] Session has ${totalToolCallsPlaceholder} tool calls. Consider compacting at next phase boundary to maintain context quality.`).replace(totalToolCallsPlaceholder,String(totalToolCalls));tryInject(message),session.lastCompactionHint=threshold;break}}}}}if(mode!=="DISCOVER"){if(config3.automation?.capabilities?.decision_drift_detection===!0&&_input.sessionID){let activeAgentForDrift=swarmState.activeAgent.get(_input.sessionID);if(!activeAgentForDrift||stripKnownSwarmPrefix(activeAgentForDrift)==="architect")try{let driftResult=await analyzeDecisionDrift(directory);if(driftResult.hasDrift){let driftText=formatDriftForContext(driftResult);if(driftText)tryInject(sanitizeContextText(driftText))}}catch{}}}let userConfig=config3.context_budget,defaultConfig=DEFAULT_CONTEXT_BUDGET_CONFIG,budgetTokens=resolveContextWindowTokens({userLimits:userConfig?.model_limits,modelID:liveModelID,providerID:liveProviderID,liveContextLimit,fallbackLookup:lookupStaticModelLimit}),contextBudgetConfig=userConfig?{...defaultConfig,...userConfig,warningPct:userConfig.warn_threshold?userConfig.warn_threshold*100:defaultConfig.warningPct,criticalPct:userConfig.critical_threshold?userConfig.critical_threshold*100:defaultConfig.criticalPct,budgetTokens}:{...defaultConfig,budgetTokens};if(contextBudgetConfig.enabled!==!1)try{let assembledSystemPrompt=output.system.join(`
|
|
7327
7328
|
`),budgetReport=await getContextBudgetReport(directory,assembledSystemPrompt,contextBudgetConfig,config3.plan_cursor);setSessionBudget(_input.sessionID??"unknown",budgetReport.budgetPct,contextBudgetConfig.budgetTokens),telemetry.budgetUpdated(_input.sessionID??"unknown",budgetReport.budgetPct,"architect");let sessionId_cb=_input.sessionID,activeAgent_cb=sessionId_cb?swarmState.activeAgent.get(sessionId_cb):null,budgetWarning=!activeAgent_cb||stripKnownSwarmPrefix(activeAgent_cb)==="architect"?await formatBudgetWarning(budgetReport,directory,contextBudgetConfig):null;if(budgetWarning)actualDemand+=estimateTokens(budgetWarning),output.system.push(`[FOR: architect]
|
|
7328
|
-
${budgetWarning}`),injectedTokens+=estimateTokens(budgetWarning)}catch(error93){warn("Context budget check failed:",error93)}try{let activeAgent_binary=swarmState.activeAgent.get(_input.sessionID??"");if(!activeAgent_binary||stripKnownSwarmPrefix(activeAgent_binary)==="architect"){let{getBinaryReadinessAdvisory:getBinaryReadinessAdvisory2}=await Promise.resolve().then(() => (init_tool_doctor(),exports_tool_doctor)),advisory=getBinaryReadinessAdvisory2();if(advisory)tryInject(advisory)}}catch{}try{let activeAgent_env=swarmState.activeAgent.get(_input.sessionID??""),agentBase_env=stripKnownSwarmPrefix(activeAgent_env??"").toLowerCase();if(agentBase_env==="coder"||agentBase_env==="test_engineer"){let{ensureSessionEnvironment:ensureSessionEnvironment2}=await Promise.resolve().then(() => (init_state2(),exports_state)),{renderEnvironmentPrompt:renderEnvironmentPrompt2}=await Promise.resolve().then(() => (init_prompt_renderer(),exports_prompt_renderer)),envSessionId=_input.sessionID??"unknown",profile=ensureSessionEnvironment2(envSessionId),envPrompt=renderEnvironmentPrompt2(profile,agentBase_env==="coder"?"coder":"testengineer");tryInject(envPrompt)}}catch{}return}let mode_b=await detectArchitectMode(directory,planReadCache),userScoringConfig=config3.context_budget?.scoring,candidates=[],idCounter=0,planContentForCursor=null,effectiveConfig=userScoringConfig?.weights?{...DEFAULT_SCORING_CONFIG,...userScoringConfig,weights:userScoringConfig.weights}:DEFAULT_SCORING_CONFIG,plan=null;try{plan=await loadPlan(directory,planReadCache)}catch(error93){warn(`Failed to load plan: ${error93 instanceof Error?error93.message:String(error93)}`)}let activePlanningAgent_b=_input.sessionID?swarmState.activeAgent.get(_input.sessionID):void 0;if(!activePlanningAgent_b||stripKnownSwarmPrefix(activePlanningAgent_b)==="architect")tryInject(renderPlanningProfileDirective(resolvePlanningProfile({directory,existingExecutionProfile:plan?.execution_profile,config:config3})));maybeAppendSpecDriftAdvisory(output,directory,plan,_input.sessionID,surface,turnLedgerGeneration);let currentPhase=null,currentTask=null;if(plan&&plan.migration_status!=="migration_failed")currentPhase=extractCurrentPhaseFromPlan(plan),currentTask=extractCurrentTaskFromPlan(plan);else if(planContentForCursor=await readSwarmFileAsync(directory,"plan.md",planReadCache),planContentForCursor)currentPhase=extractCurrentPhase(planContentForCursor),currentTask=extractCurrentTask(planContentForCursor);if(
|
|
7329
|
+
${budgetWarning}`),injectedTokens+=estimateTokens(budgetWarning)}catch(error93){warn("Context budget check failed:",error93)}try{let activeAgent_binary=swarmState.activeAgent.get(_input.sessionID??"");if(!activeAgent_binary||stripKnownSwarmPrefix(activeAgent_binary)==="architect"){let{getBinaryReadinessAdvisory:getBinaryReadinessAdvisory2}=await Promise.resolve().then(() => (init_tool_doctor(),exports_tool_doctor)),advisory=getBinaryReadinessAdvisory2();if(advisory)tryInject(advisory)}}catch{}try{let activeAgent_env=swarmState.activeAgent.get(_input.sessionID??""),agentBase_env=stripKnownSwarmPrefix(activeAgent_env??"").toLowerCase();if(agentBase_env==="coder"||agentBase_env==="test_engineer"){let{ensureSessionEnvironment:ensureSessionEnvironment2}=await Promise.resolve().then(() => (init_state2(),exports_state)),{renderEnvironmentPrompt:renderEnvironmentPrompt2}=await Promise.resolve().then(() => (init_prompt_renderer(),exports_prompt_renderer)),envSessionId=_input.sessionID??"unknown",profile=ensureSessionEnvironment2(envSessionId),envPrompt=renderEnvironmentPrompt2(profile,agentBase_env==="coder"?"coder":"testengineer");tryInject(envPrompt)}}catch{}return}let mode_b=await detectArchitectMode(directory,planReadCache),userScoringConfig=config3.context_budget?.scoring,candidates=[],idCounter=0,planContentForCursor=null,effectiveConfig=userScoringConfig?.weights?{...DEFAULT_SCORING_CONFIG,...userScoringConfig,weights:userScoringConfig.weights}:DEFAULT_SCORING_CONFIG,plan=null;try{plan=await loadPlan(directory,planReadCache)}catch(error93){warn(`Failed to load plan: ${error93 instanceof Error?error93.message:String(error93)}`)}let activePlanningAgent_b=_input.sessionID?swarmState.activeAgent.get(_input.sessionID):void 0;if(!activePlanningAgent_b||stripKnownSwarmPrefix(activePlanningAgent_b)==="architect")tryInject(renderPlanningProfileDirective(resolvePlanningProfile({directory,existingExecutionProfile:plan?.execution_profile,config:config3})));maybeAppendSpecDriftAdvisory(output,directory,plan,_input.sessionID,surface,turnLedgerGeneration);let currentPhase=null,currentTask=null;if(plan&&plan.migration_status!=="migration_failed")currentPhase=extractCurrentPhaseFromPlan(plan),currentTask=extractCurrentTaskFromPlan(plan);else if(planContentForCursor=await readSwarmFileAsync(directory,"plan.md",planReadCache),planContentForCursor)currentPhase=extractCurrentPhase(planContentForCursor),currentTask=extractCurrentTask(planContentForCursor);let planCursorControls_b=resolvePlanCursorControls(config3.plan_cursor);if(planCursorControls_b.enabled&&!planContentForCursor)planContentForCursor=await readSwarmFileAsync(directory,"plan.md",planReadCache);if(currentPhase){let text=`[SWARM CONTEXT] Current phase: ${currentPhase}`;candidates.push({id:`candidate-${idCounter++}`,kind:"phase",text,tokens:estimateTokens(text),priority:1,metadata:{contentType:estimateContentType(text)}})}if(currentTask){let text=`[SWARM CONTEXT] Current task: ${currentTask}`;candidates.push({id:`candidate-${idCounter++}`,kind:"task",text,tokens:estimateTokens(text),priority:2,metadata:{contentType:estimateContentType(text),isCurrentTask:!0}})}if(planCursorControls_b.enabled&&mode_b!=="DISCOVER"&&planContentForCursor){let planCursor=extractPlanCursor(planContentForCursor,{maxTokens:planCursorControls_b.maxTokens,lookaheadTasks:planCursorControls_b.lookaheadTasks});candidates.push({id:`candidate-${idCounter++}`,kind:"phase",text:planCursor,tokens:estimateTokens(planCursor),priority:1,metadata:{contentType:"markdown"}})}if(mode_b!=="DISCOVER")try{let handoffContent=await readSwarmFileAsync(directory,"handoff.md",planReadCache);if(handoffContent){let scopedHandoff=parseSessionScopedHandoff(handoffContent);if(shouldConsumeHandoff(scopedHandoff,_input.sessionID)){let handoffPath=validateSwarmPath(directory,"handoff.md"),consumedPath=validateSwarmPath(directory,"handoff-consumed.md");if(fs165.existsSync(consumedPath))warn("Duplicate handoff detected: handoff-consumed.md already exists"),fs165.unlinkSync(consumedPath);fs165.renameSync(handoffPath,consumedPath);try{let promptPath=validateSwarmPath(directory,"handoff-prompt.md");fs165.unlinkSync(promptPath)}catch{}let handoffText=`[HANDOFF BRIEF]
|
|
7329
7330
|
${`## HANDOFF — Resuming from model switch
|
|
7330
7331
|
The previous model's session ended. Here is your starting context:
|
|
7331
7332
|
|
|
@@ -7357,8 +7358,8 @@ ${instruction}`;else if(typeof args2.message==="string")args2.message=`${args2.m
|
|
|
7357
7358
|
${instruction}`;else if(typeof args2.task==="string")args2.task=`${args2.task}
|
|
7358
7359
|
|
|
7359
7360
|
${instruction}`}if(incrementFullAutoCounter(directory,sessionID,"coderDelegations"),!subagentRaw||!isKnownCanonicalRole(canonicalRole2))throw Error(`FULL_AUTO_DELEGATION_DENY: unknown subagent '${subagentRaw}' (canonical role '${canonicalRole2}' is not a registered plugin role). Choose a generated agent whose suffix matches one of the canonical roles.`);if(canonicalRole2==="coder"){let protectedPathScan=scanForProtectedPaths(args2,config3.full_auto);if(!protectedPathScan.complete)throw await writeDelegationEvent(directory,{type:"full_auto_subagent_warning",timestamp:new Date().toISOString(),session_id:sessionID,subagent:subagentRaw,canonical_role:canonicalRole2,phase:"outbound",category:"protected_path_scan_incomplete",matched:"scan-budget-exceeded"}),Error("FULL_AUTO_DELEGATION_DENY: coder delegation payload exceeds the protected-path scan budget");for(let p of protectedPathScan.hits)if(isProtectedPath(p,config3.full_auto))throw await writeDelegationEvent(directory,{type:"full_auto_subagent_warning",timestamp:new Date().toISOString(),session_id:sessionID,subagent:subagentRaw,canonical_role:canonicalRole2,phase:"outbound",category:"protected_path_in_prompt",matched:p}),Error(`FULL_AUTO_DELEGATION_DENY: coder delegation targets protected path '${p}'`)}},toolAfter:async(input,output)=>{let tool3=input.tool??"";if(!isTaskTool5(tool3))return;let sessionID=input.sessionID;if(!sessionID)return;let runState=loadFullAutoRunState(directory,sessionID);if(!runState||runState.status!=="running")return;let text=extractText(output.output),envelope=extractFullAutoSevereEnvelope(text),warnings=detectReturnWarnings(text),session=swarmState.agentSessions.get(sessionID),severeValidation=input.callID&&runState?validateFullAutoSevereEnvelope({envelope,sessionID,callID:input.callID,generation:runState.runGeneration??0,declaredScope:session?.declaredCoderScope??null,currentTaskID:session?.currentTaskId??null,session,projectDirectory:directory}):{accepted:!1,reason:"missing-call-id"},severe=severeValidation.accepted;if(warnings.length===0&&!envelope)return;await writeDelegationEvent(directory,{type:"full_auto_subagent_warning",timestamp:new Date().toISOString(),session_id:sessionID,phase:"return",warnings,envelope_category:envelope?.category,envelope_validation:severeValidation.reason,severe});try{recordFullAutoSubagentOutcome(directory,sessionID,{severe,pauseReason:severe?`severe subagent return envelope: ${envelope?.category??"unknown"}`:void 0})}catch(error93){if(!isFullAutoStateLockError(error93))throw error93;markFullAutoStateLockFailure(directory,sessionID),warn("[full-auto/delegation] durable state lock unavailable; pausing in-process")}if(input.callID)clearFullAutoSevereCorrelation(sessionID,input.callID)}}}init_core_events();var PATTERNS=[{category:"instruction_override",regex:/\bignore (?:all |any |the )?(?:previous|prior|earlier|above) (?:instructions|prompts|rules|directives)\b/i},{category:"instruction_override",regex:/\bdisregard (?:all |any |the )?(?:previous|prior|earlier|above) (?:instructions|prompts|rules)\b/i},{category:"instruction_override",regex:/\bforget (?:all |any |everything|the )?(?:previous|above|prior) (?:instructions|prompts|rules)\b/i},{category:"system_role_override",regex:/\b(?:you are now|act as|pretend to be|from now on you are)\s+(?:a |an |the )?(?:system|developer|root|admin|superuser)\b/i},{category:"system_role_override",regex:/\b<\|?(?:system|developer|im_start|imstart)\|?>/i},{category:"credential_request",regex:/\b(?:please |kindly |)(?:paste|share|reveal|send|provide|leak|print|echo|cat) (?:your |the |my )?(?:api[_ -]?key|password|token|secret|credentials|\.env)\b/i},{category:"credential_request",regex:/\b(?:show|dump|export) (?:env(?:ironment)?|secrets|credentials|keys?)\b/i},{category:"exfiltration_request",regex:/\b(?:upload|exfiltrate|send) (?:contents of |files? from |the )?(?:home|repo|workspace|project|secrets?|env(?:ironment)?)\b/i},{category:"exfiltration_request",regex:/\bcurl\s+-d\s+@/i},{category:"guardrail_disable_request",regex:/\bdisable (?:full[- ]auto|guardrails?|safety|policy|oversight|critic)\b/i},{category:"guardrail_disable_request",regex:/\bturn (?:off|disable) (?:full[- ]auto|guardrails?|safety|policy)\b/i},{category:"curl_pipe_shell",regex:/\bcurl\b[^|\n]*\|\s*(?:sh|bash|zsh|fish)\b/i},{category:"untrusted_run_command",regex:/\b(?:run|execute|paste) (?:this|the following) (?:command|script|bash|shell)\b/i}];function buildExcerpt(text,match){let idx=match.index??0,start=Math.max(0,idx-120),end=Math.min(text.length,idx+match[0].length+120),slice=text.slice(start,end).replace(/\s+/g," ").trim();return slice.length>280?`${slice.slice(0,280)}…`:slice}function probeFullAutoInput(text){let warnings=[];if(!text||typeof text!=="string")return{hasWarning:!1,warnings};let seen=new Set;for(let{category,regex}of PATTERNS){let m=text.match(regex);if(!m)continue;let key2=`${category}:${m[0].toLowerCase()}`;if(seen.has(key2))continue;seen.add(key2),warnings.push({category,matched:m[0],excerpt:buildExcerpt(text,m)})}return{hasWarning:warnings.length>0,warnings}}var RISKY_FOLLOWUP_TOOLS=new Set(["bash","shell","exec","web_search","webfetch","web_fetch","fetch","http","request"]),SECRET_TOOL_PATTERNS=[/\b(?:cat|head|tail|less|more)\s+[^\n]*\.env/i,/\bprintenv\b.*(?:SECRET|TOKEN|KEY|PASSWORD)/i];function shouldEscalateAfterWarning(toolName,commandOrUrl){let lower=toolName?.toLowerCase()??"";if(RISKY_FOLLOWUP_TOOLS.has(lower))return!0;if(typeof commandOrUrl==="string"){for(let re of SECRET_TOOL_PATTERNS)if(re.test(commandOrUrl))return!0}return!1}init_state3();init_logger();init_normalize_tool_name();var PROBED_TOOLS=new Set(["web_search","webfetch","web_fetch","fetch","http","request","doc_extract","doc_scan","gitingest","extract_code_blocks","retrieve_summary","retrieve_lane_output","search","read","view"]);async function writeWarningEvent(directory,sessionID,tool3,probe2){let event={type:"full_auto_input_warning",timestamp:new Date().toISOString(),session_id:sessionID,tool:tool3,warnings:probe2.warnings};try{appendCoreEventSync(directory,event)}catch(error93){error48(`[full-auto/input-probe] failed to write event: ${error93 instanceof Error?error93.message:String(error93)}`)}}function extractText2(out){if(typeof out==="string")return out;if(out&&typeof out==="object"){let candidate2=out;if(typeof candidate2.output==="string")return candidate2.output;if(typeof candidate2.text==="string")return candidate2.text;if(typeof candidate2.body==="string")return candidate2.body;try{return JSON.stringify(candidate2)}catch{return""}}return""}var MAX_TRACKED_SESSIONS10=256,WARNING_TTL_MS=300000,fullAutoInputWarningStash=new Map;function isExpired2(w,nowMs3=Date.now()){let at=Date.parse(w.at);if(!Number.isFinite(at))return!0;return nowMs3-at>WARNING_TTL_MS}function evictExpired2(){let now2=Date.now();for(let[sid,w]of fullAutoInputWarningStash)if(isExpired2(w,now2))fullAutoInputWarningStash.delete(sid);while(fullAutoInputWarningStash.size>MAX_TRACKED_SESSIONS10){let firstKey=fullAutoInputWarningStash.keys().next().value;if(firstKey===void 0)break;fullAutoInputWarningStash.delete(firstKey)}}function setPendingInputWarning(sessionID,warning){fullAutoInputWarningStash.delete(sessionID),fullAutoInputWarningStash.set(sessionID,warning),evictExpired2()}function consumePendingInputWarning(sessionID){let warning=fullAutoInputWarningStash.get(sessionID);if(warning)fullAutoInputWarningStash.delete(sessionID);if(warning&&isExpired2(warning))return;return warning}function peekPendingInputWarning(sessionID){let w=fullAutoInputWarningStash.get(sessionID);if(!w)return;if(isExpired2(w)){fullAutoInputWarningStash.delete(sessionID);return}return w}function createFullAutoInputProbeHook(options){let{directory}=options;return{toolAfter:async(input,output)=>{let tool3=(normalizeToolName(input.tool)??input.tool??"").toLowerCase();if(!PROBED_TOOLS.has(tool3))return;let sessionID=input.sessionID;if(!sessionID)return;let runState=loadFullAutoRunState(directory,sessionID);if(!runState||runState.status!=="running")return;let text=extractText2(output.output);if(!text)return;let probe2=probeFullAutoInput(text);if(!probe2.hasWarning)return;setPendingInputWarning(sessionID,{tool:tool3,at:new Date().toISOString(),categories:probe2.warnings.map((w)=>w.category)}),await writeWarningEvent(directory,sessionID,tool3,probe2)}}}init_constants();init_schema();init_oversight();init_policy();init_recovery2();init_severe_result();init_state3();init_executor();init_skip_state();init_scope_persistence();init_state2();init_file_authority();var _internals234={assessSandboxEnforcement,readSandboxWrapOutcome,clearSandboxWrapOutcome};function createFullAutoPermissionHook(options){let{config:config3,directory}=options,fullAutoConfig=config3.full_auto;return{toolBefore:async(input,output)=>{let{tool:toolName,sessionID}=input;if(!sessionID)return;let stateHealth=isFullAutoStateUnreadable();if(stateHealth.unreadable){if(isReadOnlyTool(toolName))return;throw Error(`FULL_AUTO_STATE_UNREADABLE: tool '${toolName}' blocked because the Full-Auto durable state file is unreadable (${stateHealth.reason}). Restore .swarm/full-auto-state.json (or .bak) and re-run /swarm full-auto on.`)}let runState=loadFullAutoRunState(directory,sessionID);if(!runState||runState.status==="idle")return;if(runState.status==="paused"||runState.status==="terminated"){if(toolName==="swarm_command"&&output.args&&typeof output.args==="object"&&typeof output.args.command==="string"){let raw=output.args,command=String(raw.command),commandArgs=Array.isArray(raw.args)?raw.args.filter((item)=>typeof item==="string"):[];if(isAllowedPausedSwarmCommand(command,commandArgs,runState.status))return}if(isReadOnlyTool(toolName))return;let rawReason=runState.pauseReason??runState.terminateReason??"no reason recorded",statusPrefix=rawReason.includes("infrastructure failure")&&runState.status==="paused"?"FULL_AUTO_PAUSED:OVERSIGHT_INFRASTRUCTURE_FAILURE":`FULL_AUTO_${runState.status.toUpperCase()}`;throw Error(`${statusPrefix}: tool '${toolName}' blocked because Full-Auto run is ${runState.status} (${rawReason}). Re-enable with /swarm full-auto on after the underlying issue is resolved.`)}let session=swarmState.agentSessions.get(sessionID),activeAgent=swarmState.activeAgent.get(sessionID)??session?.agentName??ORCHESTRATOR_NAME,normalizedAgentName=stripKnownSwarmPrefix(activeAgent),taskId=session?.currentTaskId??null,binding=taskId?resolveAuthorizedScopeBinding({directory,taskId,activeSessionId:sessionID}):resolveAuthorizedScopeBindingForSession({directory,activeSessionId:sessionID});if(!taskId&&binding&&session)taskId=binding.taskId,session.currentTaskId=binding.taskId,session.declaredCoderScope=[...binding.files];let declaredScope=binding?.files??null,argsObj=output.args??void 0,lowerTool=toolName?.toLowerCase()??"",phaseFromArgs;if(lowerTool==="phase_complete"){if(phaseFromArgs=parsePhaseArg(argsObj),phaseFromArgs===void 0)throw Error("FULL_AUTO_DENY [phase_complete_invalid_phase]: phase_complete called without a valid 'phase' argument. Provide a positive integer phase before calling phase_complete.")}let effectivePhase=phaseFromArgs??runState.currentPhase,safeMode=["assisted","supervised","strict"].includes(runState.mode)?runState.mode:"strict",effectiveFullAutoConfig=fullAutoConfig?{...fullAutoConfig,mode:safeMode}:{mode:safeMode},rawCommand=typeof argsObj?.command==="string"?argsObj.command.trim():"",sandboxOutcome=(toolName==="bash"||toolName==="shell")&&input.callID?_internals234.readSandboxWrapOutcome(sessionID,input.callID):null,classifierArgs=sandboxOutcome?{...argsObj,command:sandboxOutcome.originalCommand}:argsObj,classifierInput={sessionID,agentName:activeAgent,normalizedAgentName,generatedAgentNames:swarmState.generatedAgentNames,toolName,args:classifierArgs,directory,declaredScope,currentTaskID:taskId,currentPhase:effectivePhase,planSummary:void 0,changedFiles:session&&taskId?getModifiedFilesForTask(session,taskId):void 0,fullAutoConfig:effectiveFullAutoConfig,pluginConfig:config3},decision=classifyFullAutoToolAction(classifierInput);if(safeMode==="strict"&&(toolName==="bash"||toolName==="shell")&&rawCommand)try{let commandIdentity=`cmd=${hashArgs({command:rawCommand})}`,wrapOutcome=sandboxOutcome,sandboxConfig=config3.guardrails?.sandbox,identityAssessment=await _internals234.assessSandboxEnforcement({mode:sandboxConfig?.mode??"advisory",require_filesystem:sandboxConfig?.require_filesystem??!1,require_network:sandboxConfig?.require_network??!1,require_process:sandboxConfig?.require_process??!1,network_mode:sandboxConfig?.network_mode??"off",network_allowlist:sandboxConfig?.network_allowlist??[],writable_roots:sandboxConfig?.writable_roots??[]}),assessmentSupported=identityAssessment.supported!==!1,assessmentUnsupported=identityAssessment.unsupported??[],capabilityIdentity=`cap=${identityAssessment.capability.identity}`;if(!wrapOutcome)decision={action:"deny",code:"sandbox_unverified",recoverable:!0,reason:`strict mode shell command was not verified by the guardrails sandbox wrapper [${commandIdentity} ${capabilityIdentity}]`};else if(!wrapOutcome.wrapped||wrapOutcome.originalCommandHash!==hashArgs({command:wrapOutcome.originalCommand})||wrapOutcome.originalCommandHash===wrapOutcome.finalCommandHash||wrapOutcome.finalCommandHash!==hashArgs({command:rawCommand})||normalizeSandboxMechanism(wrapOutcome.executorMechanism)!==normalizeSandboxMechanism(wrapOutcome.capabilityMechanism)||wrapOutcome.capabilityIdentity!==identityAssessment.capability.identity||wrapOutcome.assessmentCacheKey!==identityAssessment.cacheKey)decision={action:"deny",code:"sandbox_unverified",recoverable:!0,reason:`strict mode shell command lost sandbox binding (${wrapOutcome.reason}) [${commandIdentity} ${capabilityIdentity}]`};else if(!assessmentSupported)decision={action:"deny",code:"sandbox_required",recoverable:!0,reason:`strict mode shell command requested unsupported sandbox policy (${assessmentUnsupported.join(", ")}) [${commandIdentity} ${capabilityIdentity}]`};else if(!identityAssessment.satisfied)decision={action:"deny",code:"sandbox_required",recoverable:!0,reason:`strict mode shell command requires independently verified sandbox containment; missing ${identityAssessment.missing.join(", ")} [${commandIdentity} ${capabilityIdentity}]`}}finally{_internals234.clearSandboxWrapOutcome(sessionID,input.callID)}let pendingWarning=peekPendingInputWarning(sessionID);if(pendingWarning){let commandOrUrl=typeof argsObj?.command==="string"&&argsObj.command||typeof argsObj?.url==="string"&&argsObj.url||void 0;if(shouldEscalateAfterWarning(toolName,commandOrUrl)){let evidenceEventID=recordFullAutoSevereEvidenceEvent({sessionID,childSessionID:sessionID,category:"external_instructions",callID:input.callID,generation:runState.runGeneration});decision={action:"escalate_critic",reason:`risky follow-up after prompt-injection warning (${pendingWarning.categories.join(",")}); evidence event ${evidenceEventID}`,risk:"high",context:{tool:toolName,priorWarningTool:pendingWarning.tool,categories:pendingWarning.categories}},consumePendingInputWarning(sessionID)}}if(decision.action==="allow"){try{tickAndMaybeDispatchCadence(directory,sessionID,"toolCalls",config3,{activeAgent}),resetFullAutoDenials(directory,sessionID)}catch(error93){if(!isFullAutoStateLockError(error93))throw error93}return}if(decision.action==="deny"){let denial=buildStructuredDenial(decision,toolName);recordFullAutoDenial(directory,sessionID,{tool:toolName,code:decision.code,reason:decision.reason});let updated2=loadFullAutoRunState(directory,sessionID);if(updated2){let pauseDecision=shouldPauseForDenials(updated2,fullAutoConfig);if(pauseDecision.pause)if(pauseDecision.mode==="terminate")terminateFullAutoRun(directory,sessionID,pauseDecision.reason??"denial-limit");else pauseFullAutoRun(directory,sessionID,pauseDecision.reason??"denial-limit")}throw Error(`FULL_AUTO_DENY [${decision.code}]: ${decision.reason}. ${JSON.stringify(denial)}`)}if(decision.action==="pause")throw pauseFullAutoRun(directory,sessionID,decision.reason),Error(`FULL_AUTO_PAUSE [${decision.code}]: ${decision.reason}`);if(decision.action==="escalate_human")throw terminateFullAutoRun(directory,sessionID,decision.reason),Error(`FULL_AUTO_ESCALATE_HUMAN [${decision.code}]: ${decision.reason}`);let triggerSource=mapTriggerSource(decision,toolName),criticModel=fullAutoConfig?.critic_model??config3.agents?.critic?.model??"opencode/big-pickle",oversightAgentName=resolveOversightAgentNameFromActive(activeAgent);if(lowerTool==="phase_complete"&&effectivePhase!==void 0){let stateForPhase=loadFullAutoRunState(directory,sessionID);if(stateForPhase&&stateForPhase.currentPhase!==effectivePhase){stateForPhase.currentPhase=effectivePhase;try{saveFullAutoRunState(directory,stateForPhase)}catch(persistErr){let msg=persistErr instanceof Error?persistErr.message:String(persistErr);throw Error(`FULL_AUTO_BLOCKED: failed to persist phase ${effectivePhase} to durable run state — ${msg}`)}}}let outcome;try{outcome=await dispatchFullAutoOversight({directory,sessionID,trigger:decision.reason,triggerSource,phase:effectivePhase,taskID:taskId??void 0,planID:runState.planID,architectOutput:output.args?JSON.stringify(output.args):void 0,actionContext:{tool:toolName,...decision.context??{}},criticModel,oversightAgentName,fullAutoConfig:{fail_closed:fullAutoConfig?.fail_closed!==!1,max_dispatch_retries:fullAutoConfig?.oversight?.max_dispatch_retries??2,max_consecutive_dispatch_failures:fullAutoConfig?.oversight?.max_consecutive_dispatch_failures??3,total_timeout_ms:fullAutoConfig?.oversight?.total_timeout_ms??120000,cleanup_timeout_ms:fullAutoConfig?.oversight?.cleanup_timeout_ms??2000}})}catch(error93){let reason=error93 instanceof Error?error93.message:String(error93);throw pauseFullAutoRun(directory,sessionID,`oversight dispatcher exception: ${reason}`),Error(`FULL_AUTO_BLOCKED: oversight dispatch threw — ${reason}`)}if(outcome.decision==="allow"){try{tickAndMaybeDispatchCadence(directory,sessionID,"toolCalls",config3,{activeAgent}),resetFullAutoDenials(directory,sessionID)}catch(error93){if(!isFullAutoStateLockError(error93))throw error93}return}if(outcome.decision==="pause")throw Error(`FULL_AUTO_BLOCKED: critic verdict ${outcome.verdict} — ${outcome.reasoning}`);if(outcome.decision==="escalate_human")throw Error(`FULL_AUTO_ESCALATE_HUMAN: critic verdict ${outcome.verdict} — ${outcome.reasoning}`);recordFullAutoDenial(directory,sessionID,{tool:toolName,code:`critic_${outcome.verdict}`.toLowerCase(),reason:outcome.reasoning||`critic verdict ${outcome.verdict}`});let updated=loadFullAutoRunState(directory,sessionID);if(updated){let pauseDecision=shouldPauseForDenials(updated,fullAutoConfig);if(pauseDecision.pause)if(pauseDecision.mode==="terminate")terminateFullAutoRun(directory,sessionID,pauseDecision.reason??"denial-limit");else pauseFullAutoRun(directory,sessionID,pauseDecision.reason??"denial-limit")}throw Error(`FULL_AUTO_CRITIC_DENY: ${outcome.verdict} — ${outcome.reasoning}`)}}}function parsePhaseArg(args2){if(!args2)return;let raw=args2.phase,n;if(typeof raw==="number")n=raw;else if(typeof raw==="string"&&raw.trim()){let trimmed=raw.trim();if(!/^[1-9][0-9]*$/.test(trimmed))return;n=Number.parseInt(trimmed,10)}else return;if(!Number.isFinite(n)||!Number.isInteger(n)||n<1)return;if(n>Number.MAX_SAFE_INTEGER)return;return n}function mapTriggerSource(decision,toolName){if(decision.action!=="escalate_critic")return"tool_action";let lower=toolName?.toLowerCase()??"";if(lower==="phase_complete")return"phase_boundary";if(lower==="update_task_status")return"task_completion";if(decision.risk==="high")return"risk";return"tool_action"}function resolveOversightAgentNameFromActive(activeAgent){if(!activeAgent)return"critic_oversight";if(stripKnownSwarmPrefix(activeAgent)===ORCHESTRATOR_NAME){let lastIdx=activeAgent.toLowerCase().lastIndexOf("architect");if(lastIdx>0)return`${activeAgent.slice(0,lastIdx)}critic_oversight`}return"critic_oversight"}init_gate_denial_tracker();init_guardrails2();init_hive_promoter();init_host_boundary();init_command_resolution();init_stored_input_args();init_normalize_tool_name();init_spawn_helper();import*as fs166 from"node:fs";import*as path290 from"node:path";var emittedSkipAdvisories=new Set;function detectPackageManager(projectDir){if(fs166.existsSync(path290.join(projectDir,"bun.lockb")))return"bun";if(fs166.existsSync(path290.join(projectDir,"pnpm-lock.yaml")))return"pnpm";if(fs166.existsSync(path290.join(projectDir,"yarn.lock")))return"yarn";if(fs166.existsSync(path290.join(projectDir,"package-lock.json")))return"npm";return"bun"}function detectTypecheckCommand(projectDir){let pkgPath=path290.join(projectDir,"package.json");if(fs166.existsSync(pkgPath))try{let pkg=JSON.parse(fs166.readFileSync(pkgPath,"utf8")),scripts=pkg.scripts;if(scripts?.typecheck)return{command:[detectPackageManager(projectDir),"run","typecheck"],language:"typescript"};if(scripts?.["type-check"])return{command:[detectPackageManager(projectDir),"run","type-check"],language:"typescript"};let deps={...pkg.dependencies,...pkg.devDependencies};if(!deps?.typescript&&!fs166.existsSync(path290.join(projectDir,"tsconfig.json")));if(deps?.typescript||fs166.existsSync(path290.join(projectDir,"tsconfig.json")))return{command:resolveLocalNodeTool("tsc",["--noEmit"],projectDir),language:"typescript"}}catch{return null}if(fs166.existsSync(path290.join(projectDir,"go.mod")))return{command:["go","vet","./..."],language:"go"};if(fs166.existsSync(path290.join(projectDir,"Cargo.toml")))return{command:["cargo","check"],language:"rust"};if(fs166.existsSync(path290.join(projectDir,"pyproject.toml"))||fs166.existsSync(path290.join(projectDir,"requirements.txt"))||fs166.existsSync(path290.join(projectDir,"setup.py")))return{command:null,language:"python"};try{if(fs166.readdirSync(projectDir).some((f)=>f.endsWith(".csproj")||f.endsWith(".sln")))return{command:["dotnet","build","--no-restore"],language:"csharp"}}catch{}return null}async function runWithTimeout(command,cwd,timeoutMs){let result=await spawnAsync(command,cwd,timeoutMs);if(result===null)return null;return{exitCode:result.exitCode,stderr:result.stderr}}function createIncrementalVerifyHook(config3,projectDir,injectMessage){return{toolAfter:async(input,output)=>{if(!config3.enabled)return;if(!isTaskToolId(input.tool))return;let args2=(typeof input.callID==="string"?getStoredInputArgs(input.callID):void 0)??input.args??output.args,subagentType=typeof args2?.subagent_type==="string"?args2.subagent_type:"",agentName=subagentType.replace(/^[^_]+_/,"");if(!config3.triggerAgents.includes(agentName)&&!config3.triggerAgents.includes(subagentType))return;let commandToRun=null;if(config3.command!=null)if(Array.isArray(config3.command))commandToRun=config3.command;else commandToRun=config3.command.split(" ");else{let detected=detectTypecheckCommand(projectDir);if(detected===null)return;if(detected.command===null){let dedupKey=`${input.sessionID}:${detected.language}`;if(!emittedSkipAdvisories.has(dedupKey))emittedSkipAdvisories.add(dedupKey),injectMessage(input.sessionID,`POST-CODER CHECK SKIPPED: ${detected.language} project detected but no default checker available. Set incremental_verify.command in .swarm/config.json to enable.`);return}commandToRun=detected.command}if(commandToRun===null)return;let result=await runWithTimeout(commandToRun,projectDir,config3.timeoutMs);if(result===null)return;if(result.exitCode===0)injectMessage(input.sessionID,"POST-CODER CHECK PASSED: No type errors.");else{let errorSummary=result.stderr.slice(0,800);injectMessage(input.sessionID,`POST-CODER CHECK FAILED: Type errors detected after coder delegation. Address these before proceeding.
|
|
7360
|
-
${errorSummary}`)}}}}init_init_orphan_recovery();init_state2();import*as fs167 from"node:fs/promises";import*as path291 from"node:path";var ADVISORY_FILENAME="init-orphan-recovery.json";function createInitOrphanRecoveryAdvisoryHook(directory){let consumedBySession=new Set;async function readAdvisoryFile(){let advisoryPath=path291.join(directory,".swarm","advisories",ADVISORY_FILENAME);try{let content=await fs167.readFile(advisoryPath,"utf-8");return JSON.parse(content)}catch{return null}}async function deleteAdvisoryFile(){let advisoryPath=path291.join(directory,".swarm","advisories",ADVISORY_FILENAME);try{await fs167.unlink(advisoryPath)}catch{}}function formatError3(error93){return`ORPHAN_RECOVERY_ERROR: Could not reclaim branch "${error93.branch}": ${error93.error}`}async function messagesTransform(_input,output){let messages=output.messages;if(!messages||messages.length===0)return;let sessionId=messages[messages.length-1]?.info?.sessionID;if(!sessionId)return;let activeAgent=swarmState.activeAgent.get(sessionId),session=swarmState.agentSessions.get(sessionId),ORCHESTRATOR_NAME2="Architect";if(!(activeAgent?activeAgent===ORCHESTRATOR_NAME2||activeAgent.endsWith("_Architect"):session?session.agentName===ORCHESTRATOR_NAME2||session.agentName.endsWith("_Architect"):!1))return;if(consumedBySession.has(sessionId))return;let advisory=await readAdvisoryFile();if(!advisory)return;consumedBySession.add(sessionId),await deleteAdvisoryFile();let reclaimedForGate=advisory.reclaimed;if(!((advisory.warnings?.length??0)>0||(advisory.errors?.length??0)>0||(reclaimedForGate?.removedBranches?.length??0)>0||(reclaimedForGate?.removedWorktrees?.length??0)>0))return;let targetSession=ensureAgentSession(sessionId,void 0,directory),timestamp=advisory.initTimestamp?new Date(advisory.initTimestamp).toLocaleString():"unknown";pushAdvisory(targetSession,`[INIT ORPHAN RECOVERY] Plugin init detected the following at ${timestamp}:`);for(let warning of advisory.warnings??[])pushAdvisory(targetSession,` WARNING: ${warning}`);for(let err of advisory.errors??[])pushAdvisory(targetSession,` ERROR: ${formatError3(err)}`);let reclaimed=advisory.reclaimed;if((reclaimed?.removedBranches?.length??0)>0)pushAdvisory(targetSession,` Reclaimed ${reclaimed.removedBranches.length} orphaned branch(es): ${reclaimed.removedBranches.join(", ")}`);if(reclaimed?.removedWorktrees&&reclaimed.removedWorktrees.length>0)pushAdvisory(targetSession,` Reclaimed ${reclaimed.removedWorktrees.length} orphaned worktree directory(ies): ${reclaimed.removedWorktrees.join(", ")}`);if(reclaimed?.prunedWorktrees)pushAdvisory(targetSession," Stale worktree metadata pruned.")}return{messagesTransform}}init_ledger_sqlite();init_logger();init_delegation_gate();import*as fs168 from"node:fs";import*as path293 from"node:path";function computeNextMode(params){let{issueReference,traceState,workflowArtifacts}=params,noop={nextMode:null,directive:null,nextLastTransition:traceState.lastTransition,nextStatus:traceState.status};if(!issueReference||issueReference.flags.trace!==!0)return noop;if(traceState.status==="merge_approval_recorded")return noop;if(traceState.status==="published"){if(workflowArtifacts.mergeApprovalObserved&&traceState.lastTransition!=="MERGE_APPROVAL_RECORDED")return{nextMode:null,directive:"Merge approval recorded for this trace, bound to the PR head SHA in .swarm/merge-approval.json. The merge decision is human-enforced: the human user owns and executes it through the host. This plugin records the approval verbatim for audit; it does not drive, gate, or green-light the merge itself.",nextLastTransition:"MERGE_APPROVAL_RECORDED",nextStatus:"merge_approval_recorded"};return noop}if(traceState.status==="publication_handoff"){if(workflowArtifacts.publicationObserved&&traceState.lastTransition!=="PUBLISHED")return{nextMode:null,directive:"Publication confirmed. The issue-trace workflow is complete.",nextLastTransition:"PUBLISHED",nextStatus:"published"};return noop}if(workflowArtifacts.specIssueNumber===null||workflowArtifacts.specIssueNumber!==issueReference.number||traceState.issueNumber!==issueReference.number)return noop;if(!workflowArtifacts.specExists)return noop;if(!workflowArtifacts.planExists){if(workflowArtifacts.freshnessPermitted===!1){if(traceState.lastTransition===null||traceState.lastTransition==="REPRO_GATE")return{nextMode:"ISSUE_INGEST",directive:'Branch freshness is not established for this trace (behind, or fetch failed without a recorded user override). Re-sync with the default branch (git fetch + rebase/merge), then call record_branch_freshness (issueNumber, freshness: "synced") — or, when the fetch genuinely failed and the user has accepted proceeding on the stale base, record freshness: "fetch-failed:<reason>" together with the verbatim override string the user provided. The trace will not transition to PLAN until this receipt permits.',nextLastTransition:"FRESHNESS_GATE",nextStatus:"in_progress"};return noop}if(!workflowArtifacts.reproductionPermitted){if(traceState.lastTransition===null||traceState.lastTransition==="FRESHNESS_GATE")return{nextMode:"ISSUE_INGEST",directive:"Reproduction evidence (or a typed --no-repro waiver) is required before this trace can transition to PLAN. Attempt a minimal reproduction and call record_issue_reproduction (performed: true, commands, output_summary), or restart with /swarm issue --no-repro.",nextLastTransition:"REPRO_GATE",nextStatus:"in_progress"};return noop}if(traceState.lastTransition===null||traceState.lastTransition==="ISSUE_INGEST_TO_PLAN"||traceState.lastTransition==="REPRO_GATE"||traceState.lastTransition==="FRESHNESS_GATE"){if(traceState.lastTransition==="ISSUE_INGEST_TO_PLAN")return noop;return{nextMode:"PLAN",directive:null,nextLastTransition:"ISSUE_INGEST_TO_PLAN",nextStatus:"in_progress"}}return noop}if(!workflowArtifacts.criticApproved)return noop;if(workflowArtifacts.planExists&&!workflowArtifacts.allPhasesComplete){if(traceState.lastTransition==="PLAN_TO_EXECUTE")return noop;return{nextMode:"EXECUTE",directive:null,nextLastTransition:"PLAN_TO_EXECUTE",nextStatus:"in_progress"}}if(!workflowArtifacts.planExists)return noop;if(!workflowArtifacts.implementationReviewVerified&&traceState.lastTransition!=="REVIEW_GATE"&&traceState.lastTransition!=="RECURRENCE_GATE"&&traceState.lastTransition!=="EXECUTE_TO_COMMIT")return{nextMode:"EXECUTE",directive:"All implementation phases are complete, but the independent implementation review is not yet recorded. Dispatch a FRESH-context reviewer and then a FRESH-context critic over the implementation diff (separate contexts from the implementer); when both approve, call record_implementation_review (issueNumber, reviewerVerdict APPROVE, criticVerdict APPROVE, the reviewed diff base/head, and notes). The trace will not hand off to commit-pr until this receipt exists.",nextLastTransition:"REVIEW_GATE",nextStatus:"in_progress"};if(workflowArtifacts.implementationReviewVerified&&!workflowArtifacts.recurrenceSweepVerified&&traceState.lastTransition!=="RECURRENCE_GATE"&&traceState.lastTransition!=="EXECUTE_TO_COMMIT")return{nextMode:"EXECUTE",directive:'The implementation review is approved, but the recurrence sweep is not yet recorded. Characterize the defect class, search the repository with explicit predicates, disposition every hit (FIX / FALSE_POSITIVE / OUT_OF_CLASS / DEFERRED_WITH_USER_APPROVAL), and install a guardrail that provably catches the original defect — or record the "no defect class" fast path with a one-line justification. Then call record_recurrence_sweep. The trace will not hand off to commit-pr until this receipt exists.',nextLastTransition:"RECURRENCE_GATE",nextStatus:"in_progress"};if(workflowArtifacts.implementationReviewVerified&&workflowArtifacts.recurrenceSweepVerified&&workflowArtifacts.traceValidationVerified===!1&&traceState.lastTransition!=="TRACE_VALIDATION_GATE"&&traceState.lastTransition!=="EXECUTE_TO_COMMIT")return{nextMode:"EXECUTE",directive:"The review and recurrence gates are satisfied, but the trace-check.sh validator receipts are not yet green. Run the issue-tracer phase validator for every completed phase (trace-check.sh phase <N> --slug <slug>) and record each outcome with record_trace_validation (issueNumber, phase, outcome, the reviewedCommit, and the treeId the validator reported). Any fail entry must be fixed and re-recorded as a pass before the trace can hand off to commit-pr.",nextLastTransition:"TRACE_VALIDATION_GATE",nextStatus:"in_progress"};if(!workflowArtifacts.implementationReviewVerified||!workflowArtifacts.recurrenceSweepVerified||workflowArtifacts.traceValidationVerified===!1)return noop;if(traceState.lastTransition==="EXECUTE_TO_COMMIT")return noop;return{nextMode:null,directive:"All implementation phases are complete. Compose commit-pr to publish the PR. Read .swarm/issue-reference.json for Closes #N. After the PR is created/updated, call record_issue_publication (with the issue number, PR number, URL, and HEAD sha) so this trace reaches its terminal published state — the trace is NOT complete until publication is confirmed.",nextLastTransition:"EXECUTE_TO_COMMIT",nextStatus:"publication_handoff"}}init_manager();import{existsSync as existsSync153,mkdirSync as mkdirSync87,readFileSync as readFileSync127,renameSync as renameSync44,unlinkSync as unlinkSync49,writeFileSync as writeFileSync56}from"node:fs";import*as path292 from"node:path";async function _defaultLoadPlanFromLedger(directory){return loadPlan(directory)}async function _defaultReproductionReceiptExists(directory,issueNumber){try{let filePath=path292.join(directory,".swarm","reproduction.json"),raw=_internals235.readFileSync(filePath,"utf-8"),parsed=JSON.parse(raw);if(typeof parsed!=="object"||parsed===null)return!1;let o=parsed;return o.performed===!0&&typeof o.issueNumber==="number"&&o.issueNumber===issueNumber}catch{return!1}}async function _defaultPublicationReceiptExists(directory,issueNumber){try{let filePath=path292.join(directory,".swarm","issue-publication.json"),raw=_internals235.readFileSync(filePath,"utf-8"),parsed=JSON.parse(raw);if(typeof parsed!=="object"||parsed===null)return!1;let o=parsed;return o.published===!0&&typeof o.issueNumber==="number"&&o.issueNumber===issueNumber}catch{return!1}}async function _defaultRecurrenceSweepReceiptExists(directory,issueNumber){try{let filePath=path292.join(directory,".swarm","recurrence-sweep.json"),raw=_internals235.readFileSync(filePath,"utf-8"),parsed=JSON.parse(raw);if(typeof parsed!=="object"||parsed===null)return!1;let o=parsed;if(o.issueNumber!==issueNumber||typeof o.defectClass!=="string"||o.defectClass.trim().length===0)return!1;let relatedProblems=o.relatedProblems;if(!(Array.isArray(relatedProblems)&&relatedProblems.length>0&&relatedProblems.every((rp)=>typeof rp==="object"&&rp!==null&&typeof rp.ref==="string"&&rp.ref.trim().length>0)))return!1;if(o.defectClass!=="no defect class"){let{predicates,dispositions,guardrail}=o,validPredicates=Array.isArray(predicates)&&predicates.length>0&&predicates.every((p)=>typeof p==="string"&&p.trim().length>0),validDispositions=Array.isArray(dispositions)&&dispositions.every((d)=>typeof d==="object"&&d!==null&&typeof d.ref==="string"&&["FIX","FALSE_POSITIVE","OUT_OF_CLASS","DEFERRED_WITH_USER_APPROVAL"].includes(String(d.disposition))),validGuardrail=typeof guardrail==="object"&&guardrail!==null&&typeof guardrail.kind==="string"&&typeof guardrail.proof==="string";if(!validPredicates||!validDispositions||!validGuardrail)return!1}else if(typeof o.justification!=="string"||o.justification.trim().length===0)return!1;return!0}catch{return!1}}async function _defaultImplementationReviewReceiptExists(directory,issueNumber){try{let filePath=path292.join(directory,".swarm","implementation-review.json"),raw=_internals235.readFileSync(filePath,"utf-8"),parsed=JSON.parse(raw);if(typeof parsed!=="object"||parsed===null)return!1;let o=parsed;return o.issueNumber===issueNumber&&o.reviewerVerdict==="APPROVE"&&o.criticVerdict==="APPROVE"}catch{return!1}}async function _defaultBranchFreshnessReceiptExists(directory,issueNumber){try{let filePath=path292.join(directory,".swarm","branch-freshness.json"),raw=_internals235.readFileSync(filePath,"utf-8"),parsed=JSON.parse(raw);if(typeof parsed!=="object"||parsed===null)return!1;let o=parsed;if(o.issueNumber!==issueNumber)return!1;if(typeof o.freshness!=="string")return!1;let freshness=o.freshness;if(freshness==="synced")return!0;if(/^behind:[1-9][0-9]*$/.test(freshness))return!1;if(/^fetch-failed:\S+$/.test(freshness))return typeof o.override==="string"&&o.override.trim().length>0;return!1}catch{return!1}}var TRACE_VALIDATION_PHASES=["0","1","2","2.5","3","4","4.2","4.5","4.6","5"];function isFortyHex(value){return typeof value==="string"&&/^[0-9a-f]{40}$/.test(value)}async function _defaultTraceValidationReceiptExists(directory,issueNumber){try{let filePath=path292.join(directory,".swarm","trace-validation.json"),raw=_internals235.readFileSync(filePath,"utf-8"),parsed=JSON.parse(raw);if(typeof parsed!=="object"||parsed===null)return!1;let o=parsed;if(o.issueNumber!==issueNumber)return!1;let validations=o.validations;if(!Array.isArray(validations)||validations.length===0)return!1;for(let entry of validations){if(typeof entry!=="object"||entry===null)return!1;let e=entry;if(!TRACE_VALIDATION_PHASES.includes(String(e.phase))||e.outcome!=="pass"||!isFortyHex(e.reviewedCommit)||!isFortyHex(e.treeId))return!1}return!0}catch{return!1}}async function _defaultMergeApprovalReceiptExists(directory,issueNumber){try{let filePath=path292.join(directory,".swarm","merge-approval.json"),raw=_internals235.readFileSync(filePath,"utf-8"),parsed=JSON.parse(raw);if(typeof parsed!=="object"||parsed===null)return!1;let o=parsed;if(o.issueNumber!==issueNumber)return!1;if(!isFortyHex(o.prHeadSha)||!isFortyHex(o.finalCriticReviewedCommit))return!1;return o.prHeadSha===o.finalCriticReviewedCommit}catch{return!1}}var _internals235={readFileSync:readFileSync127,writeFileSync:writeFileSync56,existsSync:existsSync153,renameSync:renameSync44,mkdirSync:mkdirSync87,unlinkSync:unlinkSync49,loadPlanFromLedger:_defaultLoadPlanFromLedger,reproductionReceiptExists:_defaultReproductionReceiptExists,publicationReceiptExists:_defaultPublicationReceiptExists,recurrenceSweepReceiptExists:_defaultRecurrenceSweepReceiptExists,implementationReviewReceiptExists:_defaultImplementationReviewReceiptExists,branchFreshnessReceiptExists:_defaultBranchFreshnessReceiptExists,traceValidationReceiptExists:_defaultTraceValidationReceiptExists,mergeApprovalReceiptExists:_defaultMergeApprovalReceiptExists},TRACE_STATUSES=["in_progress","publication_handoff","published","merge_approval_recorded"];function isTraceStatus(value){return typeof value==="string"&&TRACE_STATUSES.includes(value)}function isPhaseComplete(status2){return status2==="complete"||status2==="completed"}function isValidIssueReference(obj){if(typeof obj!=="object"||obj===null)return!1;let o=obj;if(typeof o.url!=="string"||!o.url.startsWith("https://github.com/"))return!1;return typeof o.owner==="string"&&typeof o.repo==="string"&&typeof o.number==="number"&&typeof o.timestamp==="string"&&typeof o.flags==="object"&&o.flags!==null}function isValidTraceStateShape(obj){if(typeof obj!=="object"||obj===null)return!1;let o=obj;return typeof o.issueNumber==="number"&&(o.lastTransition===null||typeof o.lastTransition==="string")}function normalizeTraceState(obj){let status2;if(isTraceStatus(obj.status))status2=obj.status;else if(obj.status===void 0&&typeof obj.completed==="boolean")status2=obj.completed?"publication_handoff":"in_progress";else status2="in_progress";return{issueNumber:obj.issueNumber,lastTransition:obj.lastTransition===null||typeof obj.lastTransition==="string"?obj.lastTransition:null,status:status2}}function readIssueReference(directory){try{let filePath=path292.join(directory,".swarm","issue-reference.json"),raw=_internals235.readFileSync(filePath,"utf-8"),parsed=JSON.parse(raw);if(!isValidIssueReference(parsed))return null;return parsed}catch{return null}}function readTraceState(directory){let defaultState={issueNumber:0,lastTransition:null,status:"in_progress"};try{let filePath=path292.join(directory,".swarm","issue-trace-state.json"),raw=_internals235.readFileSync(filePath,"utf-8"),parsed=JSON.parse(raw);if(!isValidTraceStateShape(parsed))return defaultState;return normalizeTraceState(parsed)}catch{return defaultState}}function writeTraceState(directory,state2){let swarmDir=path292.join(directory,".swarm");_internals235.mkdirSync(swarmDir,{recursive:!0});let finalPath=path292.join(swarmDir,"issue-trace-state.json"),tmpPath=path292.join(swarmDir,`issue-trace-state.tmp.${process.pid}.${Date.now()}.json`);_internals235.writeFileSync(tmpPath,JSON.stringify(state2,null,2),"utf-8");try{_internals235.renameSync(tmpPath,finalPath)}catch{try{_internals235.unlinkSync(finalPath)}catch{}try{_internals235.renameSync(tmpPath,finalPath)}catch(retryErr){try{_internals235.unlinkSync(tmpPath)}catch{}throw retryErr}}}function readSpecIssueNumber(directory){try{let filePath=path292.join(directory,".swarm","spec.md"),raw=_internals235.readFileSync(filePath,"utf-8"),sectionStart=raw.indexOf("## Source Issue");if(sectionStart===-1)return null;let nextHeading=raw.indexOf(`
|
|
7361
|
-
## `,sectionStart+14),sectionEnd=nextHeading===-1?raw.length:nextHeading,section=raw.slice(sectionStart,sectionEnd),numberMatch=section.match(/-\s+Number:\s*(\d+)/);if(numberMatch)return parseInt(numberMatch[1],10);let urlMatch=section.match(/-\s+URL:.*\/issues\/(\d+)/);if(urlMatch)return parseInt(urlMatch[1],10);return null}catch{return null}}async function readPlanPhaseStatus(directory){let plan=await _internals235.loadPlanFromLedger(directory);if(!plan||plan.phases.length===0)return{planExists:!1,allComplete:!1};return{planExists:!0,allComplete:plan.phases.every((phase)=>isPhaseComplete(phase.status))}}function specExists(directory){return _internals235.existsSync(path292.join(directory,".swarm","spec.md"))}async function reproductionReceiptExists(directory,issueNumber){return _internals235.reproductionReceiptExists(directory,issueNumber)}async function publicationReceiptExists(directory,issueNumber){return _internals235.publicationReceiptExists(directory,issueNumber)}async function recurrenceSweepReceiptExists(directory,issueNumber){return _internals235.recurrenceSweepReceiptExists(directory,issueNumber)}async function implementationReviewReceiptExists(directory,issueNumber){return _internals235.implementationReviewReceiptExists(directory,issueNumber)}async function branchFreshnessReceiptExists(directory,issueNumber){return _internals235.branchFreshnessReceiptExists(directory,issueNumber)}async function traceValidationReceiptExists(directory,issueNumber){return _internals235.traceValidationReceiptExists(directory,issueNumber)}async function mergeApprovalReceiptExists(directory,issueNumber){return _internals235.mergeApprovalReceiptExists(directory,issueNumber)}init_system_guidance_carrier();var _internals236={readIssueReference,readTraceState,writeTraceState,readSpecIssueNumber,readPlanPhaseStatus,specExists,reproductionReceiptExists,publicationReceiptExists,recurrenceSweepReceiptExists,implementationReviewReceiptExists,branchFreshnessReceiptExists,traceValidationReceiptExists,mergeApprovalReceiptExists,isPlanCriticApproved,getPlanLedgerState:getPlanLedgerStateReadOnly,logError:error48,boundedApprovalCheck:(directory,timeoutMs)=>boundedApprovalCheck(directory,timeoutMs)},cachedApproval=null,cachedPhaseStatus=null;async function boundedApprovalCheck(directory,timeoutMs){try{let ledgerPath3=path293.join(directory,".swarm","plan-ledger.jsonl"),currentSize=-1,currentMtime=-1;try{let stat25=fs168.statSync(ledgerPath3);currentSize=stat25.size,currentMtime=stat25.mtimeMs}catch{}let state2=null,authorityReadFailed=!1;try{state2=_internals236.getPlanLedgerState(directory)}catch{authorityReadFailed=!0}let revision=authorityReadFailed?null:state2?.authorityMode==="sqlite"?`sqlite:${state2.lastSeq}:${state2.lastEventHash??""}:${state2.updatedAt}`:`file:${currentSize}:${currentMtime}`;if(cachedApproval&&cachedApproval.dir===directory&&cachedApproval.revision===revision)return cachedApproval.result;let timer;try{let timeout=new Promise((resolve113)=>{timer=setTimeout(()=>resolve113(!1),timeoutMs)}),result=await Promise.race([_internals236.isPlanCriticApproved(directory),timeout]);if(revision!==null)cachedApproval={dir:directory,revision,result};return result}finally{if(timer!==void 0)clearTimeout(timer)}}catch{return!1}}async function cachedReadPlanPhaseStatus(directory){let planJsonPath=path293.join(directory,".swarm","plan.json"),currentSize=-1,currentMtime=-1;try{let stat25=fs168.statSync(planJsonPath);currentSize=stat25.size,currentMtime=stat25.mtimeMs}catch{}if(cachedPhaseStatus&&cachedPhaseStatus.dir===directory&&cachedPhaseStatus.planJsonSize===currentSize&&cachedPhaseStatus.planJsonMtime===currentMtime)return cachedPhaseStatus.result;let result=await _internals236.readPlanPhaseStatus(directory);return cachedPhaseStatus={dir:directory,planJsonSize:currentSize,planJsonMtime:currentMtime,result},result}function createIssueTraceHook(_config2,directory,approvalTimeoutMs=5000){return{messagesTransform:async(_input,output)=>{try{let issueRef=_internals236.readIssueReference(directory);if(!issueRef||issueRef.flags.trace!==!0)return;let traceState=_internals236.readTraceState(directory),_specExists=_internals236.specExists(directory),_specIssueNumber=_internals236.readSpecIssueNumber(directory),phaseStatus=await cachedReadPlanPhaseStatus(directory),_criticApproved=await boundedApprovalCheck(directory,approvalTimeoutMs),_reproReceipt=await _internals236.reproductionReceiptExists(directory,issueRef.number),_reproductionPermitted=issueRef.flags.noRepro===!0||issueRef.noReproWaiver?.waived===!0||_reproReceipt,_publicationObserved=await _internals236.publicationReceiptExists(directory,issueRef.number),_implementationReviewVerified=await _internals236.implementationReviewReceiptExists(directory,issueRef.number),_recurrenceSweepVerified=await _internals236.recurrenceSweepReceiptExists(directory,issueRef.number),_freshnessPermitted=await _internals236.branchFreshnessReceiptExists(directory,issueRef.number),_traceValidationVerified=await _internals236.traceValidationReceiptExists(directory,issueRef.number),_mergeApprovalObserved=await _internals236.mergeApprovalReceiptExists(directory,issueRef.number),result=computeNextMode({issueReference:issueRef,traceState,workflowArtifacts:{specExists:_specExists,specIssueNumber:_specIssueNumber,planExists:phaseStatus.planExists,criticApproved:_criticApproved,allPhasesComplete:phaseStatus.allComplete,reproductionPermitted:_reproductionPermitted,freshnessPermitted:_freshnessPermitted,publicationObserved:_publicationObserved,implementationReviewVerified:_implementationReviewVerified,recurrenceSweepVerified:_recurrenceSweepVerified,traceValidationVerified:_traceValidationVerified,mergeApprovalObserved:_mergeApprovalObserved}});if(result.nextMode===null&&result.directive===null)return;let finalDirective=result.directive?result.directive.replace("#N",`#${issueRef.number}`):null,out=output;if(!Array.isArray(out.messages))return;let modeDelivered=result.nextMode===null||appendGuidanceCarrier(out.messages,"issue-trace",`[MODE: ${result.nextMode}]`)!==null,directiveDelivered=finalDirective===null||appendGuidanceCarrier(out.messages,"issue-trace",finalDirective)!==null;if(!modeDelivered||!directiveDelivered)return;_internals236.writeTraceState(directory,{issueNumber:traceState.issueNumber,lastTransition:result.nextLastTransition,status:result.nextStatus})}catch(err){_internals236.logError("[issue-trace] hook cycle failed:",err)}}}}init_schema();init_core_events();init_state2();init_logger();init_knowledge_application();init_knowledge_receipt_ledger();init_knowledge_store();init_system_guidance_carrier();import{existsSync as existsSync154}from"node:fs";var HIGH_RISK_TOOLS=new Set(["save_plan","update_task_status","phase_complete","task","Task","skill_regenerate","skill_retire"]),DEFAULT_MAX_GATE_DENIALS=5,DEFAULT_GATE_STALENESS_MS=600000;function selectCurrentArchitectDirectiveMemberships(memberships){let activeArchitect=memberships.filter((membership)=>membership.exposure_kind==="architect_directive"&&!membership.phase_closed_at),latest,latestAt=Number.NEGATIVE_INFINITY;for(let membership of activeArchitect){let committedAt=Date.parse(membership.committed_at),comparableAt=Number.isFinite(committedAt)?committedAt:Number.NEGATIVE_INFINITY;if(!latest||comparableAt>=latestAt)latest=membership,latestAt=comparableAt}if(!latest)return[];return activeArchitect.filter((membership)=>membership.phase===latest.phase&&membership.task_id===latest.task_id)}function selectStaleUnmarkedMemberships(memberships,now2,stalenessMs){return memberships.filter((membership)=>{if(membership.application_marker||hasEffectiveGateRelease(membership))return!1;let committedAt=Date.parse(membership.committed_at);return Number.isFinite(committedAt)&&now2-committedAt>stalenessMs})}function hasEffectiveGateRelease(membership){return membership.gate_release?.membership_event_id===membership.membership_event_id}function groupMembershipsByTrace(memberships){let byTrace=new Map;for(let membership of memberships){let group=byTrace.get(membership.trace_id)??[];group.push(membership),byTrace.set(membership.trace_id,group)}return byTrace}async function loadDirectiveContents(directory,entryIds){let contents=new Map;if(entryIds.length===0)return contents;let want=new Set(entryIds),sources=[resolveSwarmKnowledgePath(directory)];try{let hivePath=resolveHiveKnowledgePath2();if(existsSync154(hivePath))sources.push(hivePath)}catch{}for(let filePath of sources)try{let entries2=await readKnowledge(filePath);for(let entry of entries2)if(want.has(entry.id)&&!contents.has(entry.id)&&typeof entry.lesson==="string")contents.set(entry.id,entry.lesson)}catch{}return contents}function buildGateDenialMessage(toolName,memberships,contents){let pairs=memberships.map((m)=>`${m.trace_id}:${m.entry_id}`),examples=memberships.map((m)=>` KNOWLEDGE_N_A:${m.trace_id}:${m.entry_id} reason=<reason>`),contentLines=memberships.map((m)=>{let lesson=contents.get(m.entry_id);return` [${m.trace_id}:${m.entry_id}] ${lesson??"content not found in knowledge store — see the most recent <swarm_knowledge_directives> block or run knowledge_recall"}`});return[`KNOWLEDGE_ENFORCE_GATE_DENY: ${toolName} blocked — unacknowledged critical knowledge directive(s): ${pairs.join(", ")}.`,"","Acknowledge each directive using its exact, colon-separated tokens (<trace_id>:<entry_id>) with one of these verb markers:"," KNOWLEDGE_APPLIED:<trace_id>:<entry_id>"," KNOWLEDGE_IGNORED:<trace_id>:<entry_id> reason=<short reason>"," KNOWLEDGE_CONTRADICTED:<trace_id>:<entry_id> reason=<observable conflict>"," KNOWLEDGE_N_A:<trace_id>:<entry_id> reason=<short reason>"," KNOWLEDGE_VIOLATED:<trace_id>:<entry_id> reason=<short reason>","KNOWLEDGE_N_A (does not apply; neutral) is a valid, penalty-free acknowledgment when the directive does not pertain to the current step.","","Copy-paste to acknowledge each directive now (replace <reason> with a short reason):",...examples,"","Directive content being acknowledged:",...contentLines].join(`
|
|
7361
|
+
${errorSummary}`)}}}}init_init_orphan_recovery();init_state2();import*as fs167 from"node:fs/promises";import*as path291 from"node:path";var ADVISORY_FILENAME="init-orphan-recovery.json";function createInitOrphanRecoveryAdvisoryHook(directory){let consumedBySession=new Set;async function readAdvisoryFile(){let advisoryPath=path291.join(directory,".swarm","advisories",ADVISORY_FILENAME);try{let content=await fs167.readFile(advisoryPath,"utf-8");return JSON.parse(content)}catch{return null}}async function deleteAdvisoryFile(){let advisoryPath=path291.join(directory,".swarm","advisories",ADVISORY_FILENAME);try{await fs167.unlink(advisoryPath)}catch{}}function formatError3(error93){return`ORPHAN_RECOVERY_ERROR: Could not reclaim branch "${error93.branch}": ${error93.error}`}async function messagesTransform(_input,output){let messages=output.messages;if(!messages||messages.length===0)return;let sessionId=messages[messages.length-1]?.info?.sessionID;if(!sessionId)return;let activeAgent=swarmState.activeAgent.get(sessionId),session=swarmState.agentSessions.get(sessionId),ORCHESTRATOR_NAME2="Architect";if(!(activeAgent?activeAgent===ORCHESTRATOR_NAME2||activeAgent.endsWith("_Architect"):session?session.agentName===ORCHESTRATOR_NAME2||session.agentName.endsWith("_Architect"):!1))return;if(consumedBySession.has(sessionId))return;let advisory=await readAdvisoryFile();if(!advisory)return;consumedBySession.add(sessionId),await deleteAdvisoryFile();let reclaimedForGate=advisory.reclaimed;if(!((advisory.warnings?.length??0)>0||(advisory.errors?.length??0)>0||(reclaimedForGate?.removedBranches?.length??0)>0||(reclaimedForGate?.removedWorktrees?.length??0)>0))return;let targetSession=ensureAgentSession(sessionId,void 0,directory),timestamp=advisory.initTimestamp?new Date(advisory.initTimestamp).toLocaleString():"unknown";pushAdvisory(targetSession,`[INIT ORPHAN RECOVERY] Plugin init detected the following at ${timestamp}:`);for(let warning of advisory.warnings??[])pushAdvisory(targetSession,` WARNING: ${warning}`);for(let err of advisory.errors??[])pushAdvisory(targetSession,` ERROR: ${formatError3(err)}`);let reclaimed=advisory.reclaimed;if((reclaimed?.removedBranches?.length??0)>0)pushAdvisory(targetSession,` Reclaimed ${reclaimed.removedBranches.length} orphaned branch(es): ${reclaimed.removedBranches.join(", ")}`);if(reclaimed?.removedWorktrees&&reclaimed.removedWorktrees.length>0)pushAdvisory(targetSession,` Reclaimed ${reclaimed.removedWorktrees.length} orphaned worktree directory(ies): ${reclaimed.removedWorktrees.join(", ")}`);if(reclaimed?.prunedWorktrees)pushAdvisory(targetSession," Stale worktree metadata pruned.")}return{messagesTransform}}init_ledger_sqlite();init_logger();init_spec_hash();init_delegation_gate();import*as fs168 from"node:fs";import*as path293 from"node:path";function computeNextMode(params){let{issueReference,traceState,workflowArtifacts}=params,noop={nextMode:null,directive:null,nextLastTransition:traceState.lastTransition,nextStatus:traceState.status};if(!issueReference||issueReference.flags.trace!==!0)return noop;if(traceState.status==="merge_approval_recorded")return noop;if(traceState.status==="published"){if(workflowArtifacts.mergeApprovalObserved&&traceState.lastTransition!=="MERGE_APPROVAL_RECORDED")return{nextMode:null,directive:"Merge approval recorded for this trace, bound to the PR head SHA in .swarm/merge-approval.json. The merge decision is human-enforced: the human user owns and executes it through the host. This plugin records the approval verbatim for audit; it does not drive, gate, or green-light the merge itself.",nextLastTransition:"MERGE_APPROVAL_RECORDED",nextStatus:"merge_approval_recorded"};return noop}if(traceState.status==="publication_handoff"){if(workflowArtifacts.publicationObserved&&traceState.lastTransition!=="PUBLISHED")return{nextMode:null,directive:"Publication confirmed. The issue-trace workflow is complete.",nextLastTransition:"PUBLISHED",nextStatus:"published"};return noop}if(workflowArtifacts.specIssueNumber===null||workflowArtifacts.specIssueNumber!==issueReference.number||traceState.issueNumber!==issueReference.number){if(traceState.lastTransition!=="SPEC_MISMATCH_GATE"&&(workflowArtifacts.specIssueNumber!==null||traceState.issueNumber!==issueReference.number))return{nextMode:"ISSUE_INGEST",directive:"The spec on disk (## Source Issue) does not match the traced issue #N. Regenerate the spec for this issue through the issue-ingest flow (/swarm issue), or correct the ## Source Issue number in .swarm/spec.md. The trace will not advance while the spec belongs to a different issue.",nextLastTransition:"SPEC_MISMATCH_GATE",nextStatus:"in_progress"};return noop}if(!workflowArtifacts.specExists)return noop;if(!workflowArtifacts.planExists){if(workflowArtifacts.freshnessPermitted===!1){if(traceState.lastTransition===null||traceState.lastTransition==="REPRO_GATE"||traceState.lastTransition==="SPEC_MISMATCH_GATE")return{nextMode:"ISSUE_INGEST",directive:'Branch freshness is not established for this trace (behind, or fetch failed without a recorded user override). Re-sync with the default branch (git fetch + rebase/merge), then call record_branch_freshness (issueNumber, freshness: "synced") — or, when the fetch genuinely failed and the user has accepted proceeding on the stale base, record freshness: "fetch-failed:<reason>" together with the verbatim override string the user provided. The trace will not transition to PLAN until this receipt permits.',nextLastTransition:"FRESHNESS_GATE",nextStatus:"in_progress"};return noop}if(!workflowArtifacts.reproductionPermitted){if(traceState.lastTransition===null||traceState.lastTransition==="FRESHNESS_GATE"||traceState.lastTransition==="SPEC_MISMATCH_GATE")return{nextMode:"ISSUE_INGEST",directive:"Reproduction evidence (or a typed --no-repro waiver) is required before this trace can transition to PLAN. Attempt a minimal reproduction and call record_issue_reproduction (performed: true, commands, output_summary), or restart with /swarm issue --no-repro.",nextLastTransition:"REPRO_GATE",nextStatus:"in_progress"};return noop}if(traceState.lastTransition===null||traceState.lastTransition==="ISSUE_INGEST_TO_PLAN"||traceState.lastTransition==="REPRO_GATE"||traceState.lastTransition==="FRESHNESS_GATE"||traceState.lastTransition==="SPEC_MISMATCH_GATE"){if(traceState.lastTransition==="ISSUE_INGEST_TO_PLAN")return noop;return{nextMode:"PLAN",directive:null,nextLastTransition:"ISSUE_INGEST_TO_PLAN",nextStatus:"in_progress"}}return noop}if(workflowArtifacts.planBoundToSpec===!1){if(traceState.lastTransition!=="PLAN_BINDING_GATE")return{nextMode:"PLAN",directive:"The loaded plan cannot be bound to the current spec for issue #N — its recorded specHash differs from the current spec (or the plan predates spec linkage), so executing it under this trace would run the wrong plan. Re-save the plan against the current spec (save_plan after the spec is correct), or run /swarm reset to clear the foreign plan and re-plan (note: reset also deletes .swarm/spec.md and the recorded review receipts, so re-run /swarm issue --trace afterwards to regenerate them). The trace will not transition to EXECUTE on a plan it cannot bind.",nextLastTransition:"PLAN_BINDING_GATE",nextStatus:"in_progress"};return noop}if(!workflowArtifacts.reproductionPermitted){if(traceState.lastTransition===null||traceState.lastTransition==="SPEC_MISMATCH_GATE"||traceState.lastTransition==="PLAN_BINDING_GATE"||traceState.lastTransition==="FRESHNESS_GATE"||traceState.lastTransition==="REPRO_GATE"||traceState.lastTransition==="ISSUE_INGEST_TO_PLAN")return{nextMode:"ISSUE_INGEST",directive:"A plan already exists for this trace, but reproduction evidence has not been recorded for issue #N. Attempt a minimal reproduction and call record_issue_reproduction (performed: true, commands, output_summary), or restart with /swarm issue --no-repro. The trace will not transition to EXECUTE until reproduction is permitted.",nextLastTransition:"REPRO_GATE_LATE",nextStatus:"in_progress"};return noop}if(!workflowArtifacts.criticApproved){if(traceState.lastTransition===null||traceState.lastTransition==="SPEC_MISMATCH_GATE"||traceState.lastTransition==="PLAN_BINDING_GATE"||traceState.lastTransition==="REPRO_GATE_LATE"||traceState.lastTransition==="FRESHNESS_GATE"||traceState.lastTransition==="REPRO_GATE"||traceState.lastTransition==="ISSUE_INGEST_TO_PLAN")return{nextMode:"CRITIC-GATE",directive:"The plan for issue #N is not yet critic-approved. Dispatch MODE: CRITIC-GATE and wait for VERDICT: APPROVED before EXECUTE. If the critic already returned APPROVED but the snapshot was not recorded (issue #2012), call approve_plan_critic with a reason, or run /swarm approve-plan-critic <reason>, to record the approval.",nextLastTransition:"CRITIC_GATE",nextStatus:"in_progress"};return noop}if(workflowArtifacts.planExists&&!workflowArtifacts.allPhasesComplete){if(traceState.lastTransition==="PLAN_TO_EXECUTE")return noop;return{nextMode:"EXECUTE",directive:null,nextLastTransition:"PLAN_TO_EXECUTE",nextStatus:"in_progress"}}if(!workflowArtifacts.planExists)return noop;if(!workflowArtifacts.implementationReviewVerified&&traceState.lastTransition!=="REVIEW_GATE"&&traceState.lastTransition!=="RECURRENCE_GATE"&&traceState.lastTransition!=="EXECUTE_TO_COMMIT")return{nextMode:"EXECUTE",directive:"All implementation phases are complete, but the independent implementation review is not yet recorded. Dispatch a FRESH-context reviewer and then a FRESH-context critic over the implementation diff (separate contexts from the implementer); when both approve, call record_implementation_review (issueNumber, reviewerVerdict APPROVE, criticVerdict APPROVE, the reviewed diff base/head, and notes). The trace will not hand off to commit-pr until this receipt exists.",nextLastTransition:"REVIEW_GATE",nextStatus:"in_progress"};if(workflowArtifacts.implementationReviewVerified&&!workflowArtifacts.recurrenceSweepVerified&&traceState.lastTransition!=="RECURRENCE_GATE"&&traceState.lastTransition!=="EXECUTE_TO_COMMIT")return{nextMode:"EXECUTE",directive:'The implementation review is approved, but the recurrence sweep is not yet recorded. Characterize the defect class, search the repository with explicit predicates, disposition every hit (FIX / FALSE_POSITIVE / OUT_OF_CLASS / DEFERRED_WITH_USER_APPROVAL), and install a guardrail that provably catches the original defect — or record the "no defect class" fast path with a one-line justification. Then call record_recurrence_sweep. The trace will not hand off to commit-pr until this receipt exists.',nextLastTransition:"RECURRENCE_GATE",nextStatus:"in_progress"};if(workflowArtifacts.implementationReviewVerified&&workflowArtifacts.recurrenceSweepVerified&&workflowArtifacts.traceValidationVerified===!1&&traceState.lastTransition!=="TRACE_VALIDATION_GATE"&&traceState.lastTransition!=="EXECUTE_TO_COMMIT")return{nextMode:"EXECUTE",directive:"The review and recurrence gates are satisfied, but the trace-check.sh validator receipts are not yet green. Run the issue-tracer phase validator for every completed phase (trace-check.sh phase <N> --slug <slug>) and record each outcome with record_trace_validation (issueNumber, phase, outcome, the reviewedCommit, and the treeId the validator reported). Any fail entry must be fixed and re-recorded as a pass before the trace can hand off to commit-pr.",nextLastTransition:"TRACE_VALIDATION_GATE",nextStatus:"in_progress"};if(!workflowArtifacts.implementationReviewVerified||!workflowArtifacts.recurrenceSweepVerified||workflowArtifacts.traceValidationVerified===!1)return noop;if(traceState.lastTransition==="EXECUTE_TO_COMMIT")return noop;return{nextMode:null,directive:"All implementation phases are complete. Compose commit-pr to publish the PR. Read .swarm/issue-reference.json for Closes #N. After the PR is created/updated, call record_issue_publication (with the issue number, PR number, URL, and HEAD sha) so this trace reaches its terminal published state — the trace is NOT complete until publication is confirmed.",nextLastTransition:"EXECUTE_TO_COMMIT",nextStatus:"publication_handoff"}}init_manager();import{existsSync as existsSync153,mkdirSync as mkdirSync87,readFileSync as readFileSync127,renameSync as renameSync44,unlinkSync as unlinkSync49,writeFileSync as writeFileSync56}from"node:fs";import*as path292 from"node:path";async function _defaultLoadPlanFromLedger(directory){return loadPlan(directory)}async function _defaultReproductionReceiptExists(directory,issueNumber){try{let filePath=path292.join(directory,".swarm","reproduction.json"),raw=_internals235.readFileSync(filePath,"utf-8"),parsed=JSON.parse(raw);if(typeof parsed!=="object"||parsed===null)return!1;let o=parsed;return o.performed===!0&&typeof o.issueNumber==="number"&&o.issueNumber===issueNumber}catch{return!1}}async function _defaultPublicationReceiptExists(directory,issueNumber){try{let filePath=path292.join(directory,".swarm","issue-publication.json"),raw=_internals235.readFileSync(filePath,"utf-8"),parsed=JSON.parse(raw);if(typeof parsed!=="object"||parsed===null)return!1;let o=parsed;return o.published===!0&&typeof o.issueNumber==="number"&&o.issueNumber===issueNumber}catch{return!1}}async function _defaultRecurrenceSweepReceiptExists(directory,issueNumber){try{let filePath=path292.join(directory,".swarm","recurrence-sweep.json"),raw=_internals235.readFileSync(filePath,"utf-8"),parsed=JSON.parse(raw);if(typeof parsed!=="object"||parsed===null)return!1;let o=parsed;if(o.issueNumber!==issueNumber||typeof o.defectClass!=="string"||o.defectClass.trim().length===0)return!1;let relatedProblems=o.relatedProblems;if(!(Array.isArray(relatedProblems)&&relatedProblems.length>0&&relatedProblems.every((rp)=>typeof rp==="object"&&rp!==null&&typeof rp.ref==="string"&&rp.ref.trim().length>0)))return!1;if(o.defectClass!=="no defect class"){let{predicates,dispositions,guardrail}=o,validPredicates=Array.isArray(predicates)&&predicates.length>0&&predicates.every((p)=>typeof p==="string"&&p.trim().length>0),validDispositions=Array.isArray(dispositions)&&dispositions.length>0&&dispositions.every((d)=>typeof d==="object"&&d!==null&&typeof d.ref==="string"&&["FIX","FALSE_POSITIVE","OUT_OF_CLASS","DEFERRED_WITH_USER_APPROVAL"].includes(String(d.disposition))),validGuardrail=typeof guardrail==="object"&&guardrail!==null&&typeof guardrail.kind==="string"&&typeof guardrail.proof==="string";if(!validPredicates||!validDispositions||!validGuardrail)return!1}else if(typeof o.justification!=="string"||o.justification.trim().length===0)return!1;return!0}catch{return!1}}async function _defaultImplementationReviewReceiptExists(directory,issueNumber){try{let filePath=path292.join(directory,".swarm","implementation-review.json"),raw=_internals235.readFileSync(filePath,"utf-8"),parsed=JSON.parse(raw);if(typeof parsed!=="object"||parsed===null)return!1;let o=parsed;return o.issueNumber===issueNumber&&o.reviewerVerdict==="APPROVE"&&o.criticVerdict==="APPROVE"}catch{return!1}}async function _defaultBranchFreshnessReceiptExists(directory,issueNumber){try{let filePath=path292.join(directory,".swarm","branch-freshness.json"),raw=_internals235.readFileSync(filePath,"utf-8"),parsed=JSON.parse(raw);if(typeof parsed!=="object"||parsed===null)return!1;let o=parsed;if(o.issueNumber!==issueNumber)return!1;if(typeof o.freshness!=="string")return!1;let freshness=o.freshness;if(freshness==="synced")return!0;if(/^behind:[1-9][0-9]*$/.test(freshness))return!1;if(/^fetch-failed:\S+$/.test(freshness))return typeof o.override==="string"&&o.override.trim().length>0;return!1}catch{return!1}}var TRACE_VALIDATION_PHASES=["0","1","2","2.5","3","4","4.2","4.5","4.6","5"];function isFortyHex(value){return typeof value==="string"&&/^[0-9a-f]{40}$/.test(value)}async function _defaultTraceValidationReceiptExists(directory,issueNumber){try{let filePath=path292.join(directory,".swarm","trace-validation.json"),raw=_internals235.readFileSync(filePath,"utf-8"),parsed=JSON.parse(raw);if(typeof parsed!=="object"||parsed===null)return!1;let o=parsed;if(o.issueNumber!==issueNumber)return!1;let validations=o.validations;if(!Array.isArray(validations)||validations.length===0)return!1;for(let entry of validations){if(typeof entry!=="object"||entry===null)return!1;let e=entry;if(!TRACE_VALIDATION_PHASES.includes(String(e.phase))||e.outcome!=="pass"||!isFortyHex(e.reviewedCommit)||!isFortyHex(e.treeId))return!1}return!0}catch{return!1}}async function _defaultMergeApprovalReceiptExists(directory,issueNumber){try{let filePath=path292.join(directory,".swarm","merge-approval.json"),raw=_internals235.readFileSync(filePath,"utf-8"),parsed=JSON.parse(raw);if(typeof parsed!=="object"||parsed===null)return!1;let o=parsed;if(o.issueNumber!==issueNumber)return!1;if(!isFortyHex(o.prHeadSha)||!isFortyHex(o.finalCriticReviewedCommit))return!1;return o.prHeadSha===o.finalCriticReviewedCommit}catch{return!1}}var _internals235={readFileSync:readFileSync127,writeFileSync:writeFileSync56,existsSync:existsSync153,renameSync:renameSync44,mkdirSync:mkdirSync87,unlinkSync:unlinkSync49,loadPlanFromLedger:_defaultLoadPlanFromLedger,reproductionReceiptExists:_defaultReproductionReceiptExists,publicationReceiptExists:_defaultPublicationReceiptExists,recurrenceSweepReceiptExists:_defaultRecurrenceSweepReceiptExists,implementationReviewReceiptExists:_defaultImplementationReviewReceiptExists,branchFreshnessReceiptExists:_defaultBranchFreshnessReceiptExists,traceValidationReceiptExists:_defaultTraceValidationReceiptExists,mergeApprovalReceiptExists:_defaultMergeApprovalReceiptExists},TRACE_STATUSES=["in_progress","publication_handoff","published","merge_approval_recorded"];function isTraceStatus(value){return typeof value==="string"&&TRACE_STATUSES.includes(value)}function isPhaseComplete(status2){return status2==="complete"||status2==="completed"}function isValidIssueReference(obj){if(typeof obj!=="object"||obj===null)return!1;let o=obj;if(typeof o.url!=="string"||!o.url.startsWith("https://github.com/"))return!1;return typeof o.owner==="string"&&typeof o.repo==="string"&&typeof o.number==="number"&&typeof o.timestamp==="string"&&typeof o.flags==="object"&&o.flags!==null}function isValidTraceStateShape(obj){if(typeof obj!=="object"||obj===null)return!1;let o=obj;return typeof o.issueNumber==="number"&&(o.lastTransition===null||typeof o.lastTransition==="string")}function normalizeTraceState(obj){let status2;if(isTraceStatus(obj.status))status2=obj.status;else if(obj.status===void 0&&typeof obj.completed==="boolean")status2=obj.completed?"publication_handoff":"in_progress";else status2="in_progress";return{issueNumber:obj.issueNumber,lastTransition:obj.lastTransition===null||typeof obj.lastTransition==="string"?obj.lastTransition:null,status:status2}}function readIssueReference(directory){try{let filePath=path292.join(directory,".swarm","issue-reference.json"),raw=_internals235.readFileSync(filePath,"utf-8"),parsed=JSON.parse(raw);if(!isValidIssueReference(parsed))return null;return parsed}catch{return null}}function readTraceState(directory){let defaultState={issueNumber:0,lastTransition:null,status:"in_progress"};try{let filePath=path292.join(directory,".swarm","issue-trace-state.json"),raw=_internals235.readFileSync(filePath,"utf-8"),parsed=JSON.parse(raw);if(!isValidTraceStateShape(parsed))return defaultState;return normalizeTraceState(parsed)}catch{return defaultState}}function writeTraceState(directory,state2){let swarmDir=path292.join(directory,".swarm");_internals235.mkdirSync(swarmDir,{recursive:!0});let finalPath=path292.join(swarmDir,"issue-trace-state.json"),tmpPath=path292.join(swarmDir,`issue-trace-state.tmp.${process.pid}.${Date.now()}.json`);_internals235.writeFileSync(tmpPath,JSON.stringify(state2,null,2),"utf-8");try{_internals235.renameSync(tmpPath,finalPath)}catch{try{_internals235.unlinkSync(finalPath)}catch{}try{_internals235.renameSync(tmpPath,finalPath)}catch(retryErr){try{_internals235.unlinkSync(tmpPath)}catch{}throw retryErr}}}function readSpecIssueNumber(directory){try{let filePath=path292.join(directory,".swarm","spec.md"),raw=_internals235.readFileSync(filePath,"utf-8"),sectionStart=raw.indexOf("## Source Issue");if(sectionStart===-1)return null;let nextHeading=raw.indexOf(`
|
|
7362
|
+
## `,sectionStart+14),sectionEnd=nextHeading===-1?raw.length:nextHeading,section=raw.slice(sectionStart,sectionEnd),numberMatch=section.match(/-\s+Number:\s*(\d+)/);if(numberMatch)return parseInt(numberMatch[1],10);let urlMatch=section.match(/-\s+URL:.*\/issues\/(\d+)/);if(urlMatch)return parseInt(urlMatch[1],10);return null}catch{return null}}async function readPlanPhaseStatus(directory){let plan=await _internals235.loadPlanFromLedger(directory);if(!plan||plan.phases.length===0)return{planExists:!1,allComplete:!1,planSpecHash:void 0};return{planExists:!0,allComplete:plan.phases.every((phase)=>isPhaseComplete(phase.status)),planSpecHash:typeof plan.specHash==="string"?plan.specHash:void 0}}function specExists(directory){return _internals235.existsSync(path292.join(directory,".swarm","spec.md"))}async function reproductionReceiptExists(directory,issueNumber){return _internals235.reproductionReceiptExists(directory,issueNumber)}async function publicationReceiptExists(directory,issueNumber){return _internals235.publicationReceiptExists(directory,issueNumber)}async function recurrenceSweepReceiptExists(directory,issueNumber){return _internals235.recurrenceSweepReceiptExists(directory,issueNumber)}async function implementationReviewReceiptExists(directory,issueNumber){return _internals235.implementationReviewReceiptExists(directory,issueNumber)}async function branchFreshnessReceiptExists(directory,issueNumber){return _internals235.branchFreshnessReceiptExists(directory,issueNumber)}async function traceValidationReceiptExists(directory,issueNumber){return _internals235.traceValidationReceiptExists(directory,issueNumber)}async function mergeApprovalReceiptExists(directory,issueNumber){return _internals235.mergeApprovalReceiptExists(directory,issueNumber)}init_system_guidance_carrier();var _internals236={readIssueReference,readTraceState,writeTraceState,readSpecIssueNumber,readPlanPhaseStatus,specExists,reproductionReceiptExists,publicationReceiptExists,recurrenceSweepReceiptExists,implementationReviewReceiptExists,branchFreshnessReceiptExists,traceValidationReceiptExists,mergeApprovalReceiptExists,isPlanCriticApproved,getPlanLedgerState:getPlanLedgerStateReadOnly,logError:error48,computeSpecHash,boundedApprovalCheck:(directory,timeoutMs)=>boundedApprovalCheck(directory,timeoutMs)},cachedApproval=null,cachedPhaseStatus=null;async function boundedApprovalCheck(directory,timeoutMs){try{let ledgerPath3=path293.join(directory,".swarm","plan-ledger.jsonl"),currentSize=-1,currentMtime=-1;try{let stat25=fs168.statSync(ledgerPath3);currentSize=stat25.size,currentMtime=stat25.mtimeMs}catch{}let state2=null,authorityReadFailed=!1;try{state2=_internals236.getPlanLedgerState(directory)}catch{authorityReadFailed=!0}let revision=authorityReadFailed?null:state2?.authorityMode==="sqlite"?`sqlite:${state2.lastSeq}:${state2.lastEventHash??""}:${state2.updatedAt}`:`file:${currentSize}:${currentMtime}`;if(cachedApproval&&cachedApproval.dir===directory&&cachedApproval.revision===revision)return cachedApproval.result;let timer;try{let timeout=new Promise((resolve113)=>{timer=setTimeout(()=>resolve113(!1),timeoutMs)}),result=await Promise.race([_internals236.isPlanCriticApproved(directory),timeout]);if(revision!==null)cachedApproval={dir:directory,revision,result};return result}finally{if(timer!==void 0)clearTimeout(timer)}}catch{return!1}}async function cachedReadPlanPhaseStatus(directory){let planJsonPath=path293.join(directory,".swarm","plan.json"),currentSize=-1,currentMtime=-1;try{let stat25=fs168.statSync(planJsonPath);currentSize=stat25.size,currentMtime=stat25.mtimeMs}catch{}let ledgerRevision;try{let state2=_internals236.getPlanLedgerState(directory);ledgerRevision=state2?`ledger:${state2.lastSeq}:${state2.lastEventHash??""}:${state2.updatedAt}`:"no-ledger"}catch{ledgerRevision=null}if(cachedPhaseStatus&&cachedPhaseStatus.dir===directory&&cachedPhaseStatus.planJsonSize===currentSize&&cachedPhaseStatus.planJsonMtime===currentMtime&&cachedPhaseStatus.ledgerRevision!==null&&cachedPhaseStatus.ledgerRevision===ledgerRevision)return cachedPhaseStatus.result;let result=await _internals236.readPlanPhaseStatus(directory);if(ledgerRevision===null)return result;return cachedPhaseStatus={dir:directory,planJsonSize:currentSize,planJsonMtime:currentMtime,ledgerRevision,result},result}function createIssueTraceHook(_config2,directory,approvalTimeoutMs=5000){return{messagesTransform:async(_input,output)=>{try{let issueRef=_internals236.readIssueReference(directory);if(!issueRef||issueRef.flags.trace!==!0)return;let traceState=_internals236.readTraceState(directory),_specExists=_internals236.specExists(directory),_specIssueNumber=_internals236.readSpecIssueNumber(directory),phaseStatus=await cachedReadPlanPhaseStatus(directory),_planBoundToSpec;if(phaseStatus.planExists){let currentSpecHash=await _internals236.computeSpecHash(directory);_planBoundToSpec=currentSpecHash!==null&¤tSpecHash===phaseStatus.planSpecHash}let _criticApproved=await boundedApprovalCheck(directory,approvalTimeoutMs),_reproReceipt=await _internals236.reproductionReceiptExists(directory,issueRef.number),_reproductionPermitted=issueRef.flags.noRepro===!0||issueRef.noReproWaiver?.waived===!0||_reproReceipt,_publicationObserved=await _internals236.publicationReceiptExists(directory,issueRef.number),_implementationReviewVerified=await _internals236.implementationReviewReceiptExists(directory,issueRef.number),_recurrenceSweepVerified=await _internals236.recurrenceSweepReceiptExists(directory,issueRef.number),_freshnessPermitted=await _internals236.branchFreshnessReceiptExists(directory,issueRef.number),_traceValidationVerified=await _internals236.traceValidationReceiptExists(directory,issueRef.number),_mergeApprovalObserved=await _internals236.mergeApprovalReceiptExists(directory,issueRef.number),result=computeNextMode({issueReference:issueRef,traceState,workflowArtifacts:{specExists:_specExists,specIssueNumber:_specIssueNumber,planExists:phaseStatus.planExists,criticApproved:_criticApproved,allPhasesComplete:phaseStatus.allComplete,reproductionPermitted:_reproductionPermitted,freshnessPermitted:_freshnessPermitted,publicationObserved:_publicationObserved,implementationReviewVerified:_implementationReviewVerified,recurrenceSweepVerified:_recurrenceSweepVerified,traceValidationVerified:_traceValidationVerified,mergeApprovalObserved:_mergeApprovalObserved,planBoundToSpec:_planBoundToSpec}});if(result.nextMode===null&&result.directive===null)return;let finalDirective=result.directive?result.directive.replace("#N",`#${issueRef.number}`):null,out=output;if(!Array.isArray(out.messages))return;let modeDelivered=result.nextMode===null||appendGuidanceCarrier(out.messages,"issue-trace",`[MODE: ${result.nextMode}]`)!==null,directiveDelivered=finalDirective===null||appendGuidanceCarrier(out.messages,"issue-trace",finalDirective)!==null;if(!modeDelivered||!directiveDelivered)return;_internals236.writeTraceState(directory,{issueNumber:traceState.issueNumber,lastTransition:result.nextLastTransition,status:result.nextStatus})}catch(err){_internals236.logError("[issue-trace] hook cycle failed:",err)}}}}init_schema();init_core_events();init_state2();init_logger();init_knowledge_application();init_knowledge_receipt_ledger();init_knowledge_store();init_system_guidance_carrier();import{existsSync as existsSync154}from"node:fs";var HIGH_RISK_TOOLS=new Set(["save_plan","update_task_status","phase_complete","task","Task","skill_regenerate","skill_retire"]),DEFAULT_MAX_GATE_DENIALS=5,DEFAULT_GATE_STALENESS_MS=600000;function selectCurrentArchitectDirectiveMemberships(memberships){let activeArchitect=memberships.filter((membership)=>membership.exposure_kind==="architect_directive"&&!membership.phase_closed_at),latest,latestAt=Number.NEGATIVE_INFINITY;for(let membership of activeArchitect){let committedAt=Date.parse(membership.committed_at),comparableAt=Number.isFinite(committedAt)?committedAt:Number.NEGATIVE_INFINITY;if(!latest||comparableAt>=latestAt)latest=membership,latestAt=comparableAt}if(!latest)return[];return activeArchitect.filter((membership)=>membership.phase===latest.phase&&membership.task_id===latest.task_id)}function selectStaleUnmarkedMemberships(memberships,now2,stalenessMs){return memberships.filter((membership)=>{if(membership.application_marker||hasEffectiveGateRelease(membership))return!1;let committedAt=Date.parse(membership.committed_at);return Number.isFinite(committedAt)&&now2-committedAt>stalenessMs})}function hasEffectiveGateRelease(membership){return membership.gate_release?.membership_event_id===membership.membership_event_id}function groupMembershipsByTrace(memberships){let byTrace=new Map;for(let membership of memberships){let group=byTrace.get(membership.trace_id)??[];group.push(membership),byTrace.set(membership.trace_id,group)}return byTrace}async function loadDirectiveContents(directory,entryIds){let contents=new Map;if(entryIds.length===0)return contents;let want=new Set(entryIds),sources=[resolveSwarmKnowledgePath(directory)];try{let hivePath=resolveHiveKnowledgePath2();if(existsSync154(hivePath))sources.push(hivePath)}catch{}for(let filePath of sources)try{let entries2=await readKnowledge(filePath);for(let entry of entries2)if(want.has(entry.id)&&!contents.has(entry.id)&&typeof entry.lesson==="string")contents.set(entry.id,entry.lesson)}catch{}return contents}function buildGateDenialMessage(toolName,memberships,contents){let pairs=memberships.map((m)=>`${m.trace_id}:${m.entry_id}`),examples=memberships.map((m)=>` KNOWLEDGE_N_A:${m.trace_id}:${m.entry_id} reason=<reason>`),contentLines=memberships.map((m)=>{let lesson=contents.get(m.entry_id);return` [${m.trace_id}:${m.entry_id}] ${lesson??"content not found in knowledge store — see the most recent <swarm_knowledge_directives> block or run knowledge_recall"}`});return[`KNOWLEDGE_ENFORCE_GATE_DENY: ${toolName} blocked — unacknowledged critical knowledge directive(s): ${pairs.join(", ")}.`,"","Acknowledge each directive using its exact, colon-separated tokens (<trace_id>:<entry_id>) with one of these verb markers:"," KNOWLEDGE_APPLIED:<trace_id>:<entry_id>"," KNOWLEDGE_IGNORED:<trace_id>:<entry_id> reason=<short reason>"," KNOWLEDGE_CONTRADICTED:<trace_id>:<entry_id> reason=<observable conflict>"," KNOWLEDGE_N_A:<trace_id>:<entry_id> reason=<short reason>"," KNOWLEDGE_VIOLATED:<trace_id>:<entry_id> reason=<short reason>","KNOWLEDGE_N_A (does not apply; neutral) is a valid, penalty-free acknowledgment when the directive does not pertain to the current step.","","Copy-paste to acknowledge each directive now (replace <reason> with a short reason):",...examples,"","Directive content being acknowledged:",...contentLines].join(`
|
|
7362
7363
|
`)}async function knowledgeApplicationGateBefore(directory,input,config3){if(!config3.enabled)return;let toolName=typeof input.tool==="string"?input.tool:"";if(!(config3.high_risk_tools?new Set(config3.high_risk_tools):HIGH_RISK_TOOLS).has(toolName))return;let agentRaw=typeof input.agent==="string"?input.agent:"";if(!agentRaw)return;if(stripKnownSwarmPrefix(agentRaw)!=="architect")return;let sessionID=typeof input.sessionID==="string"?input.sessionID:void 0;if(!sessionID){if(config3.mode==="enforce")throw Error("KNOWLEDGE_ENFORCE_GATE_DENY: missing sessionID on tool.execute.before; refusing to evaluate critical-directive ack state");writeWarnEvent2(directory,{timestamp:new Date().toISOString(),event:"knowledge_application_gate_warn",tool:toolName,agent:agentRaw,reason:"missing_sessionID",mode:config3.mode}).catch(()=>{});return}let receiptState=await queryLiveMemberships(directory,{session_id:sessionID,include_terminal:!0,include_phase_closed:!1,exposure_kind:"architect_directive"});if(!receiptState.ok){if(config3.mode==="enforce")throw Error(`KNOWLEDGE_ENFORCE_GATE_DENY: receipt authority unavailable (${receiptState.code}); refusing to infer acknowledgment from diagnostics`);writeWarnEvent2(directory,{timestamp:new Date().toISOString(),event:"knowledge_application_gate_warn",tool:toolName,agent:agentRaw,sessionID,reason:receiptState.code});return}let currentMemberships=selectCurrentArchitectDirectiveMemberships(receiptState.memberships),criticalMemberships=currentMemberships.filter((membership)=>membership.critical);if(criticalMemberships.length===0){clearGateDenialCount(sessionID);return}let acknowledgedEntryIds=new Set(currentMemberships.filter((membership)=>membership.application_marker?.source==="architect_marker").map((membership)=>membership.entry_id)),unackedMemberships=criticalMemberships.filter((membership)=>!membership.application_marker&&!hasEffectiveGateRelease(membership)&&!acknowledgedEntryIds.has(membership.entry_id));if(unackedMemberships.length===0){clearGateDenialCount(sessionID);return}if(config3.mode==="enforce"&&config3.critical_requires_ack){let maxDenials=config3.max_gate_denials??DEFAULT_MAX_GATE_DENIALS,stalenessMs=config3.gate_staleness_ms??DEFAULT_GATE_STALENESS_MS,now2=Date.now(),staleMemberships=selectStaleUnmarkedMemberships(unackedMemberships,now2,stalenessMs);if(staleMemberships.length>0){for(let[traceId,memberships]of groupMembershipsByTrace(staleMemberships)){let committed=await commitGateReleaseBatch(directory,{trace_id:traceId,session_id:sessionID,items:memberships.map((membership)=>({entry_id:membership.entry_id,source:"application_gate_staleness_release",reason:"configured staleness escape hatch"}))});if(!committed.ok||committed.rejected.length>0)throw Error("KNOWLEDGE_ENFORCE_GATE_DENY: could not durably record staleness release")}let stalePairs=new Set(staleMemberships.map((membership)=>`${membership.trace_id}/${membership.entry_id}`));unackedMemberships=unackedMemberships.filter((membership)=>!stalePairs.has(`${membership.trace_id}/${membership.entry_id}`));let staleIds=[...new Set(staleMemberships.map((membership)=>membership.entry_id))];if(await writeWarnEvent2(directory,{timestamp:new Date().toISOString(),event:"knowledge_application_gate_staleness_clear",tool:toolName,agent:agentRaw,sessionID,cleared_ids:staleIds,cleared_pairs:[...stalePairs],age_ms:Math.max(...staleMemberships.map((membership)=>now2-Date.parse(membership.committed_at))),staleness_threshold_ms:stalenessMs}).catch((err)=>{warn(`[knowledge-application-gate] staleness-clear audit write failed: ${err instanceof Error?err.message:String(err)}`)}),unackedMemberships.length===0){clearCriticalShownIds(sessionID);return}}let unacked2=[...new Set(unackedMemberships.map((membership)=>membership.entry_id))],directiveKey=buildGateDenialDirectiveKey(unacked2),denials=incrementGateDenialCount(sessionID,directiveKey);if(denials>maxDenials){for(let[traceId,memberships]of groupMembershipsByTrace(unackedMemberships)){let committed=await commitGateReleaseBatch(directory,{trace_id:traceId,session_id:sessionID,items:memberships.map((membership)=>({entry_id:membership.entry_id,source:"application_gate_denial_limit_release",reason:"configured denial-count escape hatch"}))});if(!committed.ok||committed.rejected.length>0)throw Error("KNOWLEDGE_ENFORCE_GATE_DENY: could not durably record denial-limit release")}clearCriticalShownIds(sessionID),clearGateDenialCount(sessionID),await writeWarnEvent2(directory,{timestamp:new Date().toISOString(),event:"knowledge_application_gate_denial_limit_clear",tool:toolName,agent:agentRaw,sessionID,cleared_ids:unacked2,denial_count:denials,max_gate_denials:maxDenials}).catch((err)=>{warn(`[knowledge-application-gate] denial-limit-clear audit write failed: ${err instanceof Error?err.message:String(err)}`)});return}let contents=await loadDirectiveContents(directory,unacked2);throw Error(buildGateDenialMessage(toolName,unackedMemberships,contents))}let unacked=[...new Set(unackedMemberships.map((membership)=>membership.entry_id))],unackedPairs=unackedMemberships.map((membership)=>`${membership.trace_id}/${membership.entry_id}`);writeWarnEvent2(directory,{timestamp:new Date().toISOString(),event:"knowledge_application_gate_warn",tool:toolName,agent:agentRaw,sessionID,unacknowledged_critical_ids:unacked,unacknowledged_critical_pairs:unackedPairs}).catch(()=>{})}async function writeWarnEvent2(directory,record3){appendCoreEventSync(directory,record3)}async function knowledgeApplicationTransformScan(directory,output,sessionID){if(!output?.messages)return;if(!sessionID)return;let target;for(let i=output.messages.length-1;i>=0;i--){let m=output.messages[i];if(isGuidanceCarrier(m))continue;let agent=m.info?.agent;if(typeof agent==="string"&&stripKnownSwarmPrefix(agent)==="architect"){target=m;break}}if(!target)return;let text=(target.parts??[]).map((p)=>typeof p.text==="string"?p.text:"").join(`
|
|
7363
7364
|
`);if(!text)return;let acks=parseAcknowledgments(text);if(acks.length===0)return;let ctx={sessionId:sessionID},live=await queryLiveMemberships(directory,{session_id:sessionID,include_terminal:!0,include_phase_closed:!1,exposure_kind:"architect_directive"});if(!live.ok){warn(`[knowledge-application-gate] receipt authority unavailable: ${live.code}`);return}for(let ack of acks){if(!ack.trace_id)continue;let key2=buildAckDedupKey(sessionID,JSON.stringify([ack.trace_id,ack.id]),ack.result);if(swarmState.knowledgeAckDedup.has(key2))continue;let memberships=live.memberships.filter((membership)=>membership.trace_id===ack.trace_id&&membership.entry_id===ack.id&&!membership.application_marker&&!hasEffectiveGateRelease(membership));if(memberships.length===0)continue;let byTrace=new Map;for(let membership of memberships){let group=byTrace.get(membership.trace_id)??[];group.push(membership),byTrace.set(membership.trace_id,group)}let committedAll=!0,newlyCommitted=!1;for(let[traceId,group]of byTrace){let committed=await commitApplicationOutcomeBatch(directory,{trace_id:traceId,session_id:sessionID,items:group.map((membership)=>({entry_id:membership.entry_id,outcome:ack.result,source:"architect_marker",reason:ack.reason}))});if(!committed.ok||committed.rejected.length>0){committedAll=!1;break}if(committed.committed.length>0)newlyCommitted=!0}if(!committedAll)continue;if(addKnowledgeAckDedup(key2),!newlyCommitted)continue;try{await recordAcknowledgment(directory,ack,ctx)}catch(err){warn(`[knowledge-application-gate] transform-scan record failed: ${err instanceof Error?err.message:String(err)}`)}}}init_knowledge_curator();init_knowledge_injector();init_micro_reflector();init_agent_names();init_schema();init_state2();var NON_ARCHITECT_ADVISORY_KEY="[non-architect-advisory]",HOST_INTERNAL_AGENTS=new Set(["compaction","title","summary"]),SWARM_SUBAGENT_ROLES=new Set(ALL_SUBAGENT_NAMES);function maybeEmitNonArchitectAdvisory(sessionID,agentName){if(!sessionID||!agentName.trim())return!1;let role=stripKnownSwarmPrefix(agentName);if(role==="architect")return!1;if(HOST_INTERNAL_AGENTS.has(role))return!1;if(SWARM_SUBAGENT_ROLES.has(role))return!1;let session=swarmState.agentSessions.get(sessionID)??ensureAgentSession(sessionID);if(!session||session.nonArchitectAdvisoryDone)return!1;let enqueued=pushAdvisory(session,`[swarm] This session is running on "${agentName}", not a swarm architect. The gated pipeline (plan approval, delegation gates, scoped writes) is only active on architect sessions. Switch to an architect agent or set auto_select_architect in opencode-swarm.json. ${NON_ARCHITECT_ADVISORY_KEY}`,{dedupeKey:NON_ARCHITECT_ADVISORY_KEY});if(enqueued)session.nonArchitectAdvisoryDone=!0;return enqueued}init_normalize_tool_name();init_plan_task_id_context();init_pr_subscriptions();init_utils();init_stored_input_args();init_normalize_tool_name();var MAX_OUTPUT_SCAN_BYTES=65536,PR_URL_PATTERN=/https:\/\/github\.com\/([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)\/pull\/(\d+)/,_internals237={subscribe,log};function extractPrUrl(text){let match=PR_URL_PATTERN.exec(text.slice(0,MAX_OUTPUT_SCAN_BYTES));if(!match)return null;let owner=match[1],repo=match[2],prNumber=Number.parseInt(match[3],10);if(!Number.isSafeInteger(prNumber)||prNumber<=0)return null;return{repoFullName:`${owner}/${repo}`,prNumber,prUrl:`https://github.com/${owner}/${repo}/pull/${prNumber}`}}function createPrAutoSubscribeHook(directory,config3){return{toolAfter:async(input,output)=>{try{if(!config3.enabled||!config3.auto_subscribe_on_pr_create)return;let sessionID=typeof input.sessionID==="string"?input.sessionID.trim():"";if(!sessionID)return;let tool3=normalizeToolNameLowerCase(input.tool??"");if(tool3!=="bash"&&tool3!=="shell")return;let args2=(typeof input.callID==="string"?getStoredInputArgs(input.callID):void 0)??input.args??output.args;if(!(typeof args2?.command==="string"?args2.command:"").includes("gh pr create"))return;let outputText2=typeof output.output==="string"?output.output:"";if(!outputText2)return;let prInfo=extractPrUrl(outputText2);if(!prInfo)return;await _internals237.subscribe(directory,{sessionID,prNumber:prInfo.prNumber,repoFullName:prInfo.repoFullName,prUrl:prInfo.prUrl,maxSubscriptions:config3.max_subscriptions}),_internals237.log("[pr-monitor] Auto-subscribed session to created PR",{sessionID,pr:`${prInfo.repoFullName}#${prInfo.prNumber}`})}catch(err){_internals237.log("[pr-monitor] Auto-subscribe failed (non-fatal)",{error:err instanceof Error?err.message:String(err)})}}}}init_pr_workflow_gate();init_pending_delegations();init_pr_feedback_event_queue();init_core_events();init_utils();init_pr_workflow_auto_wake();init_pr_workflow_gate();import{createHash as createHash99}from"node:crypto";var DEFAULT_WAKE_TIMEOUT_MS=5000,DEFAULT_BOUNDARY_QUIET_MS=120000,DEFAULT_BOUNDARY_WATCHDOG_MS=5000,DEFAULT_STATUS_PROBE_TIMEOUT_MS=250,MAX_TRACKED_BOUNDARY_TOOL_PARTS=200,_internals238={readPrWorkflowGateState,claimPrFeedbackMonitorEvents,readPrFeedbackMonitorQueue,observePrWorkflowAutoWakeEvent,scanDelegationsForRecovery},DEFAULT_MAX_CONSECUTIVE_UNPRODUCTIVE_WAKES=5,DEFAULT_WAKE_COOLDOWN_MS=30000,DEFAULT_BANNER_COOLDOWN_MS=20000,MAX_FALLBACK_BANNER_INJECTIONS_PER_SESSION=20,BANNER_PREFIX_PATTERN=/^--- \[(?:PR_REVIEW|PR_FEEDBACK) WORKFLOW ACTIVE/,DEFAULT_TOTAL_WAKE_CEILINGS={S:12,M:54,L:102},MAX_TRACKED_WAKE_SESSIONS=200;function activeWorkflowLaneKeys(state2){let keys=new Set;for(let batch of state2.prReviewBaseDispatches??[])for(let lane of batch.lanes)keys.add(`${batch.batchId}\x00${lane.laneId}`);for(let batch of state2.prReviewValidationBatches??[])for(let lane of batch.lanes)keys.add(`${batch.batchId}\x00${lane.laneId}`);for(let batch of state2.prFeedbackVerifications??[])for(let lane of batch.ownership)keys.add(`${batch.batchId}\x00${lane.laneId}`);for(let batch of state2.prFeedbackGateBatches??[])keys.add(`${batch.batchId}\x00${batch.laneId}`);return keys}function workflowProgressSnapshot(directory,sessionID,state2){let scan;try{scan=_internals238.scanDelegationsForRecovery(directory)}catch{return{kind:"uncertain"}}if(scan.status!=="ok")return{kind:"uncertain"};let activeKeys=activeWorkflowLaneKeys(state2),activatedAt=Date.parse(state2.activatedAt),modePrefix=state2.mode==="PR_REVIEW"?"swarm-pr-review:":"swarm-pr-feedback:",tuples=scan.owners.filter((record3)=>{if(record3.parentSessionId!==sessionID||!record3.mode?.startsWith(modePrefix)||!record3.batchId||!record3.laneId||!activeKeys.has(`${record3.batchId}\x00${record3.laneId}`)||Number.isFinite(activatedAt)&&record3.createdAt<activatedAt)return!1;return!state2.prHeadSha||record3.workspace?.prHeadSha===state2.prHeadSha}).map((record3)=>{let result=record3.result??record3.terminalResult?.result;return[record3.correlationId,record3.batchId,record3.laneId,record3.status,record3.terminalResult?.eventId??"",result?.digest??"",result?.outputRef??"",result?.prReviewResultReceipt?.semanticEnvelopeDigest??""].join("\x00")}).sort((left,right)=>left.localeCompare(right)),workflowIdentity2=state2.workflowInstanceId??`${state2.mode}\x00${state2.activatedAt}`;return{kind:"valid",token:createHash99("sha256").update(`${workflowIdentity2}\x00${state2.revision}\x00${tuples.join(`
|
|
7364
7365
|
`)}`).digest("hex")}}function observeWorkflowProgress(budget,snapshot){if(snapshot.kind==="uncertain")return budget.progressUncertain=!0,!1;if(budget.progressUncertain)return budget.progressUncertain=!1,budget.lastSeenProgressToken=snapshot.token,!1;let madeProgress=budget.lastSeenProgressToken===void 0||budget.lastSeenProgressToken!==snapshot.token;return budget.lastSeenProgressToken=snapshot.token,madeProgress}function isValidTotalWakeCeiling(value){return value!==void 0&&Number.isInteger(value)&&value>0}function asRecord3(value){return typeof value==="object"&&value!==null?value:void 0}function asArray(value){return Array.isArray(value)?value:[]}function eventEnvelope2(event){return asRecord3(event.properties)??asRecord3(event.data)??{}}function envelopeSessionID(envelope){let info=asRecord3(envelope.info),candidate2=envelope.sessionID??envelope.sessionId??info?.sessionID??info?.sessionId??info?.id;return typeof candidate2==="string"&&candidate2.trim()!==""?candidate2.trim():void 0}function normalizeSessionReadiness(value){if(value==="idle"||value==="busy"||value==="retry")return value;let nested=asRecord3(value)?.type;return nested==="idle"||nested==="busy"||nested==="retry"?nested:"unknown"}function extractToolPartID(part){let state2=asRecord3(part.state),candidate2=part.id??part.partID??part.callID??state2?.id??state2?.partID??state2?.callID;return typeof candidate2==="string"&&candidate2.trim()!==""?candidate2.trim():void 0}function isInFlightToolStatus(value){return value==="pending"||value==="running"}function isTerminalToolStatus(value){return value==="completed"||value==="error"||value==="cancelled"||value==="aborted"}function canonicalGitHubPrUrl4(value){try{let url3=new URL(value),match=url3.pathname.match(/^\/([^/]+)\/([^/]+)\/pull\/(\d+)\/?$/);if(url3.protocol!=="https:"||url3.hostname.toLowerCase()!=="github.com"||!match)return null;let number7=Number(match[3]);if(!Number.isSafeInteger(number7)||number7<=0)return null;return`github.com/${match[1].toLowerCase()}/${match[2].toLowerCase()}/pull/${number7}`}catch{return null}}function sameGitHubPr2(left,right){let leftCanonical=canonicalGitHubPrUrl4(left);return leftCanonical!==null&&leftCanonical===canonicalGitHubPrUrl4(right)}function formatQueuedMonitorEventsText(events){if(events.length===0)return"";return["Queued PR monitor events are now authorized for this PR_FEEDBACK workflow and must be treated as feedback inputs for the current round:",...events.map((event)=>`- ${event.type} on ${event.repoFullName}#${event.prNumber}: ${event.message.split(`
|
|
@@ -7526,9 +7527,15 @@ ${hint}`}]}return{file:targetPath,status:"error",hunks:hunksTotal,hunksApplied:0
|
|
|
7526
7527
|
`?resultContent.replace(/\n/g,`\r
|
|
7527
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(`
|
|
7528
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(`
|
|
7529
|
-
`)[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(`
|
|
7530
7531
|
`);if(lines.length>maxLines)return lines.slice(-maxLines).join(`
|
|
7531
|
-
`);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}
|
|
7532
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)}
|
|
7533
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(`
|
|
7534
7541
|
`))throw new CouncilRoundStateUncertainError("council attempt audit has a partial tail");if(offset>0){let firstNewline=text.indexOf(`
|
|
@@ -7548,7 +7555,7 @@ ${body}`)}function renderAdvisoryBody(result){return result.synthesis.trim()}var
|
|
|
7548
7555
|
`):"_No persisting disagreements after deliberation._",sourcesBlock=allSources.length>0?allSources.map((s)=>`- [${s.title||s.url}](${s.url})`).join(`
|
|
7549
7556
|
`):"_No sources cited._";return["## General Council Synthesis","",`**Question:** ${question}`,`**Mode:** ${mode}`,`**Members:**
|
|
7550
7557
|
${memberLines}`,`**Rounds:** ${roundsCompleted}`,"","### Consensus",consensusBlock,"","### Persistent Disagreements",disagreementsBlock,"","### Sources",sourcesBlock].join(`
|
|
7551
|
-
`)}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(`
|
|
7552
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(`
|
|
7553
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(`
|
|
7554
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=`
|
|
@@ -7712,10 +7719,10 @@ Regenerated on: save_plan and phase_complete.
|
|
|
7712
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?`
|
|
7713
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?`
|
|
7714
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?`
|
|
7715
|
-
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(`
|
|
7716
|
-
`).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(`
|
|
7717
|
-
`).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(`
|
|
7718
|
-
`);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(`
|
|
7719
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(/^\*\//,"")}
|
|
7720
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(`
|
|
7721
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(`
|
|
@@ -7723,7 +7730,7 @@ ${jsdocContent}`;else if(line.includes("*/"))break;else if(functionKeywords.test
|
|
|
7723
7730
|
`)){let trimmed=line.trim();if(!trimmed)continue;let[name,rest]=trimmed.split(/\s+/,2);if(!name||!rest||byName.has(name))continue;let url3=rest.replace(/\s+\((?:fetch|push)\)\s*$/i,"");byName.set(boundUntrusted(name,64),boundUntrusted(url3,MAX_REMOTE_URL_LEN))}let entries2=[...byName.entries()],remotes=entries2.slice(0,MAX_REMOTES).map(([name,url3])=>({name,url:url3}));return{remotes,remotesTruncated:entries2.length>remotes.length}}async function countCheckoutReceiptFiles(directory,sessionID){try{let receiptDirectory=validateSwarmPath(directory,path343.join(RECEIPT_DIR2,prWorkflowSessionFileStem(sessionID)));return(await fsp12.readdir(receiptDirectory,{withFileTypes:!0})).filter((entry)=>entry.isFile()&&/^[0-9a-f]{40,64}\.json$/i.test(entry.name)).length}catch(error93){if(error93.code==="ENOENT")return 0;return null}}function describeDelegationRead(directory){try{let outcome=_internals284.readDelegationsDetailed(directory);if(outcome.status==="ok")return{state:"ok"};return{state:"uncertain",reasonCode:boundUntrusted(outcome.reason,MAX_RECOVERY_REASON_CODE_LEN)}}catch{return{state:"uncertain",reasonCode:"reader-threw"}}}function describeRecoveryNextStep(delegationReadState){if(delegationReadState==="uncertain")return"Delegation store read is uncertain: repair the store, then re-run pr_workflow_status; if abandoning the workflow, abort via abort_pr_workflow.";return"Re-run pr_workflow_status after any store repair; if abandoning the workflow, abort via abort_pr_workflow."}function describeNextStep(gate,git2,checkout){if(checkout.kind==="recovery-required"||checkout.kind==="indeterminate")return`Manual Git recovery required. code=${checkout.code} retryable=false required_action=${checkout.requiredAction}`;if(!gate.active){if(gate.reason==="delegation-chain-uncertain")return"PR workflow gate ownership could not be resolved from this session delegation chain (cycle, depth limit, or missing ancestor). Treat the workflow state as unknown and use read-only recovery inspection; do not perform PR-workflow writes.";return"No active PR workflow gate for this session. Activate with `/swarm pr-review <pr-ref>` or `/swarm pr-feedback <pr-ref>` before PR-workflow tool calls are admitted."}if(!gate.prHeadBound)return gate.mode==="PR_FEEDBACK"?"PR_FEEDBACK gate active; PR head not yet bound. If the working tree is dirty, preserve it with prepare_pr_workflow_checkout (omit paths to include tracked and untracked changes). Prefer the intended exact tracking checkout, then bind; if this workflow inherited an already-detached exact intake head, bind it directly and the controller will attach the unique exact local/remote tracking ref. Ambiguity or an existing mismatched upstream fails closed.":"PR_REVIEW gate active; PR head not yet bound. If the working tree is dirty, preserve it with prepare_pr_workflow_checkout (omit paths to include tracked and untracked changes), then bind the exact detached PR head.";if(git2.isClean===!1)return`${gate.mode} gate active and head bound, but the working tree is dirty. Read-only observation only; the gate keeps writes and non-tracking fetches fail-closed.`;if(git2.isClean===null)return`${gate.mode} gate active and head bound, but this session could not determine whether the working tree is clean (git status failed). Treat the tree state as unknown and verify manually before assuming it is clean; read-only observation only.`;return`${gate.mode} gate active and head bound. Continue read-only review using the admitted observe/validate tools (diff, gh_evidence, repo_map, lint check, etc.).`}function summarizeGate(state2,receiptFiles,salvage){if(!state2)return{active:!1,reason:"no-active-gate"};return{active:!0,...salvage?.salvaged?{stateSalvaged:!0,stateSalvageDisclosure:salvage.disclosure}:{},mode:state2.mode,prHeadBound:Boolean(state2.prHeadSha),prHeadSha:state2.prHeadSha??null,prFeedbackTargetUrl:state2.prFeedbackTargetUrl?boundUntrusted(state2.prFeedbackTargetUrl,MAX_FIELD_LEN):null,prReviewBaseRef:state2.prReviewBaseRef?boundUntrusted(state2.prReviewBaseRef,MAX_FIELD_LEN):null,prReviewBaseSha:state2.prReviewBaseSha??null,prReviewDepthTier:state2.prReviewDepthTier??null,baseDispatchBatches:state2.prReviewBaseDispatches?.length??0,validationBatches:state2.prReviewValidationBatches?.length??0,feedbackVerificationBatches:state2.prFeedbackVerifications?.length??0,...state2.prFeedbackInventoryAmendments?.length?{inventoryAmendments:state2.prFeedbackInventoryAmendments}:{},checkoutReceiptFiles:receiptFiles,activatedAt:state2.activatedAt,updatedAt:state2.updatedAt,revision:state2.revision}}async function resolveWorkflowGate(directory,sessionID){let outcome=await _internals284.resolvePrWorkflowControllerSession({directory,sessionID,readGate:(candidate2)=>_internals284.readPrWorkflowGateStateForRecovery(directory,candidate2)});if(outcome.kind==="gate-owner")return{sessionID:outcome.sessionID,recovery:outcome.gate};if(outcome.kind==="no-gate")return{sessionID:outcome.sessionID,recovery:null};return{sessionID:null,recovery:null}}async function resolveWorkflowGateSession(directory,sessionID){return(await resolveWorkflowGate(directory,sessionID)).sessionID}async function executePrWorkflowStatus(directory,rawSessionID){let sessionID=rawSessionID?.trim()?rawSessionID.trim():null,resolvedGate=sessionID?await resolveWorkflowGate(directory,sessionID):null,gateSessionID=resolvedGate?.sessionID??null,[head2,isClean,branchInfo,porcelain,remoteOutput,liveCheckout]=await Promise.all([_internals284.resolveCurrentGitHeadAsync(directory),_internals284.resolveIsWorkingTreeCleanAsync(directory),resolveBranch(directory),_internals284.runGitCapture(directory,["status","--porcelain=v1","--untracked-files=all"]),_internals284.runGitCapture(directory,["remote","-v"]),_internals284.classifyGitState(directory)]),dirty=parseDirtyFiles(porcelain),{remotes,remotesTruncated}=parseRemotes(remoteOutput),git2={head:head2,branch:branchInfo.branch,detached:branchInfo.detached,isClean,dirtyFileCount:dirty.dirtyFileCount,dirtyFiles:dirty.dirtyFiles,dirtyFilesTruncated:dirty.dirtyFilesTruncated,remotes,remotesTruncated},gate,activeState=null;if(!gateSessionID)gate={active:!1,reason:sessionID?"delegation-chain-uncertain":"no-session-context"};else{let recovery2=resolvedGate?.recovery??null;activeState=recovery2?.state??null;let receiptFiles=activeState?await countCheckoutReceiptFiles(directory,gateSessionID):null;gate=summarizeGate(activeState,receiptFiles,recovery2?{salvaged:recovery2.salvaged,disclosure:recovery2.disclosure}:void 0)}let recovery=activeState?.checkoutRecovery,checkout=recovery?{kind:recovery.code==="GIT_STATE_INDETERMINATE"?"indeterminate":"recovery-required",code:recovery.code,retryable:!1,requiredAction:recovery.requiredAction,evidence:recovery.evidence}:liveCheckout,delegationRead=describeDelegationRead(directory),recoverySection={controllerSessionID:gateSessionID,delegationRead,lastProgress:activeState?{revision:activeState.revision,updatedAt:activeState.updatedAt}:null,wakeSuspension:{suspended:sessionID?_internals284.isPrWorkflowAutoWakeSuppressed(directory,sessionID):!1},actionCircuits:{state:"unavailable"},nextStep:describeRecoveryNextStep(delegationRead.state)},result={success:!0,sessionID,git:git2,checkout,gate,publication:activeState?describePrWorkflowPublicationSection(activeState):null,nextStep:describeNextStep(gate,git2,checkout),recovery:recoverySection};return JSON.stringify(result,null,2)}var pr_workflow_status=createSwarmTool({description:"Read-only architect observation of local git state (HEAD, branch, clean/dirty with a bounded changed-file list, remotes) plus a session-pinned PR workflow gate summary (mode, bound PR head, base ref/sha, depth tier, dispatch/validation batch counts). Use to observe state under the fail-closed PR_REVIEW/PR_FEEDBACK gate. Never executes PR-controlled scripts and never reads another session gate.",args:{},execute:async(_args,directory,ctx)=>executePrWorkflowStatus(directory,ctx?.sessionID)}),_internals284={readPrWorkflowGateStateForRecovery,readDelegationsDetailed,isPrWorkflowAutoWakeSuppressed,resolvePrWorkflowControllerSession,resolveCurrentGitHeadAsync,resolveIsWorkingTreeCleanAsync,runGitCapture:runGitCapture2,classifyGitState:classifyPrWorkflowGitState,truncateToByteBudget,resolveWorkflowGateSession};init_p_limit();init_zod();init_config();init_manager2();init_utils();init_external_tool_runner();init_filesystem_identity();init_git_executable();init_project_boundary();init_create_tool();init_lint();import*as path344 from"node:path";init_quality_budget();init_sast_scan();init_secretscan();var TOOL_TIMEOUT_MS=60000,MAX_COMBINED_BYTES=500000,MAX_COMPACT_ERROR_BYTES=4096,CANCELLATION_SETTLEMENT_GRACE_MS=1000,MAX_CONCURRENT=4,MAX_FILES=100,GIT_TIMEOUT_MS12=1e4,GIT_MAX_OUTPUT_BYTES2=2000000,ALL_LINES_CHANGED=-1,MAX_CHANGED_LINE_ENTRIES=200000,_internals285={qualityBudget,runLintWrapped,runSecretscanWrapped,runSastScanWrapped,runQualityBudgetWrapped,runWithTimeout:runWithTimeout2,getChangedLineRanges,saveEvidence,runExternalTool,detectResolvedLinter,runLintOnFiles,platform:()=>process.platform,serializePreCheckResult,resolveGatePreamble,runPreCheckBatch,loadGateOverrides,MAX_COMBINED_BYTES};function formatIncompletePaths(incompletePaths,maxEntries=3){let visible=incompletePaths.slice(0,maxEntries).map((entry)=>{return`${entry.path} (${entry.reason})`}),suffix=incompletePaths.length>maxEntries?` (+${incompletePaths.length-maxEntries} more)`:"";return`${visible.join("; ")}${suffix}`}function evaluateSecretscanGate(toolResult,requestedFiles){if(toolResult.error)return{passed:!1,summary:`Secretscan wrapper error: ${toolResult.error}`,findingsCount:0};if(!toolResult.ran||!toolResult.result)return{passed:!1,summary:"Secretscan did not return a result",findingsCount:0};if("error"in toolResult.result)return{passed:!1,summary:`Secretscan error: ${toolResult.result.error}`,findingsCount:0};let result=toolResult.result;if(typeof result.incomplete_files!=="number"||!Array.isArray(result.incomplete_paths))return{passed:!1,summary:"Secretscan failed: scanner returned incomplete coverage metadata",result,findingsCount:Math.max(result.count,result.findings.length)};let findingsCount=Math.max(result.count,result.findings.length),failures=[];if(findingsCount>0)failures.push(`${findingsCount} secret finding(s)`);if(result.incomplete_files>0||result.incomplete_paths.length>0){let incompletePaths=result.incomplete_paths.length>0?`; incomplete paths: ${formatIncompletePaths(result.incomplete_paths)}`:"";failures.push(`${result.incomplete_files} incomplete file(s)${incompletePaths}`)}if(result.count!==result.findings.length)failures.push(`findings/count mismatch (reported ${result.count}, actual ${result.findings.length})`);if(requestedFiles>0&&result.files_scanned===0)failures.push("zero requested files scanned");let statistics=`Secretscan: ${findingsCount} finding(s), ${result.files_scanned} files scanned, ${result.skipped_files} skipped`;return{passed:failures.length===0,summary:failures.length>0?`${statistics}; failed: ${failures.join("; ")}`:statistics,result,findingsCount}}function truncateUtf8(value,maxBytes){if(Buffer.byteLength(value,"utf8")<=maxBytes)return value;let marker="... (truncated)",budget=Math.max(0,maxBytes-Buffer.byteLength(marker,"utf8")),result="",usedBytes=0;for(let character of value){let characterBytes=Buffer.byteLength(character,"utf8");if(usedBytes+characterBytes>budget)break;result+=character,usedBytes+=characterBytes}return`${result}${marker}`}function compactToolResult(toolResult){return{ran:toolResult.ran,duration_ms:toolResult.duration_ms,...toolResult.error!==void 0&&{error:truncateUtf8(toolResult.error,MAX_COMPACT_ERROR_BYTES)},...toolResult.error===void 0&&toolResult.result!==void 0&&{result_omitted:!0}}}function serializePreCheckResult(result){let serialized3=JSON.stringify(result,null,2);if(Buffer.byteLength(serialized3,"utf8")<=MAX_COMBINED_BYTES)return serialized3;let compact={batch_status:result.batch_status,gates_passed:result.gates_passed,...result.sast_degraded!==void 0&&{sast_degraded:result.sast_degraded},...result.sast_skipped!==void 0&&{sast_skipped:result.sast_skipped},lint:compactToolResult(result.lint),secretscan:compactToolResult(result.secretscan),sast_scan:compactToolResult(result.sast_scan),quality_budget:compactToolResult(result.quality_budget),total_duration_ms:result.total_duration_ms,output_truncated:!0};return JSON.stringify(compact,null,2)}function isWindowsAbsolutePath(inputPath){return/^[A-Za-z]:[/\\]/.test(inputPath)}function validatePath(inputPath,baseDir,workspaceDir){if(typeof inputPath!=="string")return"path must be a string";if(!inputPath||inputPath.trim().length===0)return"path is required";let resolved,isWinAbs=isWindowsAbsolutePath(inputPath);if(isWinAbs)resolved=path344.win32.resolve(inputPath);else if(path344.isAbsolute(inputPath))resolved=path344.resolve(inputPath);else resolved=path344.resolve(baseDir,inputPath);let workspaceResolved=isWindowsAbsolutePath(workspaceDir)?path344.win32.resolve(workspaceDir):path344.resolve(workspaceDir),relative87;if(isWinAbs)relative87=path344.win32.relative(workspaceResolved,resolved);else relative87=path344.relative(workspaceResolved,resolved);if(relative87.startsWith(".."))return"path traversal detected";return null}function isAcceptedProjectRootForPlatform(dir,workspaceDir,platform,hasExplicitBoundary,exactPhysicalRoot=!1){if(exactPhysicalRoot)return!0;let pathApi=platform==="win32"?path344.win32:path344,directoryKey=pathApi.resolve(dir).replace(/\\/g,"/"),workspaceKey=pathApi.resolve(workspaceDir).replace(/\\/g,"/"),normalizedDirectoryKey=platform==="win32"?directoryKey.toLowerCase():directoryKey,normalizedWorkspaceKey=platform==="win32"?workspaceKey.toLowerCase():workspaceKey;if(normalizedDirectoryKey===normalizedWorkspaceKey)return!0;let relative87=pathApi.relative(workspaceDir,dir);return relative87!==""&&relative87!==".."&&!relative87.startsWith(`..${pathApi.sep}`)&&!pathApi.isAbsolute(relative87)&&hasExplicitBoundary}function validateDirectory2(dir,workspaceDir){if(!dir||dir.length===0)return"directory is required";if(dir.length>500)return"directory path too long";let exactPhysicalRoot=sameExistingFilesystemPath(dir,workspaceDir);if(!exactPhysicalRoot){let traversalCheck=validatePath(dir,workspaceDir,workspaceDir);if(traversalCheck)return traversalCheck}let platform=_internals285.platform();if(!isAcceptedProjectRootForPlatform(dir,workspaceDir,platform,hasExplicitProjectBoundary(dir),exactPhysicalRoot))return"directory must resolve to the project root";return null}async function runWithTimeout2(operation,timeoutMs,parentSignal,waitForCancellationSettlement=!1){let controller=new AbortController,timeoutHandle,parentAbortListener;if(parentSignal?.aborted)throw Error("Tool execution cancelled");let parentAbortPromise=new Promise((_,reject2)=>{if(!parentSignal)return;if(parentAbortListener=()=>{reject2(Error("Tool execution cancelled")),controller.abort()},parentSignal.addEventListener("abort",parentAbortListener,{once:!0}),parentSignal.aborted)parentAbortListener()});if(controller.signal.aborted)return await parentAbortPromise;let operationPromise=operation(controller.signal);try{let timeoutPromise=new Promise((_,reject2)=>{timeoutHandle=setTimeout(()=>{reject2(Error(`Timeout after ${timeoutMs}ms`)),controller.abort()},timeoutMs)});return await Promise.race([operationPromise,timeoutPromise,parentAbortPromise])}catch(error93){if(controller.signal.aborted&&waitForCancellationSettlement){let settlementTimer;try{await Promise.race([operationPromise.then(()=>{return},()=>{return}),new Promise((resolve137)=>{settlementTimer=setTimeout(resolve137,CANCELLATION_SETTLEMENT_GRACE_MS)})])}finally{if(settlementTimer!==void 0)clearTimeout(settlementTimer)}}throw error93}finally{if(timeoutHandle!==void 0)clearTimeout(timeoutHandle);if(parentAbortListener&&parentSignal)parentSignal.removeEventListener("abort",parentAbortListener)}}async function runLintWrapped(files,directory,_gates,abortSignal){let start=process.hrtime.bigint();try{let resolvedLinter=await _internals285.detectResolvedLinter(directory,abortSignal);if(!resolvedLinter)return{ran:!1,error:"No linter found (biome or eslint)",duration_ms:Number(process.hrtime.bigint()-start)/1e6};if(files&&files.length>0)return{ran:!0,result:await _internals285.runLintOnFiles(resolvedLinter,files,directory,abortSignal),duration_ms:Number(process.hrtime.bigint()-start)/1e6};return{ran:!0,result:await _internals182.runResolvedLint(resolvedLinter,"check",directory,abortSignal),duration_ms:Number(process.hrtime.bigint()-start)/1e6}}catch(error93){return{ran:!0,error:error93 instanceof Error?error93.message:"Unknown error",duration_ms:Number(process.hrtime.bigint()-start)/1e6}}}async function runLintOnFiles(resolvedLinter,files,workspaceDir,abortSignal){if(resolvedLinter.source==="legacy-test-probe")return _internals182.runResolvedLint(resolvedLinter,"check",workspaceDir,abortSignal);let validatedFiles=[];for(let file3 of files){if(typeof file3!=="string")continue;let resolvedPath=path344.resolve(file3);if(validatePath(resolvedPath,workspaceDir,workspaceDir))continue;validatedFiles.push(resolvedPath)}if(validatedFiles.length===0)return{success:!1,mode:"check",linter:resolvedLinter.linter,command:[],error:"No valid files after security validation"};let args2;if(resolvedLinter.linter==="biome")args2=[...resolvedLinter.argsPrefix,"check",...validatedFiles];else args2=[...resolvedLinter.argsPrefix,...validatedFiles];let command=[...resolvedLinter.displayPrefix,...args2];try{let execution=await _internals285.runExternalTool({executable:resolvedLinter.executable,args:args2,cwd:workspaceDir,timeoutMs:TOOL_TIMEOUT_MS,maxStdoutBytes:512000,maxStderrBytes:512000,abortSignal});if(execution.status!=="completed")return{success:!1,mode:"check",linter:resolvedLinter.linter,command,error:execution.message??`Execution ${execution.status}`};let exitCode=execution.exitCode??1,output=execution.stdout;if(execution.stderr)output+=(output?`
|
|
7724
7731
|
`:"")+execution.stderr;if(execution.stdoutTruncated||execution.stderrTruncated)output+=`
|
|
7725
7732
|
... (output truncated)`;let result={success:!0,mode:"check",linter:resolvedLinter.linter,command,exitCode,output};if(exitCode===0)result.message=`${resolvedLinter.linter} check completed successfully with no issues`;else result.message=`${resolvedLinter.linter} check found issues (exit code ${exitCode}).`;return result}catch(error93){return{success:!1,mode:"check",linter:resolvedLinter.linter,command,error:error93 instanceof Error?`Execution failed: ${error93.message}`:"Execution failed: unknown error"}}}async function runSecretscanWrapped(files,directory,_gates,abortSignal){let start=process.hrtime.bigint();try{if(files&&files.length>0)return{ran:!0,result:await runWithTimeout2(()=>runSecretscanOnFiles(files,directory),TOOL_TIMEOUT_MS,abortSignal),duration_ms:Number(process.hrtime.bigint()-start)/1e6};return{ran:!0,result:await runWithTimeout2(()=>runSecretscan(directory),TOOL_TIMEOUT_MS,abortSignal,!0),duration_ms:Number(process.hrtime.bigint()-start)/1e6}}catch(error93){return{ran:!0,error:error93 instanceof Error?error93.message:"Unknown error",duration_ms:Number(process.hrtime.bigint()-start)/1e6}}}async function runSastScanWrapped(changedFiles,directory,severityThreshold,gates,phase,abortSignal){let start=process.hrtime.bigint();try{return{ran:!0,result:await runWithTimeout2((signal2)=>sastScan({changed_files:changedFiles,severity_threshold:severityThreshold,phase,abort_signal:signal2},directory,gates),TOOL_TIMEOUT_MS,abortSignal,!0),duration_ms:Number(process.hrtime.bigint()-start)/1e6}}catch(error93){return{ran:!0,error:error93 instanceof Error?error93.message:"Unknown error",duration_ms:Number(process.hrtime.bigint()-start)/1e6}}}async function runQualityBudgetWrapped(changedFiles,directory,gates,abortSignal){let start=process.hrtime.bigint();try{return{ran:!0,result:await runWithTimeout2((signal2)=>_internals285.qualityBudget({changed_files:changedFiles,config:gates?.quality_budget},directory,signal2),TOOL_TIMEOUT_MS,abortSignal,!0),duration_ms:Number(process.hrtime.bigint()-start)/1e6}}catch(error93){return{ran:!0,error:error93 instanceof Error?error93.message:"Unknown error",duration_ms:Number(process.hrtime.bigint()-start)/1e6}}}var GATE_SEVERITIES=new Set(["high","critical"]),SEVERITY_ORDER_PCB={low:0,medium:1,high:2,critical:3};function meetsThresholdForTriage(severity2,threshold){return(SEVERITY_ORDER_PCB[severity2]??0)>=(SEVERITY_ORDER_PCB[threshold]??1)}async function runGit8(args2,directory,abortSignal){let gitExecutable;try{gitExecutable=await resolveGitExecutableAsync()}catch{return null}let result=await _internals285.runExternalTool({executable:gitExecutable,args:args2,cwd:directory,timeoutMs:GIT_TIMEOUT_MS12,maxStdoutBytes:GIT_MAX_OUTPUT_BYTES2,maxStderrBytes:64000,abortSignal});if(result.status!=="completed"||result.exitCode!==0||result.stdoutTruncated)return null;return result.stdout}function decodeGitQuotedPath(value){if(!value.startsWith('"'))return value;if(!value.endsWith('"'))return null;let bytes=[],appendText=(text)=>{bytes.push(...Buffer.from(text,"utf8"))};for(let index=1;index<value.length-1;index++){let codePoint=value.codePointAt(index);if(codePoint===void 0)return null;let char=String.fromCodePoint(codePoint);if(char!=="\\"){if(appendText(char),char.length===2)index++;continue}if(index++,index>=value.length-1)return null;let escaped=value[index],simple={"\\":"\\",'"':'"',t:"\t",n:`
|
|
7726
|
-
`,r:"\r",b:"\b",f:"\f",v:"\v"};if(simple[escaped]!==void 0){appendText(simple[escaped]);continue}if(/[0-7]/.test(escaped)){let octal=escaped;for(let count=0;count<2;count++){let next=value[index+1];if(!next||!/[0-7]/.test(next))break;octal+=next,index++}bytes.push(Number.parseInt(octal,8));continue}return null}return Buffer.from(bytes).toString("utf8")}function normalizeRepoPathKey(repoPath){let normalized=repoPath.replace(/\\/g,"/");return _internals285.platform()==="win32"||_internals285.platform()==="darwin"?normalized.toLowerCase():normalized}function normalizeDiffPath(rawPath){let pathToken=rawPath.startsWith('"')?rawPath:rawPath.split("\t",1)[0],decoded=decodeGitQuotedPath(pathToken);if(decoded===null||decoded==="/dev/null"||decoded.trim().length===0)return null;return normalizeRepoPathKey(decoded)}function parseDiffLineRangesChecked(diffOutput,requireGitFileHeaders){let result=new Map,currentFile=null,inGitFile=!1,expectingDestination=!1,destinationSeen=!1,destinationNeedsHunk=!1,collectedLines=0;for(let rawLine of diffOutput.split(/\r?\n/)){let line=rawLine.endsWith("\r")?rawLine.slice(0,-1):rawLine;if(line.startsWith("diff --git ")){if(expectingDestination||destinationNeedsHunk)return null;inGitFile=!0,currentFile=null,expectingDestination=!1,destinationSeen=!1;continue}if(line.startsWith("--- ")&&(inGitFile||!requireGitFileHeaders)){if(expectingDestination||destinationNeedsHunk)return null;expectingDestination=!0;continue}if(line.startsWith("+++ ")){if(requireGitFileHeaders&&(!inGitFile||!expectingDestination))return null;let rawDestination=line.slice(4);if(currentFile=normalizeDiffPath(rawDestination),currentFile===null&&rawDestination.trim()!=="/dev/null")return null;if(expectingDestination=!1,destinationSeen=!0,destinationNeedsHunk=!0,!currentFile)continue;if(!result.has(currentFile))result.set(currentFile,new Set);continue}if(!line.startsWith("@@"))continue;if(expectingDestination||requireGitFileHeaders&&(!inGitFile||!destinationSeen))return null;let match=/^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/.exec(line);if(!match)return null;let start=Number.parseInt(match[1],10),count=match[2]!==void 0?Number.parseInt(match[2],10):1;if(!Number.isSafeInteger(start)||!Number.isSafeInteger(count)||count<0||count>0&&start<1||count>MAX_CHANGED_LINE_ENTRIES||start+count-1>Number.MAX_SAFE_INTEGER||collectedLines+count>MAX_CHANGED_LINE_ENTRIES)return null;if(destinationNeedsHunk=!1,!currentFile)continue;let lines=result.get(currentFile);if(!lines)return null;for(let index=0;index<count;index++)lines.add(start+index);collectedLines+=count}if(expectingDestination||destinationNeedsHunk)return null;return result}function mergeChangedLines(target,source){for(let[file3,sourceLines]of source){let targetLines=target.get(file3)??new Set;for(let line of sourceLines)targetLines.add(line);target.set(file3,targetLines)}}function parseUntrackedStatus(output){if(output.length>0&&!output.endsWith("\x00"))return null;let untracked=[],records=output.split("\x00");for(let index=0;index<records.length-1;index++){let record3=records[index];if(!record3||record3.length<4||record3[2]!==" ")return null;let status2=record3.slice(0,2),filePath=record3.slice(3);if(!filePath||!isKnownPorcelainStatus(status2))return null;if(status2==="??"||status2==="!!")untracked.push(normalizeRepoPathKey(filePath));if(/[RC]/.test(status2)){let sourcePath=records[++index];if(!sourcePath||looksLikePorcelainStatusRecord(sourcePath))return null}}return untracked}function isKnownPorcelainStatus(status2){if(status2==="??"||status2==="!!")return!0;if(/U/.test(status2))return new Set(["DD","AU","UD","UA","DU","AA","UU"]).has(status2);return status2!==" "&&/^[ MTADRC]{2}$/.test(status2)}function looksLikePorcelainStatusRecord(value){return value.length>=4&&value[2]===" "&&isKnownPorcelainStatus(value.slice(0,2))}async function getChangedLineRanges(directory,abortSignal,requestedFiles=[]){let mergeBase=null;for(let baseBranch of["zaxbyhub/main","upstream/main","origin/main","main","origin/master","master"]){let candidate2=(await runGit8(["merge-base",baseBranch,"HEAD"],directory,abortSignal))?.trim();if(candidate2&&/^[0-9a-f]{40,64}$/i.test(candidate2)){mergeBase=candidate2;break}}if(!mergeBase)return null;let commonDiffArgs=["-c","core.quotePath=false","diff","--no-ext-diff","--no-color","--no-prefix","-U0"],requestedPathspecs=requestedFiles.map((file3)=>path344.relative(directory,file3).replace(/\\/g,"/")).filter((file3)=>file3.length>0&&file3!==".."&&!file3.startsWith("../")),statusArgs=["-c","core.quotePath=false","status","--porcelain=v1","-z","--untracked-files=all",...requestedPathspecs.length>0?["--ignored=matching"]:[],...requestedPathspecs.length>0?["--",...requestedPathspecs]:[]],[committed,staged,unstaged,status2]=await Promise.all([runGit8([...commonDiffArgs,`${mergeBase}..HEAD`,"--"],directory,abortSignal),runGit8([...commonDiffArgs,"--cached","HEAD","--"],directory,abortSignal),runGit8([...commonDiffArgs,"--"],directory,abortSignal),runGit8(statusArgs,directory,abortSignal)]);if(committed===null||staged===null||unstaged===null||status2===null)return null;let committedLines=parseDiffLineRangesChecked(committed,!0),stagedLines=parseDiffLineRangesChecked(staged,!0),unstagedLines=parseDiffLineRangesChecked(unstaged,!0);if(!committedLines||!stagedLines||!unstagedLines)return null;let result=new Map;mergeChangedLines(result,committedLines),mergeChangedLines(result,stagedLines),mergeChangedLines(result,unstagedLines);let untracked=parseUntrackedStatus(status2);if(untracked===null)return null;let requestedKeys=requestedPathspecs.map(normalizeRepoPathKey);for(let file3 of untracked)if(result.set(file3,new Set([ALL_LINES_CHANGED])),file3.endsWith("/")){for(let requestedFile of requestedKeys)if(requestedFile.startsWith(file3))result.set(requestedFile,new Set([ALL_LINES_CHANGED]))}return result}function classifySastFindings(findings,changedLineRanges,directory){if(!changedLineRanges)return{newFindings:findings,preexistingFindings:[]};let newFindings=[],preexistingFindings=[],pathApi=_internals285.platform()==="win32"?path344.win32:path344.posix,resolvedDirectory=pathApi.resolve(directory);for(let finding of findings){let filePath=finding.location.file,normalised;try{if(typeof filePath!=="string"||filePath.length===0||filePath.includes("\x00")){newFindings.push(finding);continue}let resolvedFinding=pathApi.isAbsolute(filePath)?pathApi.resolve(filePath):pathApi.resolve(resolvedDirectory,filePath),relative87=pathApi.relative(resolvedDirectory,resolvedFinding);if(pathApi.isAbsolute(relative87)||relative87===".."||relative87.startsWith(`..${pathApi.sep}`)){newFindings.push(finding);continue}normalised=normalizeRepoPathKey(relative87)}catch{newFindings.push(finding);continue}let changedLines=changedLineRanges.get(normalised);if(changedLines?.has(ALL_LINES_CHANGED)||changedLines?.has(finding.location.line))newFindings.push(finding);else preexistingFindings.push(finding)}return{newFindings,preexistingFindings}}async function runPreCheckBatch(input,workspaceDir,contextDir,abortSignal){let effectiveWorkspaceDir=workspaceDir||input.directory||contextDir,{files,directory,sast_threshold="medium",gates:gatesOverrides,phase,sast_enabled=!0}=input,gates=gatesOverrides??(input.config?.gates?{sast_scan:input.config.gates.sast_scan,quality_budget:input.config.gates.quality_budget}:void 0),dirError=validateDirectory2(directory,effectiveWorkspaceDir);if(dirError)return warn(`pre_check_batch: Invalid directory: ${dirError}`),{batch_status:"invalid",gates_passed:!1,lint:{ran:!1,error:dirError,duration_ms:0},secretscan:{ran:!1,error:dirError,duration_ms:0},sast_scan:{ran:!1,error:dirError,duration_ms:0},quality_budget:{ran:!1,error:dirError,duration_ms:0},total_duration_ms:0};if(!files||files.length===0)return warn("pre_check_batch: No files provided, skipping all tools (fail-closed)"),{batch_status:"invalid",gates_passed:!1,lint:{ran:!1,error:"No files provided",duration_ms:0},secretscan:{ran:!1,error:"No files provided",duration_ms:0},sast_scan:{ran:!1,error:"No files provided",duration_ms:0},quality_budget:{ran:!1,error:"No files provided",duration_ms:0},total_duration_ms:0};let changedFiles=[];for(let file3 of files){if(typeof file3!=="string"){warn(`pre_check_batch: Non-string file entry rejected: ${String(file3)}`);continue}if(validatePath(file3,directory,effectiveWorkspaceDir)){warn(`pre_check_batch: Invalid file path: ${file3}`);continue}changedFiles.push(path344.resolve(directory,file3))}if(changedFiles.length===0)return warn("pre_check_batch: No valid files after validation, skipping all tools (fail-closed)"),{batch_status:"invalid",gates_passed:!1,lint:{ran:!1,error:"No files provided",duration_ms:0},secretscan:{ran:!1,error:"No files provided",duration_ms:0},sast_scan:{ran:!1,error:"No files provided",duration_ms:0},quality_budget:{ran:!1,error:"No files provided",duration_ms:0},total_duration_ms:0};try{assertProjectRoot(directory)}catch(error93){let rootError=error93 instanceof Error?error93.message:String(error93);return warn(`pre_check_batch: Project-root validation failed: ${rootError}`),{batch_status:"invalid",gates_passed:!1,lint:{ran:!1,error:rootError,duration_ms:0},secretscan:{ran:!1,error:rootError,duration_ms:0},sast_scan:{ran:!1,error:rootError,duration_ms:0},quality_budget:{ran:!1,error:rootError,duration_ms:0},total_duration_ms:0}}if(changedFiles.length>MAX_FILES)throw Error(`Input exceeds maximum file count: ${changedFiles.length} > ${MAX_FILES}`);let limit=pLimit(MAX_CONCURRENT),sastDisabledByConfig=gates?.sast_scan?.enabled===!1,[lintResult,secretscanResult,sastScanResult,qualityBudgetResult]=await Promise.all([limit(()=>_internals285.runLintWrapped(changedFiles,directory,gates,abortSignal)),limit(()=>_internals285.runSecretscanWrapped(changedFiles,directory,gates,abortSignal)),sast_enabled&&!sastDisabledByConfig?limit(()=>_internals285.runSastScanWrapped(changedFiles,directory,sast_threshold,gates,phase,abortSignal)):Promise.resolve({ran:!1,duration_ms:0}),limit(()=>_internals285.runQualityBudgetWrapped(changedFiles,directory,gates,abortSignal))]),totalDuration=lintResult.duration_ms+secretscanResult.duration_ms+sastScanResult.duration_ms+qualityBudgetResult.duration_ms,gatesPassed=!0;if(lintResult.ran&&lintResult.result){let lintRes=lintResult.result;if("success"in lintRes&&lintRes.success===!1)warn("pre_check_batch: Lint found issues (informational only)")}else if(lintResult.error)warn(`pre_check_batch: Lint error (informational only): ${lintResult.error}`);let secretscanDecision=evaluateSecretscanGate(secretscanResult,changedFiles.length);if(!secretscanDecision.passed)gatesPassed=!1,warn(`pre_check_batch: ${secretscanDecision.summary} - GATE FAILED`);if(secretscanResult.ran||secretscanResult.error)try{let scanResult=secretscanDecision.result,secretscanEvidence={task_id:"secretscan",type:"secretscan",timestamp:new Date().toISOString(),agent:"pre_check_batch",verdict:secretscanDecision.passed?"pass":"fail",summary:secretscanDecision.summary,findings_count:secretscanDecision.findingsCount,scan_directory:scanResult?.scan_dir??directory,files_scanned:scanResult?.files_scanned??0,skipped_files:scanResult?.skipped_files??0,incomplete_files:scanResult?.incomplete_files??changedFiles.length,incomplete_paths:scanResult?.incomplete_paths??[{path:".",reason:"missing_coverage_metadata"}]};await _internals285.saveEvidence(directory,"secretscan",secretscanEvidence,abortSignal)}catch(e){let persistError=`Failed to persist secretscan evidence: ${e instanceof Error?e.message:String(e)}`;secretscanResult.error=persistError,gatesPassed=!1,warn(`pre_check_batch: ${persistError} - GATE FAILED`)}let sastPreexistingFindings,sastDegraded=!1;if(sastScanResult.ran&&sastScanResult.result){let sastResult=sastScanResult.result;if(sastResult.error)if(sastResult.failure_kind==="semgrep_process_exit"&&sastResult.findings.length===0)sastDegraded=!0,warn(`pre_check_batch: SAST coverage degraded (${sastResult.error}) - continuing without a gate failure`);else gatesPassed=!1,warn(`pre_check_batch: SAST scan error (${sastResult.error}) - GATE FAILED`);else if(sastResult.baseline_used){let sastCarryFindings=[...sastResult.pre_existing_findings??[],...sastResult.moved_findings??[]];if(sastCarryFindings.length>0){if(sastPreexistingFindings=sastCarryFindings.filter((f)=>meetsThresholdForTriage(f.severity,sast_threshold)),sastPreexistingFindings.length>0)warn(`pre_check_batch: SAST baseline diff found ${sastPreexistingFindings.length} pre-existing/moved finding(s) - passing to reviewer for triage`)}if(sastResult.verdict==="fail")gatesPassed=!1,warn("pre_check_batch: SAST scan found new findings above threshold - GATE FAILED")}else if(sastResult.verdict==="fail"){let gateFindings=sastResult.findings.filter((f)=>GATE_SEVERITIES.has(f.severity));if(gateFindings.length>0){let changedLineRanges=await _internals285.getChangedLineRanges(directory,abortSignal,changedFiles),{newFindings,preexistingFindings}=classifySastFindings(gateFindings,changedLineRanges,directory);if(newFindings.length>0)gatesPassed=!1,warn(`pre_check_batch: SAST scan found ${newFindings.length} new HIGH/CRITICAL finding(s) on changed lines - GATE FAILED`);else if(preexistingFindings.length>0)sastPreexistingFindings=preexistingFindings,warn(`pre_check_batch: SAST scan found ${preexistingFindings.length} pre-existing HIGH/CRITICAL finding(s) on unchanged lines - passing to reviewer for triage`)}else gatesPassed=!1,warn("pre_check_batch: SAST scan found vulnerabilities - GATE FAILED")}}else if(sastScanResult.error)gatesPassed=!1,warn(`pre_check_batch: SAST scan error - GATE FAILED: ${sastScanResult.error}`);if(qualityBudgetResult.ran&&qualityBudgetResult.result){if(qualityBudgetResult.result.verdict==="fail")warn("pre_check_batch: Quality budget exceeded (informational only)")}else if(qualityBudgetResult.error)warn(`pre_check_batch: Quality budget error (informational only): ${qualityBudgetResult.error}`);return{batch_status:[lintResult,secretscanResult,sastScanResult,qualityBudgetResult].every((toolResult)=>toolResult.ran===!1)?"skipped":"completed",gates_passed:gatesPassed,lint:lintResult,secretscan:secretscanResult,sast_scan:sastScanResult,quality_budget:qualityBudgetResult,total_duration_ms:Math.round(totalDuration),...sastDegraded&&{sast_degraded:!0},...(!sast_enabled||sastDisabledByConfig)&&{sast_skipped:!0},...sastPreexistingFindings&&sastPreexistingFindings.length>0&&{sast_preexisting_findings:sastPreexistingFindings}}}var pre_check_batch=createSwarmTool({allowWorkingDirectoryOverride:!0,description:"Run multiple verification tools in parallel: lint, secretscan, SAST scan, and quality budget. Returns unified result with gates_passed status. Security findings and incomplete SAST runs are hard failures; a Semgrep nonzero process exit with zero findings is returned as explicit sast_degraded coverage and does not block.",args:{files:exports_external.array(exports_external.string()).optional().describe("Specific files to check (optional, scans directory if not provided)"),directory:exports_external.string().describe("Project root directory — ordinary workspace subdirectories are rejected; direct .git or .opencode project boundaries are accepted"),sast_threshold:exports_external.enum(["low","medium","high","critical"]).optional().describe("Minimum severity for SAST findings to cause failure (default: medium)"),phase:exports_external.number().int().min(1).optional().describe("Current phase number (positive integer >= 1). When provided, enables SAST baseline diffing: only findings absent from the phase-scoped baseline fail the gate.")},async execute(args2,directory,ctx){if(!args2||typeof args2!=="object")return serializePreCheckResult({batch_status:"invalid",gates_passed:!1,lint:{ran:!1,error:"Invalid arguments",duration_ms:0},secretscan:{ran:!1,error:"Invalid arguments",duration_ms:0},sast_scan:{ran:!1,error:"Invalid arguments",duration_ms:0},quality_budget:{ran:!1,error:"Invalid arguments",duration_ms:0},total_duration_ms:0});if(!directory||typeof directory!=="string"||directory.trim()==="")return serializePreCheckResult({batch_status:"invalid",gates_passed:!1,lint:{ran:!1,error:"project directory is required but was not provided",duration_ms:0},secretscan:{ran:!1,error:"project directory is required but was not provided",duration_ms:0},sast_scan:{ran:!1,error:"project directory is required but was not provided",duration_ms:0},quality_budget:{ran:!1,error:"project directory is required but was not provided",duration_ms:0},total_duration_ms:0});let typedArgs=args2;if(!typedArgs.directory)return serializePreCheckResult({batch_status:"invalid",gates_passed:!1,lint:{ran:!1,error:"directory is required",duration_ms:0},secretscan:{ran:!1,error:"directory is required",duration_ms:0},sast_scan:{ran:!1,error:"directory is required",duration_ms:0},quality_budget:{ran:!1,error:"directory is required",duration_ms:0},total_duration_ms:0});let resolvedDirectory=path344.resolve(typedArgs.directory),workspaceAnchor=path344.resolve(directory);if(isStrictPathDescendant(resolvedDirectory,workspaceAnchor)&&!hasExplicitProjectBoundary(resolvedDirectory)){let subDirError=`directory "${typedArgs.directory}" is a subdirectory of the project root — pre_check_batch requires the project root directory "${workspaceAnchor}"`;return serializePreCheckResult({batch_status:"invalid",gates_passed:!1,lint:{ran:!1,error:subDirError,duration_ms:0},secretscan:{ran:!1,error:subDirError,duration_ms:0},sast_scan:{ran:!1,error:subDirError,duration_ms:0},quality_budget:{ran:!1,error:subDirError,duration_ms:0},total_duration_ms:0})}let dirError=validateDirectory2(resolvedDirectory,workspaceAnchor);if(dirError)return serializePreCheckResult({batch_status:"invalid",gates_passed:!1,lint:{ran:!1,error:dirError,duration_ms:0},secretscan:{ran:!1,error:dirError,duration_ms:0},sast_scan:{ran:!1,error:dirError,duration_ms:0},quality_budget:{ran:!1,error:dirError,duration_ms:0},total_duration_ms:0});try{let sastEnabled=!0;try{let preamble=await _internals285.resolveGatePreamble(resolvedDirectory,ctx?.sessionID);if(preamble.resolved&&preamble.effectiveGates)sastEnabled=preamble.effectiveGates.sast_enabled}catch{warn("pre_check_batch: QA-gate profile resolution failed; keeping SAST enabled")}let rawPhase=typedArgs.phase,safePhase=typeof rawPhase==="number"&&Number.isInteger(rawPhase)&&rawPhase>=1?rawPhase:void 0,result=await _internals285.runPreCheckBatch({files:typedArgs.files,directory:resolvedDirectory,sast_threshold:typedArgs.sast_threshold,config:typedArgs.config,gates:_internals285.loadGateOverrides(resolvedDirectory),phase:safePhase,sast_enabled:sastEnabled},workspaceAnchor,directory,ctx?.abort);return serializePreCheckResult(result)}catch(error93){let errorMessage3=error93 instanceof Error?error93.message:"Unknown error";return serializePreCheckResult({batch_status:"invalid",gates_passed:!1,lint:{ran:!1,error:errorMessage3,duration_ms:0},secretscan:{ran:!1,error:errorMessage3,duration_ms:0},sast_scan:{ran:!1,error:errorMessage3,duration_ms:0},quality_budget:{ran:!1,error:errorMessage3,duration_ms:0},total_duration_ms:0})}}});init_zod();init_guardrails2();init_pr_workflow_gate();init_scope_binding();init_create_tool();var PreparePrFeedbackScopeArgsSchema=exports_external.object({task_id:exports_external.string().regex(/^\d+\.\d+(?:\.\d+)*$/,"task_id must use N.M notation"),files:exports_external.array(exports_external.string().min(1).max(4096)).min(1).max(1e4)}).strict();function failure(message){return JSON.stringify({success:!1,message},null,2)}async function executePreparePrFeedbackScope(args2,directory,context={}){let parsed=PreparePrFeedbackScopeArgsSchema.safeParse(args2);if(!parsed.success)return failure(`Invalid PR-feedback scope: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`);let sessionID=context.sessionID?.trim();if(!sessionID)return failure("PR-feedback scope requires an active session");let files=normalizeScopeFiles(parsed.data.files);if(!files)return failure("PR-feedback scope contains an unsafe file path");for(let file3 of files){let symlinkBlock=checkWriteTargetForSymlink(file3,directory);if(symlinkBlock)return failure(symlinkBlock)}try{await declarePrFeedbackScope(directory,sessionID,parsed.data.task_id,files)}catch(error93){return failure(error93 instanceof Error?error93.message:String(error93))}return JSON.stringify({success:!0,task_id:parsed.data.task_id,files,message:"Scope is bound to the verified PR-feedback revision and will authorize only the next matching coder Task."},null,2)}var prepare_pr_feedback_scope=createSwarmTool({description:"Prepare an exact file scope for one PR-feedback coder Task after immutable feedback verification settles.",args:{task_id:PreparePrFeedbackScopeArgsSchema.shape.task_id,files:PreparePrFeedbackScopeArgsSchema.shape.files},execute:executePreparePrFeedbackScope});init_quality_budget();init_zod();init_pr_workflow_gate();init_create_tool();var RebindPrFeedbackHeadArgsSchema=exports_external.object({pr_head_sha:exports_external.string().trim().regex(/^[0-9a-f]{40}$/i)}).strict();async function executeRebindPrFeedbackHead(args2,directory,context={}){let parsed=RebindPrFeedbackHeadArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,message:`Invalid PR feedback rebind: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`});if(!context.sessionID?.trim())return JSON.stringify({success:!1,message:"PR feedback rebind requires an active sessionID"});try{let state2=await rebindPrFeedbackHead(directory,context.sessionID,parsed.data.pr_head_sha);return JSON.stringify({success:!0,pr_head_sha:state2.prHeadSha,rebind_count:state2.prFeedbackRebindCount??1,message:"Rebound the PR_FEEDBACK intake head; every Stage A / verification / gate receipt is invalidated — re-run the full mechanical ladder on the new ancestry."})}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:String(error93)})}}var rebind_pr_feedback_head=createSwarmTool({description:"Rebind a PR_FEEDBACK workflow to a new verified remote PR head after merge/rebase/conflict repair (base-sync). Use ONLY when the history genuinely changed to repair base drift or conflicts: it refuses a no-op rebind to the current intake head, refuses while publication is armed (to change approved content after arming use invalidate_pr_feedback_publication), and refuses while lanes are in flight. It invalidates every ancestry-bound receipt (Stage A, verification, ordered gates) so the full mechanical ladder re-runs on the new ancestry. Requires the full 40-char new PR head SHA; the current checkout must equal it.",args:{pr_head_sha:RebindPrFeedbackHeadArgsSchema.shape.pr_head_sha},execute:executeRebindPrFeedbackHead});init_zod();init_utils2();init_atomic_write();init_create_tool();var FreshnessValueSchema=exports_external.string().trim().min(1).max(500).regex(/^(synced|behind:[1-9][0-9]*|fetch-failed:\S+)$/,"must be 'synced', 'behind:<n>', or 'fetch-failed:<reason>' (reason contains no whitespace)"),RecordBranchFreshnessArgsSchema=exports_external.object({issueNumber:exports_external.number().int().min(1),freshness:FreshnessValueSchema,override:exports_external.string().trim().min(1).max(4000).optional()}).strict();async function executeRecordBranchFreshness(args2,directory,context={}){let parsed=RecordBranchFreshnessArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,message:`Invalid branch-freshness receipt: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`});let data=parsed.data;if(data.freshness==="synced"&&data.override)return JSON.stringify({success:!1,message:"An override is only meaningful for a fetch-failed outcome; a synced base needs none."});let receipt={issueNumber:data.issueNumber,freshness:data.freshness,timestamp:new Date().toISOString()};if(data.override)receipt.override=data.override;if(context.sessionID?.trim())receipt.sessionId=context.sessionID.trim();let validatedPath;try{validatedPath=validateSwarmPath(directory,"branch-freshness.json")}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:"Failed to validate path"})}try{await atomicWriteSwarmFile(validatedPath,JSON.stringify(receipt,null,2));let permits=await branchFreshnessReceiptExists(directory,data.issueNumber);return JSON.stringify({success:!0,issueNumber:data.issueNumber,path:".swarm/branch-freshness.json",permits,message:permits?`Branch-freshness receipt recorded for issue #${data.issueNumber}; the trace's freshness gate is satisfied.`:`Branch-freshness receipt recorded for issue #${data.issueNumber}, but the outcome (${data.freshness}) does NOT permit the trace — ${data.freshness.startsWith("behind:")?"re-sync with the default branch and re-record as synced.":"a fetch-failed outcome without a recorded user override fails closed."}`})}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:String(error93)})}}var record_branch_freshness=createSwarmTool({description:`Record the Phase 0 branch-freshness outcome for the current traced issue (issue #2564): freshness is "synced", "behind:<n>", or "fetch-failed:<reason>" exactly as the fetch recorded it, plus an optional verbatim user override for a failed fetch. The /swarm issue --trace workflow will not transition to PLAN until the recorded outcome permits (synced, or fetch-failed with an override). The response's permits field mirrors the gate reader's verdict on the persisted receipt (advisory for the calling agent — the reducer always recomputes it independently).`,args:{issueNumber:RecordBranchFreshnessArgsSchema.shape.issueNumber,freshness:RecordBranchFreshnessArgsSchema.shape.freshness,override:RecordBranchFreshnessArgsSchema.shape.override},execute:executeRecordBranchFreshness});init_zod();init_schema();init_extractors();init_manager();init_create_tool();var recordDirectiveOverrideInternals={loadPlan,recordDirectiveOverrides};async function executeRecordDirectiveOverride(args2,directory,ctx){if(!ctx?.sessionID?.trim())return{success:!1,code:"DIRECTIVE_OVERRIDE_SESSION_REQUIRED",message:"An exact session identity is required to record an override."};if(stripKnownSwarmPrefix(ctx.agent??"").toLowerCase()!=="architect")return{success:!1,code:"DIRECTIVE_OVERRIDE_ARCHITECT_ONLY",message:"Only the architect may record a critical-directive override."};let plan=await recordDirectiveOverrideInternals.loadPlan(directory),requestedPhase=plan?.phases.find((candidate2)=>candidate2.id===args2.phase);if(!plan||!requestedPhase||plan.current_phase!==args2.phase)return{success:!1,code:"DIRECTIVE_OVERRIDE_PHASE_MISMATCH",message:`Phase ${args2.phase} is not the current authoritative plan phase.`};let phaseLabel=extractCurrentPhaseFromPlan(plan)??`Phase ${plan.current_phase}`;return await recordDirectiveOverrideInternals.recordDirectiveOverrides(directory,[...new Set(args2.directive_ids)],args2.justification,ctx.sessionID,phaseLabel),{success:!0,code:"DIRECTIVE_OVERRIDE_RECORDED",phase:args2.phase,directive_ids:[...new Set(args2.directive_ids)],message:"Recorded the audited override. Retry phase_complete so every gate is re-evaluated from a fresh snapshot."}}var record_directive_override=createSwarmTool({description:"Architect-only audited override for identified critical-directive violations. Requires exact current phase/session identity and substantive justification; it cannot repair or bypass unreadable authority.",args:{directive_ids:exports_external.array(exports_external.string().min(1).max(256)).min(1).max(64),justification:exports_external.string().trim().min(10).max(2000),phase:exports_external.number().int().min(1).max(9999)},execute:async(args2,directory,ctx)=>JSON.stringify(await executeRecordDirectiveOverride(args2,directory,ctx),null,2)});init_zod();init_utils2();init_atomic_write();init_create_tool();var RecordImplementationReviewArgsSchema=exports_external.object({issueNumber:exports_external.number().int().min(1),reviewerVerdict:exports_external.enum(["APPROVE","NEEDS_REVISION","BLOCKED"]),criticVerdict:exports_external.enum(["APPROVE","NEEDS_REVISION","BLOCKED"]),diffBase:exports_external.string().trim().regex(/^[0-9a-f]{7,40}$/i),diffHead:exports_external.string().trim().regex(/^[0-9a-f]{7,40}$/i),notes:exports_external.string().trim().min(8).max(4000)}).strict();async function executeRecordImplementationReview(args2,directory,context={}){let parsed=RecordImplementationReviewArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,message:`Invalid implementation review receipt: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`});let data=parsed.data;if(data.reviewerVerdict!=="APPROVE"||data.criticVerdict!=="APPROVE")return JSON.stringify({success:!1,message:"A satisfying implementation-review receipt requires BOTH the reviewer and the critic to have delivered APPROVE; record non-approving verdicts in the working notes and fix the findings instead."});let receipt={issueNumber:data.issueNumber,reviewerVerdict:data.reviewerVerdict,criticVerdict:data.criticVerdict,diffBase:data.diffBase,diffHead:data.diffHead,notes:data.notes,timestamp:new Date().toISOString()};if(context.sessionID?.trim())receipt.sessionId=context.sessionID.trim();let validatedPath;try{validatedPath=validateSwarmPath(directory,"implementation-review.json")}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:"Failed to validate path"})}try{return await atomicWriteSwarmFile(validatedPath,JSON.stringify(receipt,null,2)),JSON.stringify({success:!0,issueNumber:data.issueNumber,path:".swarm/implementation-review.json",message:`Implementation review recorded for issue #${data.issueNumber} (reviewer APPROVE + critic APPROVE); the trace may now satisfy its review gate.`})}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:String(error93)})}}var record_implementation_review=createSwarmTool({description:"Record the independent implementation review for the current traced issue (issue #2131 residual B): dispatch FRESH-context reviewer and critic passes over the implementation diff (separate contexts from the implementer), and once BOTH approve call this with the issue number, both APPROVE verdicts, the reviewed diff base/head SHAs, and notes. The /swarm issue --trace workflow will not hand off to commit-pr until this receipt exists. Non-approving verdicts cannot be recorded here — fix the findings and re-review.",args:{issueNumber:RecordImplementationReviewArgsSchema.shape.issueNumber,reviewerVerdict:RecordImplementationReviewArgsSchema.shape.reviewerVerdict,criticVerdict:RecordImplementationReviewArgsSchema.shape.criticVerdict,diffBase:RecordImplementationReviewArgsSchema.shape.diffBase,diffHead:RecordImplementationReviewArgsSchema.shape.diffHead,notes:RecordImplementationReviewArgsSchema.shape.notes},execute:executeRecordImplementationReview});init_zod();init_utils2();init_atomic_write();init_create_tool();var RecordIssuePublicationArgsSchema=exports_external.object({issueNumber:exports_external.number().int().min(1),prNumber:exports_external.number().int().min(1),prUrl:exports_external.string().url().regex(/^https:\/\/github\.com\/[^/]+\/[^/]+\/pull\/\d+/,"prUrl must be a canonical GitHub PR URL (https://github.com/<owner>/<repo>/pull/<number>)"),headSha:exports_external.string().min(1).optional()}).strict();async function executeRecordIssuePublication(args2,directory){let parsed=RecordIssuePublicationArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,message:`Invalid publication receipt: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`});let{issueNumber,prNumber,prUrl,headSha}=parsed.data,receipt={published:!0,issueNumber,prNumber,prUrl,publishedAt:new Date().toISOString()};if(headSha)receipt.headSha=headSha;let validatedPath;try{validatedPath=validateSwarmPath(directory,"issue-publication.json")}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:"Failed to validate path"})}try{return await atomicWriteSwarmFile(validatedPath,JSON.stringify(receipt,null,2)),JSON.stringify({success:!0,issueNumber,prNumber,prUrl,path:".swarm/issue-publication.json",message:`Publication receipt recorded for issue #${issueNumber} (PR #${prNumber}); the issue-trace workflow will transition to its terminal published state.`})}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:String(error93)})}}var record_issue_publication=createSwarmTool({description:'Record that the traced issue has been published (PR created/updated) so the /swarm issue --trace workflow can reach its terminal published state. The trace stops at publication_handoff (the commit-pr directive) until this receipt is observed — publication_handoff is NOT "issue resolved". commit-pr calls this after the PR is created/updated. Supply the traced issue number, the exact PR number, the canonical GitHub PR URL, and (optionally) the published HEAD sha. The receipt is issue-bound.',args:{issueNumber:RecordIssuePublicationArgsSchema.shape.issueNumber,prNumber:RecordIssuePublicationArgsSchema.shape.prNumber,prUrl:RecordIssuePublicationArgsSchema.shape.prUrl,headSha:RecordIssuePublicationArgsSchema.shape.headSha},execute:executeRecordIssuePublication});init_zod();init_utils2();init_atomic_write();init_create_tool();var RecordIssueReproductionArgsSchema=exports_external.object({issueNumber:exports_external.number().int().min(1),performed:exports_external.boolean(),commands:exports_external.array(exports_external.string().min(1)).min(1).optional(),output_summary:exports_external.string().min(1).optional()}).strict();async function executeRecordIssueReproduction(args2,directory,context={}){let parsed=RecordIssueReproductionArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,message:`Invalid reproduction receipt: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`});let{issueNumber,performed,commands,output_summary}=parsed.data;if(performed&&(!commands||commands.length===0||!output_summary))return JSON.stringify({success:!1,message:"A performed=true reproduction receipt requires non-empty commands and output_summary."});let receipt={performed,issueNumber,timestamp:new Date().toISOString()};if(commands)receipt.commands=commands;if(output_summary)receipt.output_summary=output_summary;if(context.sessionID?.trim())receipt.sessionId=context.sessionID.trim();let validatedPath;try{validatedPath=validateSwarmPath(directory,"reproduction.json")}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:"Failed to validate path"})}try{return await atomicWriteSwarmFile(validatedPath,JSON.stringify(receipt,null,2)),JSON.stringify({success:!0,issueNumber,performed,path:".swarm/reproduction.json",message:performed?`Reproduction receipt recorded for issue #${issueNumber}; the trace may now transition to PLAN.`:`Reproduction receipt recorded (performed=false) for issue #${issueNumber}; it does NOT satisfy the reproduction gate.`})}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:String(error93)})}}var record_issue_reproduction=createSwarmTool({description:"Record the reproduction outcome for the current traced issue. The /swarm issue --trace workflow requires reproduction evidence (or a typed --no-repro waiver) before it can leave localization and transition to PLAN. Call this with performed=true, the exact commands run, and a concrete output_summary after attempting a minimal reproduction; the receipt binds to issueNumber (and records the calling session) and is read by the issue-trace engine. A performed=true receipt MUST include commands and output_summary. A performed=false receipt is recorded but does NOT satisfy the gate.",args:{issueNumber:RecordIssueReproductionArgsSchema.shape.issueNumber,performed:RecordIssueReproductionArgsSchema.shape.performed,commands:RecordIssueReproductionArgsSchema.shape.commands,output_summary:RecordIssueReproductionArgsSchema.shape.output_summary},execute:executeRecordIssueReproduction});init_zod();init_utils2();init_atomic_write();init_create_tool();var HEX40=/^[0-9a-f]{40}$/,RecordMergeApprovalArgsSchema=exports_external.object({issueNumber:exports_external.number().int().min(1),prHeadSha:exports_external.string().regex(HEX40,"must be a 40-hex commit SHA"),finalCriticReviewedCommit:exports_external.string().regex(HEX40,"must be a 40-hex commit SHA"),userApprovalVerbatim:exports_external.string().trim().min(1).max(8000)}).strict();async function executeRecordMergeApproval(args2,directory,context={}){let parsed=RecordMergeApprovalArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,message:`Invalid merge-approval receipt: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`});let data=parsed.data;if(data.prHeadSha!==data.finalCriticReviewedCommit)return JSON.stringify({success:!1,message:"Merge-approval binding failed: prHeadSha must equal finalCriticReviewedCommit (the final critic approval must be bound to the exact PR head)."});let receipt={issueNumber:data.issueNumber,prHeadSha:data.prHeadSha,finalCriticReviewedCommit:data.finalCriticReviewedCommit,userApprovalVerbatim:data.userApprovalVerbatim,timestamp:new Date().toISOString()};if(context.sessionID?.trim())receipt.sessionId=context.sessionID.trim();let validatedPath;try{validatedPath=validateSwarmPath(directory,"merge-approval.json")}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:"Failed to validate path"})}try{return await atomicWriteSwarmFile(validatedPath,JSON.stringify(receipt,null,2)),JSON.stringify({success:!0,issueNumber:data.issueNumber,path:".swarm/merge-approval.json",message:`Merge approval recorded for issue #${data.issueNumber}, bound to PR head ${data.prHeadSha}. The approval is captured verbatim for audit; the merge itself is human-enforced and this plugin neither drives nor certifies it.`})}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:String(error93)})}}var record_merge_approval=createSwarmTool({description:"Record the human merge approval for the current traced issue (issue #2564): prHeadSha and finalCriticReviewedCommit must be the same 40-hex SHA (the final critic approval bound to the exact PR head), and userApprovalVerbatim is the user approval quoted verbatim. The receipt is recorded for audit only — the merge stays human-enforced and the plugin never certifies or drives it.",args:{issueNumber:RecordMergeApprovalArgsSchema.shape.issueNumber,prHeadSha:RecordMergeApprovalArgsSchema.shape.prHeadSha,finalCriticReviewedCommit:RecordMergeApprovalArgsSchema.shape.finalCriticReviewedCommit,userApprovalVerbatim:RecordMergeApprovalArgsSchema.shape.userApprovalVerbatim},execute:executeRecordMergeApproval});init_zod();init_utils2();init_atomic_write();init_create_tool();var DispositionSchema=exports_external.object({ref:exports_external.string().trim().min(1).max(500),disposition:exports_external.enum(["FIX","FALSE_POSITIVE","OUT_OF_CLASS","DEFERRED_WITH_USER_APPROVAL"]),note:exports_external.string().trim().max(1000).optional()}).strict(),GuardrailSchema=exports_external.object({kind:exports_external.enum(["lint-static-analysis","type-level","runtime-assertion","ci-check","documented-invariant-plus-regression-test"]),description:exports_external.string().trim().min(8).max(2000),proof:exports_external.string().trim().min(8).max(4000)}).strict(),RelatedProblemSchema=exports_external.object({ref:exports_external.string().trim().min(1).max(500),note:exports_external.string().trim().max(1000).optional()}).strict(),RecordRecurrenceSweepArgsSchema=exports_external.object({issueNumber:exports_external.number().int().min(1),defectClass:exports_external.string().trim().min(1).max(1000),justification:exports_external.string().trim().min(1).max(1000).optional(),predicates:exports_external.array(exports_external.string().trim().min(1).max(500)).min(1).max(32).optional(),dispositions:exports_external.array(DispositionSchema).max(200).optional(),guardrail:GuardrailSchema.optional(),relatedProblems:exports_external.array(RelatedProblemSchema).min(1).max(200)}).strict();async function executeRecordRecurrenceSweep(args2,directory,context={}){let parsed=RecordRecurrenceSweepArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,message:`Invalid recurrence sweep receipt: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`});let data=parsed.data,noDefectClass=data.defectClass==="no defect class";if(noDefectClass){if(!data.justification)return JSON.stringify({success:!1,message:'The "no defect class" fast path requires a one-line justification.'})}else if(!data.predicates||data.predicates.length===0||!data.dispositions||!data.guardrail)return JSON.stringify({success:!1,message:"A defect-class sweep requires search predicates, a disposition for every hit, and a guardrail with proof it catches the original defect."});let receipt={issueNumber:data.issueNumber,defectClass:data.defectClass,timestamp:new Date().toISOString()};if(data.justification)receipt.justification=data.justification;if(data.predicates)receipt.predicates=data.predicates;if(data.dispositions)receipt.dispositions=data.dispositions;if(data.guardrail)receipt.guardrail=data.guardrail;if(receipt.relatedProblems=data.relatedProblems,context.sessionID?.trim())receipt.sessionId=context.sessionID.trim();let validatedPath;try{validatedPath=validateSwarmPath(directory,"recurrence-sweep.json")}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:"Failed to validate path"})}try{return await atomicWriteSwarmFile(validatedPath,JSON.stringify(receipt,null,2)),JSON.stringify({success:!0,issueNumber:data.issueNumber,path:".swarm/recurrence-sweep.json",message:noDefectClass?`Recurrence sweep recorded for issue #${data.issueNumber} (no defect class fast path).`:`Recurrence sweep recorded for issue #${data.issueNumber}; the trace may now satisfy its recurrence gate.`})}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:String(error93)})}}var record_recurrence_sweep=createSwarmTool({description:'Record the recurrence sweep for the current traced issue (issue #2131 residual B; widened in #2564). The /swarm issue --trace workflow will not hand off to commit-pr until this receipt exists. Supply relatedProblems (the Phase 1 related-problems sweep results — at least one {ref, note?} entry) plus, for a real defect class: defectClass (one-sentence characterization), predicates (the exact search predicates), dispositions (every hit as FIX / FALSE_POSITIVE / OUT_OF_CLASS / DEFERRED_WITH_USER_APPROVAL), and a guardrail (kind + description + proof it catches the original defect). If the change corrects no incorrect behavior, use the literal defectClass "no defect class" with a one-line justification (relatedProblems still required).',args:{issueNumber:RecordRecurrenceSweepArgsSchema.shape.issueNumber,defectClass:RecordRecurrenceSweepArgsSchema.shape.defectClass,justification:RecordRecurrenceSweepArgsSchema.shape.justification,predicates:RecordRecurrenceSweepArgsSchema.shape.predicates,dispositions:RecordRecurrenceSweepArgsSchema.shape.dispositions,guardrail:RecordRecurrenceSweepArgsSchema.shape.guardrail,relatedProblems:RecordRecurrenceSweepArgsSchema.shape.relatedProblems},execute:executeRecordRecurrenceSweep});init_zod();import*as fs208 from"node:fs";init_utils2();init_file_locks();init_atomic_write();init_create_tool();var HEX402=/^[0-9a-f]{40}$/,TRACE_VALIDATION_PHASES2=["0","1","2","2.5","3","4","4.2","4.5","4.6","5"],ValidationEntrySchema=exports_external.object({phase:exports_external.enum(TRACE_VALIDATION_PHASES2),outcome:exports_external.enum(["pass","fail"]),reviewedCommit:exports_external.string().regex(HEX402,"must be a 40-hex commit SHA"),treeId:exports_external.string().regex(HEX402,"must be a 40-hex tree id")}).strict(),RecordTraceValidationArgsSchema=ValidationEntrySchema.extend({issueNumber:exports_external.number().int().min(1)}).strict();async function executeRecordTraceValidation(args2,directory,context={}){let parsed=RecordTraceValidationArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,message:`Invalid trace-validation receipt: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`});let data=parsed.data,validatedPath;try{validatedPath=validateSwarmPath(directory,"trace-validation.json")}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:"Failed to validate path"})}try{let lockResult=await tryAcquireLock(directory,"trace-validation.json","trace-validation","trace-validation");if(!lockResult.acquired)return JSON.stringify({success:!1,message:"The trace-validation receipt is locked by another concurrent writer; no write was attempted. Re-run record_trace_validation for this phase once the other writer finishes."});try{let validations=[];try{let raw=await fs208.promises.readFile(validatedPath,"utf-8"),existing=JSON.parse(raw);if(typeof existing==="object"&&existing!==null&&Array.isArray(existing.validations))validations=existing.validations.filter((v)=>typeof v==="object"&&v!==null&&typeof v.phase==="string")}catch{}let entry={phase:data.phase,outcome:data.outcome,reviewedCommit:data.reviewedCommit,treeId:data.treeId,timestamp:new Date().toISOString()},idx=validations.findIndex((v)=>v.phase===data.phase);if(idx===-1)validations.push(entry);else validations[idx]=entry;let receipt={issueNumber:data.issueNumber,timestamp:new Date().toISOString(),validations};if(context.sessionID?.trim())receipt.sessionId=context.sessionID.trim();await atomicWriteSwarmFile(validatedPath,JSON.stringify(receipt,null,2));let allGreen=await traceValidationReceiptExists(directory,data.issueNumber);return JSON.stringify({success:!0,issueNumber:data.issueNumber,path:".swarm/trace-validation.json",allGreen,message:allGreen?`Validator receipt recorded for issue #${data.issueNumber} phase ${data.phase} (${data.outcome}); every recorded phase is green.`:`Validator receipt recorded for issue #${data.issueNumber} phase ${data.phase} (${data.outcome}), but at least one recorded phase is failing — fix and re-record that phase as a pass before handoff.`})}finally{try{await lockResult.lock._release?.()}catch{}}}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:String(error93)})}}var record_trace_validation=createSwarmTool({description:"Record one per-phase trace-check.sh validator outcome for the current traced issue (issue #2564): the phase (v3 enum 0..5 incl. 2.5/4.2/4.5/4.6), the outcome (pass or fail), and the exact reviewedCommit and treeId the validator reported. Re-running a phase replaces its entry. The /swarm issue --trace workflow will not hand off to commit-pr while any recorded phase is failing or none is recorded. The receipt write is serialized by a per-file receipt lock, and the response's allGreen field mirrors the gate reader's verdict on the persisted receipt (advisory for the calling agent — the reducer always recomputes it independently).",args:{issueNumber:RecordTraceValidationArgsSchema.shape.issueNumber,phase:RecordTraceValidationArgsSchema.shape.phase,outcome:RecordTraceValidationArgsSchema.shape.outcome,reviewedCommit:RecordTraceValidationArgsSchema.shape.reviewedCommit,treeId:RecordTraceValidationArgsSchema.shape.treeId},execute:executeRecordTraceValidation});init_zod();init_schema();init_gate_evidence();init_manager();init_path_identity();init_state2();init_stage_a_repair();import*as fs209 from"node:fs";import*as path345 from"node:path";async function forceRecoverReworkTask(directory,sessionID,options){let session=ensureAgentSession(sessionID,void 0,directory);if(!session||!session.agentName||stripKnownSwarmPrefix(session.agentName)!=="architect")throw Error("RECOVER_REWORK_ARCHITECT_REQUIRED: recover_rework_task requires an active architect session. The rework escape hatch is architect-only; a coder/reviewer/test_engineer cannot self-unblock a task.");let taskId=typeof options.taskId==="string"?options.taskId.trim():"";if(!taskId)throw Error('RECOVER_REWORK_UNKNOWN_TASK: recover_rework_task requires the exact plan task id (e.g. "1.1").');let plan=await loadPlanJsonOnly(directory);if(!plan){let planPath=path345.join(directory,".swarm","plan.json");if(fs209.existsSync(planPath))throw Error("PLAN_CORRUPT: .swarm/plan.json exists but could not be parsed (corrupt or schema-invalid). Repair or re-save the plan before recovering a rework_required task.");throw Error("PLAN_NOT_FOUND: no .swarm/plan.json — cannot recover a rework_required "+"task without a plan. Save a plan first.")}if(!new Set(plan.phases.flatMap((phase)=>phase.tasks.map((task2)=>task2.id))).has(taskId))throw Error(`RECOVER_REWORK_UNKNOWN_TASK: task ${taskId} is not in the current plan. Refusing to recover a foreign task id.`);let evidenceRead=await readTaskEvidenceState(directory,taskId);if(evidenceRead.kind==="unparseable")throw Error(`RECOVER_REWORK_EVIDENCE_CORRUPT: the workflow evidence file for task ${taskId} exists but could not be parsed (${evidenceRead.evidencePath}). Repair the evidence first (repair_gate_evidence or /swarm doctor); recovery cannot classify a corrupt evidence state.`);let evidence2=evidenceRead.kind==="ok"?evidenceRead.evidence:null,workflow=getTaskWorkflowSnapshot(evidence2);if(!evidence2||!workflow.authoritative)throw Error(`RECOVER_REWORK_NO_WORKFLOW: no durable task workflow evidence exists for task ${taskId} — there is no rework state to recover.`);if(workflow.state!=="rework_required")throw Error(`RECOVER_REWORK_STATE_REQUIRED: task ${taskId} is at ${workflow.state}, not rework_required. This recovery applies only to a task whose Stage B verdict moved it to rework_required without a code change. From coder_delegated, run pre_check_batch; for a genuine code defect, delegate the coder to repair it first.`);let wedgeMs=Date.parse(workflow.updatedAt);if(!Number.isFinite(wedgeMs))throw Error(`RECOVER_REWORK_GREEN_PRECHECK_REQUIRED: cannot prove pre-check recency (workflow updatedAt "${workflow.updatedAt}" is not a parseable timestamp — the evidence file for task ${taskId} is likely corrupt). Repair the evidence (repair_gate_evidence or /swarm doctor); re-running pre_check_batch cannot fix an unparseable timestamp.`);let greenness=await hasGreenPostSettlementPreCheck(directory,wedgeMs);if(!greenness.green){let sastHint=greenness.reason==="no_pre_check_bundles"?" Note: if gates.sast_scan.enabled is false, no sast_scan bundle is ever persisted and this recovery is unavailable by design — enable gates.sast_scan.enabled and run sast_scan, or use the coder repair loop.":"";throw Error(`RECOVER_REWORK_GREEN_PRECHECK_REQUIRED: refusing to mark Stage A passed without proof (${greenness.reason}). `+"The bar is a green secretscan AND sast_scan evidence pair newer than the failing verdict — normally provided by a fresh pre_check_batch run (bundle proof is global, not correlated to the task's changed files)."+sastHint)}let sanitizedReason=typeof options.reason==="string"&&options.reason.trim().length>0?sanitizeDiagnosticText(options.reason.trim(),500):void 0,recordedAt=new Date().toISOString(),transitionId=`rework-recovery:${taskId}:gen${workflow.generation}`,updated=await transitionTaskWorkflowEvidence(directory,taskId,{type:"stage_a_passed",supervisedRecovery:!0,expectedGeneration:workflow.generation,transitionId}),updatedWorkflow=getTaskWorkflowSnapshot(updated),auditEventRecorded=await appendStageARepairEvent(directory,{action:"rework_recovered",taskId,transitionId,generation:workflow.generation,sessionId:sessionID,...sanitizedReason?{reason:sanitizedReason}:{}});return{taskId,generation:updatedWorkflow.generation,state:updatedWorkflow.state,transitionId,recordedAt,auditEventRecorded}}init_create_tool();var RecoverReworkTaskArgsSchema=exports_external.object({task_id:exports_external.string().trim().min(1).max(64).describe('Exact plan task id of the rework_required task (e.g. "1.1"). Must exist in the current plan and have durable workflow evidence at state rework_required.'),reason:exports_external.string().trim().min(1).max(500).describe('Why the Stage B verdict did not require a code change (e.g. "test_engineer returned SKIPPED for a tool-argument error while pytest passes"). Audited to .swarm/events.jsonl.')}).strict();async function executeRecoverReworkTask(args2,directory,context={}){let parsed=RecoverReworkTaskArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,message:`Invalid recover_rework_task call: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`});if(!context.sessionID?.trim())return JSON.stringify({success:!1,message:"recover_rework_task requires an active sessionID"});try{let summary=await forceRecoverReworkTask(directory,context.sessionID,{taskId:parsed.data.task_id,reason:parsed.data.reason}),auditNote=summary.auditEventRecorded?"The recovery is audited to .swarm/events.jsonl (stage_a_repair action rework_recovered).":"WARNING: the audit event could NOT be appended to .swarm/events.jsonl (see the plugin log); the durable workflow evidence still records the supervised recovery via the rework-recovery: transition id.";return JSON.stringify({success:!0,task_id:summary.taskId,generation:summary.generation,state:summary.state,transition_id:summary.transitionId,recorded_at:summary.recordedAt,audit_event_recorded:summary.auditEventRecorded,method:"supervised_recovery",message:`Task ${summary.taskId} recovered from rework_required: a supervised stage_a_passed was written at generation ${summary.generation} (transition id `+summary.transitionId+"). Reviewer/test_engineer dispatch is permitted again — re-run the Stage B gates that the failed verdict cleared. "+auditNote+" Use it ONLY when the Stage B verdict did not require a code change; a genuine defect still needs the coder repair loop."})}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:String(error93)})}}var recover_rework_task=createSwarmTool({description:"Recover a task wedged at rework_required when the Stage B verdict did NOT require a code change (issue #2755): writes a supervised stage_a_passed for the current generation so reviewer/test_engineer can be re-dispatched, without re-running the coder. Requires the exact plan task id, an active architect session, durable workflow state exactly rework_required, and green pre-check proof: green secretscan AND sast_scan evidence bundles newer than the failing verdict (normally from a fresh pre_check_batch run; bundle recency is global, not file-correlated; projects with SAST disabled cannot use this path). Fail-closed otherwise; the mechanical stage_a_passed path still requires an accepted coder mutation. A reason is required and audited to .swarm/events.jsonl (stage_a_repair action rework_recovered). Prefer the coder repair loop when the code actually has a defect.",args:{task_id:RecoverReworkTaskArgsSchema.shape.task_id,reason:RecoverReworkTaskArgsSchema.shape.reason},execute:executeRecoverReworkTask});init_zod();init_schema();init_gate_evidence();init_path_identity();init_state2();init_coder_settlement();init_stage_a_repair();async function recoverStageATaskSupervised(directory,sessionID,options){let session=ensureAgentSession(sessionID,void 0,directory);if(!session||!session.agentName||stripKnownSwarmPrefix(session.agentName)!=="architect")throw Error("RECOVER_STAGE_A_ARCHITECT_REQUIRED: recover_stage_a_task requires an active architect session. The settlement-backed Stage A escape hatch is architect-only; a coder/reviewer/test_engineer cannot self-unblock a task.");let taskId=typeof options.taskId==="string"?options.taskId.trim():"";if(!taskId)throw Error('RECOVER_STAGE_A_UNKNOWN_TASK: recover_stage_a_task requires the exact task id of the settlement-wedged task (e.g. "1.1").');let sanitizedReason=typeof options.reason==="string"&&options.reason.trim().length>0?sanitizeDiagnosticText(options.reason.trim(),500):void 0;if(!sanitizedReason)throw Error("RECOVER_STAGE_A_REASON_REQUIRED: recover_stage_a_task requires a reason describing why the settlement-backed recovery is justified; it is audited to .swarm/events.jsonl.");let evidenceRead=await readTaskEvidenceState(directory,taskId);if(evidenceRead.kind==="unparseable")throw Error(`RECOVER_STAGE_A_EVIDENCE_CORRUPT: the workflow evidence file for task ${taskId} exists but could not be parsed (${evidenceRead.evidencePath}). Repair the evidence first (repair_gate_evidence or /swarm doctor); recovery cannot classify a corrupt evidence state.`);let evidence2=evidenceRead.kind==="ok"?evidenceRead.evidence:null,workflow=getTaskWorkflowSnapshot(evidence2);if(!evidence2||!workflow.authoritative)throw Error(`RECOVER_STAGE_A_NO_WORKFLOW: no durable task workflow evidence exists for task ${taskId} — there is no settlement wedge to recover.`);if(workflow.state==="pre_check_passed"||workflow.state==="reviewer_run"||workflow.state==="tests_run")return{taskId,generation:workflow.generation,state:workflow.state,transitionId:`stage-a-supervised:${taskId}:noop`,recordedAt:new Date().toISOString(),alreadyRecovered:!0,auditEventRecorded:!1};if(workflow.state!=="idle"&&workflow.state!=="blocked")throw Error(`RECOVER_STAGE_A_STATE_REQUIRED: task ${taskId} is at ${workflow.state}, not idle/blocked. This recovery applies only to the settlement-backed wedge (a COMMITTED accepted coder settlement while the workflow drifted to idle or blocked). From coder_delegated, run pre_check_batch or /swarm recover; from rework_required without a code change, use recover_rework_task.`);let{states:walStates}=await listCoderSettlementWalStates(directory),settledAfterMs=latestCommittedAcceptedSettlementMs(taskId,walStates);if(settledAfterMs===null)throw Error(`RECOVER_STAGE_A_SETTLEMENT_REQUIRED: refusing to recover task ${taskId} — no COMMITTED accepted coder settlement exists for it. `+"The settlement receipt is what distinguishes this wedge from a not-yet-started or deliberately stopped task; recovery without it would fabricate Stage A justification. Background-dispatched coder tasks never write a settlement WAL and cannot use this path.");let greenness=await hasGreenPostSettlementPreCheck(directory,settledAfterMs);if(!greenness.green){let sastHint=greenness.reason==="no_pre_check_bundles"?" Note: if gates.sast_scan.enabled is false, no sast_scan bundle is ever persisted and this recovery is unavailable by design — enable gates.sast_scan.enabled and run sast_scan, or use the coder repair loop.":"";throw Error(`RECOVER_STAGE_A_GREEN_PRECHECK_REQUIRED: refusing to mark Stage A passed without proof (${greenness.reason}). `+"The bar is a green secretscan AND sast_scan evidence pair newer than the settlement commit — normally provided by a fresh pre_check_batch run (bundle proof is global, not correlated to the task's changed files)."+sastHint)}let recordedAt=new Date().toISOString(),transitionId=`stage-a-supervised:${taskId}:${workflow.generation}`,updated=await transitionTaskWorkflowEvidence(directory,taskId,{type:"stage_a_passed",settlementRecovery:!0,expectedGeneration:workflow.generation,transitionId}),updatedWorkflow=getTaskWorkflowSnapshot(updated),auditEventRecorded=await appendStageARepairEvent(directory,{action:"repaired",via:"recover_stage_a_task",taskId,transitionId,generation:workflow.generation,settlementRecovery:!0,predecessorTransitionId:workflow.lastTransitionId??null,sessionId:sessionID,reason:sanitizedReason});return{taskId,generation:updatedWorkflow.generation,state:updatedWorkflow.state,transitionId,recordedAt,alreadyRecovered:!1,auditEventRecorded}}init_create_tool();var RecoverStageATaskArgsSchema=exports_external.object({task_id:exports_external.string().trim().min(1).max(64).describe('Exact task id of the settlement-wedged task (e.g. "1.1"). Must have durable workflow evidence at state idle or blocked, a COMMITTED accepted coder settlement, and green post-settlement pre-check proof.'),reason:exports_external.string().trim().min(1).max(500).describe('Why the settlement-backed recovery is justified (e.g. "settlement COMMITTED and pre_check_batch green but stage_a_passed never fired; force-repair cleared the proofs"). Audited to .swarm/events.jsonl.')}).strict();async function executeRecoverStageATask(args2,directory,context={}){let parsed=RecoverStageATaskArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,message:`Invalid recover_stage_a_task call: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`});if(!context.sessionID?.trim())return JSON.stringify({success:!1,message:"recover_stage_a_task requires an active sessionID"});try{let summary=await recoverStageATaskSupervised(directory,context.sessionID,{taskId:parsed.data.task_id,reason:parsed.data.reason});if(summary.alreadyRecovered)return JSON.stringify({success:!0,task_id:summary.taskId,generation:summary.generation,state:summary.state,already_recovered:!0,message:`Task ${summary.taskId} already has Stage A recorded (state ${summary.state}, generation ${summary.generation}) — nothing to recover.`});let auditNote=summary.auditEventRecorded?"The recovery is audited to .swarm/events.jsonl (stage_a_repair action repaired, via recover_stage_a_task).":"WARNING: the audit event could NOT be appended to .swarm/events.jsonl (see the plugin log); the durable workflow evidence still records the settlement-backed recovery via the stage-a-supervised: transition id and the settlementRecovery marker.";return JSON.stringify({success:!0,task_id:summary.taskId,generation:summary.generation,state:summary.state,transition_id:summary.transitionId,recorded_at:summary.recordedAt,audit_event_recorded:summary.auditEventRecorded,method:"settlement_recovery",message:`Task ${summary.taskId} recovered from the settlement wedge: a settlement-backed stage_a_passed was written at generation ${summary.generation} (transition id `+summary.transitionId+"). Reviewer/test_engineer dispatch is permitted again — run the Stage B gates the task still needs. "+auditNote+" Use it ONLY when a COMMITTED accepted settlement and green post-settlement pre-check proof already justify Stage A; it never re-runs the coder and never edits gate evidence."})}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:String(error93)})}}var recover_stage_a_task=createSwarmTool({description:"Recover a task wedged in the settlement-backed Stage A deadlock (issue #2828): workflow at idle or blocked while a COMMITTED accepted coder settlement and green post-settlement pre-check proof (green secretscan AND sast_scan evidence newer than the settlement commit) still justify Stage A — the shape where stage_a_passed never fired, a force-repair cleared the proofs, and every other recovery path refuses. Writes a settlement-backed stage_a_passed for the current generation so reviewer/test_engineer can be dispatched, without re-running the coder and without editing gate evidence. Requires the exact task id (bound by its durable workflow evidence and settlement WAL — deliberately no plan-membership precondition, mirroring the /swarm recover scan), an active architect session, a reason (audited), and durable workflow evidence at exactly idle/blocked. Fail-closed otherwise (RECOVER_STAGE_A_* errors); the mechanical stage_a_passed path still requires an accepted coder mutation or the #2665 live_wedge scan.",args:{task_id:RecoverStageATaskArgsSchema.shape.task_id,reason:RecoverStageATaskArgsSchema.shape.reason},execute:executeRecoverStageATask});init_zod();init_schema();init_gate_evidence();init_utils2();init_manager();init_state2();init_project_boundary();init_swarm_artifact_cache();init_task_id();init_task_file();init_task_gate_requirements();init_gate_evidence();import{createHash as createHash111,randomUUID as randomUUID47}from"node:crypto";import*as fs210 from"node:fs";import*as path346 from"node:path";var TASK_GATE_EVIDENCE_QUARANTINE_DIR=path346.join("evidence","task-gate-quarantine"),MAX_TASK_GATE_EVIDENCE_BYTES=262144,MAX_TASK_GATE_EVIDENCE_QUARANTINE_FILES=32,MAX_TASK_GATE_EVIDENCE_QUARANTINE_BYTES=12582912,MAX_TASK_GATE_EVIDENCE_QUARANTINE_DIRECTORY_ENTRIES=128,MAX_TASK_GATE_EVIDENCE_QUARANTINE_RECORD_BYTES=786432,TASK_GATE_EVIDENCE_QUARANTINE_SCHEMA_VERSION=1,GENERIC_REPAIR_REASONS=new Set(["fix","repair","test","debug","unknown","n/a","na","none"]);function isQuarantinableTaskEvidenceRead(read){return read.status==="corrupt"||read.status==="valid"}function sha25612(bytes){return createHash111("sha256").update(bytes).digest("hex")}function normalizeRepairReason(reason){let normalized=reason.trim().replace(/\s+/g," ");if(normalized.length<12)throw Error("TASK_GATE_EVIDENCE_REASON_REQUIRED: repair_gate_evidence requires a substantive reason of at least 12 characters.");if(GENERIC_REPAIR_REASONS.has(normalized.toLowerCase()))throw Error("TASK_GATE_EVIDENCE_REASON_REQUIRED: repair_gate_evidence requires a substantive reason, not a placeholder.");return normalized}function canonicalizeRepairRoot(directory){let requestedRoot=path346.resolve(directory),requestedStat=fs210.lstatSync(requestedRoot);if(requestedStat.isSymbolicLink()||!requestedStat.isDirectory())throw Error("TASK_GATE_EVIDENCE_ROOT_UNSAFE: repair_gate_evidence requires a canonical project root directory, not a symlink, junction, reparse point, or non-directory path.");let canonicalRoot2=fs210.realpathSync(requestedRoot);return assertProjectRoot(canonicalRoot2),canonicalRoot2}function assertExistingRegularPath(root,relativePath2){let segments=relativePath2.replace(/\\/g,"/").split("/").filter(Boolean),cursor=root;for(let segment of segments){if(cursor=path346.join(cursor,segment),!fs210.existsSync(cursor))return;if(fs210.lstatSync(cursor).isSymbolicLink())throw Error(`TASK_GATE_EVIDENCE_PATH_UNSAFE: ${relativePath2} contains a symlink, junction, or reparse point.`)}}function taskEvidenceFilePath(directory,taskId){let relativePath2=taskEvidenceRelPath(taskId);return assertExistingRegularPath(directory,".swarm"),assertExistingRegularPath(directory,path346.join(".swarm","evidence")),assertExistingRegularPath(directory,path346.join(".swarm",relativePath2)),validateSwarmPath(directory,relativePath2)}function readTaskEvidenceForRepair(directory,taskId){let filePath=taskEvidenceFilePath(directory,taskId),pathStat;try{pathStat=fs210.lstatSync(filePath)}catch(error93){if(error93.code==="ENOENT")return{status:"missing"};return{status:"unreadable",filePath,bytes:Buffer.alloc(0),sha256:sha25612(""),error:error93}}if(pathStat.isSymbolicLink()||!pathStat.isFile())return{status:"unreadable",filePath,bytes:Buffer.alloc(0),sha256:sha25612(""),error:Error("TASK_GATE_EVIDENCE_UNREADABLE: evidence path is not a regular file")};if(pathStat.size>MAX_TASK_GATE_EVIDENCE_BYTES)return{status:"oversized",filePath,bytes:Buffer.alloc(0),sha256:sha25612(""),error:Error(`TASK_GATE_EVIDENCE_OVERSIZED: ${pathStat.size} bytes exceeds ${MAX_TASK_GATE_EVIDENCE_BYTES}`)};let descriptor=fs210.openSync(filePath,fs210.constants.O_RDONLY|(fs210.constants.O_NOFOLLOW??0));try{let openedStat=fs210.fstatSync(descriptor);if(!openedStat.isFile()||openedStat.dev!==pathStat.dev||openedStat.ino!==pathStat.ino)return{status:"unreadable",filePath,bytes:Buffer.alloc(0),sha256:sha25612(""),error:Error("TASK_GATE_EVIDENCE_UNREADABLE: evidence changed while being opened")};let bytes=fs210.readFileSync(descriptor);if(bytes.byteLength>MAX_TASK_GATE_EVIDENCE_BYTES)return{status:"oversized",filePath,bytes:Buffer.alloc(0),sha256:sha25612(""),error:Error(`TASK_GATE_EVIDENCE_OVERSIZED: ${bytes.byteLength} bytes exceeds ${MAX_TASK_GATE_EVIDENCE_BYTES}`)};let digest5=sha25612(bytes);try{let evidence2=parseTaskEvidence(bytes.toString("utf8"),taskId);return{status:"valid",filePath,bytes,sha256:digest5,evidence:evidence2,generation:evidence2.workflow?.generation}}catch(error93){return{status:"corrupt",filePath,bytes,sha256:digest5,error:error93}}}finally{try{fs210.closeSync(descriptor)}catch{}}}function taskGateEvidenceQuarantinePath(directory,taskId,digest5){return validateSwarmPath(directory,path346.join(TASK_GATE_EVIDENCE_QUARANTINE_DIR,`${taskId}.${digest5}.v${TASK_GATE_EVIDENCE_QUARANTINE_SCHEMA_VERSION}.json`))}function parseErrorMetadata(error93){if(!error93)return null;return{name:error93.name||"Error",message:error93.message||String(error93),code:typeof error93.code==="string"?error93.code:null}}function parseQuarantineRecord(raw){try{let parsed=JSON.parse(raw);if(parsed?.schemaVersion!==TASK_GATE_EVIDENCE_QUARANTINE_SCHEMA_VERSION||typeof parsed.taskId!=="string"||typeof parsed.recordedAt!=="string"||typeof parsed.reason!=="string"||typeof parsed.original?.path!=="string"||typeof parsed.original?.sha256!=="string"||typeof parsed.content?.bytes!=="string"||parsed.content?.encoding!=="base64")return null;return parsed}catch{return null}}function buildQuarantineRecord(taskId,read,reason,context,receiptGeneration){let agentName=context?.sessionID!=null?swarmState.activeAgent.get(context.sessionID)??swarmState.agentSessions.get(context.sessionID)?.agentName??null:null;return{schemaVersion:TASK_GATE_EVIDENCE_QUARANTINE_SCHEMA_VERSION,taskId,recordedAt:new Date().toISOString(),reason,caller:{sessionId:context?.sessionID?.trim()||null,messageId:context?.messageID?.trim()||null,agentName},original:{path:read.filePath,sha256:read.sha256,sizeBytes:read.bytes.byteLength,status:read.status,observedGeneration:read.generation??null,receiptGeneration,requirementsState:read.evidence?.requirements_state??null},parseError:parseErrorMetadata(read.error),content:{encoding:"base64",bytes:read.bytes.toString("base64")}}}async function quarantineTaskEvidenceBytes(directory,taskId,read,reason,context,receiptGeneration){let digest5=read.sha256,quarantineDir=validateSwarmPath(directory,TASK_GATE_EVIDENCE_QUARANTINE_DIR);await fs210.promises.mkdir(quarantineDir,{recursive:!0});let dirStat=await fs210.promises.lstat(quarantineDir);if(dirStat.isSymbolicLink()||!dirStat.isDirectory())throw Error("TASK_GATE_EVIDENCE_QUARANTINE_UNREADABLE: quarantine is not a regular directory");let target=taskGateEvidenceQuarantinePath(directory,taskId,digest5),record3=buildQuarantineRecord(taskId,read,reason,context,receiptGeneration),serialized3=JSON.stringify(record3,null,2),serializedBytes=Buffer.byteLength(serialized3,"utf8");if(serializedBytes>MAX_TASK_GATE_EVIDENCE_QUARANTINE_RECORD_BYTES)throw Error("TASK_GATE_EVIDENCE_QUARANTINE_FULL: quarantine payload exceeds the bounded record size limit");let reconcileExisting=async()=>{let existingStat;try{existingStat=await fs210.promises.lstat(target)}catch(error93){if(error93.code==="ENOENT")return!1;throw error93}if(existingStat.isSymbolicLink()||!existingStat.isFile())throw Error("TASK_GATE_EVIDENCE_QUARANTINE_MISMATCH: existing quarantine path is not a regular immutable record");let existingRaw=await fs210.promises.readFile(target,"utf8"),existingRecord=parseQuarantineRecord(existingRaw);if(existingRecord&&existingRecord.taskId===taskId&&existingRecord.original.path===read.filePath&&existingRecord.original.sha256===read.sha256&&existingRecord.content.bytes===read.bytes.toString("base64"))return!0;throw Error("TASK_GATE_EVIDENCE_QUARANTINE_MISMATCH: existing quarantine record does not match the repaired evidence source")};if(await reconcileExisting())return{digest:digest5,filePath:target};let count=0,totalBytes=0,scanned=0,handle=await fs210.promises.opendir(quarantineDir,{bufferSize:16});try{for await(let entry of handle){if(scanned+=1,scanned>MAX_TASK_GATE_EVIDENCE_QUARANTINE_DIRECTORY_ENTRIES)throw Error("TASK_GATE_EVIDENCE_QUARANTINE_FULL: too many quarantine entries");if(!entry.isFile()||!/^[0-9.]+\.[a-f0-9]{64}\.v1\.json$/.test(entry.name))continue;count+=1;let candidate2=path346.join(quarantineDir,entry.name),candidateStat=await fs210.promises.lstat(candidate2);if(candidateStat.isSymbolicLink()||!candidateStat.isFile())throw Error("TASK_GATE_EVIDENCE_QUARANTINE_UNREADABLE: invalid quarantine artifact");if(totalBytes+=candidateStat.size,count>=MAX_TASK_GATE_EVIDENCE_QUARANTINE_FILES||totalBytes+serializedBytes>MAX_TASK_GATE_EVIDENCE_QUARANTINE_BYTES)throw Error("TASK_GATE_EVIDENCE_QUARANTINE_FULL: quarantine retention limit reached")}}finally{try{await handle.close()}catch{}}let tempPath=path346.join(quarantineDir,`.pending.${process.pid}.${randomUUID47()}.json`),fileHandle;try{fileHandle=await fs210.promises.open(tempPath,"wx"),await fileHandle.writeFile(serialized3,"utf8"),await fileHandle.sync(),await fileHandle.close(),fileHandle=void 0,invalidateCachedArtifact(tempPath),await fs210.promises.link(tempPath,target),invalidateCachedArtifact(target)}catch(error93){if(error93.code!=="EEXIST")throw error93;if(await reconcileExisting())return{digest:digest5,filePath:target};throw error93}finally{await fileHandle?.close().catch(()=>{return}),await fs210.promises.unlink(tempPath).catch(()=>{return})}return{digest:digest5,filePath:target}}function buildRepairTransitionId(taskId,source){return`repair_gate_evidence:${taskId}:${source.slice(0,32)}`}function withoutLegacyReconstructionGate(gates){return[...new Set(gates.filter((gate)=>gate!==TASK_GATE_REQUIREMENTS_RECONSTRUCTION_SENTINEL))].sort()}function hasLegacyReconstructionGate(gates){return gates.includes(TASK_GATE_REQUIREMENTS_RECONSTRUCTION_SENTINEL)}function buildKnownRepairedEvidence(taskId,receipt,generation,source){let requiredGates=withoutLegacyReconstructionGate(receipt.requiredGates);if(requiredGates.length!==receipt.requiredGates.length)throw Error("TASK_GATE_REQUIREMENTS_RECEIPT_TAINTED: legacy reconstruction markers cannot seed known requirements.");return{taskId,required_gates:requiredGates,gates:{},requirements_state:"known",test_engineer_exempt:receipt.testEngineerExempt??void 0,workflow:{schema:TASK_WORKFLOW_SCHEMA_MARKER,generation,state:"idle",retryCount:0,retryHistory:[],retryEpoch:0,lastOutcome:"repair_idle",lastTransitionId:buildRepairTransitionId(taskId,receipt.chainHash),updatedAt:new Date().toISOString()},repair_provenance:{source_sha256:source.sha256,source_generation:source.generation,requirements_receipt_hash:receipt.chainHash}}}function buildUnknownRepairedEvidence(taskId,requiredGates,seedGeneration,source,receiptHash){return{taskId,required_gates:withoutLegacyReconstructionGate(requiredGates),gates:{},requirements_state:"unknown",workflow:{schema:TASK_WORKFLOW_SCHEMA_MARKER,generation:seedGeneration,state:"idle",retryCount:0,retryHistory:[],retryEpoch:0,lastOutcome:"repair_idle",lastTransitionId:buildRepairTransitionId(taskId,"unknown"),updatedAt:new Date().toISOString()},repair_provenance:{source_sha256:source.sha256,source_generation:source.generation,requirements_receipt_hash:receiptHash}}}function canonicalizeTaskEvidence(taskId,evidence2){let validated=parseTaskEvidence(JSON.stringify({...evidence2,taskId}),taskId);return JSON.stringify(validated,null,2)}function isRepairWorkflowReset(taskId,workflow){return workflow!=null&&workflow.state==="idle"&&workflow.retryCount===0&&workflow.retryEpoch===0&&workflow.retryHistory.length===0&&workflow.lastOutcome==="repair_idle"&&typeof workflow.lastTransitionId==="string"&&workflow.lastTransitionId.startsWith(`repair_gate_evidence:${taskId}:`)}function isReceiptlessLegacySentinelReset(taskId,evidence2){return evidence2!=null&&isRepairWorkflowReset(taskId,evidence2.workflow)&&evidence2.requirements_state==="unknown"&&evidence2.required_gates.length===1&&evidence2.required_gates[0]===TASK_GATE_REQUIREMENTS_RECONSTRUCTION_SENTINEL&&Object.keys(evidence2.gates).length===0&&evidence2.repair_provenance!=null&&typeof evidence2.repair_provenance.source_sha256==="string"&&(evidence2.repair_provenance.source_generation===null||evidence2.repair_provenance.source_generation<evidence2.workflow.generation)&&evidence2.repair_provenance.requirements_receipt_hash===null}function isAlreadyRepairedEvidence(taskId,evidence2,receipt){if(!evidence2||!isRepairWorkflowReset(taskId,evidence2.workflow))return!1;if(Object.keys(evidence2.gates).length!==0)return!1;if(hasLegacyReconstructionGate(evidence2.required_gates))return!1;let receiptIsTainted=receipt!=null&&hasLegacyReconstructionGate(receipt.requiredGates);if(receipt&&!receiptIsTainted)return evidence2.requirements_state==="known"&&JSON.stringify(evidence2.required_gates)===JSON.stringify(receipt.requiredGates)&&evidence2.workflow.generation>receipt.generation&&(evidence2.test_engineer_exempt??null)===(receipt.testEngineerExempt??null)&&evidence2.repair_provenance?.requirements_receipt_hash===receipt.chainHash;if(!receipt||!receiptIsTainted)return!1;return evidence2.requirements_state==="unknown"&&evidence2.workflow.generation>=1&&evidence2.repair_provenance!=null&&evidence2.repair_provenance.requirements_receipt_hash===receipt.chainHash&&withoutLegacyReconstructionGate(receipt.requiredGates).every((gate)=>evidence2.required_gates.includes(gate))}function repairedEvidenceMatchesCas(evidence2,args2){let provenance=evidence2.repair_provenance;if(!provenance)return args2.expected_sha256==null&&args2.expected_generation==null;return(args2.expected_sha256==null||provenance.source_sha256===args2.expected_sha256)&&(args2.expected_generation==null||provenance.source_generation===args2.expected_generation)}function buildRepairNextActions(taskId,evidence2){if(evidence2.requirements_state==="known")return[`Delegate coder on task ${taskId} to produce a fresh accepted_mutation for the repaired evidence generation ${evidence2.workflow?.generation}.`,`Rerun Stage A for task ${taskId} until pre_check passes for the new generation.`,`Rerun Stage B gates [${evidence2.required_gates.join(", ")}] for task ${taskId} before attempting completion again.`];return[`Delegate coder on task ${taskId} to produce a fresh accepted mutation and regenerate authoritative required gates for a new exact-task generation.`,`Rerun Stage A for task ${taskId} after the new mutation is recorded.`,`Rerun the exact Stage B gates for task ${taskId} only after authoritative required gates are re-recorded; the idle recovery generation cannot complete directly.`]}function invalidateTaskEvidenceSessionFallbacks(taskId){for(let session of swarmState.agentSessions.values()){if(session.currentTaskId===taskId)session.currentTaskId=null;if(session.lastCoderDelegationTaskId===taskId)session.lastCoderDelegationTaskId=null;if(session.taskWorkflowStates?.delete(taskId),session.taskWorkflowCache?.delete(taskId),session.stageBCompletion?.delete(taskId),session.taskCouncilApproved?.delete(taskId),session.taskCouncilWorkflowGeneration?.delete(taskId),session.gateLog?.delete(taskId),session.partialGateWarningsIssuedForTask?.delete(taskId),session.completionGateWarnedForTask?.delete(taskId),session.lastGateFailure?.taskId===taskId)session.lastGateFailure=null}}async function repairTaskGateEvidence(args2,directory,context){assertStrictTaskId(args2.task_id);let normalizedReason=normalizeRepairReason(args2.reason),canonicalDirectory=canonicalizeRepairRoot(directory);if(!(await loadPlan(canonicalDirectory))?.phases.flatMap((phase)=>phase.tasks).find((candidate2)=>candidate2.id===args2.task_id))return{success:!1,message:`TASK_GATE_EVIDENCE_TASK_MISSING: ${args2.task_id} is not present in the loaded plan`,errors:[`Task ${args2.task_id} is not present in .swarm/plan.json.`]};return withTaskEvidenceLock(canonicalDirectory,args2.task_id,"repair_gate_evidence",async()=>{let read=readTaskEvidenceForRepair(canonicalDirectory,args2.task_id),latestReceipt=(await readTaskGateRequirementsReceipts(canonicalDirectory,args2.task_id)).at(-1),evidenceHasLegacyMarker=read.status==="valid"&&read.evidence!=null&&hasLegacyReconstructionGate(read.evidence.required_gates),receiptHasLegacyMarker=latestReceipt!=null&&hasLegacyReconstructionGate(latestReceipt.requiredGates);if(read.status==="valid"&&isAlreadyRepairedEvidence(args2.task_id,read.evidence,latestReceipt)){if(!repairedEvidenceMatchesCas(read.evidence,args2))return{success:!1,message:"TASK_GATE_EVIDENCE_CAS_MISMATCH",errors:["TASK_GATE_EVIDENCE_CAS_MISMATCH: the existing repaired generation was created from a different source identity."]};let nextActions2=buildRepairNextActions(args2.task_id,read.evidence);return{success:!0,repaired:!1,task_id:args2.task_id,required_gates:[...read.evidence.required_gates],requirements_state:read.evidence.requirements_state,repaired_generation:read.evidence.workflow?.generation,next_actions:nextActions2,message:`Task gate evidence for ${args2.task_id} is already in repaired fail-closed state.`}}if(read.status==="valid"&&read.evidence?.workflow?.schema===TASK_WORKFLOW_SCHEMA_MARKER&&!evidenceHasLegacyMarker&&latestReceipt!=null&&!receiptHasLegacyMarker)return{success:!1,message:"TASK_GATE_EVIDENCE_REPAIR_NOT_REQUIRED",errors:[`TASK_GATE_EVIDENCE_REPAIR_NOT_REQUIRED: ${args2.task_id} has valid authoritative evidence. Use the normal workflow repair path; this tool only rebuilds corrupt or legacy evidence.`]};if(read.status==="valid"&&read.evidence?.requirements_state==="known"&&!evidenceHasLegacyMarker&&receiptHasLegacyMarker)return{success:!1,message:"TASK_GATE_REQUIREMENTS_RECEIPT_STALE",errors:[`TASK_GATE_REQUIREMENTS_RECEIPT_STALE: ${args2.task_id} has clean accepted-mutation evidence but its latest requirements receipt is legacy-tainted. Repair was refused without modifying evidence; replay the prepared coder settlement so it can publish the exact hash-linked receipt.`]};if(typeof args2.expected_sha256==="string"&&read.status!=="missing"&&read.sha256!==args2.expected_sha256)return{success:!1,message:"TASK_GATE_EVIDENCE_CAS_MISMATCH",errors:[`TASK_GATE_EVIDENCE_CAS_MISMATCH: expected sha256 ${args2.expected_sha256}, found ${read.sha256}.`]};if(typeof args2.expected_generation==="number"){let observedGeneration=read.status==="valid"?read.generation:latestReceipt?.generation;if(observedGeneration!==args2.expected_generation)return{success:!1,message:"TASK_GATE_EVIDENCE_CAS_MISMATCH",errors:[`TASK_GATE_EVIDENCE_CAS_MISMATCH: expected generation ${args2.expected_generation}, found ${observedGeneration??"unknown"}.`]}}if(read.status==="unreadable"||read.status==="oversized")return{success:!1,message:read.error?.message??"TASK_GATE_EVIDENCE_UNREADABLE: repair requires operator intervention before evidence can be rewritten.",errors:[read.error?.message??`TASK_GATE_EVIDENCE_UNREADABLE: ${args2.task_id} could not be read safely for repair.`]};if(evidenceHasLegacyMarker&&latestReceipt==null&&!isReceiptlessLegacySentinelReset(args2.task_id,read.evidence))return{success:!1,message:"TASK_GATE_REQUIREMENTS_RECEIPT_MISSING",errors:[`TASK_GATE_REQUIREMENTS_RECEIPT_MISSING: ${args2.task_id} is marker-bearing but does not match the exact receipt-less state emitted by the historical repair flow. Repair was refused without modifying evidence or session state.`]};let nextGeneration2=Math.max(read.status==="valid"?read.generation??-1:-1,latestReceipt?.generation??-1)+1,nextEvidence;if(evidenceHasLegacyMarker||receiptHasLegacyMarker){let preservedGates=withoutLegacyReconstructionGate([...read.status==="valid"?read.evidence?.required_gates??[]:[],...latestReceipt?.requiredGates??[]]);nextEvidence=buildUnknownRepairedEvidence(args2.task_id,preservedGates,Math.max(nextGeneration2,1),{sha256:read.status==="missing"?null:read.sha256,generation:read.status==="valid"?read.generation??null:latestReceipt?.generation??null},latestReceipt?.chainHash??null)}else if(latestReceipt)nextEvidence=buildKnownRepairedEvidence(args2.task_id,latestReceipt,nextGeneration2,{sha256:read.status==="missing"?null:read.sha256,generation:read.status==="valid"?read.generation??null:latestReceipt.generation??null});else if(read.status==="missing")return{success:!1,message:"TASK_GATE_EVIDENCE_ABSENT",errors:[`TASK_GATE_EVIDENCE_ABSENT: ${args2.task_id} has no evidence file and no authoritative requirements receipt to rebuild from.`]};else return{success:!1,message:"TASK_GATE_REQUIREMENTS_RECEIPT_MISSING",errors:[`TASK_GATE_REQUIREMENTS_RECEIPT_MISSING: ${args2.task_id} has no authoritative requirements receipt. Receipt-less repair was refused without modifying the original evidence because its required gates cannot be reconstructed safely.`]};let serialized3=canonicalizeTaskEvidence(args2.task_id,nextEvidence),quarantine;if(isQuarantinableTaskEvidenceRead(read))quarantine=await quarantineTaskEvidenceBytes(canonicalDirectory,args2.task_id,read,normalizedReason,context,latestReceipt?.generation??null);assertTaskEvidenceWriteAllowed(canonicalDirectory,args2.task_id),await atomicWriteFile(taskEvidenceFilePath(canonicalDirectory,args2.task_id),serialized3),invalidateTaskEvidenceSessionFallbacks(args2.task_id);let nextActions=buildRepairNextActions(args2.task_id,nextEvidence);return{success:!0,repaired:!0,task_id:args2.task_id,required_gates:[...nextEvidence.required_gates],requirements_state:nextEvidence.requirements_state,quarantine_digest:quarantine?.digest,quarantine_path:quarantine?.filePath,repaired_generation:nextEvidence.workflow?.generation,next_actions:nextActions,message:`Repaired task gate evidence for ${args2.task_id} into a fresh fail-closed generation ${nextEvidence.workflow?.generation}. Next actions: ${nextActions.join(" ")}`}})}init_create_tool();init_resolve_working_directory();async function executeRepairGateEvidence(args2,directory,_ctx){try{if(!_ctx||stripKnownSwarmPrefix(_ctx.agent??"").toLowerCase()!=="architect")return{success:!1,message:"Only the architect may repair task gate evidence.",errors:["TASK_GATE_EVIDENCE_ARCHITECT_ONLY"]};let resolved=resolveWorkingDirectory(args2.working_directory,directory);if(!resolved.success)return{success:!1,message:resolved.message,errors:[resolved.message]};return await repairTaskGateEvidence(args2,resolved.directory,{sessionID:_ctx?.sessionID,messageID:_ctx?.messageID})}catch(error93){return{success:!1,message:"repair_gate_evidence failed",errors:[error93 instanceof Error?error93.message:String(error93)]}}}var repair_gate_evidence=createSwarmTool({description:"Architect-only evidence repair for exact-task gate files. Rebuilds from a durable requirements receipt, recovers receipt-backed legacy marker wedges or the exact sentinel-only historical reset, and refuses every other receipt-less reconstruction.",args:{task_id:exports_external.string().min(1).regex(/^\d+\.\d+(\.\d+)*$/,"Task ID must be in N.M or N.M.P format"),reason:exports_external.string().min(1).max(2000),expected_sha256:exports_external.string().regex(/^[a-f0-9]{64}$/).optional(),expected_generation:exports_external.number().int().min(0).optional(),working_directory:exports_external.string().optional()},execute:async(args2,directory,ctx)=>JSON.stringify(await executeRepairGateEvidence(args2,directory,ctx),null,2)});init_zod();init_schema();init_knowledge_receipt_ledger();init_create_tool();init_resolve_working_directory();async function executeRepairKnowledgeReceiptLedger(args2,directory,_ctx){try{if(_ctx&&stripKnownSwarmPrefix(_ctx.agent??"").toLowerCase()!=="architect")return{success:!1,message:"Only the architect may repair the knowledge receipt ledger.",errors:["RECEIPT_REPAIR_ARCHITECT_ONLY"]};if(_ctx?.sessionID&&args2.session_id!==_ctx.sessionID)return{success:!1,message:"repair_knowledge_receipt_ledger session_id must match the invoking tool context.",errors:["RECEIPT_REPAIR_SESSION_MISMATCH"]};let resolved=resolveWorkingDirectory(args2.working_directory,directory);if(!resolved.success)return{success:!1,message:resolved.message,errors:[resolved.message]};let result=await repairKnowledgeReceiptLedger(resolved.directory,args2);if(!result.ok)return{success:!1,message:"repair_knowledge_receipt_ledger failed",errors:[result.detail],code:result.code};let reEvaluationArgs=JSON.stringify({repair_id:result.repair_id,phase:args2.phase,...args2.task_id?{task_id:args2.task_id}:{},scope_complete:!0});return{success:!0,message:result.status==="validated_projection"?"knowledge receipt projection validated":result.status==="pending_re_evaluation"?`knowledge receipt ledger still pending re-evaluation; as architect, run knowledge_recall with a comprehensive query and repair_re_evaluation ${reEvaluationArgs}`:`knowledge receipt ledger repaired and blocked pending re-evaluation; as architect, run knowledge_recall with a comprehensive query and repair_re_evaluation ${reEvaluationArgs}`,...result}}catch(error93){return{success:!1,message:"repair_knowledge_receipt_ledger failed",errors:[error93 instanceof Error?error93.message:String(error93)]}}}var repair_knowledge_receipt_ledger=createSwarmTool({description:"Architect-only repair and validation for the authoritative knowledge receipt ledger. Rebuilds the derived projection when authority is readable, or quarantines a bounded corrupt authority, salvages only the validated prefix, and blocks the exact phase/session until a fresh re-evaluation is committed.",args:{phase:exports_external.string().min(1),session_id:exports_external.string().min(1),task_id:exports_external.string().min(1).optional(),reason:exports_external.string().min(1).max(2000),grace_days:exports_external.number().int().min(0).optional(),working_directory:exports_external.string().optional()},execute:async(args2,directory,ctx)=>JSON.stringify(await executeRepairKnowledgeReceiptLedger(args2,directory,ctx),null,2)});init_zod();init_loader();init_schema();init_profiles();init_telemetry();init_path_security();init_create_tool();import*as path348 from"node:path";init_zod();init_external_tool_runner();init_path_security();init_create_tool();import*as fs211 from"node:fs";import{createRequire as createRequire7}from"node:module";import*as path347 from"node:path";var require2=createRequire7(import.meta.url),DEFAULT_MAX_RESULTS4=100,DEFAULT_MAX_LINES=200,REGEX_TIMEOUT_MS=5000,MAX_FILE_SIZE_BYTES8=1048576,HARD_CAP_RESULTS4=1e4,HARD_CAP_LINES=1e4,MAX_QUERY_LENGTH=20000,MAX_INCLUDE_PATTERNS=100,MAX_RG_STDOUT_BYTES=8388608,MAX_RG_STDERR_BYTES=65536,FALLBACK_MAX_FILES=20000,FALLBACK_MAX_DIRS=5000,FALLBACK_MAX_DEPTH=40,FALLBACK_MAX_TOTAL_BYTES=67108864,DEFAULT_SKIP_DIRS=new Set([".git",".swarm","node_modules","dist","build","out","coverage",".next",".turbo",".cache"]);function globMatch(pattern,filePath){let normalizedPattern=pattern.replace(/\\/g,"/"),normalizedPath=filePath.replace(/\\/g,"/"),regexPattern=normalizedPattern.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"{{DOUBLESTAR}}").replace(/\*/g,"[^/]*").replace(/\?/g,".").replace(/\{\{DOUBLESTAR\}\}/g,".*");try{return new RegExp(`^${regexPattern}$`).test(normalizedPath)}catch{return!1}}function matchesGlobs(filePath,globs){if(globs.length===0)return!0;return globs.some((glob)=>globMatch(glob,filePath))}var WINDOWS_RESERVED_NAMES5=/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\.|:|$)/i;function containsWindowsAttacks4(str){if(/:[^\\/]/.test(str))return!0;let parts=str.split(/[/\\]/);for(let part of parts)if(WINDOWS_RESERVED_NAMES5.test(part))return!0;return!1}function resolveWithinWorkspace(filePath,workspace){try{let resolvedPath=path347.resolve(workspace,filePath),realWorkspace=fs211.realpathSync(workspace),realResolvedPath=fs211.realpathSync(resolvedPath),relativePath2=path347.relative(realWorkspace,realResolvedPath);if(relativePath2.startsWith("..")||path347.isAbsolute(relativePath2))return null;return relativePath2}catch{return null}}function isPathInWorkspace3(filePath,workspace){return resolveWithinWorkspace(filePath,workspace)!==null}function validatePathForRead2(filePath,workspace){return isPathInWorkspace3(filePath,workspace)}function splitGlobPatterns2(value){return value?value.split(",").map((p)=>p.trim()).filter(Boolean):[]}var GLOB_METACHARACTERS=/[*?[\]{}]/;function isExactPath(pattern){return!GLOB_METACHARACTERS.test(pattern)}function targetsDotDirectory(pattern){let firstSegment=pattern.split(/[\\/]/)[0];return!!firstSegment&&firstSegment.startsWith(".")&&firstSegment!=="."&&firstSegment!==".."}function hasGitSegment(resolvedRelativePath){return resolvedRelativePath.split(/[\\/]/).some((segment)=>segment.toLowerCase()===".git")}function toWorkspaceRelativePath2(filePath,workspace){try{let resolved=path347.resolve(workspace,filePath),realWorkspace=fs211.realpathSync(workspace),realResolved=fs211.realpathSync(resolved),relative88=path347.relative(realWorkspace,realResolved);if(!relative88||relative88.startsWith("..")||path347.isAbsolute(relative88))return null;return relative88.split(path347.sep).join("/")}catch{return null}}function truncateLine(line,maxLines){let trimmed=line.trimEnd();if(trimmed.length>maxLines)return`${trimmed.substring(0,maxLines)}...`;return trimmed}function resolvePackagedRipgrep(){try{let mod=require2("@vscode/ripgrep");return typeof mod.rgPath==="string"&&mod.rgPath?mod.rgPath:null}catch{return null}}function resolveRipgrepBinary(){return _internals286.resolvePackagedRipgrep()??_internals286.resolveExecutableFromPath(["rg"])}async function ripgrepSearch(opts){let rgPath=_internals286.resolveRipgrepBinary();if(!rgPath)return{error:!0,type:"rg-not-found",message:"ripgrep (rg) not found; using fallback search was not possible"};let args2=["--json","--no-config","-n"],includes=splitGlobPatterns2(opts.include),promotablePaths=[],globIncludes=[];for(let pattern of includes){let resolvedRelative=resolveWithinWorkspace(pattern,opts.workspace);if(isExactPath(pattern)&&targetsDotDirectory(pattern)&&pattern.split(/[\\/]/)[0]?.toLowerCase()!==".git"&&resolvedRelative!==null&&!hasGitSegment(resolvedRelative))promotablePaths.push(pattern);else globIncludes.push(pattern)}let pathOperands;if(promotablePaths.length>0&&globIncludes.length===0)pathOperands=promotablePaths;else{for(let pattern of[...globIncludes,...promotablePaths])args2.push("--glob",pattern);if(includes.some((p)=>targetsDotDirectory(p)&&p.split(/[\\/]/)[0]?.toLowerCase()!==".git"))args2.push("--hidden","--no-ignore"),args2.push("--glob","!.git");pathOperands=["."]}for(let pattern of splitGlobPatterns2(opts.exclude))args2.push("--glob",`!${pattern}`);if(opts.mode!=="regex")args2.push("--fixed-strings");args2.push("--",opts.query,...pathOperands);let run=await _internals286.runExternalTool({executable:rgPath,args:args2,cwd:opts.workspace,timeoutMs:REGEX_TIMEOUT_MS,maxStdoutBytes:MAX_RG_STDOUT_BYTES,maxStderrBytes:MAX_RG_STDERR_BYTES});try{if(run.status==="timeout")return{error:!0,type:"regex-timeout",message:`Search timed out after ${REGEX_TIMEOUT_MS}ms`};if(run.status==="spawn-error")return{error:!0,type:"unknown",message:run.message??"ripgrep failed to start"};if(run.exitCode!==0&&run.stderr){if(run.stderr.includes("Invalid regex")||run.stderr.includes("regex parse error")||run.stderr.includes("SyntaxError"))return{error:!0,type:"invalid-query",message:`Invalid query: ${run.stderr.split(`
|
|
7733
|
+
`,r:"\r",b:"\b",f:"\f",v:"\v"};if(simple[escaped]!==void 0){appendText(simple[escaped]);continue}if(/[0-7]/.test(escaped)){let octal=escaped;for(let count=0;count<2;count++){let next=value[index+1];if(!next||!/[0-7]/.test(next))break;octal+=next,index++}bytes.push(Number.parseInt(octal,8));continue}return null}return Buffer.from(bytes).toString("utf8")}function normalizeRepoPathKey(repoPath){let normalized=repoPath.replace(/\\/g,"/");return _internals285.platform()==="win32"||_internals285.platform()==="darwin"?normalized.toLowerCase():normalized}function normalizeDiffPath(rawPath){let pathToken=rawPath.startsWith('"')?rawPath:rawPath.split("\t",1)[0],decoded=decodeGitQuotedPath(pathToken);if(decoded===null||decoded==="/dev/null"||decoded.trim().length===0)return null;return normalizeRepoPathKey(decoded)}function parseDiffLineRangesChecked(diffOutput,requireGitFileHeaders){let result=new Map,currentFile=null,inGitFile=!1,expectingDestination=!1,destinationSeen=!1,destinationNeedsHunk=!1,collectedLines=0;for(let rawLine of diffOutput.split(/\r?\n/)){let line=rawLine.endsWith("\r")?rawLine.slice(0,-1):rawLine;if(line.startsWith("diff --git ")){if(expectingDestination||destinationNeedsHunk)return null;inGitFile=!0,currentFile=null,expectingDestination=!1,destinationSeen=!1;continue}if(line.startsWith("--- ")&&(inGitFile||!requireGitFileHeaders)){if(expectingDestination||destinationNeedsHunk)return null;expectingDestination=!0;continue}if(line.startsWith("+++ ")){if(requireGitFileHeaders&&(!inGitFile||!expectingDestination))return null;let rawDestination=line.slice(4);if(currentFile=normalizeDiffPath(rawDestination),currentFile===null&&rawDestination.trim()!=="/dev/null")return null;if(expectingDestination=!1,destinationSeen=!0,destinationNeedsHunk=!0,!currentFile)continue;if(!result.has(currentFile))result.set(currentFile,new Set);continue}if(!line.startsWith("@@"))continue;if(expectingDestination||requireGitFileHeaders&&(!inGitFile||!destinationSeen))return null;let match=/^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/.exec(line);if(!match)return null;let start=Number.parseInt(match[1],10),count=match[2]!==void 0?Number.parseInt(match[2],10):1;if(!Number.isSafeInteger(start)||!Number.isSafeInteger(count)||count<0||count>0&&start<1||count>MAX_CHANGED_LINE_ENTRIES||start+count-1>Number.MAX_SAFE_INTEGER||collectedLines+count>MAX_CHANGED_LINE_ENTRIES)return null;if(destinationNeedsHunk=!1,!currentFile)continue;let lines=result.get(currentFile);if(!lines)return null;for(let index=0;index<count;index++)lines.add(start+index);collectedLines+=count}if(expectingDestination||destinationNeedsHunk)return null;return result}function mergeChangedLines(target,source){for(let[file3,sourceLines]of source){let targetLines=target.get(file3)??new Set;for(let line of sourceLines)targetLines.add(line);target.set(file3,targetLines)}}function parseUntrackedStatus(output){if(output.length>0&&!output.endsWith("\x00"))return null;let untracked=[],records=output.split("\x00");for(let index=0;index<records.length-1;index++){let record3=records[index];if(!record3||record3.length<4||record3[2]!==" ")return null;let status2=record3.slice(0,2),filePath=record3.slice(3);if(!filePath||!isKnownPorcelainStatus(status2))return null;if(status2==="??"||status2==="!!")untracked.push(normalizeRepoPathKey(filePath));if(/[RC]/.test(status2)){let sourcePath=records[++index];if(!sourcePath||looksLikePorcelainStatusRecord(sourcePath))return null}}return untracked}function isKnownPorcelainStatus(status2){if(status2==="??"||status2==="!!")return!0;if(/U/.test(status2))return new Set(["DD","AU","UD","UA","DU","AA","UU"]).has(status2);return status2!==" "&&/^[ MTADRC]{2}$/.test(status2)}function looksLikePorcelainStatusRecord(value){return value.length>=4&&value[2]===" "&&isKnownPorcelainStatus(value.slice(0,2))}async function getChangedLineRanges(directory,abortSignal,requestedFiles=[]){let mergeBase=null;for(let baseBranch of["zaxbyhub/main","upstream/main","origin/main","main","origin/master","master"]){let candidate2=(await runGit8(["merge-base",baseBranch,"HEAD"],directory,abortSignal))?.trim();if(candidate2&&/^[0-9a-f]{40,64}$/i.test(candidate2)){mergeBase=candidate2;break}}if(!mergeBase)return null;let commonDiffArgs=["-c","core.quotePath=false","diff","--no-ext-diff","--no-color","--no-prefix","-U0"],requestedPathspecs=requestedFiles.map((file3)=>path344.relative(directory,file3).replace(/\\/g,"/")).filter((file3)=>file3.length>0&&file3!==".."&&!file3.startsWith("../")),statusArgs=["-c","core.quotePath=false","status","--porcelain=v1","-z","--untracked-files=all",...requestedPathspecs.length>0?["--ignored=matching"]:[],...requestedPathspecs.length>0?["--",...requestedPathspecs]:[]],[committed,staged,unstaged,status2]=await Promise.all([runGit8([...commonDiffArgs,`${mergeBase}..HEAD`,"--"],directory,abortSignal),runGit8([...commonDiffArgs,"--cached","HEAD","--"],directory,abortSignal),runGit8([...commonDiffArgs,"--"],directory,abortSignal),runGit8(statusArgs,directory,abortSignal)]);if(committed===null||staged===null||unstaged===null||status2===null)return null;let committedLines=parseDiffLineRangesChecked(committed,!0),stagedLines=parseDiffLineRangesChecked(staged,!0),unstagedLines=parseDiffLineRangesChecked(unstaged,!0);if(!committedLines||!stagedLines||!unstagedLines)return null;let result=new Map;mergeChangedLines(result,committedLines),mergeChangedLines(result,stagedLines),mergeChangedLines(result,unstagedLines);let untracked=parseUntrackedStatus(status2);if(untracked===null)return null;let requestedKeys=requestedPathspecs.map(normalizeRepoPathKey);for(let file3 of untracked)if(result.set(file3,new Set([ALL_LINES_CHANGED])),file3.endsWith("/")){for(let requestedFile of requestedKeys)if(requestedFile.startsWith(file3))result.set(requestedFile,new Set([ALL_LINES_CHANGED]))}return result}function classifySastFindings(findings,changedLineRanges,directory){if(!changedLineRanges)return{newFindings:findings,preexistingFindings:[]};let newFindings=[],preexistingFindings=[],pathApi=_internals285.platform()==="win32"?path344.win32:path344.posix,resolvedDirectory=pathApi.resolve(directory);for(let finding of findings){let filePath=finding.location.file,normalised;try{if(typeof filePath!=="string"||filePath.length===0||filePath.includes("\x00")){newFindings.push(finding);continue}let resolvedFinding=pathApi.isAbsolute(filePath)?pathApi.resolve(filePath):pathApi.resolve(resolvedDirectory,filePath),relative87=pathApi.relative(resolvedDirectory,resolvedFinding);if(pathApi.isAbsolute(relative87)||relative87===".."||relative87.startsWith(`..${pathApi.sep}`)){newFindings.push(finding);continue}normalised=normalizeRepoPathKey(relative87)}catch{newFindings.push(finding);continue}let changedLines=changedLineRanges.get(normalised);if(changedLines?.has(ALL_LINES_CHANGED)||changedLines?.has(finding.location.line))newFindings.push(finding);else preexistingFindings.push(finding)}return{newFindings,preexistingFindings}}async function runPreCheckBatch(input,workspaceDir,contextDir,abortSignal){let effectiveWorkspaceDir=workspaceDir||input.directory||contextDir,{files,directory,sast_threshold="medium",gates:gatesOverrides,phase,sast_enabled=!0}=input,gates=gatesOverrides??(input.config?.gates?{sast_scan:input.config.gates.sast_scan,quality_budget:input.config.gates.quality_budget}:void 0),dirError=validateDirectory2(directory,effectiveWorkspaceDir);if(dirError)return warn(`pre_check_batch: Invalid directory: ${dirError}`),{batch_status:"invalid",gates_passed:!1,lint:{ran:!1,error:dirError,duration_ms:0},secretscan:{ran:!1,error:dirError,duration_ms:0},sast_scan:{ran:!1,error:dirError,duration_ms:0},quality_budget:{ran:!1,error:dirError,duration_ms:0},total_duration_ms:0};if(!files||files.length===0)return warn("pre_check_batch: No files provided, skipping all tools (fail-closed)"),{batch_status:"invalid",gates_passed:!1,lint:{ran:!1,error:"No files provided",duration_ms:0},secretscan:{ran:!1,error:"No files provided",duration_ms:0},sast_scan:{ran:!1,error:"No files provided",duration_ms:0},quality_budget:{ran:!1,error:"No files provided",duration_ms:0},total_duration_ms:0};let changedFiles=[];for(let file3 of files){if(typeof file3!=="string"){warn(`pre_check_batch: Non-string file entry rejected: ${String(file3)}`);continue}if(validatePath(file3,directory,effectiveWorkspaceDir)){warn(`pre_check_batch: Invalid file path: ${file3}`);continue}changedFiles.push(path344.resolve(directory,file3))}if(changedFiles.length===0)return warn("pre_check_batch: No valid files after validation, skipping all tools (fail-closed)"),{batch_status:"invalid",gates_passed:!1,lint:{ran:!1,error:"No files provided",duration_ms:0},secretscan:{ran:!1,error:"No files provided",duration_ms:0},sast_scan:{ran:!1,error:"No files provided",duration_ms:0},quality_budget:{ran:!1,error:"No files provided",duration_ms:0},total_duration_ms:0};try{assertProjectRoot(directory)}catch(error93){let rootError=error93 instanceof Error?error93.message:String(error93);return warn(`pre_check_batch: Project-root validation failed: ${rootError}`),{batch_status:"invalid",gates_passed:!1,lint:{ran:!1,error:rootError,duration_ms:0},secretscan:{ran:!1,error:rootError,duration_ms:0},sast_scan:{ran:!1,error:rootError,duration_ms:0},quality_budget:{ran:!1,error:rootError,duration_ms:0},total_duration_ms:0}}if(changedFiles.length>MAX_FILES)throw Error(`Input exceeds maximum file count: ${changedFiles.length} > ${MAX_FILES}`);let limit=pLimit(MAX_CONCURRENT),sastDisabledByConfig=gates?.sast_scan?.enabled===!1,[lintResult,secretscanResult,sastScanResult,qualityBudgetResult]=await Promise.all([limit(()=>_internals285.runLintWrapped(changedFiles,directory,gates,abortSignal)),limit(()=>_internals285.runSecretscanWrapped(changedFiles,directory,gates,abortSignal)),sast_enabled&&!sastDisabledByConfig?limit(()=>_internals285.runSastScanWrapped(changedFiles,directory,sast_threshold,gates,phase,abortSignal)):Promise.resolve({ran:!1,duration_ms:0}),limit(()=>_internals285.runQualityBudgetWrapped(changedFiles,directory,gates,abortSignal))]),totalDuration=lintResult.duration_ms+secretscanResult.duration_ms+sastScanResult.duration_ms+qualityBudgetResult.duration_ms,gatesPassed=!0;if(lintResult.ran&&lintResult.result){let lintRes=lintResult.result;if("success"in lintRes&&lintRes.success===!1)warn("pre_check_batch: Lint found issues (informational only)")}else if(lintResult.error)warn(`pre_check_batch: Lint error (informational only): ${lintResult.error}`);let secretscanDecision=evaluateSecretscanGate(secretscanResult,changedFiles.length);if(!secretscanDecision.passed)gatesPassed=!1,warn(`pre_check_batch: ${secretscanDecision.summary} - GATE FAILED`);if(secretscanResult.ran||secretscanResult.error)try{let scanResult=secretscanDecision.result,secretscanEvidence={task_id:"secretscan",type:"secretscan",timestamp:new Date().toISOString(),agent:"pre_check_batch",verdict:secretscanDecision.passed?"pass":"fail",summary:secretscanDecision.summary,findings_count:secretscanDecision.findingsCount,scan_directory:scanResult?.scan_dir??directory,files_scanned:scanResult?.files_scanned??0,skipped_files:scanResult?.skipped_files??0,incomplete_files:scanResult?.incomplete_files??changedFiles.length,incomplete_paths:scanResult?.incomplete_paths??[{path:".",reason:"missing_coverage_metadata"}]};await _internals285.saveEvidence(directory,"secretscan",secretscanEvidence,abortSignal)}catch(e){let persistError=`Failed to persist secretscan evidence: ${e instanceof Error?e.message:String(e)}`;secretscanResult.error=persistError,gatesPassed=!1,warn(`pre_check_batch: ${persistError} - GATE FAILED`)}let sastPreexistingFindings,sastDegraded=!1;if(sastScanResult.ran&&sastScanResult.result){let sastResult=sastScanResult.result;if(sastResult.error)if(sastResult.failure_kind==="semgrep_process_exit"&&sastResult.findings.length===0)sastDegraded=!0,warn(`pre_check_batch: SAST coverage degraded (${sastResult.error}) - continuing without a gate failure`);else gatesPassed=!1,warn(`pre_check_batch: SAST scan error (${sastResult.error}) - GATE FAILED`);else if(sastResult.baseline_used){let sastCarryFindings=[...sastResult.pre_existing_findings??[],...sastResult.moved_findings??[]];if(sastCarryFindings.length>0){if(sastPreexistingFindings=sastCarryFindings.filter((f)=>meetsThresholdForTriage(f.severity,sast_threshold)),sastPreexistingFindings.length>0)warn(`pre_check_batch: SAST baseline diff found ${sastPreexistingFindings.length} pre-existing/moved finding(s) - passing to reviewer for triage`)}if(sastResult.verdict==="fail")gatesPassed=!1,warn("pre_check_batch: SAST scan found new findings above threshold - GATE FAILED")}else if(sastResult.verdict==="fail"){let gateFindings=sastResult.findings.filter((f)=>GATE_SEVERITIES.has(f.severity));if(gateFindings.length>0){let changedLineRanges=await _internals285.getChangedLineRanges(directory,abortSignal,changedFiles),{newFindings,preexistingFindings}=classifySastFindings(gateFindings,changedLineRanges,directory);if(newFindings.length>0)gatesPassed=!1,warn(`pre_check_batch: SAST scan found ${newFindings.length} new HIGH/CRITICAL finding(s) on changed lines - GATE FAILED`);else if(preexistingFindings.length>0)sastPreexistingFindings=preexistingFindings,warn(`pre_check_batch: SAST scan found ${preexistingFindings.length} pre-existing HIGH/CRITICAL finding(s) on unchanged lines - passing to reviewer for triage`)}else gatesPassed=!1,warn("pre_check_batch: SAST scan found vulnerabilities - GATE FAILED")}}else if(sastScanResult.error)gatesPassed=!1,warn(`pre_check_batch: SAST scan error - GATE FAILED: ${sastScanResult.error}`);if(qualityBudgetResult.ran&&qualityBudgetResult.result){if(qualityBudgetResult.result.verdict==="fail")warn("pre_check_batch: Quality budget exceeded (informational only)")}else if(qualityBudgetResult.error)warn(`pre_check_batch: Quality budget error (informational only): ${qualityBudgetResult.error}`);return{batch_status:[lintResult,secretscanResult,sastScanResult,qualityBudgetResult].every((toolResult)=>toolResult.ran===!1)?"skipped":"completed",gates_passed:gatesPassed,lint:lintResult,secretscan:secretscanResult,sast_scan:sastScanResult,quality_budget:qualityBudgetResult,total_duration_ms:Math.round(totalDuration),...sastDegraded&&{sast_degraded:!0},...(!sast_enabled||sastDisabledByConfig)&&{sast_skipped:!0},...sastPreexistingFindings&&sastPreexistingFindings.length>0&&{sast_preexisting_findings:sastPreexistingFindings}}}var pre_check_batch=createSwarmTool({allowWorkingDirectoryOverride:!0,description:"Run multiple verification tools in parallel: lint, secretscan, SAST scan, and quality budget. Returns unified result with gates_passed status. Security findings and incomplete SAST runs are hard failures; a Semgrep nonzero process exit with zero findings is returned as explicit sast_degraded coverage and does not block.",args:{files:exports_external.array(exports_external.string()).optional().describe("Specific files to check (optional, scans directory if not provided)"),directory:exports_external.string().describe("Project root directory — ordinary workspace subdirectories are rejected; direct .git or .opencode project boundaries are accepted"),sast_threshold:exports_external.enum(["low","medium","high","critical"]).optional().describe("Minimum severity for SAST findings to cause failure (default: medium)"),phase:exports_external.number().int().min(1).optional().describe("Current phase number (positive integer >= 1). When provided, enables SAST baseline diffing: only findings absent from the phase-scoped baseline fail the gate.")},async execute(args2,directory,ctx){if(!args2||typeof args2!=="object")return serializePreCheckResult({batch_status:"invalid",gates_passed:!1,lint:{ran:!1,error:"Invalid arguments",duration_ms:0},secretscan:{ran:!1,error:"Invalid arguments",duration_ms:0},sast_scan:{ran:!1,error:"Invalid arguments",duration_ms:0},quality_budget:{ran:!1,error:"Invalid arguments",duration_ms:0},total_duration_ms:0});if(!directory||typeof directory!=="string"||directory.trim()==="")return serializePreCheckResult({batch_status:"invalid",gates_passed:!1,lint:{ran:!1,error:"project directory is required but was not provided",duration_ms:0},secretscan:{ran:!1,error:"project directory is required but was not provided",duration_ms:0},sast_scan:{ran:!1,error:"project directory is required but was not provided",duration_ms:0},quality_budget:{ran:!1,error:"project directory is required but was not provided",duration_ms:0},total_duration_ms:0});let typedArgs=args2;if(!typedArgs.directory)return serializePreCheckResult({batch_status:"invalid",gates_passed:!1,lint:{ran:!1,error:"directory is required",duration_ms:0},secretscan:{ran:!1,error:"directory is required",duration_ms:0},sast_scan:{ran:!1,error:"directory is required",duration_ms:0},quality_budget:{ran:!1,error:"directory is required",duration_ms:0},total_duration_ms:0});let resolvedDirectory=path344.resolve(typedArgs.directory),workspaceAnchor=path344.resolve(directory);if(isStrictPathDescendant(resolvedDirectory,workspaceAnchor)&&!hasExplicitProjectBoundary(resolvedDirectory)){let subDirError=`directory "${typedArgs.directory}" is a subdirectory of the project root — pre_check_batch requires the project root directory "${workspaceAnchor}"`;return serializePreCheckResult({batch_status:"invalid",gates_passed:!1,lint:{ran:!1,error:subDirError,duration_ms:0},secretscan:{ran:!1,error:subDirError,duration_ms:0},sast_scan:{ran:!1,error:subDirError,duration_ms:0},quality_budget:{ran:!1,error:subDirError,duration_ms:0},total_duration_ms:0})}let dirError=validateDirectory2(resolvedDirectory,workspaceAnchor);if(dirError)return serializePreCheckResult({batch_status:"invalid",gates_passed:!1,lint:{ran:!1,error:dirError,duration_ms:0},secretscan:{ran:!1,error:dirError,duration_ms:0},sast_scan:{ran:!1,error:dirError,duration_ms:0},quality_budget:{ran:!1,error:dirError,duration_ms:0},total_duration_ms:0});try{let sastEnabled=!0;try{let preamble=await _internals285.resolveGatePreamble(resolvedDirectory,ctx?.sessionID);if(preamble.resolved&&preamble.effectiveGates)sastEnabled=preamble.effectiveGates.sast_enabled}catch{warn("pre_check_batch: QA-gate profile resolution failed; keeping SAST enabled")}let rawPhase=typedArgs.phase,safePhase=typeof rawPhase==="number"&&Number.isInteger(rawPhase)&&rawPhase>=1?rawPhase:void 0,result=await _internals285.runPreCheckBatch({files:typedArgs.files,directory:resolvedDirectory,sast_threshold:typedArgs.sast_threshold,config:typedArgs.config,gates:_internals285.loadGateOverrides(resolvedDirectory),phase:safePhase,sast_enabled:sastEnabled},workspaceAnchor,directory,ctx?.abort);return serializePreCheckResult(result)}catch(error93){let errorMessage3=error93 instanceof Error?error93.message:"Unknown error";return serializePreCheckResult({batch_status:"invalid",gates_passed:!1,lint:{ran:!1,error:errorMessage3,duration_ms:0},secretscan:{ran:!1,error:errorMessage3,duration_ms:0},sast_scan:{ran:!1,error:errorMessage3,duration_ms:0},quality_budget:{ran:!1,error:errorMessage3,duration_ms:0},total_duration_ms:0})}}});init_zod();init_guardrails2();init_pr_workflow_gate();init_scope_binding();init_create_tool();var PreparePrFeedbackScopeArgsSchema=exports_external.object({task_id:exports_external.string().regex(/^\d+\.\d+(?:\.\d+)*$/,"task_id must use N.M notation"),files:exports_external.array(exports_external.string().min(1).max(4096)).min(1).max(1e4)}).strict();function failure(message){return JSON.stringify({success:!1,message},null,2)}async function executePreparePrFeedbackScope(args2,directory,context={}){let parsed=PreparePrFeedbackScopeArgsSchema.safeParse(args2);if(!parsed.success)return failure(`Invalid PR-feedback scope: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`);let sessionID=context.sessionID?.trim();if(!sessionID)return failure("PR-feedback scope requires an active session");let files=normalizeScopeFiles(parsed.data.files);if(!files)return failure("PR-feedback scope contains an unsafe file path");for(let file3 of files){let symlinkBlock=checkWriteTargetForSymlink(file3,directory);if(symlinkBlock)return failure(symlinkBlock)}try{await declarePrFeedbackScope(directory,sessionID,parsed.data.task_id,files)}catch(error93){return failure(error93 instanceof Error?error93.message:String(error93))}return JSON.stringify({success:!0,task_id:parsed.data.task_id,files,message:"Scope is bound to the verified PR-feedback revision and will authorize only the next matching coder Task."},null,2)}var prepare_pr_feedback_scope=createSwarmTool({description:"Prepare an exact file scope for one PR-feedback coder Task after immutable feedback verification settles.",args:{task_id:PreparePrFeedbackScopeArgsSchema.shape.task_id,files:PreparePrFeedbackScopeArgsSchema.shape.files},execute:executePreparePrFeedbackScope});init_quality_budget();init_zod();init_pr_workflow_gate();init_create_tool();var RebindPrFeedbackHeadArgsSchema=exports_external.object({pr_head_sha:exports_external.string().trim().regex(/^[0-9a-f]{40}$/i)}).strict();async function executeRebindPrFeedbackHead(args2,directory,context={}){let parsed=RebindPrFeedbackHeadArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,message:`Invalid PR feedback rebind: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`});if(!context.sessionID?.trim())return JSON.stringify({success:!1,message:"PR feedback rebind requires an active sessionID"});try{let state2=await rebindPrFeedbackHead(directory,context.sessionID,parsed.data.pr_head_sha);return JSON.stringify({success:!0,pr_head_sha:state2.prHeadSha,rebind_count:state2.prFeedbackRebindCount??1,message:"Rebound the PR_FEEDBACK intake head; every Stage A / verification / gate receipt is invalidated — re-run the full mechanical ladder on the new ancestry."})}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:String(error93)})}}var rebind_pr_feedback_head=createSwarmTool({description:"Rebind a PR_FEEDBACK workflow to a new verified remote PR head after merge/rebase/conflict repair (base-sync). Use ONLY when the history genuinely changed to repair base drift or conflicts: it refuses a no-op rebind to the current intake head, refuses while publication is armed (to change approved content after arming use invalidate_pr_feedback_publication), and refuses while lanes are in flight. It invalidates every ancestry-bound receipt (Stage A, verification, ordered gates) so the full mechanical ladder re-runs on the new ancestry. Requires the full 40-char new PR head SHA; the current checkout must equal it.",args:{pr_head_sha:RebindPrFeedbackHeadArgsSchema.shape.pr_head_sha},execute:executeRebindPrFeedbackHead});init_zod();init_utils2();init_atomic_write();init_create_tool();var FreshnessValueSchema=exports_external.string().trim().min(1).max(500).regex(/^(synced|behind:[1-9][0-9]*|fetch-failed:\S+)$/,"must be 'synced', 'behind:<n>', or 'fetch-failed:<reason>' (reason contains no whitespace)"),RecordBranchFreshnessArgsSchema=exports_external.object({issueNumber:exports_external.number().int().min(1),freshness:FreshnessValueSchema,override:exports_external.string().trim().min(1).max(4000).optional()}).strict();async function executeRecordBranchFreshness(args2,directory,context={}){let parsed=RecordBranchFreshnessArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,message:`Invalid branch-freshness receipt: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`});let data=parsed.data;if(data.freshness==="synced"&&data.override)return JSON.stringify({success:!1,message:"An override is only meaningful for a fetch-failed outcome; a synced base needs none."});let receipt={issueNumber:data.issueNumber,freshness:data.freshness,timestamp:new Date().toISOString()};if(data.override)receipt.override=data.override;if(context.sessionID?.trim())receipt.sessionId=context.sessionID.trim();let validatedPath;try{validatedPath=validateSwarmPath(directory,"branch-freshness.json")}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:"Failed to validate path"})}try{await atomicWriteSwarmFile(validatedPath,JSON.stringify(receipt,null,2));let permits=await branchFreshnessReceiptExists(directory,data.issueNumber);return JSON.stringify({success:!0,issueNumber:data.issueNumber,path:".swarm/branch-freshness.json",permits,message:permits?`Branch-freshness receipt recorded for issue #${data.issueNumber}; the trace's freshness gate is satisfied.`:`Branch-freshness receipt recorded for issue #${data.issueNumber}, but the outcome (${data.freshness}) does NOT permit the trace — ${data.freshness.startsWith("behind:")?"re-sync with the default branch and re-record as synced.":"a fetch-failed outcome without a recorded user override fails closed."}`})}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:String(error93)})}}var record_branch_freshness=createSwarmTool({description:`Record the Phase 0 branch-freshness outcome for the current traced issue (issue #2564): freshness is "synced", "behind:<n>", or "fetch-failed:<reason>" exactly as the fetch recorded it, plus an optional verbatim user override for a failed fetch. The /swarm issue --trace workflow will not transition to PLAN until the recorded outcome permits (synced, or fetch-failed with an override). The response's permits field mirrors the gate reader's verdict on the persisted receipt (advisory for the calling agent — the reducer always recomputes it independently).`,args:{issueNumber:RecordBranchFreshnessArgsSchema.shape.issueNumber,freshness:RecordBranchFreshnessArgsSchema.shape.freshness,override:RecordBranchFreshnessArgsSchema.shape.override},execute:executeRecordBranchFreshness});init_zod();init_schema();init_extractors();init_manager();init_create_tool();var recordDirectiveOverrideInternals={loadPlan,recordDirectiveOverrides};async function executeRecordDirectiveOverride(args2,directory,ctx){if(!ctx?.sessionID?.trim())return{success:!1,code:"DIRECTIVE_OVERRIDE_SESSION_REQUIRED",message:"An exact session identity is required to record an override."};if(stripKnownSwarmPrefix(ctx.agent??"").toLowerCase()!=="architect")return{success:!1,code:"DIRECTIVE_OVERRIDE_ARCHITECT_ONLY",message:"Only the architect may record a critical-directive override."};let plan=await recordDirectiveOverrideInternals.loadPlan(directory),requestedPhase=plan?.phases.find((candidate2)=>candidate2.id===args2.phase);if(!plan||!requestedPhase||plan.current_phase!==args2.phase)return{success:!1,code:"DIRECTIVE_OVERRIDE_PHASE_MISMATCH",message:`Phase ${args2.phase} is not the current authoritative plan phase.`};let phaseLabel=extractCurrentPhaseFromPlan(plan)??`Phase ${plan.current_phase}`;return await recordDirectiveOverrideInternals.recordDirectiveOverrides(directory,[...new Set(args2.directive_ids)],args2.justification,ctx.sessionID,phaseLabel),{success:!0,code:"DIRECTIVE_OVERRIDE_RECORDED",phase:args2.phase,directive_ids:[...new Set(args2.directive_ids)],message:"Recorded the audited override. Retry phase_complete so every gate is re-evaluated from a fresh snapshot."}}var record_directive_override=createSwarmTool({description:"Architect-only audited override for identified critical-directive violations. Requires exact current phase/session identity and substantive justification; it cannot repair or bypass unreadable authority.",args:{directive_ids:exports_external.array(exports_external.string().min(1).max(256)).min(1).max(64),justification:exports_external.string().trim().min(10).max(2000),phase:exports_external.number().int().min(1).max(9999)},execute:async(args2,directory,ctx)=>JSON.stringify(await executeRecordDirectiveOverride(args2,directory,ctx),null,2)});init_zod();init_utils2();init_atomic_write();init_create_tool();var RecordImplementationReviewArgsSchema=exports_external.object({issueNumber:exports_external.number().int().min(1),reviewerVerdict:exports_external.enum(["APPROVE","NEEDS_REVISION","BLOCKED"]),criticVerdict:exports_external.enum(["APPROVE","NEEDS_REVISION","BLOCKED"]),diffBase:exports_external.string().trim().regex(/^[0-9a-f]{7,40}$/i),diffHead:exports_external.string().trim().regex(/^[0-9a-f]{7,40}$/i),notes:exports_external.string().trim().min(8).max(4000)}).strict();async function executeRecordImplementationReview(args2,directory,context={}){let parsed=RecordImplementationReviewArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,message:`Invalid implementation review receipt: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`});let data=parsed.data;if(data.reviewerVerdict!=="APPROVE"||data.criticVerdict!=="APPROVE")return JSON.stringify({success:!1,message:"A satisfying implementation-review receipt requires BOTH the reviewer and the critic to have delivered APPROVE; record non-approving verdicts in the working notes and fix the findings instead."});let receipt={issueNumber:data.issueNumber,reviewerVerdict:data.reviewerVerdict,criticVerdict:data.criticVerdict,diffBase:data.diffBase,diffHead:data.diffHead,notes:data.notes,timestamp:new Date().toISOString()};if(context.sessionID?.trim())receipt.sessionId=context.sessionID.trim();let validatedPath;try{validatedPath=validateSwarmPath(directory,"implementation-review.json")}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:"Failed to validate path"})}try{return await atomicWriteSwarmFile(validatedPath,JSON.stringify(receipt,null,2)),JSON.stringify({success:!0,issueNumber:data.issueNumber,path:".swarm/implementation-review.json",message:`Implementation review recorded for issue #${data.issueNumber} (reviewer APPROVE + critic APPROVE); the trace may now satisfy its review gate.`})}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:String(error93)})}}var record_implementation_review=createSwarmTool({description:"Record the independent implementation review for the current traced issue (issue #2131 residual B): dispatch FRESH-context reviewer and critic passes over the implementation diff (separate contexts from the implementer), and once BOTH approve call this with the issue number, both APPROVE verdicts, the reviewed diff base/head SHAs, and notes. The /swarm issue --trace workflow will not hand off to commit-pr until this receipt exists. Non-approving verdicts cannot be recorded here — fix the findings and re-review.",args:{issueNumber:RecordImplementationReviewArgsSchema.shape.issueNumber,reviewerVerdict:RecordImplementationReviewArgsSchema.shape.reviewerVerdict,criticVerdict:RecordImplementationReviewArgsSchema.shape.criticVerdict,diffBase:RecordImplementationReviewArgsSchema.shape.diffBase,diffHead:RecordImplementationReviewArgsSchema.shape.diffHead,notes:RecordImplementationReviewArgsSchema.shape.notes},execute:executeRecordImplementationReview});init_zod();init_utils2();init_atomic_write();init_create_tool();var RecordIssuePublicationArgsSchema=exports_external.object({issueNumber:exports_external.number().int().min(1),prNumber:exports_external.number().int().min(1),prUrl:exports_external.string().url().regex(/^https:\/\/github\.com\/[^/]+\/[^/]+\/pull\/\d+/,"prUrl must be a canonical GitHub PR URL (https://github.com/<owner>/<repo>/pull/<number>)"),headSha:exports_external.string().min(1).optional()}).strict();async function executeRecordIssuePublication(args2,directory){let parsed=RecordIssuePublicationArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,message:`Invalid publication receipt: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`});let{issueNumber,prNumber,prUrl,headSha}=parsed.data,receipt={published:!0,issueNumber,prNumber,prUrl,publishedAt:new Date().toISOString()};if(headSha)receipt.headSha=headSha;let validatedPath;try{validatedPath=validateSwarmPath(directory,"issue-publication.json")}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:"Failed to validate path"})}try{return await atomicWriteSwarmFile(validatedPath,JSON.stringify(receipt,null,2)),JSON.stringify({success:!0,issueNumber,prNumber,prUrl,path:".swarm/issue-publication.json",message:`Publication receipt recorded for issue #${issueNumber} (PR #${prNumber}); the issue-trace workflow will transition to its terminal published state.`})}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:String(error93)})}}var record_issue_publication=createSwarmTool({description:'Record that the traced issue has been published (PR created/updated) so the /swarm issue --trace workflow can reach its terminal published state. The trace stops at publication_handoff (the commit-pr directive) until this receipt is observed — publication_handoff is NOT "issue resolved". commit-pr calls this after the PR is created/updated. Supply the traced issue number, the exact PR number, the canonical GitHub PR URL, and (optionally) the published HEAD sha. The receipt is issue-bound.',args:{issueNumber:RecordIssuePublicationArgsSchema.shape.issueNumber,prNumber:RecordIssuePublicationArgsSchema.shape.prNumber,prUrl:RecordIssuePublicationArgsSchema.shape.prUrl,headSha:RecordIssuePublicationArgsSchema.shape.headSha},execute:executeRecordIssuePublication});init_zod();init_utils2();init_atomic_write();init_create_tool();var RecordIssueReproductionArgsSchema=exports_external.object({issueNumber:exports_external.number().int().min(1),performed:exports_external.boolean(),commands:exports_external.array(exports_external.string().min(1)).min(1).optional(),output_summary:exports_external.string().min(1).optional()}).strict();async function executeRecordIssueReproduction(args2,directory,context={}){let parsed=RecordIssueReproductionArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,message:`Invalid reproduction receipt: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`});let{issueNumber,performed,commands,output_summary}=parsed.data;if(performed&&(!commands||commands.length===0||!output_summary))return JSON.stringify({success:!1,message:"A performed=true reproduction receipt requires non-empty commands and output_summary."});let receipt={performed,issueNumber,timestamp:new Date().toISOString()};if(commands)receipt.commands=commands;if(output_summary)receipt.output_summary=output_summary;if(context.sessionID?.trim())receipt.sessionId=context.sessionID.trim();let validatedPath;try{validatedPath=validateSwarmPath(directory,"reproduction.json")}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:"Failed to validate path"})}try{return await atomicWriteSwarmFile(validatedPath,JSON.stringify(receipt,null,2)),JSON.stringify({success:!0,issueNumber,performed,path:".swarm/reproduction.json",message:performed?`Reproduction receipt recorded for issue #${issueNumber}; the trace may now transition to PLAN.`:`Reproduction receipt recorded (performed=false) for issue #${issueNumber}; it does NOT satisfy the reproduction gate.`})}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:String(error93)})}}var record_issue_reproduction=createSwarmTool({description:"Record the reproduction outcome for the current traced issue. The /swarm issue --trace workflow requires reproduction evidence (or a typed --no-repro waiver) before it can leave localization and transition to PLAN. Call this with performed=true, the exact commands run, and a concrete output_summary after attempting a minimal reproduction; the receipt binds to issueNumber (and records the calling session) and is read by the issue-trace engine. A performed=true receipt MUST include commands and output_summary. A performed=false receipt is recorded but does NOT satisfy the gate.",args:{issueNumber:RecordIssueReproductionArgsSchema.shape.issueNumber,performed:RecordIssueReproductionArgsSchema.shape.performed,commands:RecordIssueReproductionArgsSchema.shape.commands,output_summary:RecordIssueReproductionArgsSchema.shape.output_summary},execute:executeRecordIssueReproduction});init_zod();init_utils2();init_atomic_write();init_create_tool();var HEX40=/^[0-9a-f]{40}$/,RecordMergeApprovalArgsSchema=exports_external.object({issueNumber:exports_external.number().int().min(1),prHeadSha:exports_external.string().regex(HEX40,"must be a 40-hex commit SHA"),finalCriticReviewedCommit:exports_external.string().regex(HEX40,"must be a 40-hex commit SHA"),userApprovalVerbatim:exports_external.string().trim().min(1).max(8000)}).strict();async function executeRecordMergeApproval(args2,directory,context={}){let parsed=RecordMergeApprovalArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,message:`Invalid merge-approval receipt: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`});let data=parsed.data;if(data.prHeadSha!==data.finalCriticReviewedCommit)return JSON.stringify({success:!1,message:"Merge-approval binding failed: prHeadSha must equal finalCriticReviewedCommit (the final critic approval must be bound to the exact PR head)."});let receipt={issueNumber:data.issueNumber,prHeadSha:data.prHeadSha,finalCriticReviewedCommit:data.finalCriticReviewedCommit,userApprovalVerbatim:data.userApprovalVerbatim,timestamp:new Date().toISOString()};if(context.sessionID?.trim())receipt.sessionId=context.sessionID.trim();let validatedPath;try{validatedPath=validateSwarmPath(directory,"merge-approval.json")}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:"Failed to validate path"})}try{return await atomicWriteSwarmFile(validatedPath,JSON.stringify(receipt,null,2)),JSON.stringify({success:!0,issueNumber:data.issueNumber,path:".swarm/merge-approval.json",message:`Merge approval recorded for issue #${data.issueNumber}, bound to PR head ${data.prHeadSha}. The approval is captured verbatim for audit; the merge itself is human-enforced and this plugin neither drives nor certifies it.`})}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:String(error93)})}}var record_merge_approval=createSwarmTool({description:"Record the human merge approval for the current traced issue (issue #2564): prHeadSha and finalCriticReviewedCommit must be the same 40-hex SHA (the final critic approval bound to the exact PR head), and userApprovalVerbatim is the user approval quoted verbatim. The receipt is recorded for audit only — the merge stays human-enforced and the plugin never certifies or drives it.",args:{issueNumber:RecordMergeApprovalArgsSchema.shape.issueNumber,prHeadSha:RecordMergeApprovalArgsSchema.shape.prHeadSha,finalCriticReviewedCommit:RecordMergeApprovalArgsSchema.shape.finalCriticReviewedCommit,userApprovalVerbatim:RecordMergeApprovalArgsSchema.shape.userApprovalVerbatim},execute:executeRecordMergeApproval});init_zod();init_utils2();init_atomic_write();init_create_tool();var DispositionSchema=exports_external.object({ref:exports_external.string().trim().min(1).max(500),disposition:exports_external.enum(["FIX","FALSE_POSITIVE","OUT_OF_CLASS","DEFERRED_WITH_USER_APPROVAL"]),note:exports_external.string().trim().max(1000).optional()}).strict(),GuardrailSchema=exports_external.object({kind:exports_external.enum(["lint-static-analysis","type-level","runtime-assertion","ci-check","documented-invariant-plus-regression-test"]),description:exports_external.string().trim().min(8).max(2000),proof:exports_external.string().trim().min(8).max(4000)}).strict(),RelatedProblemSchema=exports_external.object({ref:exports_external.string().trim().min(1).max(500),note:exports_external.string().trim().max(1000).optional()}).strict(),RecordRecurrenceSweepArgsSchema=exports_external.object({issueNumber:exports_external.number().int().min(1),defectClass:exports_external.string().trim().min(1).max(1000),justification:exports_external.string().trim().min(1).max(1000).optional(),predicates:exports_external.array(exports_external.string().trim().min(1).max(500)).min(1).max(32).optional(),dispositions:exports_external.array(DispositionSchema).min(1).max(200).optional(),guardrail:GuardrailSchema.optional(),relatedProblems:exports_external.array(RelatedProblemSchema).min(1).max(200)}).strict();async function executeRecordRecurrenceSweep(args2,directory,context={}){let parsed=RecordRecurrenceSweepArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,message:`Invalid recurrence sweep receipt: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`});let data=parsed.data,noDefectClass=data.defectClass==="no defect class";if(noDefectClass){if(!data.justification)return JSON.stringify({success:!1,message:'The "no defect class" fast path requires a one-line justification.'})}else if(!data.predicates||data.predicates.length===0||!data.dispositions||data.dispositions.length===0||!data.guardrail)return JSON.stringify({success:!1,message:"A defect-class sweep requires search predicates, a non-empty disposition for every hit (at least one — the original defect site itself, dispositioned FIX), and a guardrail with proof it catches the original defect. An empty dispositions array is indistinguishable from a sweep that never ran."});let receipt={issueNumber:data.issueNumber,defectClass:data.defectClass,timestamp:new Date().toISOString()};if(data.justification)receipt.justification=data.justification;if(data.predicates)receipt.predicates=data.predicates;if(data.dispositions)receipt.dispositions=data.dispositions;if(data.guardrail)receipt.guardrail=data.guardrail;if(receipt.relatedProblems=data.relatedProblems,context.sessionID?.trim())receipt.sessionId=context.sessionID.trim();let validatedPath;try{validatedPath=validateSwarmPath(directory,"recurrence-sweep.json")}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:"Failed to validate path"})}try{return await atomicWriteSwarmFile(validatedPath,JSON.stringify(receipt,null,2)),JSON.stringify({success:!0,issueNumber:data.issueNumber,path:".swarm/recurrence-sweep.json",message:noDefectClass?`Recurrence sweep recorded for issue #${data.issueNumber} (no defect class fast path).`:`Recurrence sweep recorded for issue #${data.issueNumber}; the trace may now satisfy its recurrence gate.`})}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:String(error93)})}}var record_recurrence_sweep=createSwarmTool({description:'Record the recurrence sweep for the current traced issue (issue #2131 residual B; widened in #2564 and #2600). The /swarm issue --trace workflow will not hand off to commit-pr until this receipt exists. Supply relatedProblems (the Phase 1 related-problems sweep results — at least one {ref, note?} entry) plus, for a real defect class: defectClass (one-sentence characterization), predicates (the exact search predicates), dispositions (non-empty — every hit as FIX / FALSE_POSITIVE / OUT_OF_CLASS / DEFERRED_WITH_USER_APPROVAL, including the original defect site), and a guardrail (kind + description + proof it catches the original defect). If the change corrects no incorrect behavior, use the literal defectClass "no defect class" with a one-line justification (relatedProblems still required).',args:{issueNumber:RecordRecurrenceSweepArgsSchema.shape.issueNumber,defectClass:RecordRecurrenceSweepArgsSchema.shape.defectClass,justification:RecordRecurrenceSweepArgsSchema.shape.justification,predicates:RecordRecurrenceSweepArgsSchema.shape.predicates,dispositions:RecordRecurrenceSweepArgsSchema.shape.dispositions,guardrail:RecordRecurrenceSweepArgsSchema.shape.guardrail,relatedProblems:RecordRecurrenceSweepArgsSchema.shape.relatedProblems},execute:executeRecordRecurrenceSweep});init_zod();import*as fs208 from"node:fs";init_utils2();init_file_locks();init_atomic_write();init_create_tool();var HEX402=/^[0-9a-f]{40}$/,TRACE_VALIDATION_PHASES2=["0","1","2","2.5","3","4","4.2","4.5","4.6","5"],ValidationEntrySchema=exports_external.object({phase:exports_external.enum(TRACE_VALIDATION_PHASES2),outcome:exports_external.enum(["pass","fail"]),reviewedCommit:exports_external.string().regex(HEX402,"must be a 40-hex commit SHA"),treeId:exports_external.string().regex(HEX402,"must be a 40-hex tree id")}).strict(),RecordTraceValidationArgsSchema=ValidationEntrySchema.extend({issueNumber:exports_external.number().int().min(1)}).strict();async function executeRecordTraceValidation(args2,directory,context={}){let parsed=RecordTraceValidationArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,message:`Invalid trace-validation receipt: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`});let data=parsed.data,validatedPath;try{validatedPath=validateSwarmPath(directory,"trace-validation.json")}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:"Failed to validate path"})}try{let lockResult=await tryAcquireLock(directory,"trace-validation.json","trace-validation","trace-validation");if(!lockResult.acquired)return JSON.stringify({success:!1,message:"The trace-validation receipt is locked by another concurrent writer; no write was attempted. Re-run record_trace_validation for this phase once the other writer finishes."});try{let validations=[];try{let raw=await fs208.promises.readFile(validatedPath,"utf-8"),existing=JSON.parse(raw);if(typeof existing==="object"&&existing!==null&&Array.isArray(existing.validations))validations=existing.validations.filter((v)=>typeof v==="object"&&v!==null&&typeof v.phase==="string")}catch{}let entry={phase:data.phase,outcome:data.outcome,reviewedCommit:data.reviewedCommit,treeId:data.treeId,timestamp:new Date().toISOString()},idx=validations.findIndex((v)=>v.phase===data.phase);if(idx===-1)validations.push(entry);else validations[idx]=entry;let receipt={issueNumber:data.issueNumber,timestamp:new Date().toISOString(),validations};if(context.sessionID?.trim())receipt.sessionId=context.sessionID.trim();await atomicWriteSwarmFile(validatedPath,JSON.stringify(receipt,null,2));let allGreen=await traceValidationReceiptExists(directory,data.issueNumber);return JSON.stringify({success:!0,issueNumber:data.issueNumber,path:".swarm/trace-validation.json",allGreen,message:allGreen?`Validator receipt recorded for issue #${data.issueNumber} phase ${data.phase} (${data.outcome}); every recorded phase is green.`:`Validator receipt recorded for issue #${data.issueNumber} phase ${data.phase} (${data.outcome}), but at least one recorded phase is failing — fix and re-record that phase as a pass before handoff.`})}finally{try{await lockResult.lock._release?.()}catch{}}}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:String(error93)})}}var record_trace_validation=createSwarmTool({description:"Record one per-phase trace-check.sh validator outcome for the current traced issue (issue #2564): the phase (v3 enum 0..5 incl. 2.5/4.2/4.5/4.6), the outcome (pass or fail), and the exact reviewedCommit and treeId the validator reported. Re-running a phase replaces its entry. The /swarm issue --trace workflow will not hand off to commit-pr while any recorded phase is failing or none is recorded. The receipt write is serialized by a per-file receipt lock, and the response's allGreen field mirrors the gate reader's verdict on the persisted receipt (advisory for the calling agent — the reducer always recomputes it independently).",args:{issueNumber:RecordTraceValidationArgsSchema.shape.issueNumber,phase:RecordTraceValidationArgsSchema.shape.phase,outcome:RecordTraceValidationArgsSchema.shape.outcome,reviewedCommit:RecordTraceValidationArgsSchema.shape.reviewedCommit,treeId:RecordTraceValidationArgsSchema.shape.treeId},execute:executeRecordTraceValidation});init_zod();init_schema();init_gate_evidence();init_manager();init_path_identity();init_state2();init_stage_a_repair();import*as fs209 from"node:fs";import*as path345 from"node:path";async function forceRecoverReworkTask(directory,sessionID,options){let session=ensureAgentSession(sessionID,void 0,directory);if(!session||!session.agentName||stripKnownSwarmPrefix(session.agentName)!=="architect")throw Error("RECOVER_REWORK_ARCHITECT_REQUIRED: recover_rework_task requires an active architect session. The rework escape hatch is architect-only; a coder/reviewer/test_engineer cannot self-unblock a task.");let taskId=typeof options.taskId==="string"?options.taskId.trim():"";if(!taskId)throw Error('RECOVER_REWORK_UNKNOWN_TASK: recover_rework_task requires the exact plan task id (e.g. "1.1").');let plan=await loadPlanJsonOnly(directory);if(!plan){let planPath=path345.join(directory,".swarm","plan.json");if(fs209.existsSync(planPath))throw Error("PLAN_CORRUPT: .swarm/plan.json exists but could not be parsed (corrupt or schema-invalid). Repair or re-save the plan before recovering a rework_required task.");throw Error("PLAN_NOT_FOUND: no .swarm/plan.json — cannot recover a rework_required "+"task without a plan. Save a plan first.")}if(!new Set(plan.phases.flatMap((phase)=>phase.tasks.map((task2)=>task2.id))).has(taskId))throw Error(`RECOVER_REWORK_UNKNOWN_TASK: task ${taskId} is not in the current plan. Refusing to recover a foreign task id.`);let evidenceRead=await readTaskEvidenceState(directory,taskId);if(evidenceRead.kind==="unparseable")throw Error(`RECOVER_REWORK_EVIDENCE_CORRUPT: the workflow evidence file for task ${taskId} exists but could not be parsed (${evidenceRead.evidencePath}). Repair the evidence first (repair_gate_evidence or /swarm doctor); recovery cannot classify a corrupt evidence state.`);let evidence2=evidenceRead.kind==="ok"?evidenceRead.evidence:null,workflow=getTaskWorkflowSnapshot(evidence2);if(!evidence2||!workflow.authoritative)throw Error(`RECOVER_REWORK_NO_WORKFLOW: no durable task workflow evidence exists for task ${taskId} — there is no rework state to recover.`);if(workflow.state!=="rework_required")throw Error(`RECOVER_REWORK_STATE_REQUIRED: task ${taskId} is at ${workflow.state}, not rework_required. This recovery applies only to a task whose Stage B verdict moved it to rework_required without a code change. From coder_delegated, run pre_check_batch; for a genuine code defect, delegate the coder to repair it first.`);let wedgeMs=Date.parse(workflow.updatedAt);if(!Number.isFinite(wedgeMs))throw Error(`RECOVER_REWORK_GREEN_PRECHECK_REQUIRED: cannot prove pre-check recency (workflow updatedAt "${workflow.updatedAt}" is not a parseable timestamp — the evidence file for task ${taskId} is likely corrupt). Repair the evidence (repair_gate_evidence or /swarm doctor); re-running pre_check_batch cannot fix an unparseable timestamp.`);let greenness=await hasGreenPostSettlementPreCheck(directory,wedgeMs);if(!greenness.green){let sastHint=greenness.reason==="no_pre_check_bundles"?" Note: if gates.sast_scan.enabled is false, no sast_scan bundle is ever persisted and this recovery is unavailable by design — enable gates.sast_scan.enabled and run sast_scan, or use the coder repair loop.":"";throw Error(`RECOVER_REWORK_GREEN_PRECHECK_REQUIRED: refusing to mark Stage A passed without proof (${greenness.reason}). `+"The bar is a green secretscan AND sast_scan evidence pair newer than the failing verdict — normally provided by a fresh pre_check_batch run (bundle proof is global, not correlated to the task's changed files)."+sastHint)}let sanitizedReason=typeof options.reason==="string"&&options.reason.trim().length>0?sanitizeDiagnosticText(options.reason.trim(),500):void 0,recordedAt=new Date().toISOString(),transitionId=`rework-recovery:${taskId}:gen${workflow.generation}`,updated=await transitionTaskWorkflowEvidence(directory,taskId,{type:"stage_a_passed",supervisedRecovery:!0,expectedGeneration:workflow.generation,transitionId}),updatedWorkflow=getTaskWorkflowSnapshot(updated),auditEventRecorded=await appendStageARepairEvent(directory,{action:"rework_recovered",taskId,transitionId,generation:workflow.generation,sessionId:sessionID,...sanitizedReason?{reason:sanitizedReason}:{}});return{taskId,generation:updatedWorkflow.generation,state:updatedWorkflow.state,transitionId,recordedAt,auditEventRecorded}}init_create_tool();var RecoverReworkTaskArgsSchema=exports_external.object({task_id:exports_external.string().trim().min(1).max(64).describe('Exact plan task id of the rework_required task (e.g. "1.1"). Must exist in the current plan and have durable workflow evidence at state rework_required.'),reason:exports_external.string().trim().min(1).max(500).describe('Why the Stage B verdict did not require a code change (e.g. "test_engineer returned SKIPPED for a tool-argument error while pytest passes"). Audited to .swarm/events.jsonl.')}).strict();async function executeRecoverReworkTask(args2,directory,context={}){let parsed=RecoverReworkTaskArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,message:`Invalid recover_rework_task call: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`});if(!context.sessionID?.trim())return JSON.stringify({success:!1,message:"recover_rework_task requires an active sessionID"});try{let summary=await forceRecoverReworkTask(directory,context.sessionID,{taskId:parsed.data.task_id,reason:parsed.data.reason}),auditNote=summary.auditEventRecorded?"The recovery is audited to .swarm/events.jsonl (stage_a_repair action rework_recovered).":"WARNING: the audit event could NOT be appended to .swarm/events.jsonl (see the plugin log); the durable workflow evidence still records the supervised recovery via the rework-recovery: transition id.";return JSON.stringify({success:!0,task_id:summary.taskId,generation:summary.generation,state:summary.state,transition_id:summary.transitionId,recorded_at:summary.recordedAt,audit_event_recorded:summary.auditEventRecorded,method:"supervised_recovery",message:`Task ${summary.taskId} recovered from rework_required: a supervised stage_a_passed was written at generation ${summary.generation} (transition id `+summary.transitionId+"). Reviewer/test_engineer dispatch is permitted again — re-run the Stage B gates that the failed verdict cleared. "+auditNote+" Use it ONLY when the Stage B verdict did not require a code change; a genuine defect still needs the coder repair loop."})}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:String(error93)})}}var recover_rework_task=createSwarmTool({description:"Recover a task wedged at rework_required when the Stage B verdict did NOT require a code change (issue #2755): writes a supervised stage_a_passed for the current generation so reviewer/test_engineer can be re-dispatched, without re-running the coder. Requires the exact plan task id, an active architect session, durable workflow state exactly rework_required, and green pre-check proof: green secretscan AND sast_scan evidence bundles newer than the failing verdict (normally from a fresh pre_check_batch run; bundle recency is global, not file-correlated; projects with SAST disabled cannot use this path). Fail-closed otherwise; the mechanical stage_a_passed path still requires an accepted coder mutation. A reason is required and audited to .swarm/events.jsonl (stage_a_repair action rework_recovered). Prefer the coder repair loop when the code actually has a defect.",args:{task_id:RecoverReworkTaskArgsSchema.shape.task_id,reason:RecoverReworkTaskArgsSchema.shape.reason},execute:executeRecoverReworkTask});init_zod();init_schema();init_gate_evidence();init_path_identity();init_state2();init_coder_settlement();init_stage_a_repair();async function recoverStageATaskSupervised(directory,sessionID,options){let session=ensureAgentSession(sessionID,void 0,directory);if(!session||!session.agentName||stripKnownSwarmPrefix(session.agentName)!=="architect")throw Error("RECOVER_STAGE_A_ARCHITECT_REQUIRED: recover_stage_a_task requires an active architect session. The settlement-backed Stage A escape hatch is architect-only; a coder/reviewer/test_engineer cannot self-unblock a task.");let taskId=typeof options.taskId==="string"?options.taskId.trim():"";if(!taskId)throw Error('RECOVER_STAGE_A_UNKNOWN_TASK: recover_stage_a_task requires the exact task id of the settlement-wedged task (e.g. "1.1").');let sanitizedReason=typeof options.reason==="string"&&options.reason.trim().length>0?sanitizeDiagnosticText(options.reason.trim(),500):void 0;if(!sanitizedReason)throw Error("RECOVER_STAGE_A_REASON_REQUIRED: recover_stage_a_task requires a reason describing why the settlement-backed recovery is justified; it is audited to .swarm/events.jsonl.");let evidenceRead=await readTaskEvidenceState(directory,taskId);if(evidenceRead.kind==="unparseable")throw Error(`RECOVER_STAGE_A_EVIDENCE_CORRUPT: the workflow evidence file for task ${taskId} exists but could not be parsed (${evidenceRead.evidencePath}). Repair the evidence first (repair_gate_evidence or /swarm doctor); recovery cannot classify a corrupt evidence state.`);let evidence2=evidenceRead.kind==="ok"?evidenceRead.evidence:null,workflow=getTaskWorkflowSnapshot(evidence2);if(!evidence2||!workflow.authoritative)throw Error(`RECOVER_STAGE_A_NO_WORKFLOW: no durable task workflow evidence exists for task ${taskId} — there is no settlement wedge to recover.`);if(workflow.state==="pre_check_passed"||workflow.state==="reviewer_run"||workflow.state==="tests_run")return{taskId,generation:workflow.generation,state:workflow.state,transitionId:`stage-a-supervised:${taskId}:noop`,recordedAt:new Date().toISOString(),alreadyRecovered:!0,auditEventRecorded:!1};if(workflow.state!=="idle"&&workflow.state!=="blocked")throw Error(`RECOVER_STAGE_A_STATE_REQUIRED: task ${taskId} is at ${workflow.state}, not idle/blocked. This recovery applies only to the settlement-backed wedge (a COMMITTED accepted coder settlement while the workflow drifted to idle or blocked). From coder_delegated, run pre_check_batch or /swarm recover; from rework_required without a code change, use recover_rework_task.`);let{states:walStates}=await listCoderSettlementWalStates(directory),settledAfterMs=latestCommittedAcceptedSettlementMs(taskId,walStates);if(settledAfterMs===null)throw Error(`RECOVER_STAGE_A_SETTLEMENT_REQUIRED: refusing to recover task ${taskId} — no COMMITTED accepted coder settlement exists for it. `+"The settlement receipt is what distinguishes this wedge from a not-yet-started or deliberately stopped task; recovery without it would fabricate Stage A justification. Background-dispatched coder tasks never write a settlement WAL and cannot use this path.");let greenness=await hasGreenPostSettlementPreCheck(directory,settledAfterMs);if(!greenness.green){let sastHint=greenness.reason==="no_pre_check_bundles"?" Note: if gates.sast_scan.enabled is false, no sast_scan bundle is ever persisted and this recovery is unavailable by design — enable gates.sast_scan.enabled and run sast_scan, or use the coder repair loop.":"";throw Error(`RECOVER_STAGE_A_GREEN_PRECHECK_REQUIRED: refusing to mark Stage A passed without proof (${greenness.reason}). `+"The bar is a green secretscan AND sast_scan evidence pair newer than the settlement commit — normally provided by a fresh pre_check_batch run (bundle proof is global, not correlated to the task's changed files)."+sastHint)}let recordedAt=new Date().toISOString(),transitionId=`stage-a-supervised:${taskId}:${workflow.generation}`,updated=await transitionTaskWorkflowEvidence(directory,taskId,{type:"stage_a_passed",settlementRecovery:!0,expectedGeneration:workflow.generation,transitionId}),updatedWorkflow=getTaskWorkflowSnapshot(updated),auditEventRecorded=await appendStageARepairEvent(directory,{action:"repaired",via:"recover_stage_a_task",taskId,transitionId,generation:workflow.generation,settlementRecovery:!0,predecessorTransitionId:workflow.lastTransitionId??null,sessionId:sessionID,reason:sanitizedReason});return{taskId,generation:updatedWorkflow.generation,state:updatedWorkflow.state,transitionId,recordedAt,alreadyRecovered:!1,auditEventRecorded}}init_create_tool();var RecoverStageATaskArgsSchema=exports_external.object({task_id:exports_external.string().trim().min(1).max(64).describe('Exact task id of the settlement-wedged task (e.g. "1.1"). Must have durable workflow evidence at state idle or blocked, a COMMITTED accepted coder settlement, and green post-settlement pre-check proof.'),reason:exports_external.string().trim().min(1).max(500).describe('Why the settlement-backed recovery is justified (e.g. "settlement COMMITTED and pre_check_batch green but stage_a_passed never fired; force-repair cleared the proofs"). Audited to .swarm/events.jsonl.')}).strict();async function executeRecoverStageATask(args2,directory,context={}){let parsed=RecoverStageATaskArgsSchema.safeParse(args2);if(!parsed.success)return JSON.stringify({success:!1,message:`Invalid recover_stage_a_task call: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`});if(!context.sessionID?.trim())return JSON.stringify({success:!1,message:"recover_stage_a_task requires an active sessionID"});try{let summary=await recoverStageATaskSupervised(directory,context.sessionID,{taskId:parsed.data.task_id,reason:parsed.data.reason});if(summary.alreadyRecovered)return JSON.stringify({success:!0,task_id:summary.taskId,generation:summary.generation,state:summary.state,already_recovered:!0,message:`Task ${summary.taskId} already has Stage A recorded (state ${summary.state}, generation ${summary.generation}) — nothing to recover.`});let auditNote=summary.auditEventRecorded?"The recovery is audited to .swarm/events.jsonl (stage_a_repair action repaired, via recover_stage_a_task).":"WARNING: the audit event could NOT be appended to .swarm/events.jsonl (see the plugin log); the durable workflow evidence still records the settlement-backed recovery via the stage-a-supervised: transition id and the settlementRecovery marker.";return JSON.stringify({success:!0,task_id:summary.taskId,generation:summary.generation,state:summary.state,transition_id:summary.transitionId,recorded_at:summary.recordedAt,audit_event_recorded:summary.auditEventRecorded,method:"settlement_recovery",message:`Task ${summary.taskId} recovered from the settlement wedge: a settlement-backed stage_a_passed was written at generation ${summary.generation} (transition id `+summary.transitionId+"). Reviewer/test_engineer dispatch is permitted again — run the Stage B gates the task still needs. "+auditNote+" Use it ONLY when a COMMITTED accepted settlement and green post-settlement pre-check proof already justify Stage A; it never re-runs the coder and never edits gate evidence."})}catch(error93){return JSON.stringify({success:!1,message:error93 instanceof Error?error93.message:String(error93)})}}var recover_stage_a_task=createSwarmTool({description:"Recover a task wedged in the settlement-backed Stage A deadlock (issue #2828): workflow at idle or blocked while a COMMITTED accepted coder settlement and green post-settlement pre-check proof (green secretscan AND sast_scan evidence newer than the settlement commit) still justify Stage A — the shape where stage_a_passed never fired, a force-repair cleared the proofs, and every other recovery path refuses. Writes a settlement-backed stage_a_passed for the current generation so reviewer/test_engineer can be dispatched, without re-running the coder and without editing gate evidence. Requires the exact task id (bound by its durable workflow evidence and settlement WAL — deliberately no plan-membership precondition, mirroring the /swarm recover scan), an active architect session, a reason (audited), and durable workflow evidence at exactly idle/blocked. Fail-closed otherwise (RECOVER_STAGE_A_* errors); the mechanical stage_a_passed path still requires an accepted coder mutation or the #2665 live_wedge scan.",args:{task_id:RecoverStageATaskArgsSchema.shape.task_id,reason:RecoverStageATaskArgsSchema.shape.reason},execute:executeRecoverStageATask});init_zod();init_schema();init_gate_evidence();init_utils2();init_manager();init_state2();init_project_boundary();init_swarm_artifact_cache();init_task_id();init_task_file();init_task_gate_requirements();init_gate_evidence();import{createHash as createHash111,randomUUID as randomUUID47}from"node:crypto";import*as fs210 from"node:fs";import*as path346 from"node:path";var TASK_GATE_EVIDENCE_QUARANTINE_DIR=path346.join("evidence","task-gate-quarantine"),MAX_TASK_GATE_EVIDENCE_BYTES=262144,MAX_TASK_GATE_EVIDENCE_QUARANTINE_FILES=32,MAX_TASK_GATE_EVIDENCE_QUARANTINE_BYTES=12582912,MAX_TASK_GATE_EVIDENCE_QUARANTINE_DIRECTORY_ENTRIES=128,MAX_TASK_GATE_EVIDENCE_QUARANTINE_RECORD_BYTES=786432,TASK_GATE_EVIDENCE_QUARANTINE_SCHEMA_VERSION=1,GENERIC_REPAIR_REASONS=new Set(["fix","repair","test","debug","unknown","n/a","na","none"]);function isQuarantinableTaskEvidenceRead(read){return read.status==="corrupt"||read.status==="valid"}function sha25612(bytes){return createHash111("sha256").update(bytes).digest("hex")}function normalizeRepairReason(reason){let normalized=reason.trim().replace(/\s+/g," ");if(normalized.length<12)throw Error("TASK_GATE_EVIDENCE_REASON_REQUIRED: repair_gate_evidence requires a substantive reason of at least 12 characters.");if(GENERIC_REPAIR_REASONS.has(normalized.toLowerCase()))throw Error("TASK_GATE_EVIDENCE_REASON_REQUIRED: repair_gate_evidence requires a substantive reason, not a placeholder.");return normalized}function canonicalizeRepairRoot(directory){let requestedRoot=path346.resolve(directory),requestedStat=fs210.lstatSync(requestedRoot);if(requestedStat.isSymbolicLink()||!requestedStat.isDirectory())throw Error("TASK_GATE_EVIDENCE_ROOT_UNSAFE: repair_gate_evidence requires a canonical project root directory, not a symlink, junction, reparse point, or non-directory path.");let canonicalRoot2=fs210.realpathSync(requestedRoot);return assertProjectRoot(canonicalRoot2),canonicalRoot2}function assertExistingRegularPath(root,relativePath2){let segments=relativePath2.replace(/\\/g,"/").split("/").filter(Boolean),cursor=root;for(let segment of segments){if(cursor=path346.join(cursor,segment),!fs210.existsSync(cursor))return;if(fs210.lstatSync(cursor).isSymbolicLink())throw Error(`TASK_GATE_EVIDENCE_PATH_UNSAFE: ${relativePath2} contains a symlink, junction, or reparse point.`)}}function taskEvidenceFilePath(directory,taskId){let relativePath2=taskEvidenceRelPath(taskId);return assertExistingRegularPath(directory,".swarm"),assertExistingRegularPath(directory,path346.join(".swarm","evidence")),assertExistingRegularPath(directory,path346.join(".swarm",relativePath2)),validateSwarmPath(directory,relativePath2)}function readTaskEvidenceForRepair(directory,taskId){let filePath=taskEvidenceFilePath(directory,taskId),pathStat;try{pathStat=fs210.lstatSync(filePath)}catch(error93){if(error93.code==="ENOENT")return{status:"missing"};return{status:"unreadable",filePath,bytes:Buffer.alloc(0),sha256:sha25612(""),error:error93}}if(pathStat.isSymbolicLink()||!pathStat.isFile())return{status:"unreadable",filePath,bytes:Buffer.alloc(0),sha256:sha25612(""),error:Error("TASK_GATE_EVIDENCE_UNREADABLE: evidence path is not a regular file")};if(pathStat.size>MAX_TASK_GATE_EVIDENCE_BYTES)return{status:"oversized",filePath,bytes:Buffer.alloc(0),sha256:sha25612(""),error:Error(`TASK_GATE_EVIDENCE_OVERSIZED: ${pathStat.size} bytes exceeds ${MAX_TASK_GATE_EVIDENCE_BYTES}`)};let descriptor=fs210.openSync(filePath,fs210.constants.O_RDONLY|(fs210.constants.O_NOFOLLOW??0));try{let openedStat=fs210.fstatSync(descriptor);if(!openedStat.isFile()||openedStat.dev!==pathStat.dev||openedStat.ino!==pathStat.ino)return{status:"unreadable",filePath,bytes:Buffer.alloc(0),sha256:sha25612(""),error:Error("TASK_GATE_EVIDENCE_UNREADABLE: evidence changed while being opened")};let bytes=fs210.readFileSync(descriptor);if(bytes.byteLength>MAX_TASK_GATE_EVIDENCE_BYTES)return{status:"oversized",filePath,bytes:Buffer.alloc(0),sha256:sha25612(""),error:Error(`TASK_GATE_EVIDENCE_OVERSIZED: ${bytes.byteLength} bytes exceeds ${MAX_TASK_GATE_EVIDENCE_BYTES}`)};let digest5=sha25612(bytes);try{let evidence2=parseTaskEvidence(bytes.toString("utf8"),taskId);return{status:"valid",filePath,bytes,sha256:digest5,evidence:evidence2,generation:evidence2.workflow?.generation}}catch(error93){return{status:"corrupt",filePath,bytes,sha256:digest5,error:error93}}}finally{try{fs210.closeSync(descriptor)}catch{}}}function taskGateEvidenceQuarantinePath(directory,taskId,digest5){return validateSwarmPath(directory,path346.join(TASK_GATE_EVIDENCE_QUARANTINE_DIR,`${taskId}.${digest5}.v${TASK_GATE_EVIDENCE_QUARANTINE_SCHEMA_VERSION}.json`))}function parseErrorMetadata(error93){if(!error93)return null;return{name:error93.name||"Error",message:error93.message||String(error93),code:typeof error93.code==="string"?error93.code:null}}function parseQuarantineRecord(raw){try{let parsed=JSON.parse(raw);if(parsed?.schemaVersion!==TASK_GATE_EVIDENCE_QUARANTINE_SCHEMA_VERSION||typeof parsed.taskId!=="string"||typeof parsed.recordedAt!=="string"||typeof parsed.reason!=="string"||typeof parsed.original?.path!=="string"||typeof parsed.original?.sha256!=="string"||typeof parsed.content?.bytes!=="string"||parsed.content?.encoding!=="base64")return null;return parsed}catch{return null}}function buildQuarantineRecord(taskId,read,reason,context,receiptGeneration){let agentName=context?.sessionID!=null?swarmState.activeAgent.get(context.sessionID)??swarmState.agentSessions.get(context.sessionID)?.agentName??null:null;return{schemaVersion:TASK_GATE_EVIDENCE_QUARANTINE_SCHEMA_VERSION,taskId,recordedAt:new Date().toISOString(),reason,caller:{sessionId:context?.sessionID?.trim()||null,messageId:context?.messageID?.trim()||null,agentName},original:{path:read.filePath,sha256:read.sha256,sizeBytes:read.bytes.byteLength,status:read.status,observedGeneration:read.generation??null,receiptGeneration,requirementsState:read.evidence?.requirements_state??null},parseError:parseErrorMetadata(read.error),content:{encoding:"base64",bytes:read.bytes.toString("base64")}}}async function quarantineTaskEvidenceBytes(directory,taskId,read,reason,context,receiptGeneration){let digest5=read.sha256,quarantineDir=validateSwarmPath(directory,TASK_GATE_EVIDENCE_QUARANTINE_DIR);await fs210.promises.mkdir(quarantineDir,{recursive:!0});let dirStat=await fs210.promises.lstat(quarantineDir);if(dirStat.isSymbolicLink()||!dirStat.isDirectory())throw Error("TASK_GATE_EVIDENCE_QUARANTINE_UNREADABLE: quarantine is not a regular directory");let target=taskGateEvidenceQuarantinePath(directory,taskId,digest5),record3=buildQuarantineRecord(taskId,read,reason,context,receiptGeneration),serialized3=JSON.stringify(record3,null,2),serializedBytes=Buffer.byteLength(serialized3,"utf8");if(serializedBytes>MAX_TASK_GATE_EVIDENCE_QUARANTINE_RECORD_BYTES)throw Error("TASK_GATE_EVIDENCE_QUARANTINE_FULL: quarantine payload exceeds the bounded record size limit");let reconcileExisting=async()=>{let existingStat;try{existingStat=await fs210.promises.lstat(target)}catch(error93){if(error93.code==="ENOENT")return!1;throw error93}if(existingStat.isSymbolicLink()||!existingStat.isFile())throw Error("TASK_GATE_EVIDENCE_QUARANTINE_MISMATCH: existing quarantine path is not a regular immutable record");let existingRaw=await fs210.promises.readFile(target,"utf8"),existingRecord=parseQuarantineRecord(existingRaw);if(existingRecord&&existingRecord.taskId===taskId&&existingRecord.original.path===read.filePath&&existingRecord.original.sha256===read.sha256&&existingRecord.content.bytes===read.bytes.toString("base64"))return!0;throw Error("TASK_GATE_EVIDENCE_QUARANTINE_MISMATCH: existing quarantine record does not match the repaired evidence source")};if(await reconcileExisting())return{digest:digest5,filePath:target};let count=0,totalBytes=0,scanned=0,handle=await fs210.promises.opendir(quarantineDir,{bufferSize:16});try{for await(let entry of handle){if(scanned+=1,scanned>MAX_TASK_GATE_EVIDENCE_QUARANTINE_DIRECTORY_ENTRIES)throw Error("TASK_GATE_EVIDENCE_QUARANTINE_FULL: too many quarantine entries");if(!entry.isFile()||!/^[0-9.]+\.[a-f0-9]{64}\.v1\.json$/.test(entry.name))continue;count+=1;let candidate2=path346.join(quarantineDir,entry.name),candidateStat=await fs210.promises.lstat(candidate2);if(candidateStat.isSymbolicLink()||!candidateStat.isFile())throw Error("TASK_GATE_EVIDENCE_QUARANTINE_UNREADABLE: invalid quarantine artifact");if(totalBytes+=candidateStat.size,count>=MAX_TASK_GATE_EVIDENCE_QUARANTINE_FILES||totalBytes+serializedBytes>MAX_TASK_GATE_EVIDENCE_QUARANTINE_BYTES)throw Error("TASK_GATE_EVIDENCE_QUARANTINE_FULL: quarantine retention limit reached")}}finally{try{await handle.close()}catch{}}let tempPath=path346.join(quarantineDir,`.pending.${process.pid}.${randomUUID47()}.json`),fileHandle;try{fileHandle=await fs210.promises.open(tempPath,"wx"),await fileHandle.writeFile(serialized3,"utf8"),await fileHandle.sync(),await fileHandle.close(),fileHandle=void 0,invalidateCachedArtifact(tempPath),await fs210.promises.link(tempPath,target),invalidateCachedArtifact(target)}catch(error93){if(error93.code!=="EEXIST")throw error93;if(await reconcileExisting())return{digest:digest5,filePath:target};throw error93}finally{await fileHandle?.close().catch(()=>{return}),await fs210.promises.unlink(tempPath).catch(()=>{return})}return{digest:digest5,filePath:target}}function buildRepairTransitionId(taskId,source){return`repair_gate_evidence:${taskId}:${source.slice(0,32)}`}function withoutLegacyReconstructionGate(gates){return[...new Set(gates.filter((gate)=>gate!==TASK_GATE_REQUIREMENTS_RECONSTRUCTION_SENTINEL))].sort()}function hasLegacyReconstructionGate(gates){return gates.includes(TASK_GATE_REQUIREMENTS_RECONSTRUCTION_SENTINEL)}function buildKnownRepairedEvidence(taskId,receipt,generation,source){let requiredGates=withoutLegacyReconstructionGate(receipt.requiredGates);if(requiredGates.length!==receipt.requiredGates.length)throw Error("TASK_GATE_REQUIREMENTS_RECEIPT_TAINTED: legacy reconstruction markers cannot seed known requirements.");return{taskId,required_gates:requiredGates,gates:{},requirements_state:"known",test_engineer_exempt:receipt.testEngineerExempt??void 0,workflow:{schema:TASK_WORKFLOW_SCHEMA_MARKER,generation,state:"idle",retryCount:0,retryHistory:[],retryEpoch:0,lastOutcome:"repair_idle",lastTransitionId:buildRepairTransitionId(taskId,receipt.chainHash),updatedAt:new Date().toISOString()},repair_provenance:{source_sha256:source.sha256,source_generation:source.generation,requirements_receipt_hash:receipt.chainHash}}}function buildUnknownRepairedEvidence(taskId,requiredGates,seedGeneration,source,receiptHash){return{taskId,required_gates:withoutLegacyReconstructionGate(requiredGates),gates:{},requirements_state:"unknown",workflow:{schema:TASK_WORKFLOW_SCHEMA_MARKER,generation:seedGeneration,state:"idle",retryCount:0,retryHistory:[],retryEpoch:0,lastOutcome:"repair_idle",lastTransitionId:buildRepairTransitionId(taskId,"unknown"),updatedAt:new Date().toISOString()},repair_provenance:{source_sha256:source.sha256,source_generation:source.generation,requirements_receipt_hash:receiptHash}}}function canonicalizeTaskEvidence(taskId,evidence2){let validated=parseTaskEvidence(JSON.stringify({...evidence2,taskId}),taskId);return JSON.stringify(validated,null,2)}function isRepairWorkflowReset(taskId,workflow){return workflow!=null&&workflow.state==="idle"&&workflow.retryCount===0&&workflow.retryEpoch===0&&workflow.retryHistory.length===0&&workflow.lastOutcome==="repair_idle"&&typeof workflow.lastTransitionId==="string"&&workflow.lastTransitionId.startsWith(`repair_gate_evidence:${taskId}:`)}function isReceiptlessLegacySentinelReset(taskId,evidence2){return evidence2!=null&&isRepairWorkflowReset(taskId,evidence2.workflow)&&evidence2.requirements_state==="unknown"&&evidence2.required_gates.length===1&&evidence2.required_gates[0]===TASK_GATE_REQUIREMENTS_RECONSTRUCTION_SENTINEL&&Object.keys(evidence2.gates).length===0&&evidence2.repair_provenance!=null&&typeof evidence2.repair_provenance.source_sha256==="string"&&(evidence2.repair_provenance.source_generation===null||evidence2.repair_provenance.source_generation<evidence2.workflow.generation)&&evidence2.repair_provenance.requirements_receipt_hash===null}function isAlreadyRepairedEvidence(taskId,evidence2,receipt){if(!evidence2||!isRepairWorkflowReset(taskId,evidence2.workflow))return!1;if(Object.keys(evidence2.gates).length!==0)return!1;if(hasLegacyReconstructionGate(evidence2.required_gates))return!1;let receiptIsTainted=receipt!=null&&hasLegacyReconstructionGate(receipt.requiredGates);if(receipt&&!receiptIsTainted)return evidence2.requirements_state==="known"&&JSON.stringify(evidence2.required_gates)===JSON.stringify(receipt.requiredGates)&&evidence2.workflow.generation>receipt.generation&&(evidence2.test_engineer_exempt??null)===(receipt.testEngineerExempt??null)&&evidence2.repair_provenance?.requirements_receipt_hash===receipt.chainHash;if(!receipt||!receiptIsTainted)return!1;return evidence2.requirements_state==="unknown"&&evidence2.workflow.generation>=1&&evidence2.repair_provenance!=null&&evidence2.repair_provenance.requirements_receipt_hash===receipt.chainHash&&withoutLegacyReconstructionGate(receipt.requiredGates).every((gate)=>evidence2.required_gates.includes(gate))}function repairedEvidenceMatchesCas(evidence2,args2){let provenance=evidence2.repair_provenance;if(!provenance)return args2.expected_sha256==null&&args2.expected_generation==null;return(args2.expected_sha256==null||provenance.source_sha256===args2.expected_sha256)&&(args2.expected_generation==null||provenance.source_generation===args2.expected_generation)}function buildRepairNextActions(taskId,evidence2){if(evidence2.requirements_state==="known")return[`Delegate coder on task ${taskId} to produce a fresh accepted_mutation for the repaired evidence generation ${evidence2.workflow?.generation}.`,`Rerun Stage A for task ${taskId} until pre_check passes for the new generation.`,`Rerun Stage B gates [${evidence2.required_gates.join(", ")}] for task ${taskId} before attempting completion again.`];return[`Delegate coder on task ${taskId} to produce a fresh accepted mutation and regenerate authoritative required gates for a new exact-task generation.`,`Rerun Stage A for task ${taskId} after the new mutation is recorded.`,`Rerun the exact Stage B gates for task ${taskId} only after authoritative required gates are re-recorded; the idle recovery generation cannot complete directly.`]}function invalidateTaskEvidenceSessionFallbacks(taskId){for(let session of swarmState.agentSessions.values()){if(session.currentTaskId===taskId)session.currentTaskId=null;if(session.lastCoderDelegationTaskId===taskId)session.lastCoderDelegationTaskId=null;if(session.taskWorkflowStates?.delete(taskId),session.taskWorkflowCache?.delete(taskId),session.stageBCompletion?.delete(taskId),session.taskCouncilApproved?.delete(taskId),session.taskCouncilWorkflowGeneration?.delete(taskId),session.gateLog?.delete(taskId),session.partialGateWarningsIssuedForTask?.delete(taskId),session.completionGateWarnedForTask?.delete(taskId),session.lastGateFailure?.taskId===taskId)session.lastGateFailure=null}}async function repairTaskGateEvidence(args2,directory,context){assertStrictTaskId(args2.task_id);let normalizedReason=normalizeRepairReason(args2.reason),canonicalDirectory=canonicalizeRepairRoot(directory);if(!(await loadPlan(canonicalDirectory))?.phases.flatMap((phase)=>phase.tasks).find((candidate2)=>candidate2.id===args2.task_id))return{success:!1,message:`TASK_GATE_EVIDENCE_TASK_MISSING: ${args2.task_id} is not present in the loaded plan`,errors:[`Task ${args2.task_id} is not present in .swarm/plan.json.`]};return withTaskEvidenceLock(canonicalDirectory,args2.task_id,"repair_gate_evidence",async()=>{let read=readTaskEvidenceForRepair(canonicalDirectory,args2.task_id),latestReceipt=(await readTaskGateRequirementsReceipts(canonicalDirectory,args2.task_id)).at(-1),evidenceHasLegacyMarker=read.status==="valid"&&read.evidence!=null&&hasLegacyReconstructionGate(read.evidence.required_gates),receiptHasLegacyMarker=latestReceipt!=null&&hasLegacyReconstructionGate(latestReceipt.requiredGates);if(read.status==="valid"&&isAlreadyRepairedEvidence(args2.task_id,read.evidence,latestReceipt)){if(!repairedEvidenceMatchesCas(read.evidence,args2))return{success:!1,message:"TASK_GATE_EVIDENCE_CAS_MISMATCH",errors:["TASK_GATE_EVIDENCE_CAS_MISMATCH: the existing repaired generation was created from a different source identity."]};let nextActions2=buildRepairNextActions(args2.task_id,read.evidence);return{success:!0,repaired:!1,task_id:args2.task_id,required_gates:[...read.evidence.required_gates],requirements_state:read.evidence.requirements_state,repaired_generation:read.evidence.workflow?.generation,next_actions:nextActions2,message:`Task gate evidence for ${args2.task_id} is already in repaired fail-closed state.`}}if(read.status==="valid"&&read.evidence?.workflow?.schema===TASK_WORKFLOW_SCHEMA_MARKER&&!evidenceHasLegacyMarker&&latestReceipt!=null&&!receiptHasLegacyMarker)return{success:!1,message:"TASK_GATE_EVIDENCE_REPAIR_NOT_REQUIRED",errors:[`TASK_GATE_EVIDENCE_REPAIR_NOT_REQUIRED: ${args2.task_id} has valid authoritative evidence. Use the normal workflow repair path; this tool only rebuilds corrupt or legacy evidence.`]};if(read.status==="valid"&&read.evidence?.requirements_state==="known"&&!evidenceHasLegacyMarker&&receiptHasLegacyMarker)return{success:!1,message:"TASK_GATE_REQUIREMENTS_RECEIPT_STALE",errors:[`TASK_GATE_REQUIREMENTS_RECEIPT_STALE: ${args2.task_id} has clean accepted-mutation evidence but its latest requirements receipt is legacy-tainted. Repair was refused without modifying evidence; replay the prepared coder settlement so it can publish the exact hash-linked receipt.`]};if(typeof args2.expected_sha256==="string"&&read.status!=="missing"&&read.sha256!==args2.expected_sha256)return{success:!1,message:"TASK_GATE_EVIDENCE_CAS_MISMATCH",errors:[`TASK_GATE_EVIDENCE_CAS_MISMATCH: expected sha256 ${args2.expected_sha256}, found ${read.sha256}.`]};if(typeof args2.expected_generation==="number"){let observedGeneration=read.status==="valid"?read.generation:latestReceipt?.generation;if(observedGeneration!==args2.expected_generation)return{success:!1,message:"TASK_GATE_EVIDENCE_CAS_MISMATCH",errors:[`TASK_GATE_EVIDENCE_CAS_MISMATCH: expected generation ${args2.expected_generation}, found ${observedGeneration??"unknown"}.`]}}if(read.status==="unreadable"||read.status==="oversized")return{success:!1,message:read.error?.message??"TASK_GATE_EVIDENCE_UNREADABLE: repair requires operator intervention before evidence can be rewritten.",errors:[read.error?.message??`TASK_GATE_EVIDENCE_UNREADABLE: ${args2.task_id} could not be read safely for repair.`]};if(evidenceHasLegacyMarker&&latestReceipt==null&&!isReceiptlessLegacySentinelReset(args2.task_id,read.evidence))return{success:!1,message:"TASK_GATE_REQUIREMENTS_RECEIPT_MISSING",errors:[`TASK_GATE_REQUIREMENTS_RECEIPT_MISSING: ${args2.task_id} is marker-bearing but does not match the exact receipt-less state emitted by the historical repair flow. Repair was refused without modifying evidence or session state.`]};let nextGeneration2=Math.max(read.status==="valid"?read.generation??-1:-1,latestReceipt?.generation??-1)+1,nextEvidence;if(evidenceHasLegacyMarker||receiptHasLegacyMarker){let preservedGates=withoutLegacyReconstructionGate([...read.status==="valid"?read.evidence?.required_gates??[]:[],...latestReceipt?.requiredGates??[]]);nextEvidence=buildUnknownRepairedEvidence(args2.task_id,preservedGates,Math.max(nextGeneration2,1),{sha256:read.status==="missing"?null:read.sha256,generation:read.status==="valid"?read.generation??null:latestReceipt?.generation??null},latestReceipt?.chainHash??null)}else if(latestReceipt)nextEvidence=buildKnownRepairedEvidence(args2.task_id,latestReceipt,nextGeneration2,{sha256:read.status==="missing"?null:read.sha256,generation:read.status==="valid"?read.generation??null:latestReceipt.generation??null});else if(read.status==="missing")return{success:!1,message:"TASK_GATE_EVIDENCE_ABSENT",errors:[`TASK_GATE_EVIDENCE_ABSENT: ${args2.task_id} has no evidence file and no authoritative requirements receipt to rebuild from.`]};else return{success:!1,message:"TASK_GATE_REQUIREMENTS_RECEIPT_MISSING",errors:[`TASK_GATE_REQUIREMENTS_RECEIPT_MISSING: ${args2.task_id} has no authoritative requirements receipt. Receipt-less repair was refused without modifying the original evidence because its required gates cannot be reconstructed safely.`]};let serialized3=canonicalizeTaskEvidence(args2.task_id,nextEvidence),quarantine;if(isQuarantinableTaskEvidenceRead(read))quarantine=await quarantineTaskEvidenceBytes(canonicalDirectory,args2.task_id,read,normalizedReason,context,latestReceipt?.generation??null);assertTaskEvidenceWriteAllowed(canonicalDirectory,args2.task_id),await atomicWriteFile(taskEvidenceFilePath(canonicalDirectory,args2.task_id),serialized3),invalidateTaskEvidenceSessionFallbacks(args2.task_id);let nextActions=buildRepairNextActions(args2.task_id,nextEvidence);return{success:!0,repaired:!0,task_id:args2.task_id,required_gates:[...nextEvidence.required_gates],requirements_state:nextEvidence.requirements_state,quarantine_digest:quarantine?.digest,quarantine_path:quarantine?.filePath,repaired_generation:nextEvidence.workflow?.generation,next_actions:nextActions,message:`Repaired task gate evidence for ${args2.task_id} into a fresh fail-closed generation ${nextEvidence.workflow?.generation}. Next actions: ${nextActions.join(" ")}`}})}init_create_tool();init_resolve_working_directory();async function executeRepairGateEvidence(args2,directory,_ctx){try{if(!_ctx||stripKnownSwarmPrefix(_ctx.agent??"").toLowerCase()!=="architect")return{success:!1,message:"Only the architect may repair task gate evidence.",errors:["TASK_GATE_EVIDENCE_ARCHITECT_ONLY"]};let resolved=resolveWorkingDirectory(args2.working_directory,directory);if(!resolved.success)return{success:!1,message:resolved.message,errors:[resolved.message]};return await repairTaskGateEvidence(args2,resolved.directory,{sessionID:_ctx?.sessionID,messageID:_ctx?.messageID})}catch(error93){return{success:!1,message:"repair_gate_evidence failed",errors:[error93 instanceof Error?error93.message:String(error93)]}}}var repair_gate_evidence=createSwarmTool({description:"Architect-only evidence repair for exact-task gate files. Rebuilds from a durable requirements receipt, recovers receipt-backed legacy marker wedges or the exact sentinel-only historical reset, and refuses every other receipt-less reconstruction.",args:{task_id:exports_external.string().min(1).regex(/^\d+\.\d+(\.\d+)*$/,"Task ID must be in N.M or N.M.P format"),reason:exports_external.string().min(1).max(2000),expected_sha256:exports_external.string().regex(/^[a-f0-9]{64}$/).optional(),expected_generation:exports_external.number().int().min(0).optional(),working_directory:exports_external.string().optional()},execute:async(args2,directory,ctx)=>JSON.stringify(await executeRepairGateEvidence(args2,directory,ctx),null,2)});init_zod();init_schema();init_knowledge_receipt_ledger();init_create_tool();init_resolve_working_directory();async function executeRepairKnowledgeReceiptLedger(args2,directory,_ctx){try{if(_ctx&&stripKnownSwarmPrefix(_ctx.agent??"").toLowerCase()!=="architect")return{success:!1,message:"Only the architect may repair the knowledge receipt ledger.",errors:["RECEIPT_REPAIR_ARCHITECT_ONLY"]};if(_ctx?.sessionID&&args2.session_id!==_ctx.sessionID)return{success:!1,message:"repair_knowledge_receipt_ledger session_id must match the invoking tool context.",errors:["RECEIPT_REPAIR_SESSION_MISMATCH"]};let resolved=resolveWorkingDirectory(args2.working_directory,directory);if(!resolved.success)return{success:!1,message:resolved.message,errors:[resolved.message]};let result=await repairKnowledgeReceiptLedger(resolved.directory,args2);if(!result.ok)return{success:!1,message:"repair_knowledge_receipt_ledger failed",errors:[result.detail],code:result.code};let reEvaluationArgs=JSON.stringify({repair_id:result.repair_id,phase:args2.phase,...args2.task_id?{task_id:args2.task_id}:{},scope_complete:!0});return{success:!0,message:result.status==="validated_projection"?"knowledge receipt projection validated":result.status==="pending_re_evaluation"?`knowledge receipt ledger still pending re-evaluation; as architect, run knowledge_recall with a comprehensive query and repair_re_evaluation ${reEvaluationArgs}`:`knowledge receipt ledger repaired and blocked pending re-evaluation; as architect, run knowledge_recall with a comprehensive query and repair_re_evaluation ${reEvaluationArgs}`,...result}}catch(error93){return{success:!1,message:"repair_knowledge_receipt_ledger failed",errors:[error93 instanceof Error?error93.message:String(error93)]}}}var repair_knowledge_receipt_ledger=createSwarmTool({description:"Architect-only repair and validation for the authoritative knowledge receipt ledger. Rebuilds the derived projection when authority is readable, or quarantines a bounded corrupt authority, salvages only the validated prefix, and blocks the exact phase/session until a fresh re-evaluation is committed.",args:{phase:exports_external.string().min(1),session_id:exports_external.string().min(1),task_id:exports_external.string().min(1).optional(),reason:exports_external.string().min(1).max(2000),grace_days:exports_external.number().int().min(0).optional(),working_directory:exports_external.string().optional()},execute:async(args2,directory,ctx)=>JSON.stringify(await executeRepairKnowledgeReceiptLedger(args2,directory,ctx),null,2)});init_zod();init_loader();init_schema();init_profiles();init_telemetry();init_path_security();init_create_tool();import*as path348 from"node:path";init_zod();init_external_tool_runner();init_path_security();init_create_tool();import*as fs211 from"node:fs";import{createRequire as createRequire7}from"node:module";import*as path347 from"node:path";var require2=createRequire7(import.meta.url),DEFAULT_MAX_RESULTS4=100,DEFAULT_MAX_LINES=200,REGEX_TIMEOUT_MS=5000,MAX_FILE_SIZE_BYTES8=1048576,HARD_CAP_RESULTS4=1e4,HARD_CAP_LINES=1e4,MAX_QUERY_LENGTH=20000,MAX_INCLUDE_PATTERNS=100,MAX_RG_STDOUT_BYTES=8388608,MAX_RG_STDERR_BYTES=65536,FALLBACK_MAX_FILES=20000,FALLBACK_MAX_DIRS=5000,FALLBACK_MAX_DEPTH=40,FALLBACK_MAX_TOTAL_BYTES=67108864,DEFAULT_SKIP_DIRS=new Set([".git",".swarm","node_modules","dist","build","out","coverage",".next",".turbo",".cache"]);function globMatch(pattern,filePath){let normalizedPattern=pattern.replace(/\\/g,"/"),normalizedPath=filePath.replace(/\\/g,"/"),regexPattern=normalizedPattern.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"{{DOUBLESTAR}}").replace(/\*/g,"[^/]*").replace(/\?/g,".").replace(/\{\{DOUBLESTAR\}\}/g,".*");try{return new RegExp(`^${regexPattern}$`).test(normalizedPath)}catch{return!1}}function matchesGlobs(filePath,globs){if(globs.length===0)return!0;return globs.some((glob)=>globMatch(glob,filePath))}var WINDOWS_RESERVED_NAMES5=/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\.|:|$)/i;function containsWindowsAttacks4(str){if(/:[^\\/]/.test(str))return!0;let parts=str.split(/[/\\]/);for(let part of parts)if(WINDOWS_RESERVED_NAMES5.test(part))return!0;return!1}function resolveWithinWorkspace(filePath,workspace){try{let resolvedPath=path347.resolve(workspace,filePath),realWorkspace=fs211.realpathSync(workspace),realResolvedPath=fs211.realpathSync(resolvedPath),relativePath2=path347.relative(realWorkspace,realResolvedPath);if(relativePath2.startsWith("..")||path347.isAbsolute(relativePath2))return null;return relativePath2}catch{return null}}function isPathInWorkspace3(filePath,workspace){return resolveWithinWorkspace(filePath,workspace)!==null}function validatePathForRead2(filePath,workspace){return isPathInWorkspace3(filePath,workspace)}function splitGlobPatterns2(value){return value?value.split(",").map((p)=>p.trim()).filter(Boolean):[]}var GLOB_METACHARACTERS=/[*?[\]{}]/;function isExactPath(pattern){return!GLOB_METACHARACTERS.test(pattern)}function targetsDotDirectory(pattern){let firstSegment=pattern.split(/[\\/]/)[0];return!!firstSegment&&firstSegment.startsWith(".")&&firstSegment!=="."&&firstSegment!==".."}function hasGitSegment(resolvedRelativePath){return resolvedRelativePath.split(/[\\/]/).some((segment)=>segment.toLowerCase()===".git")}function toWorkspaceRelativePath2(filePath,workspace){try{let resolved=path347.resolve(workspace,filePath),realWorkspace=fs211.realpathSync(workspace),realResolved=fs211.realpathSync(resolved),relative88=path347.relative(realWorkspace,realResolved);if(!relative88||relative88.startsWith("..")||path347.isAbsolute(relative88))return null;return relative88.split(path347.sep).join("/")}catch{return null}}function truncateLine(line,maxLines){let trimmed=line.trimEnd();if(trimmed.length>maxLines)return`${trimmed.substring(0,maxLines)}...`;return trimmed}function resolvePackagedRipgrep(){try{let mod=require2("@vscode/ripgrep");return typeof mod.rgPath==="string"&&mod.rgPath?mod.rgPath:null}catch{return null}}function resolveRipgrepBinary(){return _internals286.resolvePackagedRipgrep()??_internals286.resolveExecutableFromPath(["rg"])}async function ripgrepSearch(opts){let rgPath=_internals286.resolveRipgrepBinary();if(!rgPath)return{error:!0,type:"rg-not-found",message:"ripgrep (rg) not found; using fallback search was not possible"};let args2=["--json","--no-config","-n"],includes=splitGlobPatterns2(opts.include),promotablePaths=[],globIncludes=[];for(let pattern of includes){let resolvedRelative=resolveWithinWorkspace(pattern,opts.workspace);if(isExactPath(pattern)&&targetsDotDirectory(pattern)&&pattern.split(/[\\/]/)[0]?.toLowerCase()!==".git"&&resolvedRelative!==null&&!hasGitSegment(resolvedRelative))promotablePaths.push(pattern);else globIncludes.push(pattern)}let pathOperands;if(promotablePaths.length>0&&globIncludes.length===0)pathOperands=promotablePaths;else{for(let pattern of[...globIncludes,...promotablePaths])args2.push("--glob",pattern);if(includes.some((p)=>targetsDotDirectory(p)&&p.split(/[\\/]/)[0]?.toLowerCase()!==".git"))args2.push("--hidden","--no-ignore"),args2.push("--glob","!.git");pathOperands=["."]}for(let pattern of splitGlobPatterns2(opts.exclude))args2.push("--glob",`!${pattern}`);if(opts.mode!=="regex")args2.push("--fixed-strings");args2.push("--",opts.query,...pathOperands);let run=await _internals286.runExternalTool({executable:rgPath,args:args2,cwd:opts.workspace,timeoutMs:REGEX_TIMEOUT_MS,maxStdoutBytes:MAX_RG_STDOUT_BYTES,maxStderrBytes:MAX_RG_STDERR_BYTES});try{if(run.status==="timeout")return{error:!0,type:"regex-timeout",message:`Search timed out after ${REGEX_TIMEOUT_MS}ms`};if(run.status==="spawn-error")return{error:!0,type:"unknown",message:run.message??"ripgrep failed to start"};if(run.exitCode!==0&&run.stderr){if(run.stderr.includes("Invalid regex")||run.stderr.includes("regex parse error")||run.stderr.includes("SyntaxError"))return{error:!0,type:"invalid-query",message:`Invalid query: ${run.stderr.split(`
|
|
7727
7734
|
`)[0]}`};if(run.exitCode===2)return{error:!0,type:"unknown",message:`ripgrep error: ${run.stderr.split(`
|
|
7728
7735
|
`)[0]}`}}let matches=[],total=0;for(let line of run.stdout.split(`
|
|
7729
7736
|
`)){if(!line.trim())continue;try{let entry=JSON.parse(line);if(entry.type==="match"){let rawPath=entry.data?.path?.text??entry.data?.path,relativePath2=typeof rawPath==="string"?toWorkspaceRelativePath2(rawPath,opts.workspace):null;if(!relativePath2)continue;if(total++,matches.length<opts.maxResults){let match={file:relativePath2,lineNumber:entry.data.line_number,lineText:truncateLine(entry.data.lines.text,opts.maxLines)};matches.push(match)}}}catch{}}return{matches,truncated:total>opts.maxResults||run.stdoutTruncated||run.stderrTruncated,total,query:opts.query,mode:opts.mode,maxResults:opts.maxResults,engine:"ripgrep",outputTruncated:run.stdoutTruncated||run.stderrTruncated}}catch(err){return{error:!0,type:"unknown",message:err instanceof Error?err.message:String(err)}}}function escapeRegex4(str){return str.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function collectFiles(dir,workspace,includeGlobs,excludeGlobs,state2,depth=0){if(depth>FALLBACK_MAX_DEPTH||state2.files.length>=FALLBACK_MAX_FILES||state2.dirCount>=FALLBACK_MAX_DIRS)return state2.truncated=!0,state2.files;try{let realDir=fs211.realpathSync(dir);if(state2.seenRealPaths.has(realDir))return state2.files;state2.seenRealPaths.add(realDir),state2.dirCount++}catch{return state2.files}if(!validatePathForRead2(dir,workspace))return state2.files;try{let entries2=fs211.readdirSync(dir,{withFileTypes:!0});for(let entry of entries2){if(state2.files.length>=FALLBACK_MAX_FILES||state2.dirCount>=FALLBACK_MAX_DIRS){state2.truncated=!0;break}let fullPath=path347.join(dir,entry.name),relativePath2=path347.relative(workspace,fullPath);if(!validatePathForRead2(fullPath,workspace))continue;if(entry.isDirectory()){if(entry.name.toLowerCase()===".git"||DEFAULT_SKIP_DIRS.has(entry.name)&&!includeGlobs.some((g)=>g.split(/[\\/]/)[0]===entry.name))continue;collectFiles(fullPath,workspace,includeGlobs,excludeGlobs,state2,depth+1)}else if(entry.isFile()){if(includeGlobs.length>0&&!matchesGlobs(relativePath2,includeGlobs))continue;if(excludeGlobs.length>0&&matchesGlobs(relativePath2,excludeGlobs))continue;let normalized=toWorkspaceRelativePath2(fullPath,workspace);if(!normalized)continue;state2.files.push(normalized)}}}catch{}return state2.files}async function searchWorkspaceLiteral(opts){let includeGlobs=opts.include?opts.include.split(",").map((p)=>p.trim()).filter(Boolean):[],excludeGlobs=opts.exclude?opts.exclude.split(",").map((p)=>p.trim()).filter(Boolean):[],collectState={files:[],seenRealPaths:new Set,dirCount:0,truncated:!1},files=collectFiles(opts.workspace,opts.workspace,includeGlobs,excludeGlobs,collectState),regex;try{if(opts.mode==="regex")regex=new RegExp(opts.query);else regex=new RegExp(escapeRegex4(opts.query))}catch(err){return{error:!0,type:"invalid-query",message:err instanceof Error?err.message:"Invalid regex pattern"}}let matches=[],total=0,totalBytesRead=0,truncated=collectState.truncated;for(let file3 of files){let fullPath=path347.join(opts.workspace,file3);if(!validatePathForRead2(fullPath,opts.workspace))continue;let stats2;try{if(stats2=fs211.statSync(fullPath),stats2.size>MAX_FILE_SIZE_BYTES8)continue;if(totalBytesRead+stats2.size>FALLBACK_MAX_TOTAL_BYTES){truncated=!0;break}totalBytesRead+=stats2.size}catch{continue}let content;try{let bytes=fs211.readFileSync(fullPath);if(bytes.includes(0))continue;content=bytes.toString("utf-8")}catch{continue}let lines=content.split(`
|
|
@@ -7785,8 +7792,8 @@ ${content}
|
|
|
7785
7792
|
`),diff2+=`
|
|
7786
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(`
|
|
7787
7794
|
`),actual:actualLines.join(`
|
|
7788
|
-
`)};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(`
|
|
7789
|
-
`),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(`
|
|
7790
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,`
|
|
7791
7798
|
# opencode-swarm local runtime state (incl. worktree lanes, #2527)
|
|
7792
7799
|
${added.join(`
|
|
@@ -7820,7 +7827,7 @@ ${outputSummary}`,sessionId,"tool")}catch{}}}}init_utils();init_git_executable()
|
|
|
7820
7827
|
${tailContent.join(`
|
|
7821
7828
|
`)}
|
|
7822
7829
|
${footerLines.join(`
|
|
7823
|
-
`)}`}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"?`
|
|
7824
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,`
|
|
7825
7832
|
`).split(`
|
|
7826
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,`
|