opencode-swarm 7.200.0 → 7.200.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/binaries/win32-arm64/swarm-sandbox-runner.exe +0 -0
- package/binaries/win32-x64/swarm-sandbox-runner.exe +0 -0
- package/dist/cli/{attest-task-8ekwny8v.js → attest-task-sg8b5a5j.js} +42 -42
- package/dist/cli/{auto-checkpoint-dqjk82s7.js → auto-checkpoint-bywgxh27.js} +7 -7
- package/dist/cli/{checkpoint-2ahps2sp.js → checkpoint-k2092cbw.js} +17 -15
- package/dist/cli/{coder-settlement-1dk37pa9.js → coder-settlement-y0hkcngn.js} +10 -10
- package/dist/cli/{config-doctor-73rctg85.js → config-doctor-0fnrwkga.js} +13 -13
- package/dist/cli/{core-y5mfws8v.js → core-mfyaj8b4.js} +3 -3
- package/dist/cli/{curation-policy-43gq6t0y.js → curation-policy-fth5n93x.js} +4 -4
- package/dist/cli/{curator-m278hyrq.js → curator-1s64jkc3.js} +41 -41
- package/dist/cli/{curator-drift-k7j9rcgp.js → curator-drift-famx6p6s.js} +8 -8
- package/dist/cli/curator-llm-factory-vya4epq6.js +82 -0
- package/dist/cli/{doctor-knowledge-receipt-phase-id-1m7pkzvt.js → doctor-knowledge-receipt-phase-id-v4y6pbek.js} +7 -7
- package/dist/cli/{evidence-summary-service-19k8x1g9.js → evidence-summary-service-rd7y6yjq.js} +17 -17
- package/dist/cli/{gate-evidence-hche0hf8.js → gate-evidence-kama66h5.js} +5 -5
- package/dist/cli/guardrail-explain-8fkhq0cg.js +83 -0
- package/dist/cli/{guardrail-log-tvbgnxns.js → guardrail-log-gdj19fq5.js} +6 -6
- package/dist/cli/{guardrail-reset-v8kvh9cn.js → guardrail-reset-bmg6czzk.js} +41 -41
- package/dist/cli/{hive-promoter-bqfa763z.js → hive-promoter-ychygdgc.js} +41 -41
- package/dist/cli/{index-1rfgzsaw.js → index-0ptf66x5.js} +4 -4
- package/dist/cli/{index-rfvnq6wd.js → index-0tygsk8b.js} +8 -8
- package/dist/cli/{index-qnst0jwc.js → index-12h2rtdj.js} +3 -3
- package/dist/cli/{index-bp476gwc.js → index-1v277wxc.js} +2 -2
- package/dist/cli/{index-511hw14d.js → index-2dm42tgp.js} +43 -43
- package/dist/cli/{index-hg4qa0aq.js → index-2hnnkj64.js} +1892 -2354
- package/dist/cli/{index-pyv8vzkx.js → index-2m740hyt.js} +5 -5
- package/dist/cli/{index-wfb6vrc2.js → index-2w5grmmj.js} +2 -2
- package/dist/cli/{index-gwc7jahh.js → index-3020n6d9.js} +1 -1
- package/dist/cli/{index-m9j9varx.js → index-3exe6k66.js} +3 -3
- package/dist/cli/{index-sk1rva12.js → index-3zspah3v.js} +2 -2
- package/dist/cli/{index-hxp5jgd8.js → index-51dw4bjc.js} +2 -2
- package/dist/cli/{index-0wg5q595.js → index-5snwc3dz.js} +1 -1
- package/dist/cli/{index-kwfhr3mz.js → index-b0d8ra32.js} +1 -1
- package/dist/cli/{index-r02aqt0a.js → index-b4kdms7x.js} +2 -2
- package/dist/cli/{index-n5k81wym.js → index-bn3aa5q1.js} +7 -7
- package/dist/cli/{index-md2180vx.js → index-c9g3hkjz.js} +3 -3
- package/dist/cli/{index-qnabg1wp.js → index-dgyddtje.js} +6 -6
- package/dist/cli/{index-q1x73nnd.js → index-epzadpmm.js} +1 -1
- package/dist/cli/{index-jbm301bq.js → index-f6nrw8am.js} +41 -41
- package/dist/cli/{index-dng8z8me.js → index-g57p8p1k.js} +1 -1
- package/dist/cli/{index-vmevv6my.js → index-na6ph1fp.js} +1 -1
- package/dist/cli/{index-tv9c3b3q.js → index-nawp90n7.js} +3 -3
- package/dist/cli/{index-wr0n2w3z.js → index-nzfq1ms2.js} +1 -1
- package/dist/cli/{index-yvv0my1a.js → index-p6v544jn.js} +1 -1
- package/dist/cli/{index-x25rhkmk.js → index-parkaa70.js} +4 -4
- package/dist/cli/{index-yss701b3.js → index-pe77h482.js} +4 -4
- package/dist/cli/{index-71bqn1nn.js → index-qaqyq25k.js} +7 -7
- package/dist/cli/{index-8rrs1nc0.js → index-qzakbjcg.js} +2 -2
- package/dist/cli/{index-22atsy06.js → index-rzkmg02a.js} +918 -154
- package/dist/cli/{index-nq3zcrhm.js → index-s3w41p1x.js} +1 -1
- package/dist/cli/{index-7v74n9a1.js → index-s8eac99p.js} +3 -3
- package/dist/cli/{index-99zt998b.js → index-s9y49avf.js} +1 -1
- package/dist/cli/{index-58cr1xg0.js → index-sva5swrs.js} +3 -3
- package/dist/cli/{index-p5m71yph.js → index-sz67z90q.js} +4 -4
- package/dist/cli/{index-e8m8bb1r.js → index-th667k1y.js} +4 -4
- package/dist/cli/{index-ac8vdmgv.js → index-traz987v.js} +1 -1
- package/dist/cli/{index-jy0mgzjq.js → index-v1h70r3y.js} +1 -1
- package/dist/cli/{index-d083d1q7.js → index-ves1rtqt.js} +1 -1
- package/dist/cli/{index-9nmrw7ek.js → index-vtkgg2qn.js} +3 -3
- package/dist/cli/{index-35tf03js.js → index-w2bhrp6z.js} +10 -10
- package/dist/cli/{index-8a3aasag.js → index-wgf1780e.js} +5 -5
- package/dist/cli/{index-x1z5d5kj.js → index-xyvsdn07.js} +1 -1
- package/dist/cli/{index-1tpz99db.js → index-ypxq0x7r.js} +1 -1
- package/dist/cli/{index-vqtca3xv.js → index-z9mysg5m.js} +2 -2
- package/dist/cli/index.js +42 -42
- package/dist/cli/{knowledge-escalator-qcra58bx.js → knowledge-escalator-zxd76jna.js} +12 -12
- package/dist/cli/{knowledge-events-9mnx1a3f.js → knowledge-events-z8h0wmaw.js} +10 -10
- package/dist/cli/{knowledge-link-2jsn9f6a.js → knowledge-link-wfhsfyn2.js} +3 -3
- package/dist/cli/{knowledge-store-fdneqf7z.js → knowledge-store-g2gm13s8.js} +4 -4
- package/dist/cli/{knowledge-validator-7nj987ga.js → knowledge-validator-2sech2sx.js} +6 -6
- package/dist/cli/{mcp-0g34wmz4.js → mcp-t88363gj.js} +1 -1
- package/dist/cli/{model-preflight-g11ykgc0.js → model-preflight-akj8g1m2.js} +41 -41
- package/dist/cli/{pending-delegations-5vme18wx.js → pending-delegations-bqp6b6as.js} +11 -11
- package/dist/cli/{pr-subscriptions-cbx5p838.js → pr-subscriptions-wxjvkg56.js} +10 -10
- package/dist/cli/{pr-workflow-gate-376gw6yj.js → pr-workflow-gate-2wcrfa6g.js} +41 -41
- package/dist/cli/{runner-vvd26z2z.js → runner-s1a73y5h.js} +4 -4
- package/dist/cli/{scan-cursor-x3j5wvfm.js → scan-cursor-8br4x41t.js} +5 -5
- package/dist/cli/{schema-d98zzrpn.js → schema-mc419qh8.js} +1 -1
- package/dist/cli/{scope-persistence-vkb8z4hc.js → scope-persistence-5gyjt70q.js} +13 -13
- package/dist/cli/{server-25svy6cb.js → server-bp247fqe.js} +41 -41
- package/dist/cli/{skill-generator-ktz33dt6.js → skill-generator-q4afafh3.js} +14 -14
- package/dist/cli/{snapshot-coordination-init-74x3psxc.js → snapshot-coordination-init-b4kmrgh7.js} +41 -41
- package/dist/cli/{speckit-checkoff-9t6cdn4a.js → speckit-checkoff-1v02b2dt.js} +4 -4
- package/dist/cli/{workspace-snapshot-afqvh9bq.js → workspace-snapshot-93gzfac2.js} +3 -3
- package/dist/cli/{worktree-collision-ownership-7a1n1f9j.js → worktree-collision-ownership-84m9f5an.js} +12 -12
- package/dist/cli/{worktree-isolation-8snw7w34.js → worktree-isolation-xwbszhja.js} +41 -41
- package/dist/commands/close/internals.d.ts +1 -1
- package/dist/commands/close/orchestrator.d.ts +7 -0
- package/dist/commands/destructive-purge.d.ts +15 -0
- package/dist/commands/git-status-read.d.ts +23 -0
- package/dist/commands/registry.d.ts +1 -1
- package/dist/commands/rollback-gate.d.ts +77 -10
- package/dist/git/branch.d.ts +22 -0
- package/dist/index.js +26 -22
- package/dist/session/snapshot-coordination-init.d.ts +34 -0
- package/dist/session/snapshot-writer.d.ts +5 -1
- package/dist/tools/checkpoint.d.ts +17 -0
- package/package.json +1 -1
- package/dist/cli/curator-llm-factory-rke0964p.js +0 -82
- package/dist/cli/guardrail-explain-jg5png4a.js +0 -83
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.200.0",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, Python, Rust, Go, Dart, Ruby, PHP, and Java",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; a destructive restore previews first and requires the confirm_token issued in the preview (#2946)",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; reviewer verdicts marked `UNVERIFIED` persist to the findings ledger as `PENDING` records routed back to the reviewer — do not resubmit a row whose verdict is already recorded",agents:["architect"]},pr_review_submission:{description:"submit a settled, head-bound PR review to GitHub through the gh PR Review API after the PR_REVIEW gate clears; architect-only, refuses while a gate is active or the run was aborted after settlement",agents:["architect"]},export_pr_review_partial_results:{description:"export the validated partial results of an ABORTED PR_REVIEW run as a partial, non-authoritative artifact bound per-item to receipt-authenticated findings; architect-only, requires the gate cleared and an abort event binding session and head, never implies completion or feedback consent",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"]},prepare_pr_feedback_commit_message:{description:"author a PR_FEEDBACK commit message that cannot go inline (e.g. a Co-Authored-By trailer) into a file OUTSIDE the repository; returns the path for git commit -F",agents:["architect"]},test_runner:{description:"auto-detect and run tests",agents:["architect","reviewer","critic_finding_validator","test_engineer"]},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, require scoped re-evaluation, and backfill stable phase ids across the whole ledger (operation backfill_phase_id; phase/session_id do not scope the backfill)",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). For an active PR_REVIEW gate it also projects that derived state read-only: per-boundary settlement (post_explorer / post_reviewer / post_critic), per-lane coverage (accepted, rejected, one-line latest finding), and the bounded candidate inventory, each degrading to a typed unavailable state rather than an absence claim. 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 — OBSERVATION ONLY; it can never cancel or abort a lane. A presumed-stale sweep runs on every call, settling lanes past the horizon: idle host to stale, unobservable host to a typed liveness error. The wait budget (timeout_ms) bounds this observer call only — its expiry, a missing messages client, or a degraded liveness probe never kills a lane, never proves it died, and never settles anything. If a collection returns pending lanes, poll again first; busy/retry host status is live evidence, not failure. Cancellation is a distinct, explicit, authorized, potentially destructive action: use cancel_lane_batch (confirm: true + reason), never this tool. An explicit operator cancellation settles as the distinct operator_cancelled class — not liveness. Unsettled lanes are reported in pending_lanes (batch_id, lane_id, status, output_ref) regardless of include_pending. 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"]},cancel_lane_batch:{description:"cancel ACTIVE lanes of a dispatch_lanes_async batch — the only cancellation surface (collect_lane_results cannot cancel). Destructive and authorization-gated: requires confirm: true + a bounded reason, recorded on cancelled terminals as the distinct operator_cancelled class (never liveness; not auto-retryable, never consumes retry budget — re-dispatch explicitly). Race-safe per lane: busy/retry refused (live work is never destroyed — human force path: /swarm abort-pr-workflow); degraded/absent status probe refuses the whole batch fail-closed; idle or host-unknown sessions may be cancelled; a child completing in the race window is preserved; an abort timeout never claims cancellation.",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_next_wave:{description:"Epic Mode: the single, idempotent way forward while an epic is open. Closes the active wave once every task is resolved (recording per-task outcomes and declared-vs-actual divergence, which Epic learning uses to plan later waves), keeps phases in order, and issues the next wave of disjoint tasks with dispatch instructions. Returns a status: dispatch | declare-scopes | in-progress | blocked | phase-ready-for-review | epic-complete | refused. Requires `epic.mode.enabled: true` and an epic opened by `/swarm epic start`.",agents:[]},epic_phase_review:{description:"Epic Mode phase readiness: dispatch a read-only phase reviewer, then (only if it APPROVES) a read-only phase critic over the completed phase; parse both verdicts from the agents and record them to .swarm/evidence/{phase}/epic-phase-review.json. Required by phase_complete while an epic is open for the current plan; re-run after any fix (evidence is bound to the plan and phase task evidence).",agents:[]}},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,EPIC_TOOL_NAMES,EPIC_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.200.1",description:"Architect-centric agentic swarm plugin for OpenCode - hub-and-spoke orchestration with SME consultation, code generation, and QA review",main:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",default:"./dist/index.js"},"./package.json":"./package.json"},bin:{"opencode-swarm":"./dist/cli/index.js"},type:"module",engines:{bun:">=1.3.13",node:">=22.13"},license:"MIT",repository:{type:"git",url:"https://github.com/ZaxbyHub/opencode-swarm.git"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},keywords:["opencode","opencode-plugin","ai","agents","orchestration","swarm","multi-agent","llm"],files:["dist","dist/lang/grammars","binaries","evaluation-fixtures",".opencode/skills/brainstorm",".opencode/skills/specify",".opencode/skills/clarify-spec",".opencode/skills/swarm-resume",".opencode/skills/clarify",".opencode/skills/discover",".opencode/skills/consult",".opencode/skills/pre-phase-briefing",".opencode/skills/council",".opencode/skills/deep-dive",".opencode/skills/deep-research",".opencode/skills/codebase-review-swarm",".opencode/skills/swarm-implement",".opencode/skills/design-docs",".opencode/skills/swarm-pr-review",".opencode/skills/swarm",".opencode/skills/swarm-pr-feedback",".opencode/skills/swarm-pr-subscribe",".opencode/skills/swarm-ci-monitor",".opencode/skills/issue-ingest",".opencode/skills/swarm-plan",".opencode/skills/critic-gate",".opencode/skills/execute",".opencode/skills/phase-wrap",".opencode/skills/loop",".opencode/skills/writing-tests",".opencode/skills/running-tests",".opencode/skills/engineering-conventions",".opencode/skills/commit-pr",".opencode/skills/ci-failure-batching",".opencode/skills/gate-attribution",".opencode/skills/merge-queue-readiness",".opencode/skills/skill-edit-validation",".opencode/skills/worktree-retry-cleanup",".opencode/skills/test-file-split",".opencode/skills/fork-pr-operations",".opencode/skills/parallel-work-check",".opencode/skills/ci-fix-monitor",".opencode/skills/issue-tracer",".opencode/skills/orchestrating-subagents",".opencode/skills/durable-session-state","tests/fixtures/memory-recall","tests/fixtures/memory-recall-heldout","opencode-swarm.schema.json","README.md","LICENSE"],scripts:{clean:`bun -e "require('fs').rmSync('dist',{recursive:true,force:true})"`,build:"bun run clean && bun run scripts/generate-config-schema.ts && bun run scripts/copy-grammars.ts && bun build src/index.ts --outdir dist --target node --format esm --external web-tree-sitter --minify-whitespace --minify-syntax && bun build src/cli/index.ts --outdir dist/cli --target bun --format esm --external bash-parser --splitting && bun run scripts/copy-grammars.ts --to-dist && tsc --emitDeclarationOnly",typecheck:"tsc --noEmit",test:"bun test",lint:"biome lint .","lint:ci":"biome ci .","test:unit:ci":"bun scripts/ci/run-unit-tests-local.ts","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, Python, Rust, Go, Dart, Ruby, PHP, and Java",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; a destructive restore previews first and requires the confirm_token issued in the preview (#2946)",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; reviewer verdicts marked `UNVERIFIED` persist to the findings ledger as `PENDING` records routed back to the reviewer — do not resubmit a row whose verdict is already recorded",agents:["architect"]},pr_review_submission:{description:"submit a settled, head-bound PR review to GitHub through the gh PR Review API after the PR_REVIEW gate clears; architect-only, refuses while a gate is active or the run was aborted after settlement",agents:["architect"]},export_pr_review_partial_results:{description:"export the validated partial results of an ABORTED PR_REVIEW run as a partial, non-authoritative artifact bound per-item to receipt-authenticated findings; architect-only, requires the gate cleared and an abort event binding session and head, never implies completion or feedback consent",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"]},prepare_pr_feedback_commit_message:{description:"author a PR_FEEDBACK commit message that cannot go inline (e.g. a Co-Authored-By trailer) into a file OUTSIDE the repository; returns the path for git commit -F",agents:["architect"]},test_runner:{description:"auto-detect and run tests",agents:["architect","reviewer","critic_finding_validator","test_engineer"]},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, require scoped re-evaluation, and backfill stable phase ids across the whole ledger (operation backfill_phase_id; phase/session_id do not scope the backfill)",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). For an active PR_REVIEW gate it also projects that derived state read-only: per-boundary settlement (post_explorer / post_reviewer / post_critic), per-lane coverage (accepted, rejected, one-line latest finding), and the bounded candidate inventory, each degrading to a typed unavailable state rather than an absence claim. 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 — OBSERVATION ONLY; it can never cancel or abort a lane. A presumed-stale sweep runs on every call, settling lanes past the horizon: idle host to stale, unobservable host to a typed liveness error. The wait budget (timeout_ms) bounds this observer call only — its expiry, a missing messages client, or a degraded liveness probe never kills a lane, never proves it died, and never settles anything. If a collection returns pending lanes, poll again first; busy/retry host status is live evidence, not failure. Cancellation is a distinct, explicit, authorized, potentially destructive action: use cancel_lane_batch (confirm: true + reason), never this tool. An explicit operator cancellation settles as the distinct operator_cancelled class — not liveness. Unsettled lanes are reported in pending_lanes (batch_id, lane_id, status, output_ref) regardless of include_pending. 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"]},cancel_lane_batch:{description:"cancel ACTIVE lanes of a dispatch_lanes_async batch — the only cancellation surface (collect_lane_results cannot cancel). Destructive and authorization-gated: requires confirm: true + a bounded reason, recorded on cancelled terminals as the distinct operator_cancelled class (never liveness; not auto-retryable, never consumes retry budget — re-dispatch explicitly). Race-safe per lane: busy/retry refused (live work is never destroyed — human force path: /swarm abort-pr-workflow); degraded/absent status probe refuses the whole batch fail-closed; idle or host-unknown sessions may be cancelled; a child completing in the race window is preserved; an abort timeout never claims cancellation.",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_next_wave:{description:"Epic Mode: the single, idempotent way forward while an epic is open. Closes the active wave once every task is resolved (recording per-task outcomes and declared-vs-actual divergence, which Epic learning uses to plan later waves), keeps phases in order, and issues the next wave of disjoint tasks with dispatch instructions. Returns a status: dispatch | declare-scopes | in-progress | blocked | phase-ready-for-review | epic-complete | refused. Requires `epic.mode.enabled: true` and an epic opened by `/swarm epic start`.",agents:[]},epic_phase_review:{description:"Epic Mode phase readiness: dispatch a read-only phase reviewer, then (only if it APPROVES) a read-only phase critic over the completed phase; parse both verdicts from the agents and record them to .swarm/evidence/{phase}/epic-phase-review.json. Required by phase_complete while an epic is open for the current plan; re-run after any fix (evidence is bound to the plan and phase task evidence).",agents:[]}},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,EPIC_TOOL_NAMES,EPIC_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
|
|
|
@@ -130,7 +130,7 @@ line break`,"required change with\rcarriage return"]),discardedReviewer=encodePr
|
|
|
130
130
|
`);return outside?`${outside}
|
|
131
131
|
${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(`
|
|
132
132
|
`),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 constants2=__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(constants2.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(path7,mode,cb){if(cb)process.nextTick(cb)},fs4.lchmodSync=function(){};if(fs4.chown&&!fs4.lchown)fs4.lchown=function(path7,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 rename3(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(rename3,fs$rename);return rename3}(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(path7,mode,callback){fs5.open(path7,constants2.O_WRONLY|constants2.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(path7,mode){var fd=fs5.openSync(path7,constants2.O_WRONLY|constants2.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(constants2.hasOwnProperty("O_SYMLINK")&&fs5.futimes)fs5.lutimes=function(path7,at,mt,cb){fs5.open(path7,constants2.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(path7,at,mt){var fd=fs5.openSync(path7,constants2.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(path7,options){if(!(this instanceof ReadStream))return new ReadStream(path7,options);Stream.call(this);var self=this;this.path=path7,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(path7,options){if(!(this instanceof WriteStream))return new WriteStream(path7,options);Stream.call(this),this.path=path7,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(`
|
|
133
|
-
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=readFile4;function readFile4(path7,options,cb){if(typeof options==="function")cb=options,options=null;return go$readFile(path7,options,cb);function go$readFile(path8,options2,cb2,startTime){return fs$readFile(path8,options2,function(err){if(err&&(err.code==="EMFILE"||err.code==="ENFILE"))enqueue([go$readFile,[path8,options2,cb2],err,startTime||Date.now(),Date.now()]);else if(typeof cb2==="function")cb2.apply(this,arguments)})}}var fs$writeFile=fs5.writeFile;fs5.writeFile=writeFile3;function writeFile3(path7,data,options,cb){if(typeof options==="function")cb=options,options=null;return go$writeFile(path7,data,options,cb);function go$writeFile(path8,data2,options2,cb2,startTime){return fs$writeFile(path8,data2,options2,function(err){if(err&&(err.code==="EMFILE"||err.code==="ENFILE"))enqueue([go$writeFile,[path8,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(path7,data,options,cb){if(typeof options==="function")cb=options,options=null;return go$appendFile(path7,data,options,cb);function go$appendFile(path8,data2,options2,cb2,startTime){return fs$appendFile(path8,data2,options2,function(err){if(err&&(err.code==="EMFILE"||err.code==="ENFILE"))enqueue([go$appendFile,[path8,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(path7,options,cb){if(typeof options==="function")cb=options,options=null;var go$readdir=noReaddirOptionVersions.test(process.version)?function(path8,options2,cb2,startTime){return fs$readdir(path8,fs$readdirCallback(path8,options2,cb2,startTime))}:function(path8,options2,cb2,startTime){return fs$readdir(path8,options2,fs$readdirCallback(path8,options2,cb2,startTime))};return go$readdir(path7,options,cb);function fs$readdirCallback(path8,options2,cb2,startTime){return function(err,files){if(err&&(err.code==="EMFILE"||err.code==="ENFILE"))enqueue([go$readdir,[path8,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(path7,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;open2(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(path7,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;open2(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(path7,options){return new fs5.ReadStream(path7,options)}function createWriteStream(path7,options){return new fs5.WriteStream(path7,options)}var fs$open=fs5.open;fs5.open=open2;function open2(path7,flags,mode,cb){if(typeof mode==="function")cb=mode,mode=null;return go$open(path7,flags,mode,cb);function go$open(path8,flags2,mode2,cb2,startTime){return fs$open(path8,flags2,mode2,function(err,fd){if(err&&(err.code==="EMFILE"||err.code==="ENFILE"))enqueue([go$open,[path8,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,stat5)=>{if(err)return callback(err);callback(null,stat5.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,stat5)=>{if(err2)return callback(err2);let precision=stat5.mtime.getTime()%1000===0?"s":"ms";Object.defineProperty(fs4,cacheSymbol,{value:precision}),callback(null,stat5.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 path7=__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,path7.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,stat5)=>{if(err2){if(err2.code==="ENOENT")return acquireLock(file2,{...options,stale:0},callback);return callback(err2)}if(!isLockStale(stat5,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(stat5,options){return stat5.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,stat5)=>{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()!==stat5.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,stat5)=>{if(err2)return err2.code==="ENOENT"?callback(null,!1):callback(err2);return callback(null,!isLockStale(stat5,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 path7 from"node:path";function matchTempGrammar(basename3){return SWARM_TEMP_GRAMMARS.find((g)=>g.match.test(basename3))}function parseTargetBasename(basename3){for(let g of SWARM_TEMP_GRAMMARS){if(!g.parsesTarget)continue;let m=g.match.exec(basename3);if(m?.[1])return m[1]}return null}function assertWellFormedTargetPath(targetPath){if(!path7.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=path7.normalize(path7.resolve(targetPath)),segments=resolved.split(path7.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(path7.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=path7.relative(swarmRoot,resolved);if(!rel||rel.startsWith("..")||path7.isAbsolute(rel))throw Error(`atomic-write target escapes .swarm root: ${targetPath}`);let probe=swarmRoot;for(let seg of rel.split(path7.sep)){if(probe=path7.join(probe,seg),!fs4.existsSync(probe))break;lstatNotSymlink(probe,"path segment under .swarm")}return{projectRoot:path7.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(path7.resolve(targetPath))}function wasRecentlyWrittenByThisProcess(targetPath,withinMs=RECENT_WRITE_WINDOW_MS){let last=recentWriteActivity.get(path7.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{_internals9.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=path7.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}.${_internals9.randomSuffix()}.tmp`;fs4.mkdirSync(path7.dirname(tempPath),{recursive:!0});try{try{let fd=fs4.openSync(tempPath,"wx",options?.mode);try{let written=0;while(written<buffer.byteLength)written+=_internals9.writeSync(fd,buffer,written,buffer.byteLength-written);if(options?.skipFsync!==!0)try{_internals9.fsyncSync(fd)}catch{}}finally{fs4.closeSync(fd)}renameWithRetry(tempPath,resolvedTarget)}finally{try{_internals9.unlinkSync(tempPath)}catch{}}}catch(error49){throw clearRecentWriteActivity(resolvedTarget),error49}try{let dirFd=fs4.openSync(path7.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,_internals9;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:466"],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:694","src/plan/manager.ts:2121","src/plan/manager.ts:2181","src/review/evidence.ts:179","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:429","src/turbo/lean/reviewer.ts:403","src/plan/ledger.ts:1486","src/services/synonym-map.ts:389","src/services/skill-optimizer/store.ts:340","src/services/skill-optimizer/store.ts:503","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:1509","src/background/lane-output-store.ts:353","src/background/pending-delegations.ts:1533","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"],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:157","src/tools/write-pr-review-artifact.ts:177","src/tools/write-pr-review-trigger-eval.ts:createTriggerReceipt"],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:2380","src/plan/manager.ts:2442"],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:206","src/full-auto/state.ts:637","src/context-map/persistence.ts:135","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:1808"],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/background/stage-b-dispatch-binding-store.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/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/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;_internals9={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*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}
|
|
133
|
+
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=readFile4;function readFile4(path7,options,cb){if(typeof options==="function")cb=options,options=null;return go$readFile(path7,options,cb);function go$readFile(path8,options2,cb2,startTime){return fs$readFile(path8,options2,function(err){if(err&&(err.code==="EMFILE"||err.code==="ENFILE"))enqueue([go$readFile,[path8,options2,cb2],err,startTime||Date.now(),Date.now()]);else if(typeof cb2==="function")cb2.apply(this,arguments)})}}var fs$writeFile=fs5.writeFile;fs5.writeFile=writeFile3;function writeFile3(path7,data,options,cb){if(typeof options==="function")cb=options,options=null;return go$writeFile(path7,data,options,cb);function go$writeFile(path8,data2,options2,cb2,startTime){return fs$writeFile(path8,data2,options2,function(err){if(err&&(err.code==="EMFILE"||err.code==="ENFILE"))enqueue([go$writeFile,[path8,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(path7,data,options,cb){if(typeof options==="function")cb=options,options=null;return go$appendFile(path7,data,options,cb);function go$appendFile(path8,data2,options2,cb2,startTime){return fs$appendFile(path8,data2,options2,function(err){if(err&&(err.code==="EMFILE"||err.code==="ENFILE"))enqueue([go$appendFile,[path8,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(path7,options,cb){if(typeof options==="function")cb=options,options=null;var go$readdir=noReaddirOptionVersions.test(process.version)?function(path8,options2,cb2,startTime){return fs$readdir(path8,fs$readdirCallback(path8,options2,cb2,startTime))}:function(path8,options2,cb2,startTime){return fs$readdir(path8,options2,fs$readdirCallback(path8,options2,cb2,startTime))};return go$readdir(path7,options,cb);function fs$readdirCallback(path8,options2,cb2,startTime){return function(err,files){if(err&&(err.code==="EMFILE"||err.code==="ENFILE"))enqueue([go$readdir,[path8,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(path7,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;open2(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(path7,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;open2(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(path7,options){return new fs5.ReadStream(path7,options)}function createWriteStream(path7,options){return new fs5.WriteStream(path7,options)}var fs$open=fs5.open;fs5.open=open2;function open2(path7,flags,mode,cb){if(typeof mode==="function")cb=mode,mode=null;return go$open(path7,flags,mode,cb);function go$open(path8,flags2,mode2,cb2,startTime){return fs$open(path8,flags2,mode2,function(err,fd){if(err&&(err.code==="EMFILE"||err.code==="ENFILE"))enqueue([go$open,[path8,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,stat5)=>{if(err)return callback(err);callback(null,stat5.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,stat5)=>{if(err2)return callback(err2);let precision=stat5.mtime.getTime()%1000===0?"s":"ms";Object.defineProperty(fs4,cacheSymbol,{value:precision}),callback(null,stat5.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 path7=__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,path7.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,stat5)=>{if(err2){if(err2.code==="ENOENT")return acquireLock(file2,{...options,stale:0},callback);return callback(err2)}if(!isLockStale(stat5,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(stat5,options){return stat5.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,stat5)=>{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()!==stat5.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,stat5)=>{if(err2)return err2.code==="ENOENT"?callback(null,!1):callback(err2);return callback(null,!isLockStale(stat5,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 path7 from"node:path";function matchTempGrammar(basename3){return SWARM_TEMP_GRAMMARS.find((g)=>g.match.test(basename3))}function parseTargetBasename(basename3){for(let g of SWARM_TEMP_GRAMMARS){if(!g.parsesTarget)continue;let m=g.match.exec(basename3);if(m?.[1])return m[1]}return null}function assertWellFormedTargetPath(targetPath){if(!path7.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=path7.normalize(path7.resolve(targetPath)),segments=resolved.split(path7.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(path7.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=path7.relative(swarmRoot,resolved);if(!rel||rel.startsWith("..")||path7.isAbsolute(rel))throw Error(`atomic-write target escapes .swarm root: ${targetPath}`);let probe=swarmRoot;for(let seg of rel.split(path7.sep)){if(probe=path7.join(probe,seg),!fs4.existsSync(probe))break;lstatNotSymlink(probe,"path segment under .swarm")}return{projectRoot:path7.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(path7.resolve(targetPath))}function wasRecentlyWrittenByThisProcess(targetPath,withinMs=RECENT_WRITE_WINDOW_MS){let last=recentWriteActivity.get(path7.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{_internals9.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=path7.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}.${_internals9.randomSuffix()}.tmp`;fs4.mkdirSync(path7.dirname(tempPath),{recursive:!0});try{try{let fd=fs4.openSync(tempPath,"wx",options?.mode);try{let written=0;while(written<buffer.byteLength)written+=_internals9.writeSync(fd,buffer,written,buffer.byteLength-written);if(options?.skipFsync!==!0)try{_internals9.fsyncSync(fd)}catch{}}finally{fs4.closeSync(fd)}renameWithRetry(tempPath,resolvedTarget)}finally{try{_internals9.unlinkSync(tempPath)}catch{}}}catch(error49){throw clearRecentWriteActivity(resolvedTarget),error49}try{let dirFd=fs4.openSync(path7.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,_internals9;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:466"],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:694","src/plan/manager.ts:2121","src/plan/manager.ts:2181","src/review/evidence.ts:179","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:429","src/turbo/lean/reviewer.ts:403","src/plan/ledger.ts:1486","src/services/synonym-map.ts:389","src/services/skill-optimizer/store.ts:340","src/services/skill-optimizer/store.ts:503","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:1509","src/background/lane-output-store.ts:353","src/background/pending-delegations.ts:1533","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"],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:157","src/tools/write-pr-review-artifact.ts:177","src/tools/write-pr-review-trigger-eval.ts:createTriggerReceipt"],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:2380","src/plan/manager.ts:2442"],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:224","src/full-auto/state.ts:637","src/context-map/persistence.ts:135","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:1808"],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/background/stage-b-dispatch-binding-store.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/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/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;_internals9={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*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}
|
|
134
134
|
→ ${_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(`
|
|
135
135
|
`)}
|
|
136
136
|
`,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(`
|
|
@@ -856,8 +856,8 @@ Use this data to avoid repeating known failure patterns.`,summaryText=summaries.
|
|
|
856
856
|
`),diffLines=computeLcsDiff(recordedLines,currentLines),MAX_DIFF_LINES=300,diffText=diffLines.length<=MAX_DIFF_LINES?diffLines.join(`
|
|
857
857
|
`):diffLines.slice(0,MAX_DIFF_LINES).join(`
|
|
858
858
|
`)+`
|
|
859
|
-
... (diff truncated — `+String(diffLines.length-MAX_DIFF_LINES)+" more lines)",changedSectionsSet=new Set,currentSection="";for(let line of diffLines){let headingMatch=line.slice(1).match(/^##\s+(.+)$/);if(headingMatch)currentSection=headingMatch[1].trim();if(line.length>0&&(line[0]==="+"||line[0]==="-")){if(currentSection)changedSectionsSet.add(currentSection)}}return{diff:diffText,changedSections:Array.from(changedSectionsSet)}}function computeLcsDiff(oldLines,newLines){let m=oldLines.length,n=newLines.length,dp=Array.from({length:m+1},()=>Array(n+1).fill(0));for(let i2=1;i2<=m;i2++)for(let j2=1;j2<=n;j2++)if(oldLines[i2-1]===newLines[j2-1])dp[i2][j2]=dp[i2-1][j2-1]+1;else dp[i2][j2]=Math.max(dp[i2-1][j2],dp[i2][j2-1]);let entries=[],i=m,j=n;while(i>0||j>0)if(i>0&&j>0&&oldLines[i-1]===newLines[j-1])entries.unshift({type:"unchanged",line:oldLines[i-1]}),i--,j--;else if(j>0&&(i===0||dp[i][j-1]>=dp[i-1][j]))entries.unshift({type:"add",line:newLines[j-1]}),j--;else entries.unshift({type:"remove",line:oldLines[i-1]}),i--;return entries.map((entry)=>{if(entry.type==="unchanged")return` ${entry.line}`;if(entry.type==="add")return`+${entry.line}`;return`-${entry.line}`})}var _internals63;var init_spec_hash=__esm(()=>{init_effective_spec();_internals63={computeSpecDiff,computeSpecHash,isObligationPreserving,isSpecStale,readEffectiveSpecSync}});function stderrTail(text){return text.slice(-GIT_READ_STDERR_TAIL_MAX_CHARS).replace(/[\x00-\x1f\x7f]+/g," ").trim()}async function readBoundedOutput(stream,maxBytes){let reader=stream.getReader(),chunks=[],totalBytes=0,truncated=!1;try{for(;;){let{done,value}=await reader.read();if(done)break;if(!value)continue;let remaining=maxBytes-totalBytes;if(value.byteLength>remaining){if(remaining>0)chunks.push(value.slice(0,remaining));truncated=!0,totalBytes+=remaining;continue}chunks.push(value),totalBytes+=value.byteLength}let joined=new Uint8Array(totalBytes),offset=0;for(let chunk of chunks)joined.set(chunk,offset),offset+=chunk.byteLength;return{text:new TextDecoder().decode(joined),truncated}}finally{try{reader.releaseLock()}catch{}}}async function readOnceDefault(args2,cwd,timeoutMs,maxBufferBytes=GIT_READ_DEFAULT_MAX_BUFFER_BYTES,ignoreOutput=!1){let proc,timer,resolutionTimer,childCompleted=!1;try{let startedAt=Date.now(),resolution=gitStatusReadInternals.resolveExecutable().then((executable2)=>({kind:"resolved",executable:executable2}));resolution.catch(()=>{});let resolutionOutcome=await Promise.race([resolution,new Promise((resolve34)=>{resolutionTimer=setTimeout(()=>resolve34({kind:"timeout"}),timeoutMs)})]);if(resolutionTimer!==void 0)clearTimeout(resolutionTimer),resolutionTimer=void 0;if(resolutionOutcome.kind==="timeout")return{ok:!1,code:"ETIMEDOUT",status:null,stderrTail:""};let executable=resolutionOutcome.executable,remainingMs=timeoutMs-(Date.now()-startedAt);if(remainingMs<=0)return{ok:!1,code:"ETIMEDOUT",status:null,stderrTail:""};let options={cwd,stdin:"ignore",stdout:ignoreOutput?"ignore":"pipe",stderr:ignoreOutput?"ignore":"pipe",killProcessTree:!0,maxBuffer:ignoreOutput?void 0:maxBufferBytes,env:{...process.env,GIT_TERMINAL_PROMPT:"0"}};if(proc=gitStatusReadInternals.spawn([executable,...args2],options),proc.spawnError)return{ok:!1,code:proc.spawnError.code??null,status:null,stderrTail:""};let completed=Promise.all([proc.exited,ignoreOutput?Promise.resolve({text:"",truncated:!1}):readBoundedOutput(proc.stdout,maxBufferBytes),ignoreOutput?Promise.resolve({text:"",truncated:!1}):readBoundedOutput(proc.stderr,maxBufferBytes)]).then(([exitCode,stdout,stderr])=>({kind:"completed",exitCode,stdout,stderr}));completed.catch(()=>{});let result=await Promise.race([completed,new Promise((resolve34)=>{timer=setTimeout(()=>resolve34({kind:"timeout"}),remainingMs)})]);if(result.kind==="timeout")return{ok:!1,code:"ETIMEDOUT",status:null,stderrTail:""};if(childCompleted=!0,proc.spawnError)return{ok:!1,code:proc.spawnError.code??null,status:null,stderrTail:stderrTail(result.stderr.text)};if(result.stdout.truncated||result.stderr.truncated){let partialStderr=stderrTail(result.stderr.text);return{ok:!1,code:"EOUTPUT",status:null,stderrTail:`output exceeded the ${maxBufferBytes}-byte bound${partialStderr?`: ${partialStderr}`:""}`}}if(result.exitCode===null||result.exitCode===-1||proc.signalCode!=null)return{ok:!1,code:"ESIGNAL",status:null,stderrTail:stderrTail(result.stderr.text)};if(result.exitCode!==0)return{ok:!1,code:null,status:result.exitCode,stderrTail:stderrTail(result.stderr.text)};return{ok:!0,stdout:result.stdout.text}}catch(err){return{ok:!1,code:err?.code??null,status:null,stderrTail:""}}finally{if(timer)clearTimeout(timer);if(resolutionTimer)clearTimeout(resolutionTimer);if(!childCompleted&&proc&&!proc.spawnError){try{proc.kill("SIGKILL")}catch{}let reapTimer;try{await Promise.race([proc.exited,new Promise((resolve34)=>{reapTimer=setTimeout(resolve34,2000)})])}catch{}finally{if(reapTimer)clearTimeout(reapTimer)}}}}async function readGitStatusAsync(args2,cwd,opts){let timeoutMs=opts?.timeoutMs??GIT_READ_DEFAULT_TIMEOUT_MS,maxBufferBytes=opts?.maxBufferBytes??GIT_READ_DEFAULT_MAX_BUFFER_BYTES,first=await gitStatusReadInternals.readOnce(args2,cwd,timeoutMs,maxBufferBytes);if(first.ok||first.code===null)return first;if(!TRANSIENT_RETRY_CODES.has(first.code))return first;return gitStatusReadInternals.readOnce(args2,cwd,timeoutMs,maxBufferBytes)}async function readGitRepositoryStatusAsync(cwd){return(await gitStatusReadInternals.readOnce(["rev-parse","--git-dir"],cwd,GIT_READ_DEFAULT_TIMEOUT_MS)).ok}var GIT_READ_DEFAULT_TIMEOUT_MS=1e4,GIT_READ_DEFAULT_MAX_BUFFER_BYTES=1048576,GIT_READ_STDERR_TAIL_MAX_CHARS=200,TRANSIENT_RETRY_CODES,gitStatusReadInternals;var init_git_status_read=__esm(()=>{init_bun_compat();init_git_executable();TRANSIENT_RETRY_CODES=new Set(["ETIMEDOUT","EBUSY","EPERM"]);gitStatusReadInternals={readOnce:readOnceDefault,resolveExecutable:()=>resolveGitExecutableAsync(),spawn:bunSpawn}});import*as fsSync8 from"node:fs";import*as path66 from"node:path";async function readToString(raw){let value=await raw;if(typeof value==="string")return value;if(value===null)return null;return value.ok?value.stdout:null}async function readFailureDetail(raw){let value=await raw;if(value===null||typeof value==="string")return null;if(value.ok)return null;return{code:value.code,status:value.status,stderrTail:value.stderrTail}}function isRealGitRepository(directory){try{if(fsSync8.statSync(path66.join(directory,".git")).isFile())return!0}catch{return!1}return fsSync8.existsSync(path66.join(directory,".git","HEAD"))}function parseTrackedDirtyPaths(statusOutput){let dirtyPaths=[],tokens=statusOutput.split("\x00");for(let i=0;i<tokens.length;i+=1){let token=tokens[i];if(token===""||token.length<4)continue;let xy=token.slice(0,2);if(xy==="??")continue;let filePath=token.slice(3);if(!filePath)continue;if(dirtyPaths.push(filePath),/[RC]/.test(xy)&&i+1<tokens.length&&tokens[i+1]!=="")dirtyPaths.push(tokens[i+1]),i+=1}return dirtyPaths}async function untrackedPathsInTargetTree(directory,targetSha){if(!isRealGitRepository(directory))return[];let targetTree=await readToString(await _rollbackGateInternals.runGitBuffered(["ls-tree","-r","-z","--name-only",targetSha],directory)),index=await readToString(await _rollbackGateInternals.runGitBuffered(["ls-files","-z"],directory));if(targetTree===null||index===null)return[];let indexed=new Set(index.split("\x00").filter((p)=>p!=="")),inWay=[];for(let rel of targetTree.split("\x00")){if(rel===""||indexed.has(rel))continue;if(fsSync8.existsSync(path66.join(directory,rel)))inWay.push(rel)}return inWay}function trackedDirtyCandidates(directory,dirtyRelPaths){return dirtyRelPaths.map((rel)=>({path:path66.join(directory,rel),reason:"uncommitted tracked change — destroyed by git reset --hard"}))}function swarmOverwriteCandidates(directory,overwriteRelPaths){return overwriteRelPaths.map((rel)=>({path:path66.join(directory,".swarm",rel),reason:"live .swarm state replaced by the checkpoint copy"}))}function describeUnreadableCause(measurement){if(measurement.code==="ETIMEDOUT")return"the read timed out (ETIMEDOUT) — the host may be unable to complete child spawns while loaded; restart the host and retry";if(measurement.code==="EOUTPUT")return`the status output exceeded the read safety bound (${measurement.stderrTail??"output too large"}) — reduce the change footprint (commit or stash some work, or remove untracked bulk) and retry`;if(measurement.code==="ESIGNAL")return"the git process was terminated before it answered (signal) — something external stopped it; retry, and inspect what terminates child processes if it recurs";if(measurement.code==="ENOENT")return"the git executable was not found (ENOENT) — install git on PATH, or set git.binary in your USER-level config, and retry";if(measurement.status!==null&&measurement.status!==void 0)return`git status exited with status ${measurement.status}${measurement.stderrTail?`: ${measurement.stderrTail}`:""} — repair the repository state and retry`;if(measurement.code)return`the read failed with code ${measurement.code} — retry, or inspect git status manually`;return"retry, or inspect git status manually"}async function measureGitDestruction(directory,targetSha){if(!isRealGitRepository(directory))return{kind:"ok",dirtyRelPaths:[]};let raw=_rollbackGateInternals.runGit(["--no-optional-locks","status","--porcelain","-z"],directory),status=await readToString(raw);if(status===null){let failure=await readFailureDetail(raw);return failure?{kind:"unreadable",code:failure.code,status:failure.status,stderrTail:failure.stderrTail}:{kind:"unreadable"}}let dirtyRelPaths=parseTrackedDirtyPaths(status);if(targetSha){for(let rel of await untrackedPathsInTargetTree(directory,targetSha))if(!dirtyRelPaths.includes(rel))dirtyRelPaths.push(rel)}return{kind:"ok",dirtyRelPaths}}var ROLLBACK_GIT_KIND="swarm-rollback-git",ROLLBACK_PHASE_KIND="swarm-rollback-phase",GIT_LIST_MAX_BUFFER_BYTES=33554432,_rollbackGateInternals;var init_rollback_gate=__esm(()=>{init_git_status_read();_rollbackGateInternals={runGit:(args2,cwd)=>readGitStatusAsync(args2,cwd),runGitBuffered:(args2,cwd)=>readGitStatusAsync(args2,cwd,{maxBufferBytes:GIT_LIST_MAX_BUFFER_BYTES})}});import{createHash as createHash36,randomBytes as randomBytes5}from"node:crypto";import*as fs39 from"node:fs";import*as path67 from"node:path";async function runGitStatusRead(args2,cwd){let raw=await _internals64.runGitStatus(args2,cwd);if(typeof raw==="string")return{stdout:raw};if(raw===null)return null;if(raw.ok)return{stdout:raw.stdout};return{cause:{code:raw.code,status:raw.status,stderrTail:raw.stderrTail}}}function parseTrackedDirtyPaths2(statusOutput){let dirtyPaths=[];for(let line of statusOutput.split(`
|
|
860
|
-
`)){if(!line)continue;if(line.startsWith("??"))continue;let filePath=line.slice(3).trim().replace(/^"|"$/g,"");if(!filePath)continue;if(/[RC]/.test(line.slice(0,2))&&filePath.includes(" -> "))for(let side of filePath.split(" -> ")){let cleaned=side.trim().replace(/^"|"$/g,"");if(cleaned)
|
|
859
|
+
... (diff truncated — `+String(diffLines.length-MAX_DIFF_LINES)+" more lines)",changedSectionsSet=new Set,currentSection="";for(let line of diffLines){let headingMatch=line.slice(1).match(/^##\s+(.+)$/);if(headingMatch)currentSection=headingMatch[1].trim();if(line.length>0&&(line[0]==="+"||line[0]==="-")){if(currentSection)changedSectionsSet.add(currentSection)}}return{diff:diffText,changedSections:Array.from(changedSectionsSet)}}function computeLcsDiff(oldLines,newLines){let m=oldLines.length,n=newLines.length,dp=Array.from({length:m+1},()=>Array(n+1).fill(0));for(let i2=1;i2<=m;i2++)for(let j2=1;j2<=n;j2++)if(oldLines[i2-1]===newLines[j2-1])dp[i2][j2]=dp[i2-1][j2-1]+1;else dp[i2][j2]=Math.max(dp[i2-1][j2],dp[i2][j2-1]);let entries=[],i=m,j=n;while(i>0||j>0)if(i>0&&j>0&&oldLines[i-1]===newLines[j-1])entries.unshift({type:"unchanged",line:oldLines[i-1]}),i--,j--;else if(j>0&&(i===0||dp[i][j-1]>=dp[i-1][j]))entries.unshift({type:"add",line:newLines[j-1]}),j--;else entries.unshift({type:"remove",line:oldLines[i-1]}),i--;return entries.map((entry)=>{if(entry.type==="unchanged")return` ${entry.line}`;if(entry.type==="add")return`+${entry.line}`;return`-${entry.line}`})}var _internals63;var init_spec_hash=__esm(()=>{init_effective_spec();_internals63={computeSpecDiff,computeSpecHash,isObligationPreserving,isSpecStale,readEffectiveSpecSync}});function stderrTail(text){return text.slice(-GIT_READ_STDERR_TAIL_MAX_CHARS).replace(/[\x00-\x1f\x7f]+/g," ").trim()}async function readBoundedOutput(stream,maxBytes){let reader=stream.getReader(),chunks=[],totalBytes=0,truncated=!1;try{for(;;){let{done,value}=await reader.read();if(done)break;if(!value)continue;let remaining=maxBytes-totalBytes;if(value.byteLength>remaining){if(remaining>0)chunks.push(value.slice(0,remaining));truncated=!0,totalBytes+=remaining;continue}chunks.push(value),totalBytes+=value.byteLength}let joined=new Uint8Array(totalBytes),offset=0;for(let chunk of chunks)joined.set(chunk,offset),offset+=chunk.byteLength;return{text:new TextDecoder().decode(joined),truncated}}finally{try{reader.releaseLock()}catch{}}}async function readOnceDefault(args2,cwd,timeoutMs,maxBufferBytes=GIT_READ_DEFAULT_MAX_BUFFER_BYTES,ignoreOutput=!1){let proc,timer,resolutionTimer,childCompleted=!1;try{let startedAt=Date.now(),resolution=gitStatusReadInternals.resolveExecutable().then((executable2)=>({kind:"resolved",executable:executable2}));resolution.catch(()=>{});let resolutionOutcome=await Promise.race([resolution,new Promise((resolve34)=>{resolutionTimer=setTimeout(()=>resolve34({kind:"timeout"}),timeoutMs)})]);if(resolutionTimer!==void 0)clearTimeout(resolutionTimer),resolutionTimer=void 0;if(resolutionOutcome.kind==="timeout")return{ok:!1,code:"ETIMEDOUT",status:null,stderrTail:""};let executable=resolutionOutcome.executable,remainingMs=timeoutMs-(Date.now()-startedAt);if(remainingMs<=0)return{ok:!1,code:"ETIMEDOUT",status:null,stderrTail:""};let options={cwd,stdin:"ignore",stdout:ignoreOutput?"ignore":"pipe",stderr:ignoreOutput?"ignore":"pipe",killProcessTree:!0,maxBuffer:ignoreOutput?void 0:maxBufferBytes,env:{...process.env,GIT_TERMINAL_PROMPT:"0"}};if(proc=gitStatusReadInternals.spawn([executable,...args2],options),proc.spawnError)return{ok:!1,code:proc.spawnError.code??null,status:null,stderrTail:""};let completed=Promise.all([proc.exited,ignoreOutput?Promise.resolve({text:"",truncated:!1}):readBoundedOutput(proc.stdout,maxBufferBytes),ignoreOutput?Promise.resolve({text:"",truncated:!1}):readBoundedOutput(proc.stderr,maxBufferBytes)]).then(([exitCode,stdout,stderr])=>({kind:"completed",exitCode,stdout,stderr}));completed.catch(()=>{});let result=await Promise.race([completed,new Promise((resolve34)=>{timer=setTimeout(()=>resolve34({kind:"timeout"}),remainingMs)})]);if(result.kind==="timeout")return{ok:!1,code:"ETIMEDOUT",status:null,stderrTail:""};if(childCompleted=!0,proc.spawnError)return{ok:!1,code:proc.spawnError.code??null,status:null,stderrTail:stderrTail(result.stderr.text)};if(result.stdout.truncated||result.stderr.truncated){let partialStderr=stderrTail(result.stderr.text);return{ok:!1,code:"EOUTPUT",status:null,stderrTail:`output exceeded the ${maxBufferBytes}-byte bound${partialStderr?`: ${partialStderr}`:""}`}}if(result.exitCode===null||result.exitCode===-1||proc.signalCode!=null)return{ok:!1,code:"ESIGNAL",status:null,stderrTail:stderrTail(result.stderr.text)};if(result.exitCode!==0)return{ok:!1,code:null,status:result.exitCode,stderrTail:stderrTail(result.stderr.text)};return{ok:!0,stdout:result.stdout.text}}catch(err){return{ok:!1,code:err?.code??null,status:null,stderrTail:""}}finally{if(timer)clearTimeout(timer);if(resolutionTimer)clearTimeout(resolutionTimer);if(!childCompleted&&proc&&!proc.spawnError){try{proc.kill("SIGKILL")}catch{}let reapTimer;try{await Promise.race([proc.exited,new Promise((resolve34)=>{reapTimer=setTimeout(resolve34,2000)})])}catch{}finally{if(reapTimer)clearTimeout(reapTimer)}}}}async function readGitStatusAsync(args2,cwd,opts){let timeoutMs=opts?.timeoutMs??GIT_READ_DEFAULT_TIMEOUT_MS,maxBufferBytes=opts?.maxBufferBytes??GIT_READ_DEFAULT_MAX_BUFFER_BYTES,first=await gitStatusReadInternals.readOnce(args2,cwd,timeoutMs,maxBufferBytes);if(first.ok||first.code===null)return first;if(!TRANSIENT_RETRY_CODES.has(first.code))return first;return gitStatusReadInternals.readOnce(args2,cwd,timeoutMs,maxBufferBytes)}async function readGitRepositoryStatusAsync(cwd){return(await gitStatusReadInternals.readOnce(["rev-parse","--git-dir"],cwd,GIT_READ_DEFAULT_TIMEOUT_MS)).ok}async function readGitRepositoryStatusDetailedAsync(cwd){let result=await gitStatusReadInternals.readOnce(["rev-parse","--git-dir"],cwd,GIT_READ_DEFAULT_TIMEOUT_MS);if(result.ok)return{isRepo:!0};if(result.code==="ENOENT"){let failureClass=classifySpawnFailure({code:result.code},cwd);if(failureClass==="cwd-missing")return{isRepo:!1,reason:"git_error",message:`git spawn cwd is missing: ${cwd} (ENOENT)`};if(failureClass==="cwd-unreadable")return{isRepo:!1,reason:"git_error",message:`git spawn cwd could not be inspected: ${cwd} (ENOENT)`};return{isRepo:!1,reason:"git_unavailable",message:gitBinaryMissingMessage(cwd)}}if(result.code===null){let stderrTail2=result.stderrTail??"";if(isNotGitRepositoryMessage(stderrTail2))return{isRepo:!1,reason:"not_git_repo",message:stderrTail2||`rev-parse exited ${result.status}`};return{isRepo:!1,reason:"git_error",message:`${result.status===null?"rev-parse failed (no exit status reported)":`rev-parse exited ${result.status}`}${stderrTail2?`: ${stderrTail2}`:""}`}}let tail=result.stderrTail??"";return{isRepo:!1,reason:"git_error",message:`git read failed (${result.code})${tail?`: ${tail}`:""}`}}var GIT_READ_DEFAULT_TIMEOUT_MS=1e4,GIT_READ_DEFAULT_MAX_BUFFER_BYTES=1048576,GIT_READ_STDERR_TAIL_MAX_CHARS=200,TRANSIENT_RETRY_CODES,gitStatusReadInternals;var init_git_status_read=__esm(()=>{init_branch();init_bun_compat();init_git_executable();TRANSIENT_RETRY_CODES=new Set(["ETIMEDOUT","EBUSY","EPERM"]);gitStatusReadInternals={readOnce:readOnceDefault,resolveExecutable:()=>resolveGitExecutableAsync(),spawn:bunSpawn}});import*as fsSync8 from"node:fs";import*as path66 from"node:path";async function readToString(raw){let value=await raw;if(typeof value==="string")return value;if(value===null)return null;return value.ok?value.stdout:null}async function readFailureDetail(raw){let value=await raw;if(value===null||typeof value==="string")return null;if(value.ok)return null;return{code:value.code,status:value.status,stderrTail:value.stderrTail}}function isRealGitRepository(directory){try{if(fsSync8.statSync(path66.join(directory,".git")).isFile())return!0}catch{return!1}return fsSync8.existsSync(path66.join(directory,".git","HEAD"))}function isOutOfRootRelativePath(rel){if(rel==="")return!1;let normalized=path66.posix.normalize(rel);return normalized===".."||normalized.startsWith("../")||normalized.startsWith("/")}function parseTrackedDirtyPathsWithExclusions(statusOutput){let dirtyPaths=[],excludedOutOfRoot=[],push=(candidate)=>{if(isOutOfRootRelativePath(candidate)){excludedOutOfRoot.push(candidate);return}dirtyPaths.push(candidate)},tokens=statusOutput.split("\x00");for(let i=0;i<tokens.length;i+=1){let token=tokens[i];if(token===""||token.length<4)continue;let xy=token.slice(0,2);if(xy==="??")continue;let filePath=token.slice(3);if(!filePath)continue;if(push(filePath),/[RC]/.test(xy)&&i+1<tokens.length&&tokens[i+1]!=="")push(tokens[i+1]),i+=1}return{dirtyPaths,excludedOutOfRoot}}async function untrackedPathsInTargetTree(directory,targetSha){if(!isRealGitRepository(directory))return{paths:[],failure:null};let targetTreeRaw=await _rollbackGateInternals.runGitBuffered(["ls-tree","-r","-z","--name-only",targetSha],directory),targetTree=await readToString(targetTreeRaw);if(targetTree===null){let detail=await readFailureDetail(targetTreeRaw);return{paths:[],failure:detail??{code:null,status:null,stderrTail:""}}}let indexRaw=await _rollbackGateInternals.runGitBuffered(["ls-files","-z"],directory),index=await readToString(indexRaw);if(index===null){let detail=await readFailureDetail(indexRaw);return{paths:[],failure:detail??{code:null,status:null,stderrTail:""}}}let indexed=new Set(index.split("\x00").filter((p)=>p!=="")),inWay=[];for(let rel of targetTree.split("\x00")){if(rel===""||indexed.has(rel))continue;if(fsSync8.existsSync(path66.join(directory,rel)))inWay.push(rel)}return{paths:inWay,failure:null}}function trackedDirtyCandidates(directory,dirtyRelPaths){return dirtyRelPaths.map((rel)=>({path:path66.join(directory,rel),reason:"uncommitted tracked change — destroyed by git reset --hard"}))}function swarmOverwriteCandidates(directory,overwriteRelPaths){return overwriteRelPaths.map((rel)=>({path:path66.join(directory,".swarm",rel),reason:"live .swarm state replaced by the checkpoint copy"}))}function describeUnreadableCause(measurement,source="status"){if(source==="status")return describeUnreadableStatusCause(measurement);if(measurement.code==="ETIMEDOUT")return"the target-tree listing read timed out (ETIMEDOUT) — the host may be unable to complete child spawns while loaded; restart the host and retry";if(measurement.code==="EOUTPUT")return`the listing output exceeded the read safety bound (${measurement.stderrTail??"output too large"}) — reduce the change footprint (commit or stash some work, or remove untracked bulk) and retry`;if(measurement.code==="ESIGNAL")return"the target-tree listing process was terminated before it answered (signal) — something external stopped it; retry, and inspect what terminates child processes if it recurs";if(measurement.code==="ENOENT")return"the git executable was not found (ENOENT) — install git on PATH, or set git.binary in your USER-level config, and retry";if(measurement.status!==null&&measurement.status!==void 0)return`the target-tree listing exited with status ${measurement.status}${measurement.stderrTail?`: ${measurement.stderrTail}`:""} — repair the repository state and retry`;if(measurement.code)return`the listing read failed with code ${measurement.code} — retry, or inspect the repository state manually`;return"retry, or inspect the repository state manually"}function describeUnreadableStatusCause(measurement){if(measurement.code==="ETIMEDOUT")return"the read timed out (ETIMEDOUT) — the host may be unable to complete child spawns while loaded; restart the host and retry";if(measurement.code==="EOUTPUT")return`the status output exceeded the read safety bound (${measurement.stderrTail??"output too large"}) — reduce the change footprint (commit or stash some work, or remove untracked bulk) and retry`;if(measurement.code==="ESIGNAL")return"the git process was terminated before it answered (signal) — something external stopped it; retry, and inspect what terminates child processes if it recurs";if(measurement.code==="ENOENT")return"the git executable was not found (ENOENT) — install git on PATH, or set git.binary in your USER-level config, and retry";if(measurement.status!==null&&measurement.status!==void 0)return`git status exited with status ${measurement.status}${measurement.stderrTail?`: ${measurement.stderrTail}`:""} — repair the repository state and retry`;if(measurement.code)return`the read failed with code ${measurement.code} — retry, or inspect git status manually`;return"retry, or inspect git status manually"}function formatExcludedRecord(rel){let sanitized=rel.replace(/[\x00-\x1f\x7f]+/g," ").trim();return sanitized.length>200?`${sanitized.slice(0,200)}…`:sanitized}async function measureGitDestruction(directory,targetSha){if(!isRealGitRepository(directory))return{kind:"ok",dirtyRelPaths:[],excludedOutOfRoot:[]};let raw=_rollbackGateInternals.runGit(["--no-optional-locks","status","--porcelain","-z"],directory),status=await readToString(raw);if(status===null){let failure=await readFailureDetail(raw);return failure?{kind:"unreadable",code:failure.code,status:failure.status,stderrTail:failure.stderrTail,source:"status"}:{kind:"unreadable",source:"status"}}let{dirtyPaths:dirtyRelPaths,excludedOutOfRoot}=parseTrackedDirtyPathsWithExclusions(status);if(targetSha){let{paths,failure}=await untrackedPathsInTargetTree(directory,targetSha);if(failure)return{kind:"unreadable",code:failure.code,status:failure.status,stderrTail:failure.stderrTail,source:"enumeration",excludedOutOfRoot};for(let rel of paths)if(!dirtyRelPaths.includes(rel))dirtyRelPaths.push(rel)}return{kind:"ok",dirtyRelPaths,excludedOutOfRoot}}var ROLLBACK_GIT_KIND="swarm-rollback-git",ROLLBACK_PHASE_KIND="swarm-rollback-phase",GIT_LIST_MAX_BUFFER_BYTES=33554432,_rollbackGateInternals;var init_rollback_gate=__esm(()=>{init_git_status_read();_rollbackGateInternals={runGit:(args2,cwd)=>readGitStatusAsync(args2,cwd),runGitBuffered:(args2,cwd)=>readGitStatusAsync(args2,cwd,{maxBufferBytes:GIT_LIST_MAX_BUFFER_BYTES})}});import{createHash as createHash36,randomBytes as randomBytes5}from"node:crypto";import*as fs39 from"node:fs";import*as path67 from"node:path";async function runGitStatusRead(args2,cwd){let raw=await _internals64.runGitStatus(args2,cwd);if(typeof raw==="string")return{stdout:raw};if(raw===null)return null;if(raw.ok)return{stdout:raw.stdout};return{cause:{code:raw.code,status:raw.status,stderrTail:raw.stderrTail}}}function parseTrackedDirtyPathsWithExclusions2(statusOutput){let dirtyPaths=[],excludedOutOfRoot=[],push=(candidate)=>{if(isOutOfRootRelativePath(candidate)){excludedOutOfRoot.push(candidate);return}dirtyPaths.push(candidate)};for(let line of statusOutput.split(`
|
|
860
|
+
`)){if(!line)continue;if(line.startsWith("??"))continue;let filePath=line.slice(3).trim().replace(/^"|"$/g,"");if(!filePath)continue;if(/[RC]/.test(line.slice(0,2))&&filePath.includes(" -> "))for(let side of filePath.split(" -> ")){let cleaned=side.trim().replace(/^"|"$/g,"");if(cleaned)push(cleaned)}else push(filePath)}return{dirtyPaths,excludedOutOfRoot}}async function readTrackedDirtyPaths(directory){let read=await runGitStatusRead(GIT_STATUS_ARGS,directory);if(read===null)return{ok:!1};if("cause"in read)return{ok:!1,failure:read.cause};let{dirtyPaths,excludedOutOfRoot}=parseTrackedDirtyPathsWithExclusions2(read.stdout);return{ok:!0,dirtyPaths,excludedOutOfRoot}}async function recheckBeforeDestructive(directory,expectedDirtyPaths){let read=await readTrackedDirtyPaths(directory);if(!read.ok)return{ok:!1,reason:`git status could not be re-read before the destructive reset — the confirmed scope cannot be re-verified${read.failure?`. Cause: ${describeUnreadableCause(read.failure)}`:""}`,newDirtyPaths:[]};let expected=new Set(expectedDirtyPaths),newDirtyPaths=read.dirtyPaths.filter((p)=>!expected.has(p));if(newDirtyPaths.length>0)return{ok:!1,reason:`${newDirtyPaths.length} tracked file(s) changed after the close gate was verified`,newDirtyPaths};return{ok:!0,dirtyPaths:read.dirtyPaths}}function pendingPath(directory){return validateSwarmPath(directory,PENDING_PURGE_PATH)}function resolveCandidates(scopeTarget,extra){if(extra?.candidates&&extra.candidates.length>0)return{kind:extra.kind??"set",candidates:extra.candidates};return{kind:extra?.kind??"single",candidates:[{path:scopeTarget,reason:"operator-requested"}]}}function scopeDigest(kind,candidates){let sorted=candidates.map((c)=>{let resolved=path67.resolve(c.path);if(resolved.includes("\x00")||resolved.includes(`
|
|
861
861
|
`))throw Error(`Purge candidate path contains a NUL or newline separator character and cannot be scope-bound: ${JSON.stringify(resolved)}`);return resolved}).sort().join(`
|
|
862
862
|
`);return createHash36("sha256").update(`${kind}\x00${sorted}`).digest("hex")}function mintToken(digest3){return createHash36("sha256").update(`${digest3}:${_internals64.randomBytes(16).toString("hex")}`).digest("hex").slice(0,24)}function readPending(directory){try{let raw=_internals64.readFileSync(pendingPath(directory),"utf-8"),parsed=JSON.parse(raw);if(!parsed||parsed.schemaVersion!==1||typeof parsed.scopeDigest!=="string"||typeof parsed.confirmToken!=="string"||typeof parsed.createdAt!=="number")return null;if(!Number.isFinite(parsed.createdAt))return null;if(parsed.createdAt>_internals64.now()+60000)return null;if(_internals64.now()-parsed.createdAt>PENDING_PURGE_TTL_MS)return null;return{schemaVersion:1,scopeDigest:parsed.scopeDigest,confirmToken:parsed.confirmToken,createdAt:parsed.createdAt}}catch{return null}}function writePending(directory,record2){_internals64.atomicWriteSwarmFileSync(pendingPath(directory),JSON.stringify(record2,null,2))}function previewDestructivePurge(scopeTarget,projectRoot,extra){let scope=resolveCandidates(scopeTarget,extra);return{previewLines:[`Destructive purge preview (${scope.candidates.length} candidate(s)) for ${projectRoot}:`,...scope.candidates.map((c)=>` - ${c.path} (${c.reason})`),"Uncommitted work inside these directories will be DESTROYED."],counts:{total:scope.candidates.length},optionLabel:"--confirm=<token>",confirmToken:"<run again to receive your confirm token>",candidates:scope.candidates}}function issueConfirmToken(scopeTarget,projectRoot,extra){let scope=resolveCandidates(scopeTarget,extra),digest3=scopeDigest(scope.kind,scope.candidates),token=mintToken(digest3);return writePending(projectRoot,{schemaVersion:1,scopeDigest:digest3,confirmToken:token,createdAt:_internals64.now()}),token}function consumeConfirmToken(scopeTarget,projectRoot,token,extra){let verdict=verifyPendingConfirmToken(scopeTarget,projectRoot,token,extra);if(!verdict.ok)return verdict;try{_internals64.rmSync(pendingPath(projectRoot),{force:!0})}catch(error49){log(`[destructive-purge] could not consume pending record: ${error49 instanceof Error?error49.message:String(error49)}`)}return{ok:!0}}function verifyPendingConfirmToken(scopeTarget,projectRoot,token,extra){let pending=readPending(projectRoot);if(!pending)return{ok:!1,reason:"no pending purge for this scope (expired, overwritten, or already executed)"};let scope=resolveCandidates(scopeTarget,extra),digest3=scopeDigest(scope.kind,scope.candidates);if(pending.confirmToken!==token)return{ok:!1,reason:"confirm token mismatch"};if(pending.scopeDigest!==digest3)return{ok:!1,reason:"purge scope changed since the token was issued — re-run the preview and confirm the new token"};return{ok:!0}}function executeDestructivePurge(scopeTarget,projectRoot,token,extra){let verdict=verifyPendingConfirmToken(scopeTarget,projectRoot,token,extra);if(!verdict.ok)return verdict;let{candidates}=resolveCandidates(scopeTarget,extra),purged=[];for(let candidate of candidates){if(!_internals64.existsSync(candidate.path))continue;try{_internals64.rmSync(candidate.path,{recursive:!0,force:!0}),purged.push(candidate.path)}catch(error49){try{_internals64.rmSync(pendingPath(projectRoot),{force:!0})}catch{}return{ok:!1,reason:`candidate ${candidate.path} could not be purged: ${error49 instanceof Error?error49.message:String(error49)}`}}}try{_internals64.rmSync(pendingPath(projectRoot),{force:!0})}catch(error49){log(`[destructive-purge] could not consume pending record: ${error49 instanceof Error?error49.message:String(error49)}`)}return{ok:!0,purged}}var PENDING_PURGE_PATH="pending-purge.json",PENDING_PURGE_TTL_MS=900000,_internals64,GIT_STATUS_ARGS;var init_destructive_purge=__esm(()=>{init_utils2();init_atomic_write();init_logger();init_git_status_read();init_rollback_gate();_internals64={readFileSync:fs39.readFileSync,rmSync:fs39.rmSync.bind(fs39),existsSync:fs39.existsSync.bind(fs39),atomicWriteSwarmFileSync,now:()=>Date.now(),randomBytes:randomBytes5,scopeDigest,runGitStatus:(args2,cwd)=>readGitStatusAsync(args2,cwd)},GIT_STATUS_ARGS=["--no-optional-locks","status","--porcelain"]});import*as fs40 from"node:fs";import*as path68 from"node:path";function backupSwarmStateBeforeReset(directory,kind,relEntries,opts){let warnings=[],copied=[],swarmDir=path68.join(directory,".swarm");try{let stat8=fs40.lstatSync(swarmDir);if(stat8.isSymbolicLink()||!stat8.isDirectory())return warnings.push("backup skipped: .swarm is a symlink or not a directory — nothing was backed up"),{backupDir:null,copied,warnings}}catch{return warnings.push("backup skipped: .swarm directory is missing — nothing was backed up"),{backupDir:null,copied,warnings}}let timestamp=new Date().toISOString().replace(/[:.]/g,"-"),backupsRoot=path68.join(swarmDir,opts?.backupsRoot??"reset-backups"),backupDir=path68.join(backupsRoot,`${kind}-${timestamp}`),backupDirCreated=!1,ensureBackupDir=()=>{if(!backupDirCreated)fs40.mkdirSync(backupDir,{recursive:!0}),backupDirCreated=!0};for(let rel of relEntries){let src;try{src=validateSwarmPath(directory,rel)}catch{warnings.push(`skipped backup of ${rel} (path validation failed)`);continue}if(!fs40.existsSync(src))continue;try{ensureBackupDir();let dest=path68.join(backupDir,rel);fs40.mkdirSync(path68.dirname(dest),{recursive:!0}),fs40.cpSync(src,dest,{recursive:!0}),copied.push(rel)}catch(err){warnings.push(`failed to back up ${rel}: ${err instanceof Error?err.message:String(err)}`)}}if(copied.length===0){if(backupDirCreated)try{fs40.rmSync(backupDir,{recursive:!0,force:!0})}catch{}return{backupDir:null,copied,warnings}}return pruneOldResetBackups(backupsRoot,warnings,path68.basename(backupDir)),{backupDir,copied,warnings}}function backupTimestampSortKey(name){for(let prefix of BACKUP_KIND_PREFIXES)if(name.startsWith(prefix))return name.slice(prefix.length).replace(/\D/g,"");return""}function pruneOldResetBackups(backupsRoot,warnings,keepDirName){try{let entries=fs40.readdirSync(backupsRoot,{withFileTypes:!0}).filter((e)=>e.isDirectory()).map((e)=>({name:e.name,key:backupTimestampSortKey(e.name)})).sort((a,b)=>a.key===b.key?b.name.localeCompare(a.name):b.key.localeCompare(a.key));for(let stale of entries.slice(RESET_BACKUP_RETENTION)){if(stale.name===keepDirName)continue;try{fs40.rmSync(path68.join(backupsRoot,stale.name),{recursive:!0,force:!0})}catch(err){warnings.push(`failed to prune old backup ${stale.name}: ${err instanceof Error?err.message:String(err)}`)}}}catch(err){warnings.push(`failed to prune old reset backups: ${err instanceof Error?err.message:String(err)}`)}}function backupTrackedChangesBeforeRollback(directory,repoRelPaths){let warnings=[],copied=[],swarmDir=path68.join(directory,".swarm");try{let stat8=fs40.lstatSync(swarmDir);if(stat8.isSymbolicLink()||!stat8.isDirectory())return warnings.push("backup skipped: .swarm is a symlink or not a directory — nothing was backed up"),{backupDir:null,copied,warnings}}catch{return warnings.push("backup skipped: .swarm directory is missing — nothing was backed up"),{backupDir:null,copied,warnings}}let timestamp=new Date().toISOString().replace(/[:.]/g,"-"),backupsRoot=path68.join(swarmDir,"rollback-backups"),backupDir=path68.join(backupsRoot,`rollback-git-${timestamp}`),backupDirCreated=!1,ensureBackupDir=()=>{if(!backupDirCreated)fs40.mkdirSync(backupDir,{recursive:!0}),backupDirCreated=!0};for(let rel of repoRelPaths){if(!rel)continue;let src=path68.join(directory,rel);if(!fs40.existsSync(src))continue;try{ensureBackupDir();let dest=path68.join(backupDir,"tracked",rel);fs40.mkdirSync(path68.dirname(dest),{recursive:!0}),fs40.cpSync(src,dest,{recursive:!0}),copied.push(rel)}catch(err){warnings.push(`failed to back up ${rel}: ${err instanceof Error?err.message:String(err)}`)}}if(copied.length===0){if(backupDirCreated)try{fs40.rmSync(backupDir,{recursive:!0,force:!0})}catch{}return{backupDir:null,copied,warnings}}return pruneOldResetBackups(backupsRoot,warnings,path68.basename(backupDir)),{backupDir,copied,warnings}}var RESET_BACKUP_RETENTION=5,BACKUP_KIND_PREFIXES;var init_reset_backup=__esm(()=>{init_utils2();BACKUP_KIND_PREFIXES=["reset-session-","rollback-git-","rollback-","reset-"]});function $constructor2(name,initializer3,params){function init(inst,def){var _a2;Object.defineProperty(inst,"_zod",{value:inst._zod??{},enumerable:!1}),(_a2=inst._zod).traits??(_a2.traits=new Set),inst._zod.traits.add(name),initializer3(inst,def);for(let k in _.prototype)if(!(k in inst))Object.defineProperty(inst,k,{value:_.prototype[k].bind(inst)});inst._zod.constr=_,inst._zod.def=def}let Parent=params?.Parent??Object;class Definition extends Parent{}Object.defineProperty(Definition,"name",{value:name});function _(def){var _a2;let inst=params?.Parent?new Definition:this;init(inst,def),(_a2=inst._zod).deferred??(_a2.deferred=[]);for(let fn2 of inst._zod.deferred)fn2();return inst}return Object.defineProperty(_,"init",{value:init}),Object.defineProperty(_,Symbol.hasInstance,{value:(inst)=>{if(params?.Parent&&inst instanceof params.Parent)return!0;return inst?._zod?.traits?.has(name)}}),Object.defineProperty(_,"name",{value:name}),_}function config2(newConfig){if(newConfig)Object.assign(globalConfig2,newConfig);return globalConfig2}var NEVER2,$brand2,$ZodAsyncError2,$ZodEncodeError2,globalConfig2;var init_core4=__esm(()=>{NEVER2=Object.freeze({status:"aborted"});$brand2=Symbol("zod_brand");$ZodAsyncError2=class $ZodAsyncError2 extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}};$ZodEncodeError2=class $ZodEncodeError2 extends Error{constructor(name){super(`Encountered unidirectional transform during encode: ${name}`);this.name="ZodEncodeError"}};globalConfig2={}});var exports_util2={};__export(exports_util2,{unwrapMessage:()=>unwrapMessage2,uint8ArrayToHex:()=>uint8ArrayToHex2,uint8ArrayToBase64url:()=>uint8ArrayToBase64url2,uint8ArrayToBase64:()=>uint8ArrayToBase642,stringifyPrimitive:()=>stringifyPrimitive2,shallowClone:()=>shallowClone2,safeExtend:()=>safeExtend2,required:()=>required2,randomString:()=>randomString2,propertyKeyTypes:()=>propertyKeyTypes2,promiseAllObject:()=>promiseAllObject2,primitiveTypes:()=>primitiveTypes2,prefixIssues:()=>prefixIssues2,pick:()=>pick2,partial:()=>partial2,optionalKeys:()=>optionalKeys2,omit:()=>omit2,objectClone:()=>objectClone2,numKeys:()=>numKeys2,nullish:()=>nullish3,normalizeParams:()=>normalizeParams2,mergeDefs:()=>mergeDefs2,merge:()=>merge2,jsonStringifyReplacer:()=>jsonStringifyReplacer2,joinValues:()=>joinValues2,issue:()=>issue2,isPlainObject:()=>isPlainObject2,isObject:()=>isObject2,hexToUint8Array:()=>hexToUint8Array2,getSizableOrigin:()=>getSizableOrigin2,getParsedType:()=>getParsedType2,getLengthableOrigin:()=>getLengthableOrigin2,getEnumValues:()=>getEnumValues2,getElementAtPath:()=>getElementAtPath2,floatSafeRemainder:()=>floatSafeRemainder2,finalizeIssue:()=>finalizeIssue2,extend:()=>extend2,escapeRegex:()=>escapeRegex3,esc:()=>esc2,defineLazy:()=>defineLazy2,createTransparentProxy:()=>createTransparentProxy2,cloneDef:()=>cloneDef2,clone:()=>clone2,cleanRegex:()=>cleanRegex2,cleanEnum:()=>cleanEnum2,captureStackTrace:()=>captureStackTrace2,cached:()=>cached2,base64urlToUint8Array:()=>base64urlToUint8Array2,base64ToUint8Array:()=>base64ToUint8Array2,assignProp:()=>assignProp2,assertNotEqual:()=>assertNotEqual2,assertNever:()=>assertNever2,assertIs:()=>assertIs2,assertEqual:()=>assertEqual2,assert:()=>assert2,allowsEval:()=>allowsEval2,aborted:()=>aborted2,NUMBER_FORMAT_RANGES:()=>NUMBER_FORMAT_RANGES2,Class:()=>Class2,BIGINT_FORMAT_RANGES:()=>BIGINT_FORMAT_RANGES2});function assertEqual2(val){return val}function assertNotEqual2(val){return val}function assertIs2(_arg){}function assertNever2(_x){throw Error()}function assert2(_){}function getEnumValues2(entries){let numericValues=Object.values(entries).filter((v)=>typeof v==="number");return Object.entries(entries).filter(([k,_])=>numericValues.indexOf(+k)===-1).map(([_,v])=>v)}function joinValues2(array2,separator="|"){return array2.map((val)=>stringifyPrimitive2(val)).join(separator)}function jsonStringifyReplacer2(_,value){if(typeof value==="bigint")return value.toString();return value}function cached2(getter){return{get value(){{let value=getter();return Object.defineProperty(this,"value",{value}),value}throw Error("cached value already set")}}}function nullish3(input){return input===null||input===void 0}function cleanRegex2(source){let start=source.startsWith("^")?1:0,end=source.endsWith("$")?source.length-1:source.length;return source.slice(start,end)}function floatSafeRemainder2(val,step){let valDecCount=(val.toString().split(".")[1]||"").length,stepString=step.toString(),stepDecCount=(stepString.split(".")[1]||"").length;if(stepDecCount===0&&/\d?e-\d?/.test(stepString)){let match=stepString.match(/\d?e-(\d?)/);if(match?.[1])stepDecCount=Number.parseInt(match[1])}let decCount=valDecCount>stepDecCount?valDecCount:stepDecCount,valInt=Number.parseInt(val.toFixed(decCount).replace(".","")),stepInt=Number.parseInt(step.toFixed(decCount).replace(".",""));return valInt%stepInt/10**decCount}function defineLazy2(object2,key,getter){let value=void 0;Object.defineProperty(object2,key,{get(){if(value===EVALUATING2)return;if(value===void 0)value=EVALUATING2,value=getter();return value},set(v){Object.defineProperty(object2,key,{value:v})},configurable:!0})}function objectClone2(obj){return Object.create(Object.getPrototypeOf(obj),Object.getOwnPropertyDescriptors(obj))}function assignProp2(target,prop,value){Object.defineProperty(target,prop,{value,writable:!0,enumerable:!0,configurable:!0})}function mergeDefs2(...defs){let mergedDescriptors={};for(let def of defs){let descriptors=Object.getOwnPropertyDescriptors(def);Object.assign(mergedDescriptors,descriptors)}return Object.defineProperties({},mergedDescriptors)}function cloneDef2(schema){return mergeDefs2(schema._zod.def)}function getElementAtPath2(obj,path69){if(!path69)return obj;return path69.reduce((acc,key)=>acc?.[key],obj)}function promiseAllObject2(promisesObj){let keys=Object.keys(promisesObj),promises6=keys.map((key)=>promisesObj[key]);return Promise.all(promises6).then((results)=>{let resolvedObj={};for(let i=0;i<keys.length;i++)resolvedObj[keys[i]]=results[i];return resolvedObj})}function randomString2(length=10){let str="";for(let i=0;i<length;i++)str+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return str}function esc2(str){return JSON.stringify(str)}function isObject2(data){return typeof data==="object"&&data!==null&&!Array.isArray(data)}function isPlainObject2(o){if(isObject2(o)===!1)return!1;let ctor=o.constructor;if(ctor===void 0)return!0;let prot=ctor.prototype;if(isObject2(prot)===!1)return!1;if(Object.prototype.hasOwnProperty.call(prot,"isPrototypeOf")===!1)return!1;return!0}function shallowClone2(o){if(isPlainObject2(o))return{...o};if(Array.isArray(o))return[...o];return o}function numKeys2(data){let keyCount=0;for(let key in data)if(Object.prototype.hasOwnProperty.call(data,key))keyCount++;return keyCount}function escapeRegex3(str){return str.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function clone2(inst,def,params){let cl=new inst._zod.constr(def??inst._zod.def);if(!def||params?.parent)cl._zod.parent=inst;return cl}function normalizeParams2(_params){let params=_params;if(!params)return{};if(typeof params==="string")return{error:()=>params};if(params?.message!==void 0){if(params?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");params.error=params.message}if(delete params.message,typeof params.error==="string")return{...params,error:()=>params.error};return params}function createTransparentProxy2(getter){let target;return new Proxy({},{get(_,prop,receiver){return target??(target=getter()),Reflect.get(target,prop,receiver)},set(_,prop,value,receiver){return target??(target=getter()),Reflect.set(target,prop,value,receiver)},has(_,prop){return target??(target=getter()),Reflect.has(target,prop)},deleteProperty(_,prop){return target??(target=getter()),Reflect.deleteProperty(target,prop)},ownKeys(_){return target??(target=getter()),Reflect.ownKeys(target)},getOwnPropertyDescriptor(_,prop){return target??(target=getter()),Reflect.getOwnPropertyDescriptor(target,prop)},defineProperty(_,prop,descriptor){return target??(target=getter()),Reflect.defineProperty(target,prop,descriptor)}})}function stringifyPrimitive2(value){if(typeof value==="bigint")return value.toString()+"n";if(typeof value==="string")return`"${value}"`;return`${value}`}function optionalKeys2(shape){return Object.keys(shape).filter((k)=>{return shape[k]._zod.optin==="optional"&&shape[k]._zod.optout==="optional"})}function pick2(schema,mask){let currDef=schema._zod.def,def=mergeDefs2(schema._zod.def,{get shape(){let newShape={};for(let key in mask){if(!(key in currDef.shape))throw Error(`Unrecognized key: "${key}"`);if(!mask[key])continue;newShape[key]=currDef.shape[key]}return assignProp2(this,"shape",newShape),newShape},checks:[]});return clone2(schema,def)}function omit2(schema,mask){let currDef=schema._zod.def,def=mergeDefs2(schema._zod.def,{get shape(){let newShape={...schema._zod.def.shape};for(let key in mask){if(!(key in currDef.shape))throw Error(`Unrecognized key: "${key}"`);if(!mask[key])continue;delete newShape[key]}return assignProp2(this,"shape",newShape),newShape},checks:[]});return clone2(schema,def)}function extend2(schema,shape){if(!isPlainObject2(shape))throw Error("Invalid input to extend: expected a plain object");let checks3=schema._zod.def.checks;if(checks3&&checks3.length>0)throw Error("Object schemas containing refinements cannot be extended. Use `.safeExtend()` instead.");let def=mergeDefs2(schema._zod.def,{get shape(){let _shape={...schema._zod.def.shape,...shape};return assignProp2(this,"shape",_shape),_shape},checks:[]});return clone2(schema,def)}function safeExtend2(schema,shape){if(!isPlainObject2(shape))throw Error("Invalid input to safeExtend: expected a plain object");let def={...schema._zod.def,get shape(){let _shape={...schema._zod.def.shape,...shape};return assignProp2(this,"shape",_shape),_shape},checks:schema._zod.def.checks};return clone2(schema,def)}function merge2(a,b){let def=mergeDefs2(a._zod.def,{get shape(){let _shape={...a._zod.def.shape,...b._zod.def.shape};return assignProp2(this,"shape",_shape),_shape},get catchall(){return b._zod.def.catchall},checks:[]});return clone2(a,def)}function partial2(Class2,schema,mask){let def=mergeDefs2(schema._zod.def,{get shape(){let oldShape=schema._zod.def.shape,shape={...oldShape};if(mask)for(let key in mask){if(!(key in oldShape))throw Error(`Unrecognized key: "${key}"`);if(!mask[key])continue;shape[key]=Class2?new Class2({type:"optional",innerType:oldShape[key]}):oldShape[key]}else for(let key in oldShape)shape[key]=Class2?new Class2({type:"optional",innerType:oldShape[key]}):oldShape[key];return assignProp2(this,"shape",shape),shape},checks:[]});return clone2(schema,def)}function required2(Class2,schema,mask){let def=mergeDefs2(schema._zod.def,{get shape(){let oldShape=schema._zod.def.shape,shape={...oldShape};if(mask)for(let key in mask){if(!(key in shape))throw Error(`Unrecognized key: "${key}"`);if(!mask[key])continue;shape[key]=new Class2({type:"nonoptional",innerType:oldShape[key]})}else for(let key in oldShape)shape[key]=new Class2({type:"nonoptional",innerType:oldShape[key]});return assignProp2(this,"shape",shape),shape},checks:[]});return clone2(schema,def)}function aborted2(x,startIndex=0){if(x.aborted===!0)return!0;for(let i=startIndex;i<x.issues.length;i++)if(x.issues[i]?.continue!==!0)return!0;return!1}function prefixIssues2(path69,issues){return issues.map((iss)=>{var _a2;return(_a2=iss).path??(_a2.path=[]),iss.path.unshift(path69),iss})}function unwrapMessage2(message){return typeof message==="string"?message:message?.message}function finalizeIssue2(iss,ctx,config3){let full={...iss,path:iss.path??[]};if(!iss.message){let message=unwrapMessage2(iss.inst?._zod.def?.error?.(iss))??unwrapMessage2(ctx?.error?.(iss))??unwrapMessage2(config3.customError?.(iss))??unwrapMessage2(config3.localeError?.(iss))??"Invalid input";full.message=message}if(delete full.inst,delete full.continue,!ctx?.reportInput)delete full.input;return full}function getSizableOrigin2(input){if(input instanceof Set)return"set";if(input instanceof Map)return"map";if(input instanceof File)return"file";return"unknown"}function getLengthableOrigin2(input){if(Array.isArray(input))return"array";if(typeof input==="string")return"string";return"unknown"}function issue2(...args2){let[iss,input,inst]=args2;if(typeof iss==="string")return{message:iss,code:"custom",input,inst};return{...iss}}function cleanEnum2(obj){return Object.entries(obj).filter(([k,_])=>{return Number.isNaN(Number.parseInt(k,10))}).map((el)=>el[1])}function base64ToUint8Array2(base643){let binaryString=atob(base643),bytes=new Uint8Array(binaryString.length);for(let i=0;i<binaryString.length;i++)bytes[i]=binaryString.charCodeAt(i);return bytes}function uint8ArrayToBase642(bytes){let binaryString="";for(let i=0;i<bytes.length;i++)binaryString+=String.fromCharCode(bytes[i]);return btoa(binaryString)}function base64urlToUint8Array2(base64url3){let base643=base64url3.replace(/-/g,"+").replace(/_/g,"/"),padding="=".repeat((4-base643.length%4)%4);return base64ToUint8Array2(base643+padding)}function uint8ArrayToBase64url2(bytes){return uint8ArrayToBase642(bytes).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function hexToUint8Array2(hex3){let cleanHex=hex3.replace(/^0x/,"");if(cleanHex.length%2!==0)throw Error("Invalid hex string length");let bytes=new Uint8Array(cleanHex.length/2);for(let i=0;i<cleanHex.length;i+=2)bytes[i/2]=Number.parseInt(cleanHex.slice(i,i+2),16);return bytes}function uint8ArrayToHex2(bytes){return Array.from(bytes).map((b)=>b.toString(16).padStart(2,"0")).join("")}class Class2{constructor(..._args){}}var EVALUATING2,captureStackTrace2,allowsEval2,getParsedType2=(data)=>{let t=typeof data;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(data)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":if(Array.isArray(data))return"array";if(data===null)return"null";if(data.then&&typeof data.then==="function"&&data.catch&&typeof data.catch==="function")return"promise";if(typeof Map<"u"&&data instanceof Map)return"map";if(typeof Set<"u"&&data instanceof Set)return"set";if(typeof Date<"u"&&data instanceof Date)return"date";if(typeof File<"u"&&data instanceof File)return"file";return"object";default:throw Error(`Unknown data type: ${t}`)}},propertyKeyTypes2,primitiveTypes2,NUMBER_FORMAT_RANGES2,BIGINT_FORMAT_RANGES2;var init_util2=__esm(()=>{EVALUATING2=Symbol("evaluating");captureStackTrace2="captureStackTrace"in Error?Error.captureStackTrace:(..._args)=>{};allowsEval2=cached2(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(_){return!1}});propertyKeyTypes2=new Set(["string","number","symbol"]),primitiveTypes2=new Set(["string","number","bigint","boolean","symbol","undefined"]);NUMBER_FORMAT_RANGES2={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},BIGINT_FORMAT_RANGES2={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]}});function flattenError2(error49,mapper=(issue3)=>issue3.message){let fieldErrors={},formErrors=[];for(let sub of error49.issues)if(sub.path.length>0)fieldErrors[sub.path[0]]=fieldErrors[sub.path[0]]||[],fieldErrors[sub.path[0]].push(mapper(sub));else formErrors.push(mapper(sub));return{formErrors,fieldErrors}}function formatError2(error49,_mapper){let mapper=_mapper||function(issue3){return issue3.message},fieldErrors={_errors:[]},processError=(error50)=>{for(let issue3 of error50.issues)if(issue3.code==="invalid_union"&&issue3.errors.length)issue3.errors.map((issues)=>processError({issues}));else if(issue3.code==="invalid_key")processError({issues:issue3.issues});else if(issue3.code==="invalid_element")processError({issues:issue3.issues});else if(issue3.path.length===0)fieldErrors._errors.push(mapper(issue3));else{let curr=fieldErrors,i=0;while(i<issue3.path.length){let el=issue3.path[i];if(i!==issue3.path.length-1)curr[el]=curr[el]||{_errors:[]};else curr[el]=curr[el]||{_errors:[]},curr[el]._errors.push(mapper(issue3));curr=curr[el],i++}}};return processError(error49),fieldErrors}function treeifyError2(error49,_mapper){let mapper=_mapper||function(issue3){return issue3.message},result={errors:[]},processError=(error50,path69=[])=>{var _a2,_b;for(let issue3 of error50.issues)if(issue3.code==="invalid_union"&&issue3.errors.length)issue3.errors.map((issues)=>processError({issues},issue3.path));else if(issue3.code==="invalid_key")processError({issues:issue3.issues},issue3.path);else if(issue3.code==="invalid_element")processError({issues:issue3.issues},issue3.path);else{let fullpath=[...path69,...issue3.path];if(fullpath.length===0){result.errors.push(mapper(issue3));continue}let curr=result,i=0;while(i<fullpath.length){let el=fullpath[i],terminal=i===fullpath.length-1;if(typeof el==="string")curr.properties??(curr.properties={}),(_a2=curr.properties)[el]??(_a2[el]={errors:[]}),curr=curr.properties[el];else curr.items??(curr.items=[]),(_b=curr.items)[el]??(_b[el]={errors:[]}),curr=curr.items[el];if(terminal)curr.errors.push(mapper(issue3));i++}}};return processError(error49),result}function toDotPath2(_path){let segs=[],path69=_path.map((seg)=>typeof seg==="object"?seg.key:seg);for(let seg of path69)if(typeof seg==="number")segs.push(`[${seg}]`);else if(typeof seg==="symbol")segs.push(`[${JSON.stringify(String(seg))}]`);else if(/[^\w$]/.test(seg))segs.push(`[${JSON.stringify(seg)}]`);else{if(segs.length)segs.push(".");segs.push(seg)}return segs.join("")}function prettifyError2(error49){let lines=[],issues=[...error49.issues].sort((a,b)=>(a.path??[]).length-(b.path??[]).length);for(let issue3 of issues)if(lines.push(`✖ ${issue3.message}`),issue3.path?.length)lines.push(` → at ${toDotPath2(issue3.path)}`);return lines.join(`
|
|
863
863
|
`)}var initializer3=(inst,def)=>{inst.name="$ZodError",Object.defineProperty(inst,"_zod",{value:inst._zod,enumerable:!1}),Object.defineProperty(inst,"issues",{value:def,enumerable:!1}),inst.message=JSON.stringify(def,jsonStringifyReplacer2,2),Object.defineProperty(inst,"toString",{value:()=>inst.message,enumerable:!1})},$ZodError2,$ZodRealError2;var init_errors4=__esm(()=>{init_core4();init_util2();$ZodError2=$constructor2("$ZodError",initializer3),$ZodRealError2=$constructor2("$ZodError",initializer3,{Parent:Error})});var _parse2=(_Err)=>(schema,value,_ctx,_params)=>{let ctx=_ctx?Object.assign(_ctx,{async:!1}):{async:!1},result=schema._zod.run({value,issues:[]},ctx);if(result instanceof Promise)throw new $ZodAsyncError2;if(result.issues.length){let e=new(_params?.Err??_Err)(result.issues.map((iss)=>finalizeIssue2(iss,ctx,config2())));throw captureStackTrace2(e,_params?.callee),e}return result.value},parse5,_parseAsync2=(_Err)=>async(schema,value,_ctx,params)=>{let ctx=_ctx?Object.assign(_ctx,{async:!0}):{async:!0},result=schema._zod.run({value,issues:[]},ctx);if(result instanceof Promise)result=await result;if(result.issues.length){let e=new(params?.Err??_Err)(result.issues.map((iss)=>finalizeIssue2(iss,ctx,config2())));throw captureStackTrace2(e,params?.callee),e}return result.value},parseAsync3,_safeParse2=(_Err)=>(schema,value,_ctx)=>{let ctx=_ctx?{..._ctx,async:!1}:{async:!1},result=schema._zod.run({value,issues:[]},ctx);if(result instanceof Promise)throw new $ZodAsyncError2;return result.issues.length?{success:!1,error:new(_Err??$ZodError2)(result.issues.map((iss)=>finalizeIssue2(iss,ctx,config2())))}:{success:!0,data:result.value}},safeParse3,_safeParseAsync2=(_Err)=>async(schema,value,_ctx)=>{let ctx=_ctx?Object.assign(_ctx,{async:!0}):{async:!0},result=schema._zod.run({value,issues:[]},ctx);if(result instanceof Promise)result=await result;return result.issues.length?{success:!1,error:new _Err(result.issues.map((iss)=>finalizeIssue2(iss,ctx,config2())))}:{success:!0,data:result.value}},safeParseAsync3,_encode2=(_Err)=>(schema,value,_ctx)=>{let ctx=_ctx?Object.assign(_ctx,{direction:"backward"}):{direction:"backward"};return _parse2(_Err)(schema,value,ctx)},encode3,_decode2=(_Err)=>(schema,value,_ctx)=>{return _parse2(_Err)(schema,value,_ctx)},decode3,_encodeAsync2=(_Err)=>async(schema,value,_ctx)=>{let ctx=_ctx?Object.assign(_ctx,{direction:"backward"}):{direction:"backward"};return _parseAsync2(_Err)(schema,value,ctx)},encodeAsync3,_decodeAsync2=(_Err)=>async(schema,value,_ctx)=>{return _parseAsync2(_Err)(schema,value,_ctx)},decodeAsync3,_safeEncode2=(_Err)=>(schema,value,_ctx)=>{let ctx=_ctx?Object.assign(_ctx,{direction:"backward"}):{direction:"backward"};return _safeParse2(_Err)(schema,value,ctx)},safeEncode3,_safeDecode2=(_Err)=>(schema,value,_ctx)=>{return _safeParse2(_Err)(schema,value,_ctx)},safeDecode3,_safeEncodeAsync2=(_Err)=>async(schema,value,_ctx)=>{let ctx=_ctx?Object.assign(_ctx,{direction:"backward"}):{direction:"backward"};return _safeParseAsync2(_Err)(schema,value,ctx)},safeEncodeAsync3,_safeDecodeAsync2=(_Err)=>async(schema,value,_ctx)=>{return _safeParseAsync2(_Err)(schema,value,_ctx)},safeDecodeAsync3;var init_parse3=__esm(()=>{init_core4();init_errors4();init_util2();parse5=_parse2($ZodRealError2),parseAsync3=_parseAsync2($ZodRealError2),safeParse3=_safeParse2($ZodRealError2),safeParseAsync3=_safeParseAsync2($ZodRealError2),encode3=_encode2($ZodRealError2),decode3=_decode2($ZodRealError2),encodeAsync3=_encodeAsync2($ZodRealError2),decodeAsync3=_decodeAsync2($ZodRealError2),safeEncode3=_safeEncode2($ZodRealError2),safeDecode3=_safeDecode2($ZodRealError2),safeEncodeAsync3=_safeEncodeAsync2($ZodRealError2),safeDecodeAsync3=_safeDecodeAsync2($ZodRealError2)});var exports_regexes2={};__export(exports_regexes2,{xid:()=>xid3,uuid7:()=>uuid72,uuid6:()=>uuid62,uuid4:()=>uuid42,uuid:()=>uuid3,uppercase:()=>uppercase2,unicodeEmail:()=>unicodeEmail2,undefined:()=>_undefined4,ulid:()=>ulid3,time:()=>time3,string:()=>string4,sha512_hex:()=>sha512_hex2,sha512_base64url:()=>sha512_base64url2,sha512_base64:()=>sha512_base642,sha384_hex:()=>sha384_hex2,sha384_base64url:()=>sha384_base64url2,sha384_base64:()=>sha384_base642,sha256_hex:()=>sha256_hex2,sha256_base64url:()=>sha256_base64url2,sha256_base64:()=>sha256_base642,sha1_hex:()=>sha1_hex2,sha1_base64url:()=>sha1_base64url2,sha1_base64:()=>sha1_base642,rfc5322Email:()=>rfc5322Email2,number:()=>number4,null:()=>_null4,nanoid:()=>nanoid3,md5_hex:()=>md5_hex2,md5_base64url:()=>md5_base64url2,md5_base64:()=>md5_base642,lowercase:()=>lowercase2,ksuid:()=>ksuid3,ipv6:()=>ipv63,ipv4:()=>ipv43,integer:()=>integer2,idnEmail:()=>idnEmail2,html5Email:()=>html5Email2,hostname:()=>hostname3,hex:()=>hex3,guid:()=>guid3,extendedDuration:()=>extendedDuration2,emoji:()=>emoji3,email:()=>email3,e164:()=>e1643,duration:()=>duration3,domain:()=>domain2,datetime:()=>datetime3,date:()=>date5,cuid2:()=>cuid23,cuid:()=>cuid5,cidrv6:()=>cidrv63,cidrv4:()=>cidrv43,browserEmail:()=>browserEmail2,boolean:()=>boolean4,bigint:()=>bigint4,base64url:()=>base64url3,base64:()=>base643});function emoji3(){return new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")}function timeSource2(args2){return typeof args2.precision==="number"?args2.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":args2.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${args2.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function time3(args2){return new RegExp(`^${timeSource2(args2)}$`)}function datetime3(args2){let time4=timeSource2({precision:args2.precision}),opts=["Z"];if(args2.local)opts.push("");if(args2.offset)opts.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let timeRegex=`${time4}(?:${opts.join("|")})`;return new RegExp(`^${dateSource2}T(?:${timeRegex})$`)}function fixedBase642(bodyLength,padding){return new RegExp(`^[A-Za-z0-9+/]{${bodyLength}}${padding}$`)}function fixedBase64url2(length){return new RegExp(`^[A-Za-z0-9_-]{${length}}$`)}var cuid5,cuid23,ulid3,xid3,ksuid3,nanoid3,duration3,extendedDuration2,guid3,uuid3=(version2)=>{if(!version2)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version2}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)},uuid42,uuid62,uuid72,email3,html5Email2,rfc5322Email2,unicodeEmail2,idnEmail2,browserEmail2,ipv43,ipv63,cidrv43,cidrv63,base643,base64url3,hostname3,domain2,e1643,dateSource2="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",date5,string4=(params)=>{let regex=params?`[\\s\\S]{${params?.minimum??0},${params?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${regex}$`)},bigint4,integer2,number4,boolean4,_null4,_undefined4,lowercase2,uppercase2,hex3,md5_hex2,md5_base642,md5_base64url2,sha1_hex2,sha1_base642,sha1_base64url2,sha256_hex2,sha256_base642,sha256_base64url2,sha384_hex2,sha384_base642,sha384_base64url2,sha512_hex2,sha512_base642,sha512_base64url2;var init_regexes2=__esm(()=>{cuid5=/^[cC][^\s-]{8,}$/,cuid23=/^[0-9a-z]+$/,ulid3=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,xid3=/^[0-9a-vA-V]{20}$/,ksuid3=/^[A-Za-z0-9]{27}$/,nanoid3=/^[a-zA-Z0-9_-]{21}$/,duration3=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,extendedDuration2=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,guid3=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,uuid42=uuid3(4),uuid62=uuid3(6),uuid72=uuid3(7),email3=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,html5Email2=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,rfc5322Email2=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,unicodeEmail2=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,idnEmail2=unicodeEmail2,browserEmail2=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;ipv43=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv63=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,cidrv43=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,cidrv63=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base643=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,base64url3=/^[A-Za-z0-9_-]*$/,hostname3=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/,domain2=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,e1643=/^\+(?:[0-9]){6,14}[0-9]$/,date5=new RegExp(`^${dateSource2}$`);bigint4=/^-?\d+n?$/,integer2=/^-?\d+$/,number4=/^-?\d+(?:\.\d+)?/,boolean4=/^(?:true|false)$/i,_null4=/^null$/i,_undefined4=/^undefined$/i,lowercase2=/^[^A-Z]*$/,uppercase2=/^[^a-z]*$/,hex3=/^[0-9a-fA-F]*$/;md5_hex2=/^[0-9a-fA-F]{32}$/,md5_base642=fixedBase642(22,"=="),md5_base64url2=fixedBase64url2(22),sha1_hex2=/^[0-9a-fA-F]{40}$/,sha1_base642=fixedBase642(27,"="),sha1_base64url2=fixedBase64url2(27),sha256_hex2=/^[0-9a-fA-F]{64}$/,sha256_base642=fixedBase642(43,"="),sha256_base64url2=fixedBase64url2(43),sha384_hex2=/^[0-9a-fA-F]{96}$/,sha384_base642=fixedBase642(64,""),sha384_base64url2=fixedBase64url2(64),sha512_hex2=/^[0-9a-fA-F]{128}$/,sha512_base642=fixedBase642(86,"=="),sha512_base64url2=fixedBase64url2(86)});function handleCheckPropertyResult2(result,payload,property){if(result.issues.length)payload.issues.push(...prefixIssues2(property,result.issues))}var $ZodCheck2,numericOriginMap2,$ZodCheckLessThan2,$ZodCheckGreaterThan2,$ZodCheckMultipleOf2,$ZodCheckNumberFormat2,$ZodCheckBigIntFormat2,$ZodCheckMaxSize2,$ZodCheckMinSize2,$ZodCheckSizeEquals2,$ZodCheckMaxLength2,$ZodCheckMinLength2,$ZodCheckLengthEquals2,$ZodCheckStringFormat2,$ZodCheckRegex2,$ZodCheckLowerCase2,$ZodCheckUpperCase2,$ZodCheckIncludes2,$ZodCheckStartsWith2,$ZodCheckEndsWith2,$ZodCheckProperty2,$ZodCheckMimeType2,$ZodCheckOverwrite2;var init_checks3=__esm(()=>{init_core4();init_regexes2();init_util2();$ZodCheck2=$constructor2("$ZodCheck",(inst,def)=>{var _a2;inst._zod??(inst._zod={}),inst._zod.def=def,(_a2=inst._zod).onattach??(_a2.onattach=[])}),numericOriginMap2={number:"number",bigint:"bigint",object:"date"},$ZodCheckLessThan2=$constructor2("$ZodCheckLessThan",(inst,def)=>{$ZodCheck2.init(inst,def);let origin=numericOriginMap2[typeof def.value];inst._zod.onattach.push((inst2)=>{let bag=inst2._zod.bag,curr=(def.inclusive?bag.maximum:bag.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(def.value<curr)if(def.inclusive)bag.maximum=def.value;else bag.exclusiveMaximum=def.value}),inst._zod.check=(payload)=>{if(def.inclusive?payload.value<=def.value:payload.value<def.value)return;payload.issues.push({origin,code:"too_big",maximum:def.value,input:payload.value,inclusive:def.inclusive,inst,continue:!def.abort})}}),$ZodCheckGreaterThan2=$constructor2("$ZodCheckGreaterThan",(inst,def)=>{$ZodCheck2.init(inst,def);let origin=numericOriginMap2[typeof def.value];inst._zod.onattach.push((inst2)=>{let bag=inst2._zod.bag,curr=(def.inclusive?bag.minimum:bag.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(def.value>curr)if(def.inclusive)bag.minimum=def.value;else bag.exclusiveMinimum=def.value}),inst._zod.check=(payload)=>{if(def.inclusive?payload.value>=def.value:payload.value>def.value)return;payload.issues.push({origin,code:"too_small",minimum:def.value,input:payload.value,inclusive:def.inclusive,inst,continue:!def.abort})}}),$ZodCheckMultipleOf2=$constructor2("$ZodCheckMultipleOf",(inst,def)=>{$ZodCheck2.init(inst,def),inst._zod.onattach.push((inst2)=>{var _a2;(_a2=inst2._zod.bag).multipleOf??(_a2.multipleOf=def.value)}),inst._zod.check=(payload)=>{if(typeof payload.value!==typeof def.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof payload.value==="bigint"?payload.value%def.value===BigInt(0):floatSafeRemainder2(payload.value,def.value)===0)return;payload.issues.push({origin:typeof payload.value,code:"not_multiple_of",divisor:def.value,input:payload.value,inst,continue:!def.abort})}}),$ZodCheckNumberFormat2=$constructor2("$ZodCheckNumberFormat",(inst,def)=>{$ZodCheck2.init(inst,def),def.format=def.format||"float64";let isInt=def.format?.includes("int"),origin=isInt?"int":"number",[minimum,maximum]=NUMBER_FORMAT_RANGES2[def.format];inst._zod.onattach.push((inst2)=>{let bag=inst2._zod.bag;if(bag.format=def.format,bag.minimum=minimum,bag.maximum=maximum,isInt)bag.pattern=integer2}),inst._zod.check=(payload)=>{let input=payload.value;if(isInt){if(!Number.isInteger(input)){payload.issues.push({expected:origin,format:def.format,code:"invalid_type",continue:!1,input,inst});return}if(!Number.isSafeInteger(input)){if(input>0)payload.issues.push({input,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst,origin,continue:!def.abort});else payload.issues.push({input,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst,origin,continue:!def.abort});return}}if(input<minimum)payload.issues.push({origin:"number",input,code:"too_small",minimum,inclusive:!0,inst,continue:!def.abort});if(input>maximum)payload.issues.push({origin:"number",input,code:"too_big",maximum,inst})}}),$ZodCheckBigIntFormat2=$constructor2("$ZodCheckBigIntFormat",(inst,def)=>{$ZodCheck2.init(inst,def);let[minimum,maximum]=BIGINT_FORMAT_RANGES2[def.format];inst._zod.onattach.push((inst2)=>{let bag=inst2._zod.bag;bag.format=def.format,bag.minimum=minimum,bag.maximum=maximum}),inst._zod.check=(payload)=>{let input=payload.value;if(input<minimum)payload.issues.push({origin:"bigint",input,code:"too_small",minimum,inclusive:!0,inst,continue:!def.abort});if(input>maximum)payload.issues.push({origin:"bigint",input,code:"too_big",maximum,inst})}}),$ZodCheckMaxSize2=$constructor2("$ZodCheckMaxSize",(inst,def)=>{var _a2;$ZodCheck2.init(inst,def),(_a2=inst._zod.def).when??(_a2.when=(payload)=>{let val=payload.value;return!nullish3(val)&&val.size!==void 0}),inst._zod.onattach.push((inst2)=>{let curr=inst2._zod.bag.maximum??Number.POSITIVE_INFINITY;if(def.maximum<curr)inst2._zod.bag.maximum=def.maximum}),inst._zod.check=(payload)=>{let input=payload.value;if(input.size<=def.maximum)return;payload.issues.push({origin:getSizableOrigin2(input),code:"too_big",maximum:def.maximum,inclusive:!0,input,inst,continue:!def.abort})}}),$ZodCheckMinSize2=$constructor2("$ZodCheckMinSize",(inst,def)=>{var _a2;$ZodCheck2.init(inst,def),(_a2=inst._zod.def).when??(_a2.when=(payload)=>{let val=payload.value;return!nullish3(val)&&val.size!==void 0}),inst._zod.onattach.push((inst2)=>{let curr=inst2._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(def.minimum>curr)inst2._zod.bag.minimum=def.minimum}),inst._zod.check=(payload)=>{let input=payload.value;if(input.size>=def.minimum)return;payload.issues.push({origin:getSizableOrigin2(input),code:"too_small",minimum:def.minimum,inclusive:!0,input,inst,continue:!def.abort})}}),$ZodCheckSizeEquals2=$constructor2("$ZodCheckSizeEquals",(inst,def)=>{var _a2;$ZodCheck2.init(inst,def),(_a2=inst._zod.def).when??(_a2.when=(payload)=>{let val=payload.value;return!nullish3(val)&&val.size!==void 0}),inst._zod.onattach.push((inst2)=>{let bag=inst2._zod.bag;bag.minimum=def.size,bag.maximum=def.size,bag.size=def.size}),inst._zod.check=(payload)=>{let input=payload.value,size=input.size;if(size===def.size)return;let tooBig=size>def.size;payload.issues.push({origin:getSizableOrigin2(input),...tooBig?{code:"too_big",maximum:def.size}:{code:"too_small",minimum:def.size},inclusive:!0,exact:!0,input:payload.value,inst,continue:!def.abort})}}),$ZodCheckMaxLength2=$constructor2("$ZodCheckMaxLength",(inst,def)=>{var _a2;$ZodCheck2.init(inst,def),(_a2=inst._zod.def).when??(_a2.when=(payload)=>{let val=payload.value;return!nullish3(val)&&val.length!==void 0}),inst._zod.onattach.push((inst2)=>{let curr=inst2._zod.bag.maximum??Number.POSITIVE_INFINITY;if(def.maximum<curr)inst2._zod.bag.maximum=def.maximum}),inst._zod.check=(payload)=>{let input=payload.value;if(input.length<=def.maximum)return;let origin=getLengthableOrigin2(input);payload.issues.push({origin,code:"too_big",maximum:def.maximum,inclusive:!0,input,inst,continue:!def.abort})}}),$ZodCheckMinLength2=$constructor2("$ZodCheckMinLength",(inst,def)=>{var _a2;$ZodCheck2.init(inst,def),(_a2=inst._zod.def).when??(_a2.when=(payload)=>{let val=payload.value;return!nullish3(val)&&val.length!==void 0}),inst._zod.onattach.push((inst2)=>{let curr=inst2._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(def.minimum>curr)inst2._zod.bag.minimum=def.minimum}),inst._zod.check=(payload)=>{let input=payload.value;if(input.length>=def.minimum)return;let origin=getLengthableOrigin2(input);payload.issues.push({origin,code:"too_small",minimum:def.minimum,inclusive:!0,input,inst,continue:!def.abort})}}),$ZodCheckLengthEquals2=$constructor2("$ZodCheckLengthEquals",(inst,def)=>{var _a2;$ZodCheck2.init(inst,def),(_a2=inst._zod.def).when??(_a2.when=(payload)=>{let val=payload.value;return!nullish3(val)&&val.length!==void 0}),inst._zod.onattach.push((inst2)=>{let bag=inst2._zod.bag;bag.minimum=def.length,bag.maximum=def.length,bag.length=def.length}),inst._zod.check=(payload)=>{let input=payload.value,length=input.length;if(length===def.length)return;let origin=getLengthableOrigin2(input),tooBig=length>def.length;payload.issues.push({origin,...tooBig?{code:"too_big",maximum:def.length}:{code:"too_small",minimum:def.length},inclusive:!0,exact:!0,input:payload.value,inst,continue:!def.abort})}}),$ZodCheckStringFormat2=$constructor2("$ZodCheckStringFormat",(inst,def)=>{var _a2,_b;if($ZodCheck2.init(inst,def),inst._zod.onattach.push((inst2)=>{let bag=inst2._zod.bag;if(bag.format=def.format,def.pattern)bag.patterns??(bag.patterns=new Set),bag.patterns.add(def.pattern)}),def.pattern)(_a2=inst._zod).check??(_a2.check=(payload)=>{if(def.pattern.lastIndex=0,def.pattern.test(payload.value))return;payload.issues.push({origin:"string",code:"invalid_format",format:def.format,input:payload.value,...def.pattern?{pattern:def.pattern.toString()}:{},inst,continue:!def.abort})});else(_b=inst._zod).check??(_b.check=()=>{})}),$ZodCheckRegex2=$constructor2("$ZodCheckRegex",(inst,def)=>{$ZodCheckStringFormat2.init(inst,def),inst._zod.check=(payload)=>{if(def.pattern.lastIndex=0,def.pattern.test(payload.value))return;payload.issues.push({origin:"string",code:"invalid_format",format:"regex",input:payload.value,pattern:def.pattern.toString(),inst,continue:!def.abort})}}),$ZodCheckLowerCase2=$constructor2("$ZodCheckLowerCase",(inst,def)=>{def.pattern??(def.pattern=lowercase2),$ZodCheckStringFormat2.init(inst,def)}),$ZodCheckUpperCase2=$constructor2("$ZodCheckUpperCase",(inst,def)=>{def.pattern??(def.pattern=uppercase2),$ZodCheckStringFormat2.init(inst,def)}),$ZodCheckIncludes2=$constructor2("$ZodCheckIncludes",(inst,def)=>{$ZodCheck2.init(inst,def);let escapedRegex=escapeRegex3(def.includes),pattern=new RegExp(typeof def.position==="number"?`^.{${def.position}}${escapedRegex}`:escapedRegex);def.pattern=pattern,inst._zod.onattach.push((inst2)=>{let bag=inst2._zod.bag;bag.patterns??(bag.patterns=new Set),bag.patterns.add(pattern)}),inst._zod.check=(payload)=>{if(payload.value.includes(def.includes,def.position))return;payload.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:def.includes,input:payload.value,inst,continue:!def.abort})}}),$ZodCheckStartsWith2=$constructor2("$ZodCheckStartsWith",(inst,def)=>{$ZodCheck2.init(inst,def);let pattern=new RegExp(`^${escapeRegex3(def.prefix)}.*`);def.pattern??(def.pattern=pattern),inst._zod.onattach.push((inst2)=>{let bag=inst2._zod.bag;bag.patterns??(bag.patterns=new Set),bag.patterns.add(pattern)}),inst._zod.check=(payload)=>{if(payload.value.startsWith(def.prefix))return;payload.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:def.prefix,input:payload.value,inst,continue:!def.abort})}}),$ZodCheckEndsWith2=$constructor2("$ZodCheckEndsWith",(inst,def)=>{$ZodCheck2.init(inst,def);let pattern=new RegExp(`.*${escapeRegex3(def.suffix)}$`);def.pattern??(def.pattern=pattern),inst._zod.onattach.push((inst2)=>{let bag=inst2._zod.bag;bag.patterns??(bag.patterns=new Set),bag.patterns.add(pattern)}),inst._zod.check=(payload)=>{if(payload.value.endsWith(def.suffix))return;payload.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:def.suffix,input:payload.value,inst,continue:!def.abort})}});$ZodCheckProperty2=$constructor2("$ZodCheckProperty",(inst,def)=>{$ZodCheck2.init(inst,def),inst._zod.check=(payload)=>{let result=def.schema._zod.run({value:payload.value[def.property],issues:[]},{});if(result instanceof Promise)return result.then((result2)=>handleCheckPropertyResult2(result2,payload,def.property));handleCheckPropertyResult2(result,payload,def.property);return}}),$ZodCheckMimeType2=$constructor2("$ZodCheckMimeType",(inst,def)=>{$ZodCheck2.init(inst,def);let mimeSet=new Set(def.mime);inst._zod.onattach.push((inst2)=>{inst2._zod.bag.mime=def.mime}),inst._zod.check=(payload)=>{if(mimeSet.has(payload.value.type))return;payload.issues.push({code:"invalid_value",values:def.mime,input:payload.value.type,inst,continue:!def.abort})}}),$ZodCheckOverwrite2=$constructor2("$ZodCheckOverwrite",(inst,def)=>{$ZodCheck2.init(inst,def),inst._zod.check=(payload)=>{payload.value=def.tx(payload.value)}})});class Doc2{constructor(args2=[]){if(this.content=[],this.indent=0,this)this.args=args2}indented(fn2){this.indent+=1,fn2(this),this.indent-=1}write(arg){if(typeof arg==="function"){arg(this,{execution:"sync"}),arg(this,{execution:"async"});return}let lines=arg.split(`
|
|
@@ -881,7 +881,7 @@ Use this data to avoid repeating known failure patterns.`,summaryText=summaries.
|
|
|
881
881
|
|
|
882
882
|
`)}doc2.write("payload.value = newResult;"),doc2.write("return payload;");let fn2=doc2.compile();return(payload,ctx)=>fn2(shape,payload,ctx)},fastpass,isObject3=isObject2,jit=!globalConfig2.jitless,fastEnabled=jit&&allowsEval2.value,catchall=def.catchall,value;inst._zod.parse=(payload,ctx)=>{value??(value=_normalized.value);let input=payload.value;if(!isObject3(input))return payload.issues.push({expected:"object",code:"invalid_type",input,inst}),payload;if(jit&&fastEnabled&&ctx?.async===!1&&ctx.jitless!==!0){if(!fastpass)fastpass=generateFastpass(def.shape);if(payload=fastpass(payload,ctx),!catchall)return payload;return handleCatchall2([],input,payload,ctx,value,inst)}return superParse(payload,ctx)}});$ZodUnion2=$constructor2("$ZodUnion",(inst,def)=>{$ZodType2.init(inst,def),defineLazy2(inst._zod,"optin",()=>def.options.some((o)=>o._zod.optin==="optional")?"optional":void 0),defineLazy2(inst._zod,"optout",()=>def.options.some((o)=>o._zod.optout==="optional")?"optional":void 0),defineLazy2(inst._zod,"values",()=>{if(def.options.every((o)=>o._zod.values))return new Set(def.options.flatMap((option)=>Array.from(option._zod.values)));return}),defineLazy2(inst._zod,"pattern",()=>{if(def.options.every((o)=>o._zod.pattern)){let patterns=def.options.map((o)=>o._zod.pattern);return new RegExp(`^(${patterns.map((p)=>cleanRegex2(p.source)).join("|")})$`)}return});let single=def.options.length===1,first=def.options[0]._zod.run;inst._zod.parse=(payload,ctx)=>{if(single)return first(payload,ctx);let async=!1,results=[];for(let option of def.options){let result=option._zod.run({value:payload.value,issues:[]},ctx);if(result instanceof Promise)results.push(result),async=!0;else{if(result.issues.length===0)return result;results.push(result)}}if(!async)return handleUnionResults2(results,payload,inst,ctx);return Promise.all(results).then((results2)=>{return handleUnionResults2(results2,payload,inst,ctx)})}}),$ZodDiscriminatedUnion2=$constructor2("$ZodDiscriminatedUnion",(inst,def)=>{$ZodUnion2.init(inst,def);let _super=inst._zod.parse;defineLazy2(inst._zod,"propValues",()=>{let propValues={};for(let option of def.options){let pv=option._zod.propValues;if(!pv||Object.keys(pv).length===0)throw Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`);for(let[k,v]of Object.entries(pv)){if(!propValues[k])propValues[k]=new Set;for(let val of v)propValues[k].add(val)}}return propValues});let disc=cached2(()=>{let opts=def.options,map2=new Map;for(let o of opts){let values=o._zod.propValues?.[def.discriminator];if(!values||values.size===0)throw Error(`Invalid discriminated union option at index "${def.options.indexOf(o)}"`);for(let v of values){if(map2.has(v))throw Error(`Duplicate discriminator value "${String(v)}"`);map2.set(v,o)}}return map2});inst._zod.parse=(payload,ctx)=>{let input=payload.value;if(!isObject2(input))return payload.issues.push({code:"invalid_type",expected:"object",input,inst}),payload;let opt=disc.value.get(input?.[def.discriminator]);if(opt)return opt._zod.run(payload,ctx);if(def.unionFallback)return _super(payload,ctx);return payload.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:def.discriminator,input,path:[def.discriminator],inst}),payload}}),$ZodIntersection2=$constructor2("$ZodIntersection",(inst,def)=>{$ZodType2.init(inst,def),inst._zod.parse=(payload,ctx)=>{let input=payload.value,left=def.left._zod.run({value:input,issues:[]},ctx),right=def.right._zod.run({value:input,issues:[]},ctx);if(left instanceof Promise||right instanceof Promise)return Promise.all([left,right]).then(([left2,right2])=>{return handleIntersectionResults2(payload,left2,right2)});return handleIntersectionResults2(payload,left,right)}});$ZodTuple2=$constructor2("$ZodTuple",(inst,def)=>{$ZodType2.init(inst,def);let items=def.items,optStart=items.length-[...items].reverse().findIndex((item)=>item._zod.optin!=="optional");inst._zod.parse=(payload,ctx)=>{let input=payload.value;if(!Array.isArray(input))return payload.issues.push({input,inst,expected:"tuple",code:"invalid_type"}),payload;payload.value=[];let proms=[];if(!def.rest){let tooBig=input.length>items.length,tooSmall=input.length<optStart-1;if(tooBig||tooSmall)return payload.issues.push({...tooBig?{code:"too_big",maximum:items.length}:{code:"too_small",minimum:items.length},input,inst,origin:"array"}),payload}let i=-1;for(let item of items){if(i++,i>=input.length){if(i>=optStart)continue}let result=item._zod.run({value:input[i],issues:[]},ctx);if(result instanceof Promise)proms.push(result.then((result2)=>handleTupleResult2(result2,payload,i)));else handleTupleResult2(result,payload,i)}if(def.rest){let rest=input.slice(items.length);for(let el of rest){i++;let result=def.rest._zod.run({value:el,issues:[]},ctx);if(result instanceof Promise)proms.push(result.then((result2)=>handleTupleResult2(result2,payload,i)));else handleTupleResult2(result,payload,i)}}if(proms.length)return Promise.all(proms).then(()=>payload);return payload}});$ZodRecord2=$constructor2("$ZodRecord",(inst,def)=>{$ZodType2.init(inst,def),inst._zod.parse=(payload,ctx)=>{let input=payload.value;if(!isPlainObject2(input))return payload.issues.push({expected:"record",code:"invalid_type",input,inst}),payload;let proms=[];if(def.keyType._zod.values){let values=def.keyType._zod.values;payload.value={};for(let key of values)if(typeof key==="string"||typeof key==="number"||typeof key==="symbol"){let result=def.valueType._zod.run({value:input[key],issues:[]},ctx);if(result instanceof Promise)proms.push(result.then((result2)=>{if(result2.issues.length)payload.issues.push(...prefixIssues2(key,result2.issues));payload.value[key]=result2.value}));else{if(result.issues.length)payload.issues.push(...prefixIssues2(key,result.issues));payload.value[key]=result.value}}let unrecognized;for(let key in input)if(!values.has(key))unrecognized=unrecognized??[],unrecognized.push(key);if(unrecognized&&unrecognized.length>0)payload.issues.push({code:"unrecognized_keys",input,inst,keys:unrecognized})}else{payload.value={};for(let key of Reflect.ownKeys(input)){if(key==="__proto__")continue;let keyResult=def.keyType._zod.run({value:key,issues:[]},ctx);if(keyResult instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(keyResult.issues.length){payload.issues.push({code:"invalid_key",origin:"record",issues:keyResult.issues.map((iss)=>finalizeIssue2(iss,ctx,config2())),input:key,path:[key],inst}),payload.value[keyResult.value]=keyResult.value;continue}let result=def.valueType._zod.run({value:input[key],issues:[]},ctx);if(result instanceof Promise)proms.push(result.then((result2)=>{if(result2.issues.length)payload.issues.push(...prefixIssues2(key,result2.issues));payload.value[keyResult.value]=result2.value}));else{if(result.issues.length)payload.issues.push(...prefixIssues2(key,result.issues));payload.value[keyResult.value]=result.value}}}if(proms.length)return Promise.all(proms).then(()=>payload);return payload}}),$ZodMap2=$constructor2("$ZodMap",(inst,def)=>{$ZodType2.init(inst,def),inst._zod.parse=(payload,ctx)=>{let input=payload.value;if(!(input instanceof Map))return payload.issues.push({expected:"map",code:"invalid_type",input,inst}),payload;let proms=[];payload.value=new Map;for(let[key,value]of input){let keyResult=def.keyType._zod.run({value:key,issues:[]},ctx),valueResult=def.valueType._zod.run({value,issues:[]},ctx);if(keyResult instanceof Promise||valueResult instanceof Promise)proms.push(Promise.all([keyResult,valueResult]).then(([keyResult2,valueResult2])=>{handleMapResult2(keyResult2,valueResult2,payload,key,input,inst,ctx)}));else handleMapResult2(keyResult,valueResult,payload,key,input,inst,ctx)}if(proms.length)return Promise.all(proms).then(()=>payload);return payload}});$ZodSet2=$constructor2("$ZodSet",(inst,def)=>{$ZodType2.init(inst,def),inst._zod.parse=(payload,ctx)=>{let input=payload.value;if(!(input instanceof Set))return payload.issues.push({input,inst,expected:"set",code:"invalid_type"}),payload;let proms=[];payload.value=new Set;for(let item of input){let result=def.valueType._zod.run({value:item,issues:[]},ctx);if(result instanceof Promise)proms.push(result.then((result2)=>handleSetResult2(result2,payload)));else handleSetResult2(result,payload)}if(proms.length)return Promise.all(proms).then(()=>payload);return payload}});$ZodEnum2=$constructor2("$ZodEnum",(inst,def)=>{$ZodType2.init(inst,def);let values=getEnumValues2(def.entries),valuesSet=new Set(values);inst._zod.values=valuesSet,inst._zod.pattern=new RegExp(`^(${values.filter((k)=>propertyKeyTypes2.has(typeof k)).map((o)=>typeof o==="string"?escapeRegex3(o):o.toString()).join("|")})$`),inst._zod.parse=(payload,_ctx)=>{let input=payload.value;if(valuesSet.has(input))return payload;return payload.issues.push({code:"invalid_value",values,input,inst}),payload}}),$ZodLiteral2=$constructor2("$ZodLiteral",(inst,def)=>{if($ZodType2.init(inst,def),def.values.length===0)throw Error("Cannot create literal schema with no valid values");inst._zod.values=new Set(def.values),inst._zod.pattern=new RegExp(`^(${def.values.map((o)=>typeof o==="string"?escapeRegex3(o):o?escapeRegex3(o.toString()):String(o)).join("|")})$`),inst._zod.parse=(payload,_ctx)=>{let input=payload.value;if(inst._zod.values.has(input))return payload;return payload.issues.push({code:"invalid_value",values:def.values,input,inst}),payload}}),$ZodFile2=$constructor2("$ZodFile",(inst,def)=>{$ZodType2.init(inst,def),inst._zod.parse=(payload,_ctx)=>{let input=payload.value;if(input instanceof File)return payload;return payload.issues.push({expected:"file",code:"invalid_type",input,inst}),payload}}),$ZodTransform2=$constructor2("$ZodTransform",(inst,def)=>{$ZodType2.init(inst,def),inst._zod.parse=(payload,ctx)=>{if(ctx.direction==="backward")throw new $ZodEncodeError2(inst.constructor.name);let _out=def.transform(payload.value,payload);if(ctx.async)return(_out instanceof Promise?_out:Promise.resolve(_out)).then((output2)=>{return payload.value=output2,payload});if(_out instanceof Promise)throw new $ZodAsyncError2;return payload.value=_out,payload}});$ZodOptional2=$constructor2("$ZodOptional",(inst,def)=>{$ZodType2.init(inst,def),inst._zod.optin="optional",inst._zod.optout="optional",defineLazy2(inst._zod,"values",()=>{return def.innerType._zod.values?new Set([...def.innerType._zod.values,void 0]):void 0}),defineLazy2(inst._zod,"pattern",()=>{let pattern=def.innerType._zod.pattern;return pattern?new RegExp(`^(${cleanRegex2(pattern.source)})?$`):void 0}),inst._zod.parse=(payload,ctx)=>{if(def.innerType._zod.optin==="optional"){let result=def.innerType._zod.run(payload,ctx);if(result instanceof Promise)return result.then((r)=>handleOptionalResult2(r,payload.value));return handleOptionalResult2(result,payload.value)}if(payload.value===void 0)return payload;return def.innerType._zod.run(payload,ctx)}}),$ZodNullable2=$constructor2("$ZodNullable",(inst,def)=>{$ZodType2.init(inst,def),defineLazy2(inst._zod,"optin",()=>def.innerType._zod.optin),defineLazy2(inst._zod,"optout",()=>def.innerType._zod.optout),defineLazy2(inst._zod,"pattern",()=>{let pattern=def.innerType._zod.pattern;return pattern?new RegExp(`^(${cleanRegex2(pattern.source)}|null)$`):void 0}),defineLazy2(inst._zod,"values",()=>{return def.innerType._zod.values?new Set([...def.innerType._zod.values,null]):void 0}),inst._zod.parse=(payload,ctx)=>{if(payload.value===null)return payload;return def.innerType._zod.run(payload,ctx)}}),$ZodDefault2=$constructor2("$ZodDefault",(inst,def)=>{$ZodType2.init(inst,def),inst._zod.optin="optional",defineLazy2(inst._zod,"values",()=>def.innerType._zod.values),inst._zod.parse=(payload,ctx)=>{if(ctx.direction==="backward")return def.innerType._zod.run(payload,ctx);if(payload.value===void 0)return payload.value=def.defaultValue,payload;let result=def.innerType._zod.run(payload,ctx);if(result instanceof Promise)return result.then((result2)=>handleDefaultResult2(result2,def));return handleDefaultResult2(result,def)}});$ZodPrefault2=$constructor2("$ZodPrefault",(inst,def)=>{$ZodType2.init(inst,def),inst._zod.optin="optional",defineLazy2(inst._zod,"values",()=>def.innerType._zod.values),inst._zod.parse=(payload,ctx)=>{if(ctx.direction==="backward")return def.innerType._zod.run(payload,ctx);if(payload.value===void 0)payload.value=def.defaultValue;return def.innerType._zod.run(payload,ctx)}}),$ZodNonOptional2=$constructor2("$ZodNonOptional",(inst,def)=>{$ZodType2.init(inst,def),defineLazy2(inst._zod,"values",()=>{let v=def.innerType._zod.values;return v?new Set([...v].filter((x)=>x!==void 0)):void 0}),inst._zod.parse=(payload,ctx)=>{let result=def.innerType._zod.run(payload,ctx);if(result instanceof Promise)return result.then((result2)=>handleNonOptionalResult2(result2,inst));return handleNonOptionalResult2(result,inst)}});$ZodSuccess2=$constructor2("$ZodSuccess",(inst,def)=>{$ZodType2.init(inst,def),inst._zod.parse=(payload,ctx)=>{if(ctx.direction==="backward")throw new $ZodEncodeError2("ZodSuccess");let result=def.innerType._zod.run(payload,ctx);if(result instanceof Promise)return result.then((result2)=>{return payload.value=result2.issues.length===0,payload});return payload.value=result.issues.length===0,payload}}),$ZodCatch2=$constructor2("$ZodCatch",(inst,def)=>{$ZodType2.init(inst,def),defineLazy2(inst._zod,"optin",()=>def.innerType._zod.optin),defineLazy2(inst._zod,"optout",()=>def.innerType._zod.optout),defineLazy2(inst._zod,"values",()=>def.innerType._zod.values),inst._zod.parse=(payload,ctx)=>{if(ctx.direction==="backward")return def.innerType._zod.run(payload,ctx);let result=def.innerType._zod.run(payload,ctx);if(result instanceof Promise)return result.then((result2)=>{if(payload.value=result2.value,result2.issues.length)payload.value=def.catchValue({...payload,error:{issues:result2.issues.map((iss)=>finalizeIssue2(iss,ctx,config2()))},input:payload.value}),payload.issues=[];return payload});if(payload.value=result.value,result.issues.length)payload.value=def.catchValue({...payload,error:{issues:result.issues.map((iss)=>finalizeIssue2(iss,ctx,config2()))},input:payload.value}),payload.issues=[];return payload}}),$ZodNaN2=$constructor2("$ZodNaN",(inst,def)=>{$ZodType2.init(inst,def),inst._zod.parse=(payload,_ctx)=>{if(typeof payload.value!=="number"||!Number.isNaN(payload.value))return payload.issues.push({input:payload.value,inst,expected:"nan",code:"invalid_type"}),payload;return payload}}),$ZodPipe2=$constructor2("$ZodPipe",(inst,def)=>{$ZodType2.init(inst,def),defineLazy2(inst._zod,"values",()=>def.in._zod.values),defineLazy2(inst._zod,"optin",()=>def.in._zod.optin),defineLazy2(inst._zod,"optout",()=>def.out._zod.optout),defineLazy2(inst._zod,"propValues",()=>def.in._zod.propValues),inst._zod.parse=(payload,ctx)=>{if(ctx.direction==="backward"){let right=def.out._zod.run(payload,ctx);if(right instanceof Promise)return right.then((right2)=>handlePipeResult2(right2,def.in,ctx));return handlePipeResult2(right,def.in,ctx)}let left=def.in._zod.run(payload,ctx);if(left instanceof Promise)return left.then((left2)=>handlePipeResult2(left2,def.out,ctx));return handlePipeResult2(left,def.out,ctx)}});$ZodCodec2=$constructor2("$ZodCodec",(inst,def)=>{$ZodType2.init(inst,def),defineLazy2(inst._zod,"values",()=>def.in._zod.values),defineLazy2(inst._zod,"optin",()=>def.in._zod.optin),defineLazy2(inst._zod,"optout",()=>def.out._zod.optout),defineLazy2(inst._zod,"propValues",()=>def.in._zod.propValues),inst._zod.parse=(payload,ctx)=>{if((ctx.direction||"forward")==="forward"){let left=def.in._zod.run(payload,ctx);if(left instanceof Promise)return left.then((left2)=>handleCodecAResult2(left2,def,ctx));return handleCodecAResult2(left,def,ctx)}else{let right=def.out._zod.run(payload,ctx);if(right instanceof Promise)return right.then((right2)=>handleCodecAResult2(right2,def,ctx));return handleCodecAResult2(right,def,ctx)}}});$ZodReadonly2=$constructor2("$ZodReadonly",(inst,def)=>{$ZodType2.init(inst,def),defineLazy2(inst._zod,"propValues",()=>def.innerType._zod.propValues),defineLazy2(inst._zod,"values",()=>def.innerType._zod.values),defineLazy2(inst._zod,"optin",()=>def.innerType._zod.optin),defineLazy2(inst._zod,"optout",()=>def.innerType._zod.optout),inst._zod.parse=(payload,ctx)=>{if(ctx.direction==="backward")return def.innerType._zod.run(payload,ctx);let result=def.innerType._zod.run(payload,ctx);if(result instanceof Promise)return result.then(handleReadonlyResult2);return handleReadonlyResult2(result)}});$ZodTemplateLiteral2=$constructor2("$ZodTemplateLiteral",(inst,def)=>{$ZodType2.init(inst,def);let regexParts=[];for(let part of def.parts)if(typeof part==="object"&&part!==null){if(!part._zod.pattern)throw Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`);let source=part._zod.pattern instanceof RegExp?part._zod.pattern.source:part._zod.pattern;if(!source)throw Error(`Invalid template literal part: ${part._zod.traits}`);let start=source.startsWith("^")?1:0,end=source.endsWith("$")?source.length-1:source.length;regexParts.push(source.slice(start,end))}else if(part===null||primitiveTypes2.has(typeof part))regexParts.push(escapeRegex3(`${part}`));else throw Error(`Invalid template literal part: ${part}`);inst._zod.pattern=new RegExp(`^${regexParts.join("")}$`),inst._zod.parse=(payload,_ctx)=>{if(typeof payload.value!=="string")return payload.issues.push({input:payload.value,inst,expected:"template_literal",code:"invalid_type"}),payload;if(inst._zod.pattern.lastIndex=0,!inst._zod.pattern.test(payload.value))return payload.issues.push({input:payload.value,inst,code:"invalid_format",format:def.format??"template_literal",pattern:inst._zod.pattern.source}),payload;return payload}}),$ZodFunction2=$constructor2("$ZodFunction",(inst,def)=>{return $ZodType2.init(inst,def),inst._def=def,inst._zod.def=def,inst.implement=(func)=>{if(typeof func!=="function")throw Error("implement() must be called with a function");return function(...args2){let parsedArgs=inst._def.input?parse5(inst._def.input,args2):args2,result=Reflect.apply(func,this,parsedArgs);if(inst._def.output)return parse5(inst._def.output,result);return result}},inst.implementAsync=(func)=>{if(typeof func!=="function")throw Error("implementAsync() must be called with a function");return async function(...args2){let parsedArgs=inst._def.input?await parseAsync3(inst._def.input,args2):args2,result=await Reflect.apply(func,this,parsedArgs);if(inst._def.output)return await parseAsync3(inst._def.output,result);return result}},inst._zod.parse=(payload,_ctx)=>{if(typeof payload.value!=="function")return payload.issues.push({code:"invalid_type",expected:"function",input:payload.value,inst}),payload;if(inst._def.output&&inst._def.output._zod.def.type==="promise")payload.value=inst.implementAsync(payload.value);else payload.value=inst.implement(payload.value);return payload},inst.input=(...args2)=>{let F=inst.constructor;if(Array.isArray(args2[0]))return new F({type:"function",input:new $ZodTuple2({type:"tuple",items:args2[0],rest:args2[1]}),output:inst._def.output});return new F({type:"function",input:args2[0],output:inst._def.output})},inst.output=(output)=>{return new inst.constructor({type:"function",input:inst._def.input,output})},inst}),$ZodPromise2=$constructor2("$ZodPromise",(inst,def)=>{$ZodType2.init(inst,def),inst._zod.parse=(payload,ctx)=>{return Promise.resolve(payload.value).then((inner)=>def.innerType._zod.run({value:inner,issues:[]},ctx))}}),$ZodLazy2=$constructor2("$ZodLazy",(inst,def)=>{$ZodType2.init(inst,def),defineLazy2(inst._zod,"innerType",()=>def.getter()),defineLazy2(inst._zod,"pattern",()=>inst._zod.innerType._zod.pattern),defineLazy2(inst._zod,"propValues",()=>inst._zod.innerType._zod.propValues),defineLazy2(inst._zod,"optin",()=>inst._zod.innerType._zod.optin??void 0),defineLazy2(inst._zod,"optout",()=>inst._zod.innerType._zod.optout??void 0),inst._zod.parse=(payload,ctx)=>{return inst._zod.innerType._zod.run(payload,ctx)}}),$ZodCustom2=$constructor2("$ZodCustom",(inst,def)=>{$ZodCheck2.init(inst,def),$ZodType2.init(inst,def),inst._zod.parse=(payload,_)=>{return payload},inst._zod.check=(payload)=>{let input=payload.value,r=def.fn(input);if(r instanceof Promise)return r.then((r2)=>handleRefineResult2(r2,payload,input,inst));handleRefineResult2(r,payload,input,inst);return}})});function ar_default2(){return{localeError:error49()}}var error49=()=>{let Sizable={string:{unit:"حرف",verb:"أن يحوي"},file:{unit:"بايت",verb:"أن يحوي"},array:{unit:"عنصر",verb:"أن يحوي"},set:{unit:"عنصر",verb:"أن يحوي"}};function getSizing(origin){return Sizable[origin]??null}let parsedType2=(data)=>{let t=typeof data;switch(t){case"number":return Number.isNaN(data)?"NaN":"number";case"object":{if(Array.isArray(data))return"array";if(data===null)return"null";if(Object.getPrototypeOf(data)!==Object.prototype&&data.constructor)return data.constructor.name}}return t},Nouns={regex:"مدخل",email:"بريد إلكتروني",url:"رابط",emoji:"إيموجي",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"تاريخ ووقت بمعيار ISO",date:"تاريخ بمعيار ISO",time:"وقت بمعيار ISO",duration:"مدة بمعيار ISO",ipv4:"عنوان IPv4",ipv6:"عنوان IPv6",cidrv4:"مدى عناوين بصيغة IPv4",cidrv6:"مدى عناوين بصيغة IPv6",base64:"نَص بترميز base64-encoded",base64url:"نَص بترميز base64url-encoded",json_string:"نَص على هيئة JSON",e164:"رقم هاتف بمعيار E.164",jwt:"JWT",template_literal:"مدخل"};return(issue3)=>{switch(issue3.code){case"invalid_type":return`مدخلات غير مقبولة: يفترض إدخال ${issue3.expected}، ولكن تم إدخال ${parsedType2(issue3.input)}`;case"invalid_value":if(issue3.values.length===1)return`مدخلات غير مقبولة: يفترض إدخال ${stringifyPrimitive2(issue3.values[0])}`;return`اختيار غير مقبول: يتوقع انتقاء أحد هذه الخيارات: ${joinValues2(issue3.values,"|")}`;case"too_big":{let adj=issue3.inclusive?"<=":"<",sizing=getSizing(issue3.origin);if(sizing)return` أكبر من اللازم: يفترض أن تكون ${issue3.origin??"القيمة"} ${adj} ${issue3.maximum.toString()} ${sizing.unit??"عنصر"}`;return`أكبر من اللازم: يفترض أن تكون ${issue3.origin??"القيمة"} ${adj} ${issue3.maximum.toString()}`}case"too_small":{let adj=issue3.inclusive?">=":">",sizing=getSizing(issue3.origin);if(sizing)return`أصغر من اللازم: يفترض لـ ${issue3.origin} أن يكون ${adj} ${issue3.minimum.toString()} ${sizing.unit}`;return`أصغر من اللازم: يفترض لـ ${issue3.origin} أن يكون ${adj} ${issue3.minimum.toString()}`}case"invalid_format":{let _issue=issue3;if(_issue.format==="starts_with")return`نَص غير مقبول: يجب أن يبدأ بـ "${issue3.prefix}"`;if(_issue.format==="ends_with")return`نَص غير مقبول: يجب أن ينتهي بـ "${_issue.suffix}"`;if(_issue.format==="includes")return`نَص غير مقبول: يجب أن يتضمَّن "${_issue.includes}"`;if(_issue.format==="regex")return`نَص غير مقبول: يجب أن يطابق النمط ${_issue.pattern}`;return`${Nouns[_issue.format]??issue3.format} غير مقبول`}case"not_multiple_of":return`رقم غير مقبول: يجب أن يكون من مضاعفات ${issue3.divisor}`;case"unrecognized_keys":return`معرف${issue3.keys.length>1?"ات":""} غريب${issue3.keys.length>1?"ة":""}: ${joinValues2(issue3.keys,"، ")}`;case"invalid_key":return`معرف غير مقبول في ${issue3.origin}`;case"invalid_union":return"مدخل غير مقبول";case"invalid_element":return`مدخل غير مقبول في ${issue3.origin}`;default:return"مدخل غير مقبول"}}};var init_ar2=__esm(()=>{init_util2()});function az_default2(){return{localeError:error50()}}var error50=()=>{let Sizable={string:{unit:"simvol",verb:"olmalıdır"},file:{unit:"bayt",verb:"olmalıdır"},array:{unit:"element",verb:"olmalıdır"},set:{unit:"element",verb:"olmalıdır"}};function getSizing(origin){return Sizable[origin]??null}let parsedType2=(data)=>{let t=typeof data;switch(t){case"number":return Number.isNaN(data)?"NaN":"number";case"object":{if(Array.isArray(data))return"array";if(data===null)return"null";if(Object.getPrototypeOf(data)!==Object.prototype&&data.constructor)return data.constructor.name}}return t},Nouns={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return(issue3)=>{switch(issue3.code){case"invalid_type":return`Yanlış dəyər: gözlənilən ${issue3.expected}, daxil olan ${parsedType2(issue3.input)}`;case"invalid_value":if(issue3.values.length===1)return`Yanlış dəyər: gözlənilən ${stringifyPrimitive2(issue3.values[0])}`;return`Yanlış seçim: aşağıdakılardan biri olmalıdır: ${joinValues2(issue3.values,"|")}`;case"too_big":{let adj=issue3.inclusive?"<=":"<",sizing=getSizing(issue3.origin);if(sizing)return`Çox böyük: gözlənilən ${issue3.origin??"dəyər"} ${adj}${issue3.maximum.toString()} ${sizing.unit??"element"}`;return`Çox böyük: gözlənilən ${issue3.origin??"dəyər"} ${adj}${issue3.maximum.toString()}`}case"too_small":{let adj=issue3.inclusive?">=":">",sizing=getSizing(issue3.origin);if(sizing)return`Çox kiçik: gözlənilən ${issue3.origin} ${adj}${issue3.minimum.toString()} ${sizing.unit}`;return`Çox kiçik: gözlənilən ${issue3.origin} ${adj}${issue3.minimum.toString()}`}case"invalid_format":{let _issue=issue3;if(_issue.format==="starts_with")return`Yanlış mətn: "${_issue.prefix}" ilə başlamalıdır`;if(_issue.format==="ends_with")return`Yanlış mətn: "${_issue.suffix}" ilə bitməlidir`;if(_issue.format==="includes")return`Yanlış mətn: "${_issue.includes}" daxil olmalıdır`;if(_issue.format==="regex")return`Yanlış mətn: ${_issue.pattern} şablonuna uyğun olmalıdır`;return`Yanlış ${Nouns[_issue.format]??issue3.format}`}case"not_multiple_of":return`Yanlış ədəd: ${issue3.divisor} ilə bölünə bilən olmalıdır`;case"unrecognized_keys":return`Tanınmayan açar${issue3.keys.length>1?"lar":""}: ${joinValues2(issue3.keys,", ")}`;case"invalid_key":return`${issue3.origin} daxilində yanlış açar`;case"invalid_union":return"Yanlış dəyər";case"invalid_element":return`${issue3.origin} daxilində yanlış dəyər`;default:return"Yanlış dəyər"}}};var init_az2=__esm(()=>{init_util2()});function getBelarusianPlural2(count2,one,few,many){let absCount=Math.abs(count2),lastDigit=absCount%10,lastTwoDigits=absCount%100;if(lastTwoDigits>=11&&lastTwoDigits<=19)return many;if(lastDigit===1)return one;if(lastDigit>=2&&lastDigit<=4)return few;return many}function be_default2(){return{localeError:error51()}}var error51=()=>{let Sizable={string:{unit:{one:"сімвал",few:"сімвалы",many:"сімвалаў"},verb:"мець"},array:{unit:{one:"элемент",few:"элементы",many:"элементаў"},verb:"мець"},set:{unit:{one:"элемент",few:"элементы",many:"элементаў"},verb:"мець"},file:{unit:{one:"байт",few:"байты",many:"байтаў"},verb:"мець"}};function getSizing(origin){return Sizable[origin]??null}let parsedType2=(data)=>{let t=typeof data;switch(t){case"number":return Number.isNaN(data)?"NaN":"лік";case"object":{if(Array.isArray(data))return"масіў";if(data===null)return"null";if(Object.getPrototypeOf(data)!==Object.prototype&&data.constructor)return data.constructor.name}}return t},Nouns={regex:"увод",email:"email адрас",url:"URL",emoji:"эмодзі",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO дата і час",date:"ISO дата",time:"ISO час",duration:"ISO працягласць",ipv4:"IPv4 адрас",ipv6:"IPv6 адрас",cidrv4:"IPv4 дыяпазон",cidrv6:"IPv6 дыяпазон",base64:"радок у фармаце base64",base64url:"радок у фармаце base64url",json_string:"JSON радок",e164:"нумар E.164",jwt:"JWT",template_literal:"увод"};return(issue3)=>{switch(issue3.code){case"invalid_type":return`Няправільны ўвод: чакаўся ${issue3.expected}, атрымана ${parsedType2(issue3.input)}`;case"invalid_value":if(issue3.values.length===1)return`Няправільны ўвод: чакалася ${stringifyPrimitive2(issue3.values[0])}`;return`Няправільны варыянт: чакаўся адзін з ${joinValues2(issue3.values,"|")}`;case"too_big":{let adj=issue3.inclusive?"<=":"<",sizing=getSizing(issue3.origin);if(sizing){let maxValue=Number(issue3.maximum),unit=getBelarusianPlural2(maxValue,sizing.unit.one,sizing.unit.few,sizing.unit.many);return`Занадта вялікі: чакалася, што ${issue3.origin??"значэнне"} павінна ${sizing.verb} ${adj}${issue3.maximum.toString()} ${unit}`}return`Занадта вялікі: чакалася, што ${issue3.origin??"значэнне"} павінна быць ${adj}${issue3.maximum.toString()}`}case"too_small":{let adj=issue3.inclusive?">=":">",sizing=getSizing(issue3.origin);if(sizing){let minValue=Number(issue3.minimum),unit=getBelarusianPlural2(minValue,sizing.unit.one,sizing.unit.few,sizing.unit.many);return`Занадта малы: чакалася, што ${issue3.origin} павінна ${sizing.verb} ${adj}${issue3.minimum.toString()} ${unit}`}return`Занадта малы: чакалася, што ${issue3.origin} павінна быць ${adj}${issue3.minimum.toString()}`}case"invalid_format":{let _issue=issue3;if(_issue.format==="starts_with")return`Няправільны радок: павінен пачынацца з "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Няправільны радок: павінен заканчвацца на "${_issue.suffix}"`;if(_issue.format==="includes")return`Няправільны радок: павінен змяшчаць "${_issue.includes}"`;if(_issue.format==="regex")return`Няправільны радок: павінен адпавядаць шаблону ${_issue.pattern}`;return`Няправільны ${Nouns[_issue.format]??issue3.format}`}case"not_multiple_of":return`Няправільны лік: павінен быць кратным ${issue3.divisor}`;case"unrecognized_keys":return`Нераспазнаны ${issue3.keys.length>1?"ключы":"ключ"}: ${joinValues2(issue3.keys,", ")}`;case"invalid_key":return`Няправільны ключ у ${issue3.origin}`;case"invalid_union":return"Няправільны ўвод";case"invalid_element":return`Няправільнае значэнне ў ${issue3.origin}`;default:return"Няправільны ўвод"}}};var init_be2=__esm(()=>{init_util2()});function ca_default2(){return{localeError:error52()}}var error52=()=>{let Sizable={string:{unit:"caràcters",verb:"contenir"},file:{unit:"bytes",verb:"contenir"},array:{unit:"elements",verb:"contenir"},set:{unit:"elements",verb:"contenir"}};function getSizing(origin){return Sizable[origin]??null}let parsedType2=(data)=>{let t=typeof data;switch(t){case"number":return Number.isNaN(data)?"NaN":"number";case"object":{if(Array.isArray(data))return"array";if(data===null)return"null";if(Object.getPrototypeOf(data)!==Object.prototype&&data.constructor)return data.constructor.name}}return t},Nouns={regex:"entrada",email:"adreça electrònica",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data i hora ISO",date:"data ISO",time:"hora ISO",duration:"durada ISO",ipv4:"adreça IPv4",ipv6:"adreça IPv6",cidrv4:"rang IPv4",cidrv6:"rang IPv6",base64:"cadena codificada en base64",base64url:"cadena codificada en base64url",json_string:"cadena JSON",e164:"número E.164",jwt:"JWT",template_literal:"entrada"};return(issue3)=>{switch(issue3.code){case"invalid_type":return`Tipus invàlid: s'esperava ${issue3.expected}, s'ha rebut ${parsedType2(issue3.input)}`;case"invalid_value":if(issue3.values.length===1)return`Valor invàlid: s'esperava ${stringifyPrimitive2(issue3.values[0])}`;return`Opció invàlida: s'esperava una de ${joinValues2(issue3.values," o ")}`;case"too_big":{let adj=issue3.inclusive?"com a màxim":"menys de",sizing=getSizing(issue3.origin);if(sizing)return`Massa gran: s'esperava que ${issue3.origin??"el valor"} contingués ${adj} ${issue3.maximum.toString()} ${sizing.unit??"elements"}`;return`Massa gran: s'esperava que ${issue3.origin??"el valor"} fos ${adj} ${issue3.maximum.toString()}`}case"too_small":{let adj=issue3.inclusive?"com a mínim":"més de",sizing=getSizing(issue3.origin);if(sizing)return`Massa petit: s'esperava que ${issue3.origin} contingués ${adj} ${issue3.minimum.toString()} ${sizing.unit}`;return`Massa petit: s'esperava que ${issue3.origin} fos ${adj} ${issue3.minimum.toString()}`}case"invalid_format":{let _issue=issue3;if(_issue.format==="starts_with")return`Format invàlid: ha de començar amb "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Format invàlid: ha d'acabar amb "${_issue.suffix}"`;if(_issue.format==="includes")return`Format invàlid: ha d'incloure "${_issue.includes}"`;if(_issue.format==="regex")return`Format invàlid: ha de coincidir amb el patró ${_issue.pattern}`;return`Format invàlid per a ${Nouns[_issue.format]??issue3.format}`}case"not_multiple_of":return`Número invàlid: ha de ser múltiple de ${issue3.divisor}`;case"unrecognized_keys":return`Clau${issue3.keys.length>1?"s":""} no reconeguda${issue3.keys.length>1?"s":""}: ${joinValues2(issue3.keys,", ")}`;case"invalid_key":return`Clau invàlida a ${issue3.origin}`;case"invalid_union":return"Entrada invàlida";case"invalid_element":return`Element invàlid a ${issue3.origin}`;default:return"Entrada invàlida"}}};var init_ca2=__esm(()=>{init_util2()});function cs_default2(){return{localeError:error53()}}var error53=()=>{let Sizable={string:{unit:"znaků",verb:"mít"},file:{unit:"bajtů",verb:"mít"},array:{unit:"prvků",verb:"mít"},set:{unit:"prvků",verb:"mít"}};function getSizing(origin){return Sizable[origin]??null}let parsedType2=(data)=>{let t=typeof data;switch(t){case"number":return Number.isNaN(data)?"NaN":"číslo";case"string":return"řetězec";case"boolean":return"boolean";case"bigint":return"bigint";case"function":return"funkce";case"symbol":return"symbol";case"undefined":return"undefined";case"object":{if(Array.isArray(data))return"pole";if(data===null)return"null";if(Object.getPrototypeOf(data)!==Object.prototype&&data.constructor)return data.constructor.name}}return t},Nouns={regex:"regulární výraz",email:"e-mailová adresa",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"datum a čas ve formátu ISO",date:"datum ve formátu ISO",time:"čas ve formátu ISO",duration:"doba trvání ISO",ipv4:"IPv4 adresa",ipv6:"IPv6 adresa",cidrv4:"rozsah IPv4",cidrv6:"rozsah IPv6",base64:"řetězec zakódovaný ve formátu base64",base64url:"řetězec zakódovaný ve formátu base64url",json_string:"řetězec ve formátu JSON",e164:"číslo E.164",jwt:"JWT",template_literal:"vstup"};return(issue3)=>{switch(issue3.code){case"invalid_type":return`Neplatný vstup: očekáváno ${issue3.expected}, obdrženo ${parsedType2(issue3.input)}`;case"invalid_value":if(issue3.values.length===1)return`Neplatný vstup: očekáváno ${stringifyPrimitive2(issue3.values[0])}`;return`Neplatná možnost: očekávána jedna z hodnot ${joinValues2(issue3.values,"|")}`;case"too_big":{let adj=issue3.inclusive?"<=":"<",sizing=getSizing(issue3.origin);if(sizing)return`Hodnota je příliš velká: ${issue3.origin??"hodnota"} musí mít ${adj}${issue3.maximum.toString()} ${sizing.unit??"prvků"}`;return`Hodnota je příliš velká: ${issue3.origin??"hodnota"} musí být ${adj}${issue3.maximum.toString()}`}case"too_small":{let adj=issue3.inclusive?">=":">",sizing=getSizing(issue3.origin);if(sizing)return`Hodnota je příliš malá: ${issue3.origin??"hodnota"} musí mít ${adj}${issue3.minimum.toString()} ${sizing.unit??"prvků"}`;return`Hodnota je příliš malá: ${issue3.origin??"hodnota"} musí být ${adj}${issue3.minimum.toString()}`}case"invalid_format":{let _issue=issue3;if(_issue.format==="starts_with")return`Neplatný řetězec: musí začínat na "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Neplatný řetězec: musí končit na "${_issue.suffix}"`;if(_issue.format==="includes")return`Neplatný řetězec: musí obsahovat "${_issue.includes}"`;if(_issue.format==="regex")return`Neplatný řetězec: musí odpovídat vzoru ${_issue.pattern}`;return`Neplatný formát ${Nouns[_issue.format]??issue3.format}`}case"not_multiple_of":return`Neplatné číslo: musí být násobkem ${issue3.divisor}`;case"unrecognized_keys":return`Neznámé klíče: ${joinValues2(issue3.keys,", ")}`;case"invalid_key":return`Neplatný klíč v ${issue3.origin}`;case"invalid_union":return"Neplatný vstup";case"invalid_element":return`Neplatná hodnota v ${issue3.origin}`;default:return"Neplatný vstup"}}};var init_cs2=__esm(()=>{init_util2()});function da_default2(){return{localeError:error54()}}var error54=()=>{let Sizable={string:{unit:"tegn",verb:"havde"},file:{unit:"bytes",verb:"havde"},array:{unit:"elementer",verb:"indeholdt"},set:{unit:"elementer",verb:"indeholdt"}},TypeNames={string:"streng",number:"tal",boolean:"boolean",array:"liste",object:"objekt",set:"sæt",file:"fil"};function getSizing(origin){return Sizable[origin]??null}function getTypeName(type){return TypeNames[type]??type}let parsedType2=(data)=>{let t=typeof data;switch(t){case"number":return Number.isNaN(data)?"NaN":"tal";case"object":{if(Array.isArray(data))return"liste";if(data===null)return"null";if(Object.getPrototypeOf(data)!==Object.prototype&&data.constructor)return data.constructor.name;return"objekt"}}return t},Nouns={regex:"input",email:"e-mailadresse",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dato- og klokkeslæt",date:"ISO-dato",time:"ISO-klokkeslæt",duration:"ISO-varighed",ipv4:"IPv4-område",ipv6:"IPv6-område",cidrv4:"IPv4-spektrum",cidrv6:"IPv6-spektrum",base64:"base64-kodet streng",base64url:"base64url-kodet streng",json_string:"JSON-streng",e164:"E.164-nummer",jwt:"JWT",template_literal:"input"};return(issue3)=>{switch(issue3.code){case"invalid_type":return`Ugyldigt input: forventede ${getTypeName(issue3.expected)}, fik ${getTypeName(parsedType2(issue3.input))}`;case"invalid_value":if(issue3.values.length===1)return`Ugyldig værdi: forventede ${stringifyPrimitive2(issue3.values[0])}`;return`Ugyldigt valg: forventede en af følgende ${joinValues2(issue3.values,"|")}`;case"too_big":{let adj=issue3.inclusive?"<=":"<",sizing=getSizing(issue3.origin),origin=getTypeName(issue3.origin);if(sizing)return`For stor: forventede ${origin??"value"} ${sizing.verb} ${adj} ${issue3.maximum.toString()} ${sizing.unit??"elementer"}`;return`For stor: forventede ${origin??"value"} havde ${adj} ${issue3.maximum.toString()}`}case"too_small":{let adj=issue3.inclusive?">=":">",sizing=getSizing(issue3.origin),origin=getTypeName(issue3.origin);if(sizing)return`For lille: forventede ${origin} ${sizing.verb} ${adj} ${issue3.minimum.toString()} ${sizing.unit}`;return`For lille: forventede ${origin} havde ${adj} ${issue3.minimum.toString()}`}case"invalid_format":{let _issue=issue3;if(_issue.format==="starts_with")return`Ugyldig streng: skal starte med "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Ugyldig streng: skal ende med "${_issue.suffix}"`;if(_issue.format==="includes")return`Ugyldig streng: skal indeholde "${_issue.includes}"`;if(_issue.format==="regex")return`Ugyldig streng: skal matche mønsteret ${_issue.pattern}`;return`Ugyldig ${Nouns[_issue.format]??issue3.format}`}case"not_multiple_of":return`Ugyldigt tal: skal være deleligt med ${issue3.divisor}`;case"unrecognized_keys":return`${issue3.keys.length>1?"Ukendte nøgler":"Ukendt nøgle"}: ${joinValues2(issue3.keys,", ")}`;case"invalid_key":return`Ugyldig nøgle i ${issue3.origin}`;case"invalid_union":return"Ugyldigt input: matcher ingen af de tilladte typer";case"invalid_element":return`Ugyldig værdi i ${issue3.origin}`;default:return"Ugyldigt input"}}};var init_da2=__esm(()=>{init_util2()});function de_default2(){return{localeError:error55()}}var error55=()=>{let Sizable={string:{unit:"Zeichen",verb:"zu haben"},file:{unit:"Bytes",verb:"zu haben"},array:{unit:"Elemente",verb:"zu haben"},set:{unit:"Elemente",verb:"zu haben"}};function getSizing(origin){return Sizable[origin]??null}let parsedType2=(data)=>{let t=typeof data;switch(t){case"number":return Number.isNaN(data)?"NaN":"Zahl";case"object":{if(Array.isArray(data))return"Array";if(data===null)return"null";if(Object.getPrototypeOf(data)!==Object.prototype&&data.constructor)return data.constructor.name}}return t},Nouns={regex:"Eingabe",email:"E-Mail-Adresse",url:"URL",emoji:"Emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-Datum und -Uhrzeit",date:"ISO-Datum",time:"ISO-Uhrzeit",duration:"ISO-Dauer",ipv4:"IPv4-Adresse",ipv6:"IPv6-Adresse",cidrv4:"IPv4-Bereich",cidrv6:"IPv6-Bereich",base64:"Base64-codierter String",base64url:"Base64-URL-codierter String",json_string:"JSON-String",e164:"E.164-Nummer",jwt:"JWT",template_literal:"Eingabe"};return(issue3)=>{switch(issue3.code){case"invalid_type":return`Ungültige Eingabe: erwartet ${issue3.expected}, erhalten ${parsedType2(issue3.input)}`;case"invalid_value":if(issue3.values.length===1)return`Ungültige Eingabe: erwartet ${stringifyPrimitive2(issue3.values[0])}`;return`Ungültige Option: erwartet eine von ${joinValues2(issue3.values,"|")}`;case"too_big":{let adj=issue3.inclusive?"<=":"<",sizing=getSizing(issue3.origin);if(sizing)return`Zu groß: erwartet, dass ${issue3.origin??"Wert"} ${adj}${issue3.maximum.toString()} ${sizing.unit??"Elemente"} hat`;return`Zu groß: erwartet, dass ${issue3.origin??"Wert"} ${adj}${issue3.maximum.toString()} ist`}case"too_small":{let adj=issue3.inclusive?">=":">",sizing=getSizing(issue3.origin);if(sizing)return`Zu klein: erwartet, dass ${issue3.origin} ${adj}${issue3.minimum.toString()} ${sizing.unit} hat`;return`Zu klein: erwartet, dass ${issue3.origin} ${adj}${issue3.minimum.toString()} ist`}case"invalid_format":{let _issue=issue3;if(_issue.format==="starts_with")return`Ungültiger String: muss mit "${_issue.prefix}" beginnen`;if(_issue.format==="ends_with")return`Ungültiger String: muss mit "${_issue.suffix}" enden`;if(_issue.format==="includes")return`Ungültiger String: muss "${_issue.includes}" enthalten`;if(_issue.format==="regex")return`Ungültiger String: muss dem Muster ${_issue.pattern} entsprechen`;return`Ungültig: ${Nouns[_issue.format]??issue3.format}`}case"not_multiple_of":return`Ungültige Zahl: muss ein Vielfaches von ${issue3.divisor} sein`;case"unrecognized_keys":return`${issue3.keys.length>1?"Unbekannte Schlüssel":"Unbekannter Schlüssel"}: ${joinValues2(issue3.keys,", ")}`;case"invalid_key":return`Ungültiger Schlüssel in ${issue3.origin}`;case"invalid_union":return"Ungültige Eingabe";case"invalid_element":return`Ungültiger Wert in ${issue3.origin}`;default:return"Ungültige Eingabe"}}};var init_de2=__esm(()=>{init_util2()});function en_default2(){return{localeError:error56()}}var parsedType2=(data)=>{let t=typeof data;switch(t){case"number":return Number.isNaN(data)?"NaN":"number";case"object":{if(Array.isArray(data))return"array";if(data===null)return"null";if(Object.getPrototypeOf(data)!==Object.prototype&&data.constructor)return data.constructor.name}}return t},error56=()=>{let Sizable={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function getSizing(origin){return Sizable[origin]??null}let Nouns={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return(issue3)=>{switch(issue3.code){case"invalid_type":return`Invalid input: expected ${issue3.expected}, received ${parsedType2(issue3.input)}`;case"invalid_value":if(issue3.values.length===1)return`Invalid input: expected ${stringifyPrimitive2(issue3.values[0])}`;return`Invalid option: expected one of ${joinValues2(issue3.values,"|")}`;case"too_big":{let adj=issue3.inclusive?"<=":"<",sizing=getSizing(issue3.origin);if(sizing)return`Too big: expected ${issue3.origin??"value"} to have ${adj}${issue3.maximum.toString()} ${sizing.unit??"elements"}`;return`Too big: expected ${issue3.origin??"value"} to be ${adj}${issue3.maximum.toString()}`}case"too_small":{let adj=issue3.inclusive?">=":">",sizing=getSizing(issue3.origin);if(sizing)return`Too small: expected ${issue3.origin} to have ${adj}${issue3.minimum.toString()} ${sizing.unit}`;return`Too small: expected ${issue3.origin} to be ${adj}${issue3.minimum.toString()}`}case"invalid_format":{let _issue=issue3;if(_issue.format==="starts_with")return`Invalid string: must start with "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Invalid string: must end with "${_issue.suffix}"`;if(_issue.format==="includes")return`Invalid string: must include "${_issue.includes}"`;if(_issue.format==="regex")return`Invalid string: must match pattern ${_issue.pattern}`;return`Invalid ${Nouns[_issue.format]??issue3.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${issue3.divisor}`;case"unrecognized_keys":return`Unrecognized key${issue3.keys.length>1?"s":""}: ${joinValues2(issue3.keys,", ")}`;case"invalid_key":return`Invalid key in ${issue3.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${issue3.origin}`;default:return"Invalid input"}}};var init_en2=__esm(()=>{init_util2()});function eo_default2(){return{localeError:error57()}}var parsedType3=(data)=>{let t=typeof data;switch(t){case"number":return Number.isNaN(data)?"NaN":"nombro";case"object":{if(Array.isArray(data))return"tabelo";if(data===null)return"senvalora";if(Object.getPrototypeOf(data)!==Object.prototype&&data.constructor)return data.constructor.name}}return t},error57=()=>{let Sizable={string:{unit:"karaktrojn",verb:"havi"},file:{unit:"bajtojn",verb:"havi"},array:{unit:"elementojn",verb:"havi"},set:{unit:"elementojn",verb:"havi"}};function getSizing(origin){return Sizable[origin]??null}let Nouns={regex:"enigo",email:"retadreso",url:"URL",emoji:"emoĝio",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-datotempo",date:"ISO-dato",time:"ISO-tempo",duration:"ISO-daŭro",ipv4:"IPv4-adreso",ipv6:"IPv6-adreso",cidrv4:"IPv4-rango",cidrv6:"IPv6-rango",base64:"64-ume kodita karaktraro",base64url:"URL-64-ume kodita karaktraro",json_string:"JSON-karaktraro",e164:"E.164-nombro",jwt:"JWT",template_literal:"enigo"};return(issue3)=>{switch(issue3.code){case"invalid_type":return`Nevalida enigo: atendiĝis ${issue3.expected}, riceviĝis ${parsedType3(issue3.input)}`;case"invalid_value":if(issue3.values.length===1)return`Nevalida enigo: atendiĝis ${stringifyPrimitive2(issue3.values[0])}`;return`Nevalida opcio: atendiĝis unu el ${joinValues2(issue3.values,"|")}`;case"too_big":{let adj=issue3.inclusive?"<=":"<",sizing=getSizing(issue3.origin);if(sizing)return`Tro granda: atendiĝis ke ${issue3.origin??"valoro"} havu ${adj}${issue3.maximum.toString()} ${sizing.unit??"elementojn"}`;return`Tro granda: atendiĝis ke ${issue3.origin??"valoro"} havu ${adj}${issue3.maximum.toString()}`}case"too_small":{let adj=issue3.inclusive?">=":">",sizing=getSizing(issue3.origin);if(sizing)return`Tro malgranda: atendiĝis ke ${issue3.origin} havu ${adj}${issue3.minimum.toString()} ${sizing.unit}`;return`Tro malgranda: atendiĝis ke ${issue3.origin} estu ${adj}${issue3.minimum.toString()}`}case"invalid_format":{let _issue=issue3;if(_issue.format==="starts_with")return`Nevalida karaktraro: devas komenciĝi per "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Nevalida karaktraro: devas finiĝi per "${_issue.suffix}"`;if(_issue.format==="includes")return`Nevalida karaktraro: devas inkluzivi "${_issue.includes}"`;if(_issue.format==="regex")return`Nevalida karaktraro: devas kongrui kun la modelo ${_issue.pattern}`;return`Nevalida ${Nouns[_issue.format]??issue3.format}`}case"not_multiple_of":return`Nevalida nombro: devas esti oblo de ${issue3.divisor}`;case"unrecognized_keys":return`Nekonata${issue3.keys.length>1?"j":""} ŝlosilo${issue3.keys.length>1?"j":""}: ${joinValues2(issue3.keys,", ")}`;case"invalid_key":return`Nevalida ŝlosilo en ${issue3.origin}`;case"invalid_union":return"Nevalida enigo";case"invalid_element":return`Nevalida valoro en ${issue3.origin}`;default:return"Nevalida enigo"}}};var init_eo2=__esm(()=>{init_util2()});function es_default2(){return{localeError:error58()}}var error58=()=>{let Sizable={string:{unit:"caracteres",verb:"tener"},file:{unit:"bytes",verb:"tener"},array:{unit:"elementos",verb:"tener"},set:{unit:"elementos",verb:"tener"}},TypeNames={string:"texto",number:"número",boolean:"booleano",array:"arreglo",object:"objeto",set:"conjunto",file:"archivo",date:"fecha",bigint:"número grande",symbol:"símbolo",undefined:"indefinido",null:"nulo",function:"función",map:"mapa",record:"registro",tuple:"tupla",enum:"enumeración",union:"unión",literal:"literal",promise:"promesa",void:"vacío",never:"nunca",unknown:"desconocido",any:"cualquiera"};function getSizing(origin){return Sizable[origin]??null}function getTypeName(type){return TypeNames[type]??type}let parsedType4=(data)=>{let t=typeof data;switch(t){case"number":return Number.isNaN(data)?"NaN":"number";case"object":{if(Array.isArray(data))return"array";if(data===null)return"null";if(Object.getPrototypeOf(data)!==Object.prototype)return data.constructor.name;return"object"}}return t},Nouns={regex:"entrada",email:"dirección de correo electrónico",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"fecha y hora ISO",date:"fecha ISO",time:"hora ISO",duration:"duración ISO",ipv4:"dirección IPv4",ipv6:"dirección IPv6",cidrv4:"rango IPv4",cidrv6:"rango IPv6",base64:"cadena codificada en base64",base64url:"URL codificada en base64",json_string:"cadena JSON",e164:"número E.164",jwt:"JWT",template_literal:"entrada"};return(issue3)=>{switch(issue3.code){case"invalid_type":return`Entrada inválida: se esperaba ${getTypeName(issue3.expected)}, recibido ${getTypeName(parsedType4(issue3.input))}`;case"invalid_value":if(issue3.values.length===1)return`Entrada inválida: se esperaba ${stringifyPrimitive2(issue3.values[0])}`;return`Opción inválida: se esperaba una de ${joinValues2(issue3.values,"|")}`;case"too_big":{let adj=issue3.inclusive?"<=":"<",sizing=getSizing(issue3.origin),origin=getTypeName(issue3.origin);if(sizing)return`Demasiado grande: se esperaba que ${origin??"valor"} tuviera ${adj}${issue3.maximum.toString()} ${sizing.unit??"elementos"}`;return`Demasiado grande: se esperaba que ${origin??"valor"} fuera ${adj}${issue3.maximum.toString()}`}case"too_small":{let adj=issue3.inclusive?">=":">",sizing=getSizing(issue3.origin),origin=getTypeName(issue3.origin);if(sizing)return`Demasiado pequeño: se esperaba que ${origin} tuviera ${adj}${issue3.minimum.toString()} ${sizing.unit}`;return`Demasiado pequeño: se esperaba que ${origin} fuera ${adj}${issue3.minimum.toString()}`}case"invalid_format":{let _issue=issue3;if(_issue.format==="starts_with")return`Cadena inválida: debe comenzar con "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Cadena inválida: debe terminar en "${_issue.suffix}"`;if(_issue.format==="includes")return`Cadena inválida: debe incluir "${_issue.includes}"`;if(_issue.format==="regex")return`Cadena inválida: debe coincidir con el patrón ${_issue.pattern}`;return`Inválido ${Nouns[_issue.format]??issue3.format}`}case"not_multiple_of":return`Número inválido: debe ser múltiplo de ${issue3.divisor}`;case"unrecognized_keys":return`Llave${issue3.keys.length>1?"s":""} desconocida${issue3.keys.length>1?"s":""}: ${joinValues2(issue3.keys,", ")}`;case"invalid_key":return`Llave inválida en ${getTypeName(issue3.origin)}`;case"invalid_union":return"Entrada inválida";case"invalid_element":return`Valor inválido en ${getTypeName(issue3.origin)}`;default:return"Entrada inválida"}}};var init_es2=__esm(()=>{init_util2()});function fa_default2(){return{localeError:error59()}}var error59=()=>{let Sizable={string:{unit:"کاراکتر",verb:"داشته باشد"},file:{unit:"بایت",verb:"داشته باشد"},array:{unit:"آیتم",verb:"داشته باشد"},set:{unit:"آیتم",verb:"داشته باشد"}};function getSizing(origin){return Sizable[origin]??null}let parsedType4=(data)=>{let t=typeof data;switch(t){case"number":return Number.isNaN(data)?"NaN":"عدد";case"object":{if(Array.isArray(data))return"آرایه";if(data===null)return"null";if(Object.getPrototypeOf(data)!==Object.prototype&&data.constructor)return data.constructor.name}}return t},Nouns={regex:"ورودی",email:"آدرس ایمیل",url:"URL",emoji:"ایموجی",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"تاریخ و زمان ایزو",date:"تاریخ ایزو",time:"زمان ایزو",duration:"مدت زمان ایزو",ipv4:"IPv4 آدرس",ipv6:"IPv6 آدرس",cidrv4:"IPv4 دامنه",cidrv6:"IPv6 دامنه",base64:"base64-encoded رشته",base64url:"base64url-encoded رشته",json_string:"JSON رشته",e164:"E.164 عدد",jwt:"JWT",template_literal:"ورودی"};return(issue3)=>{switch(issue3.code){case"invalid_type":return`ورودی نامعتبر: میبایست ${issue3.expected} میبود، ${parsedType4(issue3.input)} دریافت شد`;case"invalid_value":if(issue3.values.length===1)return`ورودی نامعتبر: میبایست ${stringifyPrimitive2(issue3.values[0])} میبود`;return`گزینه نامعتبر: میبایست یکی از ${joinValues2(issue3.values,"|")} میبود`;case"too_big":{let adj=issue3.inclusive?"<=":"<",sizing=getSizing(issue3.origin);if(sizing)return`خیلی بزرگ: ${issue3.origin??"مقدار"} باید ${adj}${issue3.maximum.toString()} ${sizing.unit??"عنصر"} باشد`;return`خیلی بزرگ: ${issue3.origin??"مقدار"} باید ${adj}${issue3.maximum.toString()} باشد`}case"too_small":{let adj=issue3.inclusive?">=":">",sizing=getSizing(issue3.origin);if(sizing)return`خیلی کوچک: ${issue3.origin} باید ${adj}${issue3.minimum.toString()} ${sizing.unit} باشد`;return`خیلی کوچک: ${issue3.origin} باید ${adj}${issue3.minimum.toString()} باشد`}case"invalid_format":{let _issue=issue3;if(_issue.format==="starts_with")return`رشته نامعتبر: باید با "${_issue.prefix}" شروع شود`;if(_issue.format==="ends_with")return`رشته نامعتبر: باید با "${_issue.suffix}" تمام شود`;if(_issue.format==="includes")return`رشته نامعتبر: باید شامل "${_issue.includes}" باشد`;if(_issue.format==="regex")return`رشته نامعتبر: باید با الگوی ${_issue.pattern} مطابقت داشته باشد`;return`${Nouns[_issue.format]??issue3.format} نامعتبر`}case"not_multiple_of":return`عدد نامعتبر: باید مضرب ${issue3.divisor} باشد`;case"unrecognized_keys":return`کلید${issue3.keys.length>1?"های":""} ناشناس: ${joinValues2(issue3.keys,", ")}`;case"invalid_key":return`کلید ناشناس در ${issue3.origin}`;case"invalid_union":return"ورودی نامعتبر";case"invalid_element":return`مقدار نامعتبر در ${issue3.origin}`;default:return"ورودی نامعتبر"}}};var init_fa2=__esm(()=>{init_util2()});function fi_default2(){return{localeError:error60()}}var error60=()=>{let Sizable={string:{unit:"merkkiä",subject:"merkkijonon"},file:{unit:"tavua",subject:"tiedoston"},array:{unit:"alkiota",subject:"listan"},set:{unit:"alkiota",subject:"joukon"},number:{unit:"",subject:"luvun"},bigint:{unit:"",subject:"suuren kokonaisluvun"},int:{unit:"",subject:"kokonaisluvun"},date:{unit:"",subject:"päivämäärän"}};function getSizing(origin){return Sizable[origin]??null}let parsedType4=(data)=>{let t=typeof data;switch(t){case"number":return Number.isNaN(data)?"NaN":"number";case"object":{if(Array.isArray(data))return"array";if(data===null)return"null";if(Object.getPrototypeOf(data)!==Object.prototype&&data.constructor)return data.constructor.name}}return t},Nouns={regex:"säännöllinen lauseke",email:"sähköpostiosoite",url:"URL-osoite",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-aikaleima",date:"ISO-päivämäärä",time:"ISO-aika",duration:"ISO-kesto",ipv4:"IPv4-osoite",ipv6:"IPv6-osoite",cidrv4:"IPv4-alue",cidrv6:"IPv6-alue",base64:"base64-koodattu merkkijono",base64url:"base64url-koodattu merkkijono",json_string:"JSON-merkkijono",e164:"E.164-luku",jwt:"JWT",template_literal:"templaattimerkkijono"};return(issue3)=>{switch(issue3.code){case"invalid_type":return`Virheellinen tyyppi: odotettiin ${issue3.expected}, oli ${parsedType4(issue3.input)}`;case"invalid_value":if(issue3.values.length===1)return`Virheellinen syöte: täytyy olla ${stringifyPrimitive2(issue3.values[0])}`;return`Virheellinen valinta: täytyy olla yksi seuraavista: ${joinValues2(issue3.values,"|")}`;case"too_big":{let adj=issue3.inclusive?"<=":"<",sizing=getSizing(issue3.origin);if(sizing)return`Liian suuri: ${sizing.subject} täytyy olla ${adj}${issue3.maximum.toString()} ${sizing.unit}`.trim();return`Liian suuri: arvon täytyy olla ${adj}${issue3.maximum.toString()}`}case"too_small":{let adj=issue3.inclusive?">=":">",sizing=getSizing(issue3.origin);if(sizing)return`Liian pieni: ${sizing.subject} täytyy olla ${adj}${issue3.minimum.toString()} ${sizing.unit}`.trim();return`Liian pieni: arvon täytyy olla ${adj}${issue3.minimum.toString()}`}case"invalid_format":{let _issue=issue3;if(_issue.format==="starts_with")return`Virheellinen syöte: täytyy alkaa "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Virheellinen syöte: täytyy loppua "${_issue.suffix}"`;if(_issue.format==="includes")return`Virheellinen syöte: täytyy sisältää "${_issue.includes}"`;if(_issue.format==="regex")return`Virheellinen syöte: täytyy vastata säännöllistä lauseketta ${_issue.pattern}`;return`Virheellinen ${Nouns[_issue.format]??issue3.format}`}case"not_multiple_of":return`Virheellinen luku: täytyy olla luvun ${issue3.divisor} monikerta`;case"unrecognized_keys":return`${issue3.keys.length>1?"Tuntemattomat avaimet":"Tuntematon avain"}: ${joinValues2(issue3.keys,", ")}`;case"invalid_key":return"Virheellinen avain tietueessa";case"invalid_union":return"Virheellinen unioni";case"invalid_element":return"Virheellinen arvo joukossa";default:return"Virheellinen syöte"}}};var init_fi2=__esm(()=>{init_util2()});function fr_default2(){return{localeError:error61()}}var error61=()=>{let Sizable={string:{unit:"caractères",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"éléments",verb:"avoir"},set:{unit:"éléments",verb:"avoir"}};function getSizing(origin){return Sizable[origin]??null}let parsedType4=(data)=>{let t=typeof data;switch(t){case"number":return Number.isNaN(data)?"NaN":"nombre";case"object":{if(Array.isArray(data))return"tableau";if(data===null)return"null";if(Object.getPrototypeOf(data)!==Object.prototype&&data.constructor)return data.constructor.name}}return t},Nouns={regex:"entrée",email:"adresse e-mail",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"date et heure ISO",date:"date ISO",time:"heure ISO",duration:"durée ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"chaîne encodée en base64",base64url:"chaîne encodée en base64url",json_string:"chaîne JSON",e164:"numéro E.164",jwt:"JWT",template_literal:"entrée"};return(issue3)=>{switch(issue3.code){case"invalid_type":return`Entrée invalide : ${issue3.expected} attendu, ${parsedType4(issue3.input)} reçu`;case"invalid_value":if(issue3.values.length===1)return`Entrée invalide : ${stringifyPrimitive2(issue3.values[0])} attendu`;return`Option invalide : une valeur parmi ${joinValues2(issue3.values,"|")} attendue`;case"too_big":{let adj=issue3.inclusive?"<=":"<",sizing=getSizing(issue3.origin);if(sizing)return`Trop grand : ${issue3.origin??"valeur"} doit ${sizing.verb} ${adj}${issue3.maximum.toString()} ${sizing.unit??"élément(s)"}`;return`Trop grand : ${issue3.origin??"valeur"} doit être ${adj}${issue3.maximum.toString()}`}case"too_small":{let adj=issue3.inclusive?">=":">",sizing=getSizing(issue3.origin);if(sizing)return`Trop petit : ${issue3.origin} doit ${sizing.verb} ${adj}${issue3.minimum.toString()} ${sizing.unit}`;return`Trop petit : ${issue3.origin} doit être ${adj}${issue3.minimum.toString()}`}case"invalid_format":{let _issue=issue3;if(_issue.format==="starts_with")return`Chaîne invalide : doit commencer par "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Chaîne invalide : doit se terminer par "${_issue.suffix}"`;if(_issue.format==="includes")return`Chaîne invalide : doit inclure "${_issue.includes}"`;if(_issue.format==="regex")return`Chaîne invalide : doit correspondre au modèle ${_issue.pattern}`;return`${Nouns[_issue.format]??issue3.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit être un multiple de ${issue3.divisor}`;case"unrecognized_keys":return`Clé${issue3.keys.length>1?"s":""} non reconnue${issue3.keys.length>1?"s":""} : ${joinValues2(issue3.keys,", ")}`;case"invalid_key":return`Clé invalide dans ${issue3.origin}`;case"invalid_union":return"Entrée invalide";case"invalid_element":return`Valeur invalide dans ${issue3.origin}`;default:return"Entrée invalide"}}};var init_fr2=__esm(()=>{init_util2()});function fr_CA_default2(){return{localeError:error62()}}var error62=()=>{let Sizable={string:{unit:"caractères",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"éléments",verb:"avoir"},set:{unit:"éléments",verb:"avoir"}};function getSizing(origin){return Sizable[origin]??null}let parsedType4=(data)=>{let t=typeof data;switch(t){case"number":return Number.isNaN(data)?"NaN":"number";case"object":{if(Array.isArray(data))return"array";if(data===null)return"null";if(Object.getPrototypeOf(data)!==Object.prototype&&data.constructor)return data.constructor.name}}return t},Nouns={regex:"entrée",email:"adresse courriel",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"date-heure ISO",date:"date ISO",time:"heure ISO",duration:"durée ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"chaîne encodée en base64",base64url:"chaîne encodée en base64url",json_string:"chaîne JSON",e164:"numéro E.164",jwt:"JWT",template_literal:"entrée"};return(issue3)=>{switch(issue3.code){case"invalid_type":return`Entrée invalide : attendu ${issue3.expected}, reçu ${parsedType4(issue3.input)}`;case"invalid_value":if(issue3.values.length===1)return`Entrée invalide : attendu ${stringifyPrimitive2(issue3.values[0])}`;return`Option invalide : attendu l'une des valeurs suivantes ${joinValues2(issue3.values,"|")}`;case"too_big":{let adj=issue3.inclusive?"≤":"<",sizing=getSizing(issue3.origin);if(sizing)return`Trop grand : attendu que ${issue3.origin??"la valeur"} ait ${adj}${issue3.maximum.toString()} ${sizing.unit}`;return`Trop grand : attendu que ${issue3.origin??"la valeur"} soit ${adj}${issue3.maximum.toString()}`}case"too_small":{let adj=issue3.inclusive?"≥":">",sizing=getSizing(issue3.origin);if(sizing)return`Trop petit : attendu que ${issue3.origin} ait ${adj}${issue3.minimum.toString()} ${sizing.unit}`;return`Trop petit : attendu que ${issue3.origin} soit ${adj}${issue3.minimum.toString()}`}case"invalid_format":{let _issue=issue3;if(_issue.format==="starts_with")return`Chaîne invalide : doit commencer par "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Chaîne invalide : doit se terminer par "${_issue.suffix}"`;if(_issue.format==="includes")return`Chaîne invalide : doit inclure "${_issue.includes}"`;if(_issue.format==="regex")return`Chaîne invalide : doit correspondre au motif ${_issue.pattern}`;return`${Nouns[_issue.format]??issue3.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit être un multiple de ${issue3.divisor}`;case"unrecognized_keys":return`Clé${issue3.keys.length>1?"s":""} non reconnue${issue3.keys.length>1?"s":""} : ${joinValues2(issue3.keys,", ")}`;case"invalid_key":return`Clé invalide dans ${issue3.origin}`;case"invalid_union":return"Entrée invalide";case"invalid_element":return`Valeur invalide dans ${issue3.origin}`;default:return"Entrée invalide"}}};var init_fr_CA2=__esm(()=>{init_util2()});function he_default2(){return{localeError:error63()}}var error63=()=>{let Sizable={string:{unit:"אותיות",verb:"לכלול"},file:{unit:"בייטים",verb:"לכלול"},array:{unit:"פריטים",verb:"לכלול"},set:{unit:"פריטים",verb:"לכלול"}};function getSizing(origin){return Sizable[origin]??null}let parsedType4=(data)=>{let t=typeof data;switch(t){case"number":return Number.isNaN(data)?"NaN":"number";case"object":{if(Array.isArray(data))return"array";if(data===null)return"null";if(Object.getPrototypeOf(data)!==Object.prototype&&data.constructor)return data.constructor.name}}return t},Nouns={regex:"קלט",email:"כתובת אימייל",url:"כתובת רשת",emoji:"אימוג'י",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"תאריך וזמן ISO",date:"תאריך ISO",time:"זמן ISO",duration:"משך זמן ISO",ipv4:"כתובת IPv4",ipv6:"כתובת IPv6",cidrv4:"טווח IPv4",cidrv6:"טווח IPv6",base64:"מחרוזת בבסיס 64",base64url:"מחרוזת בבסיס 64 לכתובות רשת",json_string:"מחרוזת JSON",e164:"מספר E.164",jwt:"JWT",template_literal:"קלט"};return(issue3)=>{switch(issue3.code){case"invalid_type":return`קלט לא תקין: צריך ${issue3.expected}, התקבל ${parsedType4(issue3.input)}`;case"invalid_value":if(issue3.values.length===1)return`קלט לא תקין: צריך ${stringifyPrimitive2(issue3.values[0])}`;return`קלט לא תקין: צריך אחת מהאפשרויות ${joinValues2(issue3.values,"|")}`;case"too_big":{let adj=issue3.inclusive?"<=":"<",sizing=getSizing(issue3.origin);if(sizing)return`גדול מדי: ${issue3.origin??"value"} צריך להיות ${adj}${issue3.maximum.toString()} ${sizing.unit??"elements"}`;return`גדול מדי: ${issue3.origin??"value"} צריך להיות ${adj}${issue3.maximum.toString()}`}case"too_small":{let adj=issue3.inclusive?">=":">",sizing=getSizing(issue3.origin);if(sizing)return`קטן מדי: ${issue3.origin} צריך להיות ${adj}${issue3.minimum.toString()} ${sizing.unit}`;return`קטן מדי: ${issue3.origin} צריך להיות ${adj}${issue3.minimum.toString()}`}case"invalid_format":{let _issue=issue3;if(_issue.format==="starts_with")return`מחרוזת לא תקינה: חייבת להתחיל ב"${_issue.prefix}"`;if(_issue.format==="ends_with")return`מחרוזת לא תקינה: חייבת להסתיים ב "${_issue.suffix}"`;if(_issue.format==="includes")return`מחרוזת לא תקינה: חייבת לכלול "${_issue.includes}"`;if(_issue.format==="regex")return`מחרוזת לא תקינה: חייבת להתאים לתבנית ${_issue.pattern}`;return`${Nouns[_issue.format]??issue3.format} לא תקין`}case"not_multiple_of":return`מספר לא תקין: חייב להיות מכפלה של ${issue3.divisor}`;case"unrecognized_keys":return`מפתח${issue3.keys.length>1?"ות":""} לא מזוה${issue3.keys.length>1?"ים":"ה"}: ${joinValues2(issue3.keys,", ")}`;case"invalid_key":return`מפתח לא תקין ב${issue3.origin}`;case"invalid_union":return"קלט לא תקין";case"invalid_element":return`ערך לא תקין ב${issue3.origin}`;default:return"קלט לא תקין"}}};var init_he2=__esm(()=>{init_util2()});function hu_default2(){return{localeError:error64()}}var error64=()=>{let Sizable={string:{unit:"karakter",verb:"legyen"},file:{unit:"byte",verb:"legyen"},array:{unit:"elem",verb:"legyen"},set:{unit:"elem",verb:"legyen"}};function getSizing(origin){return Sizable[origin]??null}let parsedType4=(data)=>{let t=typeof data;switch(t){case"number":return Number.isNaN(data)?"NaN":"szám";case"object":{if(Array.isArray(data))return"tömb";if(data===null)return"null";if(Object.getPrototypeOf(data)!==Object.prototype&&data.constructor)return data.constructor.name}}return t},Nouns={regex:"bemenet",email:"email cím",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO időbélyeg",date:"ISO dátum",time:"ISO idő",duration:"ISO időintervallum",ipv4:"IPv4 cím",ipv6:"IPv6 cím",cidrv4:"IPv4 tartomány",cidrv6:"IPv6 tartomány",base64:"base64-kódolt string",base64url:"base64url-kódolt string",json_string:"JSON string",e164:"E.164 szám",jwt:"JWT",template_literal:"bemenet"};return(issue3)=>{switch(issue3.code){case"invalid_type":return`Érvénytelen bemenet: a várt érték ${issue3.expected}, a kapott érték ${parsedType4(issue3.input)}`;case"invalid_value":if(issue3.values.length===1)return`Érvénytelen bemenet: a várt érték ${stringifyPrimitive2(issue3.values[0])}`;return`Érvénytelen opció: valamelyik érték várt ${joinValues2(issue3.values,"|")}`;case"too_big":{let adj=issue3.inclusive?"<=":"<",sizing=getSizing(issue3.origin);if(sizing)return`Túl nagy: ${issue3.origin??"érték"} mérete túl nagy ${adj}${issue3.maximum.toString()} ${sizing.unit??"elem"}`;return`Túl nagy: a bemeneti érték ${issue3.origin??"érték"} túl nagy: ${adj}${issue3.maximum.toString()}`}case"too_small":{let adj=issue3.inclusive?">=":">",sizing=getSizing(issue3.origin);if(sizing)return`Túl kicsi: a bemeneti érték ${issue3.origin} mérete túl kicsi ${adj}${issue3.minimum.toString()} ${sizing.unit}`;return`Túl kicsi: a bemeneti érték ${issue3.origin} túl kicsi ${adj}${issue3.minimum.toString()}`}case"invalid_format":{let _issue=issue3;if(_issue.format==="starts_with")return`Érvénytelen string: "${_issue.prefix}" értékkel kell kezdődnie`;if(_issue.format==="ends_with")return`Érvénytelen string: "${_issue.suffix}" értékkel kell végződnie`;if(_issue.format==="includes")return`Érvénytelen string: "${_issue.includes}" értéket kell tartalmaznia`;if(_issue.format==="regex")return`Érvénytelen string: ${_issue.pattern} mintának kell megfelelnie`;return`Érvénytelen ${Nouns[_issue.format]??issue3.format}`}case"not_multiple_of":return`Érvénytelen szám: ${issue3.divisor} többszörösének kell lennie`;case"unrecognized_keys":return`Ismeretlen kulcs${issue3.keys.length>1?"s":""}: ${joinValues2(issue3.keys,", ")}`;case"invalid_key":return`Érvénytelen kulcs ${issue3.origin}`;case"invalid_union":return"Érvénytelen bemenet";case"invalid_element":return`Érvénytelen érték: ${issue3.origin}`;default:return"Érvénytelen bemenet"}}};var init_hu2=__esm(()=>{init_util2()});function id_default2(){return{localeError:error65()}}var error65=()=>{let Sizable={string:{unit:"karakter",verb:"memiliki"},file:{unit:"byte",verb:"memiliki"},array:{unit:"item",verb:"memiliki"},set:{unit:"item",verb:"memiliki"}};function getSizing(origin){return Sizable[origin]??null}let parsedType4=(data)=>{let t=typeof data;switch(t){case"number":return Number.isNaN(data)?"NaN":"number";case"object":{if(Array.isArray(data))return"array";if(data===null)return"null";if(Object.getPrototypeOf(data)!==Object.prototype&&data.constructor)return data.constructor.name}}return t},Nouns={regex:"input",email:"alamat email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"tanggal dan waktu format ISO",date:"tanggal format ISO",time:"jam format ISO",duration:"durasi format ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"rentang alamat IPv4",cidrv6:"rentang alamat IPv6",base64:"string dengan enkode base64",base64url:"string dengan enkode base64url",json_string:"string JSON",e164:"angka E.164",jwt:"JWT",template_literal:"input"};return(issue3)=>{switch(issue3.code){case"invalid_type":return`Input tidak valid: diharapkan ${issue3.expected}, diterima ${parsedType4(issue3.input)}`;case"invalid_value":if(issue3.values.length===1)return`Input tidak valid: diharapkan ${stringifyPrimitive2(issue3.values[0])}`;return`Pilihan tidak valid: diharapkan salah satu dari ${joinValues2(issue3.values,"|")}`;case"too_big":{let adj=issue3.inclusive?"<=":"<",sizing=getSizing(issue3.origin);if(sizing)return`Terlalu besar: diharapkan ${issue3.origin??"value"} memiliki ${adj}${issue3.maximum.toString()} ${sizing.unit??"elemen"}`;return`Terlalu besar: diharapkan ${issue3.origin??"value"} menjadi ${adj}${issue3.maximum.toString()}`}case"too_small":{let adj=issue3.inclusive?">=":">",sizing=getSizing(issue3.origin);if(sizing)return`Terlalu kecil: diharapkan ${issue3.origin} memiliki ${adj}${issue3.minimum.toString()} ${sizing.unit}`;return`Terlalu kecil: diharapkan ${issue3.origin} menjadi ${adj}${issue3.minimum.toString()}`}case"invalid_format":{let _issue=issue3;if(_issue.format==="starts_with")return`String tidak valid: harus dimulai dengan "${_issue.prefix}"`;if(_issue.format==="ends_with")return`String tidak valid: harus berakhir dengan "${_issue.suffix}"`;if(_issue.format==="includes")return`String tidak valid: harus menyertakan "${_issue.includes}"`;if(_issue.format==="regex")return`String tidak valid: harus sesuai pola ${_issue.pattern}`;return`${Nouns[_issue.format]??issue3.format} tidak valid`}case"not_multiple_of":return`Angka tidak valid: harus kelipatan dari ${issue3.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali ${issue3.keys.length>1?"s":""}: ${joinValues2(issue3.keys,", ")}`;case"invalid_key":return`Kunci tidak valid di ${issue3.origin}`;case"invalid_union":return"Input tidak valid";case"invalid_element":return`Nilai tidak valid di ${issue3.origin}`;default:return"Input tidak valid"}}};var init_id2=__esm(()=>{init_util2()});function is_default2(){return{localeError:error66()}}var parsedType4=(data)=>{let t=typeof data;switch(t){case"number":return Number.isNaN(data)?"NaN":"númer";case"object":{if(Array.isArray(data))return"fylki";if(data===null)return"null";if(Object.getPrototypeOf(data)!==Object.prototype&&data.constructor)return data.constructor.name}}return t},error66=()=>{let Sizable={string:{unit:"stafi",verb:"að hafa"},file:{unit:"bæti",verb:"að hafa"},array:{unit:"hluti",verb:"að hafa"},set:{unit:"hluti",verb:"að hafa"}};function getSizing(origin){return Sizable[origin]??null}let Nouns={regex:"gildi",email:"netfang",url:"vefslóð",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dagsetning og tími",date:"ISO dagsetning",time:"ISO tími",duration:"ISO tímalengd",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded strengur",base64url:"base64url-encoded strengur",json_string:"JSON strengur",e164:"E.164 tölugildi",jwt:"JWT",template_literal:"gildi"};return(issue3)=>{switch(issue3.code){case"invalid_type":return`Rangt gildi: Þú slóst inn ${parsedType4(issue3.input)} þar sem á að vera ${issue3.expected}`;case"invalid_value":if(issue3.values.length===1)return`Rangt gildi: gert ráð fyrir ${stringifyPrimitive2(issue3.values[0])}`;return`Ógilt val: má vera eitt af eftirfarandi ${joinValues2(issue3.values,"|")}`;case"too_big":{let adj=issue3.inclusive?"<=":"<",sizing=getSizing(issue3.origin);if(sizing)return`Of stórt: gert er ráð fyrir að ${issue3.origin??"gildi"} hafi ${adj}${issue3.maximum.toString()} ${sizing.unit??"hluti"}`;return`Of stórt: gert er ráð fyrir að ${issue3.origin??"gildi"} sé ${adj}${issue3.maximum.toString()}`}case"too_small":{let adj=issue3.inclusive?">=":">",sizing=getSizing(issue3.origin);if(sizing)return`Of lítið: gert er ráð fyrir að ${issue3.origin} hafi ${adj}${issue3.minimum.toString()} ${sizing.unit}`;return`Of lítið: gert er ráð fyrir að ${issue3.origin} sé ${adj}${issue3.minimum.toString()}`}case"invalid_format":{let _issue=issue3;if(_issue.format==="starts_with")return`Ógildur strengur: verður að byrja á "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Ógildur strengur: verður að enda á "${_issue.suffix}"`;if(_issue.format==="includes")return`Ógildur strengur: verður að innihalda "${_issue.includes}"`;if(_issue.format==="regex")return`Ógildur strengur: verður að fylgja mynstri ${_issue.pattern}`;return`Rangt ${Nouns[_issue.format]??issue3.format}`}case"not_multiple_of":return`Röng tala: verður að vera margfeldi af ${issue3.divisor}`;case"unrecognized_keys":return`Óþekkt ${issue3.keys.length>1?"ir lyklar":"ur lykill"}: ${joinValues2(issue3.keys,", ")}`;case"invalid_key":return`Rangur lykill í ${issue3.origin}`;case"invalid_union":return"Rangt gildi";case"invalid_element":return`Rangt gildi í ${issue3.origin}`;default:return"Rangt gildi"}}};var init_is2=__esm(()=>{init_util2()});function it_default2(){return{localeError:error67()}}var error67=()=>{let Sizable={string:{unit:"caratteri",verb:"avere"},file:{unit:"byte",verb:"avere"},array:{unit:"elementi",verb:"avere"},set:{unit:"elementi",verb:"avere"}};function getSizing(origin){return Sizable[origin]??null}let parsedType5=(data)=>{let t=typeof data;switch(t){case"number":return Number.isNaN(data)?"NaN":"numero";case"object":{if(Array.isArray(data))return"vettore";if(data===null)return"null";if(Object.getPrototypeOf(data)!==Object.prototype&&data.constructor)return data.constructor.name}}return t},Nouns={regex:"input",email:"indirizzo email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data e ora ISO",date:"data ISO",time:"ora ISO",duration:"durata ISO",ipv4:"indirizzo IPv4",ipv6:"indirizzo IPv6",cidrv4:"intervallo IPv4",cidrv6:"intervallo IPv6",base64:"stringa codificata in base64",base64url:"URL codificata in base64",json_string:"stringa JSON",e164:"numero E.164",jwt:"JWT",template_literal:"input"};return(issue3)=>{switch(issue3.code){case"invalid_type":return`Input non valido: atteso ${issue3.expected}, ricevuto ${parsedType5(issue3.input)}`;case"invalid_value":if(issue3.values.length===1)return`Input non valido: atteso ${stringifyPrimitive2(issue3.values[0])}`;return`Opzione non valida: atteso uno tra ${joinValues2(issue3.values,"|")}`;case"too_big":{let adj=issue3.inclusive?"<=":"<",sizing=getSizing(issue3.origin);if(sizing)return`Troppo grande: ${issue3.origin??"valore"} deve avere ${adj}${issue3.maximum.toString()} ${sizing.unit??"elementi"}`;return`Troppo grande: ${issue3.origin??"valore"} deve essere ${adj}${issue3.maximum.toString()}`}case"too_small":{let adj=issue3.inclusive?">=":">",sizing=getSizing(issue3.origin);if(sizing)return`Troppo piccolo: ${issue3.origin} deve avere ${adj}${issue3.minimum.toString()} ${sizing.unit}`;return`Troppo piccolo: ${issue3.origin} deve essere ${adj}${issue3.minimum.toString()}`}case"invalid_format":{let _issue=issue3;if(_issue.format==="starts_with")return`Stringa non valida: deve iniziare con "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Stringa non valida: deve terminare con "${_issue.suffix}"`;if(_issue.format==="includes")return`Stringa non valida: deve includere "${_issue.includes}"`;if(_issue.format==="regex")return`Stringa non valida: deve corrispondere al pattern ${_issue.pattern}`;return`Invalid ${Nouns[_issue.format]??issue3.format}`}case"not_multiple_of":return`Numero non valido: deve essere un multiplo di ${issue3.divisor}`;case"unrecognized_keys":return`Chiav${issue3.keys.length>1?"i":"e"} non riconosciut${issue3.keys.length>1?"e":"a"}: ${joinValues2(issue3.keys,", ")}`;case"invalid_key":return`Chiave non valida in ${issue3.origin}`;case"invalid_union":return"Input non valido";case"invalid_element":return`Valore non valido in ${issue3.origin}`;default:return"Input non valido"}}};var init_it2=__esm(()=>{init_util2()});function ja_default2(){return{localeError:error68()}}var error68=()=>{let Sizable={string:{unit:"文字",verb:"である"},file:{unit:"バイト",verb:"である"},array:{unit:"要素",verb:"である"},set:{unit:"要素",verb:"である"}};function getSizing(origin){return Sizable[origin]??null}let parsedType5=(data)=>{let t=typeof data;switch(t){case"number":return Number.isNaN(data)?"NaN":"数値";case"object":{if(Array.isArray(data))return"配列";if(data===null)return"null";if(Object.getPrototypeOf(data)!==Object.prototype&&data.constructor)return data.constructor.name}}return t},Nouns={regex:"入力値",email:"メールアドレス",url:"URL",emoji:"絵文字",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO日時",date:"ISO日付",time:"ISO時刻",duration:"ISO期間",ipv4:"IPv4アドレス",ipv6:"IPv6アドレス",cidrv4:"IPv4範囲",cidrv6:"IPv6範囲",base64:"base64エンコード文字列",base64url:"base64urlエンコード文字列",json_string:"JSON文字列",e164:"E.164番号",jwt:"JWT",template_literal:"入力値"};return(issue3)=>{switch(issue3.code){case"invalid_type":return`無効な入力: ${issue3.expected}が期待されましたが、${parsedType5(issue3.input)}が入力されました`;case"invalid_value":if(issue3.values.length===1)return`無効な入力: ${stringifyPrimitive2(issue3.values[0])}が期待されました`;return`無効な選択: ${joinValues2(issue3.values,"、")}のいずれかである必要があります`;case"too_big":{let adj=issue3.inclusive?"以下である":"より小さい",sizing=getSizing(issue3.origin);if(sizing)return`大きすぎる値: ${issue3.origin??"値"}は${issue3.maximum.toString()}${sizing.unit??"要素"}${adj}必要があります`;return`大きすぎる値: ${issue3.origin??"値"}は${issue3.maximum.toString()}${adj}必要があります`}case"too_small":{let adj=issue3.inclusive?"以上である":"より大きい",sizing=getSizing(issue3.origin);if(sizing)return`小さすぎる値: ${issue3.origin}は${issue3.minimum.toString()}${sizing.unit}${adj}必要があります`;return`小さすぎる値: ${issue3.origin}は${issue3.minimum.toString()}${adj}必要があります`}case"invalid_format":{let _issue=issue3;if(_issue.format==="starts_with")return`無効な文字列: "${_issue.prefix}"で始まる必要があります`;if(_issue.format==="ends_with")return`無効な文字列: "${_issue.suffix}"で終わる必要があります`;if(_issue.format==="includes")return`無効な文字列: "${_issue.includes}"を含む必要があります`;if(_issue.format==="regex")return`無効な文字列: パターン${_issue.pattern}に一致する必要があります`;return`無効な${Nouns[_issue.format]??issue3.format}`}case"not_multiple_of":return`無効な数値: ${issue3.divisor}の倍数である必要があります`;case"unrecognized_keys":return`認識されていないキー${issue3.keys.length>1?"群":""}: ${joinValues2(issue3.keys,"、")}`;case"invalid_key":return`${issue3.origin}内の無効なキー`;case"invalid_union":return"無効な入力";case"invalid_element":return`${issue3.origin}内の無効な値`;default:return"無効な入力"}}};var init_ja2=__esm(()=>{init_util2()});function ka_default2(){return{localeError:error69()}}var parsedType5=(data)=>{let t=typeof data;switch(t){case"number":return Number.isNaN(data)?"NaN":"რიცხვი";case"object":{if(Array.isArray(data))return"მასივი";if(data===null)return"null";if(Object.getPrototypeOf(data)!==Object.prototype&&data.constructor)return data.constructor.name}}return{string:"სტრინგი",boolean:"ბულეანი",undefined:"undefined",bigint:"bigint",symbol:"symbol",function:"ფუნქცია"}[t]??t},error69=()=>{let Sizable={string:{unit:"სიმბოლო",verb:"უნდა შეიცავდეს"},file:{unit:"ბაიტი",verb:"უნდა შეიცავდეს"},array:{unit:"ელემენტი",verb:"უნდა შეიცავდეს"},set:{unit:"ელემენტი",verb:"უნდა შეიცავდეს"}};function getSizing(origin){return Sizable[origin]??null}let Nouns={regex:"შეყვანა",email:"ელ-ფოსტის მისამართი",url:"URL",emoji:"ემოჯი",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"თარიღი-დრო",date:"თარიღი",time:"დრო",duration:"ხანგრძლივობა",ipv4:"IPv4 მისამართი",ipv6:"IPv6 მისამართი",cidrv4:"IPv4 დიაპაზონი",cidrv6:"IPv6 დიაპაზონი",base64:"base64-კოდირებული სტრინგი",base64url:"base64url-კოდირებული სტრინგი",json_string:"JSON სტრინგი",e164:"E.164 ნომერი",jwt:"JWT",template_literal:"შეყვანა"};return(issue3)=>{switch(issue3.code){case"invalid_type":return`არასწორი შეყვანა: მოსალოდნელი ${issue3.expected}, მიღებული ${parsedType5(issue3.input)}`;case"invalid_value":if(issue3.values.length===1)return`არასწორი შეყვანა: მოსალოდნელი ${stringifyPrimitive2(issue3.values[0])}`;return`არასწორი ვარიანტი: მოსალოდნელია ერთ-ერთი ${joinValues2(issue3.values,"|")}-დან`;case"too_big":{let adj=issue3.inclusive?"<=":"<",sizing=getSizing(issue3.origin);if(sizing)return`ზედმეტად დიდი: მოსალოდნელი ${issue3.origin??"მნიშვნელობა"} ${sizing.verb} ${adj}${issue3.maximum.toString()} ${sizing.unit}`;return`ზედმეტად დიდი: მოსალოდნელი ${issue3.origin??"მნიშვნელობა"} იყოს ${adj}${issue3.maximum.toString()}`}case"too_small":{let adj=issue3.inclusive?">=":">",sizing=getSizing(issue3.origin);if(sizing)return`ზედმეტად პატარა: მოსალოდნელი ${issue3.origin} ${sizing.verb} ${adj}${issue3.minimum.toString()} ${sizing.unit}`;return`ზედმეტად პატარა: მოსალოდნელი ${issue3.origin} იყოს ${adj}${issue3.minimum.toString()}`}case"invalid_format":{let _issue=issue3;if(_issue.format==="starts_with")return`არასწორი სტრინგი: უნდა იწყებოდეს "${_issue.prefix}"-ით`;if(_issue.format==="ends_with")return`არასწორი სტრინგი: უნდა მთავრდებოდეს "${_issue.suffix}"-ით`;if(_issue.format==="includes")return`არასწორი სტრინგი: უნდა შეიცავდეს "${_issue.includes}"-ს`;if(_issue.format==="regex")return`არასწორი სტრინგი: უნდა შეესაბამებოდეს შაბლონს ${_issue.pattern}`;return`არასწორი ${Nouns[_issue.format]??issue3.format}`}case"not_multiple_of":return`არასწორი რიცხვი: უნდა იყოს ${issue3.divisor}-ის ჯერადი`;case"unrecognized_keys":return`უცნობი გასაღებ${issue3.keys.length>1?"ები":"ი"}: ${joinValues2(issue3.keys,", ")}`;case"invalid_key":return`არასწორი გასაღები ${issue3.origin}-ში`;case"invalid_union":return"არასწორი შეყვანა";case"invalid_element":return`არასწორი მნიშვნელობა ${issue3.origin}-ში`;default:return"არასწორი შეყვანა"}}};var init_ka2=__esm(()=>{init_util2()});function km_default2(){return{localeError:error70()}}var error70=()=>{let Sizable={string:{unit:"តួអក្សរ",verb:"គួរមាន"},file:{unit:"បៃ",verb:"គួរមាន"},array:{unit:"ធាតុ",verb:"គួរមាន"},set:{unit:"ធាតុ",verb:"គួរមាន"}};function getSizing(origin){return Sizable[origin]??null}let parsedType6=(data)=>{let t=typeof data;switch(t){case"number":return Number.isNaN(data)?"មិនមែនជាលេខ (NaN)":"លេខ";case"object":{if(Array.isArray(data))return"អារេ (Array)";if(data===null)return"គ្មានតម្លៃ (null)";if(Object.getPrototypeOf(data)!==Object.prototype&&data.constructor)return data.constructor.name}}return t},Nouns={regex:"ទិន្នន័យបញ្ចូល",email:"អាសយដ្ឋានអ៊ីមែល",url:"URL",emoji:"សញ្ញាអារម្មណ៍",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"កាលបរិច្ឆេទ និងម៉ោង ISO",date:"កាលបរិច្ឆេទ ISO",time:"ម៉ោង ISO",duration:"រយៈពេល ISO",ipv4:"អាសយដ្ឋាន IPv4",ipv6:"អាសយដ្ឋាន IPv6",cidrv4:"ដែនអាសយដ្ឋាន IPv4",cidrv6:"ដែនអាសយដ្ឋាន IPv6",base64:"ខ្សែអក្សរអ៊ិកូដ base64",base64url:"ខ្សែអក្សរអ៊ិកូដ base64url",json_string:"ខ្សែអក្សរ JSON",e164:"លេខ E.164",jwt:"JWT",template_literal:"ទិន្នន័យបញ្ចូល"};return(issue3)=>{switch(issue3.code){case"invalid_type":return`ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ ${issue3.expected} ប៉ុន្តែទទួលបាន ${parsedType6(issue3.input)}`;case"invalid_value":if(issue3.values.length===1)return`ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ ${stringifyPrimitive2(issue3.values[0])}`;return`ជម្រើសមិនត្រឹមត្រូវ៖ ត្រូវជាមួយក្នុងចំណោម ${joinValues2(issue3.values,"|")}`;case"too_big":{let adj=issue3.inclusive?"<=":"<",sizing=getSizing(issue3.origin);if(sizing)return`ធំពេក៖ ត្រូវការ ${issue3.origin??"តម្លៃ"} ${adj} ${issue3.maximum.toString()} ${sizing.unit??"ធាតុ"}`;return`ធំពេក៖ ត្រូវការ ${issue3.origin??"តម្លៃ"} ${adj} ${issue3.maximum.toString()}`}case"too_small":{let adj=issue3.inclusive?">=":">",sizing=getSizing(issue3.origin);if(sizing)return`តូចពេក៖ ត្រូវការ ${issue3.origin} ${adj} ${issue3.minimum.toString()} ${sizing.unit}`;return`តូចពេក៖ ត្រូវការ ${issue3.origin} ${adj} ${issue3.minimum.toString()}`}case"invalid_format":{let _issue=issue3;if(_issue.format==="starts_with")return`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវចាប់ផ្តើមដោយ "${_issue.prefix}"`;if(_issue.format==="ends_with")return`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវបញ្ចប់ដោយ "${_issue.suffix}"`;if(_issue.format==="includes")return`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវមាន "${_issue.includes}"`;if(_issue.format==="regex")return`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវតែផ្គូផ្គងនឹងទម្រង់ដែលបានកំណត់ ${_issue.pattern}`;return`មិនត្រឹមត្រូវ៖ ${Nouns[_issue.format]??issue3.format}`}case"not_multiple_of":return`លេខមិនត្រឹមត្រូវ៖ ត្រូវតែជាពហុគុណនៃ ${issue3.divisor}`;case"unrecognized_keys":return`រកឃើញសោមិនស្គាល់៖ ${joinValues2(issue3.keys,", ")}`;case"invalid_key":return`សោមិនត្រឹមត្រូវនៅក្នុង ${issue3.origin}`;case"invalid_union":return"ទិន្នន័យមិនត្រឹមត្រូវ";case"invalid_element":return`ទិន្នន័យមិនត្រឹមត្រូវនៅក្នុង ${issue3.origin}`;default:return"ទិន្នន័យមិនត្រឹមត្រូវ"}}};var init_km2=__esm(()=>{init_util2()});function kh_default2(){return km_default2()}var init_kh2=__esm(()=>{init_km2()});function ko_default2(){return{localeError:error71()}}var error71=()=>{let Sizable={string:{unit:"문자",verb:"to have"},file:{unit:"바이트",verb:"to have"},array:{unit:"개",verb:"to have"},set:{unit:"개",verb:"to have"}};function getSizing(origin){return Sizable[origin]??null}let parsedType6=(data)=>{let t=typeof data;switch(t){case"number":return Number.isNaN(data)?"NaN":"number";case"object":{if(Array.isArray(data))return"array";if(data===null)return"null";if(Object.getPrototypeOf(data)!==Object.prototype&&data.constructor)return data.constructor.name}}return t},Nouns={regex:"입력",email:"이메일 주소",url:"URL",emoji:"이모지",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO 날짜시간",date:"ISO 날짜",time:"ISO 시간",duration:"ISO 기간",ipv4:"IPv4 주소",ipv6:"IPv6 주소",cidrv4:"IPv4 범위",cidrv6:"IPv6 범위",base64:"base64 인코딩 문자열",base64url:"base64url 인코딩 문자열",json_string:"JSON 문자열",e164:"E.164 번호",jwt:"JWT",template_literal:"입력"};return(issue3)=>{switch(issue3.code){case"invalid_type":return`잘못된 입력: 예상 타입은 ${issue3.expected}, 받은 타입은 ${parsedType6(issue3.input)}입니다`;case"invalid_value":if(issue3.values.length===1)return`잘못된 입력: 값은 ${stringifyPrimitive2(issue3.values[0])} 이어야 합니다`;return`잘못된 옵션: ${joinValues2(issue3.values,"또는 ")} 중 하나여야 합니다`;case"too_big":{let adj=issue3.inclusive?"이하":"미만",suffix=adj==="미만"?"이어야 합니다":"여야 합니다",sizing=getSizing(issue3.origin),unit=sizing?.unit??"요소";if(sizing)return`${issue3.origin??"값"}이 너무 큽니다: ${issue3.maximum.toString()}${unit} ${adj}${suffix}`;return`${issue3.origin??"값"}이 너무 큽니다: ${issue3.maximum.toString()} ${adj}${suffix}`}case"too_small":{let adj=issue3.inclusive?"이상":"초과",suffix=adj==="이상"?"이어야 합니다":"여야 합니다",sizing=getSizing(issue3.origin),unit=sizing?.unit??"요소";if(sizing)return`${issue3.origin??"값"}이 너무 작습니다: ${issue3.minimum.toString()}${unit} ${adj}${suffix}`;return`${issue3.origin??"값"}이 너무 작습니다: ${issue3.minimum.toString()} ${adj}${suffix}`}case"invalid_format":{let _issue=issue3;if(_issue.format==="starts_with")return`잘못된 문자열: "${_issue.prefix}"(으)로 시작해야 합니다`;if(_issue.format==="ends_with")return`잘못된 문자열: "${_issue.suffix}"(으)로 끝나야 합니다`;if(_issue.format==="includes")return`잘못된 문자열: "${_issue.includes}"을(를) 포함해야 합니다`;if(_issue.format==="regex")return`잘못된 문자열: 정규식 ${_issue.pattern} 패턴과 일치해야 합니다`;return`잘못된 ${Nouns[_issue.format]??issue3.format}`}case"not_multiple_of":return`잘못된 숫자: ${issue3.divisor}의 배수여야 합니다`;case"unrecognized_keys":return`인식할 수 없는 키: ${joinValues2(issue3.keys,", ")}`;case"invalid_key":return`잘못된 키: ${issue3.origin}`;case"invalid_union":return"잘못된 입력";case"invalid_element":return`잘못된 값: ${issue3.origin}`;default:return"잘못된 입력"}}};var init_ko2=__esm(()=>{init_util2()});function getUnitTypeFromNumber2(number5){let abs=Math.abs(number5),last=abs%10,last2=abs%100;if(last2>=11&&last2<=19||last===0)return"many";if(last===1)return"one";return"few"}function lt_default2(){return{localeError:error72()}}var parsedType6=(data)=>{return parsedTypeFromType(typeof data,data)},parsedTypeFromType=(t,data=void 0)=>{switch(t){case"number":return Number.isNaN(data)?"NaN":"skaičius";case"bigint":return"sveikasis skaičius";case"string":return"eilutė";case"boolean":return"loginė reikšmė";case"undefined":case"void":return"neapibrėžta reikšmė";case"function":return"funkcija";case"symbol":return"simbolis";case"object":{if(data===void 0)return"nežinomas objektas";if(data===null)return"nulinė reikšmė";if(Array.isArray(data))return"masyvas";if(Object.getPrototypeOf(data)!==Object.prototype&&data.constructor)return data.constructor.name;return"objektas"}case"null":return"nulinė reikšmė"}return t},capitalizeFirstCharacter2=(text)=>{return text.charAt(0).toUpperCase()+text.slice(1)},error72=()=>{let Sizable={string:{unit:{one:"simbolis",few:"simboliai",many:"simbolių"},verb:{smaller:{inclusive:"turi būti ne ilgesnė kaip",notInclusive:"turi būti trumpesnė kaip"},bigger:{inclusive:"turi būti ne trumpesnė kaip",notInclusive:"turi būti ilgesnė kaip"}}},file:{unit:{one:"baitas",few:"baitai",many:"baitų"},verb:{smaller:{inclusive:"turi būti ne didesnis kaip",notInclusive:"turi būti mažesnis kaip"},bigger:{inclusive:"turi būti ne mažesnis kaip",notInclusive:"turi būti didesnis kaip"}}},array:{unit:{one:"elementą",few:"elementus",many:"elementų"},verb:{smaller:{inclusive:"turi turėti ne daugiau kaip",notInclusive:"turi turėti mažiau kaip"},bigger:{inclusive:"turi turėti ne mažiau kaip",notInclusive:"turi turėti daugiau kaip"}}},set:{unit:{one:"elementą",few:"elementus",many:"elementų"},verb:{smaller:{inclusive:"turi turėti ne daugiau kaip",notInclusive:"turi turėti mažiau kaip"},bigger:{inclusive:"turi turėti ne mažiau kaip",notInclusive:"turi turėti daugiau kaip"}}}};function getSizing(origin,unitType,inclusive,targetShouldBe){let result=Sizable[origin]??null;if(result===null)return result;return{unit:result.unit[unitType],verb:result.verb[targetShouldBe][inclusive?"inclusive":"notInclusive"]}}let Nouns={regex:"įvestis",email:"el. pašto adresas",url:"URL",emoji:"jaustukas",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO data ir laikas",date:"ISO data",time:"ISO laikas",duration:"ISO trukmė",ipv4:"IPv4 adresas",ipv6:"IPv6 adresas",cidrv4:"IPv4 tinklo prefiksas (CIDR)",cidrv6:"IPv6 tinklo prefiksas (CIDR)",base64:"base64 užkoduota eilutė",base64url:"base64url užkoduota eilutė",json_string:"JSON eilutė",e164:"E.164 numeris",jwt:"JWT",template_literal:"įvestis"};return(issue3)=>{switch(issue3.code){case"invalid_type":return`Gautas tipas ${parsedType6(issue3.input)}, o tikėtasi - ${parsedTypeFromType(issue3.expected)}`;case"invalid_value":if(issue3.values.length===1)return`Privalo būti ${stringifyPrimitive2(issue3.values[0])}`;return`Privalo būti vienas iš ${joinValues2(issue3.values,"|")} pasirinkimų`;case"too_big":{let origin=parsedTypeFromType(issue3.origin),sizing=getSizing(issue3.origin,getUnitTypeFromNumber2(Number(issue3.maximum)),issue3.inclusive??!1,"smaller");if(sizing?.verb)return`${capitalizeFirstCharacter2(origin??issue3.origin??"reikšmė")} ${sizing.verb} ${issue3.maximum.toString()} ${sizing.unit??"elementų"}`;let adj=issue3.inclusive?"ne didesnis kaip":"mažesnis kaip";return`${capitalizeFirstCharacter2(origin??issue3.origin??"reikšmė")} turi būti ${adj} ${issue3.maximum.toString()} ${sizing?.unit}`}case"too_small":{let origin=parsedTypeFromType(issue3.origin),sizing=getSizing(issue3.origin,getUnitTypeFromNumber2(Number(issue3.minimum)),issue3.inclusive??!1,"bigger");if(sizing?.verb)return`${capitalizeFirstCharacter2(origin??issue3.origin??"reikšmė")} ${sizing.verb} ${issue3.minimum.toString()} ${sizing.unit??"elementų"}`;let adj=issue3.inclusive?"ne mažesnis kaip":"didesnis kaip";return`${capitalizeFirstCharacter2(origin??issue3.origin??"reikšmė")} turi būti ${adj} ${issue3.minimum.toString()} ${sizing?.unit}`}case"invalid_format":{let _issue=issue3;if(_issue.format==="starts_with")return`Eilutė privalo prasidėti "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Eilutė privalo pasibaigti "${_issue.suffix}"`;if(_issue.format==="includes")return`Eilutė privalo įtraukti "${_issue.includes}"`;if(_issue.format==="regex")return`Eilutė privalo atitikti ${_issue.pattern}`;return`Neteisingas ${Nouns[_issue.format]??issue3.format}`}case"not_multiple_of":return`Skaičius privalo būti ${issue3.divisor} kartotinis.`;case"unrecognized_keys":return`Neatpažint${issue3.keys.length>1?"i":"as"} rakt${issue3.keys.length>1?"ai":"as"}: ${joinValues2(issue3.keys,", ")}`;case"invalid_key":return"Rastas klaidingas raktas";case"invalid_union":return"Klaidinga įvestis";case"invalid_element":{let origin=parsedTypeFromType(issue3.origin);return`${capitalizeFirstCharacter2(origin??issue3.origin??"reikšmė")} turi klaidingą įvestį`}default:return"Klaidinga įvestis"}}};var init_lt2=__esm(()=>{init_util2()});function mk_default2(){return{localeError:error73()}}var error73=()=>{let Sizable={string:{unit:"знаци",verb:"да имаат"},file:{unit:"бајти",verb:"да имаат"},array:{unit:"ставки",verb:"да имаат"},set:{unit:"ставки",verb:"да имаат"}};function getSizing(origin){return Sizable[origin]??null}let parsedType7=(data)=>{let t=typeof data;switch(t){case"number":return Number.isNaN(data)?"NaN":"број";case"object":{if(Array.isArray(data))return"низа";if(data===null)return"null";if(Object.getPrototypeOf(data)!==Object.prototype&&data.constructor)return data.constructor.name}}return t},Nouns={regex:"внес",email:"адреса на е-пошта",url:"URL",emoji:"емоџи",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO датум и време",date:"ISO датум",time:"ISO време",duration:"ISO времетраење",ipv4:"IPv4 адреса",ipv6:"IPv6 адреса",cidrv4:"IPv4 опсег",cidrv6:"IPv6 опсег",base64:"base64-енкодирана низа",base64url:"base64url-енкодирана низа",json_string:"JSON низа",e164:"E.164 број",jwt:"JWT",template_literal:"внес"};return(issue3)=>{switch(issue3.code){case"invalid_type":return`Грешен внес: се очекува ${issue3.expected}, примено ${parsedType7(issue3.input)}`;case"invalid_value":if(issue3.values.length===1)return`Invalid input: expected ${stringifyPrimitive2(issue3.values[0])}`;return`Грешана опција: се очекува една ${joinValues2(issue3.values,"|")}`;case"too_big":{let adj=issue3.inclusive?"<=":"<",sizing=getSizing(issue3.origin);if(sizing)return`Премногу голем: се очекува ${issue3.origin??"вредноста"} да има ${adj}${issue3.maximum.toString()} ${sizing.unit??"елементи"}`;return`Премногу голем: се очекува ${issue3.origin??"вредноста"} да биде ${adj}${issue3.maximum.toString()}`}case"too_small":{let adj=issue3.inclusive?">=":">",sizing=getSizing(issue3.origin);if(sizing)return`Премногу мал: се очекува ${issue3.origin} да има ${adj}${issue3.minimum.toString()} ${sizing.unit}`;return`Премногу мал: се очекува ${issue3.origin} да биде ${adj}${issue3.minimum.toString()}`}case"invalid_format":{let _issue=issue3;if(_issue.format==="starts_with")return`Неважечка низа: мора да започнува со "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Неважечка низа: мора да завршува со "${_issue.suffix}"`;if(_issue.format==="includes")return`Неважечка низа: мора да вклучува "${_issue.includes}"`;if(_issue.format==="regex")return`Неважечка низа: мора да одгоара на патернот ${_issue.pattern}`;return`Invalid ${Nouns[_issue.format]??issue3.format}`}case"not_multiple_of":return`Грешен број: мора да биде делив со ${issue3.divisor}`;case"unrecognized_keys":return`${issue3.keys.length>1?"Непрепознаени клучеви":"Непрепознаен клуч"}: ${joinValues2(issue3.keys,", ")}`;case"invalid_key":return`Грешен клуч во ${issue3.origin}`;case"invalid_union":return"Грешен внес";case"invalid_element":return`Грешна вредност во ${issue3.origin}`;default:return"Грешен внес"}}};var init_mk2=__esm(()=>{init_util2()});function ms_default2(){return{localeError:error74()}}var error74=()=>{let Sizable={string:{unit:"aksara",verb:"mempunyai"},file:{unit:"bait",verb:"mempunyai"},array:{unit:"elemen",verb:"mempunyai"},set:{unit:"elemen",verb:"mempunyai"}};function getSizing(origin){return Sizable[origin]??null}let parsedType7=(data)=>{let t=typeof data;switch(t){case"number":return Number.isNaN(data)?"NaN":"nombor";case"object":{if(Array.isArray(data))return"array";if(data===null)return"null";if(Object.getPrototypeOf(data)!==Object.prototype&&data.constructor)return data.constructor.name}}return t},Nouns={regex:"input",email:"alamat e-mel",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"tarikh masa ISO",date:"tarikh ISO",time:"masa ISO",duration:"tempoh ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"julat IPv4",cidrv6:"julat IPv6",base64:"string dikodkan base64",base64url:"string dikodkan base64url",json_string:"string JSON",e164:"nombor E.164",jwt:"JWT",template_literal:"input"};return(issue3)=>{switch(issue3.code){case"invalid_type":return`Input tidak sah: dijangka ${issue3.expected}, diterima ${parsedType7(issue3.input)}`;case"invalid_value":if(issue3.values.length===1)return`Input tidak sah: dijangka ${stringifyPrimitive2(issue3.values[0])}`;return`Pilihan tidak sah: dijangka salah satu daripada ${joinValues2(issue3.values,"|")}`;case"too_big":{let adj=issue3.inclusive?"<=":"<",sizing=getSizing(issue3.origin);if(sizing)return`Terlalu besar: dijangka ${issue3.origin??"nilai"} ${sizing.verb} ${adj}${issue3.maximum.toString()} ${sizing.unit??"elemen"}`;return`Terlalu besar: dijangka ${issue3.origin??"nilai"} adalah ${adj}${issue3.maximum.toString()}`}case"too_small":{let adj=issue3.inclusive?">=":">",sizing=getSizing(issue3.origin);if(sizing)return`Terlalu kecil: dijangka ${issue3.origin} ${sizing.verb} ${adj}${issue3.minimum.toString()} ${sizing.unit}`;return`Terlalu kecil: dijangka ${issue3.origin} adalah ${adj}${issue3.minimum.toString()}`}case"invalid_format":{let _issue=issue3;if(_issue.format==="starts_with")return`String tidak sah: mesti bermula dengan "${_issue.prefix}"`;if(_issue.format==="ends_with")return`String tidak sah: mesti berakhir dengan "${_issue.suffix}"`;if(_issue.format==="includes")return`String tidak sah: mesti mengandungi "${_issue.includes}"`;if(_issue.format==="regex")return`String tidak sah: mesti sepadan dengan corak ${_issue.pattern}`;return`${Nouns[_issue.format]??issue3.format} tidak sah`}case"not_multiple_of":return`Nombor tidak sah: perlu gandaan ${issue3.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali: ${joinValues2(issue3.keys,", ")}`;case"invalid_key":return`Kunci tidak sah dalam ${issue3.origin}`;case"invalid_union":return"Input tidak sah";case"invalid_element":return`Nilai tidak sah dalam ${issue3.origin}`;default:return"Input tidak sah"}}};var init_ms2=__esm(()=>{init_util2()});function nl_default2(){return{localeError:error75()}}var error75=()=>{let Sizable={string:{unit:"tekens"},file:{unit:"bytes"},array:{unit:"elementen"},set:{unit:"elementen"}};function getSizing(origin){return Sizable[origin]??null}let parsedType7=(data)=>{let t=typeof data;switch(t){case"number":return Number.isNaN(data)?"NaN":"getal";case"object":{if(Array.isArray(data))return"array";if(data===null)return"null";if(Object.getPrototypeOf(data)!==Object.prototype&&data.constructor)return data.constructor.name}}return t},Nouns={regex:"invoer",email:"emailadres",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum en tijd",date:"ISO datum",time:"ISO tijd",duration:"ISO duur",ipv4:"IPv4-adres",ipv6:"IPv6-adres",cidrv4:"IPv4-bereik",cidrv6:"IPv6-bereik",base64:"base64-gecodeerde tekst",base64url:"base64 URL-gecodeerde tekst",json_string:"JSON string",e164:"E.164-nummer",jwt:"JWT",template_literal:"invoer"};return(issue3)=>{switch(issue3.code){case"invalid_type":return`Ongeldige invoer: verwacht ${issue3.expected}, ontving ${parsedType7(issue3.input)}`;case"invalid_value":if(issue3.values.length===1)return`Ongeldige invoer: verwacht ${stringifyPrimitive2(issue3.values[0])}`;return`Ongeldige optie: verwacht één van ${joinValues2(issue3.values,"|")}`;case"too_big":{let adj=issue3.inclusive?"<=":"<",sizing=getSizing(issue3.origin);if(sizing)return`Te lang: verwacht dat ${issue3.origin??"waarde"} ${adj}${issue3.maximum.toString()} ${sizing.unit??"elementen"} bevat`;return`Te lang: verwacht dat ${issue3.origin??"waarde"} ${adj}${issue3.maximum.toString()} is`}case"too_small":{let adj=issue3.inclusive?">=":">",sizing=getSizing(issue3.origin);if(sizing)return`Te kort: verwacht dat ${issue3.origin} ${adj}${issue3.minimum.toString()} ${sizing.unit} bevat`;return`Te kort: verwacht dat ${issue3.origin} ${adj}${issue3.minimum.toString()} is`}case"invalid_format":{let _issue=issue3;if(_issue.format==="starts_with")return`Ongeldige tekst: moet met "${_issue.prefix}" beginnen`;if(_issue.format==="ends_with")return`Ongeldige tekst: moet op "${_issue.suffix}" eindigen`;if(_issue.format==="includes")return`Ongeldige tekst: moet "${_issue.includes}" bevatten`;if(_issue.format==="regex")return`Ongeldige tekst: moet overeenkomen met patroon ${_issue.pattern}`;return`Ongeldig: ${Nouns[_issue.format]??issue3.format}`}case"not_multiple_of":return`Ongeldig getal: moet een veelvoud van ${issue3.divisor} zijn`;case"unrecognized_keys":return`Onbekende key${issue3.keys.length>1?"s":""}: ${joinValues2(issue3.keys,", ")}`;case"invalid_key":return`Ongeldige key in ${issue3.origin}`;case"invalid_union":return"Ongeldige invoer";case"invalid_element":return`Ongeldige waarde in ${issue3.origin}`;default:return"Ongeldige invoer"}}};var init_nl2=__esm(()=>{init_util2()});function no_default2(){return{localeError:error76()}}var error76=()=>{let Sizable={string:{unit:"tegn",verb:"å ha"},file:{unit:"bytes",verb:"å ha"},array:{unit:"elementer",verb:"å inneholde"},set:{unit:"elementer",verb:"å inneholde"}};function getSizing(origin){return Sizable[origin]??null}let parsedType7=(data)=>{let t=typeof data;switch(t){case"number":return Number.isNaN(data)?"NaN":"tall";case"object":{if(Array.isArray(data))return"liste";if(data===null)return"null";if(Object.getPrototypeOf(data)!==Object.prototype&&data.constructor)return data.constructor.name}}return t},Nouns={regex:"input",email:"e-postadresse",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dato- og klokkeslett",date:"ISO-dato",time:"ISO-klokkeslett",duration:"ISO-varighet",ipv4:"IPv4-område",ipv6:"IPv6-område",cidrv4:"IPv4-spekter",cidrv6:"IPv6-spekter",base64:"base64-enkodet streng",base64url:"base64url-enkodet streng",json_string:"JSON-streng",e164:"E.164-nummer",jwt:"JWT",template_literal:"input"};return(issue3)=>{switch(issue3.code){case"invalid_type":return`Ugyldig input: forventet ${issue3.expected}, fikk ${parsedType7(issue3.input)}`;case"invalid_value":if(issue3.values.length===1)return`Ugyldig verdi: forventet ${stringifyPrimitive2(issue3.values[0])}`;return`Ugyldig valg: forventet en av ${joinValues2(issue3.values,"|")}`;case"too_big":{let adj=issue3.inclusive?"<=":"<",sizing=getSizing(issue3.origin);if(sizing)return`For stor(t): forventet ${issue3.origin??"value"} til å ha ${adj}${issue3.maximum.toString()} ${sizing.unit??"elementer"}`;return`For stor(t): forventet ${issue3.origin??"value"} til å ha ${adj}${issue3.maximum.toString()}`}case"too_small":{let adj=issue3.inclusive?">=":">",sizing=getSizing(issue3.origin);if(sizing)return`For lite(n): forventet ${issue3.origin} til å ha ${adj}${issue3.minimum.toString()} ${sizing.unit}`;return`For lite(n): forventet ${issue3.origin} til å ha ${adj}${issue3.minimum.toString()}`}case"invalid_format":{let _issue=issue3;if(_issue.format==="starts_with")return`Ugyldig streng: må starte med "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Ugyldig streng: må ende med "${_issue.suffix}"`;if(_issue.format==="includes")return`Ugyldig streng: må inneholde "${_issue.includes}"`;if(_issue.format==="regex")return`Ugyldig streng: må matche mønsteret ${_issue.pattern}`;return`Ugyldig ${Nouns[_issue.format]??issue3.format}`}case"not_multiple_of":return`Ugyldig tall: må være et multiplum av ${issue3.divisor}`;case"unrecognized_keys":return`${issue3.keys.length>1?"Ukjente nøkler":"Ukjent nøkkel"}: ${joinValues2(issue3.keys,", ")}`;case"invalid_key":return`Ugyldig nøkkel i ${issue3.origin}`;case"invalid_union":return"Ugyldig input";case"invalid_element":return`Ugyldig verdi i ${issue3.origin}`;default:return"Ugyldig input"}}};var init_no2=__esm(()=>{init_util2()});function ota_default2(){return{localeError:error77()}}var error77=()=>{let Sizable={string:{unit:"harf",verb:"olmalıdır"},file:{unit:"bayt",verb:"olmalıdır"},array:{unit:"unsur",verb:"olmalıdır"},set:{unit:"unsur",verb:"olmalıdır"}};function getSizing(origin){return Sizable[origin]??null}let parsedType7=(data)=>{let t=typeof data;switch(t){case"number":return Number.isNaN(data)?"NaN":"numara";case"object":{if(Array.isArray(data))return"saf";if(data===null)return"gayb";if(Object.getPrototypeOf(data)!==Object.prototype&&data.constructor)return data.constructor.name}}return t},Nouns={regex:"giren",email:"epostagâh",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO hengâmı",date:"ISO tarihi",time:"ISO zamanı",duration:"ISO müddeti",ipv4:"IPv4 nişânı",ipv6:"IPv6 nişânı",cidrv4:"IPv4 menzili",cidrv6:"IPv6 menzili",base64:"base64-şifreli metin",base64url:"base64url-şifreli metin",json_string:"JSON metin",e164:"E.164 sayısı",jwt:"JWT",template_literal:"giren"};return(issue3)=>{switch(issue3.code){case"invalid_type":return`Fâsit giren: umulan ${issue3.expected}, alınan ${parsedType7(issue3.input)}`;case"invalid_value":if(issue3.values.length===1)return`Fâsit giren: umulan ${stringifyPrimitive2(issue3.values[0])}`;return`Fâsit tercih: mûteberler ${joinValues2(issue3.values,"|")}`;case"too_big":{let adj=issue3.inclusive?"<=":"<",sizing=getSizing(issue3.origin);if(sizing)return`Fazla büyük: ${issue3.origin??"value"}, ${adj}${issue3.maximum.toString()} ${sizing.unit??"elements"} sahip olmalıydı.`;return`Fazla büyük: ${issue3.origin??"value"}, ${adj}${issue3.maximum.toString()} olmalıydı.`}case"too_small":{let adj=issue3.inclusive?">=":">",sizing=getSizing(issue3.origin);if(sizing)return`Fazla küçük: ${issue3.origin}, ${adj}${issue3.minimum.toString()} ${sizing.unit} sahip olmalıydı.`;return`Fazla küçük: ${issue3.origin}, ${adj}${issue3.minimum.toString()} olmalıydı.`}case"invalid_format":{let _issue=issue3;if(_issue.format==="starts_with")return`Fâsit metin: "${_issue.prefix}" ile başlamalı.`;if(_issue.format==="ends_with")return`Fâsit metin: "${_issue.suffix}" ile bitmeli.`;if(_issue.format==="includes")return`Fâsit metin: "${_issue.includes}" ihtivâ etmeli.`;if(_issue.format==="regex")return`Fâsit metin: ${_issue.pattern} nakşına uymalı.`;return`Fâsit ${Nouns[_issue.format]??issue3.format}`}case"not_multiple_of":return`Fâsit sayı: ${issue3.divisor} katı olmalıydı.`;case"unrecognized_keys":return`Tanınmayan anahtar ${issue3.keys.length>1?"s":""}: ${joinValues2(issue3.keys,", ")}`;case"invalid_key":return`${issue3.origin} için tanınmayan anahtar var.`;case"invalid_union":return"Giren tanınamadı.";case"invalid_element":return`${issue3.origin} için tanınmayan kıymet var.`;default:return"Kıymet tanınamadı."}}};var init_ota2=__esm(()=>{init_util2()});function ps_default2(){return{localeError:error78()}}var error78=()=>{let Sizable={string:{unit:"توکي",verb:"ولري"},file:{unit:"بایټس",verb:"ولري"},array:{unit:"توکي",verb:"ولري"},set:{unit:"توکي",verb:"ولري"}};function getSizing(origin){return Sizable[origin]??null}let parsedType7=(data)=>{let t=typeof data;switch(t){case"number":return Number.isNaN(data)?"NaN":"عدد";case"object":{if(Array.isArray(data))return"ارې";if(data===null)return"null";if(Object.getPrototypeOf(data)!==Object.prototype&&data.constructor)return data.constructor.name}}return t},Nouns={regex:"ورودي",email:"بریښنالیک",url:"یو آر ال",emoji:"ایموجي",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"نیټه او وخت",date:"نېټه",time:"وخت",duration:"موده",ipv4:"د IPv4 پته",ipv6:"د IPv6 پته",cidrv4:"د IPv4 ساحه",cidrv6:"د IPv6 ساحه",base64:"base64-encoded متن",base64url:"base64url-encoded متن",json_string:"JSON متن",e164:"د E.164 شمېره",jwt:"JWT",template_literal:"ورودي"};return(issue3)=>{switch(issue3.code){case"invalid_type":return`ناسم ورودي: باید ${issue3.expected} وای, مګر ${parsedType7(issue3.input)} ترلاسه شو`;case"invalid_value":if(issue3.values.length===1)return`ناسم ورودي: باید ${stringifyPrimitive2(issue3.values[0])} وای`;return`ناسم انتخاب: باید یو له ${joinValues2(issue3.values,"|")} څخه وای`;case"too_big":{let adj=issue3.inclusive?"<=":"<",sizing=getSizing(issue3.origin);if(sizing)return`ډیر لوی: ${issue3.origin??"ارزښت"} باید ${adj}${issue3.maximum.toString()} ${sizing.unit??"عنصرونه"} ولري`;return`ډیر لوی: ${issue3.origin??"ارزښت"} باید ${adj}${issue3.maximum.toString()} وي`}case"too_small":{let adj=issue3.inclusive?">=":">",sizing=getSizing(issue3.origin);if(sizing)return`ډیر کوچنی: ${issue3.origin} باید ${adj}${issue3.minimum.toString()} ${sizing.unit} ولري`;return`ډیر کوچنی: ${issue3.origin} باید ${adj}${issue3.minimum.toString()} وي`}case"invalid_format":{let _issue=issue3;if(_issue.format==="starts_with")return`ناسم متن: باید د "${_issue.prefix}" سره پیل شي`;if(_issue.format==="ends_with")return`ناسم متن: باید د "${_issue.suffix}" سره پای ته ورسيږي`;if(_issue.format==="includes")return`ناسم متن: باید "${_issue.includes}" ولري`;if(_issue.format==="regex")return`ناسم متن: باید د ${_issue.pattern} سره مطابقت ولري`;return`${Nouns[_issue.format]??issue3.format} ناسم دی`}case"not_multiple_of":return`ناسم عدد: باید د ${issue3.divisor} مضرب وي`;case"unrecognized_keys":return`ناسم ${issue3.keys.length>1?"کلیډونه":"کلیډ"}: ${joinValues2(issue3.keys,", ")}`;case"invalid_key":return`ناسم کلیډ په ${issue3.origin} کې`;case"invalid_union":return"ناسمه ورودي";case"invalid_element":return`ناسم عنصر په ${issue3.origin} کې`;default:return"ناسمه ورودي"}}};var init_ps2=__esm(()=>{init_util2()});function pl_default2(){return{localeError:error79()}}var error79=()=>{let Sizable={string:{unit:"znaków",verb:"mieć"},file:{unit:"bajtów",verb:"mieć"},array:{unit:"elementów",verb:"mieć"},set:{unit:"elementów",verb:"mieć"}};function getSizing(origin){return Sizable[origin]??null}let parsedType7=(data)=>{let t=typeof data;switch(t){case"number":return Number.isNaN(data)?"NaN":"liczba";case"object":{if(Array.isArray(data))return"tablica";if(data===null)return"null";if(Object.getPrototypeOf(data)!==Object.prototype&&data.constructor)return data.constructor.name}}return t},Nouns={regex:"wyrażenie",email:"adres email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data i godzina w formacie ISO",date:"data w formacie ISO",time:"godzina w formacie ISO",duration:"czas trwania ISO",ipv4:"adres IPv4",ipv6:"adres IPv6",cidrv4:"zakres IPv4",cidrv6:"zakres IPv6",base64:"ciąg znaków zakodowany w formacie base64",base64url:"ciąg znaków zakodowany w formacie base64url",json_string:"ciąg znaków w formacie JSON",e164:"liczba E.164",jwt:"JWT",template_literal:"wejście"};return(issue3)=>{switch(issue3.code){case"invalid_type":return`Nieprawidłowe dane wejściowe: oczekiwano ${issue3.expected}, otrzymano ${parsedType7(issue3.input)}`;case"invalid_value":if(issue3.values.length===1)return`Nieprawidłowe dane wejściowe: oczekiwano ${stringifyPrimitive2(issue3.values[0])}`;return`Nieprawidłowa opcja: oczekiwano jednej z wartości ${joinValues2(issue3.values,"|")}`;case"too_big":{let adj=issue3.inclusive?"<=":"<",sizing=getSizing(issue3.origin);if(sizing)return`Za duża wartość: oczekiwano, że ${issue3.origin??"wartość"} będzie mieć ${adj}${issue3.maximum.toString()} ${sizing.unit??"elementów"}`;return`Zbyt duż(y/a/e): oczekiwano, że ${issue3.origin??"wartość"} będzie wynosić ${adj}${issue3.maximum.toString()}`}case"too_small":{let adj=issue3.inclusive?">=":">",sizing=getSizing(issue3.origin);if(sizing)return`Za mała wartość: oczekiwano, że ${issue3.origin??"wartość"} będzie mieć ${adj}${issue3.minimum.toString()} ${sizing.unit??"elementów"}`;return`Zbyt mał(y/a/e): oczekiwano, że ${issue3.origin??"wartość"} będzie wynosić ${adj}${issue3.minimum.toString()}`}case"invalid_format":{let _issue=issue3;if(_issue.format==="starts_with")return`Nieprawidłowy ciąg znaków: musi zaczynać się od "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Nieprawidłowy ciąg znaków: musi kończyć się na "${_issue.suffix}"`;if(_issue.format==="includes")return`Nieprawidłowy ciąg znaków: musi zawierać "${_issue.includes}"`;if(_issue.format==="regex")return`Nieprawidłowy ciąg znaków: musi odpowiadać wzorcowi ${_issue.pattern}`;return`Nieprawidłow(y/a/e) ${Nouns[_issue.format]??issue3.format}`}case"not_multiple_of":return`Nieprawidłowa liczba: musi być wielokrotnością ${issue3.divisor}`;case"unrecognized_keys":return`Nierozpoznane klucze${issue3.keys.length>1?"s":""}: ${joinValues2(issue3.keys,", ")}`;case"invalid_key":return`Nieprawidłowy klucz w ${issue3.origin}`;case"invalid_union":return"Nieprawidłowe dane wejściowe";case"invalid_element":return`Nieprawidłowa wartość w ${issue3.origin}`;default:return"Nieprawidłowe dane wejściowe"}}};var init_pl2=__esm(()=>{init_util2()});function pt_default2(){return{localeError:error80()}}var error80=()=>{let Sizable={string:{unit:"caracteres",verb:"ter"},file:{unit:"bytes",verb:"ter"},array:{unit:"itens",verb:"ter"},set:{unit:"itens",verb:"ter"}};function getSizing(origin){return Sizable[origin]??null}let parsedType7=(data)=>{let t=typeof data;switch(t){case"number":return Number.isNaN(data)?"NaN":"número";case"object":{if(Array.isArray(data))return"array";if(data===null)return"nulo";if(Object.getPrototypeOf(data)!==Object.prototype&&data.constructor)return data.constructor.name}}return t},Nouns={regex:"padrão",email:"endereço de e-mail",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data e hora ISO",date:"data ISO",time:"hora ISO",duration:"duração ISO",ipv4:"endereço IPv4",ipv6:"endereço IPv6",cidrv4:"faixa de IPv4",cidrv6:"faixa de IPv6",base64:"texto codificado em base64",base64url:"URL codificada em base64",json_string:"texto JSON",e164:"número E.164",jwt:"JWT",template_literal:"entrada"};return(issue3)=>{switch(issue3.code){case"invalid_type":return`Tipo inválido: esperado ${issue3.expected}, recebido ${parsedType7(issue3.input)}`;case"invalid_value":if(issue3.values.length===1)return`Entrada inválida: esperado ${stringifyPrimitive2(issue3.values[0])}`;return`Opção inválida: esperada uma das ${joinValues2(issue3.values,"|")}`;case"too_big":{let adj=issue3.inclusive?"<=":"<",sizing=getSizing(issue3.origin);if(sizing)return`Muito grande: esperado que ${issue3.origin??"valor"} tivesse ${adj}${issue3.maximum.toString()} ${sizing.unit??"elementos"}`;return`Muito grande: esperado que ${issue3.origin??"valor"} fosse ${adj}${issue3.maximum.toString()}`}case"too_small":{let adj=issue3.inclusive?">=":">",sizing=getSizing(issue3.origin);if(sizing)return`Muito pequeno: esperado que ${issue3.origin} tivesse ${adj}${issue3.minimum.toString()} ${sizing.unit}`;return`Muito pequeno: esperado que ${issue3.origin} fosse ${adj}${issue3.minimum.toString()}`}case"invalid_format":{let _issue=issue3;if(_issue.format==="starts_with")return`Texto inválido: deve começar com "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Texto inválido: deve terminar com "${_issue.suffix}"`;if(_issue.format==="includes")return`Texto inválido: deve incluir "${_issue.includes}"`;if(_issue.format==="regex")return`Texto inválido: deve corresponder ao padrão ${_issue.pattern}`;return`${Nouns[_issue.format]??issue3.format} inválido`}case"not_multiple_of":return`Número inválido: deve ser múltiplo de ${issue3.divisor}`;case"unrecognized_keys":return`Chave${issue3.keys.length>1?"s":""} desconhecida${issue3.keys.length>1?"s":""}: ${joinValues2(issue3.keys,", ")}`;case"invalid_key":return`Chave inválida em ${issue3.origin}`;case"invalid_union":return"Entrada inválida";case"invalid_element":return`Valor inválido em ${issue3.origin}`;default:return"Campo inválido"}}};var init_pt2=__esm(()=>{init_util2()});function getRussianPlural2(count2,one,few,many){let absCount=Math.abs(count2),lastDigit=absCount%10,lastTwoDigits=absCount%100;if(lastTwoDigits>=11&&lastTwoDigits<=19)return many;if(lastDigit===1)return one;if(lastDigit>=2&&lastDigit<=4)return few;return many}function ru_default2(){return{localeError:error81()}}var error81=()=>{let Sizable={string:{unit:{one:"символ",few:"символа",many:"символов"},verb:"иметь"},file:{unit:{one:"байт",few:"байта",many:"байт"},verb:"иметь"},array:{unit:{one:"элемент",few:"элемента",many:"элементов"},verb:"иметь"},set:{unit:{one:"элемент",few:"элемента",many:"элементов"},verb:"иметь"}};function getSizing(origin){return Sizable[origin]??null}let parsedType7=(data)=>{let t=typeof data;switch(t){case"number":return Number.isNaN(data)?"NaN":"число";case"object":{if(Array.isArray(data))return"массив";if(data===null)return"null";if(Object.getPrototypeOf(data)!==Object.prototype&&data.constructor)return data.constructor.name}}return t},Nouns={regex:"ввод",email:"email адрес",url:"URL",emoji:"эмодзи",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO дата и время",date:"ISO дата",time:"ISO время",duration:"ISO длительность",ipv4:"IPv4 адрес",ipv6:"IPv6 адрес",cidrv4:"IPv4 диапазон",cidrv6:"IPv6 диапазон",base64:"строка в формате base64",base64url:"строка в формате base64url",json_string:"JSON строка",e164:"номер E.164",jwt:"JWT",template_literal:"ввод"};return(issue3)=>{switch(issue3.code){case"invalid_type":return`Неверный ввод: ожидалось ${issue3.expected}, получено ${parsedType7(issue3.input)}`;case"invalid_value":if(issue3.values.length===1)return`Неверный ввод: ожидалось ${stringifyPrimitive2(issue3.values[0])}`;return`Неверный вариант: ожидалось одно из ${joinValues2(issue3.values,"|")}`;case"too_big":{let adj=issue3.inclusive?"<=":"<",sizing=getSizing(issue3.origin);if(sizing){let maxValue=Number(issue3.maximum),unit=getRussianPlural2(maxValue,sizing.unit.one,sizing.unit.few,sizing.unit.many);return`Слишком большое значение: ожидалось, что ${issue3.origin??"значение"} будет иметь ${adj}${issue3.maximum.toString()} ${unit}`}return`Слишком большое значение: ожидалось, что ${issue3.origin??"значение"} будет ${adj}${issue3.maximum.toString()}`}case"too_small":{let adj=issue3.inclusive?">=":">",sizing=getSizing(issue3.origin);if(sizing){let minValue=Number(issue3.minimum),unit=getRussianPlural2(minValue,sizing.unit.one,sizing.unit.few,sizing.unit.many);return`Слишком маленькое значение: ожидалось, что ${issue3.origin} будет иметь ${adj}${issue3.minimum.toString()} ${unit}`}return`Слишком маленькое значение: ожидалось, что ${issue3.origin} будет ${adj}${issue3.minimum.toString()}`}case"invalid_format":{let _issue=issue3;if(_issue.format==="starts_with")return`Неверная строка: должна начинаться с "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Неверная строка: должна заканчиваться на "${_issue.suffix}"`;if(_issue.format==="includes")return`Неверная строка: должна содержать "${_issue.includes}"`;if(_issue.format==="regex")return`Неверная строка: должна соответствовать шаблону ${_issue.pattern}`;return`Неверный ${Nouns[_issue.format]??issue3.format}`}case"not_multiple_of":return`Неверное число: должно быть кратным ${issue3.divisor}`;case"unrecognized_keys":return`Нераспознанн${issue3.keys.length>1?"ые":"ый"} ключ${issue3.keys.length>1?"и":""}: ${joinValues2(issue3.keys,", ")}`;case"invalid_key":return`Неверный ключ в ${issue3.origin}`;case"invalid_union":return"Неверные входные данные";case"invalid_element":return`Неверное значение в ${issue3.origin}`;default:return"Неверные входные данные"}}};var init_ru2=__esm(()=>{init_util2()});function sl_default2(){return{localeError:error82()}}var error82=()=>{let Sizable={string:{unit:"znakov",verb:"imeti"},file:{unit:"bajtov",verb:"imeti"},array:{unit:"elementov",verb:"imeti"},set:{unit:"elementov",verb:"imeti"}};function getSizing(origin){return Sizable[origin]??null}let parsedType7=(data)=>{let t=typeof data;switch(t){case"number":return Number.isNaN(data)?"NaN":"število";case"object":{if(Array.isArray(data))return"tabela";if(data===null)return"null";if(Object.getPrototypeOf(data)!==Object.prototype&&data.constructor)return data.constructor.name}}return t},Nouns={regex:"vnos",email:"e-poštni naslov",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum in čas",date:"ISO datum",time:"ISO čas",duration:"ISO trajanje",ipv4:"IPv4 naslov",ipv6:"IPv6 naslov",cidrv4:"obseg IPv4",cidrv6:"obseg IPv6",base64:"base64 kodiran niz",base64url:"base64url kodiran niz",json_string:"JSON niz",e164:"E.164 številka",jwt:"JWT",template_literal:"vnos"};return(issue3)=>{switch(issue3.code){case"invalid_type":return`Neveljaven vnos: pričakovano ${issue3.expected}, prejeto ${parsedType7(issue3.input)}`;case"invalid_value":if(issue3.values.length===1)return`Neveljaven vnos: pričakovano ${stringifyPrimitive2(issue3.values[0])}`;return`Neveljavna možnost: pričakovano eno izmed ${joinValues2(issue3.values,"|")}`;case"too_big":{let adj=issue3.inclusive?"<=":"<",sizing=getSizing(issue3.origin);if(sizing)return`Preveliko: pričakovano, da bo ${issue3.origin??"vrednost"} imelo ${adj}${issue3.maximum.toString()} ${sizing.unit??"elementov"}`;return`Preveliko: pričakovano, da bo ${issue3.origin??"vrednost"} ${adj}${issue3.maximum.toString()}`}case"too_small":{let adj=issue3.inclusive?">=":">",sizing=getSizing(issue3.origin);if(sizing)return`Premajhno: pričakovano, da bo ${issue3.origin} imelo ${adj}${issue3.minimum.toString()} ${sizing.unit}`;return`Premajhno: pričakovano, da bo ${issue3.origin} ${adj}${issue3.minimum.toString()}`}case"invalid_format":{let _issue=issue3;if(_issue.format==="starts_with")return`Neveljaven niz: mora se začeti z "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Neveljaven niz: mora se končati z "${_issue.suffix}"`;if(_issue.format==="includes")return`Neveljaven niz: mora vsebovati "${_issue.includes}"`;if(_issue.format==="regex")return`Neveljaven niz: mora ustrezati vzorcu ${_issue.pattern}`;return`Neveljaven ${Nouns[_issue.format]??issue3.format}`}case"not_multiple_of":return`Neveljavno število: mora biti večkratnik ${issue3.divisor}`;case"unrecognized_keys":return`Neprepoznan${issue3.keys.length>1?"i ključi":" ključ"}: ${joinValues2(issue3.keys,", ")}`;case"invalid_key":return`Neveljaven ključ v ${issue3.origin}`;case"invalid_union":return"Neveljaven vnos";case"invalid_element":return`Neveljavna vrednost v ${issue3.origin}`;default:return"Neveljaven vnos"}}};var init_sl2=__esm(()=>{init_util2()});function sv_default2(){return{localeError:error83()}}var error83=()=>{let Sizable={string:{unit:"tecken",verb:"att ha"},file:{unit:"bytes",verb:"att ha"},array:{unit:"objekt",verb:"att innehålla"},set:{unit:"objekt",verb:"att innehålla"}};function getSizing(origin){return Sizable[origin]??null}let parsedType7=(data)=>{let t=typeof data;switch(t){case"number":return Number.isNaN(data)?"NaN":"antal";case"object":{if(Array.isArray(data))return"lista";if(data===null)return"null";if(Object.getPrototypeOf(data)!==Object.prototype&&data.constructor)return data.constructor.name}}return t},Nouns={regex:"reguljärt uttryck",email:"e-postadress",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-datum och tid",date:"ISO-datum",time:"ISO-tid",duration:"ISO-varaktighet",ipv4:"IPv4-intervall",ipv6:"IPv6-intervall",cidrv4:"IPv4-spektrum",cidrv6:"IPv6-spektrum",base64:"base64-kodad sträng",base64url:"base64url-kodad sträng",json_string:"JSON-sträng",e164:"E.164-nummer",jwt:"JWT",template_literal:"mall-literal"};return(issue3)=>{switch(issue3.code){case"invalid_type":return`Ogiltig inmatning: förväntat ${issue3.expected}, fick ${parsedType7(issue3.input)}`;case"invalid_value":if(issue3.values.length===1)return`Ogiltig inmatning: förväntat ${stringifyPrimitive2(issue3.values[0])}`;return`Ogiltigt val: förväntade en av ${joinValues2(issue3.values,"|")}`;case"too_big":{let adj=issue3.inclusive?"<=":"<",sizing=getSizing(issue3.origin);if(sizing)return`För stor(t): förväntade ${issue3.origin??"värdet"} att ha ${adj}${issue3.maximum.toString()} ${sizing.unit??"element"}`;return`För stor(t): förväntat ${issue3.origin??"värdet"} att ha ${adj}${issue3.maximum.toString()}`}case"too_small":{let adj=issue3.inclusive?">=":">",sizing=getSizing(issue3.origin);if(sizing)return`För lite(t): förväntade ${issue3.origin??"värdet"} att ha ${adj}${issue3.minimum.toString()} ${sizing.unit}`;return`För lite(t): förväntade ${issue3.origin??"värdet"} att ha ${adj}${issue3.minimum.toString()}`}case"invalid_format":{let _issue=issue3;if(_issue.format==="starts_with")return`Ogiltig sträng: måste börja med "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Ogiltig sträng: måste sluta med "${_issue.suffix}"`;if(_issue.format==="includes")return`Ogiltig sträng: måste innehålla "${_issue.includes}"`;if(_issue.format==="regex")return`Ogiltig sträng: måste matcha mönstret "${_issue.pattern}"`;return`Ogiltig(t) ${Nouns[_issue.format]??issue3.format}`}case"not_multiple_of":return`Ogiltigt tal: måste vara en multipel av ${issue3.divisor}`;case"unrecognized_keys":return`${issue3.keys.length>1?"Okända nycklar":"Okänd nyckel"}: ${joinValues2(issue3.keys,", ")}`;case"invalid_key":return`Ogiltig nyckel i ${issue3.origin??"värdet"}`;case"invalid_union":return"Ogiltig input";case"invalid_element":return`Ogiltigt värde i ${issue3.origin??"värdet"}`;default:return"Ogiltig input"}}};var init_sv2=__esm(()=>{init_util2()});function ta_default2(){return{localeError:error84()}}var error84=()=>{let Sizable={string:{unit:"எழுத்துக்கள்",verb:"கொண்டிருக்க வேண்டும்"},file:{unit:"பைட்டுகள்",verb:"கொண்டிருக்க வேண்டும்"},array:{unit:"உறுப்புகள்",verb:"கொண்டிருக்க வேண்டும்"},set:{unit:"உறுப்புகள்",verb:"கொண்டிருக்க வேண்டும்"}};function getSizing(origin){return Sizable[origin]??null}let parsedType7=(data)=>{let t=typeof data;switch(t){case"number":return Number.isNaN(data)?"எண் அல்லாதது":"எண்";case"object":{if(Array.isArray(data))return"அணி";if(data===null)return"வெறுமை";if(Object.getPrototypeOf(data)!==Object.prototype&&data.constructor)return data.constructor.name}}return t},Nouns={regex:"உள்ளீடு",email:"மின்னஞ்சல் முகவரி",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO தேதி நேரம்",date:"ISO தேதி",time:"ISO நேரம்",duration:"ISO கால அளவு",ipv4:"IPv4 முகவரி",ipv6:"IPv6 முகவரி",cidrv4:"IPv4 வரம்பு",cidrv6:"IPv6 வரம்பு",base64:"base64-encoded சரம்",base64url:"base64url-encoded சரம்",json_string:"JSON சரம்",e164:"E.164 எண்",jwt:"JWT",template_literal:"input"};return(issue3)=>{switch(issue3.code){case"invalid_type":return`தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது ${issue3.expected}, பெறப்பட்டது ${parsedType7(issue3.input)}`;case"invalid_value":if(issue3.values.length===1)return`தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது ${stringifyPrimitive2(issue3.values[0])}`;return`தவறான விருப்பம்: எதிர்பார்க்கப்பட்டது ${joinValues2(issue3.values,"|")} இல் ஒன்று`;case"too_big":{let adj=issue3.inclusive?"<=":"<",sizing=getSizing(issue3.origin);if(sizing)return`மிக பெரியது: எதிர்பார்க்கப்பட்டது ${issue3.origin??"மதிப்பு"} ${adj}${issue3.maximum.toString()} ${sizing.unit??"உறுப்புகள்"} ஆக இருக்க வேண்டும்`;return`மிக பெரியது: எதிர்பார்க்கப்பட்டது ${issue3.origin??"மதிப்பு"} ${adj}${issue3.maximum.toString()} ஆக இருக்க வேண்டும்`}case"too_small":{let adj=issue3.inclusive?">=":">",sizing=getSizing(issue3.origin);if(sizing)return`மிகச் சிறியது: எதிர்பார்க்கப்பட்டது ${issue3.origin} ${adj}${issue3.minimum.toString()} ${sizing.unit} ஆக இருக்க வேண்டும்`;return`மிகச் சிறியது: எதிர்பார்க்கப்பட்டது ${issue3.origin} ${adj}${issue3.minimum.toString()} ஆக இருக்க வேண்டும்`}case"invalid_format":{let _issue=issue3;if(_issue.format==="starts_with")return`தவறான சரம்: "${_issue.prefix}" இல் தொடங்க வேண்டும்`;if(_issue.format==="ends_with")return`தவறான சரம்: "${_issue.suffix}" இல் முடிவடைய வேண்டும்`;if(_issue.format==="includes")return`தவறான சரம்: "${_issue.includes}" ஐ உள்ளடக்க வேண்டும்`;if(_issue.format==="regex")return`தவறான சரம்: ${_issue.pattern} முறைபாட்டுடன் பொருந்த வேண்டும்`;return`தவறான ${Nouns[_issue.format]??issue3.format}`}case"not_multiple_of":return`தவறான எண்: ${issue3.divisor} இன் பலமாக இருக்க வேண்டும்`;case"unrecognized_keys":return`அடையாளம் தெரியாத விசை${issue3.keys.length>1?"கள்":""}: ${joinValues2(issue3.keys,", ")}`;case"invalid_key":return`${issue3.origin} இல் தவறான விசை`;case"invalid_union":return"தவறான உள்ளீடு";case"invalid_element":return`${issue3.origin} இல் தவறான மதிப்பு`;default:return"தவறான உள்ளீடு"}}};var init_ta2=__esm(()=>{init_util2()});function th_default2(){return{localeError:error85()}}var error85=()=>{let Sizable={string:{unit:"ตัวอักษร",verb:"ควรมี"},file:{unit:"ไบต์",verb:"ควรมี"},array:{unit:"รายการ",verb:"ควรมี"},set:{unit:"รายการ",verb:"ควรมี"}};function getSizing(origin){return Sizable[origin]??null}let parsedType7=(data)=>{let t=typeof data;switch(t){case"number":return Number.isNaN(data)?"ไม่ใช่ตัวเลข (NaN)":"ตัวเลข";case"object":{if(Array.isArray(data))return"อาร์เรย์ (Array)";if(data===null)return"ไม่มีค่า (null)";if(Object.getPrototypeOf(data)!==Object.prototype&&data.constructor)return data.constructor.name}}return t},Nouns={regex:"ข้อมูลที่ป้อน",email:"ที่อยู่อีเมล",url:"URL",emoji:"อิโมจิ",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"วันที่เวลาแบบ ISO",date:"วันที่แบบ ISO",time:"เวลาแบบ ISO",duration:"ช่วงเวลาแบบ ISO",ipv4:"ที่อยู่ IPv4",ipv6:"ที่อยู่ IPv6",cidrv4:"ช่วง IP แบบ IPv4",cidrv6:"ช่วง IP แบบ IPv6",base64:"ข้อความแบบ Base64",base64url:"ข้อความแบบ Base64 สำหรับ URL",json_string:"ข้อความแบบ JSON",e164:"เบอร์โทรศัพท์ระหว่างประเทศ (E.164)",jwt:"โทเคน JWT",template_literal:"ข้อมูลที่ป้อน"};return(issue3)=>{switch(issue3.code){case"invalid_type":return`ประเภทข้อมูลไม่ถูกต้อง: ควรเป็น ${issue3.expected} แต่ได้รับ ${parsedType7(issue3.input)}`;case"invalid_value":if(issue3.values.length===1)return`ค่าไม่ถูกต้อง: ควรเป็น ${stringifyPrimitive2(issue3.values[0])}`;return`ตัวเลือกไม่ถูกต้อง: ควรเป็นหนึ่งใน ${joinValues2(issue3.values,"|")}`;case"too_big":{let adj=issue3.inclusive?"ไม่เกิน":"น้อยกว่า",sizing=getSizing(issue3.origin);if(sizing)return`เกินกำหนด: ${issue3.origin??"ค่า"} ควรมี${adj} ${issue3.maximum.toString()} ${sizing.unit??"รายการ"}`;return`เกินกำหนด: ${issue3.origin??"ค่า"} ควรมี${adj} ${issue3.maximum.toString()}`}case"too_small":{let adj=issue3.inclusive?"อย่างน้อย":"มากกว่า",sizing=getSizing(issue3.origin);if(sizing)return`น้อยกว่ากำหนด: ${issue3.origin} ควรมี${adj} ${issue3.minimum.toString()} ${sizing.unit}`;return`น้อยกว่ากำหนด: ${issue3.origin} ควรมี${adj} ${issue3.minimum.toString()}`}case"invalid_format":{let _issue=issue3;if(_issue.format==="starts_with")return`รูปแบบไม่ถูกต้อง: ข้อความต้องขึ้นต้นด้วย "${_issue.prefix}"`;if(_issue.format==="ends_with")return`รูปแบบไม่ถูกต้อง: ข้อความต้องลงท้ายด้วย "${_issue.suffix}"`;if(_issue.format==="includes")return`รูปแบบไม่ถูกต้อง: ข้อความต้องมี "${_issue.includes}" อยู่ในข้อความ`;if(_issue.format==="regex")return`รูปแบบไม่ถูกต้อง: ต้องตรงกับรูปแบบที่กำหนด ${_issue.pattern}`;return`รูปแบบไม่ถูกต้อง: ${Nouns[_issue.format]??issue3.format}`}case"not_multiple_of":return`ตัวเลขไม่ถูกต้อง: ต้องเป็นจำนวนที่หารด้วย ${issue3.divisor} ได้ลงตัว`;case"unrecognized_keys":return`พบคีย์ที่ไม่รู้จัก: ${joinValues2(issue3.keys,", ")}`;case"invalid_key":return`คีย์ไม่ถูกต้องใน ${issue3.origin}`;case"invalid_union":return"ข้อมูลไม่ถูกต้อง: ไม่ตรงกับรูปแบบยูเนียนที่กำหนดไว้";case"invalid_element":return`ข้อมูลไม่ถูกต้องใน ${issue3.origin}`;default:return"ข้อมูลไม่ถูกต้อง"}}};var init_th2=__esm(()=>{init_util2()});function tr_default2(){return{localeError:error86()}}var parsedType7=(data)=>{let t=typeof data;switch(t){case"number":return Number.isNaN(data)?"NaN":"number";case"object":{if(Array.isArray(data))return"array";if(data===null)return"null";if(Object.getPrototypeOf(data)!==Object.prototype&&data.constructor)return data.constructor.name}}return t},error86=()=>{let Sizable={string:{unit:"karakter",verb:"olmalı"},file:{unit:"bayt",verb:"olmalı"},array:{unit:"öğe",verb:"olmalı"},set:{unit:"öğe",verb:"olmalı"}};function getSizing(origin){return Sizable[origin]??null}let Nouns={regex:"girdi",email:"e-posta adresi",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO tarih ve saat",date:"ISO tarih",time:"ISO saat",duration:"ISO süre",ipv4:"IPv4 adresi",ipv6:"IPv6 adresi",cidrv4:"IPv4 aralığı",cidrv6:"IPv6 aralığı",base64:"base64 ile şifrelenmiş metin",base64url:"base64url ile şifrelenmiş metin",json_string:"JSON dizesi",e164:"E.164 sayısı",jwt:"JWT",template_literal:"Şablon dizesi"};return(issue3)=>{switch(issue3.code){case"invalid_type":return`Geçersiz değer: beklenen ${issue3.expected}, alınan ${parsedType7(issue3.input)}`;case"invalid_value":if(issue3.values.length===1)return`Geçersiz değer: beklenen ${stringifyPrimitive2(issue3.values[0])}`;return`Geçersiz seçenek: aşağıdakilerden biri olmalı: ${joinValues2(issue3.values,"|")}`;case"too_big":{let adj=issue3.inclusive?"<=":"<",sizing=getSizing(issue3.origin);if(sizing)return`Çok büyük: beklenen ${issue3.origin??"değer"} ${adj}${issue3.maximum.toString()} ${sizing.unit??"öğe"}`;return`Çok büyük: beklenen ${issue3.origin??"değer"} ${adj}${issue3.maximum.toString()}`}case"too_small":{let adj=issue3.inclusive?">=":">",sizing=getSizing(issue3.origin);if(sizing)return`Çok küçük: beklenen ${issue3.origin} ${adj}${issue3.minimum.toString()} ${sizing.unit}`;return`Çok küçük: beklenen ${issue3.origin} ${adj}${issue3.minimum.toString()}`}case"invalid_format":{let _issue=issue3;if(_issue.format==="starts_with")return`Geçersiz metin: "${_issue.prefix}" ile başlamalı`;if(_issue.format==="ends_with")return`Geçersiz metin: "${_issue.suffix}" ile bitmeli`;if(_issue.format==="includes")return`Geçersiz metin: "${_issue.includes}" içermeli`;if(_issue.format==="regex")return`Geçersiz metin: ${_issue.pattern} desenine uymalı`;return`Geçersiz ${Nouns[_issue.format]??issue3.format}`}case"not_multiple_of":return`Geçersiz sayı: ${issue3.divisor} ile tam bölünebilmeli`;case"unrecognized_keys":return`Tanınmayan anahtar${issue3.keys.length>1?"lar":""}: ${joinValues2(issue3.keys,", ")}`;case"invalid_key":return`${issue3.origin} içinde geçersiz anahtar`;case"invalid_union":return"Geçersiz değer";case"invalid_element":return`${issue3.origin} içinde geçersiz değer`;default:return"Geçersiz değer"}}};var init_tr2=__esm(()=>{init_util2()});function uk_default2(){return{localeError:error87()}}var error87=()=>{let Sizable={string:{unit:"символів",verb:"матиме"},file:{unit:"байтів",verb:"матиме"},array:{unit:"елементів",verb:"матиме"},set:{unit:"елементів",verb:"матиме"}};function getSizing(origin){return Sizable[origin]??null}let parsedType8=(data)=>{let t=typeof data;switch(t){case"number":return Number.isNaN(data)?"NaN":"число";case"object":{if(Array.isArray(data))return"масив";if(data===null)return"null";if(Object.getPrototypeOf(data)!==Object.prototype&&data.constructor)return data.constructor.name}}return t},Nouns={regex:"вхідні дані",email:"адреса електронної пошти",url:"URL",emoji:"емодзі",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"дата та час ISO",date:"дата ISO",time:"час ISO",duration:"тривалість ISO",ipv4:"адреса IPv4",ipv6:"адреса IPv6",cidrv4:"діапазон IPv4",cidrv6:"діапазон IPv6",base64:"рядок у кодуванні base64",base64url:"рядок у кодуванні base64url",json_string:"рядок JSON",e164:"номер E.164",jwt:"JWT",template_literal:"вхідні дані"};return(issue3)=>{switch(issue3.code){case"invalid_type":return`Неправильні вхідні дані: очікується ${issue3.expected}, отримано ${parsedType8(issue3.input)}`;case"invalid_value":if(issue3.values.length===1)return`Неправильні вхідні дані: очікується ${stringifyPrimitive2(issue3.values[0])}`;return`Неправильна опція: очікується одне з ${joinValues2(issue3.values,"|")}`;case"too_big":{let adj=issue3.inclusive?"<=":"<",sizing=getSizing(issue3.origin);if(sizing)return`Занадто велике: очікується, що ${issue3.origin??"значення"} ${sizing.verb} ${adj}${issue3.maximum.toString()} ${sizing.unit??"елементів"}`;return`Занадто велике: очікується, що ${issue3.origin??"значення"} буде ${adj}${issue3.maximum.toString()}`}case"too_small":{let adj=issue3.inclusive?">=":">",sizing=getSizing(issue3.origin);if(sizing)return`Занадто мале: очікується, що ${issue3.origin} ${sizing.verb} ${adj}${issue3.minimum.toString()} ${sizing.unit}`;return`Занадто мале: очікується, що ${issue3.origin} буде ${adj}${issue3.minimum.toString()}`}case"invalid_format":{let _issue=issue3;if(_issue.format==="starts_with")return`Неправильний рядок: повинен починатися з "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Неправильний рядок: повинен закінчуватися на "${_issue.suffix}"`;if(_issue.format==="includes")return`Неправильний рядок: повинен містити "${_issue.includes}"`;if(_issue.format==="regex")return`Неправильний рядок: повинен відповідати шаблону ${_issue.pattern}`;return`Неправильний ${Nouns[_issue.format]??issue3.format}`}case"not_multiple_of":return`Неправильне число: повинно бути кратним ${issue3.divisor}`;case"unrecognized_keys":return`Нерозпізнаний ключ${issue3.keys.length>1?"і":""}: ${joinValues2(issue3.keys,", ")}`;case"invalid_key":return`Неправильний ключ у ${issue3.origin}`;case"invalid_union":return"Неправильні вхідні дані";case"invalid_element":return`Неправильне значення у ${issue3.origin}`;default:return"Неправильні вхідні дані"}}};var init_uk2=__esm(()=>{init_util2()});function ua_default2(){return uk_default2()}var init_ua2=__esm(()=>{init_uk2()});function ur_default2(){return{localeError:error88()}}var error88=()=>{let Sizable={string:{unit:"حروف",verb:"ہونا"},file:{unit:"بائٹس",verb:"ہونا"},array:{unit:"آئٹمز",verb:"ہونا"},set:{unit:"آئٹمز",verb:"ہونا"}};function getSizing(origin){return Sizable[origin]??null}let parsedType8=(data)=>{let t=typeof data;switch(t){case"number":return Number.isNaN(data)?"NaN":"نمبر";case"object":{if(Array.isArray(data))return"آرے";if(data===null)return"نل";if(Object.getPrototypeOf(data)!==Object.prototype&&data.constructor)return data.constructor.name}}return t},Nouns={regex:"ان پٹ",email:"ای میل ایڈریس",url:"یو آر ایل",emoji:"ایموجی",uuid:"یو یو آئی ڈی",uuidv4:"یو یو آئی ڈی وی 4",uuidv6:"یو یو آئی ڈی وی 6",nanoid:"نینو آئی ڈی",guid:"جی یو آئی ڈی",cuid:"سی یو آئی ڈی",cuid2:"سی یو آئی ڈی 2",ulid:"یو ایل آئی ڈی",xid:"ایکس آئی ڈی",ksuid:"کے ایس یو آئی ڈی",datetime:"آئی ایس او ڈیٹ ٹائم",date:"آئی ایس او تاریخ",time:"آئی ایس او وقت",duration:"آئی ایس او مدت",ipv4:"آئی پی وی 4 ایڈریس",ipv6:"آئی پی وی 6 ایڈریس",cidrv4:"آئی پی وی 4 رینج",cidrv6:"آئی پی وی 6 رینج",base64:"بیس 64 ان کوڈڈ سٹرنگ",base64url:"بیس 64 یو آر ایل ان کوڈڈ سٹرنگ",json_string:"جے ایس او این سٹرنگ",e164:"ای 164 نمبر",jwt:"جے ڈبلیو ٹی",template_literal:"ان پٹ"};return(issue3)=>{switch(issue3.code){case"invalid_type":return`غلط ان پٹ: ${issue3.expected} متوقع تھا، ${parsedType8(issue3.input)} موصول ہوا`;case"invalid_value":if(issue3.values.length===1)return`غلط ان پٹ: ${stringifyPrimitive2(issue3.values[0])} متوقع تھا`;return`غلط آپشن: ${joinValues2(issue3.values,"|")} میں سے ایک متوقع تھا`;case"too_big":{let adj=issue3.inclusive?"<=":"<",sizing=getSizing(issue3.origin);if(sizing)return`بہت بڑا: ${issue3.origin??"ویلیو"} کے ${adj}${issue3.maximum.toString()} ${sizing.unit??"عناصر"} ہونے متوقع تھے`;return`بہت بڑا: ${issue3.origin??"ویلیو"} کا ${adj}${issue3.maximum.toString()} ہونا متوقع تھا`}case"too_small":{let adj=issue3.inclusive?">=":">",sizing=getSizing(issue3.origin);if(sizing)return`بہت چھوٹا: ${issue3.origin} کے ${adj}${issue3.minimum.toString()} ${sizing.unit} ہونے متوقع تھے`;return`بہت چھوٹا: ${issue3.origin} کا ${adj}${issue3.minimum.toString()} ہونا متوقع تھا`}case"invalid_format":{let _issue=issue3;if(_issue.format==="starts_with")return`غلط سٹرنگ: "${_issue.prefix}" سے شروع ہونا چاہیے`;if(_issue.format==="ends_with")return`غلط سٹرنگ: "${_issue.suffix}" پر ختم ہونا چاہیے`;if(_issue.format==="includes")return`غلط سٹرنگ: "${_issue.includes}" شامل ہونا چاہیے`;if(_issue.format==="regex")return`غلط سٹرنگ: پیٹرن ${_issue.pattern} سے میچ ہونا چاہیے`;return`غلط ${Nouns[_issue.format]??issue3.format}`}case"not_multiple_of":return`غلط نمبر: ${issue3.divisor} کا مضاعف ہونا چاہیے`;case"unrecognized_keys":return`غیر تسلیم شدہ کی${issue3.keys.length>1?"ز":""}: ${joinValues2(issue3.keys,"، ")}`;case"invalid_key":return`${issue3.origin} میں غلط کی`;case"invalid_union":return"غلط ان پٹ";case"invalid_element":return`${issue3.origin} میں غلط ویلیو`;default:return"غلط ان پٹ"}}};var init_ur2=__esm(()=>{init_util2()});function vi_default2(){return{localeError:error89()}}var error89=()=>{let Sizable={string:{unit:"ký tự",verb:"có"},file:{unit:"byte",verb:"có"},array:{unit:"phần tử",verb:"có"},set:{unit:"phần tử",verb:"có"}};function getSizing(origin){return Sizable[origin]??null}let parsedType8=(data)=>{let t=typeof data;switch(t){case"number":return Number.isNaN(data)?"NaN":"số";case"object":{if(Array.isArray(data))return"mảng";if(data===null)return"null";if(Object.getPrototypeOf(data)!==Object.prototype&&data.constructor)return data.constructor.name}}return t},Nouns={regex:"đầu vào",email:"địa chỉ email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ngày giờ ISO",date:"ngày ISO",time:"giờ ISO",duration:"khoảng thời gian ISO",ipv4:"địa chỉ IPv4",ipv6:"địa chỉ IPv6",cidrv4:"dải IPv4",cidrv6:"dải IPv6",base64:"chuỗi mã hóa base64",base64url:"chuỗi mã hóa base64url",json_string:"chuỗi JSON",e164:"số E.164",jwt:"JWT",template_literal:"đầu vào"};return(issue3)=>{switch(issue3.code){case"invalid_type":return`Đầu vào không hợp lệ: mong đợi ${issue3.expected}, nhận được ${parsedType8(issue3.input)}`;case"invalid_value":if(issue3.values.length===1)return`Đầu vào không hợp lệ: mong đợi ${stringifyPrimitive2(issue3.values[0])}`;return`Tùy chọn không hợp lệ: mong đợi một trong các giá trị ${joinValues2(issue3.values,"|")}`;case"too_big":{let adj=issue3.inclusive?"<=":"<",sizing=getSizing(issue3.origin);if(sizing)return`Quá lớn: mong đợi ${issue3.origin??"giá trị"} ${sizing.verb} ${adj}${issue3.maximum.toString()} ${sizing.unit??"phần tử"}`;return`Quá lớn: mong đợi ${issue3.origin??"giá trị"} ${adj}${issue3.maximum.toString()}`}case"too_small":{let adj=issue3.inclusive?">=":">",sizing=getSizing(issue3.origin);if(sizing)return`Quá nhỏ: mong đợi ${issue3.origin} ${sizing.verb} ${adj}${issue3.minimum.toString()} ${sizing.unit}`;return`Quá nhỏ: mong đợi ${issue3.origin} ${adj}${issue3.minimum.toString()}`}case"invalid_format":{let _issue=issue3;if(_issue.format==="starts_with")return`Chuỗi không hợp lệ: phải bắt đầu bằng "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Chuỗi không hợp lệ: phải kết thúc bằng "${_issue.suffix}"`;if(_issue.format==="includes")return`Chuỗi không hợp lệ: phải bao gồm "${_issue.includes}"`;if(_issue.format==="regex")return`Chuỗi không hợp lệ: phải khớp với mẫu ${_issue.pattern}`;return`${Nouns[_issue.format]??issue3.format} không hợp lệ`}case"not_multiple_of":return`Số không hợp lệ: phải là bội số của ${issue3.divisor}`;case"unrecognized_keys":return`Khóa không được nhận dạng: ${joinValues2(issue3.keys,", ")}`;case"invalid_key":return`Khóa không hợp lệ trong ${issue3.origin}`;case"invalid_union":return"Đầu vào không hợp lệ";case"invalid_element":return`Giá trị không hợp lệ trong ${issue3.origin}`;default:return"Đầu vào không hợp lệ"}}};var init_vi2=__esm(()=>{init_util2()});function zh_CN_default2(){return{localeError:error90()}}var error90=()=>{let Sizable={string:{unit:"字符",verb:"包含"},file:{unit:"字节",verb:"包含"},array:{unit:"项",verb:"包含"},set:{unit:"项",verb:"包含"}};function getSizing(origin){return Sizable[origin]??null}let parsedType8=(data)=>{let t=typeof data;switch(t){case"number":return Number.isNaN(data)?"非数字(NaN)":"数字";case"object":{if(Array.isArray(data))return"数组";if(data===null)return"空值(null)";if(Object.getPrototypeOf(data)!==Object.prototype&&data.constructor)return data.constructor.name}}return t},Nouns={regex:"输入",email:"电子邮件",url:"URL",emoji:"表情符号",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO日期时间",date:"ISO日期",time:"ISO时间",duration:"ISO时长",ipv4:"IPv4地址",ipv6:"IPv6地址",cidrv4:"IPv4网段",cidrv6:"IPv6网段",base64:"base64编码字符串",base64url:"base64url编码字符串",json_string:"JSON字符串",e164:"E.164号码",jwt:"JWT",template_literal:"输入"};return(issue3)=>{switch(issue3.code){case"invalid_type":return`无效输入:期望 ${issue3.expected},实际接收 ${parsedType8(issue3.input)}`;case"invalid_value":if(issue3.values.length===1)return`无效输入:期望 ${stringifyPrimitive2(issue3.values[0])}`;return`无效选项:期望以下之一 ${joinValues2(issue3.values,"|")}`;case"too_big":{let adj=issue3.inclusive?"<=":"<",sizing=getSizing(issue3.origin);if(sizing)return`数值过大:期望 ${issue3.origin??"值"} ${adj}${issue3.maximum.toString()} ${sizing.unit??"个元素"}`;return`数值过大:期望 ${issue3.origin??"值"} ${adj}${issue3.maximum.toString()}`}case"too_small":{let adj=issue3.inclusive?">=":">",sizing=getSizing(issue3.origin);if(sizing)return`数值过小:期望 ${issue3.origin} ${adj}${issue3.minimum.toString()} ${sizing.unit}`;return`数值过小:期望 ${issue3.origin} ${adj}${issue3.minimum.toString()}`}case"invalid_format":{let _issue=issue3;if(_issue.format==="starts_with")return`无效字符串:必须以 "${_issue.prefix}" 开头`;if(_issue.format==="ends_with")return`无效字符串:必须以 "${_issue.suffix}" 结尾`;if(_issue.format==="includes")return`无效字符串:必须包含 "${_issue.includes}"`;if(_issue.format==="regex")return`无效字符串:必须满足正则表达式 ${_issue.pattern}`;return`无效${Nouns[_issue.format]??issue3.format}`}case"not_multiple_of":return`无效数字:必须是 ${issue3.divisor} 的倍数`;case"unrecognized_keys":return`出现未知的键(key): ${joinValues2(issue3.keys,", ")}`;case"invalid_key":return`${issue3.origin} 中的键(key)无效`;case"invalid_union":return"无效输入";case"invalid_element":return`${issue3.origin} 中包含无效值(value)`;default:return"无效输入"}}};var init_zh_CN2=__esm(()=>{init_util2()});function zh_TW_default2(){return{localeError:error91()}}var error91=()=>{let Sizable={string:{unit:"字元",verb:"擁有"},file:{unit:"位元組",verb:"擁有"},array:{unit:"項目",verb:"擁有"},set:{unit:"項目",verb:"擁有"}};function getSizing(origin){return Sizable[origin]??null}let parsedType8=(data)=>{let t=typeof data;switch(t){case"number":return Number.isNaN(data)?"NaN":"number";case"object":{if(Array.isArray(data))return"array";if(data===null)return"null";if(Object.getPrototypeOf(data)!==Object.prototype&&data.constructor)return data.constructor.name}}return t},Nouns={regex:"輸入",email:"郵件地址",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO 日期時間",date:"ISO 日期",time:"ISO 時間",duration:"ISO 期間",ipv4:"IPv4 位址",ipv6:"IPv6 位址",cidrv4:"IPv4 範圍",cidrv6:"IPv6 範圍",base64:"base64 編碼字串",base64url:"base64url 編碼字串",json_string:"JSON 字串",e164:"E.164 數值",jwt:"JWT",template_literal:"輸入"};return(issue3)=>{switch(issue3.code){case"invalid_type":return`無效的輸入值:預期為 ${issue3.expected},但收到 ${parsedType8(issue3.input)}`;case"invalid_value":if(issue3.values.length===1)return`無效的輸入值:預期為 ${stringifyPrimitive2(issue3.values[0])}`;return`無效的選項:預期為以下其中之一 ${joinValues2(issue3.values,"|")}`;case"too_big":{let adj=issue3.inclusive?"<=":"<",sizing=getSizing(issue3.origin);if(sizing)return`數值過大:預期 ${issue3.origin??"值"} 應為 ${adj}${issue3.maximum.toString()} ${sizing.unit??"個元素"}`;return`數值過大:預期 ${issue3.origin??"值"} 應為 ${adj}${issue3.maximum.toString()}`}case"too_small":{let adj=issue3.inclusive?">=":">",sizing=getSizing(issue3.origin);if(sizing)return`數值過小:預期 ${issue3.origin} 應為 ${adj}${issue3.minimum.toString()} ${sizing.unit}`;return`數值過小:預期 ${issue3.origin} 應為 ${adj}${issue3.minimum.toString()}`}case"invalid_format":{let _issue=issue3;if(_issue.format==="starts_with")return`無效的字串:必須以 "${_issue.prefix}" 開頭`;if(_issue.format==="ends_with")return`無效的字串:必須以 "${_issue.suffix}" 結尾`;if(_issue.format==="includes")return`無效的字串:必須包含 "${_issue.includes}"`;if(_issue.format==="regex")return`無效的字串:必須符合格式 ${_issue.pattern}`;return`無效的 ${Nouns[_issue.format]??issue3.format}`}case"not_multiple_of":return`無效的數字:必須為 ${issue3.divisor} 的倍數`;case"unrecognized_keys":return`無法識別的鍵值${issue3.keys.length>1?"們":""}:${joinValues2(issue3.keys,"、")}`;case"invalid_key":return`${issue3.origin} 中有無效的鍵值`;case"invalid_union":return"無效的輸入值";case"invalid_element":return`${issue3.origin} 中有無效的值`;default:return"無效的輸入值"}}};var init_zh_TW2=__esm(()=>{init_util2()});function yo_default2(){return{localeError:error92()}}var error92=()=>{let Sizable={string:{unit:"àmi",verb:"ní"},file:{unit:"bytes",verb:"ní"},array:{unit:"nkan",verb:"ní"},set:{unit:"nkan",verb:"ní"}};function getSizing(origin){return Sizable[origin]??null}let parsedType8=(data)=>{let t=typeof data;switch(t){case"number":return Number.isNaN(data)?"NaN":"nọ́mbà";case"object":{if(Array.isArray(data))return"akopọ";if(data===null)return"null";if(Object.getPrototypeOf(data)!==Object.prototype&&data.constructor)return data.constructor.name}}return t},Nouns={regex:"ẹ̀rọ ìbáwọlé",email:"àdírẹ́sì ìmẹ́lì",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"àkókò ISO",date:"ọjọ́ ISO",time:"àkókò ISO",duration:"àkókò tó pé ISO",ipv4:"àdírẹ́sì IPv4",ipv6:"àdírẹ́sì IPv6",cidrv4:"àgbègbè IPv4",cidrv6:"àgbègbè IPv6",base64:"ọ̀rọ̀ tí a kọ́ ní base64",base64url:"ọ̀rọ̀ base64url",json_string:"ọ̀rọ̀ JSON",e164:"nọ́mbà E.164",jwt:"JWT",template_literal:"ẹ̀rọ ìbáwọlé"};return(issue3)=>{switch(issue3.code){case"invalid_type":return`Ìbáwọlé aṣìṣe: a ní láti fi ${issue3.expected}, àmọ̀ a rí ${parsedType8(issue3.input)}`;case"invalid_value":if(issue3.values.length===1)return`Ìbáwọlé aṣìṣe: a ní láti fi ${stringifyPrimitive2(issue3.values[0])}`;return`Àṣàyàn aṣìṣe: yan ọ̀kan lára ${joinValues2(issue3.values,"|")}`;case"too_big":{let adj=issue3.inclusive?"<=":"<",sizing=getSizing(issue3.origin);if(sizing)return`Tó pọ̀ jù: a ní láti jẹ́ pé ${issue3.origin??"iye"} ${sizing.verb} ${adj}${issue3.maximum} ${sizing.unit}`;return`Tó pọ̀ jù: a ní láti jẹ́ ${adj}${issue3.maximum}`}case"too_small":{let adj=issue3.inclusive?">=":">",sizing=getSizing(issue3.origin);if(sizing)return`Kéré ju: a ní láti jẹ́ pé ${issue3.origin} ${sizing.verb} ${adj}${issue3.minimum} ${sizing.unit}`;return`Kéré ju: a ní láti jẹ́ ${adj}${issue3.minimum}`}case"invalid_format":{let _issue=issue3;if(_issue.format==="starts_with")return`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ bẹ̀rẹ̀ pẹ̀lú "${_issue.prefix}"`;if(_issue.format==="ends_with")return`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ parí pẹ̀lú "${_issue.suffix}"`;if(_issue.format==="includes")return`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ ní "${_issue.includes}"`;if(_issue.format==="regex")return`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ bá àpẹẹrẹ mu ${_issue.pattern}`;return`Aṣìṣe: ${Nouns[_issue.format]??issue3.format}`}case"not_multiple_of":return`Nọ́mbà aṣìṣe: gbọ́dọ̀ jẹ́ èyà pípín ti ${issue3.divisor}`;case"unrecognized_keys":return`Bọtìnì àìmọ̀: ${joinValues2(issue3.keys,", ")}`;case"invalid_key":return`Bọtìnì aṣìṣe nínú ${issue3.origin}`;case"invalid_union":return"Ìbáwọlé aṣìṣe";case"invalid_element":return`Iye aṣìṣe nínú ${issue3.origin}`;default:return"Ìbáwọlé aṣìṣe"}}};var init_yo2=__esm(()=>{init_util2()});var exports_locales2={};__export(exports_locales2,{zhTW:()=>zh_TW_default2,zhCN:()=>zh_CN_default2,yo:()=>yo_default2,vi:()=>vi_default2,ur:()=>ur_default2,uk:()=>uk_default2,ua:()=>ua_default2,tr:()=>tr_default2,th:()=>th_default2,ta:()=>ta_default2,sv:()=>sv_default2,sl:()=>sl_default2,ru:()=>ru_default2,pt:()=>pt_default2,ps:()=>ps_default2,pl:()=>pl_default2,ota:()=>ota_default2,no:()=>no_default2,nl:()=>nl_default2,ms:()=>ms_default2,mk:()=>mk_default2,lt:()=>lt_default2,ko:()=>ko_default2,km:()=>km_default2,kh:()=>kh_default2,ka:()=>ka_default2,ja:()=>ja_default2,it:()=>it_default2,is:()=>is_default2,id:()=>id_default2,hu:()=>hu_default2,he:()=>he_default2,frCA:()=>fr_CA_default2,fr:()=>fr_default2,fi:()=>fi_default2,fa:()=>fa_default2,es:()=>es_default2,eo:()=>eo_default2,en:()=>en_default2,de:()=>de_default2,da:()=>da_default2,cs:()=>cs_default2,ca:()=>ca_default2,be:()=>be_default2,az:()=>az_default2,ar:()=>ar_default2});var init_locales2=__esm(()=>{init_ar2();init_az2();init_be2();init_ca2();init_cs2();init_da2();init_de2();init_en2();init_eo2();init_es2();init_fa2();init_fi2();init_fr2();init_fr_CA2();init_he2();init_hu2();init_id2();init_is2();init_it2();init_ja2();init_ka2();init_kh2();init_km2();init_ko2();init_lt2();init_mk2();init_ms2();init_nl2();init_no2();init_ota2();init_ps2();init_pl2();init_pt2();init_ru2();init_sl2();init_sv2();init_ta2();init_th2();init_tr2();init_ua2();init_uk2();init_ur2();init_vi2();init_zh_CN2();init_zh_TW2();init_yo2()});class $ZodRegistry2{constructor(){this._map=new WeakMap,this._idmap=new Map}add(schema,..._meta){let meta3=_meta[0];if(this._map.set(schema,meta3),meta3&&typeof meta3==="object"&&"id"in meta3){if(this._idmap.has(meta3.id))throw Error(`ID ${meta3.id} already exists in the registry`);this._idmap.set(meta3.id,schema)}return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(schema){let meta3=this._map.get(schema);if(meta3&&typeof meta3==="object"&&"id"in meta3)this._idmap.delete(meta3.id);return this._map.delete(schema),this}get(schema){let p=schema._zod.parent;if(p){let pm={...this.get(p)??{}};delete pm.id;let f={...pm,...this._map.get(schema)};return Object.keys(f).length?f:void 0}return this._map.get(schema)}has(schema){return this._map.has(schema)}}function registry2(){return new $ZodRegistry2}var $output2,$input2,globalRegistry2;var init_registries2=__esm(()=>{$output2=Symbol("ZodOutput"),$input2=Symbol("ZodInput");globalRegistry2=registry2()});function _string2(Class3,params){return new Class3({type:"string",...normalizeParams2(params)})}function _coercedString2(Class3,params){return new Class3({type:"string",coerce:!0,...normalizeParams2(params)})}function _email2(Class3,params){return new Class3({type:"string",format:"email",check:"string_format",abort:!1,...normalizeParams2(params)})}function _guid2(Class3,params){return new Class3({type:"string",format:"guid",check:"string_format",abort:!1,...normalizeParams2(params)})}function _uuid2(Class3,params){return new Class3({type:"string",format:"uuid",check:"string_format",abort:!1,...normalizeParams2(params)})}function _uuidv42(Class3,params){return new Class3({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...normalizeParams2(params)})}function _uuidv62(Class3,params){return new Class3({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...normalizeParams2(params)})}function _uuidv72(Class3,params){return new Class3({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...normalizeParams2(params)})}function _url2(Class3,params){return new Class3({type:"string",format:"url",check:"string_format",abort:!1,...normalizeParams2(params)})}function _emoji3(Class3,params){return new Class3({type:"string",format:"emoji",check:"string_format",abort:!1,...normalizeParams2(params)})}function _nanoid2(Class3,params){return new Class3({type:"string",format:"nanoid",check:"string_format",abort:!1,...normalizeParams2(params)})}function _cuid3(Class3,params){return new Class3({type:"string",format:"cuid",check:"string_format",abort:!1,...normalizeParams2(params)})}function _cuid22(Class3,params){return new Class3({type:"string",format:"cuid2",check:"string_format",abort:!1,...normalizeParams2(params)})}function _ulid2(Class3,params){return new Class3({type:"string",format:"ulid",check:"string_format",abort:!1,...normalizeParams2(params)})}function _xid2(Class3,params){return new Class3({type:"string",format:"xid",check:"string_format",abort:!1,...normalizeParams2(params)})}function _ksuid2(Class3,params){return new Class3({type:"string",format:"ksuid",check:"string_format",abort:!1,...normalizeParams2(params)})}function _ipv42(Class3,params){return new Class3({type:"string",format:"ipv4",check:"string_format",abort:!1,...normalizeParams2(params)})}function _ipv62(Class3,params){return new Class3({type:"string",format:"ipv6",check:"string_format",abort:!1,...normalizeParams2(params)})}function _cidrv42(Class3,params){return new Class3({type:"string",format:"cidrv4",check:"string_format",abort:!1,...normalizeParams2(params)})}function _cidrv62(Class3,params){return new Class3({type:"string",format:"cidrv6",check:"string_format",abort:!1,...normalizeParams2(params)})}function _base642(Class3,params){return new Class3({type:"string",format:"base64",check:"string_format",abort:!1,...normalizeParams2(params)})}function _base64url2(Class3,params){return new Class3({type:"string",format:"base64url",check:"string_format",abort:!1,...normalizeParams2(params)})}function _e1642(Class3,params){return new Class3({type:"string",format:"e164",check:"string_format",abort:!1,...normalizeParams2(params)})}function _jwt2(Class3,params){return new Class3({type:"string",format:"jwt",check:"string_format",abort:!1,...normalizeParams2(params)})}function _isoDateTime2(Class3,params){return new Class3({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...normalizeParams2(params)})}function _isoDate2(Class3,params){return new Class3({type:"string",format:"date",check:"string_format",...normalizeParams2(params)})}function _isoTime2(Class3,params){return new Class3({type:"string",format:"time",check:"string_format",precision:null,...normalizeParams2(params)})}function _isoDuration2(Class3,params){return new Class3({type:"string",format:"duration",check:"string_format",...normalizeParams2(params)})}function _number2(Class3,params){return new Class3({type:"number",checks:[],...normalizeParams2(params)})}function _coercedNumber2(Class3,params){return new Class3({type:"number",coerce:!0,checks:[],...normalizeParams2(params)})}function _int2(Class3,params){return new Class3({type:"number",check:"number_format",abort:!1,format:"safeint",...normalizeParams2(params)})}function _float322(Class3,params){return new Class3({type:"number",check:"number_format",abort:!1,format:"float32",...normalizeParams2(params)})}function _float642(Class3,params){return new Class3({type:"number",check:"number_format",abort:!1,format:"float64",...normalizeParams2(params)})}function _int322(Class3,params){return new Class3({type:"number",check:"number_format",abort:!1,format:"int32",...normalizeParams2(params)})}function _uint322(Class3,params){return new Class3({type:"number",check:"number_format",abort:!1,format:"uint32",...normalizeParams2(params)})}function _boolean2(Class3,params){return new Class3({type:"boolean",...normalizeParams2(params)})}function _coercedBoolean2(Class3,params){return new Class3({type:"boolean",coerce:!0,...normalizeParams2(params)})}function _bigint2(Class3,params){return new Class3({type:"bigint",...normalizeParams2(params)})}function _coercedBigint2(Class3,params){return new Class3({type:"bigint",coerce:!0,...normalizeParams2(params)})}function _int642(Class3,params){return new Class3({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...normalizeParams2(params)})}function _uint642(Class3,params){return new Class3({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...normalizeParams2(params)})}function _symbol2(Class3,params){return new Class3({type:"symbol",...normalizeParams2(params)})}function _undefined5(Class3,params){return new Class3({type:"undefined",...normalizeParams2(params)})}function _null5(Class3,params){return new Class3({type:"null",...normalizeParams2(params)})}function _any2(Class3){return new Class3({type:"any"})}function _unknown2(Class3){return new Class3({type:"unknown"})}function _never2(Class3,params){return new Class3({type:"never",...normalizeParams2(params)})}function _void3(Class3,params){return new Class3({type:"void",...normalizeParams2(params)})}function _date2(Class3,params){return new Class3({type:"date",...normalizeParams2(params)})}function _coercedDate2(Class3,params){return new Class3({type:"date",coerce:!0,...normalizeParams2(params)})}function _nan2(Class3,params){return new Class3({type:"nan",...normalizeParams2(params)})}function _lt2(value,params){return new $ZodCheckLessThan2({check:"less_than",...normalizeParams2(params),value,inclusive:!1})}function _lte2(value,params){return new $ZodCheckLessThan2({check:"less_than",...normalizeParams2(params),value,inclusive:!0})}function _gt2(value,params){return new $ZodCheckGreaterThan2({check:"greater_than",...normalizeParams2(params),value,inclusive:!1})}function _gte2(value,params){return new $ZodCheckGreaterThan2({check:"greater_than",...normalizeParams2(params),value,inclusive:!0})}function _positive2(params){return _gt2(0,params)}function _negative2(params){return _lt2(0,params)}function _nonpositive2(params){return _lte2(0,params)}function _nonnegative2(params){return _gte2(0,params)}function _multipleOf2(value,params){return new $ZodCheckMultipleOf2({check:"multiple_of",...normalizeParams2(params),value})}function _maxSize2(maximum,params){return new $ZodCheckMaxSize2({check:"max_size",...normalizeParams2(params),maximum})}function _minSize2(minimum,params){return new $ZodCheckMinSize2({check:"min_size",...normalizeParams2(params),minimum})}function _size2(size,params){return new $ZodCheckSizeEquals2({check:"size_equals",...normalizeParams2(params),size})}function _maxLength2(maximum,params){return new $ZodCheckMaxLength2({check:"max_length",...normalizeParams2(params),maximum})}function _minLength2(minimum,params){return new $ZodCheckMinLength2({check:"min_length",...normalizeParams2(params),minimum})}function _length2(length,params){return new $ZodCheckLengthEquals2({check:"length_equals",...normalizeParams2(params),length})}function _regex2(pattern,params){return new $ZodCheckRegex2({check:"string_format",format:"regex",...normalizeParams2(params),pattern})}function _lowercase2(params){return new $ZodCheckLowerCase2({check:"string_format",format:"lowercase",...normalizeParams2(params)})}function _uppercase2(params){return new $ZodCheckUpperCase2({check:"string_format",format:"uppercase",...normalizeParams2(params)})}function _includes2(includes,params){return new $ZodCheckIncludes2({check:"string_format",format:"includes",...normalizeParams2(params),includes})}function _startsWith2(prefix,params){return new $ZodCheckStartsWith2({check:"string_format",format:"starts_with",...normalizeParams2(params),prefix})}function _endsWith2(suffix,params){return new $ZodCheckEndsWith2({check:"string_format",format:"ends_with",...normalizeParams2(params),suffix})}function _property2(property,schema,params){return new $ZodCheckProperty2({check:"property",property,schema,...normalizeParams2(params)})}function _mime2(types,params){return new $ZodCheckMimeType2({check:"mime_type",mime:types,...normalizeParams2(params)})}function _overwrite2(tx){return new $ZodCheckOverwrite2({check:"overwrite",tx})}function _normalize2(form){return _overwrite2((input)=>input.normalize(form))}function _trim2(){return _overwrite2((input)=>input.trim())}function _toLowerCase2(){return _overwrite2((input)=>input.toLowerCase())}function _toUpperCase2(){return _overwrite2((input)=>input.toUpperCase())}function _array2(Class3,element,params){return new Class3({type:"array",element,...normalizeParams2(params)})}function _union2(Class3,options,params){return new Class3({type:"union",options,...normalizeParams2(params)})}function _discriminatedUnion2(Class3,discriminator,options,params){return new Class3({type:"union",options,discriminator,...normalizeParams2(params)})}function _intersection2(Class3,left,right){return new Class3({type:"intersection",left,right})}function _tuple2(Class3,items,_paramsOrRest,_params){let hasRest=_paramsOrRest instanceof $ZodType2;return new Class3({type:"tuple",items,rest:hasRest?_paramsOrRest:null,...normalizeParams2(hasRest?_params:_paramsOrRest)})}function _record2(Class3,keyType,valueType,params){return new Class3({type:"record",keyType,valueType,...normalizeParams2(params)})}function _map2(Class3,keyType,valueType,params){return new Class3({type:"map",keyType,valueType,...normalizeParams2(params)})}function _set2(Class3,valueType,params){return new Class3({type:"set",valueType,...normalizeParams2(params)})}function _enum3(Class3,values,params){let entries=Array.isArray(values)?Object.fromEntries(values.map((v)=>[v,v])):values;return new Class3({type:"enum",entries,...normalizeParams2(params)})}function _nativeEnum2(Class3,entries,params){return new Class3({type:"enum",entries,...normalizeParams2(params)})}function _literal2(Class3,value,params){return new Class3({type:"literal",values:Array.isArray(value)?value:[value],...normalizeParams2(params)})}function _file2(Class3,params){return new Class3({type:"file",...normalizeParams2(params)})}function _transform2(Class3,fn2){return new Class3({type:"transform",transform:fn2})}function _optional2(Class3,innerType){return new Class3({type:"optional",innerType})}function _nullable2(Class3,innerType){return new Class3({type:"nullable",innerType})}function _default3(Class3,innerType,defaultValue){return new Class3({type:"default",innerType,get defaultValue(){return typeof defaultValue==="function"?defaultValue():shallowClone2(defaultValue)}})}function _nonoptional2(Class3,innerType,params){return new Class3({type:"nonoptional",innerType,...normalizeParams2(params)})}function _success2(Class3,innerType){return new Class3({type:"success",innerType})}function _catch3(Class3,innerType,catchValue){return new Class3({type:"catch",innerType,catchValue:typeof catchValue==="function"?catchValue:()=>catchValue})}function _pipe2(Class3,in_,out){return new Class3({type:"pipe",in:in_,out})}function _readonly2(Class3,innerType){return new Class3({type:"readonly",innerType})}function _templateLiteral2(Class3,parts,params){return new Class3({type:"template_literal",parts,...normalizeParams2(params)})}function _lazy2(Class3,getter){return new Class3({type:"lazy",getter})}function _promise2(Class3,innerType){return new Class3({type:"promise",innerType})}function _custom2(Class3,fn2,_params){let norm=normalizeParams2(_params);return norm.abort??(norm.abort=!0),new Class3({type:"custom",check:"custom",fn:fn2,...norm})}function _refine2(Class3,fn2,_params){return new Class3({type:"custom",check:"custom",fn:fn2,...normalizeParams2(_params)})}function _superRefine2(fn2){let ch=_check2((payload)=>{return payload.addIssue=(issue3)=>{if(typeof issue3==="string")payload.issues.push(issue2(issue3,payload.value,ch._zod.def));else{let _issue=issue3;if(_issue.fatal)_issue.continue=!1;_issue.code??(_issue.code="custom"),_issue.input??(_issue.input=payload.value),_issue.inst??(_issue.inst=ch),_issue.continue??(_issue.continue=!ch._zod.def.abort),payload.issues.push(issue2(_issue))}},fn2(payload.value,payload)});return ch}function _check2(fn2,params){let ch=new $ZodCheck2({check:"custom",...normalizeParams2(params)});return ch._zod.check=fn2,ch}function _stringbool2(Classes,_params){let params=normalizeParams2(_params),truthyArray=params.truthy??["true","1","yes","on","y","enabled"],falsyArray=params.falsy??["false","0","no","off","n","disabled"];if(params.case!=="sensitive")truthyArray=truthyArray.map((v)=>typeof v==="string"?v.toLowerCase():v),falsyArray=falsyArray.map((v)=>typeof v==="string"?v.toLowerCase():v);let truthySet=new Set(truthyArray),falsySet=new Set(falsyArray),_Codec=Classes.Codec??$ZodCodec2,_Boolean=Classes.Boolean??$ZodBoolean2,stringSchema=new(Classes.String??$ZodString2)({type:"string",error:params.error}),booleanSchema=new _Boolean({type:"boolean",error:params.error}),codec3=new _Codec({type:"pipe",in:stringSchema,out:booleanSchema,transform:(input,payload)=>{let data=input;if(params.case!=="sensitive")data=data.toLowerCase();if(truthySet.has(data))return!0;else if(falsySet.has(data))return!1;else return payload.issues.push({code:"invalid_value",expected:"stringbool",values:[...truthySet,...falsySet],input:payload.value,inst:codec3,continue:!1}),{}},reverseTransform:(input,_payload)=>{if(input===!0)return truthyArray[0]||"true";else return falsyArray[0]||"false"},error:params.error});return codec3}function _stringFormat2(Class3,format,fnOrRegex,_params={}){let params=normalizeParams2(_params),def={...normalizeParams2(_params),check:"string_format",type:"string",format,fn:typeof fnOrRegex==="function"?fnOrRegex:(val)=>fnOrRegex.test(val),...params};if(fnOrRegex instanceof RegExp)def.pattern=fnOrRegex;return new Class3(def)}var TimePrecision2;var init_api2=__esm(()=>{init_checks3();init_schemas3();init_util2();TimePrecision2={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6}});class JSONSchemaGenerator2{constructor(params){this.counter=0,this.metadataRegistry=params?.metadata??globalRegistry2,this.target=params?.target??"draft-2020-12",this.unrepresentable=params?.unrepresentable??"throw",this.override=params?.override??(()=>{}),this.io=params?.io??"output",this.seen=new Map}process(schema,_params={path:[],schemaPath:[]}){var _a2;let def=schema._zod.def,formatMap2={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},seen=this.seen.get(schema);if(seen){if(seen.count++,_params.schemaPath.includes(schema))seen.cycle=_params.path;return seen.schema}let result={schema:{},count:1,cycle:void 0,path:_params.path};this.seen.set(schema,result);let overrideSchema=schema._zod.toJSONSchema?.();if(overrideSchema)result.schema=overrideSchema;else{let params={..._params,schemaPath:[..._params.schemaPath,schema],path:_params.path},parent=schema._zod.parent;if(parent)result.ref=parent,this.process(parent,params),this.seen.get(parent).isParent=!0;else{let _json=result.schema;switch(def.type){case"string":{let json2=_json;json2.type="string";let{minimum,maximum,format,patterns,contentEncoding}=schema._zod.bag;if(typeof minimum==="number")json2.minLength=minimum;if(typeof maximum==="number")json2.maxLength=maximum;if(format){if(json2.format=formatMap2[format]??format,json2.format==="")delete json2.format}if(contentEncoding)json2.contentEncoding=contentEncoding;if(patterns&&patterns.size>0){let regexes=[...patterns];if(regexes.length===1)json2.pattern=regexes[0].source;else if(regexes.length>1)result.schema.allOf=[...regexes.map((regex)=>({...this.target==="draft-7"||this.target==="draft-4"||this.target==="openapi-3.0"?{type:"string"}:{},pattern:regex.source}))]}break}case"number":{let json2=_json,{minimum,maximum,format,multipleOf,exclusiveMaximum,exclusiveMinimum}=schema._zod.bag;if(typeof format==="string"&&format.includes("int"))json2.type="integer";else json2.type="number";if(typeof exclusiveMinimum==="number")if(this.target==="draft-4"||this.target==="openapi-3.0")json2.minimum=exclusiveMinimum,json2.exclusiveMinimum=!0;else json2.exclusiveMinimum=exclusiveMinimum;if(typeof minimum==="number"){if(json2.minimum=minimum,typeof exclusiveMinimum==="number"&&this.target!=="draft-4")if(exclusiveMinimum>=minimum)delete json2.minimum;else delete json2.exclusiveMinimum}if(typeof exclusiveMaximum==="number")if(this.target==="draft-4"||this.target==="openapi-3.0")json2.maximum=exclusiveMaximum,json2.exclusiveMaximum=!0;else json2.exclusiveMaximum=exclusiveMaximum;if(typeof maximum==="number"){if(json2.maximum=maximum,typeof exclusiveMaximum==="number"&&this.target!=="draft-4")if(exclusiveMaximum<=maximum)delete json2.maximum;else delete json2.exclusiveMaximum}if(typeof multipleOf==="number")json2.multipleOf=multipleOf;break}case"boolean":{let json2=_json;json2.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw Error("Symbols cannot be represented in JSON Schema");break}case"null":{if(this.target==="openapi-3.0")_json.type="string",_json.nullable=!0,_json.enum=[null];else _json.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw Error("Void cannot be represented in JSON Schema");break}case"never":{_json.not={};break}case"date":{if(this.unrepresentable==="throw")throw Error("Date cannot be represented in JSON Schema");break}case"array":{let json2=_json,{minimum,maximum}=schema._zod.bag;if(typeof minimum==="number")json2.minItems=minimum;if(typeof maximum==="number")json2.maxItems=maximum;json2.type="array",json2.items=this.process(def.element,{...params,path:[...params.path,"items"]});break}case"object":{let json2=_json;json2.type="object",json2.properties={};let shape=def.shape;for(let key in shape)json2.properties[key]=this.process(shape[key],{...params,path:[...params.path,"properties",key]});let allKeys=new Set(Object.keys(shape)),requiredKeys=new Set([...allKeys].filter((key)=>{let v=def.shape[key]._zod;if(this.io==="input")return v.optin===void 0;else return v.optout===void 0}));if(requiredKeys.size>0)json2.required=Array.from(requiredKeys);if(def.catchall?._zod.def.type==="never")json2.additionalProperties=!1;else if(!def.catchall){if(this.io==="output")json2.additionalProperties=!1}else if(def.catchall)json2.additionalProperties=this.process(def.catchall,{...params,path:[...params.path,"additionalProperties"]});break}case"union":{let json2=_json,options=def.options.map((x,i)=>this.process(x,{...params,path:[...params.path,"anyOf",i]}));json2.anyOf=options;break}case"intersection":{let json2=_json,a=this.process(def.left,{...params,path:[...params.path,"allOf",0]}),b=this.process(def.right,{...params,path:[...params.path,"allOf",1]}),isSimpleIntersection=(val)=>("allOf"in val)&&Object.keys(val).length===1,allOf=[...isSimpleIntersection(a)?a.allOf:[a],...isSimpleIntersection(b)?b.allOf:[b]];json2.allOf=allOf;break}case"tuple":{let json2=_json;json2.type="array";let prefixPath=this.target==="draft-2020-12"?"prefixItems":"items",restPath=this.target==="draft-2020-12"?"items":this.target==="openapi-3.0"?"items":"additionalItems",prefixItems=def.items.map((x,i)=>this.process(x,{...params,path:[...params.path,prefixPath,i]})),rest=def.rest?this.process(def.rest,{...params,path:[...params.path,restPath,...this.target==="openapi-3.0"?[def.items.length]:[]]}):null;if(this.target==="draft-2020-12"){if(json2.prefixItems=prefixItems,rest)json2.items=rest}else if(this.target==="openapi-3.0"){if(json2.items={anyOf:prefixItems},rest)json2.items.anyOf.push(rest);if(json2.minItems=prefixItems.length,!rest)json2.maxItems=prefixItems.length}else if(json2.items=prefixItems,rest)json2.additionalItems=rest;let{minimum,maximum}=schema._zod.bag;if(typeof minimum==="number")json2.minItems=minimum;if(typeof maximum==="number")json2.maxItems=maximum;break}case"record":{let json2=_json;if(json2.type="object",this.target==="draft-7"||this.target==="draft-2020-12")json2.propertyNames=this.process(def.keyType,{...params,path:[...params.path,"propertyNames"]});json2.additionalProperties=this.process(def.valueType,{...params,path:[...params.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw Error("Set cannot be represented in JSON Schema");break}case"enum":{let json2=_json,values=getEnumValues2(def.entries);if(values.every((v)=>typeof v==="number"))json2.type="number";if(values.every((v)=>typeof v==="string"))json2.type="string";json2.enum=values;break}case"literal":{let json2=_json,vals=[];for(let val of def.values)if(val===void 0){if(this.unrepresentable==="throw")throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof val==="bigint")if(this.unrepresentable==="throw")throw Error("BigInt literals cannot be represented in JSON Schema");else vals.push(Number(val));else vals.push(val);if(vals.length===0);else if(vals.length===1){let val=vals[0];if(json2.type=val===null?"null":typeof val,this.target==="draft-4"||this.target==="openapi-3.0")json2.enum=[val];else json2.const=val}else{if(vals.every((v)=>typeof v==="number"))json2.type="number";if(vals.every((v)=>typeof v==="string"))json2.type="string";if(vals.every((v)=>typeof v==="boolean"))json2.type="string";if(vals.every((v)=>v===null))json2.type="null";json2.enum=vals}break}case"file":{let json2=_json,file2={type:"string",format:"binary",contentEncoding:"binary"},{minimum,maximum,mime}=schema._zod.bag;if(minimum!==void 0)file2.minLength=minimum;if(maximum!==void 0)file2.maxLength=maximum;if(mime)if(mime.length===1)file2.contentMediaType=mime[0],Object.assign(json2,file2);else json2.anyOf=mime.map((m)=>{return{...file2,contentMediaType:m}});else Object.assign(json2,file2);break}case"transform":{if(this.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let inner=this.process(def.innerType,params);if(this.target==="openapi-3.0")result.ref=def.innerType,_json.nullable=!0;else _json.anyOf=[inner,{type:"null"}];break}case"nonoptional":{this.process(def.innerType,params),result.ref=def.innerType;break}case"success":{let json2=_json;json2.type="boolean";break}case"default":{this.process(def.innerType,params),result.ref=def.innerType,_json.default=JSON.parse(JSON.stringify(def.defaultValue));break}case"prefault":{if(this.process(def.innerType,params),result.ref=def.innerType,this.io==="input")_json._prefault=JSON.parse(JSON.stringify(def.defaultValue));break}case"catch":{this.process(def.innerType,params),result.ref=def.innerType;let catchValue;try{catchValue=def.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}_json.default=catchValue;break}case"nan":{if(this.unrepresentable==="throw")throw Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let json2=_json,pattern=schema._zod.pattern;if(!pattern)throw Error("Pattern not found in template literal");json2.type="string",json2.pattern=pattern.source;break}case"pipe":{let innerType=this.io==="input"?def.in._zod.def.type==="transform"?def.out:def.in:def.out;this.process(innerType,params),result.ref=innerType;break}case"readonly":{this.process(def.innerType,params),result.ref=def.innerType,_json.readOnly=!0;break}case"promise":{this.process(def.innerType,params),result.ref=def.innerType;break}case"optional":{this.process(def.innerType,params),result.ref=def.innerType;break}case"lazy":{let innerType=schema._zod.innerType;this.process(innerType,params),result.ref=innerType;break}case"custom":{if(this.unrepresentable==="throw")throw Error("Custom types cannot be represented in JSON Schema");break}case"function":{if(this.unrepresentable==="throw")throw Error("Function types cannot be represented in JSON Schema");break}default:}}}let meta3=this.metadataRegistry.get(schema);if(meta3)Object.assign(result.schema,meta3);if(this.io==="input"&&isTransforming2(schema))delete result.schema.examples,delete result.schema.default;if(this.io==="input"&&result.schema._prefault)(_a2=result.schema).default??(_a2.default=result.schema._prefault);return delete result.schema._prefault,this.seen.get(schema).schema}emit(schema,_params){let params={cycles:_params?.cycles??"ref",reused:_params?.reused??"inline",external:_params?.external??void 0},root=this.seen.get(schema);if(!root)throw Error("Unprocessed schema. This is a bug in Zod.");let makeURI=(entry)=>{let defsSegment=this.target==="draft-2020-12"?"$defs":"definitions";if(params.external){let externalId=params.external.registry.get(entry[0])?.id,uriGenerator=params.external.uri??((id2)=>id2);if(externalId)return{ref:uriGenerator(externalId)};let id=entry[1].defId??entry[1].schema.id??`schema${this.counter++}`;return entry[1].defId=id,{defId:id,ref:`${uriGenerator("__shared")}#/${defsSegment}/${id}`}}if(entry[1]===root)return{ref:"#"};let defUriPrefix=`${"#"}/${defsSegment}/`,defId=entry[1].schema.id??`__schema${this.counter++}`;return{defId,ref:defUriPrefix+defId}},extractToDef=(entry)=>{if(entry[1].schema.$ref)return;let seen=entry[1],{ref,defId}=makeURI(entry);if(seen.def={...seen.schema},defId)seen.defId=defId;let schema2=seen.schema;for(let key in schema2)delete schema2[key];schema2.$ref=ref};if(params.cycles==="throw")for(let entry of this.seen.entries()){let seen=entry[1];if(seen.cycle)throw Error(`Cycle detected: #/${seen.cycle?.join("/")}/<root>
|
|
883
883
|
|
|
884
|
-
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let entry of this.seen.entries()){let seen=entry[1];if(schema===entry[0]){extractToDef(entry);continue}if(params.external){let ext=params.external.registry.get(entry[0])?.id;if(schema!==entry[0]&&ext){extractToDef(entry);continue}}if(this.metadataRegistry.get(entry[0])?.id){extractToDef(entry);continue}if(seen.cycle){extractToDef(entry);continue}if(seen.count>1){if(params.reused==="ref"){extractToDef(entry);continue}}}let flattenRef=(zodSchema,params2)=>{let seen=this.seen.get(zodSchema),schema2=seen.def??seen.schema,_cached2={...schema2};if(seen.ref===null)return;let ref=seen.ref;if(seen.ref=null,ref){flattenRef(ref,params2);let refSchema=this.seen.get(ref).schema;if(refSchema.$ref&&(params2.target==="draft-7"||params2.target==="draft-4"||params2.target==="openapi-3.0"))schema2.allOf=schema2.allOf??[],schema2.allOf.push(refSchema);else Object.assign(schema2,refSchema),Object.assign(schema2,_cached2)}if(!seen.isParent)this.override({zodSchema,jsonSchema:schema2,path:seen.path??[]})};for(let entry of[...this.seen.entries()].reverse())flattenRef(entry[0],{target:this.target});let result={};if(this.target==="draft-2020-12")result.$schema="https://json-schema.org/draft/2020-12/schema";else if(this.target==="draft-7")result.$schema="http://json-schema.org/draft-07/schema#";else if(this.target==="draft-4")result.$schema="http://json-schema.org/draft-04/schema#";else if(this.target==="openapi-3.0");else console.warn(`Invalid target: ${this.target}`);if(params.external?.uri){let id=params.external.registry.get(schema)?.id;if(!id)throw Error("Schema is missing an `id` property");result.$id=params.external.uri(id)}Object.assign(result,root.def);let defs=params.external?.defs??{};for(let entry of this.seen.entries()){let seen=entry[1];if(seen.def&&seen.defId)defs[seen.defId]=seen.def}if(params.external);else if(Object.keys(defs).length>0)if(this.target==="draft-2020-12")result.$defs=defs;else result.definitions=defs;try{return JSON.parse(JSON.stringify(result))}catch(_err){throw Error("Error converting schema to JSON.")}}}function toJSONSchema2(input,_params){if(input instanceof $ZodRegistry2){let gen2=new JSONSchemaGenerator2(_params),defs={};for(let entry of input._idmap.entries()){let[_,schema]=entry;gen2.process(schema)}let schemas3={},external2={registry:input,uri:_params?.uri,defs};for(let entry of input._idmap.entries()){let[key,schema]=entry;schemas3[key]=gen2.emit(schema,{..._params,external:external2})}if(Object.keys(defs).length>0){let defsSegment=gen2.target==="draft-2020-12"?"$defs":"definitions";schemas3.__shared={[defsSegment]:defs}}return{schemas:schemas3}}let gen=new JSONSchemaGenerator2(_params);return gen.process(input),gen.emit(input,_params)}function isTransforming2(_schema,_ctx){let ctx=_ctx??{seen:new Set};if(ctx.seen.has(_schema))return!1;ctx.seen.add(_schema);let def=_schema._zod.def;switch(def.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return isTransforming2(def.element,ctx);case"object":{for(let key in def.shape)if(isTransforming2(def.shape[key],ctx))return!0;return!1}case"union":{for(let option of def.options)if(isTransforming2(option,ctx))return!0;return!1}case"intersection":return isTransforming2(def.left,ctx)||isTransforming2(def.right,ctx);case"tuple":{for(let item of def.items)if(isTransforming2(item,ctx))return!0;if(def.rest&&isTransforming2(def.rest,ctx))return!0;return!1}case"record":return isTransforming2(def.keyType,ctx)||isTransforming2(def.valueType,ctx);case"map":return isTransforming2(def.keyType,ctx)||isTransforming2(def.valueType,ctx);case"set":return isTransforming2(def.valueType,ctx);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return isTransforming2(def.innerType,ctx);case"lazy":return isTransforming2(def.getter(),ctx);case"default":return isTransforming2(def.innerType,ctx);case"prefault":return isTransforming2(def.innerType,ctx);case"custom":return!1;case"transform":return!0;case"pipe":return isTransforming2(def.in,ctx)||isTransforming2(def.out,ctx);case"success":return!1;case"catch":return!1;case"function":return!1;default:}throw Error(`Unknown schema type: ${def.type}`)}var init_to_json_schema2=__esm(()=>{init_registries2();init_util2()});var exports_json_schema2={};var init_json_schema2=()=>{};var exports_core5={};__export(exports_core5,{version:()=>version2,util:()=>exports_util2,treeifyError:()=>treeifyError2,toJSONSchema:()=>toJSONSchema2,toDotPath:()=>toDotPath2,safeParseAsync:()=>safeParseAsync3,safeParse:()=>safeParse3,safeEncodeAsync:()=>safeEncodeAsync3,safeEncode:()=>safeEncode3,safeDecodeAsync:()=>safeDecodeAsync3,safeDecode:()=>safeDecode3,registry:()=>registry2,regexes:()=>exports_regexes2,prettifyError:()=>prettifyError2,parseAsync:()=>parseAsync3,parse:()=>parse5,locales:()=>exports_locales2,isValidJWT:()=>isValidJWT2,isValidBase64URL:()=>isValidBase64URL2,isValidBase64:()=>isValidBase642,globalRegistry:()=>globalRegistry2,globalConfig:()=>globalConfig2,formatError:()=>formatError2,flattenError:()=>flattenError2,encodeAsync:()=>encodeAsync3,encode:()=>encode3,decodeAsync:()=>decodeAsync3,decode:()=>decode3,config:()=>config2,clone:()=>clone2,_xid:()=>_xid2,_void:()=>_void3,_uuidv7:()=>_uuidv72,_uuidv6:()=>_uuidv62,_uuidv4:()=>_uuidv42,_uuid:()=>_uuid2,_url:()=>_url2,_uppercase:()=>_uppercase2,_unknown:()=>_unknown2,_union:()=>_union2,_undefined:()=>_undefined5,_ulid:()=>_ulid2,_uint64:()=>_uint642,_uint32:()=>_uint322,_tuple:()=>_tuple2,_trim:()=>_trim2,_transform:()=>_transform2,_toUpperCase:()=>_toUpperCase2,_toLowerCase:()=>_toLowerCase2,_templateLiteral:()=>_templateLiteral2,_symbol:()=>_symbol2,_superRefine:()=>_superRefine2,_success:()=>_success2,_stringbool:()=>_stringbool2,_stringFormat:()=>_stringFormat2,_string:()=>_string2,_startsWith:()=>_startsWith2,_size:()=>_size2,_set:()=>_set2,_safeParseAsync:()=>_safeParseAsync2,_safeParse:()=>_safeParse2,_safeEncodeAsync:()=>_safeEncodeAsync2,_safeEncode:()=>_safeEncode2,_safeDecodeAsync:()=>_safeDecodeAsync2,_safeDecode:()=>_safeDecode2,_regex:()=>_regex2,_refine:()=>_refine2,_record:()=>_record2,_readonly:()=>_readonly2,_property:()=>_property2,_promise:()=>_promise2,_positive:()=>_positive2,_pipe:()=>_pipe2,_parseAsync:()=>_parseAsync2,_parse:()=>_parse2,_overwrite:()=>_overwrite2,_optional:()=>_optional2,_number:()=>_number2,_nullable:()=>_nullable2,_null:()=>_null5,_normalize:()=>_normalize2,_nonpositive:()=>_nonpositive2,_nonoptional:()=>_nonoptional2,_nonnegative:()=>_nonnegative2,_never:()=>_never2,_negative:()=>_negative2,_nativeEnum:()=>_nativeEnum2,_nanoid:()=>_nanoid2,_nan:()=>_nan2,_multipleOf:()=>_multipleOf2,_minSize:()=>_minSize2,_minLength:()=>_minLength2,_min:()=>_gte2,_mime:()=>_mime2,_maxSize:()=>_maxSize2,_maxLength:()=>_maxLength2,_max:()=>_lte2,_map:()=>_map2,_lte:()=>_lte2,_lt:()=>_lt2,_lowercase:()=>_lowercase2,_literal:()=>_literal2,_length:()=>_length2,_lazy:()=>_lazy2,_ksuid:()=>_ksuid2,_jwt:()=>_jwt2,_isoTime:()=>_isoTime2,_isoDuration:()=>_isoDuration2,_isoDateTime:()=>_isoDateTime2,_isoDate:()=>_isoDate2,_ipv6:()=>_ipv62,_ipv4:()=>_ipv42,_intersection:()=>_intersection2,_int64:()=>_int642,_int32:()=>_int322,_int:()=>_int2,_includes:()=>_includes2,_guid:()=>_guid2,_gte:()=>_gte2,_gt:()=>_gt2,_float64:()=>_float642,_float32:()=>_float322,_file:()=>_file2,_enum:()=>_enum3,_endsWith:()=>_endsWith2,_encodeAsync:()=>_encodeAsync2,_encode:()=>_encode2,_emoji:()=>_emoji3,_email:()=>_email2,_e164:()=>_e1642,_discriminatedUnion:()=>_discriminatedUnion2,_default:()=>_default3,_decodeAsync:()=>_decodeAsync2,_decode:()=>_decode2,_date:()=>_date2,_custom:()=>_custom2,_cuid2:()=>_cuid22,_cuid:()=>_cuid3,_coercedString:()=>_coercedString2,_coercedNumber:()=>_coercedNumber2,_coercedDate:()=>_coercedDate2,_coercedBoolean:()=>_coercedBoolean2,_coercedBigint:()=>_coercedBigint2,_cidrv6:()=>_cidrv62,_cidrv4:()=>_cidrv42,_check:()=>_check2,_catch:()=>_catch3,_boolean:()=>_boolean2,_bigint:()=>_bigint2,_base64url:()=>_base64url2,_base64:()=>_base642,_array:()=>_array2,_any:()=>_any2,TimePrecision:()=>TimePrecision2,NEVER:()=>NEVER2,JSONSchemaGenerator:()=>JSONSchemaGenerator2,JSONSchema:()=>exports_json_schema2,Doc:()=>Doc2,$output:()=>$output2,$input:()=>$input2,$constructor:()=>$constructor2,$brand:()=>$brand2,$ZodXID:()=>$ZodXID2,$ZodVoid:()=>$ZodVoid2,$ZodUnknown:()=>$ZodUnknown2,$ZodUnion:()=>$ZodUnion2,$ZodUndefined:()=>$ZodUndefined2,$ZodUUID:()=>$ZodUUID2,$ZodURL:()=>$ZodURL2,$ZodULID:()=>$ZodULID2,$ZodType:()=>$ZodType2,$ZodTuple:()=>$ZodTuple2,$ZodTransform:()=>$ZodTransform2,$ZodTemplateLiteral:()=>$ZodTemplateLiteral2,$ZodSymbol:()=>$ZodSymbol2,$ZodSuccess:()=>$ZodSuccess2,$ZodStringFormat:()=>$ZodStringFormat2,$ZodString:()=>$ZodString2,$ZodSet:()=>$ZodSet2,$ZodRegistry:()=>$ZodRegistry2,$ZodRecord:()=>$ZodRecord2,$ZodRealError:()=>$ZodRealError2,$ZodReadonly:()=>$ZodReadonly2,$ZodPromise:()=>$ZodPromise2,$ZodPrefault:()=>$ZodPrefault2,$ZodPipe:()=>$ZodPipe2,$ZodOptional:()=>$ZodOptional2,$ZodObjectJIT:()=>$ZodObjectJIT2,$ZodObject:()=>$ZodObject2,$ZodNumberFormat:()=>$ZodNumberFormat2,$ZodNumber:()=>$ZodNumber2,$ZodNullable:()=>$ZodNullable2,$ZodNull:()=>$ZodNull2,$ZodNonOptional:()=>$ZodNonOptional2,$ZodNever:()=>$ZodNever2,$ZodNanoID:()=>$ZodNanoID2,$ZodNaN:()=>$ZodNaN2,$ZodMap:()=>$ZodMap2,$ZodLiteral:()=>$ZodLiteral2,$ZodLazy:()=>$ZodLazy2,$ZodKSUID:()=>$ZodKSUID2,$ZodJWT:()=>$ZodJWT2,$ZodIntersection:()=>$ZodIntersection2,$ZodISOTime:()=>$ZodISOTime2,$ZodISODuration:()=>$ZodISODuration2,$ZodISODateTime:()=>$ZodISODateTime2,$ZodISODate:()=>$ZodISODate2,$ZodIPv6:()=>$ZodIPv62,$ZodIPv4:()=>$ZodIPv42,$ZodGUID:()=>$ZodGUID2,$ZodFunction:()=>$ZodFunction2,$ZodFile:()=>$ZodFile2,$ZodError:()=>$ZodError2,$ZodEnum:()=>$ZodEnum2,$ZodEncodeError:()=>$ZodEncodeError2,$ZodEmoji:()=>$ZodEmoji2,$ZodEmail:()=>$ZodEmail2,$ZodE164:()=>$ZodE1642,$ZodDiscriminatedUnion:()=>$ZodDiscriminatedUnion2,$ZodDefault:()=>$ZodDefault2,$ZodDate:()=>$ZodDate2,$ZodCustomStringFormat:()=>$ZodCustomStringFormat2,$ZodCustom:()=>$ZodCustom2,$ZodCodec:()=>$ZodCodec2,$ZodCheckUpperCase:()=>$ZodCheckUpperCase2,$ZodCheckStringFormat:()=>$ZodCheckStringFormat2,$ZodCheckStartsWith:()=>$ZodCheckStartsWith2,$ZodCheckSizeEquals:()=>$ZodCheckSizeEquals2,$ZodCheckRegex:()=>$ZodCheckRegex2,$ZodCheckProperty:()=>$ZodCheckProperty2,$ZodCheckOverwrite:()=>$ZodCheckOverwrite2,$ZodCheckNumberFormat:()=>$ZodCheckNumberFormat2,$ZodCheckMultipleOf:()=>$ZodCheckMultipleOf2,$ZodCheckMinSize:()=>$ZodCheckMinSize2,$ZodCheckMinLength:()=>$ZodCheckMinLength2,$ZodCheckMimeType:()=>$ZodCheckMimeType2,$ZodCheckMaxSize:()=>$ZodCheckMaxSize2,$ZodCheckMaxLength:()=>$ZodCheckMaxLength2,$ZodCheckLowerCase:()=>$ZodCheckLowerCase2,$ZodCheckLessThan:()=>$ZodCheckLessThan2,$ZodCheckLengthEquals:()=>$ZodCheckLengthEquals2,$ZodCheckIncludes:()=>$ZodCheckIncludes2,$ZodCheckGreaterThan:()=>$ZodCheckGreaterThan2,$ZodCheckEndsWith:()=>$ZodCheckEndsWith2,$ZodCheckBigIntFormat:()=>$ZodCheckBigIntFormat2,$ZodCheck:()=>$ZodCheck2,$ZodCatch:()=>$ZodCatch2,$ZodCUID2:()=>$ZodCUID22,$ZodCUID:()=>$ZodCUID3,$ZodCIDRv6:()=>$ZodCIDRv62,$ZodCIDRv4:()=>$ZodCIDRv42,$ZodBoolean:()=>$ZodBoolean2,$ZodBigIntFormat:()=>$ZodBigIntFormat2,$ZodBigInt:()=>$ZodBigInt2,$ZodBase64URL:()=>$ZodBase64URL2,$ZodBase64:()=>$ZodBase642,$ZodAsyncError:()=>$ZodAsyncError2,$ZodArray:()=>$ZodArray2,$ZodAny:()=>$ZodAny2});var init_core5=__esm(()=>{init_util2();init_regexes2();init_locales2();init_json_schema2();init_core4();init_parse3();init_errors4();init_schemas3();init_checks3();init_versions2();init_registries2();init_api2();init_to_json_schema2()});var init_checks4=__esm(()=>{init_core5()});var exports_iso2={};__export(exports_iso2,{time:()=>time4,duration:()=>duration4,datetime:()=>datetime4,date:()=>date6,ZodISOTime:()=>ZodISOTime2,ZodISODuration:()=>ZodISODuration2,ZodISODateTime:()=>ZodISODateTime2,ZodISODate:()=>ZodISODate2});function datetime4(params){return _isoDateTime2(ZodISODateTime2,params)}function date6(params){return _isoDate2(ZodISODate2,params)}function time4(params){return _isoTime2(ZodISOTime2,params)}function duration4(params){return _isoDuration2(ZodISODuration2,params)}var ZodISODateTime2,ZodISODate2,ZodISOTime2,ZodISODuration2;var init_iso2=__esm(()=>{init_core5();init_schemas4();ZodISODateTime2=$constructor2("ZodISODateTime",(inst,def)=>{$ZodISODateTime2.init(inst,def),ZodStringFormat2.init(inst,def)});ZodISODate2=$constructor2("ZodISODate",(inst,def)=>{$ZodISODate2.init(inst,def),ZodStringFormat2.init(inst,def)});ZodISOTime2=$constructor2("ZodISOTime",(inst,def)=>{$ZodISOTime2.init(inst,def),ZodStringFormat2.init(inst,def)});ZodISODuration2=$constructor2("ZodISODuration",(inst,def)=>{$ZodISODuration2.init(inst,def),ZodStringFormat2.init(inst,def)})});var initializer4=(inst,issues)=>{$ZodError2.init(inst,issues),inst.name="ZodError",Object.defineProperties(inst,{format:{value:(mapper)=>formatError2(inst,mapper)},flatten:{value:(mapper)=>flattenError2(inst,mapper)},addIssue:{value:(issue3)=>{inst.issues.push(issue3),inst.message=JSON.stringify(inst.issues,jsonStringifyReplacer2,2)}},addIssues:{value:(issues2)=>{inst.issues.push(...issues2),inst.message=JSON.stringify(inst.issues,jsonStringifyReplacer2,2)}},isEmpty:{get(){return inst.issues.length===0}}})},ZodError2,ZodRealError2;var init_errors5=__esm(()=>{init_core5();init_core5();init_util2();ZodError2=$constructor2("ZodError",initializer4),ZodRealError2=$constructor2("ZodError",initializer4,{Parent:Error})});var parse7,parseAsync4,safeParse4,safeParseAsync4,encode4,decode4,encodeAsync4,decodeAsync4,safeEncode4,safeDecode4,safeEncodeAsync4,safeDecodeAsync4;var init_parse4=__esm(()=>{init_core5();init_errors5();parse7=_parse2(ZodRealError2),parseAsync4=_parseAsync2(ZodRealError2),safeParse4=_safeParse2(ZodRealError2),safeParseAsync4=_safeParseAsync2(ZodRealError2),encode4=_encode2(ZodRealError2),decode4=_decode2(ZodRealError2),encodeAsync4=_encodeAsync2(ZodRealError2),decodeAsync4=_decodeAsync2(ZodRealError2),safeEncode4=_safeEncode2(ZodRealError2),safeDecode4=_safeDecode2(ZodRealError2),safeEncodeAsync4=_safeEncodeAsync2(ZodRealError2),safeDecodeAsync4=_safeDecodeAsync2(ZodRealError2)});function string5(params){return _string2(ZodString2,params)}function email4(params){return _email2(ZodEmail2,params)}function guid4(params){return _guid2(ZodGUID2,params)}function uuid5(params){return _uuid2(ZodUUID2,params)}function uuidv42(params){return _uuidv42(ZodUUID2,params)}function uuidv62(params){return _uuidv62(ZodUUID2,params)}function uuidv72(params){return _uuidv72(ZodUUID2,params)}function url2(params){return _url2(ZodURL2,params)}function httpUrl2(params){return _url2(ZodURL2,{protocol:/^https?$/,hostname:exports_regexes2.domain,...exports_util2.normalizeParams(params)})}function emoji4(params){return _emoji3(ZodEmoji2,params)}function nanoid4(params){return _nanoid2(ZodNanoID2,params)}function cuid6(params){return _cuid3(ZodCUID3,params)}function cuid24(params){return _cuid22(ZodCUID22,params)}function ulid4(params){return _ulid2(ZodULID2,params)}function xid4(params){return _xid2(ZodXID2,params)}function ksuid4(params){return _ksuid2(ZodKSUID2,params)}function ipv44(params){return _ipv42(ZodIPv42,params)}function ipv64(params){return _ipv62(ZodIPv62,params)}function cidrv44(params){return _cidrv42(ZodCIDRv42,params)}function cidrv64(params){return _cidrv62(ZodCIDRv62,params)}function base644(params){return _base642(ZodBase642,params)}function base64url4(params){return _base64url2(ZodBase64URL2,params)}function e1644(params){return _e1642(ZodE1642,params)}function jwt2(params){return _jwt2(ZodJWT2,params)}function stringFormat2(format,fnOrRegex,_params={}){return _stringFormat2(ZodCustomStringFormat2,format,fnOrRegex,_params)}function hostname4(_params){return _stringFormat2(ZodCustomStringFormat2,"hostname",exports_regexes2.hostname,_params)}function hex4(_params){return _stringFormat2(ZodCustomStringFormat2,"hex",exports_regexes2.hex,_params)}function hash3(alg,params){let enc=params?.enc??"hex",format=`${alg}_${enc}`,regex=exports_regexes2[format];if(!regex)throw Error(`Unrecognized hash format: ${format}`);return _stringFormat2(ZodCustomStringFormat2,format,regex,params)}function number5(params){return _number2(ZodNumber2,params)}function int2(params){return _int2(ZodNumberFormat2,params)}function float322(params){return _float322(ZodNumberFormat2,params)}function float642(params){return _float642(ZodNumberFormat2,params)}function int322(params){return _int322(ZodNumberFormat2,params)}function uint322(params){return _uint322(ZodNumberFormat2,params)}function boolean5(params){return _boolean2(ZodBoolean2,params)}function bigint5(params){return _bigint2(ZodBigInt2,params)}function int642(params){return _int642(ZodBigIntFormat2,params)}function uint642(params){return _uint642(ZodBigIntFormat2,params)}function symbol2(params){return _symbol2(ZodSymbol2,params)}function _undefined6(params){return _undefined5(ZodUndefined2,params)}function _null6(params){return _null5(ZodNull2,params)}function any2(){return _any2(ZodAny2)}function unknown2(){return _unknown2(ZodUnknown2)}function never2(params){return _never2(ZodNever2,params)}function _void4(params){return _void3(ZodVoid2,params)}function date7(params){return _date2(ZodDate2,params)}function array2(element,params){return _array2(ZodArray2,element,params)}function keyof2(schema){let shape=schema._zod.def.shape;return _enum4(Object.keys(shape))}function object2(shape,params){let def={type:"object",get shape(){return exports_util2.assignProp(this,"shape",shape?exports_util2.objectClone(shape):{}),this.shape},...exports_util2.normalizeParams(params)};return new ZodObject2(def)}function strictObject2(shape,params){return new ZodObject2({type:"object",get shape(){return exports_util2.assignProp(this,"shape",exports_util2.objectClone(shape)),this.shape},catchall:never2(),...exports_util2.normalizeParams(params)})}function looseObject2(shape,params){return new ZodObject2({type:"object",get shape(){return exports_util2.assignProp(this,"shape",exports_util2.objectClone(shape)),this.shape},catchall:unknown2(),...exports_util2.normalizeParams(params)})}function union2(options,params){return new ZodUnion2({type:"union",options,...exports_util2.normalizeParams(params)})}function discriminatedUnion2(discriminator,options,params){return new ZodDiscriminatedUnion2({type:"union",options,discriminator,...exports_util2.normalizeParams(params)})}function intersection2(left,right){return new ZodIntersection2({type:"intersection",left,right})}function tuple2(items,_paramsOrRest,_params){let hasRest=_paramsOrRest instanceof $ZodType2,params=hasRest?_params:_paramsOrRest;return new ZodTuple2({type:"tuple",items,rest:hasRest?_paramsOrRest:null,...exports_util2.normalizeParams(params)})}function record2(keyType,valueType,params){return new ZodRecord2({type:"record",keyType,valueType,...exports_util2.normalizeParams(params)})}function partialRecord2(keyType,valueType,params){let k=clone2(keyType);return k._zod.values=void 0,new ZodRecord2({type:"record",keyType:k,valueType,...exports_util2.normalizeParams(params)})}function map2(keyType,valueType,params){return new ZodMap2({type:"map",keyType,valueType,...exports_util2.normalizeParams(params)})}function set2(valueType,params){return new ZodSet2({type:"set",valueType,...exports_util2.normalizeParams(params)})}function _enum4(values,params){let entries=Array.isArray(values)?Object.fromEntries(values.map((v)=>[v,v])):values;return new ZodEnum2({type:"enum",entries,...exports_util2.normalizeParams(params)})}function nativeEnum2(entries,params){return new ZodEnum2({type:"enum",entries,...exports_util2.normalizeParams(params)})}function literal3(value,params){return new ZodLiteral2({type:"literal",values:Array.isArray(value)?value:[value],...exports_util2.normalizeParams(params)})}function file2(params){return _file2(ZodFile2,params)}function transform2(fn2){return new ZodTransform2({type:"transform",transform:fn2})}function optional2(innerType){return new ZodOptional2({type:"optional",innerType})}function nullable2(innerType){return new ZodNullable2({type:"nullable",innerType})}function nullish4(innerType){return optional2(nullable2(innerType))}function _default4(innerType,defaultValue){return new ZodDefault2({type:"default",innerType,get defaultValue(){return typeof defaultValue==="function"?defaultValue():exports_util2.shallowClone(defaultValue)}})}function prefault2(innerType,defaultValue){return new ZodPrefault2({type:"prefault",innerType,get defaultValue(){return typeof defaultValue==="function"?defaultValue():exports_util2.shallowClone(defaultValue)}})}function nonoptional2(innerType,params){return new ZodNonOptional2({type:"nonoptional",innerType,...exports_util2.normalizeParams(params)})}function success2(innerType){return new ZodSuccess2({type:"success",innerType})}function _catch4(innerType,catchValue){return new ZodCatch2({type:"catch",innerType,catchValue:typeof catchValue==="function"?catchValue:()=>catchValue})}function nan2(params){return _nan2(ZodNaN2,params)}function pipe2(in_,out){return new ZodPipe2({type:"pipe",in:in_,out})}function codec3(in_,out,params){return new ZodCodec2({type:"pipe",in:in_,out,transform:params.decode,reverseTransform:params.encode})}function readonly2(innerType){return new ZodReadonly2({type:"readonly",innerType})}function templateLiteral2(parts,params){return new ZodTemplateLiteral2({type:"template_literal",parts,...exports_util2.normalizeParams(params)})}function lazy2(getter){return new ZodLazy2({type:"lazy",getter})}function promise2(innerType){return new ZodPromise2({type:"promise",innerType})}function _function2(params){return new ZodFunction2({type:"function",input:Array.isArray(params?.input)?tuple2(params?.input):params?.input??array2(unknown2()),output:params?.output??unknown2()})}function check2(fn2){let ch=new $ZodCheck2({check:"custom"});return ch._zod.check=fn2,ch}function custom2(fn2,_params){return _custom2(ZodCustom2,fn2??(()=>!0),_params)}function refine2(fn2,_params={}){return _refine2(ZodCustom2,fn2,_params)}function superRefine2(fn2){return _superRefine2(fn2)}function _instanceof2(cls,params={error:`Input not instance of ${cls.name}`}){let inst=new ZodCustom2({type:"custom",check:"custom",fn:(data)=>data instanceof cls,abort:!0,...exports_util2.normalizeParams(params)});return inst._zod.bag.Class=cls,inst}function json2(params){let jsonSchema=lazy2(()=>{return union2([string5(params),number5(),boolean5(),_null6(),array2(jsonSchema),record2(string5(),jsonSchema)])});return jsonSchema}function preprocess2(fn2,schema){return pipe2(transform2(fn2),schema)}var ZodType2,_ZodString2,ZodString2,ZodStringFormat2,ZodEmail2,ZodGUID2,ZodUUID2,ZodURL2,ZodEmoji2,ZodNanoID2,ZodCUID3,ZodCUID22,ZodULID2,ZodXID2,ZodKSUID2,ZodIPv42,ZodIPv62,ZodCIDRv42,ZodCIDRv62,ZodBase642,ZodBase64URL2,ZodE1642,ZodJWT2,ZodCustomStringFormat2,ZodNumber2,ZodNumberFormat2,ZodBoolean2,ZodBigInt2,ZodBigIntFormat2,ZodSymbol2,ZodUndefined2,ZodNull2,ZodAny2,ZodUnknown2,ZodNever2,ZodVoid2,ZodDate2,ZodArray2,ZodObject2,ZodUnion2,ZodDiscriminatedUnion2,ZodIntersection2,ZodTuple2,ZodRecord2,ZodMap2,ZodSet2,ZodEnum2,ZodLiteral2,ZodFile2,ZodTransform2,ZodOptional2,ZodNullable2,ZodDefault2,ZodPrefault2,ZodNonOptional2,ZodSuccess2,ZodCatch2,ZodNaN2,ZodPipe2,ZodCodec2,ZodReadonly2,ZodTemplateLiteral2,ZodLazy2,ZodPromise2,ZodFunction2,ZodCustom2,stringbool2=(...args2)=>_stringbool2({Codec:ZodCodec2,Boolean:ZodBoolean2,String:ZodString2},...args2);var init_schemas4=__esm(()=>{init_core5();init_core5();init_checks4();init_iso2();init_parse4();ZodType2=$constructor2("ZodType",(inst,def)=>{return $ZodType2.init(inst,def),inst.def=def,inst.type=def.type,Object.defineProperty(inst,"_def",{value:def}),inst.check=(...checks4)=>{return inst.clone({...def,checks:[...def.checks??[],...checks4.map((ch)=>typeof ch==="function"?{_zod:{check:ch,def:{check:"custom"},onattach:[]}}:ch)]})},inst.clone=(def2,params)=>clone2(inst,def2,params),inst.brand=()=>inst,inst.register=(reg,meta3)=>{return reg.add(inst,meta3),inst},inst.parse=(data,params)=>parse7(inst,data,params,{callee:inst.parse}),inst.safeParse=(data,params)=>safeParse4(inst,data,params),inst.parseAsync=async(data,params)=>parseAsync4(inst,data,params,{callee:inst.parseAsync}),inst.safeParseAsync=async(data,params)=>safeParseAsync4(inst,data,params),inst.spa=inst.safeParseAsync,inst.encode=(data,params)=>encode4(inst,data,params),inst.decode=(data,params)=>decode4(inst,data,params),inst.encodeAsync=async(data,params)=>encodeAsync4(inst,data,params),inst.decodeAsync=async(data,params)=>decodeAsync4(inst,data,params),inst.safeEncode=(data,params)=>safeEncode4(inst,data,params),inst.safeDecode=(data,params)=>safeDecode4(inst,data,params),inst.safeEncodeAsync=async(data,params)=>safeEncodeAsync4(inst,data,params),inst.safeDecodeAsync=async(data,params)=>safeDecodeAsync4(inst,data,params),inst.refine=(check2,params)=>inst.check(refine2(check2,params)),inst.superRefine=(refinement)=>inst.check(superRefine2(refinement)),inst.overwrite=(fn2)=>inst.check(_overwrite2(fn2)),inst.optional=()=>optional2(inst),inst.nullable=()=>nullable2(inst),inst.nullish=()=>optional2(nullable2(inst)),inst.nonoptional=(params)=>nonoptional2(inst,params),inst.array=()=>array2(inst),inst.or=(arg)=>union2([inst,arg]),inst.and=(arg)=>intersection2(inst,arg),inst.transform=(tx)=>pipe2(inst,transform2(tx)),inst.default=(def2)=>_default4(inst,def2),inst.prefault=(def2)=>prefault2(inst,def2),inst.catch=(params)=>_catch4(inst,params),inst.pipe=(target)=>pipe2(inst,target),inst.readonly=()=>readonly2(inst),inst.describe=(description)=>{let cl=inst.clone();return globalRegistry2.add(cl,{description}),cl},Object.defineProperty(inst,"description",{get(){return globalRegistry2.get(inst)?.description},configurable:!0}),inst.meta=(...args2)=>{if(args2.length===0)return globalRegistry2.get(inst);let cl=inst.clone();return globalRegistry2.add(cl,args2[0]),cl},inst.isOptional=()=>inst.safeParse(void 0).success,inst.isNullable=()=>inst.safeParse(null).success,inst}),_ZodString2=$constructor2("_ZodString",(inst,def)=>{$ZodString2.init(inst,def),ZodType2.init(inst,def);let bag=inst._zod.bag;inst.format=bag.format??null,inst.minLength=bag.minimum??null,inst.maxLength=bag.maximum??null,inst.regex=(...args2)=>inst.check(_regex2(...args2)),inst.includes=(...args2)=>inst.check(_includes2(...args2)),inst.startsWith=(...args2)=>inst.check(_startsWith2(...args2)),inst.endsWith=(...args2)=>inst.check(_endsWith2(...args2)),inst.min=(...args2)=>inst.check(_minLength2(...args2)),inst.max=(...args2)=>inst.check(_maxLength2(...args2)),inst.length=(...args2)=>inst.check(_length2(...args2)),inst.nonempty=(...args2)=>inst.check(_minLength2(1,...args2)),inst.lowercase=(params)=>inst.check(_lowercase2(params)),inst.uppercase=(params)=>inst.check(_uppercase2(params)),inst.trim=()=>inst.check(_trim2()),inst.normalize=(...args2)=>inst.check(_normalize2(...args2)),inst.toLowerCase=()=>inst.check(_toLowerCase2()),inst.toUpperCase=()=>inst.check(_toUpperCase2())}),ZodString2=$constructor2("ZodString",(inst,def)=>{$ZodString2.init(inst,def),_ZodString2.init(inst,def),inst.email=(params)=>inst.check(_email2(ZodEmail2,params)),inst.url=(params)=>inst.check(_url2(ZodURL2,params)),inst.jwt=(params)=>inst.check(_jwt2(ZodJWT2,params)),inst.emoji=(params)=>inst.check(_emoji3(ZodEmoji2,params)),inst.guid=(params)=>inst.check(_guid2(ZodGUID2,params)),inst.uuid=(params)=>inst.check(_uuid2(ZodUUID2,params)),inst.uuidv4=(params)=>inst.check(_uuidv42(ZodUUID2,params)),inst.uuidv6=(params)=>inst.check(_uuidv62(ZodUUID2,params)),inst.uuidv7=(params)=>inst.check(_uuidv72(ZodUUID2,params)),inst.nanoid=(params)=>inst.check(_nanoid2(ZodNanoID2,params)),inst.guid=(params)=>inst.check(_guid2(ZodGUID2,params)),inst.cuid=(params)=>inst.check(_cuid3(ZodCUID3,params)),inst.cuid2=(params)=>inst.check(_cuid22(ZodCUID22,params)),inst.ulid=(params)=>inst.check(_ulid2(ZodULID2,params)),inst.base64=(params)=>inst.check(_base642(ZodBase642,params)),inst.base64url=(params)=>inst.check(_base64url2(ZodBase64URL2,params)),inst.xid=(params)=>inst.check(_xid2(ZodXID2,params)),inst.ksuid=(params)=>inst.check(_ksuid2(ZodKSUID2,params)),inst.ipv4=(params)=>inst.check(_ipv42(ZodIPv42,params)),inst.ipv6=(params)=>inst.check(_ipv62(ZodIPv62,params)),inst.cidrv4=(params)=>inst.check(_cidrv42(ZodCIDRv42,params)),inst.cidrv6=(params)=>inst.check(_cidrv62(ZodCIDRv62,params)),inst.e164=(params)=>inst.check(_e1642(ZodE1642,params)),inst.datetime=(params)=>inst.check(datetime4(params)),inst.date=(params)=>inst.check(date6(params)),inst.time=(params)=>inst.check(time4(params)),inst.duration=(params)=>inst.check(duration4(params))});ZodStringFormat2=$constructor2("ZodStringFormat",(inst,def)=>{$ZodStringFormat2.init(inst,def),_ZodString2.init(inst,def)}),ZodEmail2=$constructor2("ZodEmail",(inst,def)=>{$ZodEmail2.init(inst,def),ZodStringFormat2.init(inst,def)});ZodGUID2=$constructor2("ZodGUID",(inst,def)=>{$ZodGUID2.init(inst,def),ZodStringFormat2.init(inst,def)});ZodUUID2=$constructor2("ZodUUID",(inst,def)=>{$ZodUUID2.init(inst,def),ZodStringFormat2.init(inst,def)});ZodURL2=$constructor2("ZodURL",(inst,def)=>{$ZodURL2.init(inst,def),ZodStringFormat2.init(inst,def)});ZodEmoji2=$constructor2("ZodEmoji",(inst,def)=>{$ZodEmoji2.init(inst,def),ZodStringFormat2.init(inst,def)});ZodNanoID2=$constructor2("ZodNanoID",(inst,def)=>{$ZodNanoID2.init(inst,def),ZodStringFormat2.init(inst,def)});ZodCUID3=$constructor2("ZodCUID",(inst,def)=>{$ZodCUID3.init(inst,def),ZodStringFormat2.init(inst,def)});ZodCUID22=$constructor2("ZodCUID2",(inst,def)=>{$ZodCUID22.init(inst,def),ZodStringFormat2.init(inst,def)});ZodULID2=$constructor2("ZodULID",(inst,def)=>{$ZodULID2.init(inst,def),ZodStringFormat2.init(inst,def)});ZodXID2=$constructor2("ZodXID",(inst,def)=>{$ZodXID2.init(inst,def),ZodStringFormat2.init(inst,def)});ZodKSUID2=$constructor2("ZodKSUID",(inst,def)=>{$ZodKSUID2.init(inst,def),ZodStringFormat2.init(inst,def)});ZodIPv42=$constructor2("ZodIPv4",(inst,def)=>{$ZodIPv42.init(inst,def),ZodStringFormat2.init(inst,def)});ZodIPv62=$constructor2("ZodIPv6",(inst,def)=>{$ZodIPv62.init(inst,def),ZodStringFormat2.init(inst,def)});ZodCIDRv42=$constructor2("ZodCIDRv4",(inst,def)=>{$ZodCIDRv42.init(inst,def),ZodStringFormat2.init(inst,def)});ZodCIDRv62=$constructor2("ZodCIDRv6",(inst,def)=>{$ZodCIDRv62.init(inst,def),ZodStringFormat2.init(inst,def)});ZodBase642=$constructor2("ZodBase64",(inst,def)=>{$ZodBase642.init(inst,def),ZodStringFormat2.init(inst,def)});ZodBase64URL2=$constructor2("ZodBase64URL",(inst,def)=>{$ZodBase64URL2.init(inst,def),ZodStringFormat2.init(inst,def)});ZodE1642=$constructor2("ZodE164",(inst,def)=>{$ZodE1642.init(inst,def),ZodStringFormat2.init(inst,def)});ZodJWT2=$constructor2("ZodJWT",(inst,def)=>{$ZodJWT2.init(inst,def),ZodStringFormat2.init(inst,def)});ZodCustomStringFormat2=$constructor2("ZodCustomStringFormat",(inst,def)=>{$ZodCustomStringFormat2.init(inst,def),ZodStringFormat2.init(inst,def)});ZodNumber2=$constructor2("ZodNumber",(inst,def)=>{$ZodNumber2.init(inst,def),ZodType2.init(inst,def),inst.gt=(value,params)=>inst.check(_gt2(value,params)),inst.gte=(value,params)=>inst.check(_gte2(value,params)),inst.min=(value,params)=>inst.check(_gte2(value,params)),inst.lt=(value,params)=>inst.check(_lt2(value,params)),inst.lte=(value,params)=>inst.check(_lte2(value,params)),inst.max=(value,params)=>inst.check(_lte2(value,params)),inst.int=(params)=>inst.check(int2(params)),inst.safe=(params)=>inst.check(int2(params)),inst.positive=(params)=>inst.check(_gt2(0,params)),inst.nonnegative=(params)=>inst.check(_gte2(0,params)),inst.negative=(params)=>inst.check(_lt2(0,params)),inst.nonpositive=(params)=>inst.check(_lte2(0,params)),inst.multipleOf=(value,params)=>inst.check(_multipleOf2(value,params)),inst.step=(value,params)=>inst.check(_multipleOf2(value,params)),inst.finite=()=>inst;let bag=inst._zod.bag;inst.minValue=Math.max(bag.minimum??Number.NEGATIVE_INFINITY,bag.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,inst.maxValue=Math.min(bag.maximum??Number.POSITIVE_INFINITY,bag.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,inst.isInt=(bag.format??"").includes("int")||Number.isSafeInteger(bag.multipleOf??0.5),inst.isFinite=!0,inst.format=bag.format??null});ZodNumberFormat2=$constructor2("ZodNumberFormat",(inst,def)=>{$ZodNumberFormat2.init(inst,def),ZodNumber2.init(inst,def)});ZodBoolean2=$constructor2("ZodBoolean",(inst,def)=>{$ZodBoolean2.init(inst,def),ZodType2.init(inst,def)});ZodBigInt2=$constructor2("ZodBigInt",(inst,def)=>{$ZodBigInt2.init(inst,def),ZodType2.init(inst,def),inst.gte=(value,params)=>inst.check(_gte2(value,params)),inst.min=(value,params)=>inst.check(_gte2(value,params)),inst.gt=(value,params)=>inst.check(_gt2(value,params)),inst.gte=(value,params)=>inst.check(_gte2(value,params)),inst.min=(value,params)=>inst.check(_gte2(value,params)),inst.lt=(value,params)=>inst.check(_lt2(value,params)),inst.lte=(value,params)=>inst.check(_lte2(value,params)),inst.max=(value,params)=>inst.check(_lte2(value,params)),inst.positive=(params)=>inst.check(_gt2(BigInt(0),params)),inst.negative=(params)=>inst.check(_lt2(BigInt(0),params)),inst.nonpositive=(params)=>inst.check(_lte2(BigInt(0),params)),inst.nonnegative=(params)=>inst.check(_gte2(BigInt(0),params)),inst.multipleOf=(value,params)=>inst.check(_multipleOf2(value,params));let bag=inst._zod.bag;inst.minValue=bag.minimum??null,inst.maxValue=bag.maximum??null,inst.format=bag.format??null});ZodBigIntFormat2=$constructor2("ZodBigIntFormat",(inst,def)=>{$ZodBigIntFormat2.init(inst,def),ZodBigInt2.init(inst,def)});ZodSymbol2=$constructor2("ZodSymbol",(inst,def)=>{$ZodSymbol2.init(inst,def),ZodType2.init(inst,def)});ZodUndefined2=$constructor2("ZodUndefined",(inst,def)=>{$ZodUndefined2.init(inst,def),ZodType2.init(inst,def)});ZodNull2=$constructor2("ZodNull",(inst,def)=>{$ZodNull2.init(inst,def),ZodType2.init(inst,def)});ZodAny2=$constructor2("ZodAny",(inst,def)=>{$ZodAny2.init(inst,def),ZodType2.init(inst,def)});ZodUnknown2=$constructor2("ZodUnknown",(inst,def)=>{$ZodUnknown2.init(inst,def),ZodType2.init(inst,def)});ZodNever2=$constructor2("ZodNever",(inst,def)=>{$ZodNever2.init(inst,def),ZodType2.init(inst,def)});ZodVoid2=$constructor2("ZodVoid",(inst,def)=>{$ZodVoid2.init(inst,def),ZodType2.init(inst,def)});ZodDate2=$constructor2("ZodDate",(inst,def)=>{$ZodDate2.init(inst,def),ZodType2.init(inst,def),inst.min=(value,params)=>inst.check(_gte2(value,params)),inst.max=(value,params)=>inst.check(_lte2(value,params));let c=inst._zod.bag;inst.minDate=c.minimum?new Date(c.minimum):null,inst.maxDate=c.maximum?new Date(c.maximum):null});ZodArray2=$constructor2("ZodArray",(inst,def)=>{$ZodArray2.init(inst,def),ZodType2.init(inst,def),inst.element=def.element,inst.min=(minLength,params)=>inst.check(_minLength2(minLength,params)),inst.nonempty=(params)=>inst.check(_minLength2(1,params)),inst.max=(maxLength,params)=>inst.check(_maxLength2(maxLength,params)),inst.length=(len,params)=>inst.check(_length2(len,params)),inst.unwrap=()=>inst.element});ZodObject2=$constructor2("ZodObject",(inst,def)=>{$ZodObjectJIT2.init(inst,def),ZodType2.init(inst,def),exports_util2.defineLazy(inst,"shape",()=>def.shape),inst.keyof=()=>_enum4(Object.keys(inst._zod.def.shape)),inst.catchall=(catchall)=>inst.clone({...inst._zod.def,catchall}),inst.passthrough=()=>inst.clone({...inst._zod.def,catchall:unknown2()}),inst.loose=()=>inst.clone({...inst._zod.def,catchall:unknown2()}),inst.strict=()=>inst.clone({...inst._zod.def,catchall:never2()}),inst.strip=()=>inst.clone({...inst._zod.def,catchall:void 0}),inst.extend=(incoming)=>{return exports_util2.extend(inst,incoming)},inst.safeExtend=(incoming)=>{return exports_util2.safeExtend(inst,incoming)},inst.merge=(other)=>exports_util2.merge(inst,other),inst.pick=(mask)=>exports_util2.pick(inst,mask),inst.omit=(mask)=>exports_util2.omit(inst,mask),inst.partial=(...args2)=>exports_util2.partial(ZodOptional2,inst,args2[0]),inst.required=(...args2)=>exports_util2.required(ZodNonOptional2,inst,args2[0])});ZodUnion2=$constructor2("ZodUnion",(inst,def)=>{$ZodUnion2.init(inst,def),ZodType2.init(inst,def),inst.options=def.options});ZodDiscriminatedUnion2=$constructor2("ZodDiscriminatedUnion",(inst,def)=>{ZodUnion2.init(inst,def),$ZodDiscriminatedUnion2.init(inst,def)});ZodIntersection2=$constructor2("ZodIntersection",(inst,def)=>{$ZodIntersection2.init(inst,def),ZodType2.init(inst,def)});ZodTuple2=$constructor2("ZodTuple",(inst,def)=>{$ZodTuple2.init(inst,def),ZodType2.init(inst,def),inst.rest=(rest)=>inst.clone({...inst._zod.def,rest})});ZodRecord2=$constructor2("ZodRecord",(inst,def)=>{$ZodRecord2.init(inst,def),ZodType2.init(inst,def),inst.keyType=def.keyType,inst.valueType=def.valueType});ZodMap2=$constructor2("ZodMap",(inst,def)=>{$ZodMap2.init(inst,def),ZodType2.init(inst,def),inst.keyType=def.keyType,inst.valueType=def.valueType});ZodSet2=$constructor2("ZodSet",(inst,def)=>{$ZodSet2.init(inst,def),ZodType2.init(inst,def),inst.min=(...args2)=>inst.check(_minSize2(...args2)),inst.nonempty=(params)=>inst.check(_minSize2(1,params)),inst.max=(...args2)=>inst.check(_maxSize2(...args2)),inst.size=(...args2)=>inst.check(_size2(...args2))});ZodEnum2=$constructor2("ZodEnum",(inst,def)=>{$ZodEnum2.init(inst,def),ZodType2.init(inst,def),inst.enum=def.entries,inst.options=Object.values(def.entries);let keys=new Set(Object.keys(def.entries));inst.extract=(values,params)=>{let newEntries={};for(let value of values)if(keys.has(value))newEntries[value]=def.entries[value];else throw Error(`Key ${value} not found in enum`);return new ZodEnum2({...def,checks:[],...exports_util2.normalizeParams(params),entries:newEntries})},inst.exclude=(values,params)=>{let newEntries={...def.entries};for(let value of values)if(keys.has(value))delete newEntries[value];else throw Error(`Key ${value} not found in enum`);return new ZodEnum2({...def,checks:[],...exports_util2.normalizeParams(params),entries:newEntries})}});ZodLiteral2=$constructor2("ZodLiteral",(inst,def)=>{$ZodLiteral2.init(inst,def),ZodType2.init(inst,def),inst.values=new Set(def.values),Object.defineProperty(inst,"value",{get(){if(def.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return def.values[0]}})});ZodFile2=$constructor2("ZodFile",(inst,def)=>{$ZodFile2.init(inst,def),ZodType2.init(inst,def),inst.min=(size,params)=>inst.check(_minSize2(size,params)),inst.max=(size,params)=>inst.check(_maxSize2(size,params)),inst.mime=(types,params)=>inst.check(_mime2(Array.isArray(types)?types:[types],params))});ZodTransform2=$constructor2("ZodTransform",(inst,def)=>{$ZodTransform2.init(inst,def),ZodType2.init(inst,def),inst._zod.parse=(payload,_ctx)=>{if(_ctx.direction==="backward")throw new $ZodEncodeError2(inst.constructor.name);payload.addIssue=(issue3)=>{if(typeof issue3==="string")payload.issues.push(exports_util2.issue(issue3,payload.value,def));else{let _issue=issue3;if(_issue.fatal)_issue.continue=!1;_issue.code??(_issue.code="custom"),_issue.input??(_issue.input=payload.value),_issue.inst??(_issue.inst=inst),payload.issues.push(exports_util2.issue(_issue))}};let output=def.transform(payload.value,payload);if(output instanceof Promise)return output.then((output2)=>{return payload.value=output2,payload});return payload.value=output,payload}});ZodOptional2=$constructor2("ZodOptional",(inst,def)=>{$ZodOptional2.init(inst,def),ZodType2.init(inst,def),inst.unwrap=()=>inst._zod.def.innerType});ZodNullable2=$constructor2("ZodNullable",(inst,def)=>{$ZodNullable2.init(inst,def),ZodType2.init(inst,def),inst.unwrap=()=>inst._zod.def.innerType});ZodDefault2=$constructor2("ZodDefault",(inst,def)=>{$ZodDefault2.init(inst,def),ZodType2.init(inst,def),inst.unwrap=()=>inst._zod.def.innerType,inst.removeDefault=inst.unwrap});ZodPrefault2=$constructor2("ZodPrefault",(inst,def)=>{$ZodPrefault2.init(inst,def),ZodType2.init(inst,def),inst.unwrap=()=>inst._zod.def.innerType});ZodNonOptional2=$constructor2("ZodNonOptional",(inst,def)=>{$ZodNonOptional2.init(inst,def),ZodType2.init(inst,def),inst.unwrap=()=>inst._zod.def.innerType});ZodSuccess2=$constructor2("ZodSuccess",(inst,def)=>{$ZodSuccess2.init(inst,def),ZodType2.init(inst,def),inst.unwrap=()=>inst._zod.def.innerType});ZodCatch2=$constructor2("ZodCatch",(inst,def)=>{$ZodCatch2.init(inst,def),ZodType2.init(inst,def),inst.unwrap=()=>inst._zod.def.innerType,inst.removeCatch=inst.unwrap});ZodNaN2=$constructor2("ZodNaN",(inst,def)=>{$ZodNaN2.init(inst,def),ZodType2.init(inst,def)});ZodPipe2=$constructor2("ZodPipe",(inst,def)=>{$ZodPipe2.init(inst,def),ZodType2.init(inst,def),inst.in=def.in,inst.out=def.out});ZodCodec2=$constructor2("ZodCodec",(inst,def)=>{ZodPipe2.init(inst,def),$ZodCodec2.init(inst,def)});ZodReadonly2=$constructor2("ZodReadonly",(inst,def)=>{$ZodReadonly2.init(inst,def),ZodType2.init(inst,def),inst.unwrap=()=>inst._zod.def.innerType});ZodTemplateLiteral2=$constructor2("ZodTemplateLiteral",(inst,def)=>{$ZodTemplateLiteral2.init(inst,def),ZodType2.init(inst,def)});ZodLazy2=$constructor2("ZodLazy",(inst,def)=>{$ZodLazy2.init(inst,def),ZodType2.init(inst,def),inst.unwrap=()=>inst._zod.def.getter()});ZodPromise2=$constructor2("ZodPromise",(inst,def)=>{$ZodPromise2.init(inst,def),ZodType2.init(inst,def),inst.unwrap=()=>inst._zod.def.innerType});ZodFunction2=$constructor2("ZodFunction",(inst,def)=>{$ZodFunction2.init(inst,def),ZodType2.init(inst,def)});ZodCustom2=$constructor2("ZodCustom",(inst,def)=>{$ZodCustom2.init(inst,def),ZodType2.init(inst,def)})});function setErrorMap2(map3){config2({customError:map3})}function getErrorMap2(){return config2().customError}var ZodIssueCode2,ZodFirstPartyTypeKind2;var init_compat2=__esm(()=>{init_core5();ZodIssueCode2={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};(function(ZodFirstPartyTypeKind3){})(ZodFirstPartyTypeKind2||(ZodFirstPartyTypeKind2={}))});var exports_coerce2={};__export(exports_coerce2,{string:()=>string6,number:()=>number6,date:()=>date8,boolean:()=>boolean6,bigint:()=>bigint6});function string6(params){return _coercedString2(ZodString2,params)}function number6(params){return _coercedNumber2(ZodNumber2,params)}function boolean6(params){return _coercedBoolean2(ZodBoolean2,params)}function bigint6(params){return _coercedBigint2(ZodBigInt2,params)}function date8(params){return _coercedDate2(ZodDate2,params)}var init_coerce2=__esm(()=>{init_core5();init_schemas4()});var exports_external2={};__export(exports_external2,{xid:()=>xid4,void:()=>_void4,uuidv7:()=>uuidv72,uuidv6:()=>uuidv62,uuidv4:()=>uuidv42,uuid:()=>uuid5,util:()=>exports_util2,url:()=>url2,uppercase:()=>_uppercase2,unknown:()=>unknown2,union:()=>union2,undefined:()=>_undefined6,ulid:()=>ulid4,uint64:()=>uint642,uint32:()=>uint322,tuple:()=>tuple2,trim:()=>_trim2,treeifyError:()=>treeifyError2,transform:()=>transform2,toUpperCase:()=>_toUpperCase2,toLowerCase:()=>_toLowerCase2,toJSONSchema:()=>toJSONSchema2,templateLiteral:()=>templateLiteral2,symbol:()=>symbol2,superRefine:()=>superRefine2,success:()=>success2,stringbool:()=>stringbool2,stringFormat:()=>stringFormat2,string:()=>string5,strictObject:()=>strictObject2,startsWith:()=>_startsWith2,size:()=>_size2,setErrorMap:()=>setErrorMap2,set:()=>set2,safeParseAsync:()=>safeParseAsync4,safeParse:()=>safeParse4,safeEncodeAsync:()=>safeEncodeAsync4,safeEncode:()=>safeEncode4,safeDecodeAsync:()=>safeDecodeAsync4,safeDecode:()=>safeDecode4,registry:()=>registry2,regexes:()=>exports_regexes2,regex:()=>_regex2,refine:()=>refine2,record:()=>record2,readonly:()=>readonly2,property:()=>_property2,promise:()=>promise2,prettifyError:()=>prettifyError2,preprocess:()=>preprocess2,prefault:()=>prefault2,positive:()=>_positive2,pipe:()=>pipe2,partialRecord:()=>partialRecord2,parseAsync:()=>parseAsync4,parse:()=>parse7,overwrite:()=>_overwrite2,optional:()=>optional2,object:()=>object2,number:()=>number5,nullish:()=>nullish4,nullable:()=>nullable2,null:()=>_null6,normalize:()=>_normalize2,nonpositive:()=>_nonpositive2,nonoptional:()=>nonoptional2,nonnegative:()=>_nonnegative2,never:()=>never2,negative:()=>_negative2,nativeEnum:()=>nativeEnum2,nanoid:()=>nanoid4,nan:()=>nan2,multipleOf:()=>_multipleOf2,minSize:()=>_minSize2,minLength:()=>_minLength2,mime:()=>_mime2,maxSize:()=>_maxSize2,maxLength:()=>_maxLength2,map:()=>map2,lte:()=>_lte2,lt:()=>_lt2,lowercase:()=>_lowercase2,looseObject:()=>looseObject2,locales:()=>exports_locales2,literal:()=>literal3,length:()=>_length2,lazy:()=>lazy2,ksuid:()=>ksuid4,keyof:()=>keyof2,jwt:()=>jwt2,json:()=>json2,iso:()=>exports_iso2,ipv6:()=>ipv64,ipv4:()=>ipv44,intersection:()=>intersection2,int64:()=>int642,int32:()=>int322,int:()=>int2,instanceof:()=>_instanceof2,includes:()=>_includes2,httpUrl:()=>httpUrl2,hostname:()=>hostname4,hex:()=>hex4,hash:()=>hash3,guid:()=>guid4,gte:()=>_gte2,gt:()=>_gt2,globalRegistry:()=>globalRegistry2,getErrorMap:()=>getErrorMap2,function:()=>_function2,formatError:()=>formatError2,float64:()=>float642,float32:()=>float322,flattenError:()=>flattenError2,file:()=>file2,enum:()=>_enum4,endsWith:()=>_endsWith2,encodeAsync:()=>encodeAsync4,encode:()=>encode4,emoji:()=>emoji4,email:()=>email4,e164:()=>e1644,discriminatedUnion:()=>discriminatedUnion2,decodeAsync:()=>decodeAsync4,decode:()=>decode4,date:()=>date7,custom:()=>custom2,cuid2:()=>cuid24,cuid:()=>cuid6,core:()=>exports_core5,config:()=>config2,coerce:()=>exports_coerce2,codec:()=>codec3,clone:()=>clone2,cidrv6:()=>cidrv64,cidrv4:()=>cidrv44,check:()=>check2,catch:()=>_catch4,boolean:()=>boolean5,bigint:()=>bigint5,base64url:()=>base64url4,base64:()=>base644,array:()=>array2,any:()=>any2,_function:()=>_function2,_default:()=>_default4,_ZodString:()=>_ZodString2,ZodXID:()=>ZodXID2,ZodVoid:()=>ZodVoid2,ZodUnknown:()=>ZodUnknown2,ZodUnion:()=>ZodUnion2,ZodUndefined:()=>ZodUndefined2,ZodUUID:()=>ZodUUID2,ZodURL:()=>ZodURL2,ZodULID:()=>ZodULID2,ZodType:()=>ZodType2,ZodTuple:()=>ZodTuple2,ZodTransform:()=>ZodTransform2,ZodTemplateLiteral:()=>ZodTemplateLiteral2,ZodSymbol:()=>ZodSymbol2,ZodSuccess:()=>ZodSuccess2,ZodStringFormat:()=>ZodStringFormat2,ZodString:()=>ZodString2,ZodSet:()=>ZodSet2,ZodRecord:()=>ZodRecord2,ZodRealError:()=>ZodRealError2,ZodReadonly:()=>ZodReadonly2,ZodPromise:()=>ZodPromise2,ZodPrefault:()=>ZodPrefault2,ZodPipe:()=>ZodPipe2,ZodOptional:()=>ZodOptional2,ZodObject:()=>ZodObject2,ZodNumberFormat:()=>ZodNumberFormat2,ZodNumber:()=>ZodNumber2,ZodNullable:()=>ZodNullable2,ZodNull:()=>ZodNull2,ZodNonOptional:()=>ZodNonOptional2,ZodNever:()=>ZodNever2,ZodNanoID:()=>ZodNanoID2,ZodNaN:()=>ZodNaN2,ZodMap:()=>ZodMap2,ZodLiteral:()=>ZodLiteral2,ZodLazy:()=>ZodLazy2,ZodKSUID:()=>ZodKSUID2,ZodJWT:()=>ZodJWT2,ZodIssueCode:()=>ZodIssueCode2,ZodIntersection:()=>ZodIntersection2,ZodISOTime:()=>ZodISOTime2,ZodISODuration:()=>ZodISODuration2,ZodISODateTime:()=>ZodISODateTime2,ZodISODate:()=>ZodISODate2,ZodIPv6:()=>ZodIPv62,ZodIPv4:()=>ZodIPv42,ZodGUID:()=>ZodGUID2,ZodFunction:()=>ZodFunction2,ZodFirstPartyTypeKind:()=>ZodFirstPartyTypeKind2,ZodFile:()=>ZodFile2,ZodError:()=>ZodError2,ZodEnum:()=>ZodEnum2,ZodEmoji:()=>ZodEmoji2,ZodEmail:()=>ZodEmail2,ZodE164:()=>ZodE1642,ZodDiscriminatedUnion:()=>ZodDiscriminatedUnion2,ZodDefault:()=>ZodDefault2,ZodDate:()=>ZodDate2,ZodCustomStringFormat:()=>ZodCustomStringFormat2,ZodCustom:()=>ZodCustom2,ZodCodec:()=>ZodCodec2,ZodCatch:()=>ZodCatch2,ZodCUID2:()=>ZodCUID22,ZodCUID:()=>ZodCUID3,ZodCIDRv6:()=>ZodCIDRv62,ZodCIDRv4:()=>ZodCIDRv42,ZodBoolean:()=>ZodBoolean2,ZodBigIntFormat:()=>ZodBigIntFormat2,ZodBigInt:()=>ZodBigInt2,ZodBase64URL:()=>ZodBase64URL2,ZodBase64:()=>ZodBase642,ZodArray:()=>ZodArray2,ZodAny:()=>ZodAny2,TimePrecision:()=>TimePrecision2,NEVER:()=>NEVER2,$output:()=>$output2,$input:()=>$input2,$brand:()=>$brand2});var init_external2=__esm(()=>{init_core5();init_core5();init_en2();init_core5();init_locales2();init_iso2();init_iso2();init_coerce2();init_schemas4();init_checks4();init_errors5();init_parse4();init_compat2();config2(en_default2())});var init_zod2=__esm(()=>{init_external2();init_external2()});function tool(input){return input}var init_tool=__esm(()=>{init_zod2();tool.schema=exports_external2});var init_dist=__esm(()=>{init_tool()});import*as fs41 from"node:fs";import*as path69 from"node:path";function resolveWorkingDirectory(workingDirectory,fallbackDirectory){if(workingDirectory==null||workingDirectory===""){if(typeof fallbackDirectory!=="string"||fallbackDirectory==="")return{success:!1,message:"Invalid working_directory: no explicit working_directory was provided and fallbackDirectory is missing or not a string"};try{assertProjectRoot(fallbackDirectory)}catch(error93){return{success:!1,message:error93 instanceof Error?error93.message:String(error93)}}return{success:!0,directory:fallbackDirectory}}if(typeof workingDirectory!=="string")return{success:!1,message:"Invalid working_directory: path must be a string"};if(workingDirectory.includes("\x00"))return{success:!1,message:"Invalid working_directory: null bytes are not allowed"};let reservedDevicePattern=/^(NUL|CON|AUX|COM[1-9]|LPT[1-9])(\..*)?$/i;if(workingDirectory.startsWith("\\\\")||process.platform==="win32"&&reservedDevicePattern.test(workingDirectory))return{success:!1,message:"Invalid working_directory: Windows device paths are not allowed"};if(workingDirectory.split(/[\\/]/).includes(".."))return{success:!1,message:"Invalid working_directory: path traversal sequences (..) are not allowed"};let normalizedDir=path69.normalize(workingDirectory),resolvedDir=path69.resolve(normalizedDir),statResult;try{statResult=fs41.statSync(resolvedDir)}catch{return{success:!1,message:`Invalid working_directory: path "${resolvedDir}" does not exist or is inaccessible`}}if(!statResult.isDirectory())return{success:!1,message:`Invalid working_directory: path "${resolvedDir}" is not a directory`};try{assertProjectRoot(resolvedDir)}catch(error93){return{success:!1,message:error93 instanceof Error?error93.message:String(error93)}}if(typeof fallbackDirectory!=="string"||fallbackDirectory==="")return{success:!0,directory:resolvedDir};let resolvedFallback=path69.resolve(fallbackDirectory),fallbackExists=!1;try{fs41.statSync(resolvedFallback),fallbackExists=!0}catch{fallbackExists=!1}if(fallbackExists){if(isStrictPathDescendant(resolvedDir,resolvedFallback)){if(hasExplicitProjectBoundary(resolvedDir))return{success:!0,directory:resolvedDir};return{success:!1,message:`Invalid working_directory: "${workingDirectory}" resolves to "${resolvedDir}" which is a subdirectory of fallback "${resolvedFallback}". Pass the project root path or omit working_directory entirely.`}}}return{success:!0,directory:resolvedDir}}var init_resolve_working_directory=__esm(()=>{init_project_boundary()});function classifyToolError(error93){let msg=(error93 instanceof Error?error93.message??"":String(error93)).toLowerCase();if(msg.includes("not registered")||msg.includes("unknown tool"))return"not_registered";if(msg.includes("not whitelisted")||msg.includes("not allowed"))return"not_whitelisted";if(msg.includes("enoent")||msg.includes("command not found")||msg.includes("binary not found")||msg.includes("no such file or directory"))return"binary_missing";return"execution_error"}function createSwarmTool(opts){let ownsWorkingDirectory=Object.hasOwn(opts.args,"working_directory"),allowsWorkingDirectoryOverride=opts.allowWorkingDirectoryOverride===!0&&!ownsWorkingDirectory,toolArgs=allowsWorkingDirectoryOverride?{...opts.args,working_directory:exports_external.string().optional().describe("Project or linked-worktree root for this tool invocation")}:opts.args;return tool({description:opts.description,args:toolArgs,execute:async(args2,ctx)=>{let fallbackDirectory=ctx?.directory??process.cwd();try{let effectiveArgs=args2,effectiveDirectory=fallbackDirectory,effectiveContext=ctx;if(!ownsWorkingDirectory&&typeof args2==="object"&&args2!==null){if(!allowsWorkingDirectoryOverride&&Object.hasOwn(args2,"working_directory"))throw Error("Invalid working_directory: this tool does not allow working_directory overrides");if(allowsWorkingDirectoryOverride&&Object.hasOwn(args2,"working_directory")){let{working_directory:workingDirectory,...executorArgs}=args2;if(effectiveArgs=executorArgs,workingDirectory!==void 0){let resolved=resolveWorkingDirectory(workingDirectory,fallbackDirectory);if(!resolved.success)throw Error(resolved.message);effectiveDirectory=resolved.directory,effectiveContext={...ctx,directory:resolved.directory,worktree:resolved.directory}}}}return await opts.execute(effectiveArgs,effectiveDirectory,effectiveContext)}catch(error93){let message=error93 instanceof Error?error93.message:String(error93);return JSON.stringify({success:!1,failure_class:classifyToolError(error93),message:"Tool execution failed",errors:[message]},null,2)}}})}var init_create_tool=__esm(()=>{init_dist();init_zod();init_resolve_working_directory()});var exports_checkpoint={};__export(exports_checkpoint,{saveCheckpointRecord:()=>saveCheckpointRecord,checkpoint:()=>checkpoint,_internals:()=>_internals65});import*as child_process3 from"node:child_process";import*as fs42 from"node:fs";import*as path70 from"node:path";function serializeResult(action,payload){return JSON.stringify({action,...payload},null,2)}function containsNonAsciiChars(label){for(let i=0;i<label.length;i++){let charCode=label.charCodeAt(i);if(charCode<32||charCode>126)return!0}return!1}function validateLabel(label){if(!label||label.length===0)return"label is required";if(label.length>MAX_LABEL_LENGTH)return`label exceeds maximum length of ${MAX_LABEL_LENGTH}`;if(label.startsWith("--"))return'label cannot start with "--" (git flag pattern)';if(CONTROL_CHAR_PATTERN.test(label))return"label contains control characters";if(NON_ASCII_PATTERN.test(label))return"label contains non-ASCII or invalid characters";if(containsNonAsciiChars(label))return"label contains non-ASCII characters (must be printable ASCII only)";if(SHELL_METACHARACTERS.test(label))return"label contains shell metacharacters";if(!SAFE_LABEL_PATTERN.test(label))return"label contains invalid characters (use alphanumeric, hyphen, underscore, space)";if(!/[a-zA-Z0-9_]/.test(label))return"label cannot be whitespace-only";if(label.includes("..")||label.includes("/")||label.includes("\\"))return"label contains path traversal sequence";return null}function getCheckpointLogPath(directory){return path70.join(directory,CHECKPOINT_LOG_PATH)}function readCheckpointLog(directory){let logPath=getCheckpointLogPath(directory);try{if(fs42.existsSync(logPath)){let content=fs42.readFileSync(logPath,"utf-8"),parsed=JSON.parse(content);if(!parsed.checkpoints||!Array.isArray(parsed.checkpoints))return{version:1,checkpoints:[]};return parsed}}catch{}return{version:1,checkpoints:[]}}function writeCheckpointLog(log2,directory){let logPath=getCheckpointLogPath(directory),dir=path70.dirname(logPath);if(!fs42.existsSync(dir))fs42.mkdirSync(dir,{recursive:!0});let tempPath=`${logPath}.tmp`;fs42.writeFileSync(tempPath,JSON.stringify(log2,null,2),"utf-8"),fs42.renameSync(tempPath,logPath)}function appendRetentionEvent(directory,event){try{appendCoreEventSync(directory,{...event,timestamp:new Date().toISOString()})}catch{}}function loadCheckpointConfig(directory){let maxCheckpoints=20,allowEmptyCommits=!1;try{let{config:config3}=loadPluginConfigWithMeta(directory);maxCheckpoints=config3.checkpoint?.max_retention??maxCheckpoints,allowEmptyCommits=config3.checkpoint?.allow_empty_commits===!0}catch{}return{maxCheckpoints,allowEmptyCommits}}function appendCheckpointEntry(directory,log2,entry,maxCheckpoints){let existing=log2.checkpoints.find((checkpoint)=>checkpoint.label===entry.label);if(existing){if(existing.sha!==entry.sha)throw Error(`checkpoint log conflict: label "${entry.label}" already exists with a different SHA`);return}if(log2.checkpoints.push(entry),log2.checkpoints.length>maxCheckpoints){let evicted=log2.checkpoints.splice(0,log2.checkpoints.length-maxCheckpoints);appendRetentionEvent(directory,{event:"checkpoint_retention_applied",evicted_labels:evicted.map((checkpoint)=>checkpoint.label),evicted_count:evicted.length,remaining_count:log2.checkpoints.length})}}function upsertTaskCompletionCheckpointEntry(directory,log2,entry,maxCheckpoints){let existingIndex=log2.checkpoints.findIndex((checkpoint)=>checkpoint.label===entry.label);if(existingIndex>=0){if(log2.checkpoints[existingIndex].sha===entry.sha)return;log2.checkpoints[existingIndex]=entry;return}if(log2.checkpoints.push(entry),log2.checkpoints.length>maxCheckpoints){let evicted=log2.checkpoints.splice(0,log2.checkpoints.length-maxCheckpoints);appendRetentionEvent(directory,{event:"checkpoint_retention_applied",evicted_labels:evicted.map((checkpoint)=>checkpoint.label),evicted_count:evicted.length,remaining_count:log2.checkpoints.length})}}function stageAllExcludingSwarm(directory){_internals65.gitExec(["add","--all","--",...NON_SWARM_COMMIT_PATHSPEC],directory)}function gitExec2(args2,cwd){for(let attempt=0;attempt<MAX_TRANSIENT_RETRIES;attempt++){let result=child_process3.spawnSync(_internals65.resolveGitExecutable(),args2,{cwd,encoding:"utf-8",timeout:GIT_TIMEOUT_MS2,stdio:["ignore","pipe","pipe"],windowsHide:!0,maxBuffer:GIT_MAX_BUFFER_BYTES2});if(result.error){let code=result.error.code,message=result.error.message??"";if(!(isTransientSpawnError(result.error)||/ETIMEDOUT|timed out/i.test(message))||attempt>=MAX_TRANSIENT_RETRIES-1){if(isSpawnCwdMissing(result.error,cwd))throw new GitSpawnCwdError(cwd,"missing");if(isSpawnCwdUnreadable(result.error,cwd))throw new GitSpawnCwdError(cwd,"unreadable");if(isGitBinaryMissing(result.error,cwd))throw new GitBinaryMissingError(`git executable is not available on PATH (working directory ${cwd} exists)`,{cause:result.error});throw Error(`git failed to start: ${code??"unknown"} - ${message}`)}transientBackoff(attempt);continue}if(result.status===0)return result.stdout??"";throw Error(result.stderr?.trim()||`git exited with code ${result.status}`)}throw Error("git command failed after transient retries")}function getCurrentSha(directory){return gitExec2(["rev-parse","HEAD"],directory).trim()}function isGitRepo2(directory){try{return gitExec2(["rev-parse","--git-dir"],directory),{isRepo:!0}}catch(e){let message=e instanceof Error?e.message:String(e);if(/ETIMEDOUT|timed out/i.test(message)&&!/not a git repository/i.test(message))return{isRepo:!1,warning:"git probe failed after retry exhaustion - treating as not a git repository"};return{isRepo:!1,warning:"git probe failed - directory may not be a git repository"}}}function findCommitByExactSubject(directory,subject){let output=_internals65.gitExec(["log","HEAD","--format=%H%x00%s","--fixed-strings",`--grep=${subject}`,"-n",String(CHECKPOINT_RECEIPT_LOOKUP_LIMIT)],directory);for(let line of output.split(/\r?\n/)){if(!line)continue;let nulIndex=line.indexOf("\x00");if(nulIndex<=0)continue;let sha=line.slice(0,nulIndex).trim(),candidateSubject=line.slice(nulIndex+1);if(sha.length===40&&/^[a-f0-9]{40}$/i.test(sha)&&candidateSubject===subject)return sha}return null}async function withTaskCompletionLocksResult(input){let deadline=Date.now()+CHECKPOINT_LOCK_DEADLINE_MS,attempts=0;while(attempts<CHECKPOINT_LOCK_MAX_ATTEMPTS&&Date.now()<=deadline){attempts++;let planLockResult;try{planLockResult=await _internals65.tryAcquireLock(input.directory,PLAN_LOCK_PATH,CHECKPOINT_AGENT_NAME,`save-task-completion-plan-${input.taskId}`)}catch(error93){if(input.onFailure)return input.onFailure(error93);return serializeResult("save_task_completion",{success:!1,error:`save_task_completion failed: ${error93 instanceof Error?error93.message:String(error93)}`})}if(!planLockResult.acquired){if(attempts>=CHECKPOINT_LOCK_MAX_ATTEMPTS||Date.now()+CHECKPOINT_LOCK_DELAY_MS>deadline)break;await _internals65.sleep(CHECKPOINT_LOCK_DELAY_MS);continue}try{let checkpointLockResult;try{checkpointLockResult=await _internals65.tryAcquireLock(input.directory,CHECKPOINT_LOG_PATH,CHECKPOINT_AGENT_NAME,`save-task-completion-checkpoint-${input.taskId}`)}catch(error93){if(input.onFailure)return input.onFailure(error93);return serializeResult("save_task_completion",{success:!1,error:`save_task_completion failed: ${error93 instanceof Error?error93.message:String(error93)}`})}if(!checkpointLockResult.acquired){if(attempts>=CHECKPOINT_LOCK_MAX_ATTEMPTS||Date.now()+CHECKPOINT_LOCK_DELAY_MS>deadline)break;await _internals65.sleep(CHECKPOINT_LOCK_DELAY_MS);continue}try{return await input.run()}catch(error93){if(input.onFailure)return input.onFailure(error93);return serializeResult("save_task_completion",{success:!1,error:`save_task_completion failed: ${error93 instanceof Error?error93.message:String(error93)}`})}finally{if(checkpointLockResult.lock._release)try{await checkpointLockResult.lock._release()}catch{}}}finally{if(planLockResult.lock._release)try{await planLockResult.lock._release()}catch{}}}if(input.onBusy)return input.onBusy(attempts);return serializeResult("save_task_completion",{success:!1,status:"checkpoint_busy",error:"checkpoint_busy: checkpoint or plan state is locked by another operation; retry after the current mutation completes",retryable:!0,attempts})}async function withCheckpointMutationLock(input){return await withCheckpointMutationLockResult({action:input.action,directory:input.directory,operationKey:input.operationKey,run:input.run,onContendedAttempt:input.onContendedAttempt})}async function withCheckpointMutationLockResult(input){let deadline=Date.now()+CHECKPOINT_LOCK_DEADLINE_MS,attempts=0;while(attempts<CHECKPOINT_LOCK_MAX_ATTEMPTS&&Date.now()<=deadline){attempts++;let lockResult;try{lockResult=await _internals65.tryAcquireLock(input.directory,CHECKPOINT_LOG_PATH,CHECKPOINT_AGENT_NAME,input.operationKey)}catch(error93){if(input.onFailure)return input.onFailure(error93);return serializeResult(input.action,{success:!1,error:`${input.action} failed: ${error93 instanceof Error?error93.message:String(error93)}`})}if(lockResult.acquired)try{try{return await input.run()}catch(error93){if(input.onFailure)return input.onFailure(error93);return serializeResult(input.action,{success:!1,error:`${input.action} failed: ${error93 instanceof Error?error93.message:String(error93)}`})}}finally{if(lockResult.lock._release)try{await lockResult.lock._release()}catch{}}let contended=input.onContendedAttempt?.();if(contended)return contended;if(attempts>=CHECKPOINT_LOCK_MAX_ATTEMPTS||Date.now()+CHECKPOINT_LOCK_DELAY_MS>deadline)break;await _internals65.sleep(CHECKPOINT_LOCK_DELAY_MS)}if(input.onBusy)return input.onBusy(attempts);return serializeResult(input.action,{success:!1,status:"checkpoint_busy",error:"checkpoint_busy: checkpoint state is locked by another operation; retry after the current mutation completes",retryable:!0,attempts})}function handleSave(label,directory){try{let{maxCheckpoints,allowEmptyCommits}=loadCheckpointConfig(directory),log2=readCheckpointLog(directory);if(log2.checkpoints.find((checkpoint)=>checkpoint.label===label))return serializeResult("save",{success:!1,error:`duplicate label: "${label}" already exists. Use a different label or delete the existing checkpoint first.`});let timestamp=new Date().toISOString();if(_internals65.stageAllExcludingSwarm(directory),(()=>{try{return gitExec2(["diff","--cached","--quiet"],directory),!1}catch{return!0}})())gitExec2(["commit","-m",`checkpoint: ${label}`],directory);else if(allowEmptyCommits)gitExec2(["commit","--allow-empty","-m",`checkpoint: ${label}`],directory);let newSha=getCurrentSha(directory);return appendCheckpointEntry(directory,log2,{label,sha:newSha,timestamp},maxCheckpoints),writeCheckpointLog(log2,directory),serializeResult("save",{success:!0,label,sha:newSha,message:`Checkpoint saved: "${label}"`})}catch(e){return serializeResult("save",{success:!1,error:e instanceof Error?`save failed: ${e.message}`:"save failed: unknown error"})}}async function saveCheckpointRecord(label,directory){let labelError=validateLabel(label);if(labelError)return{success:!1,error:labelError};return withCheckpointMutationLockResult({action:"save",directory,operationKey:`save-record-${label}`,run:async()=>{let log2=readCheckpointLog(directory);if(log2.checkpoints.find((checkpoint)=>checkpoint.label===label))return{success:!1,error:`duplicate label: "${label}"`};let sha="";if(isGitRepo2(directory).isRepo)try{sha=getCurrentSha(directory)}catch{sha=""}appendCheckpointEntry(directory,log2,{label,sha,timestamp:new Date().toISOString()},loadCheckpointConfig(directory).maxCheckpoints),writeCheckpointLog(log2,directory);let result={success:!0,sha};if(!sha)result.warning="no git restore target - checkpoint recorded without a SHA (directory may not be a git repository or HEAD is unavailable)";return result},onBusy:()=>({success:!1,error:"checkpoint_busy: checkpoint state is locked by another operation; retry after the current mutation completes"}),onFailure:(error93)=>({success:!1,error:error93 instanceof Error?error93.message:"unknown error"})})}async function handleRestore(label,directory,confirmToken){try{let log2=readCheckpointLog(directory),checkpoint=log2.checkpoints.find((candidate)=>candidate.label===label);if(!checkpoint)return serializeResult("restore",{success:!1,error:`checkpoint not found: "${label}"`});let measurement=await measureGitDestruction(directory,checkpoint.sha);if(measurement.kind==="unreadable"){let cause=describeUnreadableCause(measurement);return serializeResult("restore",{success:!1,error:`cannot verify the working tree (git status unreadable; ${cause}) — refusing to restore without a preview.`})}if(measurement.dirtyRelPaths.length>0){let candidates=trackedDirtyCandidates(directory,measurement.dirtyRelPaths),scopeAnchor=candidates[0].path;if(!confirmToken){let token=issueConfirmToken(scopeAnchor,directory,{kind:ROLLBACK_GIT_KIND,candidates}),shown=measurement.dirtyRelPaths.slice(0,10),overflow=measurement.dirtyRelPaths.length-shown.length;return serializeResult("restore",{success:!1,requires_confirm:!0,preview:[`Restoring to checkpoint "${label}" runs a hard git reset and would DESTROY ${candidates.length} uncommitted tracked file(s):`,...shown.map((p)=>` - ${p}`),...overflow>0?[` (+${overflow} more)`]:[],"Backups are taken automatically once confirmed."],confirm_token:token,message:"restore preview — re-run with confirm_token to execute (valid 15 minutes)"})}let verdict=consumeConfirmToken(scopeAnchor,directory,confirmToken,{kind:ROLLBACK_GIT_KIND,candidates});if(!verdict.ok)return serializeResult("restore",{success:!1,error:verdict.reason});let backup=backupTrackedChangesBeforeRollback(directory,measurement.dirtyRelPaths),atRiskExisting=measurement.dirtyRelPaths.filter((rel)=>fs42.existsSync(path70.join(directory,rel))).length;if(!backup.backupDir||backup.copied.length<atRiskExisting)return serializeResult("restore",{success:!1,error:`backup incomplete (${backup.copied.length}/${atRiskExisting} at-risk file(s) copied) — restore refused so nothing is destroyed.${backup.warnings.length>0?` Warnings: ${backup.warnings.join("; ")}`:""}`});let logBeforeReset2=log2;return gitExec2(["reset","--hard",checkpoint.sha],directory),writeCheckpointLog(logBeforeReset2,directory),serializeResult("restore",{success:!0,label,sha:checkpoint.sha,backup_dir:backup.backupDir,...backup.warnings.length>0?{backup_warnings:backup.warnings}:{},message:`Restored to checkpoint: "${label}" (hard reset)${backup.backupDir?`; destroyed bytes backed up to ${path70.relative(directory,backup.backupDir)}`:""}${backup.warnings.length>0?`; warnings: ${backup.warnings.join("; ")}`:""}`})}let logBeforeReset=log2;return gitExec2(["reset","--hard",checkpoint.sha],directory),writeCheckpointLog(logBeforeReset,directory),serializeResult("restore",{success:!0,label,sha:checkpoint.sha,message:`Restored to checkpoint: "${label}" (hard reset)`})}catch(e){return serializeResult("restore",{success:!1,error:e instanceof Error?`restore failed: ${e.message}`:"restore failed: unknown error"})}}function handleList(directory){let sorted=[...readCheckpointLog(directory).checkpoints].sort((a,b)=>b.timestamp.localeCompare(a.timestamp));return serializeResult("list",{success:!0,count:sorted.length,checkpoints:sorted})}function handleDelete(label,directory){try{let log2=readCheckpointLog(directory),initialLength=log2.checkpoints.length;if(log2.checkpoints=log2.checkpoints.filter((checkpoint)=>checkpoint.label!==label),log2.checkpoints.length===initialLength)return serializeResult("delete",{success:!1,error:`checkpoint not found: "${label}"`});return writeCheckpointLog(log2,directory),serializeResult("delete",{success:!0,label,message:`Checkpoint deleted: "${label}"`})}catch(e){return serializeResult("delete",{success:!1,error:e instanceof Error?`delete failed: ${e.message}`:"delete failed: unknown error"})}}async function handleSaveTaskCompletion(taskId,directory){return withTaskCompletionLocksResult({directory,taskId,run:async()=>{let plan=await _internals65.loadPlan(directory);if(!plan)return serializeResult("save_task_completion",{success:!1,error:"save_task_completion failed: no durable plan is available under .swarm/plan.json"});let task=plan.phases.flatMap((phase)=>phase.tasks).find((candidate)=>candidate.id===taskId);if(!task)return serializeResult("save_task_completion",{success:!1,error:`save_task_completion failed: task "${taskId}" was not found in the current plan`});if(task.status!=="completed")return serializeResult("save_task_completion",{success:!1,error:`save_task_completion failed: task "${taskId}" is ${task.status}, not completed`});await _internals65.afterTaskEligibilityRead?.(directory,task.id);let planIdentityHash=derivePlanIdentityHash(plan),planId=derivePlanId(plan),planEvents=(await readLedgerEvents(directory)).filter((event)=>event.plan_id===planId),anchor=planEvents.find((event)=>event.event_type==="plan_created"),anchorPlan=anchor?.payload?.plan;if(anchorPlan&&typeof anchorPlan==="object"){let rawIdentity=anchorPlan;if(typeof rawIdentity.swarm!=="string"||typeof rawIdentity.title!=="string"||derivePlanIdentityHash({swarm:rawIdentity.swarm,title:rawIdentity.title})!==planIdentityHash)throw Error(`save_task_completion failed: ledger identity does not match the current plan for task "${task.id}"`)}let latestTaskStatusEvent=[...planEvents].reverse().find((event)=>event.event_type==="task_status_changed"&&event.task_id===task.id);if(latestTaskStatusEvent&&latestTaskStatusEvent.to_status!=="completed")throw Error(`save_task_completion failed: the authoritative ledger does not record task "${task.id}" as completed`);let completionLedgerSeq=latestTaskStatusEvent?.seq??anchor?.seq??0,receipt=ensureTaskCheckpointReceipt(directory,planIdentityHash,task.id,completionLedgerSeq),descriptor=buildTaskCompletionDescriptor(planIdentityHash,task.id,receipt.generation);if(receipt.label!==descriptor.label)throw Error(`Task checkpoint receipt label conflict for ${task.id}: expected ${descriptor.label}, found ${receipt.label}`);if(receipt.state==="logged")return serializeResult("save_task_completion",{success:!0,idempotent:!0,label:receipt.label,sha:receipt.sha,receipt_state:receipt.state,message:`Checkpoint task completion already logged for "${descriptor.taskId}"`});let recoveredSha=_internals65.findCommitByExactSubject(directory,descriptor.subject),committedSha=null;if(committedSha=recoveredSha??receipt.sha,!committedSha)_internals65.stageAllExcludingSwarm(directory),_internals65.gitExec(["commit","--allow-empty","-m",descriptor.subject,"--",...NON_SWARM_COMMIT_PATHSPEC],directory),committedSha=getCurrentSha(directory);if(!committedSha)throw Error(`save_task_completion failed: could not resolve commit SHA for task "${descriptor.taskId}"`);updateTaskCheckpointReceipt(directory,descriptor,"committed",committedSha);let log2=readCheckpointLog(directory);upsertTaskCompletionCheckpointEntry(directory,log2,{label:descriptor.label,sha:committedSha,timestamp:new Date().toISOString()},loadCheckpointConfig(directory).maxCheckpoints),writeCheckpointLog(log2,directory);let logged=updateTaskCheckpointReceipt(directory,descriptor,"logged",committedSha);return serializeResult("save_task_completion",{success:!0,label:logged.label,sha:committedSha,receipt_state:logged.state,message:`Checkpoint task completion saved for "${descriptor.taskId}"`})}})}var CHECKPOINT_LOG_PATH=".swarm/checkpoints.json",PLAN_LOCK_PATH="plan.json",CHECKPOINT_AGENT_NAME="checkpoint",MAX_LABEL_LENGTH=100,GIT_TIMEOUT_MS2=30000,GIT_MAX_BUFFER_BYTES2=5242880,CHECKPOINT_LOCK_MAX_ATTEMPTS=20,CHECKPOINT_LOCK_DELAY_MS=250,CHECKPOINT_LOCK_DEADLINE_MS=45000,CHECKPOINT_RECEIPT_LOOKUP_LIMIT=25,NON_SWARM_COMMIT_PATHSPEC,SHELL_METACHARACTERS,SAFE_LABEL_PATTERN,CONTROL_CHAR_PATTERN,NON_ASCII_PATTERN,_internals65,checkpoint;var init_checkpoint=__esm(()=>{init_zod();init_destructive_purge();init_reset_backup();init_rollback_gate();init_config2();init_task_checkpoint_receipt();init_core_events();init_file_locks();init_ledger();init_manager();init_utils3();init_git_binary_missing_error();init_git_executable();init_create_tool();NON_SWARM_COMMIT_PATHSPEC=[".",":(exclude,top).swarm",":(exclude,top).swarm/**"],SHELL_METACHARACTERS=/[;|&$`(){}<>!'"]/,SAFE_LABEL_PATTERN=/^[a-zA-Z0-9_ -]+$/,CONTROL_CHAR_PATTERN=/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/,NON_ASCII_PATTERN=/[^\x20-\x7E]/,_internals65={tryAcquireLock,loadPlan,gitExec:gitExec2,sleep:(ms)=>new Promise((resolve36)=>setTimeout(resolve36,ms)),findCommitByExactSubject,stageAllExcludingSwarm,resolveGitExecutable};checkpoint=createSwarmTool({allowWorkingDirectoryOverride:!0,description:"Save, restore, list, and delete git checkpoints. Use save to create a named snapshot, restore to return tracked files to a checkpoint (a destructive restore previews first and requires a confirm token issued in the preview; destroyed bytes are backed up under .swarm/rollback-backups/), list to see all checkpoints, delete to remove a checkpoint from the log, and save_task_completion to record a retry-safe task completion checkpoint. Git commits are preserved on delete.",args:{action:exports_external.string().describe("Action to perform: save, restore, list, delete, or save_task_completion"),label:exports_external.string().optional().describe("Checkpoint label (required for save, restore, delete)"),confirm_token:exports_external.string().optional().describe("Confirm token from a destructive-restore preview (required when restore would destroy uncommitted tracked work; the preview response carries the token)"),task_id:exports_external.string().optional().describe('Plan task ID (required for save_task_completion), e.g. "1.1"')},execute:async(args2,directory)=>{let repoProbe=isGitRepo2(directory);if(!repoProbe.isRepo)return serializeResult("unknown",{success:!1,error:`${repoProbe.warning??"not a git repository"} - checkpoint tools require a git repository`});let action,label,confirmToken,taskId;try{action=String(args2.action),label=args2.label!==void 0&&args2.label!==null?String(args2.label):void 0,confirmToken=args2.confirm_token!==void 0&&args2.confirm_token!==null?String(args2.confirm_token):void 0,taskId=args2.task_id!==void 0&&args2.task_id!==null?String(args2.task_id):void 0}catch{return serializeResult("unknown",{success:!1,error:"invalid arguments"})}let validActions=["save","restore","list","delete","save_task_completion"];if(!validActions.includes(action))return serializeResult("unknown",{success:!1,error:`invalid action: "${action}". Valid actions: ${validActions.join(", ")}`});if(["save","restore","delete"].includes(action)){if(!label)return serializeResult(action,{success:!1,error:`label is required for ${action} action`});let labelError=validateLabel(label);if(labelError)return serializeResult(action,{success:!1,error:`invalid label: ${labelError}`})}if(action==="save_task_completion"){if(!taskId||taskId.trim().length===0)return serializeResult("save_task_completion",{success:!1,error:"task_id is required for save_task_completion action"})}switch(action){case"save":return withCheckpointMutationLock({action:"save",directory,operationKey:`save-${label}`,run:async()=>handleSave(label,directory)});case"restore":return withCheckpointMutationLock({action:"restore",directory,operationKey:`restore-${label}`,run:async()=>await handleRestore(label,directory,confirmToken)});case"list":return handleList(directory);case"delete":return withCheckpointMutationLock({action:"delete",directory,operationKey:`delete-${label}`,run:async()=>handleDelete(label,directory)});case"save_task_completion":return handleSaveTaskCompletion(taskId,directory);default:return serializeResult("unknown",{success:!1,error:"unreachable"})}}})});var exports_auto_checkpoint={};__export(exports_auto_checkpoint,{maybeSaveAutoCheckpoint:()=>maybeSaveAutoCheckpoint,evaluateAutoCheckpoint:()=>evaluateAutoCheckpoint,countCompletedTasks:()=>countCompletedTasks,buildAutoCheckpointLabel:()=>buildAutoCheckpointLabel,_internals:()=>_internals66,DEFAULT_AUTO_CHECKPOINT_THRESHOLD:()=>DEFAULT_AUTO_CHECKPOINT_THRESHOLD});import*as child_process4 from"node:child_process";import*as fs43 from"node:fs";import*as path71 from"node:path";function countCompletedTasks(plan){return plan.phases.reduce((total,phase)=>total+phase.tasks.filter((task)=>task.status==="completed").length,0)}function buildAutoCheckpointLabel(plan,completedCount,generation=1){let base=`auto-task-checkpoint-${derivePlanIdentityHash(plan).slice(0,12)}-${String(completedCount).padStart(3,"0")}`;return generation<=1?base:`${base}-g${generation}`}function evaluateAutoCheckpoint(input){let{plan,completedCount,enabled}=input,threshold=Number.isInteger(input.threshold)&&input.threshold>=1?input.threshold:DEFAULT_AUTO_CHECKPOINT_THRESHOLD;if(enabled===!1)return{shouldSave:!1,completedCount,threshold,skipReason:"disabled"};if(completedCount<=0||completedCount%threshold!==0)return{shouldSave:!1,completedCount,threshold,skipReason:"below_threshold"};return{shouldSave:!0,completedCount,threshold,label:buildAutoCheckpointLabel(plan,completedCount)}}function resolveHead(directory){let result;try{result=_internals66.spawnSync(resolveGitExecutable(),["rev-parse","HEAD"],{cwd:directory,encoding:"utf-8",timeout:GIT_PROBE_TIMEOUT_MS,maxBuffer:GIT_PROBE_MAX_BUFFER_BYTES,stdio:["ignore","pipe","pipe"],windowsHide:!0})}catch{return null}if(result.error||result.status!==0)return null;let sha=(result.stdout??"").trim();return/^[0-9a-f]{40}$/i.test(sha)?sha:null}function readCheckpointEntries(directory){try{let logPath=path71.join(directory,".swarm","checkpoints.json");if(!fs43.existsSync(logPath))return[];let parsed=JSON.parse(fs43.readFileSync(logPath,"utf-8"));if(!Array.isArray(parsed.checkpoints))return[];return parsed.checkpoints.filter((entry)=>typeof entry?.label==="string"&&typeof entry?.sha==="string").map((entry)=>({label:entry.label,sha:entry.sha}))}catch{return[]}}async function maybeSaveAutoCheckpoint(directory,plan){let enabled=!0,threshold=DEFAULT_AUTO_CHECKPOINT_THRESHOLD;try{let{config:config3}=_internals66.loadPluginConfigWithMeta(directory);if(config3.checkpoint?.enabled===!1)enabled=!1;if(config3.checkpoint?.auto_checkpoint_threshold!==void 0)threshold=config3.checkpoint.auto_checkpoint_threshold}catch{}let completedCount=countCompletedTasks(plan),decision=evaluateAutoCheckpoint({plan,completedCount,threshold,enabled});if(!decision.shouldSave||!decision.label)return{...decision,saved:!1};let head=resolveHead(directory);if(head===null)return{...decision,shouldSave:!1,saved:!1,skipReason:"no_restorable_head"};let existing=readCheckpointEntries(directory),baseLabel=decision.label;if(existing.filter((entry)=>parseLabelGeneration(baseLabel,entry.label)!==null).some((entry)=>entry.sha===head))return{...decision,saved:!0,skipReason:"already_current"};let taken=new Set(existing.map((entry)=>entry.label)),generation=1,label=baseLabel;while(taken.has(label))generation+=1,label=buildAutoCheckpointLabel(plan,completedCount,generation);let{saveCheckpointRecord:saveCheckpointRecord2}=await Promise.resolve().then(() => (init_checkpoint(),exports_checkpoint)),result=await saveCheckpointRecord2(label,directory);if(result.success)return emitAutoSavedEvent(directory,{label,completedCount,threshold:decision.threshold}),{...decision,label,saved:!0};let reconcileHead=resolveHead(directory)??head;if(readCheckpointEntries(directory).some((entry)=>(entry.sha===head||entry.sha===reconcileHead)&&parseLabelGeneration(baseLabel,entry.label)!==null))return{...decision,label,saved:!0,skipReason:"already_current"};return{...decision,label,saved:!1,warning:result.warning??result.error}}function emitAutoSavedEvent(directory,payload){try{appendCoreEventSync(directory,{event:"checkpoint_auto_saved",...payload,timestamp:new Date().toISOString()})}catch{}}function parseLabelGeneration(baseLabel,label){if(label===baseLabel)return 1;if(!label.startsWith(baseLabel))return null;let match=/^-g(\d{1,6})$/.exec(label.slice(baseLabel.length));if(!match)return null;let generation=Number(match[1]);return generation>=2?generation:null}var DEFAULT_AUTO_CHECKPOINT_THRESHOLD=3,GIT_PROBE_TIMEOUT_MS=1e4,GIT_PROBE_MAX_BUFFER_BYTES=1048576,_internals66;var init_auto_checkpoint=__esm(()=>{init_config2();init_core_events();init_git_executable();init_utils3();_internals66={loadPluginConfigWithMeta,spawnSync:child_process4.spawnSync.bind(child_process4)}});import{closeSync as closeSync11,fsyncSync as fsyncSync3,mkdirSync as mkdirSync25,openSync as openSync11,renameSync as renameSync13,unlinkSync as unlinkSync13,writeFileSync as writeFileSync15}from"node:fs";import*as fsPromises4 from"node:fs/promises";import*as path72 from"node:path";function derivePhaseStatusesInPlace(plan){for(let phase of plan.phases){let tasks=phase.tasks;if(tasks.length>0&&tasks.every((t)=>t.status==="completed"))phase.status="complete";else if(tasks.some((t)=>t.status==="in_progress"))phase.status="in_progress";else if(tasks.some((t)=>t.status==="blocked"))phase.status="blocked";else phase.status="pending"}}function statusRank(s){switch(s){case"closed":return 5;case"completed":return 4;case"blocked":return 3;case"in_progress":return 2;case"pending":return 1;default:return 0}}function mergeStatusesTakingPrecedence(validated,replayed,ledgerStatusTaskIds){let projected=structuredClone(validated),replayedByTaskId=new Map;for(let phase of replayed.phases)for(let task of phase.tasks)if(ledgerStatusTaskIds.has(task.id))replayedByTaskId.set(task.id,task.status);for(let phase of projected.phases)for(let task of phase.tasks){let replayedStatus=replayedByTaskId.get(task.id);if(replayedStatus&&statusRank(replayedStatus)>statusRank(task.status))task.status=replayedStatus}return derivePhaseStatusesInPlace(projected),projected}function collectLedgerStatusTaskIds(events){let statusTaskIds=new Set;for(let event of events)if(event.event_type==="task_status_changed"&&typeof event.task_id==="string")statusTaskIds.add(event.task_id);return statusTaskIds}async function retryCasWithBackoff(directory,eventInput,options){let maxRetries=options.maxRetries??CAS_MAX_RETRIES,currentExpected=options.expectedHash,attempt=0;while(!0)try{return await appendLedgerEvent(directory,eventInput,{expectedHash:currentExpected,planHashAfter:options.planHashAfter,preCommitCheck:options.preCommitCheck})}catch(error93){if(!(error93 instanceof LedgerStaleWriterError)||attempt>=maxRetries)throw error93;attempt++;let base=Math.min(CAS_BACKOFF_START_MS*2**(attempt-1),CAS_BACKOFF_CAP_MS),jitter=base*CAS_BACKOFF_JITTER*(Math.random()*2-1),delayMs=Math.max(1,Math.round(base+jitter));if(emit("plan_ledger_cas_retry",{attempt,expectedHashPrefix:currentExpected.slice(0,8),delayMs}),await new Promise((resolve37)=>setTimeout(resolve37,delayMs)),options.verifyValid){if(!await options.verifyValid())return null}currentExpected=computeCurrentPlanHash(directory)}}async function loadPlanJsonOnly(directory){try{return await parsePlanJsonCached(directory)}catch(error93){warn(`Plan validation failed for .swarm/plan.json: ${error93 instanceof Error?error93.message:String(error93)}`)}return null}function compareTaskIds(a,b){let partsA=a.split(".").map((n)=>parseInt(n,10)),partsB=b.split(".").map((n)=>parseInt(n,10)),maxLen=Math.max(partsA.length,partsB.length);for(let i=0;i<maxLen;i++){let numA=partsA[i]??0,numB=partsB[i]??0;if(numA!==numB)return numA-numB}return 0}async function getLatestLedgerHash(directory){try{let events=await readLedgerEvents(directory);if(events.length===0)return"";return events[events.length-1].plan_hash_after}catch{return""}}async function surfaceLedgerStaleIfPersisted(directory,plan,options){let resolvedWorkspace=canonicalRootKeyFresh(directory);if(!ledgerStaleWorkspaces.has(resolvedWorkspace))return plan;try{let planHash=computePlanLedgerHash(plan),ledgerHash=await getLatestLedgerHash(directory);if(ledgerHash!==""&&planHash===ledgerHash)return options?.preCommitCheck?.(),ledgerStaleWorkspaces.delete(resolvedWorkspace),plan}catch(error93){if(error93 instanceof PlanRecoverySupersededError)throw error93}if(plan._ledgerReplayStale=!0,typeof plan._ledgerReplayStaleReason!=="string"||plan._ledgerReplayStaleReason.length===0)plan._ledgerReplayStaleReason="plan.json still hash-mismatches the ledger after a startup ledger-replay failure (replay could not be applied and no critic-approved snapshot was available). Run /swarm reset-session if this persists.";return plan}async function parsePlanJsonCached(directory){let planJsonPath=path72.resolve(directory,".swarm","plan.json");return readCachedParsedFile(planJsonPath,PLAN_JSON_CACHE_NAMESPACE,()=>_internals67.readPlanJsonUtf8(directory),(planJsonContent)=>{if(planJsonContent.includes("\x00"))throw Error("Plan rejected: .swarm/plan.json contains null bytes");let parsed=JSON.parse(planJsonContent);return PlanSchema.parse(parsed)})}async function readPlanJsonUtf8(directory){return readSwarmFileAsync(directory,"plan.json",void 0,(filePath)=>_internals67.readPlanFileUtf8(filePath),!1)}async function readPlanFileUtf8(filePath){return new TextDecoder("utf-8",{fatal:!0}).decode(await fsPromises4.readFile(filePath))}function computePlanContentHash(plan){let content={schema_version:plan.schema_version,title:plan.title,swarm:plan.swarm,current_phase:plan.current_phase,migration_status:plan.migration_status,execution_profile:normalizeExecutionProfileForHash(plan.execution_profile),phases:plan.phases.map((phase)=>({id:phase.id,name:phase.name,status:phase.status,tasks:phase.tasks.map((task)=>({id:task.id,phase:task.phase,status:task.status,size:task.size,description:task.description,depends:[...task.depends].sort(compareTaskIds),acceptance:task.acceptance,files_touched:[...task.files_touched].sort(),evidence_path:task.evidence_path,blocked_reason:task.blocked_reason,evidence_class:task.evidence_class,evidence_anchors:task.evidence_anchors})).sort((a,b)=>compareTaskIds(a.id,b.id))})).sort((a,b)=>a.id-b.id)},jsonString=JSON.stringify(content);return bunHash(jsonString).toString(36)}function extractPlanHashFromMarkdown(markdown){let match=markdown.match(/<!--\s*PLAN_HASH:\s*(\S+)\s*-->/);return match?match[1]:null}async function isPlanMdInSync(directory,plan,cache2){let planMdContent=await readSwarmFileAsync(directory,"plan.md",cache2);if(planMdContent===null)return!1;let expectedHash=computePlanContentHash(plan);if(extractPlanHashFromMarkdown(planMdContent)===expectedHash)return!0;let normalizedExpected=derivePlanMarkdown(plan).trim();if(planMdContent.trim()===normalizedExpected)return!0;return!1}async function regeneratePlanMarkdown(directory,plan,options){assertProjectRoot(directory);let swarmDir=path72.resolve(directory,".swarm"),contentHash=computePlanContentHash(plan),markdown=derivePlanMarkdown(plan),markdownWithHash=`<!-- PLAN_HASH: ${contentHash} -->
|
|
884
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let entry of this.seen.entries()){let seen=entry[1];if(schema===entry[0]){extractToDef(entry);continue}if(params.external){let ext=params.external.registry.get(entry[0])?.id;if(schema!==entry[0]&&ext){extractToDef(entry);continue}}if(this.metadataRegistry.get(entry[0])?.id){extractToDef(entry);continue}if(seen.cycle){extractToDef(entry);continue}if(seen.count>1){if(params.reused==="ref"){extractToDef(entry);continue}}}let flattenRef=(zodSchema,params2)=>{let seen=this.seen.get(zodSchema),schema2=seen.def??seen.schema,_cached2={...schema2};if(seen.ref===null)return;let ref=seen.ref;if(seen.ref=null,ref){flattenRef(ref,params2);let refSchema=this.seen.get(ref).schema;if(refSchema.$ref&&(params2.target==="draft-7"||params2.target==="draft-4"||params2.target==="openapi-3.0"))schema2.allOf=schema2.allOf??[],schema2.allOf.push(refSchema);else Object.assign(schema2,refSchema),Object.assign(schema2,_cached2)}if(!seen.isParent)this.override({zodSchema,jsonSchema:schema2,path:seen.path??[]})};for(let entry of[...this.seen.entries()].reverse())flattenRef(entry[0],{target:this.target});let result={};if(this.target==="draft-2020-12")result.$schema="https://json-schema.org/draft/2020-12/schema";else if(this.target==="draft-7")result.$schema="http://json-schema.org/draft-07/schema#";else if(this.target==="draft-4")result.$schema="http://json-schema.org/draft-04/schema#";else if(this.target==="openapi-3.0");else console.warn(`Invalid target: ${this.target}`);if(params.external?.uri){let id=params.external.registry.get(schema)?.id;if(!id)throw Error("Schema is missing an `id` property");result.$id=params.external.uri(id)}Object.assign(result,root.def);let defs=params.external?.defs??{};for(let entry of this.seen.entries()){let seen=entry[1];if(seen.def&&seen.defId)defs[seen.defId]=seen.def}if(params.external);else if(Object.keys(defs).length>0)if(this.target==="draft-2020-12")result.$defs=defs;else result.definitions=defs;try{return JSON.parse(JSON.stringify(result))}catch(_err){throw Error("Error converting schema to JSON.")}}}function toJSONSchema2(input,_params){if(input instanceof $ZodRegistry2){let gen2=new JSONSchemaGenerator2(_params),defs={};for(let entry of input._idmap.entries()){let[_,schema]=entry;gen2.process(schema)}let schemas3={},external2={registry:input,uri:_params?.uri,defs};for(let entry of input._idmap.entries()){let[key,schema]=entry;schemas3[key]=gen2.emit(schema,{..._params,external:external2})}if(Object.keys(defs).length>0){let defsSegment=gen2.target==="draft-2020-12"?"$defs":"definitions";schemas3.__shared={[defsSegment]:defs}}return{schemas:schemas3}}let gen=new JSONSchemaGenerator2(_params);return gen.process(input),gen.emit(input,_params)}function isTransforming2(_schema,_ctx){let ctx=_ctx??{seen:new Set};if(ctx.seen.has(_schema))return!1;ctx.seen.add(_schema);let def=_schema._zod.def;switch(def.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return isTransforming2(def.element,ctx);case"object":{for(let key in def.shape)if(isTransforming2(def.shape[key],ctx))return!0;return!1}case"union":{for(let option of def.options)if(isTransforming2(option,ctx))return!0;return!1}case"intersection":return isTransforming2(def.left,ctx)||isTransforming2(def.right,ctx);case"tuple":{for(let item of def.items)if(isTransforming2(item,ctx))return!0;if(def.rest&&isTransforming2(def.rest,ctx))return!0;return!1}case"record":return isTransforming2(def.keyType,ctx)||isTransforming2(def.valueType,ctx);case"map":return isTransforming2(def.keyType,ctx)||isTransforming2(def.valueType,ctx);case"set":return isTransforming2(def.valueType,ctx);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return isTransforming2(def.innerType,ctx);case"lazy":return isTransforming2(def.getter(),ctx);case"default":return isTransforming2(def.innerType,ctx);case"prefault":return isTransforming2(def.innerType,ctx);case"custom":return!1;case"transform":return!0;case"pipe":return isTransforming2(def.in,ctx)||isTransforming2(def.out,ctx);case"success":return!1;case"catch":return!1;case"function":return!1;default:}throw Error(`Unknown schema type: ${def.type}`)}var init_to_json_schema2=__esm(()=>{init_registries2();init_util2()});var exports_json_schema2={};var init_json_schema2=()=>{};var exports_core5={};__export(exports_core5,{version:()=>version2,util:()=>exports_util2,treeifyError:()=>treeifyError2,toJSONSchema:()=>toJSONSchema2,toDotPath:()=>toDotPath2,safeParseAsync:()=>safeParseAsync3,safeParse:()=>safeParse3,safeEncodeAsync:()=>safeEncodeAsync3,safeEncode:()=>safeEncode3,safeDecodeAsync:()=>safeDecodeAsync3,safeDecode:()=>safeDecode3,registry:()=>registry2,regexes:()=>exports_regexes2,prettifyError:()=>prettifyError2,parseAsync:()=>parseAsync3,parse:()=>parse5,locales:()=>exports_locales2,isValidJWT:()=>isValidJWT2,isValidBase64URL:()=>isValidBase64URL2,isValidBase64:()=>isValidBase642,globalRegistry:()=>globalRegistry2,globalConfig:()=>globalConfig2,formatError:()=>formatError2,flattenError:()=>flattenError2,encodeAsync:()=>encodeAsync3,encode:()=>encode3,decodeAsync:()=>decodeAsync3,decode:()=>decode3,config:()=>config2,clone:()=>clone2,_xid:()=>_xid2,_void:()=>_void3,_uuidv7:()=>_uuidv72,_uuidv6:()=>_uuidv62,_uuidv4:()=>_uuidv42,_uuid:()=>_uuid2,_url:()=>_url2,_uppercase:()=>_uppercase2,_unknown:()=>_unknown2,_union:()=>_union2,_undefined:()=>_undefined5,_ulid:()=>_ulid2,_uint64:()=>_uint642,_uint32:()=>_uint322,_tuple:()=>_tuple2,_trim:()=>_trim2,_transform:()=>_transform2,_toUpperCase:()=>_toUpperCase2,_toLowerCase:()=>_toLowerCase2,_templateLiteral:()=>_templateLiteral2,_symbol:()=>_symbol2,_superRefine:()=>_superRefine2,_success:()=>_success2,_stringbool:()=>_stringbool2,_stringFormat:()=>_stringFormat2,_string:()=>_string2,_startsWith:()=>_startsWith2,_size:()=>_size2,_set:()=>_set2,_safeParseAsync:()=>_safeParseAsync2,_safeParse:()=>_safeParse2,_safeEncodeAsync:()=>_safeEncodeAsync2,_safeEncode:()=>_safeEncode2,_safeDecodeAsync:()=>_safeDecodeAsync2,_safeDecode:()=>_safeDecode2,_regex:()=>_regex2,_refine:()=>_refine2,_record:()=>_record2,_readonly:()=>_readonly2,_property:()=>_property2,_promise:()=>_promise2,_positive:()=>_positive2,_pipe:()=>_pipe2,_parseAsync:()=>_parseAsync2,_parse:()=>_parse2,_overwrite:()=>_overwrite2,_optional:()=>_optional2,_number:()=>_number2,_nullable:()=>_nullable2,_null:()=>_null5,_normalize:()=>_normalize2,_nonpositive:()=>_nonpositive2,_nonoptional:()=>_nonoptional2,_nonnegative:()=>_nonnegative2,_never:()=>_never2,_negative:()=>_negative2,_nativeEnum:()=>_nativeEnum2,_nanoid:()=>_nanoid2,_nan:()=>_nan2,_multipleOf:()=>_multipleOf2,_minSize:()=>_minSize2,_minLength:()=>_minLength2,_min:()=>_gte2,_mime:()=>_mime2,_maxSize:()=>_maxSize2,_maxLength:()=>_maxLength2,_max:()=>_lte2,_map:()=>_map2,_lte:()=>_lte2,_lt:()=>_lt2,_lowercase:()=>_lowercase2,_literal:()=>_literal2,_length:()=>_length2,_lazy:()=>_lazy2,_ksuid:()=>_ksuid2,_jwt:()=>_jwt2,_isoTime:()=>_isoTime2,_isoDuration:()=>_isoDuration2,_isoDateTime:()=>_isoDateTime2,_isoDate:()=>_isoDate2,_ipv6:()=>_ipv62,_ipv4:()=>_ipv42,_intersection:()=>_intersection2,_int64:()=>_int642,_int32:()=>_int322,_int:()=>_int2,_includes:()=>_includes2,_guid:()=>_guid2,_gte:()=>_gte2,_gt:()=>_gt2,_float64:()=>_float642,_float32:()=>_float322,_file:()=>_file2,_enum:()=>_enum3,_endsWith:()=>_endsWith2,_encodeAsync:()=>_encodeAsync2,_encode:()=>_encode2,_emoji:()=>_emoji3,_email:()=>_email2,_e164:()=>_e1642,_discriminatedUnion:()=>_discriminatedUnion2,_default:()=>_default3,_decodeAsync:()=>_decodeAsync2,_decode:()=>_decode2,_date:()=>_date2,_custom:()=>_custom2,_cuid2:()=>_cuid22,_cuid:()=>_cuid3,_coercedString:()=>_coercedString2,_coercedNumber:()=>_coercedNumber2,_coercedDate:()=>_coercedDate2,_coercedBoolean:()=>_coercedBoolean2,_coercedBigint:()=>_coercedBigint2,_cidrv6:()=>_cidrv62,_cidrv4:()=>_cidrv42,_check:()=>_check2,_catch:()=>_catch3,_boolean:()=>_boolean2,_bigint:()=>_bigint2,_base64url:()=>_base64url2,_base64:()=>_base642,_array:()=>_array2,_any:()=>_any2,TimePrecision:()=>TimePrecision2,NEVER:()=>NEVER2,JSONSchemaGenerator:()=>JSONSchemaGenerator2,JSONSchema:()=>exports_json_schema2,Doc:()=>Doc2,$output:()=>$output2,$input:()=>$input2,$constructor:()=>$constructor2,$brand:()=>$brand2,$ZodXID:()=>$ZodXID2,$ZodVoid:()=>$ZodVoid2,$ZodUnknown:()=>$ZodUnknown2,$ZodUnion:()=>$ZodUnion2,$ZodUndefined:()=>$ZodUndefined2,$ZodUUID:()=>$ZodUUID2,$ZodURL:()=>$ZodURL2,$ZodULID:()=>$ZodULID2,$ZodType:()=>$ZodType2,$ZodTuple:()=>$ZodTuple2,$ZodTransform:()=>$ZodTransform2,$ZodTemplateLiteral:()=>$ZodTemplateLiteral2,$ZodSymbol:()=>$ZodSymbol2,$ZodSuccess:()=>$ZodSuccess2,$ZodStringFormat:()=>$ZodStringFormat2,$ZodString:()=>$ZodString2,$ZodSet:()=>$ZodSet2,$ZodRegistry:()=>$ZodRegistry2,$ZodRecord:()=>$ZodRecord2,$ZodRealError:()=>$ZodRealError2,$ZodReadonly:()=>$ZodReadonly2,$ZodPromise:()=>$ZodPromise2,$ZodPrefault:()=>$ZodPrefault2,$ZodPipe:()=>$ZodPipe2,$ZodOptional:()=>$ZodOptional2,$ZodObjectJIT:()=>$ZodObjectJIT2,$ZodObject:()=>$ZodObject2,$ZodNumberFormat:()=>$ZodNumberFormat2,$ZodNumber:()=>$ZodNumber2,$ZodNullable:()=>$ZodNullable2,$ZodNull:()=>$ZodNull2,$ZodNonOptional:()=>$ZodNonOptional2,$ZodNever:()=>$ZodNever2,$ZodNanoID:()=>$ZodNanoID2,$ZodNaN:()=>$ZodNaN2,$ZodMap:()=>$ZodMap2,$ZodLiteral:()=>$ZodLiteral2,$ZodLazy:()=>$ZodLazy2,$ZodKSUID:()=>$ZodKSUID2,$ZodJWT:()=>$ZodJWT2,$ZodIntersection:()=>$ZodIntersection2,$ZodISOTime:()=>$ZodISOTime2,$ZodISODuration:()=>$ZodISODuration2,$ZodISODateTime:()=>$ZodISODateTime2,$ZodISODate:()=>$ZodISODate2,$ZodIPv6:()=>$ZodIPv62,$ZodIPv4:()=>$ZodIPv42,$ZodGUID:()=>$ZodGUID2,$ZodFunction:()=>$ZodFunction2,$ZodFile:()=>$ZodFile2,$ZodError:()=>$ZodError2,$ZodEnum:()=>$ZodEnum2,$ZodEncodeError:()=>$ZodEncodeError2,$ZodEmoji:()=>$ZodEmoji2,$ZodEmail:()=>$ZodEmail2,$ZodE164:()=>$ZodE1642,$ZodDiscriminatedUnion:()=>$ZodDiscriminatedUnion2,$ZodDefault:()=>$ZodDefault2,$ZodDate:()=>$ZodDate2,$ZodCustomStringFormat:()=>$ZodCustomStringFormat2,$ZodCustom:()=>$ZodCustom2,$ZodCodec:()=>$ZodCodec2,$ZodCheckUpperCase:()=>$ZodCheckUpperCase2,$ZodCheckStringFormat:()=>$ZodCheckStringFormat2,$ZodCheckStartsWith:()=>$ZodCheckStartsWith2,$ZodCheckSizeEquals:()=>$ZodCheckSizeEquals2,$ZodCheckRegex:()=>$ZodCheckRegex2,$ZodCheckProperty:()=>$ZodCheckProperty2,$ZodCheckOverwrite:()=>$ZodCheckOverwrite2,$ZodCheckNumberFormat:()=>$ZodCheckNumberFormat2,$ZodCheckMultipleOf:()=>$ZodCheckMultipleOf2,$ZodCheckMinSize:()=>$ZodCheckMinSize2,$ZodCheckMinLength:()=>$ZodCheckMinLength2,$ZodCheckMimeType:()=>$ZodCheckMimeType2,$ZodCheckMaxSize:()=>$ZodCheckMaxSize2,$ZodCheckMaxLength:()=>$ZodCheckMaxLength2,$ZodCheckLowerCase:()=>$ZodCheckLowerCase2,$ZodCheckLessThan:()=>$ZodCheckLessThan2,$ZodCheckLengthEquals:()=>$ZodCheckLengthEquals2,$ZodCheckIncludes:()=>$ZodCheckIncludes2,$ZodCheckGreaterThan:()=>$ZodCheckGreaterThan2,$ZodCheckEndsWith:()=>$ZodCheckEndsWith2,$ZodCheckBigIntFormat:()=>$ZodCheckBigIntFormat2,$ZodCheck:()=>$ZodCheck2,$ZodCatch:()=>$ZodCatch2,$ZodCUID2:()=>$ZodCUID22,$ZodCUID:()=>$ZodCUID3,$ZodCIDRv6:()=>$ZodCIDRv62,$ZodCIDRv4:()=>$ZodCIDRv42,$ZodBoolean:()=>$ZodBoolean2,$ZodBigIntFormat:()=>$ZodBigIntFormat2,$ZodBigInt:()=>$ZodBigInt2,$ZodBase64URL:()=>$ZodBase64URL2,$ZodBase64:()=>$ZodBase642,$ZodAsyncError:()=>$ZodAsyncError2,$ZodArray:()=>$ZodArray2,$ZodAny:()=>$ZodAny2});var init_core5=__esm(()=>{init_util2();init_regexes2();init_locales2();init_json_schema2();init_core4();init_parse3();init_errors4();init_schemas3();init_checks3();init_versions2();init_registries2();init_api2();init_to_json_schema2()});var init_checks4=__esm(()=>{init_core5()});var exports_iso2={};__export(exports_iso2,{time:()=>time4,duration:()=>duration4,datetime:()=>datetime4,date:()=>date6,ZodISOTime:()=>ZodISOTime2,ZodISODuration:()=>ZodISODuration2,ZodISODateTime:()=>ZodISODateTime2,ZodISODate:()=>ZodISODate2});function datetime4(params){return _isoDateTime2(ZodISODateTime2,params)}function date6(params){return _isoDate2(ZodISODate2,params)}function time4(params){return _isoTime2(ZodISOTime2,params)}function duration4(params){return _isoDuration2(ZodISODuration2,params)}var ZodISODateTime2,ZodISODate2,ZodISOTime2,ZodISODuration2;var init_iso2=__esm(()=>{init_core5();init_schemas4();ZodISODateTime2=$constructor2("ZodISODateTime",(inst,def)=>{$ZodISODateTime2.init(inst,def),ZodStringFormat2.init(inst,def)});ZodISODate2=$constructor2("ZodISODate",(inst,def)=>{$ZodISODate2.init(inst,def),ZodStringFormat2.init(inst,def)});ZodISOTime2=$constructor2("ZodISOTime",(inst,def)=>{$ZodISOTime2.init(inst,def),ZodStringFormat2.init(inst,def)});ZodISODuration2=$constructor2("ZodISODuration",(inst,def)=>{$ZodISODuration2.init(inst,def),ZodStringFormat2.init(inst,def)})});var initializer4=(inst,issues)=>{$ZodError2.init(inst,issues),inst.name="ZodError",Object.defineProperties(inst,{format:{value:(mapper)=>formatError2(inst,mapper)},flatten:{value:(mapper)=>flattenError2(inst,mapper)},addIssue:{value:(issue3)=>{inst.issues.push(issue3),inst.message=JSON.stringify(inst.issues,jsonStringifyReplacer2,2)}},addIssues:{value:(issues2)=>{inst.issues.push(...issues2),inst.message=JSON.stringify(inst.issues,jsonStringifyReplacer2,2)}},isEmpty:{get(){return inst.issues.length===0}}})},ZodError2,ZodRealError2;var init_errors5=__esm(()=>{init_core5();init_core5();init_util2();ZodError2=$constructor2("ZodError",initializer4),ZodRealError2=$constructor2("ZodError",initializer4,{Parent:Error})});var parse7,parseAsync4,safeParse4,safeParseAsync4,encode4,decode4,encodeAsync4,decodeAsync4,safeEncode4,safeDecode4,safeEncodeAsync4,safeDecodeAsync4;var init_parse4=__esm(()=>{init_core5();init_errors5();parse7=_parse2(ZodRealError2),parseAsync4=_parseAsync2(ZodRealError2),safeParse4=_safeParse2(ZodRealError2),safeParseAsync4=_safeParseAsync2(ZodRealError2),encode4=_encode2(ZodRealError2),decode4=_decode2(ZodRealError2),encodeAsync4=_encodeAsync2(ZodRealError2),decodeAsync4=_decodeAsync2(ZodRealError2),safeEncode4=_safeEncode2(ZodRealError2),safeDecode4=_safeDecode2(ZodRealError2),safeEncodeAsync4=_safeEncodeAsync2(ZodRealError2),safeDecodeAsync4=_safeDecodeAsync2(ZodRealError2)});function string5(params){return _string2(ZodString2,params)}function email4(params){return _email2(ZodEmail2,params)}function guid4(params){return _guid2(ZodGUID2,params)}function uuid5(params){return _uuid2(ZodUUID2,params)}function uuidv42(params){return _uuidv42(ZodUUID2,params)}function uuidv62(params){return _uuidv62(ZodUUID2,params)}function uuidv72(params){return _uuidv72(ZodUUID2,params)}function url2(params){return _url2(ZodURL2,params)}function httpUrl2(params){return _url2(ZodURL2,{protocol:/^https?$/,hostname:exports_regexes2.domain,...exports_util2.normalizeParams(params)})}function emoji4(params){return _emoji3(ZodEmoji2,params)}function nanoid4(params){return _nanoid2(ZodNanoID2,params)}function cuid6(params){return _cuid3(ZodCUID3,params)}function cuid24(params){return _cuid22(ZodCUID22,params)}function ulid4(params){return _ulid2(ZodULID2,params)}function xid4(params){return _xid2(ZodXID2,params)}function ksuid4(params){return _ksuid2(ZodKSUID2,params)}function ipv44(params){return _ipv42(ZodIPv42,params)}function ipv64(params){return _ipv62(ZodIPv62,params)}function cidrv44(params){return _cidrv42(ZodCIDRv42,params)}function cidrv64(params){return _cidrv62(ZodCIDRv62,params)}function base644(params){return _base642(ZodBase642,params)}function base64url4(params){return _base64url2(ZodBase64URL2,params)}function e1644(params){return _e1642(ZodE1642,params)}function jwt2(params){return _jwt2(ZodJWT2,params)}function stringFormat2(format,fnOrRegex,_params={}){return _stringFormat2(ZodCustomStringFormat2,format,fnOrRegex,_params)}function hostname4(_params){return _stringFormat2(ZodCustomStringFormat2,"hostname",exports_regexes2.hostname,_params)}function hex4(_params){return _stringFormat2(ZodCustomStringFormat2,"hex",exports_regexes2.hex,_params)}function hash3(alg,params){let enc=params?.enc??"hex",format=`${alg}_${enc}`,regex=exports_regexes2[format];if(!regex)throw Error(`Unrecognized hash format: ${format}`);return _stringFormat2(ZodCustomStringFormat2,format,regex,params)}function number5(params){return _number2(ZodNumber2,params)}function int2(params){return _int2(ZodNumberFormat2,params)}function float322(params){return _float322(ZodNumberFormat2,params)}function float642(params){return _float642(ZodNumberFormat2,params)}function int322(params){return _int322(ZodNumberFormat2,params)}function uint322(params){return _uint322(ZodNumberFormat2,params)}function boolean5(params){return _boolean2(ZodBoolean2,params)}function bigint5(params){return _bigint2(ZodBigInt2,params)}function int642(params){return _int642(ZodBigIntFormat2,params)}function uint642(params){return _uint642(ZodBigIntFormat2,params)}function symbol2(params){return _symbol2(ZodSymbol2,params)}function _undefined6(params){return _undefined5(ZodUndefined2,params)}function _null6(params){return _null5(ZodNull2,params)}function any2(){return _any2(ZodAny2)}function unknown2(){return _unknown2(ZodUnknown2)}function never2(params){return _never2(ZodNever2,params)}function _void4(params){return _void3(ZodVoid2,params)}function date7(params){return _date2(ZodDate2,params)}function array2(element,params){return _array2(ZodArray2,element,params)}function keyof2(schema){let shape=schema._zod.def.shape;return _enum4(Object.keys(shape))}function object2(shape,params){let def={type:"object",get shape(){return exports_util2.assignProp(this,"shape",shape?exports_util2.objectClone(shape):{}),this.shape},...exports_util2.normalizeParams(params)};return new ZodObject2(def)}function strictObject2(shape,params){return new ZodObject2({type:"object",get shape(){return exports_util2.assignProp(this,"shape",exports_util2.objectClone(shape)),this.shape},catchall:never2(),...exports_util2.normalizeParams(params)})}function looseObject2(shape,params){return new ZodObject2({type:"object",get shape(){return exports_util2.assignProp(this,"shape",exports_util2.objectClone(shape)),this.shape},catchall:unknown2(),...exports_util2.normalizeParams(params)})}function union2(options,params){return new ZodUnion2({type:"union",options,...exports_util2.normalizeParams(params)})}function discriminatedUnion2(discriminator,options,params){return new ZodDiscriminatedUnion2({type:"union",options,discriminator,...exports_util2.normalizeParams(params)})}function intersection2(left,right){return new ZodIntersection2({type:"intersection",left,right})}function tuple2(items,_paramsOrRest,_params){let hasRest=_paramsOrRest instanceof $ZodType2,params=hasRest?_params:_paramsOrRest;return new ZodTuple2({type:"tuple",items,rest:hasRest?_paramsOrRest:null,...exports_util2.normalizeParams(params)})}function record2(keyType,valueType,params){return new ZodRecord2({type:"record",keyType,valueType,...exports_util2.normalizeParams(params)})}function partialRecord2(keyType,valueType,params){let k=clone2(keyType);return k._zod.values=void 0,new ZodRecord2({type:"record",keyType:k,valueType,...exports_util2.normalizeParams(params)})}function map2(keyType,valueType,params){return new ZodMap2({type:"map",keyType,valueType,...exports_util2.normalizeParams(params)})}function set2(valueType,params){return new ZodSet2({type:"set",valueType,...exports_util2.normalizeParams(params)})}function _enum4(values,params){let entries=Array.isArray(values)?Object.fromEntries(values.map((v)=>[v,v])):values;return new ZodEnum2({type:"enum",entries,...exports_util2.normalizeParams(params)})}function nativeEnum2(entries,params){return new ZodEnum2({type:"enum",entries,...exports_util2.normalizeParams(params)})}function literal3(value,params){return new ZodLiteral2({type:"literal",values:Array.isArray(value)?value:[value],...exports_util2.normalizeParams(params)})}function file2(params){return _file2(ZodFile2,params)}function transform2(fn2){return new ZodTransform2({type:"transform",transform:fn2})}function optional2(innerType){return new ZodOptional2({type:"optional",innerType})}function nullable2(innerType){return new ZodNullable2({type:"nullable",innerType})}function nullish4(innerType){return optional2(nullable2(innerType))}function _default4(innerType,defaultValue){return new ZodDefault2({type:"default",innerType,get defaultValue(){return typeof defaultValue==="function"?defaultValue():exports_util2.shallowClone(defaultValue)}})}function prefault2(innerType,defaultValue){return new ZodPrefault2({type:"prefault",innerType,get defaultValue(){return typeof defaultValue==="function"?defaultValue():exports_util2.shallowClone(defaultValue)}})}function nonoptional2(innerType,params){return new ZodNonOptional2({type:"nonoptional",innerType,...exports_util2.normalizeParams(params)})}function success2(innerType){return new ZodSuccess2({type:"success",innerType})}function _catch4(innerType,catchValue){return new ZodCatch2({type:"catch",innerType,catchValue:typeof catchValue==="function"?catchValue:()=>catchValue})}function nan2(params){return _nan2(ZodNaN2,params)}function pipe2(in_,out){return new ZodPipe2({type:"pipe",in:in_,out})}function codec3(in_,out,params){return new ZodCodec2({type:"pipe",in:in_,out,transform:params.decode,reverseTransform:params.encode})}function readonly2(innerType){return new ZodReadonly2({type:"readonly",innerType})}function templateLiteral2(parts,params){return new ZodTemplateLiteral2({type:"template_literal",parts,...exports_util2.normalizeParams(params)})}function lazy2(getter){return new ZodLazy2({type:"lazy",getter})}function promise2(innerType){return new ZodPromise2({type:"promise",innerType})}function _function2(params){return new ZodFunction2({type:"function",input:Array.isArray(params?.input)?tuple2(params?.input):params?.input??array2(unknown2()),output:params?.output??unknown2()})}function check2(fn2){let ch=new $ZodCheck2({check:"custom"});return ch._zod.check=fn2,ch}function custom2(fn2,_params){return _custom2(ZodCustom2,fn2??(()=>!0),_params)}function refine2(fn2,_params={}){return _refine2(ZodCustom2,fn2,_params)}function superRefine2(fn2){return _superRefine2(fn2)}function _instanceof2(cls,params={error:`Input not instance of ${cls.name}`}){let inst=new ZodCustom2({type:"custom",check:"custom",fn:(data)=>data instanceof cls,abort:!0,...exports_util2.normalizeParams(params)});return inst._zod.bag.Class=cls,inst}function json2(params){let jsonSchema=lazy2(()=>{return union2([string5(params),number5(),boolean5(),_null6(),array2(jsonSchema),record2(string5(),jsonSchema)])});return jsonSchema}function preprocess2(fn2,schema){return pipe2(transform2(fn2),schema)}var ZodType2,_ZodString2,ZodString2,ZodStringFormat2,ZodEmail2,ZodGUID2,ZodUUID2,ZodURL2,ZodEmoji2,ZodNanoID2,ZodCUID3,ZodCUID22,ZodULID2,ZodXID2,ZodKSUID2,ZodIPv42,ZodIPv62,ZodCIDRv42,ZodCIDRv62,ZodBase642,ZodBase64URL2,ZodE1642,ZodJWT2,ZodCustomStringFormat2,ZodNumber2,ZodNumberFormat2,ZodBoolean2,ZodBigInt2,ZodBigIntFormat2,ZodSymbol2,ZodUndefined2,ZodNull2,ZodAny2,ZodUnknown2,ZodNever2,ZodVoid2,ZodDate2,ZodArray2,ZodObject2,ZodUnion2,ZodDiscriminatedUnion2,ZodIntersection2,ZodTuple2,ZodRecord2,ZodMap2,ZodSet2,ZodEnum2,ZodLiteral2,ZodFile2,ZodTransform2,ZodOptional2,ZodNullable2,ZodDefault2,ZodPrefault2,ZodNonOptional2,ZodSuccess2,ZodCatch2,ZodNaN2,ZodPipe2,ZodCodec2,ZodReadonly2,ZodTemplateLiteral2,ZodLazy2,ZodPromise2,ZodFunction2,ZodCustom2,stringbool2=(...args2)=>_stringbool2({Codec:ZodCodec2,Boolean:ZodBoolean2,String:ZodString2},...args2);var init_schemas4=__esm(()=>{init_core5();init_core5();init_checks4();init_iso2();init_parse4();ZodType2=$constructor2("ZodType",(inst,def)=>{return $ZodType2.init(inst,def),inst.def=def,inst.type=def.type,Object.defineProperty(inst,"_def",{value:def}),inst.check=(...checks4)=>{return inst.clone({...def,checks:[...def.checks??[],...checks4.map((ch)=>typeof ch==="function"?{_zod:{check:ch,def:{check:"custom"},onattach:[]}}:ch)]})},inst.clone=(def2,params)=>clone2(inst,def2,params),inst.brand=()=>inst,inst.register=(reg,meta3)=>{return reg.add(inst,meta3),inst},inst.parse=(data,params)=>parse7(inst,data,params,{callee:inst.parse}),inst.safeParse=(data,params)=>safeParse4(inst,data,params),inst.parseAsync=async(data,params)=>parseAsync4(inst,data,params,{callee:inst.parseAsync}),inst.safeParseAsync=async(data,params)=>safeParseAsync4(inst,data,params),inst.spa=inst.safeParseAsync,inst.encode=(data,params)=>encode4(inst,data,params),inst.decode=(data,params)=>decode4(inst,data,params),inst.encodeAsync=async(data,params)=>encodeAsync4(inst,data,params),inst.decodeAsync=async(data,params)=>decodeAsync4(inst,data,params),inst.safeEncode=(data,params)=>safeEncode4(inst,data,params),inst.safeDecode=(data,params)=>safeDecode4(inst,data,params),inst.safeEncodeAsync=async(data,params)=>safeEncodeAsync4(inst,data,params),inst.safeDecodeAsync=async(data,params)=>safeDecodeAsync4(inst,data,params),inst.refine=(check2,params)=>inst.check(refine2(check2,params)),inst.superRefine=(refinement)=>inst.check(superRefine2(refinement)),inst.overwrite=(fn2)=>inst.check(_overwrite2(fn2)),inst.optional=()=>optional2(inst),inst.nullable=()=>nullable2(inst),inst.nullish=()=>optional2(nullable2(inst)),inst.nonoptional=(params)=>nonoptional2(inst,params),inst.array=()=>array2(inst),inst.or=(arg)=>union2([inst,arg]),inst.and=(arg)=>intersection2(inst,arg),inst.transform=(tx)=>pipe2(inst,transform2(tx)),inst.default=(def2)=>_default4(inst,def2),inst.prefault=(def2)=>prefault2(inst,def2),inst.catch=(params)=>_catch4(inst,params),inst.pipe=(target)=>pipe2(inst,target),inst.readonly=()=>readonly2(inst),inst.describe=(description)=>{let cl=inst.clone();return globalRegistry2.add(cl,{description}),cl},Object.defineProperty(inst,"description",{get(){return globalRegistry2.get(inst)?.description},configurable:!0}),inst.meta=(...args2)=>{if(args2.length===0)return globalRegistry2.get(inst);let cl=inst.clone();return globalRegistry2.add(cl,args2[0]),cl},inst.isOptional=()=>inst.safeParse(void 0).success,inst.isNullable=()=>inst.safeParse(null).success,inst}),_ZodString2=$constructor2("_ZodString",(inst,def)=>{$ZodString2.init(inst,def),ZodType2.init(inst,def);let bag=inst._zod.bag;inst.format=bag.format??null,inst.minLength=bag.minimum??null,inst.maxLength=bag.maximum??null,inst.regex=(...args2)=>inst.check(_regex2(...args2)),inst.includes=(...args2)=>inst.check(_includes2(...args2)),inst.startsWith=(...args2)=>inst.check(_startsWith2(...args2)),inst.endsWith=(...args2)=>inst.check(_endsWith2(...args2)),inst.min=(...args2)=>inst.check(_minLength2(...args2)),inst.max=(...args2)=>inst.check(_maxLength2(...args2)),inst.length=(...args2)=>inst.check(_length2(...args2)),inst.nonempty=(...args2)=>inst.check(_minLength2(1,...args2)),inst.lowercase=(params)=>inst.check(_lowercase2(params)),inst.uppercase=(params)=>inst.check(_uppercase2(params)),inst.trim=()=>inst.check(_trim2()),inst.normalize=(...args2)=>inst.check(_normalize2(...args2)),inst.toLowerCase=()=>inst.check(_toLowerCase2()),inst.toUpperCase=()=>inst.check(_toUpperCase2())}),ZodString2=$constructor2("ZodString",(inst,def)=>{$ZodString2.init(inst,def),_ZodString2.init(inst,def),inst.email=(params)=>inst.check(_email2(ZodEmail2,params)),inst.url=(params)=>inst.check(_url2(ZodURL2,params)),inst.jwt=(params)=>inst.check(_jwt2(ZodJWT2,params)),inst.emoji=(params)=>inst.check(_emoji3(ZodEmoji2,params)),inst.guid=(params)=>inst.check(_guid2(ZodGUID2,params)),inst.uuid=(params)=>inst.check(_uuid2(ZodUUID2,params)),inst.uuidv4=(params)=>inst.check(_uuidv42(ZodUUID2,params)),inst.uuidv6=(params)=>inst.check(_uuidv62(ZodUUID2,params)),inst.uuidv7=(params)=>inst.check(_uuidv72(ZodUUID2,params)),inst.nanoid=(params)=>inst.check(_nanoid2(ZodNanoID2,params)),inst.guid=(params)=>inst.check(_guid2(ZodGUID2,params)),inst.cuid=(params)=>inst.check(_cuid3(ZodCUID3,params)),inst.cuid2=(params)=>inst.check(_cuid22(ZodCUID22,params)),inst.ulid=(params)=>inst.check(_ulid2(ZodULID2,params)),inst.base64=(params)=>inst.check(_base642(ZodBase642,params)),inst.base64url=(params)=>inst.check(_base64url2(ZodBase64URL2,params)),inst.xid=(params)=>inst.check(_xid2(ZodXID2,params)),inst.ksuid=(params)=>inst.check(_ksuid2(ZodKSUID2,params)),inst.ipv4=(params)=>inst.check(_ipv42(ZodIPv42,params)),inst.ipv6=(params)=>inst.check(_ipv62(ZodIPv62,params)),inst.cidrv4=(params)=>inst.check(_cidrv42(ZodCIDRv42,params)),inst.cidrv6=(params)=>inst.check(_cidrv62(ZodCIDRv62,params)),inst.e164=(params)=>inst.check(_e1642(ZodE1642,params)),inst.datetime=(params)=>inst.check(datetime4(params)),inst.date=(params)=>inst.check(date6(params)),inst.time=(params)=>inst.check(time4(params)),inst.duration=(params)=>inst.check(duration4(params))});ZodStringFormat2=$constructor2("ZodStringFormat",(inst,def)=>{$ZodStringFormat2.init(inst,def),_ZodString2.init(inst,def)}),ZodEmail2=$constructor2("ZodEmail",(inst,def)=>{$ZodEmail2.init(inst,def),ZodStringFormat2.init(inst,def)});ZodGUID2=$constructor2("ZodGUID",(inst,def)=>{$ZodGUID2.init(inst,def),ZodStringFormat2.init(inst,def)});ZodUUID2=$constructor2("ZodUUID",(inst,def)=>{$ZodUUID2.init(inst,def),ZodStringFormat2.init(inst,def)});ZodURL2=$constructor2("ZodURL",(inst,def)=>{$ZodURL2.init(inst,def),ZodStringFormat2.init(inst,def)});ZodEmoji2=$constructor2("ZodEmoji",(inst,def)=>{$ZodEmoji2.init(inst,def),ZodStringFormat2.init(inst,def)});ZodNanoID2=$constructor2("ZodNanoID",(inst,def)=>{$ZodNanoID2.init(inst,def),ZodStringFormat2.init(inst,def)});ZodCUID3=$constructor2("ZodCUID",(inst,def)=>{$ZodCUID3.init(inst,def),ZodStringFormat2.init(inst,def)});ZodCUID22=$constructor2("ZodCUID2",(inst,def)=>{$ZodCUID22.init(inst,def),ZodStringFormat2.init(inst,def)});ZodULID2=$constructor2("ZodULID",(inst,def)=>{$ZodULID2.init(inst,def),ZodStringFormat2.init(inst,def)});ZodXID2=$constructor2("ZodXID",(inst,def)=>{$ZodXID2.init(inst,def),ZodStringFormat2.init(inst,def)});ZodKSUID2=$constructor2("ZodKSUID",(inst,def)=>{$ZodKSUID2.init(inst,def),ZodStringFormat2.init(inst,def)});ZodIPv42=$constructor2("ZodIPv4",(inst,def)=>{$ZodIPv42.init(inst,def),ZodStringFormat2.init(inst,def)});ZodIPv62=$constructor2("ZodIPv6",(inst,def)=>{$ZodIPv62.init(inst,def),ZodStringFormat2.init(inst,def)});ZodCIDRv42=$constructor2("ZodCIDRv4",(inst,def)=>{$ZodCIDRv42.init(inst,def),ZodStringFormat2.init(inst,def)});ZodCIDRv62=$constructor2("ZodCIDRv6",(inst,def)=>{$ZodCIDRv62.init(inst,def),ZodStringFormat2.init(inst,def)});ZodBase642=$constructor2("ZodBase64",(inst,def)=>{$ZodBase642.init(inst,def),ZodStringFormat2.init(inst,def)});ZodBase64URL2=$constructor2("ZodBase64URL",(inst,def)=>{$ZodBase64URL2.init(inst,def),ZodStringFormat2.init(inst,def)});ZodE1642=$constructor2("ZodE164",(inst,def)=>{$ZodE1642.init(inst,def),ZodStringFormat2.init(inst,def)});ZodJWT2=$constructor2("ZodJWT",(inst,def)=>{$ZodJWT2.init(inst,def),ZodStringFormat2.init(inst,def)});ZodCustomStringFormat2=$constructor2("ZodCustomStringFormat",(inst,def)=>{$ZodCustomStringFormat2.init(inst,def),ZodStringFormat2.init(inst,def)});ZodNumber2=$constructor2("ZodNumber",(inst,def)=>{$ZodNumber2.init(inst,def),ZodType2.init(inst,def),inst.gt=(value,params)=>inst.check(_gt2(value,params)),inst.gte=(value,params)=>inst.check(_gte2(value,params)),inst.min=(value,params)=>inst.check(_gte2(value,params)),inst.lt=(value,params)=>inst.check(_lt2(value,params)),inst.lte=(value,params)=>inst.check(_lte2(value,params)),inst.max=(value,params)=>inst.check(_lte2(value,params)),inst.int=(params)=>inst.check(int2(params)),inst.safe=(params)=>inst.check(int2(params)),inst.positive=(params)=>inst.check(_gt2(0,params)),inst.nonnegative=(params)=>inst.check(_gte2(0,params)),inst.negative=(params)=>inst.check(_lt2(0,params)),inst.nonpositive=(params)=>inst.check(_lte2(0,params)),inst.multipleOf=(value,params)=>inst.check(_multipleOf2(value,params)),inst.step=(value,params)=>inst.check(_multipleOf2(value,params)),inst.finite=()=>inst;let bag=inst._zod.bag;inst.minValue=Math.max(bag.minimum??Number.NEGATIVE_INFINITY,bag.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,inst.maxValue=Math.min(bag.maximum??Number.POSITIVE_INFINITY,bag.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,inst.isInt=(bag.format??"").includes("int")||Number.isSafeInteger(bag.multipleOf??0.5),inst.isFinite=!0,inst.format=bag.format??null});ZodNumberFormat2=$constructor2("ZodNumberFormat",(inst,def)=>{$ZodNumberFormat2.init(inst,def),ZodNumber2.init(inst,def)});ZodBoolean2=$constructor2("ZodBoolean",(inst,def)=>{$ZodBoolean2.init(inst,def),ZodType2.init(inst,def)});ZodBigInt2=$constructor2("ZodBigInt",(inst,def)=>{$ZodBigInt2.init(inst,def),ZodType2.init(inst,def),inst.gte=(value,params)=>inst.check(_gte2(value,params)),inst.min=(value,params)=>inst.check(_gte2(value,params)),inst.gt=(value,params)=>inst.check(_gt2(value,params)),inst.gte=(value,params)=>inst.check(_gte2(value,params)),inst.min=(value,params)=>inst.check(_gte2(value,params)),inst.lt=(value,params)=>inst.check(_lt2(value,params)),inst.lte=(value,params)=>inst.check(_lte2(value,params)),inst.max=(value,params)=>inst.check(_lte2(value,params)),inst.positive=(params)=>inst.check(_gt2(BigInt(0),params)),inst.negative=(params)=>inst.check(_lt2(BigInt(0),params)),inst.nonpositive=(params)=>inst.check(_lte2(BigInt(0),params)),inst.nonnegative=(params)=>inst.check(_gte2(BigInt(0),params)),inst.multipleOf=(value,params)=>inst.check(_multipleOf2(value,params));let bag=inst._zod.bag;inst.minValue=bag.minimum??null,inst.maxValue=bag.maximum??null,inst.format=bag.format??null});ZodBigIntFormat2=$constructor2("ZodBigIntFormat",(inst,def)=>{$ZodBigIntFormat2.init(inst,def),ZodBigInt2.init(inst,def)});ZodSymbol2=$constructor2("ZodSymbol",(inst,def)=>{$ZodSymbol2.init(inst,def),ZodType2.init(inst,def)});ZodUndefined2=$constructor2("ZodUndefined",(inst,def)=>{$ZodUndefined2.init(inst,def),ZodType2.init(inst,def)});ZodNull2=$constructor2("ZodNull",(inst,def)=>{$ZodNull2.init(inst,def),ZodType2.init(inst,def)});ZodAny2=$constructor2("ZodAny",(inst,def)=>{$ZodAny2.init(inst,def),ZodType2.init(inst,def)});ZodUnknown2=$constructor2("ZodUnknown",(inst,def)=>{$ZodUnknown2.init(inst,def),ZodType2.init(inst,def)});ZodNever2=$constructor2("ZodNever",(inst,def)=>{$ZodNever2.init(inst,def),ZodType2.init(inst,def)});ZodVoid2=$constructor2("ZodVoid",(inst,def)=>{$ZodVoid2.init(inst,def),ZodType2.init(inst,def)});ZodDate2=$constructor2("ZodDate",(inst,def)=>{$ZodDate2.init(inst,def),ZodType2.init(inst,def),inst.min=(value,params)=>inst.check(_gte2(value,params)),inst.max=(value,params)=>inst.check(_lte2(value,params));let c=inst._zod.bag;inst.minDate=c.minimum?new Date(c.minimum):null,inst.maxDate=c.maximum?new Date(c.maximum):null});ZodArray2=$constructor2("ZodArray",(inst,def)=>{$ZodArray2.init(inst,def),ZodType2.init(inst,def),inst.element=def.element,inst.min=(minLength,params)=>inst.check(_minLength2(minLength,params)),inst.nonempty=(params)=>inst.check(_minLength2(1,params)),inst.max=(maxLength,params)=>inst.check(_maxLength2(maxLength,params)),inst.length=(len,params)=>inst.check(_length2(len,params)),inst.unwrap=()=>inst.element});ZodObject2=$constructor2("ZodObject",(inst,def)=>{$ZodObjectJIT2.init(inst,def),ZodType2.init(inst,def),exports_util2.defineLazy(inst,"shape",()=>def.shape),inst.keyof=()=>_enum4(Object.keys(inst._zod.def.shape)),inst.catchall=(catchall)=>inst.clone({...inst._zod.def,catchall}),inst.passthrough=()=>inst.clone({...inst._zod.def,catchall:unknown2()}),inst.loose=()=>inst.clone({...inst._zod.def,catchall:unknown2()}),inst.strict=()=>inst.clone({...inst._zod.def,catchall:never2()}),inst.strip=()=>inst.clone({...inst._zod.def,catchall:void 0}),inst.extend=(incoming)=>{return exports_util2.extend(inst,incoming)},inst.safeExtend=(incoming)=>{return exports_util2.safeExtend(inst,incoming)},inst.merge=(other)=>exports_util2.merge(inst,other),inst.pick=(mask)=>exports_util2.pick(inst,mask),inst.omit=(mask)=>exports_util2.omit(inst,mask),inst.partial=(...args2)=>exports_util2.partial(ZodOptional2,inst,args2[0]),inst.required=(...args2)=>exports_util2.required(ZodNonOptional2,inst,args2[0])});ZodUnion2=$constructor2("ZodUnion",(inst,def)=>{$ZodUnion2.init(inst,def),ZodType2.init(inst,def),inst.options=def.options});ZodDiscriminatedUnion2=$constructor2("ZodDiscriminatedUnion",(inst,def)=>{ZodUnion2.init(inst,def),$ZodDiscriminatedUnion2.init(inst,def)});ZodIntersection2=$constructor2("ZodIntersection",(inst,def)=>{$ZodIntersection2.init(inst,def),ZodType2.init(inst,def)});ZodTuple2=$constructor2("ZodTuple",(inst,def)=>{$ZodTuple2.init(inst,def),ZodType2.init(inst,def),inst.rest=(rest)=>inst.clone({...inst._zod.def,rest})});ZodRecord2=$constructor2("ZodRecord",(inst,def)=>{$ZodRecord2.init(inst,def),ZodType2.init(inst,def),inst.keyType=def.keyType,inst.valueType=def.valueType});ZodMap2=$constructor2("ZodMap",(inst,def)=>{$ZodMap2.init(inst,def),ZodType2.init(inst,def),inst.keyType=def.keyType,inst.valueType=def.valueType});ZodSet2=$constructor2("ZodSet",(inst,def)=>{$ZodSet2.init(inst,def),ZodType2.init(inst,def),inst.min=(...args2)=>inst.check(_minSize2(...args2)),inst.nonempty=(params)=>inst.check(_minSize2(1,params)),inst.max=(...args2)=>inst.check(_maxSize2(...args2)),inst.size=(...args2)=>inst.check(_size2(...args2))});ZodEnum2=$constructor2("ZodEnum",(inst,def)=>{$ZodEnum2.init(inst,def),ZodType2.init(inst,def),inst.enum=def.entries,inst.options=Object.values(def.entries);let keys=new Set(Object.keys(def.entries));inst.extract=(values,params)=>{let newEntries={};for(let value of values)if(keys.has(value))newEntries[value]=def.entries[value];else throw Error(`Key ${value} not found in enum`);return new ZodEnum2({...def,checks:[],...exports_util2.normalizeParams(params),entries:newEntries})},inst.exclude=(values,params)=>{let newEntries={...def.entries};for(let value of values)if(keys.has(value))delete newEntries[value];else throw Error(`Key ${value} not found in enum`);return new ZodEnum2({...def,checks:[],...exports_util2.normalizeParams(params),entries:newEntries})}});ZodLiteral2=$constructor2("ZodLiteral",(inst,def)=>{$ZodLiteral2.init(inst,def),ZodType2.init(inst,def),inst.values=new Set(def.values),Object.defineProperty(inst,"value",{get(){if(def.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return def.values[0]}})});ZodFile2=$constructor2("ZodFile",(inst,def)=>{$ZodFile2.init(inst,def),ZodType2.init(inst,def),inst.min=(size,params)=>inst.check(_minSize2(size,params)),inst.max=(size,params)=>inst.check(_maxSize2(size,params)),inst.mime=(types,params)=>inst.check(_mime2(Array.isArray(types)?types:[types],params))});ZodTransform2=$constructor2("ZodTransform",(inst,def)=>{$ZodTransform2.init(inst,def),ZodType2.init(inst,def),inst._zod.parse=(payload,_ctx)=>{if(_ctx.direction==="backward")throw new $ZodEncodeError2(inst.constructor.name);payload.addIssue=(issue3)=>{if(typeof issue3==="string")payload.issues.push(exports_util2.issue(issue3,payload.value,def));else{let _issue=issue3;if(_issue.fatal)_issue.continue=!1;_issue.code??(_issue.code="custom"),_issue.input??(_issue.input=payload.value),_issue.inst??(_issue.inst=inst),payload.issues.push(exports_util2.issue(_issue))}};let output=def.transform(payload.value,payload);if(output instanceof Promise)return output.then((output2)=>{return payload.value=output2,payload});return payload.value=output,payload}});ZodOptional2=$constructor2("ZodOptional",(inst,def)=>{$ZodOptional2.init(inst,def),ZodType2.init(inst,def),inst.unwrap=()=>inst._zod.def.innerType});ZodNullable2=$constructor2("ZodNullable",(inst,def)=>{$ZodNullable2.init(inst,def),ZodType2.init(inst,def),inst.unwrap=()=>inst._zod.def.innerType});ZodDefault2=$constructor2("ZodDefault",(inst,def)=>{$ZodDefault2.init(inst,def),ZodType2.init(inst,def),inst.unwrap=()=>inst._zod.def.innerType,inst.removeDefault=inst.unwrap});ZodPrefault2=$constructor2("ZodPrefault",(inst,def)=>{$ZodPrefault2.init(inst,def),ZodType2.init(inst,def),inst.unwrap=()=>inst._zod.def.innerType});ZodNonOptional2=$constructor2("ZodNonOptional",(inst,def)=>{$ZodNonOptional2.init(inst,def),ZodType2.init(inst,def),inst.unwrap=()=>inst._zod.def.innerType});ZodSuccess2=$constructor2("ZodSuccess",(inst,def)=>{$ZodSuccess2.init(inst,def),ZodType2.init(inst,def),inst.unwrap=()=>inst._zod.def.innerType});ZodCatch2=$constructor2("ZodCatch",(inst,def)=>{$ZodCatch2.init(inst,def),ZodType2.init(inst,def),inst.unwrap=()=>inst._zod.def.innerType,inst.removeCatch=inst.unwrap});ZodNaN2=$constructor2("ZodNaN",(inst,def)=>{$ZodNaN2.init(inst,def),ZodType2.init(inst,def)});ZodPipe2=$constructor2("ZodPipe",(inst,def)=>{$ZodPipe2.init(inst,def),ZodType2.init(inst,def),inst.in=def.in,inst.out=def.out});ZodCodec2=$constructor2("ZodCodec",(inst,def)=>{ZodPipe2.init(inst,def),$ZodCodec2.init(inst,def)});ZodReadonly2=$constructor2("ZodReadonly",(inst,def)=>{$ZodReadonly2.init(inst,def),ZodType2.init(inst,def),inst.unwrap=()=>inst._zod.def.innerType});ZodTemplateLiteral2=$constructor2("ZodTemplateLiteral",(inst,def)=>{$ZodTemplateLiteral2.init(inst,def),ZodType2.init(inst,def)});ZodLazy2=$constructor2("ZodLazy",(inst,def)=>{$ZodLazy2.init(inst,def),ZodType2.init(inst,def),inst.unwrap=()=>inst._zod.def.getter()});ZodPromise2=$constructor2("ZodPromise",(inst,def)=>{$ZodPromise2.init(inst,def),ZodType2.init(inst,def),inst.unwrap=()=>inst._zod.def.innerType});ZodFunction2=$constructor2("ZodFunction",(inst,def)=>{$ZodFunction2.init(inst,def),ZodType2.init(inst,def)});ZodCustom2=$constructor2("ZodCustom",(inst,def)=>{$ZodCustom2.init(inst,def),ZodType2.init(inst,def)})});function setErrorMap2(map3){config2({customError:map3})}function getErrorMap2(){return config2().customError}var ZodIssueCode2,ZodFirstPartyTypeKind2;var init_compat2=__esm(()=>{init_core5();ZodIssueCode2={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};(function(ZodFirstPartyTypeKind3){})(ZodFirstPartyTypeKind2||(ZodFirstPartyTypeKind2={}))});var exports_coerce2={};__export(exports_coerce2,{string:()=>string6,number:()=>number6,date:()=>date8,boolean:()=>boolean6,bigint:()=>bigint6});function string6(params){return _coercedString2(ZodString2,params)}function number6(params){return _coercedNumber2(ZodNumber2,params)}function boolean6(params){return _coercedBoolean2(ZodBoolean2,params)}function bigint6(params){return _coercedBigint2(ZodBigInt2,params)}function date8(params){return _coercedDate2(ZodDate2,params)}var init_coerce2=__esm(()=>{init_core5();init_schemas4()});var exports_external2={};__export(exports_external2,{xid:()=>xid4,void:()=>_void4,uuidv7:()=>uuidv72,uuidv6:()=>uuidv62,uuidv4:()=>uuidv42,uuid:()=>uuid5,util:()=>exports_util2,url:()=>url2,uppercase:()=>_uppercase2,unknown:()=>unknown2,union:()=>union2,undefined:()=>_undefined6,ulid:()=>ulid4,uint64:()=>uint642,uint32:()=>uint322,tuple:()=>tuple2,trim:()=>_trim2,treeifyError:()=>treeifyError2,transform:()=>transform2,toUpperCase:()=>_toUpperCase2,toLowerCase:()=>_toLowerCase2,toJSONSchema:()=>toJSONSchema2,templateLiteral:()=>templateLiteral2,symbol:()=>symbol2,superRefine:()=>superRefine2,success:()=>success2,stringbool:()=>stringbool2,stringFormat:()=>stringFormat2,string:()=>string5,strictObject:()=>strictObject2,startsWith:()=>_startsWith2,size:()=>_size2,setErrorMap:()=>setErrorMap2,set:()=>set2,safeParseAsync:()=>safeParseAsync4,safeParse:()=>safeParse4,safeEncodeAsync:()=>safeEncodeAsync4,safeEncode:()=>safeEncode4,safeDecodeAsync:()=>safeDecodeAsync4,safeDecode:()=>safeDecode4,registry:()=>registry2,regexes:()=>exports_regexes2,regex:()=>_regex2,refine:()=>refine2,record:()=>record2,readonly:()=>readonly2,property:()=>_property2,promise:()=>promise2,prettifyError:()=>prettifyError2,preprocess:()=>preprocess2,prefault:()=>prefault2,positive:()=>_positive2,pipe:()=>pipe2,partialRecord:()=>partialRecord2,parseAsync:()=>parseAsync4,parse:()=>parse7,overwrite:()=>_overwrite2,optional:()=>optional2,object:()=>object2,number:()=>number5,nullish:()=>nullish4,nullable:()=>nullable2,null:()=>_null6,normalize:()=>_normalize2,nonpositive:()=>_nonpositive2,nonoptional:()=>nonoptional2,nonnegative:()=>_nonnegative2,never:()=>never2,negative:()=>_negative2,nativeEnum:()=>nativeEnum2,nanoid:()=>nanoid4,nan:()=>nan2,multipleOf:()=>_multipleOf2,minSize:()=>_minSize2,minLength:()=>_minLength2,mime:()=>_mime2,maxSize:()=>_maxSize2,maxLength:()=>_maxLength2,map:()=>map2,lte:()=>_lte2,lt:()=>_lt2,lowercase:()=>_lowercase2,looseObject:()=>looseObject2,locales:()=>exports_locales2,literal:()=>literal3,length:()=>_length2,lazy:()=>lazy2,ksuid:()=>ksuid4,keyof:()=>keyof2,jwt:()=>jwt2,json:()=>json2,iso:()=>exports_iso2,ipv6:()=>ipv64,ipv4:()=>ipv44,intersection:()=>intersection2,int64:()=>int642,int32:()=>int322,int:()=>int2,instanceof:()=>_instanceof2,includes:()=>_includes2,httpUrl:()=>httpUrl2,hostname:()=>hostname4,hex:()=>hex4,hash:()=>hash3,guid:()=>guid4,gte:()=>_gte2,gt:()=>_gt2,globalRegistry:()=>globalRegistry2,getErrorMap:()=>getErrorMap2,function:()=>_function2,formatError:()=>formatError2,float64:()=>float642,float32:()=>float322,flattenError:()=>flattenError2,file:()=>file2,enum:()=>_enum4,endsWith:()=>_endsWith2,encodeAsync:()=>encodeAsync4,encode:()=>encode4,emoji:()=>emoji4,email:()=>email4,e164:()=>e1644,discriminatedUnion:()=>discriminatedUnion2,decodeAsync:()=>decodeAsync4,decode:()=>decode4,date:()=>date7,custom:()=>custom2,cuid2:()=>cuid24,cuid:()=>cuid6,core:()=>exports_core5,config:()=>config2,coerce:()=>exports_coerce2,codec:()=>codec3,clone:()=>clone2,cidrv6:()=>cidrv64,cidrv4:()=>cidrv44,check:()=>check2,catch:()=>_catch4,boolean:()=>boolean5,bigint:()=>bigint5,base64url:()=>base64url4,base64:()=>base644,array:()=>array2,any:()=>any2,_function:()=>_function2,_default:()=>_default4,_ZodString:()=>_ZodString2,ZodXID:()=>ZodXID2,ZodVoid:()=>ZodVoid2,ZodUnknown:()=>ZodUnknown2,ZodUnion:()=>ZodUnion2,ZodUndefined:()=>ZodUndefined2,ZodUUID:()=>ZodUUID2,ZodURL:()=>ZodURL2,ZodULID:()=>ZodULID2,ZodType:()=>ZodType2,ZodTuple:()=>ZodTuple2,ZodTransform:()=>ZodTransform2,ZodTemplateLiteral:()=>ZodTemplateLiteral2,ZodSymbol:()=>ZodSymbol2,ZodSuccess:()=>ZodSuccess2,ZodStringFormat:()=>ZodStringFormat2,ZodString:()=>ZodString2,ZodSet:()=>ZodSet2,ZodRecord:()=>ZodRecord2,ZodRealError:()=>ZodRealError2,ZodReadonly:()=>ZodReadonly2,ZodPromise:()=>ZodPromise2,ZodPrefault:()=>ZodPrefault2,ZodPipe:()=>ZodPipe2,ZodOptional:()=>ZodOptional2,ZodObject:()=>ZodObject2,ZodNumberFormat:()=>ZodNumberFormat2,ZodNumber:()=>ZodNumber2,ZodNullable:()=>ZodNullable2,ZodNull:()=>ZodNull2,ZodNonOptional:()=>ZodNonOptional2,ZodNever:()=>ZodNever2,ZodNanoID:()=>ZodNanoID2,ZodNaN:()=>ZodNaN2,ZodMap:()=>ZodMap2,ZodLiteral:()=>ZodLiteral2,ZodLazy:()=>ZodLazy2,ZodKSUID:()=>ZodKSUID2,ZodJWT:()=>ZodJWT2,ZodIssueCode:()=>ZodIssueCode2,ZodIntersection:()=>ZodIntersection2,ZodISOTime:()=>ZodISOTime2,ZodISODuration:()=>ZodISODuration2,ZodISODateTime:()=>ZodISODateTime2,ZodISODate:()=>ZodISODate2,ZodIPv6:()=>ZodIPv62,ZodIPv4:()=>ZodIPv42,ZodGUID:()=>ZodGUID2,ZodFunction:()=>ZodFunction2,ZodFirstPartyTypeKind:()=>ZodFirstPartyTypeKind2,ZodFile:()=>ZodFile2,ZodError:()=>ZodError2,ZodEnum:()=>ZodEnum2,ZodEmoji:()=>ZodEmoji2,ZodEmail:()=>ZodEmail2,ZodE164:()=>ZodE1642,ZodDiscriminatedUnion:()=>ZodDiscriminatedUnion2,ZodDefault:()=>ZodDefault2,ZodDate:()=>ZodDate2,ZodCustomStringFormat:()=>ZodCustomStringFormat2,ZodCustom:()=>ZodCustom2,ZodCodec:()=>ZodCodec2,ZodCatch:()=>ZodCatch2,ZodCUID2:()=>ZodCUID22,ZodCUID:()=>ZodCUID3,ZodCIDRv6:()=>ZodCIDRv62,ZodCIDRv4:()=>ZodCIDRv42,ZodBoolean:()=>ZodBoolean2,ZodBigIntFormat:()=>ZodBigIntFormat2,ZodBigInt:()=>ZodBigInt2,ZodBase64URL:()=>ZodBase64URL2,ZodBase64:()=>ZodBase642,ZodArray:()=>ZodArray2,ZodAny:()=>ZodAny2,TimePrecision:()=>TimePrecision2,NEVER:()=>NEVER2,$output:()=>$output2,$input:()=>$input2,$brand:()=>$brand2});var init_external2=__esm(()=>{init_core5();init_core5();init_en2();init_core5();init_locales2();init_iso2();init_iso2();init_coerce2();init_schemas4();init_checks4();init_errors5();init_parse4();init_compat2();config2(en_default2())});var init_zod2=__esm(()=>{init_external2();init_external2()});function tool(input){return input}var init_tool=__esm(()=>{init_zod2();tool.schema=exports_external2});var init_dist=__esm(()=>{init_tool()});import*as fs41 from"node:fs";import*as path69 from"node:path";function resolveWorkingDirectory(workingDirectory,fallbackDirectory){if(workingDirectory==null||workingDirectory===""){if(typeof fallbackDirectory!=="string"||fallbackDirectory==="")return{success:!1,message:"Invalid working_directory: no explicit working_directory was provided and fallbackDirectory is missing or not a string"};try{assertProjectRoot(fallbackDirectory)}catch(error93){return{success:!1,message:error93 instanceof Error?error93.message:String(error93)}}return{success:!0,directory:fallbackDirectory}}if(typeof workingDirectory!=="string")return{success:!1,message:"Invalid working_directory: path must be a string"};if(workingDirectory.includes("\x00"))return{success:!1,message:"Invalid working_directory: null bytes are not allowed"};let reservedDevicePattern=/^(NUL|CON|AUX|COM[1-9]|LPT[1-9])(\..*)?$/i;if(workingDirectory.startsWith("\\\\")||process.platform==="win32"&&reservedDevicePattern.test(workingDirectory))return{success:!1,message:"Invalid working_directory: Windows device paths are not allowed"};if(workingDirectory.split(/[\\/]/).includes(".."))return{success:!1,message:"Invalid working_directory: path traversal sequences (..) are not allowed"};let normalizedDir=path69.normalize(workingDirectory),resolvedDir=path69.resolve(normalizedDir),statResult;try{statResult=fs41.statSync(resolvedDir)}catch{return{success:!1,message:`Invalid working_directory: path "${resolvedDir}" does not exist or is inaccessible`}}if(!statResult.isDirectory())return{success:!1,message:`Invalid working_directory: path "${resolvedDir}" is not a directory`};try{assertProjectRoot(resolvedDir)}catch(error93){return{success:!1,message:error93 instanceof Error?error93.message:String(error93)}}if(typeof fallbackDirectory!=="string"||fallbackDirectory==="")return{success:!0,directory:resolvedDir};let resolvedFallback=path69.resolve(fallbackDirectory),fallbackExists=!1;try{fs41.statSync(resolvedFallback),fallbackExists=!0}catch{fallbackExists=!1}if(fallbackExists){if(isStrictPathDescendant(resolvedDir,resolvedFallback)){if(hasExplicitProjectBoundary(resolvedDir))return{success:!0,directory:resolvedDir};return{success:!1,message:`Invalid working_directory: "${workingDirectory}" resolves to "${resolvedDir}" which is a subdirectory of fallback "${resolvedFallback}". Pass the project root path or omit working_directory entirely.`}}}return{success:!0,directory:resolvedDir}}var init_resolve_working_directory=__esm(()=>{init_project_boundary()});function classifyToolError(error93){let msg=(error93 instanceof Error?error93.message??"":String(error93)).toLowerCase();if(msg.includes("not registered")||msg.includes("unknown tool"))return"not_registered";if(msg.includes("not whitelisted")||msg.includes("not allowed"))return"not_whitelisted";if(msg.includes("enoent")||msg.includes("command not found")||msg.includes("binary not found")||msg.includes("no such file or directory"))return"binary_missing";return"execution_error"}function createSwarmTool(opts){let ownsWorkingDirectory=Object.hasOwn(opts.args,"working_directory"),allowsWorkingDirectoryOverride=opts.allowWorkingDirectoryOverride===!0&&!ownsWorkingDirectory,toolArgs=allowsWorkingDirectoryOverride?{...opts.args,working_directory:exports_external.string().optional().describe("Project or linked-worktree root for this tool invocation")}:opts.args;return tool({description:opts.description,args:toolArgs,execute:async(args2,ctx)=>{let fallbackDirectory=ctx?.directory??process.cwd();try{let effectiveArgs=args2,effectiveDirectory=fallbackDirectory,effectiveContext=ctx;if(!ownsWorkingDirectory&&typeof args2==="object"&&args2!==null){if(!allowsWorkingDirectoryOverride&&Object.hasOwn(args2,"working_directory"))throw Error("Invalid working_directory: this tool does not allow working_directory overrides");if(allowsWorkingDirectoryOverride&&Object.hasOwn(args2,"working_directory")){let{working_directory:workingDirectory,...executorArgs}=args2;if(effectiveArgs=executorArgs,workingDirectory!==void 0){let resolved=resolveWorkingDirectory(workingDirectory,fallbackDirectory);if(!resolved.success)throw Error(resolved.message);effectiveDirectory=resolved.directory,effectiveContext={...ctx,directory:resolved.directory,worktree:resolved.directory}}}}return await opts.execute(effectiveArgs,effectiveDirectory,effectiveContext)}catch(error93){let message=error93 instanceof Error?error93.message:String(error93);return JSON.stringify({success:!1,failure_class:classifyToolError(error93),message:"Tool execution failed",errors:[message]},null,2)}}})}var init_create_tool=__esm(()=>{init_dist();init_zod();init_resolve_working_directory()});var exports_checkpoint={};__export(exports_checkpoint,{saveCheckpointRecord:()=>saveCheckpointRecord,checkpoint:()=>checkpoint,_internals:()=>_internals65});import*as child_process3 from"node:child_process";import*as fs42 from"node:fs";import*as path70 from"node:path";function serializeResult(action,payload){return JSON.stringify({action,...payload},null,2)}function containsNonAsciiChars(label){for(let i=0;i<label.length;i++){let charCode=label.charCodeAt(i);if(charCode<32||charCode>126)return!0}return!1}function validateLabel(label){if(!label||label.length===0)return"label is required";if(label.length>MAX_LABEL_LENGTH)return`label exceeds maximum length of ${MAX_LABEL_LENGTH}`;if(label.startsWith("--"))return'label cannot start with "--" (git flag pattern)';if(CONTROL_CHAR_PATTERN.test(label))return"label contains control characters";if(NON_ASCII_PATTERN.test(label))return"label contains non-ASCII or invalid characters";if(containsNonAsciiChars(label))return"label contains non-ASCII characters (must be printable ASCII only)";if(SHELL_METACHARACTERS.test(label))return"label contains shell metacharacters";if(!SAFE_LABEL_PATTERN.test(label))return"label contains invalid characters (use alphanumeric, hyphen, underscore, space)";if(!/[a-zA-Z0-9_]/.test(label))return"label cannot be whitespace-only";if(label.includes("..")||label.includes("/")||label.includes("\\"))return"label contains path traversal sequence";return null}function getCheckpointLogPath(directory){return path70.join(directory,CHECKPOINT_LOG_PATH)}function readCheckpointLog(directory){let logPath=getCheckpointLogPath(directory);try{if(fs42.existsSync(logPath)){let content=fs42.readFileSync(logPath,"utf-8"),parsed=JSON.parse(content);if(!parsed.checkpoints||!Array.isArray(parsed.checkpoints))return{version:1,checkpoints:[]};return parsed}}catch{}return{version:1,checkpoints:[]}}function writeCheckpointLog(log2,directory){let logPath=getCheckpointLogPath(directory),dir=path70.dirname(logPath);if(!fs42.existsSync(dir))fs42.mkdirSync(dir,{recursive:!0});let tempPath=`${logPath}.tmp`;fs42.writeFileSync(tempPath,JSON.stringify(log2,null,2),"utf-8"),fs42.renameSync(tempPath,logPath)}function appendRetentionEvent(directory,event){try{appendCoreEventSync(directory,{...event,timestamp:new Date().toISOString()})}catch{}}function loadCheckpointConfig(directory){let maxCheckpoints=20,allowEmptyCommits=!1;try{let{config:config3}=loadPluginConfigWithMeta(directory);maxCheckpoints=config3.checkpoint?.max_retention??maxCheckpoints,allowEmptyCommits=config3.checkpoint?.allow_empty_commits===!0}catch{}return{maxCheckpoints,allowEmptyCommits}}function appendCheckpointEntry(directory,log2,entry,maxCheckpoints){let existing=log2.checkpoints.find((checkpoint)=>checkpoint.label===entry.label);if(existing){if(existing.sha!==entry.sha)throw Error(`checkpoint log conflict: label "${entry.label}" already exists with a different SHA`);return}if(log2.checkpoints.push(entry),log2.checkpoints.length>maxCheckpoints){let evicted=log2.checkpoints.splice(0,log2.checkpoints.length-maxCheckpoints);appendRetentionEvent(directory,{event:"checkpoint_retention_applied",evicted_labels:evicted.map((checkpoint)=>checkpoint.label),evicted_count:evicted.length,remaining_count:log2.checkpoints.length})}}function upsertTaskCompletionCheckpointEntry(directory,log2,entry,maxCheckpoints){let existingIndex=log2.checkpoints.findIndex((checkpoint)=>checkpoint.label===entry.label);if(existingIndex>=0){if(log2.checkpoints[existingIndex].sha===entry.sha)return;log2.checkpoints[existingIndex]=entry;return}if(log2.checkpoints.push(entry),log2.checkpoints.length>maxCheckpoints){let evicted=log2.checkpoints.splice(0,log2.checkpoints.length-maxCheckpoints);appendRetentionEvent(directory,{event:"checkpoint_retention_applied",evicted_labels:evicted.map((checkpoint)=>checkpoint.label),evicted_count:evicted.length,remaining_count:log2.checkpoints.length})}}function stageAllExcludingSwarm(directory){_internals65.gitExec(["add","--all","--",...NON_SWARM_COMMIT_PATHSPEC],directory)}function gitExec2(args2,cwd){for(let attempt=0;attempt<MAX_TRANSIENT_RETRIES;attempt++){let result=child_process3.spawnSync(_internals65.resolveGitExecutable(),args2,{cwd,encoding:"utf-8",timeout:GIT_TIMEOUT_MS2,stdio:["ignore","pipe","pipe"],windowsHide:!0,maxBuffer:GIT_MAX_BUFFER_BYTES2});if(result.error){let code=result.error.code,message=result.error.message??"";if(!(isTransientSpawnError(result.error)||/ETIMEDOUT|timed out/i.test(message))||attempt>=MAX_TRANSIENT_RETRIES-1){if(isSpawnCwdMissing(result.error,cwd))throw new GitSpawnCwdError(cwd,"missing");if(isSpawnCwdUnreadable(result.error,cwd))throw new GitSpawnCwdError(cwd,"unreadable");if(isGitBinaryMissing(result.error,cwd))throw new GitBinaryMissingError(`git executable is not available on PATH (working directory ${cwd} exists)`,{cause:result.error});throw Error(`git failed to start: ${code??"unknown"} - ${message}`)}transientBackoff(attempt);continue}if(result.status===0)return result.stdout??"";throw Error(result.stderr?.trim()||`git exited with code ${result.status}`)}throw Error("git command failed after transient retries")}function getCurrentSha(directory){return gitExec2(["rev-parse","HEAD"],directory).trim()}function findCommitByExactSubject(directory,subject){let output=_internals65.gitExec(["log","HEAD","--format=%H%x00%s","--fixed-strings",`--grep=${subject}`,"-n",String(CHECKPOINT_RECEIPT_LOOKUP_LIMIT)],directory);for(let line of output.split(/\r?\n/)){if(!line)continue;let nulIndex=line.indexOf("\x00");if(nulIndex<=0)continue;let sha=line.slice(0,nulIndex).trim(),candidateSubject=line.slice(nulIndex+1);if(sha.length===40&&/^[a-f0-9]{40}$/i.test(sha)&&candidateSubject===subject)return sha}return null}async function withTaskCompletionLocksResult(input){let deadline=Date.now()+CHECKPOINT_LOCK_DEADLINE_MS,attempts=0;while(attempts<CHECKPOINT_LOCK_MAX_ATTEMPTS&&Date.now()<=deadline){attempts++;let planLockResult;try{planLockResult=await _internals65.tryAcquireLock(input.directory,PLAN_LOCK_PATH,CHECKPOINT_AGENT_NAME,`save-task-completion-plan-${input.taskId}`)}catch(error93){if(input.onFailure)return input.onFailure(error93);return serializeResult("save_task_completion",{success:!1,error:`save_task_completion failed: ${error93 instanceof Error?error93.message:String(error93)}`})}if(!planLockResult.acquired){if(attempts>=CHECKPOINT_LOCK_MAX_ATTEMPTS||Date.now()+CHECKPOINT_LOCK_DELAY_MS>deadline)break;await _internals65.sleep(CHECKPOINT_LOCK_DELAY_MS);continue}try{let checkpointLockResult;try{checkpointLockResult=await _internals65.tryAcquireLock(input.directory,CHECKPOINT_LOG_PATH,CHECKPOINT_AGENT_NAME,`save-task-completion-checkpoint-${input.taskId}`)}catch(error93){if(input.onFailure)return input.onFailure(error93);return serializeResult("save_task_completion",{success:!1,error:`save_task_completion failed: ${error93 instanceof Error?error93.message:String(error93)}`})}if(!checkpointLockResult.acquired){if(attempts>=CHECKPOINT_LOCK_MAX_ATTEMPTS||Date.now()+CHECKPOINT_LOCK_DELAY_MS>deadline)break;await _internals65.sleep(CHECKPOINT_LOCK_DELAY_MS);continue}try{return await input.run()}catch(error93){if(input.onFailure)return input.onFailure(error93);return serializeResult("save_task_completion",{success:!1,error:`save_task_completion failed: ${error93 instanceof Error?error93.message:String(error93)}`})}finally{if(checkpointLockResult.lock._release)try{await checkpointLockResult.lock._release()}catch{}}}finally{if(planLockResult.lock._release)try{await planLockResult.lock._release()}catch{}}}if(input.onBusy)return input.onBusy(attempts);return serializeResult("save_task_completion",{success:!1,status:"checkpoint_busy",error:"checkpoint_busy: checkpoint or plan state is locked by another operation; retry after the current mutation completes",retryable:!0,attempts})}async function withCheckpointMutationLock(input){return await withCheckpointMutationLockResult({action:input.action,directory:input.directory,operationKey:input.operationKey,run:input.run,onContendedAttempt:input.onContendedAttempt})}async function withCheckpointMutationLockResult(input){let deadline=Date.now()+CHECKPOINT_LOCK_DEADLINE_MS,attempts=0;while(attempts<CHECKPOINT_LOCK_MAX_ATTEMPTS&&Date.now()<=deadline){attempts++;let lockResult;try{lockResult=await _internals65.tryAcquireLock(input.directory,CHECKPOINT_LOG_PATH,CHECKPOINT_AGENT_NAME,input.operationKey)}catch(error93){if(input.onFailure)return input.onFailure(error93);return serializeResult(input.action,{success:!1,error:`${input.action} failed: ${error93 instanceof Error?error93.message:String(error93)}`})}if(lockResult.acquired)try{try{return await input.run()}catch(error93){if(input.onFailure)return input.onFailure(error93);return serializeResult(input.action,{success:!1,error:`${input.action} failed: ${error93 instanceof Error?error93.message:String(error93)}`})}}finally{if(lockResult.lock._release)try{await lockResult.lock._release()}catch{}}let contended=input.onContendedAttempt?.();if(contended)return contended;if(attempts>=CHECKPOINT_LOCK_MAX_ATTEMPTS||Date.now()+CHECKPOINT_LOCK_DELAY_MS>deadline)break;await _internals65.sleep(CHECKPOINT_LOCK_DELAY_MS)}if(input.onBusy)return input.onBusy(attempts);return serializeResult(input.action,{success:!1,status:"checkpoint_busy",error:"checkpoint_busy: checkpoint state is locked by another operation; retry after the current mutation completes",retryable:!0,attempts})}function handleSave(label,directory){try{let{maxCheckpoints,allowEmptyCommits}=loadCheckpointConfig(directory),log2=readCheckpointLog(directory);if(log2.checkpoints.find((checkpoint)=>checkpoint.label===label))return serializeResult("save",{success:!1,error:`duplicate label: "${label}" already exists. Use a different label or delete the existing checkpoint first.`});let timestamp=new Date().toISOString();if(_internals65.stageAllExcludingSwarm(directory),(()=>{try{return gitExec2(["diff","--cached","--quiet"],directory),!1}catch{return!0}})())gitExec2(["commit","-m",`checkpoint: ${label}`],directory);else if(allowEmptyCommits)gitExec2(["commit","--allow-empty","-m",`checkpoint: ${label}`],directory);let newSha=getCurrentSha(directory);return appendCheckpointEntry(directory,log2,{label,sha:newSha,timestamp},maxCheckpoints),writeCheckpointLog(log2,directory),serializeResult("save",{success:!0,label,sha:newSha,message:`Checkpoint saved: "${label}"`})}catch(e){return serializeResult("save",{success:!1,error:e instanceof Error?`save failed: ${e.message}`:"save failed: unknown error"})}}async function saveCheckpointRecord(label,directory){let labelError=validateLabel(label);if(labelError)return{success:!1,error:labelError};return withCheckpointMutationLockResult({action:"save",directory,operationKey:`save-record-${label}`,run:async()=>{let log2=readCheckpointLog(directory);if(log2.checkpoints.find((checkpoint)=>checkpoint.label===label))return{success:!1,error:`duplicate label: "${label}"`};let sha="";if((await _internals65.readGitStatusAsync(["rev-parse","--git-dir"],directory)).ok)try{sha=getCurrentSha(directory)}catch{sha=""}appendCheckpointEntry(directory,log2,{label,sha,timestamp:new Date().toISOString()},loadCheckpointConfig(directory).maxCheckpoints),writeCheckpointLog(log2,directory);let result={success:!0,sha};if(!sha)result.warning="no git restore target - checkpoint recorded without a SHA (directory may not be a git repository or HEAD is unavailable)";return result},onBusy:()=>({success:!1,error:"checkpoint_busy: checkpoint state is locked by another operation; retry after the current mutation completes"}),onFailure:(error93)=>({success:!1,error:error93 instanceof Error?error93.message:"unknown error"})})}async function handleRestore(label,directory,confirmToken){try{let log2=readCheckpointLog(directory),checkpoint=log2.checkpoints.find((candidate)=>candidate.label===label);if(!checkpoint)return serializeResult("restore",{success:!1,error:`checkpoint not found: "${label}"`});let measurement=await _internals65.measureGitDestruction(directory,checkpoint.sha);if(measurement.kind==="unreadable"){let cause=describeUnreadableCause(measurement,measurement.source),unreadableNote=measurement.excludedOutOfRoot&&measurement.excludedOutOfRoot.length>0?` — ${measurement.excludedOutOfRoot.length} out-of-root porcelain record(s) had been excluded from the scope before the read failed (first: ${formatExcludedRecord(measurement.excludedOutOfRoot[0])})`:"";return serializeResult("restore",{success:!1,error:`cannot verify the working tree (${measurement.source==="enumeration"?"the target-tree listing could not be read":"git status unreadable"}; ${cause})${unreadableNote} — refusing to restore without a preview.`})}let exclusionNote=measurement.excludedOutOfRoot.length>0?`${measurement.excludedOutOfRoot.length} out-of-root porcelain record(s) were excluded from this scope (first: ${formatExcludedRecord(measurement.excludedOutOfRoot[0])})`:null;if(measurement.dirtyRelPaths.length>0){let candidates=trackedDirtyCandidates(directory,measurement.dirtyRelPaths),scopeAnchor=candidates[0].path;if(!confirmToken){let token=issueConfirmToken(scopeAnchor,directory,{kind:ROLLBACK_GIT_KIND,candidates}),shown=measurement.dirtyRelPaths.slice(0,10),overflow=measurement.dirtyRelPaths.length-shown.length;return serializeResult("restore",{success:!1,requires_confirm:!0,preview:[`Restoring to checkpoint "${label}" runs a hard git reset and would DESTROY ${candidates.length} uncommitted tracked file(s):`,...shown.map((p)=>` - ${p}`),...overflow>0?[` (+${overflow} more)`]:[],...exclusionNote?[`⚠ ${exclusionNote}`]:[],"Backups are taken automatically once confirmed."],confirm_token:token,message:"restore preview — re-run with confirm_token to execute (valid 15 minutes)"})}let verdict=consumeConfirmToken(scopeAnchor,directory,confirmToken,{kind:ROLLBACK_GIT_KIND,candidates});if(!verdict.ok)return serializeResult("restore",{success:!1,error:verdict.reason});let backup=backupTrackedChangesBeforeRollback(directory,measurement.dirtyRelPaths),atRiskExisting=measurement.dirtyRelPaths.filter((rel)=>fs42.existsSync(path70.join(directory,rel))).length;if(!backup.backupDir||backup.copied.length<atRiskExisting)return serializeResult("restore",{success:!1,error:`backup incomplete (${backup.copied.length}/${atRiskExisting} at-risk file(s) copied) — restore refused so nothing is destroyed.${backup.warnings.length>0?` Warnings: ${backup.warnings.join("; ")}`:""}`});let logBeforeReset2=log2;return gitExec2(["reset","--hard",checkpoint.sha],directory),writeCheckpointLog(logBeforeReset2,directory),serializeResult("restore",{success:!0,label,sha:checkpoint.sha,backup_dir:backup.backupDir,...backup.warnings.length>0?{backup_warnings:backup.warnings}:{},message:`Restored to checkpoint: "${label}" (hard reset)${backup.backupDir?`; destroyed bytes backed up to ${path70.relative(directory,backup.backupDir)}`:""}${backup.warnings.length>0?`; warnings: ${backup.warnings.join("; ")}`:""}${exclusionNote?`; ⚠ ${exclusionNote}`:""}`})}let logBeforeReset=log2;return gitExec2(["reset","--hard",checkpoint.sha],directory),writeCheckpointLog(logBeforeReset,directory),serializeResult("restore",{success:!0,label,sha:checkpoint.sha,message:`Restored to checkpoint: "${label}" (hard reset)${exclusionNote?`; ⚠ ${exclusionNote}`:""}`})}catch(e){return serializeResult("restore",{success:!1,error:e instanceof Error?`restore failed: ${e.message}`:"restore failed: unknown error"})}}function handleList(directory){let sorted=[...readCheckpointLog(directory).checkpoints].sort((a,b)=>b.timestamp.localeCompare(a.timestamp));return serializeResult("list",{success:!0,count:sorted.length,checkpoints:sorted})}function handleDelete(label,directory){try{let log2=readCheckpointLog(directory),initialLength=log2.checkpoints.length;if(log2.checkpoints=log2.checkpoints.filter((checkpoint)=>checkpoint.label!==label),log2.checkpoints.length===initialLength)return serializeResult("delete",{success:!1,error:`checkpoint not found: "${label}"`});return writeCheckpointLog(log2,directory),serializeResult("delete",{success:!0,label,message:`Checkpoint deleted: "${label}"`})}catch(e){return serializeResult("delete",{success:!1,error:e instanceof Error?`delete failed: ${e.message}`:"delete failed: unknown error"})}}async function handleSaveTaskCompletion(taskId,directory){return withTaskCompletionLocksResult({directory,taskId,run:async()=>{let plan=await _internals65.loadPlan(directory);if(!plan)return serializeResult("save_task_completion",{success:!1,error:"save_task_completion failed: no durable plan is available under .swarm/plan.json"});let task=plan.phases.flatMap((phase)=>phase.tasks).find((candidate)=>candidate.id===taskId);if(!task)return serializeResult("save_task_completion",{success:!1,error:`save_task_completion failed: task "${taskId}" was not found in the current plan`});if(task.status!=="completed")return serializeResult("save_task_completion",{success:!1,error:`save_task_completion failed: task "${taskId}" is ${task.status}, not completed`});await _internals65.afterTaskEligibilityRead?.(directory,task.id);let planIdentityHash=derivePlanIdentityHash(plan),planId=derivePlanId(plan),planEvents=(await readLedgerEvents(directory)).filter((event)=>event.plan_id===planId),anchor=planEvents.find((event)=>event.event_type==="plan_created"),anchorPlan=anchor?.payload?.plan;if(anchorPlan&&typeof anchorPlan==="object"){let rawIdentity=anchorPlan;if(typeof rawIdentity.swarm!=="string"||typeof rawIdentity.title!=="string"||derivePlanIdentityHash({swarm:rawIdentity.swarm,title:rawIdentity.title})!==planIdentityHash)throw Error(`save_task_completion failed: ledger identity does not match the current plan for task "${task.id}"`)}let latestTaskStatusEvent=[...planEvents].reverse().find((event)=>event.event_type==="task_status_changed"&&event.task_id===task.id);if(latestTaskStatusEvent&&latestTaskStatusEvent.to_status!=="completed")throw Error(`save_task_completion failed: the authoritative ledger does not record task "${task.id}" as completed`);let completionLedgerSeq=latestTaskStatusEvent?.seq??anchor?.seq??0,receipt=ensureTaskCheckpointReceipt(directory,planIdentityHash,task.id,completionLedgerSeq),descriptor=buildTaskCompletionDescriptor(planIdentityHash,task.id,receipt.generation);if(receipt.label!==descriptor.label)throw Error(`Task checkpoint receipt label conflict for ${task.id}: expected ${descriptor.label}, found ${receipt.label}`);if(receipt.state==="logged")return serializeResult("save_task_completion",{success:!0,idempotent:!0,label:receipt.label,sha:receipt.sha,receipt_state:receipt.state,message:`Checkpoint task completion already logged for "${descriptor.taskId}"`});let recoveredSha=_internals65.findCommitByExactSubject(directory,descriptor.subject),committedSha=null;if(committedSha=recoveredSha??receipt.sha,!committedSha)_internals65.stageAllExcludingSwarm(directory),_internals65.gitExec(["commit","--allow-empty","-m",descriptor.subject,"--",...NON_SWARM_COMMIT_PATHSPEC],directory),committedSha=getCurrentSha(directory);if(!committedSha)throw Error(`save_task_completion failed: could not resolve commit SHA for task "${descriptor.taskId}"`);updateTaskCheckpointReceipt(directory,descriptor,"committed",committedSha);let log2=readCheckpointLog(directory);upsertTaskCompletionCheckpointEntry(directory,log2,{label:descriptor.label,sha:committedSha,timestamp:new Date().toISOString()},loadCheckpointConfig(directory).maxCheckpoints),writeCheckpointLog(log2,directory);let logged=updateTaskCheckpointReceipt(directory,descriptor,"logged",committedSha);return serializeResult("save_task_completion",{success:!0,label:logged.label,sha:committedSha,receipt_state:logged.state,message:`Checkpoint task completion saved for "${descriptor.taskId}"`})}})}var CHECKPOINT_LOG_PATH=".swarm/checkpoints.json",PLAN_LOCK_PATH="plan.json",CHECKPOINT_AGENT_NAME="checkpoint",MAX_LABEL_LENGTH=100,GIT_TIMEOUT_MS2=30000,GIT_MAX_BUFFER_BYTES2=5242880,CHECKPOINT_LOCK_MAX_ATTEMPTS=20,CHECKPOINT_LOCK_DELAY_MS=250,CHECKPOINT_LOCK_DEADLINE_MS=45000,CHECKPOINT_RECEIPT_LOOKUP_LIMIT=25,NON_SWARM_COMMIT_PATHSPEC,SHELL_METACHARACTERS,SAFE_LABEL_PATTERN,CONTROL_CHAR_PATTERN,NON_ASCII_PATTERN,_internals65,checkpoint;var init_checkpoint=__esm(()=>{init_zod();init_destructive_purge();init_git_status_read();init_reset_backup();init_rollback_gate();init_config2();init_task_checkpoint_receipt();init_core_events();init_file_locks();init_ledger();init_manager();init_utils3();init_git_binary_missing_error();init_git_executable();init_create_tool();NON_SWARM_COMMIT_PATHSPEC=[".",":(exclude,top).swarm",":(exclude,top).swarm/**"],SHELL_METACHARACTERS=/[;|&$`(){}<>!'"]/,SAFE_LABEL_PATTERN=/^[a-zA-Z0-9_ -]+$/,CONTROL_CHAR_PATTERN=/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/,NON_ASCII_PATTERN=/[^\x20-\x7E]/,_internals65={tryAcquireLock,loadPlan,gitExec:gitExec2,sleep:(ms)=>new Promise((resolve36)=>setTimeout(resolve36,ms)),findCommitByExactSubject,stageAllExcludingSwarm,resolveGitExecutable,measureGitDestruction,readGitStatusAsync,readGitRepositoryStatusDetailedAsync};checkpoint=createSwarmTool({allowWorkingDirectoryOverride:!0,description:"Save, restore, list, and delete git checkpoints. Use save to create a named snapshot, restore to return tracked files to a checkpoint (a destructive restore previews first and requires a confirm token issued in the preview; destroyed bytes are backed up under .swarm/rollback-backups/), list to see all checkpoints, delete to remove a checkpoint from the log, and save_task_completion to record a retry-safe task completion checkpoint. Git commits are preserved on delete.",args:{action:exports_external.string().describe("Action to perform: save, restore, list, delete, or save_task_completion"),label:exports_external.string().optional().describe("Checkpoint label (required for save, restore, delete)"),confirm_token:exports_external.string().optional().describe("Confirm token from a destructive-restore preview (required when restore would destroy uncommitted tracked work; the preview response carries the token)"),task_id:exports_external.string().optional().describe('Plan task ID (required for save_task_completion), e.g. "1.1"')},execute:async(args2,directory)=>{let repoStatus=await _internals65.readGitRepositoryStatusDetailedAsync(directory);if(!repoStatus.isRepo){let reason=repoStatus.reason==="not_git_repo"?"not a git repository":repoStatus.reason==="git_unavailable"?"git executable is not available":`git probe failed (${repoStatus.message})`;return serializeResult("unknown",{success:!1,error:`${reason} - checkpoint tools require a git repository`})}let action,label,confirmToken,taskId;try{action=String(args2.action),label=args2.label!==void 0&&args2.label!==null?String(args2.label):void 0,confirmToken=args2.confirm_token!==void 0&&args2.confirm_token!==null?String(args2.confirm_token):void 0,taskId=args2.task_id!==void 0&&args2.task_id!==null?String(args2.task_id):void 0}catch{return serializeResult("unknown",{success:!1,error:"invalid arguments"})}let validActions=["save","restore","list","delete","save_task_completion"];if(!validActions.includes(action))return serializeResult("unknown",{success:!1,error:`invalid action: "${action}". Valid actions: ${validActions.join(", ")}`});if(["save","restore","delete"].includes(action)){if(!label)return serializeResult(action,{success:!1,error:`label is required for ${action} action`});let labelError=validateLabel(label);if(labelError)return serializeResult(action,{success:!1,error:`invalid label: ${labelError}`})}if(action==="save_task_completion"){if(!taskId||taskId.trim().length===0)return serializeResult("save_task_completion",{success:!1,error:"task_id is required for save_task_completion action"})}switch(action){case"save":return withCheckpointMutationLock({action:"save",directory,operationKey:`save-${label}`,run:async()=>handleSave(label,directory)});case"restore":return withCheckpointMutationLock({action:"restore",directory,operationKey:`restore-${label}`,run:async()=>await handleRestore(label,directory,confirmToken)});case"list":return handleList(directory);case"delete":return withCheckpointMutationLock({action:"delete",directory,operationKey:`delete-${label}`,run:async()=>handleDelete(label,directory)});case"save_task_completion":return handleSaveTaskCompletion(taskId,directory);default:return serializeResult("unknown",{success:!1,error:"unreachable"})}}})});var exports_auto_checkpoint={};__export(exports_auto_checkpoint,{maybeSaveAutoCheckpoint:()=>maybeSaveAutoCheckpoint,evaluateAutoCheckpoint:()=>evaluateAutoCheckpoint,countCompletedTasks:()=>countCompletedTasks,buildAutoCheckpointLabel:()=>buildAutoCheckpointLabel,_internals:()=>_internals66,DEFAULT_AUTO_CHECKPOINT_THRESHOLD:()=>DEFAULT_AUTO_CHECKPOINT_THRESHOLD});import*as child_process4 from"node:child_process";import*as fs43 from"node:fs";import*as path71 from"node:path";function countCompletedTasks(plan){return plan.phases.reduce((total,phase)=>total+phase.tasks.filter((task)=>task.status==="completed").length,0)}function buildAutoCheckpointLabel(plan,completedCount,generation=1){let base=`auto-task-checkpoint-${derivePlanIdentityHash(plan).slice(0,12)}-${String(completedCount).padStart(3,"0")}`;return generation<=1?base:`${base}-g${generation}`}function evaluateAutoCheckpoint(input){let{plan,completedCount,enabled}=input,threshold=Number.isInteger(input.threshold)&&input.threshold>=1?input.threshold:DEFAULT_AUTO_CHECKPOINT_THRESHOLD;if(enabled===!1)return{shouldSave:!1,completedCount,threshold,skipReason:"disabled"};if(completedCount<=0||completedCount%threshold!==0)return{shouldSave:!1,completedCount,threshold,skipReason:"below_threshold"};return{shouldSave:!0,completedCount,threshold,label:buildAutoCheckpointLabel(plan,completedCount)}}function resolveHead(directory){let result;try{result=_internals66.spawnSync(resolveGitExecutable(),["rev-parse","HEAD"],{cwd:directory,encoding:"utf-8",timeout:GIT_PROBE_TIMEOUT_MS,maxBuffer:GIT_PROBE_MAX_BUFFER_BYTES,stdio:["ignore","pipe","pipe"],windowsHide:!0})}catch{return null}if(result.error||result.status!==0)return null;let sha=(result.stdout??"").trim();return/^[0-9a-f]{40}$/i.test(sha)?sha:null}function readCheckpointEntries(directory){try{let logPath=path71.join(directory,".swarm","checkpoints.json");if(!fs43.existsSync(logPath))return[];let parsed=JSON.parse(fs43.readFileSync(logPath,"utf-8"));if(!Array.isArray(parsed.checkpoints))return[];return parsed.checkpoints.filter((entry)=>typeof entry?.label==="string"&&typeof entry?.sha==="string").map((entry)=>({label:entry.label,sha:entry.sha}))}catch{return[]}}async function maybeSaveAutoCheckpoint(directory,plan){let enabled=!0,threshold=DEFAULT_AUTO_CHECKPOINT_THRESHOLD;try{let{config:config3}=_internals66.loadPluginConfigWithMeta(directory);if(config3.checkpoint?.enabled===!1)enabled=!1;if(config3.checkpoint?.auto_checkpoint_threshold!==void 0)threshold=config3.checkpoint.auto_checkpoint_threshold}catch{}let completedCount=countCompletedTasks(plan),decision=evaluateAutoCheckpoint({plan,completedCount,threshold,enabled});if(!decision.shouldSave||!decision.label)return{...decision,saved:!1};let head=resolveHead(directory);if(head===null)return{...decision,shouldSave:!1,saved:!1,skipReason:"no_restorable_head"};let existing=readCheckpointEntries(directory),baseLabel=decision.label;if(existing.filter((entry)=>parseLabelGeneration(baseLabel,entry.label)!==null).some((entry)=>entry.sha===head))return{...decision,saved:!0,skipReason:"already_current"};let taken=new Set(existing.map((entry)=>entry.label)),generation=1,label=baseLabel;while(taken.has(label))generation+=1,label=buildAutoCheckpointLabel(plan,completedCount,generation);let{saveCheckpointRecord:saveCheckpointRecord2}=await Promise.resolve().then(() => (init_checkpoint(),exports_checkpoint)),result=await saveCheckpointRecord2(label,directory);if(result.success)return emitAutoSavedEvent(directory,{label,completedCount,threshold:decision.threshold}),{...decision,label,saved:!0};let reconcileHead=resolveHead(directory)??head;if(readCheckpointEntries(directory).some((entry)=>(entry.sha===head||entry.sha===reconcileHead)&&parseLabelGeneration(baseLabel,entry.label)!==null))return{...decision,label,saved:!0,skipReason:"already_current"};return{...decision,label,saved:!1,warning:result.warning??result.error}}function emitAutoSavedEvent(directory,payload){try{appendCoreEventSync(directory,{event:"checkpoint_auto_saved",...payload,timestamp:new Date().toISOString()})}catch{}}function parseLabelGeneration(baseLabel,label){if(label===baseLabel)return 1;if(!label.startsWith(baseLabel))return null;let match=/^-g(\d{1,6})$/.exec(label.slice(baseLabel.length));if(!match)return null;let generation=Number(match[1]);return generation>=2?generation:null}var DEFAULT_AUTO_CHECKPOINT_THRESHOLD=3,GIT_PROBE_TIMEOUT_MS=1e4,GIT_PROBE_MAX_BUFFER_BYTES=1048576,_internals66;var init_auto_checkpoint=__esm(()=>{init_config2();init_core_events();init_git_executable();init_utils3();_internals66={loadPluginConfigWithMeta,spawnSync:child_process4.spawnSync.bind(child_process4)}});import{closeSync as closeSync11,fsyncSync as fsyncSync3,mkdirSync as mkdirSync25,openSync as openSync11,renameSync as renameSync13,unlinkSync as unlinkSync13,writeFileSync as writeFileSync15}from"node:fs";import*as fsPromises4 from"node:fs/promises";import*as path72 from"node:path";function derivePhaseStatusesInPlace(plan){for(let phase of plan.phases){let tasks=phase.tasks;if(tasks.length>0&&tasks.every((t)=>t.status==="completed"))phase.status="complete";else if(tasks.some((t)=>t.status==="in_progress"))phase.status="in_progress";else if(tasks.some((t)=>t.status==="blocked"))phase.status="blocked";else phase.status="pending"}}function statusRank(s){switch(s){case"closed":return 5;case"completed":return 4;case"blocked":return 3;case"in_progress":return 2;case"pending":return 1;default:return 0}}function mergeStatusesTakingPrecedence(validated,replayed,ledgerStatusTaskIds){let projected=structuredClone(validated),replayedByTaskId=new Map;for(let phase of replayed.phases)for(let task of phase.tasks)if(ledgerStatusTaskIds.has(task.id))replayedByTaskId.set(task.id,task.status);for(let phase of projected.phases)for(let task of phase.tasks){let replayedStatus=replayedByTaskId.get(task.id);if(replayedStatus&&statusRank(replayedStatus)>statusRank(task.status))task.status=replayedStatus}return derivePhaseStatusesInPlace(projected),projected}function collectLedgerStatusTaskIds(events){let statusTaskIds=new Set;for(let event of events)if(event.event_type==="task_status_changed"&&typeof event.task_id==="string")statusTaskIds.add(event.task_id);return statusTaskIds}async function retryCasWithBackoff(directory,eventInput,options){let maxRetries=options.maxRetries??CAS_MAX_RETRIES,currentExpected=options.expectedHash,attempt=0;while(!0)try{return await appendLedgerEvent(directory,eventInput,{expectedHash:currentExpected,planHashAfter:options.planHashAfter,preCommitCheck:options.preCommitCheck})}catch(error93){if(!(error93 instanceof LedgerStaleWriterError)||attempt>=maxRetries)throw error93;attempt++;let base=Math.min(CAS_BACKOFF_START_MS*2**(attempt-1),CAS_BACKOFF_CAP_MS),jitter=base*CAS_BACKOFF_JITTER*(Math.random()*2-1),delayMs=Math.max(1,Math.round(base+jitter));if(emit("plan_ledger_cas_retry",{attempt,expectedHashPrefix:currentExpected.slice(0,8),delayMs}),await new Promise((resolve37)=>setTimeout(resolve37,delayMs)),options.verifyValid){if(!await options.verifyValid())return null}currentExpected=computeCurrentPlanHash(directory)}}async function loadPlanJsonOnly(directory){try{return await parsePlanJsonCached(directory)}catch(error93){warn(`Plan validation failed for .swarm/plan.json: ${error93 instanceof Error?error93.message:String(error93)}`)}return null}function compareTaskIds(a,b){let partsA=a.split(".").map((n)=>parseInt(n,10)),partsB=b.split(".").map((n)=>parseInt(n,10)),maxLen=Math.max(partsA.length,partsB.length);for(let i=0;i<maxLen;i++){let numA=partsA[i]??0,numB=partsB[i]??0;if(numA!==numB)return numA-numB}return 0}async function getLatestLedgerHash(directory){try{let events=await readLedgerEvents(directory);if(events.length===0)return"";return events[events.length-1].plan_hash_after}catch{return""}}async function surfaceLedgerStaleIfPersisted(directory,plan,options){let resolvedWorkspace=canonicalRootKeyFresh(directory);if(!ledgerStaleWorkspaces.has(resolvedWorkspace))return plan;try{let planHash=computePlanLedgerHash(plan),ledgerHash=await getLatestLedgerHash(directory);if(ledgerHash!==""&&planHash===ledgerHash)return options?.preCommitCheck?.(),ledgerStaleWorkspaces.delete(resolvedWorkspace),plan}catch(error93){if(error93 instanceof PlanRecoverySupersededError)throw error93}if(plan._ledgerReplayStale=!0,typeof plan._ledgerReplayStaleReason!=="string"||plan._ledgerReplayStaleReason.length===0)plan._ledgerReplayStaleReason="plan.json still hash-mismatches the ledger after a startup ledger-replay failure (replay could not be applied and no critic-approved snapshot was available). Run /swarm reset-session if this persists.";return plan}async function parsePlanJsonCached(directory){let planJsonPath=path72.resolve(directory,".swarm","plan.json");return readCachedParsedFile(planJsonPath,PLAN_JSON_CACHE_NAMESPACE,()=>_internals67.readPlanJsonUtf8(directory),(planJsonContent)=>{if(planJsonContent.includes("\x00"))throw Error("Plan rejected: .swarm/plan.json contains null bytes");let parsed=JSON.parse(planJsonContent);return PlanSchema.parse(parsed)})}async function readPlanJsonUtf8(directory){return readSwarmFileAsync(directory,"plan.json",void 0,(filePath)=>_internals67.readPlanFileUtf8(filePath),!1)}async function readPlanFileUtf8(filePath){return new TextDecoder("utf-8",{fatal:!0}).decode(await fsPromises4.readFile(filePath))}function computePlanContentHash(plan){let content={schema_version:plan.schema_version,title:plan.title,swarm:plan.swarm,current_phase:plan.current_phase,migration_status:plan.migration_status,execution_profile:normalizeExecutionProfileForHash(plan.execution_profile),phases:plan.phases.map((phase)=>({id:phase.id,name:phase.name,status:phase.status,tasks:phase.tasks.map((task)=>({id:task.id,phase:task.phase,status:task.status,size:task.size,description:task.description,depends:[...task.depends].sort(compareTaskIds),acceptance:task.acceptance,files_touched:[...task.files_touched].sort(),evidence_path:task.evidence_path,blocked_reason:task.blocked_reason,evidence_class:task.evidence_class,evidence_anchors:task.evidence_anchors})).sort((a,b)=>compareTaskIds(a.id,b.id))})).sort((a,b)=>a.id-b.id)},jsonString=JSON.stringify(content);return bunHash(jsonString).toString(36)}function extractPlanHashFromMarkdown(markdown){let match=markdown.match(/<!--\s*PLAN_HASH:\s*(\S+)\s*-->/);return match?match[1]:null}async function isPlanMdInSync(directory,plan,cache2){let planMdContent=await readSwarmFileAsync(directory,"plan.md",cache2);if(planMdContent===null)return!1;let expectedHash=computePlanContentHash(plan);if(extractPlanHashFromMarkdown(planMdContent)===expectedHash)return!0;let normalizedExpected=derivePlanMarkdown(plan).trim();if(planMdContent.trim()===normalizedExpected)return!0;return!1}async function regeneratePlanMarkdown(directory,plan,options){assertProjectRoot(directory);let swarmDir=path72.resolve(directory,".swarm"),contentHash=computePlanContentHash(plan),markdown=derivePlanMarkdown(plan),markdownWithHash=`<!-- PLAN_HASH: ${contentHash} -->
|
|
885
885
|
${markdown}`,mdPath=path72.join(swarmDir,"plan.md"),mdTempPath=path72.join(swarmDir,`plan.md.tmp.${Date.now()}.${Math.floor(Math.random()*1e9)}`);try{await bunWrite(mdTempPath,markdownWithHash),options?.preCommitCheck?.(),renameSync13(mdTempPath,mdPath)}finally{try{unlinkSync13(mdTempPath)}catch{}}invalidateCachedArtifact(mdPath)}async function loadPlan(directory,cache2,options){options?.preCommitCheck?.();let planJsonContent=null,claimedStartupWorkspace=null;try{planJsonContent=await _internals67.readPlanJsonUtf8(directory)}catch(error93){warn(`Plan rejected: .swarm/plan.json could not be decoded as valid UTF-8: ${error93 instanceof Error?error93.message:String(error93)}`)}if(planJsonContent!==null)if(planJsonContent.includes("\x00"))warn("Plan rejected: .swarm/plan.json contains null bytes");else try{let validated=await parsePlanJsonCached(directory);if(validated===null)warn("[loadPlan] plan.json disappeared during cached parse. Falling back to plan.md migration or ledger recovery.");else{if(!await isPlanMdInSync(directory,validated,cache2))try{await _internals67.regeneratePlanMarkdown(directory,validated,{preCommitCheck:options?.preCommitCheck})}catch(regenError){if(regenError instanceof PlanRecoverySupersededError)throw regenError;warn(`Failed to regenerate plan.md: ${regenError instanceof Error?regenError.message:String(regenError)}. Proceeding with plan.json only.`)}if(await ledgerExists(directory)){let planHash=computePlanLedgerHash(validated),ledgerHash=await getLatestLedgerHash(directory),resolvedWorkspace=canonicalRootKeyFresh(directory);if(!startupLedgerCheckedWorkspaces.has(resolvedWorkspace)){if(options?.preCommitCheck?.(),startupLedgerCheckedWorkspaces.add(resolvedWorkspace),claimedStartupWorkspace=resolvedWorkspace,ledgerHash!==""&&planHash!==ledgerHash){let currentPlanId=derivePlanId(validated),ledgerEvents=await readLedgerEvents(directory),firstEvent=ledgerEvents.length>0?ledgerEvents[0]:null;if(firstEvent&&firstEvent.plan_id!==currentPlanId)warn(`[loadPlan] Ledger identity mismatch (ledger: ${firstEvent.plan_id}, plan: ${currentPlanId}) — skipping ledger rebuild (migration detected). Use /swarm reset-session to reinitialize the ledger.`);else{warn("[loadPlan] plan.json is stale (hash mismatch with ledger) — rebuilding from ledger. If this recurs, run /swarm reset-session to clear stale session state.");try{let{plan:rebuilt,truncated}=await replayFromLedgerWithStatus(directory,{preCommitCheck:options?.preCommitCheck});if(truncated){let runtimeStale=validated;return runtimeStale._ledgerReplayStale=!0,runtimeStale._ledgerReplayStaleReason="Ledger truncated: a malformed line stopped replay before the tail, so the ledger could only be reconstructed up to the corruption. plan.json was PRESERVED (not rolled back to the prefix-only projection) and the corrupted suffix was quarantined to .swarm/plan-ledger.quarantine.*. Verify state, then run /swarm reset-session if this persists.",options?.preCommitCheck?.(),ledgerStaleWorkspaces.add(resolvedWorkspace),criticalWarn("[loadPlan] Ledger truncated (poison line detected) — preserving plan.json instead of rolling back to the prefix-only ledger projection. Durable post-poison events remain in plan.json. Corrupted suffix quarantined to .swarm/plan-ledger.quarantine.*. Run /swarm reset-session after verifying state if this persists."),runtimeStale}if(rebuilt)return await rebuildPlan(directory,rebuilt,{reason:"ledger_hash_mismatch_recovery",preCommitCheck:options?.preCommitCheck}),warn("[loadPlan] Rebuilt plan from ledger. Checkpoint available at .swarm/plan-export/SWARM_PLAN.md if it exists."),rebuilt}catch(replayError){if(replayError instanceof PlanRecoverySupersededError)throw replayError;try{let approved=await loadLastApprovedPlan(directory,currentPlanId);if(approved){await rebuildPlan(directory,approved.plan,{reason:"approved_snapshot_fallback",preCommitCheck:options?.preCommitCheck});try{await takeSnapshotEvent(directory,approved.plan,{source:"recovery_from_approved_snapshot",approvalMetadata:approved.approval,preCommitCheck:options?.preCommitCheck})}catch(healError){if(healError instanceof PlanRecoverySupersededError)throw healError;warn(`[loadPlan] Recovery-heal snapshot append failed: ${healError instanceof Error?healError.message:String(healError)}. Next loadPlan may re-enter recovery path.`)}let approvedPhase=approved.approval&&typeof approved.approval==="object"&&"phase"in approved.approval?approved.approval.phase:void 0;return warn(`[loadPlan] Ledger replay failed (${replayError instanceof Error?replayError.message:String(replayError)}) — recovered from critic-approved snapshot seq=${approved.seq} (approval phase=${approvedPhase??"unknown"}, timestamp=${approved.timestamp}). This may roll the plan back to an earlier phase — verify before continuing.`),approved.plan}}catch(recoveryError){if(recoveryError instanceof PlanRecoverySupersededError)throw recoveryError}{let runtimeStale=validated;runtimeStale._ledgerReplayStale=!0,runtimeStale._ledgerReplayStaleReason=`Ledger replay failed during hash-mismatch rebuild and no approved snapshot was available: ${replayError instanceof Error?replayError.message:String(replayError)}`,options?.preCommitCheck?.(),ledgerStaleWorkspaces.add(resolvedWorkspace)}warn(`[loadPlan] Ledger replay failed during hash-mismatch rebuild: ${replayError instanceof Error?replayError.message:String(replayError)}. Returning stale plan.json. To recover: check .swarm/plan-export/SWARM_PLAN.md for a checkpoint, or run /swarm reset-session.`)}}}}else if(ledgerHash!==""&&planHash!==ledgerHash){if(process.env.DEBUG_SWARM)console.warn(`[loadPlan] Ledger hash mismatch during active session for ${resolvedWorkspace} — skipping rebuild (startup check already performed).`)}}if(validated.specHash){let staleResult=await isSpecStale(directory,validated);if(staleResult.stale){let runtimePlan=validated;if(runtimePlan._specStale=!0,runtimePlan._specStaleReason=staleResult.reason,!await isObligationPreserving(directory)){try{assertProjectRoot(directory);let diffInfo=computeSpecDiff(directory),specStalenessPath=path72.join(directory,".swarm","spec-staleness.json");await commitAsyncPreparedFile(specStalenessPath,JSON.stringify({type:"spec_stale_detected",timestamp:new Date().toISOString(),phase:validated.current_phase??1,specHash_plan:validated.specHash,specHash_current:staleResult.currentHash??null,reason:staleResult.reason,planTitle:validated.title,diff:diffInfo?.diff??null,changedSections:diffInfo?.changedSections??[]},null,2),options?.preCommitCheck,"spec-staleness"),invalidateCachedArtifact(specStalenessPath)}catch(error93){if(error93 instanceof PlanRecoverySupersededError)throw error93}try{assertProjectRoot(directory);let event={type:"spec_stale_detected",timestamp:new Date().toISOString(),phase:validated.current_phase??1,specHash_plan:validated.specHash,specHash_current:staleResult.currentHash??null,reason:staleResult.reason??"unknown",planTitle:validated.title};options?.preCommitCheck?.(),appendCoreEventSync(directory,{...event})}catch(error93){if(error93 instanceof PlanRecoverySupersededError)throw error93}}}}return await surfaceLedgerStaleIfPersisted(directory,validated,options)}}catch(error93){if(error93 instanceof PlanRecoverySupersededError){if(claimedStartupWorkspace!==null)startupLedgerCheckedWorkspaces.delete(claimedStartupWorkspace);throw error93}warn(`[loadPlan] plan.json validation failed: ${error93 instanceof Error?error93.message:String(error93)}. Attempting rebuild from ledger. If rebuild fails, check .swarm/plan-export/SWARM_PLAN.md for a checkpoint.`);let rawPlanId=null,rawPlanJsonParseFailed=!1;try{let rawParsed=JSON.parse(planJsonContent);if(typeof rawParsed?.swarm==="string"&&typeof rawParsed?.title==="string")rawPlanId=derivePlanId(rawParsed)}catch{rawPlanJsonParseFailed=!0}if(await _internals67.ledgerExists(directory)){let catchIntegrity=await _internals67.readLedgerEventsWithIntegrity(directory),ledgerEventsForCatch=catchIntegrity.events,catchFirstEvent=ledgerEventsForCatch.length>0?ledgerEventsForCatch[0]:null;if(!(rawPlanId===null||catchFirstEvent===null||catchFirstEvent.plan_id===rawPlanId))warn(`[loadPlan] Ledger identity mismatch in validation-failure path (ledger: ${catchFirstEvent?.plan_id}, plan: ${rawPlanId}) — skipping ledger rebuild (migration detected).`);else if(catchFirstEvent!==null&&(rawPlanId!==null||rawPlanJsonParseFailed&&!catchIntegrity.truncated)){let rebuilt=null;try{rebuilt=await _internals67.replayFromLedger(directory,{preCommitCheck:options?.preCommitCheck})}catch(replayError){if(replayError instanceof PlanRecoverySupersededError)throw replayError;warn(`[loadPlan] Ledger replay threw in validation-failure path: ${replayError instanceof Error?replayError.message:String(replayError)}. Falling back to critic-approved snapshot before legacy migration.`)}if(rebuilt)return await rebuildPlan(directory,rebuilt,{reason:"validation_failure_recovery",preCommitCheck:options?.preCommitCheck}),warn("[loadPlan] Rebuilt plan from ledger after validation failure. Projection was stale."),rebuilt;try{let approved=await _internals67.loadLastApprovedPlan(directory,catchFirstEvent.plan_id);if(approved){let{removedCount}=await savePlanWithAutoAcknowledgedRemovals(directory,approved.plan,"load_plan_recovery_from_approved_snapshot","restore from critic-approved snapshot",{preCommitCheck:options?.preCommitCheck});if(removedCount>0)approved.plan._midLoadRemovals={count:removedCount,source:"load_plan_recovery_from_approved_snapshot"};try{await takeSnapshotEvent(directory,approved.plan,{source:"recovery_from_approved_snapshot",approvalMetadata:approved.approval,preCommitCheck:options?.preCommitCheck})}catch(healError){if(healError instanceof PlanRecoverySupersededError)throw healError;warn(`[loadPlan] Recovery-heal snapshot append failed: ${healError instanceof Error?healError.message:String(healError)}. Next loadPlan may re-enter recovery path.`)}return warn(`[loadPlan] Recovered from critic-approved snapshot seq=${approved.seq} after validation failure with exhausted ledger replay (approved snapshot beats lossy Markdown migration).`),approved.plan}}catch(approvedError){if(approvedError instanceof PlanRecoverySupersededError)throw approvedError;warn(`[loadPlan] Approved-snapshot recovery failed in validation-failure path: ${approvedError instanceof Error?approvedError.message:String(approvedError)}`)}}}let planMdContent2=await readSwarmFileAsync(directory,"plan.md",cache2);if(planMdContent2!==null){let migrated=migrateLegacyPlan(planMdContent2),{removedCount}=await savePlanWithAutoAcknowledgedRemovals(directory,migrated,"load_plan_migration_from_md","migrate legacy plan.md to plan.json",{preCommitCheck:options?.preCommitCheck});if(removedCount>0)migrated._midLoadRemovals={count:removedCount,source:"load_plan_migration_from_md"};return await appendMigrationProvenanceEvent(directory,migrated,options?.preCommitCheck),migrated}}if(await _internals67.ledgerExists(directory)){let resolvedDir=canonicalRootKeyFresh(directory),existingMutex=recoveryMutexes.get(resolvedDir);if(existingMutex){await existingMutex;let postRecoveryPlan=await _internals67.loadPlanJsonOnly(directory);if(postRecoveryPlan)return postRecoveryPlan}let resolveRecovery,mutex=new Promise((r)=>{resolveRecovery=r});recoveryMutexes.set(resolvedDir,mutex);try{let rebuilt=null;try{rebuilt=await _internals67.replayFromLedger(directory,{preCommitCheck:options?.preCommitCheck})}catch(replayError){if(replayError instanceof PlanRecoverySupersededError)throw replayError;warn(`[loadPlan] Ledger replay threw in missing-projection path: ${replayError instanceof Error?replayError.message:String(replayError)}. Falling back to critic-approved snapshot before legacy migration.`)}if(rebuilt){let{removedCount}=await savePlanWithAutoAcknowledgedRemovals(directory,rebuilt,"load_plan_rebuild_from_ledger","rebuild plan from ledger replay",{preCommitCheck:options?.preCommitCheck});if(removedCount>0)rebuilt._midLoadRemovals={count:removedCount,source:"load_plan_rebuild_from_ledger"};return rebuilt}try{let anchorEvents=(await _internals67.readLedgerEventsWithIntegrity(directory)).events;if(anchorEvents.length===0)return warn("[loadPlan] Ledger present but no events readable — refusing approved-snapshot recovery (cannot verify plan identity)."),null;let expectedPlanId=anchorEvents[0].plan_id,approved=await _internals67.loadLastApprovedPlan(directory,expectedPlanId);if(approved){let approvedPhase=approved.approval&&typeof approved.approval==="object"&&"phase"in approved.approval?approved.approval.phase:void 0;warn(`[loadPlan] Ledger replay returned no plan — recovered from critic-approved snapshot seq=${approved.seq} timestamp=${approved.timestamp} (approval phase=${approvedPhase??"unknown"}). This may roll the plan back to an earlier phase — verify before continuing.`);let{removedCount:snapshotRemovedCount}=await savePlanWithAutoAcknowledgedRemovals(directory,approved.plan,"load_plan_recovery_from_approved_snapshot","restore from critic-approved snapshot",{preCommitCheck:options?.preCommitCheck});if(snapshotRemovedCount>0)approved.plan._midLoadRemovals={count:snapshotRemovedCount,source:"load_plan_recovery_from_approved_snapshot"};try{await takeSnapshotEvent(directory,approved.plan,{source:"recovery_from_approved_snapshot",approvalMetadata:approved.approval,preCommitCheck:options?.preCommitCheck})}catch(healError){if(healError instanceof PlanRecoverySupersededError)throw healError;warn(`[loadPlan] Recovery-heal snapshot append failed: ${healError instanceof Error?healError.message:String(healError)}. Next loadPlan may re-enter recovery path.`)}return approved.plan}}catch(recoveryError){if(recoveryError instanceof PlanRecoverySupersededError)throw recoveryError;warn(`[loadPlan] Approved-snapshot recovery failed: ${recoveryError instanceof Error?recoveryError.message:String(recoveryError)}`)}}finally{resolveRecovery(),recoveryMutexes.delete(resolvedDir)}}let planMdContent=await readSwarmFileAsync(directory,"plan.md",cache2);if(planMdContent!==null){let migrated=migrateLegacyPlan(planMdContent),{removedCount}=await savePlanWithAutoAcknowledgedRemovals(directory,migrated,"load_plan_migration_from_md","migrate legacy plan.md to plan.json",{preCommitCheck:options?.preCommitCheck});if(removedCount>0)migrated._midLoadRemovals={count:removedCount,source:"load_plan_migration_from_md"};return await appendMigrationProvenanceEvent(directory,migrated,options?.preCommitCheck),migrated}return null}async function savePlanWithAutoAcknowledgedRemovals(directory,plan,source,reason,options){let existing=await _internals67.loadPlanJsonOnly(directory),newIds=new Set;for(let phase of plan.phases)for(let task of phase.tasks)newIds.add(task.id);let removedIds=[];if(existing){for(let phase of existing.phases)for(let task of phase.tasks)if(!newIds.has(task.id))removedIds.push(task.id)}return await savePlan(directory,plan,{...options??{},acknowledged_removals:{ids:removedIds,reason,source}}),{removedCount:removedIds.length}}async function withPlanLifecycleLock(directory,taskId,fn2){assertProjectRoot(directory);let lockResult=await tryAcquireLock(directory,"plan.json","plan-lifecycle",taskId);if(!lockResult.acquired)throw new PlanConcurrentModificationError(`Plan lifecycle blocked: plan.json is locked by ${lockResult.existing?.agent??"another agent"} (task: ${lockResult.existing?.taskId??"unknown"})`);try{return await fn2()}finally{if(lockResult.lock._release)await lockResult.lock._release().catch(()=>{})}}async function verifyWrittenPlanJson(directory,expected){let content;try{content=await readSwarmFileAsync(directory,"plan.json",void 0,(filePath)=>_internals67.readPlanFileUtf8(filePath),!1)}catch(error93){throw new PlanWriteVerificationError(`PLAN_WRITE_VERIFICATION_FAILED: plan.json read-back could not be read (${error93 instanceof Error?error93.message:String(error93)})`)}for(let attempt=0;content===null&&attempt<PLAN_WRITE_VERIFY_READ_RETRIES;attempt++){await new Promise((resolve37)=>setTimeout(resolve37,PLAN_WRITE_VERIFY_READ_BACKOFF_MS*(attempt+1)));try{content=await readSwarmFileAsync(directory,"plan.json",void 0,(filePath)=>_internals67.readPlanFileUtf8(filePath),!1)}catch{}}if(content===null)throw new PlanWriteVerificationError("PLAN_WRITE_VERIFICATION_FAILED: plan.json read-back returned no content after write");let parsed;try{parsed=JSON.parse(content)}catch(error93){throw new PlanWriteVerificationError(`PLAN_WRITE_VERIFICATION_FAILED: plan.json read-back did not parse (${error93 instanceof Error?error93.message:String(error93)})`)}if(JSON.stringify(parsed)!==JSON.stringify(expected))throw new PlanWriteVerificationError("PLAN_WRITE_VERIFICATION_FAILED: plan.json read-back content differs from the projected plan")}async function appendMigrationProvenanceEvent(directory,plan,preCommitCheck){try{preCommitCheck?.(),await appendLedgerEvent(directory,{event_type:"plan_rebuilt",source:"load_plan_migration_from_md",plan_id:derivePlanId(plan),payload:{reason:"load_plan_migration_from_md",phases_count:plan.phases.length,tasks_count:plan.phases.reduce((sum,phase)=>sum+phase.tasks.length,0)}},{preCommitCheck})}catch(error93){if(error93 instanceof PlanRecoverySupersededError)throw error93;warn(`[loadPlan] Markdown-migration provenance event append failed (plan remains migrated): ${error93 instanceof Error?error93.message:String(error93)}`)}}async function savePlan(directory,plan,options){if(directory===null||directory===void 0||typeof directory!=="string"||directory.trim().length===0)throw Error("Invalid directory: directory must be a non-empty string");if(assertProjectRoot(directory),!options?.planLockAlreadyHeld){let lockResult=await tryAcquireLock(directory,"plan.json","plan-manager",`save-plan-${Date.now()}-${Math.random().toString(36).slice(2,8)}`);if(!lockResult.acquired)throw new PlanConcurrentModificationError(`Plan write blocked: plan.json is locked by ${lockResult.existing?.agent??"another agent"} (task: ${lockResult.existing?.taskId??"unknown"})`);try{return await savePlan(directory,plan,{...options,planLockAlreadyHeld:!0})}finally{if(lockResult.lock._release)await lockResult.lock._release().catch(()=>{})}}let validated=PlanSchema.parse(plan),requestedForStaleProjectionReconcile=options?.staleProjectionReconcile!==void 0?PlanSchema.parse(plan):null;if(requestedForStaleProjectionReconcile)derivePhaseStatusesInPlace(requestedForStaleProjectionReconcile);if(options?.preserveCompletedStatuses!==!1)try{let currentPlan2=await _internals67.loadPlanJsonOnly(directory);if(currentPlan2){let completedTaskIds=new Set;for(let phase of currentPlan2.phases)for(let task of phase.tasks)if(task.status==="completed")completedTaskIds.add(task.id);if(completedTaskIds.size>0){for(let phase of validated.phases)for(let task of phase.tasks)if(completedTaskIds.has(task.id)&&task.status!=="completed")task.status="completed"}}}catch{}derivePhaseStatusesInPlace(validated),normalizeCurrentPhaseInPlace(validated);let currentPlan=await _internals67.loadPlanJsonOnly(directory),planId=derivePlanId(validated),planHashForInit=computePlanLedgerHash(validated);if(!await ledgerExists(directory))try{options?.preCommitCheck?.(),await initLedger(directory,planId,planHashForInit,validated,{preCommitCheck:options?.preCommitCheck})}catch(initErr){let msg=initErr instanceof Error?initErr.message:String(initErr);if(!/already initialized/i.test(msg))throw initErr}else{let existingEvents=await readLedgerEvents(directory);if(existingEvents.length>0&&existingEvents[0].plan_id!==planId)options?.preCommitCheck?.(),await replacePlanLedgerWithRoot(directory,validated,"savePlan_identity_migration",{preCommitCheck:options?.preCommitCheck}),warn(`[savePlan] Ledger identity mismatch (was "${existingEvents[0].plan_id}", now "${planId}") — archived the prior exact history and committed a new root.`)}if(options?.staleProjectionReconcile){if(!currentPlan)throw Error("RECONCILE_LEDGER_PROJECTION_MISMATCH: no current plan.json projection exists.");let comparableCurrent=PlanSchema.parse(currentPlan);if(derivePhaseStatusesInPlace(comparableCurrent),JSON.stringify(comparableCurrent)!==JSON.stringify(requestedForStaleProjectionReconcile))throw Error("RECONCILE_LEDGER_PROJECTION_MISMATCH: manager rejected content that is not the exact unchanged plan.json projection.");let events=await readLedgerEvents(directory),tail=events[events.length-1],expected=options.staleProjectionReconcile;if(!tail||tail.seq!==expected.expectedSeq||tail.plan_hash_after!==expected.expectedLedgerHash||events[0]?.plan_id!==planId)throw new PlanConcurrentModificationError("RECONCILE_LEDGER_PROJECTION_STALE: the ledger identity or tail changed before the recovery snapshot could be appended.");try{if((await _internals67.readLedgerEventsWithIntegrity(directory)).truncated)await replaceTruncatedLedgerWithRecoveryRoot(directory,validated,{seq:expected.expectedSeq,ledgerHash:expected.expectedLedgerHash});else await takeSnapshotEvent(directory,validated,{planHashAfter:computePlanLedgerHash(validated),source:"save_plan_stale_projection_reconcile",expectedSeq:expected.expectedSeq,expectedLedgerHash:expected.expectedLedgerHash})}catch(error93){if(error93 instanceof LedgerStaleWriterError)throw new PlanConcurrentModificationError(`RECONCILE_LEDGER_PROJECTION_STALE: ${error93.message}`);throw error93}}let currentHash=computeCurrentPlanHash(directory),hashAfter=computePlanLedgerHash(validated);if(currentPlan){let oldTaskMap=new Map;for(let phase of currentPlan.phases)for(let task of phase.tasks)oldTaskMap.set(task.id,{phase:task.phase,status:task.status});let newTaskIds=new Set;for(let phase of validated.phases)for(let task of phase.tasks)newTaskIds.add(task.id);let missingTasks=[];for(let[id,info]of oldTaskMap.entries())if(!newTaskIds.has(id))missingTasks.push({id,phase:info.phase,status:info.status});let ack=options?.acknowledged_removals;if(missingTasks.length>0){if(!ack)throw new PlanTaskRemovalNotAcknowledgedError(missingTasks);if(typeof ack.reason!=="string"||ack.reason.trim().length===0)throw Error("PLAN_ACKNOWLEDGED_REMOVAL_INVALID: acknowledged_removals.reason must be a non-empty string.");if(typeof ack.source!=="string"||ack.source.trim().length===0)throw Error("PLAN_ACKNOWLEDGED_REMOVAL_INVALID: acknowledged_removals.source must be a non-empty string.");let ackSet=new Set(ack.ids),missingIdsSet=new Set(missingTasks.map((t)=>t.id)),unacked=missingTasks.filter((t)=>!ackSet.has(t.id));if(unacked.length>0)throw new PlanTaskRemovalNotAcknowledgedError(unacked);for(let id of ack.ids)if(!missingIdsSet.has(id))throw Error(`PLAN_ACKNOWLEDGED_REMOVAL_INVALID: acknowledged_removals contains "${id}" but that task is not missing from the plan.`);try{for(let missing of missingTasks){options?.preCommitCheck?.();let eventInput={plan_id:derivePlanId(validated),event_type:"task_removed",task_id:missing.id,phase_id:missing.phase,from_status:missing.status,source:ack.source,payload:{reason:ack.reason,source:ack.source}},capturedTaskId=missing.id;await retryCasWithBackoff(directory,eventInput,{expectedHash:currentHash,planHashAfter:hashAfter,preCommitCheck:options?.preCommitCheck,verifyValid:async()=>{let onDisk=await _internals67.loadPlanJsonOnly(directory);if(!onDisk)return!0;for(let p of onDisk.phases)if(p.tasks.some((x)=>x.id===capturedTaskId))return!0;return!1}})}}catch(error93){if(error93 instanceof LedgerStaleWriterError)throw new PlanConcurrentModificationError(`Concurrent plan modification detected after retries: ${error93.message}. Please retry the operation.`);throw error93}}try{for(let phase of validated.phases)for(let task of phase.tasks){let oldTask=oldTaskMap.get(task.id);if(oldTask&&oldTask.status!==task.status){options?.preCommitCheck?.();let eventInput={plan_id:derivePlanId(validated),event_type:"task_status_changed",task_id:task.id,phase_id:phase.id,from_status:oldTask.status,to_status:task.status,source:"savePlan"},capturedFromStatus=oldTask.status,capturedTaskId=task.id;await retryCasWithBackoff(directory,eventInput,{expectedHash:currentHash,planHashAfter:hashAfter,preCommitCheck:options?.preCommitCheck,verifyValid:async()=>{let onDisk=await _internals67.loadPlanJsonOnly(directory);if(!onDisk)return!0;for(let p of onDisk.phases){let t=p.tasks.find((x)=>x.id===capturedTaskId);if(t)return t.status===capturedFromStatus}return!1}})}}}catch(error93){if(error93 instanceof LedgerStaleWriterError)throw new PlanConcurrentModificationError(`Concurrent plan modification detected after retries: ${error93.message}. Please retry the operation.`);throw error93}}let ledgerStatusTaskIds=collectLedgerStatusTaskIds(await readLedgerEvents(directory)),replayedBeforeProjection=await _internals67.replayFromLedger(directory,{preCommitCheck:options?.preCommitCheck}),projectionCandidate=replayedBeforeProjection?mergeStatusesTakingPrecedence(validated,replayedBeforeProjection,ledgerStatusTaskIds):validated;if(replayedBeforeProjection&&computePlanLedgerHash(replayedBeforeProjection)!==computePlanLedgerHash(projectionCandidate))options?.preCommitCheck?.(),await takeSnapshotEvent(directory,projectionCandidate,{planHashAfter:computePlanLedgerHash(projectionCandidate),source:"savePlan_structural_projection",preCommitCheck:options?.preCommitCheck});let projectedPlan=projectionCandidate,SNAPSHOT_INTERVAL=50,latestSeq=await getLatestLedgerSeq(directory);if(!options?.preCommitCheck&&latestSeq>0&&latestSeq%SNAPSHOT_INTERVAL===0)await takeSnapshotWithRetry(directory,projectedPlan,{planHashAfter:computePlanLedgerHash(projectedPlan),source:"savePlan_manager"});let swarmDir=path72.resolve(directory,".swarm"),planPath=path72.join(swarmDir,"plan.json"),tempPath=path72.join(swarmDir,`plan.json.tmp.${Date.now()}.${Math.floor(Math.random()*1e9)}`);try{await bunWrite(tempPath,JSON.stringify(projectedPlan,null,2)),options?.preCommitCheck?.(),renameSync13(tempPath,planPath)}finally{try{unlinkSync13(tempPath)}catch{}}invalidateCachedArtifact(planPath),await _internals67.verifyWrittenPlanJson(directory,projectedPlan);try{let markerPath=path72.join(swarmDir,".plan-write-marker"),inProgressMarker=JSON.stringify({source:"plan_manager",timestamp:new Date().toISOString(),phases_count:projectedPlan.phases.length,tasks_count:projectedPlan.phases.reduce((sum,p)=>sum+p.tasks.length,0),in_progress:!0});await commitAsyncPreparedFile(markerPath,inProgressMarker,options?.preCommitCheck,"plan-write-marker")}catch(error93){if(error93 instanceof PlanRecoverySupersededError)throw error93}let mdWriteError;try{let contentHash=computePlanContentHash(projectedPlan),markdown=derivePlanMarkdown(projectedPlan),markdownWithHash=`<!-- PLAN_HASH: ${contentHash} -->
|
|
886
886
|
${markdown}`,mdPath=path72.join(swarmDir,"plan.md"),mdTempPath=path72.join(swarmDir,`plan.md.tmp.${Date.now()}.${Math.floor(Math.random()*1e9)}`);try{await bunWrite(mdTempPath,markdownWithHash),options?.preCommitCheck?.(),renameSync13(mdTempPath,mdPath)}finally{try{unlinkSync13(mdTempPath)}catch{}}invalidateCachedArtifact(mdPath)}catch(mdError){if(mdError instanceof PlanRecoverySupersededError)throw mdError;let message=mdError instanceof Error?mdError.message:String(mdError);mdWriteError=message,warn(`[savePlan] plan.md write failed (non-fatal, plan.json is authoritative): ${message}`);try{emit("plan_md_write_failed",{directory,error:message,timestamp:new Date().toISOString()})}catch{}}try{let markerPath=path72.join(swarmDir,".plan-write-marker"),tasksCount=projectedPlan.phases.reduce((sum,phase)=>sum+phase.tasks.length,0),marker=JSON.stringify({source:"plan_manager",timestamp:new Date().toISOString(),phases_count:projectedPlan.phases.length,tasks_count:tasksCount,in_progress:!1});await commitAsyncPreparedFile(markerPath,marker,options?.preCommitCheck,"plan-write-marker")}catch(error93){if(error93 instanceof PlanRecoverySupersededError)throw error93}if(currentPlan)try{let oldIdentityHash=derivePlanIdentityHash(currentPlan),newIdentityHash=derivePlanIdentityHash(projectedPlan);if(oldIdentityHash===newIdentityHash){let oldStatuses=new Map;for(let phase of currentPlan.phases)for(let task of phase.tasks)oldStatuses.set(task.id,task.status);let newStatuses=new Map;for(let phase of projectedPlan.phases)for(let task of phase.tasks)newStatuses.set(task.id,task.status);for(let[taskId,oldStatus]of oldStatuses){let newStatus=newStatuses.get(taskId);if(oldStatus==="completed"&&newStatus!=="completed")options?.preCommitCheck?.(),advanceTaskCheckpointReceiptGeneration(directory,oldIdentityHash,taskId)}for(let[taskId,newStatus]of newStatuses)if(newStatus==="completed"&&oldStatuses.get(taskId)!=="completed")options?.preCommitCheck?.(),repairTaskCheckpointReceiptForCompletion(directory,newIdentityHash,taskId)}}catch(receiptError){if(receiptError instanceof PlanRecoverySupersededError)throw receiptError;warn(`[savePlan] task checkpoint receipt lifecycle sync failed (plan remains authoritative): ${receiptError instanceof Error?receiptError.message:String(receiptError)}`)}if(mdWriteError!==void 0)return{durability:"incomplete",degraded_surfaces:["plan.md"],md_write_error:mdWriteError};return{durability:"complete",degraded_surfaces:[]}}async function commitAsyncPreparedFile(targetPath,content,preCommitCheck,tempLabel="atomic"){let tempPath=`${targetPath}.${tempLabel}.${Date.now()}.${Math.floor(Math.random()*1e9)}`;try{await bunWrite(tempPath,content),preCommitCheck?.(),renameSync13(tempPath,targetPath)}catch(error93){try{unlinkSync13(tempPath)}catch{}throw error93}}async function writeRebuildPlanMarkdown(tempPath,content){await bunWrite(tempPath,content)}async function rebuildPlan(directory,plan,options){assertProjectRoot(directory);let targetPlan=plan??await replayFromLedger(directory,{preCommitCheck:options?.preCommitCheck});if(!targetPlan)return null;options?.preCommitCheck?.();let swarmDir=path72.join(directory,".swarm"),planPath=path72.join(swarmDir,"plan.json"),mdPath=path72.join(swarmDir,"plan.md");mkdirSync25(swarmDir,{recursive:!0});let tempPlanPath=path72.join(swarmDir,`plan.json.rebuild.${Date.now()}.${Math.floor(Math.random()*1e9)}`);try{{let fd=openSync11(tempPlanPath,"w");try{writeFileSync15(fd,JSON.stringify(targetPlan,null,2),"utf8"),fsyncSync3(fd)}finally{closeSync11(fd)}}options?.preCommitCheck?.(),renameSync13(tempPlanPath,planPath),invalidateCachedArtifact(planPath)}finally{try{unlinkSync13(tempPlanPath)}catch{}}try{let markerPath=path72.join(swarmDir,".plan-write-marker"),inProgressMarker=JSON.stringify({source:"plan_manager",timestamp:new Date().toISOString(),phases_count:targetPlan.phases.length,tasks_count:targetPlan.phases.reduce((sum,phase)=>sum+phase.tasks.length,0),in_progress:!0});await commitAsyncPreparedFile(markerPath,inProgressMarker,options?.preCommitCheck,"rebuild")}catch(error93){if(error93 instanceof PlanRecoverySupersededError)throw error93}let markdownWriteFailed=!1,markdownWriteError,markerSupersededError;try{let contentHash=computePlanContentHash(targetPlan),markdown=derivePlanMarkdown(targetPlan),markdownWithHash=`<!-- PLAN_HASH: ${contentHash} -->
|
|
887
887
|
${markdown}`,tempMdPath=path72.join(swarmDir,`plan.md.rebuild.${Date.now()}.${Math.floor(Math.random()*1e9)}`);try{await _internals67.writeRebuildPlanMarkdown(tempMdPath,markdownWithHash),options?.preCommitCheck?.(),renameSync13(tempMdPath,mdPath),invalidateCachedArtifact(mdPath)}finally{try{unlinkSync13(tempMdPath)}catch{}}}catch(error93){markdownWriteFailed=!0,markdownWriteError=error93}finally{try{let markerPath=path72.join(swarmDir,".plan-write-marker"),tasksCount=targetPlan.phases.reduce((sum,phase)=>sum+phase.tasks.length,0),marker=JSON.stringify({source:"plan_manager",timestamp:new Date().toISOString(),phases_count:targetPlan.phases.length,tasks_count:tasksCount,in_progress:!1});await commitAsyncPreparedFile(markerPath,marker,options?.preCommitCheck,"rebuild")}catch(error93){if(error93 instanceof PlanRecoverySupersededError)markerSupersededError=error93}}if(markerSupersededError)throw markerSupersededError;if(markdownWriteFailed){if(markdownWriteError instanceof PlanRecoverySupersededError)throw markdownWriteError;let message=markdownWriteError instanceof Error?markdownWriteError.message:String(markdownWriteError);warn(`[rebuildPlan] plan.md projection write failed (non-fatal; plan.json is authoritative): ${message}`.slice(0,512))}try{options?.preCommitCheck?.();let planId=derivePlanId(targetPlan),planHashAfter=computePlanLedgerHash(targetPlan);await appendLedgerEvent(directory,{event_type:"plan_rebuilt",source:"rebuildPlan",plan_id:planId,payload:{reason:options?.reason??"ledger_replay_recovery",phases_count:targetPlan.phases.length,tasks_count:targetPlan.phases.reduce((sum,p)=>sum+p.tasks.length,0)}},{planHashAfter,preCommitCheck:options?.preCommitCheck})}catch(error93){if(error93 instanceof PlanRecoverySupersededError)throw error93}return targetPlan}async function closePlanTerminalState(directory,plan,options){assertProjectRoot(directory);let planId=derivePlanId(plan),validated=PlanSchema.parse(plan);normalizeCurrentPhaseInPlace(validated);let hashAfter=computePlanLedgerHash(validated);for(let taskId of options.closedTaskIds){let taskPhaseId;for(let phase of validated.phases)if(phase.tasks.some((t)=>t.id===taskId)){taskPhaseId=phase.id;break}let fromStatus=options.originalStatuses?.get(taskId)??"in_progress";await appendLedgerEvent(directory,{plan_id:planId,event_type:"task_status_changed",task_id:taskId,phase_id:taskPhaseId,from_status:fromStatus,to_status:"closed",source:"close_terminal"},{planHashAfter:hashAfter})}for(let phaseId of options.closedPhaseIds)await appendLedgerEvent(directory,{plan_id:planId,event_type:"phase_completed",phase_id:phaseId,source:"close_terminal"},{planHashAfter:hashAfter});await takeSnapshotEvent(directory,validated,{planHashAfter:hashAfter,source:"close_terminal"});let swarmDir=path72.join(directory,".swarm"),planPath=path72.join(swarmDir,"plan.json"),tempPlanPath=path72.join(swarmDir,`plan.json.close.${Date.now()}.${Math.floor(Math.random()*1e9)}`);await bunWrite(tempPlanPath,JSON.stringify(validated,null,2)),renameSync13(tempPlanPath,planPath),invalidateCachedArtifact(planPath);try{let markerPath=path72.join(swarmDir,".plan-write-marker"),inProgressMarker=JSON.stringify({source:"plan_manager_close",timestamp:new Date().toISOString(),phases_count:validated.phases.length,tasks_count:validated.phases.reduce((sum,phase)=>sum+phase.tasks.length,0),in_progress:!0});await bunWrite(markerPath,inProgressMarker)}catch{}try{let mdPath=path72.join(swarmDir,"plan.md"),contentHash=computePlanContentHash(validated),markdown=derivePlanMarkdown(validated),markdownWithHash=`<!-- PLAN_HASH: ${contentHash} -->
|
|
@@ -997,7 +997,7 @@ ${transcriptTail}`].join(`
|
|
|
997
997
|
`;if(Buffer.byteLength(line,"utf-8")>TRAJECTORY_LIMITS.maxLineBytes){warn(`[trajectory-store] Skipped oversize trajectory entry (${Buffer.byteLength(line,"utf-8")} B > ${TRAJECTORY_LIMITS.maxLineBytes} B)`);return}let trajectoryPath=getTrajectoryPath(sessionId,directory);await fs52.mkdir(path85.dirname(trajectoryPath),{recursive:!0});let lock=null;try{lock=await acquireTrajectoryLock(getLockPath(trajectoryPath));let tail=await readTailBytes(trajectoryPath,1),needsReframe=tail!==null&&tail.totalBytes>0&&tail.content!==`
|
|
998
998
|
`;if(tail!==null&&tail.totalBytes>sessionMaxBytesFor(maxLines))await compactTrajectoryFile(trajectoryPath,maxLines,directory);await fs52.appendFile(trajectoryPath,needsReframe?`
|
|
999
999
|
${line}`:line,"utf-8");let sinceCheck=(appendCheckCounters.get(key)??0)+1;if(sinceCheck>=TRAJECTORY_LIMITS.checkIntervalAppends){setAppendCheckCounter(key,0);let window2=await readTailBytes(trajectoryPath,TRAJECTORY_LIMITS.readMaxBytes);if(window2!==null&&window2.totalBytes>0){let windowParsed=parseWindow(window2.content,window2.offset>0);if(window2.offset>0||windowParsed.entries.length>maxLines)await compactTrajectoryFile(trajectoryPath,maxLines,directory)}}else setAppendCheckCounter(key,sinceCheck)}finally{if(lock)await lock.release()}let cached3=_inMemoryTrajectoryCache.get(key)??[];setTrajectoryCache(key,[...cached3,entry],maxLines)})}catch(err){let busy=err instanceof Error&&err.message.includes("lock busy");if(log(`[trajectory-store] Failed to append trajectory entry: ${err}`),busy){skippedLockAppends+=1;let now=Date.now();if(now-lastAppendSkipEventAtMs>=TRAJECTORY_LIMITS.appendSkipEventCooldownMs)lastAppendSkipEventAtMs=now,emitTrajectoryHealth(directory,{trigger:"append_skip",retained_count:0,dropped_count:0,corrupt_count:0,bytes:0,limit_bytes:0}),skippedLockAppends=0}}}async function readTrajectoryWithCoverage(sessionId,directory,maxLines=1000){try{let trajectoryPath=getTrajectoryPath(sessionId,directory),tail=await readTailBytes(trajectoryPath,TRAJECTORY_LIMITS.readMaxBytes),checkpoint2=await readCheckpointByPath(getMetaPath2(trajectoryPath));if(tail===null)return{entries:[],coverage:"empty",droppedByCompaction:checkpoint2?.droppedEntries??0,skippedMalformed:0};let parsed=parseWindow(tail.content,tail.offset>0),key=compositeSessionKey(directory,sessionId);setTrajectoryCache(key,parsed.entries,maxLines);let dropped=checkpoint2?.droppedEntries??0,droppedBytes=checkpoint2?.droppedBytes??0,coverage=parsed.entries.length===0&&tail.totalBytes===0?"empty":tail.offset>0||dropped>0||droppedBytes>0?"truncated":"complete";return{entries:parsed.entries,coverage,droppedByCompaction:dropped,skippedMalformed:parsed.skippedMalformed+parsed.skippedOversize}}catch(err){if(err.code==="ENOENT")return{entries:[],coverage:"empty",droppedByCompaction:0,skippedMalformed:0};return log(`[trajectory-store] Failed to read trajectory: ${err}`),{entries:[],coverage:"empty",droppedByCompaction:0,skippedMalformed:0}}}async function readTrajectory(sessionId,directory,maxLines){return(await readTrajectoryWithCoverage(sessionId,directory,maxLines)).entries}async function getCurrentStep(sessionId,directory){try{let trajectoryPath=getTrajectoryPath(sessionId,directory),maxStep=(await readCheckpointByPath(getMetaPath2(trajectoryPath)))?.highestStep??0,tail=await readTailBytes(trajectoryPath,TRAJECTORY_LIMITS.stepReadMaxBytes);if(tail!==null&&tail.totalBytes>0){let parsed=parseWindow(tail.content,tail.offset>0);if(parsed.maxStep>maxStep)maxStep=parsed.maxStep}return maxStep}catch(err){if(err.code==="ENOENT")return 0;return log(`[trajectory-store] Failed to get current step: ${err}`),0}}function scheduleTrajectoryCleanup(directory){let now=Date.now();if(now-lastCleanupScheduledAtMs<TRAJECTORY_LIMITS.cleanupDebounceMs)return;lastCleanupScheduledAtMs=now,cleanupOldTrajectoryFiles(directory).catch(()=>{})}async function cleanupOldTrajectoryFiles(directory,maxAgeDays=TRAJECTORY_LIMITS.defaultMaxAgeDays){let cutoffMs=maxAgeDays*24*60*60*1000,now=Date.now(),removed=0,retained=0;for(let subdir of["trajectories","replays"]){if(removed>=TRAJECTORY_LIMITS.maxDeletionsPerRun)break;try{let dirPath=trajectorySwarmPath(directory,subdir),entries=await fs52.readdir(dirPath,{withFileTypes:!0}),candidates=[];for(let entry of entries){if(!entry.isFile())continue;if(entry.name.endsWith(".lock"))continue;let filePath=path85.join(dirPath,entry.name);try{let stat10=await fs52.stat(filePath);candidates.push({name:entry.name,filePath,effectiveMtimeMs:Math.min(stat10.mtimeMs,now)})}catch{}}let deleted=new Set,removeCandidate2=async(candidate)=>{if(await fs52.unlink(candidate.filePath),deleted.add(candidate.name),removed+=1,candidate.name.endsWith(".jsonl")){let metaSibling=`${candidate.filePath}.meta.json`;await fs52.unlink(metaSibling).catch(()=>{})}};for(let candidate of candidates){if(removed>=TRAJECTORY_LIMITS.maxDeletionsPerRun)break;if(now-candidate.effectiveMtimeMs>cutoffMs)await removeCandidate2(candidate).catch(()=>{})}let remainingJsonl=candidates.filter((c)=>!deleted.has(c.name)&&c.name.endsWith(".jsonl")).sort((a,b)=>b.effectiveMtimeMs-a.effectiveMtimeMs);retained+=remainingJsonl.length;while(remainingJsonl.length>TRAJECTORY_LIMITS.maxFilesPerDir&&removed<TRAJECTORY_LIMITS.maxDeletionsPerRun){let oldest=remainingJsonl.pop();if(oldest===void 0)break;await removeCandidate2(oldest).catch(()=>{}),retained-=1}}catch{}}if(removed>0)emitTrajectoryHealth(directory,{trigger:"cleanup",retained_count:retained,dropped_count:removed,corrupt_count:0,bytes:0,limit_bytes:TRAJECTORY_LIMITS.maxFilesPerDir}),skippedLockAppends=0}var MAX_TRACKED_TRAJECTORY_SESSIONS=500,TRAJECTORY_LIMITS,_internals79,skippedLockAppends=0,lastAppendSkipEventAtMs=0,_inMemoryTrajectoryCache,appendChains2,appendCheckCounters,lastCleanupScheduledAtMs=0;var init_trajectory_store=__esm(()=>{init_learning_health();init_utils2();init_telemetry();init_atomic_write();init_canonical_root();init_logger();TRAJECTORY_LIMITS={checkIntervalAppends:25,readMaxBytes:1048576,stepReadMaxBytes:65536,compactMaxBytes:1048576,maxLineBytes:65536,estimatedLineBytes:512,minSessionMaxBytes:65536,lockRetries:20,lockRetryDelayMs:5,lockStaleMs:300000,maxFilesPerDir:200,maxDeletionsPerRun:256,defaultMaxAgeDays:7,cleanupDebounceMs:600000,appendSkipEventCooldownMs:60000};_internals79={telemetry};_inMemoryTrajectoryCache=new Map;appendChains2=new Map,appendCheckCounters=new Map});function resetPrmSessionState(session,sessionId){if(session.prmEscalationTracker=void 0,session.prmInitialized=!1,session.prmPatternCounts=new Map,session.prmEscalationLevel=0,session.prmLastPatternDetected=null,session.prmHardStopPending=!1,session.prmHardStopInjectPending=!1,session.prmTrajectoryStep=0,session.prmInjectedAdvisoryKeys=new Set,session.prmStruckEpisodes=new Map,session.prmLadderCounts=new Map,session.prmEpisodes=new Map,session.prmEpisodeGeneration=0,session.replayArtifactPath=null,sessionId)_internals80.clearTrajectoryCache(sessionId)}function resolvePrmPatternPersistenceOptions(learning){return{enabled:learning.prm_persistence.enabled,min_support:learning.prm_persistence.min_support,cooldown_ms:learning.prm_persistence.cooldown_ms,admission_enabled:learning.realtime_admission.enabled,max_queue_size:learning.realtime_admission.max_queue_size}}function createPrmHook(config3,directory,patternPersistence){async function toolAfter(context){if(!config3.enabled)return;let{sessionID}=context,session=_internals80.getAgentSession(sessionID);if(!session||!session.delegationActive)return;try{let sessionPrmState=session;if(!sessionPrmState.prmInitialized)sessionPrmState.prmInitialized=!0,_internals80.scheduleTrajectoryCleanup(directory);let cachedTrajectory=_internals80.getInMemoryTrajectory(sessionID,directory),trajectory=cachedTrajectory;if(cachedTrajectory.length===0){let coldRead=await _internals80.readTrajectoryWithCoverage(sessionID,directory,config3.max_trajectory_lines);if(trajectory=coldRead.entries,coldRead.coverage==="truncated")log(`[prm] session ${sessionID} trajectory window is partial: ${coldRead.droppedByCompaction} older entries were dropped by compaction (pattern detection runs on the newest retained window)`)}let detectionResult=_internals80.detectPatterns(trajectory,config3,session.prmTrajectoryStep);if(detectionResult.matches.length===0)return;session.prmStruckEpisodes??=new Map;let struckEpisodes=session.prmStruckEpisodes,strikeable=[],claimedThisTick=new Set;for(let match of[...detectionResult.matches].sort((a,b)=>a.stepRange[0]-b.stepRange[0])){if(claimedThisTick.has(match.pattern))continue;let episodeKey=`${match.pattern}|${match.stepRange[0]}`,struckAtCount=struckEpisodes.get(episodeKey);if(struckAtCount!==void 0){let threshold=resolvePatternThreshold(config3,match.pattern);if(match.occurrenceCount<struckAtCount+threshold)continue}claimedThisTick.add(match.pattern),strikeable.push(match)}if(strikeable.length===0){if(trajectory.length>0)session.prmTrajectoryStep=trajectory[trajectory.length-1].step;return}for(let match of strikeable){let episodeKey=`${match.pattern}|${match.stepRange[0]}`;struckEpisodes.delete(episodeKey),struckEpisodes.set(episodeKey,match.occurrenceCount)}while(struckEpisodes.size>MAX_TRACKED_EPISODES){let oldest=struckEpisodes.keys().next().value;if(oldest===void 0)break;struckEpisodes.delete(oldest)}if(patternPersistence?.enabled)for(let match of strikeable){let observation=_internals80.recordPatternObservation(sessionID,match,{minSupport:patternPersistence.min_support,cooldownMs:patternPersistence.cooldown_ms});if(observation.persistable&&observation.candidate){try{await _internals80.appendInsightCandidates(directory,[observation.candidate])}catch(err){warn(`[prm] insight-candidate append failed (non-fatal): ${err instanceof Error?err.message:String(err)}`)}if(patternPersistence.admission_enabled)_internals80.enqueueCandidate(sessionID,observation.candidate,{maxQueueSize:patternPersistence.max_queue_size})}}let escalationTracker=sessionPrmState.prmEscalationTracker;if(!sessionPrmState.replayArtifactPath)sessionPrmState.replayArtifactPath=await _internals80.startReplayRecording(sessionID,directory);let artifactPath=sessionPrmState.replayArtifactPath;if(!escalationTracker){let initialState=session.prmLastPatternDetected?{patternCounts:new Map(session.prmLadderCounts??[]),escalationLevel:session.prmEscalationLevel,lastPatternDetected:session.prmLastPatternDetected,hardStopPending:session.prmHardStopPending,episodes:new Map(session.prmEpisodes??[]),generation:session.prmEpisodeGeneration??0}:void 0;escalationTracker=new EscalationTracker(sessionID,initialState),sessionPrmState.prmEscalationTracker=escalationTracker}let previousEscalationLevel=session.prmEscalationLevel,tickHardStop=!1;for(let match of strikeable){let correction=_internals80.generateCourseCorrection(match,trajectory),formattedCorrection=_internals80.formatCourseCorrectionForInjection(correction),escalationLevel=0,hardStopPending=!1,hardStopTerminal=!1;if(config3.escalation_enabled!==!1){let escalationResult=escalationTracker.recordDetection(match);escalationLevel=escalationResult.level,hardStopPending=escalationResult.hardStop,hardStopTerminal=escalationResult.terminal}let prmDedupeKey=`prm:${resolveLadderKey(match)}:${escalationLevel}${hardStopTerminal?":terminal":""}:g${escalationTracker.getGeneration()}`;if(!session.prmInjectedAdvisoryKeys?.has(prmDedupeKey))pushAdvisory(session,`[${prmDedupeKey}] ${formattedCorrection}`,{dedupeKey:prmDedupeKey}),session.prmInjectedAdvisoryKeys??=new Set,session.prmInjectedAdvisoryKeys.add(prmDedupeKey);if(session.prmPatternCounts.set(match.pattern,(session.prmPatternCounts.get(match.pattern)??0)+1),session.prmLadderCounts=escalationTracker.getLadderCounts(),session.prmEpisodes=escalationTracker.getEpisodes(),session.prmEpisodeGeneration=escalationTracker.getGeneration(),session.prmEscalationLevel=escalationLevel,session.prmLastPatternDetected=match,tickHardStop=tickHardStop||hardStopPending,session.prmHardStopPending=tickHardStop,tickHardStop)session.prmHardStopInjectPending=!0;if(_internals80.telemetry.prmPatternDetected(sessionID,match.pattern,match.severity,match.category,match.stepRange),_internals80.telemetry.prmCourseCorrectionInjected(sessionID,match.pattern,escalationLevel),artifactPath)await _internals80.recordReplayEntry(artifactPath,sessionID,{type:"pattern_detected",data:{pattern:match.pattern,severity:match.severity,category:match.category,stepRange:match.stepRange,description:match.description,affectedAgents:match.affectedAgents,affectedTargets:match.affectedTargets,occurrenceCount:match.occurrenceCount}});if(artifactPath)await _internals80.recordReplayEntry(artifactPath,sessionID,{type:"course_correction",data:{pattern:correction.pattern,alert:correction.alert,category:correction.category,guidance:correction.guidance,action:correction.action,stepRange:correction.stepRange,escalationLevel}})}if(artifactPath&&session.prmEscalationLevel>previousEscalationLevel)await _internals80.recordReplayEntry(artifactPath,sessionID,{type:"escalation",data:{previousLevel:previousEscalationLevel,newLevel:session.prmEscalationLevel,hardStopPending:session.prmHardStopPending}});if(artifactPath&&session.prmHardStopPending&&previousEscalationLevel<3)await _internals80.recordReplayEntry(artifactPath,sessionID,{type:"hard_stop",data:{escalationLevel:session.prmEscalationLevel,triggeredAt:new Date().toISOString()}});if(trajectory.length>0)session.prmTrajectoryStep=trajectory[trajectory.length-1].step}catch(err){log(`[prm] toolAfter error for session ${sessionID}: ${err}`)}}return{toolAfter}}var _internals80,MAX_TRACKED_EPISODES=256;var init_prm=__esm(()=>{init_course_correction();init_escalation();init_pattern_detector();init_micro_reflector();init_candidate_queue();init_prm_pattern_support();init_state();init_telemetry();init_logger();init_course_correction();init_escalation();init_pattern_detector();init_replay();init_trajectory_store();_internals80={getAgentSession,readTrajectoryWithCoverage,getInMemoryTrajectory,detectPatterns,generateCourseCorrection,formatCourseCorrectionForInjection,scheduleTrajectoryCleanup,clearTrajectoryCache,recordReplayEntry,startReplayRecording,telemetry,recordPatternObservation,enqueueCandidate,appendInsightCandidates}});import{createHash as createHash39,createHmac,randomBytes as randomBytes6,timingSafeEqual}from"node:crypto";import*as fs53 from"node:fs";import*as fsp4 from"node:fs/promises";import*as path86 from"node:path";function normalizedIdentity(value,label){let normalized=value.trim();if(!normalized||normalized.length>256)throw Error(`ROUTE_RECEIPT_INVALID_IDENTITY: ${label}`);return normalized}function uniqueIdentities(values,label){let result=values.map((value)=>normalizedIdentity(value,label));if(new Set(result).size!==result.length)throw Error(`ROUTE_RECEIPT_DUPLICATE: ${label}`);return[...result]}function slotsFor(role,identities,provided,taskId){let slots=provided?uniqueIdentities(provided,`${role} slots`):identities.map((_,index)=>`${taskId}:${role}:${index+1}`);if(slots.length!==identities.length)throw Error(`ROUTE_RECEIPT_SLOT_COUNT_MISMATCH: ${role}`);return slots}function buildReviewRouteReceipt(input){let sessionId=normalizedIdentity(input.sessionId,"sessionId"),taskId=normalizedIdentity(input.taskId,"taskId"),reviewers=uniqueIdentities(input.requiredReviewers,"reviewers"),testEngineers=uniqueIdentities(input.requiredTestEngineers,"test_engineers");return ReviewRouteReceiptSchema.parse({kind:"review_route_receipt",version:REVIEW_ROUTE_RECEIPT_VERSION,sessionId,taskId,complexity:input.complexity,semanticRisk:input.semanticRisk,required:{reviewers:reviewers.length,testEngineers:testEngineers.length},identities:{reviewers,testEngineers},slots:{reviewers:slotsFor("reviewer",reviewers,input.reviewerSlots,taskId),testEngineers:slotsFor("test_engineer",testEngineers,input.testEngineerSlots,taskId)},createdAt:input.createdAt??new Date().toISOString()})}function buildReviewRouteRouterError(input){return ReviewRouteRouterErrorReceiptSchema.parse({kind:"review_route_router_error",version:REVIEW_ROUTE_RECEIPT_VERSION,code:input.code,failOpen:!0,...input.sessionId?{sessionId:input.sessionId}:{},...input.taskId?{taskId:input.taskId}:{},...input.detail?{detail:input.detail.slice(0,512)}:{},createdAt:input.createdAt??new Date().toISOString()})}function buildReviewRoutePending(input){return ReviewRoutePendingReceiptSchema.parse({kind:"review_route_pending",version:REVIEW_ROUTE_RECEIPT_VERSION,sessionId:input.sessionId,taskId:input.taskId,createdAt:input.createdAt??new Date().toISOString()})}function routeReceiptRelativePath(sessionId,taskId){let normalizedSessionId=normalizedIdentity(sessionId,"sessionId"),normalizedTaskId=normalizedIdentity(taskId,"taskId"),encodeIdentity=(normalized)=>{let encoded=Buffer.from(normalized,"utf8").toString("base64url").replace(/-/g,"~");return encoded.length<=180?encoded:`sha256_${createHash39("sha256").update(normalized,"utf8").digest("hex")}`},safeSession=encodeIdentity(normalizedSessionId),safeTask=encodeIdentity(normalizedTaskId),basename15=`${safeSession}--${safeTask}.json`,boundedBasename=Buffer.byteLength(basename15,"utf8")<=255?basename15:`sha256_${createHash39("sha256").update(JSON.stringify([normalizedSessionId,normalizedTaskId]),"utf8").digest("hex")}.json`;return path86.join("pr-review","route-receipts",boundedBasename)}function routeReceiptPath(directory,sessionId,taskId){return validateSwarmPath(directory,routeReceiptRelativePath(sessionId,taskId))}async function ensureSafeParent(directory,filePath){assertProjectRoot(directory,void 0,"review route receipt");let swarmRoot=path86.resolve(directory,".swarm"),parent=path86.dirname(filePath),relative21=path86.relative(swarmRoot,parent);if(relative21===".."||relative21.startsWith(`..${path86.sep}`)||path86.isAbsolute(relative21))throw Error("ROUTE_RECEIPT_PATH_ESCAPE: route receipt is outside .swarm");await fsp4.mkdir(parent,{recursive:!0});for(let candidate of[swarmRoot,path86.join(swarmRoot,"pr-review"),parent]){let stat10=await fsp4.lstat(candidate);if(!stat10.isDirectory()||stat10.isSymbolicLink())throw Error("ROUTE_RECEIPT_PATH_UNSAFE: receipt parent is not a real directory")}}function routeReceiptSecretPath(projectRoot){let hiveDir=path86.resolve(resolveHiveDataDir());if(projectRoot){let root=path86.resolve(projectRoot),relative21=path86.relative(root,hiveDir);if(relative21===""||!path86.isAbsolute(relative21)&&!relative21.startsWith(`..${path86.sep}`))throw Error("ROUTE_RECEIPT_SECRET_UNSAFE_PATH: app-data key path is inside the project root")}return path86.join(hiveDir,ROUTE_RECEIPT_SECRET_FILE)}function parseRouteReceiptSecret(raw){let value=raw.trim();return/^[0-9a-f]{64}$/.test(value)?Buffer.from(value,"hex"):null}async function readRouteReceiptSecret(projectRoot){let secretPath=routeReceiptSecretPath(projectRoot);try{let stat10=await fsp4.lstat(secretPath);if(stat10.isSymbolicLink()||!stat10.isFile())throw Error("ROUTE_RECEIPT_SECRET_INVALID");let secret=parseRouteReceiptSecret(await fsp4.readFile(secretPath,"utf8"));if(!secret)throw Error("ROUTE_RECEIPT_SECRET_INVALID");return secret}catch(error93){if(error93.code!=="ENOENT")throw error93}await fsp4.mkdir(path86.dirname(secretPath),{recursive:!0});let generated=randomBytes6(32);try{await fsp4.writeFile(secretPath,generated.toString("hex"),{encoding:"utf8",flag:"wx",mode:384})}catch(error93){if(error93.code!=="EEXIST")throw error93;return readRouteReceiptSecret(projectRoot)}try{await fsp4.chmod(secretPath,384)}catch{}return generated}function readRouteReceiptSecretSync(projectRoot){try{let secretPath=routeReceiptSecretPath(projectRoot),stat10=fs53.lstatSync(secretPath);if(stat10.isSymbolicLink()||!stat10.isFile())return null;return parseRouteReceiptSecret(fs53.readFileSync(secretPath,"utf8"))}catch(error93){if(error93 instanceof Error&&error93.message.startsWith("ROUTE_RECEIPT_SECRET_UNSAFE_PATH:"))throw error93;return null}}function canonicalRouteReceiptJson(value){if(value===null||typeof value!=="object")return JSON.stringify(value);if(Array.isArray(value))return`[${value.map((entry)=>canonicalRouteReceiptJson(entry)).join(",")}]`;return`{${Object.entries(value).filter(([,entry])=>entry!==void 0).sort(([left],[right])=>left.localeCompare(right)).map(([key,entry])=>`${JSON.stringify(key)}:${canonicalRouteReceiptJson(entry)}`).join(",")}}`}function routeReceiptMacPayload(receipt){let{mac:_mac2,...payload}=receipt;return`${ROUTE_RECEIPT_MAC_CONTEXT}${canonicalRouteReceiptJson(payload)}`}function computeRouteReceiptMac(receipt,secret){return createHmac("sha256",secret).update(routeReceiptMacPayload(receipt),"utf8").digest("hex")}function hasValidRouteReceiptMac(receipt,secret){if(!secret||!receipt.mac||!RouteReceiptMacSchema.safeParse(receipt.mac).success)return!1;let expected=Buffer.from(computeRouteReceiptMac(receipt,secret),"hex"),supplied=Buffer.from(receipt.mac,"hex");return supplied.length===expected.length&&timingSafeEqual(supplied,expected)}function authenticatePersistedRouteReceipt(receipt,secret){if(hasValidRouteReceiptMac(receipt,secret))return receipt;throw Error("ROUTE_RECEIPT_AUTH_INVALID: receipt MAC is missing or invalid")}async function persistReviewRouteReceipt(input){let parsed=input.receipt.kind==="review_route_receipt"?ReviewRouteReceiptSchema.parse(input.receipt):input.receipt.kind==="review_route_router_error"?ReviewRouteRouterErrorReceiptSchema.parse(input.receipt):ReviewRoutePendingReceiptSchema.parse(input.receipt),sessionId=parsed.kind==="review_route_receipt"?parsed.sessionId:parsed.sessionId??"router",taskId=parsed.kind==="review_route_receipt"?parsed.taskId:parsed.taskId??"unknown",filePath=routeReceiptPath(input.projectRoot,sessionId,taskId);await ensureSafeParent(input.projectRoot,filePath);let authenticated={...parsed,mac:computeRouteReceiptMac(parsed,await readRouteReceiptSecret(input.projectRoot))},encoded=JSON.stringify(authenticated,null,2);if(Buffer.byteLength(encoded,"utf8")>MAX_ROUTE_RECEIPT_BYTES)throw Error("ROUTE_RECEIPT_OVERSIZED: receipt exceeds size bound");return await atomicWriteFile(filePath,`${encoded}
|
|
1000
|
-
`),{persisted:!0,path:filePath}}function readReviewRouteReceiptSync(input){let filePath=routeReceiptPath(input.projectRoot,input.sessionId,input.taskId),stat10;try{stat10=fs53.lstatSync(filePath)}catch(error93){if(error93.code==="ENOENT")return null;throw error93}if(stat10.isSymbolicLink()||!stat10.isFile()||stat10.size>MAX_ROUTE_RECEIPT_BYTES)throw Error("ROUTE_RECEIPT_UNREADABLE: receipt is not a bounded regular file");let value;try{value=JSON.parse(fs53.readFileSync(filePath,"utf8"))}catch(error93){if(error93 instanceof SyntaxError)throw Error("ROUTE_RECEIPT_INVALID_JSON: receipt is not valid JSON");throw error93}let parsed=typeof value==="object"&&value!==null&&value.kind==="review_route_receipt"?ReviewRouteReceiptSchema.safeParse(value):value.kind==="review_route_router_error"?ReviewRouteRouterErrorReceiptSchema.safeParse(value):ReviewRoutePendingReceiptSchema.safeParse(value);if(!parsed.success)throw Error("ROUTE_RECEIPT_INVALID: receipt failed schema validation");let authenticated=authenticatePersistedRouteReceipt(parsed.data,readRouteReceiptSecretSync(input.projectRoot));if((authenticated.kind==="review_route_receipt"||authenticated.kind==="review_route_pending")&&(authenticated.sessionId!==input.sessionId||authenticated.taskId!==input.taskId))throw Error("ROUTE_RECEIPT_IDENTITY_MISMATCH: receipt path and payload differ");if(authenticated.kind==="review_route_router_error"&&authenticated.sessionId!==void 0&&authenticated.taskId!==void 0&&(authenticated.sessionId!==input.sessionId||authenticated.taskId!==input.taskId))throw Error("ROUTE_RECEIPT_IDENTITY_MISMATCH: receipt path and payload differ");return authenticated}function parseRouteReceipt(value){if(!value||typeof value!=="object")return null;let kind=value.kind,parsed=kind==="review_route_receipt"?ReviewRouteReceiptSchema.safeParse(value):kind==="review_route_router_error"?ReviewRouteRouterErrorReceiptSchema.safeParse(value):ReviewRoutePendingReceiptSchema.safeParse(value);return parsed.success?parsed.data:null}function fail(reason){return{canAdvance:!1,mode:"enforced",reason}}function enforceReviewRouteReceipt(input){if(!input.enforcementEnabled)return{canAdvance:!0,mode:"disabled"};let route=parseRouteReceipt(input.routeReceipt);if(!route)return fail("ROUTE_RECEIPT_MISSING");if(route.kind==="review_route_router_error"){if(input.sessionId&&(!route.sessionId||!route.taskId||route.sessionId!==input.sessionId||route.taskId!==input.taskId))return fail("ROUTE_RECEIPT_IDENTITY_MISMATCH");return{canAdvance:!0,mode:"fail_open",routerFailure:route.code}}if(route.kind==="review_route_pending")return fail("ROUTE_RECEIPT_PENDING");if(input.sessionId&&route.sessionId!==input.sessionId||input.taskId&&route.taskId!==input.taskId)return fail("ROUTE_RECEIPT_IDENTITY_MISMATCH");if(route.required.reviewers!==route.identities.reviewers.length||route.required.testEngineers!==route.identities.testEngineers.length)return fail("ROUTE_RECEIPT_COUNT_MISMATCH");let expected=new Map;for(let identity of route.identities.reviewers){if(expected.has(identity))return fail("ROUTE_RECEIPT_DUPLICATE");expected.set(identity,"reviewer")}for(let identity of route.identities.testEngineers){if(expected.has(identity))return fail("ROUTE_RECEIPT_DUPLICATE");expected.set(identity,"test_engineer")}if(input.requireEvidenceBindings&&input.requireCompleteEvidence===!1&&expected.size>0&&!input.expectedDispatch)return fail("ROUTE_RECEIPT_DISPATCH_REQUIRED");let seen=new Set,seenSlots=new Set;for(let evidence of input.receipts){if(input.requireEvidenceBindings&&(!evidence.sessionId||!evidence.taskId||!evidence.slotId||!evidence.callId||!evidence.childSessionId||typeof evidence.generation!=="number"))return fail("ROUTE_RECEIPT_BINDING_MISSING");let identity=evidence.identity.trim();if(!identity||identity.length>256)return fail("ROUTE_RECEIPT_INVALID_IDENTITY");let expectedRole=expected.get(identity);if(!expectedRole)return fail("ROUTE_RECEIPT_IDENTITY_UNLISTED");if(expectedRole!==evidence.role)return fail("ROUTE_RECEIPT_ROLE_MISMATCH");if(seen.has(identity))return fail("ROUTE_RECEIPT_DUPLICATE");if(evidence.sessionId&&evidence.sessionId!==route.sessionId)return fail("ROUTE_RECEIPT_SESSION_MISMATCH");if(evidence.taskId&&evidence.taskId!==route.taskId)return fail("ROUTE_RECEIPT_TASK_MISMATCH");if(evidence.slotId){if(seenSlots.has(evidence.slotId))return fail("ROUTE_RECEIPT_DUPLICATE");let slots=evidence.role==="reviewer"?route.slots?.reviewers:route.slots?.testEngineers;if(slots&&!slots.includes(evidence.slotId))return fail("ROUTE_RECEIPT_SLOT_UNLISTED");if(slots){let expectedIndex=evidence.role==="reviewer"?route.identities.reviewers.indexOf(identity):route.identities.testEngineers.indexOf(identity);if(expectedIndex<0||slots[expectedIndex]!==evidence.slotId)return fail("ROUTE_RECEIPT_SLOT_MISMATCH")}seenSlots.add(evidence.slotId)}seen.add(identity)}if(input.expectedDispatch){let expected2=input.expectedDispatch,matching=input.receipts.find((evidence)=>evidence.role===expected2.role&&evidence.identity===expected2.identity);if(!matching||matching.callId!==expected2.callId||matching.childSessionId!==expected2.childSessionId||matching.generation!==expected2.generation)return fail("ROUTE_RECEIPT_DISPATCH_MISMATCH")}if(input.requireCompleteEvidence!==!1&&seen.size!==expected.size)return fail("ROUTE_RECEIPT_INCOMPLETE");return{canAdvance:!0,mode:"enforced"}}function enforcePersistedReviewRouteReceipt(input){if(!input.enforcementEnabled)return{canAdvance:!0,mode:"disabled"};let route;try{route=readReviewRouteReceiptSync({projectRoot:input.projectRoot,sessionId:input.sessionId,taskId:input.taskId})}catch(error93){if(error93 instanceof Error&&error93.message.startsWith("ROUTE_RECEIPT_AUTH_INVALID:"))return fail("ROUTE_RECEIPT_AUTH_INVALID");throw error93}if(!route&&input.legacyUnrouted)return{canAdvance:!0,mode:"legacy_unrouted",reason:"legacy_unrouted: route receipt predates version-1 enforcement"};return enforceReviewRouteReceipt({enforcementEnabled:!0,routeReceipt:route,receipts:input.receipts,sessionId:input.sessionId,taskId:input.taskId,requireEvidenceBindings:input.requireEvidenceBindings,expectedDispatch:input.expectedDispatch,requireCompleteEvidence:input.requireCompleteEvidence})}var REVIEW_ROUTE_RECEIPT_VERSION=1,IdentitySchema,RouteReceiptMacSchema,ReviewRouteReceiptSchema,ReviewRouteRouterErrorReceiptSchema,ReviewRoutePendingReceiptSchema,MAX_ROUTE_RECEIPT_BYTES=65536,ROUTE_RECEIPT_SECRET_FILE="review-route-receipts.key",ROUTE_RECEIPT_MAC_CONTEXT="opencode-swarm/review-route-receipt/v1\x00";var init_routing_enforcement=__esm(()=>{init_zod();init_task_file();init_utils2();init_hive_paths();init_project_boundary();IdentitySchema=exports_external.string().trim().min(1).max(256),RouteReceiptMacSchema=exports_external.string().regex(/^[0-9a-f]{64}$/,"route receipt MAC must be a SHA-256 HMAC"),ReviewRouteReceiptSchema=exports_external.object({kind:exports_external.literal("review_route_receipt"),version:exports_external.literal(REVIEW_ROUTE_RECEIPT_VERSION),sessionId:IdentitySchema,taskId:IdentitySchema,complexity:exports_external.string().trim().min(1).max(80),semanticRisk:exports_external.string().trim().min(1).max(120),required:exports_external.object({reviewers:exports_external.number().int().nonnegative().max(16),testEngineers:exports_external.number().int().nonnegative().max(16)}),identities:exports_external.object({reviewers:exports_external.array(IdentitySchema).max(16),testEngineers:exports_external.array(IdentitySchema).max(16)}),slots:exports_external.object({reviewers:exports_external.array(IdentitySchema).max(16),testEngineers:exports_external.array(IdentitySchema).max(16)}).optional(),createdAt:exports_external.string().trim().min(1).max(80).optional(),mac:RouteReceiptMacSchema.optional()}).strict(),ReviewRouteRouterErrorReceiptSchema=exports_external.object({kind:exports_external.literal("review_route_router_error"),version:exports_external.literal(REVIEW_ROUTE_RECEIPT_VERSION),code:exports_external.enum(["NO_CHANGED_FILES","ROUTER_UNAVAILABLE","ROUTER_FAILED"]),failOpen:exports_external.literal(!0),sessionId:IdentitySchema.optional(),taskId:IdentitySchema.optional(),detail:exports_external.string().trim().max(512).optional(),createdAt:exports_external.string().trim().min(1).max(80).optional(),mac:RouteReceiptMacSchema.optional()}).strict(),ReviewRoutePendingReceiptSchema=exports_external.object({kind:exports_external.literal("review_route_pending"),version:exports_external.literal(REVIEW_ROUTE_RECEIPT_VERSION),sessionId:IdentitySchema,taskId:IdentitySchema,createdAt:exports_external.string().trim().min(1).max(80).optional(),mac:RouteReceiptMacSchema.optional()}).strict()});function candidateSummary(resolution){let shown=resolution.candidates.slice(0,4).map((candidate)=>`${candidate.bindingId.slice(0,8)}/${candidate.generationId.slice(0,8)}@r${candidate.revision}`),omitted=Math.max(0,resolution.totalCandidates-shown.length);return`[${shown.join(", ")}${omitted>0?`, ... (+${omitted} more)`:""}]`}function formatScopeResolutionDiagnostic(input){let task=sanitizeDiagnosticText(input.taskId??"unknown",128),session=sanitizeDiagnosticText(input.sessionId,128);if(input.resolution.status==="ambiguous")return`SCOPE_BINDING_AMBIGUOUS: ${input.resolution.totalCandidates} exact live generations match task ${task} and session ${session}; candidates ${candidateSummary(input.resolution)}. ACTION[architect]: call declare_scope with replace_existing=true for this task/workspace, then dispatch a new Task call.`;if(input.resolution.status==="expired"){let lastExpiry=Math.max(...input.resolution.candidates.map((candidate)=>candidate.expiresAt)),expiredAt=Number.isFinite(lastExpiry)?new Date(lastExpiry).toISOString():"unknown";return`SCOPE_BINDING_EXPIRED: the exact generation for task ${task} and session ${session} expired while idle; expiredAt=${expiredAt}; candidates ${candidateSummary(input.resolution)}. ACTION[architect]: call declare_scope with replace_existing=true for this task/workspace, then dispatch a new Task call.`}if(input.resolution.status==="overloaded")return"SCOPE_BINDING_STORE_OVERLOADED: the complete live binding set exceeds the safe admission budget. ACTION[architect]: complete or expire terminal tasks, then retry declare_scope.";return null}var init_scope_resolution_diagnostic=__esm(()=>{init_path_identity()});async function recoverPreparedTaskRepairWithPlanLock(directory,taskId,actor,currentPlan){let walPath=validateSwarmPath(directory,`task-repairs/${taskId}.json`),wal=await readWal(walPath,taskId);if(wal===null)return null;if(wal.state==="ABORTED")return null;if(wal.state==="COMMITTED")return await ensureAuditEvent(directory,wal),null;let task=currentPlan.phases.flatMap((phase)=>phase.tasks).find((candidate)=>candidate.id===taskId);if(!task)throw Error(`TASK_REPAIR_TASK_MISSING: ${taskId}`);if(task.status===wal.oldPlanStatus){if(await withTaskEvidenceTransaction(directory,taskId,actor,async(transaction)=>{let workflow=getTaskWorkflowSnapshot(transaction.read());if(workflow.state!==wal.oldWorkflowState||workflow.generation!==wal.oldGeneration)return!1;return await writeWal(walPath,{...wal,state:"ABORTED"}),!0}))return null}return repairTaskWorkflowUnderPlanLock({directory,taskId,actor:wal.actor,reason:wal.reason,transitionId:wal.transitionId,expectedState:wal.oldWorkflowState,expectedGeneration:wal.oldGeneration,currentPlanStatus:task.status,currentPlan,updatePlan:()=>updateTaskStatus(directory,taskId,"in_progress",{force:!0,planLockAlreadyHeld:!0})})}async function recoverPreparedTaskRepair(directory,taskId,actor){let walPath=validateSwarmPath(directory,`task-repairs/${taskId}.json`),observedWal=await readWal(walPath,taskId);if(observedWal===null||observedWal.state==="ABORTED")return null;if(observedWal.state==="COMMITTED")return await ensureAuditEvent(directory,observedWal),null;let lock=await tryAcquireLock(directory,"plan.json",actor,`recover-task-repair-${taskId}-${Date.now()}`);if(!lock.acquired)throw Error(`TASK_REPAIR_RECOVERY_LOCKED: ${lock.existing?.agent??"another agent"} owns plan.json`);try{let replay=await replayFromLedgerWithStatus(directory);if(replay.truncated)throw Error("TASK_REPAIR_LEDGER_TRUNCATED");let plan=replay.plan??await loadPlanJsonOnly(directory);if(!plan)throw Error("TASK_REPAIR_PLAN_MISSING");return await recoverPreparedTaskRepairWithPlanLock(directory,taskId,actor,plan)}finally{if(lock.lock._release)await lock.lock._release().catch(()=>{})}}async function recoverPreparedTaskRepairUnderPlanLock(directory,taskId,actor,currentPlan){return recoverPreparedTaskRepairWithPlanLock(directory,taskId,actor,currentPlan)}async function readWal(filePath,taskId){return readWorkflowWalFile("task-repair",filePath,taskId)}async function writeWal(filePath,wal){await writeWorkflowWalFile("task-repair",filePath,wal)}async function ensureAuditEvent(directory,wal){if(hasTaskRepairAuditEvent(directory,wal.taskId,wal.transitionId))return;try{appendCoreEventSync(directory,{type:"task_workflow_repaired",timestamp:new Date().toISOString(),taskId:wal.taskId,transitionId:wal.transitionId,reason:wal.reason,actor:wal.actor,oldPlanStatus:wal.oldPlanStatus,newPlanStatus:wal.newPlanStatus,oldWorkflowState:wal.oldWorkflowState,newWorkflowState:wal.newWorkflowState,generation:wal.generation},{dedupeOnAuthorityKey:!0})}catch(error93){if(error93 instanceof Error&&error93.message===CORE_EVENT_LOCKED)throw Error("TASK_REPAIR_AUDIT_LOCKED");throw error93}if(!hasTaskRepairAuditEvent(directory,wal.taskId,wal.transitionId))throw Error("TASK_REPAIR_AUDIT_UNVERIFIED")}function workflowMatchesCommittedRepair(evidence,wal){let snapshot=getTaskWorkflowSnapshot(evidence);return snapshot.state==="idle"&&snapshot.generation===wal.generation&&snapshot.lastTransitionId===wal.transitionId}async function repairTaskWorkflowUnderPlanLock(options){let walPath=validateSwarmPath(options.directory,`task-repairs/${options.taskId}.json`);return withTaskEvidenceTransaction(options.directory,options.taskId,options.actor,async(transaction)=>{await assertNoUnsettledCoderDispatch(options.directory,options.taskId);let evidence=transaction.read(),snapshot=getTaskWorkflowSnapshot(evidence),existingWal=await readWal(walPath,options.taskId);if(existingWal?.state==="ABORTED")existingWal=null;if(existingWal&&existingWal.transitionId!==options.transitionId){if(existingWal.state==="PREPARED")throw Error(`TASK_REPAIR_IN_PROGRESS: transition ${existingWal.transitionId} owns the repair for task ${options.taskId} (${walPath}, state PREPARED); requested transition ${options.transitionId}. Recover or abort the owning repair transition before retrying.`);existingWal=null}if(existingWal&&(existingWal.reason!==options.reason||existingWal.oldWorkflowState!==options.expectedState||existingWal.oldGeneration!==options.expectedGeneration))throw Error(`TASK_REPAIR_IDEMPOTENCY_CONFLICT: transition ${options.transitionId} was prepared with different reason or workflow CAS fields`);if(existingWal?.state==="COMMITTED"&&options.currentPlanStatus==="in_progress"&&workflowMatchesCommittedRepair(evidence,existingWal))return await ensureAuditEvent(options.directory,existingWal),{plan:options.currentPlan,alreadyApplied:!0,generation:existingWal.generation,transitionId:existingWal.transitionId};if(existingWal===null&&options.currentPlanStatus!=="completed"&&options.currentPlanStatus!=="blocked"&&options.currentPlanStatus!=="closed"&&options.currentPlanStatus!=="in_progress")throw Error(`TASK_REPAIR_NOT_BACKWARD: cannot create a repair from plan status ${options.currentPlanStatus}`);if(existingWal===null&&options.currentPlanStatus==="in_progress"){let wedgeEscalated=!1;try{wedgeEscalated=getCoderRetryEscalationActions(options.directory,options.taskId,snapshot.retryEpoch).has("user_escalation")&&snapshot.retryCount>=3}catch(error93){if(error93 instanceof Error&&error93.message==="CORE_EVENT_AUTHORITY_INDEX_UNREADABLE")throw Error("TASK_REPAIR_ESCALATION_INDEX_UNREADABLE: cannot verify the retry-escalation wedge evidence for an in_progress repair (the core-event authority index is unreadable). The unreadable index is not content-restored: a later authority write rebuilds it from subsequent events only, so escalation evidence already folded out of the retained events window stays lost, and producers may refuse while the index is unreadable. "+"Recovery without discarding the events trail: re-dispatching the task re-runs the retry ladder from scratch and re-records the rungs; /swarm reset is the destructive full reset (it clears the plan, the events trail, and run state — session state is reset-session's charter and survives). Admission refuses to guess.");throw error93}if(!wedgeEscalated)throw Error(`TASK_REPAIR_NOT_BACKWARD: cannot create a repair from plan status ${options.currentPlanStatus} — an in_progress task is repairable only once the coder retry ladder has recorded a durable user_escalation for its current retry epoch with retryCount at the threshold; no such record is visible for this task.`)}let wal=existingWal??{version:1,state:"PREPARED",taskId:options.taskId,transitionId:options.transitionId,reason:options.reason,actor:options.actor,oldPlanStatus:options.currentPlanStatus,newPlanStatus:"in_progress",oldWorkflowState:options.expectedState,newWorkflowState:"idle",oldGeneration:options.expectedGeneration,generation:options.expectedGeneration+1,recordedAt:new Date().toISOString()},evidenceAlreadyRepaired=workflowMatchesCommittedRepair(evidence,wal);if(!evidenceAlreadyRepaired){if(snapshot.state!==wal.oldWorkflowState||snapshot.generation!==wal.oldGeneration)throw Error(`TASK_REPAIR_CAS_MISMATCH: expected ${wal.oldWorkflowState}@${wal.oldGeneration}, found ${snapshot.state}@${snapshot.generation}`)}if(existingWal===null)await writeWal(walPath,wal);let plan=options.currentPlan;if(options.currentPlanStatus!==wal.newPlanStatus){if(options.currentPlanStatus!==wal.oldPlanStatus)throw Error(`TASK_REPAIR_PLAN_CAS_MISMATCH: expected ${wal.oldPlanStatus}, found ${options.currentPlanStatus}`);plan=await options.updatePlan()}if(!evidenceAlreadyRepaired){if(evidence=await transaction.transition({type:"repair_idle",expectedGeneration:wal.oldGeneration,transitionId:wal.transitionId}),snapshot=getTaskWorkflowSnapshot(evidence),snapshot.state!=="idle"||snapshot.generation!==wal.generation)throw Error("TASK_REPAIR_EVIDENCE_UNVERIFIED")}return await writeWal(walPath,{...wal,state:"COMMITTED"}),await ensureAuditEvent(options.directory,wal),{plan,alreadyApplied:!1,generation:wal.generation,transitionId:wal.transitionId}})}var init_task_repair=__esm(()=>{init_core_events();init_gate_evidence();init_utils2();init_file_locks();init_ledger();init_manager();init_coder_settlement();init_workflow_wal_file()});function evidenceMatchesTerminal(evidence,wal){let workflow=getTaskWorkflowSnapshot(evidence);return workflow.authoritative&&workflow.state===wal.newWorkflowState&&workflow.generation===wal.generation&&workflow.lastTransitionId===wal.transitionId}async function applyTerminalEvidence(transaction,wal){return transaction.transition(wal.newPlanStatus==="completed"?{type:"task_completed",qaExempt:wal.qaExempt,readOnlyNoMutation:wal.readOnlyNoMutation,externalEvidence:wal.externalEvidence,expectedGeneration:wal.generation,transitionId:wal.transitionId}:wal.newPlanStatus==="blocked"?{type:"task_blocked",expectedGeneration:wal.generation,transitionId:wal.transitionId}:{type:"task_closed",expectedGeneration:wal.generation,transitionId:wal.transitionId})}async function applyTerminalEvidenceOrExplain(transaction,wal,walPath){try{return await _internals81.applyTerminalEvidence(transaction,wal)}catch(error93){throw Error(`TASK_TERMINAL_EVIDENCE_WRITE_FAILED: transition ${wal.transitionId} for task ${wal.taskId} forwarded plan.json to ${wal.newPlanStatus} but could not persist ${wal.newWorkflowState} evidence; ${walPath} stays PREPARED and fences every other evidence write for this task. Re-run task-terminal recovery for task ${wal.taskId} once the underlying write can succeed; if it fails persistently, repair the evidence file or the WAL before any further work on this task. Cause: ${error93 instanceof Error?error93.message:String(error93)}`,{cause:error93})}}async function recoverPreparedTaskTerminalWithPlanLock(directory,taskId,actor,currentPlan){let walPath=validateSwarmPath(directory,`task-terminals/${taskId}.json`),observedWal=await readWorkflowWalFile("task-terminal",walPath,taskId);if(observedWal===null)return null;if(observedWal.state!=="PREPARED")return null;let plan=currentPlan;return withTaskEvidenceTransaction(directory,taskId,actor,async(transaction)=>{let wal=await readWorkflowWalFile("task-terminal",walPath,taskId);if(wal===null)return null;if(wal.state!=="PREPARED")return null;if(wal.version===2){let identity=await readPlanEpochIdentity(directory,plan);if(!identity||identity.planIdentityHash!==wal.planIdentityHash||identity.planEpoch!==wal.planEpoch)throw Error(`TASK_TERMINAL_PLAN_IDENTITY_MISMATCH: ${walPath} belongs to a different plan epoch`)}let task=plan.phases.flatMap((phase)=>phase.tasks).find((candidate)=>candidate.id===taskId);if(!task)throw Error(`TASK_TERMINAL_TASK_MISSING: ${taskId}`);let evidence=transaction.read(),workflow=getTaskWorkflowSnapshot(evidence),evidenceAlreadyTerminal=evidenceMatchesTerminal(evidence,wal);if(wal.version===1&&task.status===wal.oldPlanStatus&&workflow.state===wal.oldWorkflowState&&workflow.generation===wal.generation)return await writeWal2(walPath,{...wal,state:"ABORTED"}),null;if(wal.externalEvidence===!0){if(!externalProofCurrent({title:plan.title,swarm:plan.swarm},task,evidence))throw Error(`TASK_TERMINAL_EXTERNAL_EVIDENCE_DIGEST_MISMATCH: ${walPath} records an external-evidence completion for task ${taskId}, but the current plan declaration no longer matches the attested declaration digest. Re-attest with /swarm attest ${taskId} (or re-plan the declaration), then re-run task-terminal recovery.`)}if(wal.readOnlyNoMutation===!0&&!evidenceAlreadyTerminal){let replayed;try{replayed=await peekPlanFromLedger(directory)}catch(error93){throw Error(`TASK_TERMINAL_READ_ONLY_SCOPE_UNKNOWN: could not inspect the authoritative plan ledger: ${error93 instanceof Error?error93.message:String(error93)}`,{cause:error93})}if(replayed.truncated||replayed.badSuffix!==null)throw Error("TASK_TERMINAL_LEDGER_TRUNCATED");if(!replayed.plan)throw Error("TASK_TERMINAL_READ_ONLY_SCOPE_UNKNOWN: authoritative plan ledger has no replayable plan");let authoritativeTask=replayed.plan.phases.flatMap((phase)=>phase.tasks).find((candidate)=>candidate.id===taskId);if(!authoritativeTask)throw Error(`TASK_TERMINAL_TASK_MISSING: ${taskId}`);if(wal.version===2){let identity=await readPlanEpochIdentity(directory,replayed.plan);if(!identity||identity.planIdentityHash!==wal.planIdentityHash||identity.planEpoch!==wal.planEpoch)throw Error(`TASK_TERMINAL_PLAN_IDENTITY_MISMATCH: ${walPath} belongs to a different plan epoch`)}plan=replayed.plan,task=authoritativeTask;let currentFiles=authoritativeTask.files_touched;if(!(Array.isArray(currentFiles)&¤tFiles.length===0)){if(authoritativeTask.status!==wal.oldPlanStatus&&authoritativeTask.status!==wal.newPlanStatus)throw Error(`TASK_TERMINAL_PLAN_CAS_MISMATCH: expected ${wal.oldPlanStatus} or ${wal.newPlanStatus}, found ${authoritativeTask.status}`);if(authoritativeTask.status===wal.newPlanStatus&&authoritativeTask.status!==wal.oldPlanStatus){let oldStatus=TaskStatusSchema.safeParse(wal.oldPlanStatus);if(!oldStatus.success)throw Error(`TASK_TERMINAL_OLD_STATUS_INVALID: ${wal.oldPlanStatus}`);let rolledBackPlan=await updateTaskStatus(directory,taskId,oldStatus.data,{planLockAlreadyHeld:!0,terminalReconciliation:!0}),rolledBackTask=rolledBackPlan.phases.flatMap((phase)=>phase.tasks).find((candidate)=>candidate.id===taskId);if(rolledBackTask?.status!==oldStatus.data)throw Error(`TASK_TERMINAL_READ_ONLY_SCOPE_ROLLBACK_FAILED: expected ${oldStatus.data}, found ${rolledBackTask?.status??"missing task"}`);plan=rolledBackPlan}throw await writeWal2(walPath,{...wal,state:"ABORTED"}),Error(`TASK_TERMINAL_READ_ONLY_SCOPE_CHANGED: task ${taskId} no longer has a known empty declared scope; terminal evidence was not applied`)}}if(task.status===wal.oldPlanStatus&&evidenceAlreadyTerminal)plan=await updateTaskStatus(directory,taskId,wal.newPlanStatus,{planLockAlreadyHeld:!0,terminalReconciliation:wal.version===2});else if(wal.version===2&&task.status===wal.oldPlanStatus)plan=await updateTaskStatus(directory,taskId,wal.newPlanStatus,{planLockAlreadyHeld:!0,terminalReconciliation:!0});else if(task.status!==wal.newPlanStatus)throw Error(`TASK_TERMINAL_PLAN_CAS_MISMATCH: expected ${wal.oldPlanStatus} or ${wal.newPlanStatus}, found ${task.status}`);let nextEvidence=evidenceAlreadyTerminal?evidence:await applyTerminalEvidenceOrExplain(transaction,wal,walPath);return await writeWal2(walPath,{...wal,state:"COMMITTED"}),{plan,evidence:nextEvidence,alreadyApplied:evidenceAlreadyTerminal,transitionId:wal.transitionId,targetStatus:wal.newPlanStatus}})}async function recoverPreparedTaskTerminal(directory,taskId,actor){let walPath=validateSwarmPath(directory,`task-terminals/${taskId}.json`),observedWal=await readWorkflowWalFile("task-terminal",walPath,taskId);if(observedWal===null||observedWal.state!=="PREPARED")return null;let lock=await tryAcquireLock(directory,"plan.json",actor,`recover-task-terminal-${taskId}-${Date.now()}`);if(!lock.acquired)throw Error(`TASK_TERMINAL_RECOVERY_LOCKED: ${lock.existing?.agent??"another agent"} owns plan.json`);try{let replay=await replayFromLedgerWithStatus(directory);if(replay.truncated)throw Error("TASK_TERMINAL_LEDGER_TRUNCATED");let loadedPlan=replay.plan??await loadPlanJsonOnly(directory);if(!loadedPlan)throw Error("TASK_TERMINAL_PLAN_MISSING");return await recoverPreparedTaskTerminalWithPlanLock(directory,taskId,actor,loadedPlan)}finally{if(lock.lock._release)await lock.lock._release().catch(()=>{})}}async function recoverPreparedTaskTerminalUnderPlanLock(directory,taskId,actor,currentPlan){return recoverPreparedTaskTerminalWithPlanLock(directory,taskId,actor,currentPlan)}async function commitTaskTerminalUnderPlanLock(options){let walPath=validateSwarmPath(options.directory,`task-terminals/${options.taskId}.json`);return withTaskEvidenceTransaction(options.directory,options.taskId,options.actor,async(transaction)=>{await assertNoUnsettledCoderDispatch(options.directory,options.taskId);let evidence=transaction.read(),workflow=getTaskWorkflowSnapshot(evidence);await options.validateEvidence?.(evidence);let terminal=options.resolveTerminal?.(evidence)??{targetStatus:options.targetStatus,qaExempt:options.qaExempt},existingWal=await readWorkflowWalFile("task-terminal",walPath,options.taskId);if(existingWal?.state==="ABORTED")existingWal=null;if(existingWal?.state==="PREPARED")throw Error(`TASK_TERMINAL_RECOVERY_REQUIRED: transition ${existingWal.transitionId} for task ${options.taskId} is PREPARED (${walPath}); requested transition ${options.transitionId}. Run task-terminal recovery for this task before retrying.`);if(existingWal?.version===2&&(existingWal.planIdentityHash!==options.planIdentityHash||existingWal.planEpoch!==options.planEpoch))throw Error(`TASK_TERMINAL_PLAN_IDENTITY_MISMATCH: ${walPath} belongs to a different plan epoch`);if(existingWal?.state==="COMMITTED"&&existingWal.transitionId===options.transitionId&&existingWal.newPlanStatus===terminal.targetStatus&&existingWal.readOnlyNoMutation===!0===(terminal.readOnlyNoMutation===!0)&&existingWal.externalEvidence===!0===(terminal.externalEvidence===!0)&&evidenceMatchesTerminal(evidence,existingWal))return{plan:options.currentPlan,evidence,alreadyApplied:!0,transitionId:options.transitionId,targetStatus:existingWal.newPlanStatus};if(terminal.preserveEvidence){if(!evidence||!workflow.authoritative)throw Error(`TASK_TERMINAL_AUTHORITATIVE_EVIDENCE_REQUIRED: task ${options.taskId} must have authoritative workflow evidence to preserve its terminal state for ${terminal.targetStatus} (transition ${options.transitionId}, ${walPath}); found ${evidence?`non-authoritative evidence in state ${workflow.state}`:"no evidence"}. Reconcile task evidence before retrying the terminal transition.`);let expectedState=terminal.targetStatus==="completed"?"complete":terminal.targetStatus==="closed"?"closed":"blocked";if(workflow.state!==expectedState)throw Error(`TASK_TERMINAL_EVIDENCE_STATE_MISMATCH: expected ${expectedState}, found ${workflow.state}`);return{plan:options.currentPlanStatus===terminal.targetStatus?options.currentPlan:await options.updatePlan(terminal.targetStatus),evidence,alreadyApplied:!0,transitionId:workflow.lastTransitionId??options.transitionId,targetStatus:terminal.targetStatus}}if(terminal.targetStatus==="closed"&&(!options.planIdentityHash||!options.planEpoch)){let missing=[options.planIdentityHash?null:"planIdentityHash",options.planEpoch?null:"planEpoch"].filter((field)=>field!==null).join(" and ");throw Error(`TASK_TERMINAL_PLAN_IDENTITY_REQUIRED: closing task ${options.taskId} requires both planIdentityHash and planEpoch (transition ${options.transitionId}, ${walPath}); missing ${missing}. Resolve the plan epoch identity (getOrAdoptPlanEpochUnderLock) before requesting a close.`)}let newWorkflowState=terminal.targetStatus==="completed"?"complete":terminal.targetStatus==="blocked"?"blocked":"closed",baseWal={state:"PREPARED",taskId:options.taskId,transitionId:options.transitionId,actor:options.actor,oldPlanStatus:options.currentPlanStatus,newPlanStatus:terminal.targetStatus,oldWorkflowState:workflow.state,newWorkflowState,generation:workflow.generation,qaExempt:terminal.qaExempt,...terminal.readOnlyNoMutation===!0?{readOnlyNoMutation:!0}:{},...terminal.externalEvidence===!0?{externalEvidence:!0}:{},recordedAt:new Date().toISOString()},wal=options.planIdentityHash&&options.planEpoch?{...baseWal,version:2,newPlanStatus:terminal.targetStatus,newWorkflowState,planIdentityHash:options.planIdentityHash,planEpoch:options.planEpoch}:{...baseWal,version:1,newPlanStatus:terminal.targetStatus,newWorkflowState};await writeWal2(walPath,wal);let plan=await options.updatePlan(terminal.targetStatus),nextEvidence=await applyTerminalEvidenceOrExplain(transaction,wal,walPath);return await writeWal2(walPath,{...wal,state:"COMMITTED"}),{plan,evidence:nextEvidence,alreadyApplied:!1,transitionId:options.transitionId,targetStatus:terminal.targetStatus}})}var writeWal2=(filePath,wal)=>writeWorkflowWalFile("task-terminal",filePath,wal),_internals81;var init_task_terminal=__esm(()=>{init_plan_schema();init_gate_evidence();init_utils2();init_file_locks();init_ledger();init_manager();init_coder_settlement();init_workflow_wal_file();_internals81={applyTerminalEvidence}});import*as fs54 from"node:fs";function storePath2(directory){return validateSwarmPath(directory,DEAD_LANE_RECLAIM_PATH)}function isDeadLaneReclaimEntry(value){if(!value||typeof value!=="object"||Array.isArray(value))return!1;let candidate=value;return typeof candidate.lanePath==="string"&&candidate.lanePath.length>0&&typeof candidate.branchName==="string"&&typeof candidate.parentSessionId==="string"&&typeof candidate.taskId==="string"&&typeof candidate.reason==="string"&&typeof candidate.recordedAt==="number"}function readStore2(directory){try{let raw=fs54.readFileSync(storePath2(directory),"utf-8");if(raw.length>MAX_DEAD_LANE_RECLAIM_BYTES)return{schemaVersion:1,entries:[]};let parsed=JSON.parse(raw);if(!parsed||parsed.schemaVersion!==1||!Array.isArray(parsed.entries))return{schemaVersion:1,entries:[]};return{schemaVersion:1,entries:parsed.entries.filter(isDeadLaneReclaimEntry)}}catch{return{schemaVersion:1,entries:[]}}}function writeStore2(directory,store){let entries=store.entries.slice(-MAX_DEAD_LANE_RECLAIMS);for(;;){let serialized2=JSON.stringify({schemaVersion:1,entries},null,2);if(serialized2.length<=MAX_DEAD_LANE_RECLAIM_BYTES||entries.length===0){if(entries.length<store.entries.length)log(`[dead-lane-reclaim] store bound dropped ${store.entries.length-entries.length} oldest entries (caps: ${MAX_DEAD_LANE_RECLAIMS} entries / ${MAX_DEAD_LANE_RECLAIM_BYTES} bytes)`);_internals82.atomicWriteSwarmFileSync(storePath2(directory),serialized2);return}entries=entries.slice(1)}}function recordDeadLaneReclaim(directory,entry){try{let filtered=readStore2(directory).entries.filter((existing)=>existing.lanePath!==entry.lanePath);filtered.push({...entry,recordedAt:Date.now()}),writeStore2(directory,{schemaVersion:1,entries:filtered})}catch(error93){log(`[dead-lane-reclaim] could not record stranded lane ${entry.lanePath}: ${error93 instanceof Error?error93.message:String(error93)}`)}}function isLaneOwnedByActiveSession(lanePath,activeSessionIds,parentSessionId){if(activeSessionIds.has(parentSessionId??""))return!0;if(parentSessionId&&!lanePathIncludesSessionSegment(lanePath,parentSessionId))return!0;return!1}function lanePathIncludesSessionSegment(lanePath,sessionId){return lanePath.replace(/\\/g,"/").split("/").includes(sessionId)}async function isLaneDirty(lanePath){let proc;try{let options={cwd:lanePath,stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:LANE_DIRTY_CHECK_TIMEOUT_MS,killProcessTree:!0};proc=_internals82.bunSpawn([_internals82.resolveGitExecutable(),"-C",lanePath,"status","--porcelain"],options);let stdout="";if(proc.stdout){let reader=proc.stdout.getReader();for(;;){let{done,value}=await reader.read();if(done||!value)break;if(stdout+=Buffer.from(value).toString("utf-8"),stdout.length>LANE_DIRTY_STDOUT_CAP_BYTES)break}}if(await proc.exited!==0)return!0;return stdout.trim().length>0}catch{return!0}finally{try{proc?.kill?.()}catch{}}}async function reclaimDeadLanes(directory,context={}){let result={reclaimed:[],retained:[]},store;try{store=readStore2(directory)}catch{return result}if(store.entries.length===0)return result;let activeSessionIds=new Set(context.activeSessionIds??[]),protectedPaths=new Set(context.protectedWorktreePaths??[]),retained=[];for(let entry of store.entries){let protectedLane=protectedPaths.has(entry.lanePath)||protectedPaths.has(_internals82.canonicalRootKeyFresh(entry.lanePath));if(_internals82.isLaneOwnedByActiveSession(entry.lanePath,activeSessionIds,entry.parentSessionId)||protectedLane){retained.push(entry),result.retained.push({lanePath:entry.lanePath,reason:"owned-by-active-session-or-protected"});continue}if(!await _internals82.pathExists(entry.lanePath))continue;if(await _internals82.isLaneDirty(entry.lanePath)){retained.push(entry),result.retained.push({lanePath:entry.lanePath,reason:"dirty-lane-preserved"});continue}_internals82.closeProjectDb(entry.lanePath);let removalError;try{let removal=await _internals82.removeWorktree(entry.lanePath,directory);if("error"in removal)removalError=removal.error}catch(error93){removalError=error93 instanceof Error?error93.message:String(error93)}if(removalError!==void 0){retained.push(entry),result.retained.push({lanePath:entry.lanePath,reason:removalError});continue}result.reclaimed.push(entry.lanePath)}try{if(retained.length===0)fs54.rmSync(storePath2(directory),{force:!0});else writeStore2(directory,{schemaVersion:1,entries:retained})}catch(error93){log(`[dead-lane-reclaim] could not persist reclaim state: ${error93 instanceof Error?error93.message:String(error93)}`)}return result}async function pathExists2(target){try{return await fs54.promises.stat(target),!0}catch{return!1}}var DEAD_LANE_RECLAIM_PATH="dead-lane-reclaims.json",MAX_DEAD_LANE_RECLAIMS=512,MAX_DEAD_LANE_RECLAIM_BYTES=262144,LANE_DIRTY_CHECK_TIMEOUT_MS=5000,LANE_DIRTY_STDOUT_CAP_BYTES=4096,_internals82;var init_dead_lane_reclaim=__esm(()=>{init_project_db();init_atomic_write();init_bun_compat();init_canonical_root();init_git_executable();init_logger();init_core3();init_utils2();_internals82={removeWorktree,closeProjectDb,isLaneOwnedByActiveSession,isLaneDirty,pathExists:pathExists2,bunSpawn,resolveGitExecutable,atomicWriteSwarmFileSync,canonicalRootKeyFresh}});function normalizeToForwardSlash(filePath){return filePath.replace(/\\/g,"/")}function matchesTier3(files){for(let file3 of files)if(isTier3Path(file3))return!0;return!1}function isTier3Path(filePath){let segments=normalizeToForwardSlash(filePath).split("/"),fileName=segments[segments.length-1]||"",fileBaseName=fileName.replace(/\.[^.]*$/,"").toLowerCase();if(TIER_3_EXACT_BASENAMES.has(fileBaseName))return!0;if(TIER_3_KEYWORD_PREFIX_RE.test(fileBaseName))return!0;for(let pattern of TIER_3_BASENAME_PATTERNS)if(pattern.test(fileName))return!0;for(let i=0;i<segments.length-1;i++)if(TIER_3_DIRECTORY_SEGMENTS.has(segments[i].toLowerCase()))return!0;return!1}var TIER_3_BASENAME_PATTERNS,TIER_3_EXACT_BASENAMES,TIER_3_KEYWORD_PREFIX_RE,TIER_3_DIRECTORY_SEGMENTS;var init_tier3_classifier=__esm(()=>{TIER_3_BASENAME_PATTERNS=[/^architect.*\.ts$/i,/^delegation.*\.ts$/i,/^guardrails?.*\.ts$/i,/^adversarial.*\.ts$/i,/^sanitiz.*\.ts$/i,/^security.*\.ts$/i],TIER_3_EXACT_BASENAMES=new Set(["auth","authenticate","authentication","authorization","permission","permissions","crypto","secret","secrets","secretscan"]),TIER_3_KEYWORD_PREFIX_RE=/^(auth|permission|crypto|secret|security)[-_.]/i,TIER_3_DIRECTORY_SEGMENTS=new Set(["auth","security","crypto","permission","secret"])});var require_constants=__commonJS((exports,module)=>{var POSIX_CHARS={DOT_LITERAL:"\\.",PLUS_LITERAL:"\\+",QMARK_LITERAL:"\\?",SLASH_LITERAL:"\\/",ONE_CHAR:"(?=.)",QMARK:"[^/]",END_ANCHOR:"(?:\\/|$)",DOTS_SLASH:"\\.{1,2}(?:\\/|$)",NO_DOT:"(?!\\.)",NO_DOTS:"(?!(?:^|\\/)\\.{1,2}(?:\\/|$))",NO_DOT_SLASH:"(?!\\.{0,1}(?:\\/|$))",NO_DOTS_SLASH:"(?!\\.{1,2}(?:\\/|$))",QMARK_NO_DOT:"[^.\\/]",STAR:"[^/]*?",START_ANCHOR:"(?:^|\\/)",SEP:"/"},WINDOWS_CHARS={...POSIX_CHARS,SLASH_LITERAL:"[\\\\/]",QMARK:"[^\\\\/]",STAR:"[^\\\\/]*?",DOTS_SLASH:"\\.{1,2}(?:[\\\\/]|$)",NO_DOT:"(?!\\.)",NO_DOTS:"(?!(?:^|[\\\\/])\\.{1,2}(?:[\\\\/]|$))",NO_DOT_SLASH:"(?!\\.{0,1}(?:[\\\\/]|$))",NO_DOTS_SLASH:"(?!\\.{1,2}(?:[\\\\/]|$))",QMARK_NO_DOT:"[^.\\\\/]",START_ANCHOR:"(?:^|[\\\\/])",END_ANCHOR:"(?:[\\\\/]|$)",SEP:"\\"},POSIX_REGEX_SOURCE={__proto__:null,alnum:"a-zA-Z0-9",alpha:"a-zA-Z",ascii:"\\x00-\\x7F",blank:" \\t",cntrl:"\\x00-\\x1F\\x7F",digit:"0-9",graph:"\\x21-\\x7E",lower:"a-z",print:"\\x20-\\x7E ",punct:"\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",space:" \\t\\r\\n\\v\\f",upper:"A-Z",word:"A-Za-z0-9_",xdigit:"A-Fa-f0-9"};module.exports={DEFAULT_MAX_EXTGLOB_RECURSION:0,MAX_LENGTH:65536,POSIX_REGEX_SOURCE,REGEX_BACKSLASH:/\\(?![*+?^${}(|)[\]])/g,REGEX_NON_SPECIAL_CHARS:/^[^@![\].,$*+?^{}()|\\/]+/,REGEX_SPECIAL_CHARS:/[-*+?.^${}(|)[\]]/,REGEX_SPECIAL_CHARS_BACKREF:/(\\?)((\W)(\3*))/g,REGEX_SPECIAL_CHARS_GLOBAL:/([-*+?.^${}(|)[\]])/g,REGEX_REMOVE_BACKSLASH:/(?:\[.*?[^\\]\]|\\(?=.))/g,REPLACEMENTS:{__proto__:null,"***":"*","**/**":"**","**/**/**":"**"},CHAR_0:48,CHAR_9:57,CHAR_UPPERCASE_A:65,CHAR_LOWERCASE_A:97,CHAR_UPPERCASE_Z:90,CHAR_LOWERCASE_Z:122,CHAR_LEFT_PARENTHESES:40,CHAR_RIGHT_PARENTHESES:41,CHAR_ASTERISK:42,CHAR_AMPERSAND:38,CHAR_AT:64,CHAR_BACKWARD_SLASH:92,CHAR_CARRIAGE_RETURN:13,CHAR_CIRCUMFLEX_ACCENT:94,CHAR_COLON:58,CHAR_COMMA:44,CHAR_DOT:46,CHAR_DOUBLE_QUOTE:34,CHAR_EQUAL:61,CHAR_EXCLAMATION_MARK:33,CHAR_FORM_FEED:12,CHAR_FORWARD_SLASH:47,CHAR_GRAVE_ACCENT:96,CHAR_HASH:35,CHAR_HYPHEN_MINUS:45,CHAR_LEFT_ANGLE_BRACKET:60,CHAR_LEFT_CURLY_BRACE:123,CHAR_LEFT_SQUARE_BRACKET:91,CHAR_LINE_FEED:10,CHAR_NO_BREAK_SPACE:160,CHAR_PERCENT:37,CHAR_PLUS:43,CHAR_QUESTION_MARK:63,CHAR_RIGHT_ANGLE_BRACKET:62,CHAR_RIGHT_CURLY_BRACE:125,CHAR_RIGHT_SQUARE_BRACKET:93,CHAR_SEMICOLON:59,CHAR_SINGLE_QUOTE:39,CHAR_SPACE:32,CHAR_TAB:9,CHAR_UNDERSCORE:95,CHAR_VERTICAL_LINE:124,CHAR_ZERO_WIDTH_NOBREAK_SPACE:65279,extglobChars(chars){return{"!":{type:"negate",open:"(?:(?!(?:",close:`))${chars.STAR})`},"?":{type:"qmark",open:"(?:",close:")?"},"+":{type:"plus",open:"(?:",close:")+"},"*":{type:"star",open:"(?:",close:")*"},"@":{type:"at",open:"(?:",close:")"}}},globChars(win329){return win329===!0?WINDOWS_CHARS:POSIX_CHARS}}});var require_utils=__commonJS((exports)=>{var{REGEX_BACKSLASH,REGEX_REMOVE_BACKSLASH,REGEX_SPECIAL_CHARS,REGEX_SPECIAL_CHARS_GLOBAL}=require_constants();exports.isObject=(val)=>val!==null&&typeof val==="object"&&!Array.isArray(val);exports.hasRegexChars=(str)=>REGEX_SPECIAL_CHARS.test(str);exports.isRegexChar=(str)=>str.length===1&&exports.hasRegexChars(str);exports.escapeRegex=(str)=>str.replace(REGEX_SPECIAL_CHARS_GLOBAL,"\\$1");exports.toPosixSlashes=(str)=>str.replace(REGEX_BACKSLASH,"/");exports.isWindows=()=>{if(typeof navigator<"u"&&navigator.platform){let platform=navigator.platform.toLowerCase();return platform==="win32"||platform==="windows"}if(typeof process<"u"&&process.platform)return process.platform==="win32";return!1};exports.removeBackslashes=(str)=>{return str.replace(REGEX_REMOVE_BACKSLASH,(match)=>{return match==="\\"?"":match})};exports.escapeLast=(input,char,lastIdx)=>{let idx=input.lastIndexOf(char,lastIdx);if(idx===-1)return input;if(input[idx-1]==="\\")return exports.escapeLast(input,char,idx-1);return`${input.slice(0,idx)}\\${input.slice(idx)}`};exports.removePrefix=(input,state2={})=>{let output=input;if(output.startsWith("./"))output=output.slice(2),state2.prefix="./";return output};exports.wrapOutput=(input,state2={},options={})=>{let prepend=options.contains?"":"^",append=options.contains?"":"$",output=`${prepend}(?:${input})${append}`;if(state2.negated===!0)output=`(?:^(?!${output}).*$)`;return output};exports.basename=(path87,{windows}={})=>{let segs=path87.split(windows?/[\\/]/:"/"),last=segs[segs.length-1];if(last==="")return segs[segs.length-2];return last}});var require_scan=__commonJS((exports,module)=>{var utils=require_utils(),{CHAR_ASTERISK,CHAR_AT,CHAR_BACKWARD_SLASH,CHAR_COMMA,CHAR_DOT,CHAR_EXCLAMATION_MARK,CHAR_FORWARD_SLASH,CHAR_LEFT_CURLY_BRACE,CHAR_LEFT_PARENTHESES,CHAR_LEFT_SQUARE_BRACKET,CHAR_PLUS,CHAR_QUESTION_MARK,CHAR_RIGHT_CURLY_BRACE,CHAR_RIGHT_PARENTHESES,CHAR_RIGHT_SQUARE_BRACKET}=require_constants(),isPathSeparator=(code)=>{return code===CHAR_FORWARD_SLASH||code===CHAR_BACKWARD_SLASH},depth=(token)=>{if(token.isPrefix!==!0)token.depth=token.isGlobstar?1/0:1},scan=(input,options)=>{let opts=options||{},length=input.length-1,scanToEnd=opts.parts===!0||opts.scanToEnd===!0,slashes=[],tokens=[],parts=[],str=input,index=-1,start=0,lastIndex=0,isBrace=!1,isBracket=!1,isGlob=!1,isExtglob=!1,isGlobstar=!1,braceEscaped=!1,backslashes=!1,negated=!1,negatedExtglob=!1,finished=!1,braces=0,prev,code,token={value:"",depth:0,isGlob:!1},eos=()=>index>=length,peek=()=>str.charCodeAt(index+1),advance=()=>{return prev=code,str.charCodeAt(++index)};while(index<length){code=advance();let next;if(code===CHAR_BACKWARD_SLASH){if(backslashes=token.backslashes=!0,code=advance(),code===CHAR_LEFT_CURLY_BRACE)braceEscaped=!0;continue}if(braceEscaped===!0||code===CHAR_LEFT_CURLY_BRACE){braces++;while(eos()!==!0&&(code=advance())){if(code===CHAR_BACKWARD_SLASH){backslashes=token.backslashes=!0,advance();continue}if(code===CHAR_LEFT_CURLY_BRACE){braces++;continue}if(braceEscaped!==!0&&code===CHAR_DOT&&(code=advance())===CHAR_DOT){if(isBrace=token.isBrace=!0,isGlob=token.isGlob=!0,finished=!0,scanToEnd===!0)continue;break}if(braceEscaped!==!0&&code===CHAR_COMMA){if(isBrace=token.isBrace=!0,isGlob=token.isGlob=!0,finished=!0,scanToEnd===!0)continue;break}if(code===CHAR_RIGHT_CURLY_BRACE){if(braces--,braces===0){braceEscaped=!1,isBrace=token.isBrace=!0,finished=!0;break}}}if(scanToEnd===!0)continue;break}if(code===CHAR_FORWARD_SLASH){if(slashes.push(index),tokens.push(token),token={value:"",depth:0,isGlob:!1},finished===!0)continue;if(prev===CHAR_DOT&&index===start+1){start+=2;continue}lastIndex=index+1;continue}if(opts.noext!==!0){if((code===CHAR_PLUS||code===CHAR_AT||code===CHAR_ASTERISK||code===CHAR_QUESTION_MARK||code===CHAR_EXCLAMATION_MARK)===!0&&peek()===CHAR_LEFT_PARENTHESES){if(isGlob=token.isGlob=!0,isExtglob=token.isExtglob=!0,finished=!0,code===CHAR_EXCLAMATION_MARK&&index===start)negatedExtglob=!0;if(scanToEnd===!0){while(eos()!==!0&&(code=advance())){if(code===CHAR_BACKWARD_SLASH){backslashes=token.backslashes=!0,code=advance();continue}if(code===CHAR_RIGHT_PARENTHESES){isGlob=token.isGlob=!0,finished=!0;break}}continue}break}}if(code===CHAR_ASTERISK){if(prev===CHAR_ASTERISK)isGlobstar=token.isGlobstar=!0;if(isGlob=token.isGlob=!0,finished=!0,scanToEnd===!0)continue;break}if(code===CHAR_QUESTION_MARK){if(isGlob=token.isGlob=!0,finished=!0,scanToEnd===!0)continue;break}if(code===CHAR_LEFT_SQUARE_BRACKET){while(eos()!==!0&&(next=advance())){if(next===CHAR_BACKWARD_SLASH){backslashes=token.backslashes=!0,advance();continue}if(next===CHAR_RIGHT_SQUARE_BRACKET){isBracket=token.isBracket=!0,isGlob=token.isGlob=!0,finished=!0;break}}if(scanToEnd===!0)continue;break}if(opts.nonegate!==!0&&code===CHAR_EXCLAMATION_MARK&&index===start){negated=token.negated=!0,start++;continue}if(opts.noparen!==!0&&code===CHAR_LEFT_PARENTHESES){if(isGlob=token.isGlob=!0,scanToEnd===!0){while(eos()!==!0&&(code=advance())){if(code===CHAR_LEFT_PARENTHESES){backslashes=token.backslashes=!0,code=advance();continue}if(code===CHAR_RIGHT_PARENTHESES){finished=!0;break}}continue}break}if(isGlob===!0){if(finished=!0,scanToEnd===!0)continue;break}}if(opts.noext===!0)isExtglob=!1,isGlob=!1;let base=str,prefix="",glob="";if(start>0)prefix=str.slice(0,start),str=str.slice(start),lastIndex-=start;if(base&&isGlob===!0&&lastIndex>0)base=str.slice(0,lastIndex),glob=str.slice(lastIndex);else if(isGlob===!0)base="",glob=str;else base=str;if(base&&base!==""&&base!=="/"&&base!==str){if(isPathSeparator(base.charCodeAt(base.length-1)))base=base.slice(0,-1)}if(opts.unescape===!0){if(glob)glob=utils.removeBackslashes(glob);if(base&&backslashes===!0)base=utils.removeBackslashes(base)}let state2={prefix,input,start,base,glob,isBrace,isBracket,isGlob,isExtglob,isGlobstar,negated,negatedExtglob};if(opts.tokens===!0){if(state2.maxDepth=0,!isPathSeparator(code))tokens.push(token);state2.tokens=tokens}if(opts.parts===!0||opts.tokens===!0){let prevIndex;for(let idx=0;idx<slashes.length;idx++){let n=prevIndex?prevIndex+1:start,i=slashes[idx],value=input.slice(n,i);if(opts.tokens){if(idx===0&&start!==0)tokens[idx].isPrefix=!0,tokens[idx].value=prefix;else tokens[idx].value=value;depth(tokens[idx]),state2.maxDepth+=tokens[idx].depth}if(idx!==0||value!=="")parts.push(value);prevIndex=i}if(prevIndex&&prevIndex+1<input.length){let value=input.slice(prevIndex+1);if(parts.push(value),opts.tokens)tokens[tokens.length-1].value=value,depth(tokens[tokens.length-1]),state2.maxDepth+=tokens[tokens.length-1].depth}state2.slashes=slashes,state2.parts=parts}return state2};module.exports=scan});var require_parse=__commonJS((exports,module)=>{var constants5=require_constants(),utils=require_utils(),{MAX_LENGTH,POSIX_REGEX_SOURCE,REGEX_NON_SPECIAL_CHARS,REGEX_SPECIAL_CHARS_BACKREF,REPLACEMENTS}=constants5,expandRange=(args2,options)=>{if(typeof options.expandRange==="function")return options.expandRange(...args2,options);args2.sort();let value=`[${args2.join("-")}]`;try{new RegExp(value)}catch(ex){return args2.map((v)=>utils.escapeRegex(v)).join("..")}return value},syntaxError=(type,char)=>{return`Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`},splitTopLevel=(input)=>{let parts=[],bracket=0,paren=0,quote=0,value="",escaped=!1;for(let ch of input){if(escaped===!0){value+=ch,escaped=!1;continue}if(ch==="\\"){value+=ch,escaped=!0;continue}if(ch==='"'){quote=quote===1?0:1,value+=ch;continue}if(quote===0){if(ch==="[")bracket++;else if(ch==="]"&&bracket>0)bracket--;else if(bracket===0){if(ch==="(")paren++;else if(ch===")"&&paren>0)paren--;else if(ch==="|"&&paren===0){parts.push(value),value="";continue}}}value+=ch}return parts.push(value),parts},isPlainBranch=(branch)=>{let escaped=!1;for(let ch of branch){if(escaped===!0){escaped=!1;continue}if(ch==="\\"){escaped=!0;continue}if(/[?*+@!()[\]{}]/.test(ch))return!1}return!0},normalizeSimpleBranch=(branch)=>{let value=branch.trim(),changed=!0;while(changed===!0)if(changed=!1,/^@\([^\\()[\]{}|]+\)$/.test(value))value=value.slice(2,-1),changed=!0;if(!isPlainBranch(value))return;return value.replace(/\\(.)/g,"$1")},hasRepeatedCharPrefixOverlap=(branches)=>{let values=branches.map(normalizeSimpleBranch).filter(Boolean);for(let i=0;i<values.length;i++)for(let j=i+1;j<values.length;j++){let a=values[i],b=values[j],char=a[0];if(!char||a!==char.repeat(a.length)||b!==char.repeat(b.length))continue;if(a===b||a.startsWith(b)||b.startsWith(a))return!0}return!1},parseRepeatedExtglob=(pattern,requireEnd=!0)=>{if(pattern[0]!=="+"&&pattern[0]!=="*"||pattern[1]!=="(")return;let bracket=0,paren=0,quote=0,escaped=!1;for(let i=1;i<pattern.length;i++){let ch=pattern[i];if(escaped===!0){escaped=!1;continue}if(ch==="\\"){escaped=!0;continue}if(ch==='"'){quote=quote===1?0:1;continue}if(quote===1)continue;if(ch==="["){bracket++;continue}if(ch==="]"&&bracket>0){bracket--;continue}if(bracket>0)continue;if(ch==="("){paren++;continue}if(ch===")"){if(paren--,paren===0){if(requireEnd===!0&&i!==pattern.length-1)return;return{type:pattern[0],body:pattern.slice(2,i),end:i}}}}},getStarExtglobSequenceOutput=(pattern)=>{let index=0,chars=[];while(index<pattern.length){let match=parseRepeatedExtglob(pattern.slice(index),!1);if(!match||match.type!=="*")return;let branches=splitTopLevel(match.body).map((branch2)=>branch2.trim());if(branches.length!==1)return;let branch=normalizeSimpleBranch(branches[0]);if(!branch||branch.length!==1)return;chars.push(branch),index+=match.end+1}if(chars.length<1)return;return`${chars.length===1?utils.escapeRegex(chars[0]):`[${chars.map((ch)=>utils.escapeRegex(ch)).join("")}]`}*`},repeatedExtglobRecursion=(pattern)=>{let depth=0,value=pattern.trim(),match=parseRepeatedExtglob(value);while(match)depth++,value=match.body.trim(),match=parseRepeatedExtglob(value);return depth},analyzeRepeatedExtglob=(body,options)=>{if(options.maxExtglobRecursion===!1)return{risky:!1};let max=typeof options.maxExtglobRecursion==="number"?options.maxExtglobRecursion:constants5.DEFAULT_MAX_EXTGLOB_RECURSION,branches=splitTopLevel(body).map((branch)=>branch.trim());if(branches.length>1){if(branches.some((branch)=>branch==="")||branches.some((branch)=>/^[*?]+$/.test(branch))||hasRepeatedCharPrefixOverlap(branches))return{risky:!0}}for(let branch of branches){let safeOutput=getStarExtglobSequenceOutput(branch);if(safeOutput)return{risky:!0,safeOutput};if(repeatedExtglobRecursion(branch)>max)return{risky:!0}}return{risky:!1}},parse9=(input,options)=>{if(typeof input!=="string")throw TypeError("Expected a string");input=REPLACEMENTS[input]||input;let opts={...options},max=typeof opts.maxLength==="number"?Math.min(MAX_LENGTH,opts.maxLength):MAX_LENGTH,len=input.length;if(len>max)throw SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);let bos={type:"bos",value:"",output:opts.prepend||""},tokens=[bos],capture=opts.capture?"":"?:",PLATFORM_CHARS=constants5.globChars(opts.windows),EXTGLOB_CHARS=constants5.extglobChars(PLATFORM_CHARS),{DOT_LITERAL,PLUS_LITERAL,SLASH_LITERAL,ONE_CHAR,DOTS_SLASH,NO_DOT,NO_DOT_SLASH,NO_DOTS_SLASH,QMARK,QMARK_NO_DOT,STAR,START_ANCHOR}=PLATFORM_CHARS,globstar=(opts2)=>{return`(${capture}(?:(?!${START_ANCHOR}${opts2.dot?DOTS_SLASH:DOT_LITERAL}).)*?)`},nodot=opts.dot?"":NO_DOT,qmarkNoDot=opts.dot?QMARK:QMARK_NO_DOT,star=opts.bash===!0?globstar(opts):STAR;if(opts.capture)star=`(${star})`;if(typeof opts.noext==="boolean")opts.noextglob=opts.noext;let state2={input,index:-1,start:0,dot:opts.dot===!0,consumed:"",output:"",prefix:"",backtrack:!1,negated:!1,brackets:0,braces:0,parens:0,quotes:0,globstar:!1,tokens};input=utils.removePrefix(input,state2),len=input.length;let extglobs=[],braces=[],stack=[],prev=bos,value,eos=()=>state2.index===len-1,peek=state2.peek=(n=1)=>input[state2.index+n],advance=state2.advance=()=>input[++state2.index]||"",remaining=()=>input.slice(state2.index+1),consume=(value2="",num=0)=>{state2.consumed+=value2,state2.index+=num},append=(token)=>{state2.output+=token.output!=null?token.output:token.value,consume(token.value)},negate=()=>{let count2=1;while(peek()==="!"&&(peek(2)!=="("||peek(3)==="?"))advance(),state2.start++,count2++;if(count2%2===0)return!1;return state2.negated=!0,state2.start++,!0},increment=(type)=>{state2[type]++,stack.push(type)},decrement=(type)=>{state2[type]--,stack.pop()},push=(tok)=>{if(prev.type==="globstar"){let isBrace=state2.braces>0&&(tok.type==="comma"||tok.type==="brace"),isExtglob=tok.extglob===!0||extglobs.length&&(tok.type==="pipe"||tok.type==="paren");if(tok.type!=="slash"&&tok.type!=="paren"&&!isBrace&&!isExtglob)state2.output=state2.output.slice(0,-prev.output.length),prev.type="star",prev.value="*",prev.output=star,state2.output+=prev.output}if(extglobs.length&&tok.type!=="paren")extglobs[extglobs.length-1].inner+=tok.value;if(tok.value||tok.output)append(tok);if(prev&&prev.type==="text"&&tok.type==="text"){prev.output=(prev.output||prev.value)+tok.value,prev.value+=tok.value;return}tok.prev=prev,tokens.push(tok),prev=tok},extglobOpen=(type,value2)=>{let token={...EXTGLOB_CHARS[value2],conditions:1,inner:""};token.prev=prev,token.parens=state2.parens,token.output=state2.output,token.startIndex=state2.index,token.tokensIndex=tokens.length;let output=(opts.capture?"(":"")+token.open;increment("parens"),push({type,value:value2,output:state2.output?"":ONE_CHAR}),push({type:"paren",extglob:!0,value:advance(),output}),extglobs.push(token)},extglobClose=(token)=>{let literal4=input.slice(token.startIndex,state2.index+1),body=input.slice(token.startIndex+2,state2.index),analysis=analyzeRepeatedExtglob(body,opts);if((token.type==="plus"||token.type==="star")&&analysis.risky){let safeOutput=analysis.safeOutput?(token.output?"":ONE_CHAR)+(opts.capture?`(${analysis.safeOutput})`:analysis.safeOutput):void 0,open6=tokens[token.tokensIndex];open6.type="text",open6.value=literal4,open6.output=safeOutput||utils.escapeRegex(literal4);for(let i=token.tokensIndex+1;i<tokens.length;i++)tokens[i].value="",tokens[i].output="",delete tokens[i].suffix;state2.output=token.output+open6.output,state2.backtrack=!0,push({type:"paren",extglob:!0,value,output:""}),decrement("parens");return}let output=token.close+(opts.capture?")":""),rest;if(token.type==="negate"){let extglobStar=star;if(token.inner&&token.inner.length>1&&token.inner.includes("/"))extglobStar=globstar(opts);if(extglobStar!==star||eos()||/^\)+$/.test(remaining()))output=token.close=`)$))${extglobStar}`;if(token.inner.includes("*")&&(rest=remaining())&&/^\.[^\\/.]+$/.test(rest)){let expression=parse9(rest,{...options,fastpaths:!1}).output;output=token.close=`)${expression})${extglobStar})`}if(token.prev.type==="bos")state2.negatedExtglob=!0}push({type:"paren",extglob:!0,value,output}),decrement("parens")};if(opts.fastpaths!==!1&&!/(^[*!]|[/()[\]{}"])/.test(input)){let backslashes=!1,output=input.replace(REGEX_SPECIAL_CHARS_BACKREF,(m,esc3,chars,first,rest,index)=>{if(first==="\\")return backslashes=!0,m;if(first==="?"){if(esc3)return esc3+first+(rest?QMARK.repeat(rest.length):"");if(index===0)return qmarkNoDot+(rest?QMARK.repeat(rest.length):"");return QMARK.repeat(chars.length)}if(first===".")return DOT_LITERAL.repeat(chars.length);if(first==="*"){if(esc3)return esc3+first+(rest?star:"");return star}return esc3?m:`\\${m}`});if(backslashes===!0)if(opts.unescape===!0)output=output.replace(/\\/g,"");else output=output.replace(/\\+/g,(m)=>{return m.length%2===0?"\\\\":m?"\\":""});if(output===input&&opts.contains===!0)return state2.output=input,state2;return state2.output=utils.wrapOutput(output,state2,options),state2}while(!eos()){if(value=advance(),value==="\x00")continue;if(value==="\\"){let next=peek();if(next==="/"&&opts.bash!==!0)continue;if(next==="."||next===";")continue;if(!next){value+="\\",push({type:"text",value});continue}let match=/^\\+/.exec(remaining()),slashes=0;if(match&&match[0].length>2){if(slashes=match[0].length,state2.index+=slashes,slashes%2!==0)value+="\\"}if(opts.unescape===!0)value=advance();else value+=advance();if(state2.brackets===0){push({type:"text",value});continue}}if(state2.brackets>0&&(value!=="]"||prev.value==="["||prev.value==="[^")){if(opts.posix!==!1&&value===":"){let inner=prev.value.slice(1);if(inner.includes("[")){if(prev.posix=!0,inner.includes(":")){let idx=prev.value.lastIndexOf("["),pre=prev.value.slice(0,idx),rest2=prev.value.slice(idx+2),posix11=POSIX_REGEX_SOURCE[rest2];if(posix11){if(prev.value=pre+posix11,state2.backtrack=!0,advance(),!bos.output&&tokens.indexOf(prev)===1)bos.output=ONE_CHAR;continue}}}}if(value==="["&&peek()!==":"||value==="-"&&peek()==="]")value=`\\${value}`;if(value==="]"&&(prev.value==="["||prev.value==="[^"))value=`\\${value}`;if(opts.posix===!0&&value==="!"&&prev.value==="[")value="^";prev.value+=value,append({value});continue}if(state2.quotes===1&&value!=='"'){value=utils.escapeRegex(value),prev.value+=value,append({value});continue}if(value==='"'){if(state2.quotes=state2.quotes===1?0:1,opts.keepQuotes===!0)push({type:"text",value});continue}if(value==="("){increment("parens"),push({type:"paren",value});continue}if(value===")"){if(state2.parens===0&&opts.strictBrackets===!0)throw SyntaxError(syntaxError("opening","("));let extglob=extglobs[extglobs.length-1];if(extglob&&state2.parens===extglob.parens+1){extglobClose(extglobs.pop());continue}push({type:"paren",value,output:state2.parens?")":"\\)"}),decrement("parens");continue}if(value==="["){if(opts.nobracket===!0||!remaining().includes("]")){if(opts.nobracket!==!0&&opts.strictBrackets===!0)throw SyntaxError(syntaxError("closing","]"));value=`\\${value}`}else increment("brackets");push({type:"bracket",value});continue}if(value==="]"){if(opts.nobracket===!0||prev&&prev.type==="bracket"&&prev.value.length===1){push({type:"text",value,output:`\\${value}`});continue}if(state2.brackets===0){if(opts.strictBrackets===!0)throw SyntaxError(syntaxError("opening","["));push({type:"text",value,output:`\\${value}`});continue}decrement("brackets");let prevValue=prev.value.slice(1);if(prev.posix!==!0&&prevValue[0]==="^"&&!prevValue.includes("/"))value=`/${value}`;if(prev.value+=value,append({value}),opts.literalBrackets===!1||utils.hasRegexChars(prevValue))continue;let escaped=utils.escapeRegex(prev.value);if(state2.output=state2.output.slice(0,-prev.value.length),opts.literalBrackets===!0){state2.output+=escaped,prev.value=escaped;continue}prev.value=`(${capture}${escaped}|${prev.value})`,state2.output+=prev.value;continue}if(value==="{"&&opts.nobrace!==!0){increment("braces");let open6={type:"brace",value,output:"(",outputIndex:state2.output.length,tokensIndex:state2.tokens.length};braces.push(open6),push(open6);continue}if(value==="}"){let brace=braces[braces.length-1];if(opts.nobrace===!0||!brace){push({type:"text",value,output:value});continue}let output=")";if(brace.dots===!0){let arr=tokens.slice(),range=[];for(let i=arr.length-1;i>=0;i--){if(tokens.pop(),arr[i].type==="brace")break;if(arr[i].type!=="dots")range.unshift(arr[i].value)}output=expandRange(range,opts),state2.backtrack=!0}if(brace.comma!==!0&&brace.dots!==!0){let out=state2.output.slice(0,brace.outputIndex),toks=state2.tokens.slice(brace.tokensIndex);brace.value=brace.output="\\{",value=output="\\}",state2.output=out;for(let t of toks)state2.output+=t.output||t.value}push({type:"brace",value,output}),decrement("braces"),braces.pop();continue}if(value==="|"){if(extglobs.length>0)extglobs[extglobs.length-1].conditions++;push({type:"text",value});continue}if(value===","){let output=value,brace=braces[braces.length-1];if(brace&&stack[stack.length-1]==="braces")brace.comma=!0,output="|";push({type:"comma",value,output});continue}if(value==="/"){if(prev.type==="dot"&&state2.index===state2.start+1){state2.start=state2.index+1,state2.consumed="",state2.output="",tokens.pop(),prev=bos;continue}push({type:"slash",value,output:SLASH_LITERAL});continue}if(value==="."){if(state2.braces>0&&prev.type==="dot"){if(prev.value===".")prev.output=DOT_LITERAL;let brace=braces[braces.length-1];prev.type="dots",prev.output+=value,prev.value+=value,brace.dots=!0;continue}if(state2.braces+state2.parens===0&&prev.type!=="bos"&&prev.type!=="slash"){push({type:"text",value,output:DOT_LITERAL});continue}push({type:"dot",value,output:DOT_LITERAL});continue}if(value==="?"){if(!(prev&&prev.value==="(")&&opts.noextglob!==!0&&peek()==="("&&peek(2)!=="?"){extglobOpen("qmark",value);continue}if(prev&&prev.type==="paren"){let next=peek(),output=value;if(prev.value==="("&&!/[!=<:]/.test(next)||next==="<"&&!/<([!=]|\w+>)/.test(remaining()))output=`\\${value}`;push({type:"text",value,output});continue}if(opts.dot!==!0&&(prev.type==="slash"||prev.type==="bos")){push({type:"qmark",value,output:QMARK_NO_DOT});continue}push({type:"qmark",value,output:QMARK});continue}if(value==="!"){if(opts.noextglob!==!0&&peek()==="("){if(peek(2)!=="?"||!/[!=<:]/.test(peek(3))){extglobOpen("negate",value);continue}}if(opts.nonegate!==!0&&state2.index===0){negate();continue}}if(value==="+"){if(opts.noextglob!==!0&&peek()==="("&&peek(2)!=="?"){extglobOpen("plus",value);continue}if(prev&&prev.value==="("||opts.regex===!1){push({type:"plus",value,output:PLUS_LITERAL});continue}if(prev&&(prev.type==="bracket"||prev.type==="paren"||prev.type==="brace")||state2.parens>0){push({type:"plus",value});continue}push({type:"plus",value:PLUS_LITERAL});continue}if(value==="@"){if(opts.noextglob!==!0&&peek()==="("&&peek(2)!=="?"){push({type:"at",extglob:!0,value,output:""});continue}push({type:"text",value});continue}if(value!=="*"){if(value==="$"||value==="^")value=`\\${value}`;let match=REGEX_NON_SPECIAL_CHARS.exec(remaining());if(match)value+=match[0],state2.index+=match[0].length;push({type:"text",value});continue}if(prev&&(prev.type==="globstar"||prev.star===!0)){prev.type="star",prev.star=!0,prev.value+=value,prev.output=star,state2.backtrack=!0,state2.globstar=!0,consume(value);continue}let rest=remaining();if(opts.noextglob!==!0&&/^\([^?]/.test(rest)){extglobOpen("star",value);continue}if(prev.type==="star"){if(opts.noglobstar===!0){consume(value);continue}let prior=prev.prev,before=prior.prev,isStart=prior.type==="slash"||prior.type==="bos",afterStar=before&&(before.type==="star"||before.type==="globstar");if(opts.bash===!0&&(!isStart||rest[0]&&rest[0]!=="/")){push({type:"star",value,output:""});continue}let isBrace=state2.braces>0&&(prior.type==="comma"||prior.type==="brace"),isExtglob=extglobs.length&&(prior.type==="pipe"||prior.type==="paren");if(!isStart&&prior.type!=="paren"&&!isBrace&&!isExtglob){push({type:"star",value,output:""});continue}while(rest.slice(0,3)==="/**"){let after=input[state2.index+4];if(after&&after!=="/")break;rest=rest.slice(3),consume("/**",3)}if(prior.type==="bos"&&eos()){prev.type="globstar",prev.value+=value,prev.output=globstar(opts),state2.output=prev.output,state2.globstar=!0,consume(value);continue}if(prior.type==="slash"&&prior.prev.type!=="bos"&&!afterStar&&eos()){state2.output=state2.output.slice(0,-(prior.output+prev.output).length),prior.output=`(?:${prior.output}`,prev.type="globstar",prev.output=globstar(opts)+(opts.strictSlashes?")":"|$)"),prev.value+=value,state2.globstar=!0,state2.output+=prior.output+prev.output,consume(value);continue}if(prior.type==="slash"&&prior.prev.type!=="bos"&&rest[0]==="/"){let end=rest[1]!==void 0?"|$":"";state2.output=state2.output.slice(0,-(prior.output+prev.output).length),prior.output=`(?:${prior.output}`,prev.type="globstar",prev.output=`${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`,prev.value+=value,state2.output+=prior.output+prev.output,state2.globstar=!0,consume(value+advance()),push({type:"slash",value:"/",output:""});continue}if(prior.type==="bos"&&rest[0]==="/"){prev.type="globstar",prev.value+=value,prev.output=`(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`,state2.output=prev.output,state2.globstar=!0,consume(value+advance()),push({type:"slash",value:"/",output:""});continue}state2.output=state2.output.slice(0,-prev.output.length),prev.type="globstar",prev.output=globstar(opts),prev.value+=value,state2.output+=prev.output,state2.globstar=!0,consume(value);continue}let token={type:"star",value,output:star};if(opts.bash===!0){if(token.output=".*?",prev.type==="bos"||prev.type==="slash")token.output=nodot+token.output;push(token);continue}if(prev&&(prev.type==="bracket"||prev.type==="paren")&&opts.regex===!0){token.output=value,push(token);continue}if(state2.index===state2.start||prev.type==="slash"||prev.type==="dot"){if(prev.type==="dot")state2.output+=NO_DOT_SLASH,prev.output+=NO_DOT_SLASH;else if(opts.dot===!0)state2.output+=NO_DOTS_SLASH,prev.output+=NO_DOTS_SLASH;else state2.output+=nodot,prev.output+=nodot;if(peek()!=="*")state2.output+=ONE_CHAR,prev.output+=ONE_CHAR}push(token)}while(state2.brackets>0){if(opts.strictBrackets===!0)throw SyntaxError(syntaxError("closing","]"));state2.output=utils.escapeLast(state2.output,"["),decrement("brackets")}while(state2.parens>0){if(opts.strictBrackets===!0)throw SyntaxError(syntaxError("closing",")"));state2.output=utils.escapeLast(state2.output,"("),decrement("parens")}while(state2.braces>0){if(opts.strictBrackets===!0)throw SyntaxError(syntaxError("closing","}"));state2.output=utils.escapeLast(state2.output,"{"),decrement("braces")}if(opts.strictSlashes!==!0&&(prev.type==="star"||prev.type==="bracket"))push({type:"maybe_slash",value:"",output:`${SLASH_LITERAL}?`});if(state2.backtrack===!0){state2.output="";for(let token of state2.tokens)if(state2.output+=token.output!=null?token.output:token.value,token.suffix)state2.output+=token.suffix}return state2};parse9.fastpaths=(input,options)=>{let opts={...options},max=typeof opts.maxLength==="number"?Math.min(MAX_LENGTH,opts.maxLength):MAX_LENGTH,len=input.length;if(len>max)throw SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);input=REPLACEMENTS[input]||input;let{DOT_LITERAL,SLASH_LITERAL,ONE_CHAR,DOTS_SLASH,NO_DOT,NO_DOTS,NO_DOTS_SLASH,STAR,START_ANCHOR}=constants5.globChars(opts.windows),nodot=opts.dot?NO_DOTS:NO_DOT,slashDot=opts.dot?NO_DOTS_SLASH:NO_DOT,capture=opts.capture?"":"?:",state2={negated:!1,prefix:""},star=opts.bash===!0?".*?":STAR;if(opts.capture)star=`(${star})`;let globstar=(opts2)=>{if(opts2.noglobstar===!0)return star;return`(${capture}(?:(?!${START_ANCHOR}${opts2.dot?DOTS_SLASH:DOT_LITERAL}).)*?)`},create=(str)=>{switch(str){case"*":return`${nodot}${ONE_CHAR}${star}`;case".*":return`${DOT_LITERAL}${ONE_CHAR}${star}`;case"*.*":return`${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;case"*/*":return`${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;case"**":return nodot+globstar(opts);case"**/*":return`(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;case"**/*.*":return`(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;case"**/.*":return`(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;default:{let match=/^(.*?)\.(\w+)$/.exec(str);if(!match)return;let source2=create(match[1]);if(!source2)return;return source2+DOT_LITERAL+match[2]}}},output=utils.removePrefix(input,state2),source=create(output);if(source&&opts.strictSlashes!==!0)source+=`${SLASH_LITERAL}?`;return source};module.exports=parse9});var require_picomatch=__commonJS((exports,module)=>{var scan=require_scan(),parse9=require_parse(),utils=require_utils(),constants5=require_constants(),isObject3=(val)=>val&&typeof val==="object"&&!Array.isArray(val),picomatch=(glob,options,returnState=!1)=>{if(Array.isArray(glob)){let fns=glob.map((input)=>picomatch(input,options,returnState));return(str)=>{for(let isMatch of fns){let state3=isMatch(str);if(state3)return state3}return!1}}let isState=isObject3(glob)&&glob.tokens&&glob.input;if(glob===""||typeof glob!=="string"&&!isState)throw TypeError("Expected pattern to be a non-empty string");let opts=options||{},posix11=opts.windows,regex=isState?picomatch.compileRe(glob,options):picomatch.makeRe(glob,options,!1,!0),state2=regex.state;delete regex.state;let isIgnored=()=>!1;if(opts.ignore){let ignoreOpts={...options,ignore:null,onMatch:null,onResult:null};isIgnored=picomatch(opts.ignore,ignoreOpts,returnState)}let matcher=(input,returnObject=!1)=>{let{isMatch,match,output}=picomatch.test(input,regex,options,{glob,posix:posix11}),result={glob,state:state2,regex,posix:posix11,input,output,match,isMatch};if(typeof opts.onResult==="function")opts.onResult(result);if(isMatch===!1)return result.isMatch=!1,returnObject?result:!1;if(isIgnored(input)){if(typeof opts.onIgnore==="function")opts.onIgnore(result);return result.isMatch=!1,returnObject?result:!1}if(typeof opts.onMatch==="function")opts.onMatch(result);return returnObject?result:!0};if(returnState)matcher.state=state2;return matcher};picomatch.test=(input,regex,options,{glob,posix:posix11}={})=>{if(typeof input!=="string")throw TypeError("Expected input to be a string");if(input==="")return{isMatch:!1,output:""};let opts=options||{},format=opts.format||(posix11?utils.toPosixSlashes:null),match=input===glob,output=match&&format?format(input):input;if(match===!1)output=format?format(input):input,match=output===glob;if(match===!1||opts.capture===!0)if(opts.matchBase===!0||opts.basename===!0)match=picomatch.matchBase(input,regex,options,posix11);else match=regex.exec(output);return{isMatch:Boolean(match),match,output}};picomatch.matchBase=(input,glob,options)=>{return(glob instanceof RegExp?glob:picomatch.makeRe(glob,options)).test(utils.basename(input))};picomatch.isMatch=(str,patterns,options)=>picomatch(patterns,options)(str);picomatch.parse=(pattern,options)=>{if(Array.isArray(pattern))return pattern.map((p)=>picomatch.parse(p,options));return parse9(pattern,{...options,fastpaths:!1})};picomatch.scan=(input,options)=>scan(input,options);picomatch.compileRe=(state2,options,returnOutput=!1,returnState=!1)=>{if(returnOutput===!0)return state2.output;let opts=options||{},prepend=opts.contains?"":"^",append=opts.contains?"":"$",source=`${prepend}(?:${state2.output})${append}`;if(state2&&state2.negated===!0)source=`^(?!${source}).*$`;let regex=picomatch.toRegex(source,options);if(returnState===!0)regex.state=state2;return regex};picomatch.makeRe=(input,options={},returnOutput=!1,returnState=!1)=>{if(!input||typeof input!=="string")throw TypeError("Expected a non-empty string");let parsed={negated:!1,fastpaths:!0};if(options.fastpaths!==!1&&(input[0]==="."||input[0]==="*"))parsed.output=parse9.fastpaths(input,options);if(!parsed.output)parsed=parse9(input,options);return picomatch.compileRe(parsed,options,returnOutput,returnState)};picomatch.toRegex=(source,options)=>{try{let opts=options||{};return new RegExp(source,opts.flags||(opts.nocase?"i":""))}catch(err){if(options&&options.debug===!0)throw err;return/$^/}};picomatch.constants=constants5;module.exports=picomatch});var require_picomatch2=__commonJS((exports,module)=>{var pico=require_picomatch(),utils=require_utils();function picomatch(glob,options,returnState=!1){if(options&&(options.windows===null||options.windows===void 0))options={...options,windows:utils.isWindows()};return pico(glob,options,returnState)}Object.assign(picomatch,pico);module.exports=picomatch});var QuickLRU;var init_quick_lru=__esm(()=>{QuickLRU=class QuickLRU extends Map{#size=0;#cache=new Map;#oldCache=new Map;#maxSize;#maxAge;#onEviction;constructor(options={}){super();if(!(options.maxSize&&options.maxSize>0))throw TypeError("`maxSize` must be a number greater than 0");if(typeof options.maxAge==="number"&&options.maxAge===0)throw TypeError("`maxAge` must be a number greater than 0");this.#maxSize=options.maxSize,this.#maxAge=options.maxAge||Number.POSITIVE_INFINITY,this.#onEviction=options.onEviction}get __oldCache(){return this.#oldCache}#emitEvictions(cache2){if(typeof this.#onEviction!=="function")return;for(let[key,item]of cache2)this.#onEviction(key,item.value)}#deleteIfExpired(key,item){if(typeof item.expiry==="number"&&item.expiry<=Date.now()){if(typeof this.#onEviction==="function")this.#onEviction(key,item.value);return this.delete(key)}return!1}#getOrDeleteIfExpired(key,item){if(this.#deleteIfExpired(key,item)===!1)return item.value}#getItemValue(key,item){return item.expiry?this.#getOrDeleteIfExpired(key,item):item.value}#peek(key,cache2){let item=cache2.get(key);return this.#getItemValue(key,item)}#set(key,value){if(this.#cache.set(key,value),this.#size++,this.#size>=this.#maxSize)this.#size=0,this.#emitEvictions(this.#oldCache),this.#oldCache=this.#cache,this.#cache=new Map}#moveToRecent(key,item){this.#oldCache.delete(key),this.#set(key,item)}*#entriesAscending(){for(let item of this.#oldCache){let[key,value]=item;if(!this.#cache.has(key)){if(this.#deleteIfExpired(key,value)===!1)yield item}}for(let item of this.#cache){let[key,value]=item;if(this.#deleteIfExpired(key,value)===!1)yield item}}get(key){if(this.#cache.has(key)){let item=this.#cache.get(key);return this.#getItemValue(key,item)}if(this.#oldCache.has(key)){let item=this.#oldCache.get(key);if(this.#deleteIfExpired(key,item)===!1)return this.#moveToRecent(key,item),item.value}}set(key,value,{maxAge=this.#maxAge}={}){let expiry=typeof maxAge==="number"&&maxAge!==Number.POSITIVE_INFINITY?Date.now()+maxAge:void 0;if(this.#cache.has(key))this.#cache.set(key,{value,expiry});else this.#set(key,{value,expiry});return this}has(key){if(this.#cache.has(key))return!this.#deleteIfExpired(key,this.#cache.get(key));if(this.#oldCache.has(key))return!this.#deleteIfExpired(key,this.#oldCache.get(key));return!1}peek(key){if(this.#cache.has(key))return this.#peek(key,this.#cache);if(this.#oldCache.has(key))return this.#peek(key,this.#oldCache)}expiresIn(key){let item=this.#cache.get(key)??this.#oldCache.get(key);if(item)return item.expiry?item.expiry-Date.now():Number.POSITIVE_INFINITY}delete(key){let deleted=this.#cache.delete(key);if(deleted)this.#size--;return this.#oldCache.delete(key)||deleted}clear(){this.#cache.clear(),this.#oldCache.clear(),this.#size=0}resize(newSize){if(!(newSize&&newSize>0))throw TypeError("`maxSize` must be a number greater than 0");let items=[...this.#entriesAscending()],removeCount=items.length-newSize;if(removeCount<0)this.#cache=new Map(items),this.#oldCache=new Map,this.#size=items.length;else{if(removeCount>0)this.#emitEvictions(items.slice(0,removeCount));this.#oldCache=new Map(items.slice(removeCount)),this.#cache=new Map,this.#size=0}this.#maxSize=newSize}evict(count2=1){let requested=Number(count2);if(!requested||requested<=0)return;let items=[...this.#entriesAscending()],evictCount=Math.trunc(Math.min(requested,Math.max(items.length-1,0)));if(evictCount<=0)return;this.#emitEvictions(items.slice(0,evictCount)),this.#oldCache=new Map(items.slice(evictCount)),this.#cache=new Map,this.#size=0}*keys(){for(let[key]of this)yield key}*values(){for(let[,value]of this)yield value}*[Symbol.iterator](){for(let item of this.#cache){let[key,value]=item;if(this.#deleteIfExpired(key,value)===!1)yield[key,value.value]}for(let item of this.#oldCache){let[key,value]=item;if(!this.#cache.has(key)){if(this.#deleteIfExpired(key,value)===!1)yield[key,value.value]}}}*entriesDescending(){let items=[...this.#cache];for(let i=items.length-1;i>=0;--i){let item=items[i],[key,value]=item;if(this.#deleteIfExpired(key,value)===!1)yield[key,value.value]}items=[...this.#oldCache];for(let i=items.length-1;i>=0;--i){let item=items[i],[key,value]=item;if(!this.#cache.has(key)){if(this.#deleteIfExpired(key,value)===!1)yield[key,value.value]}}}*entriesAscending(){for(let[key,value]of this.#entriesAscending())yield[key,value.value]}get size(){if(!this.#size)return this.#oldCache.size;let oldCacheSize=0;for(let key of this.#oldCache.keys())if(!this.#cache.has(key))oldCacheSize++;return Math.min(this.#size+oldCacheSize,this.#maxSize)}get maxSize(){return this.#maxSize}get maxAge(){return this.#maxAge}entries(){return this.entriesAscending()}forEach(callbackFunction,thisArgument=this){for(let[key,value]of this.entriesAscending())callbackFunction.call(thisArgument,value,key,this)}get[Symbol.toStringTag](){return"QuickLRU"}toString(){return`QuickLRU(${this.size}/${this.maxSize})`}[Symbol.for("nodejs.util.inspect.custom")](){return this.toString()}}});function classifyFile(filePath){let normalized=filePath.toLowerCase().replace(/\\/g,"/");if(normalized.endsWith(".wasm")||normalized.startsWith("dist/")||normalized.includes("/dist/")||normalized.startsWith("build/")||normalized.includes("/build/")||normalized.includes(".swarm/checkpoints/"))return{filePath,zone:"generated",confidence:"high",reason:"path matches generated file patterns"};if(normalized.includes("/test/")||normalized.includes("/tests/")||normalized.includes("/__tests__/")||normalized.includes(".test.")||normalized.includes(".spec.")||normalized.includes("/mocks/"))return{filePath,zone:"test",confidence:"high",reason:"path matches test/**, tests/**, __tests__/**, *.test.*, *.spec.*, or **/mocks/**"};if(normalized.includes("/scripts/")||normalized.includes("makefile")||normalized.includes("dockerfile")||normalized.includes(".github/"))return{filePath,zone:"build",confidence:"high",reason:"path matches build scripts or CI configuration"};if(normalized.endsWith(".json")&&!normalized.includes(".github/")||normalized.endsWith(".yaml")&&!normalized.includes(".github/")||normalized.endsWith(".yml")&&!normalized.includes(".github/")||normalized.endsWith(".toml")||normalized.includes(".env")||normalized.endsWith("biome.json")||normalized.endsWith("tsconfig.json"))return{filePath,zone:"config",confidence:"high",reason:"extension is config file type"};if(normalized.includes("/docs/")||normalized.endsWith(".md")&&!normalized.includes("/")||normalized.includes("readme")||normalized.includes("changelog")||normalized.includes("license"))return{filePath,zone:"docs",confidence:"high",reason:"path matches docs/** or documentation files"};if(normalized.includes("/src/")||normalized.includes("/lib/"))return{filePath,zone:"production",confidence:"high",reason:"path matches src/** or lib/**"};return{filePath,zone:"production",confidence:"medium",reason:"default classification"}}function sampleForHash(input){if(input.length<=HASH_INPUT_CAP_BYTES)return`${input.length}:${input}`;let half=Math.floor(HASH_INPUT_CAP_BYTES/2),head=input.slice(0,half),tail=input.slice(input.length-half);return`${input.length}:${head}${tail}`}function boundedBunHash(input){return bunHash(sampleForHash(input))}function coarseObjectDiscriminator(args2){try{let obj=args2,keys=Object.keys(obj).sort(),parts=keys.map((key)=>{let value=obj[key],type=typeof value,sample;if(value===null)sample="null";else if(Array.isArray(value))sample=`arr${value.length}`;else if(type==="object")sample=`obj${Object.keys(value).length}`;else if(type==="string"){let s=value;sample=s.length<=32?s:`len${s.length}`}else sample=String(value);return`${key}:${type}:${sample}`});return`${Array.isArray(args2)?`arr${keys.length}`:`obj${keys.length}`}|${parts.join(",")}`}catch{return"unknown"}}var HASH_INPUT_CAP_BYTES=65536;var init_arg_hash=__esm(()=>{init_bun_compat()});function stableCanonicalStringify(value){if(value===void 0)return"null";if(value===null)return"null";if(typeof value!=="object")return JSON.stringify(value);if(Array.isArray(value))return`[${value.map((el)=>stableCanonicalStringify(el)).join(",")}]`;let obj=value;return`{${Object.keys(obj).sort().map((k)=>`${JSON.stringify(k)}:${stableCanonicalStringify(obj[k])}`).join(",")}}`}import{execFileSync}from"node:child_process";import*as fsSync9 from"node:fs";import*as path87 from"node:path";function hashArgs(args2){try{if(typeof args2!=="object"||args2===null)return 0;let stable=stableCanonicalStringify(args2);return Number(boundedBunHash(stable))}catch(error93){return log("[Guardrails] hashArgs failed",{error:error93 instanceof Error?error93.message:String(error93)}),Number(boundedBunHash(coarseObjectDiscriminator(args2)))}}function gitEnvWithoutRepoRedirectors(){let env={...process.env};return delete env.GIT_DIR,delete env.GIT_WORK_TREE,delete env.GIT_INDEX_FILE,delete env.GIT_COMMON_DIR,env}function parseWorktreeListPorcelain(output){let records=[];for(let line of output.split(`
|
|
1000
|
+
`),{persisted:!0,path:filePath}}function readReviewRouteReceiptSync(input){let filePath=routeReceiptPath(input.projectRoot,input.sessionId,input.taskId),stat10;try{stat10=fs53.lstatSync(filePath)}catch(error93){if(error93.code==="ENOENT")return null;throw error93}if(stat10.isSymbolicLink()||!stat10.isFile()||stat10.size>MAX_ROUTE_RECEIPT_BYTES)throw Error("ROUTE_RECEIPT_UNREADABLE: receipt is not a bounded regular file");let value;try{value=JSON.parse(fs53.readFileSync(filePath,"utf8"))}catch(error93){if(error93 instanceof SyntaxError)throw Error("ROUTE_RECEIPT_INVALID_JSON: receipt is not valid JSON");throw error93}let parsed=typeof value==="object"&&value!==null&&value.kind==="review_route_receipt"?ReviewRouteReceiptSchema.safeParse(value):value.kind==="review_route_router_error"?ReviewRouteRouterErrorReceiptSchema.safeParse(value):ReviewRoutePendingReceiptSchema.safeParse(value);if(!parsed.success)throw Error("ROUTE_RECEIPT_INVALID: receipt failed schema validation");let authenticated=authenticatePersistedRouteReceipt(parsed.data,readRouteReceiptSecretSync(input.projectRoot));if((authenticated.kind==="review_route_receipt"||authenticated.kind==="review_route_pending")&&(authenticated.sessionId!==input.sessionId||authenticated.taskId!==input.taskId))throw Error("ROUTE_RECEIPT_IDENTITY_MISMATCH: receipt path and payload differ");if(authenticated.kind==="review_route_router_error"&&authenticated.sessionId!==void 0&&authenticated.taskId!==void 0&&(authenticated.sessionId!==input.sessionId||authenticated.taskId!==input.taskId))throw Error("ROUTE_RECEIPT_IDENTITY_MISMATCH: receipt path and payload differ");return authenticated}function parseRouteReceipt(value){if(!value||typeof value!=="object")return null;let kind=value.kind,parsed=kind==="review_route_receipt"?ReviewRouteReceiptSchema.safeParse(value):kind==="review_route_router_error"?ReviewRouteRouterErrorReceiptSchema.safeParse(value):ReviewRoutePendingReceiptSchema.safeParse(value);return parsed.success?parsed.data:null}function fail(reason){return{canAdvance:!1,mode:"enforced",reason}}function enforceReviewRouteReceipt(input){if(!input.enforcementEnabled)return{canAdvance:!0,mode:"disabled"};let route=parseRouteReceipt(input.routeReceipt);if(!route)return fail("ROUTE_RECEIPT_MISSING");if(route.kind==="review_route_router_error"){if(input.sessionId&&(!route.sessionId||!route.taskId||route.sessionId!==input.sessionId||route.taskId!==input.taskId))return fail("ROUTE_RECEIPT_IDENTITY_MISMATCH");return{canAdvance:!0,mode:"fail_open",routerFailure:route.code}}if(route.kind==="review_route_pending")return fail("ROUTE_RECEIPT_PENDING");if(input.sessionId&&route.sessionId!==input.sessionId||input.taskId&&route.taskId!==input.taskId)return fail("ROUTE_RECEIPT_IDENTITY_MISMATCH");if(route.required.reviewers!==route.identities.reviewers.length||route.required.testEngineers!==route.identities.testEngineers.length)return fail("ROUTE_RECEIPT_COUNT_MISMATCH");let expected=new Map;for(let identity of route.identities.reviewers){if(expected.has(identity))return fail("ROUTE_RECEIPT_DUPLICATE");expected.set(identity,"reviewer")}for(let identity of route.identities.testEngineers){if(expected.has(identity))return fail("ROUTE_RECEIPT_DUPLICATE");expected.set(identity,"test_engineer")}if(input.requireEvidenceBindings&&input.requireCompleteEvidence===!1&&expected.size>0&&!input.expectedDispatch)return fail("ROUTE_RECEIPT_DISPATCH_REQUIRED");let seen=new Set,seenSlots=new Set;for(let evidence of input.receipts){if(input.requireEvidenceBindings&&(!evidence.sessionId||!evidence.taskId||!evidence.slotId||!evidence.callId||!evidence.childSessionId||typeof evidence.generation!=="number"))return fail("ROUTE_RECEIPT_BINDING_MISSING");let identity=evidence.identity.trim();if(!identity||identity.length>256)return fail("ROUTE_RECEIPT_INVALID_IDENTITY");let expectedRole=expected.get(identity);if(!expectedRole)return fail("ROUTE_RECEIPT_IDENTITY_UNLISTED");if(expectedRole!==evidence.role)return fail("ROUTE_RECEIPT_ROLE_MISMATCH");if(seen.has(identity))return fail("ROUTE_RECEIPT_DUPLICATE");if(evidence.sessionId&&evidence.sessionId!==route.sessionId)return fail("ROUTE_RECEIPT_SESSION_MISMATCH");if(evidence.taskId&&evidence.taskId!==route.taskId)return fail("ROUTE_RECEIPT_TASK_MISMATCH");if(evidence.slotId){if(seenSlots.has(evidence.slotId))return fail("ROUTE_RECEIPT_DUPLICATE");let slots=evidence.role==="reviewer"?route.slots?.reviewers:route.slots?.testEngineers;if(slots&&!slots.includes(evidence.slotId))return fail("ROUTE_RECEIPT_SLOT_UNLISTED");if(slots){let expectedIndex=evidence.role==="reviewer"?route.identities.reviewers.indexOf(identity):route.identities.testEngineers.indexOf(identity);if(expectedIndex<0||slots[expectedIndex]!==evidence.slotId)return fail("ROUTE_RECEIPT_SLOT_MISMATCH")}seenSlots.add(evidence.slotId)}seen.add(identity)}if(input.expectedDispatch){let expected2=input.expectedDispatch,matching=input.receipts.find((evidence)=>evidence.role===expected2.role&&evidence.identity===expected2.identity);if(!matching||matching.callId!==expected2.callId||matching.childSessionId!==expected2.childSessionId||matching.generation!==expected2.generation)return fail("ROUTE_RECEIPT_DISPATCH_MISMATCH")}if(input.requireCompleteEvidence!==!1&&seen.size!==expected.size)return fail("ROUTE_RECEIPT_INCOMPLETE");return{canAdvance:!0,mode:"enforced"}}function enforcePersistedReviewRouteReceipt(input){if(!input.enforcementEnabled)return{canAdvance:!0,mode:"disabled"};let route;try{route=readReviewRouteReceiptSync({projectRoot:input.projectRoot,sessionId:input.sessionId,taskId:input.taskId})}catch(error93){if(error93 instanceof Error&&error93.message.startsWith("ROUTE_RECEIPT_AUTH_INVALID:"))return fail("ROUTE_RECEIPT_AUTH_INVALID");throw error93}if(!route&&input.legacyUnrouted)return{canAdvance:!0,mode:"legacy_unrouted",reason:"legacy_unrouted: route receipt predates version-1 enforcement"};return enforceReviewRouteReceipt({enforcementEnabled:!0,routeReceipt:route,receipts:input.receipts,sessionId:input.sessionId,taskId:input.taskId,requireEvidenceBindings:input.requireEvidenceBindings,expectedDispatch:input.expectedDispatch,requireCompleteEvidence:input.requireCompleteEvidence})}var REVIEW_ROUTE_RECEIPT_VERSION=1,IdentitySchema,RouteReceiptMacSchema,ReviewRouteReceiptSchema,ReviewRouteRouterErrorReceiptSchema,ReviewRoutePendingReceiptSchema,MAX_ROUTE_RECEIPT_BYTES=65536,ROUTE_RECEIPT_SECRET_FILE="review-route-receipts.key",ROUTE_RECEIPT_MAC_CONTEXT="opencode-swarm/review-route-receipt/v1\x00";var init_routing_enforcement=__esm(()=>{init_zod();init_task_file();init_utils2();init_hive_paths();init_project_boundary();IdentitySchema=exports_external.string().trim().min(1).max(256),RouteReceiptMacSchema=exports_external.string().regex(/^[0-9a-f]{64}$/,"route receipt MAC must be a SHA-256 HMAC"),ReviewRouteReceiptSchema=exports_external.object({kind:exports_external.literal("review_route_receipt"),version:exports_external.literal(REVIEW_ROUTE_RECEIPT_VERSION),sessionId:IdentitySchema,taskId:IdentitySchema,complexity:exports_external.string().trim().min(1).max(80),semanticRisk:exports_external.string().trim().min(1).max(120),required:exports_external.object({reviewers:exports_external.number().int().nonnegative().max(16),testEngineers:exports_external.number().int().nonnegative().max(16)}),identities:exports_external.object({reviewers:exports_external.array(IdentitySchema).max(16),testEngineers:exports_external.array(IdentitySchema).max(16)}),slots:exports_external.object({reviewers:exports_external.array(IdentitySchema).max(16),testEngineers:exports_external.array(IdentitySchema).max(16)}).optional(),createdAt:exports_external.string().trim().min(1).max(80).optional(),mac:RouteReceiptMacSchema.optional()}).strict(),ReviewRouteRouterErrorReceiptSchema=exports_external.object({kind:exports_external.literal("review_route_router_error"),version:exports_external.literal(REVIEW_ROUTE_RECEIPT_VERSION),code:exports_external.enum(["NO_CHANGED_FILES","ROUTER_UNAVAILABLE","ROUTER_FAILED"]),failOpen:exports_external.literal(!0),sessionId:IdentitySchema.optional(),taskId:IdentitySchema.optional(),detail:exports_external.string().trim().max(512).optional(),createdAt:exports_external.string().trim().min(1).max(80).optional(),mac:RouteReceiptMacSchema.optional()}).strict(),ReviewRoutePendingReceiptSchema=exports_external.object({kind:exports_external.literal("review_route_pending"),version:exports_external.literal(REVIEW_ROUTE_RECEIPT_VERSION),sessionId:IdentitySchema,taskId:IdentitySchema,createdAt:exports_external.string().trim().min(1).max(80).optional(),mac:RouteReceiptMacSchema.optional()}).strict()});function candidateSummary(resolution){let shown=resolution.candidates.slice(0,4).map((candidate)=>`${candidate.bindingId.slice(0,8)}/${candidate.generationId.slice(0,8)}@r${candidate.revision}`),omitted=Math.max(0,resolution.totalCandidates-shown.length);return`[${shown.join(", ")}${omitted>0?`, ... (+${omitted} more)`:""}]`}function formatScopeResolutionDiagnostic(input){let task=sanitizeDiagnosticText(input.taskId??"unknown",128),session=sanitizeDiagnosticText(input.sessionId,128);if(input.resolution.status==="ambiguous")return`SCOPE_BINDING_AMBIGUOUS: ${input.resolution.totalCandidates} exact live generations match task ${task} and session ${session}; candidates ${candidateSummary(input.resolution)}. ACTION[architect]: call declare_scope with replace_existing=true for this task/workspace, then dispatch a new Task call.`;if(input.resolution.status==="expired"){let lastExpiry=Math.max(...input.resolution.candidates.map((candidate)=>candidate.expiresAt)),expiredAt=Number.isFinite(lastExpiry)?new Date(lastExpiry).toISOString():"unknown";return`SCOPE_BINDING_EXPIRED: the exact generation for task ${task} and session ${session} expired while idle; expiredAt=${expiredAt}; candidates ${candidateSummary(input.resolution)}. ACTION[architect]: call declare_scope with replace_existing=true for this task/workspace, then dispatch a new Task call.`}if(input.resolution.status==="overloaded")return"SCOPE_BINDING_STORE_OVERLOADED: the complete live binding set exceeds the safe admission budget. ACTION[architect]: complete or expire terminal tasks, then retry declare_scope.";return null}var init_scope_resolution_diagnostic=__esm(()=>{init_path_identity()});async function recoverPreparedTaskRepairWithPlanLock(directory,taskId,actor,currentPlan){let walPath=validateSwarmPath(directory,`task-repairs/${taskId}.json`),wal=await readWal(walPath,taskId);if(wal===null)return null;if(wal.state==="ABORTED")return null;if(wal.state==="COMMITTED")return await ensureAuditEvent(directory,wal),null;let task=currentPlan.phases.flatMap((phase)=>phase.tasks).find((candidate)=>candidate.id===taskId);if(!task)throw Error(`TASK_REPAIR_TASK_MISSING: ${taskId}`);if(task.status===wal.oldPlanStatus){if(await withTaskEvidenceTransaction(directory,taskId,actor,async(transaction)=>{let workflow=getTaskWorkflowSnapshot(transaction.read());if(workflow.state!==wal.oldWorkflowState||workflow.generation!==wal.oldGeneration)return!1;return await writeWal(walPath,{...wal,state:"ABORTED"}),!0}))return null}return repairTaskWorkflowUnderPlanLock({directory,taskId,actor:wal.actor,reason:wal.reason,transitionId:wal.transitionId,expectedState:wal.oldWorkflowState,expectedGeneration:wal.oldGeneration,currentPlanStatus:task.status,currentPlan,updatePlan:()=>updateTaskStatus(directory,taskId,"in_progress",{force:!0,planLockAlreadyHeld:!0})})}async function recoverPreparedTaskRepair(directory,taskId,actor){let walPath=validateSwarmPath(directory,`task-repairs/${taskId}.json`),observedWal=await readWal(walPath,taskId);if(observedWal===null||observedWal.state==="ABORTED")return null;if(observedWal.state==="COMMITTED")return await ensureAuditEvent(directory,observedWal),null;let lock=await tryAcquireLock(directory,"plan.json",actor,`recover-task-repair-${taskId}-${Date.now()}`);if(!lock.acquired)throw Error(`TASK_REPAIR_RECOVERY_LOCKED: ${lock.existing?.agent??"another agent"} owns plan.json`);try{let replay=await replayFromLedgerWithStatus(directory);if(replay.truncated)throw Error("TASK_REPAIR_LEDGER_TRUNCATED");let plan=replay.plan??await loadPlanJsonOnly(directory);if(!plan)throw Error("TASK_REPAIR_PLAN_MISSING");return await recoverPreparedTaskRepairWithPlanLock(directory,taskId,actor,plan)}finally{if(lock.lock._release)await lock.lock._release().catch(()=>{})}}async function recoverPreparedTaskRepairUnderPlanLock(directory,taskId,actor,currentPlan){return recoverPreparedTaskRepairWithPlanLock(directory,taskId,actor,currentPlan)}async function readWal(filePath,taskId){return readWorkflowWalFile("task-repair",filePath,taskId)}async function writeWal(filePath,wal){await writeWorkflowWalFile("task-repair",filePath,wal)}async function ensureAuditEvent(directory,wal){if(hasTaskRepairAuditEvent(directory,wal.taskId,wal.transitionId))return;try{appendCoreEventSync(directory,{type:"task_workflow_repaired",timestamp:new Date().toISOString(),taskId:wal.taskId,transitionId:wal.transitionId,reason:wal.reason,actor:wal.actor,oldPlanStatus:wal.oldPlanStatus,newPlanStatus:wal.newPlanStatus,oldWorkflowState:wal.oldWorkflowState,newWorkflowState:wal.newWorkflowState,generation:wal.generation},{dedupeOnAuthorityKey:!0})}catch(error93){if(error93 instanceof Error&&error93.message===CORE_EVENT_LOCKED)throw Error("TASK_REPAIR_AUDIT_LOCKED");throw error93}if(!hasTaskRepairAuditEvent(directory,wal.taskId,wal.transitionId))throw Error("TASK_REPAIR_AUDIT_UNVERIFIED")}function workflowMatchesCommittedRepair(evidence,wal){let snapshot=getTaskWorkflowSnapshot(evidence);return snapshot.state==="idle"&&snapshot.generation===wal.generation&&snapshot.lastTransitionId===wal.transitionId}async function repairTaskWorkflowUnderPlanLock(options){let walPath=validateSwarmPath(options.directory,`task-repairs/${options.taskId}.json`);return withTaskEvidenceTransaction(options.directory,options.taskId,options.actor,async(transaction)=>{await assertNoUnsettledCoderDispatch(options.directory,options.taskId);let evidence=transaction.read(),snapshot=getTaskWorkflowSnapshot(evidence),existingWal=await readWal(walPath,options.taskId);if(existingWal?.state==="ABORTED")existingWal=null;if(existingWal&&existingWal.transitionId!==options.transitionId){if(existingWal.state==="PREPARED")throw Error(`TASK_REPAIR_IN_PROGRESS: transition ${existingWal.transitionId} owns the repair for task ${options.taskId} (${walPath}, state PREPARED); requested transition ${options.transitionId}. Recover or abort the owning repair transition before retrying.`);existingWal=null}if(existingWal&&(existingWal.reason!==options.reason||existingWal.oldWorkflowState!==options.expectedState||existingWal.oldGeneration!==options.expectedGeneration))throw Error(`TASK_REPAIR_IDEMPOTENCY_CONFLICT: transition ${options.transitionId} was prepared with different reason or workflow CAS fields`);if(existingWal?.state==="COMMITTED"&&options.currentPlanStatus==="in_progress"&&workflowMatchesCommittedRepair(evidence,existingWal))return await ensureAuditEvent(options.directory,existingWal),{plan:options.currentPlan,alreadyApplied:!0,generation:existingWal.generation,transitionId:existingWal.transitionId};if(existingWal===null&&options.currentPlanStatus!=="completed"&&options.currentPlanStatus!=="blocked"&&options.currentPlanStatus!=="closed"&&options.currentPlanStatus!=="in_progress")throw Error(`TASK_REPAIR_NOT_BACKWARD: cannot create a repair from plan status ${options.currentPlanStatus}`);if(existingWal===null&&options.currentPlanStatus==="in_progress"){let wedgeEscalated=!1;try{wedgeEscalated=getCoderRetryEscalationActions(options.directory,options.taskId,snapshot.retryEpoch).has("user_escalation")&&snapshot.retryCount>=3}catch(error93){if(error93 instanceof Error&&error93.message==="CORE_EVENT_AUTHORITY_INDEX_UNREADABLE")throw Error("TASK_REPAIR_ESCALATION_INDEX_UNREADABLE: cannot verify the retry-escalation wedge evidence for an in_progress repair (the core-event authority index is unreadable). The unreadable index is not content-restored: a later authority write rebuilds it from subsequent events only, so escalation evidence already folded out of the retained events window stays lost, and producers may refuse while the index is unreadable. "+"Recovery without discarding the events trail: re-dispatching the task re-runs the retry ladder from scratch and re-records the rungs; /swarm reset is the destructive full reset (it clears the plan, the events trail, and run state — session state is reset-session's charter and survives). Admission refuses to guess.");throw error93}if(!wedgeEscalated)throw Error(`TASK_REPAIR_NOT_BACKWARD: cannot create a repair from plan status ${options.currentPlanStatus} — an in_progress task is repairable only once the coder retry ladder has recorded a durable user_escalation for its current retry epoch with retryCount at the threshold; no such record is visible for this task.`)}let wal=existingWal??{version:1,state:"PREPARED",taskId:options.taskId,transitionId:options.transitionId,reason:options.reason,actor:options.actor,oldPlanStatus:options.currentPlanStatus,newPlanStatus:"in_progress",oldWorkflowState:options.expectedState,newWorkflowState:"idle",oldGeneration:options.expectedGeneration,generation:options.expectedGeneration+1,recordedAt:new Date().toISOString()},evidenceAlreadyRepaired=workflowMatchesCommittedRepair(evidence,wal);if(!evidenceAlreadyRepaired){if(snapshot.state!==wal.oldWorkflowState||snapshot.generation!==wal.oldGeneration)throw Error(`TASK_REPAIR_CAS_MISMATCH: expected ${wal.oldWorkflowState}@${wal.oldGeneration}, found ${snapshot.state}@${snapshot.generation}`)}if(existingWal===null)await writeWal(walPath,wal);let plan=options.currentPlan;if(options.currentPlanStatus!==wal.newPlanStatus){if(options.currentPlanStatus!==wal.oldPlanStatus)throw Error(`TASK_REPAIR_PLAN_CAS_MISMATCH: expected ${wal.oldPlanStatus}, found ${options.currentPlanStatus}`);plan=await options.updatePlan()}if(!evidenceAlreadyRepaired){if(evidence=await transaction.transition({type:"repair_idle",expectedGeneration:wal.oldGeneration,transitionId:wal.transitionId}),snapshot=getTaskWorkflowSnapshot(evidence),snapshot.state!=="idle"||snapshot.generation!==wal.generation)throw Error("TASK_REPAIR_EVIDENCE_UNVERIFIED")}return await writeWal(walPath,{...wal,state:"COMMITTED"}),await ensureAuditEvent(options.directory,wal),{plan,alreadyApplied:!1,generation:wal.generation,transitionId:wal.transitionId}})}var init_task_repair=__esm(()=>{init_core_events();init_gate_evidence();init_utils2();init_file_locks();init_ledger();init_manager();init_coder_settlement();init_workflow_wal_file()});function evidenceMatchesTerminal(evidence,wal){let workflow=getTaskWorkflowSnapshot(evidence);return workflow.authoritative&&workflow.state===wal.newWorkflowState&&workflow.generation===wal.generation&&workflow.lastTransitionId===wal.transitionId}async function applyTerminalEvidence(transaction,wal){return transaction.transition(wal.newPlanStatus==="completed"?{type:"task_completed",qaExempt:wal.qaExempt,readOnlyNoMutation:wal.readOnlyNoMutation,externalEvidence:wal.externalEvidence,expectedGeneration:wal.generation,transitionId:wal.transitionId}:wal.newPlanStatus==="blocked"?{type:"task_blocked",expectedGeneration:wal.generation,transitionId:wal.transitionId}:{type:"task_closed",expectedGeneration:wal.generation,transitionId:wal.transitionId})}async function applyTerminalEvidenceOrExplain(transaction,wal,walPath){try{return await _internals81.applyTerminalEvidence(transaction,wal)}catch(error93){throw Error(`TASK_TERMINAL_EVIDENCE_WRITE_FAILED: transition ${wal.transitionId} for task ${wal.taskId} forwarded plan.json to ${wal.newPlanStatus} but could not persist ${wal.newWorkflowState} evidence; ${walPath} stays PREPARED and fences every other evidence write for this task. Re-run task-terminal recovery for task ${wal.taskId} once the underlying write can succeed; if it fails persistently, repair the evidence file or the WAL before any further work on this task. Cause: ${error93 instanceof Error?error93.message:String(error93)}`,{cause:error93})}}async function recoverPreparedTaskTerminalWithPlanLock(directory,taskId,actor,currentPlan){let walPath=validateSwarmPath(directory,`task-terminals/${taskId}.json`),observedWal=await readWorkflowWalFile("task-terminal",walPath,taskId);if(observedWal===null)return null;if(observedWal.state!=="PREPARED")return null;let plan=currentPlan;return withTaskEvidenceTransaction(directory,taskId,actor,async(transaction)=>{let wal=await readWorkflowWalFile("task-terminal",walPath,taskId);if(wal===null)return null;if(wal.state!=="PREPARED")return null;if(wal.version===2){let identity=await readPlanEpochIdentity(directory,plan);if(!identity||identity.planIdentityHash!==wal.planIdentityHash||identity.planEpoch!==wal.planEpoch)throw Error(`TASK_TERMINAL_PLAN_IDENTITY_MISMATCH: ${walPath} belongs to a different plan epoch`)}let task=plan.phases.flatMap((phase)=>phase.tasks).find((candidate)=>candidate.id===taskId);if(!task)throw Error(`TASK_TERMINAL_TASK_MISSING: ${taskId}`);let evidence=transaction.read(),workflow=getTaskWorkflowSnapshot(evidence),evidenceAlreadyTerminal=evidenceMatchesTerminal(evidence,wal);if(wal.version===1&&task.status===wal.oldPlanStatus&&workflow.state===wal.oldWorkflowState&&workflow.generation===wal.generation)return await writeWal2(walPath,{...wal,state:"ABORTED"}),null;if(wal.externalEvidence===!0){if(!externalProofCurrent({title:plan.title,swarm:plan.swarm},task,evidence))throw Error(`TASK_TERMINAL_EXTERNAL_EVIDENCE_DIGEST_MISMATCH: ${walPath} records an external-evidence completion for task ${taskId}, but the current plan declaration no longer matches the attested declaration digest. Re-attest with /swarm attest ${taskId} (or re-plan the declaration), then re-run task-terminal recovery.`)}if(wal.readOnlyNoMutation===!0&&!evidenceAlreadyTerminal){let replayed;try{replayed=await peekPlanFromLedger(directory)}catch(error93){throw Error(`TASK_TERMINAL_READ_ONLY_SCOPE_UNKNOWN: could not inspect the authoritative plan ledger: ${error93 instanceof Error?error93.message:String(error93)}`,{cause:error93})}if(replayed.truncated||replayed.badSuffix!==null)throw Error("TASK_TERMINAL_LEDGER_TRUNCATED");if(!replayed.plan)throw Error("TASK_TERMINAL_READ_ONLY_SCOPE_UNKNOWN: authoritative plan ledger has no replayable plan");let authoritativeTask=replayed.plan.phases.flatMap((phase)=>phase.tasks).find((candidate)=>candidate.id===taskId);if(!authoritativeTask)throw Error(`TASK_TERMINAL_TASK_MISSING: ${taskId}`);if(wal.version===2){let identity=await readPlanEpochIdentity(directory,replayed.plan);if(!identity||identity.planIdentityHash!==wal.planIdentityHash||identity.planEpoch!==wal.planEpoch)throw Error(`TASK_TERMINAL_PLAN_IDENTITY_MISMATCH: ${walPath} belongs to a different plan epoch`)}plan=replayed.plan,task=authoritativeTask;let currentFiles=authoritativeTask.files_touched;if(!(Array.isArray(currentFiles)&¤tFiles.length===0)){if(authoritativeTask.status!==wal.oldPlanStatus&&authoritativeTask.status!==wal.newPlanStatus)throw Error(`TASK_TERMINAL_PLAN_CAS_MISMATCH: expected ${wal.oldPlanStatus} or ${wal.newPlanStatus}, found ${authoritativeTask.status}`);if(authoritativeTask.status===wal.newPlanStatus&&authoritativeTask.status!==wal.oldPlanStatus){let oldStatus=TaskStatusSchema.safeParse(wal.oldPlanStatus);if(!oldStatus.success)throw Error(`TASK_TERMINAL_OLD_STATUS_INVALID: ${wal.oldPlanStatus}`);let rolledBackPlan=await updateTaskStatus(directory,taskId,oldStatus.data,{planLockAlreadyHeld:!0,terminalReconciliation:!0}),rolledBackTask=rolledBackPlan.phases.flatMap((phase)=>phase.tasks).find((candidate)=>candidate.id===taskId);if(rolledBackTask?.status!==oldStatus.data)throw Error(`TASK_TERMINAL_READ_ONLY_SCOPE_ROLLBACK_FAILED: expected ${oldStatus.data}, found ${rolledBackTask?.status??"missing task"}`);plan=rolledBackPlan}throw await writeWal2(walPath,{...wal,state:"ABORTED"}),Error(`TASK_TERMINAL_READ_ONLY_SCOPE_CHANGED: task ${taskId} no longer has a known empty declared scope; terminal evidence was not applied`)}}if(task.status===wal.oldPlanStatus&&evidenceAlreadyTerminal)plan=await updateTaskStatus(directory,taskId,wal.newPlanStatus,{planLockAlreadyHeld:!0,terminalReconciliation:wal.version===2});else if(wal.version===2&&task.status===wal.oldPlanStatus)plan=await updateTaskStatus(directory,taskId,wal.newPlanStatus,{planLockAlreadyHeld:!0,terminalReconciliation:!0});else if(task.status!==wal.newPlanStatus)throw Error(`TASK_TERMINAL_PLAN_CAS_MISMATCH: expected ${wal.oldPlanStatus} or ${wal.newPlanStatus}, found ${task.status}`);let nextEvidence=evidenceAlreadyTerminal?evidence:await applyTerminalEvidenceOrExplain(transaction,wal,walPath);return await writeWal2(walPath,{...wal,state:"COMMITTED"}),{plan,evidence:nextEvidence,alreadyApplied:evidenceAlreadyTerminal,transitionId:wal.transitionId,targetStatus:wal.newPlanStatus}})}async function recoverPreparedTaskTerminal(directory,taskId,actor){let walPath=validateSwarmPath(directory,`task-terminals/${taskId}.json`),observedWal=await readWorkflowWalFile("task-terminal",walPath,taskId);if(observedWal===null||observedWal.state!=="PREPARED")return null;let lock=await tryAcquireLock(directory,"plan.json",actor,`recover-task-terminal-${taskId}-${Date.now()}`);if(!lock.acquired)throw Error(`TASK_TERMINAL_RECOVERY_LOCKED: ${lock.existing?.agent??"another agent"} owns plan.json`);try{let replay=await replayFromLedgerWithStatus(directory);if(replay.truncated)throw Error("TASK_TERMINAL_LEDGER_TRUNCATED");let loadedPlan=replay.plan??await loadPlanJsonOnly(directory);if(!loadedPlan)throw Error("TASK_TERMINAL_PLAN_MISSING");return await recoverPreparedTaskTerminalWithPlanLock(directory,taskId,actor,loadedPlan)}finally{if(lock.lock._release)await lock.lock._release().catch(()=>{})}}async function recoverPreparedTaskTerminalUnderPlanLock(directory,taskId,actor,currentPlan){return recoverPreparedTaskTerminalWithPlanLock(directory,taskId,actor,currentPlan)}async function commitTaskTerminalUnderPlanLock(options){let walPath=validateSwarmPath(options.directory,`task-terminals/${options.taskId}.json`);return withTaskEvidenceTransaction(options.directory,options.taskId,options.actor,async(transaction)=>{await assertNoUnsettledCoderDispatch(options.directory,options.taskId);let evidence=transaction.read(),workflow=getTaskWorkflowSnapshot(evidence);await options.validateEvidence?.(evidence);let terminal=options.resolveTerminal?.(evidence)??{targetStatus:options.targetStatus,qaExempt:options.qaExempt},existingWal=await readWorkflowWalFile("task-terminal",walPath,options.taskId);if(existingWal?.state==="ABORTED")existingWal=null;if(existingWal?.state==="PREPARED")throw Error(`TASK_TERMINAL_RECOVERY_REQUIRED: transition ${existingWal.transitionId} for task ${options.taskId} is PREPARED (${walPath}); requested transition ${options.transitionId}. Run task-terminal recovery for this task before retrying.`);if(existingWal?.version===2&&(existingWal.planIdentityHash!==options.planIdentityHash||existingWal.planEpoch!==options.planEpoch))throw Error(`TASK_TERMINAL_PLAN_IDENTITY_MISMATCH: ${walPath} belongs to a different plan epoch`);if(existingWal?.state==="COMMITTED"&&existingWal.transitionId===options.transitionId&&existingWal.newPlanStatus===terminal.targetStatus&&existingWal.readOnlyNoMutation===!0===(terminal.readOnlyNoMutation===!0)&&existingWal.externalEvidence===!0===(terminal.externalEvidence===!0)&&evidenceMatchesTerminal(evidence,existingWal))return{plan:options.currentPlan,evidence,alreadyApplied:!0,transitionId:options.transitionId,targetStatus:existingWal.newPlanStatus};if(terminal.preserveEvidence){if(!evidence||!workflow.authoritative)throw Error(`TASK_TERMINAL_AUTHORITATIVE_EVIDENCE_REQUIRED: task ${options.taskId} must have authoritative workflow evidence to preserve its terminal state for ${terminal.targetStatus} (transition ${options.transitionId}, ${walPath}); found ${evidence?`non-authoritative evidence in state ${workflow.state}`:"no evidence"}. Reconcile task evidence before retrying the terminal transition.`);let expectedState=terminal.targetStatus==="completed"?"complete":terminal.targetStatus==="closed"?"closed":"blocked";if(workflow.state!==expectedState)throw Error(`TASK_TERMINAL_EVIDENCE_STATE_MISMATCH: expected ${expectedState}, found ${workflow.state}`);return{plan:options.currentPlanStatus===terminal.targetStatus?options.currentPlan:await options.updatePlan(terminal.targetStatus),evidence,alreadyApplied:!0,transitionId:workflow.lastTransitionId??options.transitionId,targetStatus:terminal.targetStatus}}if(terminal.targetStatus==="closed"&&(!options.planIdentityHash||!options.planEpoch)){let missing=[options.planIdentityHash?null:"planIdentityHash",options.planEpoch?null:"planEpoch"].filter((field)=>field!==null).join(" and ");throw Error(`TASK_TERMINAL_PLAN_IDENTITY_REQUIRED: closing task ${options.taskId} requires both planIdentityHash and planEpoch (transition ${options.transitionId}, ${walPath}); missing ${missing}. Resolve the plan epoch identity (getOrAdoptPlanEpochUnderLock) before requesting a close.`)}let newWorkflowState=terminal.targetStatus==="completed"?"complete":terminal.targetStatus==="blocked"?"blocked":"closed",baseWal={state:"PREPARED",taskId:options.taskId,transitionId:options.transitionId,actor:options.actor,oldPlanStatus:options.currentPlanStatus,newPlanStatus:terminal.targetStatus,oldWorkflowState:workflow.state,newWorkflowState,generation:workflow.generation,qaExempt:terminal.qaExempt,...terminal.readOnlyNoMutation===!0?{readOnlyNoMutation:!0}:{},...terminal.externalEvidence===!0?{externalEvidence:!0}:{},recordedAt:new Date().toISOString()},wal=options.planIdentityHash&&options.planEpoch?{...baseWal,version:2,newPlanStatus:terminal.targetStatus,newWorkflowState,planIdentityHash:options.planIdentityHash,planEpoch:options.planEpoch}:{...baseWal,version:1,newPlanStatus:terminal.targetStatus,newWorkflowState};await writeWal2(walPath,wal);let plan=await options.updatePlan(terminal.targetStatus),nextEvidence=await applyTerminalEvidenceOrExplain(transaction,wal,walPath);return await writeWal2(walPath,{...wal,state:"COMMITTED"}),{plan,evidence:nextEvidence,alreadyApplied:!1,transitionId:options.transitionId,targetStatus:terminal.targetStatus}})}var writeWal2=(filePath,wal)=>writeWorkflowWalFile("task-terminal",filePath,wal),_internals81;var init_task_terminal=__esm(()=>{init_plan_schema();init_gate_evidence();init_utils2();init_file_locks();init_ledger();init_manager();init_coder_settlement();init_workflow_wal_file();_internals81={applyTerminalEvidence}});import*as fs54 from"node:fs";function storePath2(directory){return validateSwarmPath(directory,DEAD_LANE_RECLAIM_PATH)}function isDeadLaneReclaimEntry(value){if(!value||typeof value!=="object"||Array.isArray(value))return!1;let candidate=value;return typeof candidate.lanePath==="string"&&candidate.lanePath.length>0&&typeof candidate.branchName==="string"&&typeof candidate.parentSessionId==="string"&&typeof candidate.taskId==="string"&&typeof candidate.reason==="string"&&typeof candidate.recordedAt==="number"}function readStore2(directory){try{let raw=fs54.readFileSync(storePath2(directory),"utf-8");if(raw.length>MAX_DEAD_LANE_RECLAIM_BYTES)return{schemaVersion:1,entries:[]};let parsed=JSON.parse(raw);if(!parsed||parsed.schemaVersion!==1||!Array.isArray(parsed.entries))return{schemaVersion:1,entries:[]};return{schemaVersion:1,entries:parsed.entries.filter(isDeadLaneReclaimEntry)}}catch{return{schemaVersion:1,entries:[]}}}function writeStore2(directory,store){let entries=store.entries.slice(-MAX_DEAD_LANE_RECLAIMS);for(;;){let serialized2=JSON.stringify({schemaVersion:1,entries},null,2);if(serialized2.length<=MAX_DEAD_LANE_RECLAIM_BYTES||entries.length===0){if(entries.length<store.entries.length)log(`[dead-lane-reclaim] store bound dropped ${store.entries.length-entries.length} oldest entries (caps: ${MAX_DEAD_LANE_RECLAIMS} entries / ${MAX_DEAD_LANE_RECLAIM_BYTES} bytes)`);_internals82.atomicWriteSwarmFileSync(storePath2(directory),serialized2);return}entries=entries.slice(1)}}function recordDeadLaneReclaim(directory,entry){try{let filtered=readStore2(directory).entries.filter((existing)=>existing.lanePath!==entry.lanePath);filtered.push({...entry,recordedAt:Date.now()}),writeStore2(directory,{schemaVersion:1,entries:filtered})}catch(error93){log(`[dead-lane-reclaim] could not record stranded lane ${entry.lanePath}: ${error93 instanceof Error?error93.message:String(error93)}`)}}function isLaneOwnedByActiveSession(lanePath,activeSessionIds,parentSessionId){if(activeSessionIds.has(parentSessionId??""))return!0;if(parentSessionId&&!lanePathIncludesSessionSegment(lanePath,parentSessionId))return!0;return!1}function lanePathIncludesSessionSegment(lanePath,sessionId){return lanePath.replace(/\\/g,"/").split("/").includes(sessionId)}async function isLaneDirty(lanePath){let proc;try{let options={cwd:lanePath,stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:LANE_DIRTY_CHECK_TIMEOUT_MS,killProcessTree:!0};proc=_internals82.bunSpawn([_internals82.resolveGitExecutable(),"-C",lanePath,"status","--porcelain"],options);let stdout="";if(proc.stdout){let reader=proc.stdout.getReader();for(;;){let{done,value}=await reader.read();if(done||!value)break;if(stdout+=Buffer.from(value).toString("utf-8"),stdout.length>LANE_DIRTY_STDOUT_CAP_BYTES)break}}if(await proc.exited!==0)return!0;return stdout.trim().length>0}catch{return!0}finally{try{proc?.kill?.()}catch{}}}async function reclaimDeadLanes(directory,context={}){let result={reclaimed:[],retained:[]},store;try{store=readStore2(directory)}catch{return result}if(store.entries.length===0)return result;let activeSessionIds=new Set(context.activeSessionIds??[]),protectedPaths=new Set(context.protectedWorktreePaths??[]),retained=[];for(let entry of store.entries){let protectedLane=protectedPaths.has(entry.lanePath)||protectedPaths.has(_internals82.canonicalRootKeyFresh(entry.lanePath));if(_internals82.isLaneOwnedByActiveSession(entry.lanePath,activeSessionIds,entry.parentSessionId)||protectedLane){retained.push(entry),result.retained.push({lanePath:entry.lanePath,reason:"owned-by-active-session-or-protected"});continue}if(!await _internals82.pathExists(entry.lanePath))continue;if(await _internals82.isLaneDirty(entry.lanePath)){retained.push(entry),result.retained.push({lanePath:entry.lanePath,reason:"dirty-lane-preserved"});continue}_internals82.closeProjectDb(entry.lanePath);let removalError;try{let removal=await _internals82.removeWorktree(entry.lanePath,directory);if("error"in removal)removalError=removal.error}catch(error93){removalError=error93 instanceof Error?error93.message:String(error93)}if(removalError!==void 0){retained.push(entry),result.retained.push({lanePath:entry.lanePath,reason:removalError});continue}result.reclaimed.push(entry.lanePath)}try{if(retained.length===0)fs54.rmSync(storePath2(directory),{force:!0});else writeStore2(directory,{schemaVersion:1,entries:retained})}catch(error93){log(`[dead-lane-reclaim] could not persist reclaim state: ${error93 instanceof Error?error93.message:String(error93)}`)}return result}async function pathExists2(target){try{return await fs54.promises.stat(target),!0}catch{return!1}}var DEAD_LANE_RECLAIM_PATH="dead-lane-reclaims.json",MAX_DEAD_LANE_RECLAIMS=512,MAX_DEAD_LANE_RECLAIM_BYTES=262144,LANE_DIRTY_CHECK_TIMEOUT_MS=5000,LANE_DIRTY_STDOUT_CAP_BYTES=4096,_internals82;var init_dead_lane_reclaim=__esm(()=>{init_project_db();init_atomic_write();init_bun_compat();init_canonical_root();init_git_executable();init_logger();init_core3();init_utils2();_internals82={removeWorktree,closeProjectDb,isLaneOwnedByActiveSession,isLaneDirty,pathExists:pathExists2,bunSpawn,resolveGitExecutable,atomicWriteSwarmFileSync,canonicalRootKeyFresh}});function normalizeToForwardSlash(filePath){return filePath.replace(/\\/g,"/")}function matchesTier3(files){for(let file3 of files)if(isTier3Path(file3))return!0;return!1}function isTier3Path(filePath){let segments=normalizeToForwardSlash(filePath).split("/"),fileName=segments[segments.length-1]||"",fileBaseName=fileName.replace(/\.[^.]*$/,"").toLowerCase();if(TIER_3_EXACT_BASENAMES.has(fileBaseName))return!0;if(TIER_3_KEYWORD_PREFIX_RE.test(fileBaseName))return!0;for(let pattern of TIER_3_BASENAME_PATTERNS)if(pattern.test(fileName))return!0;for(let i=0;i<segments.length-1;i++)if(TIER_3_DIRECTORY_SEGMENTS.has(segments[i].toLowerCase()))return!0;return!1}var TIER_3_BASENAME_PATTERNS,TIER_3_EXACT_BASENAMES,TIER_3_KEYWORD_PREFIX_RE,TIER_3_DIRECTORY_SEGMENTS;var init_tier3_classifier=__esm(()=>{TIER_3_BASENAME_PATTERNS=[/^architect.*\.ts$/i,/^delegation.*\.ts$/i,/^guardrails?.*\.ts$/i,/^adversarial.*\.ts$/i,/^sanitiz.*\.ts$/i,/^security.*\.ts$/i],TIER_3_EXACT_BASENAMES=new Set(["auth","authenticate","authentication","authorization","permission","permissions","crypto","secret","secrets","secretscan"]),TIER_3_KEYWORD_PREFIX_RE=/^(auth|permission|crypto|secret|security)[-_.]/i,TIER_3_DIRECTORY_SEGMENTS=new Set(["auth","security","crypto","permission","secret"])});var require_constants=__commonJS((exports,module)=>{var POSIX_CHARS={DOT_LITERAL:"\\.",PLUS_LITERAL:"\\+",QMARK_LITERAL:"\\?",SLASH_LITERAL:"\\/",ONE_CHAR:"(?=.)",QMARK:"[^/]",END_ANCHOR:"(?:\\/|$)",DOTS_SLASH:"\\.{1,2}(?:\\/|$)",NO_DOT:"(?!\\.)",NO_DOTS:"(?!(?:^|\\/)\\.{1,2}(?:\\/|$))",NO_DOT_SLASH:"(?!\\.{0,1}(?:\\/|$))",NO_DOTS_SLASH:"(?!\\.{1,2}(?:\\/|$))",QMARK_NO_DOT:"[^.\\/]",STAR:"[^/]*?",START_ANCHOR:"(?:^|\\/)",SEP:"/"},WINDOWS_CHARS={...POSIX_CHARS,SLASH_LITERAL:"[\\\\/]",QMARK:"[^\\\\/]",STAR:"[^\\\\/]*?",DOTS_SLASH:"\\.{1,2}(?:[\\\\/]|$)",NO_DOT:"(?!\\.)",NO_DOTS:"(?!(?:^|[\\\\/])\\.{1,2}(?:[\\\\/]|$))",NO_DOT_SLASH:"(?!\\.{0,1}(?:[\\\\/]|$))",NO_DOTS_SLASH:"(?!\\.{1,2}(?:[\\\\/]|$))",QMARK_NO_DOT:"[^.\\\\/]",START_ANCHOR:"(?:^|[\\\\/])",END_ANCHOR:"(?:[\\\\/]|$)",SEP:"\\"},POSIX_REGEX_SOURCE={__proto__:null,alnum:"a-zA-Z0-9",alpha:"a-zA-Z",ascii:"\\x00-\\x7F",blank:" \\t",cntrl:"\\x00-\\x1F\\x7F",digit:"0-9",graph:"\\x21-\\x7E",lower:"a-z",print:"\\x20-\\x7E ",punct:"\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",space:" \\t\\r\\n\\v\\f",upper:"A-Z",word:"A-Za-z0-9_",xdigit:"A-Fa-f0-9"};module.exports={DEFAULT_MAX_EXTGLOB_RECURSION:0,MAX_LENGTH:65536,POSIX_REGEX_SOURCE,REGEX_BACKSLASH:/\\(?![*+?^${}(|)[\]])/g,REGEX_NON_SPECIAL_CHARS:/^[^@![\].,$*+?^{}()|\\/]+/,REGEX_SPECIAL_CHARS:/[-*+?.^${}(|)[\]]/,REGEX_SPECIAL_CHARS_BACKREF:/(\\?)((\W)(\3*))/g,REGEX_SPECIAL_CHARS_GLOBAL:/([-*+?.^${}(|)[\]])/g,REGEX_REMOVE_BACKSLASH:/(?:\[.*?[^\\]\]|\\(?=.))/g,REPLACEMENTS:{__proto__:null,"***":"*","**/**":"**","**/**/**":"**"},CHAR_0:48,CHAR_9:57,CHAR_UPPERCASE_A:65,CHAR_LOWERCASE_A:97,CHAR_UPPERCASE_Z:90,CHAR_LOWERCASE_Z:122,CHAR_LEFT_PARENTHESES:40,CHAR_RIGHT_PARENTHESES:41,CHAR_ASTERISK:42,CHAR_AMPERSAND:38,CHAR_AT:64,CHAR_BACKWARD_SLASH:92,CHAR_CARRIAGE_RETURN:13,CHAR_CIRCUMFLEX_ACCENT:94,CHAR_COLON:58,CHAR_COMMA:44,CHAR_DOT:46,CHAR_DOUBLE_QUOTE:34,CHAR_EQUAL:61,CHAR_EXCLAMATION_MARK:33,CHAR_FORM_FEED:12,CHAR_FORWARD_SLASH:47,CHAR_GRAVE_ACCENT:96,CHAR_HASH:35,CHAR_HYPHEN_MINUS:45,CHAR_LEFT_ANGLE_BRACKET:60,CHAR_LEFT_CURLY_BRACE:123,CHAR_LEFT_SQUARE_BRACKET:91,CHAR_LINE_FEED:10,CHAR_NO_BREAK_SPACE:160,CHAR_PERCENT:37,CHAR_PLUS:43,CHAR_QUESTION_MARK:63,CHAR_RIGHT_ANGLE_BRACKET:62,CHAR_RIGHT_CURLY_BRACE:125,CHAR_RIGHT_SQUARE_BRACKET:93,CHAR_SEMICOLON:59,CHAR_SINGLE_QUOTE:39,CHAR_SPACE:32,CHAR_TAB:9,CHAR_UNDERSCORE:95,CHAR_VERTICAL_LINE:124,CHAR_ZERO_WIDTH_NOBREAK_SPACE:65279,extglobChars(chars){return{"!":{type:"negate",open:"(?:(?!(?:",close:`))${chars.STAR})`},"?":{type:"qmark",open:"(?:",close:")?"},"+":{type:"plus",open:"(?:",close:")+"},"*":{type:"star",open:"(?:",close:")*"},"@":{type:"at",open:"(?:",close:")"}}},globChars(win329){return win329===!0?WINDOWS_CHARS:POSIX_CHARS}}});var require_utils=__commonJS((exports)=>{var{REGEX_BACKSLASH,REGEX_REMOVE_BACKSLASH,REGEX_SPECIAL_CHARS,REGEX_SPECIAL_CHARS_GLOBAL}=require_constants();exports.isObject=(val)=>val!==null&&typeof val==="object"&&!Array.isArray(val);exports.hasRegexChars=(str)=>REGEX_SPECIAL_CHARS.test(str);exports.isRegexChar=(str)=>str.length===1&&exports.hasRegexChars(str);exports.escapeRegex=(str)=>str.replace(REGEX_SPECIAL_CHARS_GLOBAL,"\\$1");exports.toPosixSlashes=(str)=>str.replace(REGEX_BACKSLASH,"/");exports.isWindows=()=>{if(typeof navigator<"u"&&navigator.platform){let platform=navigator.platform.toLowerCase();return platform==="win32"||platform==="windows"}if(typeof process<"u"&&process.platform)return process.platform==="win32";return!1};exports.removeBackslashes=(str)=>{return str.replace(REGEX_REMOVE_BACKSLASH,(match)=>{return match==="\\"?"":match})};exports.escapeLast=(input,char,lastIdx)=>{let idx=input.lastIndexOf(char,lastIdx);if(idx===-1)return input;if(input[idx-1]==="\\")return exports.escapeLast(input,char,idx-1);return`${input.slice(0,idx)}\\${input.slice(idx)}`};exports.removePrefix=(input,state2={})=>{let output=input;if(output.startsWith("./"))output=output.slice(2),state2.prefix="./";return output};exports.wrapOutput=(input,state2={},options={})=>{let prepend=options.contains?"":"^",append=options.contains?"":"$",output=`${prepend}(?:${input})${append}`;if(state2.negated===!0)output=`(?:^(?!${output}).*$)`;return output};exports.basename=(path87,{windows}={})=>{let segs=path87.split(windows?/[\\/]/:"/"),last=segs[segs.length-1];if(last==="")return segs[segs.length-2];return last}});var require_scan=__commonJS((exports,module)=>{var utils=require_utils(),{CHAR_ASTERISK,CHAR_AT,CHAR_BACKWARD_SLASH,CHAR_COMMA,CHAR_DOT,CHAR_EXCLAMATION_MARK,CHAR_FORWARD_SLASH,CHAR_LEFT_CURLY_BRACE,CHAR_LEFT_PARENTHESES,CHAR_LEFT_SQUARE_BRACKET,CHAR_PLUS,CHAR_QUESTION_MARK,CHAR_RIGHT_CURLY_BRACE,CHAR_RIGHT_PARENTHESES,CHAR_RIGHT_SQUARE_BRACKET}=require_constants(),isPathSeparator=(code)=>{return code===CHAR_FORWARD_SLASH||code===CHAR_BACKWARD_SLASH},depth=(token)=>{if(token.isPrefix!==!0)token.depth=token.isGlobstar?1/0:1},scan=(input,options)=>{let opts=options||{},length=input.length-1,scanToEnd=opts.parts===!0||opts.scanToEnd===!0,slashes=[],tokens=[],parts=[],str=input,index=-1,start=0,lastIndex=0,isBrace=!1,isBracket=!1,isGlob=!1,isExtglob=!1,isGlobstar=!1,braceEscaped=!1,backslashes=!1,negated=!1,negatedExtglob=!1,finished=!1,braces=0,prev,code,token={value:"",depth:0,isGlob:!1},eos=()=>index>=length,peek=()=>str.charCodeAt(index+1),advance=()=>{return prev=code,str.charCodeAt(++index)};while(index<length){code=advance();let next;if(code===CHAR_BACKWARD_SLASH){if(backslashes=token.backslashes=!0,code=advance(),code===CHAR_LEFT_CURLY_BRACE)braceEscaped=!0;continue}if(braceEscaped===!0||code===CHAR_LEFT_CURLY_BRACE){braces++;while(eos()!==!0&&(code=advance())){if(code===CHAR_BACKWARD_SLASH){backslashes=token.backslashes=!0,advance();continue}if(code===CHAR_LEFT_CURLY_BRACE){braces++;continue}if(braceEscaped!==!0&&code===CHAR_DOT&&(code=advance())===CHAR_DOT){if(isBrace=token.isBrace=!0,isGlob=token.isGlob=!0,finished=!0,scanToEnd===!0)continue;break}if(braceEscaped!==!0&&code===CHAR_COMMA){if(isBrace=token.isBrace=!0,isGlob=token.isGlob=!0,finished=!0,scanToEnd===!0)continue;break}if(code===CHAR_RIGHT_CURLY_BRACE){if(braces--,braces===0){braceEscaped=!1,isBrace=token.isBrace=!0,finished=!0;break}}}if(scanToEnd===!0)continue;break}if(code===CHAR_FORWARD_SLASH){if(slashes.push(index),tokens.push(token),token={value:"",depth:0,isGlob:!1},finished===!0)continue;if(prev===CHAR_DOT&&index===start+1){start+=2;continue}lastIndex=index+1;continue}if(opts.noext!==!0){if((code===CHAR_PLUS||code===CHAR_AT||code===CHAR_ASTERISK||code===CHAR_QUESTION_MARK||code===CHAR_EXCLAMATION_MARK)===!0&&peek()===CHAR_LEFT_PARENTHESES){if(isGlob=token.isGlob=!0,isExtglob=token.isExtglob=!0,finished=!0,code===CHAR_EXCLAMATION_MARK&&index===start)negatedExtglob=!0;if(scanToEnd===!0){while(eos()!==!0&&(code=advance())){if(code===CHAR_BACKWARD_SLASH){backslashes=token.backslashes=!0,code=advance();continue}if(code===CHAR_RIGHT_PARENTHESES){isGlob=token.isGlob=!0,finished=!0;break}}continue}break}}if(code===CHAR_ASTERISK){if(prev===CHAR_ASTERISK)isGlobstar=token.isGlobstar=!0;if(isGlob=token.isGlob=!0,finished=!0,scanToEnd===!0)continue;break}if(code===CHAR_QUESTION_MARK){if(isGlob=token.isGlob=!0,finished=!0,scanToEnd===!0)continue;break}if(code===CHAR_LEFT_SQUARE_BRACKET){while(eos()!==!0&&(next=advance())){if(next===CHAR_BACKWARD_SLASH){backslashes=token.backslashes=!0,advance();continue}if(next===CHAR_RIGHT_SQUARE_BRACKET){isBracket=token.isBracket=!0,isGlob=token.isGlob=!0,finished=!0;break}}if(scanToEnd===!0)continue;break}if(opts.nonegate!==!0&&code===CHAR_EXCLAMATION_MARK&&index===start){negated=token.negated=!0,start++;continue}if(opts.noparen!==!0&&code===CHAR_LEFT_PARENTHESES){if(isGlob=token.isGlob=!0,scanToEnd===!0){while(eos()!==!0&&(code=advance())){if(code===CHAR_LEFT_PARENTHESES){backslashes=token.backslashes=!0,code=advance();continue}if(code===CHAR_RIGHT_PARENTHESES){finished=!0;break}}continue}break}if(isGlob===!0){if(finished=!0,scanToEnd===!0)continue;break}}if(opts.noext===!0)isExtglob=!1,isGlob=!1;let base=str,prefix="",glob="";if(start>0)prefix=str.slice(0,start),str=str.slice(start),lastIndex-=start;if(base&&isGlob===!0&&lastIndex>0)base=str.slice(0,lastIndex),glob=str.slice(lastIndex);else if(isGlob===!0)base="",glob=str;else base=str;if(base&&base!==""&&base!=="/"&&base!==str){if(isPathSeparator(base.charCodeAt(base.length-1)))base=base.slice(0,-1)}if(opts.unescape===!0){if(glob)glob=utils.removeBackslashes(glob);if(base&&backslashes===!0)base=utils.removeBackslashes(base)}let state2={prefix,input,start,base,glob,isBrace,isBracket,isGlob,isExtglob,isGlobstar,negated,negatedExtglob};if(opts.tokens===!0){if(state2.maxDepth=0,!isPathSeparator(code))tokens.push(token);state2.tokens=tokens}if(opts.parts===!0||opts.tokens===!0){let prevIndex;for(let idx=0;idx<slashes.length;idx++){let n=prevIndex?prevIndex+1:start,i=slashes[idx],value=input.slice(n,i);if(opts.tokens){if(idx===0&&start!==0)tokens[idx].isPrefix=!0,tokens[idx].value=prefix;else tokens[idx].value=value;depth(tokens[idx]),state2.maxDepth+=tokens[idx].depth}if(idx!==0||value!=="")parts.push(value);prevIndex=i}if(prevIndex&&prevIndex+1<input.length){let value=input.slice(prevIndex+1);if(parts.push(value),opts.tokens)tokens[tokens.length-1].value=value,depth(tokens[tokens.length-1]),state2.maxDepth+=tokens[tokens.length-1].depth}state2.slashes=slashes,state2.parts=parts}return state2};module.exports=scan});var require_parse=__commonJS((exports,module)=>{var constants5=require_constants(),utils=require_utils(),{MAX_LENGTH,POSIX_REGEX_SOURCE,REGEX_NON_SPECIAL_CHARS,REGEX_SPECIAL_CHARS_BACKREF,REPLACEMENTS}=constants5,expandRange=(args2,options)=>{if(typeof options.expandRange==="function")return options.expandRange(...args2,options);args2.sort();let value=`[${args2.join("-")}]`;try{new RegExp(value)}catch(ex){return args2.map((v)=>utils.escapeRegex(v)).join("..")}return value},syntaxError=(type,char)=>{return`Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`},splitTopLevel=(input)=>{let parts=[],bracket=0,paren=0,quote=0,value="",escaped=!1;for(let ch of input){if(escaped===!0){value+=ch,escaped=!1;continue}if(ch==="\\"){value+=ch,escaped=!0;continue}if(ch==='"'){quote=quote===1?0:1,value+=ch;continue}if(quote===0){if(ch==="[")bracket++;else if(ch==="]"&&bracket>0)bracket--;else if(bracket===0){if(ch==="(")paren++;else if(ch===")"&&paren>0)paren--;else if(ch==="|"&&paren===0){parts.push(value),value="";continue}}}value+=ch}return parts.push(value),parts},isPlainBranch=(branch)=>{let escaped=!1;for(let ch of branch){if(escaped===!0){escaped=!1;continue}if(ch==="\\"){escaped=!0;continue}if(/[?*+@!()[\]{}]/.test(ch))return!1}return!0},normalizeSimpleBranch=(branch)=>{let value=branch.trim(),changed=!0;while(changed===!0)if(changed=!1,/^@\([^\\()[\]{}|]+\)$/.test(value))value=value.slice(2,-1),changed=!0;if(!isPlainBranch(value))return;return value.replace(/\\(.)/g,"$1")},hasRepeatedCharPrefixOverlap=(branches)=>{let values=branches.map(normalizeSimpleBranch).filter(Boolean);for(let i=0;i<values.length;i++)for(let j=i+1;j<values.length;j++){let a=values[i],b=values[j],char=a[0];if(!char||a!==char.repeat(a.length)||b!==char.repeat(b.length))continue;if(a===b||a.startsWith(b)||b.startsWith(a))return!0}return!1},parseRepeatedExtglob=(pattern,requireEnd=!0)=>{if(pattern[0]!=="+"&&pattern[0]!=="*"||pattern[1]!=="(")return;let bracket=0,paren=0,quote=0,escaped=!1;for(let i=1;i<pattern.length;i++){let ch=pattern[i];if(escaped===!0){escaped=!1;continue}if(ch==="\\"){escaped=!0;continue}if(ch==='"'){quote=quote===1?0:1;continue}if(quote===1)continue;if(ch==="["){bracket++;continue}if(ch==="]"&&bracket>0){bracket--;continue}if(bracket>0)continue;if(ch==="("){paren++;continue}if(ch===")"){if(paren--,paren===0){if(requireEnd===!0&&i!==pattern.length-1)return;return{type:pattern[0],body:pattern.slice(2,i),end:i}}}}},getStarExtglobSequenceOutput=(pattern)=>{let index=0,chars=[];while(index<pattern.length){let match=parseRepeatedExtglob(pattern.slice(index),!1);if(!match||match.type!=="*")return;let branches=splitTopLevel(match.body).map((branch2)=>branch2.trim());if(branches.length!==1)return;let branch=normalizeSimpleBranch(branches[0]);if(!branch||branch.length!==1)return;chars.push(branch),index+=match.end+1}if(chars.length<1)return;return`${chars.length===1?utils.escapeRegex(chars[0]):`[${chars.map((ch)=>utils.escapeRegex(ch)).join("")}]`}*`},repeatedExtglobRecursion=(pattern)=>{let depth=0,value=pattern.trim(),match=parseRepeatedExtglob(value);while(match)depth++,value=match.body.trim(),match=parseRepeatedExtglob(value);return depth},analyzeRepeatedExtglob=(body,options)=>{if(options.maxExtglobRecursion===!1)return{risky:!1};let max=typeof options.maxExtglobRecursion==="number"?options.maxExtglobRecursion:constants5.DEFAULT_MAX_EXTGLOB_RECURSION,branches=splitTopLevel(body).map((branch)=>branch.trim());if(branches.length>1){if(branches.some((branch)=>branch==="")||branches.some((branch)=>/^[*?]+$/.test(branch))||hasRepeatedCharPrefixOverlap(branches))return{risky:!0}}for(let branch of branches){let safeOutput=getStarExtglobSequenceOutput(branch);if(safeOutput)return{risky:!0,safeOutput};if(repeatedExtglobRecursion(branch)>max)return{risky:!0}}return{risky:!1}},parse9=(input,options)=>{if(typeof input!=="string")throw TypeError("Expected a string");input=REPLACEMENTS[input]||input;let opts={...options},max=typeof opts.maxLength==="number"?Math.min(MAX_LENGTH,opts.maxLength):MAX_LENGTH,len=input.length;if(len>max)throw SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);let bos={type:"bos",value:"",output:opts.prepend||""},tokens=[bos],capture=opts.capture?"":"?:",PLATFORM_CHARS=constants5.globChars(opts.windows),EXTGLOB_CHARS=constants5.extglobChars(PLATFORM_CHARS),{DOT_LITERAL,PLUS_LITERAL,SLASH_LITERAL,ONE_CHAR,DOTS_SLASH,NO_DOT,NO_DOT_SLASH,NO_DOTS_SLASH,QMARK,QMARK_NO_DOT,STAR,START_ANCHOR}=PLATFORM_CHARS,globstar=(opts2)=>{return`(${capture}(?:(?!${START_ANCHOR}${opts2.dot?DOTS_SLASH:DOT_LITERAL}).)*?)`},nodot=opts.dot?"":NO_DOT,qmarkNoDot=opts.dot?QMARK:QMARK_NO_DOT,star=opts.bash===!0?globstar(opts):STAR;if(opts.capture)star=`(${star})`;if(typeof opts.noext==="boolean")opts.noextglob=opts.noext;let state2={input,index:-1,start:0,dot:opts.dot===!0,consumed:"",output:"",prefix:"",backtrack:!1,negated:!1,brackets:0,braces:0,parens:0,quotes:0,globstar:!1,tokens};input=utils.removePrefix(input,state2),len=input.length;let extglobs=[],braces=[],stack=[],prev=bos,value,eos=()=>state2.index===len-1,peek=state2.peek=(n=1)=>input[state2.index+n],advance=state2.advance=()=>input[++state2.index]||"",remaining=()=>input.slice(state2.index+1),consume=(value2="",num=0)=>{state2.consumed+=value2,state2.index+=num},append=(token)=>{state2.output+=token.output!=null?token.output:token.value,consume(token.value)},negate=()=>{let count2=1;while(peek()==="!"&&(peek(2)!=="("||peek(3)==="?"))advance(),state2.start++,count2++;if(count2%2===0)return!1;return state2.negated=!0,state2.start++,!0},increment=(type)=>{state2[type]++,stack.push(type)},decrement=(type)=>{state2[type]--,stack.pop()},push=(tok)=>{if(prev.type==="globstar"){let isBrace=state2.braces>0&&(tok.type==="comma"||tok.type==="brace"),isExtglob=tok.extglob===!0||extglobs.length&&(tok.type==="pipe"||tok.type==="paren");if(tok.type!=="slash"&&tok.type!=="paren"&&!isBrace&&!isExtglob)state2.output=state2.output.slice(0,-prev.output.length),prev.type="star",prev.value="*",prev.output=star,state2.output+=prev.output}if(extglobs.length&&tok.type!=="paren")extglobs[extglobs.length-1].inner+=tok.value;if(tok.value||tok.output)append(tok);if(prev&&prev.type==="text"&&tok.type==="text"){prev.output=(prev.output||prev.value)+tok.value,prev.value+=tok.value;return}tok.prev=prev,tokens.push(tok),prev=tok},extglobOpen=(type,value2)=>{let token={...EXTGLOB_CHARS[value2],conditions:1,inner:""};token.prev=prev,token.parens=state2.parens,token.output=state2.output,token.startIndex=state2.index,token.tokensIndex=tokens.length;let output=(opts.capture?"(":"")+token.open;increment("parens"),push({type,value:value2,output:state2.output?"":ONE_CHAR}),push({type:"paren",extglob:!0,value:advance(),output}),extglobs.push(token)},extglobClose=(token)=>{let literal4=input.slice(token.startIndex,state2.index+1),body=input.slice(token.startIndex+2,state2.index),analysis=analyzeRepeatedExtglob(body,opts);if((token.type==="plus"||token.type==="star")&&analysis.risky){let safeOutput=analysis.safeOutput?(token.output?"":ONE_CHAR)+(opts.capture?`(${analysis.safeOutput})`:analysis.safeOutput):void 0,open6=tokens[token.tokensIndex];open6.type="text",open6.value=literal4,open6.output=safeOutput||utils.escapeRegex(literal4);for(let i=token.tokensIndex+1;i<tokens.length;i++)tokens[i].value="",tokens[i].output="",delete tokens[i].suffix;state2.output=token.output+open6.output,state2.backtrack=!0,push({type:"paren",extglob:!0,value,output:""}),decrement("parens");return}let output=token.close+(opts.capture?")":""),rest;if(token.type==="negate"){let extglobStar=star;if(token.inner&&token.inner.length>1&&token.inner.includes("/"))extglobStar=globstar(opts);if(extglobStar!==star||eos()||/^\)+$/.test(remaining()))output=token.close=`)$))${extglobStar}`;if(token.inner.includes("*")&&(rest=remaining())&&/^\.[^\\/.]+$/.test(rest)){let expression=parse9(rest,{...options,fastpaths:!1}).output;output=token.close=`)${expression})${extglobStar})`}if(token.prev.type==="bos")state2.negatedExtglob=!0}push({type:"paren",extglob:!0,value,output}),decrement("parens")};if(opts.fastpaths!==!1&&!/(^[*!]|[/()[\]{}"])/.test(input)){let backslashes=!1,output=input.replace(REGEX_SPECIAL_CHARS_BACKREF,(m,esc3,chars,first,rest,index)=>{if(first==="\\")return backslashes=!0,m;if(first==="?"){if(esc3)return esc3+first+(rest?QMARK.repeat(rest.length):"");if(index===0)return qmarkNoDot+(rest?QMARK.repeat(rest.length):"");return QMARK.repeat(chars.length)}if(first===".")return DOT_LITERAL.repeat(chars.length);if(first==="*"){if(esc3)return esc3+first+(rest?star:"");return star}return esc3?m:`\\${m}`});if(backslashes===!0)if(opts.unescape===!0)output=output.replace(/\\/g,"");else output=output.replace(/\\+/g,(m)=>{return m.length%2===0?"\\\\":m?"\\":""});if(output===input&&opts.contains===!0)return state2.output=input,state2;return state2.output=utils.wrapOutput(output,state2,options),state2}while(!eos()){if(value=advance(),value==="\x00")continue;if(value==="\\"){let next=peek();if(next==="/"&&opts.bash!==!0)continue;if(next==="."||next===";")continue;if(!next){value+="\\",push({type:"text",value});continue}let match=/^\\+/.exec(remaining()),slashes=0;if(match&&match[0].length>2){if(slashes=match[0].length,state2.index+=slashes,slashes%2!==0)value+="\\"}if(opts.unescape===!0)value=advance();else value+=advance();if(state2.brackets===0){push({type:"text",value});continue}}if(state2.brackets>0&&(value!=="]"||prev.value==="["||prev.value==="[^")){if(opts.posix!==!1&&value===":"){let inner=prev.value.slice(1);if(inner.includes("[")){if(prev.posix=!0,inner.includes(":")){let idx=prev.value.lastIndexOf("["),pre=prev.value.slice(0,idx),rest2=prev.value.slice(idx+2),posix12=POSIX_REGEX_SOURCE[rest2];if(posix12){if(prev.value=pre+posix12,state2.backtrack=!0,advance(),!bos.output&&tokens.indexOf(prev)===1)bos.output=ONE_CHAR;continue}}}}if(value==="["&&peek()!==":"||value==="-"&&peek()==="]")value=`\\${value}`;if(value==="]"&&(prev.value==="["||prev.value==="[^"))value=`\\${value}`;if(opts.posix===!0&&value==="!"&&prev.value==="[")value="^";prev.value+=value,append({value});continue}if(state2.quotes===1&&value!=='"'){value=utils.escapeRegex(value),prev.value+=value,append({value});continue}if(value==='"'){if(state2.quotes=state2.quotes===1?0:1,opts.keepQuotes===!0)push({type:"text",value});continue}if(value==="("){increment("parens"),push({type:"paren",value});continue}if(value===")"){if(state2.parens===0&&opts.strictBrackets===!0)throw SyntaxError(syntaxError("opening","("));let extglob=extglobs[extglobs.length-1];if(extglob&&state2.parens===extglob.parens+1){extglobClose(extglobs.pop());continue}push({type:"paren",value,output:state2.parens?")":"\\)"}),decrement("parens");continue}if(value==="["){if(opts.nobracket===!0||!remaining().includes("]")){if(opts.nobracket!==!0&&opts.strictBrackets===!0)throw SyntaxError(syntaxError("closing","]"));value=`\\${value}`}else increment("brackets");push({type:"bracket",value});continue}if(value==="]"){if(opts.nobracket===!0||prev&&prev.type==="bracket"&&prev.value.length===1){push({type:"text",value,output:`\\${value}`});continue}if(state2.brackets===0){if(opts.strictBrackets===!0)throw SyntaxError(syntaxError("opening","["));push({type:"text",value,output:`\\${value}`});continue}decrement("brackets");let prevValue=prev.value.slice(1);if(prev.posix!==!0&&prevValue[0]==="^"&&!prevValue.includes("/"))value=`/${value}`;if(prev.value+=value,append({value}),opts.literalBrackets===!1||utils.hasRegexChars(prevValue))continue;let escaped=utils.escapeRegex(prev.value);if(state2.output=state2.output.slice(0,-prev.value.length),opts.literalBrackets===!0){state2.output+=escaped,prev.value=escaped;continue}prev.value=`(${capture}${escaped}|${prev.value})`,state2.output+=prev.value;continue}if(value==="{"&&opts.nobrace!==!0){increment("braces");let open6={type:"brace",value,output:"(",outputIndex:state2.output.length,tokensIndex:state2.tokens.length};braces.push(open6),push(open6);continue}if(value==="}"){let brace=braces[braces.length-1];if(opts.nobrace===!0||!brace){push({type:"text",value,output:value});continue}let output=")";if(brace.dots===!0){let arr=tokens.slice(),range=[];for(let i=arr.length-1;i>=0;i--){if(tokens.pop(),arr[i].type==="brace")break;if(arr[i].type!=="dots")range.unshift(arr[i].value)}output=expandRange(range,opts),state2.backtrack=!0}if(brace.comma!==!0&&brace.dots!==!0){let out=state2.output.slice(0,brace.outputIndex),toks=state2.tokens.slice(brace.tokensIndex);brace.value=brace.output="\\{",value=output="\\}",state2.output=out;for(let t of toks)state2.output+=t.output||t.value}push({type:"brace",value,output}),decrement("braces"),braces.pop();continue}if(value==="|"){if(extglobs.length>0)extglobs[extglobs.length-1].conditions++;push({type:"text",value});continue}if(value===","){let output=value,brace=braces[braces.length-1];if(brace&&stack[stack.length-1]==="braces")brace.comma=!0,output="|";push({type:"comma",value,output});continue}if(value==="/"){if(prev.type==="dot"&&state2.index===state2.start+1){state2.start=state2.index+1,state2.consumed="",state2.output="",tokens.pop(),prev=bos;continue}push({type:"slash",value,output:SLASH_LITERAL});continue}if(value==="."){if(state2.braces>0&&prev.type==="dot"){if(prev.value===".")prev.output=DOT_LITERAL;let brace=braces[braces.length-1];prev.type="dots",prev.output+=value,prev.value+=value,brace.dots=!0;continue}if(state2.braces+state2.parens===0&&prev.type!=="bos"&&prev.type!=="slash"){push({type:"text",value,output:DOT_LITERAL});continue}push({type:"dot",value,output:DOT_LITERAL});continue}if(value==="?"){if(!(prev&&prev.value==="(")&&opts.noextglob!==!0&&peek()==="("&&peek(2)!=="?"){extglobOpen("qmark",value);continue}if(prev&&prev.type==="paren"){let next=peek(),output=value;if(prev.value==="("&&!/[!=<:]/.test(next)||next==="<"&&!/<([!=]|\w+>)/.test(remaining()))output=`\\${value}`;push({type:"text",value,output});continue}if(opts.dot!==!0&&(prev.type==="slash"||prev.type==="bos")){push({type:"qmark",value,output:QMARK_NO_DOT});continue}push({type:"qmark",value,output:QMARK});continue}if(value==="!"){if(opts.noextglob!==!0&&peek()==="("){if(peek(2)!=="?"||!/[!=<:]/.test(peek(3))){extglobOpen("negate",value);continue}}if(opts.nonegate!==!0&&state2.index===0){negate();continue}}if(value==="+"){if(opts.noextglob!==!0&&peek()==="("&&peek(2)!=="?"){extglobOpen("plus",value);continue}if(prev&&prev.value==="("||opts.regex===!1){push({type:"plus",value,output:PLUS_LITERAL});continue}if(prev&&(prev.type==="bracket"||prev.type==="paren"||prev.type==="brace")||state2.parens>0){push({type:"plus",value});continue}push({type:"plus",value:PLUS_LITERAL});continue}if(value==="@"){if(opts.noextglob!==!0&&peek()==="("&&peek(2)!=="?"){push({type:"at",extglob:!0,value,output:""});continue}push({type:"text",value});continue}if(value!=="*"){if(value==="$"||value==="^")value=`\\${value}`;let match=REGEX_NON_SPECIAL_CHARS.exec(remaining());if(match)value+=match[0],state2.index+=match[0].length;push({type:"text",value});continue}if(prev&&(prev.type==="globstar"||prev.star===!0)){prev.type="star",prev.star=!0,prev.value+=value,prev.output=star,state2.backtrack=!0,state2.globstar=!0,consume(value);continue}let rest=remaining();if(opts.noextglob!==!0&&/^\([^?]/.test(rest)){extglobOpen("star",value);continue}if(prev.type==="star"){if(opts.noglobstar===!0){consume(value);continue}let prior=prev.prev,before=prior.prev,isStart=prior.type==="slash"||prior.type==="bos",afterStar=before&&(before.type==="star"||before.type==="globstar");if(opts.bash===!0&&(!isStart||rest[0]&&rest[0]!=="/")){push({type:"star",value,output:""});continue}let isBrace=state2.braces>0&&(prior.type==="comma"||prior.type==="brace"),isExtglob=extglobs.length&&(prior.type==="pipe"||prior.type==="paren");if(!isStart&&prior.type!=="paren"&&!isBrace&&!isExtglob){push({type:"star",value,output:""});continue}while(rest.slice(0,3)==="/**"){let after=input[state2.index+4];if(after&&after!=="/")break;rest=rest.slice(3),consume("/**",3)}if(prior.type==="bos"&&eos()){prev.type="globstar",prev.value+=value,prev.output=globstar(opts),state2.output=prev.output,state2.globstar=!0,consume(value);continue}if(prior.type==="slash"&&prior.prev.type!=="bos"&&!afterStar&&eos()){state2.output=state2.output.slice(0,-(prior.output+prev.output).length),prior.output=`(?:${prior.output}`,prev.type="globstar",prev.output=globstar(opts)+(opts.strictSlashes?")":"|$)"),prev.value+=value,state2.globstar=!0,state2.output+=prior.output+prev.output,consume(value);continue}if(prior.type==="slash"&&prior.prev.type!=="bos"&&rest[0]==="/"){let end=rest[1]!==void 0?"|$":"";state2.output=state2.output.slice(0,-(prior.output+prev.output).length),prior.output=`(?:${prior.output}`,prev.type="globstar",prev.output=`${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`,prev.value+=value,state2.output+=prior.output+prev.output,state2.globstar=!0,consume(value+advance()),push({type:"slash",value:"/",output:""});continue}if(prior.type==="bos"&&rest[0]==="/"){prev.type="globstar",prev.value+=value,prev.output=`(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`,state2.output=prev.output,state2.globstar=!0,consume(value+advance()),push({type:"slash",value:"/",output:""});continue}state2.output=state2.output.slice(0,-prev.output.length),prev.type="globstar",prev.output=globstar(opts),prev.value+=value,state2.output+=prev.output,state2.globstar=!0,consume(value);continue}let token={type:"star",value,output:star};if(opts.bash===!0){if(token.output=".*?",prev.type==="bos"||prev.type==="slash")token.output=nodot+token.output;push(token);continue}if(prev&&(prev.type==="bracket"||prev.type==="paren")&&opts.regex===!0){token.output=value,push(token);continue}if(state2.index===state2.start||prev.type==="slash"||prev.type==="dot"){if(prev.type==="dot")state2.output+=NO_DOT_SLASH,prev.output+=NO_DOT_SLASH;else if(opts.dot===!0)state2.output+=NO_DOTS_SLASH,prev.output+=NO_DOTS_SLASH;else state2.output+=nodot,prev.output+=nodot;if(peek()!=="*")state2.output+=ONE_CHAR,prev.output+=ONE_CHAR}push(token)}while(state2.brackets>0){if(opts.strictBrackets===!0)throw SyntaxError(syntaxError("closing","]"));state2.output=utils.escapeLast(state2.output,"["),decrement("brackets")}while(state2.parens>0){if(opts.strictBrackets===!0)throw SyntaxError(syntaxError("closing",")"));state2.output=utils.escapeLast(state2.output,"("),decrement("parens")}while(state2.braces>0){if(opts.strictBrackets===!0)throw SyntaxError(syntaxError("closing","}"));state2.output=utils.escapeLast(state2.output,"{"),decrement("braces")}if(opts.strictSlashes!==!0&&(prev.type==="star"||prev.type==="bracket"))push({type:"maybe_slash",value:"",output:`${SLASH_LITERAL}?`});if(state2.backtrack===!0){state2.output="";for(let token of state2.tokens)if(state2.output+=token.output!=null?token.output:token.value,token.suffix)state2.output+=token.suffix}return state2};parse9.fastpaths=(input,options)=>{let opts={...options},max=typeof opts.maxLength==="number"?Math.min(MAX_LENGTH,opts.maxLength):MAX_LENGTH,len=input.length;if(len>max)throw SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);input=REPLACEMENTS[input]||input;let{DOT_LITERAL,SLASH_LITERAL,ONE_CHAR,DOTS_SLASH,NO_DOT,NO_DOTS,NO_DOTS_SLASH,STAR,START_ANCHOR}=constants5.globChars(opts.windows),nodot=opts.dot?NO_DOTS:NO_DOT,slashDot=opts.dot?NO_DOTS_SLASH:NO_DOT,capture=opts.capture?"":"?:",state2={negated:!1,prefix:""},star=opts.bash===!0?".*?":STAR;if(opts.capture)star=`(${star})`;let globstar=(opts2)=>{if(opts2.noglobstar===!0)return star;return`(${capture}(?:(?!${START_ANCHOR}${opts2.dot?DOTS_SLASH:DOT_LITERAL}).)*?)`},create=(str)=>{switch(str){case"*":return`${nodot}${ONE_CHAR}${star}`;case".*":return`${DOT_LITERAL}${ONE_CHAR}${star}`;case"*.*":return`${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;case"*/*":return`${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;case"**":return nodot+globstar(opts);case"**/*":return`(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;case"**/*.*":return`(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;case"**/.*":return`(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;default:{let match=/^(.*?)\.(\w+)$/.exec(str);if(!match)return;let source2=create(match[1]);if(!source2)return;return source2+DOT_LITERAL+match[2]}}},output=utils.removePrefix(input,state2),source=create(output);if(source&&opts.strictSlashes!==!0)source+=`${SLASH_LITERAL}?`;return source};module.exports=parse9});var require_picomatch=__commonJS((exports,module)=>{var scan=require_scan(),parse9=require_parse(),utils=require_utils(),constants5=require_constants(),isObject3=(val)=>val&&typeof val==="object"&&!Array.isArray(val),picomatch=(glob,options,returnState=!1)=>{if(Array.isArray(glob)){let fns=glob.map((input)=>picomatch(input,options,returnState));return(str)=>{for(let isMatch of fns){let state3=isMatch(str);if(state3)return state3}return!1}}let isState=isObject3(glob)&&glob.tokens&&glob.input;if(glob===""||typeof glob!=="string"&&!isState)throw TypeError("Expected pattern to be a non-empty string");let opts=options||{},posix12=opts.windows,regex=isState?picomatch.compileRe(glob,options):picomatch.makeRe(glob,options,!1,!0),state2=regex.state;delete regex.state;let isIgnored=()=>!1;if(opts.ignore){let ignoreOpts={...options,ignore:null,onMatch:null,onResult:null};isIgnored=picomatch(opts.ignore,ignoreOpts,returnState)}let matcher=(input,returnObject=!1)=>{let{isMatch,match,output}=picomatch.test(input,regex,options,{glob,posix:posix12}),result={glob,state:state2,regex,posix:posix12,input,output,match,isMatch};if(typeof opts.onResult==="function")opts.onResult(result);if(isMatch===!1)return result.isMatch=!1,returnObject?result:!1;if(isIgnored(input)){if(typeof opts.onIgnore==="function")opts.onIgnore(result);return result.isMatch=!1,returnObject?result:!1}if(typeof opts.onMatch==="function")opts.onMatch(result);return returnObject?result:!0};if(returnState)matcher.state=state2;return matcher};picomatch.test=(input,regex,options,{glob,posix:posix12}={})=>{if(typeof input!=="string")throw TypeError("Expected input to be a string");if(input==="")return{isMatch:!1,output:""};let opts=options||{},format=opts.format||(posix12?utils.toPosixSlashes:null),match=input===glob,output=match&&format?format(input):input;if(match===!1)output=format?format(input):input,match=output===glob;if(match===!1||opts.capture===!0)if(opts.matchBase===!0||opts.basename===!0)match=picomatch.matchBase(input,regex,options,posix12);else match=regex.exec(output);return{isMatch:Boolean(match),match,output}};picomatch.matchBase=(input,glob,options)=>{return(glob instanceof RegExp?glob:picomatch.makeRe(glob,options)).test(utils.basename(input))};picomatch.isMatch=(str,patterns,options)=>picomatch(patterns,options)(str);picomatch.parse=(pattern,options)=>{if(Array.isArray(pattern))return pattern.map((p)=>picomatch.parse(p,options));return parse9(pattern,{...options,fastpaths:!1})};picomatch.scan=(input,options)=>scan(input,options);picomatch.compileRe=(state2,options,returnOutput=!1,returnState=!1)=>{if(returnOutput===!0)return state2.output;let opts=options||{},prepend=opts.contains?"":"^",append=opts.contains?"":"$",source=`${prepend}(?:${state2.output})${append}`;if(state2&&state2.negated===!0)source=`^(?!${source}).*$`;let regex=picomatch.toRegex(source,options);if(returnState===!0)regex.state=state2;return regex};picomatch.makeRe=(input,options={},returnOutput=!1,returnState=!1)=>{if(!input||typeof input!=="string")throw TypeError("Expected a non-empty string");let parsed={negated:!1,fastpaths:!0};if(options.fastpaths!==!1&&(input[0]==="."||input[0]==="*"))parsed.output=parse9.fastpaths(input,options);if(!parsed.output)parsed=parse9(input,options);return picomatch.compileRe(parsed,options,returnOutput,returnState)};picomatch.toRegex=(source,options)=>{try{let opts=options||{};return new RegExp(source,opts.flags||(opts.nocase?"i":""))}catch(err){if(options&&options.debug===!0)throw err;return/$^/}};picomatch.constants=constants5;module.exports=picomatch});var require_picomatch2=__commonJS((exports,module)=>{var pico=require_picomatch(),utils=require_utils();function picomatch(glob,options,returnState=!1){if(options&&(options.windows===null||options.windows===void 0))options={...options,windows:utils.isWindows()};return pico(glob,options,returnState)}Object.assign(picomatch,pico);module.exports=picomatch});var QuickLRU;var init_quick_lru=__esm(()=>{QuickLRU=class QuickLRU extends Map{#size=0;#cache=new Map;#oldCache=new Map;#maxSize;#maxAge;#onEviction;constructor(options={}){super();if(!(options.maxSize&&options.maxSize>0))throw TypeError("`maxSize` must be a number greater than 0");if(typeof options.maxAge==="number"&&options.maxAge===0)throw TypeError("`maxAge` must be a number greater than 0");this.#maxSize=options.maxSize,this.#maxAge=options.maxAge||Number.POSITIVE_INFINITY,this.#onEviction=options.onEviction}get __oldCache(){return this.#oldCache}#emitEvictions(cache2){if(typeof this.#onEviction!=="function")return;for(let[key,item]of cache2)this.#onEviction(key,item.value)}#deleteIfExpired(key,item){if(typeof item.expiry==="number"&&item.expiry<=Date.now()){if(typeof this.#onEviction==="function")this.#onEviction(key,item.value);return this.delete(key)}return!1}#getOrDeleteIfExpired(key,item){if(this.#deleteIfExpired(key,item)===!1)return item.value}#getItemValue(key,item){return item.expiry?this.#getOrDeleteIfExpired(key,item):item.value}#peek(key,cache2){let item=cache2.get(key);return this.#getItemValue(key,item)}#set(key,value){if(this.#cache.set(key,value),this.#size++,this.#size>=this.#maxSize)this.#size=0,this.#emitEvictions(this.#oldCache),this.#oldCache=this.#cache,this.#cache=new Map}#moveToRecent(key,item){this.#oldCache.delete(key),this.#set(key,item)}*#entriesAscending(){for(let item of this.#oldCache){let[key,value]=item;if(!this.#cache.has(key)){if(this.#deleteIfExpired(key,value)===!1)yield item}}for(let item of this.#cache){let[key,value]=item;if(this.#deleteIfExpired(key,value)===!1)yield item}}get(key){if(this.#cache.has(key)){let item=this.#cache.get(key);return this.#getItemValue(key,item)}if(this.#oldCache.has(key)){let item=this.#oldCache.get(key);if(this.#deleteIfExpired(key,item)===!1)return this.#moveToRecent(key,item),item.value}}set(key,value,{maxAge=this.#maxAge}={}){let expiry=typeof maxAge==="number"&&maxAge!==Number.POSITIVE_INFINITY?Date.now()+maxAge:void 0;if(this.#cache.has(key))this.#cache.set(key,{value,expiry});else this.#set(key,{value,expiry});return this}has(key){if(this.#cache.has(key))return!this.#deleteIfExpired(key,this.#cache.get(key));if(this.#oldCache.has(key))return!this.#deleteIfExpired(key,this.#oldCache.get(key));return!1}peek(key){if(this.#cache.has(key))return this.#peek(key,this.#cache);if(this.#oldCache.has(key))return this.#peek(key,this.#oldCache)}expiresIn(key){let item=this.#cache.get(key)??this.#oldCache.get(key);if(item)return item.expiry?item.expiry-Date.now():Number.POSITIVE_INFINITY}delete(key){let deleted=this.#cache.delete(key);if(deleted)this.#size--;return this.#oldCache.delete(key)||deleted}clear(){this.#cache.clear(),this.#oldCache.clear(),this.#size=0}resize(newSize){if(!(newSize&&newSize>0))throw TypeError("`maxSize` must be a number greater than 0");let items=[...this.#entriesAscending()],removeCount=items.length-newSize;if(removeCount<0)this.#cache=new Map(items),this.#oldCache=new Map,this.#size=items.length;else{if(removeCount>0)this.#emitEvictions(items.slice(0,removeCount));this.#oldCache=new Map(items.slice(removeCount)),this.#cache=new Map,this.#size=0}this.#maxSize=newSize}evict(count2=1){let requested=Number(count2);if(!requested||requested<=0)return;let items=[...this.#entriesAscending()],evictCount=Math.trunc(Math.min(requested,Math.max(items.length-1,0)));if(evictCount<=0)return;this.#emitEvictions(items.slice(0,evictCount)),this.#oldCache=new Map(items.slice(evictCount)),this.#cache=new Map,this.#size=0}*keys(){for(let[key]of this)yield key}*values(){for(let[,value]of this)yield value}*[Symbol.iterator](){for(let item of this.#cache){let[key,value]=item;if(this.#deleteIfExpired(key,value)===!1)yield[key,value.value]}for(let item of this.#oldCache){let[key,value]=item;if(!this.#cache.has(key)){if(this.#deleteIfExpired(key,value)===!1)yield[key,value.value]}}}*entriesDescending(){let items=[...this.#cache];for(let i=items.length-1;i>=0;--i){let item=items[i],[key,value]=item;if(this.#deleteIfExpired(key,value)===!1)yield[key,value.value]}items=[...this.#oldCache];for(let i=items.length-1;i>=0;--i){let item=items[i],[key,value]=item;if(!this.#cache.has(key)){if(this.#deleteIfExpired(key,value)===!1)yield[key,value.value]}}}*entriesAscending(){for(let[key,value]of this.#entriesAscending())yield[key,value.value]}get size(){if(!this.#size)return this.#oldCache.size;let oldCacheSize=0;for(let key of this.#oldCache.keys())if(!this.#cache.has(key))oldCacheSize++;return Math.min(this.#size+oldCacheSize,this.#maxSize)}get maxSize(){return this.#maxSize}get maxAge(){return this.#maxAge}entries(){return this.entriesAscending()}forEach(callbackFunction,thisArgument=this){for(let[key,value]of this.entriesAscending())callbackFunction.call(thisArgument,value,key,this)}get[Symbol.toStringTag](){return"QuickLRU"}toString(){return`QuickLRU(${this.size}/${this.maxSize})`}[Symbol.for("nodejs.util.inspect.custom")](){return this.toString()}}});function classifyFile(filePath){let normalized=filePath.toLowerCase().replace(/\\/g,"/");if(normalized.endsWith(".wasm")||normalized.startsWith("dist/")||normalized.includes("/dist/")||normalized.startsWith("build/")||normalized.includes("/build/")||normalized.includes(".swarm/checkpoints/"))return{filePath,zone:"generated",confidence:"high",reason:"path matches generated file patterns"};if(normalized.includes("/test/")||normalized.includes("/tests/")||normalized.includes("/__tests__/")||normalized.includes(".test.")||normalized.includes(".spec.")||normalized.includes("/mocks/"))return{filePath,zone:"test",confidence:"high",reason:"path matches test/**, tests/**, __tests__/**, *.test.*, *.spec.*, or **/mocks/**"};if(normalized.includes("/scripts/")||normalized.includes("makefile")||normalized.includes("dockerfile")||normalized.includes(".github/"))return{filePath,zone:"build",confidence:"high",reason:"path matches build scripts or CI configuration"};if(normalized.endsWith(".json")&&!normalized.includes(".github/")||normalized.endsWith(".yaml")&&!normalized.includes(".github/")||normalized.endsWith(".yml")&&!normalized.includes(".github/")||normalized.endsWith(".toml")||normalized.includes(".env")||normalized.endsWith("biome.json")||normalized.endsWith("tsconfig.json"))return{filePath,zone:"config",confidence:"high",reason:"extension is config file type"};if(normalized.includes("/docs/")||normalized.endsWith(".md")&&!normalized.includes("/")||normalized.includes("readme")||normalized.includes("changelog")||normalized.includes("license"))return{filePath,zone:"docs",confidence:"high",reason:"path matches docs/** or documentation files"};if(normalized.includes("/src/")||normalized.includes("/lib/"))return{filePath,zone:"production",confidence:"high",reason:"path matches src/** or lib/**"};return{filePath,zone:"production",confidence:"medium",reason:"default classification"}}function sampleForHash(input){if(input.length<=HASH_INPUT_CAP_BYTES)return`${input.length}:${input}`;let half=Math.floor(HASH_INPUT_CAP_BYTES/2),head=input.slice(0,half),tail=input.slice(input.length-half);return`${input.length}:${head}${tail}`}function boundedBunHash(input){return bunHash(sampleForHash(input))}function coarseObjectDiscriminator(args2){try{let obj=args2,keys=Object.keys(obj).sort(),parts=keys.map((key)=>{let value=obj[key],type=typeof value,sample;if(value===null)sample="null";else if(Array.isArray(value))sample=`arr${value.length}`;else if(type==="object")sample=`obj${Object.keys(value).length}`;else if(type==="string"){let s=value;sample=s.length<=32?s:`len${s.length}`}else sample=String(value);return`${key}:${type}:${sample}`});return`${Array.isArray(args2)?`arr${keys.length}`:`obj${keys.length}`}|${parts.join(",")}`}catch{return"unknown"}}var HASH_INPUT_CAP_BYTES=65536;var init_arg_hash=__esm(()=>{init_bun_compat()});function stableCanonicalStringify(value){if(value===void 0)return"null";if(value===null)return"null";if(typeof value!=="object")return JSON.stringify(value);if(Array.isArray(value))return`[${value.map((el)=>stableCanonicalStringify(el)).join(",")}]`;let obj=value;return`{${Object.keys(obj).sort().map((k)=>`${JSON.stringify(k)}:${stableCanonicalStringify(obj[k])}`).join(",")}}`}import{execFileSync}from"node:child_process";import*as fsSync9 from"node:fs";import*as path87 from"node:path";function hashArgs(args2){try{if(typeof args2!=="object"||args2===null)return 0;let stable=stableCanonicalStringify(args2);return Number(boundedBunHash(stable))}catch(error93){return log("[Guardrails] hashArgs failed",{error:error93 instanceof Error?error93.message:String(error93)}),Number(boundedBunHash(coarseObjectDiscriminator(args2)))}}function gitEnvWithoutRepoRedirectors(){let env={...process.env};return delete env.GIT_DIR,delete env.GIT_WORK_TREE,delete env.GIT_INDEX_FILE,delete env.GIT_COMMON_DIR,env}function parseWorktreeListPorcelain(output){let records=[];for(let line of output.split(`
|
|
1001
1001
|
`)){if(line.startsWith("worktree ")){let wtPath=line.slice(9).trim();if(wtPath)records.push({path:wtPath,attributes:new Set});continue}let record3=records[records.length-1];if(!record3)continue;let separator=line.indexOf(" "),attribute=separator===-1?line:line.slice(0,separator);if(attribute)record3.attributes.add(attribute)}return records}function canonicalizeWindowsPathNative(p){if(process.platform!=="win32")return p;try{let native=fsSync9.realpathSync.native(p);return native.startsWith(String.fromCharCode(92,92,63,92))?native.slice(4):native}catch{return}}function canonicalizeWindowsPathTailTolerant(p){if(process.platform!=="win32")return p;let tail=[],probe2=p;for(;;){let native=canonicalizeWindowsPathNative(probe2);if(native!==void 0)return tail.length===0?native:path87.join(native,...tail.reverse());let parent=path87.dirname(probe2);if(parent===probe2)return p;tail.push(path87.basename(probe2)),probe2=parent}}function isValidWorktreeRecord(repoRootRecord,record3){if(record3===repoRootRecord)try{return fsSync9.statSync(path87.join(record3.path,".git")).isDirectory()}catch{return!1}if(record3.attributes.has("bare"))return!1;let dotGitPath=path87.join(record3.path,".git"),dotGitStat;try{dotGitStat=fsSync9.lstatSync(dotGitPath)}catch{return!1}if(!dotGitStat.isFile())return!1;let gitDirLine;try{gitDirLine=fsSync9.readFileSync(dotGitPath,"utf8").trim()}catch{return!1}if(!gitDirLine.startsWith("gitdir:"))return!1;let gitDirRef=gitDirLine.slice(7).trim();if(!gitDirRef)return!1;let gitDirPath=path87.isAbsolute(gitDirRef)?gitDirRef:path87.resolve(record3.path,gitDirRef),registrationGitdirFile;try{registrationGitdirFile=fsSync9.realpathSync(path87.join(gitDirPath,"gitdir"))}catch{return!1}if(repoRootRecord){let worktreesRoot;try{worktreesRoot=path87.join(fsSync9.realpathSync(path87.join(repoRootRecord.path,".git")),"worktrees")}catch{return!1}if(!isPathIdentityWithin(registrationGitdirFile,worktreesRoot))return!1}let backReference;try{backReference=fsSync9.readFileSync(registrationGitdirFile,"utf8").trim()}catch{return!1}try{return pathIdentitiesEqual(fsSync9.realpathSync(dotGitPath),fsSync9.realpathSync(backReference))}catch{return!1}}function getLinkedGitWorktrees(dir){let cached3=gitWorktreeCache.get(dir);if(cached3!==void 0)return cached3;let worktrees=[];try{let output=execFileSync(resolveGitExecutable(),["worktree","list","--porcelain"],{cwd:dir,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1500,maxBuffer:4194304,windowsHide:!0,env:gitEnvWithoutRepoRedirectors()}),records=parseWorktreeListPorcelain(output),repoRootRecord=records[0];for(let record3 of records){if(!isValidWorktreeRecord(repoRootRecord,record3))continue;let native=canonicalizeWindowsPathNative(record3.path);if(native===void 0)continue;worktrees.push(native)}}catch{}return gitWorktreeCache.set(dir,worktrees),worktrees}function normalizePathWithCache(filePath,cwd){let cacheKey=`${cwd}:${filePath}`,cached3=pathNormalizationCache.get(cacheKey);if(cached3!==void 0)return cached3;try{let absolutePath=path87.isAbsolute(filePath)?filePath:path87.resolve(cwd,filePath),normalized=fsSync9.realpathSync(absolutePath);return pathNormalizationCache.set(cacheKey,normalized),normalized}catch{let fallback=path87.isAbsolute(filePath)?filePath:path87.resolve(cwd,filePath);return pathNormalizationCache.set(cacheKey,fallback),fallback}}function getGlobMatcher(pattern,caseInsensitive=!0){let cacheKey=`${caseInsensitive?"nocase":"case"}\x00${pattern}`,cached3=globMatcherCache.get(cacheKey);if(cached3!==void 0)return cached3;try{let matcher=import_picomatch.default(pattern,{dot:!0,nocase:caseInsensitive});return globMatcherCache.set(cacheKey,matcher),matcher}catch(err){return warn(`picomatch error for pattern "${pattern}": ${err}`),()=>!1}}function checkWriteTargetForSymlink(targetPath,cwd){let normalizedCwd=path87.resolve(cwd),normalizedTarget=path87.resolve(cwd,targetPath),ancestors=[],current=normalizedTarget;while(!0){let rel=path87.relative(normalizedCwd,current);if(rel===""||rel===".."||rel.startsWith(`..${path87.sep}`)||path87.isAbsolute(rel))break;ancestors.push(current);let parent=path87.dirname(current);if(parent===current)break;current=parent}for(let ancestor of ancestors){let stat10=null;try{stat10=fsSync9.lstatSync(ancestor)}catch(err){if(err.code==="ENOENT")continue;return`WRITE BLOCKED: lstat failed on "${ancestor}": ${String(err)} — refusing write on unverifiable path`}if(stat10.isSymbolicLink())return`WRITE BLOCKED: "${ancestor}" is a symlink/junction — writing through a symlink or junction could redirect the write outside the working directory`}return null}function matchesAuthorityDenyPrefix(candidate,prefix,cwd,flavor=getPathFlavor()){let pathImpl=flavor==="win32"?path87.win32:path87.posix,normalizeInput=(value)=>flavor==="win32"?value.replace(/\//g,"\\"):value,normalizedPrefixInput=normalizeInput(prefix),requiresComponentBoundary=normalizedPrefixInput.endsWith(pathImpl.sep),root=pathImpl.resolve(normalizeInput(cwd)),target=pathImpl.resolve(root,normalizeInput(candidate)),denied=pathImpl.resolve(root,normalizedPrefixInput);if(!isPathIdentityWithin(target,root,flavor)||!isPathIdentityWithin(denied,root,flavor))return!1;let identity=(value)=>flavor==="win32"?value.toLowerCase():value,targetIdentity=identity(target),deniedIdentity=identity(denied);return requiresComponentBoundary?targetIdentity===deniedIdentity||targetIdentity.startsWith(`${deniedIdentity}${pathImpl.sep}`):targetIdentity.startsWith(deniedIdentity)}function buildEffectiveRules(authorityConfig){if(authorityConfig?.enabled===!1||!authorityConfig?.rules)return{...DEFAULT_AGENT_AUTHORITY_RULES};let entries=Object.entries(authorityConfig.rules);if(entries.length===0)return{...DEFAULT_AGENT_AUTHORITY_RULES};let merged={...DEFAULT_AGENT_AUTHORITY_RULES};for(let[agent,userRule]of entries){let normalizedRuleKey=agent.toLowerCase(),existing=merged[normalizedRuleKey]??{};merged[normalizedRuleKey]={...existing,...userRule,readOnly:userRule.readOnly??existing.readOnly,blockedExact:userRule.blockedExact??existing.blockedExact,allowedExact:userRule.allowedExact??existing.allowedExact,blockedPrefix:userRule.blockedPrefix??existing.blockedPrefix,allowedPrefix:userRule.allowedPrefix??existing.allowedPrefix,blockedZones:userRule.blockedZones??existing.blockedZones,blockedGlobs:userRule.blockedGlobs??existing.blockedGlobs,allowedGlobs:userRule.allowedGlobs??existing.allowedGlobs,allowedCaseSensitiveGlobs:userRule.allowedCaseSensitiveGlobs??existing.allowedCaseSensitiveGlobs}}return merged}function isOnDifferentFilesystemRoot(targetAbsolute,cwdAbsolute,pathLib=path87){let flavor=pathLib===path87.win32||pathLib.parse("C:\\probe").root!==""?"win32":"posix";return isOnDifferentPathRoot(targetAbsolute,cwdAbsolute,flavor)}function denyAuthority(agent,normalizedPath,input){let safeAgent=sanitizeDiagnosticText(agent,96),safePath=sanitizeDiagnosticText(normalizedPath,320),safeDetail=sanitizeDiagnosticText(input.detail,640);return{allowed:!1,code:input.code,layer:input.layer,rule:sanitizeDiagnosticText(input.rule,128),path:safePath,agent:safeAgent,reason:sanitizeDiagnosticText(`${input.code}: Path blocked: ${safeDetail} [agent=${safeAgent}; path=${safePath}]`,1024),recovery:input.recovery,zone:input.zone}}function formatAllowedHints(rules){let fmt=(items)=>{if(!items||items.length===0)return"(none)";if(items.length<=MAX_ALLOWED_HINT_ENTRIES)return items.join(", ");let omitted=items.length-MAX_ALLOWED_HINT_ENTRIES;return`${items.slice(0,MAX_ALLOWED_HINT_ENTRIES).join(", ")}, … (+${omitted} more)`},parts=[];if(rules.allowedExact&&rules.allowedExact.length>0)parts.push(`Allowed exact paths: ${fmt(rules.allowedExact)}`);if(parts.push(`Allowed prefixes: ${fmt(rules.allowedPrefix)}`),parts.push(`Allowed globs: ${fmt(rules.allowedGlobs)}`),rules.allowedCaseSensitiveGlobs&&rules.allowedCaseSensitiveGlobs.length>0)parts.push(`Allowed case-sensitive globs: ${fmt(rules.allowedCaseSensitiveGlobs)}`);return parts.push("Block rules (blocked zones/prefixes/globs/exact) and universal deny paths still apply."),parts.join(" ")}function checkFileAuthorityWithRules(agentName,filePath,cwd,effectiveRules,options={}){let normalizedAgent=agentName.toLowerCase(),strippedAgent=stripKnownSwarmPrefix(agentName).toLowerCase(),dir=cwd||process.cwd(),unsafePathReason=unsafePathTextReason(filePath);if(unsafePathReason)return denyAuthority(agentName,filePath,{code:"AUTHORITY_INVALID_PATH",layer:"path-validation",rule:"safe-path-text",detail:unsafePathReason});let normalizedPath,resolvedTarget;try{let normalizedWithSymlinks=normalizePathWithCache(filePath,dir);resolvedTarget=path87.resolve(dir,normalizedWithSymlinks),normalizedPath=path87.relative(dir,resolvedTarget).replace(/\\/g,"/")}catch{resolvedTarget=path87.resolve(dir,filePath),normalizedPath=path87.relative(dir,resolvedTarget).replace(/\\/g,"/")}let effectiveDir=dir,nativeTarget2=canonicalizeWindowsPathTailTolerant(resolvedTarget),matchWorktreeRoot=()=>{let worktrees=getLinkedGitWorktrees(dir),best;for(let wt of worktrees){let relToWt=path87.relative(wt,nativeTarget2).replace(/\\/g,"/");if(relToWt!==".."&&!relToWt.startsWith("../")&&!isOnDifferentFilesystemRoot(nativeTarget2,wt)){if(!best||wt.length>best.wt.length)best={wt,rel:relToWt}}}if(best)effectiveDir=best.wt,normalizedPath=best.rel;return best?.wt},findPlantedLinkBelow=(root)=>{let ancestors=[],current=nativeTarget2;while(!0){let rel=path87.relative(root,current);if(rel===""||rel===".."||rel.startsWith(`..${path87.sep}`)||path87.isAbsolute(rel))break;ancestors.push(current);let parent=path87.dirname(current);if(parent===current)break;current=parent}for(let ancestor of ancestors)try{if(fsSync9.lstatSync(ancestor).isSymbolicLink())return ancestor}catch(err){if(err.code==="ENOENT")continue;return ancestor}return null};if(isOnDifferentFilesystemRoot(resolvedTarget,dir)){let matchedWorktree=matchWorktreeRoot();if(!matchedWorktree)return denyAuthority(agentName,normalizedPath,{code:"AUTHORITY_ROOT_ESCAPE",layer:"containment",rule:"same-filesystem-root",detail:"target is on a different drive or filesystem root"});let plantedLink=findPlantedLinkBelow(matchedWorktree);if(plantedLink)return denyAuthority(agentName,normalizedPath,{code:"AUTHORITY_ROOT_ESCAPE",layer:"containment",rule:"workspace-containment",detail:`re-rooted target crosses symlink/junction "${plantedLink}" inside the matched worktree`})}else if(normalizedPath===".."||normalizedPath.startsWith("../")){let matchedWorktree=matchWorktreeRoot();if(!matchedWorktree)return denyAuthority(agentName,normalizedPath,{code:"AUTHORITY_ROOT_ESCAPE",layer:"containment",rule:"workspace-containment",detail:"target resolves outside the working directory"});let plantedLink=findPlantedLinkBelow(matchedWorktree);if(plantedLink)return denyAuthority(agentName,normalizedPath,{code:"AUTHORITY_ROOT_ESCAPE",layer:"containment",rule:"workspace-containment",detail:`re-rooted target crosses symlink/junction "${plantedLink}" inside the matched worktree`})}let classifiedRules=effectiveRules[normalizedAgent]??effectiveRules[strippedAgent],unclassifiedWhileDisabled=!classifiedRules&&options.authorityEnabled===!1&&normalizedAgent!=="unknown",rules=classifiedRules??(unclassifiedWhileDisabled?{}:void 0);if(!rules)return denyAuthority(agentName,normalizedPath,{code:"AUTHORITY_UNKNOWN_AGENT",layer:"role-capability",rule:"known-agent-role",detail:"Unknown agent: no authority classification exists"});let flavor=getPathFlavor(),matchesPathPrefix=(candidate,prefix)=>isPathIdentityWithin(path87.resolve(effectiveDir,candidate),path87.resolve(effectiveDir,prefix),flavor),matchesGlob=(glob)=>getGlobMatcher(glob)(normalizedPath);for(let prefix of options.universalDenyPrefixes??[])if(matchesAuthorityDenyPrefix(normalizedPath,prefix,effectiveDir,flavor))return denyAuthority(agentName,normalizedPath,{code:"AUTHORITY_UNIVERSAL_DENY",layer:"universal-deny",rule:`universal:${prefix}`,detail:`target is under universal deny prefix ${prefix}`});let isCoderAgent=normalizedAgent==="coder"||strippedAgent==="coder";if(isCoderAgent&&isPolicyProtectedPath(normalizedPath,{includeDefaults:!1,additional:[".git",".swarm"]}))return denyAuthority(agentName,normalizedPath,{code:"AUTHORITY_PROTECTED_PATH",layer:"protected-path",rule:"coder-control-state-protection",detail:"coder writes to repository control state (.git/.swarm) are always protected"});if(unclassifiedWhileDisabled&&isPolicyProtectedPath(normalizedPath,{includeDefaults:!1,additional:[".git",".swarm"]}))return denyAuthority(agentName,normalizedPath,{code:"AUTHORITY_PROTECTED_PATH",layer:"protected-path",rule:"unclassified-agent-control-state-protection",detail:"unclassified agent writes to repository control state (.git/.swarm) are always protected"});if(Object.hasOwn(AUTHORITY_ROLE_CAPABILITIES,strippedAgent)){let matchedVerifier=[...BUILT_IN_VERIFIER_CONFIG_GLOBS,...options.verifierConfigPaths??[]].find(matchesGlob);if(matchedVerifier)return denyAuthority(agentName,normalizedPath,{code:"AUTHORITY_VERIFIER_CONFIG",layer:"protected-path",rule:`verifier-config:${matchedVerifier}`,detail:`Path blocked (glob ${matchedVerifier}): swarm roles cannot write verifier-owned configuration in the config zone`})}let canonicalCapability=AUTHORITY_ROLE_CAPABILITIES[strippedAgent];if(canonicalCapability==="read-only"||canonicalCapability==="dedicated-tool-only")return denyAuthority(agentName,normalizedPath,{code:"AUTHORITY_ROLE_READ_ONLY",layer:"role-capability",rule:`role-capability:${canonicalCapability}`,detail:canonicalCapability==="dedicated-tool-only"?"role may mutate state only through dedicated tools":"agent role is read-only"});if(rules.readOnly)return denyAuthority(agentName,normalizedPath,{code:"AUTHORITY_ROLE_READ_ONLY",layer:"role-capability",rule:"role-policy:read-only",detail:"agent role is read-only"});if(isCoderAgent&&options.declaredScope!=null&&options.declaredScope.length>0&&isPathWithinDeclaredScope(normalizedPath,options.declaredScope,effectiveDir))return{allowed:!0,layer:"declared-scope",path:sanitizeDiagnosticText(normalizedPath,320),agent:sanitizeDiagnosticText(agentName,96)};if(options.authorityEnabled===!1)return{allowed:!0,layer:"role-policy",path:sanitizeDiagnosticText(normalizedPath,320),agent:sanitizeDiagnosticText(agentName,96)};if(rules.blockedExact){for(let blocked of rules.blockedExact)if(pathIdentitiesEqual(normalizedPath,blocked,flavor))return denyAuthority(agentName,normalizedPath,{code:"AUTHORITY_POLICY_DENY",layer:"role-policy",rule:`blockedExact:${blocked}`,detail:`path is blocked by exact role policy ${blocked}`,recovery:isCoderAgent?"declare_scope":void 0})}if(rules.blockedGlobs&&rules.blockedGlobs.length>0){for(let glob of rules.blockedGlobs)if(matchesGlob(glob))return denyAuthority(agentName,normalizedPath,{code:"AUTHORITY_POLICY_DENY",layer:"role-policy",rule:`blockedGlob:${glob}`,detail:`Path blocked (glob ${glob}) by role policy`,recovery:isCoderAgent?"declare_scope":void 0})}if(rules.allowedExact&&rules.allowedExact.length>0){if(rules.allowedExact.some((allowed)=>pathIdentitiesEqual(normalizedPath,allowed,flavor)))return{allowed:!0,layer:"role-policy",path:normalizedPath,agent:agentName}}if(rules.blockedZones&&rules.blockedZones.length>0){let{zone}=classifyFile(normalizedPath);if(rules.blockedZones.includes(zone))return denyAuthority(agentName,normalizedPath,{code:"AUTHORITY_POLICY_DENY",layer:"role-policy",rule:`blockedZone:${zone}`,detail:`path is in ${zone} zone`,recovery:isCoderAgent?"declare_scope":void 0,zone})}if(rules.allowedGlobs&&rules.allowedGlobs.length>0){if(rules.allowedGlobs.some(matchesGlob))return{allowed:!0,layer:"role-policy",path:normalizedPath,agent:agentName}}if(rules.allowedCaseSensitiveGlobs&&rules.allowedCaseSensitiveGlobs.length>0){if(rules.allowedCaseSensitiveGlobs.some((glob)=>{return getGlobMatcher(glob,!1)(normalizedPath)}))return{allowed:!0,layer:"role-policy",path:normalizedPath,agent:agentName}}if(rules.blockedPrefix&&rules.blockedPrefix.length>0){for(let prefix of rules.blockedPrefix)if(matchesPathPrefix(normalizedPath,prefix))return denyAuthority(agentName,normalizedPath,{code:"AUTHORITY_POLICY_DENY",layer:"role-policy",rule:`blockedPrefix:${prefix}`,detail:`path is under blocked role prefix ${prefix}`,recovery:isCoderAgent?"declare_scope":void 0})}if(rules.allowedPrefix!=null&&rules.allowedPrefix.length>0){if(!rules.allowedPrefix.some((prefix)=>matchesPathPrefix(normalizedPath,prefix)))return denyAuthority(agentName,normalizedPath,{code:"AUTHORITY_POLICY_DENY",layer:"role-policy",rule:"allowedPrefix",detail:`path is not in allowed list for this role. ${formatAllowedHints(rules)}`,recovery:isCoderAgent?"declare_scope":void 0})}else if(rules.allowedPrefix!=null&&rules.allowedPrefix.length===0)return denyAuthority(agentName,normalizedPath,{code:"AUTHORITY_POLICY_DENY",layer:"role-policy",rule:"allowedPrefix:empty",detail:`path is not in allowed list because the role allowlist is empty. ${formatAllowedHints(rules)}`,recovery:isCoderAgent?"declare_scope":void 0});return{allowed:!0,layer:"role-policy",path:normalizedPath,agent:agentName}}function checkFileAuthority(agentName,filePath,cwd,authorityConfig,options={}){return checkFileAuthorityWithRules(agentName,filePath,cwd,buildEffectiveRules(authorityConfig),{...options,authorityEnabled:authorityConfig?.enabled??options.authorityEnabled,universalDenyPrefixes:authorityConfig?.universal_deny_prefixes??options.universalDenyPrefixes,verifierConfigPaths:authorityConfig?.verifier_config_paths??options.verifierConfigPaths})}var import_picomatch,pathNormalizationCache,globMatcherCache,GIT_WORKTREE_CACHE_MAX_AGE_MS=60000,gitWorktreeCache,AUTHORITY_ROLE_CAPABILITIES,NON_WRITING_SWARM_RULES,DEFAULT_AGENT_AUTHORITY_RULES,BUILT_IN_VERIFIER_CONFIG_GLOBS,MAX_ALLOWED_HINT_ENTRIES=20;var init_file_authority=__esm(()=>{init_quick_lru();init_schema();init_core_events();init_path_identity();init_protected_path_policy();init_utils();init_arg_hash();init_git_executable();import_picomatch=__toESM(require_picomatch2(),1);pathNormalizationCache=new QuickLRU({maxSize:500}),globMatcherCache=new QuickLRU({maxSize:200}),gitWorktreeCache=new QuickLRU({maxSize:50,maxAge:GIT_WORKTREE_CACHE_MAX_AGE_MS});AUTHORITY_ROLE_CAPABILITIES={architect:"direct-write",coder:"direct-write",reviewer:"direct-write",critic:"direct-write",critic_oversight:"dedicated-tool-only",critic_finding_validator:"dedicated-tool-only",explorer:"read-only",sme:"read-only",researcher:"read-only",test_engineer:"direct-write",docs:"direct-write",docs_design:"direct-write",designer:"direct-write",critic_sounding_board:"read-only",critic_drift_verifier:"read-only",critic_hallucination_verifier:"read-only",critic_architecture_supervisor:"read-only",curator_init:"dedicated-tool-only",curator_phase:"dedicated-tool-only",curator_postmortem:"dedicated-tool-only",curator_consolidation:"dedicated-tool-only",council_generalist:"read-only",council_skeptic:"read-only",council_domain_expert:"read-only",skill_improver:"dedicated-tool-only",spec_writer:"dedicated-tool-only"},NON_WRITING_SWARM_RULES=Object.fromEntries(Object.entries(AUTHORITY_ROLE_CAPABILITIES).filter(([,capability])=>capability==="read-only"||capability==="dedicated-tool-only").map(([agent])=>[agent,{readOnly:!0}])),DEFAULT_AGENT_AUTHORITY_RULES={build:{},plan:{},general:{},explore:{},...NON_WRITING_SWARM_RULES,architect:{blockedExact:[".swarm/plan.md",".swarm/plan.json"],blockedZones:["generated","config"],blockedGlobs:["**/oxlintrc*","**/.oxlintrc*","**/.eslintrc*","**/eslint.config.*","**/.prettierrc*","**/prettier.config.*","**/biome.jsonc","**/.secretscanignore","**/.golangci*"]},coder:{blockedPrefix:[".swarm/"],blockedZones:["generated","config"]},reviewer:{blockedExact:[".swarm/plan.md",".swarm/plan.json"],blockedPrefix:["src/"],allowedPrefix:[".swarm/evidence/",".swarm/outputs/"],blockedZones:["generated"]},explorer:{readOnly:!0},sme:{readOnly:!0},test_engineer:{blockedExact:[".swarm/plan.md",".swarm/plan.json"],blockedPrefix:["src/"],allowedPrefix:["tests/","test/",".swarm/evidence/"],allowedGlobs:["**/tests/**","**/test/**","**/__tests__/**","**/*.test.*","**/*.spec.*","test_*.py","**/test_*.py","*_test.py","**/*_test.py","*_test.go","**/*_test.go","*_spec.rb","**/*_spec.rb","*.Tests.ps1","**/*.Tests.ps1"],allowedCaseSensitiveGlobs:["*Test.java","**/*Test.java","*Test.kt","**/*Test.kt","*Tests.cs","**/*Tests.cs"],blockedZones:["generated"]},docs:{allowedPrefix:["docs/",".swarm/outputs/"],allowedGlobs:["**/docs/**","**/*.md","**/*.mdx","**/*.rst"],blockedZones:["generated"]},docs_design:{allowedPrefix:["docs/",".swarm/outputs/"],blockedGlobs:["src/**","lib/**"],allowedGlobs:["**/docs/**","**/*.md","**/*.mdx","**/*.rst","**/reference/traceability.json"],blockedZones:["generated"]},designer:{allowedPrefix:["docs/",".swarm/outputs/"],allowedGlobs:["**/docs/**","**/*.md","**/*.mdx","**/*.rst"],blockedZones:["generated"]},critic:{allowedPrefix:[".swarm/evidence/"],blockedZones:["generated"]}};BUILT_IN_VERIFIER_CONFIG_GLOBS=["**/oxlintrc*","**/.oxlintrc*","**/.eslintrc*","**/eslint.config.*","**/.prettierrc*","**/prettier.config.*","**/biome.json","**/biome.jsonc","**/tsconfig*.json","**/.secretscanignore","**/.golangci*"]});import{createHash as createHash40}from"node:crypto";import*as fs55 from"node:fs";import*as path88 from"node:path";function fingerprint(filePath,budget){try{let stat10=fs55.lstatSync(filePath);if(stat10.isSymbolicLink())return{kind:"unsafe"};if(!stat10.isFile())return{kind:"unsafe"};if(stat10.size>MAX_HASH_BYTES||stat10.size>budget.remaining)return{kind:"unsafe"};budget.remaining-=stat10.size;let result={kind:"file",size:stat10.size,mtimeMs:stat10.mtimeMs};return result.hash=createHash40("sha256").update(fs55.readFileSync(filePath)).digest("hex"),result}catch(error93){return error93.code==="ENOENT"?{kind:"missing"}:{kind:"unsafe"}}}function changed(before,after){if(before.kind==="unsafe"||after.kind==="unsafe")return!1;if(before.kind!==after.kind)return!0;if(before.kind==="missing")return!1;if(before.hash!==void 0||after.hash!==void 0)return before.hash!==after.hash;return before.size!==after.size||before.mtimeMs!==after.mtimeMs}function effectFor(tool3,args2,targetCount){if(targetCount!==1||!args2||typeof args2!=="object")return{};let record3=args2;if(tool3==="write"||tool3==="create_file"){for(let key of["content","file_text","text"])if(typeof record3[key]==="string")return{exactContent:record3[key]}}if(tool3==="edit"||tool3==="replace"){for(let key of["newString","new_string","replacement"])if(typeof record3[key]==="string"&&record3[key]!=="")return{containsText:record3[key]}}return{}}function matchesExpected(filePath,expected,budget){if(expected.exactContent===void 0&&expected.containsText===void 0)return!0;try{let stat10=fs55.statSync(filePath);if(!stat10.isFile()||stat10.size>MAX_HASH_BYTES||stat10.size>budget.remaining)return!1;budget.remaining-=stat10.size;let content=fs55.readFileSync(filePath,"utf8");if(expected.exactContent!==void 0)return content===expected.exactContent;return content.includes(expected.containsText??"")}catch{return!1}}function numericExitCodes(metadata){if(!metadata||typeof metadata!=="object")return[];let record3=metadata;return["exitCode","exit_code","exit"].map((key)=>record3[key]).filter((value)=>typeof value==="number")}function directSuccess(output){let text=typeof output.output==="string"?output.output.trim():"",metadata=output.metadata&&typeof output.metadata==="object"?output.metadata:null;if(numericExitCodes(output.metadata).some((code)=>code!==0))return!1;if(metadata?.success===!0)return!0;if(metadata&&typeof metadata.status==="string"&&["success","completed","ok","applied"].includes(metadata.status.toLowerCase()))return!0;try{let parsed=JSON.parse(text);if(parsed.success===!0&&parsed.dryRun!==!0)return!0}catch{}return/^(?:Wrote file successfully\.|Edit applied successfully\.|Done!|Patch applied successfully\.|File (?:created|updated) successfully\.)/i.test(text)}function successful(tool3,output){if(tool3==="bash"||tool3==="shell"){let exitCodes=numericExitCodes(output.metadata);return exitCodes.length>0&&exitCodes.every((code)=>code===0)}return directSuccess(output)}function createScopeLeaseRenewalTracker(refresh=refreshScopeBindingLease,now=Date.now){let candidates=new Map,candidateKey=(sessionID,callID)=>`${sessionID}\x00${callID}`,sweep=()=>{let cutoff=now()-CANDIDATE_TTL_MS;for(let[key,candidate]of candidates)if(candidate.createdAt<cutoff)candidates.delete(key);while(candidates.size>=MAX_CANDIDATES2){let oldest=candidates.keys().next().value;if(oldest===void 0)break;candidates.delete(oldest)}};return{remember(input){sweep();let binding=input.binding;if(binding.activation!=="active"||binding.lifecycleState!=="live"||binding.expiresAt<=now()||binding.ownerSessionId!==input.sessionID||input.targets.length===0||input.targets.length>MAX_TARGETS)return;let uniqueTargets=[...new Set(input.targets.map((target)=>path88.resolve(target)))];if(uniqueTargets.length===0||uniqueTargets.length>MAX_TARGETS)return;let expected=effectFor(input.tool,input.args,uniqueTargets.length),hashBudget={remaining:MAX_AGGREGATE_HASH_BYTES},targets=uniqueTargets.map((target)=>({path:target,before:fingerprint(target,hashBudget),expected}));if(targets.some((target)=>target.before.kind==="unsafe"))return;candidates.set(candidateKey(input.sessionID,input.callID),{createdAt:now(),callID:input.callID,sessionID:input.sessionID,tool:input.tool,directory:input.directory,bindingId:binding.bindingId,generationId:binding.generationId,expectedRevision:binding.revision,taskId:binding.taskId,targets})},async consume(input){let key=candidateKey(input.sessionID,input.callID),candidate=candidates.get(key);if(candidates.delete(key),!candidate||candidate.sessionID!==input.sessionID||candidate.tool!==input.tool||now()-candidate.createdAt>CANDIDATE_TTL_MS||!input.output||!successful(candidate.tool,input.output))return null;let hashBudget={remaining:MAX_AGGREGATE_HASH_BYTES},contentBudget={remaining:MAX_AGGREGATE_HASH_BYTES};for(let target of candidate.targets){let after=fingerprint(target.path,hashBudget);if(!changed(target.before,after)||!matchesExpected(target.path,target.expected,contentBudget))return null}return refresh({directory:candidate.directory,bindingId:candidate.bindingId,generationId:candidate.generationId,expectedRevision:candidate.expectedRevision,activeSessionId:candidate.sessionID,taskId:candidate.taskId})}}}var MAX_CANDIDATES2=256,MAX_TARGETS=256,MAX_HASH_BYTES=4194304,MAX_AGGREGATE_HASH_BYTES=8388608,CANDIDATE_TTL_MS=600000;var init_scope_lease_renewal=__esm(()=>{init_scope_persistence()});function resolveAgentConflict(input){let session=swarmState.agentSessions.get(input.sessionID);if(!session)return;let rejections=input.rejectionCount??0,resolutionPath,taskId=input.taskId??"unknown",conflictDedupeKey=`conflict:${taskId}:${rejections}`;if(rejections>=3)resolutionPath="soundingboard",pushAdvisory(session,`[${conflictDedupeKey}] CONFLICT ESCALATION (rejections=${rejections}): ${input.sourceAgent} vs ${input.targetAgent} on task ${taskId}. Three or more failed cycles detected. Route to Critic in SOUNDING_BOARD mode, then simplify before any user escalation.`,{dedupeKey:conflictDedupeKey});else resolutionPath="self_resolve",pushAdvisory(session,`[${conflictDedupeKey}] CONFLICT DETECTED (rejections=${rejections}): ${input.sourceAgent} disagrees with ${input.targetAgent} on task ${taskId}. Attempt self-resolution using .swarm/plan.md, .swarm/spec.md, and .swarm/context.md before escalation.`,{dedupeKey:conflictDedupeKey});let event={type:"agent_conflict_detected",timestamp:new Date().toISOString(),sessionId:input.sessionID,phase:input.phase,taskId:input.taskId,sourceAgent:input.sourceAgent,targetAgent:input.targetAgent,conflictType:input.conflictType,resolutionPath,summary:input.summary};emit("agent_conflict_detected",event)}var init_conflict_resolution=__esm(()=>{init_state();init_telemetry()});import{createHash as createHash41}from"node:crypto";import*as fs56 from"node:fs";import*as path89 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,file3){if(file3.includes("\x00")||hasControlCharacter(file3))return null;let root=path89.resolve(directory),absolute=path89.resolve(root,file3),relative23=path89.relative(root,absolute).replaceAll("\\","/");if(!relative23||relative23===".."||relative23.startsWith("../")||path89.isAbsolute(relative23))return null;return relative23}function isWithinRoot2(root,candidate){let relative23=path89.relative(root,candidate);return relative23===""||relative23!==".."&&!relative23.startsWith(`..${path89.sep}`)&&!path89.isAbsolute(relative23)}function deletedPathIsContained(canonicalRoot,absolute){let current=path89.dirname(absolute);for(;;){try{let canonical=_internals83.realpathSync(current);return canonicalRoot===canonical||isWithinRoot2(canonicalRoot,canonical)}catch(error93){if(error93.code!=="ENOENT")return!1}let parent=path89.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,file3,options={}){if(typeof directory!=="string"||typeof file3!=="string")return{kind:"capture_failed",file:typeof file3==="string"?file3:"",code:"invalid_request",retryable:!1};if(file3.includes("\x00")||hasControlCharacter(file3))return{kind:"capture_failed",file:file3,code:"invalid_request",retryable:!1};let normalized=normalizedProjectFile(directory,file3);if(!normalized)return{kind:"capture_failed",file:file3,code:"outside_workspace",retryable:!1};let canonicalRoot,canonicalParent,absolute=path89.resolve(directory,normalized);try{canonicalRoot=_internals83.realpathSync(path89.resolve(directory))}catch{return{kind:"capture_failed",file:normalized,code:"outside_workspace",retryable:!1}}try{canonicalParent=_internals83.realpathSync(path89.dirname(absolute))}catch(error93){if(error93.code==="ENOENT"){let secondObservation=null,secondFailed=!1;try{secondObservation=_internals83.realpathSync(path89.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 _internals83.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:error93.code}}if(!isWithinRoot2(canonicalRoot,canonicalParent))return{kind:"capture_failed",file:normalized,code:"outside_workspace",retryable:!1};let before;try{before=_internals83.lstat(absolute)}catch(error93){if(error93.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:error93.code}}if(before.isSymbolicLink())return{kind:"capture_failed",file:normalized,code:"symlink_or_reparse",retryable:!1};try{let canonicalTarget=_internals83.realpathSync(absolute);if(!isWithinRoot2(canonicalRoot,canonicalTarget)||path89.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=fs56.constants.O_RDONLY|(process.platform==="win32"?0:fs56.constants.O_NOFOLLOW),beforeBigInt;try{beforeBigInt=_internals83.lstat(absolute,{bigint:!0})}catch{return{kind:"capture_failed",file:normalized,code:"file_changed_during_capture",retryable:!0}}let fd;try{fd=_internals83.open(absolute,openFlags)}catch(error93){let code=error93.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=_internals83.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 hash4=createHash41("sha256"),chunk=Buffer.alloc(REVIEWER_SCOPE_CAPTURE_CHUNK_BYTES),totalBytes=0;for(;;){if(options.deadlineAt!==void 0&&_internals83.now()>options.deadlineAt)return{kind:"capture_failed",file:normalized,code:"capture_deadline",retryable:!0};let bytesRead;try{bytesRead=_internals83.read(fd,chunk,0,chunk.byteLength,null)}catch(error93){let code=error93.code;return{kind:"capture_failed",file:normalized,code:"unreadable",retryable:!1,detail:code}}if(bytesRead===0)break;totalBytes+=bytesRead,hash4.update(bytesRead===chunk.byteLength?chunk:chunk.subarray(0,bytesRead))}let openedAfter=_internals83.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=_internals83.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=_internals83.realpathSync(absolute)}catch{return{kind:"capture_failed",file:normalized,code:"file_changed_during_capture",retryable:!0}}if(!isWithinRoot2(canonicalRoot,canonicalAfterRead)||path89.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:hash4.digest("hex")}}finally{if(fd!==void 0)try{_internals83.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,_internals83;var init_reviewer_scope_file_fingerprint=__esm(()=>{_internals83={open:fs56.openSync,fstat:(fd,options)=>fs56.fstatSync(fd,options),read:fs56.readSync,close:fs56.closeSync,lstat:fs56.lstatSync,stat:(path90,options)=>fs56.statSync(path90,options),realpathSync:fs56.realpathSync,now:Date.now}});function classifyTaskResult(output){if(!output||typeof output!=="object")return"non_success";let record3=output,nestedRecords=[record3.metadata,record3.result].filter((candidate)=>typeof candidate==="object"&&candidate!==null),records=[record3,...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 record3.output==="string")return"success";return Object.keys(record3).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_state()});import*as fs57 from"node:fs";import*as path90 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);_internals84.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(tool3,args2){if(!isTaskToolId(tool3??""))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=fs57.readFileSync(path90.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(count2){return`EXECUTION STALL: ${count2} 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(count2,normalizedTool){return`EXECUTION_STALL: ${count2} 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:tool3,args:args2,callID,options}=params;try{if(options?.enabled===!1)return;if(!isArchitectStallSession(sessionID))return;let now=_internals84.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(tool3,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:tool3,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(tool3??"");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 _internals84.changedFilesSinceSnapshotAsync(directory,baseline):null,current=await _internals84.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:tool3,callID,args:args2,output,directory,options}=params;try{let dispatchRole=takeDispatchRole(callID);if(options?.enabled===!1)return;if(!isArchitectStallSession(sessionID))return;let normalizedTool=normalizeToolNameLowerCase(tool3??""),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=_internals84.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&&_internals84.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 _internals84.captureWorkspaceSnapshotAsync(directory)}catch{state2.workspaceBaseline=null}return}if(state2.callsSinceWorkspaceProbe<WORKSPACE_PROBE_EVERY_CALLS)return;if(state2.callsSinceWorkspaceProbe=0,_internals84.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,_internals84;var init_execution_stall=__esm(()=>{init_workspace_snapshot();init_constants();init_schema();init_state();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;_internals84={now:()=>Date.now(),captureWorkspaceSnapshotAsync,changedFilesSinceSnapshotAsync,ensureArchitectSession,readPlanOpenTaskState}});import*as path91 from"node:path";function isConfigFilePath(filePath,cwd,extraGlobs){let normalized=path91.relative(path91.resolve(cwd),path91.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=path91.resolve(directory,".swarm"),resolved=path91.resolve(directory,filePath),relative24=path91.relative(swarmDir,resolved);return relative24.startsWith("..")||path91.isAbsolute(relative24)}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,config3){let budget=config3.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_SESSIONS2){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_SESSIONS2=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)}function isStickyModelError(signal){return MODEL_UNAVAILABLE_PATTERN.test(signal)||isQuotaError(signal)}var TRANSIENT_STATUS_CODES,TRANSIENT_MODEL_ERROR_PATTERN,MODEL_UNAVAILABLE_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|model.?unavailable|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,MODEL_UNAVAILABLE_PATTERN=/model.?unavailable/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(set3,key){if(set3.has(key))return!1;while(set3.size>=MAX_TRACKED_MODEL_IDENTITIES){let oldest=set3.values().next().value;if(oldest===void 0)break;set3.delete(oldest)}return set3.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),_internals85.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,_internals85,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"};_internals85={observeResolution:observeModelLimitResolution};invalidOverrideReports=new Set});function rememberCountedAssistantMsg(map3,sessionId,messageId){map3.delete(sessionId),map3.set(sessionId,messageId);while(map3.size>MAX_TRACKED_COUNTED_ASSISTANT_MSGS){let stalest=map3.keys().next().value;if(stalest===void 0)break;map3.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(`
|
|
1002
1002
|
`)}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(error93){log("[Guardrails] behavioral guidance replacement failed",{error:error93 instanceof Error?error93.message:String(error93)})}}}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 count2=(consecutiveNoToolTurns.get(sessionId)??0)+1;consecutiveNoToolTurns.set(sessionId,count2);let maxTurns=cfg.runaway_output_max_turns;if(count2>=maxTurns){let stopCarrier=ensureGuidanceCarrier(messages,"guardrails");if(!messageTextOf(stopCarrier).includes("RUNAWAY OUTPUT STOP"))prependGuidanceText(stopCarrier,"guardrails",`[RUNAWAY OUTPUT STOP]
|
|
1003
1003
|
You have produced ${count2} consecutive responses without using any tools. You MUST call a tool in your next response.
|
|
@@ -1195,7 +1195,7 @@ ${line}`)}else{let prefix=fileEndsWithNewline2(filePath)?"":`
|
|
|
1195
1195
|
`;break;case"destructive_block":case"sandbox_wrap":case"sandbox_skip":{let command=truncateUtf8Safe(redactShellCommand(entry.command),maxCommand);line=`${JSON.stringify({...entry,command,commandHash:hashRedactedCommand(command)})}
|
|
1196
1196
|
`;break}case"file_write":line=`${JSON.stringify({...entry,path:redactPath(entry.path),reason:truncateUtf8Safe(redactEmbeddedPaths(entry.reason),maxReason),resolvedScope:redactPath(entry.resolvedScope)})}
|
|
1197
1197
|
`;break;case"scope_violation":line=`${JSON.stringify({...entry,path:redactPath(entry.path),declaredScope:redactPath(entry.declaredScope),resolvedScope:redactPath(entry.resolvedScope)})}
|
|
1198
|
-
`;break}try{appendShellAuditLineSync(ctx.directory,line)}catch(error93){log("guardrail audit: append failed",{directory:ctx.directory,error:error93})}}var SHELL_AUDIT_FIELD_CLASSES,REQUIRED_STRING_FIELDS;var init_audit_log=__esm(()=>{init_logger();init_helpers();init_shell_audit_store();SHELL_AUDIT_FIELD_CLASSES=Object.freeze({ts:"timestamp",sessionID:"identifier",agent:"identifier",tool:"identifier",type:"decision-type",command:"redacted-command",commandHash:"content-hash",path:"redacted-path",reason:"free-text-redacted",resolvedScope:"redacted-path",declaredScope:"redacted-path",action:"enum",destructiveCategory:"enum",executorMechanism:"enum",skipReason:"enum"}),REQUIRED_STRING_FIELDS=["ts","sessionID","agent","tool","type"]});import*as fsSync10 from"node:fs";import*as os14 from"node:os";import*as path101 from"node:path";import{fileURLToPath as fileURLToPath3}from"node:url";function readPackageName(dir){try{let manifestPath=path101.join(dir,"package.json");if(!_internals91.existsSync(manifestPath))return null;let name=JSON.parse(_internals91.readFileSync(manifestPath,"utf-8"))?.name;return typeof name==="string"?name:null}catch{return null}}function resolvePackageRoot(){if(cachedPackageRoot!==void 0)return cachedPackageRoot.root;let root=null;try{let dir=path101.dirname(fileURLToPath3(_internals91.moduleUrl()));for(let depth=0;depth<MAX_PACKAGE_ROOT_WALK_DEPTH;depth++){if(readPackageName(dir)==="opencode-swarm"){root=dir;break}let parent=path101.dirname(dir);if(parent===dir)break;dir=parent}}catch{root=null}return cachedPackageRoot={root},root}function isSelfDevelopmentWorkspace(directory){if(!directory)return!1;let resolved;try{resolved=canonicalRootKeyFresh(directory)}catch{return!1}let cached3=selfDevelopmentWorkspaces.get(resolved);if(cached3!==void 0)return cached3;let isSelfDev=readPackageName(resolved)==="opencode-swarm";if(selfDevelopmentWorkspaces.size>=MAX_CACHED_WORKSPACE_ROOTS){let oldest=selfDevelopmentWorkspaces.keys().next().value;if(oldest!==void 0)selfDevelopmentWorkspaces.delete(oldest)}return selfDevelopmentWorkspaces.set(resolved,isSelfDev),isSelfDev}function comparablePath(value){return process.platform==="win32"?value.toLowerCase():value}function isInsidePackageRoot(root,target){try{let rel=path101.relative(comparablePath(root),comparablePath(target));if(rel==="")return!0;if(rel.startsWith(".."))return!1;return!path101.isAbsolute(rel)}catch{return!1}}function expandHome(candidate){if(!candidate.startsWith("~"))return candidate;let home=_internals91.homedir();if(!home)return null;let rest=candidate.slice(1).replace(/^[\\/]/,"");return rest?path101.join(home,rest):home}function extractGuardedPathCandidates(normalizedTool,args2){let argsObj=args2??{},raw=[];if(normalizedTool==="bash"||normalizedTool==="shell"){let command=typeof argsObj.command==="string"?argsObj.command.slice(0,MAX_SCANNED_COMMAND_LENGTH):void 0;if(command){let matcher=new RegExp(SHELL_PATH_CANDIDATE_PATTERN.source,SHELL_PATH_CANDIDATE_PATTERN.flags);for(let match of command.matchAll(matcher)){let token=match[1];if(token&&token.length>1)raw.push(token);if(raw.length>=MAX_SHELL_PATH_CANDIDATES)break}}}else for(let key2 of SCALAR_PATH_KEYS2){let value=argsObj[key2];if(typeof value==="string"&&value.length>0)raw.push(value)}let resolved=[];for(let candidate of raw){let expanded=expandHome(candidate);if(!expanded)continue;if(!path101.isAbsolute(expanded))continue;try{resolved.push(path101.resolve(expanded))}catch{}}return resolved}function enforceInternalsGuard(params){let{sessionID,tool:tool3,args:args2,directory,options}=params;if(options?.enabled===!1)return;let normalizedTool=normalizeToolNameLowerCase(tool3??"");if(!GUARDED_TOOLS.has(normalizedTool))return;let match=null,relativeTarget="";try{let packageRoot=_internals91.resolvePackageRoot();if(!packageRoot)return;if(_internals91.isSelfDevelopmentWorkspace(directory))return;if(directory&&isInsidePackageRoot(packageRoot,path101.resolve(directory)))return;for(let candidate of extractGuardedPathCandidates(normalizedTool,args2))if(isInsidePackageRoot(packageRoot,candidate)){match=candidate,relativeTarget=path101.relative(packageRoot,candidate).replace(/\\/g,"/")||"<package root>";break}}catch{return}if(!match)return;try{telemetry.swarmInternalsReadDenied(sessionID,normalizedTool,relativeTarget)}catch{}throw Error(SWARM_INTERNALS_DENIAL_MESSAGE)}var SWARM_INTERNALS_DENIAL_MESSAGE="SWARM_INTERNALS_OFF_LIMITS: the swarm plugin's installed files are never the fix for a gate error. Fix the dispatch/state the error names, or report the blocker to the user.",GUARDED_TOOLS,SCALAR_PATH_KEYS2,MAX_PACKAGE_ROOT_WALK_DEPTH=12,MAX_CACHED_WORKSPACE_ROOTS=32,SHELL_PATH_CANDIDATE_PATTERN,MAX_SHELL_PATH_CANDIDATES=64,MAX_SCANNED_COMMAND_LENGTH=8192,cachedPackageRoot,selfDevelopmentWorkspaces,_internals91;var init_internals_guard=__esm(()=>{init_telemetry();init_canonical_root();init_normalize_tool_name();GUARDED_TOOLS=new Set(["read","glob","grep","bash","shell"]),SCALAR_PATH_KEYS2=["filePath","file_path","path","file","target"],SHELL_PATH_CANDIDATE_PATTERN=/(?:^|[\s'"`;|&<>()=,])((?:~|[A-Za-z]:)?[\\/][^\s'"`;|&<>()]*)/g,selfDevelopmentWorkspaces=new Map;_internals91={moduleUrl:()=>import.meta.url,existsSync:(p)=>fsSync10.existsSync(p),readFileSync:(p,enc)=>fsSync10.readFileSync(p,enc),homedir:()=>os14.homedir(),resolvePackageRoot,isSelfDevelopmentWorkspace,resetCaches:()=>{cachedPackageRoot=void 0,selfDevelopmentWorkspaces.clear()}}});import*as fs63 from"node:fs";import*as path102 from"node:path";function normalizeSandboxMechanism2(mechanism){return mechanism.toLowerCase().replace(/[^a-z0-9]+/g,"")}function pluginOwnsExecutorEnv(mechanism){if(mechanism.startsWith("native-runner/"))return!0;switch(mechanism){case"sandbox-exec":case"powershell-wrapper":case"Bubblewrap":return!0;default:return!1}}function throwDestructiveBlock(destructiveCategory,message){throw new DestructiveCommandBlockedError(message,destructiveCategory)}function resolveWindowsWriteAuthority(tool3,command,detectedShellType,shaped,platform=process.platform){let cmdWrapper=CMD_WRAPPER_DECLARATION.test(command),psWrapper=declaresWindowsWrapperLoose(command),inheritedWindows=detectedShellType==="powershell"||detectedShellType==="cmd";if(cmdWrapper)return"cmd";if(psWrapper||shaped)return"powershell";if(inheritedWindows&&!(tool3==="bash"||tool3==="shell"&&platform!=="win32"))return detectedShellType;return null}function createToolBeforeHandler(ctx){let{effectiveDirectory,cfg,precomputedAuthorityRules,universalDenyPrefixes,shellAuditEnabled,interpreterAllowedAgents,authorityConfig,consecutiveNoToolTurns,worktreeBaseDirOverrides,getSandboxExecutor,assessSandboxEnforcement:assessSandboxEnforcement2,rememberReviewerScopeWrite,rememberScopeLeaseCandidate}=ctx,enforcePolicy=ctx.enforcePolicy!==!1;setMacOSSandboxPolicy(cfg.sandbox_macos_enabled??!1);let executionStallOptions={enabled:cfg.enabled,warnCalls:cfg.execution_stall_warn_calls,stopCalls:cfg.execution_stall_stop_calls,episodeMinutes:cfg.execution_stall_episode_minutes},internalsGuardOptions={enabled:cfg.enabled},sessionWorkspaceDirectory=(sessionID)=>resolveSessionWorkspaceDirectory(sessionID,effectiveDirectory);function resolveActiveScopeBinding(sessionID){let session=swarmState.agentSessions.get(sessionID),taskId=session?.currentTaskId??null,bindingDirectory=sessionWorkspaceDirectory(sessionID),resolution=taskId?resolveAuthorizedScopeBindingDetailed({directory:bindingDirectory,taskId,activeSessionId:sessionID}):resolveAuthorizedScopeBindingForSessionDetailed({directory:bindingDirectory,activeSessionId:sessionID}),binding=resolution.status==="found"?resolution.binding:null;if(!binding){let diagnostic=formatScopeResolutionDiagnostic({resolution,taskId,sessionId:sessionID});if(diagnostic)throw Error(diagnostic)}if(!taskId&&binding&&session)session.currentTaskId=binding.taskId,session.declaredCoderScope=[...binding.files];return binding}function resolveActiveScopeBindingObserving(sessionID){try{return resolveActiveScopeBinding(sessionID)}catch{return null}}function resolveDeclaredScope(sessionID,observing=!1){let session=swarmState.agentSessions.get(sessionID);if(!session?.currentTaskId)return session?.declaredCoderScope?.length?[...session.declaredCoderScope]:null;return(observing?resolveActiveScopeBindingObserving(sessionID):resolveActiveScopeBinding(sessionID))?.files??null}function isArchitect(sessionId){let activeAgent=swarmState.activeAgent.get(sessionId);if(activeAgent){if(stripKnownSwarmPrefix(activeAgent)===ORCHESTRATOR_NAME)return!0}let session=swarmState.agentSessions.get(sessionId);if(session){if(stripKnownSwarmPrefix(session.agentName)===ORCHESTRATOR_NAME)return!0}return!1}function handleInterpreterGating(sessionID,tool3){let normalizedTool=normalizeToolName(tool3).toLowerCase();if(normalizedTool!=="bash"&&normalizedTool!=="shell")return;if(!interpreterAllowedAgents)return;let rawAgent=swarmState.activeAgent.get(sessionID),agentRole=rawAgent?stripKnownSwarmPrefix(rawAgent).toLowerCase():"unknown";if(!interpreterAllowedAgents.some((a)=>a.toLowerCase()===agentRole))throw Error(`BLOCKED: Agent "${agentRole}" is not permitted to use the bash/shell interpreter. Allowed agents: [${interpreterAllowedAgents.map((a)=>`"${a}"`).join(", ")}]`)}function checkDestructiveCommand(sessionID,tool3,args2){if(tool3!=="bash"&&tool3!=="shell")return;if(cfg.block_destructive_commands===!1)return;let rawAgent=swarmState.activeAgent.get(sessionID),isCoder=(rawAgent?stripKnownSwarmPrefix(rawAgent).toLowerCase():"unknown")==="coder",session=swarmState.agentSessions.get(sessionID),activeBinding=isCoder&&session?.currentTaskId?resolveActiveScopeBinding(sessionID):null,bindingIdentity=activeBinding,verifiedScope=bindingIdentity&&typeof bindingIdentity.bindingId==="string"&&typeof bindingIdentity.generationId==="string"?{bindingId:bindingIdentity.bindingId,generationId:bindingIdentity.generationId,files:bindingIdentity.files}:void 0,declaredScope=activeBinding?.files??(session?.declaredCoderScope?.length?[...session.declaredCoderScope]:null),toolArgs=args2,rawCommand=typeof toolArgs?.command==="string"?toolArgs.command.trim():"";if(!rawCommand)return;let sharedClassification=classifyCommand(rawCommand),sharedGuardrailBlock=getSharedClassifierGuardrailBlock(sharedClassification);if(sharedGuardrailBlock)throwDestructiveBlock(sharedGuardrailBlock.destructiveCategory,sharedGuardrailBlock.message);let cwd=sessionWorkspaceDirectory(sessionID),command=dcNormalizeCommand(rawCommand),unwrapped=dcUnwrapWrappers(command),outerSegments=dcSplitSegments(command),innerSegments=dcSplitSegments(unwrapped),perSegmentUnwrapped=outerSegments.map((s)=>dcUnwrapWrappers(s)),allSegments=[...new Set([...outerSegments,...innerSegments,...perSegmentUnwrapped])],swarmShellVars=new Map;for(let segment of allSegments){let seg=segment.trim();if(!seg)continue;for(let m of seg.matchAll(/(?:^|[\s;&|(])([A-Za-z_][A-Za-z0-9_]*)=(?:"([^"]*)"|'([^']*)'|([^\s;&|()]+))/g)){let value=m[2]??m[3]??m[4]??"";if(m[1])swarmShellVars.set(m[1],value)}let junctionBlock=dcCheckJunctionCreation(seg,cwd);if(junctionBlock)throwDestructiveBlock("junction/symlink creation",junctionBlock);let rmTargets=dcExtractRecursiveRmTargets(seg);if(rmTargets){let decision=dcEvaluateRecursiveDeleteTargets({targets:rmTargets,cwd,verifiedScope});if(!decision.allowed)throwDestructiveBlock("recursive delete",decision.reason)}if(/^(?:rmdir|rd)(?:\.exe)?\s+.*\/[sS]/i.test(seg)){let targets=dcExtractWindowsCmdTargets(seg);if(targets.length===0)throwDestructiveBlock("recursive directory delete","BLOCKED: Windows recursive directory delete (rmdir /s or rd /s) detected. Verify the target is not a junction/symlink.");let decision=dcEvaluateRecursiveDeleteTargets({targets,cwd,verifiedScope});if(!decision.allowed)throwDestructiveBlock("recursive directory delete",decision.reason)}if(/^del(?:\.exe)?\s+.*\/[sS]/i.test(seg)){let targets=dcExtractWindowsCmdTargets(seg);if(targets.length>0){let decision=dcEvaluateRecursiveDeleteTargets({targets,cwd,verifiedScope});if(!decision.allowed)throwDestructiveBlock("recursive file delete",decision.reason)}}if(/^(?:Remove-Item|ri|rm|rmdir|del|erase|rd)\b.*-[Rr]ecurse\b/i.test(seg)||/^(?:Remove-Item|ri|rm|rmdir|del|erase|rd)\b.*-[Rr]\b/i.test(seg)){let targets=dcExtractPowerShellTargets(seg);if(targets.length>0){let decision=dcEvaluateRecursiveDeleteTargets({targets,cwd,verifiedScope});if(!decision.allowed)throwDestructiveBlock("recursive remove",decision.reason)}else throwDestructiveBlock("recursive remove","BLOCKED: PowerShell Remove-Item with -Recurse detected — cannot verify target safety")}if(/Get-ChildItem\b.*\|\s*Remove-Item\b.*-[Rr]ecurse/i.test(seg)||/gci\b.*\|\s*ri\b.*-[Rr]ecurse/i.test(seg))throwDestructiveBlock("recursive remove",'BLOCKED: PowerShell pipeline "Get-ChildItem | Remove-Item -Recurse" detected — verify target safety and avoid recursive deletion through symlinks/junctions');let worktreeRemoveMatch=/^git\s+worktree\s+remove\s+(.+)$/i.exec(seg);if(worktreeRemoveMatch){let normalizedArgs=worktreeRemoveMatch[1].trim().split(/\s+/).filter(Boolean).map((a)=>a.replace(/^["']|["']$/g,"")),isForceToken=(a)=>{let lower=a.toLowerCase();return/^-f+$/.test(lower)||lower.length>2&&"--force".startsWith(lower)};if(normalizedArgs.some(isForceToken)){let pathArgs=normalizedArgs.filter((a)=>!a.startsWith("-")),target=pathArgs.length===1?pathArgs[0].trim():null;if(!(target!=null&&target.length>0&&(declaredScope!=null&&declaredScope.length>0&&isInDeclaredScope(target,declaredScope,cwd)||isPathUnderSwarmWorktreeBase(target,cwd,worktreeBaseDirOverrides??[]))))throwDestructiveBlock("git worktree remove",'BLOCKED: "git worktree remove --force" detected — can delete working tree contents')}}if(/^rsync\b.*--delete(?:-after|-before|-during|-delay)?\b/.test(seg)){let rsyncTarget=seg.split(/\s+/).slice(1).filter((a)=>!a.startsWith("-")&&!a.includes("@")).pop();if(!(rsyncTarget!=null&&declaredScope!=null&&declaredScope.length>0&&isInDeclaredScope(rsyncTarget,declaredScope,cwd)))throwDestructiveBlock("rsync delete",'BLOCKED: "rsync --delete" detected — can delete files in the destination. Verify source is not empty.')}if(/^\\?mv\s/i.test(seg)){let mvMatch=seg.match(/^\\?mv\s+(.+)$/i);if(mvMatch){let argsStr=mvMatch[1].replace(/["']/g,"");if(/\.swarm(?:[\x5c/\s]|$)/.test(argsStr))throwDestructiveBlock("swarm path move",'BLOCKED: "mv" targeting .swarm/ detected — move operations under .swarm/ are not allowed from shell commands')}}if(/^\\?(?:move|ren)(?:\.exe)?\s/i.test(seg)){let moveMatch=seg.match(/^\\?(?:move|ren)(?:\.exe)?\s+(.+)$/i);if(moveMatch){let argsStr=moveMatch[1].replace(/["']/g,"");if(/\.swarm(?:[\x5c/\s]|$)/i.test(argsStr))throwDestructiveBlock("move/rename",'BLOCKED: "move" or "ren" targeting .swarm/ detected — move/rename operations under .swarm/ are not allowed from shell commands')}}if(/^\\?(?:Move-Item|Rename-Item|move|mi|mv|ren|rni)\b.*\.swarm(?:[\x5c/\s]|$)/i.test(seg))throwDestructiveBlock("move/rename","BLOCKED: PowerShell Move-Item or Rename-Item targeting .swarm/ detected — move/rename operations under .swarm/ are not allowed from shell commands");if(/^\\?rm\b/i.test(seg)&&!/^\\?rm\s+(?:-[a-zA-Z]*[rR][a-zA-Z]*|--recursive)\b/i.test(seg)&&/\.swarm(?:[\x5c/\s]|$)/i.test(seg))throwDestructiveBlock("swarm path delete",'BLOCKED: "rm" targeting .swarm/ detected — deleting files under .swarm/ is not allowed from shell commands');if(/\bcp\b.*\.swarm(?:[\x5c/\s]|$)/i.test(seg)&&/\brm\b.*\.swarm(?:[\x5c/\s]|$)/i.test(seg))throwDestructiveBlock("copy-and-delete bypass",'BLOCKED: "cp" of .swarm/ file followed by "rm" of .swarm/ source detected — copy-and-delete bypass is not allowed');if(/^rsync\b.*--remove-source-files\b/i.test(seg)&&/\.swarm(?:[\x5c/\s]|$)/i.test(seg))throwDestructiveBlock("archive delete source",'BLOCKED: "rsync" with delete-source flag targeting .swarm/ detected — archive with source deletion under .swarm/ is not allowed');if(/^tar\b.*--remove-files\b/i.test(seg)&&/\.swarm(?:[\x5c/\s]|$)/i.test(seg))throwDestructiveBlock("archive delete source",'BLOCKED: "tar" with delete-source flag targeting .swarm/ detected — archive with source deletion under .swarm/ is not allowed');if(/^zip\b.*\s-m\b/i.test(seg)&&/\.swarm(?:[\x5c/\s]|$)/i.test(seg))throwDestructiveBlock("archive delete source",'BLOCKED: "zip" with delete-source flag targeting .swarm/ detected — archive with source deletion under .swarm/ is not allowed');if(/^7z\b.*\s-sdel\b/i.test(seg)&&/\.swarm(?:[\x5c/\s]|$)/i.test(seg))throwDestructiveBlock("archive delete source",'BLOCKED: "7z" with delete-source flag targeting .swarm/ detected — archive with source deletion under .swarm/ is not allowed');{let HUMAN_ONLY_SWARM_SUBCOMMANDS=HUMAN_ONLY_SWARM_COMMANDS,probe2=seg.replace(/^(?:[A-Za-z_][A-Za-z0-9_]*(?:="[^"]*"|='[^']*'|=\S+)\s+)+/,"").replace(/^eval(?:\s+--)?\s+["']?/,"").replace(/["']\s*$/,"").replace(/^\$\(\s*/,"").replace(/^\(\s*/,"").replace(/\s*\)$/,"").replace(/^`/,"").replace(/`$/,"").trim();for(let i=0;i<4;i++){let before=probe2;if(probe2=probe2.replace(/^env\s+(?:-i\b|--ignore-environment\b|-u\s+\S+|-[a-zA-Z]+\s+)*\s*/,"").replace(/^command\s+(?:-[pvV]\s+)*/,"").replace(/^(?:[A-Za-z_][A-Za-z0-9_]*(?:="[^"]*"|='[^']*'|=\S+)\s+)+/,"").trim(),probe2===before)break}let dequote=(input)=>input.replace(/["']/g,""),resolveVars=(input)=>input.replace(/\$\{?([A-Za-z_][A-Za-z0-9_]*)\}?/g,(full,name)=>swarmShellVars.has(name)?swarmShellVars.get(name):full),RUNNER_SHAPE=/^(?:\\|\/?(?:[\w.:%@=+-]+[/\\])*)?(?:bunx|npx|pnpx|npm|pnpm|yarn|bun|node|deno|tsx|ts-node|opencode-swarm)\b[^|;&]*?\brun\s+\$/i;for(let variant of[resolveVars(probe2),dequote(resolveVars(probe2))])if(RUNNER_SHAPE.test(variant))throwDestructiveBlock("human-only swarm command",'BLOCKED: "opencode-swarm run" invoked with an unresolvable shell variable or command substitution in the subcommand position. Re-run with the literal subcommand name so the human-only policy can be evaluated.');let probeVariants=[probe2,dequote(probe2),resolveVars(probe2),dequote(resolveVars(probe2))],matchCaptures=(re)=>{let captures=[];for(let variant of probeVariants){let m=variant.match(re);if(m?.[1])captures.push(m[1])}return captures},blockIfHumanOnly=(captures)=>{for(let captured of captures){let normalized=captured.trim().split(/\s+/).join(" "),firstToken=normalized.includes(" ")?normalized.split(" ")[0]:normalized,cmdName=HUMAN_ONLY_SWARM_SUBCOMMANDS.has(normalized)?normalized:firstToken;if(HUMAN_ONLY_SWARM_SUBCOMMANDS.has(normalized)||HUMAN_ONLY_SWARM_SUBCOMMANDS.has(firstToken))throwDestructiveBlock("human-only swarm command",`BLOCKED: "${cmdName}" is a human-only swarm command and may not be invoked from shell by an agent. Present the situation to the user and ask them to run \`/swarm ${cmdName}\` themselves.`)}};blockIfHumanOnly(matchCaptures(/^(?:\\|\/?(?:[\w.:%@=+-]+[/\\])*)?(?:bunx|npx|pnpx|npm(?:\s+(?:exec|x)(?:\s+--)?)?|pnpm(?:\s+(?:dlx|exec))?|yarn(?:\s+(?:dlx|exec))?|bun(?:\s+x)?|node|deno\s+run|tsx|ts-node)\b[^|;&]*?\bopencode-swarm\b[^|;&]*?\brun\s+([A-Za-z0-9_-]+(?:\s+(?!-)[A-Za-z0-9_-]+)?)/i)),blockIfHumanOnly(matchCaptures(/^(?:\\|\/?(?:[\w.:%@=+-]+[/\\])*)?opencode-swarm\b[^|;&]*?\brun\s+([A-Za-z0-9_-]+(?:\s+(?!-)[A-Za-z0-9_-]+)?)/i)),blockIfHumanOnly(matchCaptures(/\bcli[/\\]+index\.[mc]?(?:js|ts)\b[^|;&]*?\brun\s+([A-Za-z0-9_-]+(?:\s+(?!-)[A-Za-z0-9_-]+)?)/i))}{let normForPathCheck=seg.replace(/\\/g,"/").replace(/\/(?:\.\/+)+/g,"/").replace(/\/{2,}/g,"/");if(/\.swarm\/spec-staleness\.json\b/i.test(normForPathCheck)){let trimmed=seg.trim(),looksReadOnly=/^(?:cat|less|more|head|tail|file|stat|ls|dir|Get-Content|gc|Get-Item|gi|type)\b/i.test(trimmed),hasWriteRedirect=/>{1,2}\s*[^\s>]/.test(trimmed);if(!looksReadOnly||hasWriteRedirect)throwDestructiveBlock("system file tampering","BLOCKED: shell command targeting .swarm/spec-staleness.json detected. This file is system-managed and gates plan-mutating tools while spec drift is unresolved. Present the drift to the user and ask them to run /swarm acknowledge-spec-drift.")}}}}function detectShellType(command){if(/^(powershell|ps1|\.\s*\\|Remove-Item|Copy-Item|Move-Item|Start-Process|New-Object|Get-ChildItem|Set-Content|Add-Content|Out-File|Invoke-WebRequest|Invoke-RestMethod|IEX|iex)\b/i.test(command)||command.includes("$PSVersionTable")||command.includes("$env:")||/-EncodedCommand|-ExecutionPolicy|Enable-PSRemoting/i.test(command))return"powershell";if(/^(cmd|c:\/|set \w+=|\.\d+|del \/|rd \/|mkdir|chdir|echo |copy |move |ren |fc |diskpart)/i.test(command)||/%[^%\s]+%/.test(command)||/\b(set|echo|if|exist)\s+/i.test(command))return"cmd";if(/^(bash|sh|zsh|ksh|ash|dash|fish|ruby|python|perl|npm|yarn|node|cargo|go|rustc|mv|cp|rm|chmod|chown|mkdir|ln|tar|gzip|gunzip|ssh|scp|rsync|sudo|su -|export |source |\.\s+)/i.test(command)||command.includes("|")||command.includes("&&")||command.includes(">>")||/\$\{?\w+\}?/.test(command))return"bash";return"unix"}function checkShellWriteScope(sessionID,callID,tool3,args2,commandOverride,options){let enforce=options?.enforce!==!1;if(tool3!=="bash"&&tool3!=="shell")return;let session=swarmState.agentSessions.get(sessionID),toolArgs=args2,command=typeof commandOverride==="string"?commandOverride.trim():typeof toolArgs?.command==="string"?toolArgs.command.trim():"";if(!command)return;let normalizedTool=tool3,detectedShellType=detectShellType(command),shaped=isPowerShellShaped(command),shellType=detectedShellType;if(enforce&&(shellType==="powershell"||shellType==="cmd"?[shellType,"posix"]:["posix"]).some((candidate)=>detectInteractiveSession(command,candidate)))throw Error("BLOCKED: interactive/session tool detected — rejecting for safety");let windowsShell=resolveWindowsWriteAuthority(normalizedTool,command,detectedShellType,shaped),wrapperDeclaredHere=declaresWindowsWrapperLoose(command),windowsAuthoritative=wrapperDeclaredHere||normalizedTool!=="bash",detect=(c)=>{let posix14=detectPosixWrites(c);if(windowsShell===null)return posix14;return mergeWriteAnalyses(posix14,detectWindowsWrites(c,windowsShell),windowsAuthoritative,wrapperDeclaredHere)},suppressParseError=(c)=>enforce&&isPowerShellReadOnlyPipeline(c),primaryAnalysis=detect(command);if(enforce&&primaryAnalysis.parseError&&!suppressParseError(command))throw Error("BLOCKED: bash write detection failed to parse command — rejecting for safety");let commandSegments=dcSplitSegments(command),unwrappedSegments=commandSegments.map((s)=>dcUnwrapWrappers(s)),didUnwrap=commandSegments.some((s,i)=>unwrappedSegments[i]!==s),detectionCommand=didUnwrap?unwrappedSegments.join(`
|
|
1198
|
+
`;break}try{appendShellAuditLineSync(ctx.directory,line)}catch(error93){log("guardrail audit: append failed",{directory:ctx.directory,error:error93})}}var SHELL_AUDIT_FIELD_CLASSES,REQUIRED_STRING_FIELDS;var init_audit_log=__esm(()=>{init_logger();init_helpers();init_shell_audit_store();SHELL_AUDIT_FIELD_CLASSES=Object.freeze({ts:"timestamp",sessionID:"identifier",agent:"identifier",tool:"identifier",type:"decision-type",command:"redacted-command",commandHash:"content-hash",path:"redacted-path",reason:"free-text-redacted",resolvedScope:"redacted-path",declaredScope:"redacted-path",action:"enum",destructiveCategory:"enum",executorMechanism:"enum",skipReason:"enum"}),REQUIRED_STRING_FIELDS=["ts","sessionID","agent","tool","type"]});import*as fsSync10 from"node:fs";import*as os14 from"node:os";import*as path101 from"node:path";import{fileURLToPath as fileURLToPath3}from"node:url";function readPackageName(dir){try{let manifestPath=path101.join(dir,"package.json");if(!_internals91.existsSync(manifestPath))return null;let name=JSON.parse(_internals91.readFileSync(manifestPath,"utf-8"))?.name;return typeof name==="string"?name:null}catch{return null}}function resolvePackageRoot(){if(cachedPackageRoot!==void 0)return cachedPackageRoot.root;let root=null;try{let dir=path101.dirname(fileURLToPath3(_internals91.moduleUrl()));for(let depth=0;depth<MAX_PACKAGE_ROOT_WALK_DEPTH;depth++){if(readPackageName(dir)==="opencode-swarm"){root=dir;break}let parent=path101.dirname(dir);if(parent===dir)break;dir=parent}}catch{root=null}return cachedPackageRoot={root},root}function isSelfDevelopmentWorkspace(directory){if(!directory)return!1;let resolved;try{resolved=canonicalRootKeyFresh(directory)}catch{return!1}let cached3=selfDevelopmentWorkspaces.get(resolved);if(cached3!==void 0)return cached3;let isSelfDev=readPackageName(resolved)==="opencode-swarm";if(selfDevelopmentWorkspaces.size>=MAX_CACHED_WORKSPACE_ROOTS){let oldest=selfDevelopmentWorkspaces.keys().next().value;if(oldest!==void 0)selfDevelopmentWorkspaces.delete(oldest)}return selfDevelopmentWorkspaces.set(resolved,isSelfDev),isSelfDev}function comparablePath(value){return process.platform==="win32"?value.toLowerCase():value}function isInsidePackageRoot(root,target){try{let rel=path101.relative(comparablePath(root),comparablePath(target));if(rel==="")return!0;if(rel.startsWith(".."))return!1;return!path101.isAbsolute(rel)}catch{return!1}}function expandHome(candidate){if(!candidate.startsWith("~"))return candidate;let home=_internals91.homedir();if(!home)return null;let rest=candidate.slice(1).replace(/^[\\/]/,"");return rest?path101.join(home,rest):home}function extractGuardedPathCandidates(normalizedTool,args2){let argsObj=args2??{},raw=[];if(normalizedTool==="bash"||normalizedTool==="shell"){let command=typeof argsObj.command==="string"?argsObj.command.slice(0,MAX_SCANNED_COMMAND_LENGTH):void 0;if(command){let matcher=new RegExp(SHELL_PATH_CANDIDATE_PATTERN.source,SHELL_PATH_CANDIDATE_PATTERN.flags);for(let match of command.matchAll(matcher)){let token=match[1];if(token&&token.length>1)raw.push(token);if(raw.length>=MAX_SHELL_PATH_CANDIDATES)break}}}else for(let key2 of SCALAR_PATH_KEYS2){let value=argsObj[key2];if(typeof value==="string"&&value.length>0)raw.push(value)}let resolved=[];for(let candidate of raw){let expanded=expandHome(candidate);if(!expanded)continue;if(!path101.isAbsolute(expanded))continue;try{resolved.push(path101.resolve(expanded))}catch{}}return resolved}function enforceInternalsGuard(params){let{sessionID,tool:tool3,args:args2,directory,options}=params;if(options?.enabled===!1)return;let normalizedTool=normalizeToolNameLowerCase(tool3??"");if(!GUARDED_TOOLS.has(normalizedTool))return;let match=null,relativeTarget="";try{let packageRoot=_internals91.resolvePackageRoot();if(!packageRoot)return;if(_internals91.isSelfDevelopmentWorkspace(directory))return;if(directory&&isInsidePackageRoot(packageRoot,path101.resolve(directory)))return;for(let candidate of extractGuardedPathCandidates(normalizedTool,args2))if(isInsidePackageRoot(packageRoot,candidate)){match=candidate,relativeTarget=path101.relative(packageRoot,candidate).replace(/\\/g,"/")||"<package root>";break}}catch{return}if(!match)return;try{telemetry.swarmInternalsReadDenied(sessionID,normalizedTool,relativeTarget)}catch{}throw Error(SWARM_INTERNALS_DENIAL_MESSAGE)}var SWARM_INTERNALS_DENIAL_MESSAGE="SWARM_INTERNALS_OFF_LIMITS: the swarm plugin's installed files are never the fix for a gate error. Fix the dispatch/state the error names, or report the blocker to the user.",GUARDED_TOOLS,SCALAR_PATH_KEYS2,MAX_PACKAGE_ROOT_WALK_DEPTH=12,MAX_CACHED_WORKSPACE_ROOTS=32,SHELL_PATH_CANDIDATE_PATTERN,MAX_SHELL_PATH_CANDIDATES=64,MAX_SCANNED_COMMAND_LENGTH=8192,cachedPackageRoot,selfDevelopmentWorkspaces,_internals91;var init_internals_guard=__esm(()=>{init_telemetry();init_canonical_root();init_normalize_tool_name();GUARDED_TOOLS=new Set(["read","glob","grep","bash","shell"]),SCALAR_PATH_KEYS2=["filePath","file_path","path","file","target"],SHELL_PATH_CANDIDATE_PATTERN=/(?:^|[\s'"`;|&<>()=,])((?:~|[A-Za-z]:)?[\\/][^\s'"`;|&<>()]*)/g,selfDevelopmentWorkspaces=new Map;_internals91={moduleUrl:()=>import.meta.url,existsSync:(p)=>fsSync10.existsSync(p),readFileSync:(p,enc)=>fsSync10.readFileSync(p,enc),homedir:()=>os14.homedir(),resolvePackageRoot,isSelfDevelopmentWorkspace,resetCaches:()=>{cachedPackageRoot=void 0,selfDevelopmentWorkspaces.clear()}}});import*as fs63 from"node:fs";import*as path102 from"node:path";function normalizeSandboxMechanism2(mechanism){return mechanism.toLowerCase().replace(/[^a-z0-9]+/g,"")}function pluginOwnsExecutorEnv(mechanism){if(mechanism.startsWith("native-runner/"))return!0;switch(mechanism){case"sandbox-exec":case"powershell-wrapper":case"Bubblewrap":return!0;default:return!1}}function throwDestructiveBlock(destructiveCategory,message){throw new DestructiveCommandBlockedError(message,destructiveCategory)}function resolveWindowsWriteAuthority(tool3,command,detectedShellType,shaped,platform=process.platform){let cmdWrapper=CMD_WRAPPER_DECLARATION.test(command),psWrapper=declaresWindowsWrapperLoose(command),inheritedWindows=detectedShellType==="powershell"||detectedShellType==="cmd";if(cmdWrapper)return"cmd";if(psWrapper||shaped)return"powershell";if(inheritedWindows&&!(tool3==="bash"||tool3==="shell"&&platform!=="win32"))return detectedShellType;return null}function createToolBeforeHandler(ctx){let{effectiveDirectory,cfg,precomputedAuthorityRules,universalDenyPrefixes,shellAuditEnabled,interpreterAllowedAgents,authorityConfig,consecutiveNoToolTurns,worktreeBaseDirOverrides,getSandboxExecutor,assessSandboxEnforcement:assessSandboxEnforcement2,rememberReviewerScopeWrite,rememberScopeLeaseCandidate}=ctx,enforcePolicy=ctx.enforcePolicy!==!1;setMacOSSandboxPolicy(cfg.sandbox_macos_enabled??!1);let executionStallOptions={enabled:cfg.enabled,warnCalls:cfg.execution_stall_warn_calls,stopCalls:cfg.execution_stall_stop_calls,episodeMinutes:cfg.execution_stall_episode_minutes},internalsGuardOptions={enabled:cfg.enabled},sessionWorkspaceDirectory=(sessionID)=>resolveSessionWorkspaceDirectory(sessionID,effectiveDirectory);function resolveActiveScopeBinding(sessionID){let session=swarmState.agentSessions.get(sessionID),taskId=session?.currentTaskId??null,bindingDirectory=sessionWorkspaceDirectory(sessionID),resolution=taskId?resolveAuthorizedScopeBindingDetailed({directory:bindingDirectory,taskId,activeSessionId:sessionID}):resolveAuthorizedScopeBindingForSessionDetailed({directory:bindingDirectory,activeSessionId:sessionID}),binding=resolution.status==="found"?resolution.binding:null;if(!binding){let diagnostic=formatScopeResolutionDiagnostic({resolution,taskId,sessionId:sessionID});if(diagnostic)throw Error(diagnostic)}if(!taskId&&binding&&session)session.currentTaskId=binding.taskId,session.declaredCoderScope=[...binding.files];return binding}function resolveActiveScopeBindingObserving(sessionID){try{return resolveActiveScopeBinding(sessionID)}catch{return null}}function resolveDeclaredScope(sessionID,observing=!1){let session=swarmState.agentSessions.get(sessionID);if(!session?.currentTaskId)return session?.declaredCoderScope?.length?[...session.declaredCoderScope]:null;return(observing?resolveActiveScopeBindingObserving(sessionID):resolveActiveScopeBinding(sessionID))?.files??null}function isArchitect(sessionId){let activeAgent=swarmState.activeAgent.get(sessionId);if(activeAgent){if(stripKnownSwarmPrefix(activeAgent)===ORCHESTRATOR_NAME)return!0}let session=swarmState.agentSessions.get(sessionId);if(session){if(stripKnownSwarmPrefix(session.agentName)===ORCHESTRATOR_NAME)return!0}return!1}function handleInterpreterGating(sessionID,tool3){let normalizedTool=normalizeToolName(tool3).toLowerCase();if(normalizedTool!=="bash"&&normalizedTool!=="shell")return;if(!interpreterAllowedAgents)return;let rawAgent=swarmState.activeAgent.get(sessionID),agentRole=rawAgent?stripKnownSwarmPrefix(rawAgent).toLowerCase():"unknown";if(!interpreterAllowedAgents.some((a)=>a.toLowerCase()===agentRole))throw Error(`BLOCKED: Agent "${agentRole}" is not permitted to use the bash/shell interpreter. Allowed agents: [${interpreterAllowedAgents.map((a)=>`"${a}"`).join(", ")}]`)}function checkDestructiveCommand(sessionID,tool3,args2){if(tool3!=="bash"&&tool3!=="shell")return;if(cfg.block_destructive_commands===!1)return;let rawAgent=swarmState.activeAgent.get(sessionID),isCoder=(rawAgent?stripKnownSwarmPrefix(rawAgent).toLowerCase():"unknown")==="coder",session=swarmState.agentSessions.get(sessionID),activeBinding=isCoder&&session?.currentTaskId?resolveActiveScopeBinding(sessionID):null,bindingIdentity=activeBinding,verifiedScope=bindingIdentity&&typeof bindingIdentity.bindingId==="string"&&typeof bindingIdentity.generationId==="string"?{bindingId:bindingIdentity.bindingId,generationId:bindingIdentity.generationId,files:bindingIdentity.files}:void 0,declaredScope=activeBinding?.files??(session?.declaredCoderScope?.length?[...session.declaredCoderScope]:null),toolArgs=args2,rawCommand=typeof toolArgs?.command==="string"?toolArgs.command.trim():"";if(!rawCommand)return;let sharedClassification=classifyCommand(rawCommand),sharedGuardrailBlock=getSharedClassifierGuardrailBlock(sharedClassification);if(sharedGuardrailBlock)throwDestructiveBlock(sharedGuardrailBlock.destructiveCategory,sharedGuardrailBlock.message);let cwd=sessionWorkspaceDirectory(sessionID),command=dcNormalizeCommand(rawCommand),unwrapped=dcUnwrapWrappers(command),outerSegments=dcSplitSegments(command),innerSegments=dcSplitSegments(unwrapped),perSegmentUnwrapped=outerSegments.map((s)=>dcUnwrapWrappers(s)),allSegments=[...new Set([...outerSegments,...innerSegments,...perSegmentUnwrapped])],swarmShellVars=new Map;for(let segment of allSegments){let seg=segment.trim();if(!seg)continue;for(let m of seg.matchAll(/(?:^|[\s;&|(])([A-Za-z_][A-Za-z0-9_]*)=(?:"([^"]*)"|'([^']*)'|([^\s;&|()]+))/g)){let value=m[2]??m[3]??m[4]??"";if(m[1])swarmShellVars.set(m[1],value)}let junctionBlock=dcCheckJunctionCreation(seg,cwd);if(junctionBlock)throwDestructiveBlock("junction/symlink creation",junctionBlock);let rmTargets=dcExtractRecursiveRmTargets(seg);if(rmTargets){let decision=dcEvaluateRecursiveDeleteTargets({targets:rmTargets,cwd,verifiedScope});if(!decision.allowed)throwDestructiveBlock("recursive delete",decision.reason)}if(/^(?:rmdir|rd)(?:\.exe)?\s+.*\/[sS]/i.test(seg)){let targets=dcExtractWindowsCmdTargets(seg);if(targets.length===0)throwDestructiveBlock("recursive directory delete","BLOCKED: Windows recursive directory delete (rmdir /s or rd /s) detected. Verify the target is not a junction/symlink.");let decision=dcEvaluateRecursiveDeleteTargets({targets,cwd,verifiedScope});if(!decision.allowed)throwDestructiveBlock("recursive directory delete",decision.reason)}if(/^del(?:\.exe)?\s+.*\/[sS]/i.test(seg)){let targets=dcExtractWindowsCmdTargets(seg);if(targets.length>0){let decision=dcEvaluateRecursiveDeleteTargets({targets,cwd,verifiedScope});if(!decision.allowed)throwDestructiveBlock("recursive file delete",decision.reason)}}if(/^(?:Remove-Item|ri|rm|rmdir|del|erase|rd)\b.*-[Rr]ecurse\b/i.test(seg)||/^(?:Remove-Item|ri|rm|rmdir|del|erase|rd)\b.*-[Rr]\b/i.test(seg)){let targets=dcExtractPowerShellTargets(seg);if(targets.length>0){let decision=dcEvaluateRecursiveDeleteTargets({targets,cwd,verifiedScope});if(!decision.allowed)throwDestructiveBlock("recursive remove",decision.reason)}else throwDestructiveBlock("recursive remove","BLOCKED: PowerShell Remove-Item with -Recurse detected — cannot verify target safety")}if(/Get-ChildItem\b.*\|\s*Remove-Item\b.*-[Rr]ecurse/i.test(seg)||/gci\b.*\|\s*ri\b.*-[Rr]ecurse/i.test(seg))throwDestructiveBlock("recursive remove",'BLOCKED: PowerShell pipeline "Get-ChildItem | Remove-Item -Recurse" detected — verify target safety and avoid recursive deletion through symlinks/junctions');let worktreeRemoveMatch=/^git\s+worktree\s+remove\s+(.+)$/i.exec(seg);if(worktreeRemoveMatch){let normalizedArgs=worktreeRemoveMatch[1].trim().split(/\s+/).filter(Boolean).map((a)=>a.replace(/^["']|["']$/g,"")),isForceToken=(a)=>{let lower=a.toLowerCase();return/^-f+$/.test(lower)||lower.length>2&&"--force".startsWith(lower)};if(normalizedArgs.some(isForceToken)){let pathArgs=normalizedArgs.filter((a)=>!a.startsWith("-")),target=pathArgs.length===1?pathArgs[0].trim():null;if(!(target!=null&&target.length>0&&(declaredScope!=null&&declaredScope.length>0&&isInDeclaredScope(target,declaredScope,cwd)||isPathUnderSwarmWorktreeBase(target,cwd,worktreeBaseDirOverrides??[]))))throwDestructiveBlock("git worktree remove",'BLOCKED: "git worktree remove --force" detected — can delete working tree contents')}}if(/^rsync\b.*--delete(?:-after|-before|-during|-delay)?\b/.test(seg)){let rsyncTarget=seg.split(/\s+/).slice(1).filter((a)=>!a.startsWith("-")&&!a.includes("@")).pop();if(!(rsyncTarget!=null&&declaredScope!=null&&declaredScope.length>0&&isInDeclaredScope(rsyncTarget,declaredScope,cwd)))throwDestructiveBlock("rsync delete",'BLOCKED: "rsync --delete" detected — can delete files in the destination. Verify source is not empty.')}if(/^\\?mv\s/i.test(seg)){let mvMatch=seg.match(/^\\?mv\s+(.+)$/i);if(mvMatch){let argsStr=mvMatch[1].replace(/["']/g,"");if(/\.swarm(?:[\x5c/\s]|$)/.test(argsStr))throwDestructiveBlock("swarm path move",'BLOCKED: "mv" targeting .swarm/ detected — move operations under .swarm/ are not allowed from shell commands')}}if(/^\\?(?:move|ren)(?:\.exe)?\s/i.test(seg)){let moveMatch=seg.match(/^\\?(?:move|ren)(?:\.exe)?\s+(.+)$/i);if(moveMatch){let argsStr=moveMatch[1].replace(/["']/g,"");if(/\.swarm(?:[\x5c/\s]|$)/i.test(argsStr))throwDestructiveBlock("move/rename",'BLOCKED: "move" or "ren" targeting .swarm/ detected — move/rename operations under .swarm/ are not allowed from shell commands')}}if(/^\\?(?:Move-Item|Rename-Item|move|mi|mv|ren|rni)\b.*\.swarm(?:[\x5c/\s]|$)/i.test(seg))throwDestructiveBlock("move/rename","BLOCKED: PowerShell Move-Item or Rename-Item targeting .swarm/ detected — move/rename operations under .swarm/ are not allowed from shell commands");if(/^\\?rm\b/i.test(seg)&&!/^\\?rm\s+(?:-[a-zA-Z]*[rR][a-zA-Z]*|--recursive)\b/i.test(seg)&&/\.swarm(?:[\x5c/\s]|$)/i.test(seg))throwDestructiveBlock("swarm path delete",'BLOCKED: "rm" targeting .swarm/ detected — deleting files under .swarm/ is not allowed from shell commands');if(/\bcp\b.*\.swarm(?:[\x5c/\s]|$)/i.test(seg)&&/\brm\b.*\.swarm(?:[\x5c/\s]|$)/i.test(seg))throwDestructiveBlock("copy-and-delete bypass",'BLOCKED: "cp" of .swarm/ file followed by "rm" of .swarm/ source detected — copy-and-delete bypass is not allowed');if(/^rsync\b.*--remove-source-files\b/i.test(seg)&&/\.swarm(?:[\x5c/\s]|$)/i.test(seg))throwDestructiveBlock("archive delete source",'BLOCKED: "rsync" with delete-source flag targeting .swarm/ detected — archive with source deletion under .swarm/ is not allowed');if(/^tar\b.*--remove-files\b/i.test(seg)&&/\.swarm(?:[\x5c/\s]|$)/i.test(seg))throwDestructiveBlock("archive delete source",'BLOCKED: "tar" with delete-source flag targeting .swarm/ detected — archive with source deletion under .swarm/ is not allowed');if(/^zip\b.*\s-m\b/i.test(seg)&&/\.swarm(?:[\x5c/\s]|$)/i.test(seg))throwDestructiveBlock("archive delete source",'BLOCKED: "zip" with delete-source flag targeting .swarm/ detected — archive with source deletion under .swarm/ is not allowed');if(/^7z\b.*\s-sdel\b/i.test(seg)&&/\.swarm(?:[\x5c/\s]|$)/i.test(seg))throwDestructiveBlock("archive delete source",'BLOCKED: "7z" with delete-source flag targeting .swarm/ detected — archive with source deletion under .swarm/ is not allowed');{let HUMAN_ONLY_SWARM_SUBCOMMANDS=HUMAN_ONLY_SWARM_COMMANDS,probe2=seg.replace(/^(?:[A-Za-z_][A-Za-z0-9_]*(?:="[^"]*"|='[^']*'|=\S+)\s+)+/,"").replace(/^eval(?:\s+--)?\s+["']?/,"").replace(/["']\s*$/,"").replace(/^\$\(\s*/,"").replace(/^\(\s*/,"").replace(/\s*\)$/,"").replace(/^`/,"").replace(/`$/,"").trim();for(let i=0;i<4;i++){let before=probe2;if(probe2=probe2.replace(/^env\s+(?:-i\b|--ignore-environment\b|-u\s+\S+|-[a-zA-Z]+\s+)*\s*/,"").replace(/^command\s+(?:-[pvV]\s+)*/,"").replace(/^(?:[A-Za-z_][A-Za-z0-9_]*(?:="[^"]*"|='[^']*'|=\S+)\s+)+/,"").trim(),probe2===before)break}let dequote=(input)=>input.replace(/["']/g,""),resolveVars=(input)=>input.replace(/\$\{?([A-Za-z_][A-Za-z0-9_]*)\}?/g,(full,name)=>swarmShellVars.has(name)?swarmShellVars.get(name):full),RUNNER_SHAPE=/^(?:\\|\/?(?:[\w.:%@=+-]+[/\\])*)?(?:bunx|npx|pnpx|npm|pnpm|yarn|bun|node|deno|tsx|ts-node|opencode-swarm)\b[^|;&]*?\brun\s+\$/i;for(let variant of[resolveVars(probe2),dequote(resolveVars(probe2))])if(RUNNER_SHAPE.test(variant))throwDestructiveBlock("human-only swarm command",'BLOCKED: "opencode-swarm run" invoked with an unresolvable shell variable or command substitution in the subcommand position. Re-run with the literal subcommand name so the human-only policy can be evaluated.');let probeVariants=[probe2,dequote(probe2),resolveVars(probe2),dequote(resolveVars(probe2))],matchCaptures=(re)=>{let captures=[];for(let variant of probeVariants){let m=variant.match(re);if(m?.[1])captures.push(m[1])}return captures},blockIfHumanOnly=(captures)=>{for(let captured of captures){let normalized=captured.trim().split(/\s+/).join(" "),firstToken=normalized.includes(" ")?normalized.split(" ")[0]:normalized,cmdName=HUMAN_ONLY_SWARM_SUBCOMMANDS.has(normalized)?normalized:firstToken;if(HUMAN_ONLY_SWARM_SUBCOMMANDS.has(normalized)||HUMAN_ONLY_SWARM_SUBCOMMANDS.has(firstToken))throwDestructiveBlock("human-only swarm command",`BLOCKED: "${cmdName}" is a human-only swarm command and may not be invoked from shell by an agent. Present the situation to the user and ask them to run \`/swarm ${cmdName}\` themselves.`)}};blockIfHumanOnly(matchCaptures(/^(?:\\|\/?(?:[\w.:%@=+-]+[/\\])*)?(?:bunx|npx|pnpx|npm(?:\s+(?:exec|x)(?:\s+--)?)?|pnpm(?:\s+(?:dlx|exec))?|yarn(?:\s+(?:dlx|exec))?|bun(?:\s+x)?|node|deno\s+run|tsx|ts-node)\b[^|;&]*?\bopencode-swarm\b[^|;&]*?\brun\s+([A-Za-z0-9_-]+(?:\s+(?!-)[A-Za-z0-9_-]+)?)/i)),blockIfHumanOnly(matchCaptures(/^(?:\\|\/?(?:[\w.:%@=+-]+[/\\])*)?opencode-swarm\b[^|;&]*?\brun\s+([A-Za-z0-9_-]+(?:\s+(?!-)[A-Za-z0-9_-]+)?)/i)),blockIfHumanOnly(matchCaptures(/\bcli[/\\]+index\.[mc]?(?:js|ts)\b[^|;&]*?\brun\s+([A-Za-z0-9_-]+(?:\s+(?!-)[A-Za-z0-9_-]+)?)/i))}{let normForPathCheck=seg.replace(/\\/g,"/").replace(/\/(?:\.\/+)+/g,"/").replace(/\/{2,}/g,"/");if(/\.swarm\/spec-staleness\.json\b/i.test(normForPathCheck)){let trimmed=seg.trim(),looksReadOnly=/^(?:cat|less|more|head|tail|file|stat|ls|dir|Get-Content|gc|Get-Item|gi|type)\b/i.test(trimmed),hasWriteRedirect=/>{1,2}\s*[^\s>]/.test(trimmed);if(!looksReadOnly||hasWriteRedirect)throwDestructiveBlock("system file tampering","BLOCKED: shell command targeting .swarm/spec-staleness.json detected. This file is system-managed and gates plan-mutating tools while spec drift is unresolved. Present the drift to the user and ask them to run /swarm acknowledge-spec-drift.")}}}}function detectShellType(command){if(/^(powershell|ps1|\.\s*\\|Remove-Item|Copy-Item|Move-Item|Start-Process|New-Object|Get-ChildItem|Set-Content|Add-Content|Out-File|Invoke-WebRequest|Invoke-RestMethod|IEX|iex)\b/i.test(command)||command.includes("$PSVersionTable")||command.includes("$env:")||/-EncodedCommand|-ExecutionPolicy|Enable-PSRemoting/i.test(command))return"powershell";if(/^(cmd|c:\/|set \w+=|\.\d+|del \/|rd \/|mkdir|chdir|echo |copy |move |ren |fc |diskpart)/i.test(command)||/%[^%\s]+%/.test(command)||/\b(set|echo|if|exist)\s+/i.test(command))return"cmd";if(/^(bash|sh|zsh|ksh|ash|dash|fish|ruby|python|perl|npm|yarn|node|cargo|go|rustc|mv|cp|rm|chmod|chown|mkdir|ln|tar|gzip|gunzip|ssh|scp|rsync|sudo|su -|export |source |\.\s+)/i.test(command)||command.includes("|")||command.includes("&&")||command.includes(">>")||/\$\{?\w+\}?/.test(command))return"bash";return"unix"}function checkShellWriteScope(sessionID,callID,tool3,args2,commandOverride,options){let enforce=options?.enforce!==!1;if(tool3!=="bash"&&tool3!=="shell")return;let session=swarmState.agentSessions.get(sessionID),toolArgs=args2,command=typeof commandOverride==="string"?commandOverride.trim():typeof toolArgs?.command==="string"?toolArgs.command.trim():"";if(!command)return;let normalizedTool=tool3,detectedShellType=detectShellType(command),shaped=isPowerShellShaped(command),shellType=detectedShellType;if(enforce&&(shellType==="powershell"||shellType==="cmd"?[shellType,"posix"]:["posix"]).some((candidate)=>detectInteractiveSession(command,candidate)))throw Error("BLOCKED: interactive/session tool detected — rejecting for safety");let windowsShell=resolveWindowsWriteAuthority(normalizedTool,command,detectedShellType,shaped),wrapperDeclaredHere=declaresWindowsWrapperLoose(command),windowsAuthoritative=wrapperDeclaredHere||normalizedTool!=="bash",detect=(c)=>{let posix15=detectPosixWrites(c);if(windowsShell===null)return posix15;return mergeWriteAnalyses(posix15,detectWindowsWrites(c,windowsShell),windowsAuthoritative,wrapperDeclaredHere)},suppressParseError=(c)=>enforce&&isPowerShellReadOnlyPipeline(c),primaryAnalysis=detect(command);if(enforce&&primaryAnalysis.parseError&&!suppressParseError(command))throw Error("BLOCKED: bash write detection failed to parse command — rejecting for safety");let commandSegments=dcSplitSegments(command),unwrappedSegments=commandSegments.map((s)=>dcUnwrapWrappers(s)),didUnwrap=commandSegments.some((s,i)=>unwrappedSegments[i]!==s),detectionCommand=didUnwrap?unwrappedSegments.join(`
|
|
1199
1199
|
`):command,analysis=didUnwrap?detect(detectionCommand):primaryAnalysis;if(enforce&&analysis.parseError&&!suppressParseError(detectionCommand))throw Error("BLOCKED: bash write detection failed to parse command — rejecting for safety");if(!analysis.hasWrites||analysis.writes.length===0)return;let declaredScope=resolveDeclaredScope(sessionID,!enforce),shellWriteAgent=swarmState.activeAgent.get(sessionID);if(!shellWriteAgent){if(enforce)throw Error(`WRITE BLOCKED: No active agent registered for session "${sessionID}". Agent identity must be established (e.g. via a chat message or Task delegation) before shell writes can be authorized.`);return}let shellWriteRole=stripKnownSwarmPrefix(shellWriteAgent).toLowerCase(),isArch=shellWriteRole==="architect",isCoder=shellWriteRole==="coder",shellRoleCapability=AUTHORITY_ROLE_CAPABILITIES[shellWriteRole],isImmutableNonWriter=shellRoleCapability==="read-only"||shellRoleCapability==="dedicated-tool-only";if(enforce&&isCoder&&(!declaredScope||declaredScope.length===0))throw Error(`SCOPE_NOT_DECLARED: ${shellWriteAgent} cannot perform shell writes without an active Task-correlated scope binding. ACTION[architect]: call declare_scope with the exact workspace-relative paths and replace_existing=true, then dispatch a new Task call.`);let noScopeLenient=!isArch&&!isCoder&&!isImmutableNonWriter&&(!declaredScope||declaredScope.length===0),shellDirectory=sessionWorkspaceDirectory(sessionID),resolvedWrites=resolveWriteTargets(detectionCommand,analysis.writes,shellDirectory);for(let write of resolvedWrites){if(write.resolvedPath===null){if(write.original.category==="here_doc"&&write.original.path===null)continue;if(enforce&&write.original.category==="interpreter_eval")throw Error(`BLOCKED: ${write.original.operator} evaluates inline code whose write targets cannot be verified against the declared scope — rejecting for safety. Write files with the write/edit tools or a checked-in script, and invoke installed tools directly (e.g. \`pytest\`, \`ruff\`) instead of an inline \`python -c\` / \`node -e\` eval.`);if(enforce)throw Error(`BLOCKED: bash/shell write to a dynamic path target${write.original.path?` "${write.original.path}"`:""} that cannot be statically resolved (shell variable or command substitution) — rejecting for safety.`);continue}if(enforce&&noScopeLenient&&universalDenyPrefixes.length>0){for(let prefix of universalDenyPrefixes)if(matchesAuthorityDenyPrefix(write.resolvedPath,prefix,shellDirectory))throw Error(`WRITE BLOCKED: Agent "${shellWriteAgent}" is not authorised to write "${write.resolvedPath}" (via shell). Reason: Path is under universal deny prefix "${prefix}"`)}if(noScopeLenient)continue;let authorityCheck=checkFileAuthorityWithRules(shellWriteAgent,write.resolvedPath,shellDirectory,precomputedAuthorityRules,{declaredScope,authorityEnabled:authorityConfig?.enabled,universalDenyPrefixes,verifierConfigPaths:authorityConfig?.verifier_config_paths});if(enforce&&!authorityCheck.allowed){let evidenceEventID=authorityCheck.layer==="protected-path"?recordFullAutoSevereEvidenceEvent({sessionID,childSessionID:sessionID,category:"protected_state_mutation",paths:[write.resolvedPath]}):void 0;throw Error(`WRITE BLOCKED: Agent "${shellWriteAgent}" is not authorised to write "${write.resolvedPath}" (via shell). Reason: ${authorityCheck.reason}${evidenceEventID?` Evidence event: ${evidenceEventID}.`:""}`)}if(enforce&&declaredScope&&declaredScope.length>0&&!isInDeclaredScope(write.resolvedPath,declaredScope,shellDirectory)){let safeTarget=sanitizeDiagnosticText(write.resolvedPath,320),scopeSummary=declaredScope.slice(0,10).map((entry)=>sanitizeDiagnosticText(entry,160)).join(", "),omitted=Math.max(0,declaredScope.length-10);throw Error(`WRITE BLOCKED: SCOPE_VIOLATION: shell write target "${safeTarget}" is outside the active scope [${scopeSummary}${omitted>0?`, ... (+${omitted} more)`:""}]. ACTION[architect]: if the target is intended, call declare_scope for the exact workspace-relative path and redispatch; otherwise correct the command.`)}if(isCoder&&session?.currentTaskId){let writeBinding=enforce?resolveActiveScopeBinding(sessionID):resolveActiveScopeBindingObserving(sessionID);if(writeBinding?.activation==="active"&&writeBinding.parentOwnerSessionId&&writeBinding.parentCallId){let relativeTarget=path102.relative(path102.resolve(shellDirectory),path102.resolve(shellDirectory,write.resolvedPath)).replace(/\\/g,"/");if(recordReviewerScopeGenerationFile({parentSessionID:writeBinding.parentOwnerSessionId,taskId:writeBinding.taskId,coderCallID:writeBinding.parentCallId,file:relativeTarget}))rememberReviewerScopeWrite?.({callID,parentSessionID:writeBinding.parentOwnerSessionId,taskId:writeBinding.taskId,coderCallID:writeBinding.parentCallId,file:relativeTarget})}}}if(isCoder&&session?.currentTaskId){let binding=enforce?resolveActiveScopeBinding(sessionID):resolveActiveScopeBindingObserving(sessionID);if(binding)rememberScopeLeaseCandidate?.({callID,sessionID,tool:tool3,directory:shellDirectory,binding,targets:resolvedWrites.flatMap((write)=>write.resolvedPath===null?[]:[path102.resolve(shellDirectory,write.resolvedPath)]),args:args2})}}function isSandboxWrapperInvocation(raw){let head=raw.replace(/^\s*(?:(?:exec|(?:\/(?:usr\/)?bin\/)?env)(?:\s+(?:-\S+|[A-Za-z_]\w*=\S*))*\s+)*/,"");return/^(?:\/(?:usr\/(?:local\/)?)?bin\/)?bwrap(?:\s|$)/.test(head)}async function applySandboxExecution(sessionID,callID,tool3,args2,agent,command,auditEnabled){if(tool3!=="bash"&&tool3!=="shell")return;let toolArgs=args2,rawCommand=typeof toolArgs?.command==="string"?toolArgs.command.trim():"";if(!rawCommand||!toolArgs)return;let executor=await getSandboxExecutor(),sandboxConfig=cfg.sandbox,originalCommandHash=hashArgs({command:rawCommand}),commandIdentity=`cmd=${originalCommandHash}`,assessment=await assessSandboxEnforcement2(sandboxConfig?{mode:sandboxConfig.mode,require_filesystem:sandboxConfig.require_filesystem,require_network:sandboxConfig.require_network,require_process:sandboxConfig.require_process,network_mode:sandboxConfig.network_mode,network_allowlist:sandboxConfig.network_allowlist,writable_roots:sandboxConfig.writable_roots}:void 0),capabilityIdentity=`cap=${assessment.capability.identity}`,recordOutcome2=(outcome)=>recordSandboxWrapOutcome({...outcome,sessionID,callID,originalCommandHash,originalCommand:rawCommand,assessmentCacheKey:assessment.cacheKey,executorMechanism:executor?.mechanism??"none",capabilityMechanism:assessment.capability.mechanism}),clearRecordedOutcome=()=>{clearSandboxWrapOutcome(sessionID,callID)};if(sandboxConfig?.mode==="required"){let assessmentSupported=assessment.supported!==!1,assessmentUnsupported=assessment.unsupported??[],missing=!executor||!executor.isAvailable()?["executor"]:assessment.missing;if(!executor||!executor.isAvailable()||!assessmentSupported||!assessment.satisfied){let missingOrUnsupported=assessmentSupported?missing.join(", "):assessmentUnsupported.join(", "),skipReason=missing[0]==="executor"?`required sandbox executor unavailable [${commandIdentity} ${capabilityIdentity}]`:!assessmentSupported?`required sandbox policy unsupported (${missingOrUnsupported}) [${commandIdentity} ${capabilityIdentity}]`:`required sandbox capability unsatisfied (${missingOrUnsupported}) [${commandIdentity} ${capabilityIdentity}]`;throw recordOutcome2({finalCommandHash:originalCommandHash,wrapped:!1,capabilityIdentity:assessment.capability.identity,reason:skipReason}),clearRecordedOutcome(),appendGuardrailDecision({type:"sandbox_skip",ts:new Date().toISOString(),sessionID,agent,tool:tool3,command,executorMechanism:executor?.mechanism??"none",skipReason},{directory:effectiveDirectory,enabled:auditEnabled}),Error(`[sandbox] BLOCKED: Required sandbox policy unsatisfied (${missingOrUnsupported}). [${commandIdentity} ${capabilityIdentity}] Command will not be executed unsandboxed.`)}}if(!executor||!executor.isAvailable()){if(recordOutcome2({finalCommandHash:originalCommandHash,wrapped:!1,capabilityIdentity:assessment.capability.identity,reason:"executor not available"}),!hasWarnedSandboxUnavailable)hasWarnedSandboxUnavailable=!0,criticalWarn("[guardrails] sandbox executor unavailable; shell commands will run unsandboxed. Run /swarm diagnose for details.");appendGuardrailDecision({type:"sandbox_skip",ts:new Date().toISOString(),sessionID,agent,tool:tool3,command,executorMechanism:executor?.mechanism??"none",skipReason:"executor not available"},{directory:effectiveDirectory,enabled:auditEnabled});return}let declaredPaths=resolveDeclaredScope(sessionID,!enforcePolicy);if(!declaredPaths||declaredPaths.length===0){if(recordOutcome2({finalCommandHash:originalCommandHash,wrapped:!1,capabilityIdentity:assessment.capability.identity,reason:"no declared scope"}),sandboxConfig?.mode==="required")throw clearRecordedOutcome(),Error("[sandbox] BLOCKED: Required sandbox policy needs a declared writable scope; command will not execute unsandboxed.");return}let resolved=resolveScopePaths(declaredPaths,sessionWorkspaceDirectory(sessionID)),configuredWritableRoots=resolveScopePaths(sandboxConfig?.writable_roots??[],sessionWorkspaceDirectory(sessionID));if(configuredWritableRoots.rejected.length>0){if(recordOutcome2({finalCommandHash:originalCommandHash,wrapped:!1,capabilityIdentity:assessment.capability.identity,reason:`configured writable_roots rejected (${configuredWritableRoots.rejected.map((item)=>item.path).join(", ")})`}),sandboxConfig?.mode==="required")throw clearRecordedOutcome(),Error("[sandbox] BLOCKED: Required sandbox policy contains writable_roots outside the session workspace; command will not execute unsandboxed.");return}if(resolved.paths.length===0){if(recordOutcome2({finalCommandHash:originalCommandHash,wrapped:!1,capabilityIdentity:assessment.capability.identity,reason:"resolved scope empty"}),sandboxConfig?.mode==="required")throw clearRecordedOutcome(),Error("[sandbox] BLOCKED: Required sandbox policy resolved no writable scope; command will not execute unsandboxed.");return}let writablePaths=[...new Set([...resolved.paths,...configuredWritableRoots.paths])];if(normalizeSandboxMechanism2(executor.mechanism)==="bubblewrap"&&isSandboxWrapperInvocation(rawCommand))throw recordOutcome2({finalCommandHash:originalCommandHash,wrapped:!1,capabilityIdentity:assessment.capability.identity,reason:"command already invokes the sandbox wrapper"}),clearRecordedOutcome(),Error(`[sandbox] BLOCKED: the command already invokes bwrap. Every bash call is sandboxed by the harness (${executor.mechanism}); a nested wrapper fails with "No permissions to create new namespace". Re-issue the plain command without the bwrap prefix.`);let workspaceRoot=sessionWorkspaceDirectory(sessionID),readonlyWorkspaceRoot=workspaceRoot;try{readonlyWorkspaceRoot=fs63.realpathSync(workspaceRoot)}catch{}try{let envOverrides=pluginOwnsExecutorEnv(executor.mechanism)?executor.getEnvOverrides():void 0,wrappedCommand=executor.wrapCommand(rawCommand,writablePaths,void 0,envOverrides,{network_mode:sandboxConfig?.network_mode??"off",network_allowlist:sandboxConfig?.network_allowlist??[],writable_roots:configuredWritableRoots.paths,readonly_roots:[readonlyWorkspaceRoot]});if(wrappedCommand.trim()===rawCommand)throw recordOutcome2({finalCommandHash:originalCommandHash,wrapped:!1,capabilityIdentity:assessment.capability.identity,reason:"sandbox wrapper returned the original command unchanged"}),clearRecordedOutcome(),Error(`[sandbox] BLOCKED: ${executor.mechanism} returned the original command unchanged. [${commandIdentity} ${capabilityIdentity}] Command will not be executed unsandboxed.`);if(normalizeSandboxMechanism2(executor.mechanism)!==normalizeSandboxMechanism2(assessment.capability.mechanism))throw recordOutcome2({finalCommandHash:originalCommandHash,wrapped:!1,capabilityIdentity:assessment.capability.identity,reason:"sandbox executor mechanism no longer matches the assessed capability"}),clearRecordedOutcome(),Error(`[sandbox] BLOCKED: sandbox executor mechanism drifted from the assessed capability (${executor.mechanism} != ${assessment.capability.mechanism}). [${commandIdentity} ${capabilityIdentity}]`);toolArgs.command=wrappedCommand,recordOutcome2({finalCommandHash:hashArgs({command:wrappedCommand}),wrapped:!0,capabilityIdentity:assessment.capability.identity,reason:"wrapped"}),markToolExecutionSandboxWrapped(sessionID,callID),appendGuardrailDecision({type:"sandbox_wrap",ts:new Date().toISOString(),sessionID,agent,tool:tool3,command:rawCommand,executorMechanism:executor.mechanism},{directory:effectiveDirectory,enabled:auditEnabled})}catch(err){recordOutcome2({finalCommandHash:originalCommandHash,wrapped:!1,capabilityIdentity:assessment.capability.identity,reason:err instanceof Error?err.message:String(err)}),clearRecordedOutcome(),forgetToolExecution(sessionID,callID);let message=`[sandbox] BLOCKED: Failed to wrap command with ${executor.mechanism}: ${err}. Command will not be executed unsandboxed.`,circuit=recordNonTransientFailure(sessionID,"sandbox_wrapper_failure",message,{tool:tool3,args:{command:rawCommand},armAttempt:!0});if(circuit?.hardStop)throw Error(nonTransientHardStopMessage(circuit));throw Error(message)}}async function checkGateLimits(params){let{sessionID,window:window2,agentConfig,elapsedMinutes,repetitionCount}=params;if(agentConfig.max_tool_calls>0&&window2.toolCalls>=agentConfig.max_tool_calls)throw window2.hardLimitHit=!0,telemetry.hardLimitHit(sessionID,window2.agentName,"tool_calls",window2.toolCalls),warn("Circuit breaker: tool call limit hit",{sessionID,agentName:window2.agentName,invocationId:window2.id,windowKey:`${window2.agentName}:${window2.id}`,resolvedMaxCalls:agentConfig.max_tool_calls,currentCalls:window2.toolCalls}),Error(`\uD83D\uDED1 LIMIT REACHED: Tool calls exhausted (${window2.toolCalls}/${agentConfig.max_tool_calls}). Finish the current operation and return your progress summary.`);if(agentConfig.max_duration_minutes>0&&elapsedMinutes>=agentConfig.max_duration_minutes)throw window2.hardLimitHit=!0,telemetry.hardLimitHit(sessionID,window2.agentName,"duration",elapsedMinutes),warn("Circuit breaker: duration limit hit",{sessionID,agentName:window2.agentName,invocationId:window2.id,windowKey:`${window2.agentName}:${window2.id}`,resolvedMaxMinutes:agentConfig.max_duration_minutes,elapsedMinutes:Math.floor(elapsedMinutes)}),Error(`\uD83D\uDED1 LIMIT REACHED: Duration exhausted (${Math.floor(elapsedMinutes)}/${agentConfig.max_duration_minutes} min). Finish the current operation and return your progress summary.`);if(repetitionCount>=agentConfig.max_repetitions)throw window2.hardLimitHit=!0,telemetry.hardLimitHit(sessionID,window2.agentName,"repetition",repetitionCount),Error(`\uD83D\uDED1 LIMIT REACHED: Repeated the same tool call ${repetitionCount} times. This suggests a loop. Return your progress summary.`);if(window2.consecutiveErrors>=agentConfig.max_consecutive_errors)throw window2.hardLimitHit=!0,telemetry.hardLimitHit(sessionID,window2.agentName,"consecutive_errors",window2.consecutiveErrors),Error(`\uD83D\uDED1 LIMIT REACHED: ${window2.consecutiveErrors} consecutive tool errors detected. Return your progress summary with details of what went wrong. Run /swarm reset-session to clear the circuit breaker without restarting your session.`);let idleMinutes=(Date.now()-window2.lastSuccessTimeMs)/60000;if(idleMinutes>=agentConfig.idle_timeout_minutes)throw window2.hardLimitHit=!0,telemetry.hardLimitHit(sessionID,window2.agentName,"idle_timeout",idleMinutes),warn("Circuit breaker: idle timeout hit",{sessionID,agentName:window2.agentName,invocationId:window2.id,windowKey:`${window2.agentName}:${window2.id}`,idleTimeoutMinutes:agentConfig.idle_timeout_minutes,idleMinutes:Math.floor(idleMinutes)}),Error(`\uD83D\uDED1 LIMIT REACHED: No successful tool call for ${Math.floor(idleMinutes)} minutes (idle timeout: ${agentConfig.idle_timeout_minutes} min). This suggests the agent may be stuck. Return your progress summary.`);if(!window2.warningIssued){let toolPct=agentConfig.max_tool_calls>0?window2.toolCalls/agentConfig.max_tool_calls:0,durationPct=agentConfig.max_duration_minutes>0?elapsedMinutes/agentConfig.max_duration_minutes:0,repPct=repetitionCount/agentConfig.max_repetitions,errorPct=window2.consecutiveErrors/agentConfig.max_consecutive_errors,reasons=[];if(agentConfig.max_tool_calls>0&&toolPct>=agentConfig.warning_threshold)reasons.push(`tool calls ${window2.toolCalls}/${agentConfig.max_tool_calls}`);if(durationPct>=agentConfig.warning_threshold)reasons.push(`duration ${Math.floor(elapsedMinutes)}/${agentConfig.max_duration_minutes} min`);if(repPct>=agentConfig.warning_threshold)reasons.push(`repetitions ${repetitionCount}/${agentConfig.max_repetitions}`);if(errorPct>=agentConfig.warning_threshold)reasons.push(`errors ${window2.consecutiveErrors}/${agentConfig.max_consecutive_errors}`);if(reasons.length>0)window2.warningIssued=!0,window2.warningReason=reasons.join(", ")}}function handleDelegatedWriteTracking(sessionID,tool3,args2){if(!swarmState.agentSessions.get(sessionID)?.delegationActive&&isArchitect(sessionID)){let coderDeleg=isAgentDelegation(tool3,args2);if(coderDeleg.isDelegation&&coderDeleg.targetAgent==="coder"){let coderSession=swarmState.agentSessions.get(sessionID);if(coderSession){let taskId=coderSession.currentTaskId??coderSession.lastCoderDelegationTaskId??`${sessionID}:unknown`;if(coderSession.currentTaskId=taskId,resetModifiedFilesForTask(coderSession,taskId),!coderSession.revisionLimitHit)coderSession.coderRevisions=0}}}}function isAgentDelegation(toolName,args2){if(!isTaskToolId(toolName))return{isDelegation:!1,targetAgent:null};let argsObj=args2;if(!argsObj)return{isDelegation:!1,targetAgent:null};let subagentType=argsObj.subagent_type;if(typeof subagentType==="string")return{isDelegation:!0,targetAgent:stripKnownSwarmPrefix(subagentType)};return{isDelegation:!1,targetAgent:null}}function handleLoopDetection(sessionID,tool3,args2){if(!isTaskToolId(tool3))return;let loopArgs=args2,loopResult=detectLoop(sessionID,tool3,loopArgs);if(loopResult.count>=5)throw Error(`CIRCUIT BREAKER: Delegation loop detected (${loopResult.count} identical patterns). Further identical delegations are blocked. Diagnose or rescope the task before retrying.`);else if(loopResult.count>=3&&loopResult.count<5){let agentName=typeof loopArgs?.subagent_type==="string"?loopArgs.subagent_type:"agent",loopSession=swarmState.agentSessions.get(sessionID);if(loopSession){let loopPattern=loopResult.pattern,modifiedFiles=loopSession.currentTaskId?getModifiedFilesForTask(loopSession,loopSession.currentTaskId):[],accomplishmentSummary=modifiedFiles.length>0?`Modified ${modifiedFiles.length} file(s): ${modifiedFiles.slice(0,3).join(", ")}${modifiedFiles.length>3?"...":""}`:"No files modified yet",alternativeSuggestions={coder:"Try a different task spec, simplify the constraint, or escalate to user",reviewer:"Try a different review dimension or escalate to user",test_engineer:"Run a specific test file with targeted scope",explorer:"Narrow the search scope or check a specific file directly"},cleanAgent=stripKnownSwarmPrefix(agentName).toLowerCase(),suggestion=alternativeSuggestions[cleanAgent]??"Try a different agent, different instructions, or escalate to the user";loopSession.loopWarningPending={agent:agentName,message:[`LOOP DETECTED: Pattern "${loopPattern}" repeated 3 times.`,`Agent: ${agentName}`,`Accomplished: ${accomplishmentSummary}`,`Suggested action: ${suggestion}`,"If still stuck after trying alternatives, escalate to the user."].join(`
|
|
1200
1200
|
`),timestamp:Date.now()}}}}function handleTestSuiteBlocking(tool3,args2){if(tool3!=="bash"&&tool3!=="shell")return;let bashArgs=args2,cmd=(typeof bashArgs?.command==="string"?bashArgs.command:"").trim();if(/^(bun\s+test|npm\s+test|npx\s+vitest|bunx\s+vitest)\b/.test(cmd)){let tokens=cmd.split(/\s+/),runnerTokenCount=tokens[0]==="npx"||tokens[0]==="bunx"?3:2;if(!tokens.slice(runnerTokenCount).some((token)=>token.length>0&&!token.startsWith("-")&&(token.includes("/")||token.includes("\\")||token.endsWith(".ts")||token.endsWith(".js")||token.endsWith(".tsx")||token.endsWith(".jsx")||token.endsWith(".mts")||token.endsWith(".mjs"))))throw Error("BLOCKED: Full test suite execution is not allowed in-session. Run a specific test file instead: bun test path/to/file.test.ts")}}function extractAllPatchPayloads(args2){let toolArgs=args2;if(!toolArgs)return[];let out=[];for(let key2 of PATCH_PAYLOAD_KEYS){let v=toolArgs[key2];if(typeof v==="string"&&v.length>0)out.push(v)}let cmd=toolArgs.cmd;if(Array.isArray(cmd)){for(let entry of cmd)if(typeof entry==="string"&&entry.length>0)out.push(entry)}return out}function getHumanOnlyAlternation(){return[...HUMAN_ONLY_SWARM_COMMANDS].map((c)=>c.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).sort((a,b)=>b.length-a.length).join("|")}function patchPayloadHasHumanOnlyInvocation(args2){let payloads=extractAllPatchPayloads(args2);if(payloads.length===0)return!1;let alternation=getHumanOnlyAlternation(),re=new RegExp(`\\bopencode-swarm\\b[\\s\\S]*?\\brun\\s+(${alternation})\\b`,"i");return payloads.some((p)=>re.test(p))}function extractPatchTargetPaths(tool3,args2){if(tool3!=="apply_patch"&&tool3!=="swarm_apply_patch"&&tool3!=="patch")return[];let toolArgs=args2,paths=new Set;if(Array.isArray(toolArgs?.files)){for(let f of toolArgs.files)if(typeof f==="string"&&f.length>0&&f!=="/dev/null")paths.add(f)}let patchText;for(let key2 of["input","patch","diff"]){let v=toolArgs?.[key2];if(typeof v==="string"){patchText=v;break}}if(patchText===void 0)for(let key2 of PATCH_PAYLOAD_KEYS){if(key2==="patch"||key2==="input"||key2==="diff")continue;let v=toolArgs?.[key2];if(typeof v==="string"){patchText=v;break}}if(patchText===void 0&&Array.isArray(toolArgs?.cmd))patchText=toolArgs.cmd[1];if(typeof patchText!=="string")return Array.from(paths);if(patchText.length>1e6)throw Error("WRITE BLOCKED: Patch payload exceeds 1 MB — authority cannot be verified for all modified paths. Split into smaller patches.");let normalizedPatchText=normalizePatchIndentation(patchText),patchPathPattern=/\*\*\*\s+(?:Update|Add|Delete)\s+File:\s*(.+)/gi,diffPathPattern=/\+\+\+\s+b\/(.+)/gm,gitDiffPathPattern=/^diff --git a\/(.+?) b\/(.+?)$/gm,minusPathPattern=/^---\s+a\/(.+)$/gm,traditionalMinusPattern=/^---\s+([^\s].+?)(?:\t.*)?$/gm,traditionalPlusPattern=/^\+\+\+\s+([^\s].+?)(?:\t.*)?$/gm;for(let match of normalizedPatchText.matchAll(patchPathPattern))paths.add(match[1].trim());for(let match of normalizedPatchText.matchAll(diffPathPattern)){let p=match[1].trim();if(p!=="/dev/null")paths.add(p)}for(let match of normalizedPatchText.matchAll(gitDiffPathPattern)){let aPath=match[1].trim(),bPath=match[2].trim();if(aPath!=="/dev/null")paths.add(aPath);if(bPath!=="/dev/null")paths.add(bPath)}for(let match of normalizedPatchText.matchAll(minusPathPattern)){let p=match[1].trim();if(p!=="/dev/null")paths.add(p)}for(let match of normalizedPatchText.matchAll(traditionalMinusPattern)){let p=match[1].trim();if(p!=="/dev/null"&&!p.startsWith("a/")&&!p.startsWith("b/"))paths.add(p)}for(let match of normalizedPatchText.matchAll(traditionalPlusPattern)){let p=match[1].trim();if(p!=="/dev/null"&&!p.startsWith("a/")&&!p.startsWith("b/"))paths.add(p)}return Array.from(paths)}function handlePlanAndScopeProtection(sessionID,tool3,args2){let toolArgs=args2,targetPath=toolArgs?.filePath??toolArgs?.path??toolArgs?.file??toolArgs?.target;if(tool3==="apply_patch"||tool3==="swarm_apply_patch"||tool3==="patch"){if(patchPayloadHasHumanOnlyInvocation(args2))throw Error("BLOCKED: apply_patch/swarm_apply_patch would introduce a script invoking a human-only swarm CLI subcommand. Present the situation to the user and ask them to run the command themselves.")}if(typeof targetPath==="string"&&targetPath.length>0){let resolvedTarget=path102.resolve(effectiveDirectory,targetPath).toLowerCase(),planMdPath=path102.resolve(effectiveDirectory,".swarm","plan.md").toLowerCase(),planJsonPath=path102.resolve(effectiveDirectory,".swarm","plan.json").toLowerCase();if(resolvedTarget===planMdPath||resolvedTarget===planJsonPath)throw Error("PLAN STATE VIOLATION: Direct writes to .swarm/plan.md and .swarm/plan.json are blocked. plan.md is auto-regenerated from plan.json by PlanSyncWorker. Use save_plan for ALL structural plan changes (adding/removing tasks, updating descriptions, dependencies, or phase names). Use update_task_status() for task status only. Use phase_complete() for phase transitions only.");let specStalenessPath=path102.resolve(effectiveDirectory,".swarm","spec-staleness.json").toLowerCase();if(resolvedTarget===specStalenessPath)throw Error("SPEC_DRIFT_VIOLATION: Direct writes to .swarm/spec-staleness.json are blocked. This file is system-managed and gates plan-mutating tools while spec drift is unresolved. Present the drift to the user and ask them to run /swarm acknowledge-spec-drift.");let content=toolArgs?.content??toolArgs?.text??toolArgs?.new_string??toolArgs?.newText;if(typeof content==="string"&&new RegExp(`\\bopencode-swarm\\b[\\s\\S]*?\\brun\\s+(${getHumanOnlyAlternation()})\\b`,"i").test(content))throw Error("BLOCKED: write/edit tool would create a script invoking a human-only swarm CLI subcommand. Present the situation to the user and ask them to run the command themselves.")}if(!targetPath&&(tool3==="apply_patch"||tool3==="swarm_apply_patch"||tool3==="patch"))for(let p of extractPatchTargetPaths(tool3,args2)){let resolvedP=path102.resolve(effectiveDirectory,p),planMdPath=path102.resolve(effectiveDirectory,".swarm","plan.md").toLowerCase(),planJsonPath=path102.resolve(effectiveDirectory,".swarm","plan.json").toLowerCase(),specStalenessPath=path102.resolve(effectiveDirectory,".swarm","spec-staleness.json").toLowerCase();if(resolvedP.toLowerCase()===planMdPath||resolvedP.toLowerCase()===planJsonPath)throw Error("PLAN STATE VIOLATION: Direct writes to .swarm/plan.md and .swarm/plan.json are blocked. plan.md is auto-regenerated from plan.json by PlanSyncWorker. Use save_plan for ALL structural plan changes (adding/removing tasks, updating descriptions, dependencies, or phase names). Use update_task_status() for task status only. Use phase_complete() for phase transitions only.");if(resolvedP.toLowerCase()===specStalenessPath)throw Error("SPEC_DRIFT_VIOLATION: Direct writes to .swarm/spec-staleness.json are blocked. This file is system-managed and gates plan-mutating tools while spec drift is unresolved. Present the drift to the user and ask them to run /swarm acknowledge-spec-drift.");if(isOutsideSwarmDir(p,effectiveDirectory)&&(isSourceCodePath(p)||hasTraversalSegments(p))){let session=swarmState.agentSessions.get(sessionID);if(session)session.architectWriteCount++,warn("Architect direct code edit detected via patch tool",{tool:tool3,sessionID,targetPath:p,writeCount:session.architectWriteCount});break}}if(typeof targetPath==="string"&&targetPath.length>0&&isOutsideSwarmDir(targetPath,effectiveDirectory)&&isSourceCodePath(path102.relative(effectiveDirectory,path102.resolve(effectiveDirectory,targetPath)))){let session=swarmState.agentSessions.get(sessionID);if(session){if(session.architectWriteCount++,warn("Architect direct code edit detected",{tool:tool3,sessionID,targetPath,writeCount:session.architectWriteCount}),session.lastGateFailure&&Date.now()-session.lastGateFailure.timestamp<120000){let failedGate=session.lastGateFailure.tool,failedTaskId=session.lastGateFailure.taskId;warn("Self-fix after gate failure detected",{failedGate,failedTaskId,currentTool:tool3,sessionID}),session.selfFixAttempted=!0}}}}function resolveSessionAndWindow(sessionID){let rawActiveAgent=swarmState.activeAgent.get(sessionID),strippedAgent=rawActiveAgent?stripKnownSwarmPrefix(rawActiveAgent):void 0;if(strippedAgent===ORCHESTRATOR_NAME)return null;if(strippedAgent&&isNativeOpencodeAgent(strippedAgent))return null;let existingSession=swarmState.agentSessions.get(sessionID);if(existingSession){let sessionAgent=stripKnownSwarmPrefix(existingSession.agentName);if(sessionAgent===ORCHESTRATOR_NAME)return null;if(isNativeOpencodeAgent(sessionAgent))return null}let agentName=swarmState.activeAgent.get(sessionID)??ORCHESTRATOR_NAME,session=ensureAgentSession(sessionID,agentName),resolvedName=stripKnownSwarmPrefix(session.agentName);if(resolvedName===ORCHESTRATOR_NAME)return null;if(isNativeOpencodeAgent(resolvedName))return null;let agentConfig=resolveGuardrailsConfig(cfg,session.agentName);if(agentConfig.max_duration_minutes===0&&agentConfig.max_tool_calls===0)return null;if(!getActiveWindow(sessionID)){let fallbackAgent=swarmState.activeAgent.get(sessionID)??session.agentName;if(stripKnownSwarmPrefix(fallbackAgent)!==ORCHESTRATOR_NAME)beginInvocation(sessionID,fallbackAgent)}let window2=getActiveWindow(sessionID);if(!window2)return null;return{agentConfig,window:window2}}function isNativeOpencodeAgent(agentName){return OPENCODE_NATIVE_AGENTS.has(agentName.toLowerCase())}function trackToolCall(window2,tool3,args2){if(window2.hardLimitHit)throw Error("\uD83D\uDED1 CIRCUIT BREAKER: Agent blocked. Hard limit was previously triggered. Stop making tool calls and return your progress summary.");window2.toolCalls++;let hash4=hashArgs(args2);if(window2.recentToolCalls.push({tool:tool3,argsHash:hash4,timestamp:Date.now()}),window2.recentToolCalls.length>20)window2.recentToolCalls.shift();let repetitionCount=0;if(window2.recentToolCalls.length>0){let lastEntry=window2.recentToolCalls[window2.recentToolCalls.length-1];for(let i=window2.recentToolCalls.length-1;i>=0;i--){let entry=window2.recentToolCalls[i];if(entry.tool===lastEntry.tool&&entry.argsHash===lastEntry.argsHash)repetitionCount++;else break}}let elapsedMinutes=(Date.now()-window2.startedAtMs)/60000;return{repetitionCount,elapsedMinutes}}return async(input,output)=>{if(enforcePolicy)assertNonTransientCircuitAllowsTool(input.sessionID,{tool:input.tool,args:output.args});let resolvedSessionWindow=swarmState.agentSessions.has(input.sessionID)||swarmState.activeAgent.has(input.sessionID)?resolveSessionAndWindow(input.sessionID):null,session=swarmState.agentSessions.get(input.sessionID),rawAgentForScope=swarmState.activeAgent.get(input.sessionID),isCoder=rawAgentForScope!==void 0&&stripKnownSwarmPrefix(rawAgentForScope).toLowerCase()==="coder";if(consecutiveNoToolTurns.set(input.sessionID,0),observeExecutionStallToolCall({sessionID:input.sessionID,tool:input.tool,args:output.args,callID:input.callID,options:executionStallOptions}),handleDelegatedWriteTracking(input.sessionID,input.tool,output.args),enforcePolicy)handleLoopDetection(input.sessionID,input.tool,output.args);if(enforcePolicy&&isSwarmOwnedSession(input.sessionID))handleTestSuiteBlocking(input.tool,output.args);let rawShellCommand=(()=>{let bashArgs=output.args;return typeof bashArgs?.command==="string"?bashArgs.command:""})(),normalizedAuditTool=normalizeToolName(input.tool).toLowerCase();if(normalizedAuditTool==="bash"||normalizedAuditTool==="shell")appendGuardrailDecision({type:"shell",ts:new Date().toISOString(),sessionID:input.sessionID,agent:(()=>{let rawAgent=swarmState.activeAgent.get(input.sessionID);return rawAgent?stripKnownSwarmPrefix(rawAgent):"unknown"})(),tool:input.tool,command:(()=>{let bashArgs=output.args,rawCmd=typeof bashArgs?.command==="string"?bashArgs.command:"";return redactShellCommand(rawCmd)})()},{directory:effectiveDirectory,enabled:shellAuditEnabled});if(enforcePolicy)handleInterpreterGating(input.sessionID,input.tool);try{if(enforcePolicy)checkDestructiveCommand(input.sessionID,input.tool,output.args)}catch(err){let destructiveCategory=err instanceof DestructiveCommandBlockedError?err.destructiveCategory:"destructive shell command";throw appendGuardrailDecision({type:"destructive_block",ts:new Date().toISOString(),sessionID:input.sessionID,agent:(()=>{let rawAgent=swarmState.activeAgent.get(input.sessionID);return rawAgent?stripKnownSwarmPrefix(rawAgent):"unknown"})(),tool:input.tool,command:(()=>{let bashArgs=output.args;return typeof bashArgs?.command==="string"?bashArgs.command:""})(),destructiveCategory},{directory:effectiveDirectory,enabled:shellAuditEnabled}),err}try{checkShellWriteScope(input.sessionID,input.callID,input.tool,output.args,rawShellCommand,{enforce:enforcePolicy})}catch(err){let toolArgs=output.args,declaredScope=resolveDeclaredScope(input.sessionID,!0),declaredScopeText=declaredScope!=null&&declaredScope.length>0?declaredScope.join(", "):"",resolvedScopeText=declaredScope!=null&&declaredScope.length>0?resolveScopePaths(declaredScope,sessionWorkspaceDirectory(input.sessionID)).paths.join(", "):"",pathMatch=/[^\s]+/.exec(err instanceof Error?err.message:String(err)),targetPath=(()=>{let p=toolArgs?.filePath??toolArgs?.path??toolArgs?.file??toolArgs?.target;if(typeof p==="string"&&p.length>0)return p;let rawMessage=err instanceof Error?err.message:String(err),extracted=/(?:write|target|file|path|scope|prefix)[^:]*:\s*(?:"([^"]+)"|'([^']+)'|(\S+))/i.exec(rawMessage)??/(?:write|target|file|path)\s+(?:"([^"]+)"|'([^']+)'|(\S+))/i.exec(rawMessage),candidate=extracted!=null?extracted[1]??extracted[2]??extracted[3]??extracted[4]??extracted[5]??extracted[6]:null;if(candidate&&candidate.length>0&&candidate.length<200)return candidate;if(pathMatch)return pathMatch[0];return"<shell write>"})(),agentName=(()=>{let rawAgent=swarmState.activeAgent.get(input.sessionID);return rawAgent?stripKnownSwarmPrefix(rawAgent):"unknown"})();throw appendGuardrailDecision({type:"scope_violation",ts:new Date().toISOString(),sessionID:input.sessionID,agent:agentName,tool:input.tool,path:targetPath,declaredScope:declaredScopeText,resolvedScope:resolvedScopeText,action:"bash"},{directory:effectiveDirectory,enabled:shellAuditEnabled}),err}let agentNameForSandbox=(()=>{let rawAgent=swarmState.activeAgent.get(input.sessionID);return rawAgent?stripKnownSwarmPrefix(rawAgent):"unknown"})();if(rememberToolExecution(input.sessionID,input.callID,input.tool,rawShellCommand),enforcePolicy)await applySandboxExecution(input.sessionID,input.callID,input.tool,output.args,agentNameForSandbox,rawShellCommand,shellAuditEnabled);if(enforcePolicy)enforceSpecDriftGate(effectiveDirectory,input.tool);if(enforcePolicy&&isArchitect(input.sessionID)&&isWriteTool(input.tool))handlePlanAndScopeProtection(input.sessionID,input.tool,output.args);if(input.tool==="apply_patch"||input.tool==="swarm_apply_patch"||input.tool==="patch"){let patchArgs=output.args,structuralPatch=typeof patchArgs?.input==="string"?patchArgs.input:typeof patchArgs?.patch==="string"?patchArgs.patch:typeof patchArgs?.diff==="string"?patchArgs.diff:void 0;if(structuralPatch===void 0)for(let key2 of PATCH_PAYLOAD_KEYS){let value=patchArgs?.[key2];if(typeof value==="string"){structuralPatch=value;break}}if(structuralPatch===void 0&&Array.isArray(patchArgs?.cmd)&&typeof patchArgs.cmd[1]==="string")structuralPatch=patchArgs.cmd[1];if(structuralPatch===void 0&&typeof patchArgs?.cmd==="string")structuralPatch=patchArgs.cmd;if((structuralPatch??"").length>1e6)throw Error("WRITE BLOCKED: Patch payload exceeds 1 MB — authority cannot be verified for all modified paths. Split into smaller patches.")}let writeDirectory=sessionWorkspaceDirectory(input.sessionID),resolvedFileTargets=null;if(isWriteTool(input.tool)){let resolution=resolveWriteTargets2(normalizeToolName(input.tool),output.args,{directory:writeDirectory});if(resolution.status==="unverifiable"){if(enforcePolicy)throw Error(`WRITE TARGET UNVERIFIABLE: ${resolution.reason}`)}else resolvedFileTargets=resolution.paths;let writeBinding=session?.currentTaskId&&isCoder?enforcePolicy?resolveActiveScopeBinding(input.sessionID):resolveActiveScopeBindingObserving(input.sessionID):null;if(writeBinding)rememberScopeLeaseCandidate?.({callID:input.callID,sessionID:input.sessionID,tool:input.tool,directory:writeDirectory,binding:writeBinding,targets:(resolvedFileTargets??[]).map((target)=>path102.resolve(writeDirectory,target)),args:output.args})}if(isWriteTool(input.tool))for(let targetPath of resolvedFileTargets??[]){let agentName=swarmState.activeAgent.get(input.sessionID);if(!agentName){if(!enforcePolicy)continue;throw Error(`WRITE BLOCKED: No active agent registered for session "${input.sessionID}". Call startAgentSession before issuing write tool calls.`)}let lstatBlock=checkWriteTargetForSymlink(targetPath,writeDirectory);if(lstatBlock){if(appendGuardrailDecision({type:"file_write",ts:new Date().toISOString(),sessionID:input.sessionID,agent:agentName,tool:input.tool,path:targetPath,reason:lstatBlock,resolvedScope:(()=>{let scope=resolveDeclaredScope(input.sessionID,!enforcePolicy);return scope!=null&&scope.length>0?scope.join(", "):""})()},{directory:effectiveDirectory,enabled:shellAuditEnabled}),enforcePolicy)throw Error(lstatBlock)}let writeBinding=session?.currentTaskId&&isCoder?enforcePolicy?resolveActiveScopeBinding(input.sessionID):resolveActiveScopeBindingObserving(input.sessionID):null,writeDeclaredScope=writeBinding?.files??null,authorityCheck=checkFileAuthorityWithRules(agentName,targetPath,writeDirectory,precomputedAuthorityRules,{declaredScope:writeDeclaredScope,authorityEnabled:authorityConfig?.enabled,universalDenyPrefixes,verifierConfigPaths:authorityConfig?.verifier_config_paths});if(!authorityCheck.allowed){let evidenceEventID=authorityCheck.layer==="protected-path"?recordFullAutoSevereEvidenceEvent({sessionID:input.sessionID,childSessionID:input.sessionID,category:"protected_state_mutation",paths:[targetPath]}):void 0;if(appendGuardrailDecision({type:"file_write",ts:new Date().toISOString(),sessionID:input.sessionID,agent:agentName,tool:input.tool,path:targetPath,reason:authorityCheck.reason,resolvedScope:(()=>{let scope=writeDeclaredScope;return scope!=null&&scope.length>0?scope.join(", "):""})()},{directory:effectiveDirectory,enabled:shellAuditEnabled}),!enforcePolicy)continue;throw Error(`WRITE BLOCKED: Agent "${agentName}" is not authorised to write "${targetPath}". Reason: ${authorityCheck.reason}${evidenceEventID?` Evidence event: ${evidenceEventID}.`:""}`)}let trackingSession=swarmState.agentSessions.get(input.sessionID),auditContext=trackingSession?.delegationActive?"delegated":"direct",auditOperation=["apply_patch","swarm_apply_patch","patch"].includes(normalizeToolName(input.tool))?"patch":"write";if(isConfigFilePath(targetPath,writeDirectory,authorityConfig?.verifier_config_paths)){let normalizedPath=path102.relative(path102.resolve(writeDirectory),path102.resolve(writeDirectory,targetPath)).replace(/\\/g,"/"),logEntry={agent:agentName,path:normalizedPath,allowed:authorityCheck.allowed,type:`${auditContext}_${auditOperation}`};if(!authorityCheck.allowed&&"reason"in authorityCheck)logEntry.reason=authorityCheck.reason;warn("Config file write attempt",logEntry)}if(trackingSession?.delegationActive){let taskId=trackingSession.currentTaskId??trackingSession.lastCoderDelegationTaskId??`${input.sessionID}:unknown`;trackingSession.currentTaskId=taskId,recordModifiedFileForTask(trackingSession,taskId,targetPath,writeDirectory)}if(writeBinding?.activation==="active"&&writeBinding.parentOwnerSessionId&&writeBinding.parentCallId){let relativeTarget=path102.relative(path102.resolve(writeDirectory),path102.resolve(writeDirectory,targetPath)).replace(/\\/g,"/");if(recordReviewerScopeGenerationFile({parentSessionID:writeBinding.parentOwnerSessionId,taskId:writeBinding.taskId,coderCallID:writeBinding.parentCallId,file:relativeTarget}))rememberReviewerScopeWrite?.({callID:input.callID,parentSessionID:writeBinding.parentOwnerSessionId,taskId:writeBinding.taskId,coderCallID:writeBinding.parentCallId,file:relativeTarget})}}let resolved=resolvedSessionWindow;if(resolved){let{agentConfig,window:window2}=resolved,{repetitionCount,elapsedMinutes}=trackToolCall(window2,input.tool,output.args);if(enforcePolicy)await checkGateLimits({sessionID:input.sessionID,window:window2,agentConfig,elapsedMinutes,repetitionCount})}if(enforcePolicy){let prmSession=swarmState.agentSessions.get(input.sessionID);if(prmSession?.prmHardStopPending){prmSession.prmHardStopPending=!1;let patternType=prmSession.prmLastPatternDetected?.pattern??"unknown";throw telemetry.prmHardStopDelivered(input.sessionID,patternType,prmSession.prmEscalationLevel,prmSession.prmPatternCounts?.get(patternType)??0),Error("\uD83D\uDED1 PRM HARD STOP: Pattern escalation maximum reached. Stop tool calls and return progress summary.")}}if(enforceInternalsGuard({sessionID:input.sessionID,tool:input.tool,args:output.args,directory:effectiveDirectory,options:internalsGuardOptions}),enforceExecutionStallDenial({sessionID:input.sessionID,tool:input.tool,options:executionStallOptions}),!resolved)return;setStoredInputArgs(input.callID,output.args)}}var hasWarnedSandboxUnavailable=!1,DestructiveCommandBlockedError;var init_tool_before=__esm(()=>{init_tool_policy();init_constants();init_schema();init_severe_result();init_executor();init_scope_resolver();init_skip_state();init_path_identity();init_scope_persistence();init_scope_resolution_diagnostic();init_command_classifier();init_state();init_telemetry();init_utils();init_core3();init_loop_detector();init_normalize_tool_name();init_shell_executor_context();init_shell_write_detect();init_write_target_resolver();init_audit_log();init_destructive_command();init_execution_stall();init_file_authority();init_guardrails();init_internals_guard();init_nontransient_circuit();init_stored_input_args();init_helpers();DestructiveCommandBlockedError=class DestructiveCommandBlockedError extends Error{destructiveCategory;constructor(message,destructiveCategory){super(message);this.destructiveCategory=destructiveCategory;this.name="DestructiveCommandBlockedError"}}});import*as fsSync11 from"node:fs";import*as path103 from"node:path";function emitDurableAttributionAdvisory(sessionID,key2,message){let now=Date.now(),prior=durableAttributionAdvisoryBySession.get(sessionID);if(prior&&prior.key===key2&&now-prior.at<DURABLE_ATTRIBUTION_ADVISORY_COOLDOWN_MS)return;if(!prior&&durableAttributionAdvisoryBySession.size>=MAX_DURABLE_ATTRIBUTION_ADVISORY_SESSIONS){let oldest=durableAttributionAdvisoryBySession.keys().next().value;if(oldest!==void 0)durableAttributionAdvisoryBySession.delete(oldest)}durableAttributionAdvisoryBySession.set(sessionID,{key:key2,at:now});let session=swarmState.agentSessions.get(sessionID);if(session)pushAdvisory(session,message);else criticalWarn(`[guardrails] ${message}`)}function stageAWriteErrorCode(error93){let message=error93 instanceof Error?error93.message:String(error93),match=/^[A-Z][A-Z0-9_]+/.exec(message);return match?match[0]:null}function extractGateCallFiles(args2){if(!args2||typeof args2!=="object")return null;let raw=args2.files;if(Array.isArray(raw)){let files=raw.filter((entry)=>typeof entry==="string"&&entry!=="");return files.length>0?files:null}let changed2=args2.changed_files;if(Array.isArray(changed2)){let files=changed2.map((entry)=>typeof entry==="string"?entry:entry&&typeof entry==="object"&&typeof entry.path==="string"?entry.path:null).filter((entry)=>entry!==null&&entry!=="");return files.length>0?files:null}return null}async function resolveDurableGateTaskId(directory,callerFiles){try{let{states,truncated}=await listCoderSettlementWalStates(directory),eligible=[],inFlightAtCoderDelegated=new Set;for(let state2 of states){if(!isStrictTaskId(state2.taskId))continue;if(state2.state==="DISPATCHED"||state2.state==="PREPARED"){if(getTaskWorkflowSnapshot(await readTaskEvidence(directory,state2.taskId)).state==="coder_delegated")inFlightAtCoderDelegated.add(state2.taskId);continue}if(state2.state!=="COMMITTED")continue;if(state2.accepted!==!0)continue;if(getTaskWorkflowSnapshot(await readTaskEvidence(directory,state2.taskId)).state==="coder_delegated")eligible.push(state2)}let ambiguousIds=new Set([...eligible.map((s)=>s.taskId),...inFlightAtCoderDelegated]);if(ambiguousIds.size>1)return{ambiguous:[...ambiguousIds].sort()};if(eligible.length===1){let candidate=eligible[0];if(truncated)return{unbound:candidate.taskId,reason:"truncated"};let declared=candidate.declaredFiles,normalizedCallerFiles=callerFiles!==null?normalizeScopeFiles(callerFiles):null;if(normalizedCallerFiles!==null&&normalizedCallerFiles.length>0&&declared!==null&&declared!==void 0&&declared.length>0&&declared.some((f)=>f!==""&&normalizedCallerFiles.includes(f)))return{taskId:candidate.taskId};return{unbound:candidate.taskId,reason:"files_mismatch"}}return null}catch(error93){return warn("Durable gate attribution fallback failed",{error:String(error93)}),null}}function enforceSpecDriftGate(directory,toolName){if(!directory)return;if(!SPEC_DRIFT_BLOCKED_TOOLS.has(toolName))return;let stalePath=path103.join(directory,".swarm","spec-staleness.json");if(fsSync11.existsSync(stalePath)){let diffInfo=null;try{diffInfo=computeSpecDiff(directory)}catch{}let message=`SPEC_DRIFT_BLOCK: tool "${toolName}" is blocked because .swarm/spec-staleness.json exists. Run /swarm clarify to enter spec repair mode. Clarify alone does not clear drift: rewrite the spec so recovery can reconcile it, or run /swarm acknowledge-spec-drift to dismiss, then retry.`;if(diffInfo){let sectionSummary=diffInfo.changedSections.length>0?`
|
|
1201
1201
|
Changed sections: ${diffInfo.changedSections.map((s)=>`## ${s}`).join(", ")}`:"";message+=`
|
|
@@ -1364,9 +1364,9 @@ Ignoring will not affect already-tracked files. To stop tracking them, run:
|
|
|
1364
1364
|
`).map((f)=>f.trim()).filter((f)=>f.length>0),basis:"HEAD"};return{files:null,basis:"HEAD~1"}}catch{return{files:null,basis:"HEAD~1"}}}async function getLatestCommitShortSha(directory){try{let gitExecutable=_internals115.resolveGitExecutable(),proc=_internals115.bunSpawn([gitExecutable,"rev-parse","--short","HEAD"],{cwd:directory,...GIT_DIFF_SPAWN_OPTIONS}),exitCode,stdout;try{[exitCode,stdout]=await Promise.all([proc.exited,proc.stdout.text()])}finally{try{proc.kill()}catch{}}if(exitCode===0){let sha=stdout.trim();if(sha.length>0&&!/\s/.test(sha))return sha}return""}catch{return""}}function hasDeclaredDiffScope(taskId,directory){try{return getDeclaredScope(taskId,directory)!==null}catch{return!1}}async function validateDiffScope(taskId,directory,attribution){try{let declaredScope=getDeclaredScope(taskId,directory);if(!declaredScope)return null;let normalise=(p)=>p.replace(/\\/g,"/").replace(/^\.\//,""),isSwarmPath2=(p)=>normalise(p).startsWith(".swarm/"),normScope=new Set(declaredScope.map(normalise)),canonicaliseAttributionEntry=(raw)=>{let resolved=path122.isAbsolute(raw)?path122.normalize(raw):path122.resolve(directory,raw),relative33=path122.relative(directory,resolved);if(!relative33)return null;if(relative33.startsWith("..")||path122.isAbsolute(relative33))return null;return relative33},attributed=attribution?.attributedFiles,undeclared,evidence2;if(Array.isArray(attributed)&&attributed.length>0){let normScopeAttribution=new Set(declaredScope.map(normalizePath));undeclared=attributed.filter((f)=>typeof f==="string"&&f.length>0).map(canonicaliseAttributionEntry).filter((entry)=>entry!==null).map(normalise).filter((f)=>!isSwarmPath2(f)).filter((f)=>!normScopeAttribution.has(normalizePath(f))),evidence2="task attribution record"}else{let{files,basis}=await getChangedFiles(directory);if(!files)return null;if(undeclared=files.filter((f)=>!isSwarmPath2(f)).map(normalise).filter((f)=>!normScope.has(f)),undeclared.length===0)return null;let sha=await getLatestCommitShortSha(directory),shaSuffix=sha?` ${sha}`:"";evidence2=basis==="HEAD"?`repository-wide uncommitted diff vs HEAD${shaSuffix}`:`repository-wide diff vs latest commit${shaSuffix}`}if(undeclared.length===0)return null;let scopeStr=declaredScope.join(", "),undeclaredStr=undeclared.slice(0,5).join(", "),extra=undeclared.length>5?` (+${undeclared.length-5} more)`:"";return`SCOPE WARNING: Task ${taskId} declared scope [${scopeStr}] but also modified [${undeclaredStr}${extra}] (evidence: ${evidence2}). Reviewer should verify these changes are intentional.`}catch{return null}}var _internals115,GIT_DIFF_SPAWN_OPTIONS;var init_diff_scope=__esm(()=>{init_bun_compat();init_git_executable();init_gitignore_warning();init_path();_internals115={bunSpawn,resolveGitExecutable};GIT_DIFF_SPAWN_OPTIONS={timeout:ENSURE_SWARM_GIT_EXCLUDED_PER_CALL_TIMEOUT_MS,stdin:"ignore",stdout:"pipe",stderr:"pipe"}});import*as fs78 from"node:fs";import*as path123 from"node:path";function verifyLeanTurboTaskCompletion(directory,taskId,sessionID){let persisted=null;try{let statePath2=path123.join(directory,".swarm","turbo-state.json");if(!fs78.existsSync(statePath2))return{ok:!1,reason:"Lean Turbo state file not found"};let raw=fs78.readFileSync(statePath2,"utf-8");persisted=JSON.parse(raw)}catch{return{ok:!1,reason:"Lean Turbo state file unreadable or malformed"}}if(typeof persisted!=="object"||persisted===null||typeof persisted.sessions!=="object"||persisted.sessions===null||Array.isArray(persisted.sessions))return{ok:!1,reason:"Lean Turbo state malformed: missing expected fields"};let runState=null;for(let sessionState of Object.values(persisted.sessions))if(typeof sessionState==="object"&&sessionState!==null&&sessionState.strategy==="lean"&&sessionState.status==="running"){if(sessionID!==void 0&&sessionState.sessionID!==sessionID)continue;runState=sessionState;break}if(!runState)return{ok:!1,reason:"No active Lean Turbo run state found"};if(!Array.isArray(runState.lanes)||!Array.isArray(runState.degradedTasks))return{ok:!1,reason:"Lean Turbo state malformed: missing expected fields"};let lane=runState.lanes.find((l)=>typeof l==="object"&&l!==null&&Array.isArray(l.taskIds)&&typeof l.laneId==="string"&&l.taskIds.includes(taskId));if(!lane)return{ok:!1,reason:`Task ${taskId} not found in any Lean Turbo lane`,laneFound:!1};let degradedTask=runState.degradedTasks.find((dt)=>typeof dt==="object"&&dt!==null&&dt.taskId===taskId);if(degradedTask)return{ok:!1,reason:`Task ${taskId} is degraded: ${degradedTask.reason}`,laneFound:!0};if(lane.status!=="completed")return{ok:!1,reason:`Lane ${lane.laneId} is not completed (status: ${lane.status})`,laneFound:!0,evidence:{laneId:lane.laneId,laneStatus:lane.status,taskIds:lane.taskIds}};if(lane.laneId.length===0||lane.laneId.includes("/")||lane.laneId.includes("\\")||lane.laneId.includes(".."))return{ok:!1,reason:`Lane ID contains invalid characters: ${lane.laneId}`,laneFound:!0,evidence:{laneId:lane.laneId,laneStatus:lane.status,taskIds:lane.taskIds}};let phase=runState.phase??0,evidencePath=path123.join(directory,".swarm","evidence",String(phase),"lean-turbo",`${lane.laneId}.json`),expectedDir=path123.join(directory,".swarm","evidence",String(phase),"lean-turbo"),resolvedPath=path123.resolve(evidencePath),resolvedDir=path123.resolve(expectedDir);if(!resolvedPath.startsWith(resolvedDir+path123.sep)&&resolvedPath!==resolvedDir)return{ok:!1,reason:`Lane ID causes path traversal: ${lane.laneId}`,laneFound:!0,evidence:{laneId:lane.laneId,laneStatus:lane.status,taskIds:lane.taskIds}};if(!fs78.existsSync(evidencePath))return{ok:!1,reason:`Lane ${lane.laneId} evidence file not found: ${evidencePath}`,laneFound:!0,evidence:{laneId:lane.laneId,laneStatus:lane.status,taskIds:lane.taskIds}};let laneLocks=_internals116.listActiveLocks(directory).filter((lock)=>lock.laneId===lane.laneId);if(laneLocks.length>0)return{ok:!1,reason:`Active file locks exist for lane ${lane.laneId}: ${laneLocks.map((l)=>l.filePath).join(", ")}`,laneFound:!0,evidence:{laneId:lane.laneId,laneStatus:lane.status,taskIds:lane.taskIds}};let filesTouched=[];try{let planPath=path123.join(directory,".swarm","plan.json"),planRaw=fs78.readFileSync(planPath,"utf-8"),plan=JSON.parse(planRaw);for(let planPhase of plan.phases??[])for(let task of planPhase.tasks??[])if(task.id===taskId&&task.files_touched){filesTouched=task.files_touched;break}}catch{return{ok:!1,reason:`Cannot verify Tier-3 patterns for task ${taskId}: plan.json unreadable`,laneFound:!0,evidence:{laneId:lane.laneId,laneStatus:lane.status,taskIds:lane.taskIds}}}if(filesTouched.length>0&&matchesTier3(filesTouched))return{ok:!1,reason:`Task ${taskId} touches Tier-3 security-sensitive files and cannot bypass Stage B`,laneFound:!0,evidence:{laneId:lane.laneId,laneStatus:lane.status,taskIds:lane.taskIds}};return{ok:!0,reason:`Task ${taskId} in completed lane ${lane.laneId}`,laneFound:!0,evidence:{laneId:lane.laneId,laneStatus:lane.status,taskIds:lane.taskIds}}}var _internals116;var init_task_completion=__esm(()=>{init_file_locks();init_tier3_classifier();_internals116={listActiveLocks,verifyLeanTurboTaskCompletion}});function applySessionWorkflowView(session,taskId,workflow){session.taskWorkflowStates.set(taskId,workflow.state),session.stageBCompletion?.delete(taskId),session.taskCouncilApproved?.delete(taskId),session.taskCouncilWorkflowGeneration?.delete(taskId),updateTaskWorkflowCache(session,taskId,workflow)}function isStageARecoveredState(state2){return STAGE_A_RECOVERED_STATES.includes(state2)}function shouldRefreshStageARecoveryView(view,recoveredState){if(view===void 0)return!0;if(view==="rework_required"||view==="blocked")return!0;if(view==="tests_run"||view==="closed"||view==="complete")return!1;return compareTaskWorkflowStateRank(recoveredState,view)>0}var STAGE_A_RECOVERED_STATES;var init_session_view=__esm(()=>{init_gate_evidence();init_state();STAGE_A_RECOVERED_STATES=["pre_check_passed","reviewer_run","tests_run"]});import*as fs79 from"node:fs";import*as path124 from"node:path";async function recordRunMemoryOutcome(directory,input){try{await _internals117.recordTaskAttempt(directory,input)}catch(_error){}}function syncCallerWorkflowFromEvidence(sessionId,taskId,evidence2){if(!sessionId)return;let callerSession=ensureAgentSession(sessionId),workflow=getTaskWorkflowSnapshot(evidence2);applySessionWorkflowView(callerSession,taskId,workflow)}async function hasPreparedWorkflowWal(directory,taskId,kind){return await readPreparedWorkflowWal(directory,taskId,kind)!==null}async function readPreparedWorkflowWal(directory,taskId,kind){let walPath2=validateSwarmPath(directory,kind==="task-repair"?`task-repairs/${taskId}.json`:`task-terminals/${taskId}.json`),wal=await readWorkflowWalFile(kind,walPath2,taskId);return wal?.state==="PREPARED"?wal:null}function resolveRunMemoryFileTargets(plan,taskId){return plan?.phases.flatMap((phase)=>phase.tasks).find((candidate)=>candidate.id===taskId)?.files_touched??[]}function validateStatus(status2){if(!VALID_STATUSES.includes(status2))return`Invalid status "${status2}". Must be one of: ${VALID_STATUSES.join(", ")}`;return}function validateTaskId(taskId){if(validateTaskIdFormat(taskId))return`Invalid task_id "${taskId}". Must match pattern N.M or N.M.P (e.g., "1.1", "1.2.3")`;return}function getSettledTransitionRejection(taskId,currentStatus,nextStatus,force){if(currentStatus!=="pending"&¤tStatus!=="in_progress"&&nextStatus!==currentStatus){if(nextStatus!=="in_progress"||force!==!0)return{success:!1,message:`Task ${taskId} is settled (${currentStatus}); backward transitions require the audited in_progress repair path.`,errors:[`Task ${taskId} is settled (${currentStatus}); use force:true with exact CAS and audit fields to repair it to in_progress.`]}}return null}function isRepairRetryShape(args2){return args2.status==="in_progress"&&args2.force===!0&&typeof args2.transition_id==="string"}function reviewerGateDecision(taskId,sessionID,result,reasonCode,evidenceKind){try{_internals117.emitReviewerGateDecision(sessionID??"",taskId,result.blocked,reasonCode,evidenceKind)}catch(_error){}return result}function hasPassedDurableGateEvidence(workingDirectory,taskId){let evidence2=readTaskEvidenceRaw(workingDirectory,taskId);if(!evidence2||!Array.isArray(evidence2.required_gates)||evidence2.required_gates.length===0)return!1;return evidence2.required_gates.every((gate)=>evidence2.gates?.[gate]!=null)}function routeGateAllowsTask(directory,taskId,sessionID){if(!directory)return!0;if(!(()=>{try{return loadPluginConfig(directory).review_routing?.enforce_receipts??!0}catch{return!0}})())return!0;let requirementReceipts=(()=>{try{return readTaskGateRequirementsReceiptsSync(directory,taskId)}catch{return null}})();if(!requirementReceipts)return!1;let session=sessionID?swarmState.agentSessions.get(sessionID):void 0,routeRequired=sessionID?session?isStageBRouteRequired(session,taskId):!1:[...swarmState.agentSessions.values()].some((candidate)=>isStageBRouteRequired(candidate,taskId)),legacyUnrouted=isLegacyTaskGateRequirementsChain(requirementReceipts)&&!routeRequired;if(!routeRequired&&requirementReceipts.length===0)return!0;let durableEvidence=routeEvidenceFromTaskGateRequirements(requirementReceipts),routeAllowsSession=(candidateSessionID,candidateSession)=>{try{readReviewRouteReceiptSync({projectRoot:directory,sessionId:candidateSessionID,taskId})}catch{return!1}let liveEvidence=candidateSession?getStageBRouteEvidence(candidateSession,taskId):[];return enforcePersistedReviewRouteReceipt({projectRoot:directory,sessionId:candidateSessionID,taskId,receipts:liveEvidence.length>0?liveEvidence:durableEvidence,enforcementEnabled:!0,legacyUnrouted:!1,requireEvidenceBindings:!0}).canAdvance};if(sessionID)return routeAllowsSession(sessionID,session);if(!routeRequired)return legacyUnrouted;let evidenceSessionIDs=new Set(durableEvidence.map((evidence2)=>evidence2.sessionId).filter((value)=>Boolean(value)));for(let[candidateSessionID,candidateSession]of swarmState.agentSessions){if(!isStageBRouteRequired(candidateSession,taskId)&&!evidenceSessionIDs.has(candidateSessionID))continue;if(routeAllowsSession(candidateSessionID,candidateSession))return!0}return!1}function checkReviewerGate(taskId,workingDirectory,stageBParallelEnabled=!1,sessionID,fallbackDir,currentDeclaredFiles){try{let skipStandardTurboBypass=!1;if(!fallbackDir&&!sessionID&&_internals117.hasActiveLeanTurbo(sessionID)){let resolvedDir2=workingDirectory;try{let leanCheck=_internals117.verifyLeanTurboTaskCompletion(resolvedDir2,taskId,sessionID);if(leanCheck.ok)return reviewerGateDecision(taskId,sessionID,{blocked:!1,reason:`Lean Turbo bypass: ${leanCheck.reason}`},"lean_turbo_completed_lane","fallback");if(leanCheck.laneFound!==!1)skipStandardTurboBypass=!0}catch{skipStandardTurboBypass=!0}}if(!fallbackDir&&!sessionID&&!skipStandardTurboBypass&&_internals117.hasActiveTurboMode(sessionID)){let resolvedDir2=workingDirectory;try{let planPath=path124.join(resolvedDir2,".swarm","plan.json"),planRaw=fs79.readFileSync(planPath,"utf-8"),plan=JSON.parse(planRaw);for(let planPhase of plan.phases??[])for(let task of planPhase.tasks??[])if(task.id===taskId&&Array.isArray(task.files_touched)&&task.files_touched.length>0){if(!matchesTier3(task.files_touched))return reviewerGateDecision(taskId,sessionID,{blocked:!1,reason:"Turbo Mode bypass"},"standard_turbo_non_tier3","fallback");break}}catch{}}let authoritativeDir;if(fallbackDir){let resolved=_internals117.resolveWorkingDirectory(workingDirectory,fallbackDir);authoritativeDir=resolved.success?resolved.directory:fallbackDir}else if(workingDirectory)authoritativeDir=workingDirectory;if(authoritativeDir){let legacyDirectCaller=Symbol("legacy-direct-reviewer-gate");try{let evidence2=_internals117.readTaskEvidenceRaw(authoritativeDir,taskId);if(!fallbackDir&&!sessionID&&!evidence2?.workflow)throw legacyDirectCaller;try{let planPath=path124.join(authoritativeDir,".swarm","plan.json"),planRaw=fs79.readFileSync(planPath,"utf-8"),plan=JSON.parse(planRaw),declaredTask=(plan.phases??[]).flatMap((phase)=>phase.tasks??[]).find((task)=>task.id===taskId);if(declaredTask&&declaredTask.evidence_class==="external_git"&&typeof plan.title==="string"&&typeof plan.swarm==="string"){let planIdentity={title:plan.title,swarm:plan.swarm},workflow2=getTaskWorkflowSnapshot(evidence2);if(isExternalEvidenceInitialCompletionEligible(planIdentity,declaredTask,evidence2)||workflow2.state==="complete"&&externalProofCurrent(planIdentity,declaredTask,evidence2))return reviewerGateDecision(taskId,sessionID,{blocked:!1,reason:`External evidence attested: task ${taskId} completed via the pinned external_git anchors (issue #3422)`,requiredGates:[],satisfiedGates:[],missingGates:[],source:"external_attest",generation:workflow2.generation},"durable_evidence_complete","fallback");return reviewerGateDecision(taskId,sessionID,{blocked:!0,reason:`Task ${taskId} declares external_git evidence but no matched attestation exists yet. Run /swarm attest ${taskId} (or re-plan it as a thin coder dispatch).`,requiredGates:[],satisfiedGates:[],missingGates:["external_attest"],source:"durable_exact_task",generation:workflow2.generation,nextAction:`Run /swarm attest ${taskId} (or re-plan it as a thin coder dispatch).`},"required_gates_missing","block")}}catch{}if(!evidence2)return reviewerGateDecision(taskId,sessionID,{blocked:!0,reason:`Task ${taskId} has no exact-task QA evidence. Delegate the required Stage B agents, then retry completion.`,requiredGates:[],satisfiedGates:[],missingGates:["reviewer","test_engineer"],source:"durable_exact_task",generation:0,nextAction:"Delegate reviewer and test_engineer for this exact task generation."},"required_gates_missing","block");if(!evidence2.workflow){let derivedGates2=deriveApplicableGateSet(evidence2);return reviewerGateDecision(taskId,sessionID,{blocked:!0,reason:`Task ${taskId} has legacy QA evidence without an authoritative workflow generation. Run a fresh exact-task workflow transition before completion.`,requiredGates:derivedGates2.requiredGates,satisfiedGates:derivedGates2.satisfiedGates,missingGates:derivedGates2.missingGates,source:"durable_exact_task",generation:0,nextAction:"Re-run the exact-task coder/Stage A/Stage B workflow to migrate evidence."},"required_gates_missing","block")}let workflow=getTaskWorkflowSnapshot(evidence2),derivedGates=deriveApplicableGateSet(evidence2,{currentDeclaredFiles:currentDeclaredFiles===void 0?readCurrentTaskDeclaredFiles(authoritativeDir,taskId):currentDeclaredFiles}),requiredGates=derivedGates.requiredGates,satisfiedGates=derivedGates.satisfiedGates,missingGates=derivedGates.missingGates;if(requiredGates.includes(TASK_GATE_REQUIREMENTS_RECONSTRUCTION_SENTINEL)){let recovery=`Task ${taskId} contains a legacy receipt-less gate-repair marker that no agent can satisfy. Call repair_gate_evidence for task ${taskId}, then delegate coder for a fresh accepted mutation before rerunning Stage A and Stage B.`;return reviewerGateDecision(taskId,sessionID,{blocked:!0,reason:recovery,requiredGates,satisfiedGates,missingGates,source:"durable_exact_task",generation:workflow.generation,nextAction:recovery},"required_gates_missing","data_quality")}let contradictorySignals=[];if((workflow.state==="tests_run"||workflow.state==="complete")&&missingGates.length>0)contradictorySignals.push(`workflow state ${workflow.state} claims completion readiness while required proof is missing`);if(workflow.state!=="tests_run"&&workflow.state!=="complete"&&evidence2.gates.pre_check!=null&&requiredGates.length>0&&missingGates.length===0)contradictorySignals.push(`all required proof exists but workflow state is ${workflow.state}`);let workflowComplete=workflow.state==="tests_run"||workflow.state==="complete";if(missingGates.length===0&&contradictorySignals.length===0&&(workflowComplete||derivedGates.readOnlyNoMutation)){if(!derivedGates.readOnlyNoMutation&&!routeGateAllowsTask(authoritativeDir,taskId,sessionID))return reviewerGateDecision(taskId,sessionID,{blocked:!0,reason:`Task ${taskId} has not satisfied its exact v1 review route receipt. Missing or mismatched route evidence fails closed.`,requiredGates,satisfiedGates,missingGates:["review_route_receipt"],source:"durable_exact_task",generation:workflow.generation,nextAction:"Recover the exact route receipt and independent Stage-B bindings before completing this task."},"required_gates_missing","block");return reviewerGateDecision(taskId,sessionID,{blocked:!1,reason:"",requiredGates,satisfiedGates,missingGates,contradictorySignals,source:"durable_exact_task",generation:workflow.generation},"durable_evidence_complete","genuine")}return reviewerGateDecision(taskId,sessionID,{blocked:!0,reason:`Task ${taskId} generation ${workflow.generation} has not passed exact-task QA. State: ${workflow.state}. Missing gates: [${missingGates.join(", ")}]. Contradictions: [${contradictorySignals.join("; ")}].`,requiredGates,satisfiedGates,missingGates,contradictorySignals,source:"durable_exact_task",generation:workflow.generation,nextAction:workflow.state==="rework_required"?"Delegate the same task to coder for repair, then rerun Stage A and Stage B.":"Complete the missing exact-task Stage A/Stage B transitions."},"required_gates_missing","block")}catch(error93){if(error93===legacyDirectCaller);else return reviewerGateDecision(taskId,sessionID,{blocked:!0,reason:`Evidence file for task ${taskId} is corrupt or unreadable: ${error93 instanceof Error?error93.message:String(error93)}. Call repair_gate_evidence for task ${taskId}; corrupt evidence fails closed until the repair completes.`,requiredGates:[],satisfiedGates:[],missingGates:["reviewer","test_engineer"],source:"durable_exact_task",corrupt:!0,nextAction:`Call repair_gate_evidence for task ${taskId}; corrupt evidence fails closed until the repair completes.`},"corrupt_evidence","data_quality")}}let resolvedDir;if(fallbackDir){let resolveResult=_internals117.resolveWorkingDirectory(workingDirectory,fallbackDir);if(resolveResult.success)resolvedDir=resolveResult.directory;else resolvedDir=fallbackDir}else if(workingDirectory)resolvedDir=workingDirectory;let routeAllowsStageB=(sessionId,_session)=>routeGateAllowsTask(resolvedDir,taskId,sessionId),evidenceIncompleteReason=null;try{if(!resolvedDir);else{let evidence2=_internals117.readTaskEvidenceRaw(resolvedDir,taskId);if(evidence2===null);else if(evidence2.required_gates&&Array.isArray(evidence2.required_gates)&&evidence2.gates){if(evidence2.required_gates.length>0&&evidence2.required_gates.every((gate)=>evidence2.gates[gate]!=null)){let routeSession=sessionID?swarmState.agentSessions.get(sessionID):void 0;if(!resolvedDir||routeAllowsStageB(sessionID,routeSession))return reviewerGateDecision(taskId,sessionID,{blocked:!1,reason:""},"durable_evidence_complete","genuine")}let missingGates=evidence2.required_gates.filter((gate)=>evidence2.gates[gate]==null);evidenceIncompleteReason=evidence2.required_gates.length===0?`Task ${taskId} has an evidence file with no required gates. Delegate reviewer and test_engineer before marking task as completed.`:`Task ${taskId} is missing required gates: [${missingGates.join(", ")}]. Required: [${evidence2.required_gates.join(", ")}]. Completed: [${Object.keys(evidence2.gates).join(", ")}]. Delegate the missing gate agents before marking task as completed.`}}}catch(error93){return log(`[gate-evidence] Evidence file for task ${taskId} is corrupt or unreadable:`,error93 instanceof Error?error93.message:String(error93)),telemetry.gateFailed("","qa_gate",taskId,"Evidence file corrupt or unreadable"),reviewerGateDecision(taskId,sessionID,{blocked:!0,reason:`Evidence file for task ${taskId} is corrupt or unreadable. Call repair_gate_evidence for task ${taskId}; corrupt evidence fails closed until the repair completes.`},"corrupt_evidence","data_quality")}if(swarmState.agentSessions.size===0&&!evidenceIncompleteReason)return reviewerGateDecision(taskId,sessionID,{blocked:!1,reason:""},"no_active_sessions","fallback");let validSessionCount=0;for(let[_sessionId,session]of swarmState.agentSessions){if(!(session.taskWorkflowStates instanceof Map))continue;validSessionCount++;let state2=getTaskState(session,taskId);if(state2==="tests_run"||state2==="complete"){if(resolvedDir&&!routeAllowsStageB(_sessionId,session))continue;return reviewerGateDecision(taskId,sessionID,{blocked:!1,reason:""},"workflow_state_complete","genuine")}if(stageBParallelEnabled&&hasBothStageBCompletions(session,taskId)&&(!resolvedDir||routeAllowsStageB(_sessionId,session)))return reviewerGateDecision(taskId,sessionID,{blocked:!1,reason:""},"stage_b_parallel_complete","genuine")}if(validSessionCount===0&&!evidenceIncompleteReason)return reviewerGateDecision(taskId,sessionID,{blocked:!1,reason:""},"zero_valid_sessions","data_quality");let stateEntries=[];for(let[sessionId,session]of swarmState.agentSessions){if(!(session.taskWorkflowStates instanceof Map))continue;let state2=getTaskState(session,taskId);stateEntries.push(`${sessionId}: ${state2}`)}if(resolvedDir)try{let planPath=path124.join(resolvedDir,".swarm","plan.json"),planRaw=fs79.readFileSync(planPath,"utf-8"),plan=JSON.parse(planRaw);for(let planPhase of plan.phases??[])for(let task of planPhase.tasks??[])if(task.id===taskId&&task.status==="completed"&&_internals117.hasPassedDurableGateEvidence(resolvedDir,taskId))return reviewerGateDecision(taskId,sessionID,{blocked:!1,reason:""},"restart_recovery_complete","genuine")}catch{}{let hasReviewer=!1,hasTestEngineer=!1;for(let[sessionId,chain]of swarmState.delegationChains){let session=swarmState.agentSessions.get(sessionId);if(session&&(session.currentTaskId===taskId||session.lastCoderDelegationTaskId===taskId))for(let delegation of chain){let target=stripKnownSwarmPrefix(delegation.to);if(target==="reviewer")hasReviewer=!0;if(target==="test_engineer")hasTestEngineer=!0}}if(hasReviewer&&hasTestEngineer)return reviewerGateDecision(taskId,sessionID,{blocked:!1,reason:""},"scoped_delegation_complete","genuine");if(!evidenceIncompleteReason&&(!hasReviewer||!hasTestEngineer)){for(let[sessionId,chain]of swarmState.delegationChains){if(chain.some((d)=>stripKnownSwarmPrefix(d.to)==="coder"))continue;let chainSession=swarmState.agentSessions.get(sessionId);if(chainSession){let chainTaskId=chainSession.currentTaskId||chainSession.lastCoderDelegationTaskId;if(chainTaskId&&chainTaskId!==taskId)continue}for(let delegation of chain){let target=stripKnownSwarmPrefix(delegation.to);if(target==="reviewer")hasReviewer=!0;if(target==="test_engineer")hasTestEngineer=!0}}if(hasReviewer&&hasTestEngineer)return reviewerGateDecision(taskId,sessionID,{blocked:!1,reason:""},"unscoped_delegation_complete","genuine")}}let currentStateStr=stateEntries.length>0?stateEntries.join(", "):"no active sessions",chainEntries=[];for(let[sessionId,chain]of swarmState.delegationChains){let session=swarmState.agentSessions.get(sessionId);if(session&&(session.currentTaskId===taskId||session.lastCoderDelegationTaskId===taskId)){let targets=chain.map((d)=>stripKnownSwarmPrefix(d.to));chainEntries.push(`${sessionId}: [${targets.join(", ")}]`)}}let chainSummary=chainEntries.length>0?chainEntries.join("; "):"no chains for this task",rehydratedSessionCount=[...swarmState.agentSessions.values()].filter((s)=>s.sessionRehydratedAt>0).length,finalReason=[`Task ${taskId} has not passed QA gates.`,` Session states: [${currentStateStr}].`,` Delegation chains: [${chainSummary}].`,` Evidence: [${evidenceIncompleteReason??"no evidence file found"}].`,` Rehydrated sessions: ${rehydratedSessionCount}.`," Missing required state: tests_run or complete."].join(`
|
|
1365
1365
|
`);return telemetry.gateFailed("","qa_gate",taskId,evidenceIncompleteReason?"Missing gates: evidence incomplete":"Missing state: tests_run or complete"),reviewerGateDecision(taskId,sessionID,{blocked:!0,reason:finalReason},"required_gates_missing","block")}catch{return reviewerGateDecision(taskId,sessionID,{blocked:!1,reason:""},"inspection_error","fallback")}}function hasForeignAttributionRecord(taskId,checkingSessionId){try{let checkerProject=swarmState.agentSessions.get(checkingSessionId)?.owningProjectKey??null;for(let[sessionId,session]of swarmState.agentSessions){if(sessionId===checkingSessionId)continue;if(!(session.modifiedFilesByTask instanceof Map))continue;if((session.owningProjectKey??null)!==checkerProject)continue;let entry=session.modifiedFilesByTask.get(taskId);if(Array.isArray(entry)&&entry.length>0)return!0}return!1}catch{return!1}}async function checkReviewerGateWithScope(taskId,workingDirectory,sessionID,fallbackDir){let result=checkReviewerGate(taskId,workingDirectory,!0,sessionID,fallbackDir),session=sessionID?getAgentSession(sessionID):void 0,attributedFiles=session?getModifiedFilesForTask(session,taskId):[],scopeAdvisoryLine=!!sessionID&&!hasModifiedFilesForTask(session,taskId)&&!!workingDirectory&&hasDeclaredDiffScope(taskId,workingDirectory)?hasForeignAttributionRecord(taskId,sessionID)?`SCOPE ADVISORY: attribution record for task ${taskId} exists under another session — not used for scope verification`:"SCOPE ADVISORY: no attribution record in this session — not used for scope verification":null,scopeWarning=await validateDiffScope(taskId,workingDirectory,sessionID&&attributedFiles.length>0?{attributedFiles}:void 0).catch(()=>null);if(!scopeWarning&&!scopeAdvisoryLine)return result;return{...result,reason:[result.reason,scopeWarning,scopeAdvisoryLine].filter((part)=>typeof part==="string"&&part.length>0).join(`
|
|
1366
1366
|
`)}}function recoverTaskStateFromDelegations(taskId,directory){let hasReviewer=!1,hasTestEngineer=!1;for(let[sessionId,chain]of swarmState.delegationChains){let session=swarmState.agentSessions.get(sessionId);if(session&&(session.currentTaskId===taskId||session.lastCoderDelegationTaskId===taskId))for(let delegation of chain){let target=stripKnownSwarmPrefix(delegation.to);if(target==="reviewer")hasReviewer=!0;if(target==="test_engineer")hasTestEngineer=!0}}let hasDurableIncompleteGates=!1;if(directory)try{let taskEvidence=readTaskEvidenceRaw(directory,taskId);if(taskEvidence?.gates&&Array.isArray(taskEvidence.required_gates)&&taskEvidence.required_gates.length>0){let gates=taskEvidence.gates;hasDurableIncompleteGates=taskEvidence.required_gates.some((g)=>gates[g]==null)}}catch{hasDurableIncompleteGates=!0}if(!hasDurableIncompleteGates&&(!hasReviewer||!hasTestEngineer))for(let[sessionId,chain]of swarmState.delegationChains){if(chain.some((d)=>stripKnownSwarmPrefix(d.to)==="coder"))continue;let chainSession=swarmState.agentSessions.get(sessionId);if(chainSession){let chainTaskId=chainSession.currentTaskId||chainSession.lastCoderDelegationTaskId;if(chainTaskId&&chainTaskId!==taskId)continue}for(let delegation of chain){let target=stripKnownSwarmPrefix(delegation.to);if(target==="reviewer")hasReviewer=!0;if(target==="test_engineer")hasTestEngineer=!0}}if((!hasReviewer||!hasTestEngineer)&&directory)try{let evidence2=readTaskEvidenceRaw(directory,taskId);if(evidence2?.gates&&Array.isArray(evidence2.required_gates)){if(evidence2.gates.reviewer!=null)hasReviewer=!0;if(evidence2.gates.test_engineer!=null)hasTestEngineer=!0}}catch{}if(!hasReviewer&&!hasTestEngineer)return;if(swarmState.agentSessions.size===0)try{startAgentSession("recovery-session","architect")}catch{}let recoveryRouteEnforcementEnabled=directory?(()=>{try{return loadPluginConfig(directory).review_routing?.enforce_receipts??!0}catch{return!0}})():!1;for(let[sessionId,session]of swarmState.agentSessions){if(!(session.taskWorkflowStates instanceof Map))continue;let routeEvidence=(()=>{let live=getStageBRouteEvidence(session,taskId);if(live.length>0)return live;try{return routeEvidenceFromTaskGateRequirements(readTaskGateRequirementsReceiptsSync(directory,taskId))}catch{return[]}})(),routeRequired=isStageBRouteRequired(session,taskId)||routeEvidence.length>0;if(directory&&recoveryRouteEnforcementEnabled&&routeRequired&&!enforcePersistedReviewRouteReceipt({projectRoot:directory,sessionId,taskId,receipts:routeEvidence,enforcementEnabled:!0,legacyUnrouted:(()=>{try{return!isStageBRouteRequired(session,taskId)&&isLegacyTaskGateRequirementsChain(readTaskGateRequirementsReceiptsSync(directory,taskId))}catch{return!1}})(),requireEvidenceBindings:!0}).canAdvance)continue;let currentState=getTaskState(session,taskId);if(currentState==="tests_run"||currentState==="complete")continue;if(hasReviewer&¤tState==="idle")try{advanceTaskState(session,taskId,"coder_delegated")}catch{}if(hasReviewer)recordStageBCompletion(session,taskId,"reviewer");if(hasTestEngineer)recordStageBCompletion(session,taskId,"test_engineer");if(hasReviewer){let stateNow=getTaskState(session,taskId);if(stateNow==="coder_delegated"||stateNow==="pre_check_passed")try{advanceTaskState(session,taskId,"reviewer_run")}catch{}}if(hasTestEngineer){if(getTaskState(session,taskId)==="reviewer_run")try{advanceTaskState(session,taskId,"tests_run")}catch{}}}}function checkCouncilGate(workingDirectory,taskId){let councilEnabled=!1,effectiveMinimum=3;try{let config3=loadPluginConfig(workingDirectory);councilEnabled=config3.council?.enabled===!0,effectiveMinimum=config3.council?.requireAllMembers?5:config3.council?.minimumMembers??3}catch{return{blocked:!1,reason:"",active:!1}}if(!councilEnabled)return{blocked:!1,reason:"",active:!1};try{let planPath=path124.join(workingDirectory,".swarm","plan.json"),planRaw=fs79.readFileSync(planPath,"utf-8"),planObj=JSON.parse(planRaw);if(planObj.swarm&&planObj.title){let lookup=getProfileLookupForIdentity(workingDirectory,planObj);if(lookup.kind==="bound"){if(!lookup.profile.gates.council_mode)return{blocked:!1,reason:"",active:!1}}else if(lookup.kind==="unbound_legacy"){if(lookup.profile.gates.council_mode)return{blocked:!0,reason:`council gate required but the QA gate profile is not exact-bound to the current raw swarm_id/plan_title. ${formatLegacyQaBindingRecovery({swarm:planObj.swarm,title:planObj.title},"retry advancing this task")}`,active:!0};return{blocked:!1,reason:"",active:!1}}else return{blocked:!1,reason:"",active:!1}}}catch{return{blocked:!1,reason:"",active:!1}}let evidence2;try{evidence2=readTaskEvidenceRaw(workingDirectory,taskId)}catch{return{blocked:!0,reason:"council gate required but not yet run — architect must call submit_council_verdicts before advancing this task",active:!0}}let councilGate=evidence2?.gates?.council;if(!councilGate)return{blocked:!0,reason:"council gate required but not yet run — architect must call submit_council_verdicts before advancing this task",active:!0};let councilWorkflow=getTaskWorkflowSnapshot(evidence2);if(!councilWorkflow.authoritative||councilWorkflow.state!=="pre_check_passed"||councilGate.workflowGeneration!==councilWorkflow.generation)return{blocked:!0,reason:`council gate evidence is stale or unbound: expected pre_check_passed@${councilWorkflow.generation}, recorded generation ${String(councilGate.workflowGeneration)}`,active:!0};if(councilGate.verdict==="REJECT")return{blocked:!0,reason:"council gate blocked advancement — resolve requiredFixes and re-run submit_council_verdicts",active:!0};let rawQuorumSize=councilGate.quorumSize,quorumSize=typeof rawQuorumSize==="number"&&Number.isFinite(rawQuorumSize)&&rawQuorumSize>=1?rawQuorumSize:1;if(quorumSize<effectiveMinimum)return{blocked:!0,reason:`council gate blocked advancement — recorded verdict has insufficient quorum (${quorumSize} of ${effectiveMinimum} required members). Re-run submit_council_verdicts with the missing council members.`,active:!0};return{blocked:!1,reason:"",active:!0}}async function executeUpdateTaskStatus(args2,fallbackDir,ctx){let statusError=validateStatus(args2.status);if(statusError)return{success:!1,message:"Validation failed",errors:[statusError]};let taskIdError=validateTaskId(args2.task_id);if(taskIdError)return{success:!1,message:"Validation failed",errors:[taskIdError]};let directory,resolveResult=_internals117.resolveWorkingDirectory(args2.working_directory,fallbackDir);if(!resolveResult.success)return{success:!1,message:resolveResult.message,errors:[resolveResult.message]};directory=resolveResult.directory;try{assertProjectRoot(directory)}catch(error93){let message=error93 instanceof Error?error93.message:String(error93);return{success:!1,message,errors:[message]}}let planPath=path124.join(directory,".swarm","plan.json");if(!fs79.existsSync(planPath))return{success:!1,message:`Invalid working_directory: plan not found in "${directory}"`,errors:[`Invalid working_directory: plan not found in "${directory}"`]};if(fallbackDir&&directory!==fallbackDir){let canonicalDir=fs79.realpathSync(path124.resolve(directory)),canonicalRoot=fs79.realpathSync(path124.resolve(fallbackDir));if(isStrictPathDescendant(canonicalDir,canonicalRoot)&&!hasExplicitProjectBoundary(canonicalDir))return{success:!1,message:`Invalid working_directory: "${directory}" is a subdirectory of the project root "${fallbackDir}". Pass the project root path or omit working_directory entirely.`,errors:[`Subdirectory rejected: use project root "${fallbackDir}" instead`]}}let exactRepairRetry=!1;if(isRepairRetryShape(args2))try{let repairWal=await readWorkflowWalFile("task-repair",validateSwarmPath(directory,`task-repairs/${args2.task_id}.json`),args2.task_id);exactRepairRetry=repairWal?.state==="PREPARED"&&repairWal.transitionId===args2.transition_id}catch(error93){return{success:!1,message:"Task operation paused while recovering an interrupted task repair",errors:[error93 instanceof Error?error93.message:String(error93)]}}try{let recoveredCoder=await recoverCoderSettlement(directory,args2.task_id);if(recoveredCoder&&ctx?.sessionID){let callerSession=ensureAgentSession(ctx.sessionID),workflow=getTaskWorkflowSnapshot(recoveredCoder.evidence);callerSession.taskWorkflowStates.set(args2.task_id,workflow.state),callerSession.stageBCompletion?.delete(args2.task_id),updateTaskWorkflowCache(callerSession,args2.task_id,workflow)}}catch(error93){return{success:!1,message:"Task operation paused while recovering an interrupted coder settlement",errors:[error93 instanceof Error?error93.message:String(error93)]}}try{let recoveredTerminal=await recoverPreparedTaskTerminal(directory,args2.task_id,ctx?.sessionID??"update-task-status");if(recoveredTerminal)syncCallerWorkflowFromEvidence(ctx?.sessionID,args2.task_id,recoveredTerminal.evidence)}catch(error93){return{success:!1,message:"Task operation paused while recovering an interrupted terminal status transition",errors:[error93 instanceof Error?error93.message:String(error93)]}}if(!exactRepairRetry)try{if(await recoverPreparedTaskRepair(directory,args2.task_id,ctx?.sessionID??"update-task-status"))syncCallerWorkflowFromEvidence(ctx?.sessionID,args2.task_id,readTaskEvidenceRaw(directory,args2.task_id))}catch(error93){if(error93 instanceof Error&&error93.message.startsWith("TASK_REPAIR_AUDIT_LOCKED"))criticalWarn(`[update-task-status] task-repair audit recovery deferred for ${args2.task_id}: ${error93.message}`);else return{success:!1,message:"Task operation paused while recovering an interrupted task repair",errors:[error93 instanceof Error?error93.message:String(error93)]}}let loadedPlan=null;try{loadedPlan=await _internals117.loadPlan(directory)}catch(error93){return{success:!1,message:"Failed to load plan for task validation",errors:[error93 instanceof Error?error93.message:String(error93)]}}if(!loadedPlan)return{success:!1,message:"Failed to load plan for task validation",errors:["Plan could not be loaded"]};if(loadedPlan._ledgerReplayStale===!0){let staleReason=loadedPlan._ledgerReplayStaleReason??"plan.json is stale relative to the active plan-ledger authority";return{success:!1,message:`Task status update refused: plan.json is stale relative to the ledger (ledger replay failed). ${staleReason}`,errors:[staleReason],recovery_guidance:"Plan state could not be reconciled with the active plan-ledger authority. Retry save_plan with the unchanged loaded plan so it can reconverge the projections and authority metadata, then retry update_task_status."}}let currentTask=loadedPlan.phases.flatMap((phase)=>phase.tasks).find((task)=>task.id===args2.task_id);if(!currentTask)return{success:!1,message:"Failed to update task status",errors:[`Task not found: ${args2.task_id}`]};{let settledRejection=getSettledTransitionRejection(args2.task_id,currentTask.status,args2.status,args2.force);if(settledRejection)return settledRejection}if(args2.status==="in_progress"&&args2.force===!0){if(!(typeof args2.expected_state==="string"&&args2.expected_state.length>0&&Number.isInteger(args2.expected_generation)&&(args2.expected_generation??-1)>=0&&args2.target_state==="idle"&&typeof args2.reason==="string"&&args2.reason.trim().length>0&&args2.reason.length<=2000&&typeof args2.transition_id==="string"&&args2.transition_id.trim().length>0&&args2.transition_id.length<=200))return{success:!1,message:"TASK_REPAIR_INVALID: force repair requires an exact CAS and audit identity",errors:['Provide expected_state, expected_generation, target_state="idle", a non-empty reason (max 2000 chars), and a non-empty transition_id (max 200 chars).']};log(`[update-task-status] Force-override: attempting audited repair for task ${args2.task_id} (settled task, or in_progress at the retry-escalation rung per issue #3389; admission is verified under the plan lock) to in_progress`)}let agentName=(ctx?.sessionID?swarmState.activeAgent.get(ctx.sessionID):void 0)??"update-task-status",scopeAdvisories;if(args2.status==="completed"){if(!fallbackDir&&!ctx?.sessionID)recoverTaskStateFromDelegations(args2.task_id,directory);let phaseRequiresReviewer=!0,taskDeclaresExternalEvidence=!1;try{let planPath2=path124.join(directory,".swarm","plan.json"),planRaw=fs79.readFileSync(planPath2,"utf-8"),taskPhase=JSON.parse(planRaw).phases.find((p)=>p.tasks.some((t)=>t.id===args2.task_id));if(taskPhase?.required_agents&&!taskPhase.required_agents.includes("reviewer"))phaseRequiresReviewer=!1;taskDeclaresExternalEvidence=taskPhase?.tasks.find((t)=>t.id===args2.task_id)?.evidence_class==="external_git"}catch{}let councilCheck=taskDeclaresExternalEvidence?{blocked:!1,active:!1}:checkCouncilGate(directory,args2.task_id);if(councilCheck.blocked)return await recordRunMemoryOutcome(directory,{taskId:args2.task_id,agent:agentName,outcome:"fail",failureReason:`council gate: ${councilCheck.reason}`,fileTargets:resolveRunMemoryFileTargets(loadedPlan,args2.task_id)}),{success:!1,message:"Gate check failed: council gate not yet satisfied for task "+args2.task_id,errors:[councilCheck.reason]};if(phaseRequiresReviewer&&!councilCheck.active&&!taskDeclaresExternalEvidence){let reviewerCheck=await checkReviewerGateWithScope(args2.task_id,directory,ctx?.sessionID,ctx?.sessionID?fallbackDir:void 0);if(reviewerCheck.reason){let advisoryLines=reviewerCheck.reason.split(`
|
|
1367
|
-
`).filter((line)=>line.length>0);if(advisoryLines.length>0)scopeAdvisories=advisoryLines}if(reviewerCheck.blocked)return await recordRunMemoryOutcome(directory,{taskId:args2.task_id,agent:agentName,outcome:"fail",failureReason:`QA gate: ${reviewerCheck.reason}`,fileTargets:resolveRunMemoryFileTargets(loadedPlan,args2.task_id)}),{success:!1,message:"Gate check failed: required QA gates not yet satisfied for task "+args2.task_id,errors:[reviewerCheck.reason]}}}let lockTaskId=`update-task-status-${args2.task_id}-${Date.now()}`,planFilePath="plan.json",lockResult;try{lockResult=await _internals117.tryAcquireLock(directory,planFilePath,agentName,lockTaskId)}catch(error93){return{success:!1,message:"Failed to acquire lock for task status update",errors:[error93 instanceof Error?error93.message:String(error93)]}}if(!lockResult.acquired)return{success:!1,message:`Task status write blocked: plan.json is locked by ${lockResult.existing?.agent??"another agent"} (task: ${lockResult.existing?.taskId??"unknown"})`,errors:["Concurrent plan write detected — retry after the current write completes"],recovery_guidance:"Wait a moment and retry update_task_status. The lock will expire automatically if the holding agent fails."};try{let lockedPlan=await _internals117.loadPlan(directory);if(lockedPlan?._ledgerReplayStale===!0)return{success:!1,message:"Task status update refused: plan became ledger-stale while waiting for the lock",errors:[lockedPlan._ledgerReplayStaleReason??"plan.json is stale relative to the authoritative ledger"],recovery_guidance:"Retry save_plan with the unchanged loaded plan to reconverge the projection/hash, then retry update_task_status."};if(!lockedPlan)return{success:!1,message:"Failed to update task status",errors:["No approved plan is available under the plan lock"]};let authoritativePlan=lockedPlan,lockedPreparedRepairWal=await readPreparedWorkflowWal(directory,args2.task_id,"task-repair"),lockedExactRepairRetry=isRepairRetryShape(args2)&&lockedPreparedRepairWal?.transitionId===args2.transition_id;if(lockedPreparedRepairWal&&!lockedExactRepairRetry)try{let recoveredRepair=await recoverPreparedTaskRepairUnderPlanLock(directory,args2.task_id,ctx?.sessionID??"update-task-status",authoritativePlan);if(recoveredRepair)authoritativePlan=recoveredRepair.plan,syncCallerWorkflowFromEvidence(ctx?.sessionID,args2.task_id,readTaskEvidenceRaw(directory,args2.task_id))}catch(error93){if(error93 instanceof Error&&error93.message.startsWith("TASK_REPAIR_AUDIT_LOCKED"))criticalWarn(`[update-task-status] task-repair audit recovery deferred for ${args2.task_id}: ${error93.message}`);else return{success:!1,message:"Task operation paused while recovering an interrupted task repair",errors:[error93 instanceof Error?error93.message:String(error93)]}}if(await hasPreparedWorkflowWal(directory,args2.task_id,"task-terminal"))try{let recoveredTerminal=await recoverPreparedTaskTerminalUnderPlanLock(directory,args2.task_id,ctx?.sessionID??"update-task-status",authoritativePlan);if(recoveredTerminal)authoritativePlan=recoveredTerminal.plan,syncCallerWorkflowFromEvidence(ctx?.sessionID,args2.task_id,recoveredTerminal.evidence)}catch(error93){return{success:!1,message:"Task operation paused while recovering an interrupted terminal status transition",errors:[error93 instanceof Error?error93.message:String(error93)]}}let lockedTask=authoritativePlan.phases.flatMap((phase)=>phase.tasks).find((task)=>task.id===args2.task_id);if(!lockedTask)return{success:!1,message:"Failed to update task status",errors:[`Task not found: ${args2.task_id}`]};let lockedSettledRejection=getSettledTransitionRejection(args2.task_id,lockedTask.status,args2.status,args2.force);if(lockedSettledRejection)return lockedSettledRejection;let repairResult=args2.status==="in_progress"&&args2.force===!0?await repairTaskWorkflowUnderPlanLock({directory,taskId:args2.task_id,actor:agentName,reason:args2.reason,transitionId:args2.transition_id,expectedState:args2.expected_state,expectedGeneration:args2.expected_generation,currentPlanStatus:lockedTask.status,currentPlan:authoritativePlan,updatePlan:()=>_internals117.updateTaskStatus(directory,args2.task_id,"in_progress",{force:!0,planLockAlreadyHeld:!0})}):null,updatedPlan,terminalEvidence=null;if(args2.status==="completed"){let lockedTaskPhase=authoritativePlan.phases.find((phase)=>phase.tasks.some((task)=>task.id===args2.task_id)),lockedPhaseRequiresReviewer=!lockedTaskPhase?.required_agents||lockedTaskPhase.required_agents.includes("reviewer"),lockedTaskDeclaresExternal=lockedTask.evidence_class==="external_git",terminalResult=await commitTaskTerminalUnderPlanLock({directory,taskId:args2.task_id,actor:agentName,transitionId:`plan-status:${args2.task_id}:completed:${Date.now()}`,currentPlanStatus:lockedTask.status,targetStatus:"completed",qaExempt:!lockedPhaseRequiresReviewer&&!lockedTaskDeclaresExternal,resolveTerminal:(evidence2)=>({targetStatus:"completed",qaExempt:!lockedPhaseRequiresReviewer&&!lockedTaskDeclaresExternal,readOnlyNoMutation:!lockedPhaseRequiresReviewer?!1:isReadOnlyNoMutationEligible(evidence2,{currentDeclaredFiles:lockedTask.files_touched}),externalEvidence:lockedTaskDeclaresExternal}),currentPlan:authoritativePlan,validateEvidence:async()=>{if(lockedTaskDeclaresExternal){let externalTaskEvidence=_internals117.readTaskEvidenceRaw(directory,args2.task_id),planIdentity={title:authoritativePlan.title,swarm:authoritativePlan.swarm},externalWorkflow=getTaskWorkflowSnapshot(externalTaskEvidence);if(!isExternalEvidenceInitialCompletionEligible(planIdentity,lockedTask,externalTaskEvidence)&&!(externalWorkflow.state==="complete"&&externalProofCurrent(planIdentity,lockedTask,externalTaskEvidence)))throw Error(`TASK_COMPLETION_CAS_MISMATCH: Task ${args2.task_id} declares external_git evidence but has no current matched attestation; run /swarm attest ${args2.task_id} first`);return}let lockedGate=checkReviewerGate(args2.task_id,directory,!1,ctx?.sessionID,fallbackDir??directory,lockedTask.files_touched??null),lockedCouncil=checkCouncilGate(directory,args2.task_id);if(lockedCouncil.blocked||lockedPhaseRequiresReviewer&&!lockedCouncil.active&&lockedGate.blocked)throw Error(`TASK_COMPLETION_CAS_MISMATCH: ${lockedCouncil.blocked?lockedCouncil.reason:lockedGate.reason}`)},updatePlan:async()=>{let next=await _internals117.updateTaskStatus(directory,args2.task_id,"completed",{force:!1,planLockAlreadyHeld:!0});if(next.phases.flatMap((phase)=>phase.tasks).find((task)=>task.id===args2.task_id)?.status!=="completed")throw Error("TASK_STATUS_WRITE_NOT_APPLIED");return next}});updatedPlan=terminalResult.plan,terminalEvidence=terminalResult.evidence}else if(args2.status==="blocked"){let terminalResult=await commitTaskTerminalUnderPlanLock({directory,taskId:args2.task_id,actor:agentName,transitionId:`plan-status:${args2.task_id}:blocked:${Date.now()}`,currentPlanStatus:lockedTask.status,targetStatus:"blocked",qaExempt:!1,currentPlan:authoritativePlan,updatePlan:async()=>{let next=await _internals117.updateTaskStatus(directory,args2.task_id,"blocked",{force:!1,planLockAlreadyHeld:!0});if(next.phases.flatMap((phase)=>phase.tasks).find((task)=>task.id===args2.task_id)?.status!=="blocked")throw Error("TASK_STATUS_WRITE_NOT_APPLIED");return next}});updatedPlan=terminalResult.plan,terminalEvidence=terminalResult.evidence}else if(updatedPlan=repairResult?.plan??await _internals117.updateTaskStatus(directory,args2.task_id,args2.status,{force:!1,planLockAlreadyHeld:!0}),updatedPlan.phases.flatMap((phase)=>phase.tasks).find((task)=>task.id===args2.task_id)?.status!==args2.status)throw Error("TASK_STATUS_WRITE_NOT_APPLIED");if(terminalEvidence){let terminal=getTaskWorkflowSnapshot(terminalEvidence),callerSession=ctx?.sessionID?swarmState.agentSessions.get(ctx.sessionID):void 0;if(callerSession){let session=callerSession;session.taskWorkflowStates.set(args2.task_id,terminal.state),session.stageBCompletion?.delete(args2.task_id),updateTaskWorkflowCache(session,args2.task_id,terminal)}}if(args2.status==="in_progress"){if(ctx?.sessionID)ensureAgentSession(ctx.sessionID).currentTaskId=args2.task_id;if(repairResult){let callerSession=ctx?.sessionID?swarmState.agentSessions.get(ctx.sessionID):void 0;if(callerSession){let session=callerSession;session.taskWorkflowStates.set(args2.task_id,"idle"),session.stageBCompletion?.delete(args2.task_id),session.taskCouncilApproved?.delete(args2.task_id),session.taskCouncilWorkflowGeneration?.delete(args2.task_id),updateTaskWorkflowCache(session,args2.task_id,{generation:repairResult.generation})}}}return{success:!0,message:"Task status updated successfully",task_id:args2.task_id,new_status:args2.status,current_phase:updatedPlan.current_phase,...scopeAdvisories&&scopeAdvisories.length>0?{warnings:scopeAdvisories}:{}}}catch(error93){return{success:!1,message:"Failed to update task status",errors:[error93 instanceof Error?error93.message:String(error93)]}}finally{if(lockResult?.acquired&&lockResult.lock._release)try{await lockResult.lock._release()}catch(releaseError){log("[update-task-status] Lock release failed:",releaseError)}}}var _internals117,VALID_STATUSES,update_task_status;var init_update_task_status=__esm(()=>{init_zod();init_loader();init_schema();init_qa_gate_profile();init_task_gate_requirements();init_gate_evidence();init_diff_scope();init_utils2();init_file_locks();init_tier3_classifier();init_manager();init_routing_enforcement();init_run_memory();init_state();init_telemetry();init_task_completion();init_logger();init_project_boundary();init_task_id();init_coder_settlement();init_session_view();init_task_repair();init_task_terminal();init_workflow_wal_file();init_create_tool();init_resolve_working_directory();_internals117={tryAcquireLock,updateTaskStatus,resolveWorkingDirectory,loadPlan,readTaskEvidenceRaw,hasActiveLeanTurbo,hasActiveTurboMode,verifyLeanTurboTaskCompletion,hasPassedDurableGateEvidence,emitReviewerGateDecision:telemetry.reviewerGateDecision,recordTaskAttempt};VALID_STATUSES=["pending","in_progress","completed","blocked"];update_task_status=createSwarmTool({description:"Update the status of a specific task in the implementation plan. Task status can be one of: pending, in_progress, completed, blocked.",args:{task_id:exports_external.string().min(1).regex(/^\d+\.\d+(\.\d+)*$/,"Task ID must be in N.M or N.M.P format").describe('Task ID in N.M format, e.g. "1.1", "1.2.3"'),status:exports_external.enum(["pending","in_progress","completed","blocked"]).describe("New status for the task: pending, in_progress, completed, or blocked"),working_directory:exports_external.string().optional().describe("Working directory where the plan is located"),force:exports_external.boolean().optional().default(!1).describe('Enable the audited repair contract: re-open a settled task, or an in_progress task that reached the retry ladder user_escalation rung (issue #3389). Requires expected_state, expected_generation, target_state="idle", reason, and transition_id.'),expected_state:exports_external.string().optional().describe("CAS workflow state expected by a force repair."),expected_generation:exports_external.number().int().min(0).optional().describe("ABA-safe workflow generation expected by a force repair."),target_state:exports_external.literal("idle").optional().describe("Repair target state. The only valid target is idle (re-opens the task for new work)."),reason:exports_external.string().min(1).max(2000).optional().describe("Required human-readable audit reason for a force repair."),transition_id:exports_external.string().min(1).max(200).optional().describe("Caller-generated idempotency key for an audited force repair.")},execute:async(args2,_directory2,_ctx)=>{return JSON.stringify(await executeUpdateTaskStatus(args2,_directory2,_ctx),null,2)}})});var exports_attest_task={};__export(exports_attest_task,{executeAttestTask:()=>executeAttestTask,buildAnchorArgv:()=>buildAnchorArgv,_internals:()=>_internals118});import*as fs80 from"node:fs";import*as path125 from"node:path";function anchorEnv(){let env={PATH:process.env.PATH,HOME:process.env.HOME,LANG:process.env.LANG,LC_ALL:process.env.LC_ALL,GIT_CONFIG_NOSYSTEM:"1"};if(process.platform==="win32")env.SYSTEMROOT=process.env.SYSTEMROOT,env.WINDIR=process.env.WINDIR,env.COMSPEC=process.env.COMSPEC;return{env,envOverrides:{GIT_EXTERNAL_DIFF:null,GIT_CONFIG_PARAMETERS:null,GIT_CONFIG_COUNT:null,GIT_DIR:null,GIT_WORK_TREE:null,GIT_INDEX_FILE:null,GIT_SSH_COMMAND:null,GIT_ASKPASS:null,GIT_EXEC_PATH:null,GIT_PAGER:null}}}function buildAnchorArgv(command){let tokens2=command.trim().split(/\s+/).filter(Boolean);if(tokens2[0]!=="git"||tokens2.length<2)return{argv:null,refusal:`anchor command is not an allowed read-only git invocation: "${command}"`};let subcommand=tokens2[1];if(subcommand.startsWith("-"))return{argv:null,refusal:`anchor command smuggles a git global option ("${subcommand}"); only bare read-only git subcommands are allowed`};let allowed=READ_ONLY_GIT_FLAGS[subcommand];if(!allowed)return{argv:null,refusal:`git "${subcommand}" is not in the read-only git subcommand allowlist (rev-list, log, rev-parse, show, diff)`};let finalTokens=[subcommand];for(let i=2;i<tokens2.length;i++){let token=tokens2[i];if(token.startsWith("-")){let eq=token.indexOf("="),flag=eq>=0?token.slice(0,eq):token,inlineValue=eq>=0?token.slice(eq+1):void 0,arity2=allowed[flag];if(arity2===void 0)return{argv:null,refusal:`flag "${flag}" is not in the read-only git allowlist for git ${subcommand}`};if(arity2===0){if(inlineValue!==void 0)return{argv:null,refusal:`flag "${flag}" takes no value; =-joined forms are not valid for it`};finalTokens.push(flag)}else{let value=inlineValue;if(value===void 0){let next=tokens2[i+1];if(next===void 0||next.startsWith("--"))return{argv:null,refusal:`flag "${flag}" requires a value token`};value=next,i++}finalTokens.push(flag.startsWith("--")?`${flag}=${value}`:`${flag}${value}`)}continue}let hasControlByte=Array.from(token).some((ch)=>ch.charCodeAt(0)<32||ch.charCodeAt(0)===127);if(token.length>400||hasControlByte)return{argv:null,refusal:"anchor argument is too long or contains control bytes"};if(REMOTE_HELPER_PATTERN.test(token))return{argv:null,refusal:`anchor argument "${token.slice(0,32)}" looks like a remote-helper URL; remote helpers can execute commands and are not read-only git invocations`};finalTokens.push(token)}if(subcommand==="diff"||subcommand==="show"||subcommand==="log")finalTokens.push("--no-ext-diff","--no-textconv");return{argv:[resolveGitExecutable(),"--no-pager","-c","diff.external=","-c","core.pager=cat","-c","core.fsmonitor=","-c","gpg.program=","-c","credential.helper=",...finalTokens],refusal:null}}async function runAnchor(argv,cwd,timeoutMs){let{env,envOverrides}=anchorEnv(),proc=bunSpawn(argv,{cwd,env,envOverrides,stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:timeoutMs,maxBuffer:ANCHOR_SPAWN_MAX_BUFFER_BYTES});try{let exited=await proc.exited,stdout;try{stdout=await proc.stdout.text()}catch{return{exitCode:exited,stdout:"",refusal:`anchor output exceeded the ${Math.floor(ANCHOR_SPAWN_MAX_BUFFER_BYTES/1024)}KB spawn capture buffer; refusing rather than truncating`}}if(exited!==0){let detail=(await proc.stderr.text()).trim().slice(0,200);return{exitCode:exited,stdout,refusal:`anchor command exited with code ${exited}${detail?`: ${detail}`:""}`}}return{exitCode:exited,stdout,refusal:null}}finally{try{proc.kill()}catch{}}}function validateAnchorExpectations(anchors){for(let anchor of anchors){if(anchor.expect===void 0&&anchor.expect_prefix===void 0)return`anchor "${anchor.command.slice(0,60)}" declares neither expect nor expect_prefix`;if(anchor.expect_prefix!==void 0&&anchor.expect_prefix.length===0)return`anchor "${anchor.command.slice(0,60)}" declares an empty expect_prefix, which would match any output`}return null}async function executeAttestTask(args2,fallbackDir){let resolveResult=_internals117.resolveWorkingDirectory(args2.working_directory,fallbackDir);if(!resolveResult.success)return{success:!1,message:resolveResult.message,errors:[resolveResult.message]};let directory=resolveResult.directory;try{assertProjectRoot(directory)}catch(error93){let message=error93 instanceof Error?error93.message:String(error93);return{success:!1,message,errors:[message]}}let found;try{found=_internals118.loadPlanTask(directory,args2.task_id)}catch(error93){let message=error93 instanceof Error?error93.message:String(error93);if(message.includes("expect_prefix")||message.includes("evidence_anchors"))return{success:!1,message:"the plan declares an invalid external-evidence anchor: every anchor must carry expect and/or a non-empty expect_prefix (an empty prefix would match any output)",errors:["the plan declares an invalid external-evidence anchor: every anchor must carry expect and/or a non-empty expect_prefix (an empty prefix would match any output)"],task_id:args2.task_id};let refusal=`the plan at ${directory} is invalid or unreadable; fix or re-save the plan before attesting`;return{success:!1,message:refusal,errors:[`${refusal} (${message.slice(0,160)})`],task_id:args2.task_id}}if(!found){let message=`Task ${args2.task_id} not found in the plan at ${directory}`;return{success:!1,message,errors:[message],task_id:args2.task_id}}if(found.task.evidence_class!=="external_git"){let message=`Task ${args2.task_id} does not declare evidence_class external_git; the attest path is fail-closed to explicitly declared external-evidence tasks (issue #3422)`;return{success:!1,message,errors:[message],task_id:args2.task_id}}let anchors=found.task.evidence_anchors??[];if(anchors.length===0){let message=`Task ${args2.task_id} declares external_git evidence but pins no evidence_anchors`;return{success:!1,message,errors:[message],task_id:args2.task_id}}let malformed=validateAnchorExpectations(anchors);if(malformed)return{success:!1,message:malformed,errors:[malformed],task_id:args2.task_id};let startedAt=Date.now(),outcomes=[];for(let anchor of anchors){let{argv,refusal}=_internals118.buildAnchorArgv(anchor.command);if(refusal!==null||argv===null){let message=`anchor not admitted: ${refusal??"not an allowed read-only git invocation"}`;return{success:!1,message,errors:[message],task_id:args2.task_id}}let remaining=ATTEST_TOTAL_DEADLINE_MS-(Date.now()-startedAt);if(remaining<=0)return{success:!1,message:"attest total deadline (30s) exhausted before all anchors ran",errors:["attest total deadline (30s) exhausted before all anchors ran"],task_id:args2.task_id};let run=await _internals118.runAnchor(argv,directory,Math.min(ANCHOR_SPAWN_TIMEOUT_MS,remaining));if(run.refusal!==null){let message=`anchor "${anchor.command.slice(0,60)}" failed: ${run.refusal}`;return{success:!1,message,errors:[message],task_id:args2.task_id}}if(run.stdout.length>ANCHOR_STDOUT_MAX_CHARS){let message=`anchor "${anchor.command.slice(0,60)}" produced ${run.stdout.length} chars of stdout, exceeding the ${ANCHOR_STDOUT_MAX_CHARS}-char evidence storage bound; refusing rather than truncating`;return{success:!1,message,errors:[message],task_id:args2.task_id}}let trimmed=run.stdout.trim(),matched=anchor.expect!==void 0?trimmed===anchor.expect&&(anchor.expect_prefix===void 0||trimmed.startsWith(anchor.expect_prefix)):trimmed.startsWith(anchor.expect_prefix);outcomes.push({command:anchor.command,expect:anchor.expect,expect_prefix:anchor.expect_prefix,matched,exit_code:run.exitCode,stdout:run.stdout})}if(!outcomes.every((outcome)=>outcome.matched)){let failed=outcomes.find((outcome)=>!outcome.matched),message=`anchor "${failed?.command.slice(0,60)??"?"}" did not match its expectation (stdout: ${JSON.stringify(failed?.stdout.slice(0,120)??"")})`;return{success:!1,message,errors:[message],task_id:args2.task_id}}let current;try{current=_internals118.loadPlanTask(directory,args2.task_id)}catch(error93){return{success:!1,message:"the plan became unreadable while anchors were running; re-run attest against the current declaration",errors:["the plan became unreadable while anchors were running; re-run attest against the current declaration"],task_id:args2.task_id}}let anchorsUnchanged=JSON.stringify(current?.task.evidence_anchors??null)===JSON.stringify(anchors);if(!current||current.task.evidence_class!=="external_git"||current.title!==found.title||current.swarm!==found.swarm||!anchorsUnchanged)return{success:!1,message:"the plan changed while anchors were running; re-run attest against the current declaration",errors:["the plan changed while anchors were running; re-run attest against the current declaration"],task_id:args2.task_id};let existingEvidence=null;try{existingEvidence=readTaskEvidenceRaw(directory,args2.task_id)}catch(error93){let message=`the existing evidence file for task ${args2.task_id} is unreadable (corrupt): ${error93 instanceof Error?error93.message.slice(0,160):String(error93).slice(0,160)}; inspect the file before attesting`;return{success:!1,message,errors:[message],task_id:args2.task_id}}let generation=existingEvidence?.workflow?.generation??0,transitionId=`attest:${args2.task_id}:${startedAt}:${Math.random().toString(36).slice(2,10)}`,bundle={class:"external_git",transitionId,declarationDigest:computeExternalDeclarationDigest({taskId:args2.task_id,evidence_class:"external_git",evidence_anchors:anchors,plan_title:current.title,plan_swarm:current.swarm,generation}),anchors:outcomes,attestedAt:new Date().toISOString()};try{await transitionTaskWorkflowEvidence(directory,args2.task_id,{type:"external_evidence_attested",bundle,expectedGeneration:generation,transitionId})}catch(error93){let message=error93 instanceof Error?error93.message:String(error93);return{success:!1,message,errors:[message],task_id:args2.task_id}}return{success:!0,message:`Task ${args2.task_id}: ${outcomes.length} external evidence anchor(s) attested and recorded; completion is now admissible for this declared task`,task_id:args2.task_id}}var ANCHOR_STDOUT_MAX_CHARS=4096,ANCHOR_SPAWN_TIMEOUT_MS=1e4,ANCHOR_SPAWN_MAX_BUFFER_BYTES=262144,ATTEST_TOTAL_DEADLINE_MS=30000,READ_ONLY_GIT_FLAGS,REMOTE_HELPER_PATTERN,_internals118;var init_attest_task=__esm(()=>{init_plan_schema();init_gate_evidence();init_bun_compat();init_git_executable();init_project_boundary();init_update_task_status();READ_ONLY_GIT_FLAGS={"rev-list":{"--count":0,"--max-count":1,"--format":1,"--skip":1},log:{"--format":1,"--max-count":1,"-n":1,"--oneline":0,"--no-patch":0,"--stat":0,"--name-only":0,"-1":0,"-2":0,"-3":0,"-4":0,"-5":0,"-9":0},show:{"--format":1,"--stat":0,"--name-only":0,"--no-patch":0,"--quiet":0},diff:{"--stat":0,"--name-only":0,"--quiet":0},"rev-parse":{"--verify":0,"--short":0}},REMOTE_HELPER_PATTERN=/^(ext::|[a-z+.-]+::)/;_internals118={runAnchor,buildAnchorArgv,loadPlanTask:(directory,taskId)=>{let planPath=path125.join(directory,".swarm","plan.json");if(!fs80.existsSync(planPath))return null;let plan=PlanSchema.parse(JSON.parse(fs80.readFileSync(planPath,"utf-8")));for(let phase of plan.phases)for(let task of phase.tasks)if(task.id===taskId)return{title:plan.title,swarm:plan.swarm,task};return null}}});async function handleAttestCommand(directory,args2,sessionID){let unknownOptions=args2.filter((arg)=>arg.startsWith("--"));if(unknownOptions.length>0)return["## External Evidence Attestation","",`❌ Unsupported option(s): ${unknownOptions.join(" ")}. Usage: /swarm attest <task_id>`].join(`
|
|
1367
|
+
`).filter((line)=>line.length>0);if(advisoryLines.length>0)scopeAdvisories=advisoryLines}if(reviewerCheck.blocked)return await recordRunMemoryOutcome(directory,{taskId:args2.task_id,agent:agentName,outcome:"fail",failureReason:`QA gate: ${reviewerCheck.reason}`,fileTargets:resolveRunMemoryFileTargets(loadedPlan,args2.task_id)}),{success:!1,message:"Gate check failed: required QA gates not yet satisfied for task "+args2.task_id,errors:[reviewerCheck.reason]}}}let lockTaskId=`update-task-status-${args2.task_id}-${Date.now()}`,planFilePath="plan.json",lockResult;try{lockResult=await _internals117.tryAcquireLock(directory,planFilePath,agentName,lockTaskId)}catch(error93){return{success:!1,message:"Failed to acquire lock for task status update",errors:[error93 instanceof Error?error93.message:String(error93)]}}if(!lockResult.acquired)return{success:!1,message:`Task status write blocked: plan.json is locked by ${lockResult.existing?.agent??"another agent"} (task: ${lockResult.existing?.taskId??"unknown"})`,errors:["Concurrent plan write detected — retry after the current write completes"],recovery_guidance:"Wait a moment and retry update_task_status. The lock will expire automatically if the holding agent fails."};try{let lockedPlan=await _internals117.loadPlan(directory);if(lockedPlan?._ledgerReplayStale===!0)return{success:!1,message:"Task status update refused: plan became ledger-stale while waiting for the lock",errors:[lockedPlan._ledgerReplayStaleReason??"plan.json is stale relative to the authoritative ledger"],recovery_guidance:"Retry save_plan with the unchanged loaded plan to reconverge the projection/hash, then retry update_task_status."};if(!lockedPlan)return{success:!1,message:"Failed to update task status",errors:["No approved plan is available under the plan lock"]};let authoritativePlan=lockedPlan,lockedPreparedRepairWal=await readPreparedWorkflowWal(directory,args2.task_id,"task-repair"),lockedExactRepairRetry=isRepairRetryShape(args2)&&lockedPreparedRepairWal?.transitionId===args2.transition_id;if(lockedPreparedRepairWal&&!lockedExactRepairRetry)try{let recoveredRepair=await recoverPreparedTaskRepairUnderPlanLock(directory,args2.task_id,ctx?.sessionID??"update-task-status",authoritativePlan);if(recoveredRepair)authoritativePlan=recoveredRepair.plan,syncCallerWorkflowFromEvidence(ctx?.sessionID,args2.task_id,readTaskEvidenceRaw(directory,args2.task_id))}catch(error93){if(error93 instanceof Error&&error93.message.startsWith("TASK_REPAIR_AUDIT_LOCKED"))criticalWarn(`[update-task-status] task-repair audit recovery deferred for ${args2.task_id}: ${error93.message}`);else return{success:!1,message:"Task operation paused while recovering an interrupted task repair",errors:[error93 instanceof Error?error93.message:String(error93)]}}if(await hasPreparedWorkflowWal(directory,args2.task_id,"task-terminal"))try{let recoveredTerminal=await recoverPreparedTaskTerminalUnderPlanLock(directory,args2.task_id,ctx?.sessionID??"update-task-status",authoritativePlan);if(recoveredTerminal)authoritativePlan=recoveredTerminal.plan,syncCallerWorkflowFromEvidence(ctx?.sessionID,args2.task_id,recoveredTerminal.evidence)}catch(error93){return{success:!1,message:"Task operation paused while recovering an interrupted terminal status transition",errors:[error93 instanceof Error?error93.message:String(error93)]}}let lockedTask=authoritativePlan.phases.flatMap((phase)=>phase.tasks).find((task)=>task.id===args2.task_id);if(!lockedTask)return{success:!1,message:"Failed to update task status",errors:[`Task not found: ${args2.task_id}`]};let lockedSettledRejection=getSettledTransitionRejection(args2.task_id,lockedTask.status,args2.status,args2.force);if(lockedSettledRejection)return lockedSettledRejection;let repairResult=args2.status==="in_progress"&&args2.force===!0?await repairTaskWorkflowUnderPlanLock({directory,taskId:args2.task_id,actor:agentName,reason:args2.reason,transitionId:args2.transition_id,expectedState:args2.expected_state,expectedGeneration:args2.expected_generation,currentPlanStatus:lockedTask.status,currentPlan:authoritativePlan,updatePlan:()=>_internals117.updateTaskStatus(directory,args2.task_id,"in_progress",{force:!0,planLockAlreadyHeld:!0})}):null,updatedPlan,terminalEvidence=null;if(args2.status==="completed"){let lockedTaskPhase=authoritativePlan.phases.find((phase)=>phase.tasks.some((task)=>task.id===args2.task_id)),lockedPhaseRequiresReviewer=!lockedTaskPhase?.required_agents||lockedTaskPhase.required_agents.includes("reviewer"),lockedTaskDeclaresExternal=lockedTask.evidence_class==="external_git",terminalResult=await commitTaskTerminalUnderPlanLock({directory,taskId:args2.task_id,actor:agentName,transitionId:`plan-status:${args2.task_id}:completed:${Date.now()}`,currentPlanStatus:lockedTask.status,targetStatus:"completed",qaExempt:!lockedPhaseRequiresReviewer&&!lockedTaskDeclaresExternal,resolveTerminal:(evidence2)=>({targetStatus:"completed",qaExempt:!lockedPhaseRequiresReviewer&&!lockedTaskDeclaresExternal,readOnlyNoMutation:!lockedPhaseRequiresReviewer?!1:isReadOnlyNoMutationEligible(evidence2,{currentDeclaredFiles:lockedTask.files_touched}),externalEvidence:lockedTaskDeclaresExternal}),currentPlan:authoritativePlan,validateEvidence:async()=>{if(lockedTaskDeclaresExternal){let externalTaskEvidence=_internals117.readTaskEvidenceRaw(directory,args2.task_id),planIdentity={title:authoritativePlan.title,swarm:authoritativePlan.swarm},externalWorkflow=getTaskWorkflowSnapshot(externalTaskEvidence);if(!isExternalEvidenceInitialCompletionEligible(planIdentity,lockedTask,externalTaskEvidence)&&!(externalWorkflow.state==="complete"&&externalProofCurrent(planIdentity,lockedTask,externalTaskEvidence)))throw Error(`TASK_COMPLETION_CAS_MISMATCH: Task ${args2.task_id} declares external_git evidence but has no current matched attestation; run /swarm attest ${args2.task_id} first`);return}let lockedGate=checkReviewerGate(args2.task_id,directory,!1,ctx?.sessionID,fallbackDir??directory,lockedTask.files_touched??null),lockedCouncil=checkCouncilGate(directory,args2.task_id);if(lockedCouncil.blocked||lockedPhaseRequiresReviewer&&!lockedCouncil.active&&lockedGate.blocked)throw Error(`TASK_COMPLETION_CAS_MISMATCH: ${lockedCouncil.blocked?lockedCouncil.reason:lockedGate.reason}`)},updatePlan:async()=>{let next=await _internals117.updateTaskStatus(directory,args2.task_id,"completed",{force:!1,planLockAlreadyHeld:!0});if(next.phases.flatMap((phase)=>phase.tasks).find((task)=>task.id===args2.task_id)?.status!=="completed")throw Error("TASK_STATUS_WRITE_NOT_APPLIED");return next}});updatedPlan=terminalResult.plan,terminalEvidence=terminalResult.evidence}else if(args2.status==="blocked"){let terminalResult=await commitTaskTerminalUnderPlanLock({directory,taskId:args2.task_id,actor:agentName,transitionId:`plan-status:${args2.task_id}:blocked:${Date.now()}`,currentPlanStatus:lockedTask.status,targetStatus:"blocked",qaExempt:!1,currentPlan:authoritativePlan,updatePlan:async()=>{let next=await _internals117.updateTaskStatus(directory,args2.task_id,"blocked",{force:!1,planLockAlreadyHeld:!0});if(next.phases.flatMap((phase)=>phase.tasks).find((task)=>task.id===args2.task_id)?.status!=="blocked")throw Error("TASK_STATUS_WRITE_NOT_APPLIED");return next}});updatedPlan=terminalResult.plan,terminalEvidence=terminalResult.evidence}else if(updatedPlan=repairResult?.plan??await _internals117.updateTaskStatus(directory,args2.task_id,args2.status,{force:!1,planLockAlreadyHeld:!0}),updatedPlan.phases.flatMap((phase)=>phase.tasks).find((task)=>task.id===args2.task_id)?.status!==args2.status)throw Error("TASK_STATUS_WRITE_NOT_APPLIED");if(terminalEvidence){let terminal=getTaskWorkflowSnapshot(terminalEvidence),callerSession=ctx?.sessionID?swarmState.agentSessions.get(ctx.sessionID):void 0;if(callerSession){let session=callerSession;session.taskWorkflowStates.set(args2.task_id,terminal.state),session.stageBCompletion?.delete(args2.task_id),updateTaskWorkflowCache(session,args2.task_id,terminal)}}if(args2.status==="in_progress"){if(ctx?.sessionID)ensureAgentSession(ctx.sessionID).currentTaskId=args2.task_id;if(repairResult){let callerSession=ctx?.sessionID?swarmState.agentSessions.get(ctx.sessionID):void 0;if(callerSession){let session=callerSession;session.taskWorkflowStates.set(args2.task_id,"idle"),session.stageBCompletion?.delete(args2.task_id),session.taskCouncilApproved?.delete(args2.task_id),session.taskCouncilWorkflowGeneration?.delete(args2.task_id),updateTaskWorkflowCache(session,args2.task_id,{generation:repairResult.generation})}}}return{success:!0,message:"Task status updated successfully",task_id:args2.task_id,new_status:args2.status,current_phase:updatedPlan.current_phase,...scopeAdvisories&&scopeAdvisories.length>0?{warnings:scopeAdvisories}:{}}}catch(error93){return{success:!1,message:"Failed to update task status",errors:[error93 instanceof Error?error93.message:String(error93)]}}finally{if(lockResult?.acquired&&lockResult.lock._release)try{await lockResult.lock._release()}catch(releaseError){log("[update-task-status] Lock release failed:",releaseError)}}}var _internals117,VALID_STATUSES,update_task_status;var init_update_task_status=__esm(()=>{init_zod();init_loader();init_schema();init_qa_gate_profile();init_task_gate_requirements();init_gate_evidence();init_diff_scope();init_utils2();init_file_locks();init_tier3_classifier();init_manager();init_routing_enforcement();init_run_memory();init_state();init_telemetry();init_task_completion();init_logger();init_project_boundary();init_task_id();init_coder_settlement();init_session_view();init_task_repair();init_task_terminal();init_workflow_wal_file();init_create_tool();init_resolve_working_directory();_internals117={tryAcquireLock,updateTaskStatus,resolveWorkingDirectory,loadPlan,readTaskEvidenceRaw,hasActiveLeanTurbo,hasActiveTurboMode,verifyLeanTurboTaskCompletion,hasPassedDurableGateEvidence,emitReviewerGateDecision:telemetry.reviewerGateDecision,recordTaskAttempt};VALID_STATUSES=["pending","in_progress","completed","blocked"];update_task_status=createSwarmTool({description:"Update the status of a specific task in the implementation plan. Task status can be one of: pending, in_progress, completed, blocked.",args:{task_id:exports_external.string().min(1).regex(/^\d+\.\d+(\.\d+)*$/,"Task ID must be in N.M or N.M.P format").describe('Task ID in N.M format, e.g. "1.1", "1.2.3"'),status:exports_external.enum(["pending","in_progress","completed","blocked"]).describe("New status for the task: pending, in_progress, completed, or blocked"),working_directory:exports_external.string().optional().describe("Working directory where the plan is located"),force:exports_external.boolean().optional().default(!1).describe('Enable the audited repair contract: re-open a settled task, or an in_progress task that reached the retry ladder user_escalation rung (issue #3389). Requires expected_state, expected_generation, target_state="idle", reason, and transition_id.'),expected_state:exports_external.string().optional().describe("CAS workflow state expected by a force repair."),expected_generation:exports_external.number().int().min(0).optional().describe("ABA-safe workflow generation expected by a force repair."),target_state:exports_external.literal("idle").optional().describe("Repair target state. The only valid target is idle (re-opens the task for new work)."),reason:exports_external.string().min(1).max(2000).optional().describe("Required human-readable audit reason for a force repair."),transition_id:exports_external.string().min(1).max(200).optional().describe("Caller-generated idempotency key for an audited force repair.")},execute:async(args2,_directory2,_ctx)=>{return JSON.stringify(await executeUpdateTaskStatus(args2,_directory2,_ctx),null,2)}})});var exports_attest_task={};__export(exports_attest_task,{executeAttestTask:()=>executeAttestTask,buildAnchorArgv:()=>buildAnchorArgv,_internals:()=>_internals118});import*as fs80 from"node:fs";import*as path125 from"node:path";function anchorEnv(){let env={PATH:process.env.PATH,HOME:process.env.HOME,LANG:process.env.LANG,LC_ALL:process.env.LC_ALL,GIT_CONFIG_NOSYSTEM:"1"};if(process.platform==="win32")env.SYSTEMROOT=process.env.SYSTEMROOT,env.WINDIR=process.env.WINDIR,env.COMSPEC=process.env.COMSPEC;return{env,envOverrides:{GIT_EXTERNAL_DIFF:null,GIT_CONFIG_PARAMETERS:null,GIT_CONFIG_COUNT:null,GIT_DIR:null,GIT_WORK_TREE:null,GIT_INDEX_FILE:null,GIT_SSH_COMMAND:null,GIT_ASKPASS:null,GIT_EXEC_PATH:null,GIT_PAGER:null}}}function buildAnchorArgv(command){let tokens2=command.trim().split(/\s+/).filter(Boolean);if(tokens2[0]!=="git"||tokens2.length<2)return{argv:null,refusal:`anchor command is not an allowed read-only git invocation: "${command}"`};let subcommand=tokens2[1];if(subcommand.startsWith("-"))return{argv:null,refusal:`anchor command smuggles a git global option ("${subcommand}"); only bare read-only git subcommands are allowed`};let allowed=READ_ONLY_GIT_FLAGS[subcommand];if(!allowed)return{argv:null,refusal:`git "${subcommand}" is not in the read-only git subcommand allowlist (rev-list, log, rev-parse, show, diff)`};let finalTokens=[subcommand];for(let i=2;i<tokens2.length;i++){let token=tokens2[i];if(token.startsWith("-")){let eq=token.indexOf("="),flag=eq>=0?token.slice(0,eq):token,inlineValue=eq>=0?token.slice(eq+1):void 0,arity2=allowed[flag];if(arity2===void 0)return{argv:null,refusal:`flag "${flag}" is not in the read-only git allowlist for git ${subcommand}`};if(arity2===0){if(inlineValue!==void 0)return{argv:null,refusal:`flag "${flag}" takes no value; =-joined forms are not valid for it`};finalTokens.push(flag)}else{let value=inlineValue;if(value===void 0){let next=tokens2[i+1];if(next===void 0||next.startsWith("--"))return{argv:null,refusal:`flag "${flag}" requires a value token`};value=next,i++}finalTokens.push(flag.startsWith("--")?`${flag}=${value}`:`${flag}${value}`)}continue}let hasControlByte=Array.from(token).some((ch)=>ch.charCodeAt(0)<32||ch.charCodeAt(0)===127);if(token.length>400||hasControlByte)return{argv:null,refusal:"anchor argument is too long or contains control bytes"};if(REMOTE_HELPER_PATTERN.test(token))return{argv:null,refusal:`anchor argument "${token.slice(0,32)}" looks like a remote-helper URL; remote helpers can execute commands and are not read-only git invocations`};finalTokens.push(token)}if(subcommand==="diff"||subcommand==="show"||subcommand==="log")finalTokens.push("--no-ext-diff","--no-textconv");return{argv:[resolveGitExecutable(),"--no-pager","-c","diff.external=","-c","core.pager=cat","-c","core.fsmonitor=","-c","gpg.program=","-c","credential.helper=",...finalTokens],refusal:null}}async function runAnchor(argv,cwd,timeoutMs){let{env,envOverrides}=anchorEnv(),proc=bunSpawn(argv,{cwd,env,envOverrides,stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:timeoutMs,maxBuffer:ANCHOR_SPAWN_MAX_BUFFER_BYTES});try{let exited=await proc.exited,stdout;try{stdout=await proc.stdout.text()}catch{return{exitCode:exited,stdout:"",refusal:`anchor output exceeded the ${Math.floor(ANCHOR_SPAWN_MAX_BUFFER_BYTES/1024)}KB spawn capture buffer; refusing rather than truncating`}}if(exited!==0){let detail=(await proc.stderr.text()).trim().slice(0,200);return{exitCode:exited,stdout,refusal:`anchor command exited with code ${exited}${detail?`: ${detail}`:""}`}}return{exitCode:exited,stdout,refusal:null}}finally{try{proc.kill()}catch{}}}function validateAnchorExpectations(anchors){for(let anchor of anchors){if(anchor.expect===void 0&&anchor.expect_prefix===void 0)return`anchor "${anchor.command.slice(0,60)}" declares neither expect nor expect_prefix`;if(anchor.expect_prefix!==void 0&&anchor.expect_prefix.length===0)return`anchor "${anchor.command.slice(0,60)}" declares an empty expect_prefix, which would match any output`}return null}async function executeAttestTask(args2,fallbackDir){let resolveResult=_internals117.resolveWorkingDirectory(args2.working_directory,fallbackDir);if(!resolveResult.success)return{success:!1,message:resolveResult.message,errors:[resolveResult.message]};let directory=resolveResult.directory;try{assertProjectRoot(directory)}catch(error93){let message=error93 instanceof Error?error93.message:String(error93);return{success:!1,message,errors:[message]}}let found;try{found=_internals118.loadPlanTask(directory,args2.task_id)}catch(error93){let message=error93 instanceof Error?error93.message:String(error93);if(message.includes("expect_prefix")||message.includes("evidence_anchors"))return{success:!1,message:"the plan declares an invalid external-evidence anchor: every anchor must carry expect and/or a non-empty expect_prefix (an empty prefix would match any output)",errors:["the plan declares an invalid external-evidence anchor: every anchor must carry expect and/or a non-empty expect_prefix (an empty prefix would match any output)"],task_id:args2.task_id};let refusal=`the plan at ${directory} is invalid or unreadable; fix or re-save the plan before attesting`;return{success:!1,message:refusal,errors:[`${refusal} (${message.slice(0,160)})`],task_id:args2.task_id}}if(!found){let message=`Task ${args2.task_id} not found in the plan at ${directory}`;return{success:!1,message,errors:[message],task_id:args2.task_id}}if(found.task.evidence_class!=="external_git"){let message=`Task ${args2.task_id} does not declare evidence_class external_git; the attest path is fail-closed to explicitly declared external-evidence tasks (issue #3422)`;return{success:!1,message,errors:[message],task_id:args2.task_id}}let anchors=found.task.evidence_anchors??[];if(anchors.length===0){let message=`Task ${args2.task_id} declares external_git evidence but pins no evidence_anchors`;return{success:!1,message,errors:[message],task_id:args2.task_id}}let malformed=validateAnchorExpectations(anchors);if(malformed)return{success:!1,message:malformed,errors:[malformed],task_id:args2.task_id};let startedAt=Date.now(),outcomes=[];for(let anchor of anchors){let{argv,refusal}=_internals118.buildAnchorArgv(anchor.command);if(refusal!==null||argv===null){let message=`anchor not admitted: ${refusal??"not an allowed read-only git invocation"}`;return{success:!1,message,errors:[message],task_id:args2.task_id}}let remaining=ATTEST_TOTAL_DEADLINE_MS-(Date.now()-startedAt);if(remaining<=0)return{success:!1,message:"attest total deadline (30s) exhausted before all anchors ran",errors:["attest total deadline (30s) exhausted before all anchors ran"],task_id:args2.task_id};let run=await _internals118.runAnchor(argv,directory,Math.min(ANCHOR_SPAWN_TIMEOUT_MS,remaining));if(run.refusal!==null){let message=`anchor "${anchor.command.slice(0,60)}" failed: ${run.refusal}`;return{success:!1,message,errors:[message],task_id:args2.task_id}}if(run.stdout.length>ANCHOR_STDOUT_MAX_CHARS){let message=`anchor "${anchor.command.slice(0,60)}" produced ${run.stdout.length} chars of stdout, exceeding the ${ANCHOR_STDOUT_MAX_CHARS}-char evidence storage bound; refusing rather than truncating`;return{success:!1,message,errors:[message],task_id:args2.task_id}}let trimmed=run.stdout.trim(),matched=anchor.expect!==void 0?trimmed===anchor.expect&&(anchor.expect_prefix===void 0||trimmed.startsWith(anchor.expect_prefix)):trimmed.startsWith(anchor.expect_prefix);outcomes.push({command:anchor.command,expect:anchor.expect,expect_prefix:anchor.expect_prefix,matched,exit_code:run.exitCode,stdout:run.stdout})}if(!outcomes.every((outcome)=>outcome.matched)){let failed=outcomes.find((outcome)=>!outcome.matched),message=`anchor "${failed?.command.slice(0,60)??"?"}" did not match its expectation (stdout: ${JSON.stringify(failed?.stdout.slice(0,120)??"")})`;return{success:!1,message,errors:[message],task_id:args2.task_id}}let current;try{current=_internals118.loadPlanTask(directory,args2.task_id)}catch{return{success:!1,message:"the plan became unreadable while anchors were running; re-run attest against the current declaration",errors:["the plan became unreadable while anchors were running; re-run attest against the current declaration"],task_id:args2.task_id}}let anchorsUnchanged=JSON.stringify(current?.task.evidence_anchors??null)===JSON.stringify(anchors);if(!current||current.task.evidence_class!=="external_git"||current.title!==found.title||current.swarm!==found.swarm||!anchorsUnchanged)return{success:!1,message:"the plan changed while anchors were running; re-run attest against the current declaration",errors:["the plan changed while anchors were running; re-run attest against the current declaration"],task_id:args2.task_id};let existingEvidence=null;try{existingEvidence=readTaskEvidenceRaw(directory,args2.task_id)}catch(error93){let message=`the existing evidence file for task ${args2.task_id} is unreadable (corrupt): ${error93 instanceof Error?error93.message.slice(0,160):String(error93).slice(0,160)}; inspect the file before attesting`;return{success:!1,message,errors:[message],task_id:args2.task_id}}let generation=existingEvidence?.workflow?.generation??0,transitionId=`attest:${args2.task_id}:${startedAt}:${Math.random().toString(36).slice(2,10)}`,bundle={class:"external_git",transitionId,declarationDigest:computeExternalDeclarationDigest({taskId:args2.task_id,evidence_class:"external_git",evidence_anchors:anchors,plan_title:current.title,plan_swarm:current.swarm,generation}),anchors:outcomes,attestedAt:new Date().toISOString()};try{await transitionTaskWorkflowEvidence(directory,args2.task_id,{type:"external_evidence_attested",bundle,expectedGeneration:generation,transitionId})}catch(error93){let message=error93 instanceof Error?error93.message:String(error93);return{success:!1,message,errors:[message],task_id:args2.task_id}}return{success:!0,message:`Task ${args2.task_id}: ${outcomes.length} external evidence anchor(s) attested and recorded; completion is now admissible for this declared task`,task_id:args2.task_id}}var ANCHOR_STDOUT_MAX_CHARS=4096,ANCHOR_SPAWN_TIMEOUT_MS=1e4,ANCHOR_SPAWN_MAX_BUFFER_BYTES=262144,ATTEST_TOTAL_DEADLINE_MS=30000,READ_ONLY_GIT_FLAGS,REMOTE_HELPER_PATTERN,_internals118;var init_attest_task=__esm(()=>{init_plan_schema();init_gate_evidence();init_bun_compat();init_git_executable();init_project_boundary();init_update_task_status();READ_ONLY_GIT_FLAGS={"rev-list":{"--count":0,"--max-count":1,"--format":1,"--skip":1},log:{"--format":1,"--max-count":1,"-n":1,"--oneline":0,"--no-patch":0,"--stat":0,"--name-only":0,"-1":0,"-2":0,"-3":0,"-4":0,"-5":0,"-9":0},show:{"--format":1,"--stat":0,"--name-only":0,"--no-patch":0,"--quiet":0},diff:{"--stat":0,"--name-only":0,"--quiet":0},"rev-parse":{"--verify":0,"--short":0}},REMOTE_HELPER_PATTERN=/^(ext::|[a-z+.-]+::)/;_internals118={runAnchor,buildAnchorArgv,loadPlanTask:(directory,taskId)=>{let planPath=path125.join(directory,".swarm","plan.json");if(!fs80.existsSync(planPath))return null;let plan=PlanSchema.parse(JSON.parse(fs80.readFileSync(planPath,"utf-8")));for(let phase of plan.phases)for(let task of phase.tasks)if(task.id===taskId)return{title:plan.title,swarm:plan.swarm,task};return null}}});async function handleAttestCommand(directory,args2,sessionID){let unknownOptions=args2.filter((arg)=>arg.startsWith("--"));if(unknownOptions.length>0)return["## External Evidence Attestation","",`❌ Unsupported option(s): ${unknownOptions.join(" ")}. Usage: /swarm attest <task_id>`].join(`
|
|
1368
1368
|
`);if(args2.length!==1)return["## External Evidence Attestation","",args2.length===0?"❌ Missing task id. Usage: /swarm attest <task_id>":`❌ Unexpected arguments: ${args2.join(" ")}. Usage: /swarm attest <task_id>`].join(`
|
|
1369
|
-
`);let taskId=args2[0],{executeAttestTask:executeAttestTask2}=await Promise.resolve().then(() => (init_attest_task(),exports_attest_task)),result=await executeAttestTask2({task_id:taskId,working_directory:directory,reason:`swarm attest (${sessionID??"no-session"})`},directory),lines=["## External Evidence Attestation",""];lines.push(result.success
|
|
1369
|
+
`);let taskId=args2[0],{executeAttestTask:executeAttestTask2}=await Promise.resolve().then(() => (init_attest_task(),exports_attest_task)),result=await executeAttestTask2({task_id:taskId,working_directory:directory,reason:`swarm attest (${sessionID??"no-session"})`},directory),lines=["## External Evidence Attestation",""];lines.push(result.success?`✅ ${result.message}`:`❌ ${result.message}`);for(let error93 of result.errors??[])lines.push(`- ${error93}`);if(!result.success)lines.push("","The attest path is fail-closed: the plan task must declare evidence_class external_git with 1..16 pinned read-only git anchors, every anchor must match, and the task must never have entered the coder QA workflow. See docs/commands.md (/swarm attest) and docs/plan-durability.md.");return lines.join(`
|
|
1370
1370
|
`)}async function handleAutoProceedCommand(_directory2,args2,sessionID){if(!sessionID||sessionID.trim()==="")return"Error: No active session context. Auto-proceed requires an active session. Use /swarm auto-proceed from within an OpenCode session, or start a session first.";let session=getAgentSession(sessionID);if(!session)return"Error: No active session. Auto-proceed requires an active session to operate.";if(stripKnownSwarmPrefix(session.agentName)!=="architect")return`Error: Auto-proceed can only be toggled from the architect session. Currently active session is: ${session.agentName}`;let arg=args2[0]?.toLowerCase(),wasUndefinedBefore=session.autoProceedOverride===void 0,newAutoProceedOverride;if(arg==="on")newAutoProceedOverride=!0;else if(arg==="off")newAutoProceedOverride=!1;else if(arg===void 0)newAutoProceedOverride=!session.autoProceedOverride;else return'Error: Invalid argument for /swarm auto-proceed. Valid options: "on", "off", or omit the argument to toggle.';if(session.autoProceedOverride=newAutoProceedOverride,arg==="on"||arg==="off"||arg===void 0&&wasUndefinedBefore)session.autoProceedNudgeDone=!0;if(newAutoProceedOverride)return"Auto-proceed is now ON. Phase boundaries will advance automatically.";else return"Auto-proceed is now OFF. You will be asked before advancing to the next phase."}var init_auto_proceed=__esm(()=>{init_schema();init_state()});async function computeEvidenceQualitySummary(directory){let reviewPasses=0,reviewFails=0,testPasses=0,testFails=0,additions=0,deletions=0,totalComplexityDelta=0,totalPublicApiDelta=0,totalDuplicationRatio=0,totalTestToCodeRatio=0,qualityEvidenceCount=0;for(let tid of await listEvidenceTaskIds(directory)){let result;try{result=await loadEvidence(directory,tid,{migrate:!1})}catch(_evidenceErr){warn("benchmark: skipping corrupt or unreadable evidence for task",tid);continue}if(result.status!=="found")continue;for(let e of result.bundle.entries){if(!isValidEvidenceType(e.type)){warn(`Unknown evidence type '${e.type}' in task ${tid}, skipping`);continue}if(e.type==="review"){if(e.verdict==="approved")reviewPasses++;else if(e.verdict==="rejected")reviewFails++}else if(e.type==="test")testPasses+=e.tests_passed,testFails+=e.tests_failed;else if(e.type==="diff")additions+=e.additions,deletions+=e.deletions;else if(e.type==="quality_budget"){let qe=e;totalComplexityDelta+=qe.metrics.complexity_delta,totalPublicApiDelta+=qe.metrics.public_api_delta,totalDuplicationRatio+=qe.metrics.duplication_ratio*100,totalTestToCodeRatio+=qe.metrics.test_to_code_ratio*100,qualityEvidenceCount++}}}let totalReviews=reviewPasses+reviewFails,totalTests=testPasses+testFails,quality={reviewPassRate:totalReviews?Math.round(reviewPasses/totalReviews*1000)/10:null,testPassRate:totalTests?Math.round(testPasses/totalTests*1000)/10:null,totalReviews,testsPassed:testPasses,testsFailed:testFails,additions,deletions};if(qualityEvidenceCount>0)return{...quality,qualityMetrics:{complexityDelta:Math.round(totalComplexityDelta/qualityEvidenceCount*10)/10,publicApiDelta:Math.round(totalPublicApiDelta/qualityEvidenceCount*10)/10,duplicationRatio:Math.round(totalDuplicationRatio/qualityEvidenceCount*10)/10,testToCodeRatio:Math.round(totalTestToCodeRatio/qualityEvidenceCount*10)/10,thresholds:{maxComplexityDelta:CI_QUALITY_THRESHOLDS.max_complexity_delta,maxPublicApiDelta:CI_QUALITY_THRESHOLDS.max_public_api_delta,maxDuplicationRatio:CI_QUALITY_THRESHOLDS.max_duplication_ratio,minTestToCodeRatio:CI_QUALITY_THRESHOLDS.min_test_to_code_ratio},hasEvidence:!0}};return{...quality,qualityMetrics:{complexityDelta:0,publicApiDelta:0,duplicationRatio:0,testToCodeRatio:0,thresholds:{maxComplexityDelta:CI_QUALITY_THRESHOLDS.max_complexity_delta,maxPublicApiDelta:CI_QUALITY_THRESHOLDS.max_public_api_delta,maxDuplicationRatio:CI_QUALITY_THRESHOLDS.max_duplication_ratio,minTestToCodeRatio:CI_QUALITY_THRESHOLDS.min_test_to_code_ratio},hasEvidence:!1}}}var CI_QUALITY_THRESHOLDS;var init_quality_checks=__esm(()=>{init_manager2();init_utils();CI_QUALITY_THRESHOLDS={review_pass_rate:70,test_pass_rate:80,max_agent_error_rate:20,max_hard_limit_hits:1,max_complexity_delta:5,max_public_api_delta:10,max_duplication_ratio:5,min_test_to_code_ratio:30}});import{mkdir as mkdir18,readFile as readFile25}from"node:fs/promises";import*as path126 from"node:path";function gateGroundTruthJoinKey(value){return[value.runId,value.taskId,value.candidateId,value.model,value.gate,String(value.repetition)].join("\x00")}function relativePath(runId){return path126.join("evidence","gate-audit",runId,"ground-truth.jsonl")}function absolutePath(directory,runId){return path126.join(directory,".swarm",relativePath(runId))}function serialize(events){return`${events.map((event)=>canonicalJson2(event)).join(`
|
|
1371
1371
|
`)}
|
|
1372
1372
|
`}function parseStrict(content){return content.split(/\r?\n/).filter((line)=>line.trim()).map((line)=>GateGroundTruthV1Schema.parse(JSON.parse(line)))}async function saveGateGroundTruth(directory,runId,input){let events=input.map((event)=>GateGroundTruthV1Schema.parse(event));if(events.some((event)=>event.runId!==runId))throw Error("gate ground truth run id does not match its storage path");let target=absolutePath(directory,runId);return assertProjectRoot(directory),await mkdir18(path126.dirname(target),{recursive:!0}),withEvidenceLock(directory,relativePath(runId),"gate-ground-truth",runId,async()=>{let existingEvents=[];try{existingEvents=parseStrict(await readFile25(target,"utf8"))}catch(error93){if(error93.code!=="ENOENT")throw error93}let byCanonicalEvent=new Map;for(let event of[...existingEvents,...events]){if(event.runId!==runId)throw Error("gate ground truth run id does not match its storage path");byCanonicalEvent.set(canonicalJson2(event),event)}let merged=[...byCanonicalEvent.values()].sort((left,right)=>{return gateGroundTruthJoinKey(left).localeCompare(gateGroundTruthJoinKey(right))||canonicalJson2(left).localeCompare(canonicalJson2(right))}),desired=serialize(merged);if(serialize(existingEvents)!==desired)await atomicWriteFile(target,desired);return merged})}async function recordTestImpactGateGroundTruth(directory,runId,input){return saveGateGroundTruth(directory,runId,input.map((event)=>({...event,v:1,source:"test-impact"})))}async function readGateGroundTruth(directory,runId){let content;try{content=await readFile25(absolutePath(directory,runId),"utf8")}catch(error93){if(error93.code==="ENOENT")return{events:[],malformed:0};throw error93}let events=[],malformed=0;for(let line of content.split(/\r?\n/)){if(!line.trim())continue;try{let event=GateGroundTruthV1Schema.parse(JSON.parse(line));if(event.runId!==runId)throw Error("run id/path mismatch");events.push(event)}catch{malformed++}}return{events,malformed}}var GateGroundTruthV1Schema;var init_gate_ground_truth=__esm(()=>{init_zod();init_lock();init_task_file();init_project_boundary();init_contracts();init_hashing();GateGroundTruthV1Schema=exports_external.object({v:exports_external.literal(1),runId:IdentifierSchema,taskId:IdentifierSchema,candidateId:IdentifierSchema,model:exports_external.string().min(1).max(300),gate:GateNameSchema,repetition:exports_external.number().int().nonnegative(),source:exports_external.enum(["integration","test-impact"]),classification:exports_external.enum(["clean","new_regression","pre_existing","flaky","infrastructure_failure","unknown"]),observedAt:exports_external.iso.datetime({offset:!0}),confidence:exports_external.number().min(0).max(1).optional()}).strict()});import*as fs81 from"node:fs";import*as path127 from"node:path";function wilson95(successes,total){if(total===0)return null;let z2=1.959963984540054,p=successes/total,denominator=1+z2*z2/total,center=(p+z2*z2/(2*total))/denominator,margin=z2/denominator*Math.sqrt(p*(1-p)/total+z2*z2/(4*total*total));return[Math.max(0,center-margin),Math.min(1,center+margin)]}function telemetryStats(directory){let summary={parsed:0,skipped:0,genuine:0,fallback:0,dataQuality:0,blocked:0,fallbackToGenuineRatio:null};for(let filename of["telemetry.jsonl.1","telemetry.jsonl"]){let content="";try{content=fs81.readFileSync(path127.join(directory,".swarm",filename),"utf8")}catch(error93){if(error93.code!=="ENOENT")summary.skipped++;continue}for(let line of content.split(/\r?\n/)){if(!line.trim())continue;let event;try{let value=JSON.parse(line);if(!value||typeof value!=="object"||Array.isArray(value))throw Error("not an object");event=value}catch{summary.skipped++;continue}if(event.event!=="reviewer_gate_decision")continue;let kind=event.evidenceKind;if(!["genuine","fallback","data_quality","block"].includes(String(kind))){summary.skipped++;continue}if(summary.parsed++,kind==="genuine")summary.genuine++;else if(kind==="fallback")summary.fallback++;else if(kind==="data_quality")summary.dataQuality++;else summary.blocked++}}return summary.fallbackToGenuineRatio=summary.genuine===0?null:summary.fallback/summary.genuine,summary}function summarizeCells(cells,truthByKey,minSamples){let groups=new Map;for(let audited of cells){let key2=`${audited.cell.model}\x00${audited.cell.gate}`,group=groups.get(key2)??[];group.push(audited),groups.set(key2,group)}let ambiguous=0,unjoined=0;return{models:[...groups.values()].map((group)=>{let first=group[0].cell,joined=[];for(let audited of group){if(!audited.cell.candidateId){unjoined++;continue}let matches=truthByKey.get(gateGroundTruthJoinKey({runId:audited.runId,taskId:audited.cell.taskId,candidateId:audited.cell.candidateId,model:audited.cell.model,gate:audited.cell.gate,repetition:audited.cell.repetition}))??[];if(matches.length===0){unjoined++;continue}if(new Set(matches.map((match)=>match.classification)).size!==1){ambiguous++;continue}joined.push({cell:audited.cell,truth:matches.find((match)=>match.source==="test-impact")??matches[0]})}let regressionCells=joined.filter((entry)=>entry.truth.classification==="new_regression"),caught=regressionCells.filter((entry)=>entry.cell.outcome==="caught").length,missed=regressionCells.filter((entry)=>entry.cell.outcome==="missed").length,denominator=caught+missed,cleanCells=joined.filter((entry)=>entry.truth.classification==="clean"),falseRejections=cleanCells.filter((entry)=>entry.cell.outcome==="caught"||entry.cell.outcome==="false_rejection").length,negativeControls=cleanCells.filter((entry)=>["caught","missed","false_rejection"].includes(entry.cell.outcome)).length,knownCosts=group.filter((entry)=>entry.cell.cost.source!=="unavailable");return{model:first.model,gate:first.gate,total:group.length,caught,missed,falseRejections,negativeControls,infrastructureFailures:group.filter((entry)=>entry.cell.outcome==="infrastructure_failure").length,unsupported:group.filter((entry)=>entry.cell.outcome==="unsupported").length,catchRate:denominator===0?null:caught/denominator,confidenceInterval:wilson95(caught,denominator),falseRejectionRate:negativeControls===0?null:falseRejections/negativeControls,falseRejectionConfidenceInterval:wilson95(falseRejections,negativeControls),insufficientData:denominator<minSamples||negativeControls<minSamples,retries:{total:group.reduce((sum,entry)=>sum+entry.cell.retries,0),maximum:Math.max(0,...group.map((entry)=>entry.cell.retries))},cost:{usd:knownCosts.reduce((sum,entry)=>sum+(entry.cell.cost.usd??0),0),unavailable:group.length-knownCosts.length}}}).sort((left,right)=>`${left.model}\x00${left.gate}`.localeCompare(`${right.model}\x00${right.gate}`)),ambiguous,unjoined}}async function computeGateStatistics(directory,minSamples=6,runId){if(!Number.isInteger(minSamples)||minSamples<1||minSamples>1e4)throw Error("minSamples must be an integer between 1 and 10000");let audit=await listGateAuditResults(directory),results=runId?audit.results.filter((result)=>result.runId===runId):audit.results,truthSummaries=await Promise.all(results.map((result)=>readGateGroundTruth(directory,result.runId))),truthByKey=new Map;for(let summary2 of truthSummaries)for(let event of summary2.events){let key2=gateGroundTruthJoinKey(event),group=truthByKey.get(key2)??[];group.push(event),truthByKey.set(key2,group)}let summary=summarizeCells(results.flatMap((result)=>result.cells.map((cell)=>({runId:result.runId,cell}))),truthByKey,minSamples);return{runs:results.length,corruptRuns:runId?audit.corruptRunIds.filter((corruptRunId)=>corruptRunId===runId):audit.corruptRunIds,groundTruth:{parsed:truthSummaries.reduce((total,value)=>total+value.events.length,0),malformed:truthSummaries.reduce((total,value)=>total+value.malformed,0),ambiguous:summary.ambiguous,unjoined:summary.unjoined},models:summary.models,reviewerTelemetry:telemetryStats(directory)}}var init_gate_stats=__esm(()=>{init_gate_ground_truth();init_store()});import*as fs82 from"node:fs";import*as fsp9 from"node:fs/promises";import*as os17 from"node:os";import*as path128 from"node:path";function maxKnownAxis(a,b){if(a===null)return b;if(b===null)return a;return Math.max(a,b)}function sumKnownAxis(total,value){if(value===null)return total;return total===null?value:total+value}function isUnknownUsage(usage){return usage.tokens_input===null&&usage.tokens_output===null&&usage.tokens_reasoning===null&&usage.tokens_cache===null}function buildDelegationCostFields(input={}){let evidence2=extractCostEvidence(input.raw,input),projection=projectCostEvidence(evidence2),usage=evidence2.reduce(mergeUsage,{...UNKNOWN_USAGE}),model=evidence2.find((item)=>item.model)?.model??input.model;return{...usage,cost_usd:projection.cost_usd,cost_source:projection.cost_source,cost_evidence:evidence2,evidence_status:projection.evidence_status,evidence_reason:projection.reason,currency:projection.currency,model,gate:input.gate,retry_index:input.retry_index}}function extractCostEvidence(raw,input={}){let candidates=collectPinnedCandidates(raw,input),reports=candidates.filter((candidate)=>candidate.kind==="provider_reported"),evidence2=[];for(let candidate of reports.slice(0,MAX_EVIDENCE_ITEMS))evidence2.push({kind:candidate.kind,amount_usd:candidate.amount,currency:candidate.currency,source_path:candidate.source_path,reason:candidate.reason??(candidate.amount===null?"invalid_number":"authoritative"),usage:candidate.usage,model:candidate.model});let usage=mergeUsage(candidates.reduce(mergeUsage,{...UNKNOWN_USAGE}),readLegacyUsage(raw)),model=candidates.find((candidate)=>candidate.model)?.model??input.model,estimate=estimateCostUsd(usage,model,input.pricing);if(estimate!==null||input.pricing?.subscription_unbilled)evidence2.push({kind:"normalized_estimate",amount_usd:input.pricing?.subscription_unbilled?null:estimate,currency:normalizeCurrency(input.pricing?.currency??"USD"),source_path:"pricing.model",reason:input.pricing?.subscription_unbilled?"unbilled":"authoritative",usage,model,pricing_version:boundedCostLabel(input.pricing?.version),pricing_effective_at:boundedCostLabel(input.pricing?.effective_at),billing_basis:boundedCostLabel(input.pricing?.billing_basis)});if(evidence2.length===0)evidence2.push({kind:"provider_reported",amount_usd:null,currency:"unknown",source_path:"legacy.cost",reason:input.pricing?.models&&model?"pricing_missing":"missing_cost",usage,model});return evidence2.slice(0,MAX_EVIDENCE_ITEMS)}function projectCostEvidence(evidence2){let reports=evidence2.filter((item)=>item.kind==="provider_reported"&&item.reason!=="missing_cost"),compatibleReports=reports.filter((item)=>item.amount_usd!==null&&item.amount_usd<=MAX_PROVIDER_REPORTED_COST_USD&&item.currency==="USD"),incompatibleReport=reports.some((item)=>item.amount_usd!==null&&item.amount_usd<=MAX_PROVIDER_REPORTED_COST_USD&&(item.currency!=="USD"||item.reason!=="authoritative")),reportConflict=hasReportConflict(reports);if(!reportConflict&&!incompatibleReport&&compatibleReports.length>0)return{cost_usd:roundUsd(compatibleReports[0].amount_usd??0),cost_source:"reported",evidence_status:"complete",reason:"authoritative",currency:"USD"};let estimate=evidence2.find((item)=>item.kind==="normalized_estimate"&&item.amount_usd!==null&&item.currency==="USD"&&item.reason==="authoritative"),hasHardIncompatibleReport=reports.some((item)=>item.amount_usd!==null&&item.amount_usd<=MAX_PROVIDER_REPORTED_COST_USD&&(item.currency!=="USD"||item.reason==="unsupported_currency"));if(!reportConflict&&!hasHardIncompatibleReport&&estimate)return{cost_usd:roundUsd(estimate.amount_usd??0),cost_source:"estimated",evidence_status:"complete",reason:"authoritative",currency:"USD"};return{cost_usd:null,cost_source:"unavailable",evidence_status:"inconclusive",reason:reportConflict?"conflict":incompatibleReport?reports[0]?.reason??"unsupported_currency":"missing_cost",currency:reports[0]?.currency??"unknown"}}function summarizeTelemetryCosts(directory){let summary=createEmptySummary(),folded=foldTelemetryEvents(readTelemetryEvents(directory));if(summary.conflict_count=folded.stats.conflict_count,summary.join_miss_count=folded.stats.join_miss_count,summary.telemetry_error_count=folded.stats.telemetry_error_count,folded.stats.join_miss_count>0||folded.stats.telemetry_error_count>0)summary.evidence_status="inconclusive";if(folded.stats.rejected_corrections>0||folded.stats.conflict_count>0)summary.evidence_status="inconclusive";summary.accepted_corrections=folded.stats.accepted_corrections,summary.rejected_corrections=folded.stats.rejected_corrections,summary.duplicate_corrections=folded.stats.duplicate_corrections;for(let event of folded.events){if(event.event!=="delegation_end")continue;addDelegationEvent(summary,event)}return finalizeSummary(summary)}function foldTelemetryEvents(events){let stats2={conflict_count:0,join_miss_count:0,telemetry_error_count:0,accepted_corrections:0,rejected_corrections:0,duplicate_corrections:0},rows=new Map,states=new Map,legacy=[],corrections=[];for(let event of events){let eventKind=event.event;if(eventKind==="delegation_cost_join"&&event.reason==="join_miss"){stats2.join_miss_count++;continue}if(eventKind==="delegation_cost_join"&&(event.reason==="unreadable"||event.reason==="malformed")){stats2.telemetry_error_count++;continue}if(eventKind!=="delegation_end"&&eventKind!=="delegation_cost_correction")continue;if(eventKind==="delegation_end"){let recordId=boundedId3(event.record_id??event.recordId);if(!recordId){legacy.push(event);continue}let fingerprint2=boundedDigest(event.identity_fingerprint),initialVersion=validVersion(event.version);if(!fingerprint2||initialVersion!==1){legacy.push(event),stats2.rejected_corrections++;continue}let snapshot={...event,record_id:recordId},digest3=boundedDigest(event.digest)??costSnapshotDigest(snapshot);if(rows.has(recordId)){stats2.rejected_corrections++;continue}if(rows.set(recordId,snapshot),states.set(recordId,{version:initialVersion,digest:digest3,fingerprint:fingerprint2}),parseCostSource(event.cost_source)==="unavailable"){if(readEventEvidence(event).some((item)=>item.reason==="conflict"))stats2.conflict_count++}continue}corrections.push(event)}corrections.sort((left,right)=>{let leftRecord=boundedId3(left.record_id??left.recordId)??"",rightRecord=boundedId3(right.record_id??right.recordId)??"";if(leftRecord!==rightRecord)return leftRecord.localeCompare(rightRecord);return(validVersion(left.version)??Number.MAX_SAFE_INTEGER)-(validVersion(right.version)??Number.MAX_SAFE_INTEGER)});for(let event of corrections){let recordId=boundedId3(event.record_id??event.recordId),state2=recordId?states.get(recordId):void 0,current=recordId?rows.get(recordId):void 0;if(!recordId||!state2||!current){stats2.rejected_corrections++;continue}let fingerprint2=boundedDigest(event.identity_fingerprint);if(!fingerprint2||fingerprint2!==state2.fingerprint){stats2.rejected_corrections++;continue}let nextVersion=validVersion(event.version);if(nextVersion===null||nextVersion!==state2.version+1){stats2.rejected_corrections++;continue}let replacement={...current,event:"delegation_end",record_id:recordId,version:event.version,digest:event.digest,cost_evidence:event.cost_evidence,evidence_status:event.evidence_status,evidence_reason:event.evidence_reason,currency:event.currency,cost_usd:event.cost_usd,cost_source:event.cost_source,tokens_input:event.tokens_input,tokens_output:event.tokens_output,tokens_reasoning:event.tokens_reasoning,tokens_cache:event.tokens_cache},digest3=boundedDigest(event.digest)??costSnapshotDigest(replacement);if(digest3===state2.digest){stats2.duplicate_corrections++,states.set(recordId,{version:nextVersion,digest:state2.digest,fingerprint:state2.fingerprint});continue}let currentEvidence=readEventEvidence(current),nextEvidence=readEventEvidence(replacement);if(hasReportConflict(nextEvidence)){stats2.conflict_count++,stats2.rejected_corrections++;continue}if(!isCostUpgrade(currentEvidence,nextEvidence)){stats2.rejected_corrections++;continue}rows.set(recordId,replacement),states.set(recordId,{version:nextVersion,digest:digest3,fingerprint:state2.fingerprint}),stats2.accepted_corrections++}return{events:[...legacy,...rows.values()],stats:stats2,versions:Object.fromEntries([...states].map(([recordId,state2])=>[recordId,state2.version]))}}function boundedId3(value){return typeof value==="string"&&/^[A-Za-z0-9_-]{1,32}$/.test(value)?value:null}function boundedDigest(value){return typeof value==="string"&&/^[a-f0-9]{32,64}$/.test(value)?value:void 0}function validVersion(value){return typeof value==="number"&&Number.isInteger(value)&&value>=1&&value<=1e5?value:null}function readEventEvidence(event){let value=event.cost_evidence??event.evidence;if(!Array.isArray(value))return legacyEventEvidence(event);return value.slice(0,MAX_EVIDENCE_ITEMS).flatMap((item)=>{if(!isRecord2(item))return[];let kind=item.kind==="provider_reported"||item.kind==="normalized_estimate"?item.kind:null,sourcePath=isCostSourcePath(item.source_path)?item.source_path:null,amount=readBoundedReportedCost(item.amount_usd),usage=isRecord2(item.usage)?readPinnedTokens(item.usage):{...UNKNOWN_USAGE};if(!kind||!sourcePath)return[];return[{kind,amount_usd:amount,currency:normalizeCurrency(item.currency),source_path:sourcePath,reason:isCostEvidenceReason(item.reason)?item.reason:amount===null?"missing_cost":"authoritative",usage,model:typeof item.model==="string"?item.model.slice(0,MAX_COST_STRING_LENGTH):void 0,digest:boundedDigest(item.digest)}]})}function legacyEventEvidence(event){let amount=readBoundedReportedCost(event.cost_usd);return[{kind:parseCostSource(event.cost_source)==="estimated"?"normalized_estimate":"provider_reported",amount_usd:amount,currency:"USD",source_path:"legacy.cost",reason:amount===null?"legacy":"authoritative",usage:{tokens_input:readFiniteNonNegative(event.tokens_input),tokens_output:readFiniteNonNegative(event.tokens_output),tokens_reasoning:readFiniteNonNegative(event.tokens_reasoning),tokens_cache:readFiniteNonNegative(event.tokens_cache)}}]}function isCostSourcePath(value){return value==="assistant.cost"||value==="step-finish.cost"||value==="response.info.cost"||value==="response.cost"||value==="legacy.cost"||value==="pricing.model"}function isCostEvidenceReason(value){return value==="authoritative"||value==="missing_cost"||value==="invalid_number"||value==="pricing_missing"||value==="unsupported_currency"||value==="conflict"||value==="unbilled"||value==="join_miss"||value==="legacy"||value==="unreadable"||value==="partial"}function costSnapshotDigest(event){let canonical=JSON.stringify({cost_usd:event.cost_usd??null,cost_source:parseCostSource(event.cost_source),tokens_input:readFiniteNonNegative(event.tokens_input)??0,tokens_output:readFiniteNonNegative(event.tokens_output)??0,tokens_reasoning:readFiniteNonNegative(event.tokens_reasoning)??0,tokens_cache:readFiniteNonNegative(event.tokens_cache)??0,cost_evidence:Array.isArray(event.cost_evidence)?event.cost_evidence.slice(0,MAX_EVIDENCE_ITEMS):void 0}),hash4=2166136261;for(let i=0;i<canonical.length;i++)hash4=Math.imul(hash4^canonical.charCodeAt(i),16777619);return`${(hash4>>>0).toString(16).padStart(8,"0")}${canonical.length.toString(16).padStart(8,"0")}`.slice(0,32)}function evidenceAuthority(evidence2){let projection=projectCostEvidence(evidence2);return projection.cost_source==="reported"?2:projection.cost_source==="estimated"?1:0}function isCostUpgrade(current,next){let currentProjection=projectCostEvidence(current),nextProjection=projectCostEvidence(next),currentAuthority=evidenceAuthority(current),nextAuthority=evidenceAuthority(next);if(nextAuthority>currentAuthority)return!0;if(nextAuthority<currentAuthority)return!1;if(currentProjection.cost_usd!==nextProjection.cost_usd)return!0;let currentUsage=current.reduce(mergeUsage,{...UNKNOWN_USAGE}),nextUsage=next.reduce(mergeUsage,{...UNKNOWN_USAGE}),knownValue=(value)=>value===null?Number.NEGATIVE_INFINITY:value;return Object.keys(currentUsage).some((key2)=>knownValue(nextUsage[key2])>knownValue(currentUsage[key2]))}function readTelemetryEvents(directory){let swarmDir=path128.join(directory,".swarm"),files=[path128.join(swarmDir,"telemetry.jsonl.1"),path128.join(swarmDir,"telemetry.jsonl")],tmpDir;try{tmpDir=fs82.mkdtempSync(path128.join(os17.tmpdir(),"telemetry-snapshot-"))}catch{return[{event:"delegation_cost_join",reason:"unreadable"}]}let snapshotFiles=[],telemetryErrors=0;try{for(let file3 of files){if(!fs82.existsSync(file3))continue;let snap=path128.join(tmpDir,path128.basename(file3));try{let stat13=fs82.statSync(file3);if(!stat13.isFile()||stat13.size>MAX_TELEMETRY_FILE_BYTES){telemetryErrors++;continue}fs82.copyFileSync(file3,snap),snapshotFiles.push(snap)}catch{telemetryErrors++}}}catch{telemetryErrors++}let events=[],unreadableSnapshots=0,firstUnreadableReason="";for(let file3 of snapshotFiles){let content="";try{content=fs82.readFileSync(file3,"utf-8")}catch(err){if(unreadableSnapshots+=1,!firstUnreadableReason)firstUnreadableReason=err instanceof Error?err.message:String(err);continue}for(let line of content.split(/\r?\n/)){let trimmed=line.trim();if(!trimmed)continue;try{let parsed=JSON.parse(trimmed);if(isRecord2(parsed))events.push(parsed)}catch{telemetryErrors++}}}if(unreadableSnapshots>0)telemetryErrors+=unreadableSnapshots,warn(`[cost-accounting] ${unreadableSnapshots} of ${snapshotFiles.length} snapshot file(s) were unreadable; cost totals undercount. First reason: ${firstUnreadableReason}`);try{for(let f of snapshotFiles)try{fs82.unlinkSync(f)}catch{}fs82.rmdirSync(tmpDir)}catch{}if(telemetryErrors>0)events.push({event:"delegation_cost_join",reason:"unreadable"});return events}async function readTelemetryEventsAsync(directory){let swarmDir=path128.join(directory,".swarm"),files=[path128.join(swarmDir,"telemetry.jsonl.1"),path128.join(swarmDir,"telemetry.jsonl")],telemetryErrors=0,contents=await Promise.all(files.map(async(file3)=>{let timer;try{let stat13=await Promise.race([fsp9.stat(file3),new Promise((_,reject2)=>{timer=setTimeout(()=>reject2(Error("telemetry stat timeout")),ASYNC_TELEMETRY_READ_TIMEOUT_MS)})]);if(!stat13.isFile()||stat13.size>MAX_TELEMETRY_FILE_BYTES)return telemetryErrors++,"";if(timer)clearTimeout(timer);return timer=void 0,await Promise.race([fsp9.readFile(file3,"utf8"),new Promise((_,reject2)=>{timer=setTimeout(()=>reject2(Error("telemetry read timeout")),ASYNC_TELEMETRY_READ_TIMEOUT_MS)})])}catch{return telemetryErrors++,""}finally{if(timer)clearTimeout(timer)}})),events=[];for(let content of contents)for(let line of content.split(/\r?\n/)){let trimmed=line.trim();if(!trimmed)continue;try{let parsed=JSON.parse(trimmed);if(isRecord2(parsed))events.push(parsed)}catch{telemetryErrors++}}if(telemetryErrors>0)events.push({event:"delegation_cost_join",reason:"unreadable"});return events}function estimateCostUsd(usage,model,pricing){if(!model)return null;let table={...BUNDLED_MODEL_PRICING,...pricing?.models??{}},entry=table[model]??table[model.toLowerCase()];if(!entry)return null;let perMillion=(value,rate)=>(value??0)/1e6*rate,cost=perMillion(usage.tokens_input,entry.input_per_million)+perMillion(usage.tokens_output,entry.output_per_million)+perMillion(usage.tokens_reasoning,entry.reasoning_per_million??entry.output_per_million)+perMillion(usage.tokens_cache,entry.cache_per_million??entry.input_per_million);return Object.values(usage).some((value)=>value!==null&&value>0)&&Number.isFinite(cost)&&cost>=0?cost:null}function collectPinnedCandidates(raw,input){if(!isRecord2(raw))return[];let candidates=[],add=(value,pathName,pinned)=>{if(!isRecord2(value))return;let model=readModelIdentifier(value)??input.model,tokens2=readPinnedTokens(value),rawCost=value.cost;if(rawCost===void 0&&pinned){candidates.push({kind:"provider_reported",amount:null,currency:"unknown",source_path:pathName,usage:tokens2,model,reason:"missing_cost"});return}if(rawCost===void 0)return;let amount=readBoundedReportedCost(rawCost),currency=pinned?reportedCurrency(model,input):"USD";candidates.push({kind:"provider_reported",amount,currency,source_path:pathName,usage:tokens2,model,reason:amount===null?"invalid_number":void 0})};if(raw.role==="assistant")add(raw,"assistant.cost",!0);if(isRecord2(raw.assistant)&&raw.assistant.role==="assistant")add(raw.assistant,"assistant.cost",!0);if(raw.type==="step-finish")add(raw,"step-finish.cost",!0);if(isRecord2(raw.part)&&raw.part.type==="step-finish")add(raw.part,"step-finish.cost",!0);let data=isRecord2(raw.data)?raw.data:void 0,info=data&&isRecord2(data.info)?data.info:isRecord2(raw.info)?raw.info:void 0;if(info)add(info,"response.info.cost",!0);if(data&&(data.type==="assistant"||data.role==="assistant"))add(data,"response.cost",!0);if(candidates.length===0){let legacy=isRecord2(raw.output)?raw.output:raw,usageRecord=isRecord2(legacy.usage)?legacy.usage:legacy,usage=readPinnedTokens(usageRecord),amount=readBoundedReportedCost(legacy.cost_usd??legacy.total_cost_usd??legacy.cost);if(amount!==null||legacy.cost_usd!==void 0||legacy.cost!==void 0)candidates.push({kind:"provider_reported",amount,currency:"USD",source_path:"legacy.cost",usage,model:readModelIdentifier(legacy)??input.model,reason:amount===null?"invalid_number":void 0})}return candidates.slice(0,MAX_EVIDENCE_ITEMS)}function readPinnedTokens(record3){let tokens2=isRecord2(record3.tokens)?record3.tokens:isRecord2(record3.usage)?record3.usage:record3;return{tokens_input:readFiniteNonNegative(tokens2.tokens_input??tokens2.input??tokens2.input_tokens??tokens2.prompt_tokens)??null,tokens_output:readFiniteNonNegative(tokens2.tokens_output??tokens2.output??tokens2.output_tokens??tokens2.completion_tokens)??null,tokens_reasoning:readFiniteNonNegative(tokens2.tokens_reasoning??tokens2.reasoning??tokens2.reasoning_tokens)??null,tokens_cache:readFiniteNonNegative(tokens2.tokens_cache)??readCacheTokens(tokens2)??null}}function readLegacyUsage(raw){if(!isRecord2(raw))return{...UNKNOWN_USAGE};let output=isRecord2(raw.output)?raw.output:raw,usage=isRecord2(output.usage)?output.usage:output;return readPinnedTokens(usage)}function mergeUsage(total,next){let usage="usage"in next&&next.usage?next.usage:next;return{tokens_input:maxKnownAxis(total.tokens_input,usage.tokens_input),tokens_output:maxKnownAxis(total.tokens_output,usage.tokens_output),tokens_reasoning:maxKnownAxis(total.tokens_reasoning,usage.tokens_reasoning),tokens_cache:maxKnownAxis(total.tokens_cache,usage.tokens_cache)}}function readFiniteNonNegative(value){return typeof value==="number"&&Number.isFinite(value)&&value>=0?value:null}function readBoundedReportedCost(value){let amount=readFiniteNonNegative(value);return amount!==null&&amount<=MAX_PROVIDER_REPORTED_COST_USD?amount:null}function normalizeCurrency(value){if(typeof value!=="string"||value.trim()==="")return"unknown";return value.trim().slice(0,MAX_COST_STRING_LENGTH).toUpperCase()||"unknown"}function boundedCostLabel(value){return typeof value==="string"&&value.trim()!==""?value.trim().slice(0,MAX_COST_STRING_LENGTH):void 0}function reportedCurrency(model,input){if(input.reported_cost_currency)return normalizeCurrency(input.reported_cost_currency);let provider=model?.split("/")[0],configured=input.pricing?.reported_cost_currency,value=provider?configured?.[provider]:void 0;return normalizeCurrency(value)}function hasReportConflict(reports){let monetary=reports.filter((item)=>item.kind==="provider_reported"&&item.amount_usd!==null);for(let i=0;i<monetary.length;i++)for(let j=i+1;j<monetary.length;j++){let left=monetary[i],right=monetary[j];if(left.currency!==right.currency)return!0;if(left.currency==="USD"&&!withinCostTolerance(left.amount_usd??0,right.amount_usd??0))return!0}return!1}function withinCostTolerance(left,right){return Math.abs(left-right)<=Math.max(0.000000001,Math.max(Math.abs(left),Math.abs(right))*0.000001)}function readNumber(record3,keys){for(let key2 of keys){let value=record3[key2];if(typeof value==="number"&&Number.isFinite(value)&&value>=0)return value;if(typeof value==="string"&&value.trim()!==""){let parsed=Number(value);if(Number.isFinite(parsed)&&parsed>=0)return parsed}}return null}function readString(record3,keys){for(let key2 of keys){let value=record3[key2];if(typeof value==="string"&&value.trim()!=="")return value.trim()}return}function readModelIdentifier(record3){let direct=readString(record3,["model","model_id"]);if(direct)return direct;let modelID=readString(record3,["modelID"]),providerID=readString(record3,["providerID"]);if(modelID&&providerID)return`${providerID}/${modelID}`;return modelID}function readCacheTokens(record3){let cacheRecord=isRecord2(record3.cache)?record3.cache:record3,read=readNumber(cacheRecord,["read","cache_read_input_tokens","cached_input_tokens"]),write=readNumber(cacheRecord,["write","cache_write_input_tokens","write_input_tokens"]);if(read===null&&write===null)return null;return(read??0)+(write??0)}function isRecord2(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function createEmptySummary(){return{total_cost_usd:0,total_reported_usd:0,total_estimated_usd:0,total_input_tokens:null,total_output_tokens:null,total_reasoning_tokens:null,total_cache_tokens:null,delegations:0,unavailable_delegations:0,unknown_usage_delegations:0,by_agent:[],by_task:[],by_gate:[],by_retry:[],by_source:{reported:{delegations:0,cost_usd:0},estimated:{delegations:0,cost_usd:0},unavailable:{delegations:0,cost_usd:0}},total_legacy_usd:0,conflict_count:0,legacy_count:0,join_miss_count:0,telemetry_error_count:0,accepted_corrections:0,rejected_corrections:0,duplicate_corrections:0,evidence_status:"complete",currencies:[]}}function addDelegationEvent(summary,event){let legacyCostSource=parseCostSource(event.cost_source),legacyCost=readNumber(event,["cost_usd"])??0,hasRecord=boundedId3(event.record_id??event.recordId)!==null,evidence2=readEventEvidence(event),projection=projectCostEvidence(evidence2),costSource=hasRecord?projection.cost_source:legacyCostSource,cost=hasRecord?projection.cost_usd??0:legacyCost;if(!hasRecord)summary.legacy_count++,summary.total_legacy_usd+=legacyCost,summary.evidence_status="inconclusive";if(projection.evidence_status==="inconclusive")summary.evidence_status="inconclusive";for(let item of evidence2)if(item.currency!=="unknown"&&!summary.currencies.includes(item.currency))summary.currencies.push(item.currency);let legacyUsage={tokens_input:readNumber(event,["tokens_input"]),tokens_output:readNumber(event,["tokens_output"]),tokens_reasoning:readNumber(event,["tokens_reasoning"]),tokens_cache:readNumber(event,["tokens_cache"])},evidenceUsage=evidence2.reduce((acc,item)=>({tokens_input:maxKnownAxis(acc.tokens_input,item.usage.tokens_input),tokens_output:maxKnownAxis(acc.tokens_output,item.usage.tokens_output),tokens_reasoning:maxKnownAxis(acc.tokens_reasoning,item.usage.tokens_reasoning),tokens_cache:maxKnownAxis(acc.tokens_cache,item.usage.tokens_cache)}),{...UNKNOWN_USAGE}),usage=hasRecord?evidenceUsage:legacyUsage;if(summary.delegations++,summary.total_cost_usd+=cost,isUnknownUsage(usage))summary.unknown_usage_delegations++;if(summary.total_input_tokens=sumKnownAxis(summary.total_input_tokens,usage.tokens_input),summary.total_output_tokens=sumKnownAxis(summary.total_output_tokens,usage.tokens_output),summary.total_reasoning_tokens=sumKnownAxis(summary.total_reasoning_tokens,usage.tokens_reasoning),summary.total_cache_tokens=sumKnownAxis(summary.total_cache_tokens,usage.tokens_cache),summary.by_source[costSource].delegations++,summary.by_source[costSource].cost_usd+=cost,costSource==="reported")summary.total_reported_usd+=cost;if(costSource==="estimated")summary.total_estimated_usd+=cost;if(costSource==="unavailable")summary.unavailable_delegations++;addRow(summary.by_agent,String(event.agentName??event.agent??"unknown"),{cost,costSource,usage}),addRow(summary.by_task,String(event.taskId??event.task_id??"unknown"),{cost,costSource,usage}),addRow(summary.by_gate,String(event.gate??"unknown"),{cost,costSource,usage}),addRow(summary.by_retry,String(readNumber(event,["retry_index","retryIndex"])??0),{cost,costSource,usage})}function addRow(rows,name,input){let row=rows.find((candidate)=>candidate.name===name);if(!row)row={name,delegations:0,cost_usd:0,input_tokens:null,output_tokens:null,reasoning_tokens:null,cache_tokens:null,unavailable_delegations:0},rows.push(row);if(row.delegations++,row.cost_usd+=input.cost,row.input_tokens=sumKnownAxis(row.input_tokens,input.usage.tokens_input),row.output_tokens=sumKnownAxis(row.output_tokens,input.usage.tokens_output),row.reasoning_tokens=sumKnownAxis(row.reasoning_tokens,input.usage.tokens_reasoning),row.cache_tokens=sumKnownAxis(row.cache_tokens,input.usage.tokens_cache),input.costSource==="unavailable")row.unavailable_delegations++}function finalizeSummary(summary){if(summary.total_cost_usd=roundUsd(summary.total_cost_usd),summary.total_reported_usd=roundUsd(summary.total_reported_usd),summary.total_estimated_usd=roundUsd(summary.total_estimated_usd),summary.total_legacy_usd=roundUsd(summary.total_legacy_usd),summary.delegations===0&&summary.join_miss_count===0&&summary.telemetry_error_count===0)summary.total_input_tokens??=0,summary.total_output_tokens??=0,summary.total_reasoning_tokens??=0,summary.total_cache_tokens??=0;for(let source of Object.values(summary.by_source))source.cost_usd=roundUsd(source.cost_usd);for(let rows of[summary.by_agent,summary.by_task,summary.by_gate,summary.by_retry]){for(let row of rows)row.cost_usd=roundUsd(row.cost_usd);rows.sort((a,b)=>b.cost_usd-a.cost_usd||b.delegations-a.delegations)}return summary}function parseCostSource(value){return value==="reported"||value==="estimated"||value==="unavailable"?value:"unavailable"}function roundUsd(value){return Math.round(value*1e6)/1e6}var UNKNOWN_USAGE,MAX_EVIDENCE_ITEMS=8,MAX_COST_STRING_LENGTH=128,MAX_PROVIDER_REPORTED_COST_USD=1e9,MAX_TELEMETRY_FILE_BYTES=4194304,ASYNC_TELEMETRY_READ_TIMEOUT_MS=500,BUNDLED_MODEL_PRICING;var init_cost_accounting=__esm(()=>{init_logger();UNKNOWN_USAGE={tokens_input:null,tokens_output:null,tokens_reasoning:null,tokens_cache:null};BUNDLED_MODEL_PRICING={}});function summarizeGateAuditStatistics(report){let caught=report.models.reduce((total,model)=>total+model.caught,0),missed=report.models.reduce((total,model)=>total+model.missed,0),falseRejections=report.models.reduce((total,model)=>total+model.falseRejections,0),negativeControls=report.models.reduce((total,model)=>total+model.negativeControls,0),regressions=caught+missed,insufficientData=report.models.length===0||report.models.some((model)=>model.insufficientData),truthAvailable=report.runs===1&&report.corruptRuns.length===0&&report.groundTruth.parsed>0&&report.groundTruth.malformed===0&&report.groundTruth.ambiguous===0&&report.groundTruth.unjoined===0&&!insufficientData;return{caught,missed,regressions,falseRejections,negativeControls,catchRate:regressions===0?null:caught/regressions*100,falseRejectionRate:negativeControls===0?null:falseRejections/negativeControls*100,insufficientData,truthAvailable}}async function handleBenchmarkCommand(directory,args2){let cumulative=args2.includes("--cumulative");if(args2.includes("--ci-gate"))cumulative=!0;let maxCostUsd=parseMaxCostUsd(args2),gateAuditRunId=parseGateAuditRunId(args2),gateAudit=gateAuditRunId?await readGateAuditResult(directory,gateAuditRunId):void 0;if(gateAuditRunId&&!gateAudit)throw Error(`Gate-audit result not found: ${gateAuditRunId}`);let gateAuditStatistics=gateAuditRunId?await computeGateStatistics(directory,GATE_AUDIT_MIN_SAMPLES,gateAuditRunId):void 0,gateAuditSummary=gateAuditStatistics?summarizeGateAuditStatistics(gateAuditStatistics):void 0,mode=cumulative?"cumulative":"in-memory",costSummary=cumulative?summarizeTelemetryCosts(directory):void 0,agentMap=new Map;for(let[,s]of swarmState.agentSessions){let e=agentMap.get(s.agentName)||{toolCalls:0,hardLimits:0,warnings:0},windows=Object.values(s.windows);e.toolCalls+=windows.reduce((sum,w)=>sum+w.toolCalls,0),e.hardLimits+=windows.filter((w)=>w.hardLimitHit).length,e.warnings+=windows.filter((w)=>w.warningIssued).length,agentMap.set(s.agentName,e)}let agentHealth=Array.from(agentMap.entries()).map(([a,v])=>({agent:a,...v})),toolPerf=[];for(let[,a]of swarmState.toolAggregates){let successRate=a.count?a.successCount/a.count*100:0;toolPerf.push({tool:a.tool,calls:a.count,successRate:Math.round(successRate*10)/10,avg:a.count?Math.round(a.totalDuration/a.count):0})}toolPerf.sort((a,b)=>b.calls-a.calls);let delegationCount=0;for(let c of swarmState.delegationChains.values())delegationCount+=c.length;let quality,qualityMetrics;if(cumulative){let summary=await computeEvidenceQualitySummary(directory);quality={reviewPassRate:summary.reviewPassRate,testPassRate:summary.testPassRate,totalReviews:summary.totalReviews,testsPassed:summary.testsPassed,testsFailed:summary.testsFailed,additions:summary.additions,deletions:summary.deletions},qualityMetrics=summary.qualityMetrics}let ciGate;if(args2.includes("--ci-gate")){let totalCalls=0,totalFailures=0;for(let[,a]of swarmState.toolAggregates)totalCalls+=a.count,totalFailures+=a.failureCount;let agentErrorRate=totalCalls?totalFailures/totalCalls*100:0,maxHardLimits=0;for(let v of agentMap.values())if(v.hardLimits>maxHardLimits)maxHardLimits=v.hardLimits;let hasQualityEvidence=qualityMetrics?.hasEvidence??!1,complexityDelta=qualityMetrics?.complexityDelta??0,publicApiDelta=qualityMetrics?.publicApiDelta??0,duplicationRatio=qualityMetrics?.duplicationRatio??0,testToCodeRatio=qualityMetrics?.testToCodeRatio??0,checks5=[{name:"Review pass rate",value:quality?.reviewPassRate??0,threshold:CI.review_pass_rate,operator:">=",passed:(quality?.reviewPassRate??0)>=CI.review_pass_rate},{name:"Test pass rate",value:quality?.testPassRate??0,threshold:CI.test_pass_rate,operator:">=",passed:(quality?.testPassRate??0)>=CI.test_pass_rate},{name:"Agent error rate",value:Math.round(agentErrorRate*10)/10,threshold:CI.max_agent_error_rate,operator:"<=",passed:agentErrorRate<=CI.max_agent_error_rate},{name:"Hard limit hits",value:maxHardLimits,threshold:CI.max_hard_limit_hits,operator:"<=",passed:maxHardLimits<=CI.max_hard_limit_hits},{name:"Complexity Delta",value:complexityDelta,threshold:CI.max_complexity_delta,operator:"<=",passed:!hasQualityEvidence||complexityDelta<=CI.max_complexity_delta},{name:"Public API Delta",value:publicApiDelta,threshold:CI.max_public_api_delta,operator:"<=",passed:!hasQualityEvidence||publicApiDelta<=CI.max_public_api_delta},{name:"Duplication Ratio",value:duplicationRatio,threshold:CI.max_duplication_ratio,operator:"<=",passed:!hasQualityEvidence||duplicationRatio<=CI.max_duplication_ratio},{name:"Test-to-Code Ratio",value:testToCodeRatio,threshold:CI.min_test_to_code_ratio,operator:">=",passed:!hasQualityEvidence||testToCodeRatio>=CI.min_test_to_code_ratio}];if(maxCostUsd!==null){let costEvidenceComplete=costSummary!==void 0&&costSummary.delegations>0&&costSummary.evidence_status==="complete";checks5.push({name:"Total cost",value:costSummary?.total_cost_usd??0,threshold:maxCostUsd,operator:"<=",passed:costEvidenceComplete&&(costSummary?.total_cost_usd??0)<=maxCostUsd,evidence_status:costEvidenceComplete?"complete":"inconclusive",reason:costEvidenceComplete?(costSummary?.total_cost_usd??0)<=maxCostUsd?void 0:"thresholdExceeded":"budgetInconclusive"})}if(gateAudit&&gateAuditSummary){let catchRate=gateAuditSummary.catchRate??0;checks5.push({name:"Gate audit complete",value:gateAudit.status==="complete"?1:0,threshold:1,operator:">=",passed:gateAudit.status==="complete"},{name:"Gate audit ground truth",value:gateAuditSummary.truthAvailable?1:0,threshold:1,operator:">=",passed:gateAuditSummary.truthAvailable},{name:"Gate audit catch rate",value:Math.round(catchRate*10)/10,threshold:100,operator:">=",passed:gateAuditSummary.truthAvailable&&catchRate===100},{name:"Gate audit clean-control rejections",value:gateAuditSummary.falseRejections,threshold:0,operator:"<=",passed:gateAuditSummary.truthAvailable&&gateAuditSummary.falseRejections===0})}ciGate={passed:checks5.every((c)=>c.passed),checks:checks5}}let lines=[`## Swarm Benchmark (mode: ${mode})`,"","### Agent Health"];if(!agentHealth.length)lines.push("No agent sessions recorded");else for(let{agent,toolCalls,hardLimits,warnings}of agentHealth){let parts=[`${toolCalls} tool calls`];if(warnings>0)parts.push(`${warnings} warning${warnings>1?"s":""}`);parts.push(hardLimits?`${hardLimits} hard limit hit${hardLimits>1?"s":""}`:"0 hard limits"),lines.push(`- ${hardLimits?"⚠️":"✅"} **${agent}**: ${parts.join(", ")}`)}if(lines.push("","### Tool Performance"),!toolPerf.length)lines.push("No tool data recorded");else{lines.push("| Tool | Calls | Success Rate | Avg Duration |","|------|-------|-------------|-------------|");for(let{tool:tool3,calls,successRate,avg}of toolPerf)lines.push(`| ${tool3} | ${calls} | ${successRate}% | ${avg}ms |`)}if(lines.push("","### Delegations",delegationCount?`Total: ${delegationCount} delegations`:"No delegations recorded",""),quality){if(lines.push("### Quality Signals"),!quality.totalReviews&&!quality.testsPassed&&!quality.additions)lines.push("No evidence data found");else{if(quality.reviewPassRate!==null)lines.push(`- Review pass rate: ${quality.reviewPassRate}% (${quality.totalReviews}) ${quality.reviewPassRate>=70?"✅":"❌"}`);else lines.push("- Review pass rate: N/A (no reviews)");if(quality.testPassRate!==null)lines.push(`- Test pass rate: ${quality.testPassRate}% (${quality.testsPassed}/${quality.testsPassed+quality.testsFailed}) ${quality.testPassRate>=80?"✅":"❌"}`);else lines.push("- Test pass rate: N/A (no tests)");lines.push(`- Code churn: +${quality.additions} / -${quality.deletions} lines`)}lines.push("")}if(qualityMetrics?.hasEvidence)lines.push("### Quality Metrics"),lines.push(`- Complexity Delta: ${qualityMetrics.complexityDelta} (max: ${qualityMetrics.thresholds.maxComplexityDelta}) ${qualityMetrics.complexityDelta<=qualityMetrics.thresholds.maxComplexityDelta?"✅":"❌"}`),lines.push(`- Public API Delta: ${qualityMetrics.publicApiDelta} (max: ${qualityMetrics.thresholds.maxPublicApiDelta}) ${qualityMetrics.publicApiDelta<=qualityMetrics.thresholds.maxPublicApiDelta?"✅":"❌"}`),lines.push(`- Duplication Ratio: ${qualityMetrics.duplicationRatio}% (max: ${qualityMetrics.thresholds.maxDuplicationRatio}%) ${qualityMetrics.duplicationRatio<=qualityMetrics.thresholds.maxDuplicationRatio?"✅":"❌"}`),lines.push(`- Test-to-Code Ratio: ${qualityMetrics.testToCodeRatio}% (min: ${qualityMetrics.thresholds.minTestToCodeRatio}%) ${qualityMetrics.testToCodeRatio>=qualityMetrics.thresholds.minTestToCodeRatio?"✅":"❌"}`),lines.push("");if(costSummary)lines.push("### Cost Signals"),lines.push(`- Total tracked cost: $${costSummary.total_cost_usd.toFixed(6)} (${costSummary.delegations} delegations)`,`- Reported: $${costSummary.total_reported_usd.toFixed(6)}; estimated: $${costSummary.total_estimated_usd.toFixed(6)}; unavailable: ${costSummary.unavailable_delegations}`),lines.push("");if(gateAudit&&gateAuditStatistics&&gateAuditSummary)lines.push("### Gate Audit",`- Run: ${gateAudit.runId}`,`- Status: ${gateAudit.status}`,`- Ground truth: ${gateAuditSummary.truthAvailable?"available":"unavailable"} (parsed ${gateAuditStatistics.groundTruth.parsed}; malformed ${gateAuditStatistics.groundTruth.malformed}; ambiguous ${gateAuditStatistics.groundTruth.ambiguous}; unjoined ${gateAuditStatistics.groundTruth.unjoined}; insufficient ${gateAuditSummary.insufficientData})`,`- Regression catches: ${gateAuditSummary.caught}/${gateAuditSummary.regressions}`,`- Clean-control rejections: ${gateAuditSummary.falseRejections}/${gateAuditSummary.negativeControls}`,"- complexity_delta/public_api_delta: true base-vs-head deltas (#2470); not consumed by promotion regression math","");if(ciGate){lines.push("### CI Gate",ciGate.passed?"✅ PASSED":"❌ FAILED");for(let c of ciGate.checks){if(c.name==="Total cost"&&c.evidence_status==="inconclusive"){lines.push(`- Total cost: inconclusive (budget evidence unavailable) <= $${c.threshold.toFixed(6)} ❌`);continue}let valueStr;if(c.name==="Complexity Delta"||c.name==="Public API Delta")valueStr=`${c.value}`;else if(c.name==="Total cost")valueStr=`$${c.value.toFixed(6)}`;else valueStr=`${c.value}%`;let thresholdStr=c.name==="Complexity Delta"||c.name==="Public API Delta"?`${c.threshold}`:c.name==="Total cost"?`$${c.threshold.toFixed(6)}`:`${c.threshold}%`;lines.push(`- ${c.name}: ${valueStr} ${c.operator} ${thresholdStr} ${c.passed?"✅":"❌"}`)}lines.push("")}let json3={mode,timestamp:new Date().toISOString(),agent_health:agentHealth.map((a)=>({agent:a.agent,tool_calls:a.toolCalls,hard_limit_hits:a.hardLimits,warnings:a.warnings})),tool_performance:toolPerf.map((t)=>({tool:t.tool,calls:t.calls,success_rate:t.successRate,avg_duration_ms:t.avg})),delegations:delegationCount};if(quality)json3.quality={review_pass_rate:quality.reviewPassRate,test_pass_rate:quality.testPassRate,total_reviews:quality.totalReviews,total_tests_passed:quality.testsPassed,total_tests_failed:quality.testsFailed,additions:quality.additions,deletions:quality.deletions};if(qualityMetrics)json3.quality_metrics={complexity_delta:qualityMetrics.complexityDelta,public_api_delta:qualityMetrics.publicApiDelta,duplication_ratio:qualityMetrics.duplicationRatio,test_to_code_ratio:qualityMetrics.testToCodeRatio,thresholds:qualityMetrics.thresholds,has_evidence:qualityMetrics.hasEvidence};if(costSummary)json3.costs={total_cost_usd:costSummary.total_cost_usd,total_reported_usd:costSummary.total_reported_usd,total_estimated_usd:costSummary.total_estimated_usd,total_input_tokens:costSummary.total_input_tokens,total_output_tokens:costSummary.total_output_tokens,total_reasoning_tokens:costSummary.total_reasoning_tokens,total_cache_tokens:costSummary.total_cache_tokens,unknown_usage_delegations:costSummary.unknown_usage_delegations,delegations:costSummary.delegations,unavailable_delegations:costSummary.unavailable_delegations};if(gateAudit&&gateAuditStatistics&&gateAuditSummary)json3.gate_audit={run_id:gateAudit.runId,status:gateAudit.status,manifest_hash:gateAudit.manifestHash,cells:gateAudit.cells.length,caught:gateAuditSummary.caught,missed:gateAuditSummary.missed,regressions:gateAuditSummary.regressions,catch_rate:gateAuditSummary.catchRate,clean_control_rejections:gateAuditSummary.falseRejections,negative_controls:gateAuditSummary.negativeControls,false_rejection_rate:gateAuditSummary.falseRejectionRate,ground_truth_available:gateAuditSummary.truthAvailable,insufficient_data:gateAuditSummary.insufficientData,ground_truth:gateAuditStatistics.groundTruth,corrupt_runs:gateAuditStatistics.corruptRuns,quality_metric_availability:gateAudit.qualityMetricAvailability};if(ciGate)json3.ci_gate={passed:ciGate.passed,checks:ciGate.checks.map((c)=>({name:c.name,value:c.value,threshold:c.threshold,operator:c.operator,passed:c.passed,...c.evidence_status?{evidence_status:c.evidence_status}:{},...c.reason?{reason:c.reason}:{}}))};lines.push("[BENCHMARK_JSON]",JSON.stringify(json3,null,2),"[/BENCHMARK_JSON]");let output=lines.join(`
|
|
@@ -1410,7 +1410,7 @@ ${step.stderr}`);if(fileRefs.length>0){lines.push(""),lines.push("**Failure loca
|
|
|
1410
1410
|
target TEXT NOT NULL,
|
|
1411
1411
|
edge_json TEXT NOT NULL
|
|
1412
1412
|
)`},{version:5,name:"create_edges_source_index",sql:"CREATE INDEX idx_edges_source ON edges(source)"},{version:6,name:"create_edges_target_index",sql:"CREATE INDEX idx_edges_target ON edges(target)"}],LATEST_SCHEMA_VERSION=MIGRATIONS2[MIGRATIONS2.length-1]?.version??0,_handles=new Map;_internals122={isIndexedStorageAvailable,removeRepoMemoryFiles,unlinkSync:unlinkSync21,cacheHandle,maxOpenHandles:MAX_OPEN_HANDLES,openHandleCount:()=>_handles.size,hasOpenHandle:(workspace)=>{try{return _handles.has(getRepoMemoryPath(workspace))}catch{return!1}}}});var NO_RECEIPT_PHASE_CLOSE_SCOPE_DETAIL="no exact receipt lifecycle scope exists for phase closure",CLOSE_SKILL_REVIEW_TIMEOUT_MS=120000,CLOSE_REFLECTION_TIMEOUT_MS=90000,ARCHIVE_ARTIFACTS,ACTIVE_STATE_TO_CLEAN,TERMINAL_STATE_FILES,KNOWLEDGE_FAMILY_ARTIFACTS,REQUIRED_ARTIFACTS,ACTIVE_STATE_DIRS_TO_CLEAN,ACTIVE_STATE_UNLINK_RETRY_DELAYS_MS;var init_constants2=__esm(()=>{init_indexed_storage();ARCHIVE_ARTIFACTS=["plan.json","plan.md","plan-ledger.jsonl","context.md","events.jsonl","events-authority-index.json","handoff.md","handoff-prompt.md","handoff-consumed.md","escalation-report.md","close-lessons.md","knowledge.jsonl","knowledge-rejected.jsonl","knowledge-receipts-v2.jsonl","knowledge-receipts-v2.snapshot.json","knowledge-receipts-v2-archive.jsonl","run-memory.jsonl","repo-graph.json","repo-graph.fingerprint.json","doc-manifest.json","dark-matter.md","telemetry.jsonl","telemetry.jsonl.1","swarm.db","epic-state.json","turbo-state.json",REPO_MEMORY_FILENAME,"close-summary.md","session-reflection.md","spec.md","spec-staleness.json","spec-snapshot.md","background-delegations.jsonl","background-delegations.checkpoint.json","background-delegations.manifest.json","background-delegations-health.json","context-telemetry.jsonl","workspace-snapshot.digest"],ACTIVE_STATE_TO_CLEAN=["plan.json","plan.md","plan-ledger.jsonl","events.jsonl","events-authority-index.json","handoff.md","handoff-prompt.md","handoff-consumed.md","escalation-report.md","knowledge-rejected.jsonl","run-memory.jsonl","repo-graph.json","repo-graph.fingerprint.json","doc-manifest.json","dark-matter.md","telemetry.jsonl","telemetry.jsonl.1","session-reflection.md","spec.md","spec-staleness.json","spec-snapshot.md","swarm.db",REPO_MEMORY_FILENAME,"epic-state.json","turbo-state.json","workspace-snapshot.digest"],TERMINAL_STATE_FILES=["plan.json","plan-ledger.jsonl","spec-staleness.json","spec-snapshot.md"],KNOWLEDGE_FAMILY_ARTIFACTS=new Set(["knowledge.jsonl","knowledge-rejected.jsonl"]),REQUIRED_ARTIFACTS=new Set(["plan.json","plan-ledger.jsonl"]),ACTIVE_STATE_DIRS_TO_CLEAN=["coder-settlements","council","evidence","session","scopes","spec-archive","task-repairs","task-terminals","runs","epic"],ACTIVE_STATE_UNLINK_RETRY_DELAYS_MS=[25,50,100,200,400,600,800,1000,1000,1000,1000,1000,1000,1000,1000,1000,1000,1000,1000,1000]});import*as fsSync12 from"node:fs";import{promises as fs85}from"node:fs";var closeReceiptLifecycleInternals,_internals123;var init_internals=__esm(()=>{init_audit_log();init_shell_audit_store();init_constants2();closeReceiptLifecycleInternals={recordPhaseCloseIntent:void 0,reconcilePhaseClose:void 0},_internals123={closeSnapshotCoordinationInitialization:void 0,closeRepoMemory:void 0,unlinkActiveStateFileWithRetry:void 0,unlink:fs85.unlink,unlinkSidecarSync:fsSync12.unlinkSync,sleep:void 0,collectGarbageBestEffort:void 0,ACTIVE_STATE_DIRS_TO_CLEAN,countSessionKnowledgeEntries:void 0,CLOSE_SKILL_REVIEW_TIMEOUT_MS,CLOSE_REFLECTION_TIMEOUT_MS,detectFullAuto:void 0,guaranteeAllPlansComplete:void 0,getGitRepositoryStatus:void 0,resetToMainAfterMerge:void 0,resetToRemoteBranch:void 0,copyDirRecursive:void 0,loadPluginConfigWithMeta:void 0,curateAndStoreSwarm:void 0,checkHivePromotions:void 0,runCuratorPostMortem:void 0,createCuratorLLMDelegate:void 0,resetSwarmStatePreservingSingletons:void 0,runFinalizeStage:void 0,runFinalizeRewardSweep:void 0,acquireFinalizeLock:void 0,runArchiveStage:void 0,archiveCloseSummary:void 0,runArchiveEvidenceRetention:void 0,runCleanStage:void 0,runAlignStage:void 0,runFinalizeDryRun:void 0,archiveEvidence:void 0,closePlanTerminalState:void 0,endAgentSession:void 0,flushAndDrainTelemetry:void 0,finalizeContextTelemetry:void 0,finalizeCoreEvents:void 0,finalizeShellAudit:(directory)=>{finalizeShellAuditForClose(directory,{lineTransform:redactDecisionLineForArchive})}}});function renderRecheckRefusal(reason,newDirtyPaths){let listed=newDirtyPaths.slice(0,10),overflow=newDirtyPaths.length-listed.length,swarmHint=newDirtyPaths.some((p)=>p.startsWith(".swarm/"))?"One or more changed paths are under .swarm/ — this project tracks swarm runtime state in git. Consider `git rm -r --cached .swarm/` and re-adding `.swarm/` to .git/info/exclude; close never confirms runtime state as destructive scope.":void 0;return[`\uD83D\uDED1 Git alignment aborted (fail-closed): ${reason} — this destructive scope was never confirmed${listed[0]?` (first: ${listed[0]})`:""}.`,...listed.map((p)=>` - ${p}`),...overflow>0?[` … and ${overflow} more`]:[],...swarmHint?[swarmHint]:[],"Nothing was reset or checked out; the session is finalized (finalize/archive/clean completed). Complete git alignment manually if still wanted."].join(`
|
|
1413
|
-
`)}async function guardResetWithRecheck(real,cwd,options){let recheck=await recheckBeforeDestructive(cwd,options?.expectedDirtyPaths??[]);if(recheck.ok)return real(cwd,{pruneBranches:options?.pruneBranches});return log(`[close-align] re-check refused destructive reset: ${recheck.reason} (${recheck.newDirtyPaths.length} newly-dirty path(s))`),{success:!1,targetBranch:"",previousBranch:"",message:renderRecheckRefusal(recheck.reason,recheck.newDirtyPaths),branchDeleted:!1,changesDiscarded:!1,warnings:[],recheckRefused:!0}}async function runAlignStage(ctx){let pruneBranches=ctx.args.includes("--prune-branches"),gitAlignResult="",prunedBranches=[],gitStatus=_internals123.getGitRepositoryStatus(ctx.directory);if(gitStatus.isRepo){let aggressiveResult=await _internals123.resetToMainAfterMerge(ctx.directory,{pruneBranches,expectedDirtyPaths:ctx.purgeGateDirtyPaths??[]});if(aggressiveResult.recheckRefused)return gitAlignResult=aggressiveResult.message,ctx.warnings.push(aggressiveResult.message),{gitAlignResult,prunedBranches};if(aggressiveResult.success){gitAlignResult=aggressiveResult.message;for(let w of aggressiveResult.warnings)ctx.warnings.push(w);if(aggressiveResult.changesDiscarded)ctx.warnings.push("Uncommitted changes were discarded during git alignment")}else{let alignResult=await _internals123.resetToRemoteBranch(ctx.directory,{pruneBranches});if(gitAlignResult=alignResult.message,prunedBranches.push(...alignResult.prunedBranches),!alignResult.success)ctx.warnings.push(`Git alignment: ${alignResult.message}`);if(alignResult.alreadyAligned)gitAlignResult=`Already aligned with ${alignResult.targetBranch}`;for(let w of alignResult.warnings)ctx.warnings.push(w)}}else if(gitStatus.reason==="git_unavailable")gitAlignResult=`Git executable unavailable — skipped git alignment: ${gitStatus.message}`,ctx.warnings.push(gitAlignResult);else if(gitStatus.reason==="git_error")gitAlignResult=`Git repository check failed — skipped git alignment: ${gitStatus.message}`,ctx.warnings.push(gitAlignResult);else gitAlignResult="Not a git repository — skipped git alignment";return{gitAlignResult,prunedBranches}}var init_align_stage=__esm(()=>{init_logger();init_destructive_purge();init_internals()});import*as fsSync13 from"node:fs";import path135 from"node:path";function resolveDatabaseCtor(){return _internals124.DatabaseCtor??loadDatabaseCtor()}function safeRemoveTemp(tempPath){try{_internals124.rmSync(tempPath,{force:!0,recursive:!0,maxRetries:3,retryDelay:100})}catch{}}function buildVacuumIntoSql(destPath){return`VACUUM INTO '${destPath.replace(/\\/g,"/").replace(/'/g,"''")}'`}function rowString(row,col){if(row&&typeof row==="object"&&col in row){let v=row[col];return v===null||v===void 0?"":String(v)}return""}function rowNumber(row,col){if(row&&typeof row==="object"&&col in row){let v=row[col];if(typeof v==="number"&&Number.isFinite(v))return v;if(typeof v==="bigint")return Number(v);if(typeof v==="string"){let n=Number(v);if(Number.isFinite(n))return n}}return null}function captureRowCounts(db){let tableExists=(name)=>{let row=db.query("SELECT COUNT(*) AS c FROM sqlite_master WHERE type='table' AND name=?").get(name);return rowNumber(row,"c")!==null&&(rowNumber(row,"c")??0)>0},schemaMigrationsMax=null;if(tableExists("schema_migrations")){let row=db.query("SELECT MAX(version) AS m FROM schema_migrations").get();schemaMigrationsMax=rowNumber(row,"m")}let projectConstraints=tableExists("project_constraints")?rowNumber(db.query("SELECT COUNT(*) AS c FROM project_constraints").get(),"c")??0:0,qaGateProfile=tableExists("qa_gate_profile")?rowNumber(db.query("SELECT COUNT(*) AS c FROM qa_gate_profile").get(),"c")??0:0;return{schema_migrations_max_version:schemaMigrationsMax,project_constraints:projectConstraints,qa_gate_profile:qaGateProfile}}async function archiveSqliteSnapshot(opts){let maxSourceBytes=opts.maxSourceBytes??DEFAULT_MAX_SOURCE_BYTES2,busyTimeoutMs=opts.busyTimeoutMs??DEFAULT_BUSY_TIMEOUT_MS;if(!_internals124.existsSync(opts.sourcePath))return{requiredness:"required",attempt:"not_attempted",validation:"not_applicable",source_disposition:"absent",method:"none",reason_code:"source_absent"};let sourceBytes=0;for(let suffix of["","-wal","-shm"]){let sidecar=opts.sourcePath+suffix;if(!_internals124.existsSync(sidecar))continue;try{sourceBytes+=_internals124.statSync(sidecar).size}catch(err){if(suffix==="")return{requiredness:"required",attempt:"failed",validation:"not_applicable",source_disposition:"retained",method:"vacuum_into",reason_code:"snapshot_failed",detail:`source stat failed: ${err instanceof Error?err.message:String(err)}`}}}if(sourceBytes>maxSourceBytes)return{requiredness:"required",attempt:"not_attempted",validation:"not_applicable",source_disposition:"retained",method:"none",reason_code:"source_over_budget",detail:`source bytes ${sourceBytes} > budget ${maxSourceBytes}`};let destFinal=path135.join(opts.destDir,opts.destName),destTemp=path135.join(opts.destDir,`.${opts.destName}.tmp.${_internals124.now()}.${_internals124.randomSuffix()}`),Db;try{Db=resolveDatabaseCtor()}catch(err){return{requiredness:"required",attempt:"failed",validation:"not_applicable",source_disposition:"retained",method:"vacuum_into",reason_code:"snapshot_failed",detail:`driver unavailable: ${err instanceof Error?err.message:String(err)}`}}let snapshotDb=null;try{snapshotDb=new Db(opts.sourcePath);try{snapshotDb.run(`PRAGMA busy_timeout = ${busyTimeoutMs};`),snapshotDb.run(buildVacuumIntoSql(destTemp))}finally{snapshotDb.close(),snapshotDb=null}}catch(err){if(snapshotDb)try{snapshotDb.close()}catch{}return safeRemoveTemp(destTemp),{requiredness:"required",attempt:"failed",validation:"not_applicable",source_disposition:"retained",method:"vacuum_into",reason_code:"snapshot_failed",detail:err instanceof Error?err.message:String(err)}}let rowCounts,verifyDb=null;try{verifyDb=new Db(destTemp),verifyDb.run("PRAGMA query_only = ON;");let integrityRow=verifyDb.query("PRAGMA integrity_check").get(),integrity=rowString(integrityRow,"integrity_check");if(integrity!=="ok")return verifyDb.close(),verifyDb=null,safeRemoveTemp(destTemp),{requiredness:"required",attempt:"failed",validation:"failed",source_disposition:"retained",method:"vacuum_into",reason_code:"validation_failed",detail:`integrity_check: ${integrity||"(empty)"}`};if((rowNumber(verifyDb.query("SELECT COUNT(*) AS c FROM sqlite_master WHERE type='table' AND name='schema_migrations'").get(),"c")??0)<1)return verifyDb.close(),verifyDb=null,safeRemoveTemp(destTemp),{requiredness:"required",attempt:"failed",validation:"failed",source_disposition:"retained",method:"vacuum_into",reason_code:"schema_mismatch",detail:"schema_migrations table absent"};rowCounts=captureRowCounts(verifyDb),verifyDb.close(),verifyDb=null}catch(err){if(verifyDb)try{verifyDb.close()}catch{}return safeRemoveTemp(destTemp),{requiredness:"required",attempt:"failed",validation:"failed",source_disposition:"retained",method:"vacuum_into",reason_code:"validation_failed",detail:err instanceof Error?err.message:String(err)}}try{_internals124.renameSync(destTemp,destFinal)}catch(err){return safeRemoveTemp(destTemp),{requiredness:"required",attempt:"failed",validation:"passed",source_disposition:"retained",method:"vacuum_into",reason_code:"publish_failed",detail:err instanceof Error?err.message:String(err),rowCounts}}return{requiredness:"required",attempt:"succeeded",validation:"passed",source_disposition:"retained",method:"vacuum_into",reason_code:"ok",destPath:destFinal,rowCounts}}var DEFAULT_MAX_SOURCE_BYTES2=2147483648,DEFAULT_BUSY_TIMEOUT_MS=5000,_internals124;var init_archive_sqlite=__esm(()=>{init_sqlite_loader();_internals124={existsSync:fsSync13.existsSync,statSync:fsSync13.statSync,renameSync:fsSync13.renameSync,rmSync:fsSync13.rmSync,now:()=>Date.now(),randomSuffix:()=>Math.random().toString(36).slice(2,8),DatabaseCtor:null}});import{promises as fs86}from"node:fs";import path136 from"node:path";async function copyDirRecursiveWithFailures(src,dest){let count2=0,failures=[],entries=await fs86.readdir(src);await fs86.mkdir(dest,{recursive:!0});for(let entry of entries){let srcEntry=path136.join(src,entry),destEntry=path136.join(dest,entry);try{if((await fs86.stat(srcEntry)).isDirectory()){let subResult=await copyDirRecursiveWithFailures(srcEntry,destEntry);count2+=subResult.copied,failures.push(...subResult.failures)}else try{await fs86.copyFile(srcEntry,destEntry),count2++}catch(err){if(err?.code!=="ENOENT")failures.push(`${srcEntry}: ${err instanceof Error?err.message:String(err)}`)}}catch(err){if(err?.code!=="ENOENT")failures.push(`${srcEntry}: ${err instanceof Error?err.message:String(err)}`)}}return{copied:count2,failures}}async function copyDirRecursive(src,dest){return(await copyDirRecursiveWithFailures(src,dest)).copied}async function unlinkActiveStateFileWithRetry(filePath){for(let attempt=0;;attempt+=1)try{await _internals123.unlink(filePath);return}catch(error93){let code=error93?.code,delay2=ACTIVE_STATE_UNLINK_RETRY_DELAYS_MS[attempt];if(code!=="EBUSY"&&code!=="EPERM"||delay2===void 0)throw error93;_internals123.collectGarbageBestEffort(),await _internals123.sleep(delay2)}}var init_fs_helpers=__esm(()=>{init_constants2();init_internals()});import*as fsSync14 from"node:fs";import{promises as fs87}from"node:fs";import path137 from"node:path";function emitCloseArchiveResult(ctx,cleanResult){let cleaned=new Set(cleanResult.cleanedFiles),failedCount=ctx.archiveResults.filter((r)=>r.attempt==="failed").length,sqliteSnapshots=ctx.archiveResults.filter((r)=>r.method==="vacuum_into"&&r.attempt==="succeeded"),archiveEmpty=sqliteSnapshots.length>0&&sqliteSnapshots.every((r)=>(r.row_counts?.project_constraints??0)===0&&(r.row_counts?.qa_gate_profile??0)===0),archiveValid=!ctx.archiveStageFailed&&failedCount===0;try{telemetry.closeArchiveResult({archive_valid:archiveValid,archive_empty:archiveEmpty,file_count:ctx.archivedFileCount,bundle:`swarm-${ctx.timestamp}-${ctx.archiveSuffix}`,artifacts:ctx.archiveResults.map((r)=>{let removed=cleaned.has(r.artifact);return{artifact:r.artifact,requiredness:r.requiredness,attempt:r.attempt,validation:r.validation,source_disposition:removed?"removed":r.source_disposition,method:r.method,reason_code:r.reason_code,...r.row_counts?{row_counts:r.row_counts}:{}}})})}catch(telemetryErr){log("[close-command] close_archive_result telemetry emit failed:",telemetryErr)}observeCloseArchive({directory:ctx.directory,archiveValid,archiveEmpty,activityPredictsContent:archiveActivityPredictsContent(ctx.directory)})}function archiveActivityPredictsContent(directory){try{for(let name of["knowledge-events.jsonl","telemetry.jsonl","evidence"]){let target=path137.join(directory,".swarm",name),stat13=fsSync14.statSync(target);if(target.endsWith("evidence")){if(fsSync14.readdirSync(target).length>0)return!0}else if(stat13.size>0)return!0}return!1}catch{return!1}}async function runArchiveStage(ctx){ctx.timestamp=new Date().toISOString().replace(/[:.]/g,"-"),ctx.archiveSuffix=Math.random().toString(36).slice(2,8),ctx.archiveDir=path137.join(ctx.swarmDir,"archive",`swarm-${ctx.timestamp}-${ctx.archiveSuffix}`);try{await fs87.mkdir(ctx.archiveDir,{recursive:!0});try{await _internals123.flushAndDrainTelemetry()}catch(flushErr){let msg=flushErr instanceof Error?flushErr.message:String(flushErr);ctx.warnings.push(`Telemetry flush before archive failed: ${msg}`)}try{_internals123.finalizeContextTelemetry(ctx.directory)}catch(finalizeErr){let msg=finalizeErr instanceof Error?finalizeErr.message:String(finalizeErr);ctx.warnings.push(`Context-map telemetry finalize before archive failed: ${msg}`)}try{_internals123.finalizeCoreEvents(ctx.directory)}catch(finalizeErr){let msg=finalizeErr instanceof Error?finalizeErr.message:String(finalizeErr);ctx.warnings.push(`Core events finalize before archive failed: ${msg}`)}try{_internals123.finalizeShellAudit(ctx.directory)}catch(finalizeErr){let msg=finalizeErr instanceof Error?finalizeErr.message:String(finalizeErr);ctx.warnings.push(`Shell audit finalize before archive failed: ${msg}`)}let linkedKnowledgeShared=isLinked(ctx.directory);if(linkedKnowledgeShared)ctx.warnings.push("Worktree is linked: shared knowledge (knowledge.jsonl, knowledge-rejected.jsonl) lives in the link store and is not archived or cleaned by /swarm close. Manage it via the link.");for(let artifact of ARCHIVE_ARTIFACTS){if(linkedKnowledgeShared&&KNOWLEDGE_FAMILY_ARTIFACTS.has(artifact))continue;let srcPath=path137.join(ctx.swarmDir,artifact),destPath=path137.join(ctx.archiveDir,artifact),requiredness=REQUIRED_ARTIFACTS.has(artifact)?"required":"optional";if(artifact==="swarm.db"||artifact===REPO_MEMORY_FILENAME){let r=await archiveSqliteSnapshot({sourcePath:srcPath,destDir:ctx.archiveDir,destName:artifact}),result={artifact,requiredness,attempt:r.attempt,validation:r.validation,source_disposition:r.attempt==="succeeded"?"retained":r.source_disposition,method:r.method,reason_code:r.reason_code,detail:r.detail,row_counts:r.rowCounts};if(ctx.archiveResults.push(result),r.attempt==="succeeded"&&r.validation==="passed"){if(ctx.archivedFileCount++,ACTIVE_STATE_TO_CLEAN.includes(artifact))ctx.archivedActiveStateFiles.add(artifact)}else if(!(r.attempt==="not_attempted"&&r.source_disposition==="absent"))ctx.archiveFailureReasons.set(artifact,`${r.reason_code}: ${r.detail??""}`),ctx.warnings.push(`Failed to archive ${artifact} [${r.reason_code}]: ${r.detail??""}. Source preserved.`)}else try{if(await fs87.copyFile(srcPath,destPath),ctx.archivedFileCount++,ACTIVE_STATE_TO_CLEAN.includes(artifact))ctx.archivedActiveStateFiles.add(artifact);ctx.archiveResults.push({artifact,requiredness,attempt:"succeeded",validation:"not_applicable",source_disposition:"retained",method:"copy",reason_code:"ok"})}catch(err){let errno=err?.code;if(errno==="ENOENT")ctx.archiveResults.push({artifact,requiredness,attempt:"not_attempted",validation:"not_applicable",source_disposition:"absent",method:"none",reason_code:"source_absent"});else{let reason=err instanceof Error?err.message:String(err);ctx.archiveFailureReasons.set(artifact,`${errno??"unknown"}: ${reason}`),ctx.warnings.push(`Failed to archive ${artifact} [${errno??"unknown"}]: ${reason}. File preserved (not cleaned up).`),ctx.archiveResults.push({artifact,requiredness,attempt:"failed",validation:"not_applicable",source_disposition:"retained",method:"copy",reason_code:"copy_failed",detail:`${errno??"unknown"}: ${reason}`})}}}let dynamicArchiveArtifacts=(await fs87.readdir(ctx.swarmDir).catch(()=>[])).filter((name)=>/^post-mortem-[^/\\]+\.md$/.test(name)||/^drift-report-phase-\d+\.json$/.test(name));for(let artifact of dynamicArchiveArtifacts){let srcPath=path137.join(ctx.swarmDir,artifact),destPath=path137.join(ctx.archiveDir,artifact);try{await fs87.copyFile(srcPath,destPath),ctx.archivedFileCount++,ctx.archivedActiveStateFiles.add(artifact),ctx.archiveResults.push({artifact,requiredness:"optional",attempt:"succeeded",validation:"not_applicable",source_disposition:"retained",method:"copy",reason_code:"ok"})}catch(err){let errno=err?.code;if(errno!=="ENOENT"){let reason=err instanceof Error?err.message:String(err);ctx.archiveFailureReasons.set(artifact,`${errno??"unknown"}: ${reason}`),ctx.warnings.push(`Failed to archive ${artifact} [${errno??"unknown"}]: ${reason}. File preserved (not cleaned up).`),ctx.archiveResults.push({artifact,requiredness:"optional",attempt:"failed",validation:"not_applicable",source_disposition:"retained",method:"copy",reason_code:"copy_failed",detail:`${errno??"unknown"}: ${reason}`})}else ctx.archiveResults.push({artifact,requiredness:"optional",attempt:"not_attempted",validation:"not_applicable",source_disposition:"absent",method:"none",reason_code:"source_absent"})}}for(let dirName of ACTIVE_STATE_DIRS_TO_CLEAN){let srcDir=path137.join(ctx.swarmDir,dirName),destDir=path137.join(ctx.archiveDir,dirName);try{let result=await copyDirRecursiveWithFailures(srcDir,destDir);if(ctx.archivedFileCount+=result.copied,result.failures.length===0)ctx.archivedActiveStateDirs.add(dirName);else{ctx.warnings.push(`Directory ${dirName} not fully archived (${result.failures.length} failure(s)). Source preserved.`);for(let failure of result.failures)ctx.warnings.push(` - ${failure}`)}}catch(err){let code=err.code;if(code!=="ENOENT")ctx.warnings.push(`Failed to archive directory ${dirName} [${code??"unknown"}]: ${err.message}. Source preserved.`)}}let succeededCount=ctx.archiveResults.filter((r)=>r.attempt==="succeeded").length,failedCount=ctx.archiveResults.filter((r)=>r.attempt==="failed").length,absentCount=ctx.archiveResults.filter((r)=>r.source_disposition==="absent").length,bundleName=`swarm-${ctx.timestamp}-${ctx.archiveSuffix}`;ctx.archiveResult=failedCount>0?`Archive partial: ${succeededCount} succeeded, ${failedCount} failed, ${absentCount} absent (see warnings). Bundle: .swarm/archive/${bundleName}/`:`Archived ${ctx.archivedFileCount} artifact(s) to .swarm/archive/${bundleName}/`}catch(archiveError){ctx.warnings.push(`Archive creation failed: ${archiveError instanceof Error?archiveError.message:String(archiveError)}`),ctx.archiveResult="Archive creation failed (see warnings)",ctx.archiveStageFailed=!0}await runArchiveEvidenceRetention({directory:ctx.directory,swarmDir:ctx.swarmDir,config:ctx.config,warnings:ctx.warnings})}async function runArchiveEvidenceRetention(ctx){let maxAgeDays=30,maxBundles=10,cacheMaxBytes,cacheMaxRecords;try{let{config:evidenceLoadedConfig}=_internals123.loadPluginConfigWithMeta(ctx.directory),evidenceCfg=evidenceLoadedConfig.evidence??{};if(typeof evidenceCfg.max_age_days==="number")maxAgeDays=evidenceCfg.max_age_days;if(typeof evidenceCfg.max_bundles==="number")maxBundles=evidenceCfg.max_bundles;if(typeof evidenceCfg.cache_max_bytes==="number")cacheMaxBytes=evidenceCfg.cache_max_bytes;if(typeof evidenceCfg.cache_max_records==="number")cacheMaxRecords=evidenceCfg.cache_max_records}catch{}try{await _internals123.archiveEvidence(ctx.directory,maxAgeDays,maxBundles,{report:!0,cacheMaxBytes,cacheMaxRecords})}catch(error93){let msg=error93 instanceof Error?error93.message:String(error93);ctx.warnings.push(`Evidence retention archive failed: ${msg}`),log("[close-command] archiveEvidence error:",error93)}}var init_archive_stage=__esm(()=>{init_learning_health();init_knowledge_link();init_telemetry();init_indexed_storage();init_logger();init_archive_sqlite();init_constants2();init_fs_helpers();init_internals()});import{createHash as createHash64}from"node:crypto";import*as fs88 from"node:fs";import*as path138 from"node:path";function collectCandidates(swarmRoot){let items=[],scannedEntries=0,truncated=!1,walk=(relDir,depth)=>{if(truncated)return;let absDir=relDir===""?swarmRoot:path138.join(swarmRoot,...relDir.split("/")),dirents;try{dirents=fs88.readdirSync(absDir,{withFileTypes:!0})}catch{return}for(let dirent of dirents){if(++scannedEntries>MAX_RESIDUE_SCAN_ENTRIES){truncated=!0;return}if(relDir===""&&RESIDUE_SKIP_DIRS.includes(dirent.name))continue;let rel=relDir===""?dirent.name:`${relDir}/${dirent.name}`;if(dirent.isDirectory()&&!dirent.isSymbolicLink()){if(depth+1<=RESIDUE_SCAN_DEPTH)walk(rel,depth+1);continue}let grammar=matchTempGrammar(dirent.name);if(!grammar)continue;let bytes=0,mtimeMs=0;if(!dirent.isSymbolicLink())try{let st=fs88.lstatSync(path138.join(swarmRoot,...rel.split("/")));if(!st.isFile())continue;bytes=st.size,mtimeMs=st.mtimeMs}catch{continue}items.push({relPath:rel,grammar,isSymlink:dirent.isSymbolicLink(),bytes,mtimeMs})}};return walk("",0),{items,scannedEntries,truncated}}async function inventorySwarmResidue(directory){let swarmRoot=path138.normalize(path138.resolve(directory,".swarm"));if(!fs88.existsSync(swarmRoot))return{swarmRoot,scannedEntries:0,truncated:!1,entries:[],summary:{matched:0,eligible:0,ambiguous:0,totalBytes:0,oldestAgeMs:0},gitState:"unknown"};if(fs88.lstatSync(swarmRoot).isSymbolicLink())throw Error(`Refusing to scan a symlinked .swarm root: ${swarmRoot}`);let projectRoot=path138.dirname(swarmRoot),{tracked}=_internals125.queryTracked(projectRoot,swarmRoot),lockTargets=_internals125.activeLockTargets(directory),{items,scannedEntries,truncated}=collectCandidates(swarmRoot),now2=_internals125.now(),entries=[];for(let item of items){let ageMs=Math.max(0,now2-item.mtimeMs);if(item.grammar.token==="constant"&&item.grammar.id!=="dot-tmp-prefix-legacy"){if(ageMs<RESIDUE_STALE_AGE_MS)continue}let abs=path138.normalize(path138.join(swarmRoot,...item.relPath.split("/"))),reasons=[];if(!item.grammar.quarantineEligible)reasons.push("constant-name-grammar");if(ageMs<RESIDUE_STALE_AGE_MS)reasons.push("recent");let trackedState;if(tracked===void 0){if(trackedState="unknown",item.grammar.quarantineEligible)reasons.push("tracked-state-unknown")}else if(trackedState=tracked.has(abs)?"tracked":"untracked",trackedState==="tracked")reasons.push("git-tracked");if(item.isSymlink)reasons.push("symlink");let lockHeld=lockTargets.has(abs)||(item.grammar.parsesTarget?lockTargets.has(path138.normalize(path138.join(path138.dirname(abs),parseTargetBasename(item.relPath.split("/").pop()??"")??""))):!1);if(lockHeld)reasons.push("active-lock");if(item.bytes>RESIDUE_HASH_MAX_BYTES)reasons.push("oversize");if(item.grammar.quarantineEligible&&item.grammar.parsesTarget){let targetBasename=parseTargetBasename(item.relPath.split("/").pop()??"");if(targetBasename){let targetAbs=path138.join(path138.dirname(abs),targetBasename),targetOk=!1;try{targetOk=fs88.lstatSync(targetAbs).isFile()}catch{targetOk=!1}if(!targetOk)reasons.push("target-absent")}}entries.push({relPath:item.relPath,grammarId:item.grammar.id,grammarEra:item.grammar.era,bytes:item.bytes,mtimeMs:item.mtimeMs,ageMs,isSymlink:item.isSymlink,tracked:trackedState,lockHeld,proposedAction:item.grammar.quarantineEligible&&reasons.length===0?"quarantine":"report_only",reasons})}entries.sort((a,b)=>b.ageMs-a.ageMs);let eligible=entries.filter((e)=>e.proposedAction==="quarantine");return{swarmRoot,scannedEntries,truncated,entries,summary:{matched:entries.length,eligible:eligible.length,ambiguous:entries.length-eligible.length,totalBytes:entries.reduce((sum,e)=>sum+e.bytes,0),oldestAgeMs:entries[0]?.ageMs??0},gitState:tracked===void 0?"unknown":"ok"}}function validateRelPath(rel,what){if(!rel||path138.isAbsolute(rel)||rel.split("/").some((s)=>s===".."||s===""||/[\0-\x1f]/.test(s)))throw Error(`unsafe ${what} in quarantine manifest: ${JSON.stringify(rel)}`);return rel}function sha256Bounded(absPath){try{return _internals125.sha256File(absPath)}catch{return}}async function quarantineSwarmResidue(directory,options){let inventory=await inventorySwarmResidue(directory),eligible=inventory.entries.filter((e)=>e.proposedAction==="quarantine"),preserved=inventory.entries.filter((e)=>e.proposedAction==="report_only").map((e)=>({relPath:e.relPath,status:"preserved",reasons:e.reasons}));if(options?.dryRun||eligible.length===0)return{inventory,quarantined:0,preserved};let swarmRoot=inventory.swarmRoot,batchId=`${new Date().toISOString().replace(/[:.]/g,"-")}-${Math.random().toString(36).slice(2,10)}`,batchAbs=path138.join(swarmRoot,"quarantine",batchId);fs88.mkdirSync(batchAbs,{recursive:!0});let manifest={schema_version:1,batch_id:batchId,created_at:new Date().toISOString(),trigger:options?.trigger??"manual",entries:[]},moved=[];for(let entry of eligible){let abs=path138.join(swarmRoot,...entry.relPath.split("/"));try{let st=fs88.lstatSync(abs);if(!st.isFile()||st.size!==entry.bytes||st.mtimeMs!==entry.mtimeMs){preserved.push({relPath:entry.relPath,status:"preserved",reasons:["changed-since-scan"]});continue}}catch{preserved.push({relPath:entry.relPath,status:"preserved",reasons:["vanished"]});continue}let sha=sha256Bounded(abs);if(!sha){preserved.push({relPath:entry.relPath,status:"preserved",reasons:["hash-failed"]});continue}let storedAbs=path138.join(batchAbs,...entry.relPath.split("/"));try{fs88.mkdirSync(path138.dirname(storedAbs),{recursive:!0}),_internals125.renameResidueEntry(abs,storedAbs)}catch(moveErr){let code=moveErr?.code??"unknown";preserved.push({relPath:entry.relPath,status:"preserved",reasons:[`move-failed:${code}`]});continue}manifest.entries.push({original_rel_path:entry.relPath,stored_rel_path:path138.posix.join("quarantine",batchId,entry.relPath),sha256:sha,bytes:entry.bytes,mtime_ms:entry.mtimeMs,grammar_id:entry.grammarId,reason:"stale-atomic-write-temp"}),moved.push({relPath:entry.relPath,status:"quarantined",reasons:[]})}let batchRelDir;if(manifest.entries.length>0)atomicWriteSwarmFileSync(path138.join(batchAbs,"manifest.json"),`${JSON.stringify(manifest,null,2)}
|
|
1413
|
+
`)}async function guardResetWithRecheck(real,cwd,options){let recheck=await recheckBeforeDestructive(cwd,options?.expectedDirtyPaths??[]);if(recheck.ok)return real(cwd,{pruneBranches:options?.pruneBranches});return log(`[close-align] re-check refused destructive reset: ${recheck.reason} (${recheck.newDirtyPaths.length} newly-dirty path(s))`),{success:!1,targetBranch:"",previousBranch:"",message:renderRecheckRefusal(recheck.reason,recheck.newDirtyPaths),branchDeleted:!1,changesDiscarded:!1,warnings:[],recheckRefused:!0}}async function runAlignStage(ctx){let pruneBranches=ctx.args.includes("--prune-branches"),gitAlignResult="",prunedBranches=[],gitStatus=await _internals123.getGitRepositoryStatus(ctx.directory);if(gitStatus.isRepo){let aggressiveResult=await _internals123.resetToMainAfterMerge(ctx.directory,{pruneBranches,expectedDirtyPaths:ctx.purgeGateDirtyPaths??[]});if(aggressiveResult.recheckRefused)return gitAlignResult=aggressiveResult.message,ctx.warnings.push(aggressiveResult.message),{gitAlignResult,prunedBranches};if(aggressiveResult.success){gitAlignResult=aggressiveResult.message;for(let w of aggressiveResult.warnings)ctx.warnings.push(w);if(aggressiveResult.changesDiscarded)ctx.warnings.push("Uncommitted changes were discarded during git alignment")}else{let alignResult=await _internals123.resetToRemoteBranch(ctx.directory,{pruneBranches});if(gitAlignResult=alignResult.message,prunedBranches.push(...alignResult.prunedBranches),!alignResult.success)ctx.warnings.push(`Git alignment: ${alignResult.message}`);if(alignResult.alreadyAligned)gitAlignResult=`Already aligned with ${alignResult.targetBranch}`;for(let w of alignResult.warnings)ctx.warnings.push(w)}}else if(gitStatus.reason==="git_unavailable")gitAlignResult=`Git executable unavailable — skipped git alignment: ${gitStatus.message}`,ctx.warnings.push(gitAlignResult);else if(gitStatus.reason==="git_error")gitAlignResult=`Git repository check failed — skipped git alignment: ${gitStatus.message}`,ctx.warnings.push(gitAlignResult);else gitAlignResult="Not a git repository — skipped git alignment";return{gitAlignResult,prunedBranches}}var init_align_stage=__esm(()=>{init_logger();init_destructive_purge();init_internals()});import*as fsSync13 from"node:fs";import path135 from"node:path";function resolveDatabaseCtor(){return _internals124.DatabaseCtor??loadDatabaseCtor()}function safeRemoveTemp(tempPath){try{_internals124.rmSync(tempPath,{force:!0,recursive:!0,maxRetries:3,retryDelay:100})}catch{}}function buildVacuumIntoSql(destPath){return`VACUUM INTO '${destPath.replace(/\\/g,"/").replace(/'/g,"''")}'`}function rowString(row,col){if(row&&typeof row==="object"&&col in row){let v=row[col];return v===null||v===void 0?"":String(v)}return""}function rowNumber(row,col){if(row&&typeof row==="object"&&col in row){let v=row[col];if(typeof v==="number"&&Number.isFinite(v))return v;if(typeof v==="bigint")return Number(v);if(typeof v==="string"){let n=Number(v);if(Number.isFinite(n))return n}}return null}function captureRowCounts(db){let tableExists=(name)=>{let row=db.query("SELECT COUNT(*) AS c FROM sqlite_master WHERE type='table' AND name=?").get(name);return rowNumber(row,"c")!==null&&(rowNumber(row,"c")??0)>0},schemaMigrationsMax=null;if(tableExists("schema_migrations")){let row=db.query("SELECT MAX(version) AS m FROM schema_migrations").get();schemaMigrationsMax=rowNumber(row,"m")}let projectConstraints=tableExists("project_constraints")?rowNumber(db.query("SELECT COUNT(*) AS c FROM project_constraints").get(),"c")??0:0,qaGateProfile=tableExists("qa_gate_profile")?rowNumber(db.query("SELECT COUNT(*) AS c FROM qa_gate_profile").get(),"c")??0:0;return{schema_migrations_max_version:schemaMigrationsMax,project_constraints:projectConstraints,qa_gate_profile:qaGateProfile}}async function archiveSqliteSnapshot(opts){let maxSourceBytes=opts.maxSourceBytes??DEFAULT_MAX_SOURCE_BYTES2,busyTimeoutMs=opts.busyTimeoutMs??DEFAULT_BUSY_TIMEOUT_MS;if(!_internals124.existsSync(opts.sourcePath))return{requiredness:"required",attempt:"not_attempted",validation:"not_applicable",source_disposition:"absent",method:"none",reason_code:"source_absent"};let sourceBytes=0;for(let suffix of["","-wal","-shm"]){let sidecar=opts.sourcePath+suffix;if(!_internals124.existsSync(sidecar))continue;try{sourceBytes+=_internals124.statSync(sidecar).size}catch(err){if(suffix==="")return{requiredness:"required",attempt:"failed",validation:"not_applicable",source_disposition:"retained",method:"vacuum_into",reason_code:"snapshot_failed",detail:`source stat failed: ${err instanceof Error?err.message:String(err)}`}}}if(sourceBytes>maxSourceBytes)return{requiredness:"required",attempt:"not_attempted",validation:"not_applicable",source_disposition:"retained",method:"none",reason_code:"source_over_budget",detail:`source bytes ${sourceBytes} > budget ${maxSourceBytes}`};let destFinal=path135.join(opts.destDir,opts.destName),destTemp=path135.join(opts.destDir,`.${opts.destName}.tmp.${_internals124.now()}.${_internals124.randomSuffix()}`),Db;try{Db=resolveDatabaseCtor()}catch(err){return{requiredness:"required",attempt:"failed",validation:"not_applicable",source_disposition:"retained",method:"vacuum_into",reason_code:"snapshot_failed",detail:`driver unavailable: ${err instanceof Error?err.message:String(err)}`}}let snapshotDb=null;try{snapshotDb=new Db(opts.sourcePath);try{snapshotDb.run(`PRAGMA busy_timeout = ${busyTimeoutMs};`),snapshotDb.run(buildVacuumIntoSql(destTemp))}finally{snapshotDb.close(),snapshotDb=null}}catch(err){if(snapshotDb)try{snapshotDb.close()}catch{}return safeRemoveTemp(destTemp),{requiredness:"required",attempt:"failed",validation:"not_applicable",source_disposition:"retained",method:"vacuum_into",reason_code:"snapshot_failed",detail:err instanceof Error?err.message:String(err)}}let rowCounts,verifyDb=null;try{verifyDb=new Db(destTemp),verifyDb.run("PRAGMA query_only = ON;");let integrityRow=verifyDb.query("PRAGMA integrity_check").get(),integrity=rowString(integrityRow,"integrity_check");if(integrity!=="ok")return verifyDb.close(),verifyDb=null,safeRemoveTemp(destTemp),{requiredness:"required",attempt:"failed",validation:"failed",source_disposition:"retained",method:"vacuum_into",reason_code:"validation_failed",detail:`integrity_check: ${integrity||"(empty)"}`};if((rowNumber(verifyDb.query("SELECT COUNT(*) AS c FROM sqlite_master WHERE type='table' AND name='schema_migrations'").get(),"c")??0)<1)return verifyDb.close(),verifyDb=null,safeRemoveTemp(destTemp),{requiredness:"required",attempt:"failed",validation:"failed",source_disposition:"retained",method:"vacuum_into",reason_code:"schema_mismatch",detail:"schema_migrations table absent"};rowCounts=captureRowCounts(verifyDb),verifyDb.close(),verifyDb=null}catch(err){if(verifyDb)try{verifyDb.close()}catch{}return safeRemoveTemp(destTemp),{requiredness:"required",attempt:"failed",validation:"failed",source_disposition:"retained",method:"vacuum_into",reason_code:"validation_failed",detail:err instanceof Error?err.message:String(err)}}try{_internals124.renameSync(destTemp,destFinal)}catch(err){return safeRemoveTemp(destTemp),{requiredness:"required",attempt:"failed",validation:"passed",source_disposition:"retained",method:"vacuum_into",reason_code:"publish_failed",detail:err instanceof Error?err.message:String(err),rowCounts}}return{requiredness:"required",attempt:"succeeded",validation:"passed",source_disposition:"retained",method:"vacuum_into",reason_code:"ok",destPath:destFinal,rowCounts}}var DEFAULT_MAX_SOURCE_BYTES2=2147483648,DEFAULT_BUSY_TIMEOUT_MS=5000,_internals124;var init_archive_sqlite=__esm(()=>{init_sqlite_loader();_internals124={existsSync:fsSync13.existsSync,statSync:fsSync13.statSync,renameSync:fsSync13.renameSync,rmSync:fsSync13.rmSync,now:()=>Date.now(),randomSuffix:()=>Math.random().toString(36).slice(2,8),DatabaseCtor:null}});import{promises as fs86}from"node:fs";import path136 from"node:path";async function copyDirRecursiveWithFailures(src,dest){let count2=0,failures=[],entries=await fs86.readdir(src);await fs86.mkdir(dest,{recursive:!0});for(let entry of entries){let srcEntry=path136.join(src,entry),destEntry=path136.join(dest,entry);try{if((await fs86.stat(srcEntry)).isDirectory()){let subResult=await copyDirRecursiveWithFailures(srcEntry,destEntry);count2+=subResult.copied,failures.push(...subResult.failures)}else try{await fs86.copyFile(srcEntry,destEntry),count2++}catch(err){if(err?.code!=="ENOENT")failures.push(`${srcEntry}: ${err instanceof Error?err.message:String(err)}`)}}catch(err){if(err?.code!=="ENOENT")failures.push(`${srcEntry}: ${err instanceof Error?err.message:String(err)}`)}}return{copied:count2,failures}}async function copyDirRecursive(src,dest){return(await copyDirRecursiveWithFailures(src,dest)).copied}async function unlinkActiveStateFileWithRetry(filePath){for(let attempt=0;;attempt+=1)try{await _internals123.unlink(filePath);return}catch(error93){let code=error93?.code,delay2=ACTIVE_STATE_UNLINK_RETRY_DELAYS_MS[attempt];if(code!=="EBUSY"&&code!=="EPERM"||delay2===void 0)throw error93;_internals123.collectGarbageBestEffort(),await _internals123.sleep(delay2)}}var init_fs_helpers=__esm(()=>{init_constants2();init_internals()});import*as fsSync14 from"node:fs";import{promises as fs87}from"node:fs";import path137 from"node:path";function emitCloseArchiveResult(ctx,cleanResult){let cleaned=new Set(cleanResult.cleanedFiles),failedCount=ctx.archiveResults.filter((r)=>r.attempt==="failed").length,sqliteSnapshots=ctx.archiveResults.filter((r)=>r.method==="vacuum_into"&&r.attempt==="succeeded"),archiveEmpty=sqliteSnapshots.length>0&&sqliteSnapshots.every((r)=>(r.row_counts?.project_constraints??0)===0&&(r.row_counts?.qa_gate_profile??0)===0),archiveValid=!ctx.archiveStageFailed&&failedCount===0;try{telemetry.closeArchiveResult({archive_valid:archiveValid,archive_empty:archiveEmpty,file_count:ctx.archivedFileCount,bundle:`swarm-${ctx.timestamp}-${ctx.archiveSuffix}`,artifacts:ctx.archiveResults.map((r)=>{let removed=cleaned.has(r.artifact);return{artifact:r.artifact,requiredness:r.requiredness,attempt:r.attempt,validation:r.validation,source_disposition:removed?"removed":r.source_disposition,method:r.method,reason_code:r.reason_code,...r.row_counts?{row_counts:r.row_counts}:{}}})})}catch(telemetryErr){log("[close-command] close_archive_result telemetry emit failed:",telemetryErr)}observeCloseArchive({directory:ctx.directory,archiveValid,archiveEmpty,activityPredictsContent:archiveActivityPredictsContent(ctx.directory)})}function archiveActivityPredictsContent(directory){try{for(let name of["knowledge-events.jsonl","telemetry.jsonl","evidence"]){let target=path137.join(directory,".swarm",name),stat13=fsSync14.statSync(target);if(target.endsWith("evidence")){if(fsSync14.readdirSync(target).length>0)return!0}else if(stat13.size>0)return!0}return!1}catch{return!1}}async function runArchiveStage(ctx){ctx.timestamp=new Date().toISOString().replace(/[:.]/g,"-"),ctx.archiveSuffix=Math.random().toString(36).slice(2,8),ctx.archiveDir=path137.join(ctx.swarmDir,"archive",`swarm-${ctx.timestamp}-${ctx.archiveSuffix}`);try{await fs87.mkdir(ctx.archiveDir,{recursive:!0});try{await _internals123.flushAndDrainTelemetry()}catch(flushErr){let msg=flushErr instanceof Error?flushErr.message:String(flushErr);ctx.warnings.push(`Telemetry flush before archive failed: ${msg}`)}try{_internals123.finalizeContextTelemetry(ctx.directory)}catch(finalizeErr){let msg=finalizeErr instanceof Error?finalizeErr.message:String(finalizeErr);ctx.warnings.push(`Context-map telemetry finalize before archive failed: ${msg}`)}try{_internals123.finalizeCoreEvents(ctx.directory)}catch(finalizeErr){let msg=finalizeErr instanceof Error?finalizeErr.message:String(finalizeErr);ctx.warnings.push(`Core events finalize before archive failed: ${msg}`)}try{_internals123.finalizeShellAudit(ctx.directory)}catch(finalizeErr){let msg=finalizeErr instanceof Error?finalizeErr.message:String(finalizeErr);ctx.warnings.push(`Shell audit finalize before archive failed: ${msg}`)}let linkedKnowledgeShared=isLinked(ctx.directory);if(linkedKnowledgeShared)ctx.warnings.push("Worktree is linked: shared knowledge (knowledge.jsonl, knowledge-rejected.jsonl) lives in the link store and is not archived or cleaned by /swarm close. Manage it via the link.");for(let artifact of ARCHIVE_ARTIFACTS){if(linkedKnowledgeShared&&KNOWLEDGE_FAMILY_ARTIFACTS.has(artifact))continue;let srcPath=path137.join(ctx.swarmDir,artifact),destPath=path137.join(ctx.archiveDir,artifact),requiredness=REQUIRED_ARTIFACTS.has(artifact)?"required":"optional";if(artifact==="swarm.db"||artifact===REPO_MEMORY_FILENAME){let r=await archiveSqliteSnapshot({sourcePath:srcPath,destDir:ctx.archiveDir,destName:artifact}),result={artifact,requiredness,attempt:r.attempt,validation:r.validation,source_disposition:r.attempt==="succeeded"?"retained":r.source_disposition,method:r.method,reason_code:r.reason_code,detail:r.detail,row_counts:r.rowCounts};if(ctx.archiveResults.push(result),r.attempt==="succeeded"&&r.validation==="passed"){if(ctx.archivedFileCount++,ACTIVE_STATE_TO_CLEAN.includes(artifact))ctx.archivedActiveStateFiles.add(artifact)}else if(!(r.attempt==="not_attempted"&&r.source_disposition==="absent"))ctx.archiveFailureReasons.set(artifact,`${r.reason_code}: ${r.detail??""}`),ctx.warnings.push(`Failed to archive ${artifact} [${r.reason_code}]: ${r.detail??""}. Source preserved.`)}else try{if(await fs87.copyFile(srcPath,destPath),ctx.archivedFileCount++,ACTIVE_STATE_TO_CLEAN.includes(artifact))ctx.archivedActiveStateFiles.add(artifact);ctx.archiveResults.push({artifact,requiredness,attempt:"succeeded",validation:"not_applicable",source_disposition:"retained",method:"copy",reason_code:"ok"})}catch(err){let errno=err?.code;if(errno==="ENOENT")ctx.archiveResults.push({artifact,requiredness,attempt:"not_attempted",validation:"not_applicable",source_disposition:"absent",method:"none",reason_code:"source_absent"});else{let reason=err instanceof Error?err.message:String(err);ctx.archiveFailureReasons.set(artifact,`${errno??"unknown"}: ${reason}`),ctx.warnings.push(`Failed to archive ${artifact} [${errno??"unknown"}]: ${reason}. File preserved (not cleaned up).`),ctx.archiveResults.push({artifact,requiredness,attempt:"failed",validation:"not_applicable",source_disposition:"retained",method:"copy",reason_code:"copy_failed",detail:`${errno??"unknown"}: ${reason}`})}}}let dynamicArchiveArtifacts=(await fs87.readdir(ctx.swarmDir).catch(()=>[])).filter((name)=>/^post-mortem-[^/\\]+\.md$/.test(name)||/^drift-report-phase-\d+\.json$/.test(name));for(let artifact of dynamicArchiveArtifacts){let srcPath=path137.join(ctx.swarmDir,artifact),destPath=path137.join(ctx.archiveDir,artifact);try{await fs87.copyFile(srcPath,destPath),ctx.archivedFileCount++,ctx.archivedActiveStateFiles.add(artifact),ctx.archiveResults.push({artifact,requiredness:"optional",attempt:"succeeded",validation:"not_applicable",source_disposition:"retained",method:"copy",reason_code:"ok"})}catch(err){let errno=err?.code;if(errno!=="ENOENT"){let reason=err instanceof Error?err.message:String(err);ctx.archiveFailureReasons.set(artifact,`${errno??"unknown"}: ${reason}`),ctx.warnings.push(`Failed to archive ${artifact} [${errno??"unknown"}]: ${reason}. File preserved (not cleaned up).`),ctx.archiveResults.push({artifact,requiredness:"optional",attempt:"failed",validation:"not_applicable",source_disposition:"retained",method:"copy",reason_code:"copy_failed",detail:`${errno??"unknown"}: ${reason}`})}else ctx.archiveResults.push({artifact,requiredness:"optional",attempt:"not_attempted",validation:"not_applicable",source_disposition:"absent",method:"none",reason_code:"source_absent"})}}for(let dirName of ACTIVE_STATE_DIRS_TO_CLEAN){let srcDir=path137.join(ctx.swarmDir,dirName),destDir=path137.join(ctx.archiveDir,dirName);try{let result=await copyDirRecursiveWithFailures(srcDir,destDir);if(ctx.archivedFileCount+=result.copied,result.failures.length===0)ctx.archivedActiveStateDirs.add(dirName);else{ctx.warnings.push(`Directory ${dirName} not fully archived (${result.failures.length} failure(s)). Source preserved.`);for(let failure of result.failures)ctx.warnings.push(` - ${failure}`)}}catch(err){let code=err.code;if(code!=="ENOENT")ctx.warnings.push(`Failed to archive directory ${dirName} [${code??"unknown"}]: ${err.message}. Source preserved.`)}}let succeededCount=ctx.archiveResults.filter((r)=>r.attempt==="succeeded").length,failedCount=ctx.archiveResults.filter((r)=>r.attempt==="failed").length,absentCount=ctx.archiveResults.filter((r)=>r.source_disposition==="absent").length,bundleName=`swarm-${ctx.timestamp}-${ctx.archiveSuffix}`;ctx.archiveResult=failedCount>0?`Archive partial: ${succeededCount} succeeded, ${failedCount} failed, ${absentCount} absent (see warnings). Bundle: .swarm/archive/${bundleName}/`:`Archived ${ctx.archivedFileCount} artifact(s) to .swarm/archive/${bundleName}/`}catch(archiveError){ctx.warnings.push(`Archive creation failed: ${archiveError instanceof Error?archiveError.message:String(archiveError)}`),ctx.archiveResult="Archive creation failed (see warnings)",ctx.archiveStageFailed=!0}await runArchiveEvidenceRetention({directory:ctx.directory,swarmDir:ctx.swarmDir,config:ctx.config,warnings:ctx.warnings})}async function runArchiveEvidenceRetention(ctx){let maxAgeDays=30,maxBundles=10,cacheMaxBytes,cacheMaxRecords;try{let{config:evidenceLoadedConfig}=_internals123.loadPluginConfigWithMeta(ctx.directory),evidenceCfg=evidenceLoadedConfig.evidence??{};if(typeof evidenceCfg.max_age_days==="number")maxAgeDays=evidenceCfg.max_age_days;if(typeof evidenceCfg.max_bundles==="number")maxBundles=evidenceCfg.max_bundles;if(typeof evidenceCfg.cache_max_bytes==="number")cacheMaxBytes=evidenceCfg.cache_max_bytes;if(typeof evidenceCfg.cache_max_records==="number")cacheMaxRecords=evidenceCfg.cache_max_records}catch{}try{await _internals123.archiveEvidence(ctx.directory,maxAgeDays,maxBundles,{report:!0,cacheMaxBytes,cacheMaxRecords})}catch(error93){let msg=error93 instanceof Error?error93.message:String(error93);ctx.warnings.push(`Evidence retention archive failed: ${msg}`),log("[close-command] archiveEvidence error:",error93)}}var init_archive_stage=__esm(()=>{init_learning_health();init_knowledge_link();init_telemetry();init_indexed_storage();init_logger();init_archive_sqlite();init_constants2();init_fs_helpers();init_internals()});import{createHash as createHash64}from"node:crypto";import*as fs88 from"node:fs";import*as path138 from"node:path";function collectCandidates(swarmRoot){let items=[],scannedEntries=0,truncated=!1,walk=(relDir,depth)=>{if(truncated)return;let absDir=relDir===""?swarmRoot:path138.join(swarmRoot,...relDir.split("/")),dirents;try{dirents=fs88.readdirSync(absDir,{withFileTypes:!0})}catch{return}for(let dirent of dirents){if(++scannedEntries>MAX_RESIDUE_SCAN_ENTRIES){truncated=!0;return}if(relDir===""&&RESIDUE_SKIP_DIRS.includes(dirent.name))continue;let rel=relDir===""?dirent.name:`${relDir}/${dirent.name}`;if(dirent.isDirectory()&&!dirent.isSymbolicLink()){if(depth+1<=RESIDUE_SCAN_DEPTH)walk(rel,depth+1);continue}let grammar=matchTempGrammar(dirent.name);if(!grammar)continue;let bytes=0,mtimeMs=0;if(!dirent.isSymbolicLink())try{let st=fs88.lstatSync(path138.join(swarmRoot,...rel.split("/")));if(!st.isFile())continue;bytes=st.size,mtimeMs=st.mtimeMs}catch{continue}items.push({relPath:rel,grammar,isSymlink:dirent.isSymbolicLink(),bytes,mtimeMs})}};return walk("",0),{items,scannedEntries,truncated}}async function inventorySwarmResidue(directory){let swarmRoot=path138.normalize(path138.resolve(directory,".swarm"));if(!fs88.existsSync(swarmRoot))return{swarmRoot,scannedEntries:0,truncated:!1,entries:[],summary:{matched:0,eligible:0,ambiguous:0,totalBytes:0,oldestAgeMs:0},gitState:"unknown"};if(fs88.lstatSync(swarmRoot).isSymbolicLink())throw Error(`Refusing to scan a symlinked .swarm root: ${swarmRoot}`);let projectRoot=path138.dirname(swarmRoot),{tracked}=_internals125.queryTracked(projectRoot,swarmRoot),lockTargets=_internals125.activeLockTargets(directory),{items,scannedEntries,truncated}=collectCandidates(swarmRoot),now2=_internals125.now(),entries=[];for(let item of items){let ageMs=Math.max(0,now2-item.mtimeMs);if(item.grammar.token==="constant"&&item.grammar.id!=="dot-tmp-prefix-legacy"){if(ageMs<RESIDUE_STALE_AGE_MS)continue}let abs=path138.normalize(path138.join(swarmRoot,...item.relPath.split("/"))),reasons=[];if(!item.grammar.quarantineEligible)reasons.push("constant-name-grammar");if(ageMs<RESIDUE_STALE_AGE_MS)reasons.push("recent");let trackedState;if(tracked===void 0){if(trackedState="unknown",item.grammar.quarantineEligible)reasons.push("tracked-state-unknown")}else if(trackedState=tracked.has(abs)?"tracked":"untracked",trackedState==="tracked")reasons.push("git-tracked");if(item.isSymlink)reasons.push("symlink");let lockHeld=lockTargets.has(abs)||(item.grammar.parsesTarget?lockTargets.has(path138.normalize(path138.join(path138.dirname(abs),parseTargetBasename(item.relPath.split("/").pop()??"")??""))):!1);if(lockHeld)reasons.push("active-lock");if(item.bytes>RESIDUE_HASH_MAX_BYTES)reasons.push("oversize");if(item.grammar.quarantineEligible&&item.grammar.parsesTarget){let targetBasename=parseTargetBasename(item.relPath.split("/").pop()??"");if(targetBasename){let targetAbs=path138.join(path138.dirname(abs),targetBasename),targetOk=!1;try{targetOk=fs88.lstatSync(targetAbs).isFile()}catch{targetOk=!1}if(!targetOk)reasons.push("target-absent")}}entries.push({relPath:item.relPath,grammarId:item.grammar.id,grammarEra:item.grammar.era,bytes:item.bytes,mtimeMs:item.mtimeMs,ageMs,isSymlink:item.isSymlink,tracked:trackedState,lockHeld,proposedAction:item.grammar.quarantineEligible&&reasons.length===0?"quarantine":"report_only",reasons})}entries.sort((a,b)=>b.ageMs-a.ageMs);let eligible=entries.filter((e)=>e.proposedAction==="quarantine");return{swarmRoot,scannedEntries,truncated,entries,summary:{matched:entries.length,eligible:eligible.length,ambiguous:entries.length-eligible.length,totalBytes:entries.reduce((sum,e)=>sum+e.bytes,0),oldestAgeMs:entries[0]?.ageMs??0},gitState:tracked===void 0?"unknown":"ok"}}function validateRelPath(rel,what){if(!rel||path138.isAbsolute(rel)||rel.split("/").some((s)=>s===".."||s===""||/[\0-\x1f]/.test(s)))throw Error(`unsafe ${what} in quarantine manifest: ${JSON.stringify(rel)}`);return rel}function sha256Bounded(absPath){try{return _internals125.sha256File(absPath)}catch{return}}async function quarantineSwarmResidue(directory,options){let inventory=await inventorySwarmResidue(directory),eligible=inventory.entries.filter((e)=>e.proposedAction==="quarantine"),preserved=inventory.entries.filter((e)=>e.proposedAction==="report_only").map((e)=>({relPath:e.relPath,status:"preserved",reasons:e.reasons}));if(options?.dryRun||eligible.length===0)return{inventory,quarantined:0,preserved};let swarmRoot=inventory.swarmRoot,batchId=`${new Date().toISOString().replace(/[:.]/g,"-")}-${Math.random().toString(36).slice(2,10)}`,batchAbs=path138.join(swarmRoot,"quarantine",batchId);fs88.mkdirSync(batchAbs,{recursive:!0});let manifest={schema_version:1,batch_id:batchId,created_at:new Date().toISOString(),trigger:options?.trigger??"manual",entries:[]},moved=[];for(let entry of eligible){let abs=path138.join(swarmRoot,...entry.relPath.split("/"));try{let st=fs88.lstatSync(abs);if(!st.isFile()||st.size!==entry.bytes||st.mtimeMs!==entry.mtimeMs){preserved.push({relPath:entry.relPath,status:"preserved",reasons:["changed-since-scan"]});continue}}catch{preserved.push({relPath:entry.relPath,status:"preserved",reasons:["vanished"]});continue}let sha=sha256Bounded(abs);if(!sha){preserved.push({relPath:entry.relPath,status:"preserved",reasons:["hash-failed"]});continue}let storedAbs=path138.join(batchAbs,...entry.relPath.split("/"));try{fs88.mkdirSync(path138.dirname(storedAbs),{recursive:!0}),_internals125.renameResidueEntry(abs,storedAbs)}catch(moveErr){let code=moveErr?.code??"unknown";preserved.push({relPath:entry.relPath,status:"preserved",reasons:[`move-failed:${code}`]});continue}manifest.entries.push({original_rel_path:entry.relPath,stored_rel_path:path138.posix.join("quarantine",batchId,entry.relPath),sha256:sha,bytes:entry.bytes,mtime_ms:entry.mtimeMs,grammar_id:entry.grammarId,reason:"stale-atomic-write-temp"}),moved.push({relPath:entry.relPath,status:"quarantined",reasons:[]})}let batchRelDir;if(manifest.entries.length>0)atomicWriteSwarmFileSync(path138.join(batchAbs,"manifest.json"),`${JSON.stringify(manifest,null,2)}
|
|
1414
1414
|
`),batchRelDir=path138.posix.join("quarantine",batchId);else try{fs88.rmSync(batchAbs,{recursive:!0,force:!0})}catch{}try{telemetry.residueHealth({trigger:options?.trigger??"manual",scanned:inventory.scannedEntries,matched:inventory.summary.matched,eligible:inventory.summary.eligible,ambiguous:inventory.summary.ambiguous,quarantined:manifest.entries.length,preserved:preserved.length,total_bytes:inventory.summary.totalBytes,oldest_age_ms:inventory.summary.oldestAgeMs,grammar_counts:Object.fromEntries(Object.entries(inventory.entries.reduce((acc,e)=>{return acc[e.grammarId]=(acc[e.grammarId]??0)+1,acc},{})).sort())})}catch{}return{inventory,batchRelDir,quarantined:manifest.entries.length,preserved}}function listQuarantineBatches(swarmRoot){let quarantineRoot=path138.join(swarmRoot,"quarantine");try{return fs88.readdirSync(quarantineRoot,{withFileTypes:!0}).filter((d)=>d.isDirectory()&&!d.isSymbolicLink()).map((d)=>d.name).sort()}catch{return[]}}async function rollbackResidueQuarantine(directory,batchId){let swarmRoot=path138.normalize(path138.resolve(directory,".swarm")),batches=listQuarantineBatches(swarmRoot);if(batches.length===0)throw Error("No quarantine batches found under .swarm/quarantine/");let selected=batchId?batches.find((b)=>b===batchId||b.endsWith(`-${batchId}`))??(()=>{throw Error(`Quarantine batch not found: ${batchId}`)})():batches[batches.length-1],batchAbs=path138.join(swarmRoot,"quarantine",selected),manifestPath2=path138.join(batchAbs,"manifest.json"),manifest;try{manifest=JSON.parse(fs88.readFileSync(manifestPath2,"utf-8"))}catch{throw Error(`Quarantine batch has no readable manifest.json: ${selected}`)}if(manifest.schema_version!==1||!Array.isArray(manifest.entries))throw Error(`Quarantine manifest has an unsupported shape: ${selected}`);let items=[],allResolved=!0;for(let entry of manifest.entries){let originalRel=validateRelPath(entry.original_rel_path,"original_rel_path"),storedRel=validateRelPath(entry.stored_rel_path,"stored_rel_path"),originalAbs=path138.join(swarmRoot,...originalRel.split("/")),storedAbs=path138.join(swarmRoot,...storedRel.split("/"));if(!originalAbs.startsWith(swarmRoot+path138.sep)||!storedAbs.startsWith(batchAbs+path138.sep))throw Error(`Quarantine manifest path escapes its root: ${selected}`);if(!fs88.existsSync(storedAbs)){items.push({relPath:originalRel,status:"missing-copy"}),allResolved=!1;continue}if(fs88.existsSync(originalAbs)){if(sha256Bounded(originalAbs)===entry.sha256)fs88.unlinkSync(storedAbs),items.push({relPath:originalRel,status:"already-restored"});else items.push({relPath:originalRel,status:"collision"}),allResolved=!1;continue}fs88.mkdirSync(path138.dirname(originalAbs),{recursive:!0}),fs88.renameSync(storedAbs,originalAbs),items.push({relPath:originalRel,status:"restored"})}if(allResolved)try{fs88.rmSync(batchAbs,{recursive:!0,force:!0})}catch{}return{batchRelDir:path138.posix.join("quarantine",selected),items,drained:allResolved}}function formatAge(ms){if(ms<=0)return"0s";let minutes=Math.floor(ms/60000);if(minutes<60)return`${minutes}m`;let hours=Math.floor(minutes/60);if(hours<48)return`${hours}h`;return`${Math.floor(hours/24)}d`}function formatResidueInventoryLines(inv,options){let maxEntries=options?.maxEntries??10,s=inv.summary,lines=[];lines.push(`- Matched registered temp grammars: ${s.matched} file(s), ${s.totalBytes} byte(s), oldest ${formatAge(s.oldestAgeMs)} old`),lines.push(`- Eligible for quarantine (stale ≥ ${Math.round(RESIDUE_STALE_AGE_MS/60000)}m, untracked, unlocked, non-symlink): ${s.eligible}; preserved/ambiguous: ${s.ambiguous}${inv.gitState==="unknown"?" (git tracked-state unknown — nothing quarantined)":""}`);let byGrammar=new Map;for(let e of inv.entries){let g=byGrammar.get(e.grammarId)??{count:0,bytes:0};g.count++,g.bytes+=e.bytes,byGrammar.set(e.grammarId,g)}for(let[id,g]of[...byGrammar.entries()].sort((a,b)=>b[1].count-a[1].count))lines.push(` - ${id}: ${g.count} file(s), ${g.bytes} byte(s)`);for(let e of inv.entries.slice(0,maxEntries)){let flags=[`${formatAge(e.ageMs)} old`,e.tracked==="tracked"?"git-tracked":e.tracked,e.isSymlink?"symlink":null,e.lockHeld?"locked":null,...e.reasons].filter(Boolean),safeRel=e.relPath.replace(/`/g,"'");lines.push(` - \`${safeRel}\` [${e.grammarId}] → ${e.proposedAction==="quarantine"?"would quarantine":"preserve"} (${flags.join(", ")})`)}if(inv.entries.length>maxEntries)lines.push(` - … ${inv.entries.length-maxEntries} more (bounded report)`);if(inv.truncated)lines.push(` - scan truncated at ${MAX_RESIDUE_SCAN_ENTRIES} entries — inventory is partial`);return lines}var RESIDUE_STALE_AGE_MS=1800000,MAX_RESIDUE_SCAN_ENTRIES=20000,RESIDUE_SCAN_DEPTH=8,RESIDUE_HASH_MAX_BYTES=134217728,RESIDUE_SKIP_DIRS,_internals125;var init_swarm_residue=__esm(()=>{init_file_locks();init_telemetry();init_atomic_write();init_bun_compat();RESIDUE_SKIP_DIRS=Object.freeze(["archive","quarantine","locks"]),_internals125={now:()=>Date.now(),renameResidueEntry:(from,to)=>{fs88.renameSync(from,to)},queryTracked:(projectRoot,swarmRoot)=>{let result=bunSpawnSync(["git","-c","core.quotepath=false","ls-files","--",swarmRoot.split(path138.sep).join("/")],{cwd:projectRoot,stdin:"ignore",timeout:5000,envOverrides:{GIT_DIR:null,GIT_WORK_TREE:null,GIT_INDEX_FILE:null}});if(result.exitCode!==0)return{tracked:void 0};let out=new TextDecoder().decode(result.stdout),tracked=new Set;for(let line of out.split(/\r?\n/)){let t=line.trim();if(t)tracked.add(path138.normalize(path138.resolve(projectRoot,t)))}return{tracked}},activeLockTargets:(directory)=>{let targets=new Set;for(let lock of listActiveLocks(directory))targets.add(path138.normalize(path138.resolve(directory,lock.filePath)));return targets},sha256File:(absPath)=>{let hash4=createHash64("sha256"),fd=fs88.openSync(absPath,"r");try{let chunk=Buffer.alloc(1048576);for(;;){let read=fs88.readSync(fd,chunk,0,chunk.byteLength,null);if(read===0)break;hash4.update(chunk.subarray(0,read))}}finally{fs88.closeSync(fd)}return hash4.digest("hex")}}});import path139 from"node:path";function removeSqliteSidecarsAfterClose(swarmDir){for(let sidecar of["swarm.db-wal","swarm.db-shm"])try{_internals123.unlinkSidecarSync(path139.join(swarmDir,sidecar))}catch(error93){let code=error93?.code;if(code!=="ENOENT"&&code!=="EBUSY")log("[close-command] failed to remove sqlite sidecar:",error93)}}var init_db_helpers=__esm(()=>{init_logger();init_internals()});import{promises as fs89}from"node:fs";import path140 from"node:path";async function runCleanStage(ctx){let configBackupsRemoved=0,cleanedFiles=[],linkedKnowledgeShared=isLinked(ctx.directory);if(linkedKnowledgeShared){for(let artifact of KNOWLEDGE_FAMILY_ARTIFACTS)if(ctx.archivedActiveStateFiles.has(artifact))ctx.warnings.push(`[link-guard] Shared knowledge artifact "${artifact}" appears in `+"the archive set while this worktree is linked — archive stage "+"should have skipped it. Artifact will NOT be deleted.")}if(ctx.archivedActiveStateFiles.size>0)for(let artifact of ACTIVE_STATE_TO_CLEAN){if(linkedKnowledgeShared&&KNOWLEDGE_FAMILY_ARTIFACTS.has(artifact))continue;if(!ctx.archivedActiveStateFiles.has(artifact)){let reason=ctx.archiveFailureReasons?.get(artifact);if(TERMINAL_STATE_FILES.includes(artifact)){ctx.warnings.push(reason?`${artifact} was not archived (${reason}); removing it anyway to prevent CLOSED-plan resurrection next session — no archive copy retained.`:`${artifact} was not archived; removing it anyway to prevent CLOSED-plan resurrection next session — no archive copy retained.`);continue}if(reason)ctx.warnings.push(`Preserved ${artifact} because it was not successfully archived: ${reason}.`);continue}let filePath=path140.join(ctx.swarmDir,artifact);if(artifact==="swarm.db"){try{await _internals123.closeSnapshotCoordinationInitialization(ctx.directory)}catch(error93){let reason=error93 instanceof Error?error93.message:String(error93);ctx.warnings.push(`Preserved swarm.db because snapshot coordination did not settle: ${reason}.`);continue}try{closeGroupCommitWriter(ctx.directory)}catch{}try{closeProjectDb(ctx.directory)}catch{}}if(artifact===REPO_MEMORY_FILENAME)try{_internals123.closeRepoMemory(ctx.directory)}catch{}try{await _internals123.unlinkActiveStateFileWithRetry(filePath),cleanedFiles.push(artifact)}catch(err){let errno=err?.code;if(errno==="ENOENT");else{let reason=err instanceof Error?err.message:String(err);ctx.warnings.push(`Failed to clean active-state file ${artifact} [${errno??"unknown"}]: ${reason}`)}}if(artifact==="swarm.db")removeSqliteSidecarsAfterClose(ctx.swarmDir)}else ctx.warnings.push("Skipped active-state cleanup because no active-state files were archived. Files preserved to prevent data loss.");for(let artifact of ctx.archivedActiveStateFiles){if(!/^post-mortem-[^/\\]+\.md$/.test(artifact)&&!/^drift-report-phase-\d+\.json$/.test(artifact))continue;try{await fs89.unlink(path140.join(ctx.swarmDir,artifact)),cleanedFiles.push(artifact)}catch(err){let errno=err?.code;if(errno!=="ENOENT"){let reason=err instanceof Error?err.message:String(err);ctx.warnings.push(`Failed to clean active-state file ${artifact} [${errno??"unknown"}]: ${reason}`)}}}for(let dirName of ACTIVE_STATE_DIRS_TO_CLEAN){if(!ctx.archivedActiveStateDirs.has(dirName))continue;let dirPath=path140.join(ctx.swarmDir,dirName);try{await fs89.rm(dirPath,{recursive:!0,force:!0}),cleanedFiles.push(`${dirName}/`)}catch{}}try{let swarmFiles=await fs89.readdir(ctx.swarmDir),configBackups=swarmFiles.filter((f)=>f.startsWith("config-backup-")&&f.endsWith(".json"));for(let backup of configBackups)try{await fs89.unlink(path140.join(ctx.swarmDir,backup)),configBackupsRemoved++}catch(err){let errno=err?.code;if(errno==="ENOENT");else{let reason=err instanceof Error?err.message:String(err);ctx.warnings.push(`Failed to clean config-backup ${backup} [${errno??"unknown"}]: ${reason}`)}}let ledgerSiblings=swarmFiles.filter((f)=>(f.startsWith("plan-ledger.archived-")||f.startsWith("plan-ledger.backup-"))&&f.endsWith(".jsonl"));for(let sibling of ledgerSiblings)try{await fs89.unlink(path140.join(ctx.swarmDir,sibling))}catch(err){let errno=err?.code;if(errno==="ENOENT");else{let reason=err instanceof Error?err.message:String(err);ctx.warnings.push(`Failed to clean ledger sibling ${sibling} [${errno??"unknown"}]: ${reason}`)}}}catch(err){let errno=err?.code;if(errno==="ENOENT");else{let reason=err instanceof Error?err.message:String(err);ctx.warnings.push(`Failed to read ${ctx.swarmDir} for stale-file cleanup [${errno??"unknown"}]: ${reason}`)}}let swarmPlanFilesRemoved=0,candidates=[path140.join(ctx.directory,".swarm","plan-export","SWARM_PLAN.json"),path140.join(ctx.directory,".swarm","plan-export","SWARM_PLAN.md"),path140.join(ctx.directory,".swarm","SWARM_PLAN.json"),path140.join(ctx.directory,".swarm","SWARM_PLAN.md"),path140.join(ctx.directory,"SWARM_PLAN.json"),path140.join(ctx.directory,"SWARM_PLAN.md")];for(let candidate of candidates)try{await fs89.unlink(candidate),swarmPlanFilesRemoved++}catch(err){if(err?.code!=="ENOENT")ctx.warnings.push(`Failed to remove ${candidate}: ${err instanceof Error?err.message:String(err)}`)}let residueQuarantined=0,residuePreserved=0;try{let residue=await quarantineSwarmResidue(ctx.directory,{trigger:"close"});if(residueQuarantined=residue.quarantined,residuePreserved=residue.preserved.length,residue.quarantined>0&&residue.batchRelDir)cleanedFiles.push(`${residue.quarantined} stale temp file(s) → ${residue.batchRelDir}/`),ctx.warnings.push(`Quarantined ${residue.quarantined} stale atomic-write temp file(s) to .swarm/${residue.batchRelDir}/ (recoverable; rollback: /swarm config doctor --rollback-residue-quarantine).`);if(residue.preserved.length>0){let sample=residue.preserved.slice(0,5).map((p)=>`\`${p.relPath}\``).join(", ");ctx.warnings.push(`Preserved ${residue.preserved.length} residue candidate(s) in place (recent/active/tracked/ambiguous): ${sample}${residue.preserved.length>5?" …":""}.`)}}catch(err){let reason=err instanceof Error?err.message:String(err);ctx.warnings.push(`Atomic-write residue quarantine failed (status of individual candidates unknown — inspect .swarm/quarantine/): ${reason}`)}for(let terminalFile of TERMINAL_STATE_FILES)try{if(await fs89.unlink(path140.join(ctx.swarmDir,terminalFile)),!cleanedFiles.includes(terminalFile))cleanedFiles.push(terminalFile)}catch(err){let errno=err?.code;if(errno==="ENOENT");else{let reason=err instanceof Error?err.message:String(err);ctx.warnings.push(`Failed to remove terminal-state file ${terminalFile} [${errno??"unknown"}]: ${reason}`)}}clearAllScopes(ctx.directory);let contextPath=path140.join(ctx.swarmDir,"context.md"),contextContent=["# Context","","## Status",`Session closed after: ${ctx.projectName}`,`Closed: ${new Date().toISOString()}`,`Finalization: ${ctx.isForced?"forced":ctx.planAlreadyDone?"plan-already-done":"normal"}`,"No active plan. Next session starts fresh.",""].join(`
|
|
1415
1415
|
`);try{await atomicWriteSwarmFile(contextPath,contextContent)}catch(error93){let msg=error93 instanceof Error?error93.message:String(error93);ctx.warnings.push(`Failed to reset context.md: ${msg}`),log("[close-command] Failed to write context.md:",error93)}return{cleanedFiles,configBackupsRemoved,swarmPlanFilesRemoved,residueQuarantined,residuePreserved}}var init_clean_stage=__esm(()=>{init_group_commit_writer();init_project_db();init_knowledge_link();init_scope_persistence();init_swarm_residue();init_indexed_storage();init_atomic_write();init_logger();init_constants2();init_db_helpers();init_internals()});import*as fsSync15 from"node:fs";import{promises as fs90}from"node:fs";import path141 from"node:path";async function runFinalizeDryRun(directory,swarmDir,planData,planExists){let existsInSwarm=(name)=>fsSync15.existsSync(path141.join(swarmDir,name)),phases=planData.phases??[],nonTerminalPhases=phases.filter((p)=>p.status!=="complete"&&p.status!=="completed"&&p.status!=="blocked"&&p.status!=="closed"),planAlreadyDone=planExists&&phases.length>0&&nonTerminalPhases.length===0,wouldArchive=ARCHIVE_ARTIFACTS.filter(existsInSwarm),dynamicArchive=(await fs90.readdir(swarmDir).catch(()=>[])).filter((name)=>/^post-mortem-[^/\\]+\.md$/.test(name)||/^drift-report-phase-\d+\.json$/.test(name)),wouldArchiveDirs=ACTIVE_STATE_DIRS_TO_CLEAN.filter(existsInSwarm),wouldRemoveTerminal=TERMINAL_STATE_FILES.filter(existsInSwarm),wouldCleanFiles=ACTIVE_STATE_TO_CLEAN.filter((f)=>existsInSwarm(f)&&!TERMINAL_STATE_FILES.includes(f)),gitNote=await readGitRepositoryStatusAsync(directory)?"would align the working tree to main/remote (git reset), pruning merged branches only with --prune-branches":"would skip git alignment (not a git repository / git unavailable)",residueSection=[];try{let residueInventory=await inventorySwarmResidue(directory);if(residueInventory.summary.matched>0)residueSection=["","### Atomic-write residue (read-only inventory)",...formatResidueInventoryLines(residueInventory),"- A real close run QUARANTINES eligible items into `.swarm/quarantine/` (recoverable, manifest-backed — never deleted); every other candidate is preserved in place."]}catch{}return["## /swarm finalize — DRY RUN (no changes made)","","No lock is taken, no files are archived or deleted, and no MUTATING git command runs (the repository probe below is a read-only `git rev-parse`).","","### Plan",planExists?planAlreadyDone?"- Plan is already terminal — no phases/tasks would be force-closed.":nonTerminalPhases.length>0?`- Would mark ${nonTerminalPhases.length} non-terminal phase(s) as closed: ${nonTerminalPhases.map((p)=>`#${p.id} ${p.name}`).join(", ")}`:"- No phases present; nothing to close.":"- No plan.json — plan-free session; cleanup-only.","","### Would archive",wouldArchive.length>0||dynamicArchive.length>0||wouldArchiveDirs.length>0?[...wouldArchive.map((f)=>`- ${f}`),...dynamicArchive.map((f)=>`- ${f}`),...wouldArchiveDirs.map((d)=>`- ${d}/`)].join(`
|
|
1416
1416
|
`):"- (nothing present to archive)","","### Would clean (removed after successful archive)",wouldCleanFiles.length>0||wouldArchiveDirs.length>0?[...wouldCleanFiles.map((f)=>`- ${f}`),...wouldArchiveDirs.map((d)=>`- ${d}/`)].join(`
|
|
@@ -1535,10 +1535,10 @@ Note: ${untracked.length} untracked file(s) outside .swarm/ belong to no task ($
|
|
|
1535
1535
|
`);break}if(computeEventHash(parsed)!==parsed.hashAfter){truncated=!0,badSuffix=lines.slice(i).join(`
|
|
1536
1536
|
`);break}events.push(parsed),lastCompleteSeq=parsed.seq}let state2=events.length===0?null:events[events.length-1].toState;return{events,state:state2,truncated,badSuffix,lastCompleteSeq}}function quarantineSuffix(directory,skillSlug,badSuffix){assertProjectRoot(directory);let dir=path158.join(directory,".swarm","evolution","skills");if(!existsSync76(dir))mkdirSync44(dir,{recursive:!0});let hash4=computeStateHash(badSuffix).slice(0,12),stamp=Date.now(),quarantinePath=path158.join(dir,`lifecycle-quarantine.${skillSlug}.${stamp}.${hash4}`);return writeFileSyncAsync(quarantinePath,badSuffix,"utf8"),quarantinePath}function writeStateProjection(directory,skillSlug,candidateId,replay){assertProjectRoot(directory);let target=stateProjectionPath(directory,skillSlug,candidateId);ensureCandidateDir(directory,skillSlug,candidateId);let projection={v:1,candidateId,skillSlug,state:replay.state,lastCompleteSeq:replay.lastCompleteSeq,truncated:replay.truncated,eventCount:replay.events.length,updatedAt:new Date().toISOString()},tempPath=`${target}.tmp.${Date.now()}.${Math.floor(Math.random()*1e9)}`;_internals140.writeFileFsyncedThenRename(tempPath,target,`${JSON.stringify(projection,null,2)}
|
|
1537
1537
|
`)}function writeArtifact(directory,skillSlug,candidateId,fileName,content){assertProjectRoot(directory);let dir=ensureCandidateDir(directory,skillSlug,candidateId),target=path158.join(dir,fileName),tempPath=`${target}.tmp.${Date.now()}.${Math.floor(Math.random()*1e9)}`;return _internals140.writeFileFsyncedThenRename(tempPath,target,content),target}function readArtifact(directory,skillSlug,candidateId,fileName){let target=path158.join(candidateDir(directory,skillSlug,candidateId),fileName);if(!existsSync76(target))return null;return readFileSync57(target,"utf8")}var SLUG_PATTERN3,_internals140;var init_store2=__esm(()=>{init_lock();init_project_boundary();SLUG_PATTERN3=/^[a-z0-9][a-z0-9-]{0,63}$/;_internals140={withEvidenceLock,writeFileFsyncedThenRename:writeFileFsyncedThenRename2,writeFileSync:writeFileSyncAsync,readFileSync:readFileSync57,renameSync:renameSync26,unlinkSync:unlinkSync27,existsSync:existsSync76,statSync:statSync54}});function isLegalTransition(from,to){return(from===null?INITIAL_TRANSITIONS:LEGAL_TRANSITIONS[from]).includes(to)}function assertTransition(from,to){if(!isLegalTransition(from,to))throw new IllegalTransitionError(from,to)}async function recordTransition(input){let replay=replayCandidate(input.directory,input.skillSlug,input.candidateId),fromState=replay.state;if(replay.truncated&&replay.badSuffix)quarantineSuffix(input.directory,input.skillSlug,replay.badSuffix),fromState=replay.events.length===0?null:replay.events[replay.events.length-1].toState;if(assertTransition(fromState,input.toState),input.toState==="validation_running"){if(replay.events.some((e)=>e.toState==="accepted_pending_approval"||e.toState==="rejected"||e.toState==="inconclusive"))throw Error(`candidate ${input.candidateId} already completed validation — start a new candidate to re-test`)}let event=await appendEvent2(input.directory,{candidateId:input.candidateId,skillSlug:input.skillSlug,eventType:input.eventType,fromState,toState:input.toState,actor:input.actor,origin:input.origin,contentHashBefore:input.contentHashBefore??null,contentHashAfter:input.contentHashAfter??null,reason:input.reason,evidenceRefs:input.evidenceRefs??[],...input.payload?{payload:input.payload}:{}});return writeStateProjection(input.directory,input.skillSlug,input.candidateId,{...replayCandidate(input.directory,input.skillSlug,input.candidateId),events:[...replay.events,event]}),{event,fromState,replayTruncated:replay.truncated}}function currentCandidateState(directory,skillSlug,candidateId){let replay=replayCandidate(directory,skillSlug,candidateId);if(replay.truncated&&replay.badSuffix)quarantineSuffix(directory,skillSlug,replay.badSuffix);return{state:replay.events.length===0?null:replay.events[replay.events.length-1].toState,lastEvent:replay.events.length===0?null:replay.events[replay.events.length-1],truncated:replay.truncated}}function isTerminal2(state2){return state2==="rejected"||state2==="expired"||state2==="rolled_back"}var IllegalTransitionError,LEGAL_TRANSITIONS,INITIAL_TRANSITIONS;var init_lifecycle2=__esm(()=>{init_store2();IllegalTransitionError=class IllegalTransitionError extends Error{from;to;constructor(from,to){super(`illegal skill-opt transition: ${from??"<none>"} → ${to}`);this.from=from;this.to=to;this.name="IllegalTransitionError"}};LEGAL_TRANSITIONS={discovered:["drafted"],drafted:["smoke_validated","rejected"],smoke_validated:["validation_running","rejected"],validation_running:["accepted_pending_approval","rejected","inconclusive"],accepted_pending_approval:["activated","expired","rolled_back"],rejected:[],inconclusive:["drafted","rejected"],activated:["rolled_back"],expired:[],rolled_back:[]},INITIAL_TRANSITIONS=["discovered"]});import{linkSync,mkdirSync as mkdirSync45,readdirSync as readdirSync18,rmSync as rmSync19,statSync as statSync55,unlinkSync as unlinkSync28}from"node:fs";import*as path159 from"node:path";function sanitizeSummaryId(id){if(!id||id.length===0)throw Error("Invalid summary ID: empty string");if(/\0/.test(id))throw Error("Invalid summary ID: contains null bytes");for(let i=0;i<id.length;i++)if(id.charCodeAt(i)<32)throw Error("Invalid summary ID: contains control characters");if(id.includes("..")||id.includes("../")||id.includes("..\\"))throw Error("Invalid summary ID: path traversal detected");if(!SUMMARY_ID_REGEX.test(id))throw Error(`Invalid summary ID: must match pattern ^S\\d+$, got "${id}"`);return id}function isEexistError(error93){return typeof error93==="object"&&error93!==null&&error93.code==="EEXIST"}async function storeSummary(directory,id,fullOutput,summaryText,maxStoredBytes){let sanitizedId=sanitizeSummaryId(id),preCheckEntry={id:sanitizedId,summaryText,fullOutput,timestamp:Date.now(),originalBytes:Buffer.byteLength(fullOutput,"utf8")},serializedSize=Buffer.byteLength(JSON.stringify(preCheckEntry),"utf8");if(serializedSize>maxStoredBytes)throw Error(`Summary entry size (${serializedSize} bytes) exceeds maximum (${maxStoredBytes} bytes)`);let relativePath2=path159.join("summaries",`${sanitizedId}.json`),summaryPath=validateSwarmPath(directory,relativePath2),summaryDir=path159.dirname(summaryPath),entry={id:sanitizedId,summaryText,fullOutput,timestamp:Date.now(),originalBytes:Buffer.byteLength(fullOutput,"utf8")},entryJson=JSON.stringify(entry);mkdirSync45(summaryDir,{recursive:!0});let tempPath=path159.join(summaryDir,`${sanitizedId}.json.tmp.${Date.now()}.${process.pid}`);try{await bunWrite(tempPath,entryJson);try{linkSync(tempPath,summaryPath)}catch(error93){if(isEexistError(error93))throw new SummaryIdCollisionError(sanitizedId);throw error93}try{unlinkSync28(tempPath)}catch{}invalidateCachedArtifact(summaryPath)}catch(error93){try{rmSync19(tempPath,{force:!0})}catch{}throw error93}}async function loadFullOutput(directory,id){let sanitizedId=sanitizeSummaryId(id),relativePath2=path159.join("summaries",`${sanitizedId}.json`);validateSwarmPath(directory,relativePath2);let content=await readSwarmFileAsync(directory,relativePath2);if(content===null)return null;try{let parsed=JSON.parse(content);if(typeof parsed.fullOutput==="string")return parsed.fullOutput;return warn(`Summary entry ${sanitizedId} missing valid fullOutput field`),null}catch(error93){return warn(`Summary entry validation failed for ${sanitizedId}: ${error93 instanceof Error?error93.message:String(error93)}`),null}}function enumerateSummaryIds(directory){let summariesBasePath=validateSwarmPath(directory,"summaries");try{statSync55(summariesBasePath)}catch{return[]}let entries;try{entries=readdirSync18(summariesBasePath)}catch{return[]}let summaryIds=[];for(let entry of entries){if(!entry.endsWith(".json"))continue;try{if(!statSync55(path159.join(summariesBasePath,entry)).isFile())continue}catch{continue}let summaryId=entry.slice(0,-5);try{sanitizeSummaryId(summaryId),summaryIds.push(summaryId)}catch(error93){if(error93 instanceof Error&&!error93.message.startsWith("Invalid summary ID"))warn(`Error reading summary entry '${entry}': ${error93.message}`)}}return summaryIds}function allocateSummaryId(directory){let max=0n;for(let id of enumerateSummaryIds(directory)){let value=BigInt(id.slice(1));if(value>max)max=value}return`S${(max+1n).toString()}`}async function listStaleSummaryIds(directory,retentionDays,options){let summariesBasePath=validateSwarmPath(directory,"summaries"),retentionFiles=[];try{retentionFiles=readdirSync18(summariesBasePath).filter((name)=>name.endsWith(".json")&&/^S.+$/.test(name.slice(0,-5)))}catch{retentionFiles=[]}let cutoffTime=(options?.now??Date.now())-retentionDays*24*60*60*1000,stale=[];for(let filename of retentionFiles){let id=filename.slice(0,-5),relativePath2=path159.join("summaries",filename),summaryPath=validateSwarmPath(directory,relativePath2),content=await readSwarmFileAsync(directory,relativePath2);if(content===null)continue;try{let timestamp=JSON.parse(content).timestamp;if(typeof timestamp==="number"&&Number.isFinite(timestamp)&×tamp<cutoffTime||typeof timestamp!=="number"&&(()=>{try{return statSync55(summaryPath).mtimeMs<cutoffTime}catch{return!1}})())stale.push(id)}catch(error93){warn(`Failed to inspect summary ${id} for retention: ${error93 instanceof Error?error93.message:String(error93)}`)}}return stale}async function cleanupSummaries(directory,retentionDays,options){let staleIds=await listStaleSummaryIds(directory,retentionDays,options),deleted=[];for(let id of staleIds)try{rmSync19(validateSwarmPath(directory,path159.join("summaries",`${id}.json`))),deleted.push(id)}catch(error93){warn(`Failed to cleanup summary ${id}: ${error93 instanceof Error?error93.message:String(error93)}`)}return deleted}var SUMMARY_ID_REGEX,SummaryIdCollisionError;var init_manager3=__esm(()=>{init_utils2();init_caps();init_utils();init_bun_compat();init_swarm_artifact_cache();SUMMARY_ID_REGEX=/^S\d+$/;SummaryIdCollisionError=class SummaryIdCollisionError extends Error{summaryId;constructor(summaryId){super(`Summary ID ${summaryId} already exists; refusing to overwrite`);this.summaryId=summaryId;this.name="SummaryIdCollisionError"}}});import*as fs96 from"node:fs";import*as path160 from"node:path";function subtreeNewestFileMtime(root,maxScan){let budget=maxScan,newest=null,stack=[root];while(stack.length>0){if(budget<=0)return Number.POSITIVE_INFINITY;let dir=stack.pop(),names;try{names=fs96.readdirSync(dir)}catch{return Number.POSITIVE_INFINITY}for(let name of names){if(budget<=0)return Number.POSITIVE_INFINITY;let entryPath=path160.join(dir,name),stat16;try{stat16=fs96.lstatSync(entryPath)}catch{continue}if(budget-=1,stat16.isSymbolicLink())continue;if(stat16.isDirectory()){stack.push(entryPath);continue}if(stat16.isFile()&&stat16.mtimeMs>(newest??-1/0))newest=stat16.mtimeMs}}return newest}function effectiveEntryMtime(entryPath,ownMtimeMs){let newest=subtreeNewestFileMtime(entryPath,SUBTREE_SCAN_CAP);if(newest===null)return ownMtimeMs;return newest}function listPruneCandidates(dir,maxScan,includeEntry=()=>!0){let candidates=[],refusedSymlinks=[],names;try{names=fs96.readdirSync(dir)}catch{return{candidates:[],refusedSymlinks:[]}}for(let name of names.slice(0,maxScan)){let entryPath=path160.join(dir,name);try{let stat16=fs96.lstatSync(entryPath);if(stat16.isSymbolicLink()){refusedSymlinks.push(name);continue}if(!includeEntry(name,stat16))continue;candidates.push({name,mtimeMs:stat16.isDirectory()?effectiveEntryMtime(entryPath,stat16.mtimeMs):stat16.mtimeMs})}catch{}}return{candidates,refusedSymlinks}}async function pruneDirectory(dir,opts){let now2=opts.now??Date.now(),maxScan=opts.maxScan??1e5,{candidates}=listPruneCandidates(dir,maxScan,opts.includeEntry);if(candidates.length===0)return 0;candidates.sort((a,b)=>a.mtimeMs===b.mtimeMs?a.name<b.name?-1:a.name>b.name?1:0:a.mtimeMs-b.mtimeMs);let cutoff=opts.maxAgeMs!==void 0?now2-opts.maxAgeMs:null,victims=[];for(let candidate of candidates){if(candidate.mtimeMs>now2)continue;if(cutoff!==null&&candidate.mtimeMs<cutoff)victims.push(candidate)}if(opts.maxEntries!==void 0){let keepNewest=opts.maxEntries,excess=candidates.length-keepNewest;for(let i=0;i<excess;i++){let candidate=candidates[i];if(candidate.mtimeMs>now2)continue;if(!victims.includes(candidate))victims.push(candidate)}}let pruned=0;if(opts.dryRun!==!0){for(let victim of victims)try{fs96.rmSync(path160.join(dir,victim.name),{recursive:!0,force:!0}),pruned+=1}catch{}return pruned}return victims.length}var SUBTREE_SCAN_CAP=2000;var init_dir_prune=()=>{};import*as fs97 from"node:fs";import*as path161 from"node:path";function familiesFor(swarmRoot,now2){let age=(days)=>days*DAY_MS2,f=(label,rel,opts)=>({label,dir:path161.join(swarmRoot,rel),maxAgeMs:opts.maxAgeDays!==void 0?age(opts.maxAgeDays):void 0,maxEntries:opts.maxEntries,includeEntry:opts.includeEntry});return[f("pr-feedback-events","pr-feedback-events",{maxAgeDays:30}),f("pr-workflow-gates","pr-workflow-gates",{maxAgeDays:30,includeEntry:isPrWorkflowGateStateProjection}),f("pr-workflow-gate-sidecars","pr-workflow-gates",{maxAgeDays:30,includeEntry:isPrWorkflowGateSidecar}),f("pr-review-reentry-shadows",path161.join("pr-review","reentry-authorizations"),{maxAgeDays:30}),f("pr-review-run-artifacts","pr-review",{maxAgeDays:30,maxEntries:PR_REVIEW_KEEP_NEWEST_RUNS,includeEntry:(name,stat16)=>name!=="route-receipts"&&isPrReviewRunArtifact(name,stat16)}),f("pr-review-route-receipts",path161.join("pr-review","route-receipts"),{maxAgeDays:30,includeEntry:isPrReviewRouteReceipt}),f("review-receipts","review-receipts",{maxAgeDays:30,maxEntries:REVIEW_RECEIPTS_KEEP_NEWEST}),f("lane-results","lane-results",{maxAgeDays:30,maxEntries:LANE_RESULTS_KEEP_NEWEST_BATCHES}),f("capsules","capsules",{maxAgeDays:30}),f("runs","runs",{maxAgeDays:30}),f("skills-proposals",path161.join("skills","proposals"),{maxAgeDays:14}),f("skill-improver-proposals",path161.join("skill-improver","proposals"),{maxAgeDays:30}),f("recovery","recovery",{maxAgeDays:30}),f("epic-prior-reports",path161.join("epic-prior","reports"),{maxAgeDays:365,maxEntries:50}),f("pr-feedback-evidence","pr-feedback-evidence",{maxAgeDays:30})]}async function runRetentionSweep(projectRoot,options={}){if(options.enabled===!1)return{pruned:{},disabled:!0,errors:{}};let now2=options.now??Date.now(),dryRun=options.dryRun===!0,swarmRoot=path161.join(projectRoot,".swarm"),result={pruned:{},dryRun,errors:{}};try{let resolvedRoot=fs97.realpathSync(projectRoot),resolvedSwarm=fs97.realpathSync(swarmRoot);if(!resolvedSwarm.startsWith(resolvedRoot+path161.sep)&&resolvedSwarm!==resolvedRoot)return result.errors.containment=".swarm resolves outside the project root; refusing sweep",result}catch(error93){if((typeof error93==="object"&&error93!==null&&"code"in error93?String(error93.code):"")!=="ENOENT")result.errors.containment=error93 instanceof Error?error93.message:String(error93);return result}let cancelled=(label)=>{if(options.shouldContinue&&!options.shouldContinue())return result.errors.sweep_cancelled=`sweep cancelled by shouldContinue token before ${label}`,!0;return!1};for(let family of familiesFor(swarmRoot,now2)){if(cancelled(family.label))return result;try{let pruned=await pruneDirectory(family.dir,{maxAgeMs:family.maxAgeMs,maxEntries:family.maxEntries,now:now2,dryRun,includeEntry:family.includeEntry});if(pruned>0)result.pruned[family.label]=pruned}catch(error93){result.errors[family.label]=error93 instanceof Error?error93.message:String(error93)}}if(cancelled("pr-workflow-checkout-temps"))return result;try{let pruned=await prunePrWorkflowCheckoutArtifacts(path161.join(swarmRoot,"pr-workflow-checkouts"),now2,dryRun);if(pruned.temps>0)result.pruned["pr-workflow-checkout-temps"]=pruned.temps;if(pruned.receipts>0)result.pruned["pr-workflow-checkout-receipts"]=pruned.receipts}catch(error93){result.errors["pr-workflow-checkout-temps"]=error93 instanceof Error?error93.message:String(error93)}if(cancelled("review-receipts-index"))return result;try{let dropped=await pruneDanglingReceiptIndexEntries(projectRoot,{dryRun});if(dropped>0)result.pruned["review-receipts-index"]=dropped}catch(error93){result.errors["review-receipts-index"]=error93 instanceof Error?error93.message:String(error93)}if(cancelled("epic-diagnostics"))return result;for(let[label,rel]of[["epic-divergence",path161.join("epic","divergence.jsonl")],["epic-calibration",path161.join("epic","calibration.json")]])try{let filePath=path161.join(swarmRoot,rel),stat16=await fs97.promises.stat(filePath).catch(()=>null);if(stat16&&stat16.mtimeMs<=now2&&stat16.mtimeMs<now2-DEFAULT_FAMILY_AGE_DAYS*DAY_MS2){if(!dryRun)await fs97.promises.unlink(filePath).catch(()=>{return});result.pruned[label]=1}}catch(error93){result.errors[label]=error93 instanceof Error?error93.message:String(error93)}if(cancelled("doc-drift-imported"))return result;try{let legacy=await fs97.promises.readdir(swarmRoot).then((names)=>names.filter((n)=>/^doc-drift-phase-\d+\.json\.imported$/.test(n))).catch(()=>[]),legacyPruned=0;for(let name of legacy){let filePath=path161.join(swarmRoot,name),stat16=await fs97.promises.stat(filePath).catch(()=>null);if(stat16&&stat16.mtimeMs<=now2&&stat16.mtimeMs<now2-DEFAULT_FAMILY_AGE_DAYS*DAY_MS2){if(!dryRun)await fs97.promises.unlink(filePath).catch(()=>{return});legacyPruned+=1}}if(legacyPruned>0)result.pruned["doc-drift-imported"]=legacyPruned}catch(error93){result.errors["doc-drift-imported"]=error93 instanceof Error?error93.message:String(error93)}if(cancelled("legacy-ledger-archives"))return result;try{let names=(await fs97.promises.readdir(swarmRoot)).filter((name)=>/^plan-ledger\.legacy-archive\.[0-9a-f]{64}\.jsonl$/.test(name)),entries=(await Promise.all(names.map(async(name)=>{let filePath=path161.join(swarmRoot,name),stat16=await fs97.promises.lstat(filePath).catch(()=>null);return stat16?.isFile()&&!stat16.isSymbolicLink()?{name,filePath,mtimeMs:stat16.mtimeMs}:null}))).filter((entry)=>entry!==null).sort((a,b)=>b.mtimeMs-a.mtimeMs||a.name.localeCompare(b.name)),removed=0;for(let[index,entry]of entries.entries()){if(index<LEGACY_LEDGER_ARCHIVES_KEEP_NEWEST)continue;if(entry.mtimeMs>now2||entry.mtimeMs>=now2-DEFAULT_FAMILY_AGE_DAYS*DAY_MS2)continue;if(!dryRun)await fs97.promises.unlink(entry.filePath).catch(()=>{return});removed++}if(removed>0)result.pruned["legacy-ledger-archives"]=removed}catch(error93){result.errors["legacy-ledger-archives"]=error93 instanceof Error?error93.message:String(error93)}if(cancelled("evolution-terminal-candidates"))return result;try{let evolutionRoot=path161.join(swarmRoot,"evolution","skills"),pruned=await pruneEvolutionCandidates(evolutionRoot,now2,dryRun);if(pruned>0)result.pruned["evolution-terminal-candidates"]=pruned}catch(error93){result.errors["evolution-terminal-candidates"]=error93 instanceof Error?error93.message:String(error93)}if(cancelled("evolution-scratch"))return result;try{let evalPruned=0;if(await walkEvolution(path161.join(swarmRoot,"evolution","skills"),async(entryPath,stat16)=>{let base=path161.basename(entryPath),isEvalInput=base==="_eval-input"&&stat16.isDirectory(),isQuarantine=base.startsWith("lifecycle-quarantine.");if(!isEvalInput&&!isQuarantine)return;let horizon=isEvalInput?7*DAY_MS2:DEFAULT_FAMILY_AGE_DAYS*DAY_MS2;if(stat16.mtimeMs<=now2&&stat16.mtimeMs<now2-horizon){if(!dryRun)fs97.rmSync(entryPath,{recursive:!0,force:!0});evalPruned+=1}}),evalPruned>0)result.pruned["evolution-scratch"]=evalPruned}catch(error93){result.errors["evolution-scratch"]=error93 instanceof Error?error93.message:String(error93)}if(cancelled("summaries-retention"))return result;try{let retentionDays=options.summariesRetentionDays??DEFAULT_SUMMARIES_RETENTION_DAYS,before=dryRun?await countStaleSummaries(projectRoot,retentionDays,now2):0;if(dryRun){if(before>0)result.pruned["summaries-retention"]=before}else{let deleted=await cleanupSummaries(projectRoot,retentionDays,{now:now2});if(deleted.length>0)result.pruned["summaries-retention"]=deleted.length}}catch(error93){result.errors["summaries-retention"]=error93 instanceof Error?error93.message:String(error93)}if(Object.keys(result.errors).length>0)log("retention sweep: per-family failures (non-fatal)",result.errors);return result}async function candidateIsTerminal(candidateDir2){let ledger=await readTailJsonlDetailed(path161.join(candidateDir2,"lifecycle.jsonl"),{maxEntries:1,maxBytes:65536});if(!ledger.tailTruncated){let last=ledger.records[ledger.records.length-1];if(last){let state2=last.toState??last.type??"";if(isTerminal2(state2))return!0}}try{let stateJson=JSON.parse(await fs97.promises.readFile(path161.join(candidateDir2,"state.json"),"utf-8"));if(isTerminal2(stateJson.state??null))return!0}catch{}return!1}async function pruneEvolutionCandidates(evolutionRoot,now2,dryRun){let pruned=0,skillDirs=await fs97.promises.readdir(evolutionRoot).catch(()=>[]);for(let skillSlug of skillDirs){let skillDir=path161.join(evolutionRoot,skillSlug);if(!await isRealDirectory(skillDir))continue;let candidates=await fs97.promises.readdir(skillDir).catch(()=>[]);for(let candidateId of candidates){let candidateDir2=path161.join(skillDir,candidateId),stat16=await fs97.promises.stat(candidateDir2).catch(()=>null);if(!stat16||!stat16.isDirectory())continue;let newest=subtreeNewestFileMtime(candidateDir2,SUBTREE_SCAN_CAP),effectiveMtime=newest===null?stat16.mtimeMs:newest;if(effectiveMtime>now2)continue;let ageMs=now2-effectiveMtime;if(!(await candidateIsTerminal(candidateDir2)&&ageMs>DEFAULT_FAMILY_AGE_DAYS*DAY_MS2||ageMs>EVOLUTION_BACKSTOP_AGE_DAYS*DAY_MS2))continue;if(!dryRun)fs97.rmSync(candidateDir2,{recursive:!0,force:!0});pruned+=1}}return pruned}async function walkEvolution(root,visit){let entries=await fs97.promises.readdir(root).catch(()=>[]);for(let name of entries){let entryPath=path161.join(root,name),stat16=await fs97.promises.lstat(entryPath).catch(()=>null);if(!stat16||stat16.isSymbolicLink())continue;if(stat16.isDirectory())await walkEvolution(entryPath,visit);await visit(entryPath,stat16)}}async function readDirectoryNamesBounded(directory,cap){let handle;try{handle=await fs97.promises.opendir(directory)}catch{return null}let names=[];try{for(;;){let entry=await handle.read();if(!entry)return names;if(names.length>=cap)return null;names.push(entry.name)}}catch{return null}finally{try{await handle.close()}catch{}}}async function prunePrWorkflowCheckoutTemps(root,now2,dryRun){let sessionNames=await readDirectoryNamesBounded(root,PR_WORKFLOW_CHECKOUT_SESSION_SCAN_CAP);if(!sessionNames)return 0;let cutoff=now2-DEFAULT_FAMILY_AGE_DAYS*DAY_MS2,pruned=0;for(let sessionName of sessionNames){if(!PR_WORKFLOW_CHECKOUT_SESSION_NAME.test(sessionName))continue;let sessionPath=path161.join(root,sessionName),sessionStat=await fs97.promises.lstat(sessionPath).catch(()=>null);if(!sessionStat||sessionStat.isSymbolicLink()||!sessionStat.isDirectory())continue;let entryNames=await readDirectoryNamesBounded(sessionPath,PR_WORKFLOW_CHECKOUT_ENTRY_SCAN_CAP);if(!entryNames)continue;for(let entryName of entryNames){if(!PR_WORKFLOW_CHECKOUT_TEMP_NAME.test(entryName))continue;let entryPath=path161.join(sessionPath,entryName),stat16=await fs97.promises.lstat(entryPath).catch(()=>null);if(!stat16||stat16.isSymbolicLink()||!stat16.isFile())continue;if(stat16.mtimeMs>now2||stat16.mtimeMs>=cutoff)continue;if(dryRun){pruned+=1;continue}try{await fs97.promises.unlink(entryPath),pruned+=1}catch{}}}return pruned}async function readBoundedCheckoutReceipt(receiptPath){let stat16=await fs97.promises.lstat(receiptPath).catch(()=>null);if(!stat16||stat16.isSymbolicLink()||!stat16.isFile())return null;let handle;try{handle=await fs97.promises.open(receiptPath,"r")}catch{return null}try{let buffer=new Uint8Array(PR_WORKFLOW_CHECKOUT_RECEIPT_BYTES+1),{bytesRead}=await handle.read(buffer,0,buffer.length,0);if(bytesRead>PR_WORKFLOW_CHECKOUT_RECEIPT_BYTES)return null;let value;try{value=JSON.parse(new TextDecoder().decode(buffer.subarray(0,bytesRead)))}catch{return null}if(!value||typeof value!=="object"||Array.isArray(value))return null;return{value,mtimeMs:stat16.mtimeMs}}finally{try{await handle.close()}catch{}}}function isStrictlyValidatedAppliedCheckoutReceipt(value,stashOid,sessionStem){if(value.schemaVersion!==1||typeof value.sessionID!=="string"||value.sessionID.length===0||prWorkflowSessionFileStem(value.sessionID)!==sessionStem||typeof value.stashOid!=="string"||value.stashOid.toLowerCase()!==stashOid.toLowerCase()||!Array.isArray(value.paths)||value.paths.length>64||value.paths.some((entry)=>typeof entry!=="string"||entry.length===0||entry.length>4096)||typeof value.preparedAt!=="string"||value.preparedAt.length===0||value.preparedAt.length>64||value.mode!=="PR_REVIEW"&&value.mode!=="PR_FEEDBACK"||!Number.isInteger(value.gateRevision)||value.gateRevision<0||typeof value.gateActivatedAt!=="string"||value.gateActivatedAt.length===0||value.gateActivatedAt.length>64||typeof value.originalHead!=="string"||!/^[0-9a-f]{40,64}$/i.test(value.originalHead)||value.originalBranch!==null&&(typeof value.originalBranch!=="string"||value.originalBranch.length===0||value.originalBranch.length>240||value.originalBranch.startsWith("-")||value.originalBranch.startsWith("/")||value.originalBranch.endsWith("/")||value.originalBranch.endsWith(".")||value.originalBranch.endsWith(".lock")||value.originalBranch.includes("..")||value.originalBranch.includes("@{")||value.originalBranch.includes("//")||/[\s~^:?*[\]\\]/.test(value.originalBranch)||containsControlChars(value.originalBranch))||value.restoreState!=="applied"||typeof value.restoreAppliedAt!=="string"||value.restoreAppliedAt.length===0||value.restoreAppliedAt.length>64||typeof value.restoreVerifiedAt!=="string"||value.restoreVerifiedAt.length===0||value.restoreVerifiedAt.length>64||typeof value.restoredHead!=="string"||!/^[0-9a-f]{40,64}$/i.test(value.restoredHead)||value.restoredBranch!==null&&(typeof value.restoredBranch!=="string"||value.restoredBranch.length===0||value.restoredBranch.length>240||value.restoredBranch.startsWith("-")||value.restoredBranch.startsWith("/")||value.restoredBranch.endsWith("/")||value.restoredBranch.endsWith(".")||value.restoredBranch.endsWith(".lock")||value.restoredBranch.includes("..")||value.restoredBranch.includes("@{")||value.restoredBranch.includes("//")||/[\s~^:?*[\]\\]/.test(value.restoredBranch)||containsControlChars(value.restoredBranch)))return!1;return!0}async function prunePrWorkflowCheckoutReceipts(root,now2,dryRun){let sessionNames=await readDirectoryNamesBounded(root,PR_WORKFLOW_CHECKOUT_SESSION_SCAN_CAP);if(!sessionNames)return 0;let cutoff=now2-DEFAULT_FAMILY_AGE_DAYS*DAY_MS2,pruned=0;for(let sessionName of sessionNames){if(!PR_WORKFLOW_CHECKOUT_SESSION_NAME.test(sessionName))continue;let sessionPath=path161.join(root,sessionName),sessionStat=await fs97.promises.lstat(sessionPath).catch(()=>null);if(!sessionStat||sessionStat.isSymbolicLink()||!sessionStat.isDirectory())continue;let entryNames=await readDirectoryNamesBounded(sessionPath,PR_WORKFLOW_CHECKOUT_ENTRY_SCAN_CAP);if(!entryNames)continue;for(let entryName of entryNames){if(!PR_WORKFLOW_CHECKOUT_RECEIPT_NAME.test(entryName))continue;let receiptPath=path161.join(sessionPath,entryName),receipt=await readBoundedCheckoutReceipt(receiptPath);if(!receipt||!isStrictlyValidatedAppliedCheckoutReceipt(receipt.value,entryName.slice(0,-5),sessionName))continue;let verifiedAt=Date.parse(receipt.value.restoreVerifiedAt);if(!Number.isFinite(verifiedAt)||verifiedAt>now2||verifiedAt>=cutoff)continue;if(dryRun){pruned+=1;continue}let beforeDelete=await fs97.promises.lstat(receiptPath).catch(()=>null);if(!beforeDelete||beforeDelete.isSymbolicLink()||!beforeDelete.isFile()||beforeDelete.mtimeMs!==receipt.mtimeMs)continue;try{await fs97.promises.unlink(receiptPath),pruned+=1}catch{}}}return pruned}async function prunePrWorkflowCheckoutArtifacts(root,now2,dryRun){return{temps:await prunePrWorkflowCheckoutTemps(root,now2,dryRun),receipts:await prunePrWorkflowCheckoutReceipts(root,now2,dryRun)}}async function isRealDirectory(dir){try{let stat16=fs97.lstatSync(dir);return stat16.isDirectory()&&!stat16.isSymbolicLink()}catch{return!1}}async function countStaleSummaries(projectRoot,retentionDays,now2){return(await listStaleSummaryIds(projectRoot,retentionDays,{now:now2})).length}var DAY_MS2=86400000,DEFAULT_FAMILY_AGE_DAYS=30,DEFAULT_SUMMARIES_RETENTION_DAYS=7,EVOLUTION_BACKSTOP_AGE_DAYS=90,PR_REVIEW_KEEP_NEWEST_RUNS=50,LANE_RESULTS_KEEP_NEWEST_BATCHES=100,REVIEW_RECEIPTS_KEEP_NEWEST=1000,LEGACY_LEDGER_ARCHIVES_KEEP_NEWEST=16,PR_WORKFLOW_GATE_STATE_STEM="[A-Za-z0-9_.-]+-[0-9a-f]{12}",PR_WORKFLOW_GATE_STATE_NAME,PR_WORKFLOW_GATE_SIDECAR_NAME,PR_WORKFLOW_CHECKOUT_SESSION_NAME,PR_WORKFLOW_CHECKOUT_TEMP_NAME,PR_WORKFLOW_CHECKOUT_RECEIPT_NAME,PR_WORKFLOW_CHECKOUT_SESSION_SCAN_CAP=256,PR_WORKFLOW_CHECKOUT_ENTRY_SCAN_CAP=64,PR_WORKFLOW_CHECKOUT_RECEIPT_BYTES=65536,isPrWorkflowGateStateProjection=(name,stat16)=>stat16.isFile()&&PR_WORKFLOW_GATE_STATE_NAME.test(name),isPrWorkflowGateSidecar=(name,stat16)=>stat16.isFile()&&PR_WORKFLOW_GATE_SIDECAR_NAME.test(name),isPrReviewRunArtifact=(_name,stat16)=>stat16.isDirectory(),isPrReviewRouteReceipt=(name,stat16)=>stat16.isFile()&&(/^[A-Za-z0-9_.~=-]+--[A-Za-z0-9_.~=-]+\.json$/.test(name)||/^sha256_[a-f0-9]{64}\.json$/.test(name));var init_sweep=__esm(()=>{init_review_receipt();init_persistence();init_lifecycle2();init_manager3();init_logger();init_path_security();init_dir_prune();init_jsonl_cap();PR_WORKFLOW_GATE_STATE_NAME=new RegExp(`^${PR_WORKFLOW_GATE_STATE_STEM}\\.json$`),PR_WORKFLOW_GATE_SIDECAR_NAME=new RegExp(`^${PR_WORKFLOW_GATE_STATE_STEM}\\.json(?:\\.imported(?:\\.[0-9]+)?|\\.sqlite-projection)$`),PR_WORKFLOW_CHECKOUT_SESSION_NAME=/^[A-Za-z0-9_.-]+-[0-9a-f]{12}$/,PR_WORKFLOW_CHECKOUT_TEMP_NAME=/^[0-9a-f]{40,64}\.json\.tmp\.[0-9]+\.[0-9a-f-]{36}$/i,PR_WORKFLOW_CHECKOUT_RECEIPT_NAME=/^[0-9a-f]{40,64}\.json$/i});import*as fsSync16 from"node:fs";import path162 from"node:path";function emptyFile(){return{version:1,entries:[]}}function readRestartReconciliation(directory){let filePath=path162.join(directory,".swarm",RESTART_RECONCILIATION_FILE),raw;try{raw=fsSync16.readFileSync(filePath,"utf8")}catch{return emptyFile()}try{let parsed=JSON.parse(raw);if(!parsed||parsed.version!==1||!Array.isArray(parsed.entries))return emptyFile();let entries=[];for(let entry of parsed.entries){if(!entry||typeof entry.sessionId!=="string"||typeof entry.agentName!=="string"||typeof entry.taskId!=="string"||typeof entry.observedAt!=="string"||typeof entry.guidance!=="string"||entry.classification!=="interrupted")continue;entries.push({sessionId:entry.sessionId,agentName:entry.agentName,taskId:entry.taskId,classification:"interrupted",observedAt:entry.observedAt,guidance:entry.guidance})}return{version:1,entries}}catch{return emptyFile()}}async function recordInterruptedExecution(directory,entry){let full={classification:"interrupted",observedAt:entry.observedAt??new Date().toISOString(),guidance:entry.guidance??RESTART_RECONCILIATION_GUIDANCE,sessionId:entry.sessionId,agentName:entry.agentName,taskId:entry.taskId},withoutDuplicate=readRestartReconciliation(directory).entries.filter((existing)=>!(existing.sessionId===full.sessionId&&existing.taskId===full.taskId)),entries=[full,...withoutDuplicate].slice(0,MAX_RESTART_RECONCILIATION_ENTRIES),filePath=path162.join(directory,".swarm",RESTART_RECONCILIATION_FILE);try{await bunWrite(filePath,`${JSON.stringify({version:1,entries},null,2)}
|
|
1538
|
-
`)}catch(err){warn(`[restart-reconciliation] failed to persist reconciliation artifact for session "${full.sessionId}" (task ${full.taskId}): ${err instanceof Error?err.message:String(err)}`)}return full}function buildInterruptedAdvisoryDedupeKey(entry){return`[restart-reconciliation:${entry.sessionId}:${entry.taskId}]`}function buildInterruptedAdvisoryMessage(entry){return`${buildInterruptedAdvisoryDedupeKey(entry)} [swarm] Restart reconciliation: session ${entry.sessionId} (agent ${entry.agentName}) was interrupted mid-execution on task ${entry.taskId}. `+"The outcome is UNKNOWN — do not treat absence as success. "+`${entry.guidance??RESTART_RECONCILIATION_GUIDANCE}.`}var RESTART_RECONCILIATION_FILE="session/restart-reconciliation.json",MAX_RESTART_RECONCILIATION_ENTRIES=50,RESTART_RECONCILIATION_GUIDANCE="outcome UNKNOWN — do not assume success; inspect /swarm status for uncertain provider effects; /swarm recover settles stale coder-settlement WALs; a human must resolve external effects (pushed commits, published PRs) manually";var init_restart_reconciliation=__esm(()=>{init_bun_compat();init_logger()});import{closeSync as closeSync27,existsSync as existsSync77,renameSync as fsRename,fsyncSync as fsyncSync8,mkdirSync as mkdirSync46,openSync as openSync27,unlinkSync as unlinkSync29}from"node:fs";import*as path163 from"node:path";async function renameWithTransientRetry(tempPath,targetPath,shouldCommit){let lastError,renameCommitted=()=>!existsSync77(tempPath)&&existsSync77(targetPath);for(let attempt=0;attempt<SNAPSHOT_RENAME_MAX_ATTEMPTS;attempt++){if(shouldCommit&&!shouldCommit())return!1;try{return await _internals141.rename(tempPath,targetPath,shouldCommit),renameCommitted()}catch(error93){lastError=error93;let code=error93.code;if((code==="EEXIST"||code==="EBUSY"||code==="EPERM"||code==="ENOENT"&&attempt>0)&&renameCommitted())return!0;if(code!=="EEXIST"&&code!=="EBUSY"&&code!=="EPERM")break;if(attempt<SNAPSHOT_RENAME_MAX_ATTEMPTS-1)await new Promise((resolve71)=>setTimeout(resolve71,SNAPSHOT_RENAME_RETRY_DELAY_MS))}}throw lastError}function serializeAgentSession(s){let gateLog={},rawGateLog=s.gateLog??new Map;for(let[taskId,gates]of rawGateLog)gateLog[taskId]=Array.from(gates??[]);let reviewerCallCount={},rawReviewerCallCount=s.reviewerCallCount??new Map;for(let[phase,count3]of rawReviewerCallCount)reviewerCallCount[String(phase)]=count3;let partialGateWarningsIssuedForTask=Array.from(s.partialGateWarningsIssuedForTask??new Set),completionGateWarnedForTask=Array.from(s.completionGateWarnedForTask??new Set),catastrophicPhaseWarnings=Array.from(s.catastrophicPhaseWarnings??new Set),phaseAgentsDispatched=Array.from(s.phaseAgentsDispatched??new Set),lastCompletedPhaseAgentsDispatched=Array.from(s.lastCompletedPhaseAgentsDispatched??new Set),stageBCompletion={};if(s.stageBCompletion)for(let[taskId,agents]of s.stageBCompletion)stageBCompletion[taskId]=Array.from(agents);let stageBRouteRequiredTasks=Array.from(s.stageBRouteRequiredTasks??[]),modifiedFilesByTask=Object.create(null);for(let[taskId,files]of s.modifiedFilesByTask??new Map)modifiedFilesByTask[taskId]=[...files];let windows={},rawWindows=s.windows??{};for(let[key2,win]of Object.entries(rawWindows))windows[key2]={id:win.id,agentName:win.agentName,startedAtMs:win.startedAtMs,toolCalls:win.toolCalls,consecutiveErrors:win.consecutiveErrors,hardLimitHit:win.hardLimitHit,lastSuccessTimeMs:win.lastSuccessTimeMs,recentToolCalls:win.recentToolCalls,warningIssued:win.warningIssued,warningReason:win.warningReason,transientRetryCount:win.transientRetryCount??0};return{agentName:s.agentName,lastToolCallTime:s.lastToolCallTime,lastAgentEventTime:s.lastAgentEventTime,delegationActive:s.delegationActive,activeInvocationId:s.activeInvocationId,lastInvocationIdByAgent:s.lastInvocationIdByAgent??{},windows,lastCompactionHint:s.lastCompactionHint??0,architectWriteCount:s.architectWriteCount??0,lastCoderDelegationTaskId:s.lastCoderDelegationTaskId??null,currentTaskId:s.currentTaskId??null,turboMode:s.turboMode??!1,...s.turboStrategy!==void 0&&{turboStrategy:s.turboStrategy},leanTurboActive:s.leanTurboActive??!1,...s.leanTurboCurrentPhase!==void 0&&{leanTurboCurrentPhase:s.leanTurboCurrentPhase},epicModeActive:!1,gateLog,reviewerCallCount,lastGateFailure:s.lastGateFailure??null,partialGateWarningsIssuedForTask,completionGateWarnedForTask,selfFixAttempted:s.selfFixAttempted??!1,selfCodingWarnedAtCount:s.selfCodingWarnedAtCount??0,catastrophicPhaseWarnings,lastPhaseCompleteTimestamp:s.lastPhaseCompleteTimestamp??0,lastPhaseCompletePhase:s.lastPhaseCompletePhase??0,phaseAgentsDispatched,lastCompletedPhaseAgentsDispatched,qaSkipCount:s.qaSkipCount??0,qaSkipTaskIds:s.qaSkipTaskIds??[],pendingAdvisoryMessages:s.pendingAdvisoryMessages??[],taskWorkflowStates:Object.fromEntries(s.taskWorkflowStates??new Map),...Object.keys(modifiedFilesByTask).length>0&&{modifiedFilesByTask},...s.scopeViolationDetected!==void 0&&{scopeViolationDetected:s.scopeViolationDetected},model_fallback_index:s.model_fallback_index??0,modelFallbackExhausted:s.modelFallbackExhausted??!1,coderRevisions:s.coderRevisions??0,revisionLimitHit:s.revisionLimitHit??!1,fullAutoMode:s.fullAutoMode??!1,fullAutoInteractionCount:s.fullAutoInteractionCount??0,fullAutoDeadlockCount:s.fullAutoDeadlockCount??0,fullAutoLastQuestionHash:s.fullAutoLastQuestionHash??null,sessionRehydratedAt:s.sessionRehydratedAt??0,...Object.keys(stageBCompletion).length>0&&{stageBCompletion},...stageBRouteRequiredTasks.length>0&&{stageBRouteRequiredTasks},...s.maxConcurrencyOverride!==void 0&&{maxConcurrencyOverride:s.maxConcurrencyOverride},...s.autoProceedOverride!==void 0&&{autoProceedOverride:s.autoProceedOverride},...s.autoProceedNudgeDone!==void 0&&{autoProceedNudgeDone:s.autoProceedNudgeDone},...s.cachedCohortId!==void 0&&{cachedCohortId:s.cachedCohortId},...s.lastObservedModel!==void 0&&{lastObservedModel:s.lastObservedModel},...s.lastObservedProviderID!==void 0&&{lastObservedProviderID:s.lastObservedProviderID}}}async function writeSnapshot2(directory,state2){try{let{ensureSnapshotCoordinationReady}=await Promise.resolve().then(() => (init_snapshot_coordination_init(),exports_snapshot_coordination_init));await ensureSnapshotCoordinationReady(directory);let snapshot={version:3,writtenAt:Date.now(),workflowSchema:TASK_WORKFLOW_SCHEMA_MARKER,toolAggregates:Object.fromEntries(state2.toolAggregates),activeAgent:Object.fromEntries([...state2.activeAgent].filter(([sessionId])=>isSnapshotSessionOwnedLocally(sessionId))),delegationChains:Object.fromEntries([...state2.delegationChains].filter(([sessionId])=>isSnapshotSessionOwnedLocally(sessionId))),agentSessions:{}};for(let[sessionId,sessionState]of state2.agentSessions){if(!isSnapshotSessionOwnedLocally(sessionId))continue;snapshot.agentSessions[sessionId]=serializeAgentSession(sessionState)}writeSnapshotRows(directory,snapshot,{onlyLocallyOwnedSessions:!0});let canonicalSnapshot=readSnapshotRows(directory)??snapshot;await writeSnapshotProjection(directory,canonicalSnapshot)}catch(error93){log("[snapshot-writer] write failed",{error:error93 instanceof Error?error93.message:String(error93)})}}async function writeSnapshotProjection(directory,snapshot,shouldCommit){let content=JSON.stringify(snapshot,null,2),resolvedPath=validateSwarmPath(directory,SNAPSHOT_PROJECTION_FILE),dir=path163.dirname(resolvedPath);mkdirSync46(dir,{recursive:!0});let tempPath=`${resolvedPath}.tmp.${Date.now()}.${Math.random().toString(36).slice(2)}`;try{await bunWrite(tempPath,content);try{let fd=openSync27(tempPath,"r+");try{fsyncSync8(fd)}finally{closeSync27(fd)}}catch{}if(!await renameWithTransientRetry(tempPath,resolvedPath,shouldCommit))return;invalidateCachedArtifact(resolvedPath)}finally{try{unlinkSync29(tempPath)}catch{}}}function createSnapshotWriterHook(directory){return(_input,_output)=>{return _writeInFlight=_writeInFlight.then(()=>_internals141.writeSnapshot(directory,swarmState),()=>_internals141.writeSnapshot(directory,swarmState)),_writeInFlight}}async function flushPendingSnapshot(directory){_writeInFlight=_writeInFlight.then(()=>_internals141.writeSnapshot(directory,swarmState),()=>_internals141.writeSnapshot(directory,swarmState)),await _writeInFlight}var SNAPSHOT_PROJECTION_FILE="session/state.sqlite-projection.json",_writeInFlight,SNAPSHOT_RENAME_MAX_ATTEMPTS=3,SNAPSHOT_RENAME_RETRY_DELAY_MS=50,_internals141;var init_snapshot_writer=__esm(()=>{init_gate_evidence();init_utils2();init_state();init_utils();init_bun_compat();init_swarm_artifact_cache();init_snapshot_store();_writeInFlight=Promise.resolve();_internals141={writeSnapshot:writeSnapshot2,createSnapshotWriterHook,flushPendingSnapshot,rename:fsRename}});import{renameSync as renameSync27}from"node:fs";function deserializeTaskWorkflowStates(raw){let m=new Map;if(!raw||typeof raw!=="object")return m;for(let[taskId,stateVal]of Object.entries(raw))if(VALID_TASK_WORKFLOW_STATES.includes(stateVal))m.set(taskId,stateVal);return m}function deserializeModifiedFilesByTask(raw){let entries=new Map;if(!raw||typeof raw!=="object")return entries;let serializedEntries=Object.entries(raw);if(serializedEntries.length>MAX_TRACKED_TASK_FILE_ATTRIBUTIONS)return entries;for(let[taskId,files]of serializedEntries){if(!taskId.trim()||!Array.isArray(files))continue;let validFiles=files.filter((file3)=>typeof file3==="string"&&file3.length>0);entries.set(taskId,[...new Set(validFiles)])}return entries}function deserializeAgentSession(s){let lastGateFailure=s.lastGateFailure?{tool:s.lastGateFailure.tool,taskId:s.lastGateFailure.taskId,timestamp:s.lastGateFailure.timestamp,...typeof s.lastGateFailure.code==="string"&&/^[A-Z][A-Z0-9_]{0,63}$/.test(s.lastGateFailure.code)&&{code:s.lastGateFailure.code}}:null,taskWorkflowStates=deserializeTaskWorkflowStates(s.taskWorkflowStates),modifiedFilesByTask=deserializeModifiedFilesByTask(s.modifiedFilesByTask),gateLog=new Map;if(s.gateLog)for(let[taskId,gates]of Object.entries(s.gateLog))gateLog.set(taskId,new Set(gates??[]));let reviewerCallCount=new Map;if(s.reviewerCallCount)for(let[phase,count3]of Object.entries(s.reviewerCallCount)){let numPhase=Number(phase);if(Number.isFinite(numPhase))reviewerCallCount.set(numPhase,count3)}let partialGateWarningsIssuedForTask=new Set(s.partialGateWarningsIssuedForTask??[]),completionGateWarnedForTask=new Set(s.completionGateWarnedForTask??[]),catastrophicPhaseWarnings=new Set(s.catastrophicPhaseWarnings??[]),phaseAgentsDispatched=new Set(s.phaseAgentsDispatched??[]),lastCompletedPhaseAgentsDispatched=new Set(s.lastCompletedPhaseAgentsDispatched??[]),stageBCompletion=new Map;if(s.stageBCompletion)for(let[taskId,agents]of Object.entries(s.stageBCompletion))stageBCompletion.set(taskId,new Set(agents));let stageBRouteRequiredTasks=new Set(Array.isArray(s.stageBRouteRequiredTasks)?s.stageBRouteRequiredTasks.filter((taskId)=>typeof taskId==="string"&&taskId.length>0):[]),windows={};for(let[key2,win]of Object.entries(s.windows??{})){if(!win||typeof win!=="object")continue;windows[key2]={...win,transientRetryCount:"transientRetryCount"in win?win.transientRetryCount??0:0}}return{agentName:s.agentName,lastToolCallTime:s.lastToolCallTime,lastAgentEventTime:s.lastAgentEventTime,delegationActive:s.delegationActive,activeInvocationId:s.activeInvocationId,lastInvocationIdByAgent:s.lastInvocationIdByAgent??{},windows,lastCompactionHint:s.lastCompactionHint??0,architectWriteCount:s.architectWriteCount??0,lastCoderDelegationTaskId:s.lastCoderDelegationTaskId??null,currentTaskId:s.currentTaskId??null,turboMode:s.turboMode??!1,turboStrategy:s.turboStrategy==="lean"||s.turboStrategy==="standard"?s.turboStrategy:void 0,leanTurboActive:s.leanTurboActive??!1,leanTurboCurrentPhase:typeof s.leanTurboCurrentPhase==="number"?s.leanTurboCurrentPhase:void 0,gateLog,reviewerCallCount,lastGateFailure,partialGateWarningsIssuedForTask,completionGateWarnedForTask,selfFixAttempted:s.selfFixAttempted??!1,selfCodingWarnedAtCount:s.selfCodingWarnedAtCount??0,catastrophicPhaseWarnings,lastPhaseCompleteTimestamp:s.lastPhaseCompleteTimestamp??0,lastPhaseCompletePhase:s.lastPhaseCompletePhase??0,phaseAgentsDispatched,lastCompletedPhaseAgentsDispatched,qaSkipCount:s.qaSkipCount??0,qaSkipTaskIds:s.qaSkipTaskIds??[],taskWorkflowStates,lastGateOutcome:null,declaredCoderScope:null,lastScopeViolation:null,scopeViolationDetected:s.scopeViolationDetected,modifiedFilesByTask,modifiedFilesThisCoderTask:s.currentTaskId&&s.currentTaskId.trim()!==""&&modifiedFilesByTask.has(s.currentTaskId)?[...modifiedFilesByTask.get(s.currentTaskId)??[]]:[],loopDetectionWindow:[],pendingAdvisoryMessages:s.pendingAdvisoryMessages??[],model_fallback_index:s.model_fallback_index??0,modelFallbackExhausted:s.modelFallbackExhausted??!1,coderRevisions:s.coderRevisions??0,revisionLimitHit:s.revisionLimitHit??!1,fullAutoMode:s.fullAutoMode??!1,fullAutoInteractionCount:s.fullAutoInteractionCount??0,fullAutoDeadlockCount:s.fullAutoDeadlockCount??0,fullAutoLastQuestionHash:s.fullAutoLastQuestionHash??null,maxConcurrencyOverride:typeof s.maxConcurrencyOverride==="number"?Math.min(64,Math.max(1,s.maxConcurrencyOverride)):void 0,autoProceedOverride:s.autoProceedOverride,autoProceedNudgeDone:s.autoProceedNudgeDone,prmPatternCounts:new Map,prmEscalationLevel:0,prmLastPatternDetected:null,prmTrajectoryStep:0,prmHardStopPending:!1,prmHardStopInjectPending:!1,prmInjectedAdvisoryKeys:new Set,prmStruckEpisodes:new Map,prmLadderCounts:new Map,executionEpisodeArmed:!1,sessionRehydratedAt:s.sessionRehydratedAt??0,stageBCompletion,stageBRouteRequiredTasks,prSubscriptions:new Map,cachedCohortId:typeof s.cachedCohortId==="string"?s.cachedCohortId:void 0,lastObservedModel:typeof s.lastObservedModel==="string"?s.lastObservedModel:void 0,lastObservedProviderID:typeof s.lastObservedProviderID==="string"?s.lastObservedProviderID:void 0}}async function readSnapshot(directory){for(let relativePath2 of[SNAPSHOT_PROJECTION_FILE,"session/state.json"])try{let resolvedPath=validateSwarmPath(directory,relativePath2),content=await bunFile(resolvedPath).text();if(!content.trim())continue;let parsed=JSON.parse(content,(key2,value)=>{if(key2==="__proto__"||key2==="constructor")return;return value});if(parsed.version!==1&&parsed.version!==2&&parsed.version!==3){try{let quarantinePath=validateSwarmPath(directory,`${relativePath2}.quarantine`);renameSync27(resolvedPath,quarantinePath)}catch{}continue}return parsed}catch{}return null}async function readSnapshotFileStrict(directory,relativePath2){let resolvedPath=validateSwarmPath(directory,relativePath2),content=await bunFile(resolvedPath).text();if(!content.trim())throw Error(`snapshot ${relativePath2} is empty`);let parsed=JSON.parse(content,(key2,value)=>{if(key2==="__proto__"||key2==="constructor")return;return value});if(parsed.version!==1&&parsed.version!==2&&parsed.version!==3)throw Error(`snapshot ${relativePath2} has an unsupported version`);if(!parsed.toolAggregates||!parsed.activeAgent||!parsed.delegationChains||!parsed.agentSessions)throw Error(`snapshot ${relativePath2} has an invalid shape`);return parsed}async function rehydrateState(snapshot,directory,scope){if(!directory)return await rehydrateStateGlobal(snapshot),{applied:!0};let projectKey=hydrationProjectKey(directory),authority=scope??captureCurrentHydrationAuthority(projectKey),generation=authority.generation,isCurrentAuthoritySession=(session)=>session.owningProjectKey===projectKey&&session.hydrationAuthorityEpoch===authority.authorityEpoch;if(scope&&!isHydrationAuthorityCurrent(scope))return log(`[snapshot-reader] Refusing superseded hydration generation ${scope.generation} for ${projectKey}`),{applied:!1,reason:"superseded"};if(swarmState.pendingRehydrations.size>0)await Promise.allSettled([...swarmState.pendingRehydrations]);if(!isHydrationAuthorityCurrent(authority))return log(`[snapshot-reader] Refusing superseded hydration generation ${generation} for ${projectKey} after waiting for pending rehydrations`),{applied:!1,reason:"superseded"};let isProtectedLiveSession=(sessionId)=>{let live=swarmState.agentSessions.get(sessionId);return live!==void 0&&isCurrentAuthoritySession(live)&&(live.hydrationStamp??0)>generation},interruptedReconciliations=new Map;if(directory&&snapshot.agentSessions)for(let[sessionId,serializedSession]of Object.entries(snapshot.agentSessions)){if(isProtectedLiveSession(sessionId)||!serializedSession||typeof serializedSession!=="object"||typeof serializedSession.agentName!=="string"||typeof serializedSession.lastToolCallTime!=="number"||serializedSession.delegationActive!==!0)continue;let entry={sessionId,agentName:serializedSession.agentName,taskId:serializedSession.currentTaskId||"(unknown)"};try{let recorded=await _internals142.recordInterruptedExecution(directory,entry);interruptedReconciliations.set(sessionId,{entry,guidance:recorded.guidance})}catch(error93){log(`[snapshot-reader] restart reconciliation failed for session ${sessionId}: ${error93 instanceof Error?error93.message:String(error93)}`)}}if(!isHydrationAuthorityCurrent(authority))return log(`[snapshot-reader] Refusing superseded hydration generation ${generation} for ${projectKey} after restart reconciliation preflight`),{applied:!1,reason:"superseded"};for(let[sessionId,session]of swarmState.agentSessions)if(session.owningProjectKey===projectKey&&(!isCurrentAuthoritySession(session)||(session.hydrationStamp??0)<=generation))swarmState.agentSessions.delete(sessionId),swarmState.activeAgent.delete(sessionId),swarmState.delegationChains.delete(sessionId);let ownAggregateKeys=hydratedAggregateKeysFor(projectKey,authority),snapshotAggregateKeys=new Set(Object.keys(snapshot.toolAggregates??{}));for(let key2 of ownAggregateKeys)if(!snapshotAggregateKeys.has(key2))swarmState.toolAggregates.delete(key2);for(let[key2,value]of Object.entries(snapshot.toolAggregates??{}))swarmState.toolAggregates.set(key2,value);recordHydratedAggregateKeys(projectKey,snapshotAggregateKeys,authority);let now2=Date.now(),epicOpenForRehydration;if(snapshot.agentSessions)for(let[sessionId,serializedSession]of Object.entries(snapshot.agentSessions)){if(isProtectedLiveSession(sessionId))continue;if(!serializedSession||typeof serializedSession!=="object"||typeof serializedSession.agentName!=="string"||typeof serializedSession.lastToolCallTime!=="number"||typeof serializedSession.delegationActive!=="boolean"){log(`[snapshot-reader] Skipping malformed session ${sessionId}: missing required fields (agentName, lastToolCallTime, delegationActive)`);continue}let session=deserializeAgentSession(serializedSession);if(session.taskWorkflowStates=new Map,session.taskWorkflowCache=new Map,session.stageBCompletion=new Map,session.owningProjectKey=projectKey,session.hydrationStamp=generation,session.hydrationAuthorityEpoch=authority.authorityEpoch,session.lastToolCallTime=now2,session.lastAgentEventTime=now2,session.sessionRehydratedAt=now2,session.windows)for(let window2 of Object.values(session.windows))window2.startedAtMs=now2,window2.lastSuccessTimeMs=now2,window2.hardLimitHit=!1,window2.toolCalls=0,window2.consecutiveErrors=0,window2.recentToolCalls=[],window2.warningIssued=!1,window2.warningReason="";for(let field of TRANSIENT_SESSION_FIELDS){let reset=field.resetValue;session[field.name]=Array.isArray(reset)?[...reset]:reset}if(directory)try{let durableOverrides=getOverrideForSession(directory,sessionId);if(Object.keys(durableOverrides).length>0)session.qaGateSessionOverrides=durableOverrides}catch(error93){log(`[snapshot-reader] override restore failed for session ${sessionId}: ${error93 instanceof Error?error93.message:String(error93)}`)}let reconciliation=interruptedReconciliations.get(sessionId);if(reconciliation)pushAdvisory(session,buildInterruptedAdvisoryMessage({...reconciliation.entry,guidance:reconciliation.guidance}),{dedupeKey:buildInterruptedAdvisoryDedupeKey(reconciliation.entry)});if(session.fullAutoMode){let runStillActive=!1;if(directory)try{runStillActive=loadFullAutoRunState(directory,sessionId)?.status==="running"}catch{runStillActive=!1}if(!runStillActive)session.fullAutoMode=!1}if(session.turboMode===!0){if(epicOpenForRehydration===void 0)epicOpenForRehydration=_internals142.isEpicOpenForProject(directory);if(epicOpenForRehydration)session.turboMode=!1}swarmState.agentSessions.set(sessionId,session)}if(snapshot.activeAgent){for(let[key2,value]of Object.entries(snapshot.activeAgent))if(swarmState.agentSessions.has(key2)&&!isProtectedLiveSession(key2))swarmState.activeAgent.set(key2,value)}if(snapshot.delegationChains){for(let[key2,value]of Object.entries(snapshot.delegationChains))if(swarmState.agentSessions.has(key2)&&!isProtectedLiveSession(key2))swarmState.delegationChains.set(key2,value)}if(directory)try{let keep=new Set;for(let sessionId of Object.keys(snapshot.agentSessions??{}))keep.add(sessionId);for(let[sessionId,live]of swarmState.agentSessions)if(live.owningProjectKey===projectKey)keep.add(sessionId);let removed=sweepOrphanOverrides(directory,keep);if(removed>0)log(`[snapshot-reader] pruned ${removed} orphaned QA override row(s) for ${projectKey}`)}catch(error93){log(`[snapshot-reader] override orphan reaper failed for ${projectKey}: ${error93 instanceof Error?error93.message:String(error93)}`)}return{applied:!0}}async function rehydrateStateGlobal(snapshot){if(swarmState.pendingRehydrations.size>0)await Promise.allSettled([...swarmState.pendingRehydrations]);swarmState.toolAggregates.clear(),swarmState.activeAgent.clear(),swarmState.delegationChains.clear(),swarmState.agentSessions.clear();for(let[key2,value]of Object.entries(snapshot.toolAggregates??{}))swarmState.toolAggregates.set(key2,value);let now2=Date.now();if(snapshot.agentSessions)for(let[sessionId,serializedSession]of Object.entries(snapshot.agentSessions)){if(!serializedSession||typeof serializedSession!=="object"||typeof serializedSession.agentName!=="string"||typeof serializedSession.lastToolCallTime!=="number"||typeof serializedSession.delegationActive!=="boolean"){log(`[snapshot-reader] Skipping malformed session ${sessionId}: missing required fields (agentName, lastToolCallTime, delegationActive)`);continue}let session=deserializeAgentSession(serializedSession);if(session.taskWorkflowStates=new Map,session.taskWorkflowCache=new Map,session.stageBCompletion=new Map,session.lastToolCallTime=now2,session.lastAgentEventTime=now2,session.sessionRehydratedAt=now2,session.windows)for(let window2 of Object.values(session.windows))window2.startedAtMs=now2,window2.lastSuccessTimeMs=now2,window2.hardLimitHit=!1,window2.toolCalls=0,window2.consecutiveErrors=0,window2.recentToolCalls=[],window2.warningIssued=!1,window2.warningReason="";for(let field of TRANSIENT_SESSION_FIELDS){let reset=field.resetValue;session[field.name]=Array.isArray(reset)?[...reset]:reset}if(session.fullAutoMode)session.fullAutoMode=!1;swarmState.agentSessions.set(sessionId,session)}if(snapshot.activeAgent){for(let[key2,value]of Object.entries(snapshot.activeAgent))if(swarmState.agentSessions.has(key2))swarmState.activeAgent.set(key2,value)}if(snapshot.delegationChains){for(let[key2,value]of Object.entries(snapshot.delegationChains))if(swarmState.agentSessions.has(key2))swarmState.delegationChains.set(key2,value)}}async function loadSnapshot(directory){let scope=beginHydrationScope(directory);try{if(!(await buildRehydrationCache(directory,{shouldCommit:()=>isHydrationScopeCurrent(scope)})).committed||!isHydrationScopeCurrent(scope))return;let snapshot=await readSnapshot(directory);if(snapshot!==null){if(!(await rehydrateState(snapshot,directory,scope)).applied||!isHydrationScopeCurrent(scope))return;for(let session of swarmState.agentSessions.values()){if(!isHydrationScopeCurrent(scope))return;applyRehydrationCache(session)}}}catch{}}var _internals142,TRANSIENT_SESSION_FIELDS,VALID_TASK_WORKFLOW_STATES;var init_snapshot_reader=__esm(()=>{init_qa_gate_session_override();init_lifecycle();init_state2();init_utils2();init_state();init_bun_compat();init_logger();init_hydration_ownership();init_restart_reconciliation();init_snapshot_writer();_internals142={recordInterruptedExecution,isEpicOpenForProject},TRANSIENT_SESSION_FIELDS=[{name:"revisionLimitHit",resetValue:!1},{name:"coderRevisions",resetValue:0},{name:"selfFixAttempted",resetValue:!1},{name:"lastGateFailure",resetValue:null},{name:"architectWriteCount",resetValue:0},{name:"selfCodingWarnedAtCount",resetValue:0},{name:"pendingAdvisoryMessages",resetValue:[]},{name:"model_fallback_index",resetValue:0},{name:"modelFallbackExhausted",resetValue:!1},{name:"scopeViolationDetected",resetValue:!1},{name:"delegationActive",resetValue:!1},{name:"autoProceedOverride",resetValue:void 0},{name:"autoProceedNudgeDone",resetValue:void 0}],VALID_TASK_WORKFLOW_STATES=["idle","coder_delegated","pre_check_passed","reviewer_run","tests_run","rework_required","complete","blocked","closed"]});var exports_snapshot_coordination_init={};__export(exports_snapshot_coordination_init,{startSnapshotCoordinationInitialization:()=>startSnapshotCoordinationInitialization,retrySnapshotCoordinationInitialization:()=>retrySnapshotCoordinationInitialization,markSnapshotCoordinationClosing:()=>markSnapshotCoordinationClosing,getSnapshotCoordinationStatus:()=>getSnapshotCoordinationStatus,ensureSnapshotCoordinationReady:()=>ensureSnapshotCoordinationReady,closeSnapshotCoordinationInitialization:()=>closeSnapshotCoordinationInitialization,beginSnapshotCoordinationReset:()=>beginSnapshotCoordinationReset,_snapshotCoordinationInternals:()=>_snapshotCoordinationInternals});import{createHash as createHash70,randomUUID as randomUUID22}from"node:crypto";import{existsSync as existsSync78,readFileSync as readFileSync59,renameSync as renameSync28}from"node:fs";function isReadinessEntryClosing(entry){return entry?.state==="closing"}function recordSupersession(trigger){supersessionStats.count+=1;try{telemetry.planRecoverySuperseded({count:supersessionStats.count,trigger})}catch{}}function isRetryableArchiveError(error93){let code=error93?.code;return code==="EBUSY"||code==="EPERM"||code==="EACCES"}async function archiveLegacySnapshotIfPresent(legacyPath,expectedSnapshot,shouldCommit=()=>!0){if(!shouldCommit())return"superseded";if(!existsSync78(legacyPath))return"not_archived";if(expectedSnapshot)try{if(JSON.stringify(JSON.parse(readFileSync59(legacyPath,"utf8")))!==JSON.stringify(expectedSnapshot))return advisoryWarn("[opencode-swarm] Legacy snapshot changed after SQLite coordination; preserving it for explicit recovery."),"not_archived"}catch{return"not_archived"}let canonicalArchive=`${legacyPath}.imported`,archivePath=existsSync78(canonicalArchive)?`${canonicalArchive}.${randomUUID22()}`:canonicalArchive,lastError;for(let attempt=1;attempt<=ARCHIVE_RETRY_ATTEMPTS;attempt+=1){if(!shouldCommit())return"superseded";try{return _snapshotCoordinationInternals.renameLegacySnapshot(legacyPath,archivePath),"archived"}catch(error93){if(lastError=error93,!isRetryableArchiveError(error93)||attempt===ARCHIVE_RETRY_ATTEMPTS)break;await new Promise((resolve71)=>setTimeout(resolve71,ARCHIVE_RETRY_DELAY_MS))}}return advisoryWarn(`[opencode-swarm] SQLite snapshot is authoritative, but the legacy shadow could not be archived: ${lastError instanceof Error?lastError.message:String(lastError)}`),"not_archived"}function evictSettledEntries(){while(entries.size>=MAX_READY_ROOTS){let victim=[...entries].find(([,entry])=>entry.settled);if(!victim)return!1;entries.delete(victim[0])}return!0}async function initializeSnapshotCoordination(directory,scope){let isCurrent=()=>scope===void 0||isHydrationScopeCurrent(scope);if(!isCurrent())return"superseded";let legacyArchiveAttempted=!1,snapshot=readSnapshotRows(directory);if(!snapshot){if(!isCurrent())return"superseded";let legacyPath=validateSwarmPath(directory,"session/state.json"),projectionPath=validateSwarmPath(directory,SNAPSHOT_PROJECTION_FILE),source=existsSync78(projectionPath)?SNAPSHOT_PROJECTION_FILE:existsSync78(legacyPath)?"session/state.json":null;if(source){if(!isCurrent())return"superseded";let candidate=await _snapshotCoordinationInternals.readSnapshotFileStrict(directory,source);if(!isCurrent())return"superseded";let serialized2=JSON.stringify(candidate),outcome=_snapshotCoordinationInternals.importSnapshotRowsOnce(directory,candidate,createHash70("sha256").update(serialized2).digest("hex"),source);if(snapshot=readSnapshotRows(directory),outcome==="imported"&&source==="session/state.json"){if(legacyArchiveAttempted=!0,await archiveLegacySnapshotIfPresent(legacyPath,candidate,isCurrent)==="superseded")return"superseded"}}}if(!isCurrent())return"superseded";if(snapshot){if(!legacyArchiveAttempted){if(await archiveLegacySnapshotIfPresent(validateSwarmPath(directory,"session/state.json"),snapshot,isCurrent)==="superseded")return"superseded"}if(!(await rehydrateState(snapshot,directory,scope)).applied||!isCurrent())return"superseded"}let authoritativePlan;try{authoritativePlan=await _snapshotCoordinationInternals.loadPlan(directory,void 0,{preCommitCheck:()=>{if(!isCurrent())throw new PlanRecoverySupersededError("Snapshot coordination initialization superseded during plan recovery")}})}catch(error93){if(error93 instanceof PlanRecoverySupersededError)throw error93;advisoryWarn(`[opencode-swarm] Authoritative plan recovery failed; retaining pre-resolution cache: ${error93 instanceof Error?error93.message:String(error93)}`.slice(0,512))}if(!isCurrent())return"superseded";if(authoritativePlan!==void 0){if(!(await buildRehydrationCache(directory,{planOverride:authoritativePlan,shouldCommit:isCurrent})).committed||!isCurrent())return"superseded"}for(let session of swarmState.agentSessions.values()){if(!isCurrent())return"superseded";applyRehydrationCache(session)}if(!snapshot||!isCurrent())return isCurrent()?"succeeded":"superseded";try{await _snapshotCoordinationInternals.writeProjection(directory,snapshot,isCurrent)}catch(error93){advisoryWarn(`[opencode-swarm] SQLite snapshot is ready, but its compatibility projection could not be written: ${error93 instanceof Error?error93.message:String(error93)}`)}return isCurrent()?"succeeded":"superseded"}function startSnapshotCoordinationInitialization(directory){let root=canonicalProjectKey(directory),existing=entries.get(root);if(existing?.state==="closing")return Promise.reject(Error("coordination initialization is closing for reset-session"));if(existing&&!existing.settled)return existing.underlying;if(existing?.state==="succeeded")return existing.underlying;if(!evictSettledEntries()){let error93=Error(`SQLite snapshot coordination capacity exhausted (${MAX_READY_ROOTS} unsettled roots)`);return advisoryWarn(`[opencode-swarm] ${error93.message}; initialization refused.`),Promise.reject(error93)}let attemptId=nextAttemptId++,generation=(existing?.generation??0)+1,scope=beginHydrationScope(root),entry={attemptId,generation,state:"running",settled:!1,underlying:Promise.resolve()},underlying=_snapshotCoordinationInternals.initialize(root,scope).then((outcome)=>{if(entries.get(root)!==entry||entry.state==="closing")return;if(outcome==="superseded"){entry.state="superseded",entry.error="coordination initialization superseded by a newer hydration generation",recordSupersession("coordination_fence");return}entry.state="succeeded"}).catch((error93)=>{if(error93 instanceof PlanRecoverySupersededError){if(entry.state!=="closing"&&entries.get(root)===entry)entry.state="superseded",entry.error=error93.message,recordSupersession("plan_recovery")}else entry.state="failed",entry.error=error93 instanceof Error?error93.message:String(error93);throw error93}).finally(()=>{entry.settled=!0});return entry.underlying=underlying,entries.set(root,entry),withTimeout(underlying,_snapshotCoordinationInternals.timeoutMs,Error("coordination initialization timed out")).catch((error93)=>{if(!entry.settled&&entry.state!=="closing"&&entries.get(root)===entry)entry.state="timed_out",entry.error=error93 instanceof Error?error93.message:String(error93),advisoryWarn("[opencode-swarm] SQLite coordination initialization is still running; authority operations remain fail-closed.")}),underlying}async function ensureSnapshotCoordinationReady(directory){let root=canonicalProjectKey(directory),entry=entries.get(root);if(entry?.state==="closing")throw Error("coordination initialization is closing for reset-session");if(entry?.state==="timed_out"&&!entry.settled)throw Error("coordination initialization remains unsettled after timeout");if(!entry||entry.state==="superseded"&&entry.settled){await startSnapshotCoordinationInitialization(root);let retried=entries.get(root);if(retried?.state==="closing")throw Error("coordination initialization is closing for reset-session");if(retried?.state!=="succeeded")throw Error(retried?.error??"coordination initialization failed");return}if(await entry.underlying,isReadinessEntryClosing(entry))throw Error("coordination initialization is closing for reset-session");if(entry.state!=="succeeded")throw Error(entry.error??"coordination initialization failed")}function retrySnapshotCoordinationInitialization(directory){let root=canonicalProjectKey(directory),entry=entries.get(root);if(entry?.state==="closing")throw Error("coordination initialization is closing for reset-session");if(entry&&!entry.settled)throw Error("coordination initialization is still unsettled; recovery refused");return entries.delete(root),startSnapshotCoordinationInitialization(root)}function getSnapshotCoordinationStatus(directory){let entry=entries.get(canonicalProjectKey(directory));if(!entry)return{state:"idle",settled:!0};return{state:entry.state,attemptId:entry.attemptId,generation:entry.generation,settled:entry.settled,...entry.error?{error:entry.error.slice(0,512)}:{}}}async function beginSnapshotCoordinationReset(directory){let root=canonicalProjectKey(directory),prior=entries.get(root),closeError,priorUnsettled=!1;if(prior){prior.state="closing";try{await withTimeout(prior.underlying,_snapshotCoordinationInternals.timeoutMs,Error("coordination initialization close timed out"))}catch(error93){if(closeError=error93 instanceof Error?error93:Error(String(error93)),priorUnsettled=!prior.settled,priorUnsettled)prior.underlying.catch(()=>{return})}}let guard={attemptId:nextAttemptId++,generation:(prior?.generation??0)+1,state:"closing",settled:!0,underlying:Promise.resolve(),...closeError?{error:closeError.message}:{}};entries.set(root,guard);let released=!1;return{release:()=>{if(released)return;released=!0;let removeGuard=()=>{if(entries.get(root)===guard)entries.delete(root)};if(!prior||prior.settled){removeGuard();return}prior.underlying.then(removeGuard,removeGuard)},...closeError?{closeError}:{},...priorUnsettled?{priorUnsettled:!0}:{}}}async function closeSnapshotCoordinationInitialization(directory){let guard=await beginSnapshotCoordinationReset(directory);try{if(guard.closeError)throw guard.closeError}finally{guard.release()}}function markSnapshotCoordinationClosing(directory){let entry=entries.get(canonicalProjectKey(directory));if(entry)entry.state="closing"}var READY_TIMEOUT_MS=1e4,MAX_READY_ROOTS=32,ARCHIVE_RETRY_ATTEMPTS=3,ARCHIVE_RETRY_DELAY_MS=25,entries,nextAttemptId=1,supersessionStats,_snapshotCoordinationInternals;var init_snapshot_coordination_init=__esm(()=>{init_canonical_project();init_utils2();init_manager();init_warning_buffer();init_state();init_telemetry();init_timeout();init_hydration_ownership();init_snapshot_reader();init_snapshot_store();init_snapshot_writer();entries=new Map,supersessionStats={count:0};_snapshotCoordinationInternals={entries,initialize:initializeSnapshotCoordination,loadPlan,readSnapshotFileStrict,importSnapshotRowsOnce,renameLegacySnapshot:renameSync28,writeProjection:writeSnapshotProjection,timeoutMs:READY_TIMEOUT_MS}});import*as fsSync17 from"node:fs";import{promises as fs98}from"node:fs";import path164 from"node:path";async function readCloseGateGit(args2,cwd){let raw=await _closeGateInternals.runGit(args2,cwd);if(typeof raw==="string")return{kind:"ok",stdout:raw};if(raw===null)return{kind:"failed",failure:{code:null,status:null,stderrTail:""}};if(raw.ok)return{kind:"ok",stdout:raw.stdout};return{kind:"failed",failure:{code:raw.code,status:raw.status,stderrTail:raw.stderrTail}}}function describeCloseGateStatusFailure(failure){if(!failure)return"The read failed without a reported cause. Inspect git status manually in that directory, then re-run /swarm close.";if(failure.code==="ETIMEDOUT")return"The git status read timed out (ETIMEDOUT): git was launched but did not answer within the deadline — the host process may be unable to complete child spawns while loaded. Restart the OpenCode host (or inspect the host runtime / security software), then re-run /swarm close.";if(failure.code==="EOUTPUT")return`The git status read exceeded its output safety bound (${failure.stderrTail}) — the working set is too large to verify in one read. Reduce the change footprint (commit or stash some work, or remove untracked bulk), then re-run /swarm close.`;if(failure.code==="ESIGNAL")return`The git process was terminated before it answered (signal)${failure.stderrTail?`: ${failure.stderrTail}`:""} — something external (a kill or resource manager) stopped it. Re-run /swarm close; if it recurs, inspect what terminates child processes in this environment.`;if(failure.code==="ENOENT")return"The git executable was not found (ENOENT). Install git on PATH, or set git.binary in your USER-level config (project-level git.binary is ignored), then re-run /swarm close.";if(failure.code!==null)return`The git status read failed to spawn (code ${failure.code}). Inspect git availability in that environment, then re-run /swarm close.`;if(failure.status!==null)return`git status exited with status ${failure.status}${failure.stderrTail?`: ${failure.stderrTail}`:""}. Repair the repository state (for example, a damaged .git/index), then re-run /swarm close.`;return"The git status read failed without a reported cause. Inspect git status manually in that directory, then re-run /swarm close."}function isRealGitRepository2(directory){try{if(fsSync17.statSync(path164.join(directory,".git")).isFile())return!0}catch{return!1}return fsSync17.existsSync(path164.join(directory,".git","HEAD"))}async function evaluateClosePurgeGate(directory,swarmDir){let statusOutput=await readCloseGateGit([...GIT_STATUS_ARGS],directory),dirtyPaths=statusOutput.kind==="ok"?parseTrackedDirtyPaths2(statusOutput.stdout):[],candidates=dirtyPaths.map((p)=>({path:path164.join(directory,p),reason:"uncommitted tracked change — discarded by git alignment"}));for(let entry of[...ACTIVE_STATE_TO_CLEAN,...ACTIVE_STATE_DIRS_TO_CLEAN]){let full=path164.join(swarmDir,entry);if(fsSync17.existsSync(full))candidates.push({path:full,reason:"active swarm state — archived then removed by close"})}return{wouldDestroyTrackedWork:dirtyPaths.length>0,dirtyPaths,candidates,scopeAnchor:candidates[0]?.path??directory,gitStatusFailed:statusOutput.kind==="failed"&&isRealGitRepository2(directory),statusFailure:statusOutput.kind==="failed"&&isRealGitRepository2(directory)?statusOutput.failure:void 0}}async function archiveCloseSummary(ctx,closeSummaryPath,summaryWritten){if(!summaryWritten||ctx.archiveStageFailed||!ctx.archiveDir)return;try{await fs98.copyFile(closeSummaryPath,path164.join(ctx.archiveDir,"close-summary.md"))}catch(error93){let msg=error93 instanceof Error?error93.message:String(error93);ctx.warnings.push(`Failed to archive close-summary.md: ${msg}`),log("[close-command] Failed to archive close-summary.md:",error93)}}async function handleCloseCommand(directory,args2,options={}){let swarmDir=path164.join(directory,".swarm");try{if(fsSync17.lstatSync(swarmDir).isSymbolicLink())return"❌ Refused: .swarm/ is a symlink or junction. Refusing to operate on a redirected directory for safety."}catch(err){if(err?.code!=="ENOENT")throw err}let planPath=validateSwarmPath(directory,"plan.json"),planExists=!1,planData={title:path164.basename(directory)||"Ad-hoc session",phases:[]};try{let content=await fs98.readFile(planPath,"utf-8");planData=JSON.parse(content),planExists=!0}catch(error93){if(error93?.code!=="ENOENT")return`❌ Failed to read plan.json: ${error93 instanceof Error?error93.message:String(error93)}`;try{let recovered=(await peekPlanFromLedger(directory)).plan;if(recovered)planData=recovered,planExists=!0}catch(recoveryError){return`❌ Failed to recover plan from the authoritative ledger: ${recoveryError instanceof Error?recoveryError.message:String(recoveryError)}`}if(!planExists){if(!await fs98.access(swarmDir).then(()=>!0).catch(()=>!1))return`❌ No .swarm/ directory found in ${directory}. Run /swarm close from the project root, or run /swarm plan first.`}}if(args2.includes("--dry-run"))return _internals123.runFinalizeDryRun(directory,swarmDir,planData,planExists);let confirmArg=args2.find((a)=>a.startsWith("--confirm=")),confirmToken=confirmArg?confirmArg.slice(10):void 0,purgeGate=await evaluateClosePurgeGate(directory,swarmDir);if(purgeGate.gitStatusFailed)return`\uD83D\uDED1 /swarm close aborted (fail-closed): git status could not be read in ${directory}, so the destructive-purge gate cannot verify uncommitted tracked work. Nothing was closed, archived, or destroyed. ${describeCloseGateStatusFailure(purgeGate.statusFailure)}`;if(confirmToken!==void 0){let verdict=consumeConfirmToken(purgeGate.scopeAnchor,directory,confirmToken,{kind:"swarm-close",candidates:purgeGate.candidates});if(!verdict.ok)return`\uD83D\uDD10 /swarm close confirmation rejected: ${verdict.reason}. Nothing was closed, archived, or destroyed. Re-run /swarm close (without --confirm) for a fresh preview and token.`}else if(purgeGate.wouldDestroyTrackedWork){let activeStateCount=purgeGate.candidates.length-purgeGate.dirtyPaths.length,token=issueConfirmToken(purgeGate.scopeAnchor,directory,{kind:"swarm-close",candidates:purgeGate.candidates}),listed=purgeGate.dirtyPaths.slice(0,10),overflow=purgeGate.dirtyPaths.length-listed.length;return["\uD83D\uDD10 Destructive close preview — confirmation required.","",`Git alignment would DISCARD ${purgeGate.dirtyPaths.length} uncommitted tracked change(s):`,...listed.map((p)=>` - ${p}`),...overflow>0?[` … and ${overflow} more`]:[],"",`${activeStateCount} active-state artifact(s) will be archived, then removed.`,"","Nothing has been closed, archived, or destroyed yet. To execute the destructive close, run:","",`/swarm close --confirm=${token}`,"","The token is valid for 15 minutes and can be used once. Untracked files are not affected."].join(`
|
|
1538
|
+
`)}catch(err){warn(`[restart-reconciliation] failed to persist reconciliation artifact for session "${full.sessionId}" (task ${full.taskId}): ${err instanceof Error?err.message:String(err)}`)}return full}function buildInterruptedAdvisoryDedupeKey(entry){return`[restart-reconciliation:${entry.sessionId}:${entry.taskId}]`}function buildInterruptedAdvisoryMessage(entry){return`${buildInterruptedAdvisoryDedupeKey(entry)} [swarm] Restart reconciliation: session ${entry.sessionId} (agent ${entry.agentName}) was interrupted mid-execution on task ${entry.taskId}. `+"The outcome is UNKNOWN — do not treat absence as success. "+`${entry.guidance??RESTART_RECONCILIATION_GUIDANCE}.`}var RESTART_RECONCILIATION_FILE="session/restart-reconciliation.json",MAX_RESTART_RECONCILIATION_ENTRIES=50,RESTART_RECONCILIATION_GUIDANCE="outcome UNKNOWN — do not assume success; inspect /swarm status for uncertain provider effects; /swarm recover settles stale coder-settlement WALs; a human must resolve external effects (pushed commits, published PRs) manually";var init_restart_reconciliation=__esm(()=>{init_bun_compat();init_logger()});import{closeSync as closeSync27,existsSync as existsSync77,renameSync as fsRename,fsyncSync as fsyncSync8,mkdirSync as mkdirSync46,openSync as openSync27,unlinkSync as unlinkSync29}from"node:fs";import*as path163 from"node:path";async function renameWithTransientRetry(tempPath,targetPath,shouldCommit){let lastError,renameCommitted=()=>!existsSync77(tempPath)&&existsSync77(targetPath);for(let attempt=0;attempt<SNAPSHOT_RENAME_MAX_ATTEMPTS;attempt++){if(shouldCommit&&!shouldCommit())return!1;try{return await _internals141.rename(tempPath,targetPath,shouldCommit),renameCommitted()}catch(error93){lastError=error93;let code=error93.code;if((code==="EEXIST"||code==="EBUSY"||code==="EPERM"||code==="ENOENT"&&attempt>0)&&renameCommitted())return!0;if(code!=="EEXIST"&&code!=="EBUSY"&&code!=="EPERM")break;if(attempt<SNAPSHOT_RENAME_MAX_ATTEMPTS-1)await new Promise((resolve71)=>setTimeout(resolve71,SNAPSHOT_RENAME_RETRY_DELAY_MS))}}throw lastError}function serializeAgentSession(s){let gateLog={},rawGateLog=s.gateLog??new Map;for(let[taskId,gates]of rawGateLog)gateLog[taskId]=Array.from(gates??[]);let reviewerCallCount={},rawReviewerCallCount=s.reviewerCallCount??new Map;for(let[phase,count3]of rawReviewerCallCount)reviewerCallCount[String(phase)]=count3;let partialGateWarningsIssuedForTask=Array.from(s.partialGateWarningsIssuedForTask??new Set),completionGateWarnedForTask=Array.from(s.completionGateWarnedForTask??new Set),catastrophicPhaseWarnings=Array.from(s.catastrophicPhaseWarnings??new Set),phaseAgentsDispatched=Array.from(s.phaseAgentsDispatched??new Set),lastCompletedPhaseAgentsDispatched=Array.from(s.lastCompletedPhaseAgentsDispatched??new Set),stageBCompletion={};if(s.stageBCompletion)for(let[taskId,agents]of s.stageBCompletion)stageBCompletion[taskId]=Array.from(agents);let stageBRouteRequiredTasks=Array.from(s.stageBRouteRequiredTasks??[]),modifiedFilesByTask=Object.create(null);for(let[taskId,files]of s.modifiedFilesByTask??new Map)modifiedFilesByTask[taskId]=[...files];let windows={},rawWindows=s.windows??{};for(let[key2,win]of Object.entries(rawWindows))windows[key2]={id:win.id,agentName:win.agentName,startedAtMs:win.startedAtMs,toolCalls:win.toolCalls,consecutiveErrors:win.consecutiveErrors,hardLimitHit:win.hardLimitHit,lastSuccessTimeMs:win.lastSuccessTimeMs,recentToolCalls:win.recentToolCalls,warningIssued:win.warningIssued,warningReason:win.warningReason,transientRetryCount:win.transientRetryCount??0};return{agentName:s.agentName,lastToolCallTime:s.lastToolCallTime,lastAgentEventTime:s.lastAgentEventTime,delegationActive:s.delegationActive,activeInvocationId:s.activeInvocationId,lastInvocationIdByAgent:s.lastInvocationIdByAgent??{},windows,lastCompactionHint:s.lastCompactionHint??0,architectWriteCount:s.architectWriteCount??0,lastCoderDelegationTaskId:s.lastCoderDelegationTaskId??null,currentTaskId:s.currentTaskId??null,turboMode:s.turboMode??!1,...s.turboStrategy!==void 0&&{turboStrategy:s.turboStrategy},leanTurboActive:s.leanTurboActive??!1,...s.leanTurboCurrentPhase!==void 0&&{leanTurboCurrentPhase:s.leanTurboCurrentPhase},epicModeActive:!1,gateLog,reviewerCallCount,lastGateFailure:s.lastGateFailure??null,partialGateWarningsIssuedForTask,completionGateWarnedForTask,selfFixAttempted:s.selfFixAttempted??!1,selfCodingWarnedAtCount:s.selfCodingWarnedAtCount??0,catastrophicPhaseWarnings,lastPhaseCompleteTimestamp:s.lastPhaseCompleteTimestamp??0,lastPhaseCompletePhase:s.lastPhaseCompletePhase??0,phaseAgentsDispatched,lastCompletedPhaseAgentsDispatched,qaSkipCount:s.qaSkipCount??0,qaSkipTaskIds:s.qaSkipTaskIds??[],pendingAdvisoryMessages:s.pendingAdvisoryMessages??[],taskWorkflowStates:Object.fromEntries(s.taskWorkflowStates??new Map),...Object.keys(modifiedFilesByTask).length>0&&{modifiedFilesByTask},...s.scopeViolationDetected!==void 0&&{scopeViolationDetected:s.scopeViolationDetected},model_fallback_index:s.model_fallback_index??0,modelFallbackExhausted:s.modelFallbackExhausted??!1,coderRevisions:s.coderRevisions??0,revisionLimitHit:s.revisionLimitHit??!1,fullAutoMode:s.fullAutoMode??!1,fullAutoInteractionCount:s.fullAutoInteractionCount??0,fullAutoDeadlockCount:s.fullAutoDeadlockCount??0,fullAutoLastQuestionHash:s.fullAutoLastQuestionHash??null,sessionRehydratedAt:s.sessionRehydratedAt??0,...Object.keys(stageBCompletion).length>0&&{stageBCompletion},...stageBRouteRequiredTasks.length>0&&{stageBRouteRequiredTasks},...s.maxConcurrencyOverride!==void 0&&{maxConcurrencyOverride:s.maxConcurrencyOverride},...s.autoProceedOverride!==void 0&&{autoProceedOverride:s.autoProceedOverride},...s.autoProceedNudgeDone!==void 0&&{autoProceedNudgeDone:s.autoProceedNudgeDone},...s.cachedCohortId!==void 0&&{cachedCohortId:s.cachedCohortId},...s.lastObservedModel!==void 0&&{lastObservedModel:s.lastObservedModel},...s.lastObservedProviderID!==void 0&&{lastObservedProviderID:s.lastObservedProviderID}}}function isClosingRefusal(message){return message.includes("closing for reset-session")}function adviseClosingStop(directory){let status2=getSnapshotCoordinationStatus(directory);if(status2.state!=="closing")return;if(!status2.pendingPriorAttempt&&!status2.closingReason)return;let root=canonicalProjectKey(directory);if(closingStopAdvisedRoots.has(root))return;if(closingStopAdvisedRoots.size>=MAX_CLOSING_STOP_ROOTS){log("[snapshot-writer] closing-stop advisory cap reached",{root});return}if(closingStopAdvisedRoots.add(root),status2.pendingPriorAttempt&&status2.closingReason==="reset-cleanup-failed"){advisoryWarn("[opencode-swarm] /swarm reset-session partially failed while a prior initialization attempt is still settling: durable session-snapshot persistence is stopped — wait for that attempt to settle, then re-run /swarm reset-session to completion (or restart the host) to recover.");return}if(status2.pendingPriorAttempt){advisoryWarn("[opencode-swarm] durable session-snapshot persistence is paused while coordination closes for reset-session (an underlying initialization attempt is still settling); wait for it to settle or restart the host.");return}if(status2.closingReason==="reset-cleanup-failed"){advisoryWarn("[opencode-swarm] durable session-snapshot persistence is stopped for this project (coordination is closing for reset-session); re-run /swarm reset-session to completion, or restart the host, to recover.");return}if(status2.closingReason==="shutdown"){advisoryWarn("[opencode-swarm] coordination is closing for host shutdown; durable session-snapshot persistence is stopped until the host restarts.");return}}async function writeSnapshot2(directory,state2){try{let{ensureSnapshotCoordinationReady}=await Promise.resolve().then(() => (init_snapshot_coordination_init(),exports_snapshot_coordination_init));if(await ensureSnapshotCoordinationReady(directory),closingStopAdvisedRoots.size>0)closingStopAdvisedRoots.delete(canonicalProjectKey(directory));let snapshot={version:3,writtenAt:Date.now(),workflowSchema:TASK_WORKFLOW_SCHEMA_MARKER,toolAggregates:Object.fromEntries(state2.toolAggregates),activeAgent:Object.fromEntries([...state2.activeAgent].filter(([sessionId])=>isSnapshotSessionOwnedLocally(sessionId))),delegationChains:Object.fromEntries([...state2.delegationChains].filter(([sessionId])=>isSnapshotSessionOwnedLocally(sessionId))),agentSessions:{}};for(let[sessionId,sessionState]of state2.agentSessions){if(!isSnapshotSessionOwnedLocally(sessionId))continue;snapshot.agentSessions[sessionId]=serializeAgentSession(sessionState)}writeSnapshotRows(directory,snapshot,{onlyLocallyOwnedSessions:!0});let canonicalSnapshot=readSnapshotRows(directory)??snapshot;await writeSnapshotProjection(directory,canonicalSnapshot)}catch(error93){let message=error93 instanceof Error?error93.message:String(error93);if(isClosingRefusal(message))adviseClosingStop(directory);log("[snapshot-writer] write failed",{error:message})}}async function writeSnapshotProjection(directory,snapshot,shouldCommit){let content=JSON.stringify(snapshot,null,2),resolvedPath=validateSwarmPath(directory,SNAPSHOT_PROJECTION_FILE),dir=path163.dirname(resolvedPath);mkdirSync46(dir,{recursive:!0});let tempPath=`${resolvedPath}.tmp.${Date.now()}.${Math.random().toString(36).slice(2)}`;try{await bunWrite(tempPath,content);try{let fd=openSync27(tempPath,"r+");try{fsyncSync8(fd)}finally{closeSync27(fd)}}catch{}if(!await renameWithTransientRetry(tempPath,resolvedPath,shouldCommit))return;invalidateCachedArtifact(resolvedPath)}finally{try{unlinkSync29(tempPath)}catch{}}}function createSnapshotWriterHook(directory){return(_input,_output)=>{return _writeInFlight=_writeInFlight.then(()=>_internals141.writeSnapshot(directory,swarmState),()=>_internals141.writeSnapshot(directory,swarmState)),_writeInFlight}}async function flushPendingSnapshot(directory){_writeInFlight=_writeInFlight.then(()=>_internals141.writeSnapshot(directory,swarmState),()=>_internals141.writeSnapshot(directory,swarmState)),await _writeInFlight}var SNAPSHOT_PROJECTION_FILE="session/state.sqlite-projection.json",_writeInFlight,SNAPSHOT_RENAME_MAX_ATTEMPTS=3,SNAPSHOT_RENAME_RETRY_DELAY_MS=50,closingStopAdvisedRoots,MAX_CLOSING_STOP_ROOTS=256,_internals141;var init_snapshot_writer=__esm(()=>{init_canonical_project();init_gate_evidence();init_utils2();init_warning_buffer();init_state();init_utils();init_bun_compat();init_swarm_artifact_cache();init_snapshot_coordination_init();init_snapshot_store();_writeInFlight=Promise.resolve();closingStopAdvisedRoots=new Set;_internals141={writeSnapshot:writeSnapshot2,createSnapshotWriterHook,flushPendingSnapshot,rename:fsRename}});import{renameSync as renameSync27}from"node:fs";function deserializeTaskWorkflowStates(raw){let m=new Map;if(!raw||typeof raw!=="object")return m;for(let[taskId,stateVal]of Object.entries(raw))if(VALID_TASK_WORKFLOW_STATES.includes(stateVal))m.set(taskId,stateVal);return m}function deserializeModifiedFilesByTask(raw){let entries=new Map;if(!raw||typeof raw!=="object")return entries;let serializedEntries=Object.entries(raw);if(serializedEntries.length>MAX_TRACKED_TASK_FILE_ATTRIBUTIONS)return entries;for(let[taskId,files]of serializedEntries){if(!taskId.trim()||!Array.isArray(files))continue;let validFiles=files.filter((file3)=>typeof file3==="string"&&file3.length>0);entries.set(taskId,[...new Set(validFiles)])}return entries}function deserializeAgentSession(s){let lastGateFailure=s.lastGateFailure?{tool:s.lastGateFailure.tool,taskId:s.lastGateFailure.taskId,timestamp:s.lastGateFailure.timestamp,...typeof s.lastGateFailure.code==="string"&&/^[A-Z][A-Z0-9_]{0,63}$/.test(s.lastGateFailure.code)&&{code:s.lastGateFailure.code}}:null,taskWorkflowStates=deserializeTaskWorkflowStates(s.taskWorkflowStates),modifiedFilesByTask=deserializeModifiedFilesByTask(s.modifiedFilesByTask),gateLog=new Map;if(s.gateLog)for(let[taskId,gates]of Object.entries(s.gateLog))gateLog.set(taskId,new Set(gates??[]));let reviewerCallCount=new Map;if(s.reviewerCallCount)for(let[phase,count3]of Object.entries(s.reviewerCallCount)){let numPhase=Number(phase);if(Number.isFinite(numPhase))reviewerCallCount.set(numPhase,count3)}let partialGateWarningsIssuedForTask=new Set(s.partialGateWarningsIssuedForTask??[]),completionGateWarnedForTask=new Set(s.completionGateWarnedForTask??[]),catastrophicPhaseWarnings=new Set(s.catastrophicPhaseWarnings??[]),phaseAgentsDispatched=new Set(s.phaseAgentsDispatched??[]),lastCompletedPhaseAgentsDispatched=new Set(s.lastCompletedPhaseAgentsDispatched??[]),stageBCompletion=new Map;if(s.stageBCompletion)for(let[taskId,agents]of Object.entries(s.stageBCompletion))stageBCompletion.set(taskId,new Set(agents));let stageBRouteRequiredTasks=new Set(Array.isArray(s.stageBRouteRequiredTasks)?s.stageBRouteRequiredTasks.filter((taskId)=>typeof taskId==="string"&&taskId.length>0):[]),windows={};for(let[key2,win]of Object.entries(s.windows??{})){if(!win||typeof win!=="object")continue;windows[key2]={...win,transientRetryCount:"transientRetryCount"in win?win.transientRetryCount??0:0}}return{agentName:s.agentName,lastToolCallTime:s.lastToolCallTime,lastAgentEventTime:s.lastAgentEventTime,delegationActive:s.delegationActive,activeInvocationId:s.activeInvocationId,lastInvocationIdByAgent:s.lastInvocationIdByAgent??{},windows,lastCompactionHint:s.lastCompactionHint??0,architectWriteCount:s.architectWriteCount??0,lastCoderDelegationTaskId:s.lastCoderDelegationTaskId??null,currentTaskId:s.currentTaskId??null,turboMode:s.turboMode??!1,turboStrategy:s.turboStrategy==="lean"||s.turboStrategy==="standard"?s.turboStrategy:void 0,leanTurboActive:s.leanTurboActive??!1,leanTurboCurrentPhase:typeof s.leanTurboCurrentPhase==="number"?s.leanTurboCurrentPhase:void 0,gateLog,reviewerCallCount,lastGateFailure,partialGateWarningsIssuedForTask,completionGateWarnedForTask,selfFixAttempted:s.selfFixAttempted??!1,selfCodingWarnedAtCount:s.selfCodingWarnedAtCount??0,catastrophicPhaseWarnings,lastPhaseCompleteTimestamp:s.lastPhaseCompleteTimestamp??0,lastPhaseCompletePhase:s.lastPhaseCompletePhase??0,phaseAgentsDispatched,lastCompletedPhaseAgentsDispatched,qaSkipCount:s.qaSkipCount??0,qaSkipTaskIds:s.qaSkipTaskIds??[],taskWorkflowStates,lastGateOutcome:null,declaredCoderScope:null,lastScopeViolation:null,scopeViolationDetected:s.scopeViolationDetected,modifiedFilesByTask,modifiedFilesThisCoderTask:s.currentTaskId&&s.currentTaskId.trim()!==""&&modifiedFilesByTask.has(s.currentTaskId)?[...modifiedFilesByTask.get(s.currentTaskId)??[]]:[],loopDetectionWindow:[],pendingAdvisoryMessages:s.pendingAdvisoryMessages??[],model_fallback_index:s.model_fallback_index??0,modelFallbackExhausted:s.modelFallbackExhausted??!1,coderRevisions:s.coderRevisions??0,revisionLimitHit:s.revisionLimitHit??!1,fullAutoMode:s.fullAutoMode??!1,fullAutoInteractionCount:s.fullAutoInteractionCount??0,fullAutoDeadlockCount:s.fullAutoDeadlockCount??0,fullAutoLastQuestionHash:s.fullAutoLastQuestionHash??null,maxConcurrencyOverride:typeof s.maxConcurrencyOverride==="number"?Math.min(64,Math.max(1,s.maxConcurrencyOverride)):void 0,autoProceedOverride:s.autoProceedOverride,autoProceedNudgeDone:s.autoProceedNudgeDone,prmPatternCounts:new Map,prmEscalationLevel:0,prmLastPatternDetected:null,prmTrajectoryStep:0,prmHardStopPending:!1,prmHardStopInjectPending:!1,prmInjectedAdvisoryKeys:new Set,prmStruckEpisodes:new Map,prmLadderCounts:new Map,executionEpisodeArmed:!1,sessionRehydratedAt:s.sessionRehydratedAt??0,stageBCompletion,stageBRouteRequiredTasks,prSubscriptions:new Map,cachedCohortId:typeof s.cachedCohortId==="string"?s.cachedCohortId:void 0,lastObservedModel:typeof s.lastObservedModel==="string"?s.lastObservedModel:void 0,lastObservedProviderID:typeof s.lastObservedProviderID==="string"?s.lastObservedProviderID:void 0}}async function readSnapshot(directory){for(let relativePath2 of[SNAPSHOT_PROJECTION_FILE,"session/state.json"])try{let resolvedPath=validateSwarmPath(directory,relativePath2),content=await bunFile(resolvedPath).text();if(!content.trim())continue;let parsed=JSON.parse(content,(key2,value)=>{if(key2==="__proto__"||key2==="constructor")return;return value});if(parsed.version!==1&&parsed.version!==2&&parsed.version!==3){try{let quarantinePath=validateSwarmPath(directory,`${relativePath2}.quarantine`);renameSync27(resolvedPath,quarantinePath)}catch{}continue}return parsed}catch{}return null}async function readSnapshotFileStrict(directory,relativePath2){let resolvedPath=validateSwarmPath(directory,relativePath2),content=await bunFile(resolvedPath).text();if(!content.trim())throw Error(`snapshot ${relativePath2} is empty`);let parsed=JSON.parse(content,(key2,value)=>{if(key2==="__proto__"||key2==="constructor")return;return value});if(parsed.version!==1&&parsed.version!==2&&parsed.version!==3)throw Error(`snapshot ${relativePath2} has an unsupported version`);if(!parsed.toolAggregates||!parsed.activeAgent||!parsed.delegationChains||!parsed.agentSessions)throw Error(`snapshot ${relativePath2} has an invalid shape`);return parsed}async function rehydrateState(snapshot,directory,scope){if(!directory)return await rehydrateStateGlobal(snapshot),{applied:!0};let projectKey=hydrationProjectKey(directory),authority=scope??captureCurrentHydrationAuthority(projectKey),generation=authority.generation,isCurrentAuthoritySession=(session)=>session.owningProjectKey===projectKey&&session.hydrationAuthorityEpoch===authority.authorityEpoch;if(scope&&!isHydrationAuthorityCurrent(scope))return log(`[snapshot-reader] Refusing superseded hydration generation ${scope.generation} for ${projectKey}`),{applied:!1,reason:"superseded"};if(swarmState.pendingRehydrations.size>0)await Promise.allSettled([...swarmState.pendingRehydrations]);if(!isHydrationAuthorityCurrent(authority))return log(`[snapshot-reader] Refusing superseded hydration generation ${generation} for ${projectKey} after waiting for pending rehydrations`),{applied:!1,reason:"superseded"};let isProtectedLiveSession=(sessionId)=>{let live=swarmState.agentSessions.get(sessionId);return live!==void 0&&isCurrentAuthoritySession(live)&&(live.hydrationStamp??0)>generation},interruptedReconciliations=new Map;if(directory&&snapshot.agentSessions)for(let[sessionId,serializedSession]of Object.entries(snapshot.agentSessions)){if(isProtectedLiveSession(sessionId)||!serializedSession||typeof serializedSession!=="object"||typeof serializedSession.agentName!=="string"||typeof serializedSession.lastToolCallTime!=="number"||serializedSession.delegationActive!==!0)continue;let entry={sessionId,agentName:serializedSession.agentName,taskId:serializedSession.currentTaskId||"(unknown)"};try{let recorded=await _internals142.recordInterruptedExecution(directory,entry);interruptedReconciliations.set(sessionId,{entry,guidance:recorded.guidance})}catch(error93){log(`[snapshot-reader] restart reconciliation failed for session ${sessionId}: ${error93 instanceof Error?error93.message:String(error93)}`)}}if(!isHydrationAuthorityCurrent(authority))return log(`[snapshot-reader] Refusing superseded hydration generation ${generation} for ${projectKey} after restart reconciliation preflight`),{applied:!1,reason:"superseded"};for(let[sessionId,session]of swarmState.agentSessions)if(session.owningProjectKey===projectKey&&(!isCurrentAuthoritySession(session)||(session.hydrationStamp??0)<=generation))swarmState.agentSessions.delete(sessionId),swarmState.activeAgent.delete(sessionId),swarmState.delegationChains.delete(sessionId);let ownAggregateKeys=hydratedAggregateKeysFor(projectKey,authority),snapshotAggregateKeys=new Set(Object.keys(snapshot.toolAggregates??{}));for(let key2 of ownAggregateKeys)if(!snapshotAggregateKeys.has(key2))swarmState.toolAggregates.delete(key2);for(let[key2,value]of Object.entries(snapshot.toolAggregates??{}))swarmState.toolAggregates.set(key2,value);recordHydratedAggregateKeys(projectKey,snapshotAggregateKeys,authority);let now2=Date.now(),epicOpenForRehydration;if(snapshot.agentSessions)for(let[sessionId,serializedSession]of Object.entries(snapshot.agentSessions)){if(isProtectedLiveSession(sessionId))continue;if(!serializedSession||typeof serializedSession!=="object"||typeof serializedSession.agentName!=="string"||typeof serializedSession.lastToolCallTime!=="number"||typeof serializedSession.delegationActive!=="boolean"){log(`[snapshot-reader] Skipping malformed session ${sessionId}: missing required fields (agentName, lastToolCallTime, delegationActive)`);continue}let session=deserializeAgentSession(serializedSession);if(session.taskWorkflowStates=new Map,session.taskWorkflowCache=new Map,session.stageBCompletion=new Map,session.owningProjectKey=projectKey,session.hydrationStamp=generation,session.hydrationAuthorityEpoch=authority.authorityEpoch,session.lastToolCallTime=now2,session.lastAgentEventTime=now2,session.sessionRehydratedAt=now2,session.windows)for(let window2 of Object.values(session.windows))window2.startedAtMs=now2,window2.lastSuccessTimeMs=now2,window2.hardLimitHit=!1,window2.toolCalls=0,window2.consecutiveErrors=0,window2.recentToolCalls=[],window2.warningIssued=!1,window2.warningReason="";for(let field of TRANSIENT_SESSION_FIELDS){let reset=field.resetValue;session[field.name]=Array.isArray(reset)?[...reset]:reset}if(directory)try{let durableOverrides=getOverrideForSession(directory,sessionId);if(Object.keys(durableOverrides).length>0)session.qaGateSessionOverrides=durableOverrides}catch(error93){log(`[snapshot-reader] override restore failed for session ${sessionId}: ${error93 instanceof Error?error93.message:String(error93)}`)}let reconciliation=interruptedReconciliations.get(sessionId);if(reconciliation)pushAdvisory(session,buildInterruptedAdvisoryMessage({...reconciliation.entry,guidance:reconciliation.guidance}),{dedupeKey:buildInterruptedAdvisoryDedupeKey(reconciliation.entry)});if(session.fullAutoMode){let runStillActive=!1;if(directory)try{runStillActive=loadFullAutoRunState(directory,sessionId)?.status==="running"}catch{runStillActive=!1}if(!runStillActive)session.fullAutoMode=!1}if(session.turboMode===!0){if(epicOpenForRehydration===void 0)epicOpenForRehydration=_internals142.isEpicOpenForProject(directory);if(epicOpenForRehydration)session.turboMode=!1}swarmState.agentSessions.set(sessionId,session)}if(snapshot.activeAgent){for(let[key2,value]of Object.entries(snapshot.activeAgent))if(swarmState.agentSessions.has(key2)&&!isProtectedLiveSession(key2))swarmState.activeAgent.set(key2,value)}if(snapshot.delegationChains){for(let[key2,value]of Object.entries(snapshot.delegationChains))if(swarmState.agentSessions.has(key2)&&!isProtectedLiveSession(key2))swarmState.delegationChains.set(key2,value)}if(directory)try{let keep=new Set;for(let sessionId of Object.keys(snapshot.agentSessions??{}))keep.add(sessionId);for(let[sessionId,live]of swarmState.agentSessions)if(live.owningProjectKey===projectKey)keep.add(sessionId);let removed=sweepOrphanOverrides(directory,keep);if(removed>0)log(`[snapshot-reader] pruned ${removed} orphaned QA override row(s) for ${projectKey}`)}catch(error93){log(`[snapshot-reader] override orphan reaper failed for ${projectKey}: ${error93 instanceof Error?error93.message:String(error93)}`)}return{applied:!0}}async function rehydrateStateGlobal(snapshot){if(swarmState.pendingRehydrations.size>0)await Promise.allSettled([...swarmState.pendingRehydrations]);swarmState.toolAggregates.clear(),swarmState.activeAgent.clear(),swarmState.delegationChains.clear(),swarmState.agentSessions.clear();for(let[key2,value]of Object.entries(snapshot.toolAggregates??{}))swarmState.toolAggregates.set(key2,value);let now2=Date.now();if(snapshot.agentSessions)for(let[sessionId,serializedSession]of Object.entries(snapshot.agentSessions)){if(!serializedSession||typeof serializedSession!=="object"||typeof serializedSession.agentName!=="string"||typeof serializedSession.lastToolCallTime!=="number"||typeof serializedSession.delegationActive!=="boolean"){log(`[snapshot-reader] Skipping malformed session ${sessionId}: missing required fields (agentName, lastToolCallTime, delegationActive)`);continue}let session=deserializeAgentSession(serializedSession);if(session.taskWorkflowStates=new Map,session.taskWorkflowCache=new Map,session.stageBCompletion=new Map,session.lastToolCallTime=now2,session.lastAgentEventTime=now2,session.sessionRehydratedAt=now2,session.windows)for(let window2 of Object.values(session.windows))window2.startedAtMs=now2,window2.lastSuccessTimeMs=now2,window2.hardLimitHit=!1,window2.toolCalls=0,window2.consecutiveErrors=0,window2.recentToolCalls=[],window2.warningIssued=!1,window2.warningReason="";for(let field of TRANSIENT_SESSION_FIELDS){let reset=field.resetValue;session[field.name]=Array.isArray(reset)?[...reset]:reset}if(session.fullAutoMode)session.fullAutoMode=!1;swarmState.agentSessions.set(sessionId,session)}if(snapshot.activeAgent){for(let[key2,value]of Object.entries(snapshot.activeAgent))if(swarmState.agentSessions.has(key2))swarmState.activeAgent.set(key2,value)}if(snapshot.delegationChains){for(let[key2,value]of Object.entries(snapshot.delegationChains))if(swarmState.agentSessions.has(key2))swarmState.delegationChains.set(key2,value)}}async function loadSnapshot(directory){let scope=beginHydrationScope(directory);try{if(!(await buildRehydrationCache(directory,{shouldCommit:()=>isHydrationScopeCurrent(scope)})).committed||!isHydrationScopeCurrent(scope))return;let snapshot=await readSnapshot(directory);if(snapshot!==null){if(!(await rehydrateState(snapshot,directory,scope)).applied||!isHydrationScopeCurrent(scope))return;for(let session of swarmState.agentSessions.values()){if(!isHydrationScopeCurrent(scope))return;applyRehydrationCache(session)}}}catch{}}var _internals142,TRANSIENT_SESSION_FIELDS,VALID_TASK_WORKFLOW_STATES;var init_snapshot_reader=__esm(()=>{init_qa_gate_session_override();init_lifecycle();init_state2();init_utils2();init_state();init_bun_compat();init_logger();init_hydration_ownership();init_restart_reconciliation();init_snapshot_writer();_internals142={recordInterruptedExecution,isEpicOpenForProject},TRANSIENT_SESSION_FIELDS=[{name:"revisionLimitHit",resetValue:!1},{name:"coderRevisions",resetValue:0},{name:"selfFixAttempted",resetValue:!1},{name:"lastGateFailure",resetValue:null},{name:"architectWriteCount",resetValue:0},{name:"selfCodingWarnedAtCount",resetValue:0},{name:"pendingAdvisoryMessages",resetValue:[]},{name:"model_fallback_index",resetValue:0},{name:"modelFallbackExhausted",resetValue:!1},{name:"scopeViolationDetected",resetValue:!1},{name:"delegationActive",resetValue:!1},{name:"autoProceedOverride",resetValue:void 0},{name:"autoProceedNudgeDone",resetValue:void 0}],VALID_TASK_WORKFLOW_STATES=["idle","coder_delegated","pre_check_passed","reviewer_run","tests_run","rework_required","complete","blocked","closed"]});var exports_snapshot_coordination_init={};__export(exports_snapshot_coordination_init,{startSnapshotCoordinationInitialization:()=>startSnapshotCoordinationInitialization,retrySnapshotCoordinationInitialization:()=>retrySnapshotCoordinationInitialization,markSnapshotCoordinationClosing:()=>markSnapshotCoordinationClosing,getSnapshotCoordinationStatus:()=>getSnapshotCoordinationStatus,ensureSnapshotCoordinationReady:()=>ensureSnapshotCoordinationReady,closeSnapshotCoordinationInitialization:()=>closeSnapshotCoordinationInitialization,beginSnapshotCoordinationReset:()=>beginSnapshotCoordinationReset,_snapshotCoordinationInternals:()=>_snapshotCoordinationInternals});import{createHash as createHash70,randomUUID as randomUUID22}from"node:crypto";import{existsSync as existsSync78,readFileSync as readFileSync59,renameSync as renameSync28}from"node:fs";function isReadinessEntryClosing(entry){return entry?.state==="closing"}function recordSupersession(trigger){supersessionStats.count+=1;try{telemetry.planRecoverySuperseded({count:supersessionStats.count,trigger})}catch{}}function isRetryableArchiveError(error93){let code=error93?.code;return code==="EBUSY"||code==="EPERM"||code==="EACCES"}async function archiveLegacySnapshotIfPresent(legacyPath,expectedSnapshot,shouldCommit=()=>!0){if(!shouldCommit())return"superseded";if(!existsSync78(legacyPath))return"not_archived";if(expectedSnapshot)try{if(JSON.stringify(JSON.parse(readFileSync59(legacyPath,"utf8")))!==JSON.stringify(expectedSnapshot))return advisoryWarn("[opencode-swarm] Legacy snapshot changed after SQLite coordination; preserving it for explicit recovery."),"not_archived"}catch{return"not_archived"}let canonicalArchive=`${legacyPath}.imported`,archivePath=existsSync78(canonicalArchive)?`${canonicalArchive}.${randomUUID22()}`:canonicalArchive,lastError;for(let attempt=1;attempt<=ARCHIVE_RETRY_ATTEMPTS;attempt+=1){if(!shouldCommit())return"superseded";try{return _snapshotCoordinationInternals.renameLegacySnapshot(legacyPath,archivePath),"archived"}catch(error93){if(lastError=error93,!isRetryableArchiveError(error93)||attempt===ARCHIVE_RETRY_ATTEMPTS)break;await new Promise((resolve71)=>setTimeout(resolve71,ARCHIVE_RETRY_DELAY_MS))}}return advisoryWarn(`[opencode-swarm] SQLite snapshot is authoritative, but the legacy shadow could not be archived: ${lastError instanceof Error?lastError.message:String(lastError)}`),"not_archived"}function evictSettledEntries(){while(entries.size>=MAX_READY_ROOTS){let victim=[...entries].find(([,entry])=>entry.settled);if(!victim)return!1;entries.delete(victim[0])}return!0}async function initializeSnapshotCoordination(directory,scope){let isCurrent=()=>scope===void 0||isHydrationScopeCurrent(scope);if(!isCurrent())return"superseded";let legacyArchiveAttempted=!1,snapshot=readSnapshotRows(directory);if(!snapshot){if(!isCurrent())return"superseded";let legacyPath=validateSwarmPath(directory,"session/state.json"),projectionPath=validateSwarmPath(directory,SNAPSHOT_PROJECTION_FILE),source=existsSync78(projectionPath)?SNAPSHOT_PROJECTION_FILE:existsSync78(legacyPath)?"session/state.json":null;if(source){if(!isCurrent())return"superseded";let candidate=await _snapshotCoordinationInternals.readSnapshotFileStrict(directory,source);if(!isCurrent())return"superseded";let serialized2=JSON.stringify(candidate),outcome=_snapshotCoordinationInternals.importSnapshotRowsOnce(directory,candidate,createHash70("sha256").update(serialized2).digest("hex"),source);if(snapshot=readSnapshotRows(directory),outcome==="imported"&&source==="session/state.json"){if(legacyArchiveAttempted=!0,await archiveLegacySnapshotIfPresent(legacyPath,candidate,isCurrent)==="superseded")return"superseded"}}}if(!isCurrent())return"superseded";if(snapshot){if(!legacyArchiveAttempted){if(await archiveLegacySnapshotIfPresent(validateSwarmPath(directory,"session/state.json"),snapshot,isCurrent)==="superseded")return"superseded"}if(!(await rehydrateState(snapshot,directory,scope)).applied||!isCurrent())return"superseded"}let authoritativePlan;try{authoritativePlan=await _snapshotCoordinationInternals.loadPlan(directory,void 0,{preCommitCheck:()=>{if(!isCurrent())throw new PlanRecoverySupersededError("Snapshot coordination initialization superseded during plan recovery")}})}catch(error93){if(error93 instanceof PlanRecoverySupersededError)throw error93;advisoryWarn(`[opencode-swarm] Authoritative plan recovery failed; retaining pre-resolution cache: ${error93 instanceof Error?error93.message:String(error93)}`.slice(0,512))}if(!isCurrent())return"superseded";if(authoritativePlan!==void 0){if(!(await buildRehydrationCache(directory,{planOverride:authoritativePlan,shouldCommit:isCurrent})).committed||!isCurrent())return"superseded"}for(let session of swarmState.agentSessions.values()){if(!isCurrent())return"superseded";applyRehydrationCache(session)}if(!snapshot||!isCurrent())return isCurrent()?"succeeded":"superseded";try{await _snapshotCoordinationInternals.writeProjection(directory,snapshot,isCurrent)}catch(error93){advisoryWarn(`[opencode-swarm] SQLite snapshot is ready, but its compatibility projection could not be written: ${error93 instanceof Error?error93.message:String(error93)}`)}return isCurrent()?"succeeded":"superseded"}function startSnapshotCoordinationInitialization(directory){let root=canonicalProjectKey(directory),existing=entries.get(root);if(existing?.state==="closing")return Promise.reject(Error("coordination initialization is closing for reset-session"));if(existing&&!existing.settled)return existing.underlying;if(existing?.state==="succeeded")return existing.underlying;if(!evictSettledEntries()){let error93=Error(`SQLite snapshot coordination capacity exhausted (${MAX_READY_ROOTS} unsettled roots)`);return advisoryWarn(`[opencode-swarm] ${error93.message}; initialization refused.`),Promise.reject(error93)}let attemptId=nextAttemptId++,generation=(existing?.generation??0)+1,scope=beginHydrationScope(root),entry={attemptId,generation,state:"running",settled:!1,underlying:Promise.resolve()},underlying=_snapshotCoordinationInternals.initialize(root,scope).then((outcome)=>{if(entries.get(root)!==entry||entry.state==="closing")return;if(outcome==="superseded"){entry.state="superseded",entry.error="coordination initialization superseded by a newer hydration generation",recordSupersession("coordination_fence");return}entry.state="succeeded"}).catch((error93)=>{if(error93 instanceof PlanRecoverySupersededError){if(entry.state!=="closing"&&entries.get(root)===entry)entry.state="superseded",entry.error=error93.message,recordSupersession("plan_recovery")}else entry.state="failed",entry.error=error93 instanceof Error?error93.message:String(error93);throw error93}).finally(()=>{entry.settled=!0});return entry.underlying=underlying,entries.set(root,entry),withTimeout(underlying,_snapshotCoordinationInternals.timeoutMs,Error("coordination initialization timed out")).catch((error93)=>{if(!entry.settled&&entry.state!=="closing"&&entries.get(root)===entry)entry.state="timed_out",entry.error=error93 instanceof Error?error93.message:String(error93),advisoryWarn("[opencode-swarm] SQLite coordination initialization is still running; authority operations remain fail-closed.")}),underlying}async function ensureSnapshotCoordinationReady(directory){let root=canonicalProjectKey(directory),entry=entries.get(root);if(entry?.state==="closing")throw Error("coordination initialization is closing for reset-session");if(entry?.state==="timed_out"&&!entry.settled)throw Error("coordination initialization remains unsettled after timeout");if(!entry||entry.state==="superseded"&&entry.settled){await startSnapshotCoordinationInitialization(root);let retried=entries.get(root);if(retried?.state==="closing")throw Error("coordination initialization is closing for reset-session");if(retried?.state!=="succeeded")throw Error(retried?.error??"coordination initialization failed");return}if(await entry.underlying,isReadinessEntryClosing(entry))throw Error("coordination initialization is closing for reset-session");if(entry.state!=="succeeded")throw Error(entry.error??"coordination initialization failed")}function retrySnapshotCoordinationInitialization(directory){let root=canonicalProjectKey(directory),entry=entries.get(root);if(entry?.state==="closing"){if(entry.pendingPriorAttempt&&entry.closingReason==="reset-cleanup-failed")throw Error("coordination is closing for reset-session (a prior initialization attempt is still settling; guard stranded): once it settles, re-run /swarm reset-session to completion, or restart the host");if(entry.pendingPriorAttempt)throw Error("coordination is closing for reset-session (a prior initialization attempt is still settling): wait for it to settle before retrying, or restart the host");if(entry.closingReason==="reset-cleanup-failed")throw Error("coordination is closing for reset-session (settled): re-run /swarm reset-session to completion, or restart the host to clear the guard");if(entry.closingReason==="shutdown")throw Error("coordination is closing for host shutdown; restart the host to clear the guard");throw Error("coordination is closing for an in-flight /swarm reset-session; wait for it to finish before retrying")}if(entry&&!entry.settled)throw Error("coordination initialization is still unsettled; recovery refused");return entries.delete(root),startSnapshotCoordinationInitialization(root)}function getSnapshotCoordinationStatus(directory){let entry=entries.get(canonicalProjectKey(directory));if(!entry)return{state:"idle",settled:!0};return{state:entry.state,attemptId:entry.attemptId,generation:entry.generation,settled:entry.settled,...entry.error?{error:entry.error.slice(0,512)}:{},...entry.closingReason?{closingReason:entry.closingReason}:{},...entry.pendingPriorAttempt?{pendingPriorAttempt:!0}:{}}}async function beginSnapshotCoordinationReset(directory){let root=canonicalProjectKey(directory),prior=entries.get(root),closeError,priorUnsettled=!1;if(prior){prior.state="closing";try{await withTimeout(prior.underlying,_snapshotCoordinationInternals.timeoutMs,Error("coordination initialization close timed out"))}catch(error93){if(closeError=error93 instanceof Error?error93:Error(String(error93)),priorUnsettled=!prior.settled,priorUnsettled)prior.underlying.catch(()=>{return})}}let pendingPriorUnderlying=priorUnsettled?prior?.underlying:prior?.pendingPriorUnderlying,guard={attemptId:nextAttemptId++,generation:(prior?.generation??0)+1,state:"closing",settled:!0,underlying:Promise.resolve(),...closeError?{error:closeError.message}:{},...priorUnsettled||prior?.pendingPriorAttempt===!0?{pendingPriorAttempt:!0}:{},...pendingPriorUnderlying?{pendingPriorUnderlying}:{}};if(entries.set(root,guard),guard.pendingPriorAttempt&&pendingPriorUnderlying&&!pendingSettlementObserved.has(pendingPriorUnderlying)){pendingSettlementObserved.add(pendingPriorUnderlying);let clearPending=()=>{let live=entries.get(root);if(live?.pendingPriorUnderlying!==pendingPriorUnderlying)return;live.pendingPriorAttempt=!1,live.pendingPriorUnderlying=void 0};pendingPriorUnderlying.then(clearPending,clearPending)}let released=!1;return{release:()=>{if(released)return;released=!0;let removeGuard=()=>{if(entries.get(root)===guard)entries.delete(root)};if(!prior||prior.settled){removeGuard();return}prior.underlying.then(removeGuard,removeGuard)},markStranded:()=>{if(entries.get(root)!==guard||guard.state!=="closing")return!1;return guard.closingReason="reset-cleanup-failed",!0},...closeError?{closeError}:{},...priorUnsettled?{priorUnsettled:!0}:{}}}async function closeSnapshotCoordinationInitialization(directory){let guard=await beginSnapshotCoordinationReset(directory);try{if(guard.closeError)throw guard.closeError}finally{guard.release()}}function markSnapshotCoordinationClosing(directory){let entry=entries.get(canonicalProjectKey(directory));if(entry){if(entry.state="closing",!entry.closingReason)entry.closingReason="shutdown"}}var READY_TIMEOUT_MS=1e4,MAX_READY_ROOTS=32,ARCHIVE_RETRY_ATTEMPTS=3,ARCHIVE_RETRY_DELAY_MS=25,entries,pendingSettlementObserved,nextAttemptId=1,supersessionStats,_snapshotCoordinationInternals;var init_snapshot_coordination_init=__esm(()=>{init_canonical_project();init_utils2();init_manager();init_warning_buffer();init_state();init_telemetry();init_timeout();init_hydration_ownership();init_snapshot_reader();init_snapshot_store();init_snapshot_writer();entries=new Map,pendingSettlementObserved=new WeakSet,supersessionStats={count:0};_snapshotCoordinationInternals={entries,initialize:initializeSnapshotCoordination,loadPlan,readSnapshotFileStrict,importSnapshotRowsOnce,renameLegacySnapshot:renameSync28,writeProjection:writeSnapshotProjection,timeoutMs:READY_TIMEOUT_MS}});import*as fsSync17 from"node:fs";import{promises as fs98}from"node:fs";import path164 from"node:path";async function readCloseGateGit(args2,cwd){let raw=await _closeGateInternals.runGit(args2,cwd);if(typeof raw==="string")return{kind:"ok",stdout:raw};if(raw===null)return{kind:"failed",failure:{code:null,status:null,stderrTail:""}};if(raw.ok)return{kind:"ok",stdout:raw.stdout};return{kind:"failed",failure:{code:raw.code,status:raw.status,stderrTail:raw.stderrTail}}}function describeCloseGateStatusFailure(failure){if(!failure)return"The read failed without a reported cause. Inspect git status manually in that directory, then re-run /swarm close.";if(failure.code==="ETIMEDOUT")return"The git status read timed out (ETIMEDOUT): git was launched but did not answer within the deadline — the host process may be unable to complete child spawns while loaded. Restart the OpenCode host (or inspect the host runtime / security software), then re-run /swarm close.";if(failure.code==="EOUTPUT")return`The git status read exceeded its output safety bound (${failure.stderrTail}) — the working set is too large to verify in one read. Reduce the change footprint (commit or stash some work, or remove untracked bulk), then re-run /swarm close.`;if(failure.code==="ESIGNAL")return`The git process was terminated before it answered (signal)${failure.stderrTail?`: ${failure.stderrTail}`:""} — something external (a kill or resource manager) stopped it. Re-run /swarm close; if it recurs, inspect what terminates child processes in this environment.`;if(failure.code==="ENOENT")return"The git executable was not found (ENOENT). Install git on PATH, or set git.binary in your USER-level config (project-level git.binary is ignored), then re-run /swarm close.";if(failure.code!==null)return`The git status read failed to spawn (code ${failure.code}). Inspect git availability in that environment, then re-run /swarm close.`;if(failure.status!==null)return`git status exited with status ${failure.status}${failure.stderrTail?`: ${failure.stderrTail}`:""}. Repair the repository state (for example, a damaged .git/index), then re-run /swarm close.`;return"The git status read failed without a reported cause. Inspect git status manually in that directory, then re-run /swarm close."}function isRealGitRepository2(directory){try{if(fsSync17.statSync(path164.join(directory,".git")).isFile())return!0}catch{return!1}return fsSync17.existsSync(path164.join(directory,".git","HEAD"))}async function evaluateClosePurgeGate(directory,swarmDir){let statusOutput=await readCloseGateGit([...GIT_STATUS_ARGS],directory),parsed=statusOutput.kind==="ok"?parseTrackedDirtyPathsWithExclusions2(statusOutput.stdout):{dirtyPaths:[],excludedOutOfRoot:[]},dirtyPaths=parsed.dirtyPaths,candidates=dirtyPaths.map((p)=>({path:path164.join(directory,p),reason:"uncommitted tracked change — discarded by git alignment"}));for(let entry of[...ACTIVE_STATE_TO_CLEAN,...ACTIVE_STATE_DIRS_TO_CLEAN]){let full=path164.join(swarmDir,entry);if(fsSync17.existsSync(full))candidates.push({path:full,reason:"active swarm state — archived then removed by close"})}return{wouldDestroyTrackedWork:dirtyPaths.length>0,dirtyPaths,candidates,scopeAnchor:candidates[0]?.path??directory,gitStatusFailed:statusOutput.kind==="failed"&&isRealGitRepository2(directory),statusFailure:statusOutput.kind==="failed"&&isRealGitRepository2(directory)?statusOutput.failure:void 0,excludedOutOfRoot:parsed.excludedOutOfRoot}}async function archiveCloseSummary(ctx,closeSummaryPath,summaryWritten){if(!summaryWritten||ctx.archiveStageFailed||!ctx.archiveDir)return;try{await fs98.copyFile(closeSummaryPath,path164.join(ctx.archiveDir,"close-summary.md"))}catch(error93){let msg=error93 instanceof Error?error93.message:String(error93);ctx.warnings.push(`Failed to archive close-summary.md: ${msg}`),log("[close-command] Failed to archive close-summary.md:",error93)}}async function handleCloseCommand(directory,args2,options={}){let swarmDir=path164.join(directory,".swarm");try{if(fsSync17.lstatSync(swarmDir).isSymbolicLink())return"❌ Refused: .swarm/ is a symlink or junction. Refusing to operate on a redirected directory for safety."}catch(err){if(err?.code!=="ENOENT")throw err}let planPath=validateSwarmPath(directory,"plan.json"),planExists=!1,planData={title:path164.basename(directory)||"Ad-hoc session",phases:[]};try{let content=await fs98.readFile(planPath,"utf-8");planData=JSON.parse(content),planExists=!0}catch(error93){if(error93?.code!=="ENOENT")return`❌ Failed to read plan.json: ${error93 instanceof Error?error93.message:String(error93)}`;try{let recovered=(await peekPlanFromLedger(directory)).plan;if(recovered)planData=recovered,planExists=!0}catch(recoveryError){return`❌ Failed to recover plan from the authoritative ledger: ${recoveryError instanceof Error?recoveryError.message:String(recoveryError)}`}if(!planExists){if(!await fs98.access(swarmDir).then(()=>!0).catch(()=>!1))return`❌ No .swarm/ directory found in ${directory}. Run /swarm close from the project root, or run /swarm plan first.`}}if(args2.includes("--dry-run"))return _internals123.runFinalizeDryRun(directory,swarmDir,planData,planExists);let confirmArg=args2.find((a)=>a.startsWith("--confirm=")),confirmToken=confirmArg?confirmArg.slice(10):void 0,purgeGate=await evaluateClosePurgeGate(directory,swarmDir);if(purgeGate.gitStatusFailed)return`\uD83D\uDED1 /swarm close aborted (fail-closed): git status could not be read in ${directory}, so the destructive-purge gate cannot verify uncommitted tracked work. Nothing was closed, archived, or destroyed. ${describeCloseGateStatusFailure(purgeGate.statusFailure)}`;if(confirmToken!==void 0){let verdict=consumeConfirmToken(purgeGate.scopeAnchor,directory,confirmToken,{kind:"swarm-close",candidates:purgeGate.candidates});if(!verdict.ok)return`\uD83D\uDD10 /swarm close confirmation rejected: ${verdict.reason}. Nothing was closed, archived, or destroyed. Re-run /swarm close (without --confirm) for a fresh preview and token.`}else if(purgeGate.wouldDestroyTrackedWork){let activeStateCount=purgeGate.candidates.length-purgeGate.dirtyPaths.length,token=issueConfirmToken(purgeGate.scopeAnchor,directory,{kind:"swarm-close",candidates:purgeGate.candidates}),listed=purgeGate.dirtyPaths.slice(0,10),overflow=purgeGate.dirtyPaths.length-listed.length;return["\uD83D\uDD10 Destructive close preview — confirmation required.","",`Git alignment would DISCARD ${purgeGate.dirtyPaths.length} uncommitted tracked change(s):`,...listed.map((p)=>` - ${p}`),...overflow>0?[` … and ${overflow} more`]:[],...purgeGate.excludedOutOfRoot.length>0?["",`⚠ ${purgeGate.excludedOutOfRoot.length} out-of-root porcelain record(s) were excluded from this scope (first: ${formatExcludedRecord(purgeGate.excludedOutOfRoot[0])})`]:[],"",`${activeStateCount} active-state artifact(s) will be archived, then removed.`,"","Nothing has been closed, archived, or destroyed yet. To execute the destructive close, run:","",`/swarm close --confirm=${token}`,"","The token is valid for 15 minutes and can be used once. Untracked files are not affected."].join(`
|
|
1539
1539
|
`)}let finalizeLock={acquired:!1};if(finalizeLock=await _internals123.acquireFinalizeLock(directory),!finalizeLock.acquired)return"❌ Another /swarm finalize is already running for this project. If you are certain no other run is active, wait for the lock to expire or remove the stale lock and retry.";try{if(await closeSnapshotCoordinationInitialization(directory),!planExists){let archiveDir=path164.join(swarmDir,"archive");try{if((await fs98.readdir(archiveDir)).some((entry)=>entry.startsWith("swarm-"))){if(![...ACTIVE_STATE_TO_CLEAN,...ACTIVE_STATE_DIRS_TO_CLEAN].some((entry)=>fsSync17.existsSync(path164.join(swarmDir,entry))))return`✅ Already finalized — nothing to do.
|
|
1540
1540
|
|
|
1541
|
-
This project was already finalized in a previous /swarm close run. The plan has been archived and cleaned up. No further action is needed.`}}catch{}}let phases=planData.phases??[],inProgressPhases=phases.filter((p)=>p.status==="in_progress"),isForced=args2.includes("--force"),runSkillReview=args2.includes("--skill-review"),planAlreadyDone=!1;if(planExists)planAlreadyDone=phases.length>0&&phases.every((p)=>p.status==="complete"||p.status==="completed"||p.status==="blocked"||p.status==="closed");let{config:loadedConfig}=_internals123.loadPluginConfigWithMeta(directory),config3=KnowledgeConfigSchema.parse(loadedConfig.knowledge??{}),ctx={directory,swarmDir,planData,planExists,planAlreadyDone,config:config3,projectName:planData.title??"Unknown Project",warnings:[],closedPhases:[],closedTasks:[],sessionStart:void 0,isForced,runSkillReview,options,phases,inProgressPhases,curationSucceeded:!1,curationResult:void 0,allLessons:[],explicitLessons:[],retroLessons:[],knowledgeSkillHint:"",skillReviewSummary:"",postMortemSummary:"",sessionReflection:void 0,hivePromoted:0,sessionKnowledgeCreated:0,fallbackKnowledgeCreated:0,dedupDropped:0,dedupAvailable:!0,retroLessonTotal:0,fullAuto:!1,originalStatuses:new Map,guaranteeResult:{closedPhaseIds:[],closedTaskIds:[]},archiveResult:"",archivedFileCount:0,archivedActiveStateFiles:new Set,archivedActiveStateDirs:new Set,archiveFailureReasons:new Map,archiveResults:[],archiveStageFailed:!1,timestamp:"",archiveDir:"",archiveSuffix:"",args:args2,purgeGateDirtyPaths:purgeGate.dirtyPaths};if(ctx.fullAuto=options.sessionID?_internals123.detectFullAuto(directory,options.sessionID):!1,await runFinalizeStage(ctx),ctx.terminalizationError)return`❌ Close paused before reward, archive, cleanup, teardown, and Git alignment because terminal plan/evidence reconciliation failed: ${ctx.terminalizationError}
|
|
1541
|
+
This project was already finalized in a previous /swarm close run. The plan has been archived and cleaned up. No further action is needed.`}}catch{}}let phases=planData.phases??[],inProgressPhases=phases.filter((p)=>p.status==="in_progress"),isForced=args2.includes("--force"),runSkillReview=args2.includes("--skill-review"),planAlreadyDone=!1;if(planExists)planAlreadyDone=phases.length>0&&phases.every((p)=>p.status==="complete"||p.status==="completed"||p.status==="blocked"||p.status==="closed");let{config:loadedConfig}=_internals123.loadPluginConfigWithMeta(directory),config3=KnowledgeConfigSchema.parse(loadedConfig.knowledge??{}),ctx={directory,swarmDir,planData,planExists,planAlreadyDone,config:config3,projectName:planData.title??"Unknown Project",warnings:purgeGate.excludedOutOfRoot.length>0?[`⚠ ${purgeGate.excludedOutOfRoot.length} out-of-root porcelain record(s) were excluded from the destructive scope (first: ${formatExcludedRecord(purgeGate.excludedOutOfRoot[0])})`]:[],closedPhases:[],closedTasks:[],sessionStart:void 0,isForced,runSkillReview,options,phases,inProgressPhases,curationSucceeded:!1,curationResult:void 0,allLessons:[],explicitLessons:[],retroLessons:[],knowledgeSkillHint:"",skillReviewSummary:"",postMortemSummary:"",sessionReflection:void 0,hivePromoted:0,sessionKnowledgeCreated:0,fallbackKnowledgeCreated:0,dedupDropped:0,dedupAvailable:!0,retroLessonTotal:0,fullAuto:!1,originalStatuses:new Map,guaranteeResult:{closedPhaseIds:[],closedTaskIds:[]},archiveResult:"",archivedFileCount:0,archivedActiveStateFiles:new Set,archivedActiveStateDirs:new Set,archiveFailureReasons:new Map,archiveResults:[],archiveStageFailed:!1,timestamp:"",archiveDir:"",archiveSuffix:"",args:args2,purgeGateDirtyPaths:purgeGate.dirtyPaths};if(ctx.fullAuto=options.sessionID?_internals123.detectFullAuto(directory,options.sessionID):!1,await runFinalizeStage(ctx),ctx.terminalizationError)return`❌ Close paused before reward, archive, cleanup, teardown, and Git alignment because terminal plan/evidence reconciliation failed: ${ctx.terminalizationError}
|
|
1542
1542
|
|
|
1543
1543
|
No active state was archived or removed. Fix the reported durable-state problem, then retry /swarm close.`;await _internals123.runFinalizeRewardSweep({directory,closedTaskIds:ctx.guaranteeResult.closedTaskIds,memoryConfig:loadedConfig.memory});let epicFinalization=await finalizeOpenEpicOnSwarmClose(directory,loadedConfig);if(epicFinalization!==null)ctx.warnings.push(epicFinalization);await runArchiveStage(ctx);try{let retentionCfg=loadedConfig.retention,summariesRetentionDays=loadedConfig?.summaries?.retention_days;await runRetentionSweep(directory,{enabled:retentionCfg?.enabled!==!1,dryRun:retentionCfg?.dry_run===!0,summariesRetentionDays:typeof summariesRetentionDays==="number"&&summariesRetentionDays>=1?summariesRetentionDays:void 0})}catch(sweepError){log("[close-command] retention sweep failed (non-fatal):",sweepError)}let cleanResult=await runCleanStage(ctx);emitCloseArchiveResult(ctx,cleanResult);let{gitAlignResult,prunedBranches}=await runAlignStage(ctx),closeSummaryPath=validateSwarmPath(ctx.directory,"close-summary.md"),finalizationType=ctx.isForced?"Forced closure":ctx.planAlreadyDone?"Plan already terminal — cleanup only":"Normal finalization",summaryContent=["# Swarm Close Summary","",`**Project:** ${ctx.projectName}`,`**Closed:** ${new Date().toISOString()}`,`**Finalization:** ${finalizationType}`,"","## Retrospective",!ctx.planExists?"_No plan — ad-hoc session_":ctx.closedPhases.length>0?ctx.closedPhases.map((id)=>`- Phase ${id} closed`).join(`
|
|
1544
1544
|
`):"_No phases closed this run_",...ctx.closedTasks.length>0?["",`**Tasks marked closed:** ${ctx.closedTasks.length}`,...ctx.closedTasks.map((id)=>`- ${id}`)]:[],"","## Lessons Committed",ctx.allLessons.length>0?"| # | Lesson |":"_No lessons committed_",...ctx.allLessons.length>0?["| --- | --- |",...ctx.allLessons.map((l,i)=>`| ${i+1} | ${l} |`)]:[],...ctx.knowledgeSkillHint?["",ctx.knowledgeSkillHint]:[],...ctx.runSkillReview?["","## Skill Review",ctx.skillReviewSummary||"Skill review completed without details."]:[],...ctx.sessionReflection?["",`## Session Reflection (${ctx.sessionReflection.source})`,"",ctx.sessionReflection.architectReport]:[],"","## Local Repo State",...gitAlignResult?[`- **Git:** ${gitAlignResult}`]:["- Git alignment skipped"],...prunedBranches.length>0?[`- **Pruned branches:** ${prunedBranches.join(", ")}`]:[],`- **Archive:** ${ctx.archiveResult}`,...cleanResult.cleanedFiles.length>0?[`- **Cleaned:** ${cleanResult.cleanedFiles.length} file(s)`]:[],"","## Context","- Reset context.md for next session","- Cleared agent sessions, delegation chains, and active-agent mappings",...cleanResult.configBackupsRemoved>0?[`- Removed ${cleanResult.configBackupsRemoved} stale config backup file(s)`]:[],...cleanResult.swarmPlanFilesRemoved>0?[`- Removed ${cleanResult.swarmPlanFilesRemoved} SWARM_PLAN checkpoint artifact(s) from .swarm/plan-export/ and legacy locations`]:[],...ctx.planExists&&!ctx.planAlreadyDone?["- Set non-completed phases/tasks to closed status"]:[],...ctx.curationSucceeded&&ctx.allLessons.length>0?[`- Committed ${ctx.allLessons.length} lesson(s) to knowledge store`]:[],...ctx.hivePromoted>0?[`- Promoted ${ctx.hivePromoted} lesson(s) to hive knowledge`]:[],"",...ctx.warnings.length>0?["## Warnings",...ctx.warnings.map((w)=>`- ${w}`),""]:[]].join(`
|
|
@@ -1576,7 +1576,7 @@ ${ctx.sessionReflection.signalsReport}`;let actionMenuOutput="";if(ctx.sessionRe
|
|
|
1576
1576
|
**Git:** ${gitAlignResult}${lessonSummary}${knowledgeHintSummary}${skillReviewOutput}${postMortemOutput}${reflectionOutput}${signalsOutput}${actionMenuOutput}${warningMsg}`;return`✅ Swarm finalized. ${ctx.closedPhases.length} phase(s) closed, ${ctx.closedTasks.length} incomplete task(s) marked closed.
|
|
1577
1577
|
|
|
1578
1578
|
**Archive:** ${ctx.archiveResult}
|
|
1579
|
-
**Git:** ${gitAlignResult}${lessonSummary}${knowledgeHintSummary}${skillReviewOutput}${postMortemOutput}${reflectionOutput}${signalsOutput}${actionMenuOutput}${warningMsg}`}finally{if(finalizeLock.release)try{await finalizeLock.release()}catch{}}}async function acquireFinalizeLock(directory){let result=await tryAcquireLock(directory,"finalize.lock","close-command","finalize");if(result.acquired)return{acquired:!0,release:result.lock._release};return{acquired:!1}}function detectFullAuto(directory,sessionID){if(hasActiveFullAuto(sessionID))return!0;try{return isFullAutoRunActive(directory,sessionID)}catch{return!1}}var _closeGateInternals;var init_orchestrator=__esm(()=>{init_schema();init_close();init_state2();init_utils2();init_file_locks();init_ledger();init_sweep();init_session_reflection();init_snapshot_coordination_init();init_state();init_atomic_write();init_logger();init_destructive_purge();init_git_status_read();init_align_stage();init_archive_stage();init_clean_stage();init_constants2();init_finalize_stage();init_internals();_closeGateInternals={runGit:(args2,cwd)=>readGitStatusAsync(args2,cwd)}});import*as fs99 from"node:fs";import*as path165 from"node:path";function isValidTelemetryEntry(value){if(typeof value!=="object"||value===null)return!1;let obj=value,nonNegFinite=(v)=>typeof v==="number"&&Number.isFinite(v)&&v>=0;return typeof obj.timestamp==="string"&&typeof obj.task_id==="string"&&typeof obj.agent_role==="string"&&typeof obj.delegation_reason==="string"&&nonNegFinite(obj.token_estimate)&&nonNegFinite(obj.cache_hits)&&nonNegFinite(obj.cache_misses)&&nonNegFinite(obj.stale_entries)&&nonNegFinite(obj.recommended_reads)&&nonNegFinite(obj.skipped_reads)&&typeof obj.success==="boolean"}function telemetryFilePath(directory){return path165.join(directory,".swarm","context-telemetry.jsonl")}function lockFilePath3(directory){return path165.join(directory,".swarm","context-telemetry.lock")}function tmpFilePath(directory){return path165.join(directory,".swarm",`.context-telemetry.jsonl.${process.pid}.tmp`)}function emptyFolded3(){return{delegations:0,successCount:0,cacheHits:0,cacheMisses:0,staleEntries:0,tokenSum:0,recommendedReads:0,skippedReads:0,corrupt:0,dropped:0,oldestTimestamp:null,newestTimestamp:null}}function emptyManifest3(){return{v:2,type:MANIFEST_TYPE3,schemaVersion:MANIFEST_SCHEMA3,folded:emptyFolded3(),updatedAt:new Date().toISOString()}}function parseManifestLine3(line){let trimmed=line.trim();if(!trimmed)return null;try{let obj=JSON.parse(trimmed);if(typeof obj!=="object"||obj===null)return null;let rec=obj;if(rec.type!==MANIFEST_TYPE3||rec.v!==2||rec.schemaVersion!==MANIFEST_SCHEMA3||typeof rec.folded!=="object"||rec.folded===null)return null;let f=rec.folded,manifest=emptyManifest3(),num=(v)=>typeof v==="number"&&Number.isFinite(v)&&v>=0?v:0;if(manifest.folded.delegations=num(f.delegations),manifest.folded.successCount=num(f.successCount),manifest.folded.cacheHits=num(f.cacheHits),manifest.folded.cacheMisses=num(f.cacheMisses),manifest.folded.staleEntries=num(f.staleEntries),manifest.folded.tokenSum=num(f.tokenSum),manifest.folded.recommendedReads=num(f.recommendedReads),manifest.folded.skippedReads=num(f.skippedReads),manifest.folded.corrupt=num(f.corrupt),manifest.folded.dropped=num(f.dropped),typeof f.oldestTimestamp==="string")manifest.folded.oldestTimestamp=f.oldestTimestamp;if(typeof f.newestTimestamp==="string")manifest.folded.newestTimestamp=f.newestTimestamp;return manifest.updatedAt=typeof rec.updatedAt==="string"?rec.updatedAt:new Date().toISOString(),manifest}catch{return null}}function readBoundedChunk3(filePath,maxBytes){try{if(!_internals143.existsSync(filePath))return{text:"",truncated:!1};let fd=_internals143.openSync(filePath,"r");try{let size=_internals143.statSync(filePath).size,truncated=size>maxBytes,len=Math.min(size,maxBytes),buf=Buffer.alloc(len),read=0;while(read<len){let n=_internals143.readSync(fd,buf,read,len-read,read);if(n<=0)break;read+=n}return{text:buf.toString("utf-8",0,read),truncated}}finally{_internals143.closeSync(fd)}}catch{return warnThrottled3("bounded read failed (transient I/O)"),{text:"",truncated:!1}}}function fileSizeOrZero3(filePath){try{if(!_internals143.existsSync(filePath))return 0;return _internals143.statSync(filePath).size}catch{return 0}}function foldEntryInto(agg,entry){if(agg.delegations+=1,entry.success)agg.successCount+=1;if(agg.cacheHits+=entry.cache_hits,agg.cacheMisses+=entry.cache_misses,agg.staleEntries+=entry.stale_entries,agg.tokenSum+=entry.token_estimate,agg.recommendedReads+=entry.recommended_reads,agg.skippedReads+=entry.skipped_reads,agg.oldestTimestamp===null||entry.timestamp<agg.oldestTimestamp)agg.oldestTimestamp=entry.timestamp;if(agg.newestTimestamp===null||entry.timestamp>agg.newestTimestamp)agg.newestTimestamp=entry.timestamp}function cloneFolded3(agg){return{delegations:agg.delegations,successCount:agg.successCount,cacheHits:agg.cacheHits,cacheMisses:agg.cacheMisses,staleEntries:agg.staleEntries,tokenSum:agg.tokenSum,recommendedReads:agg.recommendedReads,skippedReads:agg.skippedReads,corrupt:agg.corrupt,dropped:agg.dropped,oldestTimestamp:agg.oldestTimestamp,newestTimestamp:agg.newestTimestamp}}function atomicReplace3(directory,content){let finalPath=telemetryFilePath(directory),tmpPath=tmpFilePath(directory);try{if(_internals143.existsSync(tmpPath))try{_internals143.unlinkSync(tmpPath)}catch{}_internals143.writeFileSync(tmpPath,content,"utf-8"),_internals143.renameSync(tmpPath,finalPath)}catch{try{if(_internals143.existsSync(tmpPath))_internals143.unlinkSync(tmpPath)}catch{}throw Error("context-telemetry atomic replace failed")}}function withStoreLock(directory,fn2){let lockPath=lockFilePath3(directory),acquired=!1;try{_internals143.mkdirSync(path165.dirname(lockPath),{recursive:!0});let fd=_internals143.openSync(lockPath,"wx");_internals143.closeSync(fd),acquired=!0}catch{try{if(Date.now()-_internals143.statSync(lockPath).mtimeMs>300000){try{_internals143.unlinkSync(lockPath)}catch{}try{let fd=_internals143.openSync(lockPath,"wx");_internals143.closeSync(fd),acquired=!0}catch{acquired=!1}}}catch{acquired=!1}}if(!acquired)return null;try{return fn2()}finally{try{_internals143.unlinkSync(lockPath)}catch{}}}function shouldRunMaintenance3(){if(_recordCount+=1,_recordCount>=_internals143.limits.checkInterval)return _recordCount=0,!0;return!1}function warnThrottled3(message){let now2=Date.now();if(now2-_lastWarnAt3<_internals143.limits.warnCooldownMs)return;_lastWarnAt3=now2,warn(`context-telemetry: ${message}`)}function readStore3(directory,bounded){let filePath=telemetryFilePath(directory);if(!_internals143.existsSync(filePath))return{manifest:null,records:[],corruptLines:0,truncated:!1};let text,truncated=!1;if(bounded){let chunk=readBoundedChunk3(filePath,_internals143.limits.readMaxBytes);text=chunk.text,truncated=chunk.truncated}else try{text=_internals143.readFileSync(filePath,"utf-8")}catch{return{manifest:null,records:[],corruptLines:0,truncated:!1}}let lines=text.split(`
|
|
1579
|
+
**Git:** ${gitAlignResult}${lessonSummary}${knowledgeHintSummary}${skillReviewOutput}${postMortemOutput}${reflectionOutput}${signalsOutput}${actionMenuOutput}${warningMsg}`}finally{if(finalizeLock.release)try{await finalizeLock.release()}catch{}}}async function acquireFinalizeLock(directory){let result=await tryAcquireLock(directory,"finalize.lock","close-command","finalize");if(result.acquired)return{acquired:!0,release:result.lock._release};return{acquired:!1}}function detectFullAuto(directory,sessionID){if(hasActiveFullAuto(sessionID))return!0;try{return isFullAutoRunActive(directory,sessionID)}catch{return!1}}var _closeGateInternals;var init_orchestrator=__esm(()=>{init_schema();init_close();init_state2();init_utils2();init_file_locks();init_ledger();init_sweep();init_session_reflection();init_snapshot_coordination_init();init_state();init_atomic_write();init_logger();init_destructive_purge();init_git_status_read();init_rollback_gate();init_align_stage();init_archive_stage();init_clean_stage();init_constants2();init_finalize_stage();init_internals();_closeGateInternals={runGit:(args2,cwd)=>readGitStatusAsync(args2,cwd)}});import*as fs99 from"node:fs";import*as path165 from"node:path";function isValidTelemetryEntry(value){if(typeof value!=="object"||value===null)return!1;let obj=value,nonNegFinite=(v)=>typeof v==="number"&&Number.isFinite(v)&&v>=0;return typeof obj.timestamp==="string"&&typeof obj.task_id==="string"&&typeof obj.agent_role==="string"&&typeof obj.delegation_reason==="string"&&nonNegFinite(obj.token_estimate)&&nonNegFinite(obj.cache_hits)&&nonNegFinite(obj.cache_misses)&&nonNegFinite(obj.stale_entries)&&nonNegFinite(obj.recommended_reads)&&nonNegFinite(obj.skipped_reads)&&typeof obj.success==="boolean"}function telemetryFilePath(directory){return path165.join(directory,".swarm","context-telemetry.jsonl")}function lockFilePath3(directory){return path165.join(directory,".swarm","context-telemetry.lock")}function tmpFilePath(directory){return path165.join(directory,".swarm",`.context-telemetry.jsonl.${process.pid}.tmp`)}function emptyFolded3(){return{delegations:0,successCount:0,cacheHits:0,cacheMisses:0,staleEntries:0,tokenSum:0,recommendedReads:0,skippedReads:0,corrupt:0,dropped:0,oldestTimestamp:null,newestTimestamp:null}}function emptyManifest3(){return{v:2,type:MANIFEST_TYPE3,schemaVersion:MANIFEST_SCHEMA3,folded:emptyFolded3(),updatedAt:new Date().toISOString()}}function parseManifestLine3(line){let trimmed=line.trim();if(!trimmed)return null;try{let obj=JSON.parse(trimmed);if(typeof obj!=="object"||obj===null)return null;let rec=obj;if(rec.type!==MANIFEST_TYPE3||rec.v!==2||rec.schemaVersion!==MANIFEST_SCHEMA3||typeof rec.folded!=="object"||rec.folded===null)return null;let f=rec.folded,manifest=emptyManifest3(),num=(v)=>typeof v==="number"&&Number.isFinite(v)&&v>=0?v:0;if(manifest.folded.delegations=num(f.delegations),manifest.folded.successCount=num(f.successCount),manifest.folded.cacheHits=num(f.cacheHits),manifest.folded.cacheMisses=num(f.cacheMisses),manifest.folded.staleEntries=num(f.staleEntries),manifest.folded.tokenSum=num(f.tokenSum),manifest.folded.recommendedReads=num(f.recommendedReads),manifest.folded.skippedReads=num(f.skippedReads),manifest.folded.corrupt=num(f.corrupt),manifest.folded.dropped=num(f.dropped),typeof f.oldestTimestamp==="string")manifest.folded.oldestTimestamp=f.oldestTimestamp;if(typeof f.newestTimestamp==="string")manifest.folded.newestTimestamp=f.newestTimestamp;return manifest.updatedAt=typeof rec.updatedAt==="string"?rec.updatedAt:new Date().toISOString(),manifest}catch{return null}}function readBoundedChunk3(filePath,maxBytes){try{if(!_internals143.existsSync(filePath))return{text:"",truncated:!1};let fd=_internals143.openSync(filePath,"r");try{let size=_internals143.statSync(filePath).size,truncated=size>maxBytes,len=Math.min(size,maxBytes),buf=Buffer.alloc(len),read=0;while(read<len){let n=_internals143.readSync(fd,buf,read,len-read,read);if(n<=0)break;read+=n}return{text:buf.toString("utf-8",0,read),truncated}}finally{_internals143.closeSync(fd)}}catch{return warnThrottled3("bounded read failed (transient I/O)"),{text:"",truncated:!1}}}function fileSizeOrZero3(filePath){try{if(!_internals143.existsSync(filePath))return 0;return _internals143.statSync(filePath).size}catch{return 0}}function foldEntryInto(agg,entry){if(agg.delegations+=1,entry.success)agg.successCount+=1;if(agg.cacheHits+=entry.cache_hits,agg.cacheMisses+=entry.cache_misses,agg.staleEntries+=entry.stale_entries,agg.tokenSum+=entry.token_estimate,agg.recommendedReads+=entry.recommended_reads,agg.skippedReads+=entry.skipped_reads,agg.oldestTimestamp===null||entry.timestamp<agg.oldestTimestamp)agg.oldestTimestamp=entry.timestamp;if(agg.newestTimestamp===null||entry.timestamp>agg.newestTimestamp)agg.newestTimestamp=entry.timestamp}function cloneFolded3(agg){return{delegations:agg.delegations,successCount:agg.successCount,cacheHits:agg.cacheHits,cacheMisses:agg.cacheMisses,staleEntries:agg.staleEntries,tokenSum:agg.tokenSum,recommendedReads:agg.recommendedReads,skippedReads:agg.skippedReads,corrupt:agg.corrupt,dropped:agg.dropped,oldestTimestamp:agg.oldestTimestamp,newestTimestamp:agg.newestTimestamp}}function atomicReplace3(directory,content){let finalPath=telemetryFilePath(directory),tmpPath=tmpFilePath(directory);try{if(_internals143.existsSync(tmpPath))try{_internals143.unlinkSync(tmpPath)}catch{}_internals143.writeFileSync(tmpPath,content,"utf-8"),_internals143.renameSync(tmpPath,finalPath)}catch{try{if(_internals143.existsSync(tmpPath))_internals143.unlinkSync(tmpPath)}catch{}throw Error("context-telemetry atomic replace failed")}}function withStoreLock(directory,fn2){let lockPath=lockFilePath3(directory),acquired=!1;try{_internals143.mkdirSync(path165.dirname(lockPath),{recursive:!0});let fd=_internals143.openSync(lockPath,"wx");_internals143.closeSync(fd),acquired=!0}catch{try{if(Date.now()-_internals143.statSync(lockPath).mtimeMs>300000){try{_internals143.unlinkSync(lockPath)}catch{}try{let fd=_internals143.openSync(lockPath,"wx");_internals143.closeSync(fd),acquired=!0}catch{acquired=!1}}}catch{acquired=!1}}if(!acquired)return null;try{return fn2()}finally{try{_internals143.unlinkSync(lockPath)}catch{}}}function shouldRunMaintenance3(){if(_recordCount+=1,_recordCount>=_internals143.limits.checkInterval)return _recordCount=0,!0;return!1}function warnThrottled3(message){let now2=Date.now();if(now2-_lastWarnAt3<_internals143.limits.warnCooldownMs)return;_lastWarnAt3=now2,warn(`context-telemetry: ${message}`)}function readStore3(directory,bounded){let filePath=telemetryFilePath(directory);if(!_internals143.existsSync(filePath))return{manifest:null,records:[],corruptLines:0,truncated:!1};let text,truncated=!1;if(bounded){let chunk=readBoundedChunk3(filePath,_internals143.limits.readMaxBytes);text=chunk.text,truncated=chunk.truncated}else try{text=_internals143.readFileSync(filePath,"utf-8")}catch{return{manifest:null,records:[],corruptLines:0,truncated:!1}}let lines=text.split(`
|
|
1580
1580
|
`),records=[],corruptLines=0,manifest=null;for(let i=0;i<lines.length;i+=1){let line=lines[i];if(line.trim()==="")continue;if(i===0){if(manifest=parseManifestLine3(line),manifest)continue}try{let parsed=JSON.parse(line);if(isValidTelemetryEntry(parsed))records.push(parsed);else corruptLines+=1}catch{corruptLines+=1}}return{manifest,records,corruptLines,truncated}}function fileEndsWithNewline3(filePath){try{if(!_internals143.existsSync(filePath))return!0;let size=_internals143.statSync(filePath).size;if(size===0)return!0;let fd=_internals143.openSync(filePath,"r");try{let buf=Buffer.alloc(1);return _internals143.readSync(fd,buf,0,1,size-1)<=0||buf[0]===10}finally{_internals143.closeSync(fd)}}catch{return!0}}function recordTelemetry(entry,directory){let filePath=telemetryFilePath(directory),swarmDir=path165.join(directory,".swarm");try{if(_internals143.mkdirSync(swarmDir,{recursive:!0}),withStoreLock(directory,()=>{if(!_internals143.existsSync(filePath)){let manifest=emptyManifest3();atomicReplace3(directory,`${JSON.stringify(manifest)}
|
|
1581
1581
|
${JSON.stringify(entry)}
|
|
1582
1582
|
`)}else{let prefix=fileEndsWithNewline3(filePath)?"":`
|
|
@@ -2331,7 +2331,7 @@ FROM memory_events ORDER BY rowid ASC`,MEMORY_ITEM_BY_ID_SQL="SELECT id, record_
|
|
|
2331
2331
|
);
|
|
2332
2332
|
CREATE INDEX IF NOT EXISTS idx_memory_relations_source
|
|
2333
2333
|
ON memory_relations(source_id, target_id);
|
|
2334
|
-
`}];FTS_STOP_WORDS=new Set(["a","an","and","are","as","at","be","by","for","from","goal","how","in","into","is","it","of","on","or","role","task","that","the","this","to","user","what","when","with"])});import{mkdirSync as mkdirSync52}from"node:fs";function markAsPooled(provider){let originalClose=provider.close;if(provider.close=()=>{return releaseProvider(provider),Promise.resolve()},provider[POOLED_MARKER]=!0,originalClose)provider[REAL_CLOSE]=originalClose}function callRealClose(provider){let realClose=provider[REAL_CLOSE];try{realClose?.call(provider)}catch(err){let msg=err instanceof Error?err.message:String(err);if(process.env.OPENCODE_SWARM_DEBUG==="1")console.debug(`[provider-pool] real close failed: ${msg}`)}}function isPooledProvider(provider){return POOLED_MARKER in provider}function getOrCreateProviderForRoot(root,config3){if(root.kind==="cohort"&&canonicalExistingFilesystemPath(root.cohortRoot)===null&&!resolvedKeyCache.has(rawPoolKey(root.cohortRoot)))try{mkdirSync52(root.cohortRoot,{recursive:!0})}catch{}let key2=resolvePoolKeyForRoot(root),rootGeneration=root.kind==="cohort"?root.generation:0,existing=entriesByKey.get(key2);if(existing){if((existing.generation??0)===rootGeneration)return moveToHead(existing),existing.refCount++,existing.provider;evictEntryByKey(key2)}for(let deferred of deferredEntries)if(deferred.key===key2){if((deferred.generation??0)===rootGeneration){if(deferredEntries.delete(deferred),entriesByKey.size>=MAX_POOL_SIZE)evictLru();if(deferred.prev=null,deferred.next=head,head)head.prev=deferred;if(head=deferred,!tail)tail=deferred;return entriesByKey.set(key2,deferred),deferred.refCount++,deferred.provider}deferredEntries.delete(deferred),callRealClose(deferred.provider);break}let directory=root.kind==="local"?key2:resolvePoolKey(root.directory),cohortRoot=root.kind==="cohort"?key2.slice(7):null,provider=new SQLiteMemoryProvider(directory,config3,cohortRoot);if(markAsPooled(provider),entriesByKey.size>=MAX_POOL_SIZE)evictLru();let entry={key:key2,provider,refCount:1,prev:null,next:head};if(entry.generation=rootGeneration,head)head.prev=entry;if(head=entry,!tail)tail=entry;return entriesByKey.set(key2,entry),provider}function resolvePoolKeyForRoot(root){if(root.kind==="cohort")return`cohort:${resolvePoolKey(root.cohortRoot)}`;return resolvePoolKey(root.directory)}function evictEntryByKey(key2){let entry=entriesByKey.get(key2);if(!entry)return;if(entry.refCount>0){deferredEntries.add(entry),unlinkEntry(entry),entriesByKey.delete(key2);return}unlinkEntry(entry),entriesByKey.delete(key2),callRealClose(entry.provider)}function evictAndCloseForRoot(root){let key2=resolvePoolKeyForRoot(root);evictEntryByKey(key2)}function releaseProvider(provider){for(let[_key,entry]of entriesByKey)if(entry.provider===provider){entry.refCount=Math.max(0,entry.refCount-1);return}for(let entry of deferredEntries)if(entry.provider===provider){if(entry.refCount--,entry.refCount<=0)deferredEntries.delete(entry),callRealClose(provider);return}if(isPooledProvider(provider))callRealClose(provider)}function evictLru(){if(!tail)return;let evicted=tail;if(entriesByKey.delete(evicted.key),unlinkEntry(evicted),evicted.refCount>0)deferredEntries.add(evicted);else callRealClose(evicted.provider)}function moveToHead(entry){if(head===entry)return;if(unlinkEntry(entry),entry.prev=null,entry.next=head,head)head.prev=entry;if(head=entry,!tail)tail=entry}function unlinkEntry(entry){if(entry.prev)entry.prev.next=entry.next;if(entry.next)entry.next.prev=entry.prev;if(head===entry)head=entry.next;if(tail===entry)tail=entry.prev}function resolvePoolKey(directory){let rawKey=rawPoolKey(directory),canonical=canonicalExistingFilesystemPath(directory);if(canonical!==null)return rememberResolvedKey(rawKey,canonical,filesystemIdentityWitnesses(directory)),canonical;let prior=resolvedKeyCache.get(rawKey),inferred=canonicalPathFromExistingAncestor(directory),witnessRetargeted=prior?.witnesses.some((witness)=>{let current=canonicalExistingFilesystemPath(witness.lexicalPath);return current!==null&¤t!==witness.canonicalPath});if(inferred&&(prior===void 0||inferred.existingAncestorIsLink||witnessRetargeted))return rememberResolvedKey(rawKey,inferred.canonicalPath,inferred.identityWitnesses),inferred.canonicalPath;if(prior)return prior.key;if(inferred)return inferred.canonicalPath;throw new MemoryValidationError("memory storage root physical identity could not be resolved")}function rememberResolvedKey(rawKey,canonical,witnesses){if(resolvedKeyCache.delete(rawKey),resolvedKeyCache.set(rawKey,{key:canonical,witnesses}),resolvedKeyCache.size>MAX_POOL_SIZE){let oldest=resolvedKeyCache.keys().next().value;if(oldest!==void 0)resolvedKeyCache.delete(oldest)}}function rawPoolKey(directory){return lexicalRootAliasKey(directory)}function evictAndClose(directory){let key2=resolvePoolKey(directory),active=entriesByKey.get(key2);if(active)entriesByKey.delete(key2),unlinkEntry(active),callRealClose(active.provider);for(let deferred of[...deferredEntries])if(deferred.key===key2)deferredEntries.delete(deferred),callRealClose(deferred.provider)}var MAX_POOL_SIZE=16,POOLED_MARKER,REAL_CLOSE,head=null,tail=null,entriesByKey,deferredEntries,resolvedKeyCache;var init_provider_pool=__esm(()=>{init_canonical_root();init_filesystem_identity();init_errors6();init_sqlite_provider();POOLED_MARKER=Symbol("opencode-swarm-pooled-provider"),REAL_CLOSE=Symbol("opencode-swarm-real-close"),entriesByKey=new Map,deferredEntries=new Set,resolvedKeyCache=new Map});import{existsSync as existsSync89,mkdirSync as mkdirSync53,readFileSync as readFileSync66,rmSync as rmSync22,statSync as statSync60}from"node:fs";import*as path181 from"node:path";function resolveMemoryLinkPointerPath(directory){return path181.join(directory,".swarm",MEMORY_LINK_POINTER_FILENAME)}function readMemoryLinkPointer(directory){let pointerPath=resolveMemoryLinkPointerPath(directory);if(!existsSync89(pointerPath))return null;try{let raw=JSON.parse(readFileSync66(pointerPath,"utf-8"));if(!raw||typeof raw!=="object")return null;let obj=raw,linkId=obj.linkId;if(typeof linkId!=="string"||linkId.length===0)return null;let safeId=sanitizeLinkId(linkId);if(!safeId)return null;return{version:obj.version===2?2:1,linkId:safeId,name:typeof obj.name==="string"?obj.name:void 0,createdAt:typeof obj.createdAt==="string"?obj.createdAt:new Date(0).toISOString(),cohortId:typeof obj.cohortId==="string"?obj.cohortId:void 0,identitySource:obj.identitySource==="remote"||obj.identitySource==="git-common-dir"||obj.identitySource==="path"?obj.identitySource:void 0,degraded:typeof obj.degraded==="boolean"?obj.degraded:void 0,configFingerprint:typeof obj.configFingerprint==="string"?obj.configFingerprint:void 0,generation:typeof obj.generation==="number"?obj.generation:void 0}}catch{return null}}async function writeMemoryLinkPointer(directory,pointer){let swarmDir=path181.join(directory,".swarm");mkdirSync53(swarmDir,{recursive:!0});let pointerPath=resolveMemoryLinkPointerPath(directory);await atomicWriteFile(pointerPath,JSON.stringify(pointer,null,2)),invalidateMemoryStoreDirCache(directory)}async function removeMemoryLinkPointer(directory){let pointerPath=resolveMemoryLinkPointerPath(directory);try{rmSync22(pointerPath,{force:!0})}finally{invalidateMemoryStoreDirCache(directory)}}function pointerStatFingerprint2(directory){let pointerPath=resolveMemoryLinkPointerPath(directory);try{let st=statSync60(pointerPath);return`${st.mtimeMs}:${st.ctimeMs}:${st.size}`}catch{return null}}function resolveMemoryStoreDir(directory){let localSwarm=path181.join(directory,".swarm"),cacheKey=canonicalRootKeyFresh(directory),now2=Date.now(),cached3=_resolutionCache2.get(cacheKey),currentStat=pointerStatFingerprint2(directory);if(cached3&&now2<cached3.expires&&cached3.pointerStat===currentStat)return cached3.linkDir??localSwarm;let linkDir=null;try{let pointer=readMemoryLinkPointer(directory);if(pointer)linkDir=path181.resolve(resolveLinkDir(pointer.linkId))}catch{linkDir=null}if(!_resolutionCache2.has(cacheKey)&&_resolutionCache2.size>=MAX_CACHE_ENTRIES3){let oldest=_resolutionCache2.keys().next().value;if(oldest!==void 0)_resolutionCache2.delete(oldest)}return _resolutionCache2.set(cacheKey,{linkDir,expires:now2+CACHE_TTL_MS2,pointerStat:currentStat}),linkDir??localSwarm}function invalidateMemoryStoreDirCache(directory){if(directory===void 0){_resolutionCache2.clear();return}_resolutionCache2.delete(canonicalRootKeyFresh(directory))}var MEMORY_LINK_POINTER_FILENAME="memory-link.json",CACHE_TTL_MS2=2000,MAX_CACHE_ENTRIES3=500,_resolutionCache2;var init_memory_link=__esm(()=>{init_task_file();init_knowledge_link();init_canonical_root();init_logger();_resolutionCache2=new Map});import*as path182 from"node:path";function resolveVettedMemoryRoot(directory,config3){if(config3?.link?.enabled!==!0){let existingPointer=readMemoryLinkPointer(directory);if(existingPointer)warn(`[memory-link] memory.link.enabled is false but a cohort pointer exists (linkId=${existingPointer.linkId}). Cohort memory is unreachable — run \`/swarm memory link\` or remove the pointer with \`/swarm memory unlink\`.`,{directory,linkId:existingPointer.linkId});return wrapLocalRoot(directory)}let pointer=readMemoryLinkPointer(directory);if(!pointer)return wrapLocalRoot(directory);let sharedDir=resolveMemoryStoreDir(directory),localSwarm=path182.join(directory,".swarm");if(sharedDir===localSwarm)return wrapLocalRoot(directory);return{kind:"cohort",cohortRoot:path182.join(sharedDir,"memory"),cohortId:pointer.cohortId??pointer.linkId,generation:pointer.generation??0,linkId:pointer.linkId,directory}}function wrapLocalRoot(directory){return log("[memory] wrapping raw directory as local vetted root — cohort sharing inactive for this caller",{directory}),{kind:"local",root:path182.join(directory,".swarm"),directory}}function isCohortRoot(root){return root.kind==="cohort"}function rootStoragePath(root){return root.kind==="cohort"?root.cohortRoot:path182.join(root.root,"memory")}var init_storage_root=__esm(()=>{init_logger();init_memory_link()});import{createHash as createHash76,randomUUID as randomUUID27}from"node:crypto";import{existsSync as existsSync90,mkdirSync as mkdirSync54,readFileSync as readFileSync67}from"node:fs";import*as path183 from"node:path";class MemoryGateway{context;config;provider;vettedRoot;now;disposed=!1;piiDetector;constructor(context,options={}){this.config=resolveMemoryConfig(options.config??DEFAULT_MEMORY_CONFIG),this.context={...context,directory:requirePhysicalFutureIoPath(context.directory)},this.vettedRoot=resolveVettedMemoryRoot(this.context.directory,this.config),this.provider=options.provider??createConfiguredMemoryProviderForRoot(this.vettedRoot,this.config),this.now=options.now??(()=>new Date)}isEnabled(){return this.config.enabled}async dispose(){if(this.disposed)return;this.disposed=!0,await this.provider.close?.()}deriveAllowedScopes(){let resolvedRoot=this.context.directory,repoId=createStableId(readGitRemoteUrl(resolvedRoot)??path183.basename(resolvedRoot)),scopes=[{type:"workspace",workspaceId:createStableId(path183.dirname(resolvedRoot))},{type:"repository",repoId,repoRoot:resolvedRoot}];if(isCohortRoot(this.vettedRoot))scopes.push({type:"cohort",cohortId:this.vettedRoot.cohortId});if(this.context.runId||this.context.sessionID)scopes.push({type:"run",runId:this.context.runId??this.context.sessionID});if(this.context.agentId||this.context.agentRole)scopes.push({type:"agent",agentId:this.context.agentId??this.context.agentRole,runId:this.context.runId??this.context.sessionID});return scopes}async recall(input,options){this.assertEnabled();let query=normalizeMemoryText(input.query);if(query.length<3)throw new MemoryValidationError("query must be at least 3 characters");let maxItems=clampInt(input.maxItems??this.config.recall.defaultMaxItems,1,20),tokenBudget=clampInt(input.tokenBudget??this.config.recall.defaultTokenBudget,100,5000),generatedAt=this.now().toISOString(),allowedScopes=this.deriveAllowedScopes(),scopes=input.scopes?validateRequestedScopes(input.scopes,allowedScopes):allowedScopes,request={query,task:input.task,agentRole:this.context.agentRole,mode:input.mode??"manual",scopes,kinds:input.kinds,maxItems,tokenBudget,minScore:input.minScore??this.config.recall.minScore,requireQuerySignal:input.requireQuerySignal,includeExpired:input.includeExpired},recallResult=this.provider.recallWithDiagnostics?await this.provider.recallWithDiagnostics(request):{items:await this.provider.recall(request)},bundle=toRecallBundle({id:createBundleId(query,generatedAt),query,generatedAt,items:recallResult.items,tokenBudget,diagnostics:recallResult.diagnostics?{injectionSkipReason:input.mode==="injection"?resolveInjectionSkipReason(recallResult.diagnostics):void 0,candidateCount:recallResult.diagnostics.candidateCount,preScoredFilteredCount:recallResult.diagnostics.preScoredFilteredCount,noSignalCount:recallResult.diagnostics.noSignalCount,belowThresholdCount:recallResult.diagnostics.belowThresholdCount}:void 0});if(options?.recordUsage===!1)return bundle;return await this.provider.recordRecallUsage?.({bundleId:bundle.id,query,scopes,kinds:input.kinds,memoryIds:bundle.items.map((item)=>item.record.id),scores:bundle.items.map((item)=>item.score),tokenEstimate:bundle.tokenEstimate,agentRole:this.context.agentRole,runId:this.context.runId??this.context.sessionID,unitId:this.context.unitId,timestamp:generatedAt}),bundle}async propose(input){if(this.assertEnabled(),!this.provider.createProposal)throw new MemoryValidationError("memory provider does not support proposals");let redactedFields=new Set,redactProposalField=(field,value)=>{let redacted=redactSecrets(value);if(redacted!==value)redactedFields.add(field);return redacted},rationale=redactProposalField("rationale",normalizeMemoryText(input.rationale));if(!rationale)throw new MemoryValidationError("rationale is required");let evidenceRefs=(input.evidenceRefs??[]).map((ref)=>normalizeMemoryText(ref)).filter(Boolean).map((ref)=>redactProposalField("evidenceRefs",ref)).slice(0,20),needsRecord=input.operation==="add"||input.operation==="update"||input.operation==="supersede",proposedRecord,status2="pending",reviewer,reviewedAt,rejectionReason,targetMemoryId=input.targetMemoryId===void 0?void 0:redactProposalField("targetMemoryId",normalizeMemoryText(input.targetMemoryId)),relatedMemoryIds=input.relatedMemoryIds?canonicalMemoryIds(input.relatedMemoryIds.map((id)=>redactProposalField("relatedMemoryIds",normalizeMemoryText(id)))):void 0,proposalText=`${input.operation}:${targetMemoryId??""}`;if(input.operation==="merge")proposalText=`merge:${(relatedMemoryIds??[]).join(",")}`;let piiSummary;if(needsRecord){if(!input.kind)throw new MemoryValidationError("kind is required for this operation");if(!input.text)throw new MemoryValidationError("text is required for this operation");proposalText=input.text;let normalizedText=normalizeMemoryText(input.text),redactedText=redactProposalField("text",normalizedText),extractedPaths=extractFilePaths(evidenceRefs),extractedSymbols=extractSymbols2(evidenceRefs),recordMetadata={};if(extractedPaths.length>0)recordMetadata.files=extractedPaths;if(extractedSymbols.length>0)recordMetadata.symbols=extractedSymbols;proposedRecord=this.createRecord({kind:input.kind,text:redactedText,evidenceRefs,source:sourceFromEvidence(evidenceRefs,this.context),metadata:recordMetadata}),{piiSummary}=await this.validateRecordWithPiiPolicy(proposedRecord)}if(redactedFields.size>0)status2="rejected",reviewer="auto_policy",reviewedAt=this.now().toISOString(),rejectionReason=`proposal field(s) contained a likely secret and were redacted: ${Array.from(redactedFields).join(", ")}`;if((input.operation==="update"||input.operation==="delete"||input.operation==="supersede")&&!targetMemoryId)throw new MemoryValidationError(`${input.operation} proposals require targetMemoryId`);if(input.operation==="merge"&&((relatedMemoryIds??[]).length<2||(relatedMemoryIds??[]).length>MAX_MERGE_PARTICIPANTS))throw new MemoryValidationError(`merge proposals require 2-${MAX_MERGE_PARTICIPANTS} distinct relatedMemoryIds`);let createdAt=this.now().toISOString(),proposer=this.context.agentId??this.context.agentRole??this.context.sessionID??"unknown",proposal={id:createProposalId({createdAt,proposer,text:proposalText}),operation:input.operation,proposedRecord,targetMemoryId,relatedMemoryIds,proposedBy:{agentRole:this.context.agentRole,agentId:this.context.agentId,runId:this.context.runId??this.context.sessionID},rationale,evidenceRefs,status:status2,reviewer,reviewedAt,rejectionReason,createdAt,metadata:piiSummary?{pii:piiSummary}:{}};return this.provider.createProposal(proposal)}async listMemories(filter={}){return this.assertEnabled(),this.provider.list(filter)}async listProposals(filter){if(this.assertEnabled(),!this.provider.listProposals)throw new MemoryValidationError("memory provider does not support proposals");return this.provider.listProposals(filter)}async listRecallUsage(filter){if(this.assertEnabled(),!this.provider.listRecallUsage)return[];return this.provider.listRecallUsage(filter)}async upsertCurated(record3){this.assertEnabled();let{parsed}=await this.validateRecordWithPiiPolicy(record3);return this.provider.upsert(parsed)}async recordOutcome(input){if(this.assertEnabled(),!this.provider.appendOutcome)throw new MemoryValidationError("memory provider does not support outcome capture");let hasId=typeof input.memoryId==="string"&&input.memoryId.length>0,question=input.question?normalizeMemoryText(input.question):"";if(hasId===question.length>0)throw new MemoryValidationError("exactly one of memoryId or question is required");if(question.length>MAX_OUTCOME_QUESTION_LENGTH)throw new MemoryValidationError(`question must be at most ${MAX_OUTCOME_QUESTION_LENGTH} characters`);if(input.outcome==="corrected"&&!input.correction?.trim())throw new MemoryValidationError("corrected outcomes require correction text");if(input.correction)await this.enforcePiiTextPolicy(normalizeMemoryText(input.correction));let targetId=input.memoryId;if(!targetId){let candidate=this.createRecord({kind:"evidence",text:`${MEMORY_OUTCOME_QUESTION_PREFIX}${question}`,confidence:0.5,stability:"durable",tags:["outcome-result"],source:{type:"tool",ref:"swarm_memory_outcome"},metadata:{outcomeQuestion:question}});if(!await this.provider.get(candidate.id))await this.validateRecordWithPiiPolicy(candidate),await this.provider.upsert(candidate);targetId=candidate.id}let priorEvent=input.eventId&&this.provider.listOutcomeEvents?(await this.provider.listOutcomeEvents()).find((event)=>event.id===input.eventId):void 0;if(priorEvent){let requestedOutcome={outcome:input.outcome,at:priorEvent.outcome.at,...this.context.unitId?{taskId:this.context.unitId}:{},...input.correction?{correction:normalizeMemoryText(input.correction)}:{}},requestedPayload=canonicalOutcomePayload(requestedOutcome,input.anchors??[]);if(priorEvent.memoryId!==targetId||requestedPayload!==canonicalOutcomePayload(priorEvent.outcome,priorEvent.anchors))throw new MemoryValidationError("outcome event id already exists with a different payload");return this.provider.appendOutcome(priorEvent.memoryId,{id:priorEvent.id,outcome:priorEvent.outcome},priorEvent.anchors)}return this.provider.appendOutcome(targetId,{id:input.eventId??randomUUID27(),outcome:{outcome:input.outcome,at:this.now().toISOString(),taskId:this.context.unitId,correction:input.correction?normalizeMemoryText(input.correction):void 0}},input.anchors)}async applyCuratorDecision(decision){if(this.assertEnabled(),!this.provider.applyCuratorDecision)throw new MemoryValidationError("memory provider does not support curator decisions");let parsed=validateCuratorMemoryDecision(decision),resolved=this.resolveCuratorDecision(parsed);if(resolved.action==="add"&&resolved.memory)await this.validateRecordWithPiiPolicy(resolved.memory);else if(resolved.action==="supersede"&&resolved.replacement)await this.validateRecordWithPiiPolicy(resolved.replacement);else if(resolved.action==="update"&&resolved.patch?.text!==void 0){let existing=await this.provider.get(resolved.targetMemoryId);if(existing){let merged=applyPatchToMemory(existing,resolved.patch,this.now().toISOString());await this.validateRecordWithPiiPolicy(merged)}}return this.provider.applyCuratorDecision(resolved)}async validateRecordWithPiiPolicy(record3){let{detectPii,rejectDurablePii}=this.config.redaction,findings;if(detectPii||rejectDurablePii){if(!this.piiDetector)this.piiDetector=createPiiDetector(this.config.redaction.piiDetector);findings=await this.piiDetector.detect(record3.text)}try{return{parsed:validateMemoryRecordRules(record3,{rejectDurableSecrets:this.config.redaction.rejectDurableSecrets,piiFindings:findings,rejectDurablePii,piiThreshold:this.config.redaction.piiThreshold}),...findings&&findings.length>0?{piiSummary:{score:computePiiScore(findings),countsByType:findings.reduce((acc,f)=>{return acc[f.type]=(acc[f.type]??0)+1,acc},{})}}:{}}}catch(err){if(err instanceof MemoryValidationError&&err.code==="memory_pii_rejected")try{await this.provider.recordEvent?.("pii_rejected",PII_REJECTION_EVENT_TARGET,err.message)}catch(auditErr){warn("[memory] failed to persist pii_rejected audit event (the PII rejection itself still applies)",{reason:auditErr instanceof Error?auditErr.message:String(auditErr)})}throw err}}async enforcePiiTextPolicy(text){if(text.includes(MEMORY_RECALL_SENTINEL))throw new MemoryValidationError("correction text cannot contain the recall sentinel header");if(text.includes("bundle_"))throw new MemoryValidationError("correction text cannot contain the recall bundle marker prefix");let{detectPii,rejectDurablePii}=this.config.redaction;if(!detectPii&&!rejectDurablePii)return;if(!this.piiDetector)this.piiDetector=createPiiDetector(this.config.redaction.piiDetector);let findings=await this.piiDetector.detect(text),score=computePiiScore(findings);if(rejectDurablePii&&score>this.config.redaction.piiThreshold){let summary=summarizePiiFindings(findings),message=`durable memory correction exceeds the PII threshold: score ${score.toFixed(2)} (types: ${Object.entries(summary.countsByType).map(([t,n])=>`${t}x${n}`).join(", ")||"none"}) exceeded threshold ${this.config.redaction.piiThreshold.toFixed(2)}`;try{await this.provider.recordEvent?.("pii_rejected",PII_REJECTION_EVENT_TARGET,message)}catch(auditErr){warn("[memory] failed to persist pii_rejected audit event (the PII rejection itself still applies)",{reason:auditErr instanceof Error?auditErr.message:String(auditErr)})}throw new MemoryValidationError(message,"memory_pii_rejected")}}createRecord(input){let nowDate=this.now(),now2=nowDate.toISOString(),text=normalizeMemoryText(input.text),kind=input.kind,stability=input.stability??(kind==="scratch"?"ephemeral":"durable"),scope=this.resolveRecordScope(input.scope,stability),expiresAt=kind==="scratch"?new Date(nowDate.getTime()+604800000).toISOString():void 0,recordBase={scope,kind,text};return{id:createMemoryId(recordBase),scope,kind,text,tags:normalizeTags2(input.tags??inferTags2(text)),confidence:clamp(input.confidence??0.5,0,1),stability,source:input.source??sourceFromEvidence(input.evidenceRefs??[],this.context),createdAt:now2,updatedAt:now2,expiresAt,contentHash:computeMemoryContentHash(recordBase),metadata:input.metadata??{},anchors:input.anchors,outcomes:input.outcomes,cohortId:isCohortRoot(this.vettedRoot)?this.vettedRoot.cohortId:void 0,producerSessionId:this.context.sessionID,producerAgentRole:this.context.agentRole,redactionPolicyVersion:computeRedactionPolicyVersion({rejectDurableSecrets:this.config.redaction.rejectDurableSecrets,detectPii:this.config.redaction.detectPii,rejectDurablePii:this.config.redaction.rejectDurablePii,piiDetector:this.config.redaction.piiDetector}),providerVersion:this.provider.name,sourceTaskId:this.context.unitId,validFrom:now2,supersedesReason:input.supersedesReason}}resolveCuratorDecision(decision){switch(decision.action){case"add":return{action:"add",proposalId:decision.proposalId,memory:this.createRecordFromNew(decision.memory)};case"supersede":return{action:"supersede",proposalId:decision.proposalId,oldMemoryId:decision.oldMemoryId,replacement:this.createRecordFromNew(decision.replacement),reason:normalizeMemoryText(decision.reason)};case"merge":return{action:"merge",proposalId:decision.proposalId,relatedMemoryIds:canonicalMemoryIds(decision.relatedMemoryIds),reason:normalizeMemoryText(decision.reason)};case"update":{let patch2=normalizeMemoryPatch(decision.patch);if(patch2.scope)patch2.scope=this.resolveRecordScope(patch2.scope);return{action:"update",proposalId:decision.proposalId,targetMemoryId:decision.targetMemoryId,patch:patch2,reason:normalizeMemoryText(decision.reason)}}case"reject":case"noop":return{action:decision.action,proposalId:decision.proposalId,reason:normalizeMemoryText(decision.reason)}}}createRecordFromNew(input){let record3=this.createRecord({kind:input.kind,text:input.text,scope:input.scope,tags:input.tags,confidence:input.confidence,stability:input.stability,source:input.source,metadata:input.metadata,anchors:input.anchors,outcomes:input.outcomes}),next=input.expiresAt?{...record3,expiresAt:input.expiresAt}:record3;return validateMemoryRecordRules(next,{rejectDurableSecrets:this.config.redaction.rejectDurableSecrets})}resolveRecordScope(scope,stability){let allowedScopes=this.deriveAllowedScopes();if(!scope){let wantsCohort=stability!=="ephemeral"&&stability!=="session",cohortScope=allowedScopes.find((s)=>s.type==="cohort"),defaultScope=wantsCohort?cohortScope??allowedScopes[1]??allowedScopes[0]:allowedScopes[1]??allowedScopes[0];if(!defaultScope)throw new MemoryValidationError("memory scope is not available for this context");return defaultScope}return validateRequestedScopes([scope],allowedScopes,"memory scope is not allowed for this context"),scope}assertEnabled(){if(!this.config.enabled)throw new MemoryDisabledError}}function createMemoryGateway(context,options={}){return new MemoryGateway(context,options)}function createConfiguredMemoryProvider(directory,config3){let root=resolveVettedMemoryRoot(directory,config3);return createConfiguredMemoryProviderForRoot(root,config3)}function createConfiguredMemoryProviderForRoot(root,config3){if(config3.provider==="sqlite")return getOrCreateProviderForRoot(root,config3);let directory=requirePhysicalFutureIoPath(root.directory);if(root.kind==="cohort"){try{mkdirSync54(root.cohortRoot,{recursive:!0})}catch{}return new LocalJsonlMemoryProvider(directory,config3,requirePhysicalFutureIoPath(root.cohortRoot))}return new LocalJsonlMemoryProvider(directory,config3,null)}function requirePhysicalFutureIoPath(entryPath){let canonical=canonicalPathForFutureIo(entryPath);if(canonical!==null)return canonical;throw new MemoryValidationError("memory storage root physical identity could not be resolved")}function sourceFromEvidence(evidenceRefs,context){let first=evidenceRefs[0];if(!first)return{type:"agent",createdBy:context.agentId??context.agentRole};if(/^https?:\/\//i.test(first))return{type:"web",url:first};if(/^[a-f0-9]{40}$/i.test(first))return{type:"commit",commitSha:first};let filePath=extractFilePaths(evidenceRefs)[0]??first;if(filePath!==first&&(filePath.includes("/")||filePath.includes("\\")||filePath.includes(".")))return{type:"file",filePath};if(first.includes("/")||first.includes("\\")||first.includes("."))return{type:"file",filePath:first};return{type:"manual",ref:first}}function createStableId(value){return createHash76("sha256").update(value.toLowerCase()).digest("hex").slice(0,16)}function cacheGitRemoteUrl(key2,remoteUrl){if(!gitRemoteUrlCache.has(key2))while(gitRemoteUrlCache.size>=MAX_GIT_REMOTE_CACHE_ENTRIES){let oldest=gitRemoteUrlCache.keys().next().value;if(oldest===void 0)break;gitRemoteUrlCache.delete(oldest)}gitRemoteUrlCache.set(key2,remoteUrl)}function readGitRemoteUrl(directory){let key2=canonicalRootKeyFresh(directory);if(gitRemoteUrlCache.has(key2))return gitRemoteUrlCache.get(key2);let gitConfigPath=path183.join(directory,".git","config");if(!existsSync90(gitConfigPath)){cacheGitRemoteUrl(key2,void 0);return}try{let remoteUrl=readFileSync67(gitConfigPath,"utf-8").match(/\[remote "origin"\][\s\S]*?\n\s*url\s*=\s*(.+)/)?.[1]?.trim();return cacheGitRemoteUrl(key2,remoteUrl),remoteUrl}catch{cacheGitRemoteUrl(key2,void 0);return}}function validateRequestedScopes(requested,allowed,disallowedMessage="recall scope is not allowed for this context"){if(requested.length===0)throw new MemoryValidationError("recall scopes must not be empty");let allowedKeys=new Set(allowed.map(scopeKey));for(let scope of requested)if(!allowedKeys.has(scopeKey(scope)))throw new MemoryValidationError(disallowedMessage);return requested}function resolveInjectionSkipReason(diagnostics){if(diagnostics.returnedCount>0)return;if(diagnostics.candidateCount===0)return"no_results";let signalEligibleCount=diagnostics.candidateCount-diagnostics.preScoredFilteredCount-diagnostics.suppressedLowQCount;if(signalEligibleCount>0&&diagnostics.noSignalCount>0&&diagnostics.noSignalCount>=signalEligibleCount)return"no_signal";if(diagnostics.belowThresholdCount>0)return"below_threshold";return"no_results"}function scopeKey(scope){return JSON.stringify({type:scope.type,userId:scope.userId,workspaceId:scope.workspaceId,projectId:scope.projectId,repoId:scope.repoId,repoRoot:scope.repoRoot?canonicalRootKeyFresh(scope.repoRoot):void 0,runId:scope.runId,agentId:scope.agentId,cohortId:scope.cohortId})}function clamp(value,min,max){return Math.min(max,Math.max(min,value))}function clampInt(value,min,max){return Math.trunc(clamp(value,min,max))}function normalizeTags2(tags){return Array.from(new Set(tags.map((tag)=>tag.toLowerCase().replace(/[^\w-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")).filter(Boolean))).slice(0,32)}function normalizeMemoryPatch(patch2){return{...patch2,text:patch2.text===void 0?void 0:normalizeMemoryText(patch2.text),tags:patch2.tags===void 0?void 0:normalizeTags2(patch2.tags)}}function inferTags2(text){let lower=text.toLowerCase(),tags=[];for(let[tag,pattern]of[["testing",/\b(test|spec|bun|jest|vitest)\b/],["tooling",/\b(pnpm|npm|yarn|bun|biome|eslint|typescript)\b/],["security",/\b(security|auth|token|secret|password|csp)\b/],["api",/\b(api|endpoint|graphql|rest|sdk)\b/],["architecture",/\b(architecture|decision|adr|pattern)\b/],["failure",/\b(fail|failure|regression|flaky|timeout)\b/]])if(pattern.test(lower))tags.push(tag);return tags}function extractFilePaths(refs){let seen=new Set,paths=[];for(let ref of refs){FILE_PATH_REGEX.lastIndex=0;let matches=ref.match(FILE_PATH_REGEX);if(!matches)continue;for(let m of matches)if(!seen.has(m)){if(seen.add(m),paths.push(m),paths.length>=20)return paths}}return paths}function extractSymbols2(refs){let seen=new Set,symbols=[],identRegex=/\b[a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z_][a-zA-Z0-9_]*)*\b/g;for(let ref of refs){identRegex.lastIndex=0;let matches=ref.match(identRegex);if(!matches)continue;for(let m of matches)if(m.length>=3&&!seen.has(m)&&!RESERVED_IDENTIFIERS.has(m)){if(seen.add(m),symbols.push(m),symbols.length>=20)return symbols}}return symbols}var PII_REJECTION_EVENT_TARGET="pii_rejection",gitRemoteUrlCache,MAX_GIT_REMOTE_CACHE_ENTRIES=128,FILE_PATH_REGEX,RESERVED_IDENTIFIERS;var init_gateway=__esm(()=>{init_canonical_root();init_filesystem_identity();init_logger();init_config3();init_curator_decision_helpers();init_errors6();init_local_jsonl_provider();init_outcome_events();init_pii();init_prompt_block();init_provider_pool();init_redaction();init_relations();init_schema2();init_sentinel();init_storage_root();gitRemoteUrlCache=new Map;FILE_PATH_REGEX=/\b(?:src|tests|test|docs|scripts|packages|lib|config|examples|internal|cmd|pkg|bin|tools|cli|api|server|client|app|core|utils|hooks|services|commands|agents|memory)\/[A-Za-z0-9._/@+-]+/g,RESERVED_IDENTIFIERS=new Set(["const","let","var","function","class","interface","type","async","await","return","if","else","for","while","do","switch","case","break","continue","new","this","super","extends","implements","import","export","from","default","try","catch","finally","throw","typeof","instanceof","in","of","as","yield","static","get","set","readonly","public","private","protected"])});async function applyCouncilReward(provider,opts){let bundles=await provider.listRecallUsage?.({runId:opts.runId})??[];if(bundles.length===0)return{memoriesRewarded:0};let attributedBundles=bundles.filter((bundle)=>bundle.unitId==null||opts.unitId==null||bundle.unitId===opts.unitId),distinctIds=new Set;for(let bundle of attributedBundles)for(let id of bundle.memoryIds)distinctIds.add(id);let result=await(provider.withTransaction?provider.withTransaction(async()=>{let updates=new Map;for(let id of distinctIds){let rec=await provider.get(id);if(!rec)continue;let qBefore=getQValue(rec,opts.initialQValue),qAfter=applyEmaUpdate(qBefore,opts.reward,opts.eta);updates.set(id,{rec,qBefore,qAfter})}for(let[id,{rec,qBefore,qAfter}]of updates)await provider.upsert(setQValue(rec,qAfter)),await provider.appendRewardEvent?.({memoryId:id,runId:opts.runId,unitId:opts.unitId,verdict:opts.verdictLabel??"APPROVE",reward:opts.reward,qBefore,qAfter,verdictSynthesisJson:opts.verdictSynthesisJson,timestamp:opts.timestamp});return updates}):(async()=>{let updates=new Map;for(let id of distinctIds){let rec=await provider.get(id);if(!rec)continue;let qBefore=getQValue(rec,opts.initialQValue),qAfter=applyEmaUpdate(qBefore,opts.reward,opts.eta);updates.set(id,{rec,qBefore,qAfter})}for(let[id,{rec,qBefore,qAfter}]of updates)await provider.upsert(setQValue(rec,qAfter)),await provider.appendRewardEvent?.({memoryId:id,runId:opts.runId,unitId:opts.unitId,verdict:opts.verdictLabel??"APPROVE",reward:opts.reward,qBefore,qAfter,verdictSynthesisJson:opts.verdictSynthesisJson,timestamp:opts.timestamp});return updates})()),memoriesRewarded=result.size,rewardedRecords=[...result.values()].map(({rec})=>rec);try{await propagateReward(provider,opts,rewardedRecords,distinctIds)}catch(err){log(`[memory:propagation] skipped after error: ${err instanceof Error?err.message:String(err)}`)}return{memoriesRewarded}}async function propagateReward(provider,opts,sources,directlyRewardedIds){if(sources.length===0)return;let qConfig=opts.qLearning??DEFAULT_QLEARNING_CONFIG,fraction=qConfig.propagationFraction,fanoutCap=qConfig.propagationFanoutCap,windowDays=qConfig.propagationWindowDays,relatednessThreshold=qConfig.propagationRelatednessThreshold;if(!Number.isFinite(fraction)||fraction<=0)return;if(!Number.isFinite(fanoutCap)||fanoutCap<=0)return;if(!Number.isFinite(windowDays)||windowDays<=0)return;if(!Number.isFinite(relatednessThreshold))return;if(typeof provider.list!=="function")return;let nowMs3=Date.parse(opts.timestamp);if(!Number.isFinite(nowMs3))return;let windowMs=windowDays*MS_PER_DAY3,recencyById=await buildRetrievalRecency(provider,nowMs3);if(!recencyById)return;let orderedSources=[...sources].sort((a,b)=>a.id.localeCompare(b.id)),scheduled=new Map,listCache=new Map;for(let source of orderedSources){let scopeKey2=stableScopeKey(source.scope),cacheKey=`${scopeKey2}::${source.kind}`,candidates=listCache.get(cacheKey);if(!candidates)candidates=await provider.list({scopes:[source.scope],kinds:[source.kind]}),listCache.set(cacheKey,candidates);let sourceTokens=tokenize(source.text),qualified=[];for(let cand of candidates){if(cand.id===source.id)continue;if(directlyRewardedIds.has(cand.id))continue;if(stableScopeKey(cand.scope)!==scopeKey2)continue;if(cand.kind!==source.kind)continue;let retrievedAt=recencyById.get(cand.id);if(retrievedAt===void 0)continue;if(nowMs3-retrievedAt>windowMs)continue;let overlap2=jaccard(sourceTokens,tokenize(cand.text));if(overlap2<relatednessThreshold)continue;qualified.push({record:cand,overlap:overlap2})}qualified.sort((a,b)=>b.overlap-a.overlap||a.record.id.localeCompare(b.record.id));let cap=Math.trunc(fanoutCap),selected=qualified.slice(0,cap),dropped=qualified.length-selected.length;if(dropped>0)log(`[memory:propagation] fan-out cap reached for source ${source.id}: ${qualified.length} qualified, ${selected.length} propagated, ${dropped} dropped by cap ${cap}`);for(let{record:record3}of selected)if(!scheduled.has(record3.id))scheduled.set(record3.id,record3)}for(let record3 of scheduled.values()){let qBefore=getQValue(record3,opts.initialQValue),qAfter=applyPropagatedEmaUpdate(qBefore,opts.reward,opts.eta,fraction);await provider.upsert(setQValue(record3,qAfter)),await provider.appendRewardEvent?.({memoryId:record3.id,runId:opts.runId,unitId:opts.unitId,verdict:`${opts.verdictLabel??"APPROVE"}${PROPAGATED_VERDICT_SUFFIX}`,reward:opts.reward,qBefore,qAfter,verdictSynthesisJson:opts.verdictSynthesisJson,timestamp:opts.timestamp})}}function truncateObjectForJson(obj,capBytes){let asIs=JSON.stringify(obj);if(asIs.length<=capBytes)return obj;if(JSON.stringify({...obj,__truncated__:!0}).length<=capBytes)return{...obj,__truncated__:!0};return{__truncated__:!0,originalSize:asIs.length,cap:capBytes}}async function buildRetrievalRecency(provider,nowMs3){if(typeof provider.listRecallUsage!=="function")return null;let since=new Date(nowMs3-RECENCY_WINDOW_MS).toISOString(),usage=await provider.listRecallUsage({since,limit:RECENCY_EVENT_LIMIT})??[],recency=new Map;for(let event of usage){let ts=Date.parse(event.timestamp);if(!Number.isFinite(ts))continue;for(let id of event.memoryIds){let prev=recency.get(id);if(prev===void 0||ts>prev)recency.set(id,ts)}}return recency}var PROPAGATED_VERDICT_SUFFIX="_PROPAGATED",MS_PER_DAY3=86400000,RECENCY_WINDOW_MS,RECENCY_EVENT_LIMIT=1000;var init_reward_capture=__esm(()=>{init_logger();init_config3();init_schema2();init_scoring();RECENCY_WINDOW_MS=30*MS_PER_DAY3});async function runFinalizeRewardSweep(args2){let result={swept:!1,tasksSwept:0,memoriesRewarded:0,runIdsProcessed:0};try{let{directory,memoryConfig}=args2;if(memoryConfig?.enabled!==!0)return result;let taskIds=[...new Set(args2.closedTaskIds.filter((id)=>typeof id==="string"&&id.length>0))];if(taskIds.length===0)return result;let timestamp=args2.timestamp??new Date().toISOString(),vettedRoot=resolveVettedMemoryRoot(directory,memoryConfig),provider=_internals156.createConfiguredMemoryProviderForRoot(vettedRoot,memoryConfig);try{result.swept=!0;for(let taskId of taskIds){let bundles=await provider.listRecallUsage?.({unitId:taskId})??[];if(bundles.length===0)continue;let runIds=new Set;for(let bundle of bundles)if(typeof bundle.runId==="string"&&bundle.runId.length>0)runIds.add(bundle.runId);if(runIds.size===0){log(`[memory:finalize-sweep] task ${taskId} has recall bundles without a runId; skipping to avoid over-penalizing unrelated untagged memories`);continue}let taskRewarded=0;for(let runId of runIds){let{memoriesRewarded}=await _internals156.applyCouncilReward(provider,{runId,unitId:taskId,reward:FINALIZE_NEGATIVE_TERMINAL_REWARD,eta:memoryConfig.qLearning.learningRate,initialQValue:memoryConfig.qLearning.initialQValue,qLearning:memoryConfig.qLearning,timestamp,verdictLabel:"session_terminated"});taskRewarded+=memoriesRewarded,result.runIdsProcessed++}if(taskRewarded>0)result.tasksSwept++,result.memoriesRewarded+=taskRewarded}}finally{await provider.close?.()}}catch(err){log(`[memory:finalize-sweep] skipped after error: ${err instanceof Error?err.message:String(err)}`)}return result}var FINALIZE_NEGATIVE_TERMINAL_REWARD=0,_internals156;var init_finalize_reward_sweep=__esm(()=>{init_logger();init_gateway();init_reward_capture();init_storage_root();_internals156={createConfiguredMemoryProvider,createConfiguredMemoryProviderForRoot,applyCouncilReward}});import*as fsSync18 from"node:fs";import{promises as fs101}from"node:fs";function wireCloseInternals(){Object.assign(closeReceiptLifecycleInternals,{recordPhaseCloseIntent,reconcilePhaseClose}),Object.assign(_internals123,{closeSnapshotCoordinationInitialization,closeRepoMemory,unlink:fs101.unlink,unlinkSidecarSync:fsSync18.unlinkSync,sleep,collectGarbageBestEffort,getGitRepositoryStatus,resetToMainAfterMerge:(cwd,options)=>guardResetWithRecheck(resetToMainAfterMerge,cwd,options),resetToRemoteBranch,loadPluginConfigWithMeta,curateAndStoreSwarm,checkHivePromotions,runCuratorPostMortem,resetSwarmStatePreservingSingletons,runFinalizeRewardSweep,archiveEvidence,endAgentSession,flushAndDrainTelemetry:async()=>{let{flushAndDrainTelemetry:flushAndDrainTelemetry2}=await Promise.resolve().then(() => (init_telemetry(),exports_telemetry));return flushAndDrainTelemetry2()},finalizeContextTelemetry,finalizeCoreEvents:finalizeCoreEventsForClose})}var init_wiring=__esm(()=>{init_config2();init_telemetry2();init_core_events();init_manager2();init_branch();init_curator_postmortem();init_hive_promoter();init_knowledge_curator();init_knowledge_receipt_ledger();init_finalize_reward_sweep();init_snapshot_coordination_init();init_state();init_indexed_storage();init_bun_compat();init_align_stage();init_internals()});var init_close2=__esm(()=>{init_align_stage();init_archive_stage();init_clean_stage();init_dry_run();init_finalize_stage();init_fs_helpers();init_internals();init_orchestrator();init_wiring();init_align_stage();init_archive_stage();init_clean_stage();init_constants2();init_db_helpers();init_dry_run();init_finalize_stage();init_internals();init_orchestrator();Object.assign(_internals123,{unlinkActiveStateFileWithRetry,countSessionKnowledgeEntries,detectFullAuto,guaranteeAllPlansComplete,copyDirRecursive,runFinalizeStage,acquireFinalizeLock,runArchiveStage,archiveCloseSummary,runArchiveEvidenceRetention,runCleanStage,runAlignStage,runFinalizeDryRun,closePlanTerminalState:reconcileCloseTerminalStateForPlan});wireCloseInternals()});function sanitizeText(raw,maxLen){let normalized=raw.replace(/\[+\s*MODE\s*:[^\]]*(?:\]+|$)/gi,"").replace(/\s+/g," ").trim();if(normalized.length<=maxLen)return normalized;return`${normalized.slice(0,maxLen)}...`}function hasFlagValue(args2,index){return index+1<args2.length&&!args2[index+1].startsWith("--")}function jsonForModeHeader(value){return JSON.stringify(value).replace(/[[\]]/g,(ch)=>ch==="["?"\\u005B":"\\u005D")}function parseArgs(args2){let result={mode:"phase0",tracks:"",continueRun:"",output:"markdown",updateMain:!0,allowDirty:!1,rest:[]},i=0;while(i<args2.length){let token=args2[i];if(token==="--help"||token==="-h")result.help=!0;else if(token==="--mode"){if(!hasFlagValue(args2,i))return{...result,error:FLAG_VALUE_MISSING(token)};let value=args2[++i];if(!MODES.has(value))return{...result,error:`Invalid mode "${value}". Must be one of: ${[...MODES].join(", ")}.`};result.mode=value}else if(token==="--tracks"){if(!hasFlagValue(args2,i))return{...result,error:FLAG_VALUE_MISSING(token)};result.tracks=sanitizeText(args2[++i],1000)}else if(token==="--continue"){if(!hasFlagValue(args2,i))return{...result,error:FLAG_VALUE_MISSING(token)};let runId=sanitizeText(args2[++i],128);if(!/^[A-Za-z0-9_.-]+$/.test(runId))return{...result,error:"Invalid --continue value. Use only letters, numbers, dot, underscore, or dash."};result.continueRun=runId}else if(token==="--json")result.output="json";else if(token==="--skip-update")result.updateMain=!1;else if(token==="--allow-dirty")result.allowDirty=!0;else if(token.startsWith("--"))return{...result,error:`Unknown flag "${token}"`};else result.rest.push(token);i++}return result}async function handleCodebaseReviewCommand(_directory2,args2){let parsed=parseArgs(args2);if(parsed.help)return`Usage: /swarm codebase-review [scope] [--mode phase0|complete|defect|security|correctness|testing|ui|performance|ai-slop|enhancements|custom] [--tracks <list>] [--continue <run-id>] [--json] [--skip-update] [--allow-dirty]
|
|
2334
|
+
`}];FTS_STOP_WORDS=new Set(["a","an","and","are","as","at","be","by","for","from","goal","how","in","into","is","it","of","on","or","role","task","that","the","this","to","user","what","when","with"])});import{mkdirSync as mkdirSync52}from"node:fs";function markAsPooled(provider){let originalClose=provider.close;if(provider.close=()=>{return releaseProvider(provider),Promise.resolve()},provider[POOLED_MARKER]=!0,originalClose)provider[REAL_CLOSE]=originalClose}function callRealClose(provider){let realClose=provider[REAL_CLOSE];try{realClose?.call(provider)}catch(err){let msg=err instanceof Error?err.message:String(err);if(process.env.OPENCODE_SWARM_DEBUG==="1")console.debug(`[provider-pool] real close failed: ${msg}`)}}function isPooledProvider(provider){return POOLED_MARKER in provider}function getOrCreateProviderForRoot(root,config3){if(root.kind==="cohort"&&canonicalExistingFilesystemPath(root.cohortRoot)===null&&!resolvedKeyCache.has(rawPoolKey(root.cohortRoot)))try{mkdirSync52(root.cohortRoot,{recursive:!0})}catch{}let key2=resolvePoolKeyForRoot(root),rootGeneration=root.kind==="cohort"?root.generation:0,existing=entriesByKey.get(key2);if(existing){if((existing.generation??0)===rootGeneration)return moveToHead(existing),existing.refCount++,existing.provider;evictEntryByKey(key2)}for(let deferred of deferredEntries)if(deferred.key===key2){if((deferred.generation??0)===rootGeneration){if(deferredEntries.delete(deferred),entriesByKey.size>=MAX_POOL_SIZE)evictLru();if(deferred.prev=null,deferred.next=head,head)head.prev=deferred;if(head=deferred,!tail)tail=deferred;return entriesByKey.set(key2,deferred),deferred.refCount++,deferred.provider}deferredEntries.delete(deferred),callRealClose(deferred.provider);break}let directory=root.kind==="local"?key2:resolvePoolKey(root.directory),cohortRoot=root.kind==="cohort"?key2.slice(7):null,provider=new SQLiteMemoryProvider(directory,config3,cohortRoot);if(markAsPooled(provider),entriesByKey.size>=MAX_POOL_SIZE)evictLru();let entry={key:key2,provider,refCount:1,prev:null,next:head};if(entry.generation=rootGeneration,head)head.prev=entry;if(head=entry,!tail)tail=entry;return entriesByKey.set(key2,entry),provider}function resolvePoolKeyForRoot(root){if(root.kind==="cohort")return`cohort:${resolvePoolKey(root.cohortRoot)}`;return resolvePoolKey(root.directory)}function evictEntryByKey(key2){let entry=entriesByKey.get(key2);if(!entry)return;if(entry.refCount>0){deferredEntries.add(entry),unlinkEntry(entry),entriesByKey.delete(key2);return}unlinkEntry(entry),entriesByKey.delete(key2),callRealClose(entry.provider)}function evictAndCloseForRoot(root){let key2=resolvePoolKeyForRoot(root);evictEntryByKey(key2)}function releaseProvider(provider){for(let[_key,entry]of entriesByKey)if(entry.provider===provider){entry.refCount=Math.max(0,entry.refCount-1);return}for(let entry of deferredEntries)if(entry.provider===provider){if(entry.refCount--,entry.refCount<=0)deferredEntries.delete(entry),callRealClose(provider);return}if(isPooledProvider(provider))callRealClose(provider)}function evictLru(){if(!tail)return;let evicted=tail;if(entriesByKey.delete(evicted.key),unlinkEntry(evicted),evicted.refCount>0)deferredEntries.add(evicted);else callRealClose(evicted.provider)}function moveToHead(entry){if(head===entry)return;if(unlinkEntry(entry),entry.prev=null,entry.next=head,head)head.prev=entry;if(head=entry,!tail)tail=entry}function unlinkEntry(entry){if(entry.prev)entry.prev.next=entry.next;if(entry.next)entry.next.prev=entry.prev;if(head===entry)head=entry.next;if(tail===entry)tail=entry.prev}function resolvePoolKey(directory){let rawKey=rawPoolKey(directory),canonical=canonicalExistingFilesystemPath(directory);if(canonical!==null)return rememberResolvedKey(rawKey,canonical,filesystemIdentityWitnesses(directory)),canonical;let prior=resolvedKeyCache.get(rawKey),inferred=canonicalPathFromExistingAncestor(directory),witnessRetargeted=prior?.witnesses.some((witness)=>{let current=canonicalExistingFilesystemPath(witness.lexicalPath);return current!==null&¤t!==witness.canonicalPath});if(inferred&&(prior===void 0||inferred.existingAncestorIsLink||witnessRetargeted))return rememberResolvedKey(rawKey,inferred.canonicalPath,inferred.identityWitnesses),inferred.canonicalPath;if(prior)return prior.key;if(inferred)return inferred.canonicalPath;throw new MemoryValidationError("memory storage root physical identity could not be resolved")}function rememberResolvedKey(rawKey,canonical,witnesses){if(resolvedKeyCache.delete(rawKey),resolvedKeyCache.set(rawKey,{key:canonical,witnesses}),resolvedKeyCache.size>MAX_POOL_SIZE){let oldest=resolvedKeyCache.keys().next().value;if(oldest!==void 0)resolvedKeyCache.delete(oldest)}}function rawPoolKey(directory){return lexicalRootAliasKey(directory)}function evictAndClose(directory){let key2=resolvePoolKey(directory),active=entriesByKey.get(key2);if(active)entriesByKey.delete(key2),unlinkEntry(active),callRealClose(active.provider);for(let deferred of[...deferredEntries])if(deferred.key===key2)deferredEntries.delete(deferred),callRealClose(deferred.provider)}var MAX_POOL_SIZE=16,POOLED_MARKER,REAL_CLOSE,head=null,tail=null,entriesByKey,deferredEntries,resolvedKeyCache;var init_provider_pool=__esm(()=>{init_canonical_root();init_filesystem_identity();init_errors6();init_sqlite_provider();POOLED_MARKER=Symbol("opencode-swarm-pooled-provider"),REAL_CLOSE=Symbol("opencode-swarm-real-close"),entriesByKey=new Map,deferredEntries=new Set,resolvedKeyCache=new Map});import{existsSync as existsSync89,mkdirSync as mkdirSync53,readFileSync as readFileSync66,rmSync as rmSync22,statSync as statSync60}from"node:fs";import*as path181 from"node:path";function resolveMemoryLinkPointerPath(directory){return path181.join(directory,".swarm",MEMORY_LINK_POINTER_FILENAME)}function readMemoryLinkPointer(directory){let pointerPath=resolveMemoryLinkPointerPath(directory);if(!existsSync89(pointerPath))return null;try{let raw=JSON.parse(readFileSync66(pointerPath,"utf-8"));if(!raw||typeof raw!=="object")return null;let obj=raw,linkId=obj.linkId;if(typeof linkId!=="string"||linkId.length===0)return null;let safeId=sanitizeLinkId(linkId);if(!safeId)return null;return{version:obj.version===2?2:1,linkId:safeId,name:typeof obj.name==="string"?obj.name:void 0,createdAt:typeof obj.createdAt==="string"?obj.createdAt:new Date(0).toISOString(),cohortId:typeof obj.cohortId==="string"?obj.cohortId:void 0,identitySource:obj.identitySource==="remote"||obj.identitySource==="git-common-dir"||obj.identitySource==="path"?obj.identitySource:void 0,degraded:typeof obj.degraded==="boolean"?obj.degraded:void 0,configFingerprint:typeof obj.configFingerprint==="string"?obj.configFingerprint:void 0,generation:typeof obj.generation==="number"?obj.generation:void 0}}catch{return null}}async function writeMemoryLinkPointer(directory,pointer){let swarmDir=path181.join(directory,".swarm");mkdirSync53(swarmDir,{recursive:!0});let pointerPath=resolveMemoryLinkPointerPath(directory);await atomicWriteFile(pointerPath,JSON.stringify(pointer,null,2)),invalidateMemoryStoreDirCache(directory)}async function removeMemoryLinkPointer(directory){let pointerPath=resolveMemoryLinkPointerPath(directory);try{rmSync22(pointerPath,{force:!0})}finally{invalidateMemoryStoreDirCache(directory)}}function pointerStatFingerprint2(directory){let pointerPath=resolveMemoryLinkPointerPath(directory);try{let st=statSync60(pointerPath);return`${st.mtimeMs}:${st.ctimeMs}:${st.size}`}catch{return null}}function resolveMemoryStoreDir(directory){let localSwarm=path181.join(directory,".swarm"),cacheKey=canonicalRootKeyFresh(directory),now2=Date.now(),cached3=_resolutionCache2.get(cacheKey),currentStat=pointerStatFingerprint2(directory);if(cached3&&now2<cached3.expires&&cached3.pointerStat===currentStat)return cached3.linkDir??localSwarm;let linkDir=null;try{let pointer=readMemoryLinkPointer(directory);if(pointer)linkDir=path181.resolve(resolveLinkDir(pointer.linkId))}catch{linkDir=null}if(!_resolutionCache2.has(cacheKey)&&_resolutionCache2.size>=MAX_CACHE_ENTRIES3){let oldest=_resolutionCache2.keys().next().value;if(oldest!==void 0)_resolutionCache2.delete(oldest)}return _resolutionCache2.set(cacheKey,{linkDir,expires:now2+CACHE_TTL_MS2,pointerStat:currentStat}),linkDir??localSwarm}function invalidateMemoryStoreDirCache(directory){if(directory===void 0){_resolutionCache2.clear();return}_resolutionCache2.delete(canonicalRootKeyFresh(directory))}var MEMORY_LINK_POINTER_FILENAME="memory-link.json",CACHE_TTL_MS2=2000,MAX_CACHE_ENTRIES3=500,_resolutionCache2;var init_memory_link=__esm(()=>{init_task_file();init_knowledge_link();init_canonical_root();init_logger();_resolutionCache2=new Map});import*as path182 from"node:path";function resolveVettedMemoryRoot(directory,config3){if(config3?.link?.enabled!==!0){let existingPointer=readMemoryLinkPointer(directory);if(existingPointer)warn(`[memory-link] memory.link.enabled is false but a cohort pointer exists (linkId=${existingPointer.linkId}). Cohort memory is unreachable — run \`/swarm memory link\` or remove the pointer with \`/swarm memory unlink\`.`,{directory,linkId:existingPointer.linkId});return wrapLocalRoot(directory)}let pointer=readMemoryLinkPointer(directory);if(!pointer)return wrapLocalRoot(directory);let sharedDir=resolveMemoryStoreDir(directory),localSwarm=path182.join(directory,".swarm");if(sharedDir===localSwarm)return wrapLocalRoot(directory);return{kind:"cohort",cohortRoot:path182.join(sharedDir,"memory"),cohortId:pointer.cohortId??pointer.linkId,generation:pointer.generation??0,linkId:pointer.linkId,directory}}function wrapLocalRoot(directory){return log("[memory] wrapping raw directory as local vetted root — cohort sharing inactive for this caller",{directory}),{kind:"local",root:path182.join(directory,".swarm"),directory}}function isCohortRoot(root){return root.kind==="cohort"}function rootStoragePath(root){return root.kind==="cohort"?root.cohortRoot:path182.join(root.root,"memory")}var init_storage_root=__esm(()=>{init_logger();init_memory_link()});import{createHash as createHash76,randomUUID as randomUUID27}from"node:crypto";import{existsSync as existsSync90,mkdirSync as mkdirSync54,readFileSync as readFileSync67}from"node:fs";import*as path183 from"node:path";class MemoryGateway{context;config;provider;vettedRoot;now;disposed=!1;piiDetector;constructor(context,options={}){this.config=resolveMemoryConfig(options.config??DEFAULT_MEMORY_CONFIG),this.context={...context,directory:requirePhysicalFutureIoPath(context.directory)},this.vettedRoot=resolveVettedMemoryRoot(this.context.directory,this.config),this.provider=options.provider??createConfiguredMemoryProviderForRoot(this.vettedRoot,this.config),this.now=options.now??(()=>new Date)}isEnabled(){return this.config.enabled}async dispose(){if(this.disposed)return;this.disposed=!0,await this.provider.close?.()}deriveAllowedScopes(){let resolvedRoot=this.context.directory,repoId=createStableId(readGitRemoteUrl(resolvedRoot)??path183.basename(resolvedRoot)),scopes=[{type:"workspace",workspaceId:createStableId(path183.dirname(resolvedRoot))},{type:"repository",repoId,repoRoot:resolvedRoot}];if(isCohortRoot(this.vettedRoot))scopes.push({type:"cohort",cohortId:this.vettedRoot.cohortId});if(this.context.runId||this.context.sessionID)scopes.push({type:"run",runId:this.context.runId??this.context.sessionID});if(this.context.agentId||this.context.agentRole)scopes.push({type:"agent",agentId:this.context.agentId??this.context.agentRole,runId:this.context.runId??this.context.sessionID});return scopes}async recall(input,options){this.assertEnabled();let query=normalizeMemoryText(input.query);if(query.length<3)throw new MemoryValidationError("query must be at least 3 characters");let maxItems=clampInt(input.maxItems??this.config.recall.defaultMaxItems,1,20),tokenBudget=clampInt(input.tokenBudget??this.config.recall.defaultTokenBudget,100,5000),generatedAt=this.now().toISOString(),allowedScopes=this.deriveAllowedScopes(),scopes=input.scopes?validateRequestedScopes(input.scopes,allowedScopes):allowedScopes,request={query,task:input.task,agentRole:this.context.agentRole,mode:input.mode??"manual",scopes,kinds:input.kinds,maxItems,tokenBudget,minScore:input.minScore??this.config.recall.minScore,requireQuerySignal:input.requireQuerySignal,includeExpired:input.includeExpired},recallResult=this.provider.recallWithDiagnostics?await this.provider.recallWithDiagnostics(request):{items:await this.provider.recall(request)},bundle=toRecallBundle({id:createBundleId(query,generatedAt),query,generatedAt,items:recallResult.items,tokenBudget,diagnostics:recallResult.diagnostics?{injectionSkipReason:input.mode==="injection"?resolveInjectionSkipReason(recallResult.diagnostics):void 0,candidateCount:recallResult.diagnostics.candidateCount,preScoredFilteredCount:recallResult.diagnostics.preScoredFilteredCount,noSignalCount:recallResult.diagnostics.noSignalCount,belowThresholdCount:recallResult.diagnostics.belowThresholdCount}:void 0});if(options?.recordUsage===!1)return bundle;return await this.provider.recordRecallUsage?.({bundleId:bundle.id,query,scopes,kinds:input.kinds,memoryIds:bundle.items.map((item)=>item.record.id),scores:bundle.items.map((item)=>item.score),tokenEstimate:bundle.tokenEstimate,agentRole:this.context.agentRole,runId:this.context.runId??this.context.sessionID,unitId:this.context.unitId,timestamp:generatedAt}),bundle}async propose(input){if(this.assertEnabled(),!this.provider.createProposal)throw new MemoryValidationError("memory provider does not support proposals");let redactedFields=new Set,redactProposalField=(field,value)=>{let redacted=redactSecrets(value);if(redacted!==value)redactedFields.add(field);return redacted},rationale=redactProposalField("rationale",normalizeMemoryText(input.rationale));if(!rationale)throw new MemoryValidationError("rationale is required");let evidenceRefs=(input.evidenceRefs??[]).map((ref)=>normalizeMemoryText(ref)).filter(Boolean).map((ref)=>redactProposalField("evidenceRefs",ref)).slice(0,20),needsRecord=input.operation==="add"||input.operation==="update"||input.operation==="supersede",proposedRecord,status2="pending",reviewer,reviewedAt,rejectionReason,targetMemoryId=input.targetMemoryId===void 0?void 0:redactProposalField("targetMemoryId",normalizeMemoryText(input.targetMemoryId)),relatedMemoryIds=input.relatedMemoryIds?canonicalMemoryIds(input.relatedMemoryIds.map((id)=>redactProposalField("relatedMemoryIds",normalizeMemoryText(id)))):void 0,proposalText=`${input.operation}:${targetMemoryId??""}`;if(input.operation==="merge")proposalText=`merge:${(relatedMemoryIds??[]).join(",")}`;let piiSummary;if(needsRecord){if(!input.kind)throw new MemoryValidationError("kind is required for this operation");if(!input.text)throw new MemoryValidationError("text is required for this operation");proposalText=input.text;let normalizedText=normalizeMemoryText(input.text),redactedText=redactProposalField("text",normalizedText),extractedPaths=extractFilePaths(evidenceRefs),extractedSymbols=extractSymbols2(evidenceRefs),recordMetadata={};if(extractedPaths.length>0)recordMetadata.files=extractedPaths;if(extractedSymbols.length>0)recordMetadata.symbols=extractedSymbols;proposedRecord=this.createRecord({kind:input.kind,text:redactedText,evidenceRefs,source:sourceFromEvidence(evidenceRefs,this.context),metadata:recordMetadata}),{piiSummary}=await this.validateRecordWithPiiPolicy(proposedRecord)}if(redactedFields.size>0)status2="rejected",reviewer="auto_policy",reviewedAt=this.now().toISOString(),rejectionReason=`proposal field(s) contained a likely secret and were redacted: ${Array.from(redactedFields).join(", ")}`;if((input.operation==="update"||input.operation==="delete"||input.operation==="supersede")&&!targetMemoryId)throw new MemoryValidationError(`${input.operation} proposals require targetMemoryId`);if(input.operation==="merge"&&((relatedMemoryIds??[]).length<2||(relatedMemoryIds??[]).length>MAX_MERGE_PARTICIPANTS))throw new MemoryValidationError(`merge proposals require 2-${MAX_MERGE_PARTICIPANTS} distinct relatedMemoryIds`);let createdAt=this.now().toISOString(),proposer=this.context.agentId??this.context.agentRole??this.context.sessionID??"unknown",proposal={id:createProposalId({createdAt,proposer,text:proposalText}),operation:input.operation,proposedRecord,targetMemoryId,relatedMemoryIds,proposedBy:{agentRole:this.context.agentRole,agentId:this.context.agentId,runId:this.context.runId??this.context.sessionID},rationale,evidenceRefs,status:status2,reviewer,reviewedAt,rejectionReason,createdAt,metadata:piiSummary?{pii:piiSummary}:{}};return this.provider.createProposal(proposal)}async listMemories(filter={}){return this.assertEnabled(),this.provider.list(filter)}async listProposals(filter){if(this.assertEnabled(),!this.provider.listProposals)throw new MemoryValidationError("memory provider does not support proposals");return this.provider.listProposals(filter)}async listRecallUsage(filter){if(this.assertEnabled(),!this.provider.listRecallUsage)return[];return this.provider.listRecallUsage(filter)}async upsertCurated(record3){this.assertEnabled();let{parsed}=await this.validateRecordWithPiiPolicy(record3);return this.provider.upsert(parsed)}async recordOutcome(input){if(this.assertEnabled(),!this.provider.appendOutcome)throw new MemoryValidationError("memory provider does not support outcome capture");let hasId=typeof input.memoryId==="string"&&input.memoryId.length>0,question=input.question?normalizeMemoryText(input.question):"";if(hasId===question.length>0)throw new MemoryValidationError("exactly one of memoryId or question is required");if(question.length>MAX_OUTCOME_QUESTION_LENGTH)throw new MemoryValidationError(`question must be at most ${MAX_OUTCOME_QUESTION_LENGTH} characters`);if(input.outcome==="corrected"&&!input.correction?.trim())throw new MemoryValidationError("corrected outcomes require correction text");if(input.correction)await this.enforcePiiTextPolicy(normalizeMemoryText(input.correction));let targetId=input.memoryId;if(!targetId){let candidate=this.createRecord({kind:"evidence",text:`${MEMORY_OUTCOME_QUESTION_PREFIX}${question}`,confidence:0.5,stability:"durable",tags:["outcome-result"],source:{type:"tool",ref:"swarm_memory_outcome"},metadata:{outcomeQuestion:question}});if(!await this.provider.get(candidate.id))await this.validateRecordWithPiiPolicy(candidate),await this.provider.upsert(candidate);targetId=candidate.id}let priorEvent=input.eventId&&this.provider.listOutcomeEvents?(await this.provider.listOutcomeEvents()).find((event)=>event.id===input.eventId):void 0;if(priorEvent){let requestedOutcome={outcome:input.outcome,at:priorEvent.outcome.at,...this.context.unitId?{taskId:this.context.unitId}:{},...input.correction?{correction:normalizeMemoryText(input.correction)}:{}},requestedPayload=canonicalOutcomePayload(requestedOutcome,input.anchors??[]);if(priorEvent.memoryId!==targetId||requestedPayload!==canonicalOutcomePayload(priorEvent.outcome,priorEvent.anchors))throw new MemoryValidationError("outcome event id already exists with a different payload");return this.provider.appendOutcome(priorEvent.memoryId,{id:priorEvent.id,outcome:priorEvent.outcome},priorEvent.anchors)}return this.provider.appendOutcome(targetId,{id:input.eventId??randomUUID27(),outcome:{outcome:input.outcome,at:this.now().toISOString(),taskId:this.context.unitId,correction:input.correction?normalizeMemoryText(input.correction):void 0}},input.anchors)}async applyCuratorDecision(decision){if(this.assertEnabled(),!this.provider.applyCuratorDecision)throw new MemoryValidationError("memory provider does not support curator decisions");let parsed=validateCuratorMemoryDecision(decision),resolved=this.resolveCuratorDecision(parsed);if(resolved.action==="add"&&resolved.memory)await this.validateRecordWithPiiPolicy(resolved.memory);else if(resolved.action==="supersede"&&resolved.replacement)await this.validateRecordWithPiiPolicy(resolved.replacement);else if(resolved.action==="update"&&resolved.patch?.text!==void 0){let existing=await this.provider.get(resolved.targetMemoryId);if(existing){let merged=applyPatchToMemory(existing,resolved.patch,this.now().toISOString());await this.validateRecordWithPiiPolicy(merged)}}return this.provider.applyCuratorDecision(resolved)}async validateRecordWithPiiPolicy(record3){let{detectPii,rejectDurablePii}=this.config.redaction,findings;if(detectPii||rejectDurablePii){if(!this.piiDetector)this.piiDetector=createPiiDetector(this.config.redaction.piiDetector);findings=await this.piiDetector.detect(record3.text)}try{return{parsed:validateMemoryRecordRules(record3,{rejectDurableSecrets:this.config.redaction.rejectDurableSecrets,piiFindings:findings,rejectDurablePii,piiThreshold:this.config.redaction.piiThreshold}),...findings&&findings.length>0?{piiSummary:{score:computePiiScore(findings),countsByType:findings.reduce((acc,f)=>{return acc[f.type]=(acc[f.type]??0)+1,acc},{})}}:{}}}catch(err){if(err instanceof MemoryValidationError&&err.code==="memory_pii_rejected")try{await this.provider.recordEvent?.("pii_rejected",PII_REJECTION_EVENT_TARGET,err.message)}catch(auditErr){warn("[memory] failed to persist pii_rejected audit event (the PII rejection itself still applies)",{reason:auditErr instanceof Error?auditErr.message:String(auditErr)})}throw err}}async enforcePiiTextPolicy(text){if(text.includes(MEMORY_RECALL_SENTINEL))throw new MemoryValidationError("correction text cannot contain the recall sentinel header");if(text.includes("bundle_"))throw new MemoryValidationError("correction text cannot contain the recall bundle marker prefix");let{detectPii,rejectDurablePii}=this.config.redaction;if(!detectPii&&!rejectDurablePii)return;if(!this.piiDetector)this.piiDetector=createPiiDetector(this.config.redaction.piiDetector);let findings=await this.piiDetector.detect(text),score=computePiiScore(findings);if(rejectDurablePii&&score>this.config.redaction.piiThreshold){let summary=summarizePiiFindings(findings),message=`durable memory correction exceeds the PII threshold: score ${score.toFixed(2)} (types: ${Object.entries(summary.countsByType).map(([t,n])=>`${t}x${n}`).join(", ")||"none"}) exceeded threshold ${this.config.redaction.piiThreshold.toFixed(2)}`;try{await this.provider.recordEvent?.("pii_rejected",PII_REJECTION_EVENT_TARGET,message)}catch(auditErr){warn("[memory] failed to persist pii_rejected audit event (the PII rejection itself still applies)",{reason:auditErr instanceof Error?auditErr.message:String(auditErr)})}throw new MemoryValidationError(message,"memory_pii_rejected")}}createRecord(input){let nowDate=this.now(),now2=nowDate.toISOString(),text=normalizeMemoryText(input.text),kind=input.kind,stability=input.stability??(kind==="scratch"?"ephemeral":"durable"),scope=this.resolveRecordScope(input.scope,stability),expiresAt=kind==="scratch"?new Date(nowDate.getTime()+604800000).toISOString():void 0,recordBase={scope,kind,text};return{id:createMemoryId(recordBase),scope,kind,text,tags:normalizeTags2(input.tags??inferTags2(text)),confidence:clamp(input.confidence??0.5,0,1),stability,source:input.source??sourceFromEvidence(input.evidenceRefs??[],this.context),createdAt:now2,updatedAt:now2,expiresAt,contentHash:computeMemoryContentHash(recordBase),metadata:input.metadata??{},anchors:input.anchors,outcomes:input.outcomes,cohortId:isCohortRoot(this.vettedRoot)?this.vettedRoot.cohortId:void 0,producerSessionId:this.context.sessionID,producerAgentRole:this.context.agentRole,redactionPolicyVersion:computeRedactionPolicyVersion({rejectDurableSecrets:this.config.redaction.rejectDurableSecrets,detectPii:this.config.redaction.detectPii,rejectDurablePii:this.config.redaction.rejectDurablePii,piiDetector:this.config.redaction.piiDetector}),providerVersion:this.provider.name,sourceTaskId:this.context.unitId,validFrom:now2,supersedesReason:input.supersedesReason}}resolveCuratorDecision(decision){switch(decision.action){case"add":return{action:"add",proposalId:decision.proposalId,memory:this.createRecordFromNew(decision.memory)};case"supersede":return{action:"supersede",proposalId:decision.proposalId,oldMemoryId:decision.oldMemoryId,replacement:this.createRecordFromNew(decision.replacement),reason:normalizeMemoryText(decision.reason)};case"merge":return{action:"merge",proposalId:decision.proposalId,relatedMemoryIds:canonicalMemoryIds(decision.relatedMemoryIds),reason:normalizeMemoryText(decision.reason)};case"update":{let patch2=normalizeMemoryPatch(decision.patch);if(patch2.scope)patch2.scope=this.resolveRecordScope(patch2.scope);return{action:"update",proposalId:decision.proposalId,targetMemoryId:decision.targetMemoryId,patch:patch2,reason:normalizeMemoryText(decision.reason)}}case"reject":case"noop":return{action:decision.action,proposalId:decision.proposalId,reason:normalizeMemoryText(decision.reason)}}}createRecordFromNew(input){let record3=this.createRecord({kind:input.kind,text:input.text,scope:input.scope,tags:input.tags,confidence:input.confidence,stability:input.stability,source:input.source,metadata:input.metadata,anchors:input.anchors,outcomes:input.outcomes}),next=input.expiresAt?{...record3,expiresAt:input.expiresAt}:record3;return validateMemoryRecordRules(next,{rejectDurableSecrets:this.config.redaction.rejectDurableSecrets})}resolveRecordScope(scope,stability){let allowedScopes=this.deriveAllowedScopes();if(!scope){let wantsCohort=stability!=="ephemeral"&&stability!=="session",cohortScope=allowedScopes.find((s)=>s.type==="cohort"),defaultScope=wantsCohort?cohortScope??allowedScopes[1]??allowedScopes[0]:allowedScopes[1]??allowedScopes[0];if(!defaultScope)throw new MemoryValidationError("memory scope is not available for this context");return defaultScope}return validateRequestedScopes([scope],allowedScopes,"memory scope is not allowed for this context"),scope}assertEnabled(){if(!this.config.enabled)throw new MemoryDisabledError}}function createMemoryGateway(context,options={}){return new MemoryGateway(context,options)}function createConfiguredMemoryProvider(directory,config3){let root=resolveVettedMemoryRoot(directory,config3);return createConfiguredMemoryProviderForRoot(root,config3)}function createConfiguredMemoryProviderForRoot(root,config3){if(config3.provider==="sqlite")return getOrCreateProviderForRoot(root,config3);let directory=requirePhysicalFutureIoPath(root.directory);if(root.kind==="cohort"){try{mkdirSync54(root.cohortRoot,{recursive:!0})}catch{}return new LocalJsonlMemoryProvider(directory,config3,requirePhysicalFutureIoPath(root.cohortRoot))}return new LocalJsonlMemoryProvider(directory,config3,null)}function requirePhysicalFutureIoPath(entryPath){let canonical=canonicalPathForFutureIo(entryPath);if(canonical!==null)return canonical;throw new MemoryValidationError("memory storage root physical identity could not be resolved")}function sourceFromEvidence(evidenceRefs,context){let first=evidenceRefs[0];if(!first)return{type:"agent",createdBy:context.agentId??context.agentRole};if(/^https?:\/\//i.test(first))return{type:"web",url:first};if(/^[a-f0-9]{40}$/i.test(first))return{type:"commit",commitSha:first};let filePath=extractFilePaths(evidenceRefs)[0]??first;if(filePath!==first&&(filePath.includes("/")||filePath.includes("\\")||filePath.includes(".")))return{type:"file",filePath};if(first.includes("/")||first.includes("\\")||first.includes("."))return{type:"file",filePath:first};return{type:"manual",ref:first}}function createStableId(value){return createHash76("sha256").update(value.toLowerCase()).digest("hex").slice(0,16)}function cacheGitRemoteUrl(key2,remoteUrl){if(!gitRemoteUrlCache.has(key2))while(gitRemoteUrlCache.size>=MAX_GIT_REMOTE_CACHE_ENTRIES){let oldest=gitRemoteUrlCache.keys().next().value;if(oldest===void 0)break;gitRemoteUrlCache.delete(oldest)}gitRemoteUrlCache.set(key2,remoteUrl)}function readGitRemoteUrl(directory){let key2=canonicalRootKeyFresh(directory);if(gitRemoteUrlCache.has(key2))return gitRemoteUrlCache.get(key2);let gitConfigPath=path183.join(directory,".git","config");if(!existsSync90(gitConfigPath)){cacheGitRemoteUrl(key2,void 0);return}try{let remoteUrl=readFileSync67(gitConfigPath,"utf-8").match(/\[remote "origin"\][\s\S]*?\n\s*url\s*=\s*(.+)/)?.[1]?.trim();return cacheGitRemoteUrl(key2,remoteUrl),remoteUrl}catch{cacheGitRemoteUrl(key2,void 0);return}}function validateRequestedScopes(requested,allowed,disallowedMessage="recall scope is not allowed for this context"){if(requested.length===0)throw new MemoryValidationError("recall scopes must not be empty");let allowedKeys=new Set(allowed.map(scopeKey));for(let scope of requested)if(!allowedKeys.has(scopeKey(scope)))throw new MemoryValidationError(disallowedMessage);return requested}function resolveInjectionSkipReason(diagnostics){if(diagnostics.returnedCount>0)return;if(diagnostics.candidateCount===0)return"no_results";let signalEligibleCount=diagnostics.candidateCount-diagnostics.preScoredFilteredCount-diagnostics.suppressedLowQCount;if(signalEligibleCount>0&&diagnostics.noSignalCount>0&&diagnostics.noSignalCount>=signalEligibleCount)return"no_signal";if(diagnostics.belowThresholdCount>0)return"below_threshold";return"no_results"}function scopeKey(scope){return JSON.stringify({type:scope.type,userId:scope.userId,workspaceId:scope.workspaceId,projectId:scope.projectId,repoId:scope.repoId,repoRoot:scope.repoRoot?canonicalRootKeyFresh(scope.repoRoot):void 0,runId:scope.runId,agentId:scope.agentId,cohortId:scope.cohortId})}function clamp(value,min,max){return Math.min(max,Math.max(min,value))}function clampInt(value,min,max){return Math.trunc(clamp(value,min,max))}function normalizeTags2(tags){return Array.from(new Set(tags.map((tag)=>tag.toLowerCase().replace(/[^\w-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")).filter(Boolean))).slice(0,32)}function normalizeMemoryPatch(patch2){return{...patch2,text:patch2.text===void 0?void 0:normalizeMemoryText(patch2.text),tags:patch2.tags===void 0?void 0:normalizeTags2(patch2.tags)}}function inferTags2(text){let lower=text.toLowerCase(),tags=[];for(let[tag,pattern]of[["testing",/\b(test|spec|bun|jest|vitest)\b/],["tooling",/\b(pnpm|npm|yarn|bun|biome|eslint|typescript)\b/],["security",/\b(security|auth|token|secret|password|csp)\b/],["api",/\b(api|endpoint|graphql|rest|sdk)\b/],["architecture",/\b(architecture|decision|adr|pattern)\b/],["failure",/\b(fail|failure|regression|flaky|timeout)\b/]])if(pattern.test(lower))tags.push(tag);return tags}function extractFilePaths(refs){let seen=new Set,paths=[];for(let ref of refs){FILE_PATH_REGEX.lastIndex=0;let matches=ref.match(FILE_PATH_REGEX);if(!matches)continue;for(let m of matches)if(!seen.has(m)){if(seen.add(m),paths.push(m),paths.length>=20)return paths}}return paths}function extractSymbols2(refs){let seen=new Set,symbols=[],identRegex=/\b[a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z_][a-zA-Z0-9_]*)*\b/g;for(let ref of refs){identRegex.lastIndex=0;let matches=ref.match(identRegex);if(!matches)continue;for(let m of matches)if(m.length>=3&&!seen.has(m)&&!RESERVED_IDENTIFIERS.has(m)){if(seen.add(m),symbols.push(m),symbols.length>=20)return symbols}}return symbols}var PII_REJECTION_EVENT_TARGET="pii_rejection",gitRemoteUrlCache,MAX_GIT_REMOTE_CACHE_ENTRIES=128,FILE_PATH_REGEX,RESERVED_IDENTIFIERS;var init_gateway=__esm(()=>{init_canonical_root();init_filesystem_identity();init_logger();init_config3();init_curator_decision_helpers();init_errors6();init_local_jsonl_provider();init_outcome_events();init_pii();init_prompt_block();init_provider_pool();init_redaction();init_relations();init_schema2();init_sentinel();init_storage_root();gitRemoteUrlCache=new Map;FILE_PATH_REGEX=/\b(?:src|tests|test|docs|scripts|packages|lib|config|examples|internal|cmd|pkg|bin|tools|cli|api|server|client|app|core|utils|hooks|services|commands|agents|memory)\/[A-Za-z0-9._/@+-]+/g,RESERVED_IDENTIFIERS=new Set(["const","let","var","function","class","interface","type","async","await","return","if","else","for","while","do","switch","case","break","continue","new","this","super","extends","implements","import","export","from","default","try","catch","finally","throw","typeof","instanceof","in","of","as","yield","static","get","set","readonly","public","private","protected"])});async function applyCouncilReward(provider,opts){let bundles=await provider.listRecallUsage?.({runId:opts.runId})??[];if(bundles.length===0)return{memoriesRewarded:0};let attributedBundles=bundles.filter((bundle)=>bundle.unitId==null||opts.unitId==null||bundle.unitId===opts.unitId),distinctIds=new Set;for(let bundle of attributedBundles)for(let id of bundle.memoryIds)distinctIds.add(id);let result=await(provider.withTransaction?provider.withTransaction(async()=>{let updates=new Map;for(let id of distinctIds){let rec=await provider.get(id);if(!rec)continue;let qBefore=getQValue(rec,opts.initialQValue),qAfter=applyEmaUpdate(qBefore,opts.reward,opts.eta);updates.set(id,{rec,qBefore,qAfter})}for(let[id,{rec,qBefore,qAfter}]of updates)await provider.upsert(setQValue(rec,qAfter)),await provider.appendRewardEvent?.({memoryId:id,runId:opts.runId,unitId:opts.unitId,verdict:opts.verdictLabel??"APPROVE",reward:opts.reward,qBefore,qAfter,verdictSynthesisJson:opts.verdictSynthesisJson,timestamp:opts.timestamp});return updates}):(async()=>{let updates=new Map;for(let id of distinctIds){let rec=await provider.get(id);if(!rec)continue;let qBefore=getQValue(rec,opts.initialQValue),qAfter=applyEmaUpdate(qBefore,opts.reward,opts.eta);updates.set(id,{rec,qBefore,qAfter})}for(let[id,{rec,qBefore,qAfter}]of updates)await provider.upsert(setQValue(rec,qAfter)),await provider.appendRewardEvent?.({memoryId:id,runId:opts.runId,unitId:opts.unitId,verdict:opts.verdictLabel??"APPROVE",reward:opts.reward,qBefore,qAfter,verdictSynthesisJson:opts.verdictSynthesisJson,timestamp:opts.timestamp});return updates})()),memoriesRewarded=result.size,rewardedRecords=[...result.values()].map(({rec})=>rec);try{await propagateReward(provider,opts,rewardedRecords,distinctIds)}catch(err){log(`[memory:propagation] skipped after error: ${err instanceof Error?err.message:String(err)}`)}return{memoriesRewarded}}async function propagateReward(provider,opts,sources,directlyRewardedIds){if(sources.length===0)return;let qConfig=opts.qLearning??DEFAULT_QLEARNING_CONFIG,fraction=qConfig.propagationFraction,fanoutCap=qConfig.propagationFanoutCap,windowDays=qConfig.propagationWindowDays,relatednessThreshold=qConfig.propagationRelatednessThreshold;if(!Number.isFinite(fraction)||fraction<=0)return;if(!Number.isFinite(fanoutCap)||fanoutCap<=0)return;if(!Number.isFinite(windowDays)||windowDays<=0)return;if(!Number.isFinite(relatednessThreshold))return;if(typeof provider.list!=="function")return;let nowMs3=Date.parse(opts.timestamp);if(!Number.isFinite(nowMs3))return;let windowMs=windowDays*MS_PER_DAY3,recencyById=await buildRetrievalRecency(provider,nowMs3);if(!recencyById)return;let orderedSources=[...sources].sort((a,b)=>a.id.localeCompare(b.id)),scheduled=new Map,listCache=new Map;for(let source of orderedSources){let scopeKey2=stableScopeKey(source.scope),cacheKey=`${scopeKey2}::${source.kind}`,candidates=listCache.get(cacheKey);if(!candidates)candidates=await provider.list({scopes:[source.scope],kinds:[source.kind]}),listCache.set(cacheKey,candidates);let sourceTokens=tokenize(source.text),qualified=[];for(let cand of candidates){if(cand.id===source.id)continue;if(directlyRewardedIds.has(cand.id))continue;if(stableScopeKey(cand.scope)!==scopeKey2)continue;if(cand.kind!==source.kind)continue;let retrievedAt=recencyById.get(cand.id);if(retrievedAt===void 0)continue;if(nowMs3-retrievedAt>windowMs)continue;let overlap2=jaccard(sourceTokens,tokenize(cand.text));if(overlap2<relatednessThreshold)continue;qualified.push({record:cand,overlap:overlap2})}qualified.sort((a,b)=>b.overlap-a.overlap||a.record.id.localeCompare(b.record.id));let cap=Math.trunc(fanoutCap),selected=qualified.slice(0,cap),dropped=qualified.length-selected.length;if(dropped>0)log(`[memory:propagation] fan-out cap reached for source ${source.id}: ${qualified.length} qualified, ${selected.length} propagated, ${dropped} dropped by cap ${cap}`);for(let{record:record3}of selected)if(!scheduled.has(record3.id))scheduled.set(record3.id,record3)}for(let record3 of scheduled.values()){let qBefore=getQValue(record3,opts.initialQValue),qAfter=applyPropagatedEmaUpdate(qBefore,opts.reward,opts.eta,fraction);await provider.upsert(setQValue(record3,qAfter)),await provider.appendRewardEvent?.({memoryId:record3.id,runId:opts.runId,unitId:opts.unitId,verdict:`${opts.verdictLabel??"APPROVE"}${PROPAGATED_VERDICT_SUFFIX}`,reward:opts.reward,qBefore,qAfter,verdictSynthesisJson:opts.verdictSynthesisJson,timestamp:opts.timestamp})}}function truncateObjectForJson(obj,capBytes){let asIs=JSON.stringify(obj);if(asIs.length<=capBytes)return obj;if(JSON.stringify({...obj,__truncated__:!0}).length<=capBytes)return{...obj,__truncated__:!0};return{__truncated__:!0,originalSize:asIs.length,cap:capBytes}}async function buildRetrievalRecency(provider,nowMs3){if(typeof provider.listRecallUsage!=="function")return null;let since=new Date(nowMs3-RECENCY_WINDOW_MS).toISOString(),usage=await provider.listRecallUsage({since,limit:RECENCY_EVENT_LIMIT})??[],recency=new Map;for(let event of usage){let ts=Date.parse(event.timestamp);if(!Number.isFinite(ts))continue;for(let id of event.memoryIds){let prev=recency.get(id);if(prev===void 0||ts>prev)recency.set(id,ts)}}return recency}var PROPAGATED_VERDICT_SUFFIX="_PROPAGATED",MS_PER_DAY3=86400000,RECENCY_WINDOW_MS,RECENCY_EVENT_LIMIT=1000;var init_reward_capture=__esm(()=>{init_logger();init_config3();init_schema2();init_scoring();RECENCY_WINDOW_MS=30*MS_PER_DAY3});async function runFinalizeRewardSweep(args2){let result={swept:!1,tasksSwept:0,memoriesRewarded:0,runIdsProcessed:0};try{let{directory,memoryConfig}=args2;if(memoryConfig?.enabled!==!0)return result;let taskIds=[...new Set(args2.closedTaskIds.filter((id)=>typeof id==="string"&&id.length>0))];if(taskIds.length===0)return result;let timestamp=args2.timestamp??new Date().toISOString(),vettedRoot=resolveVettedMemoryRoot(directory,memoryConfig),provider=_internals156.createConfiguredMemoryProviderForRoot(vettedRoot,memoryConfig);try{result.swept=!0;for(let taskId of taskIds){let bundles=await provider.listRecallUsage?.({unitId:taskId})??[];if(bundles.length===0)continue;let runIds=new Set;for(let bundle of bundles)if(typeof bundle.runId==="string"&&bundle.runId.length>0)runIds.add(bundle.runId);if(runIds.size===0){log(`[memory:finalize-sweep] task ${taskId} has recall bundles without a runId; skipping to avoid over-penalizing unrelated untagged memories`);continue}let taskRewarded=0;for(let runId of runIds){let{memoriesRewarded}=await _internals156.applyCouncilReward(provider,{runId,unitId:taskId,reward:FINALIZE_NEGATIVE_TERMINAL_REWARD,eta:memoryConfig.qLearning.learningRate,initialQValue:memoryConfig.qLearning.initialQValue,qLearning:memoryConfig.qLearning,timestamp,verdictLabel:"session_terminated"});taskRewarded+=memoriesRewarded,result.runIdsProcessed++}if(taskRewarded>0)result.tasksSwept++,result.memoriesRewarded+=taskRewarded}}finally{await provider.close?.()}}catch(err){log(`[memory:finalize-sweep] skipped after error: ${err instanceof Error?err.message:String(err)}`)}return result}var FINALIZE_NEGATIVE_TERMINAL_REWARD=0,_internals156;var init_finalize_reward_sweep=__esm(()=>{init_logger();init_gateway();init_reward_capture();init_storage_root();_internals156={createConfiguredMemoryProvider,createConfiguredMemoryProviderForRoot,applyCouncilReward}});import*as fsSync18 from"node:fs";import{promises as fs101}from"node:fs";function wireCloseInternals(){Object.assign(closeReceiptLifecycleInternals,{recordPhaseCloseIntent,reconcilePhaseClose}),Object.assign(_internals123,{closeSnapshotCoordinationInitialization,closeRepoMemory,unlink:fs101.unlink,unlinkSidecarSync:fsSync18.unlinkSync,sleep,collectGarbageBestEffort,getGitRepositoryStatus:readGitRepositoryStatusDetailedAsync,resetToMainAfterMerge:(cwd,options)=>guardResetWithRecheck(resetToMainAfterMerge,cwd,options),resetToRemoteBranch,loadPluginConfigWithMeta,curateAndStoreSwarm,checkHivePromotions,runCuratorPostMortem,resetSwarmStatePreservingSingletons,runFinalizeRewardSweep,archiveEvidence,endAgentSession,flushAndDrainTelemetry:async()=>{let{flushAndDrainTelemetry:flushAndDrainTelemetry2}=await Promise.resolve().then(() => (init_telemetry(),exports_telemetry));return flushAndDrainTelemetry2()},finalizeContextTelemetry,finalizeCoreEvents:finalizeCoreEventsForClose})}var init_wiring=__esm(()=>{init_config2();init_telemetry2();init_core_events();init_manager2();init_branch();init_curator_postmortem();init_hive_promoter();init_knowledge_curator();init_knowledge_receipt_ledger();init_finalize_reward_sweep();init_snapshot_coordination_init();init_state();init_indexed_storage();init_bun_compat();init_git_status_read();init_align_stage();init_internals()});var init_close2=__esm(()=>{init_align_stage();init_archive_stage();init_clean_stage();init_dry_run();init_finalize_stage();init_fs_helpers();init_internals();init_orchestrator();init_wiring();init_align_stage();init_archive_stage();init_clean_stage();init_constants2();init_db_helpers();init_dry_run();init_finalize_stage();init_internals();init_orchestrator();Object.assign(_internals123,{unlinkActiveStateFileWithRetry,countSessionKnowledgeEntries,detectFullAuto,guaranteeAllPlansComplete,copyDirRecursive,runFinalizeStage,acquireFinalizeLock,runArchiveStage,archiveCloseSummary,runArchiveEvidenceRetention,runCleanStage,runAlignStage,runFinalizeDryRun,closePlanTerminalState:reconcileCloseTerminalStateForPlan});wireCloseInternals()});function sanitizeText(raw,maxLen){let normalized=raw.replace(/\[+\s*MODE\s*:[^\]]*(?:\]+|$)/gi,"").replace(/\s+/g," ").trim();if(normalized.length<=maxLen)return normalized;return`${normalized.slice(0,maxLen)}...`}function hasFlagValue(args2,index){return index+1<args2.length&&!args2[index+1].startsWith("--")}function jsonForModeHeader(value){return JSON.stringify(value).replace(/[[\]]/g,(ch)=>ch==="["?"\\u005B":"\\u005D")}function parseArgs(args2){let result={mode:"phase0",tracks:"",continueRun:"",output:"markdown",updateMain:!0,allowDirty:!1,rest:[]},i=0;while(i<args2.length){let token=args2[i];if(token==="--help"||token==="-h")result.help=!0;else if(token==="--mode"){if(!hasFlagValue(args2,i))return{...result,error:FLAG_VALUE_MISSING(token)};let value=args2[++i];if(!MODES.has(value))return{...result,error:`Invalid mode "${value}". Must be one of: ${[...MODES].join(", ")}.`};result.mode=value}else if(token==="--tracks"){if(!hasFlagValue(args2,i))return{...result,error:FLAG_VALUE_MISSING(token)};result.tracks=sanitizeText(args2[++i],1000)}else if(token==="--continue"){if(!hasFlagValue(args2,i))return{...result,error:FLAG_VALUE_MISSING(token)};let runId=sanitizeText(args2[++i],128);if(!/^[A-Za-z0-9_.-]+$/.test(runId))return{...result,error:"Invalid --continue value. Use only letters, numbers, dot, underscore, or dash."};result.continueRun=runId}else if(token==="--json")result.output="json";else if(token==="--skip-update")result.updateMain=!1;else if(token==="--allow-dirty")result.allowDirty=!0;else if(token.startsWith("--"))return{...result,error:`Unknown flag "${token}"`};else result.rest.push(token);i++}return result}async function handleCodebaseReviewCommand(_directory2,args2){let parsed=parseArgs(args2);if(parsed.help)return`Usage: /swarm codebase-review [scope] [--mode phase0|complete|defect|security|correctness|testing|ui|performance|ai-slop|enhancements|custom] [--tracks <list>] [--continue <run-id>] [--json] [--skip-update] [--allow-dirty]
|
|
2335
2335
|
|
|
2336
2336
|
Run the codebase-review-swarm workflow in the current repository.
|
|
2337
2337
|
|
|
@@ -2382,7 +2382,7 @@ Flags:
|
|
|
2382
2382
|
`)});function computeCouplingReport(tasks,cochangePairs,threshold,options){let roadmapTop=options?.roadmapTop??5,conflictingPairs=[],moduleConflictCount=new Map;for(let i=0;i<tasks.length;i++)for(let j=i+1;j<tasks.length;j++){let a=tasks[i],b=tasks[j],v=epicPairConflict(a.scope,b.scope,cochangePairs,threshold);if(!v.conflict)continue;conflictingPairs.push({a:a.id,b:b.id,reason:v.reason,cochangeMatches:v.evidence.cochangePairs.length,pathMatches:v.evidence.pathPairs.length});let driving=new Set;for(let[p1,p2]of v.evidence.pathPairs)driving.add(p1),driving.add(p2);for(let cp2 of v.evidence.cochangePairs)driving.add(cp2.a),driving.add(cp2.b);for(let m of driving)moduleConflictCount.set(m,(moduleConflictCount.get(m)??0)+1)}let totalPairs=tasks.length<=1?0:tasks.length*(tasks.length-1)/2,conflictingPairCount=conflictingPairs.length,p=totalPairs===0?0:conflictingPairCount/totalPairs,perModule=Array.from(moduleConflictCount.entries()).map(([module,conflicts])=>({module,conflicts,share:conflictingPairCount===0?0:conflicts/conflictingPairCount})).sort((x,y)=>{if(y.conflicts!==x.conflicts)return y.conflicts-x.conflicts;return x.module.localeCompare(y.module)}),roadmap=[];for(let m of perModule.slice(0,roadmapTop)){let pct=(m.share*100).toFixed(0);roadmap.push(`\`${m.module}\` appears in ${pct}% of conflicting pairs (${m.conflicts} pair${m.conflicts===1?"":"s"}) — isolating it behind an interface is a high-leverage refactor.`)}return{taskCount:tasks.length,totalPairs,conflictingPairCount,p,conflictingPairs,perModule,roadmap}}function formatCouplingReportMarkdown(report){let lines=[];if(lines.push("## Coupling Report"),lines.push(""),report.taskCount===0)return lines.push("No tasks to analyze (the plan is empty or all tasks were filtered out)."),lines.join(`
|
|
2383
2383
|
`);if(report.totalPairs===0)return lines.push(`Only ${report.taskCount} task in scope — at least two tasks are needed to measure coupling.`),lines.join(`
|
|
2384
2384
|
`);let pPct=(report.p*100).toFixed(2);if(lines.push(`**p = ${report.p.toFixed(3)}** (${report.conflictingPairCount} conflicting pair${report.conflictingPairCount===1?"":"s"} out of ${report.totalPairs} total — ${pPct}% of task pairs conflict)`),lines.push(""),lines.push("`p` is a measured coupling coefficient — *not* a target. Lower means the plan is naturally more parallelizable. Estimates above flow from the combined path + co-change signal Capability A computes; treat them as inputs to your refactor decisions, not as established facts."),lines.push(""),report.perModule.length>0){lines.push("### Per-module contention"),lines.push(""),lines.push("| Module | Conflicts | Pair coverage |"),lines.push("|---|---:|---:|");for(let m of report.perModule){let pct=(m.share*100).toFixed(0);lines.push(`| \`${m.module}\` | ${m.conflicts} | ${pct}% |`)}lines.push(""),lines.push("_Pair coverage = the fraction of conflicting pairs this module appears in. A single co-change pair attributes both endpoints, so coverage values can sum past 100%._"),lines.push("")}if(report.roadmap.length>0)lines.push("### Decoupling roadmap"),lines.push(""),report.roadmap.forEach((line,i)=>{lines.push(`${i+1}. ${line}`)}),lines.push("");if(report.conflictingPairs.length>0){lines.push("### Conflicting task pairs"),lines.push(""),lines.push("| Task A | Task B | Reason | Path overlaps | Co-change matches |"),lines.push("|---|---|---|---:|---:|");for(let pair of report.conflictingPairs)lines.push(`| ${pair.a} | ${pair.b} | ${pair.reason} | ${pair.pathMatches} | ${pair.cochangeMatches} |`);lines.push("")}return lines.join(`
|
|
2385
|
-
`)}var init_coupling_report=__esm(()=>{init_cochange_conflict()});import*as fs102 from"node:fs";import*as path186 from"node:path";function isDirectoryOnDisk(directory,entry){let target=path186.resolve(directory,entry),relative43=path186.relative(path186.resolve(directory),target);if(relative43.startsWith("..")||path186.isAbsolute(relative43))return!1;try{return fs102.statSync(target).isDirectory()}catch{return!1}}function isEpicPendingStatus(status2){return status2!=="completed"&&status2!=="closed"}function estimateEpicScopes(phases,declared){let scopes=Object.create(null),pendingIds=[],scoped=0;for(let phase of phases)for(let task of phase.tasks??[]){if(!isEpicPendingStatus(task.status))continue;pendingIds.push(task.id);let live=declared[task.id]??[];if(scopes[task.id]=live.length>0?[...live]:[...task.files_touched??[]],scopes[task.id].length>0)scoped+=1}return{scopes,pendingIds,scoped}}function epicWaveWidth(config3,isGitRepo3){if(!isGitRepo3)return 1;return Math.max(1,config3.turbo?.lean?.max_parallel_coders??DEFAULT_LEAN_TURBO_CONFIG.max_parallel_coders)}function epicSizingContextFor(directory,config3,maxParallel,signals){return{directory,leanConfig:{...DEFAULT_LEAN_TURBO_CONFIG,...config3.turbo?.lean??{}},signals,maxParallel,thresholds:resolveEpicSizingThresholds(resolveEpicConfig(config3)?.sizing)}}function pendingTasksOf(phase){return(phase.tasks??[]).filter((task)=>isEpicPendingStatus(task.status))}function runEpicPhase(context,tasks,scopes,maxWork){if(tasks.length===0)return{steps:0,unscheduled:0,work:0,aborted:!1};let dryRun=dryRunEpicPhase({directory:context.directory,tasks,scopes,leanConfig:context.leanConfig,hotFiles:context.signals.hotFiles,coWrites:context.signals.coWrites,cochange:context.signals.cochange,maxParallel:context.maxParallel,densityThreshold:context.signals.densityThreshold,...maxWork!==void 0?{maxWork}:{}});return{steps:dryRun.waves.length+dryRun.unscheduled.length,unscheduled:dryRun.unscheduled.length,work:dryRun.work,aborted:dryRun.aborted}}function sizeEpicPlan(context,phases,estimate,maxWork){let runs=new Map,serialSteps=0,work=0,aborted3=!1;for(let phase of phases){let pending=pendingTasksOf(phase);if(pending.length===0)continue;let run=runEpicPhase(context,pending,estimate.scopes,maxWork===void 0?void 0:Math.max(0,maxWork-work));runs.set(phase.id,run),serialSteps+=run.steps,work+=run.work,aborted3||=run.aborted}return{verdict:evaluateEpicSizing({pendingTasks:estimate.pendingIds.length,scopedTasks:estimate.scoped,serialSteps},context.thresholds),phases:runs,work,aborted:aborted3}}var MAX_START_SIZING_WORK=60000000;var init_shaping_sizing=__esm(()=>{init_constants();init_components();init_config();init_sizing()});class EpicWorkMeter{max;spent=0;truncated=!1;constructor(max){this.max=max}get left(){return Math.max(0,this.max-this.spent)}charge(cost){if(this.spent+cost>this.max)return this.truncated=!0,!1;return this.spent+=cost,!0}}function round3(value){return Math.round(value*1000)/1000}function ancestors(p){let out=[];for(let k=p.lastIndexOf("/");k>0;k=p.lastIndexOf("/",k-1))out.push(p.slice(0,k));return out}function nextTaskId(phaseId,taken){let max=0,prefix=`${phaseId}.`;for(let id2 of taken){if(!id2.startsWith(prefix))continue;let minor=Number.parseInt(id2.slice(prefix.length).split(".")[0],10);if(Number.isInteger(minor)&&minor>max)max=minor}let candidate=max+1;while(taken.has(`${phaseId}.${candidate}`))candidate+=1;let id=`${phaseId}.${candidate}`;return taken.add(id),id}function dependsOnTransitively(base,from,target){let seen=new Set,stack=[from];while(stack.length>0){let id=stack.pop();if(id===target)return!0;if(seen.has(id))continue;seen.add(id);for(let dep of base.dependsOf.get(id)??[])stack.push(dep)}return!1}function modelPhase(base,phase){let scopes=base.estimate.scopes,tasks=pendingTasksOf(phase).filter((t)=>t.status!=="blocked");if(tasks.length===0)return null;if(!base.meter.charge(epicWaveWork(tasks.map((t)=>(scopes[t.id]??[]).length),0)))return null;let graph=buildEpicConflictGraph({directory:base.context.directory,tasks,scopes,leanConfig:base.context.leanConfig,hotFiles:base.context.signals.hotFiles,coWrites:base.context.signals.coWrites,cochange:base.context.signals.cochange}),index=new Map;for(let id of graph.adjacency.keys()){let files=expandEpicScope(scopes[id]??[],base.context.signals.coWrites),paths=new Map,dirs=new Map;for(let file3 of files){paths.set(cmpKey(file3),file3);for(let dir of ancestors(file3))dirs.set(cmpKey(dir),dir)}index.set(id,{files,paths,dirs})}let edgeCount=0,driven=new Map;for(let[a,neighbours]of graph.adjacency)for(let b of neighbours){if(a>=b)continue;edgeCount+=1;let ia=index.get(a),ib=index.get(b);if(!ia||!ib)continue;if(!base.meter.charge(ia.files.length*4+1))return null;let drivers=new Set;for(let x of ia.files){let key2=cmpKey(x);if(ib.paths.has(key2)||ib.dirs.has(key2))drivers.add(x);for(let dir of ancestors(x)){let hit=ib.paths.get(cmpKey(dir));if(hit!==void 0)drivers.add(hit)}}for(let file3 of drivers)driven.set(file3,(driven.get(file3)??0)+1)}let exclusiveCaused=new Map;for(let[id,reason]of graph.exclusive){if(reason!=="global-file"&&reason!=="hot-file")continue;for(let file3 of new Set((scopes[id]??[]).map(normalizePath)))if(isGlobalFile(file3)||base.hot.has(file3))exclusiveCaused.set(file3,(exclusiveCaused.get(file3)??0)+1)}return{phase,tasks,graph,edgeCount,driven,exclusiveCaused}}function whatIf(base,phase,phaseTasks,scopes){let baseline=base.sizing.phases.get(phase.id);if(!baseline)return null;let run=runEpicPhase(base.context,phaseTasks,scopes,base.meter.left);if(base.meter.charge(Math.min(run.work,base.meter.left)),run.aborted)return base.meter.truncated=!0,null;if(run.unscheduled>baseline.unscheduled)return null;let before=pendingTasksOf(phase),scopedIn=(list2,map3)=>list2.filter((task)=>(map3[task.id]??[]).length>0).length,verdict=evaluateEpicSizing({pendingTasks:base.estimate.pendingIds.length+phaseTasks.length-before.length,scopedTasks:base.estimate.scoped-scopedIn(before,base.estimate.scopes)+scopedIn(phaseTasks,scopes),serialSteps:base.sizing.verdict.serialSteps-baseline.steps+run.steps},base.context.thresholds);return{effectiveSpeedup:verdict.effectiveSpeedup,serialSteps:verdict.serialSteps,pendingTasks:verdict.pendingTasks,epicSized:verdict.epicSized}}function gainOf(base,result){return round3(result.effectiveSpeedup-base.sizing.verdict.effectiveSpeedup)}function speedupText(base,result){return`effective speedup ${base.sizing.verdict.effectiveSpeedup.toFixed(2)}× → ${result.effectiveSpeedup.toFixed(2)}×`}function withDepends(phaseTasks,edits){return phaseTasks.map((task)=>{let depends=edits.get(task.id);return depends?{...task,depends:[...depends]}:task})}function isDirectoryEntry(base,entry,rawEntries,allPaths){if(rawEntries.some((raw)=>/[\\/]$/.test(raw)))return!0;for(let dir of allPaths)if(dir!==entry&&pathsConflict(entry,dir)&&dir.length>entry.length)return!0;if(entry.slice(entry.lastIndexOf("/")+1).includes("."))return!1;return base.isDirectory?base.isDirectory(entry):!0}function narrowScopeSuggestion(phase,entry,taskIds){return{type:"narrow-scope",phase:phase.id,entry,taskIds,deltaEffectiveSpeedup:null,whatIf:null,summary:`Narrow the directory scope ${entry} of task(s) ${taskIds.join(", ")} to the files they actually change (files_touched in save_plan) — a directory entry conflicts with every task under it, so it cannot be extracted.`}}function fileSuggestion(base,model,file3,totalEdges){let{phase}=model,scopes=base.estimate.scopes,owners=model.tasks.filter((task)=>task.status==="pending"&&(scopes[task.id]??[]).some((entry)=>normalizePath(entry)===file3));if(owners.length===0)return null;let ownerIds=owners.map((task)=>task.id),taken=new Set(base.usedIds),newId=nextTaskId(phase.id,taken),prereqDepends=[...new Set(owners.flatMap((task)=>task.depends??[]))].filter((dep)=>!ownerIds.includes(dep)&&!ownerIds.some((owner)=>dependsOnTransitively(base,dep,owner))).sort((a,b)=>a.localeCompare(b)),edits=owners.map((task)=>{let scope=scopes[task.id]??[],removed=scope.filter((entry)=>normalizePath(entry)===file3),rest=scope.filter((entry)=>normalizePath(entry)!==file3),keep=rest.length===0;return{taskId:task.id,remove_files:keep?[]:removed,add_depends:[newId],files_touched:keep?[...scope]:rest,depends:[...task.depends??[],newId]}}),description=`Prepare ${file3} for tasks ${ownerIds.join(", ")}: make every change they need in ${file3} first (extracted shared prerequisite), so they can run in parallel without touching it.`,nextScopes={...scopes,[newId]:[file3]};for(let edit of edits)nextScopes[edit.taskId]=edit.files_touched??[];let phaseTasks=[...withDepends(pendingTasksOf(phase),new Map(edits.map((edit)=>[edit.taskId,edit.depends]))),{id:newId,description,status:"pending",depends:prereqDepends,files_touched:[file3]}],result=whatIf(base,phase,phaseTasks,nextScopes);if(!result)return null;let gain=gainOf(base,result);if(!(gain>0))return null;let edgeShare=totalEdges>0?round3((model.driven.get(file3)??0)/totalEdges):0,isHot=base.hot.has(file3),fileKind=isGlobalFile(file3)?"global-file":isHot?"hot-file":"hub-file",type;if(owners.length>=HUB_MIN_TASKS&&(edgeShare>=HUB_MIN_EDGE_SHARE||gain>=HUB_MIN_DELTA))type="extract-prerequisite";else if(isHot)type="isolate-hot-file";else return null;let verb=type==="extract-prerequisite"?`Extract ${fileKind} ${file3} (declared by ${ownerIds.length} tasks, ${Math.round(edgeShare*100)}% of conflict edges) into prerequisite task ${newId}`:`Isolate hot file ${file3} into its own task ${newId} (so ${ownerIds.join(", ")} stop running alone)`;return{type,phase:phase.id,file:file3,fileKind,taskIds:ownerIds,edgeShare,patch:{newTask:{id:newId,phase:phase.id,description,files_touched:[file3],depends:prereqDepends},edits},deltaEffectiveSpeedup:gain,whatIf:result,summary:`${verb}: ${speedupText(base,result)}.`}}function articulationPoints(graph){let index=new Map,low=new Map,points=new Set,counter=0,visit=(node,parent)=>{index.set(node,counter),low.set(node,counter),counter+=1;let children=0;for(let next of graph.adjacency.get(node)??[])if(!index.has(next)){if(children+=1,visit(next,node),low.set(node,Math.min(low.get(node)??0,low.get(next)??0)),parent!==null&&(low.get(next)??0)>=(index.get(node)??0))points.add(node)}else if(next!==parent)low.set(node,Math.min(low.get(node)??0,index.get(next)??0));if(parent===null&&children>1)points.add(node)},nodes=[...graph.adjacency.keys()].sort((a,b)=>a.localeCompare(b));for(let node of nodes)if(!index.has(node))visit(node,null);return[...points]}function clustersAround(graph,taskId){let seen=new Set([taskId]),clusters=[],neighbours=[...graph.adjacency.get(taskId)??[]].sort((a,b)=>a.localeCompare(b));for(let start of neighbours){if(seen.has(start))continue;let cluster=[],queue=[start];seen.add(start);while(queue.length>0){let node=queue.shift();cluster.push(node);for(let next of graph.adjacency.get(node)??[])if(!seen.has(next))seen.add(next),queue.push(next)}clusters.push(cluster.sort((a,b)=>a.localeCompare(b)))}return clusters}function splitSuggestion(base,model,taskId){let{phase}=model,scopes=base.estimate.scopes,own=scopes[taskId]??[];if(own.length<2)return null;let clusters=clustersAround(model.graph,taskId);if(clusters.length<2)return null;let clusterFiles=clusters.map((cluster)=>cluster.flatMap((id)=>expandEpicScope(scopes[id]??[],base.context.signals.coWrites)));if(!base.meter.charge(own.length*clusterFiles.flat().length+1))return null;let parts=clusters.map(()=>[]),loose=[];for(let entry of own){let file3=normalizePath(entry),at=clusterFiles.findIndex((files)=>files.some((other)=>pathsConflict(file3,other)));if(at===-1)loose.push(entry);else parts[at].push(entry)}let nonEmpty2=parts.filter((part)=>part.length>0);if(nonEmpty2.length<2)return null;nonEmpty2[0].push(...loose);let taken=new Set(base.usedIds),partIds=nonEmpty2.map((_,i)=>i===0?taskId:nextTaskId(phase.id,taken)),ownDepends=[...model.tasks.find((t)=>t.id===taskId)?.depends??[]],newTasks=nonEmpty2.slice(1).map((files,i)=>({id:partIds[i+1],phase:phase.id,description:`Part ${i+2} of task ${taskId}: its work in ${files.join(", ")} (split out so it no longer joins two conflict clusters).`,files_touched:files,depends:ownDepends})),edits=[{taskId,depends:ownDepends,files_touched:nonEmpty2[0]},...(base.dependents.get(taskId)??[]).map((dependent)=>({taskId:dependent,depends:[...base.dependsOf.get(dependent)??[],...partIds.slice(1)]}))],editDepends=new Map(edits.map((edit)=>[edit.taskId,edit.depends])),nextScopes={...scopes};nonEmpty2.forEach((files,i)=>{nextScopes[partIds[i]]=files});let phaseTasks=[...withDepends(pendingTasksOf(phase),editDepends),...newTasks.map((part)=>({id:part.id,description:part.description,status:"pending",depends:part.depends,files_touched:part.files_touched}))],result=whatIf(base,phase,phaseTasks,nextScopes);if(!result)return null;let gain=gainOf(base,result);if(!(gain>0))return null;return{type:"split-task",phase:phase.id,taskId,parts:nonEmpty2,patch:{newTasks,edits},deltaEffectiveSpeedup:gain,whatIf:result,summary:`Split task ${taskId} (it joins ${nonEmpty2.length} conflict clusters) into ${partIds.join(", ")}, one per cluster: ${nonEmpty2.map((files)=>`[${files.join(", ")}]`).join(" / ")}; every task depending on ${taskId} must depend on all parts — ${speedupText(base,result)}.`}}function jaccard2(a,b){let both=0;for(let file3 of a)if(b.has(file3))both+=1;let union3=a.size+b.size-both;return union3===0?0:both/union3}function mergeSuggestion(base,phase,keep,absorb,similarity){let keepDeps=base.dependsOf.get(keep.id)??[],absorbDeps=base.dependsOf.get(absorb.id)??[];if(absorbDeps.some((dep)=>dep!==keep.id&&dependsOnTransitively(base,dep,keep.id))||keepDeps.some((dep)=>dep!==absorb.id&&dependsOnTransitively(base,dep,absorb.id)))return null;let scopes=base.estimate.scopes,files=[],seen=new Set;for(let entry of[...scopes[keep.id]??[],...scopes[absorb.id]??[]]){let key2=normalizePath(entry);if(seen.has(key2))continue;seen.add(key2),files.push(entry)}let depends=[...new Set([...keepDeps,...absorbDeps])].filter((dep)=>dep!==keep.id&&dep!==absorb.id),edits=[{taskId:keep.id,depends,files_touched:files},...(base.dependents.get(absorb.id)??[]).filter((dependent)=>dependent!==keep.id).map((dependent)=>({taskId:dependent,depends:[...new Set((base.dependsOf.get(dependent)??[]).map((dep)=>dep===absorb.id?keep.id:dep))]}))],nextScopes={...scopes,[keep.id]:files};delete nextScopes[absorb.id];let phaseTasks=withDepends(pendingTasksOf(phase).filter((task)=>task.id!==absorb.id),new Map(edits.map((edit)=>[edit.taskId,edit.depends]))),result=whatIf(base,phase,phaseTasks,nextScopes);if(!result)return null;let gain=gainOf(base,result);if(gain<0)return null;return{type:"merge-tasks",phase:phase.id,keep:keep.id,absorb:absorb.id,jaccard:round3(similarity),patch:{removed_task_ids:[absorb.id],removal_reason:`Merged into ${keep.id} (plan shaping: ${Math.round(similarity*100)}% scope overlap).`,edits},deltaEffectiveSpeedup:gain,whatIf:result,summary:`Merge task ${absorb.id} into ${keep.id} (small tasks, ${Math.round(similarity*100)}% scope overlap — they serialize anyway; one task saves a QA cycle): save_plan without ${absorb.id} (removed_task_ids + removal_reason), ${keep.id} with the union scope, dependents re-pointed to ${keep.id} — ${speedupText(base,result)}.`}}function dependencyIndex(phases){let dependsOf=new Map,dependents=new Map;for(let phase of phases)for(let task of phase.tasks??[]){let deps=[...task.depends??[]];dependsOf.set(task.id,deps);for(let dep of deps){let list2=dependents.get(dep);if(list2)list2.push(task.id);else dependents.set(dep,[task.id])}}return{dependsOf,dependents}}var HUB_MIN_TASKS=3,HUB_MIN_EDGE_SHARE=0.25,HUB_MIN_DELTA=0.25,MERGE_MIN_JACCARD=0.8,cmpKey=(p)=>process.platform==="win32"?p.toLowerCase():p;var init_shaping_suggestions=__esm(()=>{init_conflicts();init_components();init_learning();init_shaping_sizing();init_sizing()});function shapeEpicPlan(input){let estimate=estimateEpicScopes(input.phases,input.declared),files=new Set;for(let id of estimate.pendingIds)for(let entry of estimate.scopes[id]??[])files.add(normalizePath(entry));let meter=new EpicWorkMeter(input.maxWork??MAX_SHAPING_WORK),budget={tasks:estimate.pendingIds.length,files:files.size,maxTasks:MAX_SHAPING_TASKS,maxFiles:MAX_SHAPING_FILES,whatIfs:0,work:0,maxWork:meter.max,truncated:!1},skipped=(sizing2)=>({verdict:"skipped-budget",sizing:sizing2,suggestions:[],budget:{...budget,work:meter.spent,truncated:!0}});if(budget.tasks>MAX_SHAPING_TASKS||budget.files>MAX_SHAPING_FILES)return skipped(null);let sizing=input.baseline;if(!sizing)sizing=sizeEpicPlan(input,input.phases,estimate,meter.left),meter.charge(Math.min(sizing.work,meter.left));if(sizing.aborted)return skipped(null);let{dependsOf,dependents}=dependencyIndex(input.phases),usedIds=new Set(dependsOf.keys()),base={context:input,phases:input.phases,estimate,sizing,hot:new Set(input.signals.hotFiles.map(normalizePath)),usedIds,dependsOf,dependents,...input.isDirectory?{isDirectory:input.isDirectory}:{},meter},suggestions=[],unscoped=estimate.pendingIds.filter((id)=>(estimate.scopes[id]??[]).length===0);if(unscoped.length>0){let listed=unscoped.slice(0,MAX_LISTED_TASKS);suggestions.push({type:"declare-scope",taskIds:listed,count:unscoped.length,deltaEffectiveSpeedup:null,whatIf:null,summary:`Give ${unscoped.length} task(s) a scope (files_touched in save_plan): ${listed.join(", ")}${unscoped.length>listed.length?", …":""} — a task without a scope always runs alone.`})}let models=[];for(let phase of input.phases){let model=modelPhase(base,phase);if(model)models.push(model)}let totalEdges=models.reduce((sum,m)=>sum+m.edgeCount,0),attempted=0,allPaths=files,candidates=[];for(let model of models){let fileSet=new Set([...model.driven.keys(),...model.exclusiveCaused.keys(),...[...base.hot].filter((file3)=>model.tasks.some((task)=>(estimate.scopes[task.id]??[]).some((entry)=>normalizePath(entry)===file3)))]);for(let file3 of fileSet){let score=(model.driven.get(file3)??0)+(model.exclusiveCaused.get(file3)??0);if(score>0||base.hot.has(file3))candidates.push({model,file:file3,score})}}candidates.sort((a,b)=>b.score-a.score||a.model.phase.id-b.model.phase.id||a.file.localeCompare(b.file));for(let candidate of candidates.slice(0,MAX_WHAT_IF_FILES)){let owners=candidate.model.tasks.filter((task)=>(estimate.scopes[task.id]??[]).some((entry)=>normalizePath(entry)===candidate.file)),raw=owners.flatMap((task)=>(estimate.scopes[task.id]??[]).filter((entry)=>normalizePath(entry)===candidate.file));if(owners.length>0&&isDirectoryEntry(base,candidate.file,raw,allPaths)){suggestions.push(narrowScopeSuggestion(candidate.model.phase,candidate.file,owners.map((task)=>task.id)));continue}if(meter.left===0)break;attempted+=1;let suggestion=fileSuggestion(base,candidate.model,candidate.file,totalEdges);if(suggestion)suggestions.push(suggestion)}let splits=[];for(let model of models){if(!meter.charge(model.edgeCount+model.tasks.length))break;for(let id of articulationPoints(model.graph)){if(model.tasks.find((t)=>t.id===id)?.status!=="pending")continue;splits.push({model,id,degree:model.graph.adjacency.get(id)?.size??0})}}splits.sort((a,b)=>b.degree-a.degree||a.model.phase.id-b.model.phase.id||a.id.localeCompare(b.id));for(let split of splits.slice(0,MAX_WHAT_IF_SPLITS)){if(meter.left===0)break;attempted+=1;let suggestion=splitSuggestion(base,split.model,split.id);if(suggestion)suggestions.push(suggestion)}let merges=[];for(let model of models){let small=model.tasks.filter((task)=>task.status==="pending"&&(task.size??"small")==="small"&&(estimate.scopes[task.id]??[]).length>0),sets=new Map(small.map((task)=>[task.id,new Set((estimate.scopes[task.id]??[]).map(normalizePath))])),avg=small.reduce((sum,task)=>sum+(sets.get(task.id)?.size??0),0)/Math.max(1,small.length);if(!meter.charge(Math.ceil(small.length*(small.length-1)/2*(avg+1))))break;for(let i=0;i<small.length;i+=1)for(let j=i+1;j<small.length;j+=1){let similarity=jaccard2(sets.get(small[i].id)??new Set,sets.get(small[j].id)??new Set);if(similarity<MERGE_MIN_JACCARD)continue;let[keep,absorb]=(model.graph.topoIndex.get(small[i].id)??0)<=(model.graph.topoIndex.get(small[j].id)??0)?[small[i],small[j]]:[small[j],small[i]];merges.push({model,keep,absorb,similarity})}}merges.sort((a,b)=>b.similarity-a.similarity||a.model.phase.id-b.model.phase.id||a.keep.id.localeCompare(b.keep.id)||a.absorb.id.localeCompare(b.absorb.id));for(let merge3 of merges.slice(0,MAX_WHAT_IF_MERGES)){if(meter.left===0)break;attempted+=1;let suggestion=mergeSuggestion(base,merge3.model.phase,merge3.keep,merge3.absorb,merge3.similarity);if(suggestion)suggestions.push(suggestion)}suggestions.sort((a,b)=>(isScopeAdvice(a)?0:1)-(isScopeAdvice(b)?0:1)||(b.deltaEffectiveSpeedup??0)-(a.deltaEffectiveSpeedup??0)||TYPE_ORDER[a.type]-TYPE_ORDER[b.type]||a.summary.localeCompare(b.summary));let ranked=suggestions.slice(0,MAX_SHAPING_SUGGESTIONS),finalBudget={...budget,whatIfs:attempted,work:meter.spent,truncated:meter.truncated};if(meter.truncated&&ranked.length===0&&!sizing.verdict.epicSized)return{verdict:"skipped-budget",sizing:sizing.verdict,suggestions:[],budget:finalBudget};return{verdict:verdictOf(sizing.verdict,ranked),sizing:sizing.verdict,suggestions:ranked,budget:finalBudget}}function verdictOf(sizing,suggestions){let scopeAdvice=suggestions.some(isScopeAdvice);if(sizing.epicSized)return suggestions.some((s)=>(s.deltaEffectiveSpeedup??0)>=MIN_USEFUL_DELTA)||scopeAdvice?"improvable":"acceptable";if(suggestions.some((s)=>s.whatIf?.epicSized===!0))return"improvable";if(scopeAdvice&&!sizing.reasons.includes("too-few-tasks"))return"improvable";return"not-epic-sized"}function describeEpicShapingSkip(report){let{budget}=report;if(budget.tasks>budget.maxTasks||budget.files>budget.maxFiles)return`Plan shaping skipped: ${budget.tasks} pending task(s) / ${budget.files} scope file(s) exceed the shaping budget (${budget.maxTasks} tasks / ${budget.maxFiles} files).`;if(report.sizing===null)return`Plan shaping skipped: the plan (${budget.tasks} pending task(s), ${budget.files} scope file(s)) is too large or densely coupled to size within the shaping work budget.`;return`Plan shaping skipped: the plan is too densely coupled to evaluate suggestions within the shaping work budget (effective speedup ${report.sizing.effectiveSpeedup.toFixed(2)}×, ${report.sizing.pendingTasks} task(s) in ${report.sizing.serialSteps} serial step(s)${report.sizing.epicSized?"":" — not epic-sized"}).`}function describeEpicShapingReasons(sizing){return sizing.reasons.map((reason)=>describeEpicSizingReason(reason,sizing)).join("; ")}function depList(ids){return`[${ids.join(", ")}]`}function formatEpicShapingLines(report,options={}){if(report.verdict==="skipped-budget")return[describeEpicShapingSkip(report)];let sizing=report.sizing,lines=[`Plan shaping: **${report.verdict}** — ${VERDICT_TEXT[report.verdict]}${sizing?` (effective speedup ${sizing.effectiveSpeedup.toFixed(2)}×, ${sizing.pendingTasks} task(s) in ${sizing.serialSteps} serial step(s))`:""}.`],shown=report.suggestions.slice(0,options.maxSuggestions??MAX_SHAPING_SUGGESTIONS);if(shown.forEach((suggestion,index)=>{lines.push(`${index+1}. [${suggestion.type}] ${suggestion.summary}`);let editText=(edits)=>edits.map((edit)=>`${edit.taskId}: ${edit.files_touched?`files_touched ${depList(edit.files_touched)}, `:""}depends ${depList(edit.depends)}`).join("; ");if(suggestion.type==="extract-prerequisite"||suggestion.type==="isolate-hot-file"){let{newTask,edits}=suggestion.patch;lines.push(` Patch: add task ${newTask.id} to phase ${newTask.phase} (files_touched ${depList(newTask.files_touched)}, depends ${depList(newTask.depends)}); ${editText(edits)}.`)}else if(suggestion.type==="split-task"){let{newTasks,edits}=suggestion.patch;lines.push(` Patch: add ${newTasks.map((t)=>`task ${t.id} (files_touched ${depList(t.files_touched)})`).join(", ")} to phase ${suggestion.phase}; ${editText(edits)}.`)}else if(suggestion.type==="merge-tasks")lines.push(` Patch: removed_task_ids [${suggestion.absorb}] (removal_reason given); ${editText(suggestion.patch.edits)}.`)}),report.suggestions.length>shown.length)lines.push(`(${report.suggestions.length-shown.length} more — \`/swarm coupling --suggest\` lists all.)`);return lines}var MAX_SHAPING_TASKS=200,MAX_SHAPING_FILES=500,MAX_WHAT_IF_FILES=10,MAX_WHAT_IF_SPLITS=3,MAX_WHAT_IF_MERGES=3,MAX_SHAPING_WORK=6000000,MAX_SHAPING_SUGGESTIONS=5,MIN_USEFUL_DELTA=0.05,MAX_LISTED_TASKS=20,TYPE_ORDER,isScopeAdvice=(s)=>s.type==="declare-scope"||s.type==="narrow-scope",VERDICT_TEXT;var init_shaping=__esm(()=>{init_conflicts();init_shaping_sizing();init_shaping_suggestions();init_sizing();TYPE_ORDER={"declare-scope":0,"narrow-scope":1,"extract-prerequisite":2,"isolate-hot-file":3,"split-task":4,"merge-tasks":5};VERDICT_TEXT={acceptable:"epic-sized, nothing worth reshaping",improvable:"the suggestions below would help","not-epic-sized":"not epic-sized, and no suggestion makes it epic-sized — run it in Balanced","skipped-budget":"skipped (budget)"}});import*as fs103 from"node:fs";import*as path187 from"node:path";function parseArgs3(args2){let parsed={threshold:DEFAULT_THRESHOLD,minCoChanges:DEFAULT_MIN_CO_CHANGES2,format:"markdown",persist:!1,suggest:!1};for(let i=0;i<args2.length;i++){let flag=args2[i],next=args2[i+1];switch(flag){case"--phase":{if(!next)return parsed.parseError="--phase requires a numeric argument",parsed;if(!/^\d+$/.test(next))return parsed.parseError=`--phase must be a positive integer (got '${next}')`,parsed;let v=Number.parseInt(next,10);if(v<1)return parsed.parseError=`--phase must be a positive integer (got '${next}')`,parsed;parsed.phase=v,i+=1;break}case"--threshold":{if(!next)return parsed.parseError="--threshold requires a numeric argument",parsed;let v=Number.parseFloat(next);if(Number.isNaN(v)||v<-1||v>1)return parsed.parseError=`--threshold must be a number in [-1, 1] (got '${next}')`,parsed;parsed.threshold=v,i+=1;break}case"--min-co-changes":{if(!next)return parsed.parseError="--min-co-changes requires a numeric argument",parsed;if(!/^\d+$/.test(next))return parsed.parseError=`--min-co-changes must be a positive integer (got '${next}')`,parsed;let v=Number.parseInt(next,10);if(v<1)return parsed.parseError=`--min-co-changes must be a positive integer (got '${next}')`,parsed;parsed.minCoChanges=v,i+=1;break}case"--format":{if(!next||next!=="markdown"&&next!=="json")return parsed.parseError=`--format must be 'markdown' or 'json' (got '${next??"<missing>"}')`,parsed;parsed.format=next,i+=1;break}case"--persist":parsed.persist=!0;break;case"--suggest":parsed.suggest=!0;break;default:return parsed.parseError=`unknown argument: ${flag}`,parsed}}return parsed}function persistReportJson(directory,report){let epicDir=path187.join(directory,".swarm","epic");fs103.mkdirSync(epicDir,{recursive:!0});let filePath=path187.join(epicDir,"coupling-report.json");return atomicWriteSwarmFileSync(filePath,`${JSON.stringify(report,null,2)}
|
|
2385
|
+
`)}var init_coupling_report=__esm(()=>{init_cochange_conflict()});import*as fs102 from"node:fs";import*as path186 from"node:path";function isDirectoryOnDisk(directory,entry){let target=path186.resolve(directory,entry),relative43=path186.relative(path186.resolve(directory),target);if(relative43.startsWith("..")||path186.isAbsolute(relative43))return!1;try{return fs102.statSync(target).isDirectory()}catch{return!1}}function isEpicPendingStatus(status2){return status2!=="completed"&&status2!=="closed"}function estimateEpicScopes(phases,declared){let scopes=Object.create(null),pendingIds=[],scoped=0;for(let phase of phases)for(let task of phase.tasks??[]){if(!isEpicPendingStatus(task.status))continue;pendingIds.push(task.id);let live=declared[task.id]??[];if(scopes[task.id]=live.length>0?[...live]:[...task.files_touched??[]],scopes[task.id].length>0)scoped+=1}return{scopes,pendingIds,scoped}}function epicWaveWidth(config3,isGitRepo2){if(!isGitRepo2)return 1;return Math.max(1,config3.turbo?.lean?.max_parallel_coders??DEFAULT_LEAN_TURBO_CONFIG.max_parallel_coders)}function epicSizingContextFor(directory,config3,maxParallel,signals){return{directory,leanConfig:{...DEFAULT_LEAN_TURBO_CONFIG,...config3.turbo?.lean??{}},signals,maxParallel,thresholds:resolveEpicSizingThresholds(resolveEpicConfig(config3)?.sizing)}}function pendingTasksOf(phase){return(phase.tasks??[]).filter((task)=>isEpicPendingStatus(task.status))}function runEpicPhase(context,tasks,scopes,maxWork){if(tasks.length===0)return{steps:0,unscheduled:0,work:0,aborted:!1};let dryRun=dryRunEpicPhase({directory:context.directory,tasks,scopes,leanConfig:context.leanConfig,hotFiles:context.signals.hotFiles,coWrites:context.signals.coWrites,cochange:context.signals.cochange,maxParallel:context.maxParallel,densityThreshold:context.signals.densityThreshold,...maxWork!==void 0?{maxWork}:{}});return{steps:dryRun.waves.length+dryRun.unscheduled.length,unscheduled:dryRun.unscheduled.length,work:dryRun.work,aborted:dryRun.aborted}}function sizeEpicPlan(context,phases,estimate,maxWork){let runs=new Map,serialSteps=0,work=0,aborted3=!1;for(let phase of phases){let pending=pendingTasksOf(phase);if(pending.length===0)continue;let run=runEpicPhase(context,pending,estimate.scopes,maxWork===void 0?void 0:Math.max(0,maxWork-work));runs.set(phase.id,run),serialSteps+=run.steps,work+=run.work,aborted3||=run.aborted}return{verdict:evaluateEpicSizing({pendingTasks:estimate.pendingIds.length,scopedTasks:estimate.scoped,serialSteps},context.thresholds),phases:runs,work,aborted:aborted3}}var MAX_START_SIZING_WORK=60000000;var init_shaping_sizing=__esm(()=>{init_constants();init_components();init_config();init_sizing()});class EpicWorkMeter{max;spent=0;truncated=!1;constructor(max){this.max=max}get left(){return Math.max(0,this.max-this.spent)}charge(cost){if(this.spent+cost>this.max)return this.truncated=!0,!1;return this.spent+=cost,!0}}function round3(value){return Math.round(value*1000)/1000}function ancestors(p){let out=[];for(let k=p.lastIndexOf("/");k>0;k=p.lastIndexOf("/",k-1))out.push(p.slice(0,k));return out}function nextTaskId(phaseId,taken){let max=0,prefix=`${phaseId}.`;for(let id2 of taken){if(!id2.startsWith(prefix))continue;let minor=Number.parseInt(id2.slice(prefix.length).split(".")[0],10);if(Number.isInteger(minor)&&minor>max)max=minor}let candidate=max+1;while(taken.has(`${phaseId}.${candidate}`))candidate+=1;let id=`${phaseId}.${candidate}`;return taken.add(id),id}function dependsOnTransitively(base,from,target){let seen=new Set,stack=[from];while(stack.length>0){let id=stack.pop();if(id===target)return!0;if(seen.has(id))continue;seen.add(id);for(let dep of base.dependsOf.get(id)??[])stack.push(dep)}return!1}function modelPhase(base,phase){let scopes=base.estimate.scopes,tasks=pendingTasksOf(phase).filter((t)=>t.status!=="blocked");if(tasks.length===0)return null;if(!base.meter.charge(epicWaveWork(tasks.map((t)=>(scopes[t.id]??[]).length),0)))return null;let graph=buildEpicConflictGraph({directory:base.context.directory,tasks,scopes,leanConfig:base.context.leanConfig,hotFiles:base.context.signals.hotFiles,coWrites:base.context.signals.coWrites,cochange:base.context.signals.cochange}),index=new Map;for(let id of graph.adjacency.keys()){let files=expandEpicScope(scopes[id]??[],base.context.signals.coWrites),paths=new Map,dirs=new Map;for(let file3 of files){paths.set(cmpKey(file3),file3);for(let dir of ancestors(file3))dirs.set(cmpKey(dir),dir)}index.set(id,{files,paths,dirs})}let edgeCount=0,driven=new Map;for(let[a,neighbours]of graph.adjacency)for(let b of neighbours){if(a>=b)continue;edgeCount+=1;let ia=index.get(a),ib=index.get(b);if(!ia||!ib)continue;if(!base.meter.charge(ia.files.length*4+1))return null;let drivers=new Set;for(let x of ia.files){let key2=cmpKey(x);if(ib.paths.has(key2)||ib.dirs.has(key2))drivers.add(x);for(let dir of ancestors(x)){let hit=ib.paths.get(cmpKey(dir));if(hit!==void 0)drivers.add(hit)}}for(let file3 of drivers)driven.set(file3,(driven.get(file3)??0)+1)}let exclusiveCaused=new Map;for(let[id,reason]of graph.exclusive){if(reason!=="global-file"&&reason!=="hot-file")continue;for(let file3 of new Set((scopes[id]??[]).map(normalizePath)))if(isGlobalFile(file3)||base.hot.has(file3))exclusiveCaused.set(file3,(exclusiveCaused.get(file3)??0)+1)}return{phase,tasks,graph,edgeCount,driven,exclusiveCaused}}function whatIf(base,phase,phaseTasks,scopes){let baseline=base.sizing.phases.get(phase.id);if(!baseline)return null;let run=runEpicPhase(base.context,phaseTasks,scopes,base.meter.left);if(base.meter.charge(Math.min(run.work,base.meter.left)),run.aborted)return base.meter.truncated=!0,null;if(run.unscheduled>baseline.unscheduled)return null;let before=pendingTasksOf(phase),scopedIn=(list2,map3)=>list2.filter((task)=>(map3[task.id]??[]).length>0).length,verdict=evaluateEpicSizing({pendingTasks:base.estimate.pendingIds.length+phaseTasks.length-before.length,scopedTasks:base.estimate.scoped-scopedIn(before,base.estimate.scopes)+scopedIn(phaseTasks,scopes),serialSteps:base.sizing.verdict.serialSteps-baseline.steps+run.steps},base.context.thresholds);return{effectiveSpeedup:verdict.effectiveSpeedup,serialSteps:verdict.serialSteps,pendingTasks:verdict.pendingTasks,epicSized:verdict.epicSized}}function gainOf(base,result){return round3(result.effectiveSpeedup-base.sizing.verdict.effectiveSpeedup)}function speedupText(base,result){return`effective speedup ${base.sizing.verdict.effectiveSpeedup.toFixed(2)}× → ${result.effectiveSpeedup.toFixed(2)}×`}function withDepends(phaseTasks,edits){return phaseTasks.map((task)=>{let depends=edits.get(task.id);return depends?{...task,depends:[...depends]}:task})}function isDirectoryEntry(base,entry,rawEntries,allPaths){if(rawEntries.some((raw)=>/[\\/]$/.test(raw)))return!0;for(let dir of allPaths)if(dir!==entry&&pathsConflict(entry,dir)&&dir.length>entry.length)return!0;if(entry.slice(entry.lastIndexOf("/")+1).includes("."))return!1;return base.isDirectory?base.isDirectory(entry):!0}function narrowScopeSuggestion(phase,entry,taskIds){return{type:"narrow-scope",phase:phase.id,entry,taskIds,deltaEffectiveSpeedup:null,whatIf:null,summary:`Narrow the directory scope ${entry} of task(s) ${taskIds.join(", ")} to the files they actually change (files_touched in save_plan) — a directory entry conflicts with every task under it, so it cannot be extracted.`}}function fileSuggestion(base,model,file3,totalEdges){let{phase}=model,scopes=base.estimate.scopes,owners=model.tasks.filter((task)=>task.status==="pending"&&(scopes[task.id]??[]).some((entry)=>normalizePath(entry)===file3));if(owners.length===0)return null;let ownerIds=owners.map((task)=>task.id),taken=new Set(base.usedIds),newId=nextTaskId(phase.id,taken),prereqDepends=[...new Set(owners.flatMap((task)=>task.depends??[]))].filter((dep)=>!ownerIds.includes(dep)&&!ownerIds.some((owner)=>dependsOnTransitively(base,dep,owner))).sort((a,b)=>a.localeCompare(b)),edits=owners.map((task)=>{let scope=scopes[task.id]??[],removed=scope.filter((entry)=>normalizePath(entry)===file3),rest=scope.filter((entry)=>normalizePath(entry)!==file3),keep=rest.length===0;return{taskId:task.id,remove_files:keep?[]:removed,add_depends:[newId],files_touched:keep?[...scope]:rest,depends:[...task.depends??[],newId]}}),description=`Prepare ${file3} for tasks ${ownerIds.join(", ")}: make every change they need in ${file3} first (extracted shared prerequisite), so they can run in parallel without touching it.`,nextScopes={...scopes,[newId]:[file3]};for(let edit of edits)nextScopes[edit.taskId]=edit.files_touched??[];let phaseTasks=[...withDepends(pendingTasksOf(phase),new Map(edits.map((edit)=>[edit.taskId,edit.depends]))),{id:newId,description,status:"pending",depends:prereqDepends,files_touched:[file3]}],result=whatIf(base,phase,phaseTasks,nextScopes);if(!result)return null;let gain=gainOf(base,result);if(!(gain>0))return null;let edgeShare=totalEdges>0?round3((model.driven.get(file3)??0)/totalEdges):0,isHot=base.hot.has(file3),fileKind=isGlobalFile(file3)?"global-file":isHot?"hot-file":"hub-file",type;if(owners.length>=HUB_MIN_TASKS&&(edgeShare>=HUB_MIN_EDGE_SHARE||gain>=HUB_MIN_DELTA))type="extract-prerequisite";else if(isHot)type="isolate-hot-file";else return null;let verb=type==="extract-prerequisite"?`Extract ${fileKind} ${file3} (declared by ${ownerIds.length} tasks, ${Math.round(edgeShare*100)}% of conflict edges) into prerequisite task ${newId}`:`Isolate hot file ${file3} into its own task ${newId} (so ${ownerIds.join(", ")} stop running alone)`;return{type,phase:phase.id,file:file3,fileKind,taskIds:ownerIds,edgeShare,patch:{newTask:{id:newId,phase:phase.id,description,files_touched:[file3],depends:prereqDepends},edits},deltaEffectiveSpeedup:gain,whatIf:result,summary:`${verb}: ${speedupText(base,result)}.`}}function articulationPoints(graph){let index=new Map,low=new Map,points=new Set,counter=0,visit=(node,parent)=>{index.set(node,counter),low.set(node,counter),counter+=1;let children=0;for(let next of graph.adjacency.get(node)??[])if(!index.has(next)){if(children+=1,visit(next,node),low.set(node,Math.min(low.get(node)??0,low.get(next)??0)),parent!==null&&(low.get(next)??0)>=(index.get(node)??0))points.add(node)}else if(next!==parent)low.set(node,Math.min(low.get(node)??0,index.get(next)??0));if(parent===null&&children>1)points.add(node)},nodes=[...graph.adjacency.keys()].sort((a,b)=>a.localeCompare(b));for(let node of nodes)if(!index.has(node))visit(node,null);return[...points]}function clustersAround(graph,taskId){let seen=new Set([taskId]),clusters=[],neighbours=[...graph.adjacency.get(taskId)??[]].sort((a,b)=>a.localeCompare(b));for(let start of neighbours){if(seen.has(start))continue;let cluster=[],queue=[start];seen.add(start);while(queue.length>0){let node=queue.shift();cluster.push(node);for(let next of graph.adjacency.get(node)??[])if(!seen.has(next))seen.add(next),queue.push(next)}clusters.push(cluster.sort((a,b)=>a.localeCompare(b)))}return clusters}function splitSuggestion(base,model,taskId){let{phase}=model,scopes=base.estimate.scopes,own=scopes[taskId]??[];if(own.length<2)return null;let clusters=clustersAround(model.graph,taskId);if(clusters.length<2)return null;let clusterFiles=clusters.map((cluster)=>cluster.flatMap((id)=>expandEpicScope(scopes[id]??[],base.context.signals.coWrites)));if(!base.meter.charge(own.length*clusterFiles.flat().length+1))return null;let parts=clusters.map(()=>[]),loose=[];for(let entry of own){let file3=normalizePath(entry),at=clusterFiles.findIndex((files)=>files.some((other)=>pathsConflict(file3,other)));if(at===-1)loose.push(entry);else parts[at].push(entry)}let nonEmpty2=parts.filter((part)=>part.length>0);if(nonEmpty2.length<2)return null;nonEmpty2[0].push(...loose);let taken=new Set(base.usedIds),partIds=nonEmpty2.map((_,i)=>i===0?taskId:nextTaskId(phase.id,taken)),ownDepends=[...model.tasks.find((t)=>t.id===taskId)?.depends??[]],newTasks=nonEmpty2.slice(1).map((files,i)=>({id:partIds[i+1],phase:phase.id,description:`Part ${i+2} of task ${taskId}: its work in ${files.join(", ")} (split out so it no longer joins two conflict clusters).`,files_touched:files,depends:ownDepends})),edits=[{taskId,depends:ownDepends,files_touched:nonEmpty2[0]},...(base.dependents.get(taskId)??[]).map((dependent)=>({taskId:dependent,depends:[...base.dependsOf.get(dependent)??[],...partIds.slice(1)]}))],editDepends=new Map(edits.map((edit)=>[edit.taskId,edit.depends])),nextScopes={...scopes};nonEmpty2.forEach((files,i)=>{nextScopes[partIds[i]]=files});let phaseTasks=[...withDepends(pendingTasksOf(phase),editDepends),...newTasks.map((part)=>({id:part.id,description:part.description,status:"pending",depends:part.depends,files_touched:part.files_touched}))],result=whatIf(base,phase,phaseTasks,nextScopes);if(!result)return null;let gain=gainOf(base,result);if(!(gain>0))return null;return{type:"split-task",phase:phase.id,taskId,parts:nonEmpty2,patch:{newTasks,edits},deltaEffectiveSpeedup:gain,whatIf:result,summary:`Split task ${taskId} (it joins ${nonEmpty2.length} conflict clusters) into ${partIds.join(", ")}, one per cluster: ${nonEmpty2.map((files)=>`[${files.join(", ")}]`).join(" / ")}; every task depending on ${taskId} must depend on all parts — ${speedupText(base,result)}.`}}function jaccard2(a,b){let both=0;for(let file3 of a)if(b.has(file3))both+=1;let union3=a.size+b.size-both;return union3===0?0:both/union3}function mergeSuggestion(base,phase,keep,absorb,similarity){let keepDeps=base.dependsOf.get(keep.id)??[],absorbDeps=base.dependsOf.get(absorb.id)??[];if(absorbDeps.some((dep)=>dep!==keep.id&&dependsOnTransitively(base,dep,keep.id))||keepDeps.some((dep)=>dep!==absorb.id&&dependsOnTransitively(base,dep,absorb.id)))return null;let scopes=base.estimate.scopes,files=[],seen=new Set;for(let entry of[...scopes[keep.id]??[],...scopes[absorb.id]??[]]){let key2=normalizePath(entry);if(seen.has(key2))continue;seen.add(key2),files.push(entry)}let depends=[...new Set([...keepDeps,...absorbDeps])].filter((dep)=>dep!==keep.id&&dep!==absorb.id),edits=[{taskId:keep.id,depends,files_touched:files},...(base.dependents.get(absorb.id)??[]).filter((dependent)=>dependent!==keep.id).map((dependent)=>({taskId:dependent,depends:[...new Set((base.dependsOf.get(dependent)??[]).map((dep)=>dep===absorb.id?keep.id:dep))]}))],nextScopes={...scopes,[keep.id]:files};delete nextScopes[absorb.id];let phaseTasks=withDepends(pendingTasksOf(phase).filter((task)=>task.id!==absorb.id),new Map(edits.map((edit)=>[edit.taskId,edit.depends]))),result=whatIf(base,phase,phaseTasks,nextScopes);if(!result)return null;let gain=gainOf(base,result);if(gain<0)return null;return{type:"merge-tasks",phase:phase.id,keep:keep.id,absorb:absorb.id,jaccard:round3(similarity),patch:{removed_task_ids:[absorb.id],removal_reason:`Merged into ${keep.id} (plan shaping: ${Math.round(similarity*100)}% scope overlap).`,edits},deltaEffectiveSpeedup:gain,whatIf:result,summary:`Merge task ${absorb.id} into ${keep.id} (small tasks, ${Math.round(similarity*100)}% scope overlap — they serialize anyway; one task saves a QA cycle): save_plan without ${absorb.id} (removed_task_ids + removal_reason), ${keep.id} with the union scope, dependents re-pointed to ${keep.id} — ${speedupText(base,result)}.`}}function dependencyIndex(phases){let dependsOf=new Map,dependents=new Map;for(let phase of phases)for(let task of phase.tasks??[]){let deps=[...task.depends??[]];dependsOf.set(task.id,deps);for(let dep of deps){let list2=dependents.get(dep);if(list2)list2.push(task.id);else dependents.set(dep,[task.id])}}return{dependsOf,dependents}}var HUB_MIN_TASKS=3,HUB_MIN_EDGE_SHARE=0.25,HUB_MIN_DELTA=0.25,MERGE_MIN_JACCARD=0.8,cmpKey=(p)=>process.platform==="win32"?p.toLowerCase():p;var init_shaping_suggestions=__esm(()=>{init_conflicts();init_components();init_learning();init_shaping_sizing();init_sizing()});function shapeEpicPlan(input){let estimate=estimateEpicScopes(input.phases,input.declared),files=new Set;for(let id of estimate.pendingIds)for(let entry of estimate.scopes[id]??[])files.add(normalizePath(entry));let meter=new EpicWorkMeter(input.maxWork??MAX_SHAPING_WORK),budget={tasks:estimate.pendingIds.length,files:files.size,maxTasks:MAX_SHAPING_TASKS,maxFiles:MAX_SHAPING_FILES,whatIfs:0,work:0,maxWork:meter.max,truncated:!1},skipped=(sizing2)=>({verdict:"skipped-budget",sizing:sizing2,suggestions:[],budget:{...budget,work:meter.spent,truncated:!0}});if(budget.tasks>MAX_SHAPING_TASKS||budget.files>MAX_SHAPING_FILES)return skipped(null);let sizing=input.baseline;if(!sizing)sizing=sizeEpicPlan(input,input.phases,estimate,meter.left),meter.charge(Math.min(sizing.work,meter.left));if(sizing.aborted)return skipped(null);let{dependsOf,dependents}=dependencyIndex(input.phases),usedIds=new Set(dependsOf.keys()),base={context:input,phases:input.phases,estimate,sizing,hot:new Set(input.signals.hotFiles.map(normalizePath)),usedIds,dependsOf,dependents,...input.isDirectory?{isDirectory:input.isDirectory}:{},meter},suggestions=[],unscoped=estimate.pendingIds.filter((id)=>(estimate.scopes[id]??[]).length===0);if(unscoped.length>0){let listed=unscoped.slice(0,MAX_LISTED_TASKS);suggestions.push({type:"declare-scope",taskIds:listed,count:unscoped.length,deltaEffectiveSpeedup:null,whatIf:null,summary:`Give ${unscoped.length} task(s) a scope (files_touched in save_plan): ${listed.join(", ")}${unscoped.length>listed.length?", …":""} — a task without a scope always runs alone.`})}let models=[];for(let phase of input.phases){let model=modelPhase(base,phase);if(model)models.push(model)}let totalEdges=models.reduce((sum,m)=>sum+m.edgeCount,0),attempted=0,allPaths=files,candidates=[];for(let model of models){let fileSet=new Set([...model.driven.keys(),...model.exclusiveCaused.keys(),...[...base.hot].filter((file3)=>model.tasks.some((task)=>(estimate.scopes[task.id]??[]).some((entry)=>normalizePath(entry)===file3)))]);for(let file3 of fileSet){let score=(model.driven.get(file3)??0)+(model.exclusiveCaused.get(file3)??0);if(score>0||base.hot.has(file3))candidates.push({model,file:file3,score})}}candidates.sort((a,b)=>b.score-a.score||a.model.phase.id-b.model.phase.id||a.file.localeCompare(b.file));for(let candidate of candidates.slice(0,MAX_WHAT_IF_FILES)){let owners=candidate.model.tasks.filter((task)=>(estimate.scopes[task.id]??[]).some((entry)=>normalizePath(entry)===candidate.file)),raw=owners.flatMap((task)=>(estimate.scopes[task.id]??[]).filter((entry)=>normalizePath(entry)===candidate.file));if(owners.length>0&&isDirectoryEntry(base,candidate.file,raw,allPaths)){suggestions.push(narrowScopeSuggestion(candidate.model.phase,candidate.file,owners.map((task)=>task.id)));continue}if(meter.left===0)break;attempted+=1;let suggestion=fileSuggestion(base,candidate.model,candidate.file,totalEdges);if(suggestion)suggestions.push(suggestion)}let splits=[];for(let model of models){if(!meter.charge(model.edgeCount+model.tasks.length))break;for(let id of articulationPoints(model.graph)){if(model.tasks.find((t)=>t.id===id)?.status!=="pending")continue;splits.push({model,id,degree:model.graph.adjacency.get(id)?.size??0})}}splits.sort((a,b)=>b.degree-a.degree||a.model.phase.id-b.model.phase.id||a.id.localeCompare(b.id));for(let split of splits.slice(0,MAX_WHAT_IF_SPLITS)){if(meter.left===0)break;attempted+=1;let suggestion=splitSuggestion(base,split.model,split.id);if(suggestion)suggestions.push(suggestion)}let merges=[];for(let model of models){let small=model.tasks.filter((task)=>task.status==="pending"&&(task.size??"small")==="small"&&(estimate.scopes[task.id]??[]).length>0),sets=new Map(small.map((task)=>[task.id,new Set((estimate.scopes[task.id]??[]).map(normalizePath))])),avg=small.reduce((sum,task)=>sum+(sets.get(task.id)?.size??0),0)/Math.max(1,small.length);if(!meter.charge(Math.ceil(small.length*(small.length-1)/2*(avg+1))))break;for(let i=0;i<small.length;i+=1)for(let j=i+1;j<small.length;j+=1){let similarity=jaccard2(sets.get(small[i].id)??new Set,sets.get(small[j].id)??new Set);if(similarity<MERGE_MIN_JACCARD)continue;let[keep,absorb]=(model.graph.topoIndex.get(small[i].id)??0)<=(model.graph.topoIndex.get(small[j].id)??0)?[small[i],small[j]]:[small[j],small[i]];merges.push({model,keep,absorb,similarity})}}merges.sort((a,b)=>b.similarity-a.similarity||a.model.phase.id-b.model.phase.id||a.keep.id.localeCompare(b.keep.id)||a.absorb.id.localeCompare(b.absorb.id));for(let merge3 of merges.slice(0,MAX_WHAT_IF_MERGES)){if(meter.left===0)break;attempted+=1;let suggestion=mergeSuggestion(base,merge3.model.phase,merge3.keep,merge3.absorb,merge3.similarity);if(suggestion)suggestions.push(suggestion)}suggestions.sort((a,b)=>(isScopeAdvice(a)?0:1)-(isScopeAdvice(b)?0:1)||(b.deltaEffectiveSpeedup??0)-(a.deltaEffectiveSpeedup??0)||TYPE_ORDER[a.type]-TYPE_ORDER[b.type]||a.summary.localeCompare(b.summary));let ranked=suggestions.slice(0,MAX_SHAPING_SUGGESTIONS),finalBudget={...budget,whatIfs:attempted,work:meter.spent,truncated:meter.truncated};if(meter.truncated&&ranked.length===0&&!sizing.verdict.epicSized)return{verdict:"skipped-budget",sizing:sizing.verdict,suggestions:[],budget:finalBudget};return{verdict:verdictOf(sizing.verdict,ranked),sizing:sizing.verdict,suggestions:ranked,budget:finalBudget}}function verdictOf(sizing,suggestions){let scopeAdvice=suggestions.some(isScopeAdvice);if(sizing.epicSized)return suggestions.some((s)=>(s.deltaEffectiveSpeedup??0)>=MIN_USEFUL_DELTA)||scopeAdvice?"improvable":"acceptable";if(suggestions.some((s)=>s.whatIf?.epicSized===!0))return"improvable";if(scopeAdvice&&!sizing.reasons.includes("too-few-tasks"))return"improvable";return"not-epic-sized"}function describeEpicShapingSkip(report){let{budget}=report;if(budget.tasks>budget.maxTasks||budget.files>budget.maxFiles)return`Plan shaping skipped: ${budget.tasks} pending task(s) / ${budget.files} scope file(s) exceed the shaping budget (${budget.maxTasks} tasks / ${budget.maxFiles} files).`;if(report.sizing===null)return`Plan shaping skipped: the plan (${budget.tasks} pending task(s), ${budget.files} scope file(s)) is too large or densely coupled to size within the shaping work budget.`;return`Plan shaping skipped: the plan is too densely coupled to evaluate suggestions within the shaping work budget (effective speedup ${report.sizing.effectiveSpeedup.toFixed(2)}×, ${report.sizing.pendingTasks} task(s) in ${report.sizing.serialSteps} serial step(s)${report.sizing.epicSized?"":" — not epic-sized"}).`}function describeEpicShapingReasons(sizing){return sizing.reasons.map((reason)=>describeEpicSizingReason(reason,sizing)).join("; ")}function depList(ids){return`[${ids.join(", ")}]`}function formatEpicShapingLines(report,options={}){if(report.verdict==="skipped-budget")return[describeEpicShapingSkip(report)];let sizing=report.sizing,lines=[`Plan shaping: **${report.verdict}** — ${VERDICT_TEXT[report.verdict]}${sizing?` (effective speedup ${sizing.effectiveSpeedup.toFixed(2)}×, ${sizing.pendingTasks} task(s) in ${sizing.serialSteps} serial step(s))`:""}.`],shown=report.suggestions.slice(0,options.maxSuggestions??MAX_SHAPING_SUGGESTIONS);if(shown.forEach((suggestion,index)=>{lines.push(`${index+1}. [${suggestion.type}] ${suggestion.summary}`);let editText=(edits)=>edits.map((edit)=>`${edit.taskId}: ${edit.files_touched?`files_touched ${depList(edit.files_touched)}, `:""}depends ${depList(edit.depends)}`).join("; ");if(suggestion.type==="extract-prerequisite"||suggestion.type==="isolate-hot-file"){let{newTask,edits}=suggestion.patch;lines.push(` Patch: add task ${newTask.id} to phase ${newTask.phase} (files_touched ${depList(newTask.files_touched)}, depends ${depList(newTask.depends)}); ${editText(edits)}.`)}else if(suggestion.type==="split-task"){let{newTasks,edits}=suggestion.patch;lines.push(` Patch: add ${newTasks.map((t)=>`task ${t.id} (files_touched ${depList(t.files_touched)})`).join(", ")} to phase ${suggestion.phase}; ${editText(edits)}.`)}else if(suggestion.type==="merge-tasks")lines.push(` Patch: removed_task_ids [${suggestion.absorb}] (removal_reason given); ${editText(suggestion.patch.edits)}.`)}),report.suggestions.length>shown.length)lines.push(`(${report.suggestions.length-shown.length} more — \`/swarm coupling --suggest\` lists all.)`);return lines}var MAX_SHAPING_TASKS=200,MAX_SHAPING_FILES=500,MAX_WHAT_IF_FILES=10,MAX_WHAT_IF_SPLITS=3,MAX_WHAT_IF_MERGES=3,MAX_SHAPING_WORK=6000000,MAX_SHAPING_SUGGESTIONS=5,MIN_USEFUL_DELTA=0.05,MAX_LISTED_TASKS=20,TYPE_ORDER,isScopeAdvice=(s)=>s.type==="declare-scope"||s.type==="narrow-scope",VERDICT_TEXT;var init_shaping=__esm(()=>{init_conflicts();init_shaping_sizing();init_shaping_suggestions();init_sizing();TYPE_ORDER={"declare-scope":0,"narrow-scope":1,"extract-prerequisite":2,"isolate-hot-file":3,"split-task":4,"merge-tasks":5};VERDICT_TEXT={acceptable:"epic-sized, nothing worth reshaping",improvable:"the suggestions below would help","not-epic-sized":"not epic-sized, and no suggestion makes it epic-sized — run it in Balanced","skipped-budget":"skipped (budget)"}});import*as fs103 from"node:fs";import*as path187 from"node:path";function parseArgs3(args2){let parsed={threshold:DEFAULT_THRESHOLD,minCoChanges:DEFAULT_MIN_CO_CHANGES2,format:"markdown",persist:!1,suggest:!1};for(let i=0;i<args2.length;i++){let flag=args2[i],next=args2[i+1];switch(flag){case"--phase":{if(!next)return parsed.parseError="--phase requires a numeric argument",parsed;if(!/^\d+$/.test(next))return parsed.parseError=`--phase must be a positive integer (got '${next}')`,parsed;let v=Number.parseInt(next,10);if(v<1)return parsed.parseError=`--phase must be a positive integer (got '${next}')`,parsed;parsed.phase=v,i+=1;break}case"--threshold":{if(!next)return parsed.parseError="--threshold requires a numeric argument",parsed;let v=Number.parseFloat(next);if(Number.isNaN(v)||v<-1||v>1)return parsed.parseError=`--threshold must be a number in [-1, 1] (got '${next}')`,parsed;parsed.threshold=v,i+=1;break}case"--min-co-changes":{if(!next)return parsed.parseError="--min-co-changes requires a numeric argument",parsed;if(!/^\d+$/.test(next))return parsed.parseError=`--min-co-changes must be a positive integer (got '${next}')`,parsed;let v=Number.parseInt(next,10);if(v<1)return parsed.parseError=`--min-co-changes must be a positive integer (got '${next}')`,parsed;parsed.minCoChanges=v,i+=1;break}case"--format":{if(!next||next!=="markdown"&&next!=="json")return parsed.parseError=`--format must be 'markdown' or 'json' (got '${next??"<missing>"}')`,parsed;parsed.format=next,i+=1;break}case"--persist":parsed.persist=!0;break;case"--suggest":parsed.suggest=!0;break;default:return parsed.parseError=`unknown argument: ${flag}`,parsed}}return parsed}function persistReportJson(directory,report){let epicDir=path187.join(directory,".swarm","epic");fs103.mkdirSync(epicDir,{recursive:!0});let filePath=path187.join(epicDir,"coupling-report.json");return atomicWriteSwarmFileSync(filePath,`${JSON.stringify(report,null,2)}
|
|
2386
2386
|
`),filePath}async function handleCouplingCommand(directory,args2){let parsed=parseArgs3(args2);if(parsed.parseError)return`Error: ${parsed.parseError}
|
|
2387
2387
|
|
|
2388
2388
|
Usage: /swarm coupling [--phase <n>] [--threshold <-1..1>] [--min-co-changes <n>] [--format markdown|json] [--persist] [--suggest]`;let plan=await _internals158.loadPlanJsonOnly(directory);if(plan===null)return"No plan found at `.swarm/plan.json`. Run `/swarm plan` to create one before measuring coupling.";let rawTasks=[];if(parsed.phase!==void 0){let phase=plan.phases.find((p)=>p.id===parsed.phase);if(!phase){let available=plan.phases.map((p)=>p.id).join(", ")||"(none)";return`Phase ${parsed.phase} not found. Available phases: ${available}`}rawTasks=phase.tasks}else for(let phase of plan.phases)for(let task of phase.tasks)rawTasks.push(task);let declaredScopes=resolveEpicDeclaredScopes(directory,plan,rawTasks.map((task)=>task.id)),tasks=rawTasks.map((task)=>{let scopeFiles=declaredScopes[task.id]??[],scope=scopeFiles.length>0?scopeFiles:task.files_touched??[];return{id:task.id,scope}}),cochangeEnabled=!1,config3=null;try{config3=_internals158.loadPluginConfigWithMeta(directory).config,cochangeEnabled=isEpicCochangeConfigEnabled(config3)}catch{cochangeEnabled=!1}let cochangeSignal=cochangeEnabled?"enabled":"disabled-by-config",cochangePairs=cochangeEnabled?await _internals158.getCoChangePairs(directory):[],report=computeCouplingReport(tasks,cochangePairs,{npmi:parsed.threshold,minCoChanges:parsed.minCoChanges}),persistStatus={requested:!1};if(parsed.persist)try{let writtenAt=persistReportJson(directory,report);persistStatus={requested:!0,written:!0,path:path187.relative(directory,writtenAt).replace(/\\/g,"/")}}catch(err){persistStatus={requested:!0,written:!1,error:err instanceof Error?err.message:String(err)}}let shaping=parsed.suggest?await shapeCurrentPlan(directory,plan,config3??{}):null;if(parsed.format==="json")return JSON.stringify({...report,cochangeSignal,persist:persistStatus,...shaping?{shaping}:{}},null,2);let persistTrailer="";if(persistStatus.requested&&persistStatus.written)persistTrailer=`
|
|
@@ -4123,7 +4123,8 @@ Actionability (direct text only; required unless knowledge.promotion_require_act
|
|
|
4123
4123
|
`)}return["Usage:"," /swarm qa-gates show current profile + effective gates"," /swarm qa-gates enable <gate>... persist-enable gate(s) (rejected if locked)"," /swarm qa-gates override <gate>... session-only enable (ratchet-tighter)",`Valid gates: ${ALL_GATE_NAMES.join(", ")}`].join(`
|
|
4124
4124
|
`)}var ALL_GATE_NAMES;var init_qa_gates=__esm(()=>{init_qa_gate_profile();init_qa_gate_session_override();init_manager();init_utils3();init_state();ALL_GATE_NAMES=["reviewer","test_engineer","council_mode","sme_enabled","critic_pre_plan","hallucination_guard","sast_enabled","mutation_test","phase_council","drift_check","final_council"]});import*as fs150 from"node:fs";function scanTaskDispatchHistory(directory,taskId){try{let eventsPath=coreEventsFilePath(directory);if(!fs150.existsSync(eventsPath))return"absent";if(fs150.statSync(eventsPath).size>DISPATCH_HISTORY_SCAN_MAX_BYTES)return"unknown";let content=fs150.readFileSync(eventsPath,"utf-8");for(let line of content.split(`
|
|
4125
4125
|
`)){if(!line.includes("coder_settlement"))continue;try{let record3=JSON.parse(line);if(record3.type==="coder_settlement"&&record3.taskId===taskId)return"present"}catch{}}return"absent"}catch{return"unknown"}}function inspectTaskEvidenceState(directory,taskId){try{return readTaskEvidenceRaw(directory,taskId)?"present":"absent"}catch{return"corrupt"}}function renderOutcome(outcome){switch(outcome.outcome){case"recovered":return`✅ Task ${outcome.taskId}: settlement recovered (${outcome.accepted?"changes attributed":"no workspace change to attribute"}${outcome.forced?", in-process ownership released by --force":""})`;case"already_terminal":return`⏭️ Task ${outcome.taskId}: settlement already ${outcome.state} (nothing to recover)`;case"owned_in_process":return`ℹ️ Task ${outcome.taskId}: dispatch ${sanitizeDiagnosticText(outcome.transitionId)} is still registered as in flight in this process. If no coder is genuinely running, re-run with --force to release it.`;case"owned_by_live_foreign_pid":return`ℹ️ Task ${outcome.taskId}: owned by live process pid ${outcome.processId} (another OpenCode instance). Close that instance or run /swarm recover there; this command never interrupts another live process's dispatch.`;case"unreadable_wal":return`⚠️ Task ${outcome.taskId}: settlement WAL is unreadable (corrupt) — this command refuses corrupt WALs; inspect .swarm/coder-settlements/${outcome.taskId}.json and consult docs/troubleshooting/recovery-runbook.md; do not delete or hand-edit the file`;case"error":return`❌ Task ${outcome.taskId}: recovery failed — ${sanitizeDiagnosticText(outcome.message,512)}`;default:return`❌ Task ${outcome.taskId}: unknown outcome`}}function renderStageARepairOutcome(outcome){switch(outcome.outcome){case"repaired":return`✅ Task ${outcome.taskId}: Stage A repaired — stage_a_passed written at generation ${outcome.generation} without re-running the coder`;case"skipped_not_wedged":if(outcome.state==="rework_required")return`⏭️ Task ${outcome.taskId}: workflow state is rework_required — not a coder_delegated Stage A wedge, nothing to repair here. If the Stage B verdict did not require a code change, have the architect run the recover_rework_task tool for this task; otherwise delegate the coder to repair first.`;if(outcome.state==="idle"||outcome.state==="blocked")return`⏭️ Task ${outcome.taskId}: workflow state is ${outcome.state} — no Stage A repair is needed or provable here (a mechanical repair requires a COMMITTED accepted coder settlement AND green post-settlement pre-check evidence AND no Stage A proof already recorded). When Stage A is already recorded the task needs nothing; when the receipts exist but the mechanical envelope excludes them, the architect can run the audited recover_stage_a_task tool. --force does not override Stage A wedge-classification refusals.`;return`⏭️ Task ${outcome.taskId}: workflow state is ${outcome.state} with pre_check proof present or not settled — nothing to repair`;case"skipped_not_green":return`⏭️ Task ${outcome.taskId}: no green post-settlement pre-check evidence (${outcome.reason==="no_pre_check_bundles"?"missing or non-green secretscan/SAST bundle — run pre_check_batch first":"latest pre-check run failed or predates the settlement"}) — refusing to mark Stage A passed without proof`;case"error":return`❌ Task ${outcome.taskId}: Stage A repair failed — ${sanitizeDiagnosticText(outcome.message,512)}`;default:return`❌ Task ${outcome.taskId}: unknown repair outcome`}}async function handleRecoverCommand(directory,args2,sessionID){let force=args2.includes("--force");if(args2.includes("--coordination"))try{return await retrySnapshotCoordinationInitialization(directory),["## SQLite Coordination Recovery","","✅ Coordination initialization/import completed successfully."].join(`
|
|
4126
|
-
`)}catch(err){
|
|
4126
|
+
`)}catch(err){let message=err instanceof Error?err.message:String(err),lines=["## SQLite Coordination Recovery","",`❌ Recovery refused or failed: ${sanitizeDiagnosticText(message,512)}`];if(message.includes("still settling")||message.includes("still unsettled")){if(lines.push("If an earlier attempt timed out, wait for that underlying attempt to settle before retrying; it is never abandoned or run concurrently."),message.includes("guard stranded"))lines.push("Once it settles: re-run /swarm reset-session to completion, or restart the host.")}else if(message.includes("in-flight /swarm reset-session"))lines.push("A /swarm reset-session is in progress; wait for it to complete and retry.");else if(message.includes("host shutdown"))lines.push("Coordination is closing for host shutdown; restart the host.");else if(message.includes("closing for reset-session"))return["## SQLite Coordination Recovery","","❌ Recovery refused: coordination is closing for a partially-failed /swarm reset-session (settled).","Durable session-snapshot persistence is stopped for this project until the guard clears.","Recovery: re-run /swarm reset-session to completion, or restart the host."].join(`
|
|
4127
|
+
`);else lines.push("Fix the reported cause (or restart the host) and re-run /swarm recover --coordination.");return lines.join(`
|
|
4127
4128
|
`)}let positional=args2.filter((arg)=>!arg.startsWith("--")),taskId=positional[0];if(positional.length>1)return["## Coder Settlement Recovery","",`❌ Unexpected arguments: ${positional.join(" ")}`,"Usage: /swarm recover [task_id] [--force]"].join(`
|
|
4128
4129
|
`);let{states:listed,truncated:listTruncated}=await listCoderSettlementWalStates(directory),report=["## Coder Settlement Recovery",""],hasKnownWal=listed.length>0&&(!taskId||listed.some((entry)=>entry.taskId===taskId));if(listed.length===0||taskId&&!hasKnownWal)if(taskId){let dispatchHistory=scanTaskDispatchHistory(directory,taskId),evidenceState=inspectTaskEvidenceState(directory,taskId);if(dispatchHistory==="present")report.push(`⚠️ No settlement WAL for task ${taskId}, but coder-settlement lifecycle events exist for it in the core event log — this looks like a partial cleanup or a background dispatch (WALs are optional for background dispatches). Nothing to recover here; see docs/troubleshooting/recovery-runbook.md.`);else if(evidenceState==="corrupt")report.push(`⚠️ No settlement WAL for task ${taskId} and its task-evidence file is unreadable (corrupt) — inspect .swarm/evidence/${taskId}.json; this command refuses corrupt evidence. See docs/troubleshooting/recovery-runbook.md.`);else if(dispatchHistory==="unknown")report.push(`⚠️ No settlement WAL for task ${taskId}, and its dispatch history could not be established (the core event log is missing, oversized, or unreadable). Task-evidence state: ${evidenceState}.`,"","Inspect the core event log before assuming the task was never dispatched. If the task declares external_git evidence, `/swarm attest "+taskId+"` remains available; otherwise re-plan it as a thin coder dispatch so a settlement exists.");else if(dispatchHistory==="absent"&&evidenceState==="absent")report.push(`❌ No coder dispatch or settlement evidence was found for task ${taskId} (no settlement WAL, no exact-task workflow evidence file, no coder_settlement events).`,"","This is the git-external-deliverable shape (issue #3422): if the work was commit/push/gh ops done outside a coder lane, there is nothing to recover — the coder-mutation gate cannot be satisfied by recovery. Options:","1. If the task declares evidence_class external_git (or you can re-plan it to): run `/swarm attest "+taskId+"` to verify the deliverable with its pinned anchors and admit completion.","2. manual close — flip the task status in the TUI and record the wedge plus the close reason in your execution trace.","3. Re-plan the task as a thin coder dispatch (the coder executes the pinned-scope git commands) so a settlement exists and the normal gate applies.");else report.push(`❌ No settlement WAL for task ${taskId}. Task-evidence exists (${evidenceState}) but no coder dispatch ran for this task, so in-machine settlement recovery does not apply.`,"","Next steps: run `/swarm attest "+taskId+"` if the task declares external_git evidence (or re-plan it to), or re-plan it as a thin coder dispatch so a settlement exists.");if(listed.length>0)report.push(`Known tasks: ${listed.map((entry)=>entry.taskId).join(", ")}`);if(listTruncated)report.push("⚠️ The settlement-WAL listing hit the recovery scan cap (200) — the absence above is only established for the listed tasks.")}else report.push("No coder settlement WALs found in .swarm/coder-settlements/ — nothing to recover.");else{let{results,truncated:recoverTruncated}=await recoverStaleCoderSettlements(directory,{...taskId?{taskIds:[taskId]}:{},force}),lines=results.map((outcome)=>renderOutcome(outcome)),recoveredCount=results.filter((r)=>r.outcome==="recovered").length,blockedCount=results.filter((r)=>r.outcome==="owned_in_process"||r.outcome==="owned_by_live_foreign_pid").length;if(report.push(...lines,"",`Recovered ${recoveredCount} settlement(s)${blockedCount>0?`; ${blockedCount} still owned by a live dispatch (see above for the exact remediation)`:""}.`),listTruncated||recoverTruncated)report.push("","⚠️ More settlement WALs exist than the recovery scan cap (200) — older settlements were NOT listed or processed. Re-run after the tasks above are settled to reach the rest.");if(force&&recoveredCount>0)report.push("","⚠️ --force released in-process ownership before recovery. If any of these dispatches was genuinely still running, its completion will report CODER_SETTLEMENT_IDEMPOTENCY_CONFLICT — that error is expected and safe to ignore; the settlement is already durably recovered.")}try{let{results:repairResults,truncated:repairTruncated}=await repairWedgedStageA(directory,{...taskId?{taskIds:[taskId]}:{},...sessionID?{sessionId:sessionID}:{}}),repaired=repairResults.filter((r)=>r.outcome==="repaired");if(repairResults.length>0){if(report.push("","## Wedged Stage A Repair","",...repairResults.map(renderStageARepairOutcome),"",repaired.length===0?"No wedged tasks repaired.":`Repaired ${repaired.length} wedged task(s); reviewer/test_engineer dispatch is now permitted for them.`),repairTruncated)report.push("","⚠️ More evidence files exist than the repair scan cap (200) — re-run after the tasks above are processed to reach the rest.")}}catch(err){report.push("",`⚠️ Wedged Stage A repair failed (settlement recovery above is unaffected): ${sanitizeDiagnosticText(err instanceof Error?err.message:String(err),512)}`)}return report.push("",renderRecoveryInvocationQuickForms()),report.join(`
|
|
4129
4130
|
`)}var DISPATCH_HISTORY_SCAN_MAX_BYTES=8388608;var init_recover=__esm(()=>{init_core_events();init_gate_evidence();init_path_identity();init_snapshot_coordination_init();init_coder_settlement();init_recovery_invocation();init_stage_a_repair()});class CircuitBreaker{state="closed";failureCount=0;successCount=0;lastFailureTime;config;name;onStateChange;constructor(name,config3,onStateChange){this.name=name,this.config={failureThreshold:config3?.failureThreshold??5,resetTimeoutMs:config3?.resetTimeoutMs??30000,successThreshold:config3?.successThreshold??3,callTimeoutMs:config3?.callTimeoutMs??1e4},this.onStateChange=onStateChange}getState(){if(this.state==="open"&&this.lastFailureTime){if(Date.now()-this.lastFailureTime>=this.config.resetTimeoutMs)this.transitionTo("half-open")}return this.state}async execute(fn2){if(this.getState()==="open")throw Error(`Circuit breaker '${this.name}' is open`);let startTime=Date.now();try{let result=await this.executeWithTimeout(fn2),duration5=Date.now()-startTime;return this.recordSuccess(duration5),result}catch(error93){let duration5=Date.now()-startTime;throw this.recordFailure(error93,duration5),error93}}async executeWithTimeout(fn2){if(this.config.callTimeoutMs<=0)return fn2();return new Promise((resolve104,reject2)=>{let timeout=setTimeout(()=>{reject2(Error(`Call timeout after ${this.config.callTimeoutMs}ms`))},this.config.callTimeoutMs);fn2().then((result)=>{clearTimeout(timeout),resolve104(result)}).catch((error93)=>{clearTimeout(timeout),reject2(error93)})})}recordSuccess(duration5){if(this.failureCount=0,this.state==="half-open"){if(this.successCount++,this.successCount>=this.config.successThreshold)this.transitionTo("closed")}this.onStateChange?.("callSuccess",{duration:duration5})}recordFailure(error93,duration5){if(this.failureCount++,this.lastFailureTime=Date.now(),this.state==="half-open")this.transitionTo("open");else if(this.state==="closed"&&this.failureCount>=this.config.failureThreshold)this.transitionTo("open");this.onStateChange?.("callFailure",{error:error93,duration:duration5})}transitionTo(newState2){let oldState=this.state;if(this.state=newState2,newState2==="closed")this.failureCount=0,this.successCount=0,this.onStateChange?.("closed",{timestamp:Date.now(),successCount:0,oldState});else if(newState2==="open")this.successCount=0,this.onStateChange?.("opened",{timestamp:Date.now(),failureCount:this.failureCount,oldState});else if(newState2==="half-open")this.successCount=0,this.onStateChange?.("half-open",{timestamp:Date.now(),oldState})}reset(){this.transitionTo("closed")}getStats(){return{state:this.getState(),failureCount:this.failureCount,successCount:this.successCount,lastFailureTime:this.lastFailureTime}}}class LoopProtection{records=new Map;config;onLoopDetected;constructor(config3,onLoopDetected){this.config=config3,this.onLoopDetected=onLoopDetected}recordAttempt(key2){let operationKey=key2??this.config.operationKey,now2=Date.now(),record3=this.records.get(operationKey);if(record3&&now2-record3.firstAttempt>this.config.timeWindowMs)record3=void 0;if(!record3)return this.records.set(operationKey,{count:1,firstAttempt:now2,lastAttempt:now2}),!0;if(record3.count++,record3.lastAttempt=now2,record3.count>this.config.maxIterations)return this.onLoopDetected?.(operationKey,record3.count),!1;return!0}canProceed(key2){let operationKey=key2??this.config.operationKey,record3=this.records.get(operationKey);if(!record3)return!0;if(Date.now()-record3.firstAttempt>this.config.timeWindowMs)return!0;return record3.count<=this.config.maxIterations}getRemainingIterations(key2){let operationKey=key2??this.config.operationKey,record3=this.records.get(operationKey);if(!record3)return this.config.maxIterations;if(Date.now()-record3.firstAttempt>this.config.timeWindowMs)return this.config.maxIterations;return Math.max(0,this.config.maxIterations-record3.count)}reset(key2){let operationKey=key2??this.config.operationKey;this.records.delete(operationKey)}resetAll(){this.records.clear()}getIterationCount(key2){let operationKey=key2??this.config.operationKey,record3=this.records.get(operationKey);if(!record3)return 0;if(Date.now()-record3.firstAttempt>this.config.timeWindowMs)return 0;return record3.count}getTrackedOperations(){return Array.from(this.records.keys())}}function comparePriority(a,b){let priorityOrder={critical:0,high:1,normal:2,low:3},priorityDiff=priorityOrder[a.priority]-priorityOrder[b.priority];if(priorityDiff!==0)return priorityDiff;return a.createdAt-b.createdAt}class AutomationQueue{items=[];inflight=new Map;terminalIds=new Map;maxSize;defaultMaxRetries;defaultBackoffMs;maxBackoffMs;eventBus;overflowStrategy;itemCounter=0;constructor(config3){this.maxSize=config3?.maxSize??1000,this.defaultMaxRetries=config3?.defaultMaxRetries??3,this.defaultBackoffMs=config3?.defaultBackoffMs??1000,this.maxBackoffMs=config3?.maxBackoffMs??60000,this.overflowStrategy=config3?.overflowStrategy??"throw",this.eventBus=getGlobalEventBus()}generateId(){return`queue-${Date.now()}-${++this.itemCounter}`}enqueue(payload,priority="normal",metadata){if(this.items.length>=this.maxSize)if(this.overflowStrategy==="evict-oldest"){let oldestIdx=0;for(let i=1;i<this.items.length;i++)if(this.items[i].createdAt<this.items[oldestIdx].createdAt)oldestIdx=i;let[evicted]=this.items.splice(oldestIdx,1);if(evicted)this.eventBus.publish("queue.item.evicted",{itemId:evicted.id})}else throw Error(`Queue is full (max ${this.maxSize} items)`);let item={id:this.generateId(),priority,payload,createdAt:Date.now(),metadata,retry:{attempts:0,maxAttempts:this.defaultMaxRetries,backoffMs:this.defaultBackoffMs,maxBackoffMs:this.maxBackoffMs}};return this.items.push(item),this.items.sort(comparePriority),this.eventBus.publish("queue.item.enqueued",{itemId:item.id,priority}),item.id}dequeue(){if(this.inflight.size>=this.maxSize)return;let now2=Date.now(),index=this.items.findIndex((item2)=>item2.retry?.nextAttemptAt===void 0||item2.retry.nextAttemptAt<=now2);if(index===-1)return;let[item]=this.items.splice(index,1);if(!item)return;return this.inflight.set(item.id,item),this.eventBus.publish("queue.item.dequeued",{itemId:item.id}),item}peek(){return this.items[0]}get(id){return this.items.find((item)=>item.id===id)??this.inflight.get(id)}inflightSize(){return this.inflight.size}removeQueuedOrInflight(id){let queuedIndex=this.items.findIndex((item)=>item.id===id);if(queuedIndex!==-1){let[removed]=this.items.splice(queuedIndex,1);return removed}let inflightItem=this.inflight.get(id);if(inflightItem)this.inflight.delete(id);return inflightItem}markTerminal(id,at){if(this.terminalIds.set(id,at),this.terminalIds.size>MAX_TERMINAL_IDS){let oldest=this.terminalIds.keys().next().value;if(oldest!==void 0)this.terminalIds.delete(oldest)}}remove(id){if(this.terminalIds.has(id))return!1;return this.removeQueuedOrInflight(id)!==void 0}complete(id){if(this.terminalIds.has(id))return!1;if(!this.removeQueuedOrInflight(id))return!1;return this.markTerminal(id,Date.now()),this.eventBus.publish("queue.item.completed",{itemId:id}),!0}retry(id,_error){if(this.terminalIds.has(id))return!1;let item=this.get(id);if(!item||!item.retry)return!1;if(item.retry.attempts++,item.retry.lastAttempt=Date.now(),item.retry.attempts>=item.retry.maxAttempts)return this.removeQueuedOrInflight(id),this.markTerminal(id,Date.now()),this.eventBus.publish("queue.item.failed",{itemId:id,attempts:item.retry.attempts}),!1;let backoff=Math.min(item.retry.backoffMs*2**(item.retry.attempts-1),item.retry.maxBackoffMs);if(item.retry.nextAttemptAt=Date.now()+backoff,this.inflight.delete(id),!this.items.some((queued)=>queued.id===id))this.items.push(item),this.items.sort(comparePriority);return this.eventBus.publish("queue.item.retry scheduled",{itemId:id,attempt:item.retry.attempts,nextAttemptAt:item.retry.nextAttemptAt,backoffMs:backoff}),!0}getRetryableItems(){let now2=Date.now();return this.items.filter((item)=>item.retry?.nextAttemptAt&&item.retry.nextAttemptAt<=now2)}size(){return this.items.length}isEmpty(){return this.items.length===0}isFull(){return this.items.length>=this.maxSize}clear(){for(let item of this.items)this.eventBus.publish("queue.item.evicted",{itemId:item.id});this.items=[];for(let item of this.inflight.values())this.eventBus.publish("queue.item.evicted",{itemId:item.id});this.inflight.clear()}getAll(){return[...this.items]}getByPriority(priority){return this.items.filter((item)=>item.priority===priority)}getStats(){return{size:this.items.length,maxSize:this.maxSize,byPriority:{critical:this.items.filter((i)=>i.priority==="critical").length,high:this.items.filter((i)=>i.priority==="high").length,normal:this.items.filter((i)=>i.priority==="normal").length,low:this.items.filter((i)=>i.priority==="low").length},retryable:this.getRetryableItems().length,inflight:this.inflight.size}}}var MAX_TERMINAL_IDS=2048;var init_queue=__esm(()=>{init_event_bus()});function sleep4(ms2){return new Promise((resolve104)=>setTimeout(resolve104,ms2))}class WorkerManager{workers=new Map;eventBus;constructor(){this.eventBus=getGlobalEventBus()}register(registration){if(this.workers.has(registration.name))throw Error(`Worker '${registration.name}' is already registered`);let worker={name:registration.name,handler:registration.handler,queue:registration.queue,concurrency:registration.concurrency??1,status:"idle",activeCount:0,processedCount:0,errorCount:0};if(this.workers.set(registration.name,worker),this.eventBus.publish("worker.started",{workerName:registration.name,concurrency:worker.concurrency}),registration.autoStart)this.start(registration.name)}unregister(name){let worker=this.workers.get(name);if(!worker)return!1;if(worker.status==="running")this.stop(name);return this.workers.delete(name),!0}start(name){let worker=this.workers.get(name);if(!worker)throw Error(`Worker '${name}' is not registered`);if(worker.status==="running")return!1;return worker.status="running",this.startProcessingLoop(worker),this.eventBus.publish("worker.started",{workerName:name,concurrency:worker.concurrency}),!0}startProcessingLoop(worker){(async()=>{while(worker.status==="running"){if(worker.activeCount>=worker.concurrency){await sleep4(50);continue}let item=worker.queue.dequeue();if(!item){await sleep4(100);continue}worker.activeCount++,this.handleItem(worker,item).finally(()=>{worker.activeCount--})}})().catch((error93)=>{this.eventBus.publish("worker.error",{workerName:worker.name,itemId:"loop",error:error93})})}async handleItem(worker,item){try{let result=await worker.handler(item);if(result.success)worker.processedCount++,worker.queue.complete(item.id);else worker.errorCount++,worker.lastError=result.error,worker.queue.retry(item.id,result.error)}catch(error93){worker.errorCount++,worker.lastError=error93,this.eventBus.publish("worker.error",{workerName:worker.name,itemId:item.id,error:error93}),worker.queue.retry(item.id,error93)}}stop(name){let worker=this.workers.get(name);if(!worker)return!1;if(worker.status!=="running")return!1;return worker.status="stopping",this.eventBus.publish("worker.stopped",{workerName:name,processedCount:worker.processedCount,errorCount:worker.errorCount}),worker.status="stopped",!0}startAll(){for(let[name,worker]of this.workers)if(worker.status==="idle"||worker.status==="stopped")this.start(name)}stopAll(){for(let name of this.workers.keys())this.stop(name)}getStatus(name){return this.workers.get(name)?.status}getStats(name){let worker=this.workers.get(name);if(!worker)return;return{status:worker.status,activeCount:worker.activeCount,processedCount:worker.processedCount,errorCount:worker.errorCount,lastError:worker.lastError,queueSize:worker.queue.size(),queueInflight:worker.queue.inflightSize()}}getWorkerNames(){return Array.from(this.workers.keys())}isAnyRunning(){for(let worker of this.workers.values())if(worker.status==="running")return!0;return!1}getTotalStats(){let stats2={};for(let name of this.workers.keys())stats2[name]=this.getStats(name);return stats2}}var init_worker=__esm(()=>{init_event_bus()});class BackgroundAutomationManager{config;eventBus;workerManager;queues=new Map;circuitBreakers=new Map;loopProtections=new Map;isInitialized=!1;isRunning=!1;constructor(config3){this.config={enabled:config3.enabled,maxQueueSize:config3.maxQueueSize??1000,maxRetries:config3.maxRetries??3,circuitBreaker:config3.circuitBreaker,loopProtection:config3.loopProtection},this.eventBus=getGlobalEventBus(),this.workerManager=new WorkerManager}initialize(){if(!this.config.enabled){log("[Automation] Framework disabled, skipping initialization");return}if(this.isInitialized){log("[Automation] Already initialized");return}log("[Automation] Initializing framework..."),this.isInitialized=!0,this.eventBus.publish("automation.started",{config:this.config})}start(){if(!this.config.enabled||!this.isInitialized)return;if(this.isRunning)return;log("[Automation] Starting framework..."),this.isRunning=!0,this.eventBus.publish("automation.started",{timestamp:Date.now()})}stop(){if(!this.isRunning)return;log("[Automation] Stopping framework..."),this.workerManager.stopAll(),this.isRunning=!1,this.eventBus.publish("automation.stopped",{timestamp:Date.now()})}isEnabled(){return this.config.enabled}isActive(){return this.isRunning}getOrCreateQueue(name){if(!this.queues.has(name)){let queue=new AutomationQueue({maxSize:this.config.maxQueueSize,defaultMaxRetries:this.config.maxRetries});this.queues.set(name,queue)}return this.queues.get(name)}registerWorker(registration){if(!this.config.enabled)throw Error("Cannot register worker: automation framework is disabled");this.workerManager.register(registration)}startWorker(name){if(!this.config.enabled)return!1;return this.workerManager.start(name)}stopWorker(name){if(!this.config.enabled)return!1;return this.workerManager.stop(name)}getOrCreateCircuitBreaker(name){if(!this.circuitBreakers.has(name)){let cb=new CircuitBreaker(name,this.config.circuitBreaker,(eventType,event)=>{log(`[CircuitBreaker] ${name}: ${eventType}`,event),this.eventBus.publish("circuit.breaker.opened",{breakerName:name,eventType,event})});this.circuitBreakers.set(name,cb)}return this.circuitBreakers.get(name)}getOrCreateLoopProtection(operationKey){if(!this.loopProtections.has(operationKey)){let config3={maxIterations:this.config.loopProtection?.maxIterations??10,timeWindowMs:this.config.loopProtection?.timeWindowMs??60000,operationKey},lp=new LoopProtection(config3,(key2,count4)=>{log(`[LoopProtection] ${key2}: Detected potential loop (${count4} iterations)`),this.eventBus.publish("loop.protection.triggered",{operationKey:key2,count:count4,timestamp:Date.now()})});this.loopProtections.set(operationKey,lp)}return this.loopProtections.get(operationKey)}subscribe(type,listener){return this.eventBus.subscribe(type,listener)}async publish(type,payload,source){await this.eventBus.publish(type,payload,source)}getStats(){return{enabled:this.config.enabled,initialized:this.isInitialized,running:this.isRunning,queues:Object.fromEntries(Array.from(this.queues.entries()).map(([name,queue])=>[name,queue.getStats()])),workers:this.workerManager.getTotalStats(),circuitBreakers:Object.fromEntries(Array.from(this.circuitBreakers.entries()).map(([name,cb])=>[name,cb.getStats()])),loopProtections:Array.from(this.loopProtections.keys())}}reset(){this.stop(),this.workerManager.stopAll(),this.queues.clear(),this.circuitBreakers.clear(),this.loopProtections.clear(),this.isInitialized=!1}}function createAutomationManager(automationConfig){let config3={enabled:automationConfig?.mode!=="manual",maxQueueSize:500,maxRetries:3,circuitBreaker:{failureThreshold:5,resetTimeoutMs:30000,successThreshold:2,callTimeoutMs:15000},loopProtection:{maxIterations:10,timeWindowMs:60000}},manager=new BackgroundAutomationManager(config3);return manager.initialize(),manager}function resetAutomationManager(){if(managerInstance)managerInstance.reset(),managerInstance=null}var managerInstance=null;var init_manager4=__esm(()=>{init_utils();init_event_bus();init_queue();init_worker()});import*as fs151 from"node:fs";import*as path265 from"node:path";async function handleResetCommand(directory,args2){if(!args2.includes("--confirm"))return["## Swarm Reset","","⚠️ This will delete all swarm state from .swarm/ (plan, context, checkpoints, SWARM_PLAN artifacts including .swarm/plan-export/)","","A timestamped backup of the deleted state is saved to `.swarm/reset-backups/` automatically (restore by copying files back). Run `/swarm export` first if you also want a portable JSON snapshot.","","To confirm, run: `/swarm reset --confirm`"].join(`
|
|
@@ -4138,8 +4139,8 @@ Actionability (direct text only; required unless knowledge.promotion_require_act
|
|
|
4138
4139
|
`,"utf-8"),invalidateCachedArtifact(filePath)}catch{}}function deriveAction(tool3){let toolLower=normalizeToolNameLowerCase(tool3??"");if(isTaskToolId(tool3))return"delegate";if(["write","edit","apply_patch","swarm_apply_patch"].includes(toolLower))return"edit";if(["read","glob","grep","search"].includes(toolLower))return"read";if(["bash","shell"].includes(toolLower))return"execute";if(toolLower==="test_runner")return"test";return"tool_use"}function fnv1aHex(text){let hash5=2166136261;for(let i=0;i<text.length;i++)hash5^=text.charCodeAt(i),hash5=Math.imul(hash5,16777619)>>>0;return hash5.toString(16).padStart(8,"0")}function redactCommandSecrets(text){let redacted=redactSecrets(text).replace(URL_CREDENTIALS_PATTERN,"$1[REDACTED:url_credentials]@"),beginMarker=redacted.search(/-----BEGIN [A-Z ]*PRIVATE KEY-----/);return beginMarker===-1?redacted:`${redacted.slice(0,beginMarker)}[REDACTED:private_key_block]`}function normalizeCommandTarget(command){let normalized=command.trim().replace(/\s+/g," "),bounded=normalized.length>MAX_COMMAND_TARGET_LENGTH?`${normalized.slice(0,MAX_COMMAND_TARGET_LENGTH-3)}...`:normalized,redacted=redactCommandSecrets(bounded);if(redacted===bounded)return redacted;let prefix=`#${fnv1aHex(bounded)} `,room=MAX_COMMAND_TARGET_LENGTH-prefix.length,body=redacted.length>room?`${redacted.slice(0,room-3)}...`:redacted;return`${prefix}${body}`}function extractTarget(tool3,args2){if(!args2)return"";if(tool3.toLowerCase()==="task"){let subagentType=args2.subagent_type;if(typeof subagentType==="string"&&subagentType.length>0)return subagentType}let targetFields=["filePath","path","file","target"];for(let field of targetFields){let value=args2[field];if(typeof value==="string"&&value.length>0)return value}let toolLower=tool3.toLowerCase();if(toolLower==="bash"||toolLower==="shell"||toolLower==="execute"||toolLower==="command"){let command=args2.command;if(typeof command==="string"&&command.trim().length>0)return normalizeCommandTarget(command);let description=args2.description;if(typeof description==="string"&&description.length>0){let safeDescription=redactCommandSecrets(description.slice(0,REDACTION_SCAN_WINDOW));return safeDescription.length>30?`${safeDescription.slice(0,27)}...`:safeDescription}let argsStr=args2.args;if(typeof argsStr==="string"&&argsStr.trim().length>0)return normalizeCommandTarget(argsStr)}return""}function extractIntent(tool3,args2){if(!args2)return"";if(tool3.toLowerCase()==="task"){let{prompt,description}=args2,safeText=redactCommandSecrets((typeof prompt==="string"?prompt:typeof description==="string"?description:"").slice(0,REDACTION_SCAN_WINDOW));if(safeText.length>100)return`${safeText.slice(0,97)}...`;return safeText}let intentFields=["description","task"];for(let field of intentFields){let value=args2[field];if(typeof value==="string"&&value.length>0){let safe=redactCommandSecrets(value.slice(0,REDACTION_SCAN_WINDOW));return safe.length>200?`${safe.slice(0,197)}...`:safe}}return""}function mapResult(verdict){if(verdict==="success")return"success";if(verdict==="failure")return"failure";return"pending"}function stepSeedKey(sessionId,directory){return`${trajectoryStepGeneration()}:${compositeSessionKey(directory,sessionId)}`}function markStepSeedGate(gateKey){if(stepSeedGate.has(gateKey))return;while(stepSeedGate.size>=MAX_STEP_SEED_GATE_SESSIONS){let oldest=stepSeedGate.keys().next().value;if(oldest===void 0)break;stepSeedGate.delete(oldest)}stepSeedGate.set(gateKey,!0)}async function ensureSessionStepSeeded(sessionId,directory){let gateKey=stepSeedKey(sessionId,directory);if(stepSeedGate.has(gateKey))return;let inFlight=stepSeedPromises.get(gateKey);if(inFlight!==void 0){await inFlight;return}let promise3=(async()=>{let lastStep=await getCurrentStep(sessionId,directory);if(lastStep>0)seedTrajectoryStepCounter(sessionId,directory,lastStep);markStepSeedGate(gateKey)})().catch(()=>{markStepSeedGate(gateKey)}).finally(()=>{stepSeedPromises.delete(gateKey)});stepSeedPromises.set(gateKey,promise3),await promise3}function invalidateStepSeedGate(sessionId){if(sessionId===void 0){stepSeedGate.clear();return}let suffix=sessionKeySuffix(sessionId);for(let gateKey of stepSeedGate.keys())if(gateKey.endsWith(suffix))stepSeedGate.delete(gateKey)}function createTrajectoryLoggerHook(config3,_directory2){let enabled=config3.enabled??!0,maxLines=config3.max_lines??500;return{toolAfter:async(input,output)=>{if(!enabled)return;let sessionId=input.sessionID;if(consumeDeniedCallMarker(sessionId,input.callID)){callStartTimes.delete(`${sessionId}:${input.callID}`);return}let session=swarmState.agentSessions.get(sessionId);if(!session?.delegationActive)return;let taskId=session.currentTaskId;if(!taskId)return;let startKey=`${sessionId}:${input.callID}`,startTime=callStartTimes.get(startKey)??Date.now();callStartTimes.delete(startKey);let elapsed_ms=Date.now()-startTime,agentName=swarmState.activeAgent.get(sessionId)??session?.agentName??"unknown",args_summary=summarizeArgs(input.args,200),verdict=deriveVerdict(output);await ensureSessionStepSeeded(sessionId,_directory2);let step=nextTrajectoryStep(sessionId,_directory2),action2=deriveAction(input.tool),target=extractTarget(input.tool,input.args),intent=extractIntent(input.tool,input.args),result=mapResult(verdict),entry={step,agent:agentName,action:action2,target,intent,timestamp:new Date().toISOString(),result,tool:input.tool,args_summary,verdict,elapsed_ms},sanitized=sanitizeTaskId2(taskId),relativePath2=path270.join("evidence",sanitized,"trajectory.jsonl"),trajectoryPath=validateSwarmPath(_directory2,relativePath2);try{await fs156.mkdir(path270.dirname(trajectoryPath),{recursive:!0});let line=`${JSON.stringify(entry)}
|
|
4139
4140
|
`;await fs156.appendFile(trajectoryPath,line,"utf-8"),await truncateTrajectoryFile(trajectoryPath,maxLines)}catch{}try{await appendTrajectoryEntry(sessionId,entry,_directory2,maxLines)}catch{}}}}function markDeniedCall(sessionId,callID){if(!callID)return;let now2=Date.now();for(let[key3,expiresAt]of deniedCallMarkers)if(expiresAt<=now2)deniedCallMarkers.delete(key3);let key2=`${sessionId}:${callID}`;deniedCallMarkers.delete(key2),deniedCallMarkers.set(key2,now2+DENIED_CALL_TTL_MS);while(deniedCallMarkers.size>MAX_DENIED_CALL_MARKERS){let oldest=deniedCallMarkers.keys().next().value;if(oldest===void 0||oldest===key2)break;deniedCallMarkers.delete(oldest)}}function consumeDeniedCallMarker(sessionId,callID){if(!callID)return!1;let key2=`${sessionId}:${callID}`,expiresAt=deniedCallMarkers.get(key2);if(expiresAt===void 0)return!1;return deniedCallMarkers.delete(key2),expiresAt>Date.now()}async function recordDeniedToolCall(sessionID,input,errorMessage2,directory,options){try{let session=swarmState.agentSessions.get(sessionID);if(!session?.delegationActive)return;let maxLines=options?.maxLines??500,startKey=`${sessionID}:${input.callID}`,startTime=callStartTimes.get(startKey);if(startTime!==void 0)callStartTimes.delete(startKey);let elapsed_ms=startTime===void 0?0:Date.now()-startTime,agentName=swarmState.activeAgent.get(sessionID)??session.agentName??"unknown",code=deriveGateDenialCode(errorMessage2);await ensureSessionStepSeeded(sessionID,directory);let entry={step:nextTrajectoryStep(sessionID,directory),agent:agentName,action:deriveAction(input.tool),target:extractTarget(input.tool,input.args),intent:`denied: ${code}`,timestamp:new Date().toISOString(),result:"failure",tool:input.tool,args_summary:summarizeArgs(input.args,200),verdict:"failure",elapsed_ms,callID:input.callID};markDeniedCall(sessionID,input.callID);try{await appendTrajectoryEntry(sessionID,entry,directory,maxLines)}catch{}let taskId=session.currentTaskId;if(!taskId)return;try{let relativePath2=path270.join("evidence",sanitizeTaskId2(taskId),"trajectory.jsonl"),trajectoryPath=validateSwarmPath(directory,relativePath2);await fs156.mkdir(path270.dirname(trajectoryPath),{recursive:!0}),await fs156.appendFile(trajectoryPath,`${JSON.stringify(entry)}
|
|
4140
4141
|
`,"utf-8"),await truncateTrajectoryFile(trajectoryPath,maxLines)}catch{}}catch{}}function clearTrajectoryStep(sessionId){clearTrajectoryStepCounters(sessionId),invalidateStepSeedGate(sessionId)}function summarizeArgs(args2,maxLength){if(!args2||Object.keys(args2).length===0)return"";let summaries=[];for(let[key2,value]of Object.entries(args2)){if(SENSITIVE_FIELDS.has(key2)||isSensitiveKey(key2)){summaries.push(`${key2}:[REDACTED]`);continue}if(value===null||value===void 0)summaries.push(`${key2}:null`);else if(typeof value==="string"){let window2=value.slice(0,REDACTION_SCAN_WINDOW),redacted=redactCommandSecrets(window2),truncated=redacted.length>50?`${redacted.slice(0,50)}...`:redacted;summaries.push(`${key2}:"${truncated}"`)}else if(typeof value==="number"||typeof value==="boolean")summaries.push(`${key2}:${String(value)}`);else if(Array.isArray(value)){let itemSummary=value.length>3?`${value.slice(0,3).map(String).join(",")},...(+${value.length-3})`:value.map(String).join(",");summaries.push(`${key2}:[${itemSummary}]`)}else if(typeof value==="object"){let keys=Object.keys(value);summaries.push(`${key2}:{${keys.join(",")}}`)}else summaries.push(`${key2}:${typeof value}`)}let summary=summaries.join(" ");return summary.length>maxLength?`${summary.slice(0,maxLength-3)}...`:summary}function deriveVerdict(output){if(output.metadata&&typeof output.metadata==="object"&&!Array.isArray(output.metadata)){let meta3=output.metadata;if(typeof meta3.verdict==="string"&&meta3.verdict.length>0)return meta3.verdict;if(meta3.success===!1||meta3.passed===!1)return"failure";if(meta3.success===!0||meta3.passed===!0)return"success"}let outputStr=String(output.output??"");if(outputStr.startsWith("Error:")||outputStr.startsWith("error:")||outputStr.startsWith("Error: "))return"failure";return"success"}var callStartTimes,SENSITIVE_FIELDS,SENSITIVE_SUBSTRINGS,URL_CREDENTIALS_PATTERN,REDACTION_SCAN_WINDOW=4096,MAX_COMMAND_TARGET_LENGTH=200,stepSeedGate,MAX_STEP_SEED_GATE_SESSIONS=500,stepSeedPromises,MAX_DENIED_CALL_MARKERS=500,DENIED_CALL_TTL_MS=300000,deniedCallMarkers;var init_trajectory_logger=__esm(()=>{init_manager2();init_redaction();init_trajectory_store();init_state();init_canonical_root();init_swarm_artifact_cache();init_gate_denial_tracker();init_normalize_tool_name();init_trajectory_step_state();init_utils2();callStartTimes=new Map,SENSITIVE_FIELDS=new Set(["password","token","secret","api_key","apikey","authorization","access_token","refresh_token","private_key","secret_key","credential","auth","bearer","x-api-key","session_id","cookie"]),SENSITIVE_SUBSTRINGS=["key","secret","token","password","auth","credential","private","certificate","bearer","session","cookie"];URL_CREDENTIALS_PATTERN=/\b([a-zA-Z][a-zA-Z0-9+.-]*:\/\/)[^\s/@:]+:[^\s/@]+@/g;stepSeedGate=new Map,stepSeedPromises=new Map;deniedCallMarkers=new Map});import*as fs157 from"node:fs";import*as path271 from"node:path";function errorMessage2(err){if(err instanceof Error)return err.message;return String(err)}async function releaseKnowledgeGateObligations(directory,sessionID){let results=[],live;try{live=await _internals227.queryLiveMemberships(directory,{session_id:sessionID,include_terminal:!0})}catch(err){return[`⚠️ Knowledge gate state not cleared: receipt authority unavailable (${errorMessage2(err)})`]}if(!live.ok)return[`⚠️ Knowledge gate state not cleared: receipt authority unavailable (${live.code})`];let pending=live.memberships.filter((membership)=>membership.exposure_kind==="architect_directive"&&!membership.application_marker&&membership.gate_release?.membership_event_id!==membership.membership_event_id);if(pending.length===0)return["⏭️ No pending knowledge gate obligations for this session"];let byTrace=new Map;for(let membership of pending){let group=byTrace.get(membership.trace_id)??[];group.push(membership),byTrace.set(membership.trace_id,group)}let committedCount=0,releasedPairs=[];for(let[traceId,group]of byTrace){let committed=await _internals227.commitGateReleaseBatch(directory,{trace_id:traceId,session_id:sessionID,items:group.map((membership)=>({entry_id:membership.entry_id,source:"application_gate_session_reset_release",reason:"/swarm reset-session operator escape (#2398)"}))});if(!committed.ok){results.push(`⚠️ Failed to release knowledge gate obligations on trace ${sanitizeDiagnosticText(traceId,64)}: ${committed.code}`);continue}committedCount+=committed.committed.length;for(let item of committed.committed)releasedPairs.push(`${traceId}/${item.entry_id}`);if(committed.rejected.length>0){let reasons=committed.rejected.map((item)=>item.reason).join("; "),hasWrongSession=committed.rejected.some((item)=>item.reason==="wrong_session");results.push(`⚠️ Partially released trace ${sanitizeDiagnosticText(traceId,64)}: ${reasons}`+(hasWrongSession?" — a re-dispatched child session is an authorized filer for its dispatch's stamps, or surface fresh knowledge via knowledge_recall for a new trace":""))}}if(committedCount===0)return results;if(committedCount<pending.length)results.push(`⚠️ Released ${committedCount} of ${pending.length} pending knowledge gate obligation(s) — ${pending.length-committedCount} not released; see warnings above`);else results.push(`✅ Released ${committedCount} pending knowledge gate obligation(s) for this session`);try{appendCoreEventSync(directory,{timestamp:new Date().toISOString(),event:"knowledge_application_gate_session_reset_clear",sessionID,released_pairs:releasedPairs})}catch{}return results}async function handleResetSessionCommand(directory,args2,sessionID){let results=[],snapshotResetGuard;try{if(snapshotResetGuard=await _internals227.beginSnapshotCoordinationReset(directory),snapshotResetGuard.closeError){if(snapshotResetGuard.priorUnsettled)return results.push(`❌ Snapshot coordination close timed out; reset aborted to avoid racing an in-flight initializer: ${errorMessage2(snapshotResetGuard.closeError)}`),snapshotResetGuard.release(),results.join(`
|
|
4141
|
-
`);throw snapshotResetGuard.closeError}}catch(err){results.push(`⚠️ Snapshot coordination close failed (continuing with reset): ${errorMessage2(err)}`)}try{let backup=_internals227.backupSwarmStateBeforeReset(directory,"reset-session",["session"]);if(backup.backupDir&&backup.copied.length>0){let rel=path271.relative(directory,backup.backupDir);results.push(`\uD83D\uDCE6 Backed up session state to ${rel}/ (restore by copying files back into .swarm/session/)`)}for(let w of backup.warnings)results.push(`⚠️ Backup warning: ${w}`)}catch(err){results.push(`⚠️ Auto-backup failed (continuing with reset): ${err instanceof Error?err.message:String(err)}`)}let snapshotAuthorityCleared=!1;try{let removed=_internals227.clearSnapshotRows(directory);snapshotAuthorityCleared=!0,results.push(removed>0?`✅ Deleted ${removed} authoritative session snapshot row(s)`:"⏭️ SQLite session snapshot already clean")}catch(err){results.push(`❌ Failed to clear SQLite session snapshot: ${errorMessage2(err)}`)}let snapshotProjectionCleared=!0;try{let projectionPath=validateSwarmPath(directory,SNAPSHOT_PROJECTION_FILE);if(fs157.existsSync(projectionPath))fs157.unlinkSync(projectionPath),results.push(`✅ Deleted .swarm/${SNAPSHOT_PROJECTION_FILE}`)}catch(err){snapshotProjectionCleared=!1,results.push(`❌ Failed to delete ${SNAPSHOT_PROJECTION_FILE}: ${errorMessage2(err)}`)}let statePath3,legacySnapshotCleared=!0;try{if(statePath3=validateSwarmPath(directory,"session/state.json"),fs157.existsSync(statePath3))fs157.unlinkSync(statePath3),results.push("✅ Deleted .swarm/session/state.json");else results.push("⏭️ state.json not found (already clean)")}catch{legacySnapshotCleared=!1,results.push("❌ Failed to delete state.json")}let sessionDir=statePath3?path271.dirname(statePath3):void 0,sessionFiles=[];if(sessionDir&&fs157.existsSync(sessionDir))try{sessionFiles=fs157.readdirSync(sessionDir)}catch(err){results.push(`❌ Failed to read session directory: ${errorMessage2(err)}`)}for(let file3 of sessionFiles){if(file3==="state.json"||file3===path271.basename(SNAPSHOT_PROJECTION_FILE))continue;let filePath=path271.join(sessionDir,file3);try{if(!fs157.existsSync(filePath))continue;if(!fs157.lstatSync(filePath).isFile())continue;fs157.unlinkSync(filePath),results.push(`✓ Deleted ${file3}`)}catch(err){results.push(`❌ Failed to delete ${file3}: ${errorMessage2(err)}`)}}let sessionCount=swarmState.agentSessions.size;for(let[sessionId,session]of swarmState.agentSessions)resetPrmSessionState(session,sessionId),clearTrajectoryStep(sessionId);swarmState.agentSessions.clear(),swarmState.dispatchParentByChildSession.clear(),swarmState.pendingDispatchAuthorizations=[],clearSnapshotSessionOwnerships(),results.push(`✅ Cleared ${sessionCount} in-memory agent session(s)`);try{let swept=clearAllSessionOverrides(directory);if(swept>0)results.push(`✅ Cleared ${swept} durable session QA override row(s)`)}catch(err){results.push(`⚠️ Durable session QA override sweep failed: ${errorMessage2(err)}`)}if(sessionID)clearSessionActionCircuits(sessionID),results.push("✅ Released this session’s guardrail circuit(s) (audited; re-delegate to re-arm)");let chainCount=swarmState.delegationChains.size;swarmState.delegationChains.clear(),results.push(`✅ Cleared ${chainCount} delegation chain(s)`);let activeAgentCount=swarmState.activeAgent.size;if(swarmState.activeAgent.clear(),results.push(`✅ Cleared ${activeAgentCount} active-agent mapping(s)`),snapshotResetGuard&&snapshotAuthorityCleared&&snapshotProjectionCleared&&legacySnapshotCleared)snapshotResetGuard.release();if(sessionID)try{results.push(...await _internals227.releaseKnowledgeGateObligations(directory,sessionID))}catch(err){results.push(`⚠️ Knowledge gate state not cleared: ${errorMessage2(err)}`)}else results.push("⚠️ Knowledge gate obligations not released: no session context on this invocation");if(sessionID)try{let{existsSync:existsSync136,rmSync:rmSync34}=await import("node:fs"),sessionBindingDir=validateSwarmPath(directory,`${STAGE_B_BINDINGS_DIR}/${stageBSessionDirName(sessionID)}`);if(existsSync136(sessionBindingDir))rmSync34(sessionBindingDir,{recursive:!0,force:!0}),results.push("✅ Deleted stage-b-dispatch-bindings for this session")}catch{results.push("⚠️ Stage B durable bindings not cleared (best-effort; TTL prune collects them)")}swarmState.gateDenialCounts.clear(),swarmState.currentCriticalShownIds.clear(),results.push("✅ Cleared in-memory knowledge gate denial state");let preserveWorktrees=!1;try{let{results:settlementResults,truncated}=await _internals227.recoverStaleCoderSettlements(directory,{force:!0});if(settlementResults.length===0)results.push("⏭️ No coder settlements to recover");for(let outcome of settlementResults)switch(outcome.outcome){case"recovered":results.push(`✅ Recovered coder settlement ${outcome.taskId} (${outcome.accepted?"changes attributed":"no workspace change to attribute"})`);break;case"already_terminal":results.push(`⏭️ Coder settlement ${outcome.taskId} already ${outcome.state}`);break;case"owned_in_process":results.push(`ℹ️ Coder settlement ${outcome.taskId} still registered in flight (${sanitizeDiagnosticText(outcome.transitionId)}) — its dispatch may be genuinely running; not force-recovered`);break;case"owned_by_live_foreign_pid":results.push(`ℹ️ Coder settlement ${outcome.taskId} owned by live process pid ${outcome.processId} (another OpenCode instance) — not touched; run /swarm recover there after closing it`);break;case"unreadable_wal":results.push(`⚠️ Coder settlement WAL ${outcome.taskId} is unreadable — inspect .swarm/coder-settlements/${outcome.taskId}.json`);break;case"error":results.push(`⚠️ Coder settlement ${outcome.taskId} recovery failed: ${sanitizeDiagnosticText(outcome.message,512)}`);break;default:results.push(`⚠️ Coder settlement ${outcome.taskId}: unknown outcome`);break}if(truncated)results.push("⚠️ More settlement WALs exist than the recovery scan cap (200) — older settlements were NOT recovered. Re-run /swarm reset-session after the tasks above are settled.");let forcedRecovered=settlementResults.filter((outcome)=>outcome.outcome==="recovered"&&outcome.forced).length;if(forcedRecovered>0)results.push(`⚠️ Released in-process ownership for ${forcedRecovered} dispatch(es) before recovery — if any was genuinely still running, its completion will report CODER_SETTLEMENT_IDEMPOTENCY_CONFLICT (safe to ignore; the settlement is already recovered).`);if(preserveWorktrees=settlementResults.some((outcome)=>outcome.outcome==="error"||outcome.outcome==="unreadable_wal"),preserveWorktrees)results.push("⚠️ Preserved .swarm-worktrees/ because at least one settlement recovery failed — a worktree referenced by an unsettled WAL would become unrecoverable if deleted. Resolve the failures above (re-run /swarm reset-session or /swarm recover) before clearing worktrees.")}catch(err){preserveWorktrees=!0,results.push(`⚠️ Coder settlement recovery failed (continuing with reset): ${errorMessage2(err)}`)}try{if(preserveWorktrees)results.push("⏭️ Skipped worktree reclamation (see above)");else{let confirmArg=args2.find((a)=>a.startsWith("--confirm=")),confirmToken=confirmArg?confirmArg.slice(10):void 0,candidates=[];for(let base of resolveWorktreeEnumerationBases(directory)){if(!fs157.existsSync(base))continue;for(let sessionEntry of fs157.readdirSync(base,{withFileTypes:!0})){if(!sessionEntry.isDirectory())continue;let sessionDir2=path271.join(base,sessionEntry.name);for(let laneEntry of fs157.readdirSync(sessionDir2,{withFileTypes:!0}))if(laneEntry.isDirectory())candidates.push(path271.join(sessionDir2,laneEntry.name))}}if(candidates.length===0)results.push("⏭️ No worktree lanes to reclaim");else{for(let lane of candidates)closeProjectDb(lane);let livePaths=new Set(_internals227.listLiveLaneOwners(directory).live.map((owner)=>owner.lanePath)),own=[],foreign=[],unprovable=[];for(let candidate2 of candidates){let marker=probeGitMarker(path271.join(candidate2,".git"));if(marker==="uncertain"){unprovable.push(candidate2);continue}if(marker==="gitless"){if(isPathUnderSwarmWorktreeBase(candidate2,directory))own.push(candidate2);else unprovable.push(candidate2);continue}if(resolveWorktreeRepoOwnership(candidate2,directory).owned)own.push(candidate2);else foreign.push(candidate2)}for(let lane of foreign)results.push(`ℹ️ Preserved "${lane}" — owned by a different repository; never deleted by this project.`);for(let lane of unprovable)results.push(`ℹ️ Preserved "${lane}" — ownership unprovable (git-less outside the project worktree base, or unreadable metadata); never deleted by this project.`);if(confirmToken){let scope=own.filter((lane)=>probeGitMarker(path271.join(lane,".git"))==="present"||isPathUnderSwarmWorktreeBase(lane,directory)).map((lane)=>({path:lane,reason:"confirmed reset-session purge"})),execution=executeDestructivePurge(own[0]??"",directory,confirmToken,{candidates:scope});if(execution.ok)results.push(`✅ Removed ${execution.purged?.length??0} confirmed worktree lane(s)`);else results.push(`⚠️ Confirmed purge rejected: ${execution.reason}`)}else{let removedCount=0,preservedOwn=[];for(let lane of own){if(livePaths.has(lane)){preservedOwn.push(lane);continue}if((await _internals227.removeOwnedWorktreeDir(lane,directory)).status==="removed")removedCount++;else preservedOwn.push(lane)}if(removedCount>0)results.push(`✅ Removed ${removedCount} clean worktree lane(s)`);if(preservedOwn.length>0){let scope=preservedOwn.map((lane)=>({path:lane,reason:"uncommitted or live-owned work"})),preview=previewDestructivePurge(preservedOwn[0],directory,{candidates:scope});for(let line of preview.previewLines)results.push(` ${line}`);let token=issueConfirmToken(preservedOwn[0],directory,{candidates:scope});results.push(`\uD83D\uDD10 Preserved ${preservedOwn.length} lane(s) containing uncommitted or live work. Destroying them requires confirmation: re-run /swarm reset-session with --confirm=${token} (valid 15 minutes).`)}}}}}catch(err){results.push(`⚠️ Failed to reclaim worktree lanes: ${errorMessage2(err)}`)}try{let branchResult=await _internals227.cleanupOrphanedBranches(directory,[]);if(branchResult.removed.length>0)results.push(`✅ Removed ${branchResult.removed.length} orphan swarm-lane branch(es)`);if(branchResult.errors.length>0)results.push(`⚠️ Failed to remove ${branchResult.errors.length} branch(es): ${branchResult.errors.map((e)=>e.error).join("; ")}`);if(branchResult.skippedRecoveryBranches&&branchResult.skippedRecoveryBranches.length>0)results.push(`ℹ️ Preserved ${branchResult.skippedRecoveryBranches.length} branch(es) with unresolved merge-back recovery records (run /swarm status to inspect)`);if(branchResult.recoveryReadError)results.push("⚠️ Skipped all lane-branch deletions: .swarm/recovery/ was unreadable (fail-safe). Resolve or clear corrupt recovery records and re-run.")}catch(err){results.push(`⚠️ Failed to cleanup orphan branches: ${errorMessage2(err)}`)}return["## Session State Reset","",...results,"","Session state cleared. Plan, evidence, and knowledge preserved.","","In-memory circuit breakers and revision limits have been cleared. Durable per-task retry gates (the coder retry circuit breaker, bound to commit settlement in the events audit log and .swarm/evidence/) intentionally survive this reset. If a task is blocked with TASK_RETRY_CRITIC_REQUIRED waiting for a critic_sounding_board APPROVED verdict that was already obtained, have the architect record it with the approve_retry_sounding_board tool. A task left at rework_required also survives this reset; when the Stage B verdict did not require a code change, the architect can exit it with the recover_rework_task tool (issue #2755). A task wedged at TASK_RETRY_USER_ESCALATION_REQUIRED is exited with the audited update_task_status force repair (issue #3389; see docs/troubleshooting/recovery-runbook.md), which reopens the task "+"and clears the retry circuit — the task's plan status must "+"already be in_progress; a task still pending in the plan takes one ordinary in_progress status update first."].join(`
|
|
4142
|
-
`)}var _internals227;var init_reset_session=__esm(()=>{init_stage_b_dispatch_binding_store();init_lane_context();init_project_db();init_qa_gate_session_override();init_core_events();init_action_circuit();init_init_orphan_recovery();init_knowledge_receipt_ledger();init_trajectory_logger();init_utils2();init_lane_owners();init_prm();init_path_identity();init_snapshot_coordination_init();init_snapshot_store();init_snapshot_writer();init_state();init_coder_settlement();init_core3();init_merge2();init_ownership();init_destructive_purge();init_reset_backup();_internals227={cleanupOrphanedBranches,removeOwnedWorktreeDir,listLiveLaneOwners,backupSwarmStateBeforeReset,recoverStaleCoderSettlements,queryLiveMemberships,commitGateReleaseBatch,beginSnapshotCoordinationReset,clearSnapshotRows,releaseKnowledgeGateObligations}});async function handleRetrieveCommand(directory,args2){let summaryId=args2[0];if(!summaryId)return["## Swarm Retrieve","","Usage: `/swarm retrieve <id>`","","Example: `/swarm retrieve S1`","","Retrieves the full output that was replaced by a summary."].join(`
|
|
4142
|
+
`);throw snapshotResetGuard.closeError}}catch(err){results.push(`⚠️ Snapshot coordination close failed (continuing with reset): ${errorMessage2(err)}`)}try{let backup=_internals227.backupSwarmStateBeforeReset(directory,"reset-session",["session"]);if(backup.backupDir&&backup.copied.length>0){let rel=path271.relative(directory,backup.backupDir);results.push(`\uD83D\uDCE6 Backed up session state to ${rel}/ (restore by copying files back into .swarm/session/)`)}for(let w of backup.warnings)results.push(`⚠️ Backup warning: ${w}`)}catch(err){results.push(`⚠️ Auto-backup failed (continuing with reset): ${err instanceof Error?err.message:String(err)}`)}let snapshotAuthorityCleared=!1;try{let removed=_internals227.clearSnapshotRows(directory);snapshotAuthorityCleared=!0,results.push(removed>0?`✅ Deleted ${removed} authoritative session snapshot row(s)`:"⏭️ SQLite session snapshot already clean")}catch(err){results.push(`❌ Failed to clear SQLite session snapshot: ${errorMessage2(err)}`)}let snapshotProjectionCleared=!0;try{let projectionPath=validateSwarmPath(directory,SNAPSHOT_PROJECTION_FILE);if(fs157.existsSync(projectionPath))fs157.unlinkSync(projectionPath),results.push(`✅ Deleted .swarm/${SNAPSHOT_PROJECTION_FILE}`)}catch(err){snapshotProjectionCleared=!1,results.push(`❌ Failed to delete ${SNAPSHOT_PROJECTION_FILE}: ${errorMessage2(err)}`)}let statePath3,legacySnapshotCleared=!0;try{if(statePath3=validateSwarmPath(directory,"session/state.json"),fs157.existsSync(statePath3))fs157.unlinkSync(statePath3),results.push("✅ Deleted .swarm/session/state.json");else results.push("⏭️ state.json not found (already clean)")}catch{legacySnapshotCleared=!1,results.push("❌ Failed to delete state.json")}let sessionDir=statePath3?path271.dirname(statePath3):void 0,sessionFiles=[];if(sessionDir&&fs157.existsSync(sessionDir))try{sessionFiles=fs157.readdirSync(sessionDir)}catch(err){results.push(`❌ Failed to read session directory: ${errorMessage2(err)}`)}for(let file3 of sessionFiles){if(file3==="state.json"||file3===path271.basename(SNAPSHOT_PROJECTION_FILE))continue;let filePath=path271.join(sessionDir,file3);try{if(!fs157.existsSync(filePath))continue;if(!fs157.lstatSync(filePath).isFile())continue;fs157.unlinkSync(filePath),results.push(`✓ Deleted ${file3}`)}catch(err){results.push(`❌ Failed to delete ${file3}: ${errorMessage2(err)}`)}}let sessionCount=swarmState.agentSessions.size;for(let[sessionId,session]of swarmState.agentSessions)resetPrmSessionState(session,sessionId),clearTrajectoryStep(sessionId);swarmState.agentSessions.clear(),swarmState.dispatchParentByChildSession.clear(),swarmState.pendingDispatchAuthorizations=[],clearSnapshotSessionOwnerships(),results.push(`✅ Cleared ${sessionCount} in-memory agent session(s)`);try{let swept=clearAllSessionOverrides(directory);if(swept>0)results.push(`✅ Cleared ${swept} durable session QA override row(s)`)}catch(err){results.push(`⚠️ Durable session QA override sweep failed: ${errorMessage2(err)}`)}if(sessionID)clearSessionActionCircuits(sessionID),results.push("✅ Released this session’s guardrail circuit(s) (audited; re-delegate to re-arm)");let chainCount=swarmState.delegationChains.size;swarmState.delegationChains.clear(),results.push(`✅ Cleared ${chainCount} delegation chain(s)`);let activeAgentCount=swarmState.activeAgent.size;swarmState.activeAgent.clear(),results.push(`✅ Cleared ${activeAgentCount} active-agent mapping(s)`);let persistenceStopAdvised=!1,advisePersistenceStop=(combined)=>{if(persistenceStopAdvised)return;persistenceStopAdvised=!0,advisoryWarn(combined?"[opencode-swarm] /swarm reset-session partially failed while a prior initialization attempt is still settling: durable session-snapshot persistence is stopped — wait for that attempt to settle, then re-run /swarm reset-session to completion (or restart the host) to recover.":"[opencode-swarm] /swarm reset-session partially failed: durable session-snapshot persistence is stopped for this project until a reset-session run succeeds — re-run /swarm reset-session (or restart the host) to recover.")};if(snapshotResetGuard&&snapshotAuthorityCleared&&snapshotProjectionCleared&&legacySnapshotCleared)snapshotResetGuard.release();else if(snapshotResetGuard){if(snapshotResetGuard.markStranded())advisePersistenceStop(getSnapshotCoordinationStatus(directory).pendingPriorAttempt===!0)}else if(getSnapshotCoordinationStatus(directory).state==="closing")advisePersistenceStop(!1);if(sessionID)try{results.push(...await _internals227.releaseKnowledgeGateObligations(directory,sessionID))}catch(err){results.push(`⚠️ Knowledge gate state not cleared: ${errorMessage2(err)}`)}else results.push("⚠️ Knowledge gate obligations not released: no session context on this invocation");if(sessionID)try{let{existsSync:existsSync136,rmSync:rmSync34}=await import("node:fs"),sessionBindingDir=validateSwarmPath(directory,`${STAGE_B_BINDINGS_DIR}/${stageBSessionDirName(sessionID)}`);if(existsSync136(sessionBindingDir))rmSync34(sessionBindingDir,{recursive:!0,force:!0}),results.push("✅ Deleted stage-b-dispatch-bindings for this session")}catch{results.push("⚠️ Stage B durable bindings not cleared (best-effort; TTL prune collects them)")}swarmState.gateDenialCounts.clear(),swarmState.currentCriticalShownIds.clear(),results.push("✅ Cleared in-memory knowledge gate denial state");let preserveWorktrees=!1;try{let{results:settlementResults,truncated}=await _internals227.recoverStaleCoderSettlements(directory,{force:!0});if(settlementResults.length===0)results.push("⏭️ No coder settlements to recover");for(let outcome of settlementResults)switch(outcome.outcome){case"recovered":results.push(`✅ Recovered coder settlement ${outcome.taskId} (${outcome.accepted?"changes attributed":"no workspace change to attribute"})`);break;case"already_terminal":results.push(`⏭️ Coder settlement ${outcome.taskId} already ${outcome.state}`);break;case"owned_in_process":results.push(`ℹ️ Coder settlement ${outcome.taskId} still registered in flight (${sanitizeDiagnosticText(outcome.transitionId)}) — its dispatch may be genuinely running; not force-recovered`);break;case"owned_by_live_foreign_pid":results.push(`ℹ️ Coder settlement ${outcome.taskId} owned by live process pid ${outcome.processId} (another OpenCode instance) — not touched; run /swarm recover there after closing it`);break;case"unreadable_wal":results.push(`⚠️ Coder settlement WAL ${outcome.taskId} is unreadable — inspect .swarm/coder-settlements/${outcome.taskId}.json`);break;case"error":results.push(`⚠️ Coder settlement ${outcome.taskId} recovery failed: ${sanitizeDiagnosticText(outcome.message,512)}`);break;default:results.push(`⚠️ Coder settlement ${outcome.taskId}: unknown outcome`);break}if(truncated)results.push("⚠️ More settlement WALs exist than the recovery scan cap (200) — older settlements were NOT recovered. Re-run /swarm reset-session after the tasks above are settled.");let forcedRecovered=settlementResults.filter((outcome)=>outcome.outcome==="recovered"&&outcome.forced).length;if(forcedRecovered>0)results.push(`⚠️ Released in-process ownership for ${forcedRecovered} dispatch(es) before recovery — if any was genuinely still running, its completion will report CODER_SETTLEMENT_IDEMPOTENCY_CONFLICT (safe to ignore; the settlement is already recovered).`);if(preserveWorktrees=settlementResults.some((outcome)=>outcome.outcome==="error"||outcome.outcome==="unreadable_wal"),preserveWorktrees)results.push("⚠️ Preserved .swarm-worktrees/ because at least one settlement recovery failed — a worktree referenced by an unsettled WAL would become unrecoverable if deleted. Resolve the failures above (re-run /swarm reset-session or /swarm recover) before clearing worktrees.")}catch(err){preserveWorktrees=!0,results.push(`⚠️ Coder settlement recovery failed (continuing with reset): ${errorMessage2(err)}`)}try{if(preserveWorktrees)results.push("⏭️ Skipped worktree reclamation (see above)");else{let confirmArg=args2.find((a)=>a.startsWith("--confirm=")),confirmToken=confirmArg?confirmArg.slice(10):void 0,candidates=[];for(let base of resolveWorktreeEnumerationBases(directory)){if(!fs157.existsSync(base))continue;for(let sessionEntry of fs157.readdirSync(base,{withFileTypes:!0})){if(!sessionEntry.isDirectory())continue;let sessionDir2=path271.join(base,sessionEntry.name);for(let laneEntry of fs157.readdirSync(sessionDir2,{withFileTypes:!0}))if(laneEntry.isDirectory())candidates.push(path271.join(sessionDir2,laneEntry.name))}}if(candidates.length===0)results.push("⏭️ No worktree lanes to reclaim");else{for(let lane of candidates)closeProjectDb(lane);let livePaths=new Set(_internals227.listLiveLaneOwners(directory).live.map((owner)=>owner.lanePath)),own=[],foreign=[],unprovable=[];for(let candidate2 of candidates){let marker=probeGitMarker(path271.join(candidate2,".git"));if(marker==="uncertain"){unprovable.push(candidate2);continue}if(marker==="gitless"){if(isPathUnderSwarmWorktreeBase(candidate2,directory))own.push(candidate2);else unprovable.push(candidate2);continue}if(resolveWorktreeRepoOwnership(candidate2,directory).owned)own.push(candidate2);else foreign.push(candidate2)}for(let lane of foreign)results.push(`ℹ️ Preserved "${lane}" — owned by a different repository; never deleted by this project.`);for(let lane of unprovable)results.push(`ℹ️ Preserved "${lane}" — ownership unprovable (git-less outside the project worktree base, or unreadable metadata); never deleted by this project.`);if(confirmToken){let scope=own.filter((lane)=>probeGitMarker(path271.join(lane,".git"))==="present"||isPathUnderSwarmWorktreeBase(lane,directory)).map((lane)=>({path:lane,reason:"confirmed reset-session purge"})),execution=executeDestructivePurge(own[0]??"",directory,confirmToken,{candidates:scope});if(execution.ok)results.push(`✅ Removed ${execution.purged?.length??0} confirmed worktree lane(s)`);else results.push(`⚠️ Confirmed purge rejected: ${execution.reason}`)}else{let removedCount=0,preservedOwn=[];for(let lane of own){if(livePaths.has(lane)){preservedOwn.push(lane);continue}if((await _internals227.removeOwnedWorktreeDir(lane,directory)).status==="removed")removedCount++;else preservedOwn.push(lane)}if(removedCount>0)results.push(`✅ Removed ${removedCount} clean worktree lane(s)`);if(preservedOwn.length>0){let scope=preservedOwn.map((lane)=>({path:lane,reason:"uncommitted or live-owned work"})),preview=previewDestructivePurge(preservedOwn[0],directory,{candidates:scope});for(let line of preview.previewLines)results.push(` ${line}`);let token=issueConfirmToken(preservedOwn[0],directory,{candidates:scope});results.push(`\uD83D\uDD10 Preserved ${preservedOwn.length} lane(s) containing uncommitted or live work. Destroying them requires confirmation: re-run /swarm reset-session with --confirm=${token} (valid 15 minutes).`)}}}}}catch(err){results.push(`⚠️ Failed to reclaim worktree lanes: ${errorMessage2(err)}`)}try{let branchResult=await _internals227.cleanupOrphanedBranches(directory,[]);if(branchResult.removed.length>0)results.push(`✅ Removed ${branchResult.removed.length} orphan swarm-lane branch(es)`);if(branchResult.errors.length>0)results.push(`⚠️ Failed to remove ${branchResult.errors.length} branch(es): ${branchResult.errors.map((e)=>e.error).join("; ")}`);if(branchResult.skippedRecoveryBranches&&branchResult.skippedRecoveryBranches.length>0)results.push(`ℹ️ Preserved ${branchResult.skippedRecoveryBranches.length} branch(es) with unresolved merge-back recovery records (run /swarm status to inspect)`);if(branchResult.recoveryReadError)results.push("⚠️ Skipped all lane-branch deletions: .swarm/recovery/ was unreadable (fail-safe). Resolve or clear corrupt recovery records and re-run.")}catch(err){results.push(`⚠️ Failed to cleanup orphan branches: ${errorMessage2(err)}`)}return["## Session State Reset","",...results,"","Session state cleared. Plan, evidence, and knowledge preserved.","","In-memory circuit breakers and revision limits have been cleared. Durable per-task retry gates (the coder retry circuit breaker, bound to commit settlement in the events audit log and .swarm/evidence/) intentionally survive this reset. If a task is blocked with TASK_RETRY_CRITIC_REQUIRED waiting for a critic_sounding_board APPROVED verdict that was already obtained, have the architect record it with the approve_retry_sounding_board tool. A task left at rework_required also survives this reset; when the Stage B verdict did not require a code change, the architect can exit it with the recover_rework_task tool (issue #2755). A task wedged at TASK_RETRY_USER_ESCALATION_REQUIRED is exited with the audited update_task_status force repair (issue #3389; see docs/troubleshooting/recovery-runbook.md), which reopens the task "+"and clears the retry circuit — the task's plan status must "+"already be in_progress; a task still pending in the plan takes one ordinary in_progress status update first."].join(`
|
|
4143
|
+
`)}var _internals227;var init_reset_session=__esm(()=>{init_stage_b_dispatch_binding_store();init_lane_context();init_project_db();init_qa_gate_session_override();init_core_events();init_action_circuit();init_init_orphan_recovery();init_knowledge_receipt_ledger();init_trajectory_logger();init_utils2();init_lane_owners();init_prm();init_path_identity();init_warning_buffer();init_snapshot_coordination_init();init_snapshot_store();init_snapshot_writer();init_state();init_coder_settlement();init_core3();init_merge2();init_ownership();init_destructive_purge();init_reset_backup();_internals227={cleanupOrphanedBranches,removeOwnedWorktreeDir,listLiveLaneOwners,backupSwarmStateBeforeReset,recoverStaleCoderSettlements,queryLiveMemberships,commitGateReleaseBatch,beginSnapshotCoordinationReset,clearSnapshotRows,releaseKnowledgeGateObligations}});async function handleRetrieveCommand(directory,args2){let summaryId=args2[0];if(!summaryId)return["## Swarm Retrieve","","Usage: `/swarm retrieve <id>`","","Example: `/swarm retrieve S1`","","Retrieves the full output that was replaced by a summary."].join(`
|
|
4143
4144
|
`);try{let fullOutput=await loadFullOutput(directory,summaryId);if(fullOutput===null)return`## Summary Not Found
|
|
4144
4145
|
|
|
4145
4146
|
No stored output found for ID \`${summaryId}\`.
|
|
@@ -4163,7 +4164,10 @@ ${JSON_CLOSE_TAG}`,body=JSON.stringify(payload,null,2);while(Buffer.byteLength(w
|
|
|
4163
4164
|
`);if(!ctx.reviewModelDispatcher)return"Review runtime unavailable: no ReviewModelDispatcher is bound. Run `/swarm review` from an active plugin session; the standalone CLI cannot dispatch isolated review-model sessions.";let reviewerAgent,validatorAgent;try{let names=resolveReviewAgentNames(Object.keys(ctx.agents),ctx.activeAgentName);reviewerAgent=names.reviewer,validatorAgent=names.validator}catch(error93){return`Review runtime unavailable: ${error93 instanceof Error?error93.message:String(error93)}`}if(!Object.hasOwn(ctx.agents,reviewerAgent))return"Review runtime unavailable: no generated reviewer agent is registered for this plugin session.";let config3=ctx.autoReviewConfig??resolveAutoReviewConfig({});if((config3.validate_findings||config3.final_review.mode==="gate")&&!Object.hasOwn(ctx.agents,validatorAgent))return"Review runtime unavailable: finding validation is enabled but no generated critic_finding_validator agent is registered.";let reviewerModel,reviewerFallbackModels=[],validatorModel,validatorFallbackModels=[];try{reviewerModel=config3.final_review.model?parseModelString2(config3.final_review.model):void 0,reviewerFallbackModels=resolveReviewFallbackModels(reviewerAgent,ctx.reviewAgentModelRegistry),validatorModel=config3.validation_model?parseModelString2(config3.validation_model):void 0,validatorFallbackModels=resolveReviewFallbackModels(validatorAgent,ctx.reviewAgentModelRegistry)}catch(error93){return`Review configuration error: ${error93 instanceof Error?error93.message:String(error93)}`}let result=await _internals232.runReviewEngine({directory:ctx.directory,sessionID:ctx.sessionID,trigger:"manual",selector:parsed.selector,config:config3,dispatcher:ctx.reviewModelDispatcher,reviewerAgent,validatorAgent,reviewerModel,reviewerFallbackModels,validatorModel,validatorFallbackModels}),evidence2=_internals232.readEvidence(result.evidencePath,ctx.directory);return parsed.json?renderJson(result,evidence2,parsed.selector):renderHuman(result,evidence2,parsed.selector)}var MAX_EVIDENCE_BYTES=524288,MAX_JSON_WRAPPER_BYTES=65536,MAX_DISPLAY_TEXT=500,MAX_SCOPE_WARNINGS=20,MAX_SCOPE_FILES2=25,JSON_OPEN_TAG="[SWARM_REVIEW_JSON]",JSON_CLOSE_TAG="[/SWARM_REVIEW_JSON]",SEVERITY_RANK2,_internals232;var init_review=__esm(()=>{init_schema();init_diff_source();init_engine2();init_evidence2();init_runtime3();init_model_dispatch_fallback();SEVERITY_RANK2={critical:0,high:1,medium:2,low:3,info:4};_internals232={runReviewEngine,readEvidence}});import*as fs162 from"node:fs";import*as path276 from"node:path";function safeParseToolJson(result){try{let jsonStr=typeof result==="string"?result:result.output;return JSON.parse(jsonStr)}catch{return null}}async function listGitCheckpoints(directory){try{let result=await checkpoint.execute({action:"list"},{directory}),parsed=safeParseToolJson(result);if(!parsed)return null;if(parsed.success!==!0||!Array.isArray(parsed.checkpoints))return null;return parsed.checkpoints}catch{return null}}function formatGitCheckpointList(checkpoints){if(checkpoints.length===0)return"No checkpoints found. Create one with `/swarm checkpoint save <label>`";return["## Available Checkpoints","",...checkpoints.map((c,index)=>`- ${index+1}. "${c.label}" - ${new Date(c.timestamp).toLocaleString()} (${c.sha.slice(0,12)})`),"","Run `/swarm rollback <label-or-number>` to restore to a checkpoint."].join(`
|
|
4164
4165
|
`)}function resolveGitCheckpoint(checkpoints,selector){let index=Number.parseInt(selector,10);if(/^\d+$/.test(selector)&&index>=1&&index<=checkpoints.length)return checkpoints[index-1]??null;return checkpoints.find((c)=>c.label===selector)??null}async function restoreGitCheckpoint(directory,selected,confirmToken){let result=await checkpoint.execute(confirmToken?{action:"restore",label:selected.label,confirm_token:confirmToken}:{action:"restore",label:selected.label},{directory}),parsed=safeParseToolJson(result);if(!parsed)return`Error: Failed to parse checkpoint response for "${selected.label}"`;if(parsed.requires_confirm&&parsed.confirm_token)return[...parsed.preview??[],"",`\uD83D\uDD10 Nothing was restored. Re-run /swarm rollback ${selected.label} --confirm=${parsed.confirm_token} (valid 15 minutes), or add --yes to confirm in one step.`].join(`
|
|
4165
4166
|
`);if(parsed.success!==!0)return`Error: ${parsed.error||`Failed to restore checkpoint "${selected.label}"`}`;let rollbackEvent={type:"rollback",label:selected.label,sha:selected.sha,timestamp:new Date().toISOString(),source:"checkpoints.json"};try{appendCoreEventSync(directory,rollbackEvent)}catch(error93){log("Failed to write rollback event:",error93 instanceof Error?error93.message:String(error93))}let lines=[`Rolled back to checkpoint "${selected.label}" (${selected.sha.slice(0,12)})`];if(parsed.backup_dir)lines.push(`\uD83D\uDCE6 Destroyed bytes backed up to ${path276.relative(directory,parsed.backup_dir)} — copy files back to recover.`);for(let warning of parsed.backup_warnings??[])lines.push(`⚠️ ${warning}`);return lines.join(`
|
|
4166
|
-
`)}function parseRollbackArgs(args2){let selector,confirmToken,yes=!1;for(let arg of args2){if(arg==="--yes"){yes=!0;continue}let confirmMatch=/^--confirm=(.+)$/.exec(arg);if(confirmMatch){confirmToken=confirmMatch[1];continue}if(selector===void 0)selector=arg}return{selector,confirmToken,yes}}async function restoreGitCheckpointGated(directory,selected,flags){let measurement=await measureGitDestruction(directory,selected.sha);if(measurement.kind==="unreadable")return`Error: cannot verify the working tree (git status unreadable; ${
|
|
4167
|
+
`)}function parseRollbackArgs(args2){let selector,confirmToken,yes=!1;for(let arg of args2){if(arg==="--yes"){yes=!0;continue}let confirmMatch=/^--confirm=(.+)$/.exec(arg);if(confirmMatch){confirmToken=confirmMatch[1];continue}if(selector===void 0)selector=arg}return{selector,confirmToken,yes}}async function restoreGitCheckpointGated(directory,selected,flags){let measurement=await measureGitDestruction(directory,selected.sha);if(measurement.kind==="unreadable"){let cause=describeUnreadableCause(measurement,measurement.source),unreadableNote=measurement.excludedOutOfRoot&&measurement.excludedOutOfRoot.length>0?` — ${measurement.excludedOutOfRoot.length} out-of-root porcelain record(s) had been excluded from the scope before the read failed (first: ${formatExcludedRecord(measurement.excludedOutOfRoot[0])})`:"";return`Error: cannot verify the working tree (${measurement.source==="enumeration"?"the target-tree listing could not be read":"git status unreadable"}; ${cause})${unreadableNote} — refusing to restore without a preview.`}let exclusionNote=measurement.excludedOutOfRoot.length>0?`⚠ ${measurement.excludedOutOfRoot.length} out-of-root porcelain record(s) were excluded from this scope (first: ${formatExcludedRecord(measurement.excludedOutOfRoot[0])})`:null;if(flags.yes&&flags.confirmToken)return"Error: pass either --yes or --confirm=<token>, not both.";if(measurement.dirtyRelPaths.length===0){let restored=await restoreGitCheckpoint(directory,selected,flags.confirmToken);return exclusionNote?`${restored}
|
|
4168
|
+
${exclusionNote}`:restored}let candidates=trackedDirtyCandidates(directory,measurement.dirtyRelPaths),scopeAnchor=candidates[0].path;if(flags.yes){let token2=issueConfirmToken(scopeAnchor,directory,{kind:ROLLBACK_GIT_KIND,candidates}),restored=await restoreGitCheckpoint(directory,selected,token2);return exclusionNote?`${restored}
|
|
4169
|
+
${exclusionNote}`:restored}if(flags.confirmToken){let restored=await restoreGitCheckpoint(directory,selected,flags.confirmToken);return exclusionNote?`${restored}
|
|
4170
|
+
${exclusionNote}`:restored}let token=issueConfirmToken(scopeAnchor,directory,{kind:ROLLBACK_GIT_KIND,candidates}),shown=measurement.dirtyRelPaths.slice(0,10),overflow=measurement.dirtyRelPaths.length-shown.length;return[`⚠️ Restoring to checkpoint "${selected.label}" (${selected.sha.slice(0,12)}) runs git reset --hard and would DESTROY ${candidates.length} uncommitted tracked file(s):`,...shown.map((p)=>` - ${p}`),...overflow>0?[` (+${overflow} more)`]:[],...exclusionNote?["",exclusionNote]:[],"","\uD83D\uDD10 Nothing was restored. Destroyed bytes are backed up to .swarm/rollback-backups/ once confirmed.",`Re-run /swarm rollback ${selected.label} --confirm=${token} (valid 15 minutes), or add --yes to confirm in one step.`].join(`
|
|
4167
4171
|
`)}async function handleRollbackCommand(directory,args2){let{selector:phaseArg,confirmToken,yes}=parseRollbackArgs(args2);if(!phaseArg){let manifestPath3=validateSwarmPath(directory,"checkpoints/manifest.json");if(!fs162.existsSync(manifestPath3)){let gitCheckpoints=await listGitCheckpoints(directory);if(gitCheckpoints)return formatGitCheckpointList(gitCheckpoints);return"No checkpoints found. Use `/swarm checkpoint save <label>` to create checkpoints."}let manifest2;try{manifest2=JSON.parse(fs162.readFileSync(manifestPath3,"utf-8"))}catch{return"Error: Checkpoint manifest is corrupted. Delete .swarm/checkpoints/manifest.json and re-checkpoint."}let checkpoints=manifest2.checkpoints||[];if(checkpoints.length===0)return"No checkpoints found in manifest.";return["## Available Checkpoints","",...checkpoints.map((c)=>`- Phase ${c.phase}: ${c.label||"no label"} (${new Date(c.timestamp).toLocaleString()})`),"","Run `/swarm rollback <phase>` to restore to a checkpoint."].join(`
|
|
4168
4172
|
`)}let targetPhase=parseInt(phaseArg,10);if(Number.isNaN(targetPhase)||targetPhase<1){let gitCheckpoints=await listGitCheckpoints(directory);if(!gitCheckpoints)return"Error: Phase number must be a positive integer.";let selected=resolveGitCheckpoint(gitCheckpoints,phaseArg);if(!selected)return`Error: Checkpoint "${phaseArg}" not found. Available checkpoints: ${gitCheckpoints.map((c)=>`"${c.label}"`).join(", ")||"none"}`;return restoreGitCheckpointGated(directory,selected,{confirmToken,yes})}let manifestPath2=validateSwarmPath(directory,"checkpoints/manifest.json");if(!fs162.existsSync(manifestPath2)){let gitCheckpoints=await listGitCheckpoints(directory);if(!gitCheckpoints)return`Error: No checkpoints found. Cannot rollback to phase ${targetPhase}.`;let selected=resolveGitCheckpoint(gitCheckpoints,phaseArg);if(!selected)return`Error: Checkpoint ${phaseArg} not found. Available checkpoints: ${gitCheckpoints.map((c,index)=>`${index+1}="${c.label}"`).join(", ")||"none"}`;return restoreGitCheckpointGated(directory,selected,{confirmToken,yes})}let manifest;try{manifest=JSON.parse(fs162.readFileSync(manifestPath2,"utf-8"))}catch{return"Error: Checkpoint manifest is corrupted. Delete .swarm/checkpoints/manifest.json and re-checkpoint."}let checkpoint2=manifest.checkpoints?.find((c)=>c.phase===targetPhase);if(!checkpoint2){let available=manifest.checkpoints?.map((c)=>c.phase).join(", ")||"none";return`Error: Checkpoint for phase ${targetPhase} not found. Available phases: ${available}`}let checkpointDir=validateSwarmPath(directory,`checkpoints/phase-${targetPhase}`);if(!fs162.existsSync(checkpointDir))return`Error: Checkpoint directory for phase ${targetPhase} does not exist.`;let checkpointFiles=fs162.readdirSync(checkpointDir);if(checkpointFiles.length===0)return`Error: Checkpoint for phase ${targetPhase} is empty. Cannot rollback.`;let checkpointPlan=null;if(checkpointFiles.includes("plan.json"))try{checkpointPlan=PlanSchema.parse(JSON.parse(fs162.readFileSync(path276.join(checkpointDir,"plan.json"),"utf-8")))}catch(error93){return`Error: Checkpoint plan.json is invalid. Cannot rollback: ${error93 instanceof Error?error93.message:String(error93)}`}let swarmDir=path276.dirname(validateSwarmPath(directory,".keep")),EXCLUDE_FILES=new Set(["plan-ledger.jsonl","plan-ledger.quarantine"]),PLAN_PROJECTION_FILES=new Set(["plan.json","plan.md"]),overwriteSet=[];for(let file3 of checkpointFiles){if(EXCLUDE_FILES.has(file3)||file3.startsWith("plan-ledger.archived-"))continue;if(checkpointPlan&&PLAN_PROJECTION_FILES.has(file3))continue;if(fs162.existsSync(path276.join(swarmDir,file3)))overwriteSet.push(file3)}let backupNote="";if(overwriteSet.length>0){if(yes&&confirmToken)return"Error: pass either --yes or --confirm=<token>, not both.";let candidates=swarmOverwriteCandidates(directory,overwriteSet),scopeAnchor=candidates[0].path;if(!confirmToken&&!yes){let token2=issueConfirmToken(scopeAnchor,directory,{kind:ROLLBACK_PHASE_KIND,candidates});return[`⚠️ Rolling back to phase ${targetPhase} replaces ${overwriteSet.length} live .swarm/ entry/entries with checkpoint copies:`,...overwriteSet.slice(0,10).map((f)=>` - ${f}`),...overwriteSet.length>10?[` (+${overwriteSet.length-10} more)`]:[],"","\uD83D\uDD10 Nothing was restored. The replaced bytes are backed up to .swarm/rollback-backups/ once confirmed.",`Re-run /swarm rollback ${targetPhase} --confirm=${token2} (valid 15 minutes), or add --yes to confirm in one step.`].join(`
|
|
4169
4173
|
`)}let token=yes?issueConfirmToken(scopeAnchor,directory,{kind:ROLLBACK_PHASE_KIND,candidates}):confirmToken,verdict=consumeConfirmToken(scopeAnchor,directory,token,{kind:ROLLBACK_PHASE_KIND,candidates});if(!verdict.ok)return`Error: ${verdict.reason} \uD83D\uDD10 Nothing was restored.`;let backupEntries=[...overwriteSet];for(let file3 of PLAN_PROJECTION_FILES)if(!backupEntries.includes(file3)&&fs162.existsSync(path276.join(swarmDir,file3)))backupEntries.push(file3);let backup=backupSwarmStateBeforeReset(directory,"rollback",backupEntries,{backupsRoot:"rollback-backups"});if(!backup.backupDir||backup.copied.length<backupEntries.length)return`Error: backup incomplete (${backup.copied.length}/${backupEntries.length} at-risk entr(ies) copied) — rollback refused so nothing was replaced.${backup.warnings.length>0?` Warnings: ${backup.warnings.join("; ")}`:""} \uD83D\uDD10 Nothing was restored.`;if(backupNote=`; replaced bytes backed up to ${path276.relative(directory,backup.backupDir)}`,backup.warnings.length>0)backupNote+=`; warnings: ${backup.warnings.join("; ")}`}let successes=[],failures=[],warnings=[];for(let file3 of checkpointFiles){if(EXCLUDE_FILES.has(file3)||file3.startsWith("plan-ledger.archived-"))continue;if(checkpointPlan&&PLAN_PROJECTION_FILES.has(file3))continue;let src=path276.join(checkpointDir,file3),dest=path276.join(swarmDir,file3);try{fs162.cpSync(src,dest,{recursive:!0,force:!0}),successes.push(file3)}catch(error93){failures.push({file:file3,error:error93.message})}}if(resetSwarmArtifactCache(),failures.length>0)return[`Rollback partially completed. Successfully restored ${successes.length} files.`,`Failed on ${failures.length} files:`,...failures.map((f)=>` - ${f.file}: ${f.error}`),"","Some files could not be restored. The .swarm/ directory may be in an inconsistent state.","Check permissions and disk space, then retry the rollback."].join(`
|
|
@@ -4304,7 +4308,7 @@ ${message}
|
|
|
4304
4308
|
`+`INSTRUCTIONS: Retain ONLY the system prompt, the current task context, and the last ${preserveLastN} conversation turns. Discard everything else. If you cannot complete the current task in the remaining context, escalate to the user.
|
|
4305
4309
|
[/CONTEXT COMPACTION]`}function createCompactionService(config3,directory,injectMessage){return{toolAfter:async(_input,_output)=>{if(!config3.enabled)return;let budgetPct=getFinalPromptPressure(_input.sessionID)?.pct??getSessionBudgetPct(_input.sessionID);if(budgetPct<=0)return;let sessionId=_input.sessionID,state2=getSessionState(sessionId);try{if(budgetPct>=config3.emergencyThreshold&&budgetPct>state2.lastEmergencyAt+5){state2.lastEmergencyAt=budgetPct,state2.emergencyCount++;let msg=buildEmergencyMessage(budgetPct,config3.preserveLastNTurns);await appendSnapshot(directory,"emergency",budgetPct,msg),state2.lastSnapshotAt=new Date().toISOString(),injectMessage(sessionId,msg);return}if(budgetPct>=config3.reflectionThreshold&&budgetPct>state2.lastReflectionAt+5){state2.lastReflectionAt=budgetPct,state2.reflectionCount++;let msg=buildReflectionMessage(budgetPct);await appendSnapshot(directory,"reflection",budgetPct,msg),state2.lastSnapshotAt=new Date().toISOString(),injectMessage(sessionId,msg);return}if(budgetPct>=config3.observationThreshold&&budgetPct>state2.lastObservationAt+5){state2.lastObservationAt=budgetPct,state2.observationCount++;let msg=buildObservationMessage(budgetPct);await appendSnapshot(directory,"observation",budgetPct,msg),state2.lastSnapshotAt=new Date().toISOString(),injectMessage(sessionId,msg)}}catch{}}}}function getCompactionMetrics(sessionId){if(sessionId){let state2=getSessionState(sessionId);return{compactionCount:state2.observationCount+state2.reflectionCount+state2.emergencyCount,lastSnapshotAt:state2.lastSnapshotAt}}let total=0,lastSnapshot=null;for(let state2 of sessionStates.values())if(total+=state2.observationCount+state2.reflectionCount+state2.emergencyCount,state2.lastSnapshotAt&&(!lastSnapshot||state2.lastSnapshotAt>lastSnapshot))lastSnapshot=state2.lastSnapshotAt;return{compactionCount:total,lastSnapshotAt:lastSnapshot}}var sessionStates,MAX_TRACKED_COMPACTION_SESSIONS=500,MAX_CONTEXT_SNAPSHOT_BYTES=65536,MAX_CONTEXT_SNAPSHOT_ENTRIES=1e5;var init_compaction_service=__esm(()=>{init_caps();init_jsonl_cap();init_state();sessionStates=new Map});import*as fs165 from"node:fs";import*as path288 from"node:path";function extractDecisionsFromContext(contextContent){return extractContextDecisions(contextContent)}function isDecisionStale(decision,currentPhase,threshold){if(decision.phase===null)return!decision.confirmed;let phaseDiff=currentPhase-decision.phase;if(phaseDiff>=threshold)return!0;if(phaseDiff===0&&!decision.confirmed)return!0;return!1}function classifyPolarity(textLower,positiveKeywords,negativeKeywords){if(negativeKeywords.some((k)=>textLower.includes(k)))return"negative";if(positiveKeywords.some((k)=>textLower.includes(k)))return"positive";return null}function findContradictions(decisions){let signals=[],contradictionPairs=[[["use","using","use ","adopt","implement","enable"],["not use","don't use","do not use","avoid","disable","remove"]],[["keep","retain","preserve"],["remove","delete","drop","eliminate"]],[["include","add","incorporate"],["exclude","skip","omit"]],[["require","mandatory","must"],["optional","skip","can skip"]],[["background","async"],["foreground","sync","synchronous"]]];for(let i=0;i<decisions.length;i++){let decisionA=decisions[i],textLower=decisionA.text.toLowerCase();for(let j=i+1;j<decisions.length;j++){let decisionB=decisions[j],textBLower=decisionB.text.toLowerCase();for(let[positiveKeywords,negativeKeywords]of contradictionPairs){let polarityA=classifyPolarity(textLower,positiveKeywords,negativeKeywords),polarityB=classifyPolarity(textBLower,positiveKeywords,negativeKeywords);if(polarityA==="positive"&&polarityB==="negative"||polarityA==="negative"&&polarityB==="positive"){let wordsA=textLower.split(/\s+/).slice(0,4).join(" "),wordsB=textBLower.split(/\s+/).slice(0,4).join(" ");if(wordsA.split(/\s+/).filter((w)=>w.length>2&&wordsB.includes(w)).length>0||wordsA.includes("file"))signals.push({id:`contradiction-${i}-${j}`,severity:"error",type:"contradiction",message:"Contradictory decisions detected",source:{file:"context.md",line:decisionA.line},relatedDecisions:[decisionA.text,decisionB.text],hint:"Review both decisions and clarify the intended approach."})}}}}return signals}function extractCurrentPhaseFromLegacy(planContent){if(!planContent)return null;let lines=planContent.split(`
|
|
4306
4310
|
`);for(let i=0;i<Math.min(30,lines.length);i++){let progressMatch=lines[i].trim().match(/^## Phase (\d+):?\s*(.*?)\s*\[IN PROGRESS\]/i);if(progressMatch)return parseInt(progressMatch[1],10)}for(let i=0;i<Math.min(5,lines.length);i++){let phaseMatch=lines[i].trim().match(/Phase:\s*(\d+)/i);if(phaseMatch)return parseInt(phaseMatch[1],10)}return null}async function analyzeDecisionDrift(directory,config3={}){let effectiveConfig={...DEFAULT_DRIFT_CONFIG,...config3},signals=[],analyzedAt=new Date().toISOString();try{let plan=await loadPlan(directory),currentPhase=plan?.current_phase??1;if(!plan){let legacyPhase=extractCurrentPhaseFromLegacy(await readSwarmFileAsync(directory,"plan.md")??"");if(legacyPhase!==null)currentPhase=legacyPhase}let contextPath=path288.join(directory,".swarm","context.md"),contextContent="";try{if(fs165.existsSync(contextPath))contextContent=fs165.readFileSync(contextPath,"utf-8")}catch(error93){return log("[DecisionDriftAnalyzer] context file read failed",{error:error93 instanceof Error?error93.message:String(error93)}),{hasDrift:!1,signals:[],summary:"",analyzedAt}}if(!contextContent)return{hasDrift:!1,signals:[],summary:"",analyzedAt};let decisions=extractDecisionsFromContext(contextContent);if(decisions.length===0)return{hasDrift:!1,signals:[],summary:"",analyzedAt};for(let decision of decisions)if(isDecisionStale(decision,currentPhase,effectiveConfig.staleThresholdPhases)){let hint;if(decision.phase!==null&&decision.phase<currentPhase)hint=`Decision was from Phase ${decision.phase}, current is Phase ${currentPhase}.`;else if(!decision.confirmed)hint="Decision has not been confirmed. Consider confirming or revisiting.";signals.push({id:`stale-${decision.line}`,severity:decision.phase!==null&&decision.phase<currentPhase?"warning":"warning",type:"stale",message:`Stale decision: "${decision.text.substring(0,50)}${decision.text.length>50?"...":""}"`,source:{file:"context.md",line:decision.line},hint})}if(effectiveConfig.detectContradictions){let contradictions=findContradictions(decisions);signals.push(...contradictions)}let limitedSignals=signals.slice(0,effectiveConfig.maxSignals),summary=buildDriftSummary(limitedSignals);return{hasDrift:limitedSignals.length>0,signals:limitedSignals,summary,analyzedAt}}catch(error93){return log("[DecisionDriftAnalyzer] drift analysis failed",{error:error93 instanceof Error?error93.message:String(error93)}),{hasDrift:!1,signals:[],summary:"",analyzedAt}}}function buildDriftSummary(signals){if(signals.length===0)return"";let warnings=signals.filter((s)=>s.severity==="warning"),errors5=signals.filter((s)=>s.severity==="error"),lines=["[SWARM DECISION DRIFT]"];if(errors5.length>0){lines.push(`⚠️ ${errors5.length} contradiction(s) detected:`);for(let err of errors5.slice(0,2)){let related=err.relatedDecisions?` (${err.relatedDecisions[0].substring(0,30)}... vs ${err.relatedDecisions[1].substring(0,30)}...)`:"";lines.push(` - ${err.type}: ${err.message}${related}`)}}if(warnings.length>0){lines.push(`\uD83D\uDCA1 ${warnings.length} stale decision(s) found:`);for(let warn2 of warnings.slice(0,3)){let hint=warn2.hint?` - ${warn2.hint}`:"";lines.push(` - ${warn2.message.substring(0,60)}${hint}`)}}return lines.push("See .swarm/context.md for details."),lines.join(`
|
|
4307
|
-
`)}function formatDriftForContext(result){if(!result.hasDrift||!result.summary)return"";let maxLength=600,summary=result.summary;if(summary.length>maxLength)summary=`${summary.substring(0,maxLength-3)}...`;return summary}var DEFAULT_DRIFT_CONFIG;var init_decision_drift_analyzer=__esm(()=>{init_utils2();init_manager();init_utils();DEFAULT_DRIFT_CONFIG={staleThresholdPhases:1,detectContradictions:!0,maxSignals:5}});import*as fsSync21 from"node:fs";import{readFile as readFile54}from"node:fs/promises";import*as path289 from"node:path";function getTelemetryCostSummary(directory){let key2=canonicalRootKeyFresh(directory),stamp=readTelemetryCostStamp(directory),cached3=telemetryCostSummaryCache.get(key2);if(cached3&&cached3.stamp===stamp)return cached3.summary;let summary=_internals240.summarizeTelemetryCosts(directory);telemetryCostSummaryCache.set(key2,{stamp,summary});while(telemetryCostSummaryCache.size>MAX_TRACKED_TELEMETRY_COST_SUMMARIES){let oldest=telemetryCostSummaryCache.keys().next().value;if(oldest===void 0)break;telemetryCostSummaryCache.delete(oldest)}return summary}function readTelemetryCostStamp(directory){let swarmDir=path289.join(directory,".swarm");return[path289.join(swarmDir,"telemetry.jsonl.1"),path289.join(swarmDir,"telemetry.jsonl")].map((file3)=>{try{let stat23=fsSync21.statSync(file3);return stat23.isFile()?`${stat23.mtimeMs}:${stat23.ctimeMs}:${stat23.size}`:"missing"}catch{return"missing"}}).join("|")}async function collectBackgroundWorkStatus(directory){try{await maintainBackgroundDelegations(directory,{lockTimeoutMs:2000,reason:"status"})}catch{}let counts={pending:0,running:0,completed:0,consumed:0,stale:0,cancelled:0,rejected:0,error:0,ingestion_error:0},maintenance=readDelegationHealthArtifact(directory)?.maintenance??null,empty={counts,reservations:[],maintenance,source:"uncertain"},scan;try{scan=scanDelegationsForRecovery(directory)}catch(error93){return{...empty,uncertainty:`delegation recovery scan failed: ${error93 instanceof Error?error93.message:String(error93)}`}}if(scan.status==="uncertain")return{...empty,uncertainty:`delegation ledger over its recovery bound or corrupt: ${scan.reason}`};let reservationScan=scanBackgroundCoderReservationsForAdmission(directory);if(reservationScan.status==="uncertain")return{...empty,uncertainty:`coder reservation store unreadable: ${reservationScan.reason}`};for(let record3 of scan.owners)if(record3.status in counts)counts[record3.status]+=1;let now2=Date.now(),reservations=reservationScan.reservations.map((reservation)=>({reservationId:reservation.reservationId,planTaskId:reservation.planTaskId,generation:reservation.generation??1,state:reservation.state,leaseState:reservation.leaseExpiresAt===void 0?"protected-legacy":reservation.leaseExpiresAt>now2?"active":"expired",...reservation.leaseExpiresAt!==void 0?{leaseExpiresAt:reservation.leaseExpiresAt}:{}}));return{counts,reservations,maintenance,source:"validated-recovery"}}function formatLedgerBytes(bytes){if(bytes>=1048576)return`${Math.round(bytes/1048576*10)/10} MiB`;if(bytes>=1024)return`${Math.round(bytes/1024*10)/10} KiB`;return`${bytes} B`}function readSpecStalenessSnapshot(directory){try{let p=path289.join(directory,".swarm","spec-staleness.json");if(!fsSync21.existsSync(p))return{stale:!1};let raw=fsSync21.readFileSync(p,"utf-8"),parsed=JSON.parse(raw);return{stale:!0,reason:typeof parsed?.reason==="string"?parsed.reason:void 0,storedHash:typeof parsed?.specHash_plan==="string"?parsed.specHash_plan:void 0,currentHash:typeof parsed?.specHash_current==="string"||parsed?.specHash_current===null?parsed.specHash_current:void 0}}catch{return{stale:!1}}}function formatAgo(ms2){let seconds=Math.floor(ms2/1000);if(seconds<60)return`${seconds}s ago`;let minutes=Math.floor(seconds/60);if(minutes<60)return`${minutes}m ago`;let hours=Math.floor(minutes/60);if(hours<24)return`${hours}h ago`;return`${Math.floor(hours/24)}d ago`}async function collectDecisionDriftSnapshot(directory){try{if(loadPluginConfig(directory).automation?.capabilities?.decision_drift_detection===!1)return;let result=await analyzeDecisionDrift(directory),staleCount=result.signals.filter((s)=>s.type==="stale").length,contradictionCount=result.signals.filter((s)=>s.type==="contradiction").length;if(staleCount===0&&contradictionCount===0)return;let contextContent=await readSwarmFileAsync(directory,"context.md"),lastDecisionAt=latestDecisionTimestamp(contextContent);return lastDecisionAt?{staleCount,contradictionCount,lastDecisionAt}:{staleCount,contradictionCount}}catch{return}}function latestDecisionTimestamp(contextContent){if(!contextContent)return null;let latest=null;for(let decision of extractContextDecisions(contextContent))if(decision.timestamp&&(!latest||decision.timestamp>latest))latest=decision.timestamp;return latest}function formatDecisionDriftLines(drift){if(!drift)return null;if(drift.staleCount<=0&&drift.contradictionCount<=0)return null;let parts=[];if(drift.staleCount>0)parts.push(`${drift.staleCount} stale`);if(drift.contradictionCount>0)parts.push(`${drift.contradictionCount} contradictory`);let lastSuffix=drift.lastDecisionAt?` (last decision ${drift.lastDecisionAt})`:"",total=drift.staleCount+drift.contradictionCount;return[`**Decision drift detected**: ${parts.join(", ")} decision${total>1?"s":""}${lastSuffix}. See .swarm/context.md.`]}async function getStatusData(directory,agents,sessionId,options){let plan=await loadPlan(directory),status2;if(plan&&plan.migration_status!=="migration_failed"){let currentPhase=extractCurrentPhaseFromPlan(plan)||"Unknown",completedTasks=0,totalTasks=0;for(let phase of plan.phases)for(let task2 of phase.tasks)if(totalTasks++,task2.status==="completed")completedTasks++;let agentCount=Object.keys(agents).length,metrics=getCompactionMetrics();status2={hasPlan:!0,currentPhase,completedTasks,totalTasks,agentCount,isLegacy:!1,turboMode:hasActiveTurboMode(),contextBudgetPct:getDisplayBudget()?.pct??null,contextBudgetTokens:getDisplayBudget()?.tokens??null,compactionCount:metrics.compactionCount,lastSnapshotAt:metrics.lastSnapshotAt}}else{let planContent=await readSwarmFileAsync(directory,"plan.md");if(!planContent){let metrics=getCompactionMetrics();status2={hasPlan:!1,currentPhase:"Unknown",completedTasks:0,totalTasks:0,agentCount:Object.keys(agents).length,isLegacy:!0,turboMode:hasActiveTurboMode(),contextBudgetPct:getDisplayBudget()?.pct??null,contextBudgetTokens:getDisplayBudget()?.tokens??null,compactionCount:metrics.compactionCount,lastSnapshotAt:metrics.lastSnapshotAt}}else{let currentPhase=extractCurrentPhase(planContent)||"Unknown",completedTasks=(planContent.match(/^- \[x\]/gm)||[]).length,incompleteTasks=(planContent.match(/^- \[ \]/gm)||[]).length,totalTasks=completedTasks+incompleteTasks,agentCount=Object.keys(agents).length,metrics=getCompactionMetrics();status2={hasPlan:!0,currentPhase,completedTasks,totalTasks,agentCount,isLegacy:!0,turboMode:hasActiveTurboMode(),contextBudgetPct:getDisplayBudget()?.pct??null,contextBudgetTokens:getDisplayBudget()?.tokens??null,compactionCount:metrics.compactionCount,lastSnapshotAt:metrics.lastSnapshotAt}}}let drift=readSpecStalenessSnapshot(directory);if(drift.stale)status2.specStale=!0,status2.specStaleReason=drift.reason,status2.specStaleStoredHash=drift.storedHash,status2.specStaleCurrentHash=drift.currentHash;else if(plan&&plan._specStale)status2.specStale=!0,status2.specStaleReason=plan._specStaleReason;status2.decisionDrift=await collectDecisionDriftSnapshot(directory),status2.recentEscalations=await readRecentEscalations(directory),status2.pendingProposals=await countProposals(directory),status2.unactionableQueueDepth=await safeLineCount(resolveUnactionablePath(directory)),status2.insightCandidatesPending=await countInsightCandidatesPending(directory);try{status2.consensusReports=await countConsensusReportFiles(directory)}catch{status2.consensusReports=0}try{status2.delegationLedgerHealth=collectDelegationLedgerHealth(directory,{ledgerLimitBytes:MAX_RECOVERY_LEDGER_BYTES,lowWaterBytes:DELEGATION_COMPACTION_LOW_WATER_BYTES,highWaterBytes:DELEGATION_COMPACTION_HIGH_WATER_BYTES})??void 0}catch{status2.delegationLedgerHealth=void 0}try{let snapshot=await readLearningHealth(directory);status2.learningHealth={activeAlarms:snapshot.activeAlarms.map((alarm)=>({alarm:alarm.alarm,severity:alarm.severity,scopeClass:alarm.scopeClass,scopeRef:alarm.scopeRef,ageMs:alarm.ageMs,coverageFacts:alarm.coverageFacts,transitionCount:alarm.transitionCount})),totalTransitions:snapshot.totalTransitions}}catch{status2.learningHealth=void 0}if(options?.backgroundSubagents??(()=>{try{return loadPluginConfig(directory)?.hooks?.background_subagents===!0}catch{return!1}})())status2.backgroundWork=await collectBackgroundWorkStatus(directory);try{let pointer=readLinkPointer(directory);if(pointer)status2.cohort={linked:!0,linkId:pointer.linkId,cohortId:pointer.cohortId,identitySource:pointer.identitySource,degraded:pointer.degraded,sharedRoot:resolveLinkDir(pointer.linkId),generation:pointer.generation};else status2.cohort={linked:!1}}catch{status2.cohort={linked:!1}}try{let memoryPointer=readMemoryLinkPointer(directory),provider,configFingerprintMatch;try{let memoryConfig=MemoryConfigSchema.parse(loadPluginConfig(directory).memory??{});if(provider=memoryConfig.provider,memoryPointer){let cohortConfigPath=path289.join(resolveLinkDir(memoryPointer.linkId),"memory","memory-cohort-config.json");if(fsSync21.existsSync(cohortConfigPath)){let stored=JSON.parse(fsSync21.readFileSync(cohortConfigPath,"utf-8"));if(classifyStoredFingerprintAlgorithmVersion(stored.algorithm_version).status==="comparable"&&typeof stored.fingerprint==="string"){let expected=computeMemoryCohortFingerprint(buildMemoryCohortFingerprintInput(memoryConfig));configFingerprintMatch=stored.fingerprint===expected}}}}catch{}if(memoryPointer)status2.memoryCohort={linked:!0,linkId:memoryPointer.linkId,cohortId:memoryPointer.cohortId,identitySource:memoryPointer.identitySource,degraded:memoryPointer.degraded,sharedRoot:resolveLinkDir(memoryPointer.linkId),generation:memoryPointer.generation,provider,configFingerprintMatch};else status2.memoryCohort={linked:!1,provider}}catch{status2.memoryCohort={linked:!1}}if(status2.fullAutoActive=_internals240.hasActiveFullAuto(),status2.fullAutoActive){let sid=_internals240.getActiveFullAutoSessionID();if(sid){let runState=_internals240.loadFullAutoRunState(directory,sid);if(runState?.lastEscalation)status2.fullAutoEscalation={reason:runState.lastEscalation.reason,interactionCount:runState.lastEscalation.interactionCount,deadlockCount:runState.lastEscalation.deadlockCount,phase:runState.lastEscalation.phase}}}if(sessionId){let timestamp=getLastHeartbeat(sessionId);if(timestamp!==void 0){let agoMs=Date.now()-timestamp;status2.lastActivity={sessionId,timestamp,agoMs,agoLabel:formatAgo(agoMs)}}else status2.lastActivity={sessionId,timestamp:0,agoMs:null,agoLabel:"never"}}status2=enrichWithLeanTurbo(status2,directory);try{let costs=getTelemetryCostSummary(directory);status2.costs={totalCostUsd:costs.total_cost_usd,delegations:costs.delegations,unavailableDelegations:costs.unavailable_delegations,evidenceStatus:costs.evidence_status,conflictCount:costs.conflict_count,joinMissCount:costs.join_miss_count,telemetryErrorCount:costs.telemetry_error_count}}catch{}let coordination=getSnapshotCoordinationStatus(directory);if(coordination.state!=="idle"&&coordination.state!=="succeeded")status2.coordination=coordination;return status2}function renderCoordinationStatus(status2){return["",`**SQLite coordination**: ${status2.state}${status2.settled?" (settled)":" (unsettled)"}`,...status2.error?[` - ${status2.error}`]:[]," - Recovery: `/swarm recover --coordination` (an unsettled timed-out attempt must finish before retry)"]}function enrichWithLeanTurbo(status2,directory){let turboMode=hasActiveTurboMode(),leanActive=_internals240.hasActiveLeanTurbo(),turboStrategy="off";if(leanActive)turboStrategy="lean";else if(turboMode)turboStrategy="standard";status2.turboStrategy=turboStrategy;try{let recoveryRecords=listRecoveryRecords(directory);if(recoveryRecords.length>0)status2.leanPreservedRecoveryWorktrees=recoveryRecords.map((r)=>({laneId:r.laneId,status:r.status,worktreePath:r.worktreePath,reason:r.reason,replayHint:r.replayHint}))}catch{}if(!leanActive)return status2;let leanSessionID=null;for(let[sessionId,session]of swarmState.agentSessions)if(session.turboStrategy==="lean"&&session.leanTurboActive===!0){leanSessionID=sessionId;break}if(leanSessionID){let runState=_internals240.loadLeanTurboRunState(directory,leanSessionID);if(runState){if(status2.leanTurboPhase=runState.phase,status2.leanMaxParallelCoders=runState.maxParallelCoders,status2.leanPauseReason=runState.pauseReason,!Array.isArray(runState.lanes))runState.lanes=[];let activeLanes=0,completedLanes=0;for(let lane of runState.lanes){if(lane.status==="running")activeLanes++;if(lane.status==="completed")completedLanes++}if(status2.leanActiveLaneCount=activeLanes,status2.leanCompletedLanes=completedLanes,!Array.isArray(runState.degradedTasks))runState.degradedTasks=[],status2.leanDegradedTasks=0;if(runState.degradedTasks.length>0){status2.leanDegradedTasks=runState.degradedTasks.length;let summaryParts=[];for(let dt of runState.degradedTasks)summaryParts.push(`${dt.taskId} (${dt.reason})`);status2.leanDegradationSummary=summaryParts.join("; ")}}}return status2}function formatStatusMarkdown(status2){let lines=["## Swarm Status","",`**Current Phase**: ${status2.currentPhase}`,`**Tasks**: ${status2.completedTasks}/${status2.totalTasks} complete`,`**Agents**: ${status2.agentCount} registered`];if(status2.coordination)lines.push(...renderCoordinationStatus(status2.coordination));if(status2.costs&&status2.costs.delegations>0){let evidence2=status2.costs.evidenceStatus==="complete"?"complete evidence":`inconclusive evidence (${status2.costs.unavailableDelegations} unavailable, ${status2.costs.conflictCount} conflicts, ${status2.costs.joinMissCount} join misses, ${status2.costs.telemetryErrorCount} telemetry errors)`;lines.push("",`**Cost**: $${status2.costs.totalCostUsd.toFixed(6)} across ${status2.costs.delegations} delegations — ${evidence2}`)}if(status2.lastActivity){let label=status2.lastActivity.agoLabel,annotation=status2.lastActivity.agoLabel!=="never"&&status2.lastActivity.agoMs!==null&&status2.lastActivity.agoMs>120000?" ⚠️ possibly stalled":"";lines.push(""),lines.push(`**Last activity:** ${label}${annotation}`)}if(status2.specStale){let reason=status2.specStaleReason??"spec.md changed since plan saved",stored=status2.specStaleStoredHash??"unknown",current=status2.specStaleCurrentHash??"(spec.md missing)";lines.push("",`**Spec drift detected**: ${reason} (stored: ${stored}, current: ${current})`,"Run `/swarm clarify` to enter spec repair mode. Clarify alone does not clear drift: rewrite the spec so recovery can reconcile it, or run `/swarm acknowledge-spec-drift` to dismiss.")}let decisionDriftLines=formatDecisionDriftLines(status2.decisionDrift);if(decisionDriftLines)lines.push("",...decisionDriftLines);if(status2.turboStrategy&&status2.turboStrategy!=="off")if(lines.push(""),status2.turboStrategy==="lean"){let parts=["lean"];if(status2.leanTurboPhase!==void 0)parts.push(`Phase ${status2.leanTurboPhase}`);if(status2.leanActiveLaneCount!==void 0){let totalLanes=(status2.leanActiveLaneCount??0)+(status2.leanCompletedLanes??0);parts.push(`${status2.leanActiveLaneCount}/${totalLanes} lanes active`)}if(status2.leanDegradedTasks!==void 0&&status2.leanDegradedTasks>0)parts.push(`${status2.leanDegradedTasks} degraded`);if(lines.push(`**Turbo**: ${parts.join(", ")}`),status2.leanDegradationSummary)lines.push(` - ${status2.leanDegradationSummary}`);if(status2.leanPauseReason)lines.push(`**Lean paused**: ${status2.leanPauseReason}`)}else lines.push("**Turbo**: standard");else if(status2.turboStrategy===void 0&&status2.turboMode===!0)lines.push(""),lines.push("**TURBO MODE**: active");if(status2.leanPreservedRecoveryWorktrees&&status2.leanPreservedRecoveryWorktrees.length>0){lines.push(""),lines.push(`**Preserved recovery worktrees**: ${status2.leanPreservedRecoveryWorktrees.length} lane(s) preserved for manual merge-back recovery`);for(let w of status2.leanPreservedRecoveryWorktrees)lines.push(` - ${w.laneId} (${w.status}): ${w.reason} — \`${w.replayHint}\``)}if(status2.fullAutoActive){if(lines.push(""),lines.push("**Full-Auto**: active"),status2.fullAutoEscalation){let e=status2.fullAutoEscalation,phaseStr=e.phase!==void 0?` | Phase ${e.phase}`:"";lines.push(` - Escalation: ${e.reason} (interactions=${e.interactionCount}, deadlocks=${e.deadlockCount}${phaseStr})`)}}if(status2.contextBudgetPct!==null&&status2.contextBudgetPct>0){let pct=status2.contextBudgetPct.toFixed(1),budgetTokens=status2.contextBudgetTokens;if(budgetTokens!==void 0&&budgetTokens!==null&&budgetTokens>0){let est=Math.round(status2.contextBudgetPct/100*budgetTokens);lines.push("",`**Swarm injection footprint**: ${pct}% of model window (intermediate measurement; est. ${est.toLocaleString()} / ${budgetTokens.toLocaleString()} tokens)`)}else lines.push("",`**Swarm injection footprint**: ${pct}% of model window (intermediate measurement)`);let finalPressure=getDisplayFinalPromptPressure();if(finalPressure&&finalPressure.pct>0)lines.push(`**Prompt pressure (final)**: ${finalPressure.pct.toFixed(1)}% estimated (est. ${finalPressure.usedTokens.toLocaleString()} / ${finalPressure.limitTokens.toLocaleString()} tokens; ${finalPressure.estimatorSource}${finalPressure.providerReported?"; provider-reported":""})`);if(status2.compactionCount>0)lines.push(`**Compaction events**: ${status2.compactionCount} triggered`);if(status2.lastSnapshotAt)lines.push(`**Last snapshot**: ${status2.lastSnapshotAt}`)}if(status2.recentEscalations&&status2.recentEscalations.length>0){lines.push("","**Recently Escalated (last 7 days)**:");for(let e of status2.recentEscalations)lines.push(` - ${e.entry_id} (${e.from}→${e.to}) reason=${e.reason}`)}let proposals=status2.pendingProposals??0,unactionable=status2.unactionableQueueDepth??0,insights=status2.insightCandidatesPending??0,consensusReports=status2.consensusReports??0;if(proposals>0||unactionable>0||insights>0||consensusReports>0){if(lines.push("","**Learning Queues**:"),proposals>0)lines.push(` - Pending proposals: ${proposals} (review with \`/swarm skill list\`)`);if(unactionable>0)lines.push(` - Unactionable queue: ${unactionable} (inspect with \`/swarm knowledge unactionable\`)`);if(insights>0)lines.push(` - Insight candidates: ${insights} (consumed at phase end)`);if(consensusReports>0)lines.push(` - Consensus reports: ${consensusReports} (read under \`.swarm/evolution/consensus/\`; each holds proposals-only recommendations)`)}if(status2.learningHealth){lines.push("","**Learning Health**:");let active=status2.learningHealth.activeAlarms;if(active.length===0)lines.push(` - ✅ no active learning-health alarms (${status2.learningHealth.totalTransitions} transitions recorded)`);else{for(let alarm of active){let ageMinutes=Math.floor(alarm.ageMs/60000);lines.push(` - ⚠ ${alarm.severity}: ${alarm.alarm} [${alarm.scopeClass} ${alarm.scopeRef}] age ${ageMinutes}m, coverage ${alarm.coverageFacts} facts (${alarm.transitionCount} transitions)`)}lines.push(" - run `/swarm diagnose` for the learning-health check detail")}}if(status2.cohort?.linked){if(lines.push("","**Knowledge Cohort**:"),lines.push(` - \uD83D\uDD17 Linked to shared store "${status2.cohort.linkId}"`),status2.cohort.cohortId)lines.push(` cohort: ${status2.cohort.cohortId}`);if(status2.cohort.identitySource)lines.push(` identity: ${status2.cohort.identitySource}`);if(status2.cohort.degraded)lines.push(" ⚠ degraded (machine-local, not portable across machines)");if(status2.cohort.sharedRoot)lines.push(` shared at: ${status2.cohort.sharedRoot}`);if(status2.cohort.generation!==void 0)lines.push(` generation: ${status2.cohort.generation}`)}else lines.push("","**Knowledge Cohort**: local (not linked — run `/swarm link` to share across worktrees)");if(status2.memoryCohort?.linked){if(lines.push("","**Memory Cohort**:"),lines.push(` - \uD83D\uDD17 Memory shared across linked worktrees "${status2.memoryCohort.linkId}"`),status2.memoryCohort.cohortId)lines.push(` cohort: ${status2.memoryCohort.cohortId}`);if(status2.memoryCohort.identitySource)lines.push(` identity: ${status2.memoryCohort.identitySource}`);if(status2.memoryCohort.degraded)lines.push(" ⚠ degraded (machine-local, not portable across machines)");if(status2.memoryCohort.sharedRoot)lines.push(` shared at: ${status2.memoryCohort.sharedRoot}/memory`);if(status2.memoryCohort.generation!==void 0)lines.push(` generation: ${status2.memoryCohort.generation}`);if(status2.memoryCohort.provider)lines.push(` provider: ${status2.memoryCohort.provider}`);if(status2.memoryCohort.configFingerprintMatch===!1)lines.push(" ⚠ config fingerprint mismatch — provider/embedding/redaction config differs across cohort members");else if(status2.memoryCohort.configFingerprintMatch===!0)lines.push(" config: ✅ fingerprint matches cohort")}else lines.push("","**Memory Cohort**: local (not linked — run `/swarm memory link` to share memory across worktrees; requires `memory.link.enabled: true`)");let delegationHealth=status2.delegationLedgerHealth;if(delegationHealth){if(lines.push("","**Background Delegations**:"),lines.push(` - Ledger tail: ${formatLedgerBytes(delegationHealth.ledger.bytes)} / ${formatLedgerBytes(delegationHealth.ledger.limitBytes)} recovery bound (${delegationHealth.ledger.pressurePct}% — ${delegationHealth.ledger.band})`),delegationHealth.checkpoint){let checkpoint2=delegationHealth.checkpoint;lines.push(` - Checkpoint #${checkpoint2.sequence}: ${checkpoint2.liveRecords} live records, ${checkpoint2.closedSummaries} archived summaries (${formatLedgerBytes(checkpoint2.bytes)}, ${new Date(checkpoint2.createdAt).toISOString()})`)}else lines.push(" - Checkpoint: none (full-history recovery)");if(delegationHealth.recovery){let recovery=delegationHealth.recovery;lines.push(` - Recovery: ${recovery.source} (${recovery.ok?"ok":`FAILED: ${recovery.reason??"uncertain"}`})`)}if(delegationHealth.lastUncertainty){let uncertainty=delegationHealth.lastUncertainty;if(lines.push(` - ⚠ Last uncertainty (${new Date(uncertainty.at).toISOString()}, ${uncertainty.source}): ${uncertainty.reason}`),uncertainty.repairHint)lines.push(` repair: ${uncertainty.repairHint}`)}let counts=delegationHealth.counts;if(counts.activeOwners>0||counts.pendingAdvisories>0||counts.lateTerminals>0||counts.orphanWorktreeOwners>0)lines.push(` - Live set: ${counts.activeOwners} active owners, ${counts.pendingAdvisories} pending advisories, ${counts.lateTerminals} late terminals, ${counts.orphanWorktreeOwners} unsettled worktree owners`)}let backgroundWork=status2.backgroundWork;if(backgroundWork)lines.push(...renderBackgroundWorkLines(backgroundWork));return lines.join(`
|
|
4311
|
+
`)}function formatDriftForContext(result){if(!result.hasDrift||!result.summary)return"";let maxLength=600,summary=result.summary;if(summary.length>maxLength)summary=`${summary.substring(0,maxLength-3)}...`;return summary}var DEFAULT_DRIFT_CONFIG;var init_decision_drift_analyzer=__esm(()=>{init_utils2();init_manager();init_utils();DEFAULT_DRIFT_CONFIG={staleThresholdPhases:1,detectContradictions:!0,maxSignals:5}});import*as fsSync21 from"node:fs";import{readFile as readFile54}from"node:fs/promises";import*as path289 from"node:path";function getTelemetryCostSummary(directory){let key2=canonicalRootKeyFresh(directory),stamp=readTelemetryCostStamp(directory),cached3=telemetryCostSummaryCache.get(key2);if(cached3&&cached3.stamp===stamp)return cached3.summary;let summary=_internals240.summarizeTelemetryCosts(directory);telemetryCostSummaryCache.set(key2,{stamp,summary});while(telemetryCostSummaryCache.size>MAX_TRACKED_TELEMETRY_COST_SUMMARIES){let oldest=telemetryCostSummaryCache.keys().next().value;if(oldest===void 0)break;telemetryCostSummaryCache.delete(oldest)}return summary}function readTelemetryCostStamp(directory){let swarmDir=path289.join(directory,".swarm");return[path289.join(swarmDir,"telemetry.jsonl.1"),path289.join(swarmDir,"telemetry.jsonl")].map((file3)=>{try{let stat23=fsSync21.statSync(file3);return stat23.isFile()?`${stat23.mtimeMs}:${stat23.ctimeMs}:${stat23.size}`:"missing"}catch{return"missing"}}).join("|")}async function collectBackgroundWorkStatus(directory){try{await maintainBackgroundDelegations(directory,{lockTimeoutMs:2000,reason:"status"})}catch{}let counts={pending:0,running:0,completed:0,consumed:0,stale:0,cancelled:0,rejected:0,error:0,ingestion_error:0},maintenance=readDelegationHealthArtifact(directory)?.maintenance??null,empty={counts,reservations:[],maintenance,source:"uncertain"},scan;try{scan=scanDelegationsForRecovery(directory)}catch(error93){return{...empty,uncertainty:`delegation recovery scan failed: ${error93 instanceof Error?error93.message:String(error93)}`}}if(scan.status==="uncertain")return{...empty,uncertainty:`delegation ledger over its recovery bound or corrupt: ${scan.reason}`};let reservationScan=scanBackgroundCoderReservationsForAdmission(directory);if(reservationScan.status==="uncertain")return{...empty,uncertainty:`coder reservation store unreadable: ${reservationScan.reason}`};for(let record3 of scan.owners)if(record3.status in counts)counts[record3.status]+=1;let now2=Date.now(),reservations=reservationScan.reservations.map((reservation)=>({reservationId:reservation.reservationId,planTaskId:reservation.planTaskId,generation:reservation.generation??1,state:reservation.state,leaseState:reservation.leaseExpiresAt===void 0?"protected-legacy":reservation.leaseExpiresAt>now2?"active":"expired",...reservation.leaseExpiresAt!==void 0?{leaseExpiresAt:reservation.leaseExpiresAt}:{}}));return{counts,reservations,maintenance,source:"validated-recovery"}}function formatLedgerBytes(bytes){if(bytes>=1048576)return`${Math.round(bytes/1048576*10)/10} MiB`;if(bytes>=1024)return`${Math.round(bytes/1024*10)/10} KiB`;return`${bytes} B`}function readSpecStalenessSnapshot(directory){try{let p=path289.join(directory,".swarm","spec-staleness.json");if(!fsSync21.existsSync(p))return{stale:!1};let raw=fsSync21.readFileSync(p,"utf-8"),parsed=JSON.parse(raw);return{stale:!0,reason:typeof parsed?.reason==="string"?parsed.reason:void 0,storedHash:typeof parsed?.specHash_plan==="string"?parsed.specHash_plan:void 0,currentHash:typeof parsed?.specHash_current==="string"||parsed?.specHash_current===null?parsed.specHash_current:void 0}}catch{return{stale:!1}}}function formatAgo(ms2){let seconds=Math.floor(ms2/1000);if(seconds<60)return`${seconds}s ago`;let minutes=Math.floor(seconds/60);if(minutes<60)return`${minutes}m ago`;let hours=Math.floor(minutes/60);if(hours<24)return`${hours}h ago`;return`${Math.floor(hours/24)}d ago`}async function collectDecisionDriftSnapshot(directory){try{if(loadPluginConfig(directory).automation?.capabilities?.decision_drift_detection===!1)return;let result=await analyzeDecisionDrift(directory),staleCount=result.signals.filter((s)=>s.type==="stale").length,contradictionCount=result.signals.filter((s)=>s.type==="contradiction").length;if(staleCount===0&&contradictionCount===0)return;let contextContent=await readSwarmFileAsync(directory,"context.md"),lastDecisionAt=latestDecisionTimestamp(contextContent);return lastDecisionAt?{staleCount,contradictionCount,lastDecisionAt}:{staleCount,contradictionCount}}catch{return}}function latestDecisionTimestamp(contextContent){if(!contextContent)return null;let latest=null;for(let decision of extractContextDecisions(contextContent))if(decision.timestamp&&(!latest||decision.timestamp>latest))latest=decision.timestamp;return latest}function formatDecisionDriftLines(drift){if(!drift)return null;if(drift.staleCount<=0&&drift.contradictionCount<=0)return null;let parts=[];if(drift.staleCount>0)parts.push(`${drift.staleCount} stale`);if(drift.contradictionCount>0)parts.push(`${drift.contradictionCount} contradictory`);let lastSuffix=drift.lastDecisionAt?` (last decision ${drift.lastDecisionAt})`:"",total=drift.staleCount+drift.contradictionCount;return[`**Decision drift detected**: ${parts.join(", ")} decision${total>1?"s":""}${lastSuffix}. See .swarm/context.md.`]}async function getStatusData(directory,agents,sessionId,options){let plan=await loadPlan(directory),status2;if(plan&&plan.migration_status!=="migration_failed"){let currentPhase=extractCurrentPhaseFromPlan(plan)||"Unknown",completedTasks=0,totalTasks=0;for(let phase of plan.phases)for(let task2 of phase.tasks)if(totalTasks++,task2.status==="completed")completedTasks++;let agentCount=Object.keys(agents).length,metrics=getCompactionMetrics();status2={hasPlan:!0,currentPhase,completedTasks,totalTasks,agentCount,isLegacy:!1,turboMode:hasActiveTurboMode(),contextBudgetPct:getDisplayBudget()?.pct??null,contextBudgetTokens:getDisplayBudget()?.tokens??null,compactionCount:metrics.compactionCount,lastSnapshotAt:metrics.lastSnapshotAt}}else{let planContent=await readSwarmFileAsync(directory,"plan.md");if(!planContent){let metrics=getCompactionMetrics();status2={hasPlan:!1,currentPhase:"Unknown",completedTasks:0,totalTasks:0,agentCount:Object.keys(agents).length,isLegacy:!0,turboMode:hasActiveTurboMode(),contextBudgetPct:getDisplayBudget()?.pct??null,contextBudgetTokens:getDisplayBudget()?.tokens??null,compactionCount:metrics.compactionCount,lastSnapshotAt:metrics.lastSnapshotAt}}else{let currentPhase=extractCurrentPhase(planContent)||"Unknown",completedTasks=(planContent.match(/^- \[x\]/gm)||[]).length,incompleteTasks=(planContent.match(/^- \[ \]/gm)||[]).length,totalTasks=completedTasks+incompleteTasks,agentCount=Object.keys(agents).length,metrics=getCompactionMetrics();status2={hasPlan:!0,currentPhase,completedTasks,totalTasks,agentCount,isLegacy:!0,turboMode:hasActiveTurboMode(),contextBudgetPct:getDisplayBudget()?.pct??null,contextBudgetTokens:getDisplayBudget()?.tokens??null,compactionCount:metrics.compactionCount,lastSnapshotAt:metrics.lastSnapshotAt}}}let drift=readSpecStalenessSnapshot(directory);if(drift.stale)status2.specStale=!0,status2.specStaleReason=drift.reason,status2.specStaleStoredHash=drift.storedHash,status2.specStaleCurrentHash=drift.currentHash;else if(plan&&plan._specStale)status2.specStale=!0,status2.specStaleReason=plan._specStaleReason;status2.decisionDrift=await collectDecisionDriftSnapshot(directory),status2.recentEscalations=await readRecentEscalations(directory),status2.pendingProposals=await countProposals(directory),status2.unactionableQueueDepth=await safeLineCount(resolveUnactionablePath(directory)),status2.insightCandidatesPending=await countInsightCandidatesPending(directory);try{status2.consensusReports=await countConsensusReportFiles(directory)}catch{status2.consensusReports=0}try{status2.delegationLedgerHealth=collectDelegationLedgerHealth(directory,{ledgerLimitBytes:MAX_RECOVERY_LEDGER_BYTES,lowWaterBytes:DELEGATION_COMPACTION_LOW_WATER_BYTES,highWaterBytes:DELEGATION_COMPACTION_HIGH_WATER_BYTES})??void 0}catch{status2.delegationLedgerHealth=void 0}try{let snapshot=await readLearningHealth(directory);status2.learningHealth={activeAlarms:snapshot.activeAlarms.map((alarm)=>({alarm:alarm.alarm,severity:alarm.severity,scopeClass:alarm.scopeClass,scopeRef:alarm.scopeRef,ageMs:alarm.ageMs,coverageFacts:alarm.coverageFacts,transitionCount:alarm.transitionCount})),totalTransitions:snapshot.totalTransitions}}catch{status2.learningHealth=void 0}if(options?.backgroundSubagents??(()=>{try{return loadPluginConfig(directory)?.hooks?.background_subagents===!0}catch{return!1}})())status2.backgroundWork=await collectBackgroundWorkStatus(directory);try{let pointer=readLinkPointer(directory);if(pointer)status2.cohort={linked:!0,linkId:pointer.linkId,cohortId:pointer.cohortId,identitySource:pointer.identitySource,degraded:pointer.degraded,sharedRoot:resolveLinkDir(pointer.linkId),generation:pointer.generation};else status2.cohort={linked:!1}}catch{status2.cohort={linked:!1}}try{let memoryPointer=readMemoryLinkPointer(directory),provider,configFingerprintMatch;try{let memoryConfig=MemoryConfigSchema.parse(loadPluginConfig(directory).memory??{});if(provider=memoryConfig.provider,memoryPointer){let cohortConfigPath=path289.join(resolveLinkDir(memoryPointer.linkId),"memory","memory-cohort-config.json");if(fsSync21.existsSync(cohortConfigPath)){let stored=JSON.parse(fsSync21.readFileSync(cohortConfigPath,"utf-8"));if(classifyStoredFingerprintAlgorithmVersion(stored.algorithm_version).status==="comparable"&&typeof stored.fingerprint==="string"){let expected=computeMemoryCohortFingerprint(buildMemoryCohortFingerprintInput(memoryConfig));configFingerprintMatch=stored.fingerprint===expected}}}}catch{}if(memoryPointer)status2.memoryCohort={linked:!0,linkId:memoryPointer.linkId,cohortId:memoryPointer.cohortId,identitySource:memoryPointer.identitySource,degraded:memoryPointer.degraded,sharedRoot:resolveLinkDir(memoryPointer.linkId),generation:memoryPointer.generation,provider,configFingerprintMatch};else status2.memoryCohort={linked:!1,provider}}catch{status2.memoryCohort={linked:!1}}if(status2.fullAutoActive=_internals240.hasActiveFullAuto(),status2.fullAutoActive){let sid=_internals240.getActiveFullAutoSessionID();if(sid){let runState=_internals240.loadFullAutoRunState(directory,sid);if(runState?.lastEscalation)status2.fullAutoEscalation={reason:runState.lastEscalation.reason,interactionCount:runState.lastEscalation.interactionCount,deadlockCount:runState.lastEscalation.deadlockCount,phase:runState.lastEscalation.phase}}}if(sessionId){let timestamp=getLastHeartbeat(sessionId);if(timestamp!==void 0){let agoMs=Date.now()-timestamp;status2.lastActivity={sessionId,timestamp,agoMs,agoLabel:formatAgo(agoMs)}}else status2.lastActivity={sessionId,timestamp:0,agoMs:null,agoLabel:"never"}}status2=enrichWithLeanTurbo(status2,directory);try{let costs=getTelemetryCostSummary(directory);status2.costs={totalCostUsd:costs.total_cost_usd,delegations:costs.delegations,unavailableDelegations:costs.unavailable_delegations,evidenceStatus:costs.evidence_status,conflictCount:costs.conflict_count,joinMissCount:costs.join_miss_count,telemetryErrorCount:costs.telemetry_error_count}}catch{}let coordination=getSnapshotCoordinationStatus(directory);if(coordination.state!=="idle"&&coordination.state!=="succeeded")status2.coordination=coordination;return status2}function renderCoordinationStatus(status2){if(status2.state==="closing"){if(status2.pendingPriorAttempt&&status2.closingReason==="reset-cleanup-failed")return["",`**SQLite coordination**: ${status2.state}${status2.settled?" (settled)":" (unsettled)"}`,...status2.error?[` - ${status2.error}`]:[]," - Recovery: wait for the settling initialization attempt, then re-run `/swarm reset-session` (or restart the host); durable snapshot writes are stopped until then"];if(status2.pendingPriorAttempt)return["",`**SQLite coordination**: ${status2.state}${status2.settled?" (settled)":" (unsettled)"}`,...status2.error?[` - ${status2.error}`]:[]," - Recovery: `/swarm recover --coordination` (an unsettled timed-out attempt must finish before retry)"];if(status2.closingReason==="reset-cleanup-failed")return["",`**SQLite coordination**: ${status2.state}${status2.settled?" (settled)":" (unsettled)"}`,...status2.error?[` - ${status2.error}`]:[]," - Recovery: re-run `/swarm reset-session` (durable snapshot writes are stopped until it succeeds; a host restart also clears the guard)"];if(status2.closingReason==="shutdown")return["",`**SQLite coordination**: ${status2.state}${status2.settled?" (settled)":" (unsettled)"}`,...status2.error?[` - ${status2.error}`]:[]," - Coordination is closing for host shutdown; durable snapshot writes are stopped until the host restarts."];return["",`**SQLite coordination**: ${status2.state}${status2.settled?" (settled)":" (unsettled)"}`,...status2.error?[` - ${status2.error}`]:[]," - A `/swarm reset-session` is in progress; durable snapshot writes resume when it completes."]}return["",`**SQLite coordination**: ${status2.state}${status2.settled?" (settled)":" (unsettled)"}`,...status2.error?[` - ${status2.error}`]:[]," - Recovery: `/swarm recover --coordination` (an unsettled timed-out attempt must finish before retry)"]}function enrichWithLeanTurbo(status2,directory){let turboMode=hasActiveTurboMode(),leanActive=_internals240.hasActiveLeanTurbo(),turboStrategy="off";if(leanActive)turboStrategy="lean";else if(turboMode)turboStrategy="standard";status2.turboStrategy=turboStrategy;try{let recoveryRecords=listRecoveryRecords(directory);if(recoveryRecords.length>0)status2.leanPreservedRecoveryWorktrees=recoveryRecords.map((r)=>({laneId:r.laneId,status:r.status,worktreePath:r.worktreePath,reason:r.reason,replayHint:r.replayHint}))}catch{}if(!leanActive)return status2;let leanSessionID=null;for(let[sessionId,session]of swarmState.agentSessions)if(session.turboStrategy==="lean"&&session.leanTurboActive===!0){leanSessionID=sessionId;break}if(leanSessionID){let runState=_internals240.loadLeanTurboRunState(directory,leanSessionID);if(runState){if(status2.leanTurboPhase=runState.phase,status2.leanMaxParallelCoders=runState.maxParallelCoders,status2.leanPauseReason=runState.pauseReason,!Array.isArray(runState.lanes))runState.lanes=[];let activeLanes=0,completedLanes=0;for(let lane of runState.lanes){if(lane.status==="running")activeLanes++;if(lane.status==="completed")completedLanes++}if(status2.leanActiveLaneCount=activeLanes,status2.leanCompletedLanes=completedLanes,!Array.isArray(runState.degradedTasks))runState.degradedTasks=[],status2.leanDegradedTasks=0;if(runState.degradedTasks.length>0){status2.leanDegradedTasks=runState.degradedTasks.length;let summaryParts=[];for(let dt of runState.degradedTasks)summaryParts.push(`${dt.taskId} (${dt.reason})`);status2.leanDegradationSummary=summaryParts.join("; ")}}}return status2}function formatStatusMarkdown(status2){let lines=["## Swarm Status","",`**Current Phase**: ${status2.currentPhase}`,`**Tasks**: ${status2.completedTasks}/${status2.totalTasks} complete`,`**Agents**: ${status2.agentCount} registered`];if(status2.coordination)lines.push(...renderCoordinationStatus(status2.coordination));if(status2.costs&&status2.costs.delegations>0){let evidence2=status2.costs.evidenceStatus==="complete"?"complete evidence":`inconclusive evidence (${status2.costs.unavailableDelegations} unavailable, ${status2.costs.conflictCount} conflicts, ${status2.costs.joinMissCount} join misses, ${status2.costs.telemetryErrorCount} telemetry errors)`;lines.push("",`**Cost**: $${status2.costs.totalCostUsd.toFixed(6)} across ${status2.costs.delegations} delegations — ${evidence2}`)}if(status2.lastActivity){let label=status2.lastActivity.agoLabel,annotation=status2.lastActivity.agoLabel!=="never"&&status2.lastActivity.agoMs!==null&&status2.lastActivity.agoMs>120000?" ⚠️ possibly stalled":"";lines.push(""),lines.push(`**Last activity:** ${label}${annotation}`)}if(status2.specStale){let reason=status2.specStaleReason??"spec.md changed since plan saved",stored=status2.specStaleStoredHash??"unknown",current=status2.specStaleCurrentHash??"(spec.md missing)";lines.push("",`**Spec drift detected**: ${reason} (stored: ${stored}, current: ${current})`,"Run `/swarm clarify` to enter spec repair mode. Clarify alone does not clear drift: rewrite the spec so recovery can reconcile it, or run `/swarm acknowledge-spec-drift` to dismiss.")}let decisionDriftLines=formatDecisionDriftLines(status2.decisionDrift);if(decisionDriftLines)lines.push("",...decisionDriftLines);if(status2.turboStrategy&&status2.turboStrategy!=="off")if(lines.push(""),status2.turboStrategy==="lean"){let parts=["lean"];if(status2.leanTurboPhase!==void 0)parts.push(`Phase ${status2.leanTurboPhase}`);if(status2.leanActiveLaneCount!==void 0){let totalLanes=(status2.leanActiveLaneCount??0)+(status2.leanCompletedLanes??0);parts.push(`${status2.leanActiveLaneCount}/${totalLanes} lanes active`)}if(status2.leanDegradedTasks!==void 0&&status2.leanDegradedTasks>0)parts.push(`${status2.leanDegradedTasks} degraded`);if(lines.push(`**Turbo**: ${parts.join(", ")}`),status2.leanDegradationSummary)lines.push(` - ${status2.leanDegradationSummary}`);if(status2.leanPauseReason)lines.push(`**Lean paused**: ${status2.leanPauseReason}`)}else lines.push("**Turbo**: standard");else if(status2.turboStrategy===void 0&&status2.turboMode===!0)lines.push(""),lines.push("**TURBO MODE**: active");if(status2.leanPreservedRecoveryWorktrees&&status2.leanPreservedRecoveryWorktrees.length>0){lines.push(""),lines.push(`**Preserved recovery worktrees**: ${status2.leanPreservedRecoveryWorktrees.length} lane(s) preserved for manual merge-back recovery`);for(let w of status2.leanPreservedRecoveryWorktrees)lines.push(` - ${w.laneId} (${w.status}): ${w.reason} — \`${w.replayHint}\``)}if(status2.fullAutoActive){if(lines.push(""),lines.push("**Full-Auto**: active"),status2.fullAutoEscalation){let e=status2.fullAutoEscalation,phaseStr=e.phase!==void 0?` | Phase ${e.phase}`:"";lines.push(` - Escalation: ${e.reason} (interactions=${e.interactionCount}, deadlocks=${e.deadlockCount}${phaseStr})`)}}if(status2.contextBudgetPct!==null&&status2.contextBudgetPct>0){let pct=status2.contextBudgetPct.toFixed(1),budgetTokens=status2.contextBudgetTokens;if(budgetTokens!==void 0&&budgetTokens!==null&&budgetTokens>0){let est=Math.round(status2.contextBudgetPct/100*budgetTokens);lines.push("",`**Swarm injection footprint**: ${pct}% of model window (intermediate measurement; est. ${est.toLocaleString()} / ${budgetTokens.toLocaleString()} tokens)`)}else lines.push("",`**Swarm injection footprint**: ${pct}% of model window (intermediate measurement)`);let finalPressure=getDisplayFinalPromptPressure();if(finalPressure&&finalPressure.pct>0)lines.push(`**Prompt pressure (final)**: ${finalPressure.pct.toFixed(1)}% estimated (est. ${finalPressure.usedTokens.toLocaleString()} / ${finalPressure.limitTokens.toLocaleString()} tokens; ${finalPressure.estimatorSource}${finalPressure.providerReported?"; provider-reported":""})`);if(status2.compactionCount>0)lines.push(`**Compaction events**: ${status2.compactionCount} triggered`);if(status2.lastSnapshotAt)lines.push(`**Last snapshot**: ${status2.lastSnapshotAt}`)}if(status2.recentEscalations&&status2.recentEscalations.length>0){lines.push("","**Recently Escalated (last 7 days)**:");for(let e of status2.recentEscalations)lines.push(` - ${e.entry_id} (${e.from}→${e.to}) reason=${e.reason}`)}let proposals=status2.pendingProposals??0,unactionable=status2.unactionableQueueDepth??0,insights=status2.insightCandidatesPending??0,consensusReports=status2.consensusReports??0;if(proposals>0||unactionable>0||insights>0||consensusReports>0){if(lines.push("","**Learning Queues**:"),proposals>0)lines.push(` - Pending proposals: ${proposals} (review with \`/swarm skill list\`)`);if(unactionable>0)lines.push(` - Unactionable queue: ${unactionable} (inspect with \`/swarm knowledge unactionable\`)`);if(insights>0)lines.push(` - Insight candidates: ${insights} (consumed at phase end)`);if(consensusReports>0)lines.push(` - Consensus reports: ${consensusReports} (read under \`.swarm/evolution/consensus/\`; each holds proposals-only recommendations)`)}if(status2.learningHealth){lines.push("","**Learning Health**:");let active=status2.learningHealth.activeAlarms;if(active.length===0)lines.push(` - ✅ no active learning-health alarms (${status2.learningHealth.totalTransitions} transitions recorded)`);else{for(let alarm of active){let ageMinutes=Math.floor(alarm.ageMs/60000);lines.push(` - ⚠ ${alarm.severity}: ${alarm.alarm} [${alarm.scopeClass} ${alarm.scopeRef}] age ${ageMinutes}m, coverage ${alarm.coverageFacts} facts (${alarm.transitionCount} transitions)`)}lines.push(" - run `/swarm diagnose` for the learning-health check detail")}}if(status2.cohort?.linked){if(lines.push("","**Knowledge Cohort**:"),lines.push(` - \uD83D\uDD17 Linked to shared store "${status2.cohort.linkId}"`),status2.cohort.cohortId)lines.push(` cohort: ${status2.cohort.cohortId}`);if(status2.cohort.identitySource)lines.push(` identity: ${status2.cohort.identitySource}`);if(status2.cohort.degraded)lines.push(" ⚠ degraded (machine-local, not portable across machines)");if(status2.cohort.sharedRoot)lines.push(` shared at: ${status2.cohort.sharedRoot}`);if(status2.cohort.generation!==void 0)lines.push(` generation: ${status2.cohort.generation}`)}else lines.push("","**Knowledge Cohort**: local (not linked — run `/swarm link` to share across worktrees)");if(status2.memoryCohort?.linked){if(lines.push("","**Memory Cohort**:"),lines.push(` - \uD83D\uDD17 Memory shared across linked worktrees "${status2.memoryCohort.linkId}"`),status2.memoryCohort.cohortId)lines.push(` cohort: ${status2.memoryCohort.cohortId}`);if(status2.memoryCohort.identitySource)lines.push(` identity: ${status2.memoryCohort.identitySource}`);if(status2.memoryCohort.degraded)lines.push(" ⚠ degraded (machine-local, not portable across machines)");if(status2.memoryCohort.sharedRoot)lines.push(` shared at: ${status2.memoryCohort.sharedRoot}/memory`);if(status2.memoryCohort.generation!==void 0)lines.push(` generation: ${status2.memoryCohort.generation}`);if(status2.memoryCohort.provider)lines.push(` provider: ${status2.memoryCohort.provider}`);if(status2.memoryCohort.configFingerprintMatch===!1)lines.push(" ⚠ config fingerprint mismatch — provider/embedding/redaction config differs across cohort members");else if(status2.memoryCohort.configFingerprintMatch===!0)lines.push(" config: ✅ fingerprint matches cohort")}else lines.push("","**Memory Cohort**: local (not linked — run `/swarm memory link` to share memory across worktrees; requires `memory.link.enabled: true`)");let delegationHealth=status2.delegationLedgerHealth;if(delegationHealth){if(lines.push("","**Background Delegations**:"),lines.push(` - Ledger tail: ${formatLedgerBytes(delegationHealth.ledger.bytes)} / ${formatLedgerBytes(delegationHealth.ledger.limitBytes)} recovery bound (${delegationHealth.ledger.pressurePct}% — ${delegationHealth.ledger.band})`),delegationHealth.checkpoint){let checkpoint2=delegationHealth.checkpoint;lines.push(` - Checkpoint #${checkpoint2.sequence}: ${checkpoint2.liveRecords} live records, ${checkpoint2.closedSummaries} archived summaries (${formatLedgerBytes(checkpoint2.bytes)}, ${new Date(checkpoint2.createdAt).toISOString()})`)}else lines.push(" - Checkpoint: none (full-history recovery)");if(delegationHealth.recovery){let recovery=delegationHealth.recovery;lines.push(` - Recovery: ${recovery.source} (${recovery.ok?"ok":`FAILED: ${recovery.reason??"uncertain"}`})`)}if(delegationHealth.lastUncertainty){let uncertainty=delegationHealth.lastUncertainty;if(lines.push(` - ⚠ Last uncertainty (${new Date(uncertainty.at).toISOString()}, ${uncertainty.source}): ${uncertainty.reason}`),uncertainty.repairHint)lines.push(` repair: ${uncertainty.repairHint}`)}let counts=delegationHealth.counts;if(counts.activeOwners>0||counts.pendingAdvisories>0||counts.lateTerminals>0||counts.orphanWorktreeOwners>0)lines.push(` - Live set: ${counts.activeOwners} active owners, ${counts.pendingAdvisories} pending advisories, ${counts.lateTerminals} late terminals, ${counts.orphanWorktreeOwners} unsettled worktree owners`)}let backgroundWork=status2.backgroundWork;if(backgroundWork)lines.push(...renderBackgroundWorkLines(backgroundWork));return lines.join(`
|
|
4308
4312
|
`)}function renderBackgroundWorkLines(backgroundWork){let lines=["","**Background Work** (opt-in):"];if(backgroundWork.source==="uncertain")lines.push(` - ⚠ State uncertain: ${backgroundWork.uncertainty??"unknown reason"} — counts and reservations are not shown rather than partially trusted`);else{let counts=backgroundWork.counts;if(lines.push(` - Delegations: ${counts.pending} pending, ${counts.running} running, ${counts.completed} completed (unconsumed), ${counts.consumed} consumed, ${counts.stale} stale, ${counts.cancelled} cancelled, ${counts.rejected} rejected, ${counts.error} error, ${counts.ingestion_error} ingestion_error`),backgroundWork.reservations.length>0){lines.push(` - Reservations (${backgroundWork.reservations.length} active):`);for(let reservation of backgroundWork.reservations){let lease=reservation.leaseState==="active"&&reservation.leaseExpiresAt?`active until ${new Date(reservation.leaseExpiresAt).toISOString()}`:reservation.leaseState;lines.push(` - ${reservation.reservationId.slice(0,12)}… ${reservation.state} gen ${reservation.generation} task ${reservation.planTaskId??"(call-scoped)"} — lease ${lease}`)}}else lines.push(" - Reservations: none");lines.push(" - Source: validated recovery (bounded scan)")}let maintenance=backgroundWork.maintenance;if(maintenance){if(maintenance.lastOkAt!==null){let summary=maintenance.lastSummary;lines.push(` - Maintenance: last ok ${new Date(maintenance.lastOkAt).toISOString()} (swept ${summary.sweptStale}, released ${summary.released}, renewed ${summary.renewed}, retained ${summary.retained})`)}else lines.push(" - Maintenance: no successful run recorded");if(maintenance.lastFailure)lines.push(` - ⚠ Last maintenance failure (${new Date(maintenance.lastFailure.at).toISOString()}): ${maintenance.lastFailure.reason}`);if(maintenance.lastContentionAt!==null)lines.push(` - ⚠ Last maintenance lock contention: ${new Date(maintenance.lastContentionAt).toISOString()}`);if(maintenance.facts.length>0){lines.push(` - Recent maintenance facts (${maintenance.facts.length}):`);for(let fact of maintenance.facts.slice(-5).reverse()){let target=fact.reservationId?` ${fact.reservationId.slice(0,12)}…`:fact.correlationId?` ${fact.correlationId.slice(0,12)}…`:"";lines.push(` - ${new Date(fact.at).toISOString()} ${fact.kind}${target} — ${fact.reason}`)}}}return lines}function renderNoActivePlanStatusTail(statusData){let decisionDriftLines=formatDecisionDriftLines(statusData.decisionDrift);if(statusData.specStale){let reason=statusData.specStaleReason??"spec.md changed since plan saved",stored=statusData.specStaleStoredHash??"unknown",current=statusData.specStaleCurrentHash??"(spec.md missing)";return["No active swarm plan found.","",`**Spec drift detected**: ${reason} (stored: ${stored}, current: ${current})`,"Run `/swarm clarify` to enter spec repair mode. Clarify alone does not clear drift: rewrite the spec so recovery can reconcile it, or run `/swarm acknowledge-spec-drift` to dismiss.",...decisionDriftLines??[]].join(`
|
|
4309
4313
|
`)}let delegationHealth=statusData.delegationLedgerHealth;if(delegationHealth&&(delegationHealth.checkpoint||delegationHealth.recovery||delegationHealth.lastUncertainty||delegationHealth.ledger.band!=="ok"||delegationHealth.counts.activeOwners>0||delegationHealth.counts.pendingAdvisories>0||delegationHealth.counts.lateTerminals>0||delegationHealth.counts.orphanWorktreeOwners>0)){let lines=["No active swarm plan found.","","**Background Delegations**:"];if(lines.push(` - Ledger tail: ${formatLedgerBytes(delegationHealth.ledger.bytes)} / ${formatLedgerBytes(delegationHealth.ledger.limitBytes)} recovery bound (${delegationHealth.ledger.pressurePct}% — ${delegationHealth.ledger.band})`),delegationHealth.checkpoint)lines.push(` - Checkpoint #${delegationHealth.checkpoint.sequence} (${delegationHealth.checkpoint.liveRecords} live, ${delegationHealth.checkpoint.closedSummaries} archived)`);if(delegationHealth.recovery)lines.push(` - Recovery: ${delegationHealth.recovery.source} (${delegationHealth.recovery.ok?"ok":`FAILED: ${delegationHealth.recovery.reason??"uncertain"}`})`);let compactCounts=delegationHealth.counts;if(compactCounts.activeOwners>0||compactCounts.pendingAdvisories>0||compactCounts.lateTerminals>0||compactCounts.orphanWorktreeOwners>0)lines.push(` - Live set: ${compactCounts.activeOwners} active owners, ${compactCounts.pendingAdvisories} pending advisories, ${compactCounts.lateTerminals} late terminals, ${compactCounts.orphanWorktreeOwners} unsettled worktree owners`);if(delegationHealth.lastUncertainty){if(lines.push(` - ⚠ Last uncertainty (${new Date(delegationHealth.lastUncertainty.at).toISOString()}): ${delegationHealth.lastUncertainty.reason}`),delegationHealth.lastUncertainty.repairHint)lines.push(` repair: ${delegationHealth.lastUncertainty.repairHint}`)}return lines.push(...decisionDriftLines??[]),lines.join(`
|
|
4310
4314
|
`)}if(decisionDriftLines)return["No active swarm plan found.","",...decisionDriftLines].join(`
|
|
@@ -4359,7 +4363,7 @@ Phase **${result.phase??"unknown"}** retrospective saved to \`.swarm/evidence/${
|
|
|
4359
4363
|
Run \`/swarm evidence ${result.task_id??"unknown"}\` to view it, or \`/swarm status\` to check phase_complete readiness.`;return`Error: ${result.message}`}var init_write_retro2=__esm(()=>{init_write_retro()});var COMMAND_NAMES,COMMAND_NAME_SET;var init_command_names=__esm(()=>{init_registry2();COMMAND_NAMES=Object.freeze(Object.keys(COMMAND_REGISTRY)),COMMAND_NAME_SET=new Set(COMMAND_NAMES)});import path291 from"node:path";function parseGuardrailExplainArgs(args2){let agent="coder",scope=null,writeTargets=[],positional=[],i=0;while(i<args2.length){let token=args2[i];if(token==="--agent"&&i+1<args2.length)agent=args2[i+1],i+=2;else if(token==="--scope"&&i+1<args2.length)scope=args2[i+1],i+=2;else if(token==="--write"&&i+1<args2.length)writeTargets.push(args2[i+1]),i+=2;else positional.push(token),i++}return{agent,scope,writeTargets,shellCommand:positional.join(" ")}}function resolveShellType(command){if(/^(powershell|ps1|\.\s*\\|Remove-Item|Copy-Item|Move-Item|Start-Process|New-Object|Get-ChildItem|Set-Content|Add-Content|Out-File|Invoke-WebRequest|Invoke-RestMethod|IEX|iex)\b/i.test(command)||command.includes("$PSVersionTable")||command.includes("$env:")||/-EncodedCommand|-ExecutionPolicy|Enable-PSRemoting/i.test(command))return"powershell";if(/^(cmd|cmd\.exe|c:\/|set \w+=|\.\d+|del \/|rd \/|mkdir|chdir|echo |copy |move |ren |fc |diskpart)/i.test(command)||/%[^%\s]+%/.test(command)||/\b(set|echo|if|exist)\s+/i.test(command))return"cmd";return"posix"}function evaluateDestructiveDecision(rawCommand,cwd,declaredScope){if(!rawCommand)return{decision:"allow",firingRule:"allow: no rule matched"};let shared=classifyCommand(rawCommand),sharedFiringRule=`shared_classifier: ${shared.aggregate}`;if(getSharedClassifierGuardrailBlock(shared))return{decision:"block",firingRule:sharedFiringRule};let command=dcNormalizeCommand(rawCommand),unwrapped=dcUnwrapWrappers(command),outerSegments=dcSplitSegments(command),innerSegments=dcSplitSegments(unwrapped),perSegmentUnwrapped=outerSegments.map((s)=>dcUnwrapWrappers(s)),allSegments=[...new Set([...outerSegments,...innerSegments,...perSegmentUnwrapped])];for(let segment of allSegments){let seg=segment.trim();if(!seg)continue;if(dcCheckJunctionCreation(seg,cwd))return{decision:"block",firingRule:"destructive_block: junction creation"};let targets=dcExtractRecursiveRmTargets(seg);if(targets){let targetDecision=dcEvaluateRecursiveDeleteTargets({targets,cwd});if(!targetDecision.allowed)return{decision:"block",firingRule:`${targetDecision.code}: ${targetDecision.reason}`}}if(/^(?:rmdir|rd)(?:\.exe)?\s+.*\/[sS]/i.test(seg)){let targets2=dcExtractWindowsCmdTargets(seg);if(targets2.length===0)return{decision:"block",firingRule:"destructive_block: Windows recursive directory delete (rmdir /s)"};let targetDecision=dcEvaluateRecursiveDeleteTargets({targets:targets2,cwd});if(!targetDecision.allowed)return{decision:"block",firingRule:`${targetDecision.code}: ${targetDecision.reason}`}}if(/^del(?:\.exe)?\s+.*\/[sS]/i.test(seg)){let targets2=dcExtractWindowsCmdTargets(seg);if(targets2.length>0){let targetDecision=dcEvaluateRecursiveDeleteTargets({targets:targets2,cwd});if(!targetDecision.allowed)return{decision:"block",firingRule:`${targetDecision.code}: ${targetDecision.reason}`}}}if(/^(?:Remove-Item|ri|rm|rmdir|del|erase|rd)\b.*-[Rr]ecurse\b/i.test(seg)||/^(?:Remove-Item|ri|rm|rmdir|del|erase|rd)\b.*-[Rr]\b/i.test(seg)){let targets2=dcExtractPowerShellTargets(seg);if(targets2.length>0){let targetDecision=dcEvaluateRecursiveDeleteTargets({targets:targets2,cwd});if(!targetDecision.allowed)return{decision:"block",firingRule:`${targetDecision.code}: ${targetDecision.reason}`}}else return{decision:"block",firingRule:"destructive_block: PowerShell Remove-Item -Recurse (target unverifiable)"}}if(/Get-ChildItem\b.*\|\s*Remove-Item\b.*-[Rr]ecurse/i.test(seg)||/gci\b.*\|\s*ri\b.*-[Rr]ecurse/i.test(seg))return{decision:"block",firingRule:"destructive_block: PowerShell pipeline Get-ChildItem | Remove-Item -Recurse"};if(/^git\s+worktree\s+remove\s+.*--force\b/i.test(seg)){let worktreeRemoveMatch=/^git\s+worktree\s+remove\s+(.+)$/i.exec(seg);if(worktreeRemoveMatch){let pathArgs=worktreeRemoveMatch[1].trim().split(/\s+/).filter(Boolean).map((token)=>token.replace(/^["']|["']$/g,"")).filter((token)=>!token.startsWith("-")),target=pathArgs.length===1?pathArgs[0]?.trim():null;if(!(target!=null&&target.length>0&&declaredScope!=null&&declaredScope.length>0&&isInDeclaredScope(target,declaredScope,cwd)))return{decision:"block",firingRule:"destructive_block: git worktree remove --force"}}}if(/^rsync\b.*--delete(?:-after|-before|-during|-delay)?\b/.test(seg)){let rsyncTarget=seg.split(/\s+/).slice(1).filter((a)=>!a.startsWith("-")&&!a.includes("@")).pop();if(!(rsyncTarget!=null&&declaredScope!=null&&declaredScope.length>0&&isInDeclaredScope(rsyncTarget,declaredScope,cwd)))return{decision:"block",firingRule:`destructive_block: rsync --delete (target: ${redactPath(rsyncTarget??"unknown")})`}}if(/^\\?mv\s/i.test(seg)){let mvMatch=seg.match(/^\\?mv\s+(.+)$/i);if(mvMatch){let argsStr=mvMatch[1].replace(/["']/g,"");if(/\.swarm(?:[\x5c/\s]|$)/.test(argsStr))return{decision:"block",firingRule:'destructive_block: "mv" targeting .swarm/ detected — move operations under .swarm/ are not allowed from shell commands'}}}if(/^\\?(?:move|ren)(?:\.exe)?\s/i.test(seg)){let moveMatch=seg.match(/^\\?(?:move|ren)(?:\.exe)?\s+(.+)$/i);if(moveMatch){let argsStr=moveMatch[1].replace(/["']/g,"");if(/\.swarm(?:[\x5c/\s]|$)/i.test(argsStr))return{decision:"block",firingRule:'destructive_block: "move" or "ren" targeting .swarm/ detected — move/rename operations under .swarm/ are not allowed from shell commands'}}}if(/^\\?(?:Move-Item|Rename-Item|move|mi|mv|ren|rni)\b.*\.swarm(?:[\x5c/\s]|$)/i.test(seg))return{decision:"block",firingRule:"destructive_block: PowerShell Move-Item or Rename-Item targeting .swarm/ detected — move/rename operations under .swarm/ are not allowed from shell commands"};if(/^\\?rm\b/i.test(seg)&&!/^\\?rm\s+(?:-[a-zA-Z]*[rR][a-zA-Z]*|--recursive)\b/i.test(seg)&&/\.swarm(?:[\x5c/\s]|$)/i.test(seg))return{decision:"block",firingRule:'destructive_block: "rm" targeting .swarm/ detected — deleting files under .swarm/ is not allowed from shell commands'};if(/\bcp\b.*\.swarm(?:[\x5c/\s]|$)/i.test(seg)&&/\brm\b.*\.swarm(?:[\x5c/\s]|$)/i.test(seg))return{decision:"block",firingRule:'destructive_block: "cp" of .swarm/ file followed by "rm" of .swarm/ source detected — copy-and-delete bypass is not allowed'};if(/^rsync\b.*--remove-source-files\b/i.test(seg)&&/\.swarm(?:[\x5c/\s]|$)/i.test(seg))return{decision:"block",firingRule:'destructive_block: "rsync" with delete-source flag targeting .swarm/ detected — archive with source deletion under .swarm/ is not allowed'};if(/^tar\b.*--remove-files\b/i.test(seg)&&/\.swarm(?:[\x5c/\s]|$)/i.test(seg))return{decision:"block",firingRule:'destructive_block: "tar" with delete-source flag targeting .swarm/ detected — archive with source deletion under .swarm/ is not allowed'};if(/^zip\b.*\s-m\b/i.test(seg)&&/\.swarm(?:[\x5c/\s]|$)/i.test(seg))return{decision:"block",firingRule:'destructive_block: "zip" with delete-source flag targeting .swarm/ detected — archive with source deletion under .swarm/ is not allowed'};if(/^7z\b.*\s-sdel\b/i.test(seg)&&/\.swarm(?:[\x5c/\s]|$)/i.test(seg))return{decision:"block",firingRule:'destructive_block: "7z" with delete-source flag targeting .swarm/ detected — archive with source deletion under .swarm/ is not allowed'};{let probe2=seg.replace(/^(?:[A-Za-z_][A-Za-z0-9_]*=\S+\s+)+/,"").replace(/^eval(?:\s+--)?\s+["']?/,"").replace(/["']\s*$/,"").replace(/^\$\(\s*/,"").replace(/^\(\s*/,"").replace(/\s*\)$/,"").replace(/^`/,"").replace(/`$/,"").trim();for(let i=0;i<4;i++){let before=probe2;if(probe2=probe2.replace(/^env\s+(?:-i\b|--ignore-environment\b|-u\s+\S+|-[a-zA-Z]+\s+)*\s*/,"").replace(/^command\s+(?:-[pvV]\s+)*/,"").replace(/^(?:[A-Za-z_][A-Za-z0-9_]*=\S+\s+)+/,"").trim(),probe2===before)break}let swarmCliMatches=[probe2.match(/^\\?(?:bunx|npx|pnpx|npm(?:\s+(?:exec|x)(?:\s+--)?)?|pnpm(?:\s+(?:dlx|exec))?|yarn(?:\s+(?:dlx|exec))?|bun(?:\s+x)?|node|deno\s+run|tsx|ts-node)\b[^|;&]*?\bopencode-swarm\b[^|;&]*?\brun\s+([A-Za-z0-9_-]+(?:\s+(?!-)[A-Za-z0-9_-]+)?)/i),probe2.match(/^\\?opencode-swarm\b[^|;&]*?\brun\s+([A-Za-z0-9_-]+(?:\s+(?!-)[A-Za-z0-9_-]+)?)/i),probe2.match(/\bcli[/\\]+index\.[mc]?(?:js|ts)\b[^|;&]*?\brun\s+([A-Za-z0-9_-]+(?:\s+(?!-)[A-Za-z0-9_-]+)?)/i)];for(let m of swarmCliMatches){if(!m)continue;let normalized=m[1].trim().split(/\s+/).join(" "),firstToken=normalized.includes(" ")?normalized.split(" ")[0]:normalized;if(HUMAN_ONLY_SWARM_COMMANDS.has(normalized)||HUMAN_ONLY_SWARM_COMMANDS.has(firstToken))return{decision:"block",firingRule:`human_only_command: "${HUMAN_ONLY_SWARM_COMMANDS.has(normalized)?normalized:firstToken}" is a human-only swarm command (not invocable from shell by an agent)`}}}{let normForPathCheck=seg.replace(/\\/g,"/").replace(/\/(?:\.\/+)+/g,"/").replace(/\/{2,}/g,"/");if(/\.swarm\/spec-staleness\.json\b/i.test(normForPathCheck)){let trimmed=seg.trim(),looksReadOnly=/^(?:cat|less|more|head|tail|file|stat|ls|dir|Get-Content|gc|Get-Item|gi|type)\b/i.test(trimmed),hasWriteRedirect=/>{1,2}\s*[^\s>]/.test(trimmed);if(!looksReadOnly||hasWriteRedirect)return{decision:"block",firingRule:"system_file_tampering: shell command targeting .swarm/spec-staleness.json (system-managed file)"}}}}return{decision:"allow",firingRule:"allow: no destructive/scope rule matched"}}async function handleGuardrailExplain(directory,args2){let{agent,scope,writeTargets,shellCommand}=parseGuardrailExplainArgs(args2),resolvedScope=scope??directory,scopeEntries=scope!=null&&scope.length>0?[scope]:[resolvedScope];if(writeTargets.length>0){let results=[];for(let rawPath of writeTargets){let absolutePath2=path291.resolve(directory,rawPath),decision2=checkFileAuthority(agent,absolutePath2,directory,void 0,{declaredScope:scope!=null?[scope]:null}),zoneResult=classifyFile(absolutePath2),allowed=decision2.allowed===!0,zone=allowed?zoneResult.zone:decision2.zone??zoneResult.zone;results.push({path:rawPath,decision:allowed?"allow":"block",firingRule:allowed?"allow: no rule matched":decision2.reason,resolvedScope,zone})}let redactedResolvedScope=redactPath(resolvedScope);return["## Guardrail Explain (dry-run)","",`**Mode**: write-target | **Agent**: ${agent} | **Resolved scope**: ${redactedResolvedScope}`,"","| Path | Decision | Firing Rule | Resolved Scope | Zone |","| --- | --- | --- | --- | --- |",...results.map((r)=>`| ${redactPath(r.path)} | ${r.decision} | ${r.firingRule} | ${redactPath(r.resolvedScope)} | ${r.zone} |`),""].join(`
|
|
4360
4364
|
`)}if(!shellCommand)return["## Guardrail Explain (dry-run)","","Provide a shell command to analyze, or use `--write <path>` for write-target mode.","","```","/swarm guardrail explain <command>","/swarm guardrail explain --agent <role> --scope <path> <command>","/swarm guardrail explain --write <path> [--write <path2> ...]","```",""].join(`
|
|
4361
4365
|
`);let decision="allow",firingRule="allow: no rule matched",writeCategories=new Set,destructiveEval=evaluateDestructiveDecision(shellCommand,directory,scopeEntries);if(destructiveEval.decision==="block")decision="block",firingRule=destructiveEval.firingRule;let commandSegments=dcSplitSegments(shellCommand),unwrappedSegments=commandSegments.map((s)=>dcUnwrapWrappers(s)),detectionCommand=commandSegments.some((s,i)=>unwrappedSegments[i]!==s)?unwrappedSegments.join(`
|
|
4362
|
-
`):shellCommand;if(decision==="allow"){let detected=resolveShellType(shellCommand),authority=resolveWindowsWriteAuthority("shell",shellCommand,detected,isPowerShellShaped(shellCommand)),wrapperDeclaredHere=declaresWindowsWrapperLoose(shellCommand),
|
|
4366
|
+
`):shellCommand;if(decision==="allow"){let detected=resolveShellType(shellCommand),authority=resolveWindowsWriteAuthority("shell",shellCommand,detected,isPowerShellShaped(shellCommand)),wrapperDeclaredHere=declaresWindowsWrapperLoose(shellCommand),posix24=detectPosixWrites(detectionCommand),analysis=authority===null?posix24:mergeWriteAnalyses(posix24,detectWindowsWrites(detectionCommand,authority),!0,wrapperDeclaredHere),rawPosix=detectPosixWrites(shellCommand);if((authority===null?rawPosix:mergeWriteAnalyses(rawPosix,detectWindowsWrites(shellCommand,authority),!0,wrapperDeclaredHere)).parseError&&!isPowerShellReadOnlyPipeline(shellCommand))decision="block",firingRule="parse_error: write detection failed to parse command — rejecting for safety";else if(analysis.parseError&&!isPowerShellReadOnlyPipeline(detectionCommand))decision="block",firingRule="parse_error: write detection failed to parse command — rejecting for safety";else if(analysis.hasWrites){let resolvedWrites=resolveWriteTargets(detectionCommand,analysis.writes,directory);for(let write of resolvedWrites)if(write.resolvedPath){if(agent!=="architect"){if(!isInDeclaredScope(write.resolvedPath,scopeEntries,directory)){decision="block",firingRule=`scope_violation: write outside declared scope: ${redactPath(write.resolvedPath)}`;break}}writeCategories.add(write.original.category)}else writeCategories.add(write.original.category)}}else{let detected=resolveShellType(shellCommand),authority=resolveWindowsWriteAuthority("shell",shellCommand,detected,isPowerShellShaped(shellCommand)),wrapperDeclaredElse=declaresWindowsWrapperLoose(shellCommand),posix24=detectPosixWrites(detectionCommand),analysis=authority===null?posix24:mergeWriteAnalyses(posix24,detectWindowsWrites(detectionCommand,authority),!0,wrapperDeclaredElse);if(!analysis.parseError&&analysis.hasWrites)for(let write of analysis.writes)writeCategories.add(write.category)}let redactedCommand=redactShellCommand(shellCommand),redactedResolvedScopeShell=redactPath(resolvedScope),shellResult={decision,firingRule,resolvedScope:redactedResolvedScopeShell,writeCategories:writeCategories.size>0?[...writeCategories]:[],command:redactedCommand};return["## Guardrail Explain (dry-run)","",`**Mode**: shell | **Agent**: ${agent} | **Resolved scope**: ${redactedResolvedScopeShell}`,"","| Field | Value |","| --- | --- |",`| Command | \`${shellResult.command}\` |`,`| Decision | ${shellResult.decision} |`,`| Firing Rule | ${shellResult.firingRule} |`,`| Resolved Scope | ${shellResult.resolvedScope} |`,`| Write Categories | ${shellResult.writeCategories.length>0?shellResult.writeCategories.join(", "):"(none)"} |`,""].join(`
|
|
4363
4367
|
`)}var init_guardrail_explain_service=__esm(()=>{init_tool_policy();init_audit_log();init_destructive_command();init_file_authority();init_helpers();init_tool_before();init_shell_executor_context();init_shell_write_detect();init_command_classifier()});var exports_guardrail_explain={};__export(exports_guardrail_explain,{handleGuardrailExplain:()=>handleGuardrailExplain});var init_guardrail_explain=__esm(()=>{init_guardrail_explain_service()});function isBlockEntry(entry){if(entry.type===null||entry.type===void 0)return!1;return BLOCK_TYPES.has(entry.type)}function redactSummary(entry){if(entry.type==="file_write"||entry.type==="scope_violation"){let raw=entry.path??"";return redactPath(raw)}if(entry.type==="destructive_block"||entry.type==="sandbox_wrap"||entry.type==="sandbox_skip"||entry.type==="shell"||entry.type===null||entry.type===void 0){let raw=entry.command??"";return redactShellCommand(raw)}return""}function sanitizeDisplayText(value){return value.replace(/\u001b\[[0-9;?]*[ -/]*[@-~]/g,"").replace(/[\u0000-\u0008\u000a-\u001f\u007f-\u009f]/g,"").replace(/[\u202a-\u202e\u2066-\u2069]/g,"").replace(/[\u200e\u200f\u200b-\u200d\u2060-\u2064\ufeff]/g,"")}function formatEntry(entry){let decisionType=entry.type??"shell",summary=redactSummary(entry),line=`- [${sanitizeDisplayText(entry.ts)}] ${sanitizeDisplayText(decisionType)} | agent: ${sanitizeDisplayText(entry.agent)} | ${sanitizeDisplayText(summary)}`;if(entry.commandHash!==void 0)line+=` · fp:${sanitizeDisplayText(entry.commandHash)}`;return line.length>MAX_RENDERED_LINE_CHARS?`${line.slice(0,MAX_RENDERED_LINE_CHARS)}…`:line}function isPlainObject8(value){return typeof value==="object"&&value!==null&&(value.constructor===Object||Object.getPrototypeOf(value)===null)}function parseEntries(raw){let lines=raw.split(/\r?\n/),entries2=[];for(let line of lines){if(line.trim().length===0)continue;let parsed;try{parsed=JSON.parse(line)}catch{continue}if(!isPlainObject8(parsed))continue;if(typeof parsed.ts!=="string")continue;if(typeof parsed.sessionID!=="string")continue;if(typeof parsed.agent!=="string")continue;if(typeof parsed.tool!=="string")continue;let entry={ts:parsed.ts,sessionID:parsed.sessionID,agent:parsed.agent,tool:parsed.tool};if(typeof parsed.type==="string")entry.type=parsed.type;if(typeof parsed.command==="string")entry.command=parsed.command;if(typeof parsed.path==="string")entry.path=parsed.path;if(typeof parsed.commandHash==="string")entry.commandHash=parsed.commandHash;entries2.push(entry)}return entries2}async function handleGuardrailLog(directory,args2){let window2=readShellAuditTail(directory),entries2=parseEntries(window2.text),blocksOnly=args2.includes("--blocks-only");if(entries2.length===0){let folded2=getShellAuditFoldedSummary(directory);if(folded2!==null&&folded2.totalDecisions>0){let note=`${folded2.totalDecisions} earlier decision(s) compacted into the audit manifest.`;return blocksOnly?`No guardrail block decisions in the read window; ${note}`:`No guardrail decisions in the read window; ${note}`}return blocksOnly?"No guardrail block decisions recorded yet.":"No guardrail decisions recorded yet."}let filtered=blocksOnly?entries2.filter(isBlockEntry):entries2;if(filtered.length===0){let folded2=getShellAuditFoldedSummary(directory);if(blocksOnly&&folded2!==null){let foldedBlocks=[...BLOCK_TYPES].reduce((sum,type)=>sum+(folded2.byType[type]??0),0);if(foldedBlocks>0)return`No guardrail block decisions in the read window; ${foldedBlocks} earlier block decision(s) compacted into the audit manifest.`}if(blocksOnly)return"No guardrail block decisions recorded yet.";return"No guardrail decisions recorded yet."}filtered.sort((a,b)=>{let diff=b.ts.localeCompare(a.ts);return diff===0?0:diff});let rendered=filtered.slice(0,MAX_RENDERED_ENTRIES),header=blocksOnly?"# Guardrail Block Log (most-recent-first)":"# Guardrail Decision Log (most-recent-first)",body=rendered.map(formatEntry).join(`
|
|
4364
4368
|
`),notes=[];if(rendered.length<filtered.length)notes.push(`showing ${rendered.length} most recent of ${filtered.length} matching entries in the read window`);if(window2.truncated||window2.coverage==="truncated")notes.push("read window truncated to the newest bounded tail (older decisions may exist beyond it)");let folded=getShellAuditFoldedSummary(directory);if(folded!==null&&folded.totalDecisions>0)notes.push(`${folded.totalDecisions} earlier decision(s) already compacted into the audit manifest (lifetime total)`);if(notes.length===0)return`${header}
|
|
4365
4369
|
|
|
@@ -4402,7 +4406,7 @@ Subcommands:
|
|
|
4402
4406
|
`+` concurrency status — Show effective concurrency (override, plan baseline, operational effective)
|
|
4403
4407
|
`+` concurrency reset — Clear the session concurrency override
|
|
4404
4408
|
`+`
|
|
4405
|
-
`+"Session-scoped — resets on new session.",category:"utility",toolPolicy:"none"},simulate:{handler:(ctx)=>handleSimulateCommand(ctx.directory,ctx.args),description:"Dry-run hidden coupling analysis with configurable thresholds",args:"--threshold <number>, --min-commits <number>",category:"diagnostics",toolPolicy:"none"},sdd:{handler:(ctx)=>handleSddCommand(ctx.directory,ctx.args),description:"Manage OpenSpec-compatible SDD artifacts and effective spec projection",args:"status|validate|project [--json] [--change <id>] [--dry-run] [--source <provider>] [--feature <id>|all] [--overwrite]",details:"Parent command for spec-driven development artifacts. Use sdd status to inspect .swarm/spec.md plus openspec/ artifacts, sdd validate to validate OpenSpec-compatible deltas, and sdd project to materialize the effective spec into .swarm/spec.md for planning. Spec-Kit: sdd project projects ALL features with feature-scoped ids (featureId/FR-nnn) when several exist; --feature <id> selects one (v1 bare-id output); --feature all is the explicit multi-feature alias (project only).",category:"utility",toolPolicy:"agent"},"sdd status":{handler:(ctx)=>handleSddStatusCommand(ctx.directory,ctx.args),description:"Show OpenSpec-compatible SDD status and effective spec source",subcommandOf:"sdd",args:"[--json]",category:"utility",toolPolicy:"agent"},"sdd validate":{handler:(ctx)=>handleSddValidateCommand(ctx.directory,ctx.args),description:"Validate OpenSpec-compatible artifacts and effective spec projection",subcommandOf:"sdd",args:"[--json] [--change <id>]",category:"utility",toolPolicy:"agent"},"sdd project":{handler:(ctx)=>handleSddProjectCommand(ctx.directory,ctx.args),description:"Materialize the OpenSpec-compatible effective spec into .swarm/spec.md",subcommandOf:"sdd",args:"[--dry-run] [--overwrite] [--json] [--change <id>]",category:"utility",toolPolicy:"agent"},"sdd-status":{description:"Show OpenSpec-compatible SDD status and effective spec source",aliasOf:"sdd status",deprecated:!0},"sdd-validate":{description:"Validate OpenSpec-compatible artifacts and effective spec projection",aliasOf:"sdd validate",deprecated:!0},"sdd-project":{description:"Materialize the OpenSpec-compatible effective spec into .swarm/spec.md",aliasOf:"sdd project",deprecated:!0},analyze:{handler:(ctx)=>handleAnalyzeCommand(ctx.directory,ctx.args),description:"Analyze spec.md vs plan.md for requirement coverage gaps",args:"",category:"agent",toolPolicy:"none"},clarify:{handler:(ctx)=>handleModeCommandWithBundledSkills(ctx,handleClarifyCommand),description:"Clarify and refine an existing feature specification",args:"[description-text]",category:"agent",toolPolicy:"none"},specify:{handler:(ctx)=>handleModeCommandWithBundledSkills(ctx,handleSpecifyCommand),description:"Generate or import a feature specification [description]",args:"[description-text]",category:"agent",toolPolicy:"none"},brainstorm:{handler:(ctx)=>handleModeCommandWithBundledSkills(ctx,handleBrainstormCommand),description:"Enter architect MODE: BRAINSTORM — structured seven-phase planning workflow [topic]",args:"[topic-text]",details:"Triggers the architect to run the brainstorm workflow: CONTEXT SCAN, single-question DIALOGUE, APPROACHES, DESIGN SECTIONS, SPEC WRITE + SELF-REVIEW, QA GATE SELECTION, TRANSITION. Use for new plans where requirements need to be drawn out before writing spec.md / plan.md.",category:"agent",toolPolicy:"none"},loop:{handler:(ctx)=>handleModeCommandWithBundledSkills(ctx,handleLoopCommand),description:"Enter architect MODE: LOOP — compound-engineering loop: brainstorm → plan → build → review → improve, iterating until done [objective]",args:"<objective> [--max-cycles 1..5] [--autonomy checkpoint|auto] [--depth standard|exhaustive] [--resume]",details:`Triggers the architect to run the compound-engineering loop defined in ${BUNDLED_PROJECT_SKILL_ROOT}/loop/SKILL.md: BRAINSTORM (requirements) → PLAN (+ critic gate) → BUILD (execute) → REVIEW (independent reviewer + critic on the diff, report-only) → IMPROVE (phase-wrap retrospective + compounding learning capture), then evaluate stop conditions and loop for another improvement cycle if the objective is unmet and budget remains. Generator and reviewer/critic run in separate contexts; failing assertions must be fixed at the root cause, never weakened, mocked, or skipped. Defense-in-depth stop conditions: objective met, --max-cycles budget (default 3), no-progress/plateau, oscillation, unrecoverable error, or explicit user stop. --autonomy auto (default) runs unattended with hard stops still enforced; --autonomy checkpoint pauses at phase gates for user approval. --depth exhaustive widens exploration. --resume continues an existing loop run from durable .swarm/loop/ state. Distinct from full-auto (a critic gate that intercepts phase completions and high-risk actions for review — it never plans, delegates, or executes; the architect retains all delegation duty) and turbo (parallel lanes within a phase): loop is a user-initiated, gated, compounding workflow.`,category:"agent",toolPolicy:"none"},council:{handler:(ctx)=>handleModeCommandWithBundledSkills(ctx,handleCouncilCommand),description:"Enter architect MODE: COUNCIL — multi-model deliberation [question] [--spec-review]",args:"<question> [--spec-review]",details:"Triggers the architect to convene a three-agent General Council: Generalist (reviewer model), Skeptic (critic model), and Domain Expert (SME model). "+"The architect first runs 1–3 targeted web searches and passes a compiled RESEARCH CONTEXT "+"to all three agents before dispatching them in parallel. Agents deliberate using the NSED peer-review protocol (Round 1 independent analysis, Round 2 MAINTAIN/CONCEDE/NUANCE for disagreements). The architect synthesizes the final answer directly from convene_general_council output. --spec-review switches to single-pass advisory mode for spec review. Requires council.general.enabled: true and a search API key in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides.",category:"agent",toolPolicy:"none"},"abort-pr-workflow":{handler:(ctx)=>handleAbortPrWorkflowCommand(ctx.directory,ctx.args,ctx.sessionID),description:"Clear a stuck PR_REVIEW/PR_FEEDBACK mechanical gate and stop the auto-resume loop [mode] [reason] or PR_FEEDBACK --cancel-publication <reason...> (cancelled_without_publication)",args:"[PR_REVIEW|PR_FEEDBACK] [reason...] | PR_FEEDBACK --cancel-publication <reason...>",details:"Human-only escape hatch for an unrecoverable PR_REVIEW or PR_FEEDBACK mechanical gate. When the architect cannot reach complete_pr_workflow — for example a compound `git fetch && git checkout` was rejected as read-only shell syntax, the PR head cannot be fetched, or the working tree is on the wrong branch — running this clears the durable gate state for the current session and stops the auto-resume loop without depending on the trapped model. The agent itself cannot run this command; it must call the abort_pr_workflow tool (or ask you to run this command). Both paths funnel into the same fail-closed abortPrWorkflow hook, which refuses while the workflow is armed for publication or while PR workflow lanes are still in flight. To cancel an armed PR_FEEDBACK publication without publishing, use the exact human syntax `PR_FEEDBACK --cancel-publication <reason...>`; it requires a non-empty reason, records the terminal `cancelled_without_publication` status with the observed remote head, and never grants push authority. A plain recovery or force abort never clears an armed window. This human-only force path has exactly one exception to the lane refusal (issue #2251): when the ONLY lanes still blocking are ones past the 30-minute staleness horizon that the liveness probe reports as still running — a lane nothing will ever settle on a schedule — it clears the gate anyway, names exactly which lanes it overrode, and finalizes their delegation records so the session can start a new PR workflow. Those sessions are NOT stopped and their output is NOT collected. A lane with a fresh updatedAt still blocks even under force, and any delegation record that still keeps the session blocked is named in the warning. When checkout preparation preserved a stash, the result instructs the caller to run prepare_pr_workflow_checkout operation=restore after the clear. An audit event is appended to .swarm/events.jsonl.",category:"utility",toolPolicy:"restricted"},"pr-feedback-loop":{handler:(ctx)=>handlePrFeedbackLoopCommand(ctx.directory,ctx.args,ctx.sessionID),description:"Stop the autonomous PR babysitting settling loop for this session [stop] [reason...]",args:"stop <reason...>",details:"Human-only stop for the #2502 settling loop (triple opt-in: pr_monitor.enabled + pr_monitor.auto_pr_feedback + pr_feedback_loop.enabled). stop cancels any armed publication generation via the audited #2584 no-publish route (fail-open when nothing is armed), records a terminal cancelled state with the operator-visible reason, clears claimed-but-unsettled monitor events from the session queue via the sanctioned queue-clear primitive, and writes an atomic cleanup receipt under .swarm/pr-feedback-loop-cleanups/. Idempotent: re-running returns the same terminal without duplicating effects. Never issues new wakes; a wake already in flight may still surface in the session, but the workflow gate refuses pushes against a cancelled generation. The reason is mandatory.",category:"utility",toolPolicy:"restricted"},"approve-plan-critic":{handler:(ctx)=>handleApprovePlanCriticCommand(ctx.directory,ctx.args,ctx.sessionID),description:"Record a MANUAL plan-critic approval to unblock the critic_pre_plan execution gate [reason...]",args:"[reason...]",details:'Human-only escape hatch for the ratchet-tighter critic_pre_plan execution gate (issue #2012). 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), an enabled critic_pre_plan gate blocks coder delegation. Running this records a manual plan_critic_gate approval snapshot so the gate unblocks, with a distinct method: "manual_override" audit marker. The agent itself cannot run this command; it must call the approve_plan_critic tool (or ask you to run this command). Both paths funnel into the same forceRecordPlanCriticApproval hook, which requires an active architect session. An audit event is appended to .swarm/events.jsonl. Prefer re-running MODE: CRITIC-GATE first; use this only as an escape hatch when a legitimate APPROVED was lost.',category:"utility",toolPolicy:"restricted"},"pr-review":{handler:(ctx)=>handleModeCommandWithBundledSkills(ctx,handlePrReviewCommand,"PR_REVIEW"),description:"Launch deep PR review with multi-lane analysis [url] [--council]",args:"<pr-url|owner/repo#N|N> [--council]",details:"Launches a structured PR review: preserves dirty state, verifies and binds an exact detached PR head, reconstructs PR intent via obligation extraction cascade, computes a depth tier (S/M/L) from the bound merge-base diff, launches the base explorer wave through dispatch_lanes_async (all 6 review dimensions covered on every PR — six singleton lanes at tier L, consolidated owned_workflow_lanes partitions at tiers S/M) while the architect keeps doing non-dependent work, and polls collect_lane_results incrementally. It evaluates an exact 11-row repository-agnostic risk-family ledger, records applicable rows as MATCHED and concretely inapplicable rows as provenance-free NOT_TRIGGERED, always keeps unclassified-risk MATCHED, and dispatches micro work only for MATCHED families (dedicated lanes at tier L, consolidated sweeps at S/M). It then validates findings through independent reviewer confirmation, applies critic challenge to HIGH/CRITICAL findings, and synthesizes only after matched coverage is closed. Failed obligations retry through the same structured async mode and exact PR head; blocking or direct-Task dispatch is not provenance-equivalent, so unclosed matched coverage leaves the review BLOCKED rather than degraded. --council variant fires adversarial multi-model review. Supports full GitHub URL, owner/repo#N shorthand, or bare PR number (resolves against origin remote).",category:"agent",toolPolicy:"none"},"pr-feedback":{handler:(ctx)=>handlePrFeedbackCommandWithTransition(ctx),description:"Ingest and close known PR feedback (review comments, CI failures, conflicts) [pr] [instructions]",args:"[url|owner/repo#N|N] [instructions...]",details:"Triggers MODE: PR_FEEDBACK — ingests existing pull-request feedback (review threads, requested changes, CI/check failures, merge conflicts, stale branch state, pasted notes), verifies every claim against source, clusters related problems, fixes confirmed items, validates the branch, and reports closure status for every ledger item. Distinct from /swarm pr-review, which discovers new findings. The PR reference is optional: with none, the architect builds the ledger from the current PR/branch; text after the reference is forwarded as extra instructions. Supports full GitHub URL, owner/repo#N shorthand, or bare PR number (resolved against origin).",category:"agent",toolPolicy:"none"},ci:{handler:(ctx)=>handleCiCommand(ctx),description:"Advisory headless CI: evaluate the repo gate/evidence state read-only with machine exit codes [--timeout-ms <n>] [--json]",args:"--timeout-ms <n>, --json",details:"Host-decoupled, read-only evaluation of the checked-out repo (#2497): per-task required gates (tri-state evidence), plan-critic approval, and evidence-quality thresholds, composed from the authoritative readers. Exits 0 only when every evaluated gate passes; 1 on any violation, no-data, corrupt evidence, or a missing plan; 2 on cancellation (SIGINT/SIGTERM); 3 on deadline/internal error. Emits a Markdown report plus a [SWARM_CI_JSON] machine block. Never writes to .swarm and cannot satisfy or bypass any gate; runs with no TTY and no OpenCode host.",category:"diagnostics",toolPolicy:"none"},"ci-monitor":{handler:(ctx)=>handleModeCommandWithBundledSkills(ctx,handleCiMonitorCommand),description:"Drive an already-reviewed, approved PR to green and merged (monitor CI, fix, merge) [pr]",args:"<pr-url|owner/repo#N|N>",details:"Triggers MODE: CI_MONITOR — takes an already human-reviewed, approved PR, exhaustively researches every CI failure, fixes it end-to-end, iterates until all required checks are green (max 5 fix cycles), then merges via `gh pr merge` with no merge-strategy flag. Invoke only after human review is complete; the skill re-verifies reviewDecision: APPROVED and mergeable state before doing anything destructive. Distinct from /swarm pr-subscribe, which passively watches a PR without a merge terminal. Supports full GitHub URL, owner/repo#N shorthand, or bare PR number (resolved against origin).",category:"agent",toolPolicy:"none"},"pr subscribe":{handler:(ctx)=>handlePrSubscribeCommand(ctx.directory,ctx.args,ctx.sessionID),description:"Subscribe the current session to PR state-change notifications",args:"<pr-url|owner/repo#N|N>",details:'Subscribes the current session to PR state-change events for the specified PR. When pr_monitor.enabled is true, the background polling worker detects CI failures, new comments, review state changes (changes requested / approved), merge conflicts and conflict resolutions, and merge/close events — each gated by its pr_monitor notify_* config flag (notify_ci_success defaults to false). Delivery follows pr_monitor.event_delivery: "prompt" (default) wakes the subscribed session with a structured <pr-activity> message; "advisory" queues session-scoped advisories with dedup tokens for the next turn. Subscriptions are idempotent, capped by pr_monitor.max_subscriptions, and agent-callable. Supports full GitHub URL, owner/repo#N shorthand, or bare PR number (resolved against origin). Requires pr_monitor.enabled: true in config.',category:"agent",toolPolicy:"agent"},"pr-subscribe":{description:"Subscribe the current session to PR state-change notifications",aliasOf:"pr subscribe",deprecated:!0},"pr unsubscribe":{handler:(ctx)=>handlePrUnsubscribeCommand(ctx.directory,ctx.args,ctx.sessionID),description:"Unsubscribe the current session from PR state-change notifications",args:"<pr-url|owner/repo#N|N>",details:"Unsubscribes the current session from PR state-change events for the specified PR. Removes the active subscription record (idempotent; agent-callable). Supports full GitHub URL, owner/repo#N shorthand, or bare PR number (resolved against origin).",category:"agent",toolPolicy:"agent"},"pr-unsubscribe":{description:"Unsubscribe the current session from PR state-change notifications",aliasOf:"pr unsubscribe",deprecated:!0},"pr status":{handler:(ctx)=>handlePrMonitorStatusCommand(ctx.directory,ctx.args,ctx.sessionID,ctx.source),description:"Show PR monitor subscription status for the current session",args:"",details:"Displays all active PR subscriptions for the current session. Shows PR URL, last checked time, watching status, and error count per subscription. Also shows total active subscriptions across all sessions.",category:"agent",toolPolicy:"agent",toolNoArgs:!0},"pr-status":{description:"Show PR monitor subscription status for the current session",aliasOf:"pr status",deprecated:!0},"ci-simulate":{handler:(ctx)=>handleCiSimulateCommand(ctx.directory,ctx.args),description:"Create a temporary merge-result worktree and run CI before merge queue entry",args:"[pr-ref] [--base <ref>]",details:"Creates a detached temporary worktree under the OS temp dir (swarm-ci-simulate) from the base — an explicit validated --base <ref> when given (stacked/release-branch PRs), otherwise the detected default remote branch (origin/HEAD, init.defaultBranch, origin/main, origin/master, verified to exist) — merges the given PR ref (or the current ref), runs fixed local CI gates (typecheck, lint, build, test), then removes the worktree non-force and prunes metadata. Worktree removal is fail-closed: a blocked or dirty worktree is surfaced, never force-deleted. Intended as a pre-queue merge_group simulation helper.",category:"agent",toolPolicy:"agent"},"deep-dive":{handler:(ctx)=>handleModeCommandWithBundledSkills(ctx,handleDeepDiveCommand),description:"Launch deep codebase audit with parallel explorer waves, dual reviewers, and critic challenge [scope]",args:"<scope> [--profile standard|security|ux|architecture|full] [--max-explorers 1..8] [--json] [--skip-update] [--allow-dirty]",details:"Runs a read-only deep audit of the specified scope using parallel explorer waves (8-file cap per mission, ~3500 line guardrail), always 2 parallel reviewers for verification, and sequential critic challenge on HIGH/CRITICAL findings. Profiles select explorer lanes: standard (5 lanes), security, ux, architecture, full (all 8 lanes). Emits a structured findings report without mutating source code.",category:"agent",toolPolicy:"none"},"deep dive":{description:"Alias for /swarm deep-dive — launch deep codebase audit",args:"<scope> [--profile standard|security|ux|architecture|full] [--max-explorers 1..8] [--json] [--skip-update] [--allow-dirty]",category:"agent",aliasOf:"deep-dive"},"deep-research":{handler:(ctx)=>handleModeCommandWithBundledSkills(ctx,handleDeepResearchCommand),description:"Launch a multi-source, fact-checked deep research pass and synthesize a cited report [question]",args:"<question> [--depth standard|exhaustive] [--max-researchers 1..6] [--rounds 1..4] [--brief]",details:"Runs the orchestrator-worker deep-research protocol: the architect decomposes the question into subtopics, gathers evidence with web_search and web_fetch across up to N iterative rounds, dispatches parallel sme synthesis workers, verifies every claim against cited sources with dual reviewers, challenges high-stakes claims with the critic, and presents a cited report in chat. Read-only — does not mutate source code, delegate to coder, or call declare_scope. Requires council.general.enabled and a search API key.",category:"agent",toolPolicy:"none"},"deep research":{description:"Alias for /swarm deep-research — launch a cited deep research pass",args:"<question> [--depth standard|exhaustive] [--max-researchers 1..6] [--rounds 1..4] [--brief]",category:"agent",aliasOf:"deep-research"},"codebase-review":{handler:(ctx)=>handleModeCommandWithBundledSkills(ctx,handleCodebaseReviewCommand),description:"Launch codebase-review-swarm for a quote-grounded full-repo or large-subsystem audit",args:"[scope] [--mode phase0|complete|defect|security|correctness|testing|ui|performance|ai-slop|enhancements|custom] [--tracks <list>] [--continue <run-id>] [--json] [--skip-update] [--allow-dirty]",details:"Runs the codebase-review-swarm workflow: Phase 0 inventory, selected-track depth planning, non-diluting review passes, coverage closure, reviewer validation, critic challenge, and .swarm/review-v8 artifacts. Materializes the bundled skill package if missing, then emits a MODE signal; the architect workflow must not mutate source files.",category:"agent",toolPolicy:"none"},"codebase review":{description:"Alias for /swarm codebase-review - launch codebase-review-swarm",args:"[scope] [--mode phase0|complete|defect|security|correctness|testing|ui|performance|ai-slop|enhancements|custom] [--tracks <list>] [--continue <run-id>] [--json] [--skip-update] [--allow-dirty]",category:"agent",aliasOf:"codebase-review"},"design-docs":{handler:(ctx)=>handleModeCommandWithBundledSkills(ctx,handleDesignDocsCommand),description:"Generate or sync language-agnostic design docs (domain, technical-spec, behavior-spec, reference/) for the project under build [description]",args:"<description> [--out <dir>] [--lang <name>] [--update]",details:"Triggers the architect to enter MODE: DESIGN_DOCS — delegates to the docs_design agent to author/sync docs/domain.md, docs/technical-spec.md, docs/behavior-spec.md, and docs/reference/* (plus reference/traceability.json and design-changelog.md). Normative docs are 100% language-agnostic; all framework-specific material is quarantined under reference/. --update syncs existing docs to current code/spec instead of generating fresh. Requires design_docs.enabled: true.",category:"agent",toolPolicy:"none"},"design docs":{description:"Alias for /swarm design-docs — generate or sync design docs",args:"<description> [--out <dir>] [--lang <name>] [--update]",category:"agent",aliasOf:"design-docs"},issue:{handler:(ctx)=>handleModeCommandWithBundledSkills(ctx,handleIssueCommand),description:"Ingest a GitHub issue into the swarm workflow [url] [--plan] [--trace] [--no-repro]",args:"<issue-url|owner/repo#N|N> [--plan] [--trace] [--no-repro]",details:"Triggers the architect to enter MODE: ISSUE_INGEST — ingests a GitHub issue, restructures it into a normalized intake note, localizes root cause through hypothesis-driven tracing, and outputs a resolution spec. --plan transitions to plan creation after spec generation. --trace runs the fix workflow end-to-end (implies --plan); compose commit-pr to publish. --no-repro skips the reproduction step. Supports full GitHub URL, owner/repo#N shorthand, or bare issue number (resolves against origin remote).",category:"agent",toolPolicy:"none"},"qa-gates":{handler:(ctx)=>handleQaGatesCommand(ctx.directory,ctx.args,ctx.sessionID),description:"View or modify QA gate profile for the current plan [enable|override <gate>...]",args:"[show|enable|override] <gate>...",details:"show: display spec-level, session-override, and effective QA gates for the current plan. enable: persist gate(s) into the locked-once profile (architect; rejected after critic approval lock). override: session-only ratchet-tighter enable. Valid gates: reviewer, test_engineer, council_mode, sme_enabled, critic_pre_plan, hallucination_guard, sast_enabled, mutation_test, phase_council, drift_check, final_council.",category:"config",toolPolicy:"none"},link:{handler:(ctx)=>handleLinkCommand(ctx.directory,ctx.args),description:"Tie this worktree to a shared swarm knowledge store [name]",details:"Links the current worktree to a shared knowledge store so multiple swarms working on the same project (e.g. separate git worktrees) pool their lessons instead of each keeping an isolated .swarm/knowledge.jsonl. With no name, ties all worktrees of the same repo via the project hash; with a name, ties any worktrees/repos that use the same name. Existing local lessons are merged (deduped) into the shared store. Use `/swarm link status` to inspect.",args:"[<name> | status]",category:"utility",toolPolicy:"none"},"link status":{handler:(ctx)=>handleLinkCommand(ctx.directory,["status"]),description:"Show whether this worktree shares knowledge via a link",subcommandOf:"link",category:"utility",toolPolicy:"none"},unlink:{handler:(ctx)=>handleUnlinkCommand(ctx.directory,ctx.args),description:"Stop sharing swarm knowledge for this worktree [--no-copy]",details:"Unlinks the current worktree from its shared knowledge store and returns it to a local .swarm/knowledge.jsonl. By default the shared lessons are copied back into the local store (deduped) so nothing is lost; pass --no-copy to skip the copy-back.",args:"[--no-copy]",category:"utility",toolPolicy:"none"},promote:{handler:(ctx)=>handlePromoteCommand(ctx.directory,ctx.args),description:"Manually promote lesson to hive knowledge (policy-gated; --force --reason overrides with audit)",details:'Promotes a lesson to hive knowledge directly (--category) or via an existing swarm lesson (--from-swarm), in one cross-process policy transaction (#1847). A policy failure blocks promotion unless --force --reason "<why>" is given (audited); an entry id alone is not authorization. Requires direct text or --from-swarm. An actionability floor (#1821) needs at least one predicate flag and one scope flag (see args), unless knowledge.promotion_require_actionable=false.',args:"--category <category>, --from-swarm <lesson-id>, --applies-to-tools <a,b>, --applies-to-agents <a,b>, --required-actions <a,b>, --forbidden-actions <a,b>, --verification-checks <a,b>, --force --reason <why>, <lesson-text>",category:"utility",toolPolicy:"none"},reset:{handler:(ctx)=>handleResetCommand(ctx.directory,ctx.args),description:"Clear swarm state files [--confirm]",details:"DELETES plan.md, plan.json, context.md, events.jsonl, run-memory.jsonl, and summaries/ from .swarm/. Stops background automation and clears in-memory queues. SAFETY: requires --confirm flag — without it, displays a warning and tips to export first. Before deleting, auto-backs up the state it removes to .swarm/reset-backups/<timestamp>/ (newest 5 kept) so it can be restored by copying the files back.",args:"--confirm (required)",category:"utility",clashesWithNativeCcCommand:"/reset",toolPolicy:"restricted"},"reset-session":{handler:(ctx)=>handleResetSessionCommand(ctx.directory,ctx.args,ctx.sessionID),description:"Clear session state while preserving plan, evidence, and knowledge",details:"Deletes only .swarm/session/state.json and other session files. Clears in-memory agent sessions, delegation chains, and active-agent mappings. Preserves plan, evidence, and knowledge. Also releases this session's pending knowledge-gate obligations (#2398) and recovers stale coder settlements so dispatches cannot wedge on CODER_DISPATCH_IN_PROGRESS (#2268). Auto-backs up removed files to .swarm/reset-backups/ (newest 5 kept).",args:"--confirm=<token> (purge dirty/live lanes)",category:"utility",toolPolicy:"restricted"},attest:{handler:(ctx)=>handleAttestCommand(ctx.directory,ctx.args,ctx.sessionID),description:"Verify a git-external deliverable with pinned anchors <task_id>",details:"Runs the task's pinned read-only git evidence_anchors (issue #3422) inside the project root and records the durable external-evidence bundle that admits completion — the in-machine exit for tasks whose deliverable (commit/push, gh ops) can never produce a coder settlement. Fail-closed: the plan task must declare evidence_class external_git with 1..16 anchors (expect exact / expect_prefix non-empty), every anchor runs as a bounded no-shell argv spawn (stdin ignored, 10s per anchor, 30s total; output over the 4096-char evidence bound refuses the anchor rather than truncating it), and only positively-known read-only git subcommands/flags (rev-list, log, rev-parse, show, diff) are admitted. Undeclared tasks, mismatched anchors, and non-read-only commands refuse exactly as the completion gate does. Declaration changes revoke stale proofs (a fresh attest is then required). See docs/commands.md and docs/plan-durability.md.",args:"<task_id>",category:"utility",toolPolicy:"agent"},recover:{handler:(ctx)=>handleRecoverCommand(ctx.directory,ctx.args,ctx.sessionID),description:"Recover wedged coder settlements [task_id] [--force]",details:"Settles stale coder-settlement WALs in .swarm/coder-settlements/ — the CODER_DISPATCH_IN_PROGRESS wedge where a dispatch's completion never fired (issue #2268). Safe mode recovers settlements whose owner process is gone. --force also releases ownership keys held by this process: use only when no dispatch is genuinely running (a late completion then reports CODER_SETTLEMENT_IDEMPOTENCY_CONFLICT, safe to ignore). Never interrupts another live OpenCode process. Also repairs tasks wedged at coder_delegated with unattributed green pre_check evidence — the post-reset TASK_WORKFLOW_STAGE_A_REQUIRED wedge — and the settlement-wedge class (issue #2828): a task whose workflow drifted to idle or blocked while a COMMITTED accepted coder settlement and green post-settlement pre-check evidence still justify Stage A gets the missing stage_a_passed written directly, with a settlementRecovery marker and a stage_a_repair audit event in .swarm/events.jsonl; the architect-side audited escape hatch for the same receipts is the recover_stage_a_task tool. Both recovery surfaces also refresh the invoking session's in-memory task workflow view, so a blocked-start wedge does not survive the recovery in the session that ran it (#3043). Note that --force affects only in-process settlement-WAL ownership and does not override Stage A wedge-classification refusals. Pass [task_id] to scope both phases to one task. Diagnose and repair emit per-category status explanations (missing/stale/ambiguous/corrupt/live_wedge/settlement_wedge) with shell-correct invocation guidance per host — see docs/troubleshooting/recovery-runbook.md (#2665). Human-only.",args:"[task_id] [--force]",category:"utility",toolPolicy:"human-only"},rollback:{handler:(ctx)=>handleRollbackCommand(ctx.directory,ctx.args),description:"Restore swarm state or project files to a checkpoint",details:"Restores legacy .swarm/ phase checkpoints from checkpoints/phase-<N> when present; otherwise named git checkpoints from .swarm/checkpoints.json. SAFETY (#2946): a restore that would DESTROY uncommitted work previews first and issues a 15-minute --confirm token; re-run with that token (or --yes) to execute. Every executing restore backs up the destroyed bytes to .swarm/rollback-backups/ (newest 5). Clean trees stay single-call. Bare invocation lists checkpoints.",args:"<phase-number|label|list-number> [--confirm <token>] [--yes]",category:"utility",toolPolicy:"restricted"},retrieve:{handler:(ctx)=>handleRetrieveCommand(ctx.directory,ctx.args),description:"Retrieve full output from a summary <id>",args:"<summary-id>",details:"Loads the full tool output that was previously summarized (referenced by IDs like S1, S2). Use when you need the complete output instead of the truncated summary.",category:"utility",toolPolicy:"agent"},handoff:{handler:(ctx)=>handleHandoffCommand(ctx.directory,ctx.args,ctx.sessionID),description:"Prepare state for clean model switch (new session)",args:"",details:"Generates handoff.md with full session state snapshot, including plan progress, recent decisions, and agent delegation history. Prepended to the next session prompt for seamless model switches.",category:"core",toolPolicy:"none"},turbo:{handler:(ctx)=>handleTurboCommand(ctx.directory,ctx.args,ctx.sessionID),description:"Toggle Turbo Mode strategy for the active session [on|off|lean|standard|status]",args:"on, off, lean, standard, status",details:`Toggles Turbo Mode for the current session. Supports two strategies:
|
|
4409
|
+
`+"Session-scoped — resets on new session.",category:"utility",toolPolicy:"none"},simulate:{handler:(ctx)=>handleSimulateCommand(ctx.directory,ctx.args),description:"Dry-run hidden coupling analysis with configurable thresholds",args:"--threshold <number>, --min-commits <number>",category:"diagnostics",toolPolicy:"none"},sdd:{handler:(ctx)=>handleSddCommand(ctx.directory,ctx.args),description:"Manage OpenSpec-compatible SDD artifacts and effective spec projection",args:"status|validate|project [--json] [--change <id>] [--dry-run] [--source <provider>] [--feature <id>|all] [--overwrite]",details:"Parent command for spec-driven development artifacts. Use sdd status to inspect .swarm/spec.md plus openspec/ artifacts, sdd validate to validate OpenSpec-compatible deltas, and sdd project to materialize the effective spec into .swarm/spec.md for planning. Spec-Kit: sdd project projects ALL features with feature-scoped ids (featureId/FR-nnn) when several exist; --feature <id> selects one (v1 bare-id output); --feature all is the explicit multi-feature alias (project only).",category:"utility",toolPolicy:"agent"},"sdd status":{handler:(ctx)=>handleSddStatusCommand(ctx.directory,ctx.args),description:"Show OpenSpec-compatible SDD status and effective spec source",subcommandOf:"sdd",args:"[--json]",category:"utility",toolPolicy:"agent"},"sdd validate":{handler:(ctx)=>handleSddValidateCommand(ctx.directory,ctx.args),description:"Validate OpenSpec-compatible artifacts and effective spec projection",subcommandOf:"sdd",args:"[--json] [--change <id>]",category:"utility",toolPolicy:"agent"},"sdd project":{handler:(ctx)=>handleSddProjectCommand(ctx.directory,ctx.args),description:"Materialize the OpenSpec-compatible effective spec into .swarm/spec.md",subcommandOf:"sdd",args:"[--dry-run] [--overwrite] [--json] [--change <id>]",category:"utility",toolPolicy:"agent"},"sdd-status":{description:"Show OpenSpec-compatible SDD status and effective spec source",aliasOf:"sdd status",deprecated:!0},"sdd-validate":{description:"Validate OpenSpec-compatible artifacts and effective spec projection",aliasOf:"sdd validate",deprecated:!0},"sdd-project":{description:"Materialize the OpenSpec-compatible effective spec into .swarm/spec.md",aliasOf:"sdd project",deprecated:!0},analyze:{handler:(ctx)=>handleAnalyzeCommand(ctx.directory,ctx.args),description:"Analyze spec.md vs plan.md for requirement coverage gaps",args:"",category:"agent",toolPolicy:"none"},clarify:{handler:(ctx)=>handleModeCommandWithBundledSkills(ctx,handleClarifyCommand),description:"Clarify and refine an existing feature specification",args:"[description-text]",category:"agent",toolPolicy:"none"},specify:{handler:(ctx)=>handleModeCommandWithBundledSkills(ctx,handleSpecifyCommand),description:"Generate or import a feature specification [description]",args:"[description-text]",category:"agent",toolPolicy:"none"},brainstorm:{handler:(ctx)=>handleModeCommandWithBundledSkills(ctx,handleBrainstormCommand),description:"Enter architect MODE: BRAINSTORM — structured seven-phase planning workflow [topic]",args:"[topic-text]",details:"Triggers the architect to run the brainstorm workflow: CONTEXT SCAN, single-question DIALOGUE, APPROACHES, DESIGN SECTIONS, SPEC WRITE + SELF-REVIEW, QA GATE SELECTION, TRANSITION. Use for new plans where requirements need to be drawn out before writing spec.md / plan.md.",category:"agent",toolPolicy:"none"},loop:{handler:(ctx)=>handleModeCommandWithBundledSkills(ctx,handleLoopCommand),description:"Enter architect MODE: LOOP — compound-engineering loop: brainstorm → plan → build → review → improve, iterating until done [objective]",args:"<objective> [--max-cycles 1..5] [--autonomy checkpoint|auto] [--depth standard|exhaustive] [--resume]",details:`Triggers the architect to run the compound-engineering loop defined in ${BUNDLED_PROJECT_SKILL_ROOT}/loop/SKILL.md: BRAINSTORM (requirements) → PLAN (+ critic gate) → BUILD (execute) → REVIEW (independent reviewer + critic on the diff, report-only) → IMPROVE (phase-wrap retrospective + compounding learning capture), then evaluate stop conditions and loop for another improvement cycle if the objective is unmet and budget remains. Generator and reviewer/critic run in separate contexts; failing assertions must be fixed at the root cause, never weakened, mocked, or skipped. Defense-in-depth stop conditions: objective met, --max-cycles budget (default 3), no-progress/plateau, oscillation, unrecoverable error, or explicit user stop. --autonomy auto (default) runs unattended with hard stops still enforced; --autonomy checkpoint pauses at phase gates for user approval. --depth exhaustive widens exploration. --resume continues an existing loop run from durable .swarm/loop/ state. Distinct from full-auto (a critic gate that intercepts phase completions and high-risk actions for review — it never plans, delegates, or executes; the architect retains all delegation duty) and turbo (parallel lanes within a phase): loop is a user-initiated, gated, compounding workflow.`,category:"agent",toolPolicy:"none"},council:{handler:(ctx)=>handleModeCommandWithBundledSkills(ctx,handleCouncilCommand),description:"Enter architect MODE: COUNCIL — multi-model deliberation [question] [--spec-review]",args:"<question> [--spec-review]",details:"Triggers the architect to convene a three-agent General Council: Generalist (reviewer model), Skeptic (critic model), and Domain Expert (SME model). "+"The architect first runs 1–3 targeted web searches and passes a compiled RESEARCH CONTEXT "+"to all three agents before dispatching them in parallel. Agents deliberate using the NSED peer-review protocol (Round 1 independent analysis, Round 2 MAINTAIN/CONCEDE/NUANCE for disagreements). The architect synthesizes the final answer directly from convene_general_council output. --spec-review switches to single-pass advisory mode for spec review. Requires council.general.enabled: true and a search API key in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides.",category:"agent",toolPolicy:"none"},"abort-pr-workflow":{handler:(ctx)=>handleAbortPrWorkflowCommand(ctx.directory,ctx.args,ctx.sessionID),description:"Clear a stuck PR_REVIEW/PR_FEEDBACK mechanical gate and stop the auto-resume loop [mode] [reason] or PR_FEEDBACK --cancel-publication <reason...> (cancelled_without_publication)",args:"[PR_REVIEW|PR_FEEDBACK] [reason...] | PR_FEEDBACK --cancel-publication <reason...>",details:"Human-only escape hatch for an unrecoverable PR_REVIEW or PR_FEEDBACK mechanical gate. When the architect cannot reach complete_pr_workflow — for example a compound `git fetch && git checkout` was rejected as read-only shell syntax, the PR head cannot be fetched, or the working tree is on the wrong branch — running this clears the durable gate state for the current session and stops the auto-resume loop without depending on the trapped model. The agent itself cannot run this command; it must call the abort_pr_workflow tool (or ask you to run this command). Both paths funnel into the same fail-closed abortPrWorkflow hook, which refuses while the workflow is armed for publication or while PR workflow lanes are still in flight. To cancel an armed PR_FEEDBACK publication without publishing, use the exact human syntax `PR_FEEDBACK --cancel-publication <reason...>`; it requires a non-empty reason, records the terminal `cancelled_without_publication` status with the observed remote head, and never grants push authority. A plain recovery or force abort never clears an armed window. This human-only force path has exactly one exception to the lane refusal (issue #2251): when the ONLY lanes still blocking are ones past the 30-minute staleness horizon that the liveness probe reports as still running — a lane nothing will ever settle on a schedule — it clears the gate anyway, names exactly which lanes it overrode, and finalizes their delegation records so the session can start a new PR workflow. Those sessions are NOT stopped and their output is NOT collected. A lane with a fresh updatedAt still blocks even under force, and any delegation record that still keeps the session blocked is named in the warning. When checkout preparation preserved a stash, the result instructs the caller to run prepare_pr_workflow_checkout operation=restore after the clear. An audit event is appended to .swarm/events.jsonl.",category:"utility",toolPolicy:"restricted"},"pr-feedback-loop":{handler:(ctx)=>handlePrFeedbackLoopCommand(ctx.directory,ctx.args,ctx.sessionID),description:"Stop the autonomous PR babysitting settling loop for this session [stop] [reason...]",args:"stop <reason...>",details:"Human-only stop for the #2502 settling loop (triple opt-in: pr_monitor.enabled + pr_monitor.auto_pr_feedback + pr_feedback_loop.enabled). stop cancels any armed publication generation via the audited #2584 no-publish route (fail-open when nothing is armed), records a terminal cancelled state with the operator-visible reason, clears claimed-but-unsettled monitor events from the session queue via the sanctioned queue-clear primitive, and writes an atomic cleanup receipt under .swarm/pr-feedback-loop-cleanups/. Idempotent: re-running returns the same terminal without duplicating effects. Never issues new wakes; a wake already in flight may still surface in the session, but the workflow gate refuses pushes against a cancelled generation. The reason is mandatory.",category:"utility",toolPolicy:"restricted"},"approve-plan-critic":{handler:(ctx)=>handleApprovePlanCriticCommand(ctx.directory,ctx.args,ctx.sessionID),description:"Record a MANUAL plan-critic approval to unblock the critic_pre_plan execution gate [reason...]",args:"[reason...]",details:'Human-only escape hatch for the ratchet-tighter critic_pre_plan execution gate (issue #2012). 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), an enabled critic_pre_plan gate blocks coder delegation. Running this records a manual plan_critic_gate approval snapshot so the gate unblocks, with a distinct method: "manual_override" audit marker. The agent itself cannot run this command; it must call the approve_plan_critic tool (or ask you to run this command). Both paths funnel into the same forceRecordPlanCriticApproval hook, which requires an active architect session. An audit event is appended to .swarm/events.jsonl. Prefer re-running MODE: CRITIC-GATE first; use this only as an escape hatch when a legitimate APPROVED was lost.',category:"utility",toolPolicy:"restricted"},"pr-review":{handler:(ctx)=>handleModeCommandWithBundledSkills(ctx,handlePrReviewCommand,"PR_REVIEW"),description:"Launch deep PR review with multi-lane analysis [url] [--council]",args:"<pr-url|owner/repo#N|N> [--council]",details:"Launches a structured PR review: preserves dirty state, verifies and binds an exact detached PR head, reconstructs PR intent via obligation extraction cascade, computes a depth tier (S/M/L) from the bound merge-base diff, launches the base explorer wave through dispatch_lanes_async (all 6 review dimensions covered on every PR — six singleton lanes at tier L, consolidated owned_workflow_lanes partitions at tiers S/M) while the architect keeps doing non-dependent work, and polls collect_lane_results incrementally. It evaluates an exact 11-row repository-agnostic risk-family ledger, records applicable rows as MATCHED and concretely inapplicable rows as provenance-free NOT_TRIGGERED, always keeps unclassified-risk MATCHED, and dispatches micro work only for MATCHED families (dedicated lanes at tier L, consolidated sweeps at S/M). It then validates findings through independent reviewer confirmation, applies critic challenge to HIGH/CRITICAL findings, and synthesizes only after matched coverage is closed. Failed obligations retry through the same structured async mode and exact PR head; blocking or direct-Task dispatch is not provenance-equivalent, so unclosed matched coverage leaves the review BLOCKED rather than degraded. --council variant fires adversarial multi-model review. Supports full GitHub URL, owner/repo#N shorthand, or bare PR number (resolves against origin remote).",category:"agent",toolPolicy:"none"},"pr-feedback":{handler:(ctx)=>handlePrFeedbackCommandWithTransition(ctx),description:"Ingest and close known PR feedback (review comments, CI failures, conflicts) [pr] [instructions]",args:"[url|owner/repo#N|N] [instructions...]",details:"Triggers MODE: PR_FEEDBACK — ingests existing pull-request feedback (review threads, requested changes, CI/check failures, merge conflicts, stale branch state, pasted notes), verifies every claim against source, clusters related problems, fixes confirmed items, validates the branch, and reports closure status for every ledger item. Distinct from /swarm pr-review, which discovers new findings. The PR reference is optional: with none, the architect builds the ledger from the current PR/branch; text after the reference is forwarded as extra instructions. Supports full GitHub URL, owner/repo#N shorthand, or bare PR number (resolved against origin).",category:"agent",toolPolicy:"none"},ci:{handler:(ctx)=>handleCiCommand(ctx),description:"Advisory headless CI: evaluate the repo gate/evidence state read-only with machine exit codes [--timeout-ms <n>] [--json]",args:"--timeout-ms <n>, --json",details:"Host-decoupled, read-only evaluation of the checked-out repo (#2497): per-task required gates (tri-state evidence), plan-critic approval, and evidence-quality thresholds, composed from the authoritative readers. Exits 0 only when every evaluated gate passes; 1 on any violation, no-data, corrupt evidence, or a missing plan; 2 on cancellation (SIGINT/SIGTERM); 3 on deadline/internal error. Emits a Markdown report plus a [SWARM_CI_JSON] machine block. Never writes to .swarm and cannot satisfy or bypass any gate; runs with no TTY and no OpenCode host.",category:"diagnostics",toolPolicy:"none"},"ci-monitor":{handler:(ctx)=>handleModeCommandWithBundledSkills(ctx,handleCiMonitorCommand),description:"Drive an already-reviewed, approved PR to green and merged (monitor CI, fix, merge) [pr]",args:"<pr-url|owner/repo#N|N>",details:"Triggers MODE: CI_MONITOR — takes an already human-reviewed, approved PR, exhaustively researches every CI failure, fixes it end-to-end, iterates until all required checks are green (max 5 fix cycles), then merges via `gh pr merge` with no merge-strategy flag. Invoke only after human review is complete; the skill re-verifies reviewDecision: APPROVED and mergeable state before doing anything destructive. Distinct from /swarm pr-subscribe, which passively watches a PR without a merge terminal. Supports full GitHub URL, owner/repo#N shorthand, or bare PR number (resolved against origin).",category:"agent",toolPolicy:"none"},"pr subscribe":{handler:(ctx)=>handlePrSubscribeCommand(ctx.directory,ctx.args,ctx.sessionID),description:"Subscribe the current session to PR state-change notifications",args:"<pr-url|owner/repo#N|N>",details:'Subscribes the current session to PR state-change events for the specified PR. When pr_monitor.enabled is true, the background polling worker detects CI failures, new comments, review state changes (changes requested / approved), merge conflicts and conflict resolutions, and merge/close events — each gated by its pr_monitor notify_* config flag (notify_ci_success defaults to false). Delivery follows pr_monitor.event_delivery: "prompt" (default) wakes the subscribed session with a structured <pr-activity> message; "advisory" queues session-scoped advisories with dedup tokens for the next turn. Subscriptions are idempotent, capped by pr_monitor.max_subscriptions, and agent-callable. Supports full GitHub URL, owner/repo#N shorthand, or bare PR number (resolved against origin). Requires pr_monitor.enabled: true in config.',category:"agent",toolPolicy:"agent"},"pr-subscribe":{description:"Subscribe the current session to PR state-change notifications",aliasOf:"pr subscribe",deprecated:!0},"pr unsubscribe":{handler:(ctx)=>handlePrUnsubscribeCommand(ctx.directory,ctx.args,ctx.sessionID),description:"Unsubscribe the current session from PR state-change notifications",args:"<pr-url|owner/repo#N|N>",details:"Unsubscribes the current session from PR state-change events for the specified PR. Removes the active subscription record (idempotent; agent-callable). Supports full GitHub URL, owner/repo#N shorthand, or bare PR number (resolved against origin).",category:"agent",toolPolicy:"agent"},"pr-unsubscribe":{description:"Unsubscribe the current session from PR state-change notifications",aliasOf:"pr unsubscribe",deprecated:!0},"pr status":{handler:(ctx)=>handlePrMonitorStatusCommand(ctx.directory,ctx.args,ctx.sessionID,ctx.source),description:"Show PR monitor subscription status for the current session",args:"",details:"Displays all active PR subscriptions for the current session. Shows PR URL, last checked time, watching status, and error count per subscription. Also shows total active subscriptions across all sessions.",category:"agent",toolPolicy:"agent",toolNoArgs:!0},"pr-status":{description:"Show PR monitor subscription status for the current session",aliasOf:"pr status",deprecated:!0},"ci-simulate":{handler:(ctx)=>handleCiSimulateCommand(ctx.directory,ctx.args),description:"Create a temporary merge-result worktree and run CI before merge queue entry",args:"[pr-ref] [--base <ref>]",details:"Creates a detached temporary worktree under the OS temp dir (swarm-ci-simulate) from the base — an explicit validated --base <ref> when given (stacked/release-branch PRs), otherwise the detected default remote branch (origin/HEAD, init.defaultBranch, origin/main, origin/master, verified to exist) — merges the given PR ref (or the current ref), runs fixed local CI gates (typecheck, lint, build, test), then removes the worktree non-force and prunes metadata. Worktree removal is fail-closed: a blocked or dirty worktree is surfaced, never force-deleted. Intended as a pre-queue merge_group simulation helper.",category:"agent",toolPolicy:"agent"},"deep-dive":{handler:(ctx)=>handleModeCommandWithBundledSkills(ctx,handleDeepDiveCommand),description:"Launch deep codebase audit with parallel explorer waves, dual reviewers, and critic challenge [scope]",args:"<scope> [--profile standard|security|ux|architecture|full] [--max-explorers 1..8] [--json] [--skip-update] [--allow-dirty]",details:"Runs a read-only deep audit of the specified scope using parallel explorer waves (8-file cap per mission, ~3500 line guardrail), always 2 parallel reviewers for verification, and sequential critic challenge on HIGH/CRITICAL findings. Profiles select explorer lanes: standard (5 lanes), security, ux, architecture, full (all 8 lanes). Emits a structured findings report without mutating source code.",category:"agent",toolPolicy:"none"},"deep dive":{description:"Alias for /swarm deep-dive — launch deep codebase audit",args:"<scope> [--profile standard|security|ux|architecture|full] [--max-explorers 1..8] [--json] [--skip-update] [--allow-dirty]",category:"agent",aliasOf:"deep-dive"},"deep-research":{handler:(ctx)=>handleModeCommandWithBundledSkills(ctx,handleDeepResearchCommand),description:"Launch a multi-source, fact-checked deep research pass and synthesize a cited report [question]",args:"<question> [--depth standard|exhaustive] [--max-researchers 1..6] [--rounds 1..4] [--brief]",details:"Runs the orchestrator-worker deep-research protocol: the architect decomposes the question into subtopics, gathers evidence with web_search and web_fetch across up to N iterative rounds, dispatches parallel sme synthesis workers, verifies every claim against cited sources with dual reviewers, challenges high-stakes claims with the critic, and presents a cited report in chat. Read-only — does not mutate source code, delegate to coder, or call declare_scope. Requires council.general.enabled and a search API key.",category:"agent",toolPolicy:"none"},"deep research":{description:"Alias for /swarm deep-research — launch a cited deep research pass",args:"<question> [--depth standard|exhaustive] [--max-researchers 1..6] [--rounds 1..4] [--brief]",category:"agent",aliasOf:"deep-research"},"codebase-review":{handler:(ctx)=>handleModeCommandWithBundledSkills(ctx,handleCodebaseReviewCommand),description:"Launch codebase-review-swarm for a quote-grounded full-repo or large-subsystem audit",args:"[scope] [--mode phase0|complete|defect|security|correctness|testing|ui|performance|ai-slop|enhancements|custom] [--tracks <list>] [--continue <run-id>] [--json] [--skip-update] [--allow-dirty]",details:"Runs the codebase-review-swarm workflow: Phase 0 inventory, selected-track depth planning, non-diluting review passes, coverage closure, reviewer validation, critic challenge, and .swarm/review-v8 artifacts. Materializes the bundled skill package if missing, then emits a MODE signal; the architect workflow must not mutate source files.",category:"agent",toolPolicy:"none"},"codebase review":{description:"Alias for /swarm codebase-review - launch codebase-review-swarm",args:"[scope] [--mode phase0|complete|defect|security|correctness|testing|ui|performance|ai-slop|enhancements|custom] [--tracks <list>] [--continue <run-id>] [--json] [--skip-update] [--allow-dirty]",category:"agent",aliasOf:"codebase-review"},"design-docs":{handler:(ctx)=>handleModeCommandWithBundledSkills(ctx,handleDesignDocsCommand),description:"Generate or sync language-agnostic design docs (domain, technical-spec, behavior-spec, reference/) for the project under build [description]",args:"<description> [--out <dir>] [--lang <name>] [--update]",details:"Triggers the architect to enter MODE: DESIGN_DOCS — delegates to the docs_design agent to author/sync docs/domain.md, docs/technical-spec.md, docs/behavior-spec.md, and docs/reference/* (plus reference/traceability.json and design-changelog.md). Normative docs are 100% language-agnostic; all framework-specific material is quarantined under reference/. --update syncs existing docs to current code/spec instead of generating fresh. Requires design_docs.enabled: true.",category:"agent",toolPolicy:"none"},"design docs":{description:"Alias for /swarm design-docs — generate or sync design docs",args:"<description> [--out <dir>] [--lang <name>] [--update]",category:"agent",aliasOf:"design-docs"},issue:{handler:(ctx)=>handleModeCommandWithBundledSkills(ctx,handleIssueCommand),description:"Ingest a GitHub issue into the swarm workflow [url] [--plan] [--trace] [--no-repro]",args:"<issue-url|owner/repo#N|N> [--plan] [--trace] [--no-repro]",details:"Triggers the architect to enter MODE: ISSUE_INGEST — ingests a GitHub issue, restructures it into a normalized intake note, localizes root cause through hypothesis-driven tracing, and outputs a resolution spec. --plan transitions to plan creation after spec generation. --trace runs the fix workflow end-to-end (implies --plan); compose commit-pr to publish. --no-repro skips the reproduction step. Supports full GitHub URL, owner/repo#N shorthand, or bare issue number (resolves against origin remote).",category:"agent",toolPolicy:"none"},"qa-gates":{handler:(ctx)=>handleQaGatesCommand(ctx.directory,ctx.args,ctx.sessionID),description:"View or modify QA gate profile for the current plan [enable|override <gate>...]",args:"[show|enable|override] <gate>...",details:"show: display spec-level, session-override, and effective QA gates for the current plan. enable: persist gate(s) into the locked-once profile (architect; rejected after critic approval lock). override: session-only ratchet-tighter enable. Valid gates: reviewer, test_engineer, council_mode, sme_enabled, critic_pre_plan, hallucination_guard, sast_enabled, mutation_test, phase_council, drift_check, final_council.",category:"config",toolPolicy:"none"},link:{handler:(ctx)=>handleLinkCommand(ctx.directory,ctx.args),description:"Tie this worktree to a shared swarm knowledge store [name]",details:"Links the current worktree to a shared knowledge store so multiple swarms working on the same project (e.g. separate git worktrees) pool their lessons instead of each keeping an isolated .swarm/knowledge.jsonl. With no name, ties all worktrees of the same repo via the project hash; with a name, ties any worktrees/repos that use the same name. Existing local lessons are merged (deduped) into the shared store. Use `/swarm link status` to inspect.",args:"[<name> | status]",category:"utility",toolPolicy:"none"},"link status":{handler:(ctx)=>handleLinkCommand(ctx.directory,["status"]),description:"Show whether this worktree shares knowledge via a link",subcommandOf:"link",category:"utility",toolPolicy:"none"},unlink:{handler:(ctx)=>handleUnlinkCommand(ctx.directory,ctx.args),description:"Stop sharing swarm knowledge for this worktree [--no-copy]",details:"Unlinks the current worktree from its shared knowledge store and returns it to a local .swarm/knowledge.jsonl. By default the shared lessons are copied back into the local store (deduped) so nothing is lost; pass --no-copy to skip the copy-back.",args:"[--no-copy]",category:"utility",toolPolicy:"none"},promote:{handler:(ctx)=>handlePromoteCommand(ctx.directory,ctx.args),description:"Manually promote lesson to hive knowledge (policy-gated; --force --reason overrides with audit)",details:'Promotes a lesson to hive knowledge directly (--category) or via an existing swarm lesson (--from-swarm), in one cross-process policy transaction (#1847). A policy failure blocks promotion unless --force --reason "<why>" is given (audited); an entry id alone is not authorization. Requires direct text or --from-swarm. An actionability floor (#1821) needs at least one predicate flag and one scope flag (see args), unless knowledge.promotion_require_actionable=false.',args:"--category <category>, --from-swarm <lesson-id>, --applies-to-tools <a,b>, --applies-to-agents <a,b>, --required-actions <a,b>, --forbidden-actions <a,b>, --verification-checks <a,b>, --force --reason <why>, <lesson-text>",category:"utility",toolPolicy:"none"},reset:{handler:(ctx)=>handleResetCommand(ctx.directory,ctx.args),description:"Clear swarm state files [--confirm]",details:"DELETES plan.md, plan.json, context.md, events.jsonl, run-memory.jsonl, and summaries/ from .swarm/. Stops background automation and clears in-memory queues. SAFETY: requires --confirm flag — without it, displays a warning and tips to export first. Before deleting, auto-backs up the state it removes to .swarm/reset-backups/<timestamp>/ (newest 5 kept) so it can be restored by copying the files back.",args:"--confirm (required)",category:"utility",clashesWithNativeCcCommand:"/reset",toolPolicy:"restricted"},"reset-session":{handler:(ctx)=>handleResetSessionCommand(ctx.directory,ctx.args,ctx.sessionID),description:"Clear session state while preserving plan, evidence, and knowledge",details:"Deletes .swarm/session/state.json plus other session files; clears in-memory sessions, chains, and active-agent maps. Preserves plan, evidence, and knowledge; releases this session's pending knowledge-gate obligations (#2398); recovers coder settlements wedged on CODER_DISPATCH_IN_PROGRESS (#2268); backs up to .swarm/reset-backups/ (newest 5 kept). If a cleanup step fails, the closing guard stays closed by design, writes pause (an advisory says why), and a reset re-run or restart recovers.",args:"--confirm=<token> (purge dirty/live lanes)",category:"utility",toolPolicy:"restricted"},attest:{handler:(ctx)=>handleAttestCommand(ctx.directory,ctx.args,ctx.sessionID),description:"Verify a git-external deliverable with pinned anchors <task_id>",details:"Runs the task's pinned read-only git evidence_anchors (issue #3422) inside the project root and records the durable external-evidence bundle that admits completion — the in-machine exit for tasks whose deliverable (commit/push, gh ops) can never produce a coder settlement. Fail-closed: the plan task must declare evidence_class external_git with 1..16 anchors (expect exact / expect_prefix non-empty), every anchor runs as a bounded no-shell argv spawn (stdin ignored, 10s per anchor, 30s total; output over the 4096-char evidence bound refuses the anchor rather than truncating it), and only positively-known read-only git subcommands/flags (rev-list, log, rev-parse, show, diff) are admitted. Undeclared tasks, mismatched anchors, and non-read-only commands refuse exactly as the completion gate does. Declaration changes revoke stale proofs (a fresh attest is then required). See docs/commands.md and docs/plan-durability.md.",args:"<task_id>",category:"utility",toolPolicy:"agent"},recover:{handler:(ctx)=>handleRecoverCommand(ctx.directory,ctx.args,ctx.sessionID),description:"Recover wedged coder settlements [task_id] [--force]",details:"Settles stale coder-settlement WALs in .swarm/coder-settlements/ — the CODER_DISPATCH_IN_PROGRESS wedge where a dispatch's completion never fired (issue #2268). Safe mode recovers settlements whose owner process is gone. --force also releases ownership keys held by this process: use only when no dispatch is genuinely running (a late completion then reports CODER_SETTLEMENT_IDEMPOTENCY_CONFLICT, safe to ignore). Never interrupts another live OpenCode process. Also repairs tasks wedged at coder_delegated with unattributed green pre_check evidence — the post-reset TASK_WORKFLOW_STAGE_A_REQUIRED wedge — and the settlement-wedge class (issue #2828): a task whose workflow drifted to idle or blocked while a COMMITTED accepted coder settlement and green post-settlement pre-check evidence still justify Stage A gets the missing stage_a_passed written directly, with a settlementRecovery marker and a stage_a_repair audit event in .swarm/events.jsonl; the architect-side audited escape hatch for the same receipts is the recover_stage_a_task tool. Both recovery surfaces also refresh the invoking session's in-memory task workflow view, so a blocked-start wedge does not survive the recovery in the session that ran it (#3043). Note that --force affects only in-process settlement-WAL ownership and does not override Stage A wedge-classification refusals. Pass [task_id] to scope both phases to one task. Diagnose and repair emit per-category status explanations (missing/stale/ambiguous/corrupt/live_wedge/settlement_wedge) with shell-correct invocation guidance per host — see docs/troubleshooting/recovery-runbook.md (#2665). Human-only.",args:"[task_id] [--force]",category:"utility",toolPolicy:"human-only"},rollback:{handler:(ctx)=>handleRollbackCommand(ctx.directory,ctx.args),description:"Restore swarm state or project files to a checkpoint",details:"Restores legacy .swarm/ phase checkpoints from checkpoints/phase-<N> when present; otherwise named git checkpoints from .swarm/checkpoints.json. SAFETY (#2946): a restore that would DESTROY uncommitted work previews first and issues a 15-minute --confirm token; re-run with that token (or --yes) to execute. Every executing restore backs up the destroyed bytes to .swarm/rollback-backups/ (newest 5). Clean trees stay single-call. Bare invocation lists checkpoints.",args:"<phase-number|label|list-number> [--confirm <token>] [--yes]",category:"utility",toolPolicy:"restricted"},retrieve:{handler:(ctx)=>handleRetrieveCommand(ctx.directory,ctx.args),description:"Retrieve full output from a summary <id>",args:"<summary-id>",details:"Loads the full tool output that was previously summarized (referenced by IDs like S1, S2). Use when you need the complete output instead of the truncated summary.",category:"utility",toolPolicy:"agent"},handoff:{handler:(ctx)=>handleHandoffCommand(ctx.directory,ctx.args,ctx.sessionID),description:"Prepare state for clean model switch (new session)",args:"",details:"Generates handoff.md with full session state snapshot, including plan progress, recent decisions, and agent delegation history. Prepended to the next session prompt for seamless model switches.",category:"core",toolPolicy:"none"},turbo:{handler:(ctx)=>handleTurboCommand(ctx.directory,ctx.args,ctx.sessionID),description:"Toggle Turbo Mode strategy for the active session [on|off|lean|standard|status]",args:"on, off, lean, standard, status",details:`Toggles Turbo Mode for the current session. Supports two strategies:
|
|
4406
4410
|
|
|
4407
4411
|
`+`**Standard turbo** — ${TURBO_BYPASS_DISCLOSURE}
|
|
4408
4412
|
`+`**Lean turbo** — parallel lane execution with per-lane reviewer gates and file-lock conflict detection. ${TURBO_BYPASS_DISCLOSURE}
|