opencode-swarm 7.186.2 → 7.186.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/binaries/win32-arm64/swarm-sandbox-runner.exe +0 -0
- package/binaries/win32-x64/swarm-sandbox-runner.exe +0 -0
- package/dist/cli/{auto-checkpoint-c7ykm2vt.js → auto-checkpoint-3fsd5nhp.js} +7 -7
- package/dist/cli/{checkpoint-jafvsq23.js → checkpoint-cnt2zfc4.js} +12 -12
- package/dist/cli/{coder-settlement-n00djebn.js → coder-settlement-h9t6anbr.js} +8 -8
- package/dist/cli/{config-doctor-17yft6hp.js → config-doctor-7vewvger.js} +2 -2
- package/dist/cli/{core-trk38w53.js → core-azfp090f.js} +1 -1
- package/dist/cli/{curation-policy-1zdsb3h0.js → curation-policy-3dvythny.js} +5 -5
- package/dist/cli/{curator-yvp2e7tk.js → curator-6347y33h.js} +34 -34
- package/dist/cli/{curator-drift-b6cjgsq3.js → curator-drift-rsh7k3vj.js} +5 -5
- package/dist/cli/{curator-llm-factory-a1hy89ea.js → curator-llm-factory-bvazaeax.js} +34 -34
- package/dist/cli/{evidence-summary-service-9vh0t896.js → evidence-summary-service-71g302wy.js} +15 -15
- package/dist/cli/{gate-evidence-tbjsm6r8.js → gate-evidence-zfj7q5f7.js} +5 -5
- package/dist/cli/{guardrail-explain-a16eabym.js → guardrail-explain-mfgjbr2t.js} +35 -35
- package/dist/cli/{guardrail-log-4kj5e7da.js → guardrail-log-j0afxr5d.js} +6 -6
- package/dist/cli/{guardrail-reset-fstvd42q.js → guardrail-reset-mqv4chxa.js} +34 -34
- package/dist/cli/{hive-promoter-68prvn82.js → hive-promoter-5t3xhvf5.js} +34 -34
- package/dist/cli/{index-y8prb5a1.js → index-02fema92.js} +3 -3
- package/dist/cli/{index-tnt9dnvm.js → index-02stsgw6.js} +4 -4
- package/dist/cli/{index-8r96zar7.js → index-0ab8x2nj.js} +1 -1
- package/dist/cli/{index-w3fyzw3s.js → index-0tccxc8m.js} +1 -1
- package/dist/cli/{index-k3gz8b6j.js → index-1cdkdha7.js} +4 -4
- package/dist/cli/{index-5cybjkj0.js → index-2mtbc0wz.js} +1 -1
- package/dist/cli/{index-4tpwp24b.js → index-4dkmehar.js} +1 -1
- package/dist/cli/{index-n8aep8en.js → index-5mh1638n.js} +4 -4
- package/dist/cli/{index-kbcx6rqh.js → index-743kwz1r.js} +2 -2
- package/dist/cli/{index-d7kz64yr.js → index-7fk8zcnj.js} +1 -1
- package/dist/cli/{index-qd5pnbz9.js → index-8fhczdja.js} +7 -7
- package/dist/cli/{index-h8pb617g.js → index-8jhpedx9.js} +2 -2
- package/dist/cli/{index-cbpggzdm.js → index-8y9p665v.js} +1 -1
- package/dist/cli/{index-nq6evkky.js → index-92hcbz8j.js} +3 -3
- package/dist/cli/{index-8n2emawn.js → index-bb2myjge.js} +2 -2
- package/dist/cli/{index-g23nwtfq.js → index-dg39ea2t.js} +2 -2
- package/dist/cli/{index-3w0v6n9x.js → index-f2nbkpsd.js} +5 -5
- package/dist/cli/{index-sqksezk4.js → index-h9gkgwn6.js} +1 -1
- package/dist/cli/{index-s5ek7jdr.js → index-htwb6znd.js} +7 -7
- package/dist/cli/{index-98hksf1k.js → index-j0j82th1.js} +1 -1
- package/dist/cli/{index-a07nc99k.js → index-j3j3xknh.js} +3 -3
- package/dist/cli/{index-js4spqjf.js → index-m47nt45k.js} +4 -4
- package/dist/cli/{index-8ehsv9yw.js → index-m9xhje7p.js} +1 -1
- package/dist/cli/{index-hdeqj1k4.js → index-mcvp13x7.js} +1 -1
- package/dist/cli/{index-y9wsfekf.js → index-mr86ywsj.js} +1 -1
- package/dist/cli/{index-27yspj61.js → index-ne82w55j.js} +6 -6
- package/dist/cli/{index-mqc6phah.js → index-nkr29v6k.js} +3 -3
- package/dist/cli/{index-f2mtzrsr.js → index-p3tkx10s.js} +4 -4
- package/dist/cli/{index-msejg9hk.js → index-qt6101j8.js} +1 -1
- package/dist/cli/{index-pppczpa6.js → index-scasxhsf.js} +34 -34
- package/dist/cli/{index-3h80xyek.js → index-sev04gtf.js} +2 -2
- package/dist/cli/{index-1m3502g5.js → index-tq8f6ar8.js} +3 -3
- package/dist/cli/{index-b58k1wy8.js → index-tynapn5c.js} +85 -86
- package/dist/cli/{index-5qbm61fh.js → index-v2b00xgq.js} +1 -1
- package/dist/cli/{index-70m4cxys.js → index-vacbzrma.js} +1 -1
- package/dist/cli/{index-1f7mkb7p.js → index-xdjwefa5.js} +43 -43
- package/dist/cli/{index-52s3tsmj.js → index-xdtt2xxx.js} +2 -2
- package/dist/cli/{index-fxvthwwk.js → index-xn3axfb7.js} +36 -36
- package/dist/cli/{index-g7rp7200.js → index-ys4888ae.js} +3 -3
- package/dist/cli/index.js +35 -35
- package/dist/cli/{knowledge-escalator-7xdvw9qy.js → knowledge-escalator-d51hm9bf.js} +11 -11
- package/dist/cli/{knowledge-events-hp5yr9dm.js → knowledge-events-7n6fq6ga.js} +9 -9
- package/dist/cli/{knowledge-link-5jhded41.js → knowledge-link-xwn2ww1d.js} +4 -4
- package/dist/cli/{knowledge-store-7erepd4t.js → knowledge-store-5yq3dr0w.js} +5 -5
- package/dist/cli/{knowledge-validator-ejdh74qq.js → knowledge-validator-snb5k0t7.js} +7 -7
- package/dist/cli/{mcp-msrbe1bx.js → mcp-85386zbc.js} +1 -1
- package/dist/cli/{model-preflight-gsesc142.js → model-preflight-bjcm13dz.js} +34 -34
- package/dist/cli/{pending-delegations-97pcsaak.js → pending-delegations-gajb3g07.js} +7 -7
- package/dist/cli/{pr-subscriptions-p0dm693y.js → pr-subscriptions-5nxh5d6n.js} +7 -7
- package/dist/cli/{pr-workflow-gate-y122hbd1.js → pr-workflow-gate-2ky49yr6.js} +34 -34
- package/dist/cli/{runner-fbmancth.js → runner-mfxyvzv5.js} +5 -5
- package/dist/cli/{scan-cursor-yp2kvnjz.js → scan-cursor-44kwkvzz.js} +6 -6
- package/dist/cli/{schema-0jatfw66.js → schema-f8rw7sep.js} +1 -1
- package/dist/cli/{scope-persistence-hqw7br2s.js → scope-persistence-90yg8kfc.js} +11 -11
- package/dist/cli/{server-kyqq4pan.js → server-x5aaqtfp.js} +34 -34
- package/dist/cli/{skill-generator-0hbmdy2p.js → skill-generator-5dytd2v5.js} +13 -13
- package/dist/cli/{snapshot-coordination-init-akt1wad4.js → snapshot-coordination-init-16g8rnk9.js} +34 -34
- package/dist/cli/{speckit-checkoff-rnfy30qb.js → speckit-checkoff-s06hxcsr.js} +3 -3
- package/dist/cli/{telemetry-3bjvjbcp.js → telemetry-rb8hrvbx.js} +1 -1
- package/dist/cli/{worktree-collision-ownership-q4604rmc.js → worktree-collision-ownership-rfspbxph.js} +7 -7
- package/dist/cli/{worktree-isolation-5bafpzf9.js → worktree-isolation-1bzyww4e.js} +34 -34
- package/dist/hooks/diff-scope.d.ts +24 -1
- package/dist/index.js +14 -14
- package/dist/services/cost-accounting.d.ts +2 -0
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{createRequire}from"node:module";var __create=Object.create;var{getPrototypeOf:__getProtoOf,defineProperty:__defProp,getOwnPropertyNames:__getOwnPropNames,getOwnPropertyDescriptor:__getOwnPropDesc}=Object,__hasOwnProp=Object.prototype.hasOwnProperty;function __accessProp(key){return this[key]}var __toESMCache_node,__toESMCache_esm,__toESM=(mod,isNodeMode,target)=>{var canCache=mod!=null&&typeof mod==="object";if(canCache){var cache=isNodeMode?__toESMCache_node??=new WeakMap:__toESMCache_esm??=new WeakMap,cached=cache.get(mod);if(cached)return cached}target=mod!=null?__create(__getProtoOf(mod)):{};let to=isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target;for(let key of __getOwnPropNames(mod))if(!__hasOwnProp.call(to,key))__defProp(to,key,{get:__accessProp.bind(mod,key),enumerable:!0});if(canCache)cache.set(mod,to);return to},__toCommonJS=(from)=>{var entry=(__moduleCache??=new WeakMap).get(from),desc;if(entry)return entry;if(entry=__defProp({},"__esModule",{value:!0}),from&&typeof from==="object"||typeof from==="function"){for(var key of __getOwnPropNames(from))if(!__hasOwnProp.call(entry,key))__defProp(entry,key,{get:__accessProp.bind(from,key),enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return __moduleCache.set(from,entry),entry},__moduleCache,__commonJS=(cb,mod)=>()=>(mod||cb((mod={exports:{}}).exports,mod),mod.exports);var __returnValue=(v)=>v;function __exportSetter(name,newValue){this[name]=__returnValue.bind(null,newValue)}var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0,configurable:!0,set:__exportSetter.bind(all,name)})};var __esm=(fn2,res)=>()=>(fn2&&(res=fn2(fn2=0)),res);var __require=createRequire(import.meta.url);var package_default;var init_package=__esm(()=>{package_default={name:"opencode-swarm",version:"7.186.2",description:"Architect-centric agentic swarm plugin for OpenCode - hub-and-spoke orchestration with SME consultation, code generation, and QA review",main:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",default:"./dist/index.js"},"./package.json":"./package.json"},bin:{"opencode-swarm":"./dist/cli/index.js"},type:"module",engines:{bun:">=1.3.13",node:">=22.13"},license:"MIT",repository:{type:"git",url:"https://github.com/ZaxbyHub/opencode-swarm.git"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},keywords:["opencode","opencode-plugin","ai","agents","orchestration","swarm","multi-agent","llm"],files:["dist","dist/lang/grammars","binaries","evaluation-fixtures",".opencode/skills/brainstorm",".opencode/skills/specify",".opencode/skills/clarify-spec",".opencode/skills/swarm-resume",".opencode/skills/clarify",".opencode/skills/discover",".opencode/skills/consult",".opencode/skills/pre-phase-briefing",".opencode/skills/council",".opencode/skills/deep-dive",".opencode/skills/deep-research",".opencode/skills/codebase-review-swarm",".opencode/skills/swarm-implement",".opencode/skills/design-docs",".opencode/skills/swarm-pr-review",".opencode/skills/swarm",".opencode/skills/swarm-pr-feedback",".opencode/skills/swarm-pr-subscribe",".opencode/skills/swarm-ci-monitor",".opencode/skills/issue-ingest",".opencode/skills/swarm-plan",".opencode/skills/critic-gate",".opencode/skills/execute",".opencode/skills/phase-wrap",".opencode/skills/loop",".opencode/skills/writing-tests",".opencode/skills/running-tests",".opencode/skills/engineering-conventions",".opencode/skills/commit-pr",".opencode/skills/ci-failure-batching",".opencode/skills/gate-attribution",".opencode/skills/merge-queue-readiness",".opencode/skills/skill-edit-validation",".opencode/skills/worktree-retry-cleanup",".opencode/skills/test-file-split",".opencode/skills/fork-pr-operations",".opencode/skills/parallel-work-check",".opencode/skills/ci-fix-monitor",".opencode/skills/issue-tracer",".opencode/skills/orchestrating-subagents",".opencode/skills/durable-session-state","tests/fixtures/memory-recall","tests/fixtures/memory-recall-heldout","opencode-swarm.schema.json","README.md","LICENSE"],scripts:{clean:`bun -e "require('fs').rmSync('dist',{recursive:true,force:true})"`,build:"bun run clean && bun run scripts/generate-config-schema.ts && bun run scripts/copy-grammars.ts && bun build src/index.ts --outdir dist --target node --format esm --external web-tree-sitter --minify-whitespace --minify-syntax && bun build src/cli/index.ts --outdir dist/cli --target bun --format esm --external bash-parser --splitting && bun run scripts/copy-grammars.ts --to-dist && tsc --emitDeclarationOnly",typecheck:"tsc --noEmit",test:"bun test",lint:"biome lint .","lint:ci":"biome ci .","test:unit:ci":"bun scripts/ci/run-unit-tests-local.ts","validate:repo":"bun scripts/ci/repository-validation.ts","drift:check":"bun run scripts/drift-check.ts","check:pre-push":"bun run scripts/drift-check.ts --enforce --no-report && bun run check:registry-citations","schema:generate":"bun run scripts/generate-config-schema.ts","generate:commands-docs":"bun run scripts/generate-commands-docs.ts","check:runtime-src-refs":"bun run scripts/check-runtime-src-refs.ts","drift:fix":"bun run scripts/drift-check.ts --fix --confirm","skills:sync":"bun run scripts/sync-qa-gate-skills.ts",format:"biome format . --write",check:"biome check --write .",dev:"bun run build && opencode","package:smoke":"node scripts/package-smoke.mjs",prepare:"bun run build","repro:704":"node scripts/repro-704.mjs","repro:2669":"node scripts/repro-2669.mjs","repro:2670":"node scripts/repro-2670.mjs","repro:1144":"bun scripts/repro-1144.mjs","repro:1873":"bun build scripts/repro-1873-entry.ts --outdir dist-build-test/repro-1873 --target node --format esm && node scripts/repro-1873.mjs","repro:2487":"bun build scripts/repro-2487-parity-entry.ts --outdir dist-build-test/repro-2487 --target node --format esm && node scripts/repro-2487-parity.mjs","check:events":"bun run scripts/check-event-contract.ts","check:retention":"bun run scripts/check-retention-registry.ts","check:core-events":"bun run scripts/check-core-events-usage.ts","check:shell-audit":"bun run scripts/check-shell-audit-usage.ts","check:trajectory-store":"bun run scripts/check-trajectory-store-usage.ts","check:mock-cleanup":"bun run scripts/check-mock-cleanup.ts","check:invariants":"bun run scripts/check-invariants.ts","check:token-formula":"bun run scripts/check-token-formula.ts","check:cross-contamination":"bun run scripts/check-cross-contamination.ts","check:test-clock":"bun run scripts/check-test-clock.ts","check:test-file-cap":"bun run scripts/check-test-file-cap.ts","check:test-tmpdir":"bun run scripts/check-test-tmpdir.ts","check:bash-portability":"bun run scripts/check-bash-portability.ts","check:pending-fragment":"bun run scripts/check-pending-fragment.ts","check:gate-portability":"bun run scripts/check-gate-portability.ts","check:bare-spawn":"bun run scripts/check-bare-executable-spawn.ts","check:error-channel-discard":"bun run scripts/check-error-channel-discard.ts","check:path-identity":"bun run scripts/check-path-identity.ts","check:registry-citations":"bun run scripts/check-registry-citations.ts","check:memory-recall":"bun run scripts/memory-recall-regression.ts","check:retrieval-quality":"bun run scripts/retrieval-quality-regression.ts"},dependencies:{"@modelcontextprotocol/sdk":"^1.30.0","@opencode-ai/plugin":"^1.18.3","@opencode-ai/sdk":"^1.18.3","@vscode/tree-sitter-wasm":"^0.3.0","bash-parser":"^0.5.0","p-limit":"^7.3.0",picomatch:"^4.0.4","proper-lockfile":"^4.1.2","quick-lru":"^7.3.0","web-tree-sitter":"^0.25.0",zod:"4.3.6"},devDependencies:{"@biomejs/biome":"2.3.14","@types/picomatch":"^4.0.3","bun-types":"1.3.8","js-yaml":"^4.1.1",typescript:"^5.7.3"},peerDependencies:{"@xenova/transformers":"^2.17.2"},peerDependenciesMeta:{"@xenova/transformers":{optional:!0}}}});var QA_AGENTS,PIPELINE_AGENTS,ORCHESTRATOR_NAME="architect",ALL_SUBAGENT_NAMES,ALL_AGENT_NAMES;var init_agent_names=__esm(()=>{QA_AGENTS=["reviewer","critic","critic_oversight","critic_finding_validator"],PIPELINE_AGENTS=["explorer","coder","test_engineer"],ALL_SUBAGENT_NAMES=["sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","curator_postmortem","curator_consolidation","council_generalist","council_skeptic","council_domain_expert","skill_improver","spec_writer",...QA_AGENTS,...PIPELINE_AGENTS],ALL_AGENT_NAMES=["architect",...ALL_SUBAGENT_NAMES]});function getPrWorkflowToolCapability(toolName,mode){let metadata=TOOL_METADATA[toolName];if(!metadata?.prWorkflow?.modes.includes(mode))return null;return metadata.prWorkflow.capability}var TOOL_METADATA,TOOL_NAMES,TOOL_NAME_SET,TOOL_DESCRIPTIONS,AGENT_TOOL_MAP;var init_tool_metadata=__esm(()=>{init_agent_names();TOOL_METADATA={diff:{description:"structured git diff with contract change detection",agents:["architect","reviewer","critic_finding_validator","critic_oversight","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},diff_summary:{description:"filter classified AST changes by category, risk level, or file for reviewer drill-down",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},syntax_check:{description:"check syntax of source files using tree-sitter parsers across multiple languages, returning per-file errors",agents:["architect","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},placeholder_scan:{description:"todo and FIXME comment detection",agents:["architect","reviewer","critic_finding_validator"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},imports:{description:"find all consumers that import from a given file — use before refactoring shared modules to avoid breaking unseen dependents",agents:["architect","sme","researcher","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},lint:{description:"run project linter in check or fix mode; supports biome, eslint, ruff, clippy, and more, returns structured results",agents:["architect","reviewer","critic_finding_validator","coder"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},secretscan:{description:"scan for secrets (API keys, tokens, passwords) via regex and entropy; returns redacted previews, excludes common dirs",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},sast_scan:{description:"static analysis security scan",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},build_check:{description:"discover and run build, typecheck, and test commands for various project ecosystems in the working directory",agents:["architect","coder","test_engineer"]},pre_check_batch:{description:"parallel verification: lint:check + secretscan + sast_scan + quality_budget",agents:["architect","reviewer","critic_finding_validator"]},quality_budget:{description:"code quality budget check",agents:["architect"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},symbols:{description:"extract exported symbols (functions, classes, interfaces, types) from source files; supports TypeScript, JavaScript, and Python",agents:["architect","sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},complexity_hotspots:{description:"git churn × complexity risk map",agents:["architect","sme","researcher","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","critic_oversight","explorer","test_engineer"]},schema_drift:{description:"OpenAPI spec vs route drift",agents:["architect","sme","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},todo_extract:{description:"structured TODO/FIXME extraction; with task_id, records the high-priority count as todo_scan gate evidence",agents:["architect","researcher","docs","explorer","coder"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},evidence_check:{description:"verify task evidence completeness",agents:["architect","critic_oversight"]},check_gate_status:{description:"check the gate status of a specific task",agents:["architect","critic_oversight"]},completion_verify:{description:"verify completed tasks have required evidence",agents:["architect","critic_oversight"]},complete_pr_workflow:{description:"validate terminal PR workflow evidence and clear its durable session gate",agents:["architect"]},abort_pr_workflow:{description:"abort an unrecoverable PR_REVIEW/PR_FEEDBACK mechanical gate and clear its durable session state",agents:["architect"]},authorize_pr_review_reentry:{description:"issue a one-use, identity-bound reviewer/test_engineer re-entry authorization for the active PR_REVIEW workflow (issue #2383)",agents:["architect"]},submit_pr_review_result:{description:"submit one child-bound typed result for an active PR-review base or micro discovery lane",agents:[],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},approve_plan_critic:{description:"record a MANUAL plan_critic_gate approval snapshot to unblock the ratchet-tighter critic_pre_plan execution gate when the critic already returned APPROVED but the mechanical recorder failed to persist it (issue #2012), or as the sanctioned recovery for a bookkeeping-grade hashed-field repair under the critic-gate PLAN FREEZE rule (the reason must state which case applies)",agents:["architect"]},approve_retry_sounding_board:{description:"record a MANUAL critic_sounding_board gate entry to unblock the coder retry circuit-breaker gate when the sounding board returned APPROVED but the mechanical recorder missed it (issue #2703)",agents:["architect"]},recover_rework_task:{description:"recover a task wedged at rework_required when the reviewer/test_engineer verdict did not require a code change: write a supervised stage_a_passed so those gates can be re-dispatched without re-running the coder (issue #2755)",agents:["architect"]},recover_stage_a_task:{description:"recover a task wedged in the settlement-backed Stage A deadlock — workflow at idle/blocked while a COMMITTED accepted coder settlement and green post-settlement pre-check proof justify Stage A: write a settlement-backed stage_a_passed so reviewer/test_engineer can be dispatched, without re-running the coder (issue #2828)",agents:["architect"]},prepare_pr_workflow_checkout:{description:"prepare an auditable PR workflow checkout or restore its exact original branch/HEAD and preserved stash after terminal cleanup",agents:["architect"]},invalidate_pr_feedback_publication:{description:"invalidate the armed PR_FEEDBACK publication generation so approved content can change, superseding every content-dependent approval and reopening the exact scoped rework + fresh-review path (issue #2108)",agents:["architect"]},record_implementation_review:{description:"record fresh-context reviewer + critic APPROVE verdicts for the implementation diff so the /swarm issue --trace workflow can satisfy its review gate before commit-pr handoff",agents:["architect"]},record_issue_publication:{description:"record a publication receipt so the /swarm issue --trace workflow reaches its terminal published state after the PR is created/updated",agents:["architect"]},record_issue_reproduction:{description:"record the reproduction outcome for the current traced issue so the /swarm issue --trace workflow can satisfy its reproduction gate and transition to PLAN",agents:["architect"]},record_recurrence_sweep:{description:"record the recurrence sweep (defect class, predicates, hit dispositions, guardrail proof, related-problems results) so the /swarm issue --trace workflow can satisfy its recurrence gate before commit-pr handoff",agents:["architect"]},record_branch_freshness:{description:"record the Phase 0 branch-freshness outcome (synced / behind:<n> / fetch-failed:<reason> plus optional user override) so the /swarm issue --trace workflow can pass its freshness gate before transitioning to PLAN (issue #2564)",agents:["architect"]},record_trace_validation:{description:"record one per-phase trace-check.sh validator outcome (phase, pass/fail, reviewedCommit, treeId) so the /swarm issue --trace workflow can satisfy its validator-receipt gate before commit-pr handoff (issue #2564)",agents:["architect"]},record_merge_approval:{description:"record the human merge approval bound to the exact PR head SHA so the /swarm issue --trace workflow reaches its terminal merge_approval_recorded state — recorded for audit only, never certified or driven by the plugin (issue #2564)",agents:["architect"]},rebind_pr_feedback_head:{description:"rebind a PR_FEEDBACK workflow to a new verified remote PR head after merge/rebase/conflict repair, invalidating ancestry-bound receipts so the mechanical ladder re-runs",agents:["architect"]},run_pr_feedback_stage_a:{description:"execute and persist mandatory PR-feedback Stage A checks on a content-bound revision",agents:["architect"]},submit_council_verdicts:{description:"submit pre-collected council member verdicts for synthesis (architect MUST dispatch critic/reviewer/sme/test_engineer/explorer as Agent tasks first; this tool synthesizes only, it does not contact members)",agents:[]},submit_phase_council_verdicts:{description:"submit pre-collected phase-level council member verdicts for holistic phase synthesis (architect MUST dispatch all 5 council members with phase-scoped context first; this tool synthesizes only, it does not contact members)",agents:[]},declare_council_criteria:{description:"pre-declare acceptance criteria for a task before the coder starts work; criteria are read back during council evaluation",agents:[]},sbom_generate:{description:"SBOM generation for dependency inventory",agents:["architect"]},checkpoint:{description:"create named git checkpoints for save, restore, and delete — use before risky operations to enable rollback",agents:["architect"]},pkg_audit:{description:"dependency vulnerability scan — npm/pip/cargo",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},parse_lane_candidates:{description:"Parse [CANDIDATE] rows from a dispatch_lanes or collect_lane_results artifact (by output_ref), produce structured records with provenance, optionally persist to a per-batch sidecar JSONL. Pure-parser variant exists as internal module.",agents:["architect"]},plan_conflict_check:{description:"read-only advisory check (#1656): compute a pairwise file-conflict matrix for N proposed parallel task groups using declared scopes and optional git co-change; returns a verdict (all_disjoint / conflicts_present / unknown_scopes), per-pair evidence, and a suggested serialization order. Writes nothing — the execution gate independently recomputes the verdict inline at dispatch time via the same helper. Call BEFORE attempting parallel dispatch to confirm disjointness.",agents:["architect"]},write_pr_review_trigger_eval:{description:"persist the complete PR-review trigger evaluation with exact-set validation, dispatch provenance, and live merge-base verification",agents:["architect"]},write_pr_review_artifact:{description:"persist schema-validated PR-review findings checkpoints and exact actionable feedback handoffs under the active run",agents:["architect"]},prepare_pr_feedback_scope:{description:"prepare an exact file scope for one PR-feedback coder Task after immutable feedback verification settles",agents:["architect"]},test_runner:{description:"auto-detect and run tests",agents:["architect","reviewer","critic_finding_validator","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},test_impact:{description:"identify test files impacted by changed source files via import analysis",agents:["architect","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},mutation_test:{description:"executes pre-generated mutation patches against tests, evaluates kill rate against quality gate thresholds; test selection comes from explicit files (override) or source_files derived via the impact analyzer with a typed bounded fallback",agents:["architect","test_engineer"]},generate_mutants:{description:"generate LLM-based mutation testing patches for source files; returns MutationPatch[] for direct consumption by the mutation_test tool",agents:["architect"]},detect_domains:{description:"detect which SME domains are relevant for a given text",agents:["architect","sme","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic","critic_oversight","explorer"]},git_blame:{description:"per-line git blame metadata: sha, author, date, summary for each line in a file",agents:["reviewer","critic_finding_validator","explorer","architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},gitingest:{description:"fetch a GitHub repository full content via gitingest.com",agents:["architect","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_summary:{description:"retrieve the full content of a stored tool output summary",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_lane_output:{description:"retrieve paged full dispatch lane output by output_ref; use before consuming truncated lane previews or routing candidates from lane results",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},extract_code_blocks:{description:"extract code blocks from text content and save them to files",agents:["docs","docs_design","designer","spec_writer","coder","test_engineer"]},phase_complete:{description:"preflight every applicable phase gate, report all blockers, and atomically commit a current passing snapshot",agents:["architect"]},run_phase_review:{description:"run the bounded phase-final review engine and persist complete content-addressed review evidence",agents:["architect"]},repair_gate_evidence:{description:"quarantine recoverable exact-task gate evidence, rebuild from durable requirements, recover receipt-backed legacy marker wedges or the exact sentinel-only historical reset, and refuse every other receipt-less reconstruction",agents:["architect"]},repair_knowledge_receipt_ledger:{description:"validate or repair authoritative knowledge receipts, preserve corrupt authority in bounded quarantine, and require scoped re-evaluation",agents:["architect"]},record_directive_override:{description:"record an audited architect override for identified critical-directive violations without bypassing unreadable authority",agents:["architect"]},save_plan:{description:"save a structured implementation plan",agents:["architect"]},update_task_status:{description:"mark tasks complete, track phase progress",agents:["architect"]},lint_spec:{description:"validate .swarm/spec.md format and required fields",agents:["architect","spec_writer"]},write_retro:{description:"document phase retrospectives via phase_complete workflow, capture lessons learned",agents:["architect"]},write_drift_evidence:{description:"write drift verification evidence for a completed phase",agents:["architect"]},write_hallucination_evidence:{description:"write hallucination verification evidence for a completed phase",agents:["architect"]},write_mutation_evidence:{description:"write mutation gate evidence for a completed phase; normalizes PASS/WARN/FAIL/SKIP verdicts and writes .swarm/evidence/{phase}/mutation-gate.json",agents:["architect"]},declare_scope:{description:"declare file scope for next coder delegation",agents:["architect"]},scope_validate:{description:"validate shell writes against an inline file scope",agents:["architect"]},knowledge_query:{description:"query swarm or hive knowledge with optional filters",agents:["architect","skill_improver","spec_writer"]},doc_scan:{description:"scan project documentation files and build an index manifest",agents:["architect","docs_design","skill_improver","spec_writer","explorer"]},doc_extract:{description:"extract actionable constraints from project documentation",agents:["architect","docs_design","skill_improver","spec_writer"]},curator_analyze:{description:"run curator phase analysis and optionally apply knowledge recommendations",agents:["architect"]},consensus_mine:{description:"mine cross-run consensus from existing .swarm evidence into an immutable proposals-only report; also deletes its own reports past consensus.report_retention, appends to the shared recommendation dedup ledger (in the shared cohort root, outside this project, when a knowledge link is active), and mirrors proposals into pending swarm-memory proposals when memory is enabled",agents:["architect","curator_phase","curator_postmortem"]},knowledge_add:{description:"store a new lesson in the knowledge base",agents:["architect","coder"]},knowledge_recall:{description:"search the knowledge base for relevant past decisions",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"]},knowledge_remove:{description:"delete an outdated swarm knowledge entry by ID (swarm tier only)",agents:["architect"]},co_change_analyzer:{description:"detect hidden couplings by analyzing git history",agents:["architect"]},context_status:{description:"report current context-window headroom for the active session — returns tokens-used, usageSource (provider|estimated), model-limit with provenance (modelLimitSource: host|override|provider_cap|native|fallback; modelLimitResolution: user_provider_model|user_model|user_default|live_model_limit|static_provider_cap|static_native|static_default; fallbackActive: true when the denominator came from a static table or the flat 128k default — treat headroom as uncertain), usage-percent, threshold-state (none/warn/critical), model name, and provider. Pure read-only: no state mutation, no warning injection. Works whether context_budget.enabled is true or false.",agents:["architect"]},search:{description:"Workspace-scoped ripgrep-style text search with structured JSON output. Supports literal and regex modes, glob filtering, and result limits. NOTE: This is text search, not structural AST search — use symbols and imports tools for structural queries.",agents:["architect","sme","docs","docs_design","designer","critic_hallucination_verifier","skill_improver","spec_writer","reviewer","critic_finding_validator","critic_oversight","explorer","coder","test_engineer","researcher"]},ast_grep:{description:"Read-only structural AST search using ast-grep patterns with optional language and glob filters. Use for syntax-aware code pattern searches; does not rewrite files.",agents:["architect","sme","docs","docs_design","critic_hallucination_verifier","spec_writer","explorer","coder","test_engineer","researcher"]},actionlint_scan:{description:"Run actionlint against GitHub Actions workflow YAML files with structured findings. Resolves actionlint lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},osv_scan:{description:"Run OSV-Scanner against a workspace path and return structured dependency vulnerability findings. Resolves osv-scanner lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},gh_evidence:{description:"Fetch bounded GitHub pull request or issue metadata through gh for review and CI evidence. Resolves gh lazily and is read-only.",agents:["architect","researcher"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},pr_workflow_status:{description:"Read-only architect observation of local git state (HEAD, branch, clean/dirty with a bounded changed-file list, remotes) plus a session-pinned PR workflow gate summary and the PR_FEEDBACK publication-generation section (state, attempts, invalidation reason, recovery guidance). Use to observe state under the fail-closed PR_REVIEW/PR_FEEDBACK gate. Never executes PR-controlled scripts and never reads another session gate.",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},batch_symbols:{description:"Batched symbol extraction across multiple files. Returns per-file symbol summaries with isolated error handling.",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","explorer"]},suggest_patch:{description:"Reviewer-safe structured patch suggestion tool. Produces context-anchored patch artifacts without file modification. Returns structured diagnostics on context mismatch.",agents:["architect","reviewer","critic_finding_validator"]},req_coverage:{description:"query requirement coverage status for tracked functional requirements",agents:["critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","critic","critic_oversight"]},get_approved_plan:{description:"retrieve the last critic-approved immutable plan snapshot for baseline drift comparison",agents:["critic_drift_verifier","critic","critic_oversight"]},repo_map:{description:"query the repo code graph: importers, dependencies, blast radius, localization, ontology facts, package boundaries, and heuristic preflight packets before refactoring; ontology findings are advisory, not formal proofs",agents:["architect","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},get_qa_gate_profile:{description:"retrieve the QA gate profile for the current or exact future plan identity: gates (reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council), lock state, profile hash, the calling session’s ratchet-tighter overrides, and the EFFECTIVE gates (profile merged with those overrides; durable across restart). Read-only and never creates state.",agents:["architect"]},set_qa_gates:{description:"configure the QA gate profile for the current plan or bootstrap an exact future plan with swarm_id and plan_title. Architect-only. The initial selection may set explicit true/false values over defaults; later changes are ratchet-tighter and rejected once locked after critic approval. Supports: reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council, plus adopt_legacy_binding_only for exact-binding recovery without mutating gates.",agents:["architect"]},web_search:{description:"External web search (Tavily or Brave) for architect-driven council research, SME domain research, researcher auto-research, and skill-improver research. Returns titled results with snippets, URLs, normalized query metadata, temporal intent, freshness, and removed stale years. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides. Requires a search API key. Used by the architect in MODE: COUNCIL to gather a RESEARCH CONTEXT before dispatching council agents, by SME for opt-in external skill/source evaluation, and by the researcher agent for multi-source auto-research.",agents:["sme","researcher","skill_improver"]},web_fetch:{description:"Fetch the readable text of a single http(s) URL (architect-only). Returns decoded page text, document title, final URL after redirects, and an evidence reference. Reads primary sources that web_search only surfaces as snippets. Config-gated on council.general.enabled. Blocks private/loopback/link-local/metadata addresses (re-validated and re-pinned across redirects); enforces timeout and body size cap.",agents:[]},convene_general_council:{description:"Synthesize responses from a multi-model General Council. Accepts parallel member responses (Round 1, optionally Round 2), detects disagreements, and returns consensus points, persisting disagreements, and a structured synthesis. Architect-only. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides.",agents:[]},write_final_council_evidence:{description:"Persist project-scoped final council evidence to .swarm/evidence/final-council.json. PREREQUISITE: dispatch critic, reviewer, sme, test_engineer, and explorer as project-scoped Agent tasks and collect their CouncilMemberVerdict JSON — this tool synthesizes only. Rejects on insufficient quorum or CONCERNS with unresolved requiredFixes; normalizes verdicts to approved/concerns/rejected. Architect-only.",agents:[]},skill_generate:{description:"compile knowledge entries into a structured SKILL.md draft",agents:["skill_improver"]},skill_list:{description:"list generated skill files and their status",agents:["skill_improver"]},skill_apply:{description:"activate a draft skill proposal",agents:[]},skill_inspect:{description:"inspect the content and source entries of a skill file",agents:["skill_improver"]},run_stale_reconciliation:{description:"reconcile skills against the knowledge store: mark skills stale when source knowledge is archived or deleted, or clear stale markers",agents:["architect"]},skill_regenerate:{description:"regenerate an active skill by re-clustering its source knowledge entries and updating the SKILL.md in place",agents:[]},skill_retire:{description:"retire a generated skill by adding a retired.marker file; retired skills are excluded from scoring and injection",agents:[]},skill_improve:{description:"run the skill_improver agent to review and refine skills",agents:["skill_improver"]},spec_write:{description:"author or update .swarm/spec.md for the current project",agents:["spec_writer"]},knowledge_receipt:{description:"file a receipt for retrieved knowledge (applied/ignored/contradicted + new lessons), recorded as immutable knowledge events",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},knowledge_receipt_status:{description:"receipt status",agents:["architect"]},knowledge_archive:{description:"archive (default), quarantine, or purge a swarm or hive knowledge entry by ID with an immutable audit tombstone; purge requires an admin flag",agents:["architect"]},swarm_memory_recall:{description:"recall scoped Swarm memory for the current repository as untrusted background",agents:[]},swarm_memory_propose:{description:"create a pending Swarm memory proposal; does not write durable memory directly",agents:[]},swarm_memory_outcome:{description:"record useful, dead-end, or corrected outcomes and, when enabled, synchronously refresh deterministic memory lessons",agents:[]},swarm_command:{description:"run supported /swarm commands through the canonical command registry",agents:["architect","sme","researcher","docs","docs_design","designer","reviewer","critic_finding_validator","critic","explorer","coder","test_engineer"]},dispatch_lanes:{description:"dispatch read-only exploration/review lanes concurrently and BLOCK until all finish; prefer dispatch_lanes_async for non-blocking dispatch, use this only when promptAsync is unavailable",agents:["architect"]},dispatch_lanes_async:{description:"launch read-only advisory lanes non-blockingly and return a batch id plus lane session handles immediately; each lane agent must be a registered generated agent name (unregistered bare roles are refused on multi-swarm hosts); launch_timeout_ms is only a promptAsync acceptance budget, not a lane runtime timeout; poll incrementally with collect_lane_results (wait omitted), or join with wait: true for all results",agents:["architect"]},collect_lane_results:{description:"collect/poll a dispatch_lanes_async batch; a presumed-stale sweep runs on every call, settling lanes past the horizon: idle host to stale, unobservable host to a typed liveness error; cancel_pending cancels pending lanes; otherwise observe-only. Non-blocking poll (wait omitted or false) and blocking join (wait: true) supported. The wait budget bounds the observer call only — expiry never kills a lane nor proves it died; poll again or cancel explicitly, never abort. Unsettled lanes are reported in pending_lanes (batch_id, lane_id, status, output_ref) regardless of include_pending; busy/retry lanes never go stale for running long. Does not advance workflow gates. Settled-lane inline output is delivered once: later polls set output_omitted_repeat: true and omit output but keep output_ref for retrieval via retrieve_lane_output.",agents:["architect"]},summarize_work:{description:"emit a short structured summary of completed work (key decisions, assumptions, risks, constraints) at task completion; rolls up per phase for architecture-supervisor review. Advisory, never blocks.",agents:["architect","sme","researcher","docs","docs_design","designer","explorer","coder","test_engineer"]},write_architecture_supervisor_evidence:{description:"persist the architecture supervisor verdict for a phase (architect MUST dispatch critic_architecture_supervisor first and collect its JSON verdict; this tool persists only, it does not contact the supervisor)",agents:["architect"]},lean_turbo_plan_lanes:{description:"partition phase tasks into parallel lanes based on file-scope conflicts for Lean Turbo execution",agents:[]},lean_turbo_acquire_locks:{description:"acquire file locks for all files in a lane (all-or-nothing) before lane execution",agents:[]},lean_turbo_runner_status:{description:"read Lean Turbo run state from .swarm/turbo-state.json",agents:[]},lean_turbo_critic:{description:"dispatch a read-only critic agent to evaluate boundary conditions for a completed Lean Turbo phase (satisfies the turbo.lean.phase_critic gate)",agents:[]},lean_turbo_review:{description:"dispatch a read-only reviewer agent to evaluate a completed Lean Turbo phase",agents:[]},lean_turbo_run_phase:{description:"Execute a phase using Lean Turbo parallel lane execution. Plans lanes, acquires file locks, and dispatches coder agents concurrently. Use when Lean Turbo is active and you want to execute all tasks in a phase in parallel lanes.",agents:[]},lean_turbo_status:{description:"returns Lean Turbo configuration and active status for the current session",agents:[]},swarm_apply_patch:{description:"Apply a unified diff patch to workspace files with exact context matching, atomic writes, and path validation. Use standard unified diff format only — does NOT support *** Begin Patch / *** Update File payloads (use native apply_patch for those).",agents:["coder","test_engineer"]},external_skill_discover:{description:"Discover external skill candidates from configured sources. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_list:{description:"List external skill candidates in the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_inspect:{description:"Inspect a specific external skill candidate by ID. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_promote:{description:"Promote a validated external skill candidate to an active generated skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_reject:{description:"Reject an external skill candidate after evaluation. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_delete:{description:"Delete an external skill candidate from the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_revoke:{description:"Revoke a previously promoted external skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},epic_decide_phase:{description:"Compute the Epic Mode verdict for a phase WITHOUT dispatching coders. Runs preflight + calibration + the three gates (p-threshold, hot-module, greenfield), persists the decision, and returns the verdict so the architect can dispatch waves via the visible Task tool (promote) or fall back to per-task serial (demote). Pair with `epic_plan_waves` to get the wave plan when promoted. Use when /swarm epic is on for the session.",agents:["architect"]},epic_plan_waves:{description:"Partition a phase's pending tasks into ordered concurrent waves for Epic Mode dispatch. A wave is a set of tasks with mutually disjoint declared scopes and all dependencies satisfied by prior waves. Returns `{ waves: [{ waveId, taskIds, files }, ...], serializedTasks, degradedTasks }`. "+'For each wave in order, the architect dispatches one `Task(subagent_type="coder", ...)` per `taskId` — all in one assistant message — so the wave runs concurrently and each coder appears as a visible subagent. '+"Wait for the wave to finish before dispatching the next. Pair with `epic_decide_phase` (called first; this tool is only relevant on a `promote` verdict). "+"Preflight reject reasons: `no-plan`, `no-phase`, `phase-empty`, `phase-already-complete`, `scopes-missing` (call `declare_scope` for `missingScopes`), `git-failed` (transient — retry), `planner-error`.",agents:["architect"]},epic_record_divergence:{description:"After every `update_task_status(completed)`, record the task's declared-vs-actual divergence to .swarm/epic/divergence.jsonl. Feeds Epic Mode's self-calibration loop (Capability D). Best-effort: never blocks.",agents:["architect"]}},TOOL_NAMES=Object.keys(TOOL_METADATA),TOOL_NAME_SET=new Set(TOOL_NAMES);TOOL_DESCRIPTIONS=Object.fromEntries(Object.entries(TOOL_METADATA).map(([name,meta])=>[name,meta.description])),AGENT_TOOL_MAP=(()=>{let map=Object.fromEntries(ALL_AGENT_NAMES.map((agent)=>[agent,[]]));for(let[name,meta]of Object.entries(TOOL_METADATA))for(let agent of meta.agents)map[agent].push(name);return map})()});function scanOverrideForDangerousKeys(value,path,depth){if(depth>=10)return;if(Array.isArray(value)){for(let i=0;i<value.length;i++)scanOverrideForDangerousKeys(value[i],`${path}[${i}]`,depth+1);return}if(typeof value!=="object"||value===null)return;for(let key of Object.keys(value)){if(DANGEROUS_MERGE_KEYS.has(key))throw new DangerousMergeKeyError(key,path);scanOverrideForDangerousKeys(value[key],`${path}.${key}`,depth+1)}}function deepMergeInternal(base,override,depth,path){if(depth>=10)throw Error("deepMerge exceeded maximum depth of 10");let result={...base};for(let key of Object.keys(override)){let baseVal=base[key],overrideVal=override[key];if(typeof baseVal==="object"&&baseVal!==null&&typeof overrideVal==="object"&&overrideVal!==null&&!Array.isArray(baseVal)&&!Array.isArray(overrideVal))result[key]=deepMergeInternal(baseVal,overrideVal,depth+1,`${path}.${key}`);else result[key]=overrideVal}return result}function deepMerge(base,override){if(!base)return override;if(!override)return base;return scanOverrideForDangerousKeys(override,"$",0),deepMergeInternal(base,override,0,"$")}var MAX_MERGE_DEPTH=10,DANGEROUS_MERGE_KEYS,DangerousMergeKeyError;var init_merge=__esm(()=>{DANGEROUS_MERGE_KEYS=new Set(["__proto__","constructor","prototype"]);DangerousMergeKeyError=class DangerousMergeKeyError extends Error{key;path;constructor(key,path){super(`deepMerge refused dangerous key "${key}" at "${path}": prototype-pollution carriers (__proto__/constructor/prototype) are never merged`);this.key=key;this.path=path;this.name="DangerousMergeKeyError"}}});function freezeSet(items,name="CLAUDE_CODE_NATIVE_COMMANDS"){let set=new Set(items),proxy=new Proxy(set,{get(target,prop){if(prop==="add"||prop==="delete"||prop==="clear")return()=>{throw TypeError(`${name} is readonly`)};if(prop==="forEach")return(callback,thisArg)=>{let wrapped=(v,k)=>callback.call(thisArg??void 0,v,k,proxy);return set.forEach(wrapped)};let value=Reflect.get(target,prop);return typeof value==="function"?value.bind(target):value},set(){throw TypeError(`${name} is readonly`)},deleteProperty(){throw TypeError(`${name} is readonly`)},defineProperty(){throw TypeError(`${name} is readonly`)},setPrototypeOf(){throw TypeError(`${name} is readonly`)}});return proxy}function isQAAgent(name){return QA_AGENTS.includes(name)}function isSubagent(name){return ALL_SUBAGENT_NAMES.includes(name)}function isLowCapabilityModel(modelId){let lower=(modelId||"").toLowerCase();return LOW_CAPABILITY_MODELS.some((substr)=>lower.includes(substr))}var OPENCODE_NATIVE_AGENTS,CLAUDE_CODE_NATIVE_COMMANDS,OPENCODE_NATIVE_COMMANDS,MEMORY_AGENT_TOOL_MAP,EXTERNAL_SKILL_TOOL_NAMES,EXTERNAL_SKILL_AGENT_TOOL_MAP,COUNCIL_TOOL_NAMES,COUNCIL_AGENT_TOOL_MAP,GENERAL_COUNCIL_TOOL_NAMES,GENERAL_COUNCIL_AGENT_TOOL_MAP,TURBO_TOOL_NAMES,TURBO_AGENT_TOOL_MAP,SKILL_TOOL_NAMES,SKILL_AGENT_TOOL_MAP,PR_REVIEW_CHILD_TOOL_NAMES,PR_REVIEW_CHILD_AGENT_TOOL_MAP,WRITE_TOOL_NAMES,SUMMARIZER_EXEMPT_TOOL_NAMES,DEFAULT_MODELS,DEFAULT_AGENT_CONFIGS,DEFAULT_SCORING_CONFIG,LOW_CAPABILITY_MODELS,TURBO_MODE_BANNER=`## \uD83D\uDE80 TURBO MODE ACTIVE
|
|
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.186.4",description:"Architect-centric agentic swarm plugin for OpenCode - hub-and-spoke orchestration with SME consultation, code generation, and QA review",main:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",default:"./dist/index.js"},"./package.json":"./package.json"},bin:{"opencode-swarm":"./dist/cli/index.js"},type:"module",engines:{bun:">=1.3.13",node:">=22.13"},license:"MIT",repository:{type:"git",url:"https://github.com/ZaxbyHub/opencode-swarm.git"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},keywords:["opencode","opencode-plugin","ai","agents","orchestration","swarm","multi-agent","llm"],files:["dist","dist/lang/grammars","binaries","evaluation-fixtures",".opencode/skills/brainstorm",".opencode/skills/specify",".opencode/skills/clarify-spec",".opencode/skills/swarm-resume",".opencode/skills/clarify",".opencode/skills/discover",".opencode/skills/consult",".opencode/skills/pre-phase-briefing",".opencode/skills/council",".opencode/skills/deep-dive",".opencode/skills/deep-research",".opencode/skills/codebase-review-swarm",".opencode/skills/swarm-implement",".opencode/skills/design-docs",".opencode/skills/swarm-pr-review",".opencode/skills/swarm",".opencode/skills/swarm-pr-feedback",".opencode/skills/swarm-pr-subscribe",".opencode/skills/swarm-ci-monitor",".opencode/skills/issue-ingest",".opencode/skills/swarm-plan",".opencode/skills/critic-gate",".opencode/skills/execute",".opencode/skills/phase-wrap",".opencode/skills/loop",".opencode/skills/writing-tests",".opencode/skills/running-tests",".opencode/skills/engineering-conventions",".opencode/skills/commit-pr",".opencode/skills/ci-failure-batching",".opencode/skills/gate-attribution",".opencode/skills/merge-queue-readiness",".opencode/skills/skill-edit-validation",".opencode/skills/worktree-retry-cleanup",".opencode/skills/test-file-split",".opencode/skills/fork-pr-operations",".opencode/skills/parallel-work-check",".opencode/skills/ci-fix-monitor",".opencode/skills/issue-tracer",".opencode/skills/orchestrating-subagents",".opencode/skills/durable-session-state","tests/fixtures/memory-recall","tests/fixtures/memory-recall-heldout","opencode-swarm.schema.json","README.md","LICENSE"],scripts:{clean:`bun -e "require('fs').rmSync('dist',{recursive:true,force:true})"`,build:"bun run clean && bun run scripts/generate-config-schema.ts && bun run scripts/copy-grammars.ts && bun build src/index.ts --outdir dist --target node --format esm --external web-tree-sitter --minify-whitespace --minify-syntax && bun build src/cli/index.ts --outdir dist/cli --target bun --format esm --external bash-parser --splitting && bun run scripts/copy-grammars.ts --to-dist && tsc --emitDeclarationOnly",typecheck:"tsc --noEmit",test:"bun test",lint:"biome lint .","lint:ci":"biome ci .","test:unit:ci":"bun scripts/ci/run-unit-tests-local.ts","validate:repo":"bun scripts/ci/repository-validation.ts","drift:check":"bun run scripts/drift-check.ts","check:pre-push":"bun run scripts/drift-check.ts --enforce --no-report && bun run check:registry-citations","schema:generate":"bun run scripts/generate-config-schema.ts","generate:commands-docs":"bun run scripts/generate-commands-docs.ts","check:runtime-src-refs":"bun run scripts/check-runtime-src-refs.ts","drift:fix":"bun run scripts/drift-check.ts --fix --confirm","skills:sync":"bun run scripts/sync-qa-gate-skills.ts",format:"biome format . --write",check:"biome check --write .",dev:"bun run build && opencode","package:smoke":"node scripts/package-smoke.mjs",prepare:"bun run build","repro:704":"node scripts/repro-704.mjs","repro:2669":"node scripts/repro-2669.mjs","repro:2670":"node scripts/repro-2670.mjs","repro:1144":"bun scripts/repro-1144.mjs","repro:1873":"bun build scripts/repro-1873-entry.ts --outdir dist-build-test/repro-1873 --target node --format esm && node scripts/repro-1873.mjs","repro:2487":"bun build scripts/repro-2487-parity-entry.ts --outdir dist-build-test/repro-2487 --target node --format esm && node scripts/repro-2487-parity.mjs","check:events":"bun run scripts/check-event-contract.ts","check:retention":"bun run scripts/check-retention-registry.ts","check:core-events":"bun run scripts/check-core-events-usage.ts","check:shell-audit":"bun run scripts/check-shell-audit-usage.ts","check:trajectory-store":"bun run scripts/check-trajectory-store-usage.ts","check:mock-cleanup":"bun run scripts/check-mock-cleanup.ts","check:invariants":"bun run scripts/check-invariants.ts","check:token-formula":"bun run scripts/check-token-formula.ts","check:cross-contamination":"bun run scripts/check-cross-contamination.ts","check:test-clock":"bun run scripts/check-test-clock.ts","check:test-file-cap":"bun run scripts/check-test-file-cap.ts","check:test-tmpdir":"bun run scripts/check-test-tmpdir.ts","check:bash-portability":"bun run scripts/check-bash-portability.ts","check:pending-fragment":"bun run scripts/check-pending-fragment.ts","check:gate-portability":"bun run scripts/check-gate-portability.ts","check:bare-spawn":"bun run scripts/check-bare-executable-spawn.ts","check:error-channel-discard":"bun run scripts/check-error-channel-discard.ts","check:path-identity":"bun run scripts/check-path-identity.ts","check:registry-citations":"bun run scripts/check-registry-citations.ts","check:memory-recall":"bun run scripts/memory-recall-regression.ts","check:retrieval-quality":"bun run scripts/retrieval-quality-regression.ts"},dependencies:{"@modelcontextprotocol/sdk":"^1.30.0","@opencode-ai/plugin":"^1.18.3","@opencode-ai/sdk":"^1.18.3","@vscode/tree-sitter-wasm":"^0.3.0","bash-parser":"^0.5.0","p-limit":"^7.3.0",picomatch:"^4.0.4","proper-lockfile":"^4.1.2","quick-lru":"^7.3.0","web-tree-sitter":"^0.25.0",zod:"4.3.6"},devDependencies:{"@biomejs/biome":"2.3.14","@types/picomatch":"^4.0.3","bun-types":"1.3.8","js-yaml":"^4.1.1",typescript:"^5.7.3"},peerDependencies:{"@xenova/transformers":"^2.17.2"},peerDependenciesMeta:{"@xenova/transformers":{optional:!0}}}});var QA_AGENTS,PIPELINE_AGENTS,ORCHESTRATOR_NAME="architect",ALL_SUBAGENT_NAMES,ALL_AGENT_NAMES;var init_agent_names=__esm(()=>{QA_AGENTS=["reviewer","critic","critic_oversight","critic_finding_validator"],PIPELINE_AGENTS=["explorer","coder","test_engineer"],ALL_SUBAGENT_NAMES=["sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","curator_postmortem","curator_consolidation","council_generalist","council_skeptic","council_domain_expert","skill_improver","spec_writer",...QA_AGENTS,...PIPELINE_AGENTS],ALL_AGENT_NAMES=["architect",...ALL_SUBAGENT_NAMES]});function getPrWorkflowToolCapability(toolName,mode){let metadata=TOOL_METADATA[toolName];if(!metadata?.prWorkflow?.modes.includes(mode))return null;return metadata.prWorkflow.capability}var TOOL_METADATA,TOOL_NAMES,TOOL_NAME_SET,TOOL_DESCRIPTIONS,AGENT_TOOL_MAP;var init_tool_metadata=__esm(()=>{init_agent_names();TOOL_METADATA={diff:{description:"structured git diff with contract change detection",agents:["architect","reviewer","critic_finding_validator","critic_oversight","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},diff_summary:{description:"filter classified AST changes by category, risk level, or file for reviewer drill-down",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},syntax_check:{description:"check syntax of source files using tree-sitter parsers across multiple languages, returning per-file errors",agents:["architect","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},placeholder_scan:{description:"todo and FIXME comment detection",agents:["architect","reviewer","critic_finding_validator"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},imports:{description:"find all consumers that import from a given file — use before refactoring shared modules to avoid breaking unseen dependents",agents:["architect","sme","researcher","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},lint:{description:"run project linter in check or fix mode; supports biome, eslint, ruff, clippy, and more, returns structured results",agents:["architect","reviewer","critic_finding_validator","coder"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},secretscan:{description:"scan for secrets (API keys, tokens, passwords) via regex and entropy; returns redacted previews, excludes common dirs",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},sast_scan:{description:"static analysis security scan",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},build_check:{description:"discover and run build, typecheck, and test commands for various project ecosystems in the working directory",agents:["architect","coder","test_engineer"]},pre_check_batch:{description:"parallel verification: lint:check + secretscan + sast_scan + quality_budget",agents:["architect","reviewer","critic_finding_validator"]},quality_budget:{description:"code quality budget check",agents:["architect"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},symbols:{description:"extract exported symbols (functions, classes, interfaces, types) from source files; supports TypeScript, JavaScript, and Python",agents:["architect","sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},complexity_hotspots:{description:"git churn × complexity risk map",agents:["architect","sme","researcher","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","critic_oversight","explorer","test_engineer"]},schema_drift:{description:"OpenAPI spec vs route drift",agents:["architect","sme","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},todo_extract:{description:"structured TODO/FIXME extraction; with task_id, records the high-priority count as todo_scan gate evidence",agents:["architect","researcher","docs","explorer","coder"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},evidence_check:{description:"verify task evidence completeness",agents:["architect","critic_oversight"]},check_gate_status:{description:"check the gate status of a specific task",agents:["architect","critic_oversight"]},completion_verify:{description:"verify completed tasks have required evidence",agents:["architect","critic_oversight"]},complete_pr_workflow:{description:"validate terminal PR workflow evidence and clear its durable session gate",agents:["architect"]},abort_pr_workflow:{description:"abort an unrecoverable PR_REVIEW/PR_FEEDBACK mechanical gate and clear its durable session state",agents:["architect"]},authorize_pr_review_reentry:{description:"issue a one-use, identity-bound reviewer/test_engineer re-entry authorization for the active PR_REVIEW workflow (issue #2383)",agents:["architect"]},submit_pr_review_result:{description:"submit one child-bound typed result for an active PR-review base or micro discovery lane",agents:[],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},approve_plan_critic:{description:"record a MANUAL plan_critic_gate approval snapshot to unblock the ratchet-tighter critic_pre_plan execution gate when the critic already returned APPROVED but the mechanical recorder failed to persist it (issue #2012), or as the sanctioned recovery for a bookkeeping-grade hashed-field repair under the critic-gate PLAN FREEZE rule (the reason must state which case applies)",agents:["architect"]},approve_retry_sounding_board:{description:"record a MANUAL critic_sounding_board gate entry to unblock the coder retry circuit-breaker gate when the sounding board returned APPROVED but the mechanical recorder missed it (issue #2703)",agents:["architect"]},recover_rework_task:{description:"recover a task wedged at rework_required when the reviewer/test_engineer verdict did not require a code change: write a supervised stage_a_passed so those gates can be re-dispatched without re-running the coder (issue #2755)",agents:["architect"]},recover_stage_a_task:{description:"recover a task wedged in the settlement-backed Stage A deadlock — workflow at idle/blocked while a COMMITTED accepted coder settlement and green post-settlement pre-check proof justify Stage A: write a settlement-backed stage_a_passed so reviewer/test_engineer can be dispatched, without re-running the coder (issue #2828)",agents:["architect"]},prepare_pr_workflow_checkout:{description:"prepare an auditable PR workflow checkout or restore its exact original branch/HEAD and preserved stash after terminal cleanup",agents:["architect"]},invalidate_pr_feedback_publication:{description:"invalidate the armed PR_FEEDBACK publication generation so approved content can change, superseding every content-dependent approval and reopening the exact scoped rework + fresh-review path (issue #2108)",agents:["architect"]},record_implementation_review:{description:"record fresh-context reviewer + critic APPROVE verdicts for the implementation diff so the /swarm issue --trace workflow can satisfy its review gate before commit-pr handoff",agents:["architect"]},record_issue_publication:{description:"record a publication receipt so the /swarm issue --trace workflow reaches its terminal published state after the PR is created/updated",agents:["architect"]},record_issue_reproduction:{description:"record the reproduction outcome for the current traced issue so the /swarm issue --trace workflow can satisfy its reproduction gate and transition to PLAN",agents:["architect"]},record_recurrence_sweep:{description:"record the recurrence sweep (defect class, predicates, hit dispositions, guardrail proof, related-problems results) so the /swarm issue --trace workflow can satisfy its recurrence gate before commit-pr handoff",agents:["architect"]},record_branch_freshness:{description:"record the Phase 0 branch-freshness outcome (synced / behind:<n> / fetch-failed:<reason> plus optional user override) so the /swarm issue --trace workflow can pass its freshness gate before transitioning to PLAN (issue #2564)",agents:["architect"]},record_trace_validation:{description:"record one per-phase trace-check.sh validator outcome (phase, pass/fail, reviewedCommit, treeId) so the /swarm issue --trace workflow can satisfy its validator-receipt gate before commit-pr handoff (issue #2564)",agents:["architect"]},record_merge_approval:{description:"record the human merge approval bound to the exact PR head SHA so the /swarm issue --trace workflow reaches its terminal merge_approval_recorded state — recorded for audit only, never certified or driven by the plugin (issue #2564)",agents:["architect"]},rebind_pr_feedback_head:{description:"rebind a PR_FEEDBACK workflow to a new verified remote PR head after merge/rebase/conflict repair, invalidating ancestry-bound receipts so the mechanical ladder re-runs",agents:["architect"]},run_pr_feedback_stage_a:{description:"execute and persist mandatory PR-feedback Stage A checks on a content-bound revision",agents:["architect"]},submit_council_verdicts:{description:"submit pre-collected council member verdicts for synthesis (architect MUST dispatch critic/reviewer/sme/test_engineer/explorer as Agent tasks first; this tool synthesizes only, it does not contact members)",agents:[]},submit_phase_council_verdicts:{description:"submit pre-collected phase-level council member verdicts for holistic phase synthesis (architect MUST dispatch all 5 council members with phase-scoped context first; this tool synthesizes only, it does not contact members)",agents:[]},declare_council_criteria:{description:"pre-declare acceptance criteria for a task before the coder starts work; criteria are read back during council evaluation",agents:[]},sbom_generate:{description:"SBOM generation for dependency inventory",agents:["architect"]},checkpoint:{description:"create named git checkpoints for save, restore, and delete — use before risky operations to enable rollback",agents:["architect"]},pkg_audit:{description:"dependency vulnerability scan — npm/pip/cargo",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},parse_lane_candidates:{description:"Parse [CANDIDATE] rows from a dispatch_lanes or collect_lane_results artifact (by output_ref), produce structured records with provenance, optionally persist to a per-batch sidecar JSONL. Pure-parser variant exists as internal module.",agents:["architect"]},plan_conflict_check:{description:"read-only advisory check (#1656): compute a pairwise file-conflict matrix for N proposed parallel task groups using declared scopes and optional git co-change; returns a verdict (all_disjoint / conflicts_present / unknown_scopes), per-pair evidence, and a suggested serialization order. Writes nothing — the execution gate independently recomputes the verdict inline at dispatch time via the same helper. Call BEFORE attempting parallel dispatch to confirm disjointness.",agents:["architect"]},write_pr_review_trigger_eval:{description:"persist the complete PR-review trigger evaluation with exact-set validation, dispatch provenance, and live merge-base verification",agents:["architect"]},write_pr_review_artifact:{description:"persist schema-validated PR-review findings checkpoints and exact actionable feedback handoffs under the active run",agents:["architect"]},prepare_pr_feedback_scope:{description:"prepare an exact file scope for one PR-feedback coder Task after immutable feedback verification settles",agents:["architect"]},test_runner:{description:"auto-detect and run tests",agents:["architect","reviewer","critic_finding_validator","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},test_impact:{description:"identify test files impacted by changed source files via import analysis",agents:["architect","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},mutation_test:{description:"executes pre-generated mutation patches against tests, evaluates kill rate against quality gate thresholds; test selection comes from explicit files (override) or source_files derived via the impact analyzer with a typed bounded fallback",agents:["architect","test_engineer"]},generate_mutants:{description:"generate LLM-based mutation testing patches for source files; returns MutationPatch[] for direct consumption by the mutation_test tool",agents:["architect"]},detect_domains:{description:"detect which SME domains are relevant for a given text",agents:["architect","sme","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic","critic_oversight","explorer"]},git_blame:{description:"per-line git blame metadata: sha, author, date, summary for each line in a file",agents:["reviewer","critic_finding_validator","explorer","architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},gitingest:{description:"fetch a GitHub repository full content via gitingest.com",agents:["architect","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_summary:{description:"retrieve the full content of a stored tool output summary",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_lane_output:{description:"retrieve paged full dispatch lane output by output_ref; use before consuming truncated lane previews or routing candidates from lane results",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},extract_code_blocks:{description:"extract code blocks from text content and save them to files",agents:["docs","docs_design","designer","spec_writer","coder","test_engineer"]},phase_complete:{description:"preflight every applicable phase gate, report all blockers, and atomically commit a current passing snapshot",agents:["architect"]},run_phase_review:{description:"run the bounded phase-final review engine and persist complete content-addressed review evidence",agents:["architect"]},repair_gate_evidence:{description:"quarantine recoverable exact-task gate evidence, rebuild from durable requirements, recover receipt-backed legacy marker wedges or the exact sentinel-only historical reset, and refuse every other receipt-less reconstruction",agents:["architect"]},repair_knowledge_receipt_ledger:{description:"validate or repair authoritative knowledge receipts, preserve corrupt authority in bounded quarantine, and require scoped re-evaluation",agents:["architect"]},record_directive_override:{description:"record an audited architect override for identified critical-directive violations without bypassing unreadable authority",agents:["architect"]},save_plan:{description:"save a structured implementation plan",agents:["architect"]},update_task_status:{description:"mark tasks complete, track phase progress",agents:["architect"]},lint_spec:{description:"validate .swarm/spec.md format and required fields",agents:["architect","spec_writer"]},write_retro:{description:"document phase retrospectives via phase_complete workflow, capture lessons learned",agents:["architect"]},write_drift_evidence:{description:"write drift verification evidence for a completed phase",agents:["architect"]},write_hallucination_evidence:{description:"write hallucination verification evidence for a completed phase",agents:["architect"]},write_mutation_evidence:{description:"write mutation gate evidence for a completed phase; normalizes PASS/WARN/FAIL/SKIP verdicts and writes .swarm/evidence/{phase}/mutation-gate.json",agents:["architect"]},declare_scope:{description:"declare file scope for next coder delegation",agents:["architect"]},scope_validate:{description:"validate shell writes against an inline file scope",agents:["architect"]},knowledge_query:{description:"query swarm or hive knowledge with optional filters",agents:["architect","skill_improver","spec_writer"]},doc_scan:{description:"scan project documentation files and build an index manifest",agents:["architect","docs_design","skill_improver","spec_writer","explorer"]},doc_extract:{description:"extract actionable constraints from project documentation",agents:["architect","docs_design","skill_improver","spec_writer"]},curator_analyze:{description:"run curator phase analysis and optionally apply knowledge recommendations",agents:["architect"]},consensus_mine:{description:"mine cross-run consensus from existing .swarm evidence into an immutable proposals-only report; also deletes its own reports past consensus.report_retention, appends to the shared recommendation dedup ledger (in the shared cohort root, outside this project, when a knowledge link is active), and mirrors proposals into pending swarm-memory proposals when memory is enabled",agents:["architect","curator_phase","curator_postmortem"]},knowledge_add:{description:"store a new lesson in the knowledge base",agents:["architect","coder"]},knowledge_recall:{description:"search the knowledge base for relevant past decisions",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"]},knowledge_remove:{description:"delete an outdated swarm knowledge entry by ID (swarm tier only)",agents:["architect"]},co_change_analyzer:{description:"detect hidden couplings by analyzing git history",agents:["architect"]},context_status:{description:"report current context-window headroom for the active session — returns tokens-used, usageSource (provider|estimated), model-limit with provenance (modelLimitSource: host|override|provider_cap|native|fallback; modelLimitResolution: user_provider_model|user_model|user_default|live_model_limit|static_provider_cap|static_native|static_default; fallbackActive: true when the denominator came from a static table or the flat 128k default — treat headroom as uncertain), usage-percent, threshold-state (none/warn/critical), model name, and provider. Pure read-only: no state mutation, no warning injection. Works whether context_budget.enabled is true or false.",agents:["architect"]},search:{description:"Workspace-scoped ripgrep-style text search with structured JSON output. Supports literal and regex modes, glob filtering, and result limits. NOTE: This is text search, not structural AST search — use symbols and imports tools for structural queries.",agents:["architect","sme","docs","docs_design","designer","critic_hallucination_verifier","skill_improver","spec_writer","reviewer","critic_finding_validator","critic_oversight","explorer","coder","test_engineer","researcher"]},ast_grep:{description:"Read-only structural AST search using ast-grep patterns with optional language and glob filters. Use for syntax-aware code pattern searches; does not rewrite files.",agents:["architect","sme","docs","docs_design","critic_hallucination_verifier","spec_writer","explorer","coder","test_engineer","researcher"]},actionlint_scan:{description:"Run actionlint against GitHub Actions workflow YAML files with structured findings. Resolves actionlint lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},osv_scan:{description:"Run OSV-Scanner against a workspace path and return structured dependency vulnerability findings. Resolves osv-scanner lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},gh_evidence:{description:"Fetch bounded GitHub pull request or issue metadata through gh for review and CI evidence. Resolves gh lazily and is read-only.",agents:["architect","researcher"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},pr_workflow_status:{description:"Read-only architect observation of local git state (HEAD, branch, clean/dirty with a bounded changed-file list, remotes) plus a session-pinned PR workflow gate summary and the PR_FEEDBACK publication-generation section (state, attempts, invalidation reason, recovery guidance). Use to observe state under the fail-closed PR_REVIEW/PR_FEEDBACK gate. Never executes PR-controlled scripts and never reads another session gate.",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},batch_symbols:{description:"Batched symbol extraction across multiple files. Returns per-file symbol summaries with isolated error handling.",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","explorer"]},suggest_patch:{description:"Reviewer-safe structured patch suggestion tool. Produces context-anchored patch artifacts without file modification. Returns structured diagnostics on context mismatch.",agents:["architect","reviewer","critic_finding_validator"]},req_coverage:{description:"query requirement coverage status for tracked functional requirements",agents:["critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","critic","critic_oversight"]},get_approved_plan:{description:"retrieve the last critic-approved immutable plan snapshot for baseline drift comparison",agents:["critic_drift_verifier","critic","critic_oversight"]},repo_map:{description:"query the repo code graph: importers, dependencies, blast radius, localization, ontology facts, package boundaries, and heuristic preflight packets before refactoring; ontology findings are advisory, not formal proofs",agents:["architect","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},get_qa_gate_profile:{description:"retrieve the QA gate profile for the current or exact future plan identity: gates (reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council), lock state, profile hash, the calling session’s ratchet-tighter overrides, and the EFFECTIVE gates (profile merged with those overrides; durable across restart). Read-only and never creates state.",agents:["architect"]},set_qa_gates:{description:"configure the QA gate profile for the current plan or bootstrap an exact future plan with swarm_id and plan_title. Architect-only. The initial selection may set explicit true/false values over defaults; later changes are ratchet-tighter and rejected once locked after critic approval. Supports: reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council, plus adopt_legacy_binding_only for exact-binding recovery without mutating gates.",agents:["architect"]},web_search:{description:"External web search (Tavily or Brave) for architect-driven council research, SME domain research, researcher auto-research, and skill-improver research. Returns titled results with snippets, URLs, normalized query metadata, temporal intent, freshness, and removed stale years. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides. Requires a search API key. Used by the architect in MODE: COUNCIL to gather a RESEARCH CONTEXT before dispatching council agents, by SME for opt-in external skill/source evaluation, and by the researcher agent for multi-source auto-research.",agents:["sme","researcher","skill_improver"]},web_fetch:{description:"Fetch the readable text of a single http(s) URL (architect-only). Returns decoded page text, document title, final URL after redirects, and an evidence reference. Reads primary sources that web_search only surfaces as snippets. Config-gated on council.general.enabled. Blocks private/loopback/link-local/metadata addresses (re-validated and re-pinned across redirects); enforces timeout and body size cap.",agents:[]},convene_general_council:{description:"Synthesize responses from a multi-model General Council. Accepts parallel member responses (Round 1, optionally Round 2), detects disagreements, and returns consensus points, persisting disagreements, and a structured synthesis. Architect-only. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides.",agents:[]},write_final_council_evidence:{description:"Persist project-scoped final council evidence to .swarm/evidence/final-council.json. PREREQUISITE: dispatch critic, reviewer, sme, test_engineer, and explorer as project-scoped Agent tasks and collect their CouncilMemberVerdict JSON — this tool synthesizes only. Rejects on insufficient quorum or CONCERNS with unresolved requiredFixes; normalizes verdicts to approved/concerns/rejected. Architect-only.",agents:[]},skill_generate:{description:"compile knowledge entries into a structured SKILL.md draft",agents:["skill_improver"]},skill_list:{description:"list generated skill files and their status",agents:["skill_improver"]},skill_apply:{description:"activate a draft skill proposal",agents:[]},skill_inspect:{description:"inspect the content and source entries of a skill file",agents:["skill_improver"]},run_stale_reconciliation:{description:"reconcile skills against the knowledge store: mark skills stale when source knowledge is archived or deleted, or clear stale markers",agents:["architect"]},skill_regenerate:{description:"regenerate an active skill by re-clustering its source knowledge entries and updating the SKILL.md in place",agents:[]},skill_retire:{description:"retire a generated skill by adding a retired.marker file; retired skills are excluded from scoring and injection",agents:[]},skill_improve:{description:"run the skill_improver agent to review and refine skills",agents:["skill_improver"]},spec_write:{description:"author or update .swarm/spec.md for the current project",agents:["spec_writer"]},knowledge_receipt:{description:"file a receipt for retrieved knowledge (applied/ignored/contradicted + new lessons), recorded as immutable knowledge events",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},knowledge_receipt_status:{description:"receipt status",agents:["architect"]},knowledge_archive:{description:"archive (default), quarantine, or purge a swarm or hive knowledge entry by ID with an immutable audit tombstone; purge requires an admin flag",agents:["architect"]},swarm_memory_recall:{description:"recall scoped Swarm memory for the current repository as untrusted background",agents:[]},swarm_memory_propose:{description:"create a pending Swarm memory proposal; does not write durable memory directly",agents:[]},swarm_memory_outcome:{description:"record useful, dead-end, or corrected outcomes and, when enabled, synchronously refresh deterministic memory lessons",agents:[]},swarm_command:{description:"run supported /swarm commands through the canonical command registry",agents:["architect","sme","researcher","docs","docs_design","designer","reviewer","critic_finding_validator","critic","explorer","coder","test_engineer"]},dispatch_lanes:{description:"dispatch read-only exploration/review lanes concurrently and BLOCK until all finish; prefer dispatch_lanes_async for non-blocking dispatch, use this only when promptAsync is unavailable",agents:["architect"]},dispatch_lanes_async:{description:"launch read-only advisory lanes non-blockingly and return a batch id plus lane session handles immediately; each lane agent must be a registered generated agent name (unregistered bare roles are refused on multi-swarm hosts); launch_timeout_ms is only a promptAsync acceptance budget, not a lane runtime timeout; poll incrementally with collect_lane_results (wait omitted), or join with wait: true for all results",agents:["architect"]},collect_lane_results:{description:"collect/poll a dispatch_lanes_async batch; a presumed-stale sweep runs on every call, settling lanes past the horizon: idle host to stale, unobservable host to a typed liveness error; cancel_pending cancels pending lanes; otherwise observe-only. Non-blocking poll (wait omitted or false) and blocking join (wait: true) supported. The wait budget bounds the observer call only — expiry never kills a lane nor proves it died; poll again or cancel explicitly, never abort. Unsettled lanes are reported in pending_lanes (batch_id, lane_id, status, output_ref) regardless of include_pending; busy/retry lanes never go stale for running long. Does not advance workflow gates. Settled-lane inline output is delivered once: later polls set output_omitted_repeat: true and omit output but keep output_ref for retrieval via retrieve_lane_output.",agents:["architect"]},summarize_work:{description:"emit a short structured summary of completed work (key decisions, assumptions, risks, constraints) at task completion; rolls up per phase for architecture-supervisor review. Advisory, never blocks.",agents:["architect","sme","researcher","docs","docs_design","designer","explorer","coder","test_engineer"]},write_architecture_supervisor_evidence:{description:"persist the architecture supervisor verdict for a phase (architect MUST dispatch critic_architecture_supervisor first and collect its JSON verdict; this tool persists only, it does not contact the supervisor)",agents:["architect"]},lean_turbo_plan_lanes:{description:"partition phase tasks into parallel lanes based on file-scope conflicts for Lean Turbo execution",agents:[]},lean_turbo_acquire_locks:{description:"acquire file locks for all files in a lane (all-or-nothing) before lane execution",agents:[]},lean_turbo_runner_status:{description:"read Lean Turbo run state from .swarm/turbo-state.json",agents:[]},lean_turbo_critic:{description:"dispatch a read-only critic agent to evaluate boundary conditions for a completed Lean Turbo phase (satisfies the turbo.lean.phase_critic gate)",agents:[]},lean_turbo_review:{description:"dispatch a read-only reviewer agent to evaluate a completed Lean Turbo phase",agents:[]},lean_turbo_run_phase:{description:"Execute a phase using Lean Turbo parallel lane execution. Plans lanes, acquires file locks, and dispatches coder agents concurrently. Use when Lean Turbo is active and you want to execute all tasks in a phase in parallel lanes.",agents:[]},lean_turbo_status:{description:"returns Lean Turbo configuration and active status for the current session",agents:[]},swarm_apply_patch:{description:"Apply a unified diff patch to workspace files with exact context matching, atomic writes, and path validation. Use standard unified diff format only — does NOT support *** Begin Patch / *** Update File payloads (use native apply_patch for those).",agents:["coder","test_engineer"]},external_skill_discover:{description:"Discover external skill candidates from configured sources. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_list:{description:"List external skill candidates in the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_inspect:{description:"Inspect a specific external skill candidate by ID. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_promote:{description:"Promote a validated external skill candidate to an active generated skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_reject:{description:"Reject an external skill candidate after evaluation. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_delete:{description:"Delete an external skill candidate from the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_revoke:{description:"Revoke a previously promoted external skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},epic_decide_phase:{description:"Compute the Epic Mode verdict for a phase WITHOUT dispatching coders. Runs preflight + calibration + the three gates (p-threshold, hot-module, greenfield), persists the decision, and returns the verdict so the architect can dispatch waves via the visible Task tool (promote) or fall back to per-task serial (demote). Pair with `epic_plan_waves` to get the wave plan when promoted. Use when /swarm epic is on for the session.",agents:["architect"]},epic_plan_waves:{description:"Partition a phase's pending tasks into ordered concurrent waves for Epic Mode dispatch. A wave is a set of tasks with mutually disjoint declared scopes and all dependencies satisfied by prior waves. Returns `{ waves: [{ waveId, taskIds, files }, ...], serializedTasks, degradedTasks }`. "+'For each wave in order, the architect dispatches one `Task(subagent_type="coder", ...)` per `taskId` — all in one assistant message — so the wave runs concurrently and each coder appears as a visible subagent. '+"Wait for the wave to finish before dispatching the next. Pair with `epic_decide_phase` (called first; this tool is only relevant on a `promote` verdict). "+"Preflight reject reasons: `no-plan`, `no-phase`, `phase-empty`, `phase-already-complete`, `scopes-missing` (call `declare_scope` for `missingScopes`), `git-failed` (transient — retry), `planner-error`.",agents:["architect"]},epic_record_divergence:{description:"After every `update_task_status(completed)`, record the task's declared-vs-actual divergence to .swarm/epic/divergence.jsonl. Feeds Epic Mode's self-calibration loop (Capability D). Best-effort: never blocks.",agents:["architect"]}},TOOL_NAMES=Object.keys(TOOL_METADATA),TOOL_NAME_SET=new Set(TOOL_NAMES);TOOL_DESCRIPTIONS=Object.fromEntries(Object.entries(TOOL_METADATA).map(([name,meta])=>[name,meta.description])),AGENT_TOOL_MAP=(()=>{let map=Object.fromEntries(ALL_AGENT_NAMES.map((agent)=>[agent,[]]));for(let[name,meta]of Object.entries(TOOL_METADATA))for(let agent of meta.agents)map[agent].push(name);return map})()});function scanOverrideForDangerousKeys(value,path,depth){if(depth>=10)return;if(Array.isArray(value)){for(let i=0;i<value.length;i++)scanOverrideForDangerousKeys(value[i],`${path}[${i}]`,depth+1);return}if(typeof value!=="object"||value===null)return;for(let key of Object.keys(value)){if(DANGEROUS_MERGE_KEYS.has(key))throw new DangerousMergeKeyError(key,path);scanOverrideForDangerousKeys(value[key],`${path}.${key}`,depth+1)}}function deepMergeInternal(base,override,depth,path){if(depth>=10)throw Error("deepMerge exceeded maximum depth of 10");let result={...base};for(let key of Object.keys(override)){let baseVal=base[key],overrideVal=override[key];if(typeof baseVal==="object"&&baseVal!==null&&typeof overrideVal==="object"&&overrideVal!==null&&!Array.isArray(baseVal)&&!Array.isArray(overrideVal))result[key]=deepMergeInternal(baseVal,overrideVal,depth+1,`${path}.${key}`);else result[key]=overrideVal}return result}function deepMerge(base,override){if(!base)return override;if(!override)return base;return scanOverrideForDangerousKeys(override,"$",0),deepMergeInternal(base,override,0,"$")}var MAX_MERGE_DEPTH=10,DANGEROUS_MERGE_KEYS,DangerousMergeKeyError;var init_merge=__esm(()=>{DANGEROUS_MERGE_KEYS=new Set(["__proto__","constructor","prototype"]);DangerousMergeKeyError=class DangerousMergeKeyError extends Error{key;path;constructor(key,path){super(`deepMerge refused dangerous key "${key}" at "${path}": prototype-pollution carriers (__proto__/constructor/prototype) are never merged`);this.key=key;this.path=path;this.name="DangerousMergeKeyError"}}});function freezeSet(items,name="CLAUDE_CODE_NATIVE_COMMANDS"){let set=new Set(items),proxy=new Proxy(set,{get(target,prop){if(prop==="add"||prop==="delete"||prop==="clear")return()=>{throw TypeError(`${name} is readonly`)};if(prop==="forEach")return(callback,thisArg)=>{let wrapped=(v,k)=>callback.call(thisArg??void 0,v,k,proxy);return set.forEach(wrapped)};let value=Reflect.get(target,prop);return typeof value==="function"?value.bind(target):value},set(){throw TypeError(`${name} is readonly`)},deleteProperty(){throw TypeError(`${name} is readonly`)},defineProperty(){throw TypeError(`${name} is readonly`)},setPrototypeOf(){throw TypeError(`${name} is readonly`)}});return proxy}function isQAAgent(name){return QA_AGENTS.includes(name)}function isSubagent(name){return ALL_SUBAGENT_NAMES.includes(name)}function isLowCapabilityModel(modelId){let lower=(modelId||"").toLowerCase();return LOW_CAPABILITY_MODELS.some((substr)=>lower.includes(substr))}var OPENCODE_NATIVE_AGENTS,CLAUDE_CODE_NATIVE_COMMANDS,OPENCODE_NATIVE_COMMANDS,MEMORY_AGENT_TOOL_MAP,EXTERNAL_SKILL_TOOL_NAMES,EXTERNAL_SKILL_AGENT_TOOL_MAP,COUNCIL_TOOL_NAMES,COUNCIL_AGENT_TOOL_MAP,GENERAL_COUNCIL_TOOL_NAMES,GENERAL_COUNCIL_AGENT_TOOL_MAP,TURBO_TOOL_NAMES,TURBO_AGENT_TOOL_MAP,SKILL_TOOL_NAMES,SKILL_AGENT_TOOL_MAP,PR_REVIEW_CHILD_TOOL_NAMES,PR_REVIEW_CHILD_AGENT_TOOL_MAP,WRITE_TOOL_NAMES,SUMMARIZER_EXEMPT_TOOL_NAMES,DEFAULT_MODELS,DEFAULT_AGENT_CONFIGS,DEFAULT_SCORING_CONFIG,LOW_CAPABILITY_MODELS,TURBO_MODE_BANNER=`## \uD83D\uDE80 TURBO MODE ACTIVE
|
|
2
2
|
|
|
3
3
|
**Speed optimization enabled for this session.**
|
|
4
4
|
|
|
@@ -471,7 +471,7 @@ ${trimmed}`}else malformedRows++;continue}let rowFields=fields.slice(0,CANDIDATE
|
|
|
471
471
|
lease_expires_at = excluded.lease_expires_at, payload = excluded.payload,
|
|
472
472
|
updated_at = excluded.updated_at`,[input.namespace,input.entityKey,input.generation,input.ownerToken,input.leaseExpiresAt,input.payload,now]),{outcome:"acquired"}})}function releaseCoordinationLease(directory,namespace,entityKey,generation,ownerToken){return withCoordinationTransaction(directory,()=>{return getProjectDb(directory).run(`DELETE FROM coordination_lease
|
|
473
473
|
WHERE namespace = ? AND entity_key = ? AND generation = ? AND owner_token = ?`,[namespace,entityKey,generation,ownerToken]).changes===1})}function importCoordinationOnce(directory,input,importer){if(boundedText(input.source,"source",MAX_KEY_CHARS),boundedText(input.sourceDigest,"sourceDigest",MAX_KEY_CHARS),boundedText(input.emptyNamespace,"emptyNamespace",MAX_KEY_CHARS),!Number.isSafeInteger(input.rowCount)||input.rowCount<0)throw Error("rowCount must be a nonnegative safe integer");let result=withCoordinationTransaction(directory,()=>{let db=getProjectDb(directory);if(db.query("SELECT 1 AS present FROM coordination_import WHERE source = ?").get(input.source))return"already_imported";if((db.query("SELECT COUNT(*) AS count FROM coordination_state WHERE namespace = ?").get(input.emptyNamespace)?.count??0)!==0)return"state_exists";return importer(),db.run(`INSERT INTO coordination_import
|
|
474
|
-
(source, imported_at, source_digest, row_count) VALUES (?, ?, ?, ?)`,[input.source,new Date().toISOString(),input.sourceDigest,input.rowCount]),"imported"});if(result==="imported")_internals14.coordinationFaultInjector?.("after_commit_before_archive",getProjectDb(directory));return result}function deleteCoordinationImports(directory,sources){let boundedSources=sources.map((source)=>boundedText(source,"source",MAX_KEY_CHARS));if(boundedSources.length===0||!projectDbExists(directory))return 0;return withCoordinationTransaction(directory,()=>{let placeholders=boundedSources.map(()=>"?").join(", ");return getProjectDb(directory).run(`DELETE FROM coordination_import WHERE source IN (${placeholders})`,boundedSources).changes})}var MAX_KEY_CHARS=512,MAX_STATUS_CHARS=128,MAX_PAYLOAD_CHARS=1048576,MAX_EVENTS_PER_STREAM=2048,MAX_TOTAL_EVENTS=1e5,MAX_EVENT_FENCES_PER_STREAM=8192,MAX_TOTAL_EVENT_FENCES=400000,MAX_COORDINATION_STATE_LIST_ROWS=25000,COORDINATION_STATE_PAGE_SIZE=5000,_internals14;var init_coordination_store=__esm(()=>{init_durability();init_project_db();_internals14={maxEventsPerStream:MAX_EVENTS_PER_STREAM,maxTotalEvents:MAX_TOTAL_EVENTS,maxEventFencesPerStream:MAX_EVENT_FENCES_PER_STREAM,maxTotalEventFences:MAX_TOTAL_EVENT_FENCES}});import*as crypto2 from"node:crypto";import*as fs6 from"node:fs";import*as path12 from"node:path";function getLockFilePath(directory,filePath){let normalized=path12.resolve(directory,filePath),baseDir=path12.resolve(directory)+path12.sep;if(!(process.platform==="win32"?normalized.toLowerCase().startsWith(baseDir.toLowerCase()):normalized.startsWith(baseDir)))throw Error("Invalid file path: path traversal not allowed");let pathForHash=process.platform==="win32"?normalized.toLowerCase():normalized,hash2=crypto2.createHash("sha256").update(pathForHash).digest("hex"),lockPath=path12.join(directory,LOCKS_DIR,`${hash2}.lock`),legacyPaths=[pathForHash];if(process.platform==="win32"&&normalized!==pathForHash)legacyPaths.push(normalized);for(let legacyPath of legacyPaths){let oldHash=Buffer.from(legacyPath).toString("base64").replace(/[/+=]/g,"_"),oldLockPath=path12.join(directory,LOCKS_DIR,`${oldHash}.lock`);if(fs6.existsSync(oldLockPath))return oldLockPath}return lockPath}function getMetaPath(lockPath){return`${lockPath.replace(/\.lock$/,"")}.meta`}async function writeMetaFile(metaPath,metadata){let tmpPath=`${metaPath}.tmp`;try{await _internals15.writeFile(tmpPath,JSON.stringify(metadata),"utf-8"),await fs6.promises.rename(tmpPath,metaPath)}catch(err){try{await fs6.promises.unlink(tmpPath)}catch{}throw err}}function readMetaFile(metaPath){try{let content=fs6.readFileSync(metaPath,"utf-8");return JSON.parse(content)}catch{return null}}async function tryAcquireLock(directory,filePath,agent,taskId){let lockPath=getLockFilePath(directory,filePath),locksDir=path12.dirname(lockPath);if(!fs6.existsSync(locksDir))fs6.mkdirSync(locksDir,{recursive:!0});if(!fs6.existsSync(lockPath))fs6.writeFileSync(lockPath,"","utf-8");let release;try{release=await import_proper_lockfile2.default.lock(lockPath,{stale:LOCK_TIMEOUT_MS,retries:{retries:5,minTimeout:10,maxTimeout:500,factor:2},realpath:!1})}catch(err){let code=err.code;if(code==="ELOCKED"||code==="EEXIST")return{acquired:!1};throw err}return{acquired:!0,lock:{filePath,agent,taskId,timestamp:new Date().toISOString(),expiresAt:Date.now()+LOCK_TIMEOUT_MS,_release:release}}}function isLocked(directory,filePath){let plLockDir=`${getLockFilePath(directory,filePath)}.lock`;if(fs6.existsSync(plLockDir)){let acquiredAt=Date.now();try{acquiredAt=fs6.statSync(plLockDir).mtimeMs}catch{}return{filePath,agent:"unknown",taskId:"unknown",timestamp:new Date(acquiredAt).toISOString(),expiresAt:acquiredAt+LOCK_TIMEOUT_MS}}return null}function listActiveLocks(directory){let locksDir=path12.join(directory,LOCKS_DIR),locks=[];if(!fs6.existsSync(locksDir))return locks;let files=fs6.readdirSync(locksDir),now=Date.now();for(let file2 of files){if(!file2.endsWith(".lock"))continue;let lockPath=path12.join(locksDir,file2);try{if(fs6.statSync(lockPath).isFile()){let plLockDir=`${lockPath}.lock`;if(fs6.existsSync(plLockDir)){let metaPath=getMetaPath(lockPath),meta3=readMetaFile(metaPath);if(meta3){if(meta3.expiresAt<now)continue;locks.push({filePath:meta3.originalPath,agent:meta3.agent,taskId:meta3.taskId,timestamp:meta3.acquiredAt,expiresAt:meta3.expiresAt,laneId:meta3.laneId})}else{let acquiredAt=Date.now();try{acquiredAt=fs6.statSync(plLockDir).mtimeMs}catch{}let expiresAt=acquiredAt+LOCK_TIMEOUT_MS;if(expiresAt<now)continue;locks.push({filePath:lockPath,agent:"unknown",taskId:"unknown",timestamp:new Date(acquiredAt).toISOString(),expiresAt})}}}}catch{}}return locks}async function acquireLaneLocks(directory,laneId,files,agent,taskId,sessionID){let acquiredLocks=[],conflicts=[];for(let file2 of files){let result=await tryAcquireLock(directory,file2,agent,taskId);if(!result.acquired){for(let lock of acquiredLocks)try{if(lock._release)await lock._release();let lockPath2=getLockFilePath(directory,lock.filePath),metaPath2=getMetaPath(lockPath2);try{fs6.unlinkSync(metaPath2)}catch{}try{fs6.unlinkSync(lockPath2)}catch{}}catch{}return conflicts.push(file2),{acquired:!1,conflicts}}let lockPath=getLockFilePath(directory,file2),metaPath=getMetaPath(lockPath),meta3={originalPath:file2,laneId,taskId,agent,sessionID,acquiredAt:result.lock.timestamp,expiresAt:result.lock.expiresAt};try{await writeMetaFile(metaPath,meta3)}catch(err){for(let lock of acquiredLocks)try{if(lock._release)await lock._release();let lp=getLockFilePath(directory,lock.filePath),mp=getMetaPath(lp);try{fs6.unlinkSync(mp)}catch{}try{fs6.unlinkSync(lp)}catch{}}catch{}if(result.lock._release)await result.lock._release();try{fs6.unlinkSync(lockPath)}catch{}throw err}result.lock.laneId=laneId,acquiredLocks.push(result.lock)}return{acquired:!0,locks:acquiredLocks}}async function releaseLaneLocks(directory,laneId){let locksDir=path12.join(directory,LOCKS_DIR);if(!fs6.existsSync(locksDir))return 0;let files=fs6.readdirSync(locksDir),releasedCount=0;for(let file2 of files){if(!file2.endsWith(".meta"))continue;let metaPath=path12.join(locksDir,file2),meta3=readMetaFile(metaPath);if(!meta3||meta3.laneId!==laneId)continue;let lockPath=metaPath.replace(/\.meta$/,".lock");try{try{await import_proper_lockfile2.default.unlock(lockPath,{realpath:!1})}catch{}try{fs6.unlinkSync(lockPath)}catch{}try{fs6.unlinkSync(metaPath)}catch{}releasedCount++}catch{}}return releasedCount}var import_proper_lockfile2,LOCKS_DIR=".swarm/locks",LOCK_TIMEOUT_MS=300000,_internals15;var init_file_locks=__esm(()=>{import_proper_lockfile2=__toESM(require_proper_lockfile(),1),_internals15={tryAcquireLock,writeFile:fs6.promises.writeFile}});function defineEntry(kind,input){let entry={kind,category:input.category,severity:input.severity,privacyClass:input.privacyClass,producer:input.producer,consumers:input.consumers,retentionOwnerIssue:input.retentionOwnerIssue,requiredWorkflowIds:input.requiredWorkflowIds??NO_WORKFLOW_IDS,forbiddenWorkflowIds:input.forbiddenWorkflowIds??NO_WORKFLOW_IDS,requiresParent:input.requiresParent??!1,allowsLinks:input.allowsLinks??!0,otelMapping:input.otelMapping??"none",docAnchor:`#${kind}`,testFile:"tests/unit/observability/catalog-contract.test.ts"};if(input.futureOwnerIssue!==void 0)return Object.freeze({...entry,futureOwnerIssue:input.futureOwnerIssue});return Object.freeze(entry)}function getCatalogEntry(kind){return Object.hasOwn(EVENT_CATALOG,kind)?EVENT_CATALOG[kind]:void 0}var NO_WORKFLOW_IDS,NO_CONSUMERS,REQUIRE_SESSION,REQUIRE_SESSION_AND_TASK,REQUIRE_TASK,REQUIRE_COUNCIL_ROUND,FORBID_SESSION,FORBID_COUNCIL_ROUND,CONSUMER_COST_ACCOUNTING,CONSUMER_COST_CORRECTION,CONSUMER_COST_JOIN,CONSUMER_GATE_STATS,CONSUMER_HEARTBEAT_LISTENER,CATALOG_SOURCE,catalog,EVENT_CATALOG,CATALOG_KINDS;var init_catalog=__esm(()=>{NO_WORKFLOW_IDS=Object.freeze([]),NO_CONSUMERS=Object.freeze([]),REQUIRE_SESSION=Object.freeze(["hostSessionId"]),REQUIRE_SESSION_AND_TASK=Object.freeze(["hostSessionId","taskId"]),REQUIRE_TASK=Object.freeze(["taskId"]),REQUIRE_COUNCIL_ROUND=Object.freeze(["councilRoundId"]),FORBID_SESSION=Object.freeze(["hostSessionId"]),FORBID_COUNCIL_ROUND=Object.freeze(["councilRoundId"]),CONSUMER_COST_ACCOUNTING=Object.freeze(["src/services/cost-accounting.ts:405"]),CONSUMER_COST_CORRECTION=Object.freeze(["src/services/cost-accounting.ts:465"]),CONSUMER_COST_JOIN=Object.freeze(["src/services/cost-accounting.ts:452"]),CONSUMER_GATE_STATS=Object.freeze(["src/evaluation/gate-stats.ts:99"]),CONSUMER_HEARTBEAT_LISTENER=Object.freeze(["src/telemetry.ts:282"]);CATALOG_SOURCE=[["session_started",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:669",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"openinference"}],["session_ended",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:673",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"openinference"}],["agent_activated",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:677",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"openinference"}],["task_state_changed",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:735",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK,otelMapping:"openinference"}],["phase_changed",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:783",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"openinference"}],["heartbeat",{category:"lifecycle",severity:"debug",privacyClass:"pseudonymous",producer:"src/telemetry.ts:965",consumers:CONSUMER_HEARTBEAT_LISTENER,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,allowsLinks:!1}],["turbo_mode_changed",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:973",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION}],["environment_detected",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:998",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,allowsLinks:!1}],["delegation_begin",{category:"delegation",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:681",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK,otelMapping:"genai"}],["delegation_end",{category:"delegation",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:691",consumers:CONSUMER_COST_ACCOUNTING,retentionOwnerIssue:2043,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK,otelMapping:"genai"}],["delegation_read_uncertain",{category:"delegation",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:722",consumers:NO_CONSUMERS,futureOwnerIssue:2511,retentionOwnerIssue:2511,otelMapping:"none"}],["delegation_cost_correction",{category:"delegation",severity:"info",privacyClass:"pseudonymous",producer:"src/index.ts:959",consumers:CONSUMER_COST_CORRECTION,retentionOwnerIssue:2043,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK,otelMapping:"genai"}],["delegation_cost_binding",{category:"delegation",severity:"info",privacyClass:"pseudonymous",producer:"src/index.ts:2087",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2043,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"none"}],["delegation_cost_join",{category:"delegation",severity:"notice",privacyClass:"pseudonymous",producer:"src/index.ts:2107",consumers:CONSUMER_COST_JOIN,retentionOwnerIssue:2043,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"none"}],["model_fallback",{category:"delegation",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:816",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"genai"}],["model_unresolved",{category:"delegation",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:830",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"genai"}],["gate_passed",{category:"gate",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:744",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK}],["gate_failed",{category:"gate",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:761",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK}],["gate_parse_error",{category:"gate",severity:"warning",privacyClass:"sensitive",producer:"src/telemetry.ts:748",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_TASK,forbiddenWorkflowIds:FORBID_SESSION}],["reviewer_gate_decision",{category:"gate",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:771",consumers:CONSUMER_GATE_STATS,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK}],["council_attempt",{category:"gate",severity:"info",privacyClass:"pseudonymous",producer:"src/council/council-observability.ts:85",consumers:NO_CONSUMERS,futureOwnerIssue:2048,retentionOwnerIssue:2046,requiredWorkflowIds:REQUIRE_COUNCIL_ROUND}],["council_round_transition",{category:"gate",severity:"info",privacyClass:"pseudonymous",producer:"src/council/council-observability.ts:115",consumers:NO_CONSUMERS,futureOwnerIssue:2048,retentionOwnerIssue:2046,requiredWorkflowIds:REQUIRE_COUNCIL_ROUND}],["council_attempt_unscoped",{category:"gate",severity:"warning",privacyClass:"pseudonymous",producer:"src/council/council-observability.ts:152",consumers:NO_CONSUMERS,futureOwnerIssue:2048,retentionOwnerIssue:2046,forbiddenWorkflowIds:FORBID_COUNCIL_ROUND}],["context_source_attribution",{category:"cost",severity:"info",privacyClass:"pseudonymous",producer:"src/services/context-attribution.ts:124",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION}],["verdict_row_pipe_recovery",{category:"gate",severity:"info",privacyClass:"pseudonymous",producer:"src/pr-review/legacy-transcript-adapter.ts:689",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045}],["training_vault_health",{category:"guardrail",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1167",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:NO_WORKFLOW_IDS}],["budget_updated",{category:"cost",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:787",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2043,requiredWorkflowIds:REQUIRE_SESSION}],["context_pruned",{category:"guardrail",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:806",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["retrieval_routed",{category:"guardrail",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1400",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["hard_limit_hit",{category:"guardrail",severity:"error",privacyClass:"pseudonymous",producer:"src/telemetry.ts:844",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["revision_limit_hit",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:853",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["loop_detected",{category:"guardrail",severity:"warning",privacyClass:"sensitive",producer:"src/telemetry.ts:857",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["scope_violation",{category:"guardrail",severity:"error",privacyClass:"sensitive",producer:"src/telemetry.ts:953",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["qa_skip_violation",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:961",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["auto_oversight_escalation",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:983",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["no_op_strong_warning",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:871",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["gate_denial_loop",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:892",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["execution_stall_warning",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:906",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["execution_stall_denied",{category:"guardrail",severity:"error",privacyClass:"pseudonymous",producer:"src/telemetry.ts:923",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["swarm_internals_read_denied",{category:"guardrail",severity:"error",privacyClass:"sensitive",producer:"src/telemetry.ts:940",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_hard_stop_delivered",{category:"prm",severity:"error",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1381",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_pattern_detected",{category:"prm",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1013",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_course_correction_injected",{category:"prm",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1027",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_escalation_triggered",{category:"prm",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1040",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_hard_stop",{category:"prm",severity:"critical",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1054",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_hard_stop_terminal",{category:"prm",severity:"critical",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1079",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["evidence_lock_acquired",{category:"evidence",severity:"info",privacyClass:"sensitive",producer:"src/evidence/lock.ts:99",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,requiredWorkflowIds:REQUIRE_TASK,forbiddenWorkflowIds:FORBID_SESSION}],["evidence_lock_contended",{category:"evidence",severity:"notice",privacyClass:"sensitive",producer:"src/evidence/lock.ts:134",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,requiredWorkflowIds:REQUIRE_TASK,forbiddenWorkflowIds:FORBID_SESSION}],["evidence_lock_stale_recovered",{category:"evidence",severity:"notice",privacyClass:"sensitive",producer:"src/evidence/lock.ts:91",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,requiredWorkflowIds:REQUIRE_TASK,forbiddenWorkflowIds:FORBID_SESSION}],["plan_ledger_cas_retry",{category:"plan",severity:"notice",privacyClass:"operational",producer:"src/plan/manager.ts:388",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,forbiddenWorkflowIds:FORBID_SESSION}],["plan_md_write_failed",{category:"plan",severity:"warning",privacyClass:"sensitive",producer:"src/plan/manager.ts:2207",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,forbiddenWorkflowIds:FORBID_SESSION}],["snapshot_failed",{category:"plan",severity:"error",privacyClass:"sensitive",producer:"src/plan/ledger.ts:1620",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,forbiddenWorkflowIds:FORBID_SESSION}],["agent_conflict_detected",{category:"conflict",severity:"warning",privacyClass:"pseudonymous",producer:"src/hooks/conflict-resolution.ts:73",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:Object.freeze(["hostSessionId","phaseId"])}],["close_archive_result",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:1116",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047}],["knowledge_receipt_transition",{category:"knowledge",severity:"info",privacyClass:"pseudonymous",producer:"src/hooks/knowledge-receipt-observability.ts:197",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["knowledge_maintenance",{category:"knowledge",severity:"notice",privacyClass:"pseudonymous",producer:"src/knowledge/hive-quarantine.ts:1265",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["residue_health",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:1138",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["context_telemetry_health",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:1182",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["skill_usage_health",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:1219",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["core_events_health",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:1245",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["shell_audit_health",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:1269",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["trajectory_health",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:1292",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["pr_subscription_health",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:1321",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["learning_health_alarm",{category:"lifecycle",severity:"warning",privacyClass:"operational",producer:"src/telemetry.ts:1365",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2044,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["execution_attempt_recorded",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/services/execution-attempt.ts:265",consumers:["src/commands/report.ts:60"],retentionOwnerIssue:2676,requiredWorkflowIds:REQUIRE_SESSION,forbiddenWorkflowIds:FORBID_COUNCIL_ROUND,otelMapping:"none"}]],catalog={};for(let[kind,input]of CATALOG_SOURCE)catalog[kind]=defineEntry(kind,input);EVENT_CATALOG=Object.freeze(catalog),CATALOG_KINDS=Object.freeze(Object.keys(EVENT_CATALOG))});var OBSERVABILITY_SCHEMA_VERSION=1,EventCategorySchema,EventSeveritySchema,PrivacyClassSchema,TimingConfidenceSchema,SpanLinkSchema,TraceContextSchema,WorkflowIdsSchema,LineageSchema,ProvenanceSchema,OutcomeSchema,PolicySchema,LegacyProjectionSchema,ObservabilityEventSchema;var init_envelope=__esm(()=>{init_zod();EventCategorySchema=exports_external.enum(["lifecycle","delegation","gate","plan","evidence","guardrail","knowledge","cost","prm","conflict","unrecognized"]),EventSeveritySchema=exports_external.enum(["debug","info","notice","warning","error","critical"]),PrivacyClassSchema=exports_external.enum(["operational","pseudonymous","sensitive","content"]),TimingConfidenceSchema=exports_external.enum(["exact","writer-clock","inferred","unknown"]),SpanLinkSchema=exports_external.object({traceId:exports_external.string(),spanId:exports_external.string(),kind:exports_external.enum(["resume","lane","cross-process","retry","parent-batch"]),note:exports_external.string().optional()}),TraceContextSchema=exports_external.object({traceId:exports_external.string(),spanId:exports_external.string(),parentSpanId:exports_external.string().optional(),links:exports_external.array(SpanLinkSchema)}),WorkflowIdsSchema=exports_external.object({rootConversationId:exports_external.string().optional(),hostSessionId:exports_external.string().optional(),swarmSessionId:exports_external.string().optional(),taskId:exports_external.string().optional(),callId:exports_external.string().optional(),invocationId:exports_external.string().optional(),phaseId:exports_external.string().optional(),laneId:exports_external.string().optional(),batchId:exports_external.string().optional(),resultId:exports_external.string().optional(),councilRoundId:exports_external.string().optional(),backgroundInvocationId:exports_external.string().optional(),knowledgeTraceId:exports_external.string().optional(),knowledgeEntryId:exports_external.string().optional(),prRunId:exports_external.string().optional()}),LineageSchema=exports_external.object({projectRef:exports_external.string().optional(),cohortRef:exports_external.string().optional(),worktreeRef:exports_external.string().optional()}),ProvenanceSchema=exports_external.object({pluginVersion:exports_external.string().optional(),opencodeVersion:exports_external.string().optional(),runtime:exports_external.string().optional(),runtimeVersion:exports_external.string().optional(),os:exports_external.string().optional(),arch:exports_external.string().optional(),model:exports_external.string().optional(),provider:exports_external.string().optional(),gitSha:exports_external.string().optional(),configHash:exports_external.string().optional()}),OutcomeSchema=exports_external.object({status:exports_external.enum(["success","failure","partial","unknown"]).optional(),reason:exports_external.string().optional(),errorName:exports_external.string().optional(),errorMessage:exports_external.string().optional(),retryIndex:exports_external.number().optional(),durationMs:exports_external.number().optional()}),PolicySchema=exports_external.object({sampled:exports_external.boolean(),sampleRate:exports_external.number(),dropReason:exports_external.string().optional(),privacyClass:PrivacyClassSchema}),LegacyProjectionSchema=exports_external.object({sourceStore:exports_external.string(),sourceSchemaVersion:exports_external.number().nullable(),timingConfidence:TimingConfidenceSchema,unknown:exports_external.array(exports_external.string()),extra:exports_external.record(exports_external.string(),exports_external.unknown()),raw:exports_external.unknown()}),ObservabilityEventSchema=exports_external.object({schemaVersion:exports_external.number(),eventId:exports_external.string(),kind:exports_external.string(),category:EventCategorySchema,severity:EventSeveritySchema,occurredAt:exports_external.string(),observedAt:exports_external.string(),writerSequence:exports_external.number(),trace:TraceContextSchema,workflow:WorkflowIdsSchema,lineage:LineageSchema,provenance:ProvenanceSchema,outcome:OutcomeSchema,policy:PolicySchema,legacy:LegacyProjectionSchema,relationshipViolations:exports_external.array(exports_external.string())})});import{createHash as createHash7,randomBytes as randomBytes2,randomUUID as randomUUID2}from"node:crypto";function newTraceId(){for(let attempt=0;attempt<MAX_REGENERATION_ATTEMPTS;attempt++){let hex3=randomBytes2(TRACE_ID_BYTES).toString("hex");if(hex3!==ALL_ZERO_TRACE_ID)return hex3}return SENTINEL_TRACE_ID}function newSpanId(){for(let attempt=0;attempt<MAX_REGENERATION_ATTEMPTS;attempt++){let hex3=randomBytes2(SPAN_ID_BYTES).toString("hex");if(hex3!==ALL_ZERO_SPAN_ID)return hex3}return SENTINEL_SPAN_ID}function newEventId(){return randomUUID2()}function takeIdBytes(){let need=TRACE_ID_BYTES+SPAN_ID_BYTES;if(_poolOffset+need>_pool.length)_pool=randomBytes2(POOL_BYTES),_poolOffset=0;let slice=_pool.subarray(_poolOffset,_poolOffset+need);return _poolOffset+=need,slice}function newTraceAndSpanId(){let buffer=takeIdBytes(),traceId=buffer.subarray(0,TRACE_ID_BYTES).toString("hex"),spanId=buffer.subarray(TRACE_ID_BYTES).toString("hex");if(traceId===ALL_ZERO_TRACE_ID||spanId===ALL_ZERO_SPAN_ID)return{traceId:newTraceId(),spanId:newSpanId()};return{traceId,spanId}}function resolveLineageSalt(){let configured=process.env[LINEAGE_SALT_ENV];if(typeof configured==="string"&&configured.length>0)return configured;return DEFAULT_LINEAGE_SALT}function pseudonymousRef(absolutePath,salt){return createHash7("sha256").update(salt+LINEAGE_SEPARATOR+absolutePath,"utf8").digest("hex").slice(0,PSEUDONYMOUS_REF_LENGTH)}function pseudonymousSessionRef(sessionId,salt=resolveLineageSalt()){return pseudonymousRef(sessionId,salt)}var TRACE_ID_BYTES=16,SPAN_ID_BYTES=8,TRACE_ID_HEX_LENGTH,SPAN_ID_HEX_LENGTH,ALL_ZERO_TRACE_ID,ALL_ZERO_SPAN_ID,SENTINEL_TRACE_ID,SENTINEL_SPAN_ID,MAX_REGENERATION_ATTEMPTS=4,LINEAGE_SALT_ENV="SWARM_OBSERVABILITY_LINEAGE_SALT",DEFAULT_LINEAGE_SALT="opencode-swarm/observability/lineage/v1",LINEAGE_SEPARATOR="\x00",PSEUDONYMOUS_REF_LENGTH=16,POOL_DRAWS=128,POOL_BYTES,_pool,_poolOffset;var init_ids=__esm(()=>{TRACE_ID_HEX_LENGTH=TRACE_ID_BYTES*2,SPAN_ID_HEX_LENGTH=SPAN_ID_BYTES*2,ALL_ZERO_TRACE_ID="0".repeat(TRACE_ID_HEX_LENGTH),ALL_ZERO_SPAN_ID="0".repeat(SPAN_ID_HEX_LENGTH),SENTINEL_TRACE_ID=`${"0".repeat(TRACE_ID_HEX_LENGTH-1)}1`,SENTINEL_SPAN_ID=`${"0".repeat(SPAN_ID_HEX_LENGTH-1)}1`;POOL_BYTES=(TRACE_ID_BYTES+SPAN_ID_BYTES)*POOL_DRAWS,_pool=Buffer.alloc(0),_poolOffset=Number.POSITIVE_INFINITY});function degradedProjection(marker,data){return{sourceStore:".swarm/telemetry.jsonl",sourceSchemaVersion:null,timingConfidence:"writer-clock",unknown:[marker],extra:EMPTY_EXTRA,raw:data}}function knownKeySetFor(knownKeys){let cached2=_knownKeySetCache.get(knownKeys);if(cached2!==void 0)return cached2;let built=new Set(knownKeys);return _knownKeySetCache.set(knownKeys,built),built}function adaptLegacyTelemetryPayload(kind,data,knownKeys){if(data===null||typeof data!=="object")return degradedProjection("<non-object-payload>",data);try{let record2=data,known=knownKeySetFor(knownKeys),ownKeys=Object.keys(record2),extra;for(let key of ownKeys){if(known.has(key))continue;if(extra??={},key==="__proto__"){Object.defineProperty(extra,key,{value:record2[key],enumerable:!0,writable:!0,configurable:!0});continue}extra[key]=record2[key]}let unknownFields;for(let key of knownKeys)if(record2[key]===void 0)unknownFields??=[],unknownFields.push(key);return{sourceStore:".swarm/telemetry.jsonl",sourceSchemaVersion:null,timingConfidence:"writer-clock",unknown:unknownFields??EMPTY_UNKNOWN,extra:extra??EMPTY_EXTRA,raw:data}}catch{return degradedProjection("<payload-introspection-failed>",data)}}function nonEmptyString(value){return typeof value==="string"&&value.length>0?value:void 0}function extractWorkflowIds(data){let ids={};try{if(data===null||typeof data!=="object")return ids;let record2=data,hostSessionId=nonEmptyString(record2.sessionId);if(hostSessionId!==void 0)ids.hostSessionId=hostSessionId;let taskId=nonEmptyString(record2.taskId);if(taskId!==void 0)ids.taskId=taskId;let callId=nonEmptyString(record2.callId);if(callId!==void 0)ids.callId=callId;let invocationId=nonEmptyString(record2.invocationId);if(invocationId!==void 0)ids.invocationId=invocationId;let laneId=nonEmptyString(record2.laneId);if(laneId!==void 0)ids.laneId=laneId;let batchId=nonEmptyString(record2.batchId);if(batchId!==void 0)ids.batchId=batchId;let councilRoundId=nonEmptyString(record2.councilRoundId);if(councilRoundId!==void 0)ids.councilRoundId=councilRoundId;let knowledgeTraceId=nonEmptyString(record2.knowledgeTraceId);if(knowledgeTraceId!==void 0)ids.knowledgeTraceId=knowledgeTraceId;let knowledgeEntryId=nonEmptyString(record2.knowledgeEntryId);if(knowledgeEntryId!==void 0)ids.knowledgeEntryId=knowledgeEntryId;let phase=record2.phase;if(typeof phase==="number"&&Number.isFinite(phase))ids.phaseId=String(phase);else{let phaseString=nonEmptyString(phase);if(phaseString!==void 0)ids.phaseId=phaseString}}catch{}return ids}function extractOutcome(data){let outcome={};try{if(data===null||typeof data!=="object")return outcome;let record2=data,result=nonEmptyString(record2.result);if(result!==void 0){let normalized=result.toLowerCase();outcome.status=Object.hasOwn(RESULT_STATUS_MAP,normalized)?RESULT_STATUS_MAP[normalized]:"unknown"}let reason=nonEmptyString(record2.reason);if(reason!==void 0)outcome.reason=reason;let errorName=nonEmptyString(record2.errorName);if(errorName!==void 0)outcome.errorName=errorName;let errorMessage=nonEmptyString(record2.errorMessage);if(errorMessage!==void 0)outcome.errorMessage=errorMessage;let retryIndex=record2.retry_index;if(typeof retryIndex==="number"&&Number.isFinite(retryIndex))outcome.retryIndex=retryIndex}catch{}return outcome}var LEGACY_TELEMETRY_SOURCE_STORE=".swarm/telemetry.jsonl",LEGACY_ADAPTER_RULES,KNOWN_TELEMETRY_KEYS,EMPTY_EXTRA,EMPTY_UNKNOWN,_knownKeySetCache,RESULT_STATUS_MAP;var init_legacy=__esm(()=>{LEGACY_ADAPTER_RULES=Object.freeze(["Preserve unknown fields: an own key the contract does not recognize is kept under `extra` by reference and is never dropped.","Record the source store and its schema version: `sourceStore` names the file; `sourceSchemaVersion` is the version the store declares.","Preserve originally reported values: values are aliased, never coerced, normalized, rounded, or re-serialized.","Record timing confidence: a time read by the writer at record time is `writer-clock`, never `exact`.","Unknown is not zero: the adapter lists in `unknown` every catalogued key the PRODUCER left undefined, and never itself defaults one to 0, \"\", false, or null. The guarantee stops at the adapter boundary — a producer that pre-coerces its own defaults defeats it, because the adapter only ever sees the coerced value. The known instance was `delegation_end` (`src/telemetry.ts` `delegationEnd`): before issue #2789 it coerced token axes with `?? 0`, so they could never appear in `unknown`; it now emits held-null token axes (`?? null`), matching `cost_usd`, and `cost_source: 'unavailable'` still records absence of a cost basis.","Missing lineage stays missing: an absent correlation ID stays `undefined` and is never synthesized to make a join succeed.","Never drop unrecognized fields: no allowlist filter is applied to the payload on the way through."]),KNOWN_TELEMETRY_KEYS=Object.freeze({session_started:Object.freeze(["sessionId","agentName"]),session_ended:Object.freeze(["sessionId","reason"]),agent_activated:Object.freeze(["sessionId","agentName","oldName"]),delegation_begin:Object.freeze(["sessionId","agentName","taskId"]),delegation_end:Object.freeze(["sessionId","agentName","taskId","result","tokens_input","tokens_output","tokens_reasoning","tokens_cache","cost_usd","cost_source","model","gate","retry_index","cost_evidence","evidence_status","evidence_reason","currency","record_id","identity_fingerprint","parent_session_digest","child_session_digest","version"]),delegation_cost_correction:Object.freeze(["sessionId","agentName","taskId","parent_session_digest","record_id","identity_fingerprint","version","cost_evidence","evidence_status","evidence_reason","currency","cost_usd","cost_source","tokens_input","tokens_output","tokens_reasoning","tokens_cache","model","gate","retry_index"]),delegation_cost_binding:Object.freeze(["sessionId","record_id","identity_fingerprint","child_session_digest"]),delegation_cost_join:Object.freeze(["sessionId","reason"]),execution_attempt_recorded:Object.freeze(["sessionId","taskId","callId","invocationId","attemptClass","generation","retryIndex","laneId","knowledgeTraceId","outcomeStatus","captured","unknown","cost","duplicateOf"]),task_state_changed:Object.freeze(["sessionId","taskId","newState","oldState"]),gate_passed:Object.freeze(["sessionId","gate","taskId"]),gate_parse_error:Object.freeze(["taskId","errorName","errorMessage"]),gate_failed:Object.freeze(["sessionId","gate","taskId","reason"]),reviewer_gate_decision:Object.freeze(["sessionId","gate","taskId","blocked","allowed","reasonCode","evidenceKind"]),phase_changed:Object.freeze(["sessionId","oldPhase","newPhase"]),budget_updated:Object.freeze(["sessionId","budgetPct","agentName"]),context_pruned:Object.freeze(["sessionId","agentName","trigger","usageSource","beforeTokens","afterTokens","modelLimit","maskedMessages","maskedToolParts","maskedTokensFreed","prunedMessages","prunedTextParts","prunedToolParts","prunedTokensFreed"]),model_fallback:Object.freeze(["sessionId","agentName","fromModel","toModel","reason"]),model_unresolved:Object.freeze(["sessionId","agentName","model","detail"]),hard_limit_hit:Object.freeze(["sessionId","agentName","limitType","value"]),revision_limit_hit:Object.freeze(["sessionId","agentName"]),loop_detected:Object.freeze(["sessionId","agentName","loopType"]),scope_violation:Object.freeze(["sessionId","agentName","file","reason"]),qa_skip_violation:Object.freeze(["sessionId","agentName","skipCount"]),heartbeat:Object.freeze(["sessionId"]),turbo_mode_changed:Object.freeze(["sessionId","enabled","agentName"]),auto_oversight_escalation:Object.freeze(["sessionId","reason","interactionCount","deadlockCount","phase"]),environment_detected:Object.freeze(["sessionId","hostOS","shellFamily","executionMode"]),prm_pattern_detected:Object.freeze(["sessionId","pattern","severity","category","stepRange"]),prm_course_correction_injected:Object.freeze(["sessionId","pattern","level"]),prm_escalation_triggered:Object.freeze(["sessionId","pattern","level","occurrenceCount"]),prm_hard_stop:Object.freeze(["sessionId","pattern","level","occurrenceCount"]),no_op_strong_warning:Object.freeze(["sessionId","agentName","count","threshold"]),gate_denial_loop:Object.freeze(["sessionId","tool","code","count"]),execution_stall_warning:Object.freeze(["sessionId","count","threshold"]),execution_stall_denied:Object.freeze(["sessionId","tool","count","threshold"]),swarm_internals_read_denied:Object.freeze(["sessionId","tool","target"]),prm_hard_stop_delivered:Object.freeze(["sessionId","pattern","level","occurrenceCount"]),evidence_lock_acquired:Object.freeze(["directory","evidencePath","agent","taskId","attempt"]),evidence_lock_contended:Object.freeze(["directory","evidencePath","agent","taskId","attempt"]),evidence_lock_stale_recovered:Object.freeze(["directory","evidencePath","agent","taskId","attempt"]),plan_ledger_cas_retry:Object.freeze(["attempt","expectedHashPrefix","delayMs"]),plan_md_write_failed:Object.freeze(["directory","error","timestamp"]),snapshot_failed:Object.freeze(["error","retries","source"]),agent_conflict_detected:Object.freeze(["type","timestamp","sessionId","phase","taskId","sourceAgent","targetAgent","conflictType","resolutionPath","summary"]),knowledge_receipt_transition:Object.freeze(["transition","reasonCode","schemaVersion","receiptSemantics","knowledgeTraceId","knowledgeEntryId","sessionId","taskId","phase","receiptOutcome","receiptSource"]),knowledge_maintenance:Object.freeze(["phase","abortReason","selectedCount","storeEntriesBefore","storeEntriesAfter","backupBytes","storeSha256Prefix","token12"]),residue_health:Object.freeze(["trigger","scanned","matched","eligible","ambiguous","quarantined","preserved","total_bytes","oldest_age_ms","grammar_counts"]),training_vault_health:Object.freeze(["project_ref","reason","count"]),context_telemetry_health:Object.freeze(["trigger","accepted_count","compacted_count","retained_count","dropped_count","corrupt_count","oldest_timestamp","newest_timestamp","bytes","limit_bytes"]),skill_usage_health:Object.freeze(["trigger","accepted","compacted","dropped","skills_dropped","corrupt","pending_retained","uncertain_retained","uncertain_expired","pending_evicted","no_source_knowledge","no_matching_knowledge","bump_retry","bump_unrecoverable","bump_applied_zero","pressure","curator_skipped","bytes","limit_bytes","oldest_timestamp","newest_timestamp","coverage"]),learning_health_alarm:Object.freeze(["alarm","transition","severity","scope_class","session_ref","model","provider","window_ms","coverage_facts","raise_facts","age_ms","limit_source","denominator_fallback","pressure_pct","band","share_pct","field_count","non_field_count","store","dropped","corrupt","retained","accepted","gap_type","role","phase","reason"]),core_events_health:Object.freeze(["trigger","accepted_count","compacted_count","retained_count","dropped_count","corrupt_count","authority_index_count","authority_evicted_count","oldest_timestamp","newest_timestamp","bytes","limit_bytes"]),council_attempt:Object.freeze(["sessionId","councilRoundId","level","stage","attemptId","disposition","taskId","phase","identityDigest","authoritativeRound","clientRound","verdictCount","memberCount","quorumSize","verdict","transition","gateEffect"]),council_round_transition:Object.freeze(["sessionId","councilRoundId","level","attemptId","transition","gateEffect","taskId","phase","identityDigest","round","nextRound","roundStatus","maxRoundsExhausted","verdict","quorumSize"]),council_attempt_unscoped:Object.freeze(["sessionId","level","disposition","fingerprint","attemptId"])}),EMPTY_EXTRA=Object.freeze({});EMPTY_UNKNOWN=Object.freeze([]),_knownKeySetCache=new WeakMap;RESULT_STATUS_MAP=Object.freeze({success:"success",succeeded:"success",ok:"success",pass:"success",passed:"success",complete:"success",completed:"success",failure:"failure",failed:"failure",fail:"failure",error:"failure",partial:"partial"})});function validateEventRelationships(event){let violations=[];try{let entry=getCatalogEntry(event.kind),links=Array.isArray(event.trace?.links)?event.trace.links:[];if(entry===void 0)violations.push(`${RELATIONSHIP_VIOLATION_CODES.unknownKind}:${event.kind}`);else{let workflow=event.workflow??{};for(let id of entry.requiredWorkflowIds)if(workflow[id]===void 0)violations.push(`${RELATIONSHIP_VIOLATION_CODES.requiredWorkflowIdMissing}:${id}`);for(let id of entry.forbiddenWorkflowIds)if(workflow[id]!==void 0)violations.push(`${RELATIONSHIP_VIOLATION_CODES.forbiddenWorkflowIdPresent}:${id}`);let parentSpanId=event.trace?.parentSpanId;if(!entry.requiresParent&&parentSpanId!==void 0)violations.push(RELATIONSHIP_VIOLATION_CODES.parentSpanNotAllowed);if(entry.requiresParent&&parentSpanId===void 0)violations.push(RELATIONSHIP_VIOLATION_CODES.parentSpanMissing);if(parentSpanId!==void 0&&!SPAN_ID_PATTERN.test(String(parentSpanId)))violations.push(RELATIONSHIP_VIOLATION_CODES.malformedParentSpanId);if(!entry.allowsLinks&&links.length>0)violations.push(RELATIONSHIP_VIOLATION_CODES.linksNotAllowed)}for(let index=0;index<links.length;index++){let link=links[index];if(link===void 0||link===null)continue;if(!TRACE_ID_PATTERN.test(String(link.traceId)))violations.push(`${RELATIONSHIP_VIOLATION_CODES.malformedLinkTraceId}:${index}`);if(!SPAN_ID_PATTERN.test(String(link.spanId)))violations.push(`${RELATIONSHIP_VIOLATION_CODES.malformedLinkSpanId}:${index}`)}}catch{return{ok:!1,violations:[RELATIONSHIP_VIOLATION_CODES.validationFailed]}}return violations.length===0?{ok:!0}:{ok:!1,violations}}var TRACE_ID_PATTERN,SPAN_ID_PATTERN,RELATIONSHIP_VIOLATION_CODES;var init_relationships=__esm(()=>{init_catalog();TRACE_ID_PATTERN=/^[0-9a-f]{32}$/,SPAN_ID_PATTERN=/^[0-9a-f]{16}$/,RELATIONSHIP_VIOLATION_CODES=Object.freeze({unknownKind:"unknown_kind",requiredWorkflowIdMissing:"required_workflow_id_missing",forbiddenWorkflowIdPresent:"forbidden_workflow_id_present",parentSpanNotAllowed:"parent_span_not_allowed",parentSpanMissing:"parent_span_missing",malformedParentSpanId:"malformed_parent_span_id",linksNotAllowed:"links_not_allowed",malformedLinkTraceId:"malformed_link_trace_id",malformedLinkSpanId:"malformed_link_span_id",validationFailed:"relationship_validation_failed"})});function shouldSample(traceId,rate){if(typeof rate!=="number"||!Number.isFinite(rate))return!0;if(rate>=1)return!0;if(rate<=0)return!1;if(typeof traceId!=="string"||traceId.length<8)return!0;let suffix=traceId.slice(-8).toLowerCase();if(!SAMPLE_SUFFIX_PATTERN.test(suffix))return!0;let value=Number.parseInt(suffix,16);if(!Number.isFinite(value))return!0;return value/4294967295<rate}var DEFAULT_SAMPLE_RATE=1,SAMPLE_SUFFIX_PATTERN,METRIC_LABEL_ALLOWLIST,ALLOWED_LABELS,CARDINALITY_VIOLATION_CODES;var init_sampling=__esm(()=>{SAMPLE_SUFFIX_PATTERN=/^[0-9a-f]{8}$/;METRIC_LABEL_ALLOWLIST=Object.freeze(["kind","category","severity","outcome_status","cost_source","privacy_class","runtime","os","provider","sampled"]),ALLOWED_LABELS=new Set(METRIC_LABEL_ALLOWLIST),CARDINALITY_VIOLATION_CODES=Object.freeze({notAllowlisted:"label_not_allowlisted",highCardinalityShape:"high_cardinality_label_shape"})});function initObservability(input){try{let salt=resolveLineageSalt(),lineage={},directory=typeof input.directory==="string"&&input.directory.length>0?input.directory:void 0;if(directory!==void 0)lineage.projectRef=pseudonymousRef(directory,salt);if(typeof input.cohortLabel==="string"&&input.cohortLabel.length>0)lineage.cohortRef=pseudonymousRef(`${directory??""}\x00cohort\x00${input.cohortLabel}`,salt);if(typeof input.worktreeId==="string"&&input.worktreeId.length>0)lineage.worktreeRef=pseudonymousRef(`${directory??""}\x00worktree\x00${input.worktreeId}`,salt);if(_lineage=Object.freeze(lineage),_provenance=Object.freeze(input.provenance?{...input.provenance}:{}),typeof input.sampleRate==="number"&&Number.isFinite(input.sampleRate))_sampleRate=input.sampleRate}catch{}}function nextWriterSequence(){if(_writerSequence>=Number.MAX_SAFE_INTEGER)_writerSequence=0;return _writerSequence+=1,_writerSequence}function safeNowIso(){try{return new Date().toISOString()}catch{return FALLBACK_TIMESTAMP}}function buildFallbackObservation(kind,data,writerSequence){let now=safeNowIso();return{schemaVersion:OBSERVABILITY_SCHEMA_VERSION,eventId:FALLBACK_EVENT_ID,kind,category:"unrecognized",severity:"error",occurredAt:now,observedAt:now,writerSequence,trace:{traceId:FALLBACK_TRACE_ID,spanId:FALLBACK_SPAN_ID,links:[]},workflow:{},lineage:{},provenance:{},outcome:{},policy:{sampled:shouldSample(FALLBACK_TRACE_ID,_sampleRate),sampleRate:_sampleRate,privacyClass:"operational"},legacy:{sourceStore:LEGACY_TELEMETRY_SOURCE_STORE,sourceSchemaVersion:null,timingConfidence:"unknown",unknown:[],extra:{},raw:data},relationshipViolations:[OBSERVATION_BUILD_FAILED]}}function createObservation(kind,data){let writerSequence=nextWriterSequence();try{let entry=getCatalogEntry(kind),{traceId,spanId}=newTraceAndSpanId(),observedAt=new Date().toISOString(),knownKeys=Object.hasOwn(KNOWN_TELEMETRY_KEYS,kind)?KNOWN_TELEMETRY_KEYS[kind]:EMPTY_KNOWN_KEYS,event={schemaVersion:OBSERVABILITY_SCHEMA_VERSION,eventId:newEventId(),kind,category:entry?.category??"unrecognized",severity:entry?.severity??"warning",occurredAt:observedAt,observedAt,writerSequence,trace:{traceId,spanId,links:[]},workflow:extractWorkflowIds(data),lineage:_lineage,provenance:_provenance,outcome:extractOutcome(data),policy:{sampled:shouldSample(traceId,_sampleRate),sampleRate:_sampleRate,privacyClass:entry?.privacyClass??"operational"},legacy:adaptLegacyTelemetryPayload(kind,data,knownKeys),relationshipViolations:[]},validation=validateEventRelationships(event);if(!validation.ok)event.relationshipViolations=validation.violations;return event}catch{return buildFallbackObservation(kind,data,writerSequence)}}function toLegacyTelemetryLine(event){return{timestamp:event.observedAt,event:event.kind,...event.legacy.raw}}function canonicalLineContent(event){return JSON.stringify(toLegacyTelemetryLine(event))}var _provenance,_lineage,_writerSequence=0,_sampleRate,EMPTY_KNOWN_KEYS,FALLBACK_EVENT_ID="00000000-0000-4000-8000-000000000000",FALLBACK_TRACE_ID="00000000000000000000000000000001",FALLBACK_SPAN_ID="0000000000000001",FALLBACK_TIMESTAMP="1970-01-01T00:00:00.000Z",OBSERVATION_BUILD_FAILED="observation_build_failed";var init_observe=__esm(()=>{init_catalog();init_envelope();init_ids();init_legacy();init_relationships();init_sampling();_provenance=Object.freeze({}),_lineage=Object.freeze({}),_sampleRate=DEFAULT_SAMPLE_RATE,EMPTY_KNOWN_KEYS=Object.freeze([])});var OTEL_GENAI_MAPPING_VERSION="1.29.0",OPENINFERENCE_MAPPING_VERSION="0.1.14",OTEL_GENAI_ATTRIBUTES,OPENINFERENCE_ATTRIBUTES,NO_ATTRIBUTES;var init_otel_mapping=__esm(()=>{OTEL_GENAI_ATTRIBUTES=Object.freeze({kind:"gen_ai.operation.name","provenance.provider":"gen_ai.system","provenance.model":"gen_ai.request.model","legacy.raw.model":"gen_ai.response.model","legacy.raw.agentName":"gen_ai.agent.name","workflow.hostSessionId":"gen_ai.conversation.id","outcome.status":"gen_ai.response.finish_reasons","legacy.raw.tokens_input":"gen_ai.usage.input_tokens","legacy.raw.tokens_output":"gen_ai.usage.output_tokens","legacy.raw.tokens_cache":"gen_ai.usage.cache_read_input_tokens","legacy.raw.tokens_reasoning":"swarm.gen_ai.usage.reasoning_tokens","legacy.raw.cost_usd":"swarm.gen_ai.usage.cost_usd"}),OPENINFERENCE_ATTRIBUTES=Object.freeze({kind:"openinference.span.kind","provenance.model":"llm.model_name","provenance.provider":"llm.provider","legacy.raw.agentName":"agent.name","workflow.hostSessionId":"session.id","legacy.raw.tokens_input":"llm.token_count.prompt","legacy.raw.tokens_output":"llm.token_count.completion","legacy.raw.tokens_cache":"llm.token_count.prompt_details.cache_read","legacy.raw.tokens_reasoning":"llm.token_count.completion_details.reasoning","legacy.raw.cost_usd":"swarm.llm.cost_usd"}),NO_ATTRIBUTES=Object.freeze({})});var init_observability=__esm(()=>{init_catalog();init_envelope();init_ids();init_legacy();init_observe();init_otel_mapping();init_relationships();init_sampling()});var exports_telemetry={};__export(exports_telemetry,{telemetry:()=>telemetry,stopHeartbeatTracking:()=>stopHeartbeatTracking,startHeartbeatTracking:()=>startHeartbeatTracking,rotateTelemetryIfNeeded:()=>rotateTelemetryIfNeeded,resetTelemetryForTesting:()=>resetTelemetryForTesting,resetHeartbeatTrackingForTesting:()=>resetHeartbeatTrackingForTesting,removeTelemetryListener:()=>removeTelemetryListener,initTelemetry:()=>initTelemetry,getLastHeartbeat:()=>getLastHeartbeat,flushAndDrainTelemetry:()=>flushAndDrainTelemetry,emit:()=>emit,addTelemetryListener:()=>addTelemetryListener,_internals:()=>_internals16,ROTATION_CHECK_INTERVAL:()=>ROTATION_CHECK_INTERVAL});import*as fs7 from"node:fs";import{createWriteStream}from"node:fs";import*as os3 from"node:os";import*as path13 from"node:path";function capHeartbeatMap(){while(heartbeatTimestamps.size>=500){let oldestKey=heartbeatTimestamps.keys().next().value;if(oldestKey===void 0)break;heartbeatTimestamps.delete(oldestKey)}}function startHeartbeatTracking(){if(_heartbeatTrackingActive)return;_heartbeatTrackingActive=!0;let listener=(event,data)=>{if(event!=="heartbeat")return;let payload=data;if(!payload?.sessionId)return;heartbeatTimestamps.set(payload.sessionId,Date.now()),capHeartbeatMap()};_heartbeatListener=listener,addTelemetryListener(listener)}function getLastHeartbeat(sessionId){return heartbeatTimestamps.get(sessionId)}function stopHeartbeatTracking(){if(_heartbeatTrackingActive=!1,_heartbeatListener!==null){let idx=_listeners.indexOf(_heartbeatListener);if(idx>=0)_listeners.splice(idx,1);_heartbeatListener=null}}function resetHeartbeatTrackingForTesting(){if(_heartbeatTrackingActive=!1,heartbeatTimestamps.clear(),_heartbeatListener!==null){let idx=_listeners.indexOf(_heartbeatListener);if(idx>=0)_listeners.splice(idx,1);_heartbeatListener=null}}function resetTelemetryForTesting(){if(_disabled=!1,_projectDirectory=null,_listeners.length=0,_emitCount=0,resetHeartbeatTrackingForTesting(),_writeStream!==null)_writeStream.end(),_writeStream=null}function initTelemetry(projectDirectory){if(_disabled)return;if(_writeStream!==null&&_projectDirectory!==null&&sameProjectRoot(_projectDirectory,projectDirectory))return;let oldStream=_writeStream;try{let swarmDir=path13.join(projectDirectory,".swarm");if(!fs7.existsSync(swarmDir))fs7.mkdirSync(swarmDir,{recursive:!0});let telemetryPath=path13.join(swarmDir,"telemetry.jsonl"),stream=createWriteStream(telemetryPath,{flags:"a"});stream.on("error",()=>{if(_writeStream===stream)_disabled=!0,_writeStream=null}),_writeStream=stream,_projectDirectory=projectDirectory}catch(error49){log(`[telemetry] failed to open the new project's telemetry stream (retaining the previous stream, non-fatal): ${error49 instanceof Error?error49.message:String(error49)}`);return}if(oldStream!==null)try{oldStream.end()}catch(error49){log(`[telemetry] failed to close the previous project's stream during re-home (non-fatal): ${error49 instanceof Error?error49.message:String(error49)}`)}}function emit(event,data){try{if(_disabled||_writeStream===null)return;let canonical=_internals16.createObservation(event,data),content=_internals16.canonicalLineContent(canonical),line=content+os3.EOL,stream=_writeStream;stream.write(line,(err)=>{if(err&&_writeStream===stream)_disabled=!0,_writeStream=null});for(let listener of _listeners)try{listener(event,data,canonical,content)}catch{}if(_emitCount++,_emitCount>=ROTATION_CHECK_INTERVAL)_emitCount=0,_internals16.rotateTelemetryIfNeeded()}catch{}}function addTelemetryListener(callback){_listeners.push(callback)}function removeTelemetryListener(callback){let idx=_listeners.indexOf(callback);if(idx>=0)_listeners.splice(idx,1)}function rotateTelemetryIfNeeded(maxBytes=10485760){try{if(_projectDirectory===null)return;let telemetryPath=path13.join(_projectDirectory,".swarm","telemetry.jsonl");if(!fs7.existsSync(telemetryPath))return;if(fs7.statSync(telemetryPath).size<maxBytes)return;let rotatedPath=path13.join(_projectDirectory,".swarm","telemetry.jsonl.1");if(fs7.renameSync(telemetryPath,rotatedPath),_writeStream!==null){_writeStream.end();let stream=createWriteStream(telemetryPath,{flags:"a"});stream.on("error",()=>{if(_writeStream===stream)_disabled=!0,_writeStream=null}),_writeStream=stream}}catch{}}async function flushAndDrainTelemetry(){let stream=_writeStream;if(stream===null||_projectDirectory===null)return;let next;try{let telemetryPath=path13.join(_projectDirectory,".swarm","telemetry.jsonl");next=createWriteStream(telemetryPath,{flags:"a"}),next.on("error",()=>{if(_writeStream===next)_disabled=!0,_writeStream=null}),_writeStream=next}catch{_disabled=!0,_writeStream=null;return}await new Promise((resolve9)=>{stream.end(()=>resolve9())})}var _writeStream=null,_projectDirectory=null,_listeners,_disabled=!1,_heartbeatTrackingActive=!1,_heartbeatListener=null,heartbeatTimestamps,_emitCount=0,ROTATION_CHECK_INTERVAL=50,telemetry,_internals16;var init_telemetry=__esm(()=>{init_observability();init_utils();init_canonical_root();_listeners=[],heartbeatTimestamps=new Map;telemetry={sessionStarted(sessionId,agentName){_internals16.emit("session_started",{sessionId,agentName})},sessionEnded(sessionId,reason){_internals16.emit("session_ended",{sessionId,reason})},agentActivated(sessionId,agentName,oldName){_internals16.emit("agent_activated",{sessionId,agentName,oldName})},delegationBegin(sessionId,agentName,taskId){_internals16.emit("delegation_begin",{sessionId,agentName,taskId})},delegationEnd(sessionId,agentName,taskId,result,costFields){_internals16.emit("delegation_end",{sessionId,agentName,taskId,result,tokens_input:costFields?.tokens_input??null,tokens_output:costFields?.tokens_output??null,tokens_reasoning:costFields?.tokens_reasoning??null,tokens_cache:costFields?.tokens_cache??null,cost_usd:costFields?.cost_usd??null,...costFields,cost_source:costFields?.cost_source??"unavailable",model:costFields?.model,gate:costFields?.gate,retry_index:costFields?.retry_index})},delegationReadUncertain(event){_internals16.emit("delegation_read_uncertain",{attempt:event.attempt,reasonCode:event.reasonCode.slice(0,64),source:event.source})},taskStateChanged(sessionId,taskId,newState,oldState){_internals16.emit("task_state_changed",{sessionId,taskId,newState,oldState})},gatePassed(sessionId,gate,taskId){_internals16.emit("gate_passed",{sessionId,gate,taskId})},gateParseError(taskId,error49){_internals16.emit("gate_parse_error",{taskId,errorName:error49.name,errorMessage:error49.message.slice(0,200)})},gateFailed(sessionId,gate,taskId,reason){_internals16.emit("gate_failed",{sessionId,gate,taskId,reason})},reviewerGateDecision(sessionId,taskId,blocked,reasonCode,evidenceKind){_internals16.emit("reviewer_gate_decision",{sessionId,gate:"qa_gate",taskId,blocked,allowed:!blocked,reasonCode,evidenceKind})},phaseChanged(sessionId,oldPhase,newPhase){_internals16.emit("phase_changed",{sessionId,oldPhase,newPhase})},budgetUpdated(sessionId,budgetPct,agentName){_internals16.emit("budget_updated",{sessionId,budgetPct,agentName})},contextPruned(data){_internals16.emit("context_pruned",data)},modelFallback(sessionId,agentName,fromModel,toModel,reason){_internals16.emit("model_fallback",{sessionId,agentName,fromModel,toModel,reason})},modelUnresolved(agentName,model,detail){_internals16.emit("model_unresolved",{sessionId:"preflight",agentName,model,detail})},hardLimitHit(sessionId,agentName,limitType,value){_internals16.emit("hard_limit_hit",{sessionId,agentName,limitType,value})},revisionLimitHit(sessionId,agentName){_internals16.emit("revision_limit_hit",{sessionId,agentName})},loopDetected(sessionId,agentName,loopType){_internals16.emit("loop_detected",{sessionId,agentName,loopType})},noOpStrongWarning(sessionId,agentName,count,threshold){_internals16.emit("no_op_strong_warning",{sessionId,agentName,count,threshold})},gateDenialLoop(sessionId,tool,code,count){_internals16.emit("gate_denial_loop",{sessionId,tool,code,count})},executionStallWarning(sessionId,count,threshold){_internals16.emit("execution_stall_warning",{sessionId,count,threshold})},executionStallDenied(sessionId,tool,count,threshold){_internals16.emit("execution_stall_denied",{sessionId,tool,count,threshold})},swarmInternalsReadDenied(sessionId,tool,target){_internals16.emit("swarm_internals_read_denied",{sessionId,tool,target})},scopeViolation(sessionId,agentName,file2,reason){_internals16.emit("scope_violation",{sessionId,agentName,file:file2,reason})},qaSkipViolation(sessionId,agentName,skipCount){_internals16.emit("qa_skip_violation",{sessionId,agentName,skipCount})},heartbeat(sessionId){_internals16.emit("heartbeat",{sessionId})},turboModeChanged(sessionId,enabled,agentName){_internals16.emit("turbo_mode_changed",{sessionId,enabled,agentName})},autoOversightEscalation(sessionId,reason,interactionCount,deadlockCount,phase){_internals16.emit("auto_oversight_escalation",{sessionId,reason,interactionCount,deadlockCount,phase})},environmentDetected(sessionId,hostOS,shellFamily,executionMode){_internals16.emit("environment_detected",{sessionId,hostOS,shellFamily,executionMode})},prmPatternDetected(sessionId,pattern,severity,category,stepRange){_internals16.emit("prm_pattern_detected",{sessionId,pattern,severity,category,stepRange})},prmCourseCorrectionInjected(sessionId,pattern,level){_internals16.emit("prm_course_correction_injected",{sessionId,pattern,level})},prmEscalationTriggered(sessionId,pattern,level,occurrenceCount){_internals16.emit("prm_escalation_triggered",{sessionId,pattern,level,occurrenceCount})},prmHardStop(sessionId,pattern,level,occurrenceCount){_internals16.emit("prm_hard_stop",{sessionId,pattern,level,occurrenceCount})},prmHardStopTerminal(sessionId,pattern,level,occurrenceCount){_internals16.emit("prm_hard_stop_terminal",{sessionId,pattern,level,occurrenceCount})},closeArchiveResult(data){_internals16.emit("close_archive_result",data)},residueHealth(data){_internals16.emit("residue_health",data)},trainingVaultHealth(data){_internals16.emit("training_vault_health",data)},contextTelemetryHealth(data){_internals16.emit("context_telemetry_health",data)},skillUsageHealth(data){_internals16.emit("skill_usage_health",data)},coreEventsHealth(data){_internals16.emit("core_events_health",data)},shellAuditHealth(data){_internals16.emit("shell_audit_health",data)},trajectoryHealth(data){_internals16.emit("trajectory_health",data)},prSubscriptionHealth(data){_internals16.emit("pr_subscription_health",data)},learningHealthAlarm(data){_internals16.emit("learning_health_alarm",data)},prmHardStopDelivered(sessionId,pattern,level,occurrenceCount){_internals16.emit("prm_hard_stop_delivered",{sessionId,pattern,level,occurrenceCount})},retrievalRouted(sessionId,data){_internals16.emit("retrieval_routed",{sessionId,...data})}},_internals16={telemetry,emit,rotateTelemetryIfNeeded,flushAndDrainTelemetry,heartbeatListenerCount:()=>_heartbeatListener!==null?1:0,createObservation,toLegacyTelemetryLine,canonicalLineContent}});import*as fs8 from"node:fs";import*as os4 from"node:os";import*as path14 from"node:path";function isAbsoluteDirectoryInput(value){return typeof value==="string"&&value.trim().length>0&&path14.isAbsolute(value)}function hasExplicitProjectBoundary(directory){if(!isAbsoluteDirectoryInput(directory))return!1;for(let marker of PROJECT_BOUNDARY_MARKERS)try{let stat5=_internals17.lstatSync(path14.join(directory,marker.name));if(!stat5.isSymbolicLink()&&marker.accepts(stat5))return!0}catch{}return!1}function isStrictPathDescendant(candidate,root){if(!isAbsoluteDirectoryInput(candidate)||!isAbsoluteDirectoryInput(root))return!1;let relative4=path14.relative(root,candidate);return relative4!==""&&relative4!==".."&&!relative4.startsWith(`..${path14.sep}`)&&!path14.isAbsolute(relative4)}function walkProjectBoundary(resolved,dependencies){if(hasExplicitProjectBoundary(resolved))return{outcome:"marker-root"};let current=resolved,depth=0;while(!0){if(depth>=MAX_PROJECT_ROOT_DEPTH)return{outcome:"fail-closed",reason:"depth"};depth++;let parent=path14.dirname(current);if(parent===current)return{outcome:"unclaimed"};if(path14.dirname(parent)===parent){current=parent;continue}let parentSwarm=path14.join(parent,".swarm"),parentSwarmStat;try{parentSwarmStat=dependencies.statSync(parentSwarm)}catch(error49){if(isMissingPathError(error49)){current=parent;continue}return{outcome:"fail-closed",reason:"ancestor-swarm",path:parentSwarm}}if(parentSwarmStat.isDirectory()){let indicatorState=projectIndicatorState(parent,dependencies,{allowConfigOnly:!isWeakConfigContainerRoot(parent,dependencies)});if(indicatorState==="inaccessible")return{outcome:"fail-closed",reason:"ancestor-indicators",path:parent};if(indicatorState==="present")return{outcome:"claimed",ancestor:parent}}current=parent}}function isMissingPathError(error49){let code=error49?.code;return code==="ENOENT"||code==="ENOTDIR"}function isWeakConfigContainerRoot(directory,dependencies){try{let resolved=dependencies.realpathSync(directory);return resolved===dependencies.realpathSync(os4.tmpdir())||resolved===dependencies.realpathSync(os4.homedir())}catch{let resolved=path14.resolve(directory);return resolved===path14.resolve(os4.tmpdir())||resolved===path14.resolve(os4.homedir())}}function projectIndicatorState(directory,dependencies,options={}){let allowConfigOnly=options.allowConfigOnly??!0;for(let indicator of PROJECT_ROOT_INDICATORS){if(!allowConfigOnly&&indicator===".opencode")continue;try{let indicatorStat=dependencies.statSync(path14.join(directory,indicator));if(indicatorStat.isFile()||indicatorStat.isDirectory())return"present"}catch(error49){if(!isMissingPathError(error49))return"inaccessible"}}return"absent"}function assertProjectRoot(directory,dependencies=fs8,artifactLabel="runtime state"){let resolved;try{resolved=dependencies.realpathSync(directory)}catch{throw warn(`[project-boundary] Cannot canonicalize directory "${directory}" — failing closed`),Error(`Cannot verify project root for "${directory}" — directory may not exist or is inaccessible`)}let walk=walkProjectBoundary(resolved,dependencies);if(walk.outcome==="marker-root"||walk.outcome==="unclaimed")return;if(walk.outcome==="claimed")throw warn(`[project-boundary] Rejecting write to subdirectory "${resolved}" — parent "${walk.ancestor}" already contains .swarm/`),Error(`Cannot write ${artifactLabel} in "${resolved}" — parent directory "${walk.ancestor}" already contains a .swarm/ folder. Runtime state must be written to the project root.`);if(walk.reason==="depth")throw warn(`[project-boundary] Ancestor search exceeded ${MAX_PROJECT_ROOT_DEPTH} levels for "${resolved}" — failing closed`),Error(`Cannot verify project root for "${resolved}" — ancestor search exceeded ${MAX_PROJECT_ROOT_DEPTH} levels`);if(walk.reason==="ancestor-swarm")throw warn(`[project-boundary] Cannot inspect ancestor state "${walk.path}" — failing closed`),Error(`Cannot verify project root for "${resolved}" — ancestor state "${walk.path}" is inaccessible`);throw warn(`[project-boundary] Cannot inspect project indicators in ancestor "${walk.path}" — failing closed`),Error(`Cannot verify project root for "${resolved}" — project indicators in ancestor "${walk.path}" are inaccessible`)}function resolveProjectRootDecision(directory,dependencies=fs8){let resolved;try{resolved=dependencies.realpathSync(directory)}catch{return{kind:"fail-closed",directory,reason:`cannot canonicalize directory "${directory}" — it may not exist or is inaccessible`}}let walk=walkProjectBoundary(resolved,dependencies);if(walk.outcome==="marker-root"||walk.outcome==="unclaimed")return{kind:"root",directory:resolved};if(walk.outcome==="claimed")return{kind:"redirect",directory:resolved,owningRoot:walk.ancestor};let reason=walk.reason==="depth"?`ancestor search exceeded ${MAX_PROJECT_ROOT_DEPTH} levels`:walk.reason==="ancestor-swarm"?`ancestor state "${walk.path}" is inaccessible`:`project indicators in ancestor "${walk.path}" are inaccessible`;return{kind:"fail-closed",directory:resolved,reason}}var MAX_PROJECT_ROOT_DEPTH=20,PROJECT_ROOT_INDICATORS,PROJECT_BOUNDARY_MARKERS,_internals17;var init_project_boundary=__esm(()=>{init_logger();PROJECT_ROOT_INDICATORS=["package.json",".git",".opencode","Cargo.toml","go.mod","pyproject.toml","Gemfile","composer.json","pom.xml","build.gradle","CMakeLists.txt"],PROJECT_BOUNDARY_MARKERS=[{name:".git",accepts:(stat5)=>stat5.isFile()||stat5.isDirectory()},{name:".opencode",accepts:(stat5)=>stat5.isDirectory()}];_internals17={lstatSync:fs8.lstatSync}});function backoffMs(attempt){let base=Math.min(BACKOFF_START_MS*2**attempt,BACKOFF_MAX_MS),jitter=base*BACKOFF_JITTER_RATIO*(Math.random()*2-1);return Math.max(1,Math.round(base+jitter))}async function withEvidenceLock(directory,evidencePath,agent,taskId,fn2,timeoutMs=60000){assertProjectRoot(directory);let deadline=Date.now()+timeoutMs,attempt=0;while(!0){let result=await tryAcquireLock(directory,evidencePath,agent,taskId);if(result.acquired){let lock=result.lock;if(attempt>0)emit("evidence_lock_stale_recovered",{directory,evidencePath,agent,taskId,attempt});emit("evidence_lock_acquired",{directory,evidencePath,agent,taskId,attempt});try{return await fn2()}finally{if(lock._release)try{await lock._release()}catch{}}}if(Date.now()>=deadline)throw new EvidenceLockTimeoutError(directory,evidencePath,agent,taskId,timeoutMs);emit("evidence_lock_contended",{directory,evidencePath,agent,taskId,attempt});let delay=Math.min(backoffMs(attempt),deadline-Date.now());if(delay>0)await new Promise((resolve10)=>setTimeout(resolve10,delay));attempt++}}var EvidenceLockTimeoutError,BACKOFF_START_MS=50,BACKOFF_MAX_MS=2000,BACKOFF_JITTER_RATIO=0.25;var init_lock=__esm(()=>{init_file_locks();init_telemetry();init_project_boundary();EvidenceLockTimeoutError=class EvidenceLockTimeoutError extends Error{directory;evidencePath;agent;taskId;constructor(directory,evidencePath,agent,taskId,timeoutMs){super(`Evidence lock timeout after ${timeoutMs}ms for ${evidencePath} (agent=${agent}, task=${taskId})`);this.name="EvidenceLockTimeoutError",this.directory=directory,this.evidencePath=evidencePath,this.agent=agent,this.taskId=taskId}}});import*as path15 from"node:path";function taskEvidenceRelPath(taskId){return path15.join("evidence",`${taskId}.json`)}function taskEvidencePath(directory,taskId){return path15.join(directory,".swarm",taskEvidenceRelPath(taskId))}async function atomicWriteFile(targetPath,content){await atomicWriteFileAnyRoot(targetPath,content)}function withTaskEvidenceLock(directory,taskId,agent,fn2){return withEvidenceLock(directory,taskEvidenceRelPath(taskId),agent,taskId,fn2)}var init_task_file=__esm(()=>{init_atomic_write();init_lock()});import*as os5 from"node:os";import*as path16 from"node:path";function resolveHiveDataDir(){let platform=process.platform,home=process.env.HOME||os5.homedir();if(platform==="win32")return path16.join(process.env.LOCALAPPDATA||path16.join(home,"AppData","Local"),"opencode-swarm","Data");if(platform==="darwin")return path16.join(home,"Library","Application Support","opencode-swarm");return path16.join(process.env.XDG_DATA_HOME||path16.join(home,".local","share"),"opencode-swarm")}function resolveHiveKnowledgePath(){return path16.join(resolveHiveDataDir(),"shared-learnings.jsonl")}function resolveHiveRejectedPath(){return path16.join(resolveHiveDataDir(),"shared-learnings-rejected.jsonl")}function resolveHiveEventsPath(){return path16.join(resolveHiveDataDir(),"shared-knowledge-events.jsonl")}var init_hive_paths=()=>{};function resolveRetentionCap(name,defaultValue){let override=overrides.get(name);if(override!==void 0&&Number.isFinite(override)&&override>=1)return override;return defaultValue}var overrides;var init_caps=__esm(()=>{overrides=new Map});import*as fs9 from"node:fs";import*as path17 from"node:path";function withFileLock(filePath,task){let key=path17.resolve(filePath),run=(appendChains.get(key)??Promise.resolve()).then(task,task),settled=run.then(()=>{if((appendChains.get(key)??settled)===settled)appendChains.delete(key)},()=>{if((appendChains.get(key)??settled)===settled)appendChains.delete(key)});return appendChains.set(key,settled),run}function sleep2(ms){return new Promise((resolve11)=>setTimeout(resolve11,ms))}async function renameWithRetry2(from,to){let lastError;for(let attempt=1;attempt<=RENAME_MAX_ATTEMPTS;attempt++)try{await fs9.promises.rename(from,to);return}catch(error49){lastError=error49;let code=typeof error49==="object"&&error49!==null&&"code"in error49?String(error49.code):"";if(code!=="EBUSY"&&code!=="EPERM"&&code!=="EEXIST"&&code!=="ENOTEMPTY")throw error49;if(attempt<RENAME_MAX_ATTEMPTS)await sleep2(RENAME_RETRY_DELAY_MS)}throw lastError instanceof Error?lastError:Error(String(lastError))}function wholeLines(content){return content.split(`
|
|
474
|
+
(source, imported_at, source_digest, row_count) VALUES (?, ?, ?, ?)`,[input.source,new Date().toISOString(),input.sourceDigest,input.rowCount]),"imported"});if(result==="imported")_internals14.coordinationFaultInjector?.("after_commit_before_archive",getProjectDb(directory));return result}function deleteCoordinationImports(directory,sources){let boundedSources=sources.map((source)=>boundedText(source,"source",MAX_KEY_CHARS));if(boundedSources.length===0||!projectDbExists(directory))return 0;return withCoordinationTransaction(directory,()=>{let placeholders=boundedSources.map(()=>"?").join(", ");return getProjectDb(directory).run(`DELETE FROM coordination_import WHERE source IN (${placeholders})`,boundedSources).changes})}var MAX_KEY_CHARS=512,MAX_STATUS_CHARS=128,MAX_PAYLOAD_CHARS=1048576,MAX_EVENTS_PER_STREAM=2048,MAX_TOTAL_EVENTS=1e5,MAX_EVENT_FENCES_PER_STREAM=8192,MAX_TOTAL_EVENT_FENCES=400000,MAX_COORDINATION_STATE_LIST_ROWS=25000,COORDINATION_STATE_PAGE_SIZE=5000,_internals14;var init_coordination_store=__esm(()=>{init_durability();init_project_db();_internals14={maxEventsPerStream:MAX_EVENTS_PER_STREAM,maxTotalEvents:MAX_TOTAL_EVENTS,maxEventFencesPerStream:MAX_EVENT_FENCES_PER_STREAM,maxTotalEventFences:MAX_TOTAL_EVENT_FENCES}});import*as crypto2 from"node:crypto";import*as fs6 from"node:fs";import*as path12 from"node:path";function getLockFilePath(directory,filePath){let normalized=path12.resolve(directory,filePath),baseDir=path12.resolve(directory)+path12.sep;if(!(process.platform==="win32"?normalized.toLowerCase().startsWith(baseDir.toLowerCase()):normalized.startsWith(baseDir)))throw Error("Invalid file path: path traversal not allowed");let pathForHash=process.platform==="win32"?normalized.toLowerCase():normalized,hash2=crypto2.createHash("sha256").update(pathForHash).digest("hex"),lockPath=path12.join(directory,LOCKS_DIR,`${hash2}.lock`),legacyPaths=[pathForHash];if(process.platform==="win32"&&normalized!==pathForHash)legacyPaths.push(normalized);for(let legacyPath of legacyPaths){let oldHash=Buffer.from(legacyPath).toString("base64").replace(/[/+=]/g,"_"),oldLockPath=path12.join(directory,LOCKS_DIR,`${oldHash}.lock`);if(fs6.existsSync(oldLockPath))return oldLockPath}return lockPath}function getMetaPath(lockPath){return`${lockPath.replace(/\.lock$/,"")}.meta`}async function writeMetaFile(metaPath,metadata){let tmpPath=`${metaPath}.tmp`;try{await _internals15.writeFile(tmpPath,JSON.stringify(metadata),"utf-8"),await fs6.promises.rename(tmpPath,metaPath)}catch(err){try{await fs6.promises.unlink(tmpPath)}catch{}throw err}}function readMetaFile(metaPath){try{let content=fs6.readFileSync(metaPath,"utf-8");return JSON.parse(content)}catch{return null}}async function tryAcquireLock(directory,filePath,agent,taskId){let lockPath=getLockFilePath(directory,filePath),locksDir=path12.dirname(lockPath);if(!fs6.existsSync(locksDir))fs6.mkdirSync(locksDir,{recursive:!0});if(!fs6.existsSync(lockPath))fs6.writeFileSync(lockPath,"","utf-8");let release;try{release=await import_proper_lockfile2.default.lock(lockPath,{stale:LOCK_TIMEOUT_MS,retries:{retries:5,minTimeout:10,maxTimeout:500,factor:2},realpath:!1})}catch(err){let code=err.code;if(code==="ELOCKED"||code==="EEXIST")return{acquired:!1};throw err}return{acquired:!0,lock:{filePath,agent,taskId,timestamp:new Date().toISOString(),expiresAt:Date.now()+LOCK_TIMEOUT_MS,_release:release}}}function isLocked(directory,filePath){let plLockDir=`${getLockFilePath(directory,filePath)}.lock`;if(fs6.existsSync(plLockDir)){let acquiredAt=Date.now();try{acquiredAt=fs6.statSync(plLockDir).mtimeMs}catch{}return{filePath,agent:"unknown",taskId:"unknown",timestamp:new Date(acquiredAt).toISOString(),expiresAt:acquiredAt+LOCK_TIMEOUT_MS}}return null}function listActiveLocks(directory){let locksDir=path12.join(directory,LOCKS_DIR),locks=[];if(!fs6.existsSync(locksDir))return locks;let files=fs6.readdirSync(locksDir),now=Date.now();for(let file2 of files){if(!file2.endsWith(".lock"))continue;let lockPath=path12.join(locksDir,file2);try{if(fs6.statSync(lockPath).isFile()){let plLockDir=`${lockPath}.lock`;if(fs6.existsSync(plLockDir)){let metaPath=getMetaPath(lockPath),meta3=readMetaFile(metaPath);if(meta3){if(meta3.expiresAt<now)continue;locks.push({filePath:meta3.originalPath,agent:meta3.agent,taskId:meta3.taskId,timestamp:meta3.acquiredAt,expiresAt:meta3.expiresAt,laneId:meta3.laneId})}else{let acquiredAt=Date.now();try{acquiredAt=fs6.statSync(plLockDir).mtimeMs}catch{}let expiresAt=acquiredAt+LOCK_TIMEOUT_MS;if(expiresAt<now)continue;locks.push({filePath:lockPath,agent:"unknown",taskId:"unknown",timestamp:new Date(acquiredAt).toISOString(),expiresAt})}}}}catch{}}return locks}async function acquireLaneLocks(directory,laneId,files,agent,taskId,sessionID){let acquiredLocks=[],conflicts=[];for(let file2 of files){let result=await tryAcquireLock(directory,file2,agent,taskId);if(!result.acquired){for(let lock of acquiredLocks)try{if(lock._release)await lock._release();let lockPath2=getLockFilePath(directory,lock.filePath),metaPath2=getMetaPath(lockPath2);try{fs6.unlinkSync(metaPath2)}catch{}try{fs6.unlinkSync(lockPath2)}catch{}}catch{}return conflicts.push(file2),{acquired:!1,conflicts}}let lockPath=getLockFilePath(directory,file2),metaPath=getMetaPath(lockPath),meta3={originalPath:file2,laneId,taskId,agent,sessionID,acquiredAt:result.lock.timestamp,expiresAt:result.lock.expiresAt};try{await writeMetaFile(metaPath,meta3)}catch(err){for(let lock of acquiredLocks)try{if(lock._release)await lock._release();let lp=getLockFilePath(directory,lock.filePath),mp=getMetaPath(lp);try{fs6.unlinkSync(mp)}catch{}try{fs6.unlinkSync(lp)}catch{}}catch{}if(result.lock._release)await result.lock._release();try{fs6.unlinkSync(lockPath)}catch{}throw err}result.lock.laneId=laneId,acquiredLocks.push(result.lock)}return{acquired:!0,locks:acquiredLocks}}async function releaseLaneLocks(directory,laneId){let locksDir=path12.join(directory,LOCKS_DIR);if(!fs6.existsSync(locksDir))return 0;let files=fs6.readdirSync(locksDir),releasedCount=0;for(let file2 of files){if(!file2.endsWith(".meta"))continue;let metaPath=path12.join(locksDir,file2),meta3=readMetaFile(metaPath);if(!meta3||meta3.laneId!==laneId)continue;let lockPath=metaPath.replace(/\.meta$/,".lock");try{try{await import_proper_lockfile2.default.unlock(lockPath,{realpath:!1})}catch{}try{fs6.unlinkSync(lockPath)}catch{}try{fs6.unlinkSync(metaPath)}catch{}releasedCount++}catch{}}return releasedCount}var import_proper_lockfile2,LOCKS_DIR=".swarm/locks",LOCK_TIMEOUT_MS=300000,_internals15;var init_file_locks=__esm(()=>{import_proper_lockfile2=__toESM(require_proper_lockfile(),1),_internals15={tryAcquireLock,writeFile:fs6.promises.writeFile}});function defineEntry(kind,input){let entry={kind,category:input.category,severity:input.severity,privacyClass:input.privacyClass,producer:input.producer,consumers:input.consumers,retentionOwnerIssue:input.retentionOwnerIssue,requiredWorkflowIds:input.requiredWorkflowIds??NO_WORKFLOW_IDS,forbiddenWorkflowIds:input.forbiddenWorkflowIds??NO_WORKFLOW_IDS,requiresParent:input.requiresParent??!1,allowsLinks:input.allowsLinks??!0,otelMapping:input.otelMapping??"none",docAnchor:`#${kind}`,testFile:"tests/unit/observability/catalog-contract.test.ts"};if(input.futureOwnerIssue!==void 0)return Object.freeze({...entry,futureOwnerIssue:input.futureOwnerIssue});return Object.freeze(entry)}function getCatalogEntry(kind){return Object.hasOwn(EVENT_CATALOG,kind)?EVENT_CATALOG[kind]:void 0}var NO_WORKFLOW_IDS,NO_CONSUMERS,REQUIRE_SESSION,REQUIRE_SESSION_AND_TASK,REQUIRE_TASK,REQUIRE_COUNCIL_ROUND,FORBID_SESSION,FORBID_COUNCIL_ROUND,CONSUMER_COST_ACCOUNTING,CONSUMER_COST_CORRECTION,CONSUMER_COST_JOIN,CONSUMER_GATE_STATS,CONSUMER_HEARTBEAT_LISTENER,CATALOG_SOURCE,catalog,EVENT_CATALOG,CATALOG_KINDS;var init_catalog=__esm(()=>{NO_WORKFLOW_IDS=Object.freeze([]),NO_CONSUMERS=Object.freeze([]),REQUIRE_SESSION=Object.freeze(["hostSessionId"]),REQUIRE_SESSION_AND_TASK=Object.freeze(["hostSessionId","taskId"]),REQUIRE_TASK=Object.freeze(["taskId"]),REQUIRE_COUNCIL_ROUND=Object.freeze(["councilRoundId"]),FORBID_SESSION=Object.freeze(["hostSessionId"]),FORBID_COUNCIL_ROUND=Object.freeze(["councilRoundId"]),CONSUMER_COST_ACCOUNTING=Object.freeze(["src/services/cost-accounting.ts:405"]),CONSUMER_COST_CORRECTION=Object.freeze(["src/services/cost-accounting.ts:465"]),CONSUMER_COST_JOIN=Object.freeze(["src/services/cost-accounting.ts:452"]),CONSUMER_GATE_STATS=Object.freeze(["src/evaluation/gate-stats.ts:99"]),CONSUMER_HEARTBEAT_LISTENER=Object.freeze(["src/telemetry.ts:282"]);CATALOG_SOURCE=[["session_started",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:669",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"openinference"}],["session_ended",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:673",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"openinference"}],["agent_activated",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:677",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"openinference"}],["task_state_changed",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:737",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK,otelMapping:"openinference"}],["phase_changed",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:785",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"openinference"}],["heartbeat",{category:"lifecycle",severity:"debug",privacyClass:"pseudonymous",producer:"src/telemetry.ts:967",consumers:CONSUMER_HEARTBEAT_LISTENER,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,allowsLinks:!1}],["turbo_mode_changed",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:975",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION}],["environment_detected",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1000",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,allowsLinks:!1}],["delegation_begin",{category:"delegation",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:681",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK,otelMapping:"genai"}],["delegation_end",{category:"delegation",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:691",consumers:CONSUMER_COST_ACCOUNTING,retentionOwnerIssue:2043,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK,otelMapping:"genai"}],["delegation_read_uncertain",{category:"delegation",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:724",consumers:NO_CONSUMERS,futureOwnerIssue:2511,retentionOwnerIssue:2511,otelMapping:"none"}],["delegation_cost_correction",{category:"delegation",severity:"info",privacyClass:"pseudonymous",producer:"src/index.ts:959",consumers:CONSUMER_COST_CORRECTION,retentionOwnerIssue:2043,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK,otelMapping:"genai"}],["delegation_cost_binding",{category:"delegation",severity:"info",privacyClass:"pseudonymous",producer:"src/index.ts:2087",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2043,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"none"}],["delegation_cost_join",{category:"delegation",severity:"notice",privacyClass:"pseudonymous",producer:"src/index.ts:2107",consumers:CONSUMER_COST_JOIN,retentionOwnerIssue:2043,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"none"}],["model_fallback",{category:"delegation",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:818",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"genai"}],["model_unresolved",{category:"delegation",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:832",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"genai"}],["gate_passed",{category:"gate",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:746",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK}],["gate_failed",{category:"gate",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:763",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK}],["gate_parse_error",{category:"gate",severity:"warning",privacyClass:"sensitive",producer:"src/telemetry.ts:750",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_TASK,forbiddenWorkflowIds:FORBID_SESSION}],["reviewer_gate_decision",{category:"gate",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:773",consumers:CONSUMER_GATE_STATS,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK}],["council_attempt",{category:"gate",severity:"info",privacyClass:"pseudonymous",producer:"src/council/council-observability.ts:85",consumers:NO_CONSUMERS,futureOwnerIssue:2048,retentionOwnerIssue:2046,requiredWorkflowIds:REQUIRE_COUNCIL_ROUND}],["council_round_transition",{category:"gate",severity:"info",privacyClass:"pseudonymous",producer:"src/council/council-observability.ts:115",consumers:NO_CONSUMERS,futureOwnerIssue:2048,retentionOwnerIssue:2046,requiredWorkflowIds:REQUIRE_COUNCIL_ROUND}],["council_attempt_unscoped",{category:"gate",severity:"warning",privacyClass:"pseudonymous",producer:"src/council/council-observability.ts:152",consumers:NO_CONSUMERS,futureOwnerIssue:2048,retentionOwnerIssue:2046,forbiddenWorkflowIds:FORBID_COUNCIL_ROUND}],["context_source_attribution",{category:"cost",severity:"info",privacyClass:"pseudonymous",producer:"src/services/context-attribution.ts:124",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION}],["verdict_row_pipe_recovery",{category:"gate",severity:"info",privacyClass:"pseudonymous",producer:"src/pr-review/legacy-transcript-adapter.ts:689",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045}],["training_vault_health",{category:"guardrail",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1169",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:NO_WORKFLOW_IDS}],["budget_updated",{category:"cost",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:789",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2043,requiredWorkflowIds:REQUIRE_SESSION}],["context_pruned",{category:"guardrail",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:808",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["retrieval_routed",{category:"guardrail",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1402",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["hard_limit_hit",{category:"guardrail",severity:"error",privacyClass:"pseudonymous",producer:"src/telemetry.ts:846",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["revision_limit_hit",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:855",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["loop_detected",{category:"guardrail",severity:"warning",privacyClass:"sensitive",producer:"src/telemetry.ts:859",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["scope_violation",{category:"guardrail",severity:"error",privacyClass:"sensitive",producer:"src/telemetry.ts:955",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["qa_skip_violation",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:963",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["auto_oversight_escalation",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:985",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["no_op_strong_warning",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:873",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["gate_denial_loop",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:894",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["execution_stall_warning",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:908",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["execution_stall_denied",{category:"guardrail",severity:"error",privacyClass:"pseudonymous",producer:"src/telemetry.ts:925",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["swarm_internals_read_denied",{category:"guardrail",severity:"error",privacyClass:"sensitive",producer:"src/telemetry.ts:942",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_hard_stop_delivered",{category:"prm",severity:"error",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1383",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_pattern_detected",{category:"prm",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1015",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_course_correction_injected",{category:"prm",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1029",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_escalation_triggered",{category:"prm",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1042",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_hard_stop",{category:"prm",severity:"critical",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1056",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_hard_stop_terminal",{category:"prm",severity:"critical",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1081",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["evidence_lock_acquired",{category:"evidence",severity:"info",privacyClass:"sensitive",producer:"src/evidence/lock.ts:99",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,requiredWorkflowIds:REQUIRE_TASK,forbiddenWorkflowIds:FORBID_SESSION}],["evidence_lock_contended",{category:"evidence",severity:"notice",privacyClass:"sensitive",producer:"src/evidence/lock.ts:134",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,requiredWorkflowIds:REQUIRE_TASK,forbiddenWorkflowIds:FORBID_SESSION}],["evidence_lock_stale_recovered",{category:"evidence",severity:"notice",privacyClass:"sensitive",producer:"src/evidence/lock.ts:91",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,requiredWorkflowIds:REQUIRE_TASK,forbiddenWorkflowIds:FORBID_SESSION}],["plan_ledger_cas_retry",{category:"plan",severity:"notice",privacyClass:"operational",producer:"src/plan/manager.ts:388",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,forbiddenWorkflowIds:FORBID_SESSION}],["plan_md_write_failed",{category:"plan",severity:"warning",privacyClass:"sensitive",producer:"src/plan/manager.ts:2207",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,forbiddenWorkflowIds:FORBID_SESSION}],["snapshot_failed",{category:"plan",severity:"error",privacyClass:"sensitive",producer:"src/plan/ledger.ts:1620",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,forbiddenWorkflowIds:FORBID_SESSION}],["agent_conflict_detected",{category:"conflict",severity:"warning",privacyClass:"pseudonymous",producer:"src/hooks/conflict-resolution.ts:73",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:Object.freeze(["hostSessionId","phaseId"])}],["close_archive_result",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:1118",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047}],["knowledge_receipt_transition",{category:"knowledge",severity:"info",privacyClass:"pseudonymous",producer:"src/hooks/knowledge-receipt-observability.ts:197",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["knowledge_maintenance",{category:"knowledge",severity:"notice",privacyClass:"pseudonymous",producer:"src/knowledge/hive-quarantine.ts:1265",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["residue_health",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:1140",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["context_telemetry_health",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:1184",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["skill_usage_health",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:1221",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["core_events_health",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:1247",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["shell_audit_health",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:1271",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["trajectory_health",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:1294",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["pr_subscription_health",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:1323",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["learning_health_alarm",{category:"lifecycle",severity:"warning",privacyClass:"operational",producer:"src/telemetry.ts:1367",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2044,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["execution_attempt_recorded",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/services/execution-attempt.ts:265",consumers:["src/commands/report.ts:60"],retentionOwnerIssue:2676,requiredWorkflowIds:REQUIRE_SESSION,forbiddenWorkflowIds:FORBID_COUNCIL_ROUND,otelMapping:"none"}]],catalog={};for(let[kind,input]of CATALOG_SOURCE)catalog[kind]=defineEntry(kind,input);EVENT_CATALOG=Object.freeze(catalog),CATALOG_KINDS=Object.freeze(Object.keys(EVENT_CATALOG))});var OBSERVABILITY_SCHEMA_VERSION=1,EventCategorySchema,EventSeveritySchema,PrivacyClassSchema,TimingConfidenceSchema,SpanLinkSchema,TraceContextSchema,WorkflowIdsSchema,LineageSchema,ProvenanceSchema,OutcomeSchema,PolicySchema,LegacyProjectionSchema,ObservabilityEventSchema;var init_envelope=__esm(()=>{init_zod();EventCategorySchema=exports_external.enum(["lifecycle","delegation","gate","plan","evidence","guardrail","knowledge","cost","prm","conflict","unrecognized"]),EventSeveritySchema=exports_external.enum(["debug","info","notice","warning","error","critical"]),PrivacyClassSchema=exports_external.enum(["operational","pseudonymous","sensitive","content"]),TimingConfidenceSchema=exports_external.enum(["exact","writer-clock","inferred","unknown"]),SpanLinkSchema=exports_external.object({traceId:exports_external.string(),spanId:exports_external.string(),kind:exports_external.enum(["resume","lane","cross-process","retry","parent-batch"]),note:exports_external.string().optional()}),TraceContextSchema=exports_external.object({traceId:exports_external.string(),spanId:exports_external.string(),parentSpanId:exports_external.string().optional(),links:exports_external.array(SpanLinkSchema)}),WorkflowIdsSchema=exports_external.object({rootConversationId:exports_external.string().optional(),hostSessionId:exports_external.string().optional(),swarmSessionId:exports_external.string().optional(),taskId:exports_external.string().optional(),callId:exports_external.string().optional(),invocationId:exports_external.string().optional(),phaseId:exports_external.string().optional(),laneId:exports_external.string().optional(),batchId:exports_external.string().optional(),resultId:exports_external.string().optional(),councilRoundId:exports_external.string().optional(),backgroundInvocationId:exports_external.string().optional(),knowledgeTraceId:exports_external.string().optional(),knowledgeEntryId:exports_external.string().optional(),prRunId:exports_external.string().optional()}),LineageSchema=exports_external.object({projectRef:exports_external.string().optional(),cohortRef:exports_external.string().optional(),worktreeRef:exports_external.string().optional()}),ProvenanceSchema=exports_external.object({pluginVersion:exports_external.string().optional(),opencodeVersion:exports_external.string().optional(),runtime:exports_external.string().optional(),runtimeVersion:exports_external.string().optional(),os:exports_external.string().optional(),arch:exports_external.string().optional(),model:exports_external.string().optional(),provider:exports_external.string().optional(),gitSha:exports_external.string().optional(),configHash:exports_external.string().optional()}),OutcomeSchema=exports_external.object({status:exports_external.enum(["success","failure","partial","unknown"]).optional(),reason:exports_external.string().optional(),errorName:exports_external.string().optional(),errorMessage:exports_external.string().optional(),retryIndex:exports_external.number().optional(),durationMs:exports_external.number().optional()}),PolicySchema=exports_external.object({sampled:exports_external.boolean(),sampleRate:exports_external.number(),dropReason:exports_external.string().optional(),privacyClass:PrivacyClassSchema}),LegacyProjectionSchema=exports_external.object({sourceStore:exports_external.string(),sourceSchemaVersion:exports_external.number().nullable(),timingConfidence:TimingConfidenceSchema,unknown:exports_external.array(exports_external.string()),extra:exports_external.record(exports_external.string(),exports_external.unknown()),raw:exports_external.unknown()}),ObservabilityEventSchema=exports_external.object({schemaVersion:exports_external.number(),eventId:exports_external.string(),kind:exports_external.string(),category:EventCategorySchema,severity:EventSeveritySchema,occurredAt:exports_external.string(),observedAt:exports_external.string(),writerSequence:exports_external.number(),trace:TraceContextSchema,workflow:WorkflowIdsSchema,lineage:LineageSchema,provenance:ProvenanceSchema,outcome:OutcomeSchema,policy:PolicySchema,legacy:LegacyProjectionSchema,relationshipViolations:exports_external.array(exports_external.string())})});import{createHash as createHash7,randomBytes as randomBytes2,randomUUID as randomUUID2}from"node:crypto";function newTraceId(){for(let attempt=0;attempt<MAX_REGENERATION_ATTEMPTS;attempt++){let hex3=randomBytes2(TRACE_ID_BYTES).toString("hex");if(hex3!==ALL_ZERO_TRACE_ID)return hex3}return SENTINEL_TRACE_ID}function newSpanId(){for(let attempt=0;attempt<MAX_REGENERATION_ATTEMPTS;attempt++){let hex3=randomBytes2(SPAN_ID_BYTES).toString("hex");if(hex3!==ALL_ZERO_SPAN_ID)return hex3}return SENTINEL_SPAN_ID}function newEventId(){return randomUUID2()}function takeIdBytes(){let need=TRACE_ID_BYTES+SPAN_ID_BYTES;if(_poolOffset+need>_pool.length)_pool=randomBytes2(POOL_BYTES),_poolOffset=0;let slice=_pool.subarray(_poolOffset,_poolOffset+need);return _poolOffset+=need,slice}function newTraceAndSpanId(){let buffer=takeIdBytes(),traceId=buffer.subarray(0,TRACE_ID_BYTES).toString("hex"),spanId=buffer.subarray(TRACE_ID_BYTES).toString("hex");if(traceId===ALL_ZERO_TRACE_ID||spanId===ALL_ZERO_SPAN_ID)return{traceId:newTraceId(),spanId:newSpanId()};return{traceId,spanId}}function resolveLineageSalt(){let configured=process.env[LINEAGE_SALT_ENV];if(typeof configured==="string"&&configured.length>0)return configured;return DEFAULT_LINEAGE_SALT}function pseudonymousRef(absolutePath,salt){return createHash7("sha256").update(salt+LINEAGE_SEPARATOR+absolutePath,"utf8").digest("hex").slice(0,PSEUDONYMOUS_REF_LENGTH)}function pseudonymousSessionRef(sessionId,salt=resolveLineageSalt()){return pseudonymousRef(sessionId,salt)}var TRACE_ID_BYTES=16,SPAN_ID_BYTES=8,TRACE_ID_HEX_LENGTH,SPAN_ID_HEX_LENGTH,ALL_ZERO_TRACE_ID,ALL_ZERO_SPAN_ID,SENTINEL_TRACE_ID,SENTINEL_SPAN_ID,MAX_REGENERATION_ATTEMPTS=4,LINEAGE_SALT_ENV="SWARM_OBSERVABILITY_LINEAGE_SALT",DEFAULT_LINEAGE_SALT="opencode-swarm/observability/lineage/v1",LINEAGE_SEPARATOR="\x00",PSEUDONYMOUS_REF_LENGTH=16,POOL_DRAWS=128,POOL_BYTES,_pool,_poolOffset;var init_ids=__esm(()=>{TRACE_ID_HEX_LENGTH=TRACE_ID_BYTES*2,SPAN_ID_HEX_LENGTH=SPAN_ID_BYTES*2,ALL_ZERO_TRACE_ID="0".repeat(TRACE_ID_HEX_LENGTH),ALL_ZERO_SPAN_ID="0".repeat(SPAN_ID_HEX_LENGTH),SENTINEL_TRACE_ID=`${"0".repeat(TRACE_ID_HEX_LENGTH-1)}1`,SENTINEL_SPAN_ID=`${"0".repeat(SPAN_ID_HEX_LENGTH-1)}1`;POOL_BYTES=(TRACE_ID_BYTES+SPAN_ID_BYTES)*POOL_DRAWS,_pool=Buffer.alloc(0),_poolOffset=Number.POSITIVE_INFINITY});function degradedProjection(marker,data){return{sourceStore:".swarm/telemetry.jsonl",sourceSchemaVersion:null,timingConfidence:"writer-clock",unknown:[marker],extra:EMPTY_EXTRA,raw:data}}function knownKeySetFor(knownKeys){let cached2=_knownKeySetCache.get(knownKeys);if(cached2!==void 0)return cached2;let built=new Set(knownKeys);return _knownKeySetCache.set(knownKeys,built),built}function adaptLegacyTelemetryPayload(kind,data,knownKeys){if(data===null||typeof data!=="object")return degradedProjection("<non-object-payload>",data);try{let record2=data,known=knownKeySetFor(knownKeys),ownKeys=Object.keys(record2),extra;for(let key of ownKeys){if(known.has(key))continue;if(extra??={},key==="__proto__"){Object.defineProperty(extra,key,{value:record2[key],enumerable:!0,writable:!0,configurable:!0});continue}extra[key]=record2[key]}let unknownFields;for(let key of knownKeys)if(record2[key]===void 0)unknownFields??=[],unknownFields.push(key);return{sourceStore:".swarm/telemetry.jsonl",sourceSchemaVersion:null,timingConfidence:"writer-clock",unknown:unknownFields??EMPTY_UNKNOWN,extra:extra??EMPTY_EXTRA,raw:data}}catch{return degradedProjection("<payload-introspection-failed>",data)}}function nonEmptyString(value){return typeof value==="string"&&value.length>0?value:void 0}function extractWorkflowIds(data){let ids={};try{if(data===null||typeof data!=="object")return ids;let record2=data,hostSessionId=nonEmptyString(record2.sessionId);if(hostSessionId!==void 0)ids.hostSessionId=hostSessionId;let taskId=nonEmptyString(record2.taskId);if(taskId!==void 0)ids.taskId=taskId;let callId=nonEmptyString(record2.callId);if(callId!==void 0)ids.callId=callId;let invocationId=nonEmptyString(record2.invocationId);if(invocationId!==void 0)ids.invocationId=invocationId;let laneId=nonEmptyString(record2.laneId);if(laneId!==void 0)ids.laneId=laneId;let batchId=nonEmptyString(record2.batchId);if(batchId!==void 0)ids.batchId=batchId;let councilRoundId=nonEmptyString(record2.councilRoundId);if(councilRoundId!==void 0)ids.councilRoundId=councilRoundId;let knowledgeTraceId=nonEmptyString(record2.knowledgeTraceId);if(knowledgeTraceId!==void 0)ids.knowledgeTraceId=knowledgeTraceId;let knowledgeEntryId=nonEmptyString(record2.knowledgeEntryId);if(knowledgeEntryId!==void 0)ids.knowledgeEntryId=knowledgeEntryId;let phase=record2.phase;if(typeof phase==="number"&&Number.isFinite(phase))ids.phaseId=String(phase);else{let phaseString=nonEmptyString(phase);if(phaseString!==void 0)ids.phaseId=phaseString}}catch{}return ids}function extractOutcome(data){let outcome={};try{if(data===null||typeof data!=="object")return outcome;let record2=data,result=nonEmptyString(record2.result);if(result!==void 0){let normalized=result.toLowerCase();outcome.status=Object.hasOwn(RESULT_STATUS_MAP,normalized)?RESULT_STATUS_MAP[normalized]:"unknown"}let reason=nonEmptyString(record2.reason);if(reason!==void 0)outcome.reason=reason;let errorName=nonEmptyString(record2.errorName);if(errorName!==void 0)outcome.errorName=errorName;let errorMessage=nonEmptyString(record2.errorMessage);if(errorMessage!==void 0)outcome.errorMessage=errorMessage;let retryIndex=record2.retry_index;if(typeof retryIndex==="number"&&Number.isFinite(retryIndex))outcome.retryIndex=retryIndex}catch{}return outcome}var LEGACY_TELEMETRY_SOURCE_STORE=".swarm/telemetry.jsonl",LEGACY_ADAPTER_RULES,KNOWN_TELEMETRY_KEYS,EMPTY_EXTRA,EMPTY_UNKNOWN,_knownKeySetCache,RESULT_STATUS_MAP;var init_legacy=__esm(()=>{LEGACY_ADAPTER_RULES=Object.freeze(["Preserve unknown fields: an own key the contract does not recognize is kept under `extra` by reference and is never dropped.","Record the source store and its schema version: `sourceStore` names the file; `sourceSchemaVersion` is the version the store declares.","Preserve originally reported values: values are aliased, never coerced, normalized, rounded, or re-serialized.","Record timing confidence: a time read by the writer at record time is `writer-clock`, never `exact`.","Unknown is not zero: the adapter lists in `unknown` every catalogued key the PRODUCER left undefined, and never itself defaults one to 0, \"\", false, or null. The guarantee stops at the adapter boundary — a producer that pre-coerces its own defaults defeats it, because the adapter only ever sees the coerced value. The known instance was `delegation_end` (`src/telemetry.ts` `delegationEnd`): before issue #2789 it coerced token axes with `?? 0`, so they could never appear in `unknown`; it now emits held-null token axes (`?? null`), matching `cost_usd`, and `cost_source: 'unavailable'` still records absence of a cost basis.","Missing lineage stays missing: an absent correlation ID stays `undefined` and is never synthesized to make a join succeed.","Never drop unrecognized fields: no allowlist filter is applied to the payload on the way through."]),KNOWN_TELEMETRY_KEYS=Object.freeze({session_started:Object.freeze(["sessionId","agentName"]),session_ended:Object.freeze(["sessionId","reason"]),agent_activated:Object.freeze(["sessionId","agentName","oldName"]),delegation_begin:Object.freeze(["sessionId","agentName","taskId"]),delegation_end:Object.freeze(["sessionId","agentName","taskId","result","tokens_input","tokens_output","tokens_reasoning","tokens_cache","cost_usd","cost_source","model","gate","retry_index","cost_evidence","evidence_status","evidence_reason","currency","record_id","identity_fingerprint","parent_session_digest","child_session_digest","version"]),delegation_cost_correction:Object.freeze(["sessionId","agentName","taskId","parent_session_digest","record_id","identity_fingerprint","version","cost_evidence","evidence_status","evidence_reason","currency","cost_usd","cost_source","tokens_input","tokens_output","tokens_reasoning","tokens_cache","model","gate","retry_index"]),delegation_cost_binding:Object.freeze(["sessionId","record_id","identity_fingerprint","child_session_digest"]),delegation_cost_join:Object.freeze(["sessionId","reason"]),execution_attempt_recorded:Object.freeze(["sessionId","taskId","callId","invocationId","attemptClass","generation","retryIndex","laneId","knowledgeTraceId","outcomeStatus","captured","unknown","cost","duplicateOf"]),task_state_changed:Object.freeze(["sessionId","taskId","newState","oldState"]),gate_passed:Object.freeze(["sessionId","gate","taskId"]),gate_parse_error:Object.freeze(["taskId","errorName","errorMessage"]),gate_failed:Object.freeze(["sessionId","gate","taskId","reason"]),reviewer_gate_decision:Object.freeze(["sessionId","gate","taskId","blocked","allowed","reasonCode","evidenceKind"]),phase_changed:Object.freeze(["sessionId","oldPhase","newPhase"]),budget_updated:Object.freeze(["sessionId","budgetPct","agentName"]),context_pruned:Object.freeze(["sessionId","agentName","trigger","usageSource","beforeTokens","afterTokens","modelLimit","maskedMessages","maskedToolParts","maskedTokensFreed","prunedMessages","prunedTextParts","prunedToolParts","prunedTokensFreed"]),model_fallback:Object.freeze(["sessionId","agentName","fromModel","toModel","reason"]),model_unresolved:Object.freeze(["sessionId","agentName","model","detail"]),hard_limit_hit:Object.freeze(["sessionId","agentName","limitType","value"]),revision_limit_hit:Object.freeze(["sessionId","agentName"]),loop_detected:Object.freeze(["sessionId","agentName","loopType"]),scope_violation:Object.freeze(["sessionId","agentName","file","reason"]),qa_skip_violation:Object.freeze(["sessionId","agentName","skipCount"]),heartbeat:Object.freeze(["sessionId"]),turbo_mode_changed:Object.freeze(["sessionId","enabled","agentName"]),auto_oversight_escalation:Object.freeze(["sessionId","reason","interactionCount","deadlockCount","phase"]),environment_detected:Object.freeze(["sessionId","hostOS","shellFamily","executionMode"]),prm_pattern_detected:Object.freeze(["sessionId","pattern","severity","category","stepRange"]),prm_course_correction_injected:Object.freeze(["sessionId","pattern","level"]),prm_escalation_triggered:Object.freeze(["sessionId","pattern","level","occurrenceCount"]),prm_hard_stop:Object.freeze(["sessionId","pattern","level","occurrenceCount"]),no_op_strong_warning:Object.freeze(["sessionId","agentName","count","threshold"]),gate_denial_loop:Object.freeze(["sessionId","tool","code","count"]),execution_stall_warning:Object.freeze(["sessionId","count","threshold"]),execution_stall_denied:Object.freeze(["sessionId","tool","count","threshold"]),swarm_internals_read_denied:Object.freeze(["sessionId","tool","target"]),prm_hard_stop_delivered:Object.freeze(["sessionId","pattern","level","occurrenceCount"]),evidence_lock_acquired:Object.freeze(["directory","evidencePath","agent","taskId","attempt"]),evidence_lock_contended:Object.freeze(["directory","evidencePath","agent","taskId","attempt"]),evidence_lock_stale_recovered:Object.freeze(["directory","evidencePath","agent","taskId","attempt"]),plan_ledger_cas_retry:Object.freeze(["attempt","expectedHashPrefix","delayMs"]),plan_md_write_failed:Object.freeze(["directory","error","timestamp"]),snapshot_failed:Object.freeze(["error","retries","source"]),agent_conflict_detected:Object.freeze(["type","timestamp","sessionId","phase","taskId","sourceAgent","targetAgent","conflictType","resolutionPath","summary"]),knowledge_receipt_transition:Object.freeze(["transition","reasonCode","schemaVersion","receiptSemantics","knowledgeTraceId","knowledgeEntryId","sessionId","taskId","phase","receiptOutcome","receiptSource"]),knowledge_maintenance:Object.freeze(["phase","abortReason","selectedCount","storeEntriesBefore","storeEntriesAfter","backupBytes","storeSha256Prefix","token12"]),residue_health:Object.freeze(["trigger","scanned","matched","eligible","ambiguous","quarantined","preserved","total_bytes","oldest_age_ms","grammar_counts"]),training_vault_health:Object.freeze(["project_ref","reason","count"]),context_telemetry_health:Object.freeze(["trigger","accepted_count","compacted_count","retained_count","dropped_count","corrupt_count","oldest_timestamp","newest_timestamp","bytes","limit_bytes"]),skill_usage_health:Object.freeze(["trigger","accepted","compacted","dropped","skills_dropped","corrupt","pending_retained","uncertain_retained","uncertain_expired","pending_evicted","no_source_knowledge","no_matching_knowledge","bump_retry","bump_unrecoverable","bump_applied_zero","pressure","curator_skipped","bytes","limit_bytes","oldest_timestamp","newest_timestamp","coverage"]),learning_health_alarm:Object.freeze(["alarm","transition","severity","scope_class","session_ref","model","provider","window_ms","coverage_facts","raise_facts","age_ms","limit_source","denominator_fallback","pressure_pct","band","share_pct","field_count","non_field_count","store","dropped","corrupt","retained","accepted","gap_type","role","phase","reason"]),core_events_health:Object.freeze(["trigger","accepted_count","compacted_count","retained_count","dropped_count","corrupt_count","authority_index_count","authority_evicted_count","oldest_timestamp","newest_timestamp","bytes","limit_bytes"]),council_attempt:Object.freeze(["sessionId","councilRoundId","level","stage","attemptId","disposition","taskId","phase","identityDigest","authoritativeRound","clientRound","verdictCount","memberCount","quorumSize","verdict","transition","gateEffect"]),council_round_transition:Object.freeze(["sessionId","councilRoundId","level","attemptId","transition","gateEffect","taskId","phase","identityDigest","round","nextRound","roundStatus","maxRoundsExhausted","verdict","quorumSize"]),council_attempt_unscoped:Object.freeze(["sessionId","level","disposition","fingerprint","attemptId"])}),EMPTY_EXTRA=Object.freeze({});EMPTY_UNKNOWN=Object.freeze([]),_knownKeySetCache=new WeakMap;RESULT_STATUS_MAP=Object.freeze({success:"success",succeeded:"success",ok:"success",pass:"success",passed:"success",complete:"success",completed:"success",failure:"failure",failed:"failure",fail:"failure",error:"failure",partial:"partial"})});function validateEventRelationships(event){let violations=[];try{let entry=getCatalogEntry(event.kind),links=Array.isArray(event.trace?.links)?event.trace.links:[];if(entry===void 0)violations.push(`${RELATIONSHIP_VIOLATION_CODES.unknownKind}:${event.kind}`);else{let workflow=event.workflow??{};for(let id of entry.requiredWorkflowIds)if(workflow[id]===void 0)violations.push(`${RELATIONSHIP_VIOLATION_CODES.requiredWorkflowIdMissing}:${id}`);for(let id of entry.forbiddenWorkflowIds)if(workflow[id]!==void 0)violations.push(`${RELATIONSHIP_VIOLATION_CODES.forbiddenWorkflowIdPresent}:${id}`);let parentSpanId=event.trace?.parentSpanId;if(!entry.requiresParent&&parentSpanId!==void 0)violations.push(RELATIONSHIP_VIOLATION_CODES.parentSpanNotAllowed);if(entry.requiresParent&&parentSpanId===void 0)violations.push(RELATIONSHIP_VIOLATION_CODES.parentSpanMissing);if(parentSpanId!==void 0&&!SPAN_ID_PATTERN.test(String(parentSpanId)))violations.push(RELATIONSHIP_VIOLATION_CODES.malformedParentSpanId);if(!entry.allowsLinks&&links.length>0)violations.push(RELATIONSHIP_VIOLATION_CODES.linksNotAllowed)}for(let index=0;index<links.length;index++){let link=links[index];if(link===void 0||link===null)continue;if(!TRACE_ID_PATTERN.test(String(link.traceId)))violations.push(`${RELATIONSHIP_VIOLATION_CODES.malformedLinkTraceId}:${index}`);if(!SPAN_ID_PATTERN.test(String(link.spanId)))violations.push(`${RELATIONSHIP_VIOLATION_CODES.malformedLinkSpanId}:${index}`)}}catch{return{ok:!1,violations:[RELATIONSHIP_VIOLATION_CODES.validationFailed]}}return violations.length===0?{ok:!0}:{ok:!1,violations}}var TRACE_ID_PATTERN,SPAN_ID_PATTERN,RELATIONSHIP_VIOLATION_CODES;var init_relationships=__esm(()=>{init_catalog();TRACE_ID_PATTERN=/^[0-9a-f]{32}$/,SPAN_ID_PATTERN=/^[0-9a-f]{16}$/,RELATIONSHIP_VIOLATION_CODES=Object.freeze({unknownKind:"unknown_kind",requiredWorkflowIdMissing:"required_workflow_id_missing",forbiddenWorkflowIdPresent:"forbidden_workflow_id_present",parentSpanNotAllowed:"parent_span_not_allowed",parentSpanMissing:"parent_span_missing",malformedParentSpanId:"malformed_parent_span_id",linksNotAllowed:"links_not_allowed",malformedLinkTraceId:"malformed_link_trace_id",malformedLinkSpanId:"malformed_link_span_id",validationFailed:"relationship_validation_failed"})});function shouldSample(traceId,rate){if(typeof rate!=="number"||!Number.isFinite(rate))return!0;if(rate>=1)return!0;if(rate<=0)return!1;if(typeof traceId!=="string"||traceId.length<8)return!0;let suffix=traceId.slice(-8).toLowerCase();if(!SAMPLE_SUFFIX_PATTERN.test(suffix))return!0;let value=Number.parseInt(suffix,16);if(!Number.isFinite(value))return!0;return value/4294967295<rate}var DEFAULT_SAMPLE_RATE=1,SAMPLE_SUFFIX_PATTERN,METRIC_LABEL_ALLOWLIST,ALLOWED_LABELS,CARDINALITY_VIOLATION_CODES;var init_sampling=__esm(()=>{SAMPLE_SUFFIX_PATTERN=/^[0-9a-f]{8}$/;METRIC_LABEL_ALLOWLIST=Object.freeze(["kind","category","severity","outcome_status","cost_source","privacy_class","runtime","os","provider","sampled"]),ALLOWED_LABELS=new Set(METRIC_LABEL_ALLOWLIST),CARDINALITY_VIOLATION_CODES=Object.freeze({notAllowlisted:"label_not_allowlisted",highCardinalityShape:"high_cardinality_label_shape"})});function initObservability(input){try{let salt=resolveLineageSalt(),lineage={},directory=typeof input.directory==="string"&&input.directory.length>0?input.directory:void 0;if(directory!==void 0)lineage.projectRef=pseudonymousRef(directory,salt);if(typeof input.cohortLabel==="string"&&input.cohortLabel.length>0)lineage.cohortRef=pseudonymousRef(`${directory??""}\x00cohort\x00${input.cohortLabel}`,salt);if(typeof input.worktreeId==="string"&&input.worktreeId.length>0)lineage.worktreeRef=pseudonymousRef(`${directory??""}\x00worktree\x00${input.worktreeId}`,salt);if(_lineage=Object.freeze(lineage),_provenance=Object.freeze(input.provenance?{...input.provenance}:{}),typeof input.sampleRate==="number"&&Number.isFinite(input.sampleRate))_sampleRate=input.sampleRate}catch{}}function nextWriterSequence(){if(_writerSequence>=Number.MAX_SAFE_INTEGER)_writerSequence=0;return _writerSequence+=1,_writerSequence}function safeNowIso(){try{return new Date().toISOString()}catch{return FALLBACK_TIMESTAMP}}function buildFallbackObservation(kind,data,writerSequence){let now=safeNowIso();return{schemaVersion:OBSERVABILITY_SCHEMA_VERSION,eventId:FALLBACK_EVENT_ID,kind,category:"unrecognized",severity:"error",occurredAt:now,observedAt:now,writerSequence,trace:{traceId:FALLBACK_TRACE_ID,spanId:FALLBACK_SPAN_ID,links:[]},workflow:{},lineage:{},provenance:{},outcome:{},policy:{sampled:shouldSample(FALLBACK_TRACE_ID,_sampleRate),sampleRate:_sampleRate,privacyClass:"operational"},legacy:{sourceStore:LEGACY_TELEMETRY_SOURCE_STORE,sourceSchemaVersion:null,timingConfidence:"unknown",unknown:[],extra:{},raw:data},relationshipViolations:[OBSERVATION_BUILD_FAILED]}}function createObservation(kind,data){let writerSequence=nextWriterSequence();try{let entry=getCatalogEntry(kind),{traceId,spanId}=newTraceAndSpanId(),observedAt=new Date().toISOString(),knownKeys=Object.hasOwn(KNOWN_TELEMETRY_KEYS,kind)?KNOWN_TELEMETRY_KEYS[kind]:EMPTY_KNOWN_KEYS,event={schemaVersion:OBSERVABILITY_SCHEMA_VERSION,eventId:newEventId(),kind,category:entry?.category??"unrecognized",severity:entry?.severity??"warning",occurredAt:observedAt,observedAt,writerSequence,trace:{traceId,spanId,links:[]},workflow:extractWorkflowIds(data),lineage:_lineage,provenance:_provenance,outcome:extractOutcome(data),policy:{sampled:shouldSample(traceId,_sampleRate),sampleRate:_sampleRate,privacyClass:entry?.privacyClass??"operational"},legacy:adaptLegacyTelemetryPayload(kind,data,knownKeys),relationshipViolations:[]},validation=validateEventRelationships(event);if(!validation.ok)event.relationshipViolations=validation.violations;return event}catch{return buildFallbackObservation(kind,data,writerSequence)}}function toLegacyTelemetryLine(event){return{timestamp:event.observedAt,event:event.kind,...event.legacy.raw}}function canonicalLineContent(event){return JSON.stringify(toLegacyTelemetryLine(event))}var _provenance,_lineage,_writerSequence=0,_sampleRate,EMPTY_KNOWN_KEYS,FALLBACK_EVENT_ID="00000000-0000-4000-8000-000000000000",FALLBACK_TRACE_ID="00000000000000000000000000000001",FALLBACK_SPAN_ID="0000000000000001",FALLBACK_TIMESTAMP="1970-01-01T00:00:00.000Z",OBSERVATION_BUILD_FAILED="observation_build_failed";var init_observe=__esm(()=>{init_catalog();init_envelope();init_ids();init_legacy();init_relationships();init_sampling();_provenance=Object.freeze({}),_lineage=Object.freeze({}),_sampleRate=DEFAULT_SAMPLE_RATE,EMPTY_KNOWN_KEYS=Object.freeze([])});var OTEL_GENAI_MAPPING_VERSION="1.29.0",OPENINFERENCE_MAPPING_VERSION="0.1.14",OTEL_GENAI_ATTRIBUTES,OPENINFERENCE_ATTRIBUTES,NO_ATTRIBUTES;var init_otel_mapping=__esm(()=>{OTEL_GENAI_ATTRIBUTES=Object.freeze({kind:"gen_ai.operation.name","provenance.provider":"gen_ai.system","provenance.model":"gen_ai.request.model","legacy.raw.model":"gen_ai.response.model","legacy.raw.agentName":"gen_ai.agent.name","workflow.hostSessionId":"gen_ai.conversation.id","outcome.status":"gen_ai.response.finish_reasons","legacy.raw.tokens_input":"gen_ai.usage.input_tokens","legacy.raw.tokens_output":"gen_ai.usage.output_tokens","legacy.raw.tokens_cache":"gen_ai.usage.cache_read_input_tokens","legacy.raw.tokens_reasoning":"swarm.gen_ai.usage.reasoning_tokens","legacy.raw.cost_usd":"swarm.gen_ai.usage.cost_usd"}),OPENINFERENCE_ATTRIBUTES=Object.freeze({kind:"openinference.span.kind","provenance.model":"llm.model_name","provenance.provider":"llm.provider","legacy.raw.agentName":"agent.name","workflow.hostSessionId":"session.id","legacy.raw.tokens_input":"llm.token_count.prompt","legacy.raw.tokens_output":"llm.token_count.completion","legacy.raw.tokens_cache":"llm.token_count.prompt_details.cache_read","legacy.raw.tokens_reasoning":"llm.token_count.completion_details.reasoning","legacy.raw.cost_usd":"swarm.llm.cost_usd"}),NO_ATTRIBUTES=Object.freeze({})});var init_observability=__esm(()=>{init_catalog();init_envelope();init_ids();init_legacy();init_observe();init_otel_mapping();init_relationships();init_sampling()});var exports_telemetry={};__export(exports_telemetry,{telemetry:()=>telemetry,stopHeartbeatTracking:()=>stopHeartbeatTracking,startHeartbeatTracking:()=>startHeartbeatTracking,rotateTelemetryIfNeeded:()=>rotateTelemetryIfNeeded,resetTelemetryForTesting:()=>resetTelemetryForTesting,resetHeartbeatTrackingForTesting:()=>resetHeartbeatTrackingForTesting,removeTelemetryListener:()=>removeTelemetryListener,initTelemetry:()=>initTelemetry,getLastHeartbeat:()=>getLastHeartbeat,flushAndDrainTelemetry:()=>flushAndDrainTelemetry,emit:()=>emit,addTelemetryListener:()=>addTelemetryListener,_internals:()=>_internals16,ROTATION_CHECK_INTERVAL:()=>ROTATION_CHECK_INTERVAL});import*as fs7 from"node:fs";import{createWriteStream}from"node:fs";import*as os3 from"node:os";import*as path13 from"node:path";function capHeartbeatMap(){while(heartbeatTimestamps.size>=500){let oldestKey=heartbeatTimestamps.keys().next().value;if(oldestKey===void 0)break;heartbeatTimestamps.delete(oldestKey)}}function startHeartbeatTracking(){if(_heartbeatTrackingActive)return;_heartbeatTrackingActive=!0;let listener=(event,data)=>{if(event!=="heartbeat")return;let payload=data;if(!payload?.sessionId)return;heartbeatTimestamps.set(payload.sessionId,Date.now()),capHeartbeatMap()};_heartbeatListener=listener,addTelemetryListener(listener)}function getLastHeartbeat(sessionId){return heartbeatTimestamps.get(sessionId)}function stopHeartbeatTracking(){if(_heartbeatTrackingActive=!1,_heartbeatListener!==null){let idx=_listeners.indexOf(_heartbeatListener);if(idx>=0)_listeners.splice(idx,1);_heartbeatListener=null}}function resetHeartbeatTrackingForTesting(){if(_heartbeatTrackingActive=!1,heartbeatTimestamps.clear(),_heartbeatListener!==null){let idx=_listeners.indexOf(_heartbeatListener);if(idx>=0)_listeners.splice(idx,1);_heartbeatListener=null}}function resetTelemetryForTesting(){if(_disabled=!1,_projectDirectory=null,_listeners.length=0,_emitCount=0,resetHeartbeatTrackingForTesting(),_writeStream!==null)_writeStream.end(),_writeStream=null}function initTelemetry(projectDirectory){if(_disabled)return;if(_writeStream!==null&&_projectDirectory!==null&&sameProjectRoot(_projectDirectory,projectDirectory))return;let oldStream=_writeStream;try{let swarmDir=path13.join(projectDirectory,".swarm");if(!fs7.existsSync(swarmDir))fs7.mkdirSync(swarmDir,{recursive:!0});let telemetryPath=path13.join(swarmDir,"telemetry.jsonl"),stream=createWriteStream(telemetryPath,{flags:"a"});stream.on("error",()=>{if(_writeStream===stream)_disabled=!0,_writeStream=null}),_writeStream=stream,_projectDirectory=projectDirectory}catch(error49){log(`[telemetry] failed to open the new project's telemetry stream (retaining the previous stream, non-fatal): ${error49 instanceof Error?error49.message:String(error49)}`);return}if(oldStream!==null)try{oldStream.end()}catch(error49){log(`[telemetry] failed to close the previous project's stream during re-home (non-fatal): ${error49 instanceof Error?error49.message:String(error49)}`)}}function emit(event,data){try{if(_disabled||_writeStream===null)return;let canonical=_internals16.createObservation(event,data),content=_internals16.canonicalLineContent(canonical),line=content+os3.EOL,stream=_writeStream;stream.write(line,(err)=>{if(err&&_writeStream===stream)_disabled=!0,_writeStream=null});for(let listener of _listeners)try{listener(event,data,canonical,content)}catch{}if(_emitCount++,_emitCount>=ROTATION_CHECK_INTERVAL)_emitCount=0,_internals16.rotateTelemetryIfNeeded()}catch{}}function addTelemetryListener(callback){_listeners.push(callback)}function removeTelemetryListener(callback){let idx=_listeners.indexOf(callback);if(idx>=0)_listeners.splice(idx,1)}function rotateTelemetryIfNeeded(maxBytes=10485760){try{if(_projectDirectory===null)return;let telemetryPath=path13.join(_projectDirectory,".swarm","telemetry.jsonl");if(!fs7.existsSync(telemetryPath))return;if(fs7.statSync(telemetryPath).size<maxBytes)return;let rotatedPath=path13.join(_projectDirectory,".swarm","telemetry.jsonl.1");if(fs7.renameSync(telemetryPath,rotatedPath),_writeStream!==null){_writeStream.end();let stream=createWriteStream(telemetryPath,{flags:"a"});stream.on("error",()=>{if(_writeStream===stream)_disabled=!0,_writeStream=null}),_writeStream=stream}}catch{}}async function flushAndDrainTelemetry(){let stream=_writeStream;if(stream===null||_projectDirectory===null)return;let next;try{let telemetryPath=path13.join(_projectDirectory,".swarm","telemetry.jsonl");next=createWriteStream(telemetryPath,{flags:"a"}),next.on("error",()=>{if(_writeStream===next)_disabled=!0,_writeStream=null}),_writeStream=next}catch{_disabled=!0,_writeStream=null;return}await new Promise((resolve9)=>{stream.end(()=>resolve9())})}var _writeStream=null,_projectDirectory=null,_listeners,_disabled=!1,_heartbeatTrackingActive=!1,_heartbeatListener=null,heartbeatTimestamps,_emitCount=0,ROTATION_CHECK_INTERVAL=50,telemetry,_internals16;var init_telemetry=__esm(()=>{init_observability();init_utils();init_canonical_root();_listeners=[],heartbeatTimestamps=new Map;telemetry={sessionStarted(sessionId,agentName){_internals16.emit("session_started",{sessionId,agentName})},sessionEnded(sessionId,reason){_internals16.emit("session_ended",{sessionId,reason})},agentActivated(sessionId,agentName,oldName){_internals16.emit("agent_activated",{sessionId,agentName,oldName})},delegationBegin(sessionId,agentName,taskId){_internals16.emit("delegation_begin",{sessionId,agentName,taskId})},delegationEnd(sessionId,agentName,taskId,result,costFields){_internals16.emit("delegation_end",{sessionId,agentName,taskId,result,...costFields,tokens_input:costFields?.tokens_input??null,tokens_output:costFields?.tokens_output??null,tokens_reasoning:costFields?.tokens_reasoning??null,tokens_cache:costFields?.tokens_cache??null,cost_usd:costFields?.cost_usd??null,cost_source:costFields?.cost_source??"unavailable",model:costFields?.model,gate:costFields?.gate,retry_index:costFields?.retry_index})},delegationReadUncertain(event){_internals16.emit("delegation_read_uncertain",{attempt:event.attempt,reasonCode:event.reasonCode.slice(0,64),source:event.source})},taskStateChanged(sessionId,taskId,newState,oldState){_internals16.emit("task_state_changed",{sessionId,taskId,newState,oldState})},gatePassed(sessionId,gate,taskId){_internals16.emit("gate_passed",{sessionId,gate,taskId})},gateParseError(taskId,error49){_internals16.emit("gate_parse_error",{taskId,errorName:error49.name,errorMessage:error49.message.slice(0,200)})},gateFailed(sessionId,gate,taskId,reason){_internals16.emit("gate_failed",{sessionId,gate,taskId,reason})},reviewerGateDecision(sessionId,taskId,blocked,reasonCode,evidenceKind){_internals16.emit("reviewer_gate_decision",{sessionId,gate:"qa_gate",taskId,blocked,allowed:!blocked,reasonCode,evidenceKind})},phaseChanged(sessionId,oldPhase,newPhase){_internals16.emit("phase_changed",{sessionId,oldPhase,newPhase})},budgetUpdated(sessionId,budgetPct,agentName){_internals16.emit("budget_updated",{sessionId,budgetPct,agentName})},contextPruned(data){_internals16.emit("context_pruned",data)},modelFallback(sessionId,agentName,fromModel,toModel,reason){_internals16.emit("model_fallback",{sessionId,agentName,fromModel,toModel,reason})},modelUnresolved(agentName,model,detail){_internals16.emit("model_unresolved",{sessionId:"preflight",agentName,model,detail})},hardLimitHit(sessionId,agentName,limitType,value){_internals16.emit("hard_limit_hit",{sessionId,agentName,limitType,value})},revisionLimitHit(sessionId,agentName){_internals16.emit("revision_limit_hit",{sessionId,agentName})},loopDetected(sessionId,agentName,loopType){_internals16.emit("loop_detected",{sessionId,agentName,loopType})},noOpStrongWarning(sessionId,agentName,count,threshold){_internals16.emit("no_op_strong_warning",{sessionId,agentName,count,threshold})},gateDenialLoop(sessionId,tool,code,count){_internals16.emit("gate_denial_loop",{sessionId,tool,code,count})},executionStallWarning(sessionId,count,threshold){_internals16.emit("execution_stall_warning",{sessionId,count,threshold})},executionStallDenied(sessionId,tool,count,threshold){_internals16.emit("execution_stall_denied",{sessionId,tool,count,threshold})},swarmInternalsReadDenied(sessionId,tool,target){_internals16.emit("swarm_internals_read_denied",{sessionId,tool,target})},scopeViolation(sessionId,agentName,file2,reason){_internals16.emit("scope_violation",{sessionId,agentName,file:file2,reason})},qaSkipViolation(sessionId,agentName,skipCount){_internals16.emit("qa_skip_violation",{sessionId,agentName,skipCount})},heartbeat(sessionId){_internals16.emit("heartbeat",{sessionId})},turboModeChanged(sessionId,enabled,agentName){_internals16.emit("turbo_mode_changed",{sessionId,enabled,agentName})},autoOversightEscalation(sessionId,reason,interactionCount,deadlockCount,phase){_internals16.emit("auto_oversight_escalation",{sessionId,reason,interactionCount,deadlockCount,phase})},environmentDetected(sessionId,hostOS,shellFamily,executionMode){_internals16.emit("environment_detected",{sessionId,hostOS,shellFamily,executionMode})},prmPatternDetected(sessionId,pattern,severity,category,stepRange){_internals16.emit("prm_pattern_detected",{sessionId,pattern,severity,category,stepRange})},prmCourseCorrectionInjected(sessionId,pattern,level){_internals16.emit("prm_course_correction_injected",{sessionId,pattern,level})},prmEscalationTriggered(sessionId,pattern,level,occurrenceCount){_internals16.emit("prm_escalation_triggered",{sessionId,pattern,level,occurrenceCount})},prmHardStop(sessionId,pattern,level,occurrenceCount){_internals16.emit("prm_hard_stop",{sessionId,pattern,level,occurrenceCount})},prmHardStopTerminal(sessionId,pattern,level,occurrenceCount){_internals16.emit("prm_hard_stop_terminal",{sessionId,pattern,level,occurrenceCount})},closeArchiveResult(data){_internals16.emit("close_archive_result",data)},residueHealth(data){_internals16.emit("residue_health",data)},trainingVaultHealth(data){_internals16.emit("training_vault_health",data)},contextTelemetryHealth(data){_internals16.emit("context_telemetry_health",data)},skillUsageHealth(data){_internals16.emit("skill_usage_health",data)},coreEventsHealth(data){_internals16.emit("core_events_health",data)},shellAuditHealth(data){_internals16.emit("shell_audit_health",data)},trajectoryHealth(data){_internals16.emit("trajectory_health",data)},prSubscriptionHealth(data){_internals16.emit("pr_subscription_health",data)},learningHealthAlarm(data){_internals16.emit("learning_health_alarm",data)},prmHardStopDelivered(sessionId,pattern,level,occurrenceCount){_internals16.emit("prm_hard_stop_delivered",{sessionId,pattern,level,occurrenceCount})},retrievalRouted(sessionId,data){_internals16.emit("retrieval_routed",{sessionId,...data})}},_internals16={telemetry,emit,rotateTelemetryIfNeeded,flushAndDrainTelemetry,heartbeatListenerCount:()=>_heartbeatListener!==null?1:0,createObservation,toLegacyTelemetryLine,canonicalLineContent}});import*as fs8 from"node:fs";import*as os4 from"node:os";import*as path14 from"node:path";function isAbsoluteDirectoryInput(value){return typeof value==="string"&&value.trim().length>0&&path14.isAbsolute(value)}function hasExplicitProjectBoundary(directory){if(!isAbsoluteDirectoryInput(directory))return!1;for(let marker of PROJECT_BOUNDARY_MARKERS)try{let stat5=_internals17.lstatSync(path14.join(directory,marker.name));if(!stat5.isSymbolicLink()&&marker.accepts(stat5))return!0}catch{}return!1}function isStrictPathDescendant(candidate,root){if(!isAbsoluteDirectoryInput(candidate)||!isAbsoluteDirectoryInput(root))return!1;let relative4=path14.relative(root,candidate);return relative4!==""&&relative4!==".."&&!relative4.startsWith(`..${path14.sep}`)&&!path14.isAbsolute(relative4)}function walkProjectBoundary(resolved,dependencies){if(hasExplicitProjectBoundary(resolved))return{outcome:"marker-root"};let current=resolved,depth=0;while(!0){if(depth>=MAX_PROJECT_ROOT_DEPTH)return{outcome:"fail-closed",reason:"depth"};depth++;let parent=path14.dirname(current);if(parent===current)return{outcome:"unclaimed"};if(path14.dirname(parent)===parent){current=parent;continue}let parentSwarm=path14.join(parent,".swarm"),parentSwarmStat;try{parentSwarmStat=dependencies.statSync(parentSwarm)}catch(error49){if(isMissingPathError(error49)){current=parent;continue}return{outcome:"fail-closed",reason:"ancestor-swarm",path:parentSwarm}}if(parentSwarmStat.isDirectory()){let indicatorState=projectIndicatorState(parent,dependencies,{allowConfigOnly:!isWeakConfigContainerRoot(parent,dependencies)});if(indicatorState==="inaccessible")return{outcome:"fail-closed",reason:"ancestor-indicators",path:parent};if(indicatorState==="present")return{outcome:"claimed",ancestor:parent}}current=parent}}function isMissingPathError(error49){let code=error49?.code;return code==="ENOENT"||code==="ENOTDIR"}function isWeakConfigContainerRoot(directory,dependencies){try{let resolved=dependencies.realpathSync(directory);return resolved===dependencies.realpathSync(os4.tmpdir())||resolved===dependencies.realpathSync(os4.homedir())}catch{let resolved=path14.resolve(directory);return resolved===path14.resolve(os4.tmpdir())||resolved===path14.resolve(os4.homedir())}}function projectIndicatorState(directory,dependencies,options={}){let allowConfigOnly=options.allowConfigOnly??!0;for(let indicator of PROJECT_ROOT_INDICATORS){if(!allowConfigOnly&&indicator===".opencode")continue;try{let indicatorStat=dependencies.statSync(path14.join(directory,indicator));if(indicatorStat.isFile()||indicatorStat.isDirectory())return"present"}catch(error49){if(!isMissingPathError(error49))return"inaccessible"}}return"absent"}function assertProjectRoot(directory,dependencies=fs8,artifactLabel="runtime state"){let resolved;try{resolved=dependencies.realpathSync(directory)}catch{throw warn(`[project-boundary] Cannot canonicalize directory "${directory}" — failing closed`),Error(`Cannot verify project root for "${directory}" — directory may not exist or is inaccessible`)}let walk=walkProjectBoundary(resolved,dependencies);if(walk.outcome==="marker-root"||walk.outcome==="unclaimed")return;if(walk.outcome==="claimed")throw warn(`[project-boundary] Rejecting write to subdirectory "${resolved}" — parent "${walk.ancestor}" already contains .swarm/`),Error(`Cannot write ${artifactLabel} in "${resolved}" — parent directory "${walk.ancestor}" already contains a .swarm/ folder. Runtime state must be written to the project root.`);if(walk.reason==="depth")throw warn(`[project-boundary] Ancestor search exceeded ${MAX_PROJECT_ROOT_DEPTH} levels for "${resolved}" — failing closed`),Error(`Cannot verify project root for "${resolved}" — ancestor search exceeded ${MAX_PROJECT_ROOT_DEPTH} levels`);if(walk.reason==="ancestor-swarm")throw warn(`[project-boundary] Cannot inspect ancestor state "${walk.path}" — failing closed`),Error(`Cannot verify project root for "${resolved}" — ancestor state "${walk.path}" is inaccessible`);throw warn(`[project-boundary] Cannot inspect project indicators in ancestor "${walk.path}" — failing closed`),Error(`Cannot verify project root for "${resolved}" — project indicators in ancestor "${walk.path}" are inaccessible`)}function resolveProjectRootDecision(directory,dependencies=fs8){let resolved;try{resolved=dependencies.realpathSync(directory)}catch{return{kind:"fail-closed",directory,reason:`cannot canonicalize directory "${directory}" — it may not exist or is inaccessible`}}let walk=walkProjectBoundary(resolved,dependencies);if(walk.outcome==="marker-root"||walk.outcome==="unclaimed")return{kind:"root",directory:resolved};if(walk.outcome==="claimed")return{kind:"redirect",directory:resolved,owningRoot:walk.ancestor};let reason=walk.reason==="depth"?`ancestor search exceeded ${MAX_PROJECT_ROOT_DEPTH} levels`:walk.reason==="ancestor-swarm"?`ancestor state "${walk.path}" is inaccessible`:`project indicators in ancestor "${walk.path}" are inaccessible`;return{kind:"fail-closed",directory:resolved,reason}}var MAX_PROJECT_ROOT_DEPTH=20,PROJECT_ROOT_INDICATORS,PROJECT_BOUNDARY_MARKERS,_internals17;var init_project_boundary=__esm(()=>{init_logger();PROJECT_ROOT_INDICATORS=["package.json",".git",".opencode","Cargo.toml","go.mod","pyproject.toml","Gemfile","composer.json","pom.xml","build.gradle","CMakeLists.txt"],PROJECT_BOUNDARY_MARKERS=[{name:".git",accepts:(stat5)=>stat5.isFile()||stat5.isDirectory()},{name:".opencode",accepts:(stat5)=>stat5.isDirectory()}];_internals17={lstatSync:fs8.lstatSync}});function backoffMs(attempt){let base=Math.min(BACKOFF_START_MS*2**attempt,BACKOFF_MAX_MS),jitter=base*BACKOFF_JITTER_RATIO*(Math.random()*2-1);return Math.max(1,Math.round(base+jitter))}async function withEvidenceLock(directory,evidencePath,agent,taskId,fn2,timeoutMs=60000){assertProjectRoot(directory);let deadline=Date.now()+timeoutMs,attempt=0;while(!0){let result=await tryAcquireLock(directory,evidencePath,agent,taskId);if(result.acquired){let lock=result.lock;if(attempt>0)emit("evidence_lock_stale_recovered",{directory,evidencePath,agent,taskId,attempt});emit("evidence_lock_acquired",{directory,evidencePath,agent,taskId,attempt});try{return await fn2()}finally{if(lock._release)try{await lock._release()}catch{}}}if(Date.now()>=deadline)throw new EvidenceLockTimeoutError(directory,evidencePath,agent,taskId,timeoutMs);emit("evidence_lock_contended",{directory,evidencePath,agent,taskId,attempt});let delay=Math.min(backoffMs(attempt),deadline-Date.now());if(delay>0)await new Promise((resolve10)=>setTimeout(resolve10,delay));attempt++}}var EvidenceLockTimeoutError,BACKOFF_START_MS=50,BACKOFF_MAX_MS=2000,BACKOFF_JITTER_RATIO=0.25;var init_lock=__esm(()=>{init_file_locks();init_telemetry();init_project_boundary();EvidenceLockTimeoutError=class EvidenceLockTimeoutError extends Error{directory;evidencePath;agent;taskId;constructor(directory,evidencePath,agent,taskId,timeoutMs){super(`Evidence lock timeout after ${timeoutMs}ms for ${evidencePath} (agent=${agent}, task=${taskId})`);this.name="EvidenceLockTimeoutError",this.directory=directory,this.evidencePath=evidencePath,this.agent=agent,this.taskId=taskId}}});import*as path15 from"node:path";function taskEvidenceRelPath(taskId){return path15.join("evidence",`${taskId}.json`)}function taskEvidencePath(directory,taskId){return path15.join(directory,".swarm",taskEvidenceRelPath(taskId))}async function atomicWriteFile(targetPath,content){await atomicWriteFileAnyRoot(targetPath,content)}function withTaskEvidenceLock(directory,taskId,agent,fn2){return withEvidenceLock(directory,taskEvidenceRelPath(taskId),agent,taskId,fn2)}var init_task_file=__esm(()=>{init_atomic_write();init_lock()});import*as os5 from"node:os";import*as path16 from"node:path";function resolveHiveDataDir(){let platform=process.platform,home=process.env.HOME||os5.homedir();if(platform==="win32")return path16.join(process.env.LOCALAPPDATA||path16.join(home,"AppData","Local"),"opencode-swarm","Data");if(platform==="darwin")return path16.join(home,"Library","Application Support","opencode-swarm");return path16.join(process.env.XDG_DATA_HOME||path16.join(home,".local","share"),"opencode-swarm")}function resolveHiveKnowledgePath(){return path16.join(resolveHiveDataDir(),"shared-learnings.jsonl")}function resolveHiveRejectedPath(){return path16.join(resolveHiveDataDir(),"shared-learnings-rejected.jsonl")}function resolveHiveEventsPath(){return path16.join(resolveHiveDataDir(),"shared-knowledge-events.jsonl")}var init_hive_paths=()=>{};function resolveRetentionCap(name,defaultValue){let override=overrides.get(name);if(override!==void 0&&Number.isFinite(override)&&override>=1)return override;return defaultValue}var overrides;var init_caps=__esm(()=>{overrides=new Map});import*as fs9 from"node:fs";import*as path17 from"node:path";function withFileLock(filePath,task){let key=path17.resolve(filePath),run=(appendChains.get(key)??Promise.resolve()).then(task,task),settled=run.then(()=>{if((appendChains.get(key)??settled)===settled)appendChains.delete(key)},()=>{if((appendChains.get(key)??settled)===settled)appendChains.delete(key)});return appendChains.set(key,settled),run}function sleep2(ms){return new Promise((resolve11)=>setTimeout(resolve11,ms))}async function renameWithRetry2(from,to){let lastError;for(let attempt=1;attempt<=RENAME_MAX_ATTEMPTS;attempt++)try{await fs9.promises.rename(from,to);return}catch(error49){lastError=error49;let code=typeof error49==="object"&&error49!==null&&"code"in error49?String(error49.code):"";if(code!=="EBUSY"&&code!=="EPERM"&&code!=="EEXIST"&&code!=="ENOTEMPTY")throw error49;if(attempt<RENAME_MAX_ATTEMPTS)await sleep2(RENAME_RETRY_DELAY_MS)}throw lastError instanceof Error?lastError:Error(String(lastError))}function wholeLines(content){return content.split(`
|
|
475
475
|
`).map((line)=>line.trim()).filter((line)=>line.length>0)}function selectCompactionSurvivors(lines,opts){let kept=[],keptBytes=0;for(let i=lines.length-1;i>=0;i--){if(kept.length>=opts.maxEntries)break;let line=lines[i],lineBytes=Buffer.byteLength(`${line}
|
|
476
476
|
`,"utf-8");if(kept.length>0&&opts.maxBytes!==void 0&&keptBytes+lineBytes>opts.maxBytes)break;kept.unshift(line),keptBytes+=lineBytes}return kept}async function appendAndCap(filePath,line,opts){let directory=path17.dirname(filePath);fs9.mkdirSync(directory,{recursive:!0});let record2=`${line.trim()}
|
|
477
477
|
`,existing="";try{existing=await fs9.promises.readFile(filePath,"utf-8")}catch{}let combined=[...wholeLines(existing),line.trim()],survivors=selectCompactionSurvivors(combined,opts),dropped=combined.length-survivors.length;if(dropped>0){let compactedLines=combined.slice(dropped,combined.length-1),compacted=compactedLines.length>0?`${compactedLines.join(`
|
|
@@ -1368,7 +1368,7 @@ ${cacheSection2}`;return baseMsg}let lines2=["## Archive Preview (dry run)","",`
|
|
|
1368
1368
|
`);if(failedCount2>0)return`No evidence bundles were archived; ${failedCount2} selected deletion(s) failed and remain on disk.`;if(corruptCount>0)return`No valid evidence bundles were archived. Preserved ${corruptCount} corrupt evaluation artifact(s) for data-quality review.`;if(inventoryCount===0)return"No evidence bundles to archive.";return`No evidence bundles older than ${maxAgeDays} days found.`}let lines=["## Evidence Archived","",`**Retention**: ${maxAgeDays} days`,`**Archived**: ${archivedCount} bundle(s)`,"",...report.archivedEvidence.map((id)=>`- ${id}`),...evaluationArchived.map((id)=>`- ${id}`)],failedCount=report.failedEvidence.length+report.evaluation.failed.length;if(failedCount>0)lines.push("",`**Failed deletions preserved**: ${failedCount}`);let cacheSection=formatDocumentsCacheSection(report.documentsCache,cacheMaxBytes,cacheMaxRecords);if(cacheSection)lines.push(cacheSection);return lines.join(`
|
|
1369
1369
|
`)}var _internals98;var init_archive=__esm(()=>{init_loader();init_manager2();_internals98={now:()=>new Date}});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_state2()});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 path110 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 path110.join("evidence","gate-audit",runId,"ground-truth.jsonl")}function absolutePath(directory,runId){return path110.join(directory,".swarm",relativePath(runId))}function serialize(events){return`${events.map((event)=>canonicalJson2(event)).join(`
|
|
1370
1370
|
`)}
|
|
1371
|
-
`}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(path110.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 fs69 from"node:fs";import*as path111 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=fs69.readFileSync(path111.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 fs70 from"node:fs";import*as fsp9 from"node:fs/promises";import*as os16 from"node:os";import*as path112 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(!isRecord3(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=isRecord3(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=path112.join(directory,".swarm"),files=[path112.join(swarmDir,"telemetry.jsonl.1"),path112.join(swarmDir,"telemetry.jsonl")],tmpDir;try{tmpDir=fs70.mkdtempSync(path112.join(os16.tmpdir(),"telemetry-snapshot-"))}catch{return[{event:"delegation_cost_join",reason:"unreadable"}]}let snapshotFiles=[],telemetryErrors=0;try{for(let file3 of files){if(!fs70.existsSync(file3))continue;let snap=path112.join(tmpDir,path112.basename(file3));try{let stat13=fs70.statSync(file3);if(!stat13.isFile()||stat13.size>MAX_TELEMETRY_FILE_BYTES){telemetryErrors++;continue}fs70.copyFileSync(file3,snap),snapshotFiles.push(snap)}catch{telemetryErrors++}}}catch{telemetryErrors++}let events=[],unreadableSnapshots=0,firstUnreadableReason="";for(let file3 of snapshotFiles){let content="";try{content=fs70.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(isRecord3(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{fs70.unlinkSync(f)}catch{}fs70.rmdirSync(tmpDir)}catch{}if(telemetryErrors>0)events.push({event:"delegation_cost_join",reason:"unreadable"});return events}async function readTelemetryEventsAsync(directory){let swarmDir=path112.join(directory,".swarm"),files=[path112.join(swarmDir,"telemetry.jsonl.1"),path112.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((_,reject)=>{timer=setTimeout(()=>reject(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((_,reject)=>{timer=setTimeout(()=>reject(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(isRecord3(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(!isRecord3(raw))return[];let candidates=[],add=(value,pathName,pinned)=>{if(!isRecord3(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(isRecord3(raw.assistant)&&raw.assistant.role==="assistant")add(raw.assistant,"assistant.cost",!0);if(raw.type==="step-finish")add(raw,"step-finish.cost",!0);if(isRecord3(raw.part)&&raw.part.type==="step-finish")add(raw.part,"step-finish.cost",!0);let data=isRecord3(raw.data)?raw.data:void 0,info=data&&isRecord3(data.info)?data.info:isRecord3(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=isRecord3(raw.output)?raw.output:raw,usageRecord=isRecord3(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=isRecord3(record3.tokens)?record3.tokens:isRecord3(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(!isRecord3(raw))return{...UNKNOWN_USAGE};let output=isRecord3(raw.output)?raw.output:raw,usage=isRecord3(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=isRecord3(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 isRecord3(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.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,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(`
|
|
1371
|
+
`}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(path110.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 fs69 from"node:fs";import*as path111 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=fs69.readFileSync(path111.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 fs70 from"node:fs";import*as fsp9 from"node:fs/promises";import*as os16 from"node:os";import*as path112 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(!isRecord3(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=isRecord3(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=path112.join(directory,".swarm"),files=[path112.join(swarmDir,"telemetry.jsonl.1"),path112.join(swarmDir,"telemetry.jsonl")],tmpDir;try{tmpDir=fs70.mkdtempSync(path112.join(os16.tmpdir(),"telemetry-snapshot-"))}catch{return[{event:"delegation_cost_join",reason:"unreadable"}]}let snapshotFiles=[],telemetryErrors=0;try{for(let file3 of files){if(!fs70.existsSync(file3))continue;let snap=path112.join(tmpDir,path112.basename(file3));try{let stat13=fs70.statSync(file3);if(!stat13.isFile()||stat13.size>MAX_TELEMETRY_FILE_BYTES){telemetryErrors++;continue}fs70.copyFileSync(file3,snap),snapshotFiles.push(snap)}catch{telemetryErrors++}}}catch{telemetryErrors++}let events=[],unreadableSnapshots=0,firstUnreadableReason="";for(let file3 of snapshotFiles){let content="";try{content=fs70.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(isRecord3(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{fs70.unlinkSync(f)}catch{}fs70.rmdirSync(tmpDir)}catch{}if(telemetryErrors>0)events.push({event:"delegation_cost_join",reason:"unreadable"});return events}async function readTelemetryEventsAsync(directory){let swarmDir=path112.join(directory,".swarm"),files=[path112.join(swarmDir,"telemetry.jsonl.1"),path112.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((_,reject)=>{timer=setTimeout(()=>reject(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((_,reject)=>{timer=setTimeout(()=>reject(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(isRecord3(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(!isRecord3(raw))return[];let candidates=[],add=(value,pathName,pinned)=>{if(!isRecord3(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(isRecord3(raw.assistant)&&raw.assistant.role==="assistant")add(raw.assistant,"assistant.cost",!0);if(raw.type==="step-finish")add(raw,"step-finish.cost",!0);if(isRecord3(raw.part)&&raw.part.type==="step-finish")add(raw.part,"step-finish.cost",!0);let data=isRecord3(raw.data)?raw.data:void 0,info=data&&isRecord3(data.info)?data.info:isRecord3(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=isRecord3(raw.output)?raw.output:raw,usageRecord=isRecord3(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=isRecord3(record3.tokens)?record3.tokens:isRecord3(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(!isRecord3(raw))return{...UNKNOWN_USAGE};let output=isRecord3(raw.output)?raw.output:raw,usage=isRecord3(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=isRecord3(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 isRecord3(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(`
|
|
1372
1372
|
`);if(ciGate&&!ciGate.passed)return{text:output,ok:!1,exitCode:1};return output}function parseMaxCostUsd(args2){let index=args2.indexOf("--max-cost-usd");if(index===-1)return null;let raw=args2[index+1];if(!raw||raw.startsWith("--"))throw Error("Invalid --max-cost-usd value: expected a non-negative number.");let parsed=Number(raw);if(!Number.isFinite(parsed)||parsed<0)throw Error("Invalid --max-cost-usd value: expected a non-negative number.");return parsed}function parseGateAuditRunId(args2){let index=args2.indexOf("--gate-audit-run");if(index===-1)return null;let value=args2[index+1];if(!value||!/^[A-Za-z0-9][A-Za-z0-9._-]{0,159}$/.test(value))throw Error("Invalid --gate-audit-run value: expected a safe run id.");return value}var CI,GATE_AUDIT_MIN_SAMPLES=6;var init_benchmark=__esm(()=>{init_quality_checks();init_gate_stats();init_store();init_cost_accounting();init_state2();CI=CI_QUALITY_THRESHOLDS});function sanitizeTopic(raw){let normalized=raw.replace(/\s+/g," ").trim().replace(/\[\s*MODE\s*:[^\]]*\]/gi,"").replace(/\s+/g," ").trim(),MAX_TOPIC_LEN=2000;if(normalized.length<=2000)return normalized;return`${normalized.slice(0,2000)}…`}async function handleBrainstormCommand(_directory2,args2){let description=sanitizeTopic(args2.join(" "));if(description)return`[MODE: BRAINSTORM] ${description}`;return"[MODE: BRAINSTORM] Please enter MODE: BRAINSTORM and begin the structured brainstorm workflow (CONTEXT SCAN → DIALOGUE → APPROACHES → DESIGN SECTIONS → SPEC WRITE + SELF-REVIEW → QA GATE SELECTION → TRANSITION)."}function safeParseResult(result){let jsonStr=typeof result==="string"?result:result.output,parsed=CheckpointResultSchema.safeParse(JSON.parse(jsonStr));if(!parsed.success)return{success:!1,error:`Invalid response: ${parsed.error.message}`};return parsed.data}async function handleCheckpointCommand(directory,args2){let subcommand=args2[0]||"list",label=args2[1];switch(subcommand){case"save":return handleSave2(directory,label);case"restore":return handleRestore2(directory,label);case"delete":return handleDelete2(directory,label);default:return handleList2(directory)}}async function handleSave2(directory,label){if(!label)return"Error: Label required. Usage: `/swarm checkpoint save <label>`";try{let result=await checkpoint.execute({action:"save",label},{directory}),parsed=safeParseResult(result);if(parsed.success)return`✓ Checkpoint saved: "${label}"`;else return`Error: ${parsed.error||"Failed to save checkpoint"}`}catch(error93){return`Error: ${error93 instanceof Error?error93.message:String(error93)}`}}async function handleRestore2(directory,label){if(!label)return"Error: Label required. Usage: `/swarm checkpoint restore <label>`";try{let result=await checkpoint.execute({action:"restore",label},{directory}),parsed=safeParseResult(result);if(parsed.success)return`✓ Restored to checkpoint: "${label}"`;else return`Error: ${parsed.error||"Failed to restore checkpoint"}`}catch(error93){return`Error: ${error93 instanceof Error?error93.message:String(error93)}`}}async function handleDelete2(directory,label){if(!label)return"Error: Label required. Usage: `/swarm checkpoint delete <label>`";try{let result=await checkpoint.execute({action:"delete",label},{directory}),parsed=safeParseResult(result);if(parsed.success)return`✓ Checkpoint deleted: "${label}"`;else return`Error: ${parsed.error||"Failed to delete checkpoint"}`}catch(error93){return`Error: ${error93 instanceof Error?error93.message:String(error93)}`}}async function handleList2(directory){try{let result=await checkpoint.execute({action:"list"},{directory}),parsed=safeParseResult(result);if(!parsed.success)return`Error: ${parsed.error||"Failed to list checkpoints"}`;let checkpoints=parsed.checkpoints||[];if(checkpoints.length===0)return"No checkpoints found. Create one with `/swarm checkpoint save <label>`";return["## Checkpoints","",...checkpoints.map((c)=>`- "${c.label}" — ${new Date(c.timestamp).toLocaleString()}`),"","Commands:","- `/swarm checkpoint save <label>` — Create checkpoint","- `/swarm checkpoint restore <label>` — Restore checkpoint","- `/swarm checkpoint delete <label>` — Delete checkpoint"].join(`
|
|
1373
1373
|
`)}catch(error93){return`Error: ${error93 instanceof Error?error93.message:String(error93)}`}}var CheckpointResultSchema;var init_checkpoint2=__esm(()=>{init_zod();init_checkpoint();CheckpointResultSchema=exports_external.object({action:exports_external.string().optional(),success:exports_external.boolean(),error:exports_external.string().optional(),checkpoints:exports_external.array(exports_external.unknown()).optional()}).passthrough()});import*as fs71 from"node:fs";import*as os17 from"node:os";import*as path113 from"node:path";function countStatuses(rows){let counts={pass:0,fail:0,no_data:0,corrupt:0,error:0};for(let row of rows)counts[row.status]++;return counts}function removeShadowRoot(shadowRoot){try{fs71.rmSync(shadowRoot,{recursive:!0,force:!0})}catch{}}function copyFileBounded(source,destination,remainingBytes){let sourceFd,destinationFd,copiedBytes=0;try{sourceFd=fs71.openSync(source,"r"),destinationFd=fs71.openSync(destination,"w");let buffer=Buffer.allocUnsafe(Math.min(SHADOW_COPY_CHUNK_BYTES,remainingBytes+1));while(!0){let bytesRead=fs71.readSync(sourceFd,buffer,0,buffer.length,null);if(bytesRead===0)return copiedBytes;if(bytesRead>remainingBytes-copiedBytes)return null;let written=0;while(written<bytesRead){let bytesWritten=fs71.writeSync(destinationFd,buffer,written,bytesRead-written);if(bytesWritten<=0)throw Error("shadow-copy write made no progress");written+=bytesWritten}copiedBytes+=bytesRead}}finally{if(invalidateCachedArtifact(destination),destinationFd!==void 0)try{fs71.closeSync(destinationFd)}catch{}if(sourceFd!==void 0)try{fs71.closeSync(sourceFd)}catch{}}}function isClosedDirectoryError(error93){return typeof error93==="object"&&error93!==null&&"code"in error93&&error93.code==="ERR_DIR_CLOSED"}function createShadowCopy(directory,maxBytes=MAX_SHADOW_COPY_BYTES){let swarmDir=path113.join(directory,".swarm");if(!fs71.existsSync(swarmDir))return null;let total=0,entriesSeen=0,files=[],budgetExceeded=!1,walk=(dir)=>{let directoryHandle,traversalError,closeError;try{directoryHandle=fs71.opendirSync(dir);while(!0){let entry=directoryHandle.readSync();if(entry===null)break;if(entriesSeen++,entriesSeen>MAX_SHADOW_COPY_ENTRIES){budgetExceeded=!0;break}let src=path113.join(dir,entry.name);if(entry.isDirectory()){if(walk(src),budgetExceeded)break;continue}if(!entry.isFile())continue;let size=fs71.statSync(src).size;if(total+=size,total>maxBytes){budgetExceeded=!0;break}files.push(src)}}catch(error93){throw traversalError=error93,error93}finally{if(directoryHandle!==void 0)try{directoryHandle.closeSync()}catch(error93){if(!isClosedDirectoryError(error93)&&traversalError===void 0)closeError=error93}}if(closeError!==void 0)throw closeError};if(walk(swarmDir),budgetExceeded)return null;let shadowRoot=fs71.mkdtempSync(path113.join(os17.tmpdir(),"swarm-ci-shadow-"));try{let shadowSwarm=path113.join(shadowRoot,".swarm");fs71.mkdirSync(shadowSwarm,{recursive:!0});let copiedBytes=0;for(let src of files){let rel=path113.relative(directory,src),dest=path113.join(shadowRoot,rel);fs71.mkdirSync(path113.dirname(dest),{recursive:!0});let copied=_internals99.copyFileBounded(src,dest,maxBytes-copiedBytes);if(copied===null)return removeShadowRoot(shadowRoot),null;copiedBytes+=copied}return shadowRoot}catch(error93){throw removeShadowRoot(shadowRoot),error93}}async function evaluateAdvisoryCi(options){let{directory,tty}=options,journal=options.journal??(()=>{}),externalRegisterCleanup=options.registerCleanup,directShadowCleanup,directShadowCleanups=[],registerCleanup=(fn2)=>{if(externalRegisterCleanup)externalRegisterCleanup(fn2);else directShadowCleanups.push(fn2),directShadowCleanup??=()=>{for(let cleanup of directShadowCleanups.splice(0))try{cleanup()}catch{}}},gates=[],tasks=[],planPath=path113.join(directory,".swarm","plan.json"),planExists=fs71.existsSync(planPath),plan=planExists?await loadPlanJsonOnly(directory):null;if(planExists&&!plan)return gates.push({name:"plan",status:"corrupt",detail:".swarm/plan.json exists but failed schema validation"}),finishReport({gates,tasks,planMeta:{present:!0,task_count:0},tty,exit_reason:"plan_corrupt",effectiveGates:{...DEFAULT_QA_GATES},gateProfile:"default"});if(!plan)return gates.push({name:"plan",status:"no_data",detail:".swarm/plan.json is missing — nothing to evaluate is not a pass"}),finishReport({gates,tasks,planMeta:{present:!1,task_count:0},tty,exit_reason:"plan_missing",effectiveGates:{...DEFAULT_QA_GATES},gateProfile:"default"});let planLike=plan,planTasks=[];for(let phase of planLike.phases??[])for(let task of phase.tasks??[])planTasks.push(task);if(journal("plan_loaded",`${planTasks.length} tasks`),planTasks.length===0)return gates.push({name:"plan",status:"pass"}),gates.push({name:"plan tasks",status:"no_data",detail:"plan contains no tasks — nothing demonstrably gated"}),finishReport({gates,tasks,planMeta:{present:!0,title:planLike.title,swarm:planLike.swarm,task_count:0},tty,exit_reason:"no_tasks",effectiveGates:{...DEFAULT_QA_GATES},gateProfile:"default"});let shadowDir=null;try{shadowDir=createShadowCopy(directory)}catch{shadowDir=null}if(shadowDir){let cleanupShadow=()=>{try{closeProjectDb(shadowDir)}finally{removeShadowRoot(shadowDir)}};try{registerCleanup(cleanupShadow)}catch(error93){try{cleanupShadow()}catch{}throw error93}}try{let identity={swarm:planLike.swarm??"local",title:planLike.title??""},effectiveGates={...DEFAULT_QA_GATES},gateProfile="default";if(shadowDir){let lookup=getProfileLookupForIdentity(shadowDir,identity);if(lookup&&"profile"in lookup&&lookup.profile)effectiveGates=getEffectiveGates(lookup.profile,{}),gateProfile="profile"}if(journal("gate_profile",gateProfile),gates.push({name:"plan",status:"pass"}),effectiveGates.critic_pre_plan)if(shadowDir){let approved=await isPlanCriticApproved(shadowDir);gates.push({name:"plan_critic",status:approved?"pass":"fail",detail:approved?"plan-critic APPROVED snapshot matches the current plan structure":"no plan_critic_gate APPROVED snapshot matching the current plan (critic_pre_plan is enabled)"})}else gates.push({name:"plan_critic",status:"error",detail:"ledger snapshot read unavailable: durable state exceeds the shadow-copy budget"});for(let task of planTasks)try{let state2=await readTaskEvidenceState(directory,task.id);if(state2.kind==="ok"){let evidence2=state2.evidence,required3=[...evidence2.required_gates],satisfiedKeys=Object.keys(evidence2.gates??{}),missing=required3.filter((g)=>!satisfiedKeys.includes(g)),workflowState=evidence2.workflow?.state,terminal=TERMINAL_SUCCESS_STATES.includes(workflowState),satisfied=missing.length===0&&terminal;tasks.push({task_id:task.id,evidence_state:"valid",required_gates:required3,missing_gates:missing,workflow_state:workflowState,satisfied}),gates.push({name:`task ${task.id} gates`,status:satisfied?"pass":"fail",detail:satisfied?`all required gates satisfied; workflow ${workflowState}`:missing.length>0?`missing gate evidence: ${missing.join(", ")}${terminal?"":`; workflow state ${workflowState} is not terminal`}`:`workflow state ${workflowState} is not a terminal-success state`})}else if(state2.kind==="missing"){let required3=deriveRequiredGates("coder");tasks.push({task_id:task.id,evidence_state:"missing",required_gates:required3,missing_gates:[...required3],satisfied:!1}),gates.push({name:`task ${task.id} gates`,status:"no_data",detail:"no durable task-gate evidence recorded"})}else if(state2.kind==="unparseable"){let required3=deriveRequiredGates("coder");tasks.push({task_id:task.id,evidence_state:"corrupt",required_gates:required3,missing_gates:[...required3],satisfied:!1}),gates.push({name:`task ${task.id} gates`,status:"corrupt",detail:"task-gate evidence exists but cannot be parsed (#2470 tri-state)"})}else tasks.push({task_id:task.id,evidence_state:"error",required_gates:deriveRequiredGates("coder"),missing_gates:deriveRequiredGates("coder"),satisfied:!1}),gates.push({name:`task ${task.id} gates`,status:"error",detail:`evidence reader returned unexpected state ${JSON.stringify(state2.kind)}`})}catch(error93){tasks.push({task_id:task.id,evidence_state:"error",required_gates:deriveRequiredGates("coder"),missing_gates:deriveRequiredGates("coder"),satisfied:!1}),gates.push({name:`task ${task.id} gates`,status:"error",detail:error93 instanceof Error?error93.message:String(error93)})}let summary=await _internals99.computeEvidenceQualitySummary(directory),q=summary.qualityMetrics,qualityRows=[["review_pass_rate",summary.reviewPassRate===null?null:summary.reviewPassRate>=CI_QUALITY_THRESHOLDS.review_pass_rate,summary.reviewPassRate,`>= ${CI_QUALITY_THRESHOLDS.review_pass_rate}% over ${summary.totalReviews} reviews`],["test_pass_rate",summary.testPassRate===null?null:summary.testPassRate>=CI_QUALITY_THRESHOLDS.test_pass_rate,summary.testPassRate,`>= ${CI_QUALITY_THRESHOLDS.test_pass_rate}% over ${summary.testsPassed+summary.testsFailed} tests`],["quality_budget.complexity_delta",q.hasEvidence?q.complexityDelta<=CI_QUALITY_THRESHOLDS.max_complexity_delta:null,q.hasEvidence?q.complexityDelta:null,`<= ${CI_QUALITY_THRESHOLDS.max_complexity_delta}`],["quality_budget.public_api_delta",q.hasEvidence?q.publicApiDelta<=CI_QUALITY_THRESHOLDS.max_public_api_delta:null,q.hasEvidence?q.publicApiDelta:null,`<= ${CI_QUALITY_THRESHOLDS.max_public_api_delta}`],["quality_budget.duplication_ratio",q.hasEvidence?q.duplicationRatio<=CI_QUALITY_THRESHOLDS.max_duplication_ratio:null,q.hasEvidence?q.duplicationRatio:null,`<= ${CI_QUALITY_THRESHOLDS.max_duplication_ratio}%`],["quality_budget.test_to_code_ratio",q.hasEvidence?q.testToCodeRatio>=CI_QUALITY_THRESHOLDS.min_test_to_code_ratio:null,q.hasEvidence?q.testToCodeRatio:null,`>= ${CI_QUALITY_THRESHOLDS.min_test_to_code_ratio}%`]];for(let[name,passed,value,threshold]of qualityRows)gates.push({name,status:passed===null?"no_data":passed?"pass":"fail",detail:passed===null?`no evidence data (${threshold}); not a pass`:`value ${value} ${threshold}`});return finishReport({gates,tasks,planMeta:{present:!0,title:planLike.title,swarm:planLike.swarm,task_count:planTasks.length},tty,exit_reason:"gate_violations",effectiveGates,gateProfile})}finally{directShadowCleanup?.()}}function finishReport(args2){let counts=countStatuses(args2.gates),allPassed=args2.gates.length>0&&counts.pass===args2.gates.length,verdict=allPassed?"pass":"fail",exit_reason=allPassed?"all_gates_passed":args2.exit_reason,not_evaluated=[];for(let[flag,reason]of Object.entries(NOT_EVALUATED_REASONS))if(args2.effectiveGates[flag])not_evaluated.push({name:flag,reason});return{version:1,verdict,exit_reason,gates:args2.gates,tasks:args2.tasks,plan:args2.planMeta,environment:{mode:"advisory",tty:args2.tty,host:"none"},gate_profile:args2.gateProfile,effective_gates:args2.effectiveGates,not_evaluated,not_evaluable:[...NOT_EVALUABLE],counts}}var TERMINAL_SUCCESS_STATES,MAX_SHADOW_COPY_BYTES=536870912,MAX_SHADOW_COPY_ENTRIES=1e5,SHADOW_COPY_CHUNK_BYTES=65536,_internals99,NOT_EVALUABLE,NOT_EVALUATED_REASONS;var init_evaluate=__esm(()=>{init_project_db();init_qa_gate_profile();init_gate_evidence();init_delegation_gate();init_manager();init_swarm_artifact_cache();init_quality_checks();TERMINAL_SUCCESS_STATES=["complete","closed"];_internals99={computeEvidenceQualitySummary,copyFileBounded,createShadowCopy},NOT_EVALUABLE=[{name:"agent_error_rate",reason:"requires the plugin live in-process tool-aggregate state; not reconstructible headless"},{name:"hard_limit_hits",reason:"requires the plugin live in-process agent-session state; not reconstructible headless"}],NOT_EVALUATED_REASONS={drift_check:"enforced inline by the write-drift-evidence flow; no standalone durable whole-plan reader",sast_enabled:"recorded per-task in evidence bundles; not a whole-plan gate row",sme_enabled:"advisory SME pass has no durable whole-plan verdict artifact",council_mode:"council gating is per-task through checkCouncilGate at completion time",mutation_test:"mutation gate runs in the evolution harness, not the advisory path",phase_council:"phase councils run interactively; no durable whole-plan verdict",final_council:"final council runs interactively; no durable whole-plan verdict",hallucination_guard:"stream-time guard; no durable whole-plan verdict artifact"}});function mdCell(text){return text.replace(/[\r\n]+/g," ").replace(/\|/g,"\\|")}function renderJsonBlock(report){return["[SWARM_CI_JSON]",JSON.stringify(report,null,2),"[/SWARM_CI_JSON]"].join(`
|
|
1374
1374
|
`)}function renderMarkdownReport(report){let lines=["## Swarm CI Advisory Report","",`Verdict: ${report.verdict==="pass"?"✅ PASS":"❌ FAIL"} (exit_reason: ${report.exit_reason})`,`Environment: mode=${report.environment.mode} tty=${report.environment.tty} host=${report.environment.host} gate_profile=${report.gate_profile}`,"","### Gates","","| Gate | Status | Detail |","|------|--------|--------|"];for(let gate of report.gates){let icon=STATUS_ICONS[gate.status]??"",detail=mdCell(gate.detail??"");lines.push(`| ${mdCell(gate.name)} | ${icon} ${gate.status} | ${detail} |`)}if(report.tasks.length>0){lines.push("","### Tasks",""),lines.push("| Task | Evidence state | Required gates | Missing gates | Workflow | Satisfied |","|------|----------------|----------------|---------------|----------|-----------|");for(let task of report.tasks)lines.push(`| ${mdCell(task.task_id)} | ${task.evidence_state} | ${task.required_gates.map(mdCell).join(", ")||"-"} | ${task.missing_gates.map(mdCell).join(", ")||"-"} | ${task.workflow_state?mdCell(task.workflow_state):"-"} | ${task.satisfied?"✅":"❌"} |`)}if(report.not_evaluated.length>0){lines.push("","### Enabled gates not evaluated (reported, never passed)","");for(let item of report.not_evaluated)lines.push(`- ${mdCell(item.name)}: ${mdCell(item.reason)}`)}if(report.not_evaluable.length>0){lines.push("","### Not evaluable headless","");for(let item of report.not_evaluable)lines.push(`- ${mdCell(item.name)}: ${mdCell(item.reason)}`)}return lines.push("",`Counts: ${report.counts.pass} pass, ${report.counts.fail} fail, ${report.counts.no_data} no_data, ${report.counts.corrupt} corrupt, ${report.counts.error} error`,"","Advisory read-only evaluation: this run cannot satisfy, bypass, or modify any gate."),lines.join(`
|
|
@@ -2358,7 +2358,7 @@ Flags:
|
|
|
2358
2358
|
`)}}var init_consolidate=__esm(()=>{init_config();init_schema();init_skill_consolidation()});async function handleContextMapStatsCommand(directory){let summary=getTelemetrySummary(directory);if(summary.total_delegations===0&&summary.corrupt_entries===0)return"No capsule telemetry recorded.";let pct=(n,d)=>d===0?"N/A":`${(n/d*100).toFixed(1)}%`,lines=["# Context-map capsule telemetry","",`**Total delegations:** ${summary.total_delegations}`,`**Cache hits:** ${summary.total_cache_hits} (${pct(summary.total_cache_hits,summary.total_cache_hits+summary.total_cache_misses)} hit rate)`,`**Cache misses:** ${summary.total_cache_misses}`,`**Stale entries detected:** ${summary.total_stale_entries}`,`**Avg token estimate:** ${summary.avg_token_estimate.toFixed(1)} tokens/capsule`,`**Success rate:** ${summary.success_rate.toFixed(1)}%`,`**Recommended reads:** ${summary.total_recommended_reads}`,`**Skipped reads:** ${summary.total_skipped_reads}`];if(summary.coverage==="partial-unmigrated")lines.push("","> Historical context telemetry spans more than the documented read bound and is being migrated in bounded passes; totals above cover only the part already accounted. Run `/swarm context-map stats` again after the store settles for the full lifetime figure.");if(summary.dropped_entries>0)lines.push(`**Dropped (age-pruned raw records, totals unaffected):** ${summary.dropped_entries}`);if(summary.corrupt_entries>0)lines.push(`**Corrupt/partial lines skipped (diagnostics only):** ${summary.corrupt_entries}`);return lines.join(`
|
|
2359
2359
|
`)}var init_context_map_stats=__esm(()=>{init_telemetry2()});async function handleCostsCommand(directory,args2){let summary=summarizeTelemetryCosts(directory);if(args2.includes("--json"))return["[COSTS_JSON]",JSON.stringify(summary,null,2),"[/COSTS_JSON]"].join(`
|
|
2360
2360
|
`);return renderCostSummary(summary)}function renderCostSummary(summary){let lines=["## Swarm Costs","",`Total tracked cost: ${formatUsd(summary.total_cost_usd)}`,`Delegations: ${summary.delegations}`,`Tokens: input ${formatTokens(summary.total_input_tokens)}, output ${formatTokens(summary.total_output_tokens)}, reasoning ${formatTokens(summary.total_reasoning_tokens)}, cache ${formatTokens(summary.total_cache_tokens)}`,`Unknown usage: ${summary.unknown_usage_delegations}`,`Cost source: reported ${formatUsd(summary.total_reported_usd)}, estimated ${formatUsd(summary.total_estimated_usd)}, unavailable ${summary.unavailable_delegations}`,`Evidence: ${summary.evidence_status}; joins missed ${summary.join_miss_count}; telemetry errors ${summary.telemetry_error_count}; corrections accepted ${summary.accepted_corrections}, rejected ${summary.rejected_corrections}, duplicate ${summary.duplicate_corrections}`,"","### By Agent"];return appendCostRows(lines,"Agent",summary.by_agent,"No delegation cost telemetry recorded."),lines.push("","### By Task"),appendCostRows(lines,"Task",summary.by_task,"No task cost telemetry recorded."),lines.push("","### By Gate"),appendCostRows(lines,"Gate",summary.by_gate,"No gate cost telemetry recorded."),lines.push("","### By Retry Loop"),appendCostRows(lines,"Retry",summary.by_retry,"No retry-loop cost telemetry recorded."),lines.join(`
|
|
2361
|
-
`)}function appendCostRows(lines,label,rows,emptyMessage){if(rows.length===0){lines.push(emptyMessage);return}lines.push(`| ${label} | Delegations | Cost | Input | Output | Reasoning | Cache | Unavailable |`,"|------|-------------|------|-------|--------|-----------|-------|-------------|");for(let row of rows)lines.push(`| ${row.name} | ${row.delegations} | ${formatUsd(row.cost_usd)} | ${formatTokens(row.input_tokens)} | ${formatTokens(row.output_tokens)} | ${formatTokens(row.reasoning_tokens)} | ${formatTokens(row.cache_tokens)} | ${row.unavailable_delegations} |`)}function formatTokens(value){return value===null?"unknown":value.toLocaleString()}function formatUsd(value){return`$${value.toFixed(6)}`}var init_costs=__esm(()=>{init_cost_accounting()});function sanitizeQuestion(raw){let normalized=raw.replace(/\s+/g," ").trim().replace(/\[\s*MODE\s*:[^\]]*\]/gi,"").replace(/\s+/g," ").trim();if(normalized.length<=2000)return normalized;return`${normalized.slice(0,2000)}…`}function sanitizePresetName(raw){let trimmed=raw.trim();if(!trimmed)return null;if(trimmed.length>64)return null;if(!/^[A-Za-z0-9_-]+$/.test(trimmed))return null;return trimmed}function parseArgs2(args2){let out={specReview:!1,rest:[]};for(let i=0;i<args2.length;i++){let token=args2[i];if(token==="--spec-review"){out.specReview=!0;continue}if(token==="--preset"){let next=args2[i+1];if(next!==void 0){let sanitized=sanitizePresetName(next);if(sanitized)out.preset=sanitized;i++}continue}out.rest.push(token)}return out}async function handleCouncilCommand(_directory2,args2){let parsed=parseArgs2(args2),question=sanitizeQuestion(parsed.rest.join(" "));if(!question)return USAGE6;let tokens2=["MODE: COUNCIL"];if(parsed.preset)tokens2.push(`preset=${parsed.preset}`);if(parsed.specReview)tokens2.push("spec_review");return`[${tokens2.join(" ")}] ${question}`}var USAGE6;var init_council=__esm(()=>{USAGE6=["Usage: /swarm council <question> [--spec-review]",""," question The question to put to the council"," --spec-review Use spec_review mode (single advisory pass on a draft spec)","","Requires council.general.enabled: true and a configured search API key in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides."].join(`
|
|
2361
|
+
`)}function appendCostRows(lines,label,rows,emptyMessage){if(rows.length===0){lines.push(emptyMessage);return}lines.push(`| ${label} | Delegations | Cost | Input | Output | Reasoning | Cache | Unavailable |`,"|------|-------------|------|-------|--------|-----------|-------|-------------|");for(let row of rows)lines.push(`| ${sanitizeTableCell(row.name)} | ${row.delegations} | ${formatUsd(row.cost_usd)} | ${formatTokens(row.input_tokens)} | ${formatTokens(row.output_tokens)} | ${formatTokens(row.reasoning_tokens)} | ${formatTokens(row.cache_tokens)} | ${row.unavailable_delegations} |`)}function formatTokens(value){return value===null?"unknown":value.toLocaleString("en-US")}function sanitizeTableCell(value){return value.replace(/\|/g,"\\|").replace(/[\r\n]+/g," ")}function formatUsd(value){return`$${value.toFixed(6)}`}var init_costs=__esm(()=>{init_cost_accounting()});function sanitizeQuestion(raw){let normalized=raw.replace(/\s+/g," ").trim().replace(/\[\s*MODE\s*:[^\]]*\]/gi,"").replace(/\s+/g," ").trim();if(normalized.length<=2000)return normalized;return`${normalized.slice(0,2000)}…`}function sanitizePresetName(raw){let trimmed=raw.trim();if(!trimmed)return null;if(trimmed.length>64)return null;if(!/^[A-Za-z0-9_-]+$/.test(trimmed))return null;return trimmed}function parseArgs2(args2){let out={specReview:!1,rest:[]};for(let i=0;i<args2.length;i++){let token=args2[i];if(token==="--spec-review"){out.specReview=!0;continue}if(token==="--preset"){let next=args2[i+1];if(next!==void 0){let sanitized=sanitizePresetName(next);if(sanitized)out.preset=sanitized;i++}continue}out.rest.push(token)}return out}async function handleCouncilCommand(_directory2,args2){let parsed=parseArgs2(args2),question=sanitizeQuestion(parsed.rest.join(" "));if(!question)return USAGE6;let tokens2=["MODE: COUNCIL"];if(parsed.preset)tokens2.push(`preset=${parsed.preset}`);if(parsed.specReview)tokens2.push("spec_review");return`[${tokens2.join(" ")}] ${question}`}var USAGE6;var init_council=__esm(()=>{USAGE6=["Usage: /swarm council <question> [--spec-review]",""," question The question to put to the council"," --spec-review Use spec_review mode (single advisory pass on a draft spec)","","Requires council.general.enabled: true and a configured search API key in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides."].join(`
|
|
2362
2362
|
`)});import*as child_process6 from"node:child_process";import{randomUUID as randomUUID27}from"node:crypto";import{readdir as readdir10,readFile as readFile39,stat as stat16}from"node:fs/promises";import*as path168 from"node:path";import{promisify}from"node:util";function getExecFileAsync(){return promisify(child_process6.execFile)}async function parseGitLog(directory,maxCommits){let commitMap=new Map;try{let{stdout}=await _internals135.getExecFileAsync()(resolveGitExecutable(),["log","--name-only","--pretty=format:COMMIT:%H","--no-merges",`-n${maxCommits}`],{cwd:directory,timeout:1e4}),currentCommit=null;for(let line of stdout.split(`
|
|
2363
2363
|
`))if(line.startsWith("COMMIT:")){if(currentCommit=line.slice(7),currentCommit&&!commitMap.has(currentCommit))commitMap.set(currentCommit,new Set)}else if(currentCommit&&line.trim()){let filePath=line.trim();if(filePath.startsWith(".swarm/")||filePath.startsWith("node_modules/")||filePath==="")continue;commitMap.get(currentCommit).add(filePath)}}catch{return new Map}return commitMap}function buildCoChangeMatrix(commitMap,maxFilesPerCommit=500){let matrix=new Map,fileCommitCount=new Map;for(let files of commitMap.values()){for(let file3 of files)fileCommitCount.set(file3,(fileCommitCount.get(file3)||0)+1);if(files.size>maxFilesPerCommit)continue;let fileArray=Array.from(files).sort();for(let i=0;i<fileArray.length;i++)for(let j=i+1;j<fileArray.length;j++){let fileA=fileArray[i],fileB=fileArray[j],[key2,a,b]=fileA<fileB?[`${fileA}::${fileB}`,fileA,fileB]:[`${fileB}::${fileA}`,fileB,fileA],existing=matrix.get(key2);if(existing)existing.coChangeCount++;else matrix.set(key2,{fileA:a,fileB:b,coChangeCount:1,npmi:0,lift:0,hasStaticEdge:!1,totalCommits:0,commitsA:0,commitsB:0})}}let totalCommits=commitMap.size;for(let entry of matrix.values()){if(entry.coChangeCount<3)continue;let pAB=entry.coChangeCount/totalCommits,pA=(fileCommitCount.get(entry.fileA)||0)/totalCommits,pB=(fileCommitCount.get(entry.fileB)||0)/totalCommits;if(entry.commitsA=fileCommitCount.get(entry.fileA)||0,entry.commitsB=fileCommitCount.get(entry.fileB)||0,entry.totalCommits=totalCommits,pA>0&&pB>0)entry.lift=pAB/(pA*pB);if(pAB>0){let logPAB=Math.log(pAB),negLogPAB=-logPAB;if(negLogPAB>0){let numerator=logPAB-Math.log(pA*pB);entry.npmi=numerator/negLogPAB,entry.npmi=Math.max(-1,Math.min(1,entry.npmi))}else entry.npmi=1}}return matrix}async function scanSourceFiles(dir){let results=[],skipDirs=new Set(["node_modules",".swarm","dist","build"]);try{let entries2=await readdir10(dir,{withFileTypes:!0});for(let entry of entries2){let fullPath=path168.join(dir,entry.name);if(entry.isDirectory()){if(skipDirs.has(entry.name))continue;let subFiles=await scanSourceFiles(fullPath);results.push(...subFiles)}else if(entry.isFile()){let ext=path168.extname(entry.name);if([".ts",".tsx",".js",".jsx",".mjs"].includes(ext))results.push(fullPath)}}}catch{}return results}async function getStaticEdges(directory){let edges=new Set,sourceFiles=await scanSourceFiles(directory);for(let sourceFile of sourceFiles)try{let content=await readFile39(sourceFile,"utf-8"),importRegex=/(?:import|require)\s*(?:\(?\s*['"`]|.*?from\s+['"`])([^'"`]+)['"`]/g;for(let match=importRegex.exec(content);match!==null;match=importRegex.exec(content)){let importPath=match[1].trim();if(!importPath.startsWith("."))continue;try{let sourceDir=path168.dirname(sourceFile),resolvedPath=path168.resolve(sourceDir,importPath),extensions=["",".ts",".tsx",".js",".jsx",".mjs","/index.ts","/index.js"],targetFile=null;for(let ext of extensions){let testPath=resolvedPath+ext;try{if((await stat16(testPath)).isFile()){targetFile=testPath;break}}catch{}}if(!targetFile)continue;let relSource=path168.relative(directory,sourceFile).replace(/\\/g,"/"),relTarget=path168.relative(directory,targetFile).replace(/\\/g,"/"),[key2]=relSource<relTarget?[`${relSource}::${relTarget}`,relSource,relTarget]:[`${relTarget}::${relSource}`,relTarget,relSource];edges.add(key2)}catch{}}}catch{}return edges}function isTestImplementationPair(fileA,fileB){let testPatterns=[".test.ts",".test.js",".spec.ts",".spec.js"],getBaseName=(filePath)=>{let base=path168.basename(filePath);for(let pattern of testPatterns)if(base.endsWith(pattern))return base.slice(0,-pattern.length);return base.replace(/\.(ts|js|tsx|jsx|mjs)$/,"")},baseA=getBaseName(fileA),baseB=getBaseName(fileB);return baseA===baseB&&baseA!==path168.basename(fileA)&&baseA!==path168.basename(fileB)}function hasSharedPrefix(fileA,fileB){let dirA=path168.dirname(fileA),dirB=path168.dirname(fileB);if(dirA!==dirB)return!1;let baseA=path168.basename(fileA).replace(/\.(ts|js|tsx|jsx|mjs)$/,""),baseB=path168.basename(fileB).replace(/\.(ts|js|tsx|jsx|mjs)$/,"");if(baseA.startsWith(baseB)||baseB.startsWith(baseA))return!0;let splitA=baseA.split(/-|_/),splitB=baseB.split(/-|_/);if(splitA.length>0&&splitB.length>0&&splitA[0]===splitB[0])return!0;return!1}async function detectDarkMatter(directory,options){let minCommits=options?.minCommits??20,minCoChanges=options?.minCoChanges??3,npmiThreshold=options?.npmiThreshold??0.5,maxCommitsToAnalyze=options?.maxCommitsToAnalyze??500,maxFilesPerCommit=options?.maxFilesPerCommit??500;try{let{stdout}=await _internals135.getExecFileAsync()(resolveGitExecutable(),["rev-list","--count","HEAD"],{cwd:directory,timeout:1e4}),totalCommitCount=parseInt(stdout.trim(),10);if(Number.isNaN(totalCommitCount)||totalCommitCount<minCommits)return[]}catch{return[]}let commitMap=await _internals135.parseGitLog(directory,maxCommitsToAnalyze),matrix=_internals135.buildCoChangeMatrix(commitMap,maxFilesPerCommit),staticEdges=await _internals135.getStaticEdges(directory),results=[];for(let entry of matrix.values()){let key2=`${entry.fileA}::${entry.fileB}`;if(entry.hasStaticEdge=staticEdges.has(key2),entry.coChangeCount<minCoChanges)continue;if(entry.npmi<npmiThreshold)continue;if(entry.hasStaticEdge)continue;if(isTestImplementationPair(entry.fileA,entry.fileB))continue;if(hasSharedPrefix(entry.fileA,entry.fileB))continue;results.push(entry)}return results.sort((a,b)=>b.npmi-a.npmi),results.slice(0,20)}function darkMatterToKnowledgeEntries(pairs,projectName){let entries2=[],now2=new Date().toISOString();for(let pair of pairs.slice(0,10)){let baseA=path168.basename(pair.fileA),baseB=path168.basename(pair.fileB),lesson=`Files ${pair.fileA} and ${pair.fileB} co-change with NPMI=${pair.npmi.toFixed(3)} but have no import relationship. This hidden coupling suggests a shared architectural concern — changes to one likely require changes to the other.`;if(lesson.length>280)lesson=`Files ${baseA} and ${baseB} co-change with NPMI=${pair.npmi.toFixed(3)} but have no import relationship. This hidden coupling suggests a shared architectural concern — changes to one likely require changes to the other.`;if(lesson.length>280)lesson=`Files ${baseA} and ${baseB} co-change frequently (NPMI=${pair.npmi.toFixed(3)}) without import relationship. This hidden coupling suggests a shared architectural concern.`;if(lesson.length>280)lesson=`Hidden coupling: ${baseA.slice(0,50)}... ↔ ${baseB.slice(0,50)}... (NPMI=${pair.npmi.toFixed(3)})`;let confidence=Math.min(0.3+0.2*Math.min(pair.coChangeCount/10,1),0.5);entries2.push({id:randomUUID27(),tier:"swarm",lesson,category:"architecture",tags:["hidden-coupling","co-change","dark-matter"],scope:"global",confidence,status:"candidate",confirmed_by:[],retrieval_outcomes:{applied_count:0,succeeded_after_count:0,failed_after_count:0},schema_version:1,created_at:now2,updated_at:now2,auto_generated:!0,project_name:projectName,applies_to_agents:["coder","reviewer"],required_actions:[`when modifying ${baseA}, check whether ${baseB} needs a matching change (and vice versa)`.slice(0,200)],verification_checks:[`coupled file ${baseB} was considered when ${baseA} changed`.slice(0,200)],triggers:[baseA,baseB].map((t)=>t.slice(0,80))})}return entries2}function formatDarkMatterOutput(pairs){if(pairs.length===0)return`## Dark Matter: Hidden Couplings
|
|
2364
2364
|
|
|
@@ -4096,11 +4096,11 @@ ${error93 instanceof Error?error93.message:String(error93)}`}}var init_retrieve=
|
|
|
4096
4096
|
`)}
|
|
4097
4097
|
`,description:REVIEWER_TASK_SCOPE_DESCRIPTION,files:ordered.map((candidate2)=>candidate2.relativePath),headSha,workspaceIdentity,delivery,...provenance?{taskId:provenance.taskId,coderCallID:provenance.coderCallID,generation:provenance.generation,sessionIncarnation:provenance.sessionIncarnation}:{}}}}async function resolveReviewerTaskScope(directory,sessionID,maxBytes=DEFAULT_MAX_SCOPE_BYTES,options={}){let session=swarmState.agentSessions.get(sessionID);if(!session)return null;if(options.consumeHandoff){let{expectedTaskId,reviewerCallID}=options;if(!expectedTaskId||!reviewerCallID)return null;let handoff=peekReviewerScopeGenerationClaim({parentSessionID:sessionID,taskId:expectedTaskId,reviewerCallID,now:options.now});if(!handoff)return null;let snapshot=handoff.reviewerDispatchScope;if(!snapshot)return null;let current=await buildReviewerTaskScope(directory,handoff.modifiedFiles,maxBytes,{taskId:handoff.taskId,coderCallID:handoff.coderCallID,generation:handoff.generation,sessionIncarnation:handoff.sessionIncarnation});if(!current.ok||computeScopeFingerprint(current.scope.content,current.scope.description).hash!==snapshot.hash||current.scope.description!==snapshot.description||current.scope.headSha!==snapshot.headSha||JSON.stringify(current.scope.files)!==JSON.stringify(snapshot.files))return null;return current.scope}let live=await buildReviewerTaskScope(directory,session.modifiedFilesThisCoderTask,maxBytes);return live.ok?live.scope:null}var MAX_SCOPE_FILES=256,DEFAULT_MAX_SCOPE_BYTES=262144,MAX_SCOPE_BYTES2=2097152,HEAD_TIMEOUT_MS=5000,HEAD_OUTPUT_BYTES=256,HEAD_SHA_PATTERN,REVIEWER_TASK_SCOPE_DESCRIPTION="reviewer-task-files-v2",REVIEWER_TASK_SCOPE_HEADER="opencode-swarm-reviewer-task-scope-v2",_internals202;var init_review_receipt_scope=__esm(()=>{init_manager();init_scope_binding();init_state2();init_git_executable();init_plan_task_id_context();init_review_receipt();init_reviewer_scope_file_fingerprint();init_task_id_resolver();HEAD_SHA_PATTERN=/^[0-9a-f]{40,64}$/i;_internals202={spawn:child_process10.spawn,realpath:fs144.promises.realpath,resolveGitExecutable}});function inferSeverity(line){let upper=line.toUpperCase();if(upper.includes("CRITICAL"))return"critical";if(upper.includes("HIGH"))return"high";if(upper.includes("LOW"))return"low";if(upper.includes("INFO"))return"info";return"medium"}function collectSectionLines(lines,section){let headerPattern=new RegExp(`^\\s*${section}\\s*:\\s*(.*)$`,"i"),nextSectionPattern=new RegExp(`^\\s*(${SECTION_FIELDS.join("|")})\\s*:`,"i"),collected=[],inSection=!1;for(let line of lines){if(!inSection){let m=line.match(headerPattern);if(m){inSection=!0;let inline=m[1]?.trim();if(inline&&!/^(none|n\/a)\.?$/i.test(inline))collected.push(inline)}continue}if(nextSectionPattern.test(line)||/^\s*```/.test(line))break;let cleaned=line.replace(/^\s*(?:[-*•]|\d+[.)])\s*/,"").trim();if(cleaned)collected.push(cleaned)}return collected}function parseReviewerOutput(text,options={}){if(!text||typeof text!=="string")return null;let structured=options.structured===!1?{findings:[],review:void 0,error:"structured parsing disabled"}:extractReviewFindingsFromAgentOutput(text),verdictTokens=[...text.matchAll(VERDICT_LINE_PATTERN)].map((m)=>m[1].toUpperCase());if(verdictTokens.length!==1)return null;let legacyVerdict=verdictTokens[0];if(structured.review){if(structured.review.verdict!==legacyVerdict)return null;let riskTokens2=[...text.matchAll(RISK_LINE_PATTERN)].map((m)=>m[1].toUpperCase()),fixes2=collectSectionLines(text.split(/\r?\n/),"FIXES").slice(0,50).map((line)=>line.slice(0,500));return{verdict:structured.review.verdict==="APPROVED"?"approved":"rejected",risk:riskTokens2.at(-1),issues:structured.findings.map((finding)=>({text:`${finding.title}: ${finding.body}`.slice(0,500),severity:finding.severity,location:`${finding.file}:${finding.line_start}`,finding})),fixes:fixes2,outputMode:"structured",overallConfidence:structured.review.overall_confidence,structuredFindings:structured.findings}}let verdict=legacyVerdict==="APPROVED"?"approved":"rejected",risk=[...text.matchAll(RISK_LINE_PATTERN)].map((m)=>m[1].toUpperCase()).at(-1),lines=text.split(/\r?\n/),issues=collectSectionLines(lines,"ISSUES").slice(0,50).map((line)=>{let location=line.match(LOCATION_PATTERN)?.[0];return{text:line.slice(0,500),severity:inferSeverity(line),location}}),fixes=collectSectionLines(lines,"FIXES").slice(0,50).map((line)=>line.slice(0,500));return{verdict,risk,issues,fixes,outputMode:"legacy"}}function findingId2(finding){return finding?canonicalizeValidationCandidates([finding])[0]?.finding_id:void 0}function effectiveSeverityForFinding(finding,minConfidence){return finding.severity!=="critical"&&finding.confidence<minConfidence?"info":finding.severity}function isValidationCandidate(finding,minConfidence){let effectiveSeverity=effectiveSeverityForFinding(finding,minConfidence);return effectiveSeverity==="high"||effectiveSeverity==="critical"}function validatorForReviewer(reviewer){return`${stripKnownSwarmPrefix(reviewer)===reviewer?"":reviewer.slice(0,reviewer.length-8)}critic_finding_validator`}function validationErrorText(error93){return(error93 instanceof Error?error93.message:String(error93)).trim()||"unknown validation error"}function emitStageBValidationTelemetry(sessionID,validatorAgent,result,costFields){try{_internals203.delegationBegin(sessionID,validatorAgent,STAGE_B_VALIDATION_TASK_ID),_internals203.delegationEnd(sessionID,validatorAgent,STAGE_B_VALIDATION_TASK_ID,result,costFields)}catch(error93){warn(`[review-receipt-collector] validation telemetry failed: ${validationErrorText(error93)}`)}}function materializeValidationOutcome(candidates,result){if(result.complete)return result.validations;let candidateIds=new Set(candidates.map((candidate2)=>candidate2.finding_id)),byId=new Map(result.validations.filter((validation)=>candidateIds.has(validation.finding_id)).map((validation)=>[validation.finding_id,validation])),reason=(result.error??"validator did not return a complete exact-ID result").slice(0,1900);return candidates.map((candidate2)=>byId.get(candidate2.finding_id)??{finding_id:candidate2.finding_id,disposition:"UNVERIFIED",confidence:0,evidence:`Validation incomplete: ${reason}`})}function isTaskTool2(tool3){return tool3==="Task"||tool3==="task"}function hasExactScopeIdentity(scope){return typeof scope.taskId==="string"&&typeof scope.coderCallID==="string"&&typeof scope.generation==="number"&&typeof scope.sessionIncarnation==="string"}async function reviewerScopeRemainsCurrent(input){if(!hasExactScopeIdentity(input.scope))return!0;if(input.reviewerCallID){let claim=peekReviewerScopeGenerationClaim({parentSessionID:input.sessionID,taskId:input.scope.taskId,reviewerCallID:input.reviewerCallID});if(!claim||claim.coderCallID!==input.scope.coderCallID||claim.generation!==input.scope.generation||claim.sessionIncarnation!==input.scope.sessionIncarnation)return!1}let currentScope=await _internals203.buildReviewerTaskScope(input.directory,input.scope.files,input.maxBytes,{taskId:input.scope.taskId,coderCallID:input.scope.coderCallID,generation:input.scope.generation,sessionIncarnation:input.scope.sessionIncarnation});if(currentScope===null)return!1;if(!currentScope.ok)return!1;let scope=currentScope.scope;return isReviewerScopeGenerationCurrent({parentSessionID:input.sessionID,taskId:input.scope.taskId,coderCallID:input.scope.coderCallID,generation:input.scope.generation,sessionIncarnation:input.scope.sessionIncarnation})&&scope.headSha===input.scope.headSha&&scope.content===input.scope.content&&scope.description===input.scope.description&&JSON.stringify(scope.files)===JSON.stringify(input.scope.files)}function discardConsumedReviewerClaim(input){if(!input.reviewerCallID||!hasExactScopeIdentity(input.scope))return;discardReviewerScopeGenerationClaim({parentSessionID:input.sessionID,taskId:input.scope.taskId,reviewerCallID:input.reviewerCallID})}async function collectReviewerReceiptFromTranscript(directory,input,validationOptions={}){try{let validationConfig=validationOptions.config;if(validationConfig?.enabled!==!0)return null;if(input.targetAgent&&stripKnownSwarmPrefix(input.targetAgent).toLowerCase()!=="reviewer")return null;let sessionID=input.sessionID??input.sessionId;if(!sessionID)return null;let scope=await _internals203.resolveReviewerTaskScope(directory,sessionID,validationConfig.max_diff_kb*1024,input.consumeHandoff?{consumeHandoff:!0,expectedTaskId:input.taskId,reviewerCallID:input.reviewerCallID}:void 0);if(!scope)return null;if(!await reviewerScopeRemainsCurrent({directory,sessionID,scope,maxBytes:validationConfig.max_diff_kb*1024,reviewerCallID:input.reviewerCallID}))return discardConsumedReviewerClaim({sessionID,reviewerCallID:input.reviewerCallID,scope}),null;if(!input.transcript)return discardConsumedReviewerClaim({sessionID,reviewerCallID:input.reviewerCallID,scope}),null;let parsed=parseReviewerOutput(input.transcript,{structured:validationConfig.structured_findings!==!1});if(!parsed)return discardConsumedReviewerClaim({sessionID,reviewerCallID:input.reviewerCallID,scope}),null;let minConfidence=validationConfig.min_confidence,receipt=parsed.verdict==="approved"?buildApprovedReceipt({agent:"reviewer",sessionId:sessionID,scopeContent:scope.content,scopeDescription:scope.description,checkedAspects:["code-review"],validatedClaims:[`VERDICT: APPROVED${parsed.risk?` (risk ${parsed.risk})`:""}`],caveats:parsed.issues.map((i)=>i.text),structuredFindings:parsed.structuredFindings,reviewOverallConfidence:parsed.overallConfidence}):buildRejectedReceipt({agent:"reviewer",sessionId:sessionID,scopeContent:scope.content,scopeDescription:scope.description,blockingFindings:parsed.issues.map((i)=>({location:i.location??"unknown",summary:i.text,severity:i.severity,finding_id:findingId2(i.finding),line:i.finding?.line_start,title:i.finding?.title,body:i.finding?.body,confidence:i.finding?.confidence,file:i.finding?.file,line_start:i.finding?.line_start,line_end:i.finding?.line_end,effective_severity:i.finding?effectiveSeverityForFinding(i.finding,minConfidence):void 0})),evidenceReferences:parsed.issues.map((i)=>i.location).filter((loc)=>Boolean(loc)),passConditions:parsed.fixes,summary:`Reviewer REJECTED${parsed.risk?` (risk ${parsed.risk})`:""}`,structuredFindings:parsed.structuredFindings,reviewOverallConfidence:parsed.overallConfidence});if(!await reviewerScopeRemainsCurrent({directory,sessionID,scope,maxBytes:validationConfig.max_diff_kb*1024,reviewerCallID:input.reviewerCallID}))return discardConsumedReviewerClaim({sessionID,reviewerCallID:input.reviewerCallID,scope}),null;let scopeBecameStale=!1,receiptPath;try{receiptPath=await _internals203.persistReviewReceipt(directory,receipt,{verifyCurrent:async()=>{let current=await reviewerScopeRemainsCurrent({directory,sessionID,scope,maxBytes:validationConfig.max_diff_kb*1024,reviewerCallID:input.reviewerCallID});if(!current)scopeBecameStale=!0;return current}})}catch(error93){if(scopeBecameStale)discardConsumedReviewerClaim({sessionID,reviewerCallID:input.reviewerCallID,scope});throw error93}discardConsumedReviewerClaim({sessionID,reviewerCallID:input.reviewerCallID,scope});let candidates=parsed.structuredFindings?.filter((finding)=>isValidationCandidate(finding,minConfidence))??[];if(sessionID&&validationOptions.dispatcher&&validationConfig?.enabled&&validationConfig.validate_findings&&candidates.length>0){let reviewer=input.targetAgent??"reviewer",canonicalCandidates=canonicalizeValidationCandidates(candidates),validatorAgent=validatorForReviewer(reviewer),immutableScope={...scope,files:[...scope.files]},receiptIdentity={id:receipt.id,scopeHash:receipt.scope_fingerprint.hash,scopeDescription:receipt.scope_fingerprint.scope_description},persistAndAdvise=async(result)=>{for(let attempt of result.attempts)emitStageBValidationTelemetry(sessionID,validatorAgent,attempt.status,{...attempt.costFields,gate:"finding_validation"});let validationScopeIsCurrent=async()=>{if(!hasExactScopeIdentity(immutableScope))return!0;let current=await reviewerScopeRemainsCurrent({directory,sessionID,scope:immutableScope,maxBytes:validationConfig.max_diff_kb*1024}),currentFingerprint=current?computeScopeFingerprint(immutableScope.content,immutableScope.description):null;return current&¤tFingerprint?.hash===receiptIdentity.scopeHash&¤tFingerprint.scope_description===receiptIdentity.scopeDescription},discardStaleValidation=()=>{warn("[review-receipt-collector] Independent finding validation was discarded as stale because the exact reviewed scope changed before validation completed.");try{validationOptions.injectAdvisory?.(sessionID,"Independent finding validation was discarded as stale because the exact reviewed scope changed before validation completed.")}catch(error93){warn(`[review-receipt-collector] validation advisory injection failed: ${validationErrorText(error93)}`)}};if(!await validationScopeIsCurrent()){discardStaleValidation();return}let validations=materializeValidationOutcome(canonicalCandidates,result),validationScopeBecameStale=!1;try{await _internals203.updateReviewReceiptValidations(receiptPath,validations,{expectedIdentity:receiptIdentity,verifyCurrent:async()=>{let current=await validationScopeIsCurrent();if(!current)validationScopeBecameStale=!0;return current}})}catch(error93){if(validationScopeBecameStale){discardStaleValidation();return}warn(`[review-receipt-collector] validation persistence failed: ${validationErrorText(error93)}`);try{validationOptions.injectAdvisory?.(sessionID,`Independent finding validation completed but was not persisted: ${validationErrorText(error93)}. Receipt: ${receiptPath}`)}catch(advisoryError){warn(`[review-receipt-collector] validation advisory injection failed: ${validationErrorText(advisoryError)}`)}return}let counts={confirmed:validations.filter((item)=>item.disposition==="CONFIRMED").length,disproved:validations.filter((item)=>item.disposition==="DISPROVED").length,unverified:validations.filter((item)=>item.disposition==="UNVERIFIED").length};try{validationOptions.injectAdvisory?.(sessionID,result.complete?`Independent finding validation completed: ${counts.confirmed} confirmed, ${counts.disproved} disproved, ${counts.unverified} unverified. Receipt: ${receiptPath}`:`Independent finding validation was incomplete: ${result.error??"unknown error"}. ${counts.unverified} finding(s) recorded as UNVERIFIED. Receipt: ${receiptPath}`)}catch(error93){warn(`[review-receipt-collector] validation advisory injection failed: ${validationErrorText(error93)}`)}},validationIdentity=[sessionID,receipt.id,immutableScope.taskId??"legacy-task",immutableScope.coderCallID??"legacy-coder-call",String(immutableScope.generation??"legacy-generation"),immutableScope.sessionIncarnation??"legacy-incarnation"].join("\x00"),validationScheduler=validationOptions.validationScheduler;if(!validationScheduler)return await persistAndAdvise({complete:!1,candidates:canonicalCandidates,validations:[],attempts:[],error:"validation scheduling refused because the owning plugin instance did not provide its bounded validation scheduler"}),receiptPath;if(!validationScheduler.schedule(validationIdentity,()=>runFindingValidation({dispatcher:validationOptions.dispatcher,directory,parentSessionId:sessionID,agentName:validatorAgent,model:optionalModelOverride(validationConfig.validation_model),fallbackModels:resolveReviewFallbackModels(validatorAgent,validationOptions.agentModelRegistry),timeoutMs:validationConfig.validation_timeout_ms,findings:canonicalCandidates,scopeContext:{selector:{kind:"working-tree"},canonicalText:immutableScope.content,scopeHash:receiptIdentity.scopeHash,headSha:immutableScope.headSha,completeness:{complete:!0,truncated:!1,skipReasons:[]},scopeDescription:immutableScope.description,files:[...immutableScope.files]}}),persistAndAdvise,(error93)=>persistAndAdvise({complete:!1,candidates:canonicalCandidates,validations:[],attempts:[],error:`validator execution failed: ${validationErrorText(error93)}`})))await persistAndAdvise({complete:!1,candidates:canonicalCandidates,validations:[],attempts:[],error:"validation scheduling refused because this exact receipt generation is already being validated or the 256-validation capacity is full"})}return receiptPath}catch(err){return warn(`[review-receipt-collector] failed: ${err instanceof Error?err.message:String(err)}`),null}}async function collectReviewerReceiptAfter(directory,input,output,validationOptions={}){try{if(validationOptions.config?.enabled!==!0)return null;if(!isTaskTool2(input.tool))return null;let taskResult=classifyTaskResult(output);if(taskResult==="running")return null;let parsedArgs=parseDelegationArgs(input.args);if(!parsedArgs)return null;if(stripKnownSwarmPrefix(parsedArgs.targetAgent).toLowerCase()!=="reviewer")return null;let argsRecord=input.args&&typeof input.args==="object"?input.args:null,prompt=argsRecord&&typeof argsRecord.prompt==="string"?argsRecord.prompt:"",transcript=typeof output.output==="string"?output.output:"",sessionID=typeof input.sessionID==="string"?input.sessionID:void 0,reviewerCallID=typeof input.callID==="string"?input.callID:void 0;if(!sessionID)return null;let taskId=reviewerCallID?await resolveReviewerScopeTaskId(directory,input.args):void 0;if(reviewerCallID&&!taskId)return discardReviewerScopeGenerationClaim({parentSessionID:sessionID,reviewerCallID}),null;if(reviewerCallID&&taskId&&taskResult!=="success")return discardReviewerScopeGenerationClaim({parentSessionID:sessionID,taskId,reviewerCallID}),null;return await collectReviewerReceiptFromTranscript(directory,{targetAgent:parsedArgs.targetAgent,prompt,transcript,sessionID,taskId:taskId??void 0,reviewerCallID,consumeHandoff:reviewerCallID!==void 0},validationOptions)}catch(err){return warn(`[review-receipt-collector] failed: ${err instanceof Error?err.message:String(err)}`),null}}var SECTION_FIELDS,LOCATION_PATTERN,VERDICT_LINE_PATTERN,RISK_LINE_PATTERN,STAGE_B_VALIDATION_TASK_ID="reviewer-task-validation",_internals203;var init_review_receipt_collector=__esm(()=>{init_agent_output_schema();init_schema();init_finding_validator();init_runtime3();init_state2();init_telemetry();init_logger();init_review_receipt();init_review_receipt_scope();init_skill_propagation_gate();init_task_result_classifier();SECTION_FIELDS=["VERDICT","REUSE_RE_VERIFICATION","RISK","ISSUES","ACCEPTANCE_SATISFACTION","SKILL_COMPLIANCE","DIRECTIVE_COMPLIANCE","FIXES"],LOCATION_PATTERN=/([\w./-]+\.[A-Za-z]{1,8}):(\d{1,6})/;VERDICT_LINE_PATTERN=/^\s*(?:\*\*)?VERDICT(?:\*\*)?\s*:\s*(APPROVED|REJECTED)\s*$/gim,RISK_LINE_PATTERN=/^\s*(?:\*\*)?RISK(?:\*\*)?\s*:\s*(LOW|MEDIUM|HIGH|CRITICAL)\b/gim;_internals203={delegationBegin:telemetry.delegationBegin,delegationEnd:telemetry.delegationEnd,resolveReviewerTaskScope,buildReviewerTaskScope,persistReviewReceipt,updateReviewReceiptValidations}});import{createHash as createHash94}from"node:crypto";import*as fs145 from"node:fs";import*as path254 from"node:path";function computeAutoReviewManifestHash(manifest){return createHash94("sha256").update(JSON.stringify({schema_version:manifest.schema_version,content_hash:manifest.content_hash,plan_requirements_hash:manifest.plan_requirements_hash,review_policy_digest:manifest.review_policy_digest,selector:manifest.selector,selector_key:manifest.selector_key,review_target_kind:manifest.review_target_kind,completeness:manifest.completeness,path_records:manifest.path_records}),"utf8").digest("hex")}function autoReviewEvidenceRelativePath(trigger,scopeHash,phase){if((trigger==="phase_completion"||trigger==="plan_completion")&&Number.isInteger(phase)&&(phase??0)>0)return path254.join("evidence",String(phase),"auto-review.json");return path254.join("evidence","auto-review",`${trigger}-${scopeHash.slice(0,64)}.json`)}async function persistAutoReviewEvidence(directory,evidence2,options={}){let target=validateSwarmPath(directory,autoReviewEvidenceRelativePath(evidence2.trigger,evidence2.scope.hash,evidence2.phase));fs145.mkdirSync(path254.dirname(target),{recursive:!0});let tempPath=`${target}.tmp.${Date.now()}.${Math.floor(Math.random()*1e9)}`;try{await _internals204.bunWrite(tempPath,`${JSON.stringify(evidence2,null,2)}
|
|
4098
4098
|
`);let safeTemp=validateSwarmPath(directory,path254.relative(path254.join(directory,".swarm"),tempPath)),tempStat=fs145.lstatSync(safeTemp);if(!tempStat.isFile()||tempStat.isSymbolicLink())throw Error("auto-review evidence temp path must be a real file");if(options.verifyCurrent&&!await options.verifyCurrent())throw new ReviewScopeStaleError("auto-review scope became stale before evidence commit");let safeTarget=validateSwarmPath(directory,path254.relative(path254.join(directory,".swarm"),target)),revalidatedTemp=validateSwarmPath(directory,path254.relative(path254.join(directory,".swarm"),tempPath)),revalidatedStat=fs145.lstatSync(revalidatedTemp);if(!revalidatedStat.isFile()||revalidatedStat.isSymbolicLink())throw Error("auto-review evidence temp path changed before commit");return _internals204.renameSync(revalidatedTemp,safeTarget),invalidateCachedArtifact(safeTarget),safeTarget}finally{try{fs145.unlinkSync(tempPath)}catch{}}}function readAutoReviewEvidenceForPhase(directory,phase){try{let target=validateSwarmPath(directory,path254.join("evidence",String(phase),"auto-review.json")),parsed=JSON.parse(fs145.readFileSync(target,"utf8"));if(!isAutoReviewEvidence(parsed))return null;return parsed}catch{return null}}function isAutoReviewEvidence(value){if(!value||typeof value!=="object")return!1;let candidate2=value;if(!((candidate2.schema_version===1||candidate2.schema_version===2)&&typeof candidate2.timestamp==="string"&&["task_completion","phase_completion","plan_completion","manual"].includes(String(candidate2.trigger))&&typeof candidate2.session_id==="string"&&Boolean(candidate2.scope)&&typeof candidate2.scope?.hash==="string"&&typeof candidate2.scope?.head_sha==="string"&&Boolean(candidate2.scope?.selector)&&Boolean(candidate2.scope?.completeness)&&Boolean(candidate2.policy)&&(candidate2.policy?.mode==="advisory"||candidate2.policy?.mode==="gate")&&typeof candidate2.policy?.min_confidence==="number"&&typeof candidate2.policy?.structured_findings==="boolean"&&typeof candidate2.policy?.validate_findings==="boolean"&&Array.isArray(candidate2.findings)&&Array.isArray(candidate2.blocking_finding_ids)&&typeof candidate2.validation_complete==="boolean"&&Boolean(candidate2.review)&&["completed","clean","error"].includes(String(candidate2.review?.status))))return!1;if(candidate2.schema_version===2){if(!candidate2.scope?.manifest||candidate2.scope.manifest.schema_version!==2||typeof candidate2.scope.manifest.content_hash!=="string"||typeof candidate2.scope.manifest.plan_requirements_hash!=="string"||typeof candidate2.scope.manifest.review_policy_digest!=="string"||typeof candidate2.scope.manifest.hash!=="string"||typeof candidate2.policy?.digest!=="string")return!1;let{hash:hash5,...manifestPayload}=candidate2.scope.manifest;if(hash5!==computeAutoReviewManifestHash(manifestPayload))return!1}return candidate2.findings.every(isAutoReviewEvidenceFinding)}async function computePlanRequirementsHash(directory){let plan=await loadReviewRequirementsPlan(directory);return plan?computeReviewPlanRequirementsHash(plan):"plan:none"}function computeAutoReviewPolicyDigest(config3){return createHash94("sha256").update(JSON.stringify({mode:config3.final_review.mode,min_confidence:config3.min_confidence,structured_findings:config3.structured_findings,validate_findings:config3.validate_findings,final_review:{on_phase_complete:config3.final_review.on_phase_complete,on_plan_complete:config3.final_review.on_plan_complete,max_diff_bytes:config3.final_review.max_diff_bytes,timeout_ms:config3.final_review.timeout_ms,model:config3.final_review.model},validation_timeout_ms:config3.validation_timeout_ms,validation_model:config3.validation_model}),"utf8").digest("hex")}async function materializeAutoReviewManifest(directory,manifest,config3){let planRequirementsHash=await computePlanRequirementsHash(directory),policyDigest=computeAutoReviewPolicyDigest(config3),payload={...manifest,plan_requirements_hash:planRequirementsHash,review_policy_digest:policyDigest},hash5=computeAutoReviewManifestHash(payload);return{...payload,hash:hash5}}async function loadReviewRequirementsPlan(directory){if(!await ledgerExists(directory))return loadPlanJsonOnly(directory);let replayed;try{replayed=await replayFromLedgerWithStatus(directory)}catch(error93){throw Error(`authoritative plan ledger replay failed for final-review requirements: ${error93 instanceof Error?error93.message:String(error93)}`)}if(replayed.truncated)throw Error("authoritative plan ledger replay is truncated; final-review requirements are unavailable");if(!replayed.plan)throw Error("authoritative plan ledger replay returned no plan; final-review requirements are unavailable");return replayed.plan}function computeReviewPlanRequirementsHash(plan){return createHash94("sha256").update(JSON.stringify({schema_version:plan.schema_version,title:plan.title,swarm:plan.swarm,migration_status:plan.migration_status,phases:plan.phases.map((phase)=>({id:phase.id,name:phase.name,type:phase.type,required_agents:phase.required_agents?[...phase.required_agents].sort():void 0,tasks:phase.tasks.map((task2)=>({id:task2.id,phase:task2.phase,size:task2.size,description:task2.description,depends:[...task2.depends].sort(),acceptance:task2.acceptance,files_touched:[...task2.files_touched].sort(),fr_refs:task2.fr_refs?[...task2.fr_refs].sort():void 0}))}))}),"utf8").digest("hex")}function baseFinding(finding){return{title:finding.title,body:finding.body,severity:finding.severity,confidence:finding.confidence,file:finding.file,line_start:finding.line_start,line_end:finding.line_end}}function isAutoReviewEvidenceFinding(value){if(!value||typeof value!=="object")return!1;let finding=value;if(!ReviewFindingSchema.safeParse(baseFinding(finding)).success||!/^[a-f0-9]{64}$/.test(finding.finding_id)||!Number.isInteger(finding.duplicate_count)||finding.duplicate_count<1||typeof finding.anchored!=="boolean"||!["critical","high","medium","low","info"].includes(finding.effective_severity))return!1;return finding.validation===void 0||FindingValidationSchema.safeParse(finding.validation).success&&finding.validation.finding_id===finding.finding_id}function failIntegrity(code,reason){return{ok:!1,code,reason}}function readContainedReceipt(directory,receiptPath){if(!receiptPath)return null;try{let content=readReviewReceiptText(directory,receiptPath);if(content===null)return null;let parsed=JSON.parse(content);if(!parsed||typeof parsed!=="object")return null;let receipt=parsed;if(receipt.schema_version!==1||!["approved","rejected"].includes(receipt.verdict)||receipt.receipt_type!==receipt.verdict||typeof receipt.id!=="string"||typeof receipt.reviewer?.agent!=="string"||typeof receipt.scope_fingerprint?.hash!=="string"||typeof receipt.scope_fingerprint?.scope_description!=="string"||!Array.isArray(receipt.structured_findings)||!receipt.structured_findings.every((finding)=>ReviewFindingSchema.safeParse(finding).success)||!Array.isArray(receipt.finding_validations)||!receipt.finding_validations.every((validation)=>FindingValidationSchema.safeParse(validation).success))return null;return receipt}catch{return null}}function sameValidation(left,right){return left.finding_id===right.finding_id&&left.disposition===right.disposition&&left.confidence===right.confidence&&left.evidence===right.evidence}function validateAutoReviewEvidenceIntegrity(directory,evidence2,expected){if(evidence2.scope.hash!==expected.scopeHash||evidence2.phase!==expected.phase||evidence2.trigger!==expected.trigger)return failIntegrity("evidence","phase, trigger, or scope binding mismatch");if(evidence2.policy.mode!==expected.policy.mode||evidence2.policy.min_confidence!==expected.policy.min_confidence||evidence2.policy.structured_findings!==expected.policy.structured_findings||evidence2.policy.validate_findings!==expected.policy.validate_findings)return failIntegrity("evidence","policy binding mismatch");let canonicalEvidence=canonicalizeValidationCandidates(evidence2.findings);if(canonicalEvidence.length!==evidence2.findings.length||canonicalEvidence.some((canonical,index)=>{let recorded=[...evidence2.findings].sort((a,b)=>a.finding_id.localeCompare(b.finding_id))[index];return canonical.finding_id!==recorded.finding_id||canonical.duplicate_count!==recorded.duplicate_count}))return failIntegrity("evidence","finding IDs or duplicate counts are invalid");if(evidence2.findings.some((finding)=>finding.effective_severity!==(finding.severity!=="critical"&&finding.confidence<expected.policy.min_confidence?"info":finding.severity)))return failIntegrity("evidence","effective finding severity does not match current policy");let derivedBlockingIds=evidence2.findings.filter((finding)=>finding.anchored&&(finding.effective_severity==="high"||finding.effective_severity==="critical")&&finding.validation?.disposition==="CONFIRMED").map((finding)=>finding.finding_id).sort(),recordedBlockingIds=[...evidence2.blocking_finding_ids].sort();if(derivedBlockingIds.length!==recordedBlockingIds.length||derivedBlockingIds.some((findingId3,index)=>findingId3!==recordedBlockingIds[index]))return failIntegrity("evidence","blocking finding IDs do not match derived confirmed findings");if(evidence2.review.status!=="completed")return evidence2.findings.length===0&&evidence2.blocking_finding_ids.length===0?{ok:!0}:failIntegrity("evidence","non-completed evidence contains findings");let receipt=readContainedReceipt(directory,evidence2.receipt_path);if(!receipt)return failIntegrity("receipt_missing","receipt is missing or malformed");if(receipt.reviewer.session_id!==evidence2.session_id||receipt.scope_fingerprint.scope_description!==`${evidence2.trigger}-review`||expected.scopeContent!==void 0&&isScopeStale(receipt,expected.scopeContent))return failIntegrity("receipt","receipt scope or session binding mismatch");let receiptCandidates=canonicalizeValidationCandidates(receipt.structured_findings??[]),evidenceById=new Map(evidence2.findings.map((finding)=>[finding.finding_id,finding]));if(receiptCandidates.length!==evidence2.findings.length||receiptCandidates.some((candidate2)=>{let recorded=evidenceById.get(candidate2.finding_id);return!recorded||candidate2.duplicate_count!==recorded.duplicate_count||JSON.stringify(baseFinding(recorded))!==JSON.stringify(baseFinding(candidate2))}))return failIntegrity("receipt","receipt finding IDs or payloads mismatch");let evidenceValidations=evidence2.findings.flatMap((finding)=>finding.validation?[finding.validation]:[]).sort((a,b)=>a.finding_id.localeCompare(b.finding_id)),receiptValidations=[...receipt.finding_validations??[]].sort((a,b)=>a.finding_id.localeCompare(b.finding_id));if(evidenceValidations.length!==receiptValidations.length||evidenceValidations.some((validation,index)=>!sameValidation(validation,receiptValidations[index])))return failIntegrity("receipt","receipt finding validations mismatch");if(receipt.receipt_type==="rejected"){let receiptById=new Map(receipt.blocking_findings.map((finding)=>[finding.finding_id,finding]));if(receiptById.size!==evidence2.findings.length)return failIntegrity("receipt","rejected receipt finding IDs mismatch");for(let finding of evidence2.findings){let recorded=receiptById.get(finding.finding_id);if(!recorded||recorded.anchor_status!==(finding.anchored?"anchored":"unanchored")||recorded.anchor_reason!==finding.anchor_rejection||recorded.effective_severity!==finding.effective_severity||recorded.validator_disposition!==finding.validation?.disposition||recorded.validator_confidence!==finding.validation?.confidence||recorded.validator_evidence!==finding.validation?.evidence)return failIntegrity("receipt","rejected receipt derived finding state mismatch")}}else{let expectedCaveats=evidence2.findings.filter((finding)=>!finding.anchored).map((finding)=>`${finding.title}: ${finding.anchor_rejection??"unanchored"}`).sort(),receiptCaveats=[...receipt.caveats??[]].sort();if(expectedCaveats.length!==receiptCaveats.length||expectedCaveats.some((caveat,index)=>caveat!==receiptCaveats[index]))return failIntegrity("receipt","approved receipt anchoring caveats mismatch")}return{ok:!0,receipt}}var _internals204;var init_evidence2=__esm(()=>{init_agent_output_schema();init_review_receipt();init_utils2();init_ledger();init_manager();init_bun_compat();init_swarm_artifact_cache();init_finding_validator();_internals204={bunWrite,renameSync:fs145.renameSync}});import*as fs146 from"node:fs";import*as path255 from"node:path";function scopeFreshnessMismatches(reviewed,current){let mismatches=[],compare=(field,left,right)=>{if(left!==right)mismatches.push(field)};return compare("status",reviewed.status,current.status),compare("scopeHash",reviewed.scopeHash,current.scopeHash),compare("manifestHash",reviewed.manifest.hash,current.manifest.hash),compare("canonicalText",reviewed.canonicalText,current.canonicalText),compare("reviewTextBytes",reviewed.reviewTextBytes,current.reviewTextBytes),compare("selector",JSON.stringify(reviewed.selector),JSON.stringify(current.selector)),compare("completeness",JSON.stringify(reviewed.completeness),JSON.stringify(current.completeness)),compare("includesWorkingTree",reviewed.staleness.includesWorkingTree,current.staleness.includesWorkingTree),mismatches}function createScopeVerifier(input,reviewed,maxBytes){return async()=>{let current=await _internals205.collectReviewDiff({directory:input.directory,selector:input.selector,maxBytes});return current.status!=="error"&&scopeFreshnessMismatches(reviewed,current).length===0}}async function stalePersistenceResult(input,maxBytes,message,modelCalls){let current=await _internals205.collectReviewDiff({directory:input.directory,selector:input.selector,maxBytes}),result=emptyResult4("error",`${message} Stale review artifacts were discarded and provide no current coverage.`,input.config.final_review.mode==="gate",input.config.final_review.mode==="gate"?"REVIEW_SCOPE_STALE":void 0);if(result.modelCalls=modelCalls,current.status!=="error")result.scopeHash=current.scopeHash,result.manifestHash=current.manifest.hash,result.scopeComplete=current.completeness.complete,Object.assign(result,scopeResultFields(current));return input.injectAdvisory?.(input.sessionID,advisoryMessage(input,result)),result}function scopeResultFields(diff,promptRequest){if(diff.completeness.complete)return{scopeWarnings:[]};let fallback=diff.completeness.fileListFallback,promptInventory=promptRequest?.fileInventory,warnings=["Review scope was incomplete; findings cover only the supplied diff subset and must not be treated as a whole-diff verdict."];if(promptInventory&&promptInventory.omittedFiles>0)warnings.push(`Review prompt changed-file inventory included ${promptInventory.files.length} of ${promptInventory.totalFiles} file name(s); ${promptInventory.omittedFiles} name(s) were omitted to stay within the ${MAX_EPHEMERAL_PROMPT_BYTE_LIMIT}-byte isolated-session ceiling. The full bounded collector inventory remains in durable scope evidence.`);else if(fallback)warnings.push(`Bounded changed-file fallback lists ${fallback.files.length} file(s) and is ${fallback.complete?"complete":"itself incomplete"}.`);return{scopeWarnings:warnings,scopeFileList:promptInventory?.files??fallback?.files,scopeFileListComplete:promptInventory?.complete??fallback?.complete}}function renderReviewPrompt(input,renderedFallbackFiles,omittedFallbackFiles){let{diff}=input,exactRange=diff.selector.kind==="range",reviewTargetKind2=diff.selector.kind==="range"?"exact-committed-range":diff.selector.kind==="working-tree"?"checkout-index-working-tree":"checkout-history-index-working-tree",fallback=diff.completeness.fileListFallback,promptFallbackComplete=fallback?.complete&&omittedFallbackFiles===0;return[`TASK: Review the complete ${input.trigger.replaceAll("_"," ")} diff.`,input.phase?`PHASE: ${input.phase}`:"",`REVIEW_SELECTOR: ${JSON.stringify(diff.selector)}`,`REVIEW_TARGET_KIND: ${reviewTargetKind2}`,`SCOPE_HASH: ${diff.scopeHash}`,`BASE_REF: ${diff.baseRef??"none"}`,`BASE_SHA: ${diff.baseSha??"none"}`,`RESOLVED_BASE_SHA: ${diff.baseSha??"none"}`,exactRange?`RESOLVED_FROM_SHA: ${diff.baseSha??"none"}`:"",exactRange?`RESOLVED_TO_SHA: ${diff.rangeToSha??"none"}`:"",exactRange?`REVIEW_TARGET_SHA: ${diff.rangeToSha??"none"}`:"",`MERGE_BASE: ${diff.mergeBase??"none"}`,`CHECKOUT_HEAD_SHA: ${diff.headSha}`,exactRange?`CHECKOUT_MATCHES_REVIEW_TARGET: ${diff.headSha===diff.rangeToSha}`:"",`REVIEW_SCOPE_INCLUDES_WORKING_TREE: ${diff.staleness.includesWorkingTree}`,`SCOPE_COMPLETE: ${diff.completeness.complete}`,diff.completeness.complete?"":"SCOPE_WARNING: INCOMPLETE. The diff block is a bounded subset. Never describe this as a whole-diff approval or infer findings from unsupplied content.",fallback?`FILE_LIST_FALLBACK_COMPLETE: ${promptFallbackComplete}`:"",fallback&&omittedFallbackFiles>0?`FILE_LIST_FALLBACK_SOURCE_COMPLETE: ${fallback.complete}`:"",fallback&&omittedFallbackFiles>0?`FILE_LIST_FALLBACK_INCLUDED: ${renderedFallbackFiles.length}`:"",fallback&&omittedFallbackFiles>0?`FILE_LIST_FALLBACK_TOTAL: ${fallback.files.length}`:"",fallback&&omittedFallbackFiles>0?`FILE_LIST_FALLBACK_OMITTED: ${omittedFallbackFiles}`:"",fallback&&omittedFallbackFiles>0?"FILE_LIST_FALLBACK_WARNING: INCOMPLETE PROMPT INVENTORY. Some changed path names are omitted only to satisfy the isolated-session byte ceiling. Review only supplied diff content and listed names; do not infer omitted paths.":"",fallback?omittedFallbackFiles>0?`FILE_LIST_FALLBACK (${renderedFallbackFiles.length} of ${fallback.files.length} changed path(s), names only; do not infer file contents):`:`FILE_LIST_FALLBACK (${fallback.files.length} changed path(s), names only; do not infer file contents):`:"",...renderedFallbackFiles.map((file3)=>JSON.stringify(file3)),"DIFF:","```diff",diff.canonicalText,"```"].filter(Boolean).join(`
|
|
4099
|
-
`)}function reviewRequestBytes(prompt){return Buffer.byteLength(REVIEW_SYSTEM_PROMPT,"utf8")+Buffer.byteLength(prompt,"utf8")}function buildReviewPromptRequest(input){let fallback=input.diff.completeness.fileListFallback,allFiles=fallback?.files??[],prompt=renderReviewPrompt(input,allFiles,0),requestBytes=reviewRequestBytes(prompt);if(requestBytes<=MAX_EPHEMERAL_PROMPT_BYTE_LIMIT)return{prompt,requestBytes,promptByteLimit:requestBytes,fits:!0,fileInventory:fallback?{files:allFiles,totalFiles:allFiles.length,omittedFiles:0,complete:fallback.complete}:void 0};let lowerBound=0,upperBound=allFiles.length;while(lowerBound<upperBound){let candidateCount=Math.ceil((lowerBound+upperBound)/2),candidatePrompt=renderReviewPrompt(input,allFiles.slice(0,candidateCount),allFiles.length-candidateCount);if(reviewRequestBytes(candidatePrompt)<=MAX_EPHEMERAL_PROMPT_BYTE_LIMIT)lowerBound=candidateCount;else upperBound=candidateCount-1}let renderedFiles=allFiles.slice(0,lowerBound),omittedFiles=allFiles.length-renderedFiles.length;return prompt=renderReviewPrompt(input,renderedFiles,omittedFiles),requestBytes=reviewRequestBytes(prompt),{prompt,requestBytes,promptByteLimit:Math.min(requestBytes,MAX_EPHEMERAL_PROMPT_BYTE_LIMIT),fits:requestBytes<=MAX_EPHEMERAL_PROMPT_BYTE_LIMIT,fileInventory:fallback?{files:renderedFiles,totalFiles:allFiles.length,omittedFiles,complete:fallback.complete&&omittedFiles===0}:void 0}}function hasControlCharacter4(value){for(let index=0;index<value.length;index++){let code=value.charCodeAt(index);if(code<=31||code===127)return!0}return!1}function normalizedRelativePath(file3){if(file3.length===0||file3.length>500||hasControlCharacter4(file3)||/^[A-Za-z]:[\\/]/.test(file3)||file3.startsWith("\\\\")||file3.startsWith("//")||path255.isAbsolute(file3))return null;let normalized=file3.replaceAll("\\","/");if(normalized.split("/").some((segment)=>segment===".."||segment==="")||normalized.startsWith("/"))return null;return normalized.replace(/^\.\//,"")}function isWithinRoot3(root,candidate2){let relative58=path255.relative(root,candidate2);return relative58.length>0&&relative58!==".."&&!relative58.startsWith(`..${path255.sep}`)&&!path255.isAbsolute(relative58)}function rangesOverlap(start,end,ranges){return ranges.some((range)=>start<=range.end&&end>=range.start)}function anchorExactRangeFinding(diff,normalized,start,end){if(!diff.rangeToSha||!/^[0-9a-f]{6,64}$/i.test(diff.rangeToSha))return"exact_range_target_unavailable";let ranges=diff.changedLines.get(normalized);if(!ranges||!rangesOverlap(start,end,ranges))return"line_range_does_not_overlap_diff";let file3=diff.files.get(normalized);if(!file3?.newPath||file3.newPath!==normalized||file3.kind==="deleted")return"nonexistent_target_path";return}function anchorFinding(directory,diff,finding,minConfidence){let anchorRejection,normalized=normalizedRelativePath(finding.file);if(!diff.completeness.complete||diff.completeness.truncated)anchorRejection="incomplete_or_truncated_scope";else if(!normalized)anchorRejection="unsafe_or_absolute_path";else if(diff.selector.kind==="range")anchorRejection=anchorExactRangeFinding(diff,normalized,finding.line_start,finding.line_end);else{let root,currentPath2;try{root=fs146.realpathSync(directory),currentPath2=fs146.realpathSync(path255.resolve(root,...normalized.split("/")))}catch{return{...finding,file:normalized,anchored:!1,anchor_rejection:"nonexistent_current_path",effective_severity:finding.severity!=="critical"&&finding.confidence<minConfidence?"info":finding.severity}}if(!isWithinRoot3(root,currentPath2))anchorRejection="path_outside_project";else{let ranges=diff.changedLines.get(normalized);if(!ranges||!rangesOverlap(finding.line_start,finding.line_end,ranges))anchorRejection="line_range_does_not_overlap_diff"}}return{...finding,file:normalized??finding.file,anchored:anchorRejection===void 0,anchor_rejection:anchorRejection,effective_severity:finding.severity!=="critical"&&finding.confidence<minConfidence?"info":finding.severity}}function isGateSeverity(severity2){return severity2==="critical"||severity2==="high"}function reviewModelLabel(model){return model?`${model.providerID}/${model.modelID}`:"default"}async function dispatchReviewerWithFallback(input,prompt,timeoutMs,promptByteLimit){let models=[input.reviewerModel,...input.reviewerFallbackModels??[]],attempts=[];for(let index=0;index<models.length;index++){telemetry.delegationBegin(input.sessionID,input.reviewerAgent,input.trigger);let result=await input.dispatcher.dispatch({directory:input.directory,parentSessionId:input.sessionID,agentName:input.reviewerAgent,model:models[index],system:REVIEW_SYSTEM_PROMPT,prompt,title:`auto review (${input.trigger})`,timeoutMs,promptByteLimit});if(attempts.push(result),telemetry.delegationEnd(input.sessionID,input.reviewerAgent,input.trigger,result.status,{...result.costFields,gate:"auto_review",retry_index:index}),result.status==="completed")return{result,attempts};let detail=result.error??result.status,taskCompletionTimeout=input.trigger==="task_completion"&&(result.status==="timeout"||/auto-review timed out/i.test(detail)),transient=isRetryableProviderFailure(classifyProviderFailure(result.status==="timeout"?{name:"TimeoutError",code:"ETIMEDOUT",message:detail||"provider timeout"}:detail));if(taskCompletionTimeout||!transient||index===models.length-1)return{result,attempts};let nextModel=models[index+1],fromModel=reviewModelLabel(models[index]),toModel=reviewModelLabel(nextModel);telemetry.modelFallback(input.sessionID,input.reviewerAgent,fromModel,toModel,"transient_model_error"),input.injectAdvisory?.(input.sessionID,`MODEL FALLBACK: auto-review reviewer failed over to "${toModel}" (fallback ${index+1}) after a transient/quota dispatch error.`)}return{result:attempts[0],attempts}}function
|
|
4099
|
+
`)}function reviewRequestBytes(prompt){return Buffer.byteLength(REVIEW_SYSTEM_PROMPT,"utf8")+Buffer.byteLength(prompt,"utf8")}function buildReviewPromptRequest(input){let fallback=input.diff.completeness.fileListFallback,allFiles=fallback?.files??[],prompt=renderReviewPrompt(input,allFiles,0),requestBytes=reviewRequestBytes(prompt);if(requestBytes<=MAX_EPHEMERAL_PROMPT_BYTE_LIMIT)return{prompt,requestBytes,promptByteLimit:requestBytes,fits:!0,fileInventory:fallback?{files:allFiles,totalFiles:allFiles.length,omittedFiles:0,complete:fallback.complete}:void 0};let lowerBound=0,upperBound=allFiles.length;while(lowerBound<upperBound){let candidateCount=Math.ceil((lowerBound+upperBound)/2),candidatePrompt=renderReviewPrompt(input,allFiles.slice(0,candidateCount),allFiles.length-candidateCount);if(reviewRequestBytes(candidatePrompt)<=MAX_EPHEMERAL_PROMPT_BYTE_LIMIT)lowerBound=candidateCount;else upperBound=candidateCount-1}let renderedFiles=allFiles.slice(0,lowerBound),omittedFiles=allFiles.length-renderedFiles.length;return prompt=renderReviewPrompt(input,renderedFiles,omittedFiles),requestBytes=reviewRequestBytes(prompt),{prompt,requestBytes,promptByteLimit:Math.min(requestBytes,MAX_EPHEMERAL_PROMPT_BYTE_LIMIT),fits:requestBytes<=MAX_EPHEMERAL_PROMPT_BYTE_LIMIT,fileInventory:fallback?{files:renderedFiles,totalFiles:allFiles.length,omittedFiles,complete:fallback.complete&&omittedFiles===0}:void 0}}function hasControlCharacter4(value){for(let index=0;index<value.length;index++){let code=value.charCodeAt(index);if(code<=31||code===127)return!0}return!1}function normalizedRelativePath(file3){if(file3.length===0||file3.length>500||hasControlCharacter4(file3)||/^[A-Za-z]:[\\/]/.test(file3)||file3.startsWith("\\\\")||file3.startsWith("//")||path255.isAbsolute(file3))return null;let normalized=file3.replaceAll("\\","/");if(normalized.split("/").some((segment)=>segment===".."||segment==="")||normalized.startsWith("/"))return null;return normalized.replace(/^\.\//,"")}function isWithinRoot3(root,candidate2){let relative58=path255.relative(root,candidate2);return relative58.length>0&&relative58!==".."&&!relative58.startsWith(`..${path255.sep}`)&&!path255.isAbsolute(relative58)}function rangesOverlap(start,end,ranges){return ranges.some((range)=>start<=range.end&&end>=range.start)}function anchorExactRangeFinding(diff,normalized,start,end){if(!diff.rangeToSha||!/^[0-9a-f]{6,64}$/i.test(diff.rangeToSha))return"exact_range_target_unavailable";let ranges=diff.changedLines.get(normalized);if(!ranges||!rangesOverlap(start,end,ranges))return"line_range_does_not_overlap_diff";let file3=diff.files.get(normalized);if(!file3?.newPath||file3.newPath!==normalized||file3.kind==="deleted")return"nonexistent_target_path";return}function anchorFinding(directory,diff,finding,minConfidence){let anchorRejection,normalized=normalizedRelativePath(finding.file);if(!diff.completeness.complete||diff.completeness.truncated)anchorRejection="incomplete_or_truncated_scope";else if(!normalized)anchorRejection="unsafe_or_absolute_path";else if(diff.selector.kind==="range")anchorRejection=anchorExactRangeFinding(diff,normalized,finding.line_start,finding.line_end);else{let root,currentPath2;try{root=fs146.realpathSync(directory),currentPath2=fs146.realpathSync(path255.resolve(root,...normalized.split("/")))}catch{return{...finding,file:normalized,anchored:!1,anchor_rejection:"nonexistent_current_path",effective_severity:finding.severity!=="critical"&&finding.confidence<minConfidence?"info":finding.severity}}if(!isWithinRoot3(root,currentPath2))anchorRejection="path_outside_project";else{let ranges=diff.changedLines.get(normalized);if(!ranges||!rangesOverlap(finding.line_start,finding.line_end,ranges))anchorRejection="line_range_does_not_overlap_diff"}}return{...finding,file:normalized??finding.file,anchored:anchorRejection===void 0,anchor_rejection:anchorRejection,effective_severity:finding.severity!=="critical"&&finding.confidence<minConfidence?"info":finding.severity}}function isGateSeverity(severity2){return severity2==="critical"||severity2==="high"}function reviewModelLabel(model){return model?`${model.providerID}/${model.modelID}`:"default"}async function dispatchReviewerWithFallback(input,prompt,timeoutMs,promptByteLimit){let models=[input.reviewerModel,...input.reviewerFallbackModels??[]],attempts=[];for(let index=0;index<models.length;index++){telemetry.delegationBegin(input.sessionID,input.reviewerAgent,input.trigger);let result=await input.dispatcher.dispatch({directory:input.directory,parentSessionId:input.sessionID,agentName:input.reviewerAgent,model:models[index],system:REVIEW_SYSTEM_PROMPT,prompt,title:`auto review (${input.trigger})`,timeoutMs,promptByteLimit});if(attempts.push(result),telemetry.delegationEnd(input.sessionID,input.reviewerAgent,input.trigger,result.status,{...result.costFields,gate:"auto_review",retry_index:index}),result.status==="completed")return{result,attempts};let detail=result.error??result.status,taskCompletionTimeout=input.trigger==="task_completion"&&(result.status==="timeout"||/auto-review timed out/i.test(detail)),transient=isRetryableProviderFailure(classifyProviderFailure(result.status==="timeout"?{name:"TimeoutError",code:"ETIMEDOUT",message:detail||"provider timeout"}:detail));if(taskCompletionTimeout||!transient||index===models.length-1)return{result,attempts};let nextModel=models[index+1],fromModel=reviewModelLabel(models[index]),toModel=reviewModelLabel(nextModel);telemetry.modelFallback(input.sessionID,input.reviewerAgent,fromModel,toModel,"transient_model_error"),input.injectAdvisory?.(input.sessionID,`MODEL FALLBACK: auto-review reviewer failed over to "${toModel}" (fallback ${index+1}) after a transient/quota dispatch error.`)}return{result:attempts[0],attempts}}function addCost(evidence2,dispatches){evidence2.cost.model_calls=dispatches.length,evidence2.cost.prompt_bytes=dispatches.reduce((sum,dispatch)=>sum+dispatch.promptBytes,0);for(let dispatch of dispatches){let fields=dispatch.costFields;for(let item of fields?.cost_evidence??[]){if(evidence2.cost.cost_evidence.length>=32)break;evidence2.cost.cost_evidence.push(item)}if(fields?.evidence_status!=="complete")evidence2.cost.evidence_status="inconclusive",evidence2.cost.evidence_reason=fields?.evidence_reason??"missing_cost";if(evidence2.cost.tokens_input=sumKnownAxis(evidence2.cost.tokens_input,fields?.tokens_input??null),evidence2.cost.tokens_output=sumKnownAxis(evidence2.cost.tokens_output,fields?.tokens_output??null),evidence2.cost.tokens_reasoning=sumKnownAxis(evidence2.cost.tokens_reasoning,fields?.tokens_reasoning??null),evidence2.cost.tokens_cache=sumKnownAxis(evidence2.cost.tokens_cache,fields?.tokens_cache??null),typeof fields?.cost_usd==="number")evidence2.cost.cost_usd=(evidence2.cost.cost_usd??0)+fields.cost_usd,evidence2.cost.cost_source=fields.cost_source==="estimated"?"estimated":evidence2.cost.cost_source==="estimated"?"estimated":"reported"}}function baseEvidence(input,diff,status2){return{schema_version:2,timestamp:new Date().toISOString(),trigger:input.trigger,session_id:input.sessionID,phase:input.phase,scope:{hash:diff.scopeHash,selector:diff.selector,head_sha:diff.headSha,base_ref:diff.baseRef,base_sha:diff.baseSha,merge_base:diff.mergeBase,range_to_sha:diff.rangeToSha,review_text_bytes:diff.reviewTextBytes,completeness:diff.completeness},policy:{mode:input.config.final_review.mode,min_confidence:input.config.min_confidence,structured_findings:input.config.structured_findings,validate_findings:input.config.validate_findings,digest:void 0},review:{status:status2},findings:[],validation_complete:!0,blocking_finding_ids:[],cost:{model_calls:0,diff_bytes:diff.reviewTextBytes,prompt_bytes:0,tokens_input:null,tokens_output:null,tokens_reasoning:null,tokens_cache:null,cost_usd:null,cost_source:"unavailable",cost_evidence:[],evidence_status:"complete"}}}function advisoryMessage(input,result){let prefix=`[AUTO-REVIEW ${input.trigger.toUpperCase()}]`,scopeWarnings=result.scopeWarnings??[];if(result.status==="error")return[`${prefix} ${result.message}`,...scopeWarnings].join(`
|
|
4100
4100
|
`);if(result.findings.length===0)return[result.scopeComplete===!1?`${prefix} No findings were reported in the reviewed subset; the scope was incomplete.`:`${prefix} No findings reported.`,...scopeWarnings].join(`
|
|
4101
4101
|
`);let items=result.findings.slice(0,5).map((finding)=>{let validation=finding.validation?` ${finding.validation.disposition}`:"",anchor=finding.anchored?"":` rejected-anchor=${finding.anchor_rejection}`;return`- [${finding.effective_severity.toUpperCase()}${validation}] ${finding.file}:${finding.line_start} ${finding.title}${anchor}`});return[`${prefix} ${result.findings.length} finding(s); ${result.blockingFindings.length} confirmed blocker(s).`,...scopeWarnings,...items].join(`
|
|
4102
|
-
`)}function emptyResult4(status2,message,blocked,blockReason){return{status:status2,blocked,blockReason,message,findings:[],blockingFindings:[],validationComplete:!1,modelCalls:0}}async function persistErrorResult(input,diff,result,error93,dispatches,promptRequest){let evidence2=baseEvidence(input,diff,"error");evidence2.scope.manifest=await materializeAutoReviewManifest(input.directory,diff.manifest,input.config),evidence2.policy.digest=evidence2.scope.manifest.review_policy_digest,evidence2.review.error=error93,addCost(evidence2,dispatches);try{result.evidencePath=await _internals205.persistEvidence(input.directory,evidence2)}catch{if(input.config.final_review.mode==="gate")result.blocked=!0,result.blockReason="EVIDENCE_PERSISTENCE_FAILED"}return result.scopeHash=diff.scopeHash,result.manifestHash=evidence2.scope.manifest.hash,result.scopeComplete=diff.completeness.complete,Object.assign(result,scopeResultFields(diff,promptRequest)),result}async function runReviewEngine(input){let gateMode=input.config.final_review.mode==="gate",maxBytes=input.trigger==="task_completion"?input.config.max_diff_kb*1024:input.config.final_review.max_diff_bytes,timeoutMs=input.trigger==="task_completion"?input.config.timeout_ms:input.config.final_review.timeout_ms,diff=await _internals205.collectReviewDiff({directory:input.directory,selector:input.selector,maxBytes});if(diff.status==="error"){let result2=emptyResult4("error",`Diff collection failed: ${diff.reason}`,gateMode,gateMode?"DIFF_COLLECTION_FAILED":void 0);return input.injectAdvisory?.(input.sessionID,advisoryMessage(input,result2)),result2}if(diff.status==="clean"){let evidence3=baseEvidence(input,diff,"clean");evidence3.scope.manifest=await materializeAutoReviewManifest(input.directory,diff.manifest,input.config),evidence3.policy.digest=evidence3.scope.manifest.review_policy_digest;let evidencePath2;try{evidencePath2=await _internals205.persistEvidence(input.directory,evidence3,{verifyCurrent:createScopeVerifier(input,diff,maxBytes)})}catch(error93){if(error93 instanceof ReviewScopeStaleError)return stalePersistenceResult(input,maxBytes,"Review scope changed before clean evidence could be committed.",0)}let blocked2=gateMode&&!evidencePath2;return{...emptyResult4("clean","Review scope is clean.",blocked2,blocked2?"EVIDENCE_PERSISTENCE_FAILED":void 0),validationComplete:!0,scopeHash:diff.scopeHash,manifestHash:evidence3.scope.manifest.hash,scopeComplete:diff.completeness.complete,...scopeResultFields(diff),evidencePath:evidencePath2}}let promptRequest=buildReviewPromptRequest({trigger:input.trigger,diff,phase:input.phase}),reviewManifest=await materializeAutoReviewManifest(input.directory,diff.manifest,input.config);if(input.phase!==void 0&&(input.trigger==="phase_completion"||input.trigger==="plan_completion")){let existing=_internals205.readPhaseEvidence(input.directory,input.phase),integrity=existing?validateAutoReviewEvidenceIntegrity(input.directory,existing,{scopeHash:diff.scopeHash,phase:input.phase,trigger:input.trigger,policy:{mode:input.config.final_review.mode,min_confidence:input.config.min_confidence,structured_findings:input.config.structured_findings,validate_findings:input.config.validate_findings},scopeContent:diff.canonicalText}):void 0;if(existing?.review.status==="completed"&&existing.schema_version===2&&existing.scope.manifest?.hash===reviewManifest.hash&&integrity?.ok&&integrity.receipt){let validationsById=new Map((integrity.receipt.finding_validations??[]).map((validation)=>[validation.finding_id,validation])),findings2=canonicalizeValidationCandidates(integrity.receipt.structured_findings??[]).map((candidate2)=>{return{...anchorFinding(input.directory,diff,candidate2,input.config.min_confidence),validation:validationsById.get(candidate2.finding_id)}}),validationCandidates2=findings2.filter((finding)=>finding.anchored&&isGateSeverity(finding.effective_severity)),validationComplete2=!((input.config.validate_findings||gateMode)&&validationCandidates2.length>0)||validationCandidates2.every((finding)=>finding.validation),blockingFindings2=validationCandidates2.filter((finding)=>finding.validation?.disposition==="CONFIRMED"),blocked2=gateMode&&(!diff.completeness.complete||!validationComplete2||blockingFindings2.length>0);return{status:"completed",reviewVerdict:integrity.receipt.verdict,blocked:blocked2,blockReason:blocked2?!diff.completeness.complete?"INCOMPLETE_SCOPE":!validationComplete2?"INCOMPLETE_VALIDATION":"CONFIRMED_FINDINGS":void 0,message:"Reused fresh auto-review evidence for the unchanged scope.",findings:findings2,blockingFindings:blockingFindings2,validationComplete:validationComplete2,receiptPath:existing.receipt_path,evidencePath:path255.join(input.directory,".swarm","evidence",String(input.phase),"auto-review.json"),scopeHash:existing.scope.hash,manifestHash:existing.scope.manifest?.hash,scopeComplete:diff.completeness.complete,...scopeResultFields(diff,promptRequest),reviewModel:existing.review.model,modelCalls:0}}}if(!promptRequest.fits){let error93=`Rendered review prompt requires ${promptRequest.requestBytes} bytes after omitting all fallback file names, exceeding the ${MAX_EPHEMERAL_PROMPT_BYTE_LIMIT}-byte isolated-session ceiling.`,result2=await persistErrorResult(input,diff,emptyResult4("error",`Review dispatch failed: ${error93}`,gateMode,gateMode?"REVIEW_DISPATCH_FAILED":void 0),error93,[],promptRequest);return input.injectAdvisory?.(input.sessionID,advisoryMessage(input,result2)),result2}let dispatched=await dispatchReviewerWithFallback(input,promptRequest.prompt,timeoutMs,promptRequest.promptByteLimit);if(dispatched.result.status!=="completed"){let dispatchDetail=dispatched.result.error??dispatched.result.status,quotaAnnotation=isQuotaError(dispatchDetail)?" (model quota/usage limit exhausted across all configured fallbacks)":"",result2=await persistErrorResult(input,diff,emptyResult4("error",`Review dispatch failed${quotaAnnotation}: ${dispatchDetail}`,gateMode,gateMode?"REVIEW_DISPATCH_FAILED":void 0),dispatchDetail,dispatched.attempts,promptRequest);return result2.modelCalls=dispatched.attempts.length,input.injectAdvisory?.(input.sessionID,advisoryMessage(input,result2)),result2}let parsed=parseReviewerOutput(dispatched.result.text,{structured:input.config.structured_findings});if(!parsed){let result2=await persistErrorResult(input,diff,emptyResult4("error","Reviewer returned no machine-readable verdict.",gateMode,gateMode?"INCOMPLETE_REVIEW_EVIDENCE":void 0),"Reviewer returned no machine-readable verdict.",dispatched.attempts,promptRequest);return result2.modelCalls=dispatched.attempts.length,input.injectAdvisory?.(input.sessionID,advisoryMessage(input,result2)),result2}let legacyVerdict=[...dispatched.result.text.matchAll(/^\s*VERDICT\s*:\s*(APPROVED|REJECTED)\s*$/gim)].at(-1)?.[1]?.toLowerCase();if(legacyVerdict&&legacyVerdict!==parsed.verdict){let result2=await persistErrorResult(input,diff,emptyResult4("error","Reviewer legacy and structured verdicts disagree.",gateMode,gateMode?"INCOMPLETE_REVIEW_EVIDENCE":void 0),"Reviewer legacy and structured verdicts disagree.",dispatched.attempts,promptRequest);return result2.modelCalls=dispatched.attempts.length,result2}let findings=canonicalizeValidationCandidates(parsed.structuredFindings??[]).map((candidate2)=>anchorFinding(input.directory,diff,candidate2,input.config.min_confidence)),validationCandidates=findings.filter((finding)=>finding.anchored&&isGateSeverity(finding.effective_severity)),validationComplete=!0,validationError,allDispatches=[...dispatched.attempts];if((input.config.validate_findings||gateMode)&&validationCandidates.length>0){let validation=await runFindingValidation({dispatcher:input.dispatcher,directory:input.directory,parentSessionId:input.sessionID,agentName:input.validatorAgent,model:input.validatorModel,fallbackModels:input.validatorFallbackModels,timeoutMs:input.config.validation_timeout_ms,findings:validationCandidates,scopeContext:{selector:diff.selector,canonicalText:diff.canonicalText,scopeHash:diff.scopeHash,headSha:diff.headSha,baseRef:diff.baseRef,baseSha:diff.baseSha,mergeBase:diff.mergeBase,rangeToSha:diff.rangeToSha,completeness:diff.completeness}});validationComplete=validation.complete,validationError=validation.error;for(let[retryIndex,attempt]of validation.attempts.entries())allDispatches.push(attempt),telemetry.delegationBegin(input.sessionID,input.validatorAgent,input.trigger),telemetry.delegationEnd(input.sessionID,input.validatorAgent,input.trigger,attempt.status,{...attempt.costFields,gate:"finding_validation",retry_index:retryIndex});let byId=new Map(validation.validations.map((item)=>[item.finding_id,item]));findings=findings.map((finding)=>({...finding,validation:byId.get(finding.finding_id)}))}let currentScope=await _internals205.collectReviewDiff({directory:input.directory,selector:input.selector,maxBytes});if(currentScope.status==="error"){let result2=emptyResult4("error",`Review scope freshness check failed after model dispatch: ${currentScope.reason}. Stale reviewer and validator output was discarded and provides no current coverage.`,gateMode,gateMode?"REVIEW_SCOPE_STALE":void 0);return result2.modelCalls=allDispatches.length,input.injectAdvisory?.(input.sessionID,advisoryMessage(input,result2)),result2}let freshnessMismatches=scopeFreshnessMismatches(diff,currentScope);if(freshnessMismatches.length>0){let staleMessage=`Review scope changed during model dispatch (${freshnessMismatches.join(", ")}). Stale reviewer and validator output was discarded and provides no current coverage.`,result2=await persistErrorResult(input,currentScope,emptyResult4("error",staleMessage,gateMode,gateMode?"REVIEW_SCOPE_STALE":void 0),staleMessage,allDispatches);return result2.modelCalls=allDispatches.length,input.injectAdvisory?.(input.sessionID,advisoryMessage(input,result2)),result2}let blockingFindings=findings.filter((finding)=>finding.anchored&&isGateSeverity(finding.effective_severity)&&finding.validation?.disposition==="CONFIRMED"),evidence2=baseEvidence(input,diff,"completed");evidence2.scope.manifest=reviewManifest,evidence2.policy.digest=reviewManifest.review_policy_digest,evidence2.review={status:"completed",output_mode:parsed.outputMode,overall_confidence:parsed.overallConfidence,model:dispatched.result.modelId,duration_ms:dispatched.result.durationMs},evidence2.findings=findings,evidence2.validation_complete=validationComplete,evidence2.validation_error=validationError,evidence2.blocking_finding_ids=blockingFindings.map((finding)=>finding.finding_id),addCost(evidence2,allDispatches);let receiptPath,receiptId;try{let receipt=parsed.verdict==="approved"?buildApprovedReceipt({agent:input.reviewerAgent,sessionId:input.sessionID,scopeContent:diff.canonicalText,scopeDescription:`${input.trigger}-review`,checkedAspects:["correctness","security","regressions"],validatedClaims:["structured review completed"],caveats:findings.filter((finding)=>!finding.anchored).map((finding)=>`${finding.title}: ${finding.anchor_rejection??"unanchored"}`),structuredFindings:parsed.structuredFindings,reviewOverallConfidence:parsed.overallConfidence,findingValidations:findings.map((finding)=>finding.validation).filter((item)=>Boolean(item))}):buildRejectedReceipt({agent:input.reviewerAgent,sessionId:input.sessionID,scopeContent:diff.canonicalText,scopeDescription:`${input.trigger}-review`,blockingFindings:findings.map((finding)=>({location:`${finding.file}:${finding.line_start}`,summary:finding.body,line:finding.line_start,severity:finding.severity,finding_id:finding.finding_id,title:finding.title,body:finding.body,confidence:finding.confidence,file:finding.file,line_start:finding.line_start,line_end:finding.line_end,effective_severity:finding.effective_severity,validator_disposition:finding.validation?.disposition,validator_confidence:finding.validation?.confidence,validator_evidence:finding.validation?.evidence,anchor_status:finding.anchored?"anchored":"unanchored",anchor_reason:finding.anchor_rejection})),evidenceReferences:findings.map((finding)=>`${finding.file}:${finding.line_start}`),passConditions:parsed.fixes,summary:`${input.trigger} review`,structuredFindings:parsed.structuredFindings,reviewOverallConfidence:parsed.overallConfidence,findingValidations:findings.map((finding)=>finding.validation).filter((item)=>Boolean(item))});receiptId=receipt.id,receiptPath=await _internals205.persistReceipt(input.directory,receipt,{verifyCurrent:createScopeVerifier(input,diff,maxBytes)}),evidence2.receipt_path=receiptPath}catch(error93){if(error93 instanceof ReviewScopeStaleError)return stalePersistenceResult(input,maxBytes,"Review scope changed before the review receipt could be committed.",allDispatches.length);evidence2.review.error=`receipt persistence failed: ${error93 instanceof Error?error93.message:String(error93)}`}let blocked=!1,blockReason;if(gateMode&&!diff.completeness.complete)blocked=!0,blockReason="INCOMPLETE_SCOPE";else if(gateMode&&parsed.outputMode!=="structured")blocked=!0,blockReason="INCOMPLETE_REVIEW_EVIDENCE";else if(gateMode&&!validationComplete)blocked=!0,blockReason="INCOMPLETE_VALIDATION";else if(gateMode&&!receiptPath)blocked=!0,blockReason="EVIDENCE_PERSISTENCE_FAILED";else if(gateMode&&blockingFindings.length>0)blocked=!0,blockReason="CONFIRMED_FINDINGS";let evidencePath;try{evidencePath=await _internals205.persistEvidence(input.directory,evidence2,{verifyCurrent:createScopeVerifier(input,diff,maxBytes)})}catch(error93){if(receiptPath&&receiptId)await removeReviewReceipt(input.directory,receiptPath,receiptId).catch(()=>{}),receiptPath=void 0,evidence2.receipt_path=void 0;if(error93 instanceof ReviewScopeStaleError)return stalePersistenceResult(input,maxBytes,"Review scope changed before auto-review evidence could be committed.",allDispatches.length);if(gateMode)blocked=!0,blockReason="EVIDENCE_PERSISTENCE_FAILED"}let result={status:"completed",reviewVerdict:parsed.verdict,blocked,blockReason,message:blocked?`Review gate blocked: ${blockReason}`:`Review completed with ${findings.length} finding(s).`,findings,blockingFindings,validationComplete,receiptPath,evidencePath,scopeHash:diff.scopeHash,manifestHash:reviewManifest.hash,scopeComplete:diff.completeness.complete,...scopeResultFields(diff,promptRequest),reviewModel:dispatched.result.modelId,modelCalls:allDispatches.length};return input.injectAdvisory?.(input.sessionID,advisoryMessage(input,result)),result}var REVIEW_SYSTEM_PROMPT,_internals205;var init_engine2=__esm(()=>{init_ephemeral_agent_dispatcher();init_invocation_failure();init_review_receipt();init_review_receipt_collector();init_telemetry();init_provider_error_classification();init_diff_source();init_evidence2();init_finding_validator();REVIEW_SYSTEM_PROMPT=["You are an isolated repository-aware code review model.","Review only defects introduced by the supplied exact diff. Inspect the repository when needed, but never edit it.","Do not report pre-existing issues, speculation, style-only preferences, or locations outside changed hunks.","A finding must identify a concrete impact and a current-side line overlapping the diff.","If there is no finding the author would definitely want to fix, prefer an empty findings array.","","Your complete response must be at most 800 output tokens.","Emit each of these legacy fields exactly once, in this order:","VERDICT: APPROVED | REJECTED","REUSE_RE_VERIFICATION: VERIFIED | DUPLICATION_DETECTED | SKIPPED","RISK: LOW | MEDIUM | HIGH | CRITICAL","ISSUES: none (see structured findings JSON)","ACCEPTANCE_SATISFACTION: SATISFIED | PARTIAL | NOT_SATISFIED — concise evidence","TASK: task id or unknown","SKILL_COMPLIANCE: COMPLIANT | PARTIAL | VIOLATED — concise evidence","DIRECTIVE_COMPLIANCE: one line per supplied directive, or none","FIXES: required changes if rejected, otherwise none","","Then emit exactly one fenced json block and no other JSON block.","The JSON object is strict: no additional keys are allowed at the root or finding level.","The root keys are exactly findings, verdict, and overall_confidence.","findings is an array of at most 50 objects. Each finding has exactly these keys:","- title: non-empty string, at most 200 characters","- body: non-empty string, at most 2000 characters","- severity: exactly critical | high | medium | low | info","- confidence: finite number from 0 through 1","- file: non-empty repository-relative path, at most 500 characters","- line_start: integer from 1 through 10000000","- line_end: integer from line_start through 10000000","verdict is exactly APPROVED or REJECTED and must match the legacy VERDICT.","overall_confidence is a finite number from 0 through 1.","```json",'{"findings":[{"title":"Concrete defect","body":"Concrete impact and reproduction path.","severity":"high","confidence":0.95,"file":"src/example.ts","line_start":10,"line_end":10}],"verdict":"REJECTED","overall_confidence":0.95}',"```"].join(`
|
|
4103
|
-
`);_internals205={collectReviewDiff,persistEvidence:persistAutoReviewEvidence,persistReceipt:persistReviewReceipt,readPhaseEvidence:readAutoReviewEvidenceForPhase}});import*as fs147 from"node:fs";import*as path256 from"node:path";function truncateText(value,maximum=MAX_DISPLAY_TEXT){if(!value)return"";if(value.length<=maximum)return value;return`${value.slice(0,Math.max(0,maximum-16))}... [truncated]`}function formatSelector(selector){switch(selector.kind){case"default":return"default (merge-base plus working tree)";case"base":return`base ${selector.ref}`;case"range":return`range ${selector.from}${selector.operator}${selector.to}`;case"working-tree":return"working tree"}}function isPathInside(parent,candidate2){let relative59=path256.relative(parent,candidate2);return relative59.length>0&&relative59!==".."&&!relative59.startsWith(`..${path256.sep}`)&&!path256.isAbsolute(relative59)}function sameFileSnapshot3(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 readEvidence(evidencePath,directory){if(!evidencePath)return null;let swarmRoot=path256.resolve(directory,".swarm"),candidate2=path256.resolve(evidencePath);if(!isPathInside(swarmRoot,candidate2))return null;let descriptor;try{let statBeforeOpen=fs147.lstatSync(candidate2,{bigint:!0});if(!statBeforeOpen.isFile()||statBeforeOpen.isSymbolicLink()||statBeforeOpen.size>BigInt(MAX_EVIDENCE_BYTES))return null;let canonicalBeforeOpen=fs147.realpathSync(candidate2);if(!isPathInside(swarmRoot,canonicalBeforeOpen))return null;descriptor=fs147.openSync(canonicalBeforeOpen,"r");let openedBeforeRead=fs147.fstatSync(descriptor,{bigint:!0}),canonicalAfterOpen=fs147.realpathSync(candidate2);if(!openedBeforeRead.isFile()||!sameFileSnapshot3(statBeforeOpen,openedBeforeRead)||!sameFileSnapshot3(openedBeforeRead,fs147.lstatSync(candidate2,{bigint:!0}))||canonicalBeforeOpen!==canonicalAfterOpen||!isPathInside(swarmRoot,canonicalAfterOpen))return null;let buffer=Buffer.alloc(Number(openedBeforeRead.size)),bytesRead=fs147.readSync(descriptor,buffer,0,buffer.length,0),openedAfterRead=fs147.fstatSync(descriptor,{bigint:!0});if(bytesRead!==buffer.length||!sameFileSnapshot3(openedBeforeRead,openedAfterRead))return null;let parsed=JSON.parse(buffer.toString("utf8"));return isAutoReviewEvidence(parsed)?parsed:null}catch{return null}finally{if(descriptor!==void 0)try{fs147.closeSync(descriptor)}catch{}}}function sortedFindings(result){return[...result.findings].sort((left,right)=>{let severity2=(SEVERITY_RANK2[left.effective_severity]??99)-(SEVERITY_RANK2[right.effective_severity]??99);if(severity2!==0)return severity2;let validationRank=(finding)=>finding.validation?.disposition==="CONFIRMED"?0:finding.validation?.disposition==="UNVERIFIED"?1:finding.validation?.disposition==="DISPROVED"?2:3,validation=validationRank(left)-validationRank(right);if(validation!==0)return validation;return left.finding_id.localeCompare(right.finding_id)})}function costLine(evidence2){if(!evidence2)return"Cost: unavailable (durable evidence was not readable)";let cost=evidence2.cost,dollars=cost.cost_usd===null?`unavailable (${cost.cost_source})`:`$${cost.cost_usd.toFixed(6)} (${cost.cost_source})`,axis=(value)=>value===null?"unknown":
|
|
4102
|
+
`)}function emptyResult4(status2,message,blocked,blockReason){return{status:status2,blocked,blockReason,message,findings:[],blockingFindings:[],validationComplete:!1,modelCalls:0}}async function persistErrorResult(input,diff,result,error93,dispatches,promptRequest){let evidence2=baseEvidence(input,diff,"error");evidence2.scope.manifest=await materializeAutoReviewManifest(input.directory,diff.manifest,input.config),evidence2.policy.digest=evidence2.scope.manifest.review_policy_digest,evidence2.review.error=error93,addCost(evidence2,dispatches);try{result.evidencePath=await _internals205.persistEvidence(input.directory,evidence2)}catch{if(input.config.final_review.mode==="gate")result.blocked=!0,result.blockReason="EVIDENCE_PERSISTENCE_FAILED"}return result.scopeHash=diff.scopeHash,result.manifestHash=evidence2.scope.manifest.hash,result.scopeComplete=diff.completeness.complete,Object.assign(result,scopeResultFields(diff,promptRequest)),result}async function runReviewEngine(input){let gateMode=input.config.final_review.mode==="gate",maxBytes=input.trigger==="task_completion"?input.config.max_diff_kb*1024:input.config.final_review.max_diff_bytes,timeoutMs=input.trigger==="task_completion"?input.config.timeout_ms:input.config.final_review.timeout_ms,diff=await _internals205.collectReviewDiff({directory:input.directory,selector:input.selector,maxBytes});if(diff.status==="error"){let result2=emptyResult4("error",`Diff collection failed: ${diff.reason}`,gateMode,gateMode?"DIFF_COLLECTION_FAILED":void 0);return input.injectAdvisory?.(input.sessionID,advisoryMessage(input,result2)),result2}if(diff.status==="clean"){let evidence3=baseEvidence(input,diff,"clean");evidence3.scope.manifest=await materializeAutoReviewManifest(input.directory,diff.manifest,input.config),evidence3.policy.digest=evidence3.scope.manifest.review_policy_digest;let evidencePath2;try{evidencePath2=await _internals205.persistEvidence(input.directory,evidence3,{verifyCurrent:createScopeVerifier(input,diff,maxBytes)})}catch(error93){if(error93 instanceof ReviewScopeStaleError)return stalePersistenceResult(input,maxBytes,"Review scope changed before clean evidence could be committed.",0)}let blocked2=gateMode&&!evidencePath2;return{...emptyResult4("clean","Review scope is clean.",blocked2,blocked2?"EVIDENCE_PERSISTENCE_FAILED":void 0),validationComplete:!0,scopeHash:diff.scopeHash,manifestHash:evidence3.scope.manifest.hash,scopeComplete:diff.completeness.complete,...scopeResultFields(diff),evidencePath:evidencePath2}}let promptRequest=buildReviewPromptRequest({trigger:input.trigger,diff,phase:input.phase}),reviewManifest=await materializeAutoReviewManifest(input.directory,diff.manifest,input.config);if(input.phase!==void 0&&(input.trigger==="phase_completion"||input.trigger==="plan_completion")){let existing=_internals205.readPhaseEvidence(input.directory,input.phase),integrity=existing?validateAutoReviewEvidenceIntegrity(input.directory,existing,{scopeHash:diff.scopeHash,phase:input.phase,trigger:input.trigger,policy:{mode:input.config.final_review.mode,min_confidence:input.config.min_confidence,structured_findings:input.config.structured_findings,validate_findings:input.config.validate_findings},scopeContent:diff.canonicalText}):void 0;if(existing?.review.status==="completed"&&existing.schema_version===2&&existing.scope.manifest?.hash===reviewManifest.hash&&integrity?.ok&&integrity.receipt){let validationsById=new Map((integrity.receipt.finding_validations??[]).map((validation)=>[validation.finding_id,validation])),findings2=canonicalizeValidationCandidates(integrity.receipt.structured_findings??[]).map((candidate2)=>{return{...anchorFinding(input.directory,diff,candidate2,input.config.min_confidence),validation:validationsById.get(candidate2.finding_id)}}),validationCandidates2=findings2.filter((finding)=>finding.anchored&&isGateSeverity(finding.effective_severity)),validationComplete2=!((input.config.validate_findings||gateMode)&&validationCandidates2.length>0)||validationCandidates2.every((finding)=>finding.validation),blockingFindings2=validationCandidates2.filter((finding)=>finding.validation?.disposition==="CONFIRMED"),blocked2=gateMode&&(!diff.completeness.complete||!validationComplete2||blockingFindings2.length>0);return{status:"completed",reviewVerdict:integrity.receipt.verdict,blocked:blocked2,blockReason:blocked2?!diff.completeness.complete?"INCOMPLETE_SCOPE":!validationComplete2?"INCOMPLETE_VALIDATION":"CONFIRMED_FINDINGS":void 0,message:"Reused fresh auto-review evidence for the unchanged scope.",findings:findings2,blockingFindings:blockingFindings2,validationComplete:validationComplete2,receiptPath:existing.receipt_path,evidencePath:path255.join(input.directory,".swarm","evidence",String(input.phase),"auto-review.json"),scopeHash:existing.scope.hash,manifestHash:existing.scope.manifest?.hash,scopeComplete:diff.completeness.complete,...scopeResultFields(diff,promptRequest),reviewModel:existing.review.model,modelCalls:0}}}if(!promptRequest.fits){let error93=`Rendered review prompt requires ${promptRequest.requestBytes} bytes after omitting all fallback file names, exceeding the ${MAX_EPHEMERAL_PROMPT_BYTE_LIMIT}-byte isolated-session ceiling.`,result2=await persistErrorResult(input,diff,emptyResult4("error",`Review dispatch failed: ${error93}`,gateMode,gateMode?"REVIEW_DISPATCH_FAILED":void 0),error93,[],promptRequest);return input.injectAdvisory?.(input.sessionID,advisoryMessage(input,result2)),result2}let dispatched=await dispatchReviewerWithFallback(input,promptRequest.prompt,timeoutMs,promptRequest.promptByteLimit);if(dispatched.result.status!=="completed"){let dispatchDetail=dispatched.result.error??dispatched.result.status,quotaAnnotation=isQuotaError(dispatchDetail)?" (model quota/usage limit exhausted across all configured fallbacks)":"",result2=await persistErrorResult(input,diff,emptyResult4("error",`Review dispatch failed${quotaAnnotation}: ${dispatchDetail}`,gateMode,gateMode?"REVIEW_DISPATCH_FAILED":void 0),dispatchDetail,dispatched.attempts,promptRequest);return result2.modelCalls=dispatched.attempts.length,input.injectAdvisory?.(input.sessionID,advisoryMessage(input,result2)),result2}let parsed=parseReviewerOutput(dispatched.result.text,{structured:input.config.structured_findings});if(!parsed){let result2=await persistErrorResult(input,diff,emptyResult4("error","Reviewer returned no machine-readable verdict.",gateMode,gateMode?"INCOMPLETE_REVIEW_EVIDENCE":void 0),"Reviewer returned no machine-readable verdict.",dispatched.attempts,promptRequest);return result2.modelCalls=dispatched.attempts.length,input.injectAdvisory?.(input.sessionID,advisoryMessage(input,result2)),result2}let legacyVerdict=[...dispatched.result.text.matchAll(/^\s*VERDICT\s*:\s*(APPROVED|REJECTED)\s*$/gim)].at(-1)?.[1]?.toLowerCase();if(legacyVerdict&&legacyVerdict!==parsed.verdict){let result2=await persistErrorResult(input,diff,emptyResult4("error","Reviewer legacy and structured verdicts disagree.",gateMode,gateMode?"INCOMPLETE_REVIEW_EVIDENCE":void 0),"Reviewer legacy and structured verdicts disagree.",dispatched.attempts,promptRequest);return result2.modelCalls=dispatched.attempts.length,result2}let findings=canonicalizeValidationCandidates(parsed.structuredFindings??[]).map((candidate2)=>anchorFinding(input.directory,diff,candidate2,input.config.min_confidence)),validationCandidates=findings.filter((finding)=>finding.anchored&&isGateSeverity(finding.effective_severity)),validationComplete=!0,validationError,allDispatches=[...dispatched.attempts];if((input.config.validate_findings||gateMode)&&validationCandidates.length>0){let validation=await runFindingValidation({dispatcher:input.dispatcher,directory:input.directory,parentSessionId:input.sessionID,agentName:input.validatorAgent,model:input.validatorModel,fallbackModels:input.validatorFallbackModels,timeoutMs:input.config.validation_timeout_ms,findings:validationCandidates,scopeContext:{selector:diff.selector,canonicalText:diff.canonicalText,scopeHash:diff.scopeHash,headSha:diff.headSha,baseRef:diff.baseRef,baseSha:diff.baseSha,mergeBase:diff.mergeBase,rangeToSha:diff.rangeToSha,completeness:diff.completeness}});validationComplete=validation.complete,validationError=validation.error;for(let[retryIndex,attempt]of validation.attempts.entries())allDispatches.push(attempt),telemetry.delegationBegin(input.sessionID,input.validatorAgent,input.trigger),telemetry.delegationEnd(input.sessionID,input.validatorAgent,input.trigger,attempt.status,{...attempt.costFields,gate:"finding_validation",retry_index:retryIndex});let byId=new Map(validation.validations.map((item)=>[item.finding_id,item]));findings=findings.map((finding)=>({...finding,validation:byId.get(finding.finding_id)}))}let currentScope=await _internals205.collectReviewDiff({directory:input.directory,selector:input.selector,maxBytes});if(currentScope.status==="error"){let result2=emptyResult4("error",`Review scope freshness check failed after model dispatch: ${currentScope.reason}. Stale reviewer and validator output was discarded and provides no current coverage.`,gateMode,gateMode?"REVIEW_SCOPE_STALE":void 0);return result2.modelCalls=allDispatches.length,input.injectAdvisory?.(input.sessionID,advisoryMessage(input,result2)),result2}let freshnessMismatches=scopeFreshnessMismatches(diff,currentScope);if(freshnessMismatches.length>0){let staleMessage=`Review scope changed during model dispatch (${freshnessMismatches.join(", ")}). Stale reviewer and validator output was discarded and provides no current coverage.`,result2=await persistErrorResult(input,currentScope,emptyResult4("error",staleMessage,gateMode,gateMode?"REVIEW_SCOPE_STALE":void 0),staleMessage,allDispatches);return result2.modelCalls=allDispatches.length,input.injectAdvisory?.(input.sessionID,advisoryMessage(input,result2)),result2}let blockingFindings=findings.filter((finding)=>finding.anchored&&isGateSeverity(finding.effective_severity)&&finding.validation?.disposition==="CONFIRMED"),evidence2=baseEvidence(input,diff,"completed");evidence2.scope.manifest=reviewManifest,evidence2.policy.digest=reviewManifest.review_policy_digest,evidence2.review={status:"completed",output_mode:parsed.outputMode,overall_confidence:parsed.overallConfidence,model:dispatched.result.modelId,duration_ms:dispatched.result.durationMs},evidence2.findings=findings,evidence2.validation_complete=validationComplete,evidence2.validation_error=validationError,evidence2.blocking_finding_ids=blockingFindings.map((finding)=>finding.finding_id),addCost(evidence2,allDispatches);let receiptPath,receiptId;try{let receipt=parsed.verdict==="approved"?buildApprovedReceipt({agent:input.reviewerAgent,sessionId:input.sessionID,scopeContent:diff.canonicalText,scopeDescription:`${input.trigger}-review`,checkedAspects:["correctness","security","regressions"],validatedClaims:["structured review completed"],caveats:findings.filter((finding)=>!finding.anchored).map((finding)=>`${finding.title}: ${finding.anchor_rejection??"unanchored"}`),structuredFindings:parsed.structuredFindings,reviewOverallConfidence:parsed.overallConfidence,findingValidations:findings.map((finding)=>finding.validation).filter((item)=>Boolean(item))}):buildRejectedReceipt({agent:input.reviewerAgent,sessionId:input.sessionID,scopeContent:diff.canonicalText,scopeDescription:`${input.trigger}-review`,blockingFindings:findings.map((finding)=>({location:`${finding.file}:${finding.line_start}`,summary:finding.body,line:finding.line_start,severity:finding.severity,finding_id:finding.finding_id,title:finding.title,body:finding.body,confidence:finding.confidence,file:finding.file,line_start:finding.line_start,line_end:finding.line_end,effective_severity:finding.effective_severity,validator_disposition:finding.validation?.disposition,validator_confidence:finding.validation?.confidence,validator_evidence:finding.validation?.evidence,anchor_status:finding.anchored?"anchored":"unanchored",anchor_reason:finding.anchor_rejection})),evidenceReferences:findings.map((finding)=>`${finding.file}:${finding.line_start}`),passConditions:parsed.fixes,summary:`${input.trigger} review`,structuredFindings:parsed.structuredFindings,reviewOverallConfidence:parsed.overallConfidence,findingValidations:findings.map((finding)=>finding.validation).filter((item)=>Boolean(item))});receiptId=receipt.id,receiptPath=await _internals205.persistReceipt(input.directory,receipt,{verifyCurrent:createScopeVerifier(input,diff,maxBytes)}),evidence2.receipt_path=receiptPath}catch(error93){if(error93 instanceof ReviewScopeStaleError)return stalePersistenceResult(input,maxBytes,"Review scope changed before the review receipt could be committed.",allDispatches.length);evidence2.review.error=`receipt persistence failed: ${error93 instanceof Error?error93.message:String(error93)}`}let blocked=!1,blockReason;if(gateMode&&!diff.completeness.complete)blocked=!0,blockReason="INCOMPLETE_SCOPE";else if(gateMode&&parsed.outputMode!=="structured")blocked=!0,blockReason="INCOMPLETE_REVIEW_EVIDENCE";else if(gateMode&&!validationComplete)blocked=!0,blockReason="INCOMPLETE_VALIDATION";else if(gateMode&&!receiptPath)blocked=!0,blockReason="EVIDENCE_PERSISTENCE_FAILED";else if(gateMode&&blockingFindings.length>0)blocked=!0,blockReason="CONFIRMED_FINDINGS";let evidencePath;try{evidencePath=await _internals205.persistEvidence(input.directory,evidence2,{verifyCurrent:createScopeVerifier(input,diff,maxBytes)})}catch(error93){if(receiptPath&&receiptId)await removeReviewReceipt(input.directory,receiptPath,receiptId).catch(()=>{}),receiptPath=void 0,evidence2.receipt_path=void 0;if(error93 instanceof ReviewScopeStaleError)return stalePersistenceResult(input,maxBytes,"Review scope changed before auto-review evidence could be committed.",allDispatches.length);if(gateMode)blocked=!0,blockReason="EVIDENCE_PERSISTENCE_FAILED"}let result={status:"completed",reviewVerdict:parsed.verdict,blocked,blockReason,message:blocked?`Review gate blocked: ${blockReason}`:`Review completed with ${findings.length} finding(s).`,findings,blockingFindings,validationComplete,receiptPath,evidencePath,scopeHash:diff.scopeHash,manifestHash:reviewManifest.hash,scopeComplete:diff.completeness.complete,...scopeResultFields(diff,promptRequest),reviewModel:dispatched.result.modelId,modelCalls:allDispatches.length};return input.injectAdvisory?.(input.sessionID,advisoryMessage(input,result)),result}var REVIEW_SYSTEM_PROMPT,_internals205;var init_engine2=__esm(()=>{init_ephemeral_agent_dispatcher();init_invocation_failure();init_review_receipt();init_review_receipt_collector();init_cost_accounting();init_telemetry();init_provider_error_classification();init_diff_source();init_evidence2();init_finding_validator();REVIEW_SYSTEM_PROMPT=["You are an isolated repository-aware code review model.","Review only defects introduced by the supplied exact diff. Inspect the repository when needed, but never edit it.","Do not report pre-existing issues, speculation, style-only preferences, or locations outside changed hunks.","A finding must identify a concrete impact and a current-side line overlapping the diff.","If there is no finding the author would definitely want to fix, prefer an empty findings array.","","Your complete response must be at most 800 output tokens.","Emit each of these legacy fields exactly once, in this order:","VERDICT: APPROVED | REJECTED","REUSE_RE_VERIFICATION: VERIFIED | DUPLICATION_DETECTED | SKIPPED","RISK: LOW | MEDIUM | HIGH | CRITICAL","ISSUES: none (see structured findings JSON)","ACCEPTANCE_SATISFACTION: SATISFIED | PARTIAL | NOT_SATISFIED — concise evidence","TASK: task id or unknown","SKILL_COMPLIANCE: COMPLIANT | PARTIAL | VIOLATED — concise evidence","DIRECTIVE_COMPLIANCE: one line per supplied directive, or none","FIXES: required changes if rejected, otherwise none","","Then emit exactly one fenced json block and no other JSON block.","The JSON object is strict: no additional keys are allowed at the root or finding level.","The root keys are exactly findings, verdict, and overall_confidence.","findings is an array of at most 50 objects. Each finding has exactly these keys:","- title: non-empty string, at most 200 characters","- body: non-empty string, at most 2000 characters","- severity: exactly critical | high | medium | low | info","- confidence: finite number from 0 through 1","- file: non-empty repository-relative path, at most 500 characters","- line_start: integer from 1 through 10000000","- line_end: integer from line_start through 10000000","verdict is exactly APPROVED or REJECTED and must match the legacy VERDICT.","overall_confidence is a finite number from 0 through 1.","```json",'{"findings":[{"title":"Concrete defect","body":"Concrete impact and reproduction path.","severity":"high","confidence":0.95,"file":"src/example.ts","line_start":10,"line_end":10}],"verdict":"REJECTED","overall_confidence":0.95}',"```"].join(`
|
|
4103
|
+
`);_internals205={collectReviewDiff,persistEvidence:persistAutoReviewEvidence,persistReceipt:persistReviewReceipt,readPhaseEvidence:readAutoReviewEvidenceForPhase}});import*as fs147 from"node:fs";import*as path256 from"node:path";function truncateText(value,maximum=MAX_DISPLAY_TEXT){if(!value)return"";if(value.length<=maximum)return value;return`${value.slice(0,Math.max(0,maximum-16))}... [truncated]`}function formatSelector(selector){switch(selector.kind){case"default":return"default (merge-base plus working tree)";case"base":return`base ${selector.ref}`;case"range":return`range ${selector.from}${selector.operator}${selector.to}`;case"working-tree":return"working tree"}}function isPathInside(parent,candidate2){let relative59=path256.relative(parent,candidate2);return relative59.length>0&&relative59!==".."&&!relative59.startsWith(`..${path256.sep}`)&&!path256.isAbsolute(relative59)}function sameFileSnapshot3(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 readEvidence(evidencePath,directory){if(!evidencePath)return null;let swarmRoot=path256.resolve(directory,".swarm"),candidate2=path256.resolve(evidencePath);if(!isPathInside(swarmRoot,candidate2))return null;let descriptor;try{let statBeforeOpen=fs147.lstatSync(candidate2,{bigint:!0});if(!statBeforeOpen.isFile()||statBeforeOpen.isSymbolicLink()||statBeforeOpen.size>BigInt(MAX_EVIDENCE_BYTES))return null;let canonicalBeforeOpen=fs147.realpathSync(candidate2);if(!isPathInside(swarmRoot,canonicalBeforeOpen))return null;descriptor=fs147.openSync(canonicalBeforeOpen,"r");let openedBeforeRead=fs147.fstatSync(descriptor,{bigint:!0}),canonicalAfterOpen=fs147.realpathSync(candidate2);if(!openedBeforeRead.isFile()||!sameFileSnapshot3(statBeforeOpen,openedBeforeRead)||!sameFileSnapshot3(openedBeforeRead,fs147.lstatSync(candidate2,{bigint:!0}))||canonicalBeforeOpen!==canonicalAfterOpen||!isPathInside(swarmRoot,canonicalAfterOpen))return null;let buffer=Buffer.alloc(Number(openedBeforeRead.size)),bytesRead=fs147.readSync(descriptor,buffer,0,buffer.length,0),openedAfterRead=fs147.fstatSync(descriptor,{bigint:!0});if(bytesRead!==buffer.length||!sameFileSnapshot3(openedBeforeRead,openedAfterRead))return null;let parsed=JSON.parse(buffer.toString("utf8"));return isAutoReviewEvidence(parsed)?parsed:null}catch{return null}finally{if(descriptor!==void 0)try{fs147.closeSync(descriptor)}catch{}}}function sortedFindings(result){return[...result.findings].sort((left,right)=>{let severity2=(SEVERITY_RANK2[left.effective_severity]??99)-(SEVERITY_RANK2[right.effective_severity]??99);if(severity2!==0)return severity2;let validationRank=(finding)=>finding.validation?.disposition==="CONFIRMED"?0:finding.validation?.disposition==="UNVERIFIED"?1:finding.validation?.disposition==="DISPROVED"?2:3,validation=validationRank(left)-validationRank(right);if(validation!==0)return validation;return left.finding_id.localeCompare(right.finding_id)})}function costLine(evidence2){if(!evidence2)return"Cost: unavailable (durable evidence was not readable)";let cost=evidence2.cost,dollars=cost.cost_usd===null?`unavailable (${cost.cost_source})`:`$${cost.cost_usd.toFixed(6)} (${cost.cost_source})`,axis=(value)=>value===null?"unknown":value.toLocaleString("en-US");return`Cost: ${dollars}; tokens ${axis(cost.tokens_input)} input / ${axis(cost.tokens_output)} output / ${axis(cost.tokens_reasoning)} reasoning / ${axis(cost.tokens_cache)} cache; prompt ${cost.prompt_bytes} bytes`}function renderHuman(result,evidence2,requestedSelector){let selector=evidence2?.scope.selector??requestedSelector,completeness=evidence2?.scope.completeness,scopeWarnings=(result.scopeWarnings??[]).slice(0,MAX_SCOPE_WARNINGS),scopeFiles=(result.scopeFileList??[]).slice(0,MAX_SCOPE_FILES2),lines=["## Swarm Review","",`Status: ${result.status}${result.blocked?` — BLOCKED (${result.blockReason??"unspecified"})`:" — advisory"}`,`Scope: ${formatSelector(selector)}; ${completeness?`${completeness.complete?"complete":"incomplete"}${completeness.truncated?", truncated":""}; ${evidence2?.scope.review_text_bytes??0} bytes`:"scope metadata unavailable"}`,`Scope hash: ${result.scopeHash??evidence2?.scope.hash??"unavailable"}`,`Validation: ${result.validationComplete?"complete":"incomplete"}`,`Reviewer model: ${result.reviewModel??evidence2?.review.model??"registered agent default / unavailable"}`,`Model calls: ${result.modelCalls}`,costLine(evidence2),`Receipt: ${result.receiptPath??evidence2?.receipt_path??"unavailable"}`,`Evidence: ${result.evidencePath??"unavailable"}`];if(scopeWarnings.length>0)lines.push("",`### Scope warnings (${result.scopeWarnings?.length??scopeWarnings.length})`,...scopeWarnings.map((warning)=>`- ${truncateText(warning)}`));if(result.scopeFileList!==void 0){let omitted=Math.max(0,result.scopeFileList.length-scopeFiles.length);if(lines.push("",`### Scope files (${result.scopeFileList.length}${result.scopeFileListComplete===!1?", fallback list may be incomplete":""})`,...scopeFiles.map((file3)=>`- ${truncateText(file3,300)}`)),omitted>0)lines.push(`- ... ${omitted} additional file(s) omitted`)}lines.push("",`### Findings (${result.findings.length})`);let findings=sortedFindings(result);if(findings.length===0)lines.push("No findings reported.");else for(let index=0;index<findings.length;index++){let finding=findings[index],validation=finding.validation?.disposition??"NOT_VALIDATED",anchor=finding.anchored?"anchored":`unanchored — ${truncateText(finding.anchor_rejection,240)||"reason unavailable"}`;if(lines.push("",`${index+1}. [${finding.effective_severity.toUpperCase()} / ${validation}] ${truncateText(finding.title,300)}`,` Location: ${truncateText(finding.file,300)}:${finding.line_start}${finding.line_end!==finding.line_start?`-${finding.line_end}`:""}`,` Anchor: ${anchor}; confidence ${finding.confidence.toFixed(2)}; duplicates ${finding.duplicate_count}`,` ${truncateText(finding.body)}`),finding.validation?.evidence)lines.push(` Validator evidence: ${truncateText(finding.validation.evidence)}`)}return lines.join(`
|
|
4104
4104
|
`)}function findingForJson(finding){return{finding_id:truncateText(finding.finding_id,128),title:truncateText(finding.title),body:truncateText(finding.body),severity:finding.severity,effective_severity:finding.effective_severity,confidence:finding.confidence,file:truncateText(finding.file),line_start:finding.line_start,line_end:finding.line_end,duplicate_count:finding.duplicate_count,anchor:{anchored:finding.anchored,rejection:truncateText(finding.anchor_rejection)},validation:finding.validation?{disposition:finding.validation.disposition,confidence:finding.validation.confidence,evidence:truncateText(finding.validation.evidence)}:null}}function renderJson(result,evidence2,requestedSelector){let ranked=sortedFindings(result).map(findingForJson),scopeWarnings=(result.scopeWarnings??[]).slice(0,MAX_SCOPE_WARNINGS).map((warning)=>truncateText(warning)),scopeFiles=(result.scopeFileList??[]).slice(0,MAX_SCOPE_FILES2).map((file3)=>truncateText(file3,300)),payload={schema_version:1,command:"review",status:result.status,blocked:result.blocked,block_reason:result.blockReason??null,message:truncateText(result.message,1000),scope:{selector:evidence2?.scope.selector??requestedSelector,hash:result.scopeHash??evidence2?.scope.hash??null,complete:evidence2?.scope.completeness.complete??null,truncated:evidence2?.scope.completeness.truncated??null,skip_reasons:(evidence2?.scope.completeness.skipReasons??[]).slice(0,50).map((reason)=>({code:reason.code,path:truncateText(reason.path),detail:truncateText(reason.detail)})),review_text_bytes:evidence2?.scope.review_text_bytes??null,warnings:scopeWarnings,warnings_omitted:Math.max(0,(result.scopeWarnings?.length??0)-scopeWarnings.length),file_list:scopeFiles,file_list_complete:result.scopeFileListComplete??null,files_omitted:Math.max(0,(result.scopeFileList?.length??0)-scopeFiles.length)},validation_complete:result.validationComplete,model:result.reviewModel??evidence2?.review.model??null,model_calls:result.modelCalls,cost:evidence2?.cost??null,receipt_path:result.receiptPath??evidence2?.receipt_path??null,evidence_path:result.evidencePath??null,findings:ranked,findings_omitted:0},wrapper=(body2)=>`${JSON_OPEN_TAG}
|
|
4105
4105
|
${body2}
|
|
4106
4106
|
${JSON_CLOSE_TAG}`,body=JSON.stringify(payload,null,2);while(Buffer.byteLength(wrapper(body),"utf8")>MAX_JSON_WRAPPER_BYTES&&ranked.length>0)ranked.pop(),payload.findings_omitted=result.findings.length-ranked.length,body=JSON.stringify(payload,null,2);if(Buffer.byteLength(wrapper(body),"utf8")>MAX_JSON_WRAPPER_BYTES)body=JSON.stringify({schema_version:1,command:"review",status:"error",message:"bounded review JSON payload could not include result details"});return wrapper(body)}async function handleReviewCommand(ctx){let parsed=parseReviewDiffSelector(ctx.args);if(!parsed.ok)return[`Review argument error [${parsed.code}]: ${parsed.reason}`,"Usage: /swarm review [--base <ref> | --range <from..to|from...to> | --working-tree] [--json]"].join(`
|
|
@@ -7813,10 +7813,10 @@ ${added.join(`
|
|
|
7813
7813
|
Ignoring will not affect already-tracked files. To stop tracking them, run:
|
|
7814
7814
|
git rm -r --cached .swarm
|
|
7815
7815
|
echo ".swarm/" >> .gitignore
|
|
7816
|
-
git commit -m "Stop tracking opencode-swarm runtime state"`)}catch{}}var _internals302={bunSpawn,resolveGitExecutable};function getDeclaredScope(taskId,directory){try{let planPath=path365.join(directory,".swarm","plan.json");if(!fs224.existsSync(planPath))return null;let raw=fs224.readFileSync(planPath,"utf-8"),plan=JSON.parse(raw);for(let phase of plan.phases??[])for(let task2 of phase.tasks??[]){if(task2.id!==taskId)continue;let ft=task2.files_touched;if(Array.isArray(ft)&&ft.length>0)return ft;if(typeof ft==="string"&&ft.length>0)return[ft];return null}return null}catch{return null}}var GIT_DIFF_SPAWN_OPTIONS={timeout:ENSURE_SWARM_GIT_EXCLUDED_PER_CALL_TIMEOUT_MS,stdin:"ignore",stdout:"pipe",stderr:"pipe"};async function getChangedFiles2(directory){try{let gitExecutable=_internals302.resolveGitExecutable(),proc=_internals302.bunSpawn([gitExecutable,"diff","--name-only","HEAD~1"],{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)return
|
|
7817
|
-
`).map((f)=>f.trim()).filter((f)=>f.length>0);let proc2=_internals302.bunSpawn([gitExecutable,"diff","--name-only","HEAD"],{cwd:directory,...GIT_DIFF_SPAWN_OPTIONS}),exitCode2,stdout2;try{[exitCode2,stdout2]=await Promise.all([proc2.exited,proc2.stdout.text()])}finally{try{proc2.kill()}catch{}}if(exitCode2===0)return
|
|
7818
|
-
`).map((f)=>f.trim()).filter((f)=>f.length>0);return null}catch{return null}}async function validateDiffScope(taskId,directory){try{let declaredScope=getDeclaredScope(taskId,directory);if(!declaredScope)return null;let changedFiles=await getChangedFiles2(directory);if(!changedFiles)return null;let nonSwarmFiles=changedFiles.filter((f)=>!f.replace(/\\/g,"/").replace(/^\.\//,"").startsWith(".swarm/")),normalise=(p)=>p.replace(/\\/g,"/").replace(/^\.\//,""),normScope=new Set(declaredScope.map(normalise)),undeclared=nonSwarmFiles.map(normalise).filter((f)=>!normScope.has(f));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}]. Reviewer should verify these changes are intentional.`}catch{return null}}init_utils2();init_file_locks();var 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"]);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}init_manager();init_routing_enforcement();init_run_memory();init_state2();init_telemetry();init_file_locks();import*as fs225 from"node:fs";import*as path366 from"node:path";var _internals303={listActiveLocks,verifyLeanTurboTaskCompletion};function verifyLeanTurboTaskCompletion(directory,taskId,sessionID){let persisted=null;try{let statePath3=path366.join(directory,".swarm","turbo-state.json");if(!fs225.existsSync(statePath3))return{ok:!1,reason:"Lean Turbo state file not found"};let raw=fs225.readFileSync(statePath3,"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=path366.join(directory,".swarm","evidence",String(phase),"lean-turbo",`${lane.laneId}.json`),expectedDir=path366.join(directory,".swarm","evidence",String(phase),"lean-turbo"),resolvedPath=path366.resolve(evidencePath),resolvedDir=path366.resolve(expectedDir);if(!resolvedPath.startsWith(resolvedDir+path366.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(!fs225.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=_internals303.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=path366.join(directory,".swarm","plan.json"),planRaw=fs225.readFileSync(planPath,"utf-8"),plan=JSON.parse(planRaw);for(let planPhase of plan.phases??[])for(let task2 of planPhase.tasks??[])if(task2.id===taskId&&task2.files_touched){filesTouched=task2.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}}}init_logger();init_project_boundary();init_task_id();init_coder_settlement();init_task_repair();init_task_terminal();init_workflow_wal_file();init_create_tool();init_resolve_working_directory();var _internals304={tryAcquireLock,updateTaskStatus,resolveWorkingDirectory,loadPlan,readTaskEvidenceRaw,hasActiveLeanTurbo,hasActiveTurboMode,verifyLeanTurboTaskCompletion,hasPassedDurableGateEvidence,emitReviewerGateDecision:telemetry.reviewerGateDecision,recordTaskAttempt};async function recordRunMemoryOutcome(directory,input){try{await _internals304.recordTaskAttempt(directory,input)}catch(_error){}}function syncCallerWorkflowFromEvidence(sessionId,taskId,evidence2){if(!sessionId)return;let callerSession=ensureAgentSession(sessionId),workflow=getTaskWorkflowSnapshot(evidence2);callerSession.taskWorkflowStates.set(taskId,workflow.state),callerSession.stageBCompletion?.delete(taskId),callerSession.taskCouncilApproved?.delete(taskId),callerSession.taskCouncilWorkflowGeneration?.delete(taskId),updateTaskWorkflowCache(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((candidate2)=>candidate2.id===taskId)?.files_touched??[]}var VALID_STATUSES2=["pending","in_progress","completed","blocked"];function validateStatus(status2){if(!VALID_STATUSES2.includes(status2))return`Invalid status "${status2}". Must be one of: ${VALID_STATUSES2.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{_internals304.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((candidate2)=>isStageBRouteRequired(candidate2,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&&_internals304.hasActiveLeanTurbo(sessionID)){let resolvedDir2=workingDirectory;try{let leanCheck=_internals304.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&&_internals304.hasActiveTurboMode(sessionID)){let resolvedDir2=workingDirectory;try{let planPath=path367.join(resolvedDir2,".swarm","plan.json"),planRaw=fs226.readFileSync(planPath,"utf-8"),plan=JSON.parse(planRaw);for(let planPhase of plan.phases??[])for(let task2 of planPhase.tasks??[])if(task2.id===taskId&&Array.isArray(task2.files_touched)&&task2.files_touched.length>0){if(!matchesTier3(task2.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=_internals304.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=_internals304.readTaskEvidenceRaw(authoritativeDir,taskId);if(!fallbackDir&&!sessionID&&!evidence2?.workflow)throw legacyDirectCaller;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=_internals304.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=_internals304.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=path367.join(resolvedDir,".swarm","plan.json"),planRaw=fs226.readFileSync(planPath,"utf-8"),plan=JSON.parse(planRaw);for(let planPhase of plan.phases??[])for(let task2 of planPhase.tasks??[])if(task2.id===taskId&&task2.status==="completed"&&_internals304.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(`
|
|
7819
|
-
`);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")}}async function checkReviewerGateWithScope(taskId,workingDirectory,sessionID,fallbackDir){let result=checkReviewerGate(taskId,workingDirectory,!0,sessionID,fallbackDir),scopeWarning=await validateDiffScope(taskId,workingDirectory).catch(()=>null);if(!scopeWarning)return result;return{...result,reason:result.reason?`${result.reason}
|
|
7816
|
+
git commit -m "Stop tracking opencode-swarm runtime state"`)}catch{}}var _internals302={bunSpawn,resolveGitExecutable};function getDeclaredScope(taskId,directory){try{let planPath=path365.join(directory,".swarm","plan.json");if(!fs224.existsSync(planPath))return null;let raw=fs224.readFileSync(planPath,"utf-8"),plan=JSON.parse(raw);for(let phase of plan.phases??[])for(let task2 of phase.tasks??[]){if(task2.id!==taskId)continue;let ft=task2.files_touched;if(Array.isArray(ft)&&ft.length>0)return ft;if(typeof ft==="string"&&ft.length>0)return[ft];return null}return null}catch{return null}}var GIT_DIFF_SPAWN_OPTIONS={timeout:ENSURE_SWARM_GIT_EXCLUDED_PER_CALL_TIMEOUT_MS,stdin:"ignore",stdout:"pipe",stderr:"pipe"};async function getChangedFiles2(directory){try{let gitExecutable=_internals302.resolveGitExecutable(),proc=_internals302.bunSpawn([gitExecutable,"diff","--name-only","HEAD~1"],{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)return{files:stdout.trim().split(`
|
|
7817
|
+
`).map((f)=>f.trim()).filter((f)=>f.length>0),basis:"HEAD~1"};let proc2=_internals302.bunSpawn([gitExecutable,"diff","--name-only","HEAD"],{cwd:directory,...GIT_DIFF_SPAWN_OPTIONS}),exitCode2,stdout2;try{[exitCode2,stdout2]=await Promise.all([proc2.exited,proc2.stdout.text()])}finally{try{proc2.kill()}catch{}}if(exitCode2===0)return{files:stdout2.trim().split(`
|
|
7818
|
+
`).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=_internals302.resolveGitExecutable(),proc=_internals302.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""}}async function validateDiffScope(taskId,directory,attribution){try{let declaredScope=getDeclaredScope(taskId,directory);if(!declaredScope)return null;let normalise=(p)=>p.replace(/\\/g,"/").replace(/^\.\//,""),isSwarmPath=(p)=>normalise(p).startsWith(".swarm/"),normScope=new Set(declaredScope.map(normalise)),canonicaliseAttributionEntry=(raw)=>{let resolved=path365.isAbsolute(raw)?path365.normalize(raw):path365.resolve(directory,raw),relative93=path365.relative(directory,resolved);if(!relative93)return null;if(relative93.startsWith("..")||path365.isAbsolute(relative93))return null;return relative93},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)=>!isSwarmPath(f)).filter((f)=>!normScopeAttribution.has(normalizePath(f))),evidence2="task attribution record"}else{let{files,basis}=await getChangedFiles2(directory);if(!files)return null;if(undeclared=files.filter((f)=>!isSwarmPath(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}}init_utils2();init_file_locks();var 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"]);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}init_manager();init_routing_enforcement();init_run_memory();init_state2();init_telemetry();init_file_locks();import*as fs225 from"node:fs";import*as path366 from"node:path";var _internals303={listActiveLocks,verifyLeanTurboTaskCompletion};function verifyLeanTurboTaskCompletion(directory,taskId,sessionID){let persisted=null;try{let statePath3=path366.join(directory,".swarm","turbo-state.json");if(!fs225.existsSync(statePath3))return{ok:!1,reason:"Lean Turbo state file not found"};let raw=fs225.readFileSync(statePath3,"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=path366.join(directory,".swarm","evidence",String(phase),"lean-turbo",`${lane.laneId}.json`),expectedDir=path366.join(directory,".swarm","evidence",String(phase),"lean-turbo"),resolvedPath=path366.resolve(evidencePath),resolvedDir=path366.resolve(expectedDir);if(!resolvedPath.startsWith(resolvedDir+path366.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(!fs225.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=_internals303.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=path366.join(directory,".swarm","plan.json"),planRaw=fs225.readFileSync(planPath,"utf-8"),plan=JSON.parse(planRaw);for(let planPhase of plan.phases??[])for(let task2 of planPhase.tasks??[])if(task2.id===taskId&&task2.files_touched){filesTouched=task2.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}}}init_logger();init_project_boundary();init_task_id();init_coder_settlement();init_task_repair();init_task_terminal();init_workflow_wal_file();init_create_tool();init_resolve_working_directory();var _internals304={tryAcquireLock,updateTaskStatus,resolveWorkingDirectory,loadPlan,readTaskEvidenceRaw,hasActiveLeanTurbo,hasActiveTurboMode,verifyLeanTurboTaskCompletion,hasPassedDurableGateEvidence,emitReviewerGateDecision:telemetry.reviewerGateDecision,recordTaskAttempt};async function recordRunMemoryOutcome(directory,input){try{await _internals304.recordTaskAttempt(directory,input)}catch(_error){}}function syncCallerWorkflowFromEvidence(sessionId,taskId,evidence2){if(!sessionId)return;let callerSession=ensureAgentSession(sessionId),workflow=getTaskWorkflowSnapshot(evidence2);callerSession.taskWorkflowStates.set(taskId,workflow.state),callerSession.stageBCompletion?.delete(taskId),callerSession.taskCouncilApproved?.delete(taskId),callerSession.taskCouncilWorkflowGeneration?.delete(taskId),updateTaskWorkflowCache(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((candidate2)=>candidate2.id===taskId)?.files_touched??[]}var VALID_STATUSES2=["pending","in_progress","completed","blocked"];function validateStatus(status2){if(!VALID_STATUSES2.includes(status2))return`Invalid status "${status2}". Must be one of: ${VALID_STATUSES2.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{_internals304.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((candidate2)=>isStageBRouteRequired(candidate2,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&&_internals304.hasActiveLeanTurbo(sessionID)){let resolvedDir2=workingDirectory;try{let leanCheck=_internals304.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&&_internals304.hasActiveTurboMode(sessionID)){let resolvedDir2=workingDirectory;try{let planPath=path367.join(resolvedDir2,".swarm","plan.json"),planRaw=fs226.readFileSync(planPath,"utf-8"),plan=JSON.parse(planRaw);for(let planPhase of plan.phases??[])for(let task2 of planPhase.tasks??[])if(task2.id===taskId&&Array.isArray(task2.files_touched)&&task2.files_touched.length>0){if(!matchesTier3(task2.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=_internals304.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=_internals304.readTaskEvidenceRaw(authoritativeDir,taskId);if(!fallbackDir&&!sessionID&&!evidence2?.workflow)throw legacyDirectCaller;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=_internals304.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=_internals304.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=path367.join(resolvedDir,".swarm","plan.json"),planRaw=fs226.readFileSync(planPath,"utf-8"),plan=JSON.parse(planRaw);for(let planPhase of plan.phases??[])for(let task2 of planPhase.tasks??[])if(task2.id===taskId&&task2.status==="completed"&&_internals304.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(`
|
|
7819
|
+
`);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")}}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):[],scopeWarning=await validateDiffScope(taskId,workingDirectory,sessionID&&attributedFiles.length>0?{attributedFiles}:void 0).catch(()=>null);if(!scopeWarning)return result;return{...result,reason:result.reason?`${result.reason}
|
|
7820
7820
|
${scopeWarning}`:scopeWarning}}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=path367.join(workingDirectory,".swarm","plan.json"),planRaw=fs226.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=_internals304.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=path367.join(directory,".swarm","plan.json");if(!fs226.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=fs226.realpathSync(path367.resolve(directory)),canonicalRoot2=fs226.realpathSync(path367.resolve(fallbackDir));if(isStrictPathDescendant(canonicalDir,canonicalRoot2)&&!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 _internals304.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((task2)=>task2.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: re-opening settled task ${args2.task_id} to in_progress`)}let agentName=(ctx?.sessionID?swarmState.activeAgent.get(ctx.sessionID):void 0)??"update-task-status";if(args2.status==="completed"){if(!fallbackDir&&!ctx?.sessionID)recoverTaskStateFromDelegations(args2.task_id,directory);let phaseRequiresReviewer=!0;try{let planPath2=path367.join(directory,".swarm","plan.json"),planRaw=fs226.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}catch{}let councilCheck=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){let reviewerCheck=await checkReviewerGateWithScope(args2.task_id,directory,ctx?.sessionID,ctx?.sessionID?fallbackDir:void 0);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 _internals304.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 _internals304.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((task2)=>task2.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:()=>_internals304.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((task2)=>task2.id===args2.task_id)),lockedPhaseRequiresReviewer=!lockedTaskPhase?.required_agents||lockedTaskPhase.required_agents.includes("reviewer"),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,resolveTerminal:(evidence2)=>({targetStatus:"completed",qaExempt:!lockedPhaseRequiresReviewer,readOnlyNoMutation:!lockedPhaseRequiresReviewer?!1:isReadOnlyNoMutationEligible(evidence2,{currentDeclaredFiles:lockedTask.files_touched})}),currentPlan:authoritativePlan,validateEvidence:async()=>{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 _internals304.updateTaskStatus(directory,args2.task_id,"completed",{force:!1,planLockAlreadyHeld:!0});if(next.phases.flatMap((phase)=>phase.tasks).find((task2)=>task2.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 _internals304.updateTaskStatus(directory,args2.task_id,"blocked",{force:!1,planLockAlreadyHeld:!0});if(next.phases.flatMap((phase)=>phase.tasks).find((task2)=>task2.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 _internals304.updateTaskStatus(directory,args2.task_id,args2.status,{force:!1,planLockAlreadyHeld:!0}),updatedPlan.phases.flatMap((phase)=>phase.tasks).find((task2)=>task2.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}}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 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 backward-only repair contract. 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("Backward-only repair target. The only valid target is idle."),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)}});init_zod();init_loader();import{lookup}from"node:dns/promises";import*as http from"node:http";import*as https from"node:https";import{isIP}from"node:net";import{Readable}from"node:stream";import*as zlib from"node:zlib";init_utils2();init_redaction();init_project_boundary();import{createHash as createHash115}from"node:crypto";import{appendFile as appendFile11,mkdir as mkdir50}from"node:fs/promises";import*as path368 from"node:path";var EVIDENCE_CACHE_FILE2="evidence-cache/documents.jsonl",MAX_EVIDENCE_TEXT_LENGTH=4000;async function writeEvidenceDocuments(directory,inputs,now2=()=>new Date){assertProjectRoot(directory);let filePath=validateSwarmPath(directory,EVIDENCE_CACHE_FILE2),capturedAt=now2().toISOString(),records=inputs.map((input)=>createEvidenceDocumentRecord(input,capturedAt)).filter((record3)=>record3!==null);if(records.length>0)await mkdir50(path368.dirname(filePath),{recursive:!0}),await appendFile11(filePath,`${records.map((record3)=>JSON.stringify(record3)).join(`
|
|
7821
7821
|
`)}
|
|
7822
7822
|
`,"utf-8");return{path:".swarm/evidence-cache/documents.jsonl",records,refs:records.map((record3)=>record3.ref)}}function createEvidenceDocumentRecord(input,defaultCapturedAt){let text=normalizeEvidenceText(input.text??input.snippet??"");if(!text)return null;let capturedAt=input.capturedAt??defaultCapturedAt,base={sourceType:input.sourceType,query:normalizeOptional(input.query),title:normalizeOptional(input.title),url:normalizeOptional(input.url),text},id=createEvidenceDocumentId(base);return{id,ref:`evidence-cache:${id}`,...base,capturedAt,createdBy:normalizeOptional(input.createdBy),metadata:input.metadata??{}}}function createEvidenceDocumentId(input){return`evd_${createHash115("sha256").update([input.sourceType,input.query??"",input.title??"",input.url??"",input.text].join(`
|
|
@@ -7825,7 +7825,7 @@ ${scopeWarning}`:scopeWarning}}function recoverTaskStateFromDelegations(taskId,d
|
|
|
7825
7825
|
`).replace(/<[^>]+>/g," ");return decodeEntities(noTags).replace(/[ \t\f\v]+/g," ").replace(/\s*\n\s*/g,`
|
|
7826
7826
|
`).replace(/\n{3,}/g,`
|
|
7827
7827
|
|
|
7828
|
-
`).trim()}function makeAbortError(){try{return new DOMException("The operation was aborted","AbortError")}catch{let err2=Error("The operation was aborted");return err2.name="AbortError",err2}}function performHttpRequest(args2){let{url:url3,pinnedAddress,signal:signal2,headers}=args2,isHttps=url3.protocol==="https:",port=url3.port?Number(url3.port):isHttps?443:80,hostNoBrackets=url3.hostname.replace(/^\[|\]$/g,""),useSni=isHttps&&isIP(hostNoBrackets)===0,options={host:pinnedAddress,port,path:`${url3.pathname}${url3.search}`,method:"GET",headers:{Host:url3.host,...headers}};if(useSni)options.servername=url3.hostname;return new Promise((
|
|
7828
|
+
`).trim()}function makeAbortError(){try{return new DOMException("The operation was aborted","AbortError")}catch{let err2=Error("The operation was aborted");return err2.name="AbortError",err2}}function performHttpRequest(args2){let{url:url3,pinnedAddress,signal:signal2,headers}=args2,isHttps=url3.protocol==="https:",port=url3.port?Number(url3.port):isHttps?443:80,hostNoBrackets=url3.hostname.replace(/^\[|\]$/g,""),useSni=isHttps&&isIP(hostNoBrackets)===0,options={host:pinnedAddress,port,path:`${url3.pathname}${url3.search}`,method:"GET",headers:{Host:url3.host,...headers}};if(useSni)options.servername=url3.hostname;return new Promise((resolve149,reject2)=>{let req,onResponse=(res)=>{let normHeaders={};for(let[key2,value]of Object.entries(res.headers))normHeaders[key2]=Array.isArray(value)?value[0]:value;res.on("error",()=>{}),resolve149({status:res.statusCode??0,headers:normHeaders,body:res,cancel:()=>req.destroy()})};req=isHttps?https.request(options,onResponse):http.request(options,onResponse);let onAbort=()=>req.destroy(makeAbortError());if(signal2.aborted)req.destroy(makeAbortError());else signal2.addEventListener("abort",onAbort,{once:!0});req.on("error",reject2),req.end()})}async function boundedFetch(start,maxBytes,timeoutMs,deps){let current=start,controller=new AbortController,timer=setTimeout(()=>controller.abort(),timeoutMs);try{for(let hop=0;hop<=MAX_REDIRECTS;hop++){let raw;try{raw=await deps.httpRequest({url:current.url,pinnedAddress:current.address,signal:controller.signal,headers:{Accept:"text/html,application/xhtml+xml,text/plain,application/json;q=0.9,*/*;q=0.5"}})}catch(err2){if(controller.signal.aborted)return{ok:!1,reason:"timeout",message:`Fetch exceeded ${timeoutMs}ms for ${current.url.toString()}`};return{ok:!1,reason:"network_error",message:err2 instanceof Error?err2.message:String(err2)}}if(raw.status>=300&&raw.status<400){let location=raw.headers.location;if(raw.cancel?.(),!location)return{ok:!1,reason:"bad_redirect",message:`Redirect ${raw.status} with no Location header.`};let next;try{next=new URL(location,current.url)}catch{return{ok:!1,reason:"bad_redirect",message:`Invalid redirect target: ${location}`}}let revalidated=await validateFetchUrl(next.toString(),deps.dnsLookup);if(!revalidated.ok)return revalidated;if(hop===MAX_REDIRECTS)return{ok:!1,reason:"too_many_redirects",message:`Exceeded ${MAX_REDIRECTS} redirect hops.`};current={url:revalidated.url,address:revalidated.address};continue}if(raw.status<200||raw.status>=300)return raw.cancel?.(),{ok:!1,reason:"http_error",message:`HTTP ${raw.status} for ${current.url.toString()}`};let contentType=raw.headers["content-type"]??null;if(!isAllowedContentType(contentType))return raw.cancel?.(),{ok:!1,reason:"unsupported_content_type",message:`Refusing to read non-text content type "${contentType}".`};let activeBody=raw.body;if(raw.body!==null&&raw.body instanceof Readable){let encoding=(raw.headers["content-encoding"]??"").toLowerCase(),decoder=null;if(encoding==="gzip"||encoding==="x-gzip")decoder=raw.body.pipe(zlib.createGunzip());else if(encoding==="deflate")decoder=raw.body.pipe(zlib.createInflate());else if(encoding==="br")decoder=raw.body.pipe(zlib.createBrotliDecompress());if(decoder)decoder.on("error",()=>{}),activeBody=decoder}let body;try{body=await readBounded2(activeBody,maxBytes)}catch(err2){if(raw.cancel?.(),controller.signal.aborted)return{ok:!1,reason:"timeout",message:`Fetch exceeded ${timeoutMs}ms while reading the body of ${current.url.toString()}`};return{ok:!1,reason:"network_error",message:err2 instanceof Error?err2.message:String(err2)}}return raw.cancel?.(),{ok:!0,outcome:{status:raw.status,finalUrl:current.url.toString(),contentType,bytes:body.bytes,truncated:body.truncated}}}return{ok:!1,reason:"too_many_redirects",message:`Exceeded ${MAX_REDIRECTS} redirect hops.`}}finally{clearTimeout(timer)}}async function readBounded2(body,maxBytes){if(!body)return{bytes:new Uint8Array(0),truncated:!1};let chunks=[],received=0,truncated=!1;for await(let value of body){if(!value||value.byteLength===0)continue;if(chunks.push(value),received+=value.byteLength,received>maxBytes){truncated=!0;break}}let merged=new Uint8Array(Math.min(received,maxBytes)),offset=0;for(let chunk of chunks){if(offset>=merged.length)break;let slice=chunk.subarray(0,merged.length-offset);merged.set(slice,offset),offset+=slice.byteLength}return{bytes:merged,truncated}}var web_fetch=createSwarmTool({description:"Fetch the readable text of a single http(s) URL for architect-driven deep research (MODE: DEEP_RESEARCH). Returns decoded page text (HTML stripped to plain text), the document title, the final URL after redirects, and an evidence reference stored alongside web_search results. Use it to read primary sources that web_search only surfaces as snippets. Config-gated on council.general.enabled; no search API key required. Blocks private/loopback/link-local/metadata addresses (re-validated across redirects), enforces a timeout, and caps the response body size.",args:{url:exports_external.string().min(1).max(2048).describe("Absolute http(s) URL to fetch (1–2048 chars)."),max_bytes:exports_external.number().int().min(1024).max(MAX_BYTES_HARD_CAP).optional().describe(`Max decoded response bytes to read (1024..${MAX_BYTES_HARD_CAP}, default ${DEFAULT_MAX_BYTES2}).`),timeout_ms:exports_external.number().int().min(1000).max(MAX_TIMEOUT_MS5).optional().describe(`Request timeout in ms (1000..${MAX_TIMEOUT_MS5}, default ${DEFAULT_TIMEOUT_MS6}).`),working_directory:exports_external.string().optional().describe("Project root for config resolution and evidence storage. Optional.")},execute:async(args2,directory)=>{let parsed=ArgsSchema6.safeParse(args2);if(!parsed.success){let fail3={success:!1,reason:"invalid_args",message:parsed.error.issues.map((i)=>`${i.path.join(".")}: ${i.message}`).join("; ")};return JSON.stringify(fail3,null,2)}let dirResult=resolveWorkingDirectory(parsed.data.working_directory,directory);if(!dirResult.success){let fail3={success:!1,reason:"invalid_working_directory",message:dirResult.message};return JSON.stringify(fail3,null,2)}let generalConfig=_internals305.loadPluginConfig(dirResult.directory).council?.general;if(!generalConfig||generalConfig.enabled!==!0)return JSON.stringify({success:!1,reason:"council_general_disabled",message:"web_fetch is disabled - set council.general.enabled: true in the resolved config: global ~/.config/opencode/opencode-swarm.json or project .opencode/opencode-swarm.json."},null,2);let validated=await validateFetchUrl(parsed.data.url,_internals305.dnsLookup);if(!validated.ok){let fail3={success:!1,reason:validated.reason,message:validated.message};return JSON.stringify(fail3,null,2)}let maxBytes=parsed.data.max_bytes??DEFAULT_MAX_BYTES2,timeoutMs=parsed.data.timeout_ms??DEFAULT_TIMEOUT_MS6,result=await boundedFetch({url:validated.url,address:validated.address},maxBytes,timeoutMs,_internals305);if(!result.ok){let fail3={success:!1,reason:result.reason,message:result.message};return JSON.stringify(fail3,null,2)}let{outcome}=result,raw=new TextDecoder("utf-8",{fatal:!1}).decode(outcome.bytes),isHtml=(outcome.contentType??"").toLowerCase().includes("html")||/<html|<!doctype html/i.test(raw),title=isHtml?extractTitle(raw):void 0,bodyText=isHtml?htmlToText(raw):raw.replace(/\s*\n\s*/g,`
|
|
7829
7829
|
`).trim(),text=bodyText.length>MAX_TEXT_LENGTH2?`${bodyText.slice(0,MAX_TEXT_LENGTH2)}…`:bodyText,textTruncated=outcome.truncated||bodyText.length>MAX_TEXT_LENGTH2,evidence2=await captureFetchEvidence(dirResult.directory,outcome.finalUrl,title,text),ok2={success:!0,url:parsed.data.url,finalUrl:outcome.finalUrl,status:outcome.status,contentType:outcome.contentType??void 0,title,text,truncated:textTruncated,bytesReturned:outcome.bytes.byteLength,evidence:evidence2};return JSON.stringify(ok2,null,2)}});async function captureFetchEvidence(directory,url3,title,text){try{let written=await _internals305.writeEvidenceDocuments(directory,[{sourceType:"crawl",url:url3,title,text,createdBy:"web_fetch"}]);return{stored:written.records.length>0,ref:written.refs[0],path:written.path}}catch(err2){return{stored:!1,error:err2 instanceof Error?err2.message:String(err2)}}}var _internals305={httpRequest:performHttpRequest,dnsLookup:lookup,loadPluginConfig,writeEvidenceDocuments};init_zod();init_loader();var CURRENT_INTENT_RE=/\b(?:latest|current|currently|today|now|newest|recent|recently|up\s*-?\s*to\s*-?\s*date|this\s+(?:week|month|year)|as\s+of\s+(?:today|now))\b/i,HISTORICAL_INTENT_RE=/\b(?:history|historical|archive|archived|in\s+20\d{2}|during\s+20\d{2}|from\s+20\d{2}|for\s+20\d{2}|as\s+of\s+20\d{2})\b/i;function applySearchQueryPolicy(rawQuery,now2=new Date){let originalQuery=rawQuery,query=rawQuery.trim().replace(/\s+/g," "),currentYear=now2.getUTCFullYear(),temporalIntent=detectTemporalIntent(query),removedStaleYears=[];if(temporalIntent==="current")query=removeTrailingStaleCutoffYears(query,currentYear,removedStaleYears);return{originalQuery,query,temporalIntent,freshness:temporalIntent==="current"?chooseFreshness(query):void 0,removedStaleYears}}function detectTemporalIntent(query){if(CURRENT_INTENT_RE.test(query))return"current";if(HISTORICAL_INTENT_RE.test(query))return"historical";return"unspecified"}function chooseFreshness(query){if(/\b(?:today|now|as\s+of\s+(?:today|now))\b/i.test(query))return"day";if(/\bthis\s+week\b/i.test(query))return"week";if(/\b(?:recent|recently|this\s+month)\b/i.test(query))return"month";return"year"}function removeTrailingStaleCutoffYears(query,currentYear,removed){return query.replace(/\s+(?:as\s+of\s+)?(20\d{2})\s*$/i,(match,year)=>{if(Number(year)>=currentYear)return match;return removed.push(year),""}).replace(/\s+/g," ").trim()}init_timeout();class WebSearchError extends Error{cause;constructor(message,cause){super(message);this.cause=cause;this.name="WebSearchError"}}class WebSearchConfigError extends Error{constructor(message){super(message);this.name="WebSearchConfigError"}}var SEARCH_TIMEOUT_MS=6000;class TavilyProvider{apiKey;constructor(apiKey){this.apiKey=apiKey}async search(query,maxResults,options={}){let requestBody={api_key:this.apiKey,query,max_results:maxResults,search_depth:"advanced"};if(options.freshness)requestBody.time_range=options.freshness;let response,timeoutError2=new WebSearchError(`Tavily search timed out after ${SEARCH_TIMEOUT_MS}ms`);try{response=await withTimeoutSignal((signal2)=>fetch("https://api.tavily.com/search",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(requestBody),signal:signal2}),SEARCH_TIMEOUT_MS,timeoutError2)}catch(err2){if(err2===timeoutError2)throw err2;throw new WebSearchError(`Tavily network error for query "${query}"`,err2)}if(!response.ok)throw new WebSearchError(`Tavily HTTP ${response.status} for query "${query}"`);let body;try{body=await response.json()}catch(err2){throw new WebSearchError("Tavily returned non-JSON response",err2)}let results=body?.results;if(!Array.isArray(results))return[];return results.filter((r)=>typeof r?.title==="string"&&typeof r?.url==="string"&&typeof r?.content==="string").map((r)=>({title:r.title,url:r.url,snippet:r.content,query}))}}class BraveProvider{apiKey;constructor(apiKey){this.apiKey=apiKey}async search(query,maxResults,options={}){let url3=new URL("https://api.search.brave.com/res/v1/web/search");url3.searchParams.set("q",query),url3.searchParams.set("count",String(maxResults));let freshness=toBraveFreshness(options.freshness);if(freshness)url3.searchParams.set("freshness",freshness);let response,braveTimeoutError=new WebSearchError(`Brave search timed out after ${SEARCH_TIMEOUT_MS}ms`);try{response=await withTimeoutSignal((signal2)=>fetch(url3.toString(),{method:"GET",headers:{"X-Subscription-Token":this.apiKey,Accept:"application/json"},signal:signal2}),SEARCH_TIMEOUT_MS,braveTimeoutError)}catch(err2){if(err2===braveTimeoutError)throw err2;throw new WebSearchError(`Brave network error for query "${query}"`,err2)}if(!response.ok)throw new WebSearchError(`Brave HTTP ${response.status} for query "${query}"`);let body;try{body=await response.json()}catch(err2){throw new WebSearchError("Brave returned non-JSON response",err2)}let results=body?.web?.results;if(!Array.isArray(results))return[];return results.filter((r)=>typeof r?.title==="string"&&typeof r?.url==="string"&&typeof r?.description==="string").map((r)=>({title:r.title,url:r.url,snippet:r.description,query}))}}function toBraveFreshness(freshness){switch(freshness){case"day":return"pd";case"week":return"pw";case"month":return"pm";case"year":return"py";default:return}}function resolveApiKey(provider,configKey){if(configKey&&configKey.length>0)return configKey;let envName=provider==="tavily"?"TAVILY_API_KEY":"BRAVE_SEARCH_API_KEY",fromEnv=process.env[envName];return fromEnv&&fromEnv.length>0?fromEnv:void 0}function createWebSearchProvider(config3){let apiKey=resolveApiKey(config3.searchProvider,config3.searchApiKey);if(!apiKey){let envName=config3.searchProvider==="tavily"?"TAVILY_API_KEY":"BRAVE_SEARCH_API_KEY";throw new WebSearchConfigError(`No API key for search provider "${config3.searchProvider}". Set council.general.searchApiKey in the resolved config (global ~/.config/opencode/opencode-swarm.json, project .opencode/opencode-swarm.json override) or export ${envName}.`)}switch(config3.searchProvider){case"tavily":return new TavilyProvider(apiKey);case"brave":return new BraveProvider(apiKey)}}init_create_tool();init_resolve_working_directory();var MAX_RESULTS_HARD_CAP=10,ArgsSchema7=exports_external.object({query:exports_external.string().min(1).max(500),max_results:exports_external.number().int().min(1).max(20).optional(),freshness:exports_external.enum(["auto","none","day","week","month","year"]).default("auto"),working_directory:exports_external.string().optional()}),web_search=createSwarmTool({description:"External web search for architect-driven council research, SME domain research, and skill-improver research. Returns titled results with snippets and URLs. Used by the architect in MODE: COUNCIL to gather a RESEARCH CONTEXT before dispatching council agents and by SME to evaluate external skill/source candidates. Normalizes current-intent queries, strips trailing stale cutoff years, and applies provider freshness filters by default. Requires council.general.enabled and a configured search API key (Tavily or Brave) in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides. max_results is capped at 10 with default from council.general.maxSourcesPerMember.",args:{query:exports_external.string().min(1).max(500).describe("Search query string (1–500 characters)."),freshness:exports_external.enum(["auto","none","day","week","month","year"]).optional().describe('Optional freshness filter. Query normalization always runs; "auto" infers provider freshness from current/recency terms, while "none" disables provider freshness filtering.'),max_results:exports_external.number().int().min(1).max(20).optional().describe(`Number of results to request (1–20). Hard-capped at ${MAX_RESULTS_HARD_CAP}. Defaults to council.general.maxSourcesPerMember.`),working_directory:exports_external.string().optional().describe("Project root for config resolution. Optional.")},execute:async(args2,directory)=>{let parsed=ArgsSchema7.safeParse(args2);if(!parsed.success){let fail3={success:!1,reason:"invalid_args",message:parsed.error.issues.map((i)=>`${i.path.join(".")}: ${i.message}`).join("; ")};return JSON.stringify(fail3,null,2)}let dirResult=resolveWorkingDirectory(parsed.data.working_directory,directory);if(!dirResult.success){let fail3={success:!1,reason:"invalid_working_directory",message:dirResult.message};return JSON.stringify(fail3,null,2)}let generalConfig=loadPluginConfig(dirResult.directory).council?.general;if(!generalConfig||generalConfig.enabled!==!0)return JSON.stringify({success:!1,reason:"council_general_disabled",message:"web_search is disabled - set council.general.enabled: true in the resolved config: global ~/.config/opencode/opencode-swarm.json or project .opencode/opencode-swarm.json."},null,2);let requested=parsed.data.max_results??generalConfig.maxSourcesPerMember,maxResults=Math.min(requested,MAX_RESULTS_HARD_CAP),policy=applySearchQueryPolicy(parsed.data.query),requestedFreshness=parsed.data.freshness??"auto",freshness=requestedFreshness==="auto"?policy.freshness:requestedFreshness==="none"?void 0:requestedFreshness,provider;try{provider=createWebSearchProvider(generalConfig)}catch(err2){let fail3={success:!1,reason:err2 instanceof WebSearchConfigError?"missing_api_key":"provider_init_failed",message:err2 instanceof Error?err2.message:String(err2)};return JSON.stringify(fail3,null,2)}try{let results=await provider.search(policy.query,maxResults,{freshness}),evidence2=await captureSearchEvidence(dirResult.directory,policy.query,results),scannedResults=results.map(({title,url:url3,snippet})=>{let titleScan=scanExternalContent(title,{trustLevel:"low"}),snippetScan=scanExternalContent(snippet,{trustLevel:"low"}),threatLevel=titleScan.threatLevel==="error"||snippetScan.threatLevel==="error"?"error":titleScan.threatLevel==="warning"||snippetScan.threatLevel==="warning"?"warning":"none";return{title:titleScan.clean?title:titleScan.neutralized,url:url3,snippet:snippetScan.clean?snippet:snippetScan.neutralized,evidenceRef:evidence2.refByUrl.get(url3),threatLevel}}),ok2={success:!0,query:policy.query,originalQuery:policy.originalQuery,temporalIntent:policy.temporalIntent,freshness,removedStaleYears:policy.removedStaleYears,totalResults:results.length,results:scannedResults,evidence:{stored:evidence2.stored,path:evidence2.path,refs:evidence2.refs,error:evidence2.error}};return JSON.stringify(ok2,null,2)}catch(err2){let fail3={success:!1,reason:err2 instanceof WebSearchError?"search_failed":"unknown",message:err2 instanceof Error?err2.message:String(err2)};return JSON.stringify(fail3,null,2)}}});async function captureSearchEvidence(directory,query,results){try{let written=await _internals306.writeEvidenceDocuments(directory,results.map((result)=>({sourceType:"web_search",query,title:result.title,url:result.url,snippet:result.snippet,createdBy:"web_search"}))),refByUrl=new Map;for(let record3 of written.records)if(record3.url)refByUrl.set(record3.url,record3.ref);return{stored:written.records.length>0,path:written.path,refs:written.refs,refByUrl}}catch(err2){return{stored:!1,refs:[],refByUrl:new Map,error:err2 instanceof Error?err2.message:String(err2)}}}var _internals306={writeEvidenceDocuments};init_zod();init_loader();init_schema();init_curator_llm_factory();init_knowledge_curator();init_skill_generator();init_schema3();init_store5();init_create_tool();init_resolve_working_directory();import*as path369 from"node:path";var FindingSchema3=exports_external.object({severity:exports_external.enum(["low","medium","high","critical"]),category:exports_external.string().min(1),agents:exports_external.array(exports_external.string().min(1)).default([]),tasks:exports_external.array(exports_external.string().min(1)).default([]),evidence_refs:exports_external.array(exports_external.string().min(1)).default([]),description:exports_external.string().min(1),recommendation:exports_external.string().default("")}),KnowledgeRecommendationSchema2=exports_external.object({lesson:exports_external.string().min(1),target_agents:exports_external.array(exports_external.string().min(1)).default([]),confidence:exports_external.number().min(0).max(1).default(0.5),evidence_refs:exports_external.array(exports_external.string().min(1)).default([])}),ArgsSchema8=exports_external.object({phase:exports_external.number().int().min(0).max(999),verdict:exports_external.enum(["APPROVE","CONCERNS","REJECT"]),findings:exports_external.array(FindingSchema3).default([]),knowledge_recommendations:exports_external.array(KnowledgeRecommendationSchema2).default([]),working_directory:exports_external.string().optional(),provenance_agent_name:exports_external.string().min(1).optional(),provenance_session_id:exports_external.string().min(1).optional()}),write_architecture_supervisor_evidence=createSwarmTool({description:"Persist the architecture supervisor verdict for a phase. PREREQUISITE: dispatch critic_architecture_supervisor as an Agent task with the phase + agent summaries, collect its strict-JSON verdict (verdict/findings/knowledge_recommendations), then call this tool with those values. Writes .swarm/evidence/{phase}/"+"architecture-supervisor.json. This tool persists only — it does not contact the "+"supervisor. Architect-only; config-gated via architectural_supervision.enabled.",args:{phase:exports_external.number().int().min(0).max(999).describe("Phase number being reviewed."),verdict:exports_external.enum(["APPROVE","CONCERNS","REJECT"]).describe("Supervisor verdict."),findings:exports_external.array(FindingSchema3).optional().describe("System-level findings from the supervisor."),knowledge_recommendations:exports_external.array(KnowledgeRecommendationSchema2).optional().describe("Durable lessons proposed by the supervisor."),working_directory:exports_external.string().optional(),provenance_agent_name:exports_external.string().min(1).optional().describe("Agent name that produced this evidence (optional provenance)."),provenance_session_id:exports_external.string().min(1).optional().describe("Session ID of the agent that produced this evidence (optional provenance).")},execute:async(rawArgs,directory)=>{let parsed=ArgsSchema8.safeParse(rawArgs);if(!parsed.success)return JSON.stringify({success:!1,reason:"invalid arguments",errors:parsed.error.issues.map((i)=>({path:i.path.join("."),message:i.message}))},null,2);let args2=parsed.data,dirResult=resolveWorkingDirectory(args2.working_directory,directory);if(!dirResult.success)return JSON.stringify({success:!1,reason:dirResult.message},null,2);let provenance=args2.provenance_agent_name||args2.provenance_session_id?{agent_name:args2.provenance_agent_name,session_id:args2.provenance_session_id,captured_at:new Date().toISOString()}:void 0,report={schema_version:SUMMARY_SCHEMA_VERSION,phase:args2.phase,verdict:args2.verdict,findings:args2.findings,knowledge_recommendations:args2.knowledge_recommendations,created_at:new Date().toISOString(),...provenance?{provenance}:{}},evidencePath=writeSupervisorReport(dirResult.directory,report),knowledgeProposed=0,knowledgeReinforced=0,knowledgeQuarantined=0;try{let config3=loadPluginConfig(dirResult.directory);if(config3.architectural_supervision?.persist_knowledge_recommendations&&args2.knowledge_recommendations.length>0){let knowledgeConfig=KnowledgeConfigSchema.parse(config3.knowledge??{}),lessons=args2.knowledge_recommendations.map((r)=>r.lesson),result=await curateAndStoreSwarm(lessons,path369.basename(dirResult.directory),{phase_number:args2.phase},dirResult.directory,knowledgeConfig,{skipAutoPromotion:!0,llmDelegate:createCuratorLLMDelegate(dirResult.directory,"phase"),enrichmentQuota:{maxCalls:knowledgeConfig.enrichment.max_calls_per_day,window:knowledgeConfig.enrichment.quota_window}});knowledgeProposed=result.stored,knowledgeReinforced=result.reinforced,knowledgeQuarantined=result.quarantined}}catch{}let skillsProposed=0;try{let config3=loadPluginConfig(dirResult.directory),hasFailureLoop=args2.findings.some((f)=>f.category==="failure_loop");if(config3.architectural_supervision?.persist_knowledge_recommendations&&hasFailureLoop)skillsProposed=(await generateSkills({directory:dirResult.directory,mode:"draft"})).written.length}catch{}return JSON.stringify({success:!0,phase:args2.phase,verdict:args2.verdict,findings_count:args2.findings.length,knowledge_proposed:knowledgeProposed,knowledge_reinforced:knowledgeReinforced,knowledge_quarantined:knowledgeQuarantined,skills_proposed:skillsProposed,evidence_path:evidencePath},null,2)}});init_zod();init_qa_gate_profile();import fs227 from"node:fs";import path370 from"node:path";function normalizeVerdict2(verdict){if(!LIVE_VERDICT_SET_2.includes(verdict))throw Error(`Invalid verdict: must be 'APPROVED' or 'NEEDS_REVISION', got '${verdict}'`);switch(verdict){case"APPROVED":return"approved";case"NEEDS_REVISION":return"rejected";default:return verdict.toLowerCase()}}function normalizeVerdict4(verdict){if(!LIVE_VERDICT_SET_4.includes(verdict))throw Error(`Invalid verdict: must be 'PASS', 'WARN', 'FAIL', or 'SKIP', got '${verdict}'`);switch(verdict){case"PASS":return"pass";case"WARN":return"warn";case"FAIL":return"fail";case"SKIP":return"skip";default:return verdict.toLowerCase()}}var LIVE_VERDICT_SET_2=["APPROVED","NEEDS_REVISION"],LIVE_VERDICT_SET_4=["PASS","WARN","FAIL","SKIP"],VERDICT_SET_2=LIVE_VERDICT_SET_2,VERDICT_SET_4=LIVE_VERDICT_SET_4;function isAcceptedVerdict2(v){return LIVE_VERDICT_SET_2.includes(v)}function isAcceptedVerdict4(v){return LIVE_VERDICT_SET_4.includes(v)}init_utils2();init_ledger();init_manager();init_utils3();init_logger();init_swarm_artifact_cache();init_create_tool();function buildApprovedPreflightFailure(phase,failure3){return JSON.stringify({success:!1,phase,reason:failure3.reason,message:failure3.message,recovery_guidance:failure3.recovery_guidance},null,2)}async function executeWriteDriftEvidence(args2,directory){let phase=args2.phase;if(!Number.isInteger(phase)||phase<1)return JSON.stringify({success:!1,phase,message:"Invalid phase: must be a positive integer"},null,2);if(!isAcceptedVerdict2(args2.verdict))return JSON.stringify({success:!1,phase,message:"Invalid verdict: must be 'APPROVED' or 'NEEDS_REVISION'"},null,2);let summary=args2.summary;if(typeof summary!=="string"||summary.trim().length===0)return JSON.stringify({success:!1,phase,message:"Invalid summary: must be a non-empty string"},null,2);let normalizedVerdict=_internals307.normalizeVerdict2(args2.verdict),approvedPlan=null,snapshotInfo,qaProfileLocked;if(normalizedVerdict==="approved"){if(approvedPlan=await loadPlanJsonOnly(directory),!approvedPlan)return buildApprovedPreflightFailure(phase,{reason:"plan_required_for_approval",message:"PLAN_REQUIRED_FOR_APPROVAL: plan.json must exist before APPROVED drift evidence can be persisted.",recovery_guidance:"Restore the current .swarm/plan.json and ensure the exact plan identity is available before retrying write_drift_evidence."});let profileLookup=getProfileLookupForIdentity(directory,approvedPlan);if(profileLookup.kind==="missing")return buildApprovedPreflightFailure(phase,{reason:"qa_gate_selection_required",message:"QA_GATE_SELECTION_REQUIRED: no durable QA gate selection exists for this exact plan identity.",recovery_guidance:`Call set_qa_gates with swarm_id=${JSON.stringify(approvedPlan.swarm)} and plan_title=${JSON.stringify(approvedPlan.title)} before retrying write_drift_evidence with the identical identity.`});if(profileLookup.kind==="unbound_legacy")return buildApprovedPreflightFailure(phase,{reason:"qa_gate_identity_unbound",message:"QA_GATE_IDENTITY_UNBOUND: the current plan has a legacy QA gate profile row that is not exact-bound.",recovery_guidance:formatLegacyQaBindingRecovery({swarm:approvedPlan.swarm,title:approvedPlan.title},"retry write_drift_evidence with the identical identity")});try{let lockAnchor=await takeSnapshotEvent(directory,approvedPlan,{source:"drift_approval_prelock"}),planId=derivePlanId(approvedPlan),locked=_internals307.lockProfileForIdentity(directory,approvedPlan,lockAnchor.seq),lockedBySnapshotSeq=locked.locked_by_snapshot_seq??lockAnchor.seq,approvedSnapshot=await takeSnapshotEvent(directory,approvedPlan,{source:"critic_approved",approvalMetadata:{phase,verdict:"APPROVED",summary:summary.trim(),approved_at:new Date().toISOString(),locked_by_snapshot_seq:lockedBySnapshotSeq}});snapshotInfo={seq:approvedSnapshot.seq,timestamp:approvedSnapshot.timestamp,locked_by_snapshot_seq:lockedBySnapshotSeq},qaProfileLocked={plan_id:planId,locked_at:locked.locked_at??"",locked_by_snapshot_seq:locked.locked_by_snapshot_seq??-1}}catch(error93){let message=error93 instanceof Error?error93.message:String(error93);return log("[write_drift_evidence] critic-approved persistence failed:",message),buildApprovedPreflightFailure(phase,{reason:"approval_persistence_failed",message:`APPROVAL_PERSISTENCE_FAILED: QA gate profile lock or critic-approved snapshot failed: ${message}`,recovery_guidance:"Resolve the ledger or QA profile persistence failure, then rerun write_drift_evidence. A completed profile lock is idempotent, and no visible approval is published until both persistence steps succeed."})}}let provenance=args2.provenanceAgentName||args2.provenanceSessionId?{agent_name:args2.provenanceAgentName,session_id:args2.provenanceSessionId,captured_at:new Date().toISOString()}:void 0,evidenceContent={entries:[{type:"drift-verification",verdict:normalizedVerdict,summary:summary.trim(),timestamp:new Date().toISOString(),requirementCoverage:args2.requirementCoverage,...provenance?{provenance}:{}}]},filename="drift-verifier.json",relativePath2=path370.join("evidence",String(phase),filename),validatedPath;try{validatedPath=validateSwarmPath(directory,relativePath2)}catch(error93){return JSON.stringify({success:!1,phase,message:error93 instanceof Error?error93.message:"Failed to validate path"},null,2)}let evidenceDir=path370.dirname(validatedPath);try{await fs227.promises.mkdir(evidenceDir,{recursive:!0});let tempPath=path370.join(evidenceDir,`.${filename}.tmp`);return await fs227.promises.writeFile(tempPath,JSON.stringify(evidenceContent,null,2),"utf-8"),await fs227.promises.rename(tempPath,validatedPath),invalidateCachedArtifact(validatedPath),JSON.stringify({success:!0,phase,verdict:normalizedVerdict,message:`Drift evidence written to .swarm/evidence/${phase}/drift-verifier.json`,approvedSnapshot:snapshotInfo,qaProfileLocked},null,2)}catch(error93){return JSON.stringify({success:!1,phase,message:error93 instanceof Error?error93.message:String(error93)},null,2)}}var _internals307={normalizeVerdict2,VERDICT_SET_2,isAcceptedVerdict2,lockProfileForIdentity},write_drift_evidence=createSwarmTool({allowWorkingDirectoryOverride:!0,description:"Write drift verification evidence for a completed phase. Normalizes verdict (APPROVED->approved, NEEDS_REVISION->rejected) and writes a gate-contract formatted EvidenceBundle to .swarm/evidence/{phase}/drift-verifier.json. Use this after critic_drift_verifier delegation to persist the verification result.",args:{phase:exports_external.number().int().min(1).describe("The phase number for the drift verification (e.g., 1, 2, 3)"),verdict:exports_external.enum(VERDICT_SET_2).describe("Verdict of the drift verification: 'APPROVED' or 'NEEDS_REVISION'"),summary:exports_external.string().describe("Human-readable summary of the drift verification"),requirementCoverage:exports_external.string().optional().describe("Requirement coverage report from req_coverage tool (JSON string)"),provenanceAgentName:exports_external.string().min(1).optional().describe("Agent name that produced this evidence (optional provenance)"),provenanceSessionId:exports_external.string().min(1).optional().describe("Session ID of the agent that produced this evidence (optional provenance)")},execute:async(args2,directory)=>{let rawPhase=args2.phase!==void 0?Number(args2.phase):0;try{let writeDriftEvidenceArgs={phase:Number(args2.phase),verdict:String(args2.verdict),summary:String(args2.summary??""),requirementCoverage:args2.requirementCoverage!==void 0?String(args2.requirementCoverage):void 0,provenanceAgentName:args2.provenanceAgentName!==void 0?String(args2.provenanceAgentName):void 0,provenanceSessionId:args2.provenanceSessionId!==void 0?String(args2.provenanceSessionId):void 0};return await executeWriteDriftEvidence(writeDriftEvidenceArgs,directory)}catch(error93){return JSON.stringify({success:!1,phase:rawPhase,message:error93 instanceof Error?error93.message:"Unknown error"},null,2)}}});init_zod();init_loader();init_council_review_identity();import fs228 from"node:fs";import path371 from"node:path";init_types();init_lock();init_utils2();init_config2();init_gateway();init_reward_capture();init_ledger();init_manager();init_utils3();init_logger();init_swarm_artifact_cache();init_create_tool();var FINAL_COUNCIL_MEMBERS=COUNCIL_MEMBER_ROLES,VerdictSchema3=exports_external.object({agent:exports_external.string().min(1).max(64),verdict:exports_external.enum(["APPROVE","CONCERNS","REJECT"]),confidence:exports_external.number().min(0).max(1),findings:exports_external.array(exports_external.object({severity:exports_external.enum(["CRITICAL","HIGH","MEDIUM","LOW"]),category:exports_external.string().min(1),location:exports_external.string(),detail:exports_external.string(),evidence:exports_external.string()})),criteriaAssessed:exports_external.array(exports_external.string()),criteriaUnmet:exports_external.array(exports_external.string()),durationMs:exports_external.number().nonnegative()}),ArgsSchema9=exports_external.object({phase:exports_external.number().int().min(1).max(1000),projectSummary:exports_external.string().min(1),roundNumber:exports_external.number().int().min(1).max(10).optional(),verdicts:exports_external.array(VerdictSchema3).min(1).max(5)});function normalizeFinalVerdict(verdict,requiredFixesCount){if(verdict==="APPROVE")return"approved";if(verdict==="REJECT")return"rejected";return requiredFixesCount>0?"rejected":"concerns"}function resolveFinalCouncilVerdicts(verdicts){let resolved=[],distinctRoles=[],unknownAgents=[],duplicateAgents=[];for(let verdict of verdicts){let role=resolveCouncilMemberRole(verdict.agent);if(!role){if(!unknownAgents.includes(verdict.agent))unknownAgents.push(verdict.agent);continue}if(distinctRoles.includes(role)){if(!duplicateAgents.includes(verdict.agent))duplicateAgents.push(verdict.agent);continue}distinctRoles.push(role),resolved.push({...verdict,agent:role})}return{resolved,distinctRoles,unknownAgents,duplicateAgents}}function invalidResponse3(issues){return JSON.stringify({success:!1,reason:"invalid arguments",errors:issues.map((issue3)=>({path:issue3.path.join("."),message:issue3.message}))},null,2)}async function executeWriteFinalCouncilEvidence(args2,directory,ctx){let parsed=ArgsSchema9.safeParse(args2);if(!parsed.success)return await recordUnscopedCouncilAttempt(directory,"final","invalid_arguments",args2,parsed.error.issues.map((issue3)=>({path:issue3.path,code:issue3.code})),ctx?.sessionID)??invalidResponse3(parsed.error.issues);let input=parsed.data,config3=loadPluginConfig(directory),plan=null;try{plan=await loadPlan(directory)}catch{}let planHash=plan?computePlanLedgerHash(plan):void 0,planId=plan?derivePlanId(plan):void 0,planIdentityHash=plan?derivePlanIdentityHash(plan):void 0,reviewHash=plan?computeCouncilReviewHash(plan):null,identity=computeCouncilReviewIdentity({level:"final",scope:{kind:"final",final:!0},plan,config:config3.council}),completionPolicy=resolveFinalCompletionPolicy(config3.council),{resolved,distinctRoles,unknownAgents,duplicateAgents}=resolveFinalCouncilVerdicts(input.verdicts),membersVoted=distinctRoles,membersAbsent=FINAL_COUNCIL_MEMBERS.filter((member)=>!distinctRoles.includes(member)),requiredMembers=completionPolicy.mode==="quorum"?completionPolicy.minimumMembers:FINAL_COUNCIL_MEMBERS.length;return runCouncilAttempt({directory,scope:{kind:"final",identityDigest:identity.identityDigest},clientRound:input.roundNumber,maxRounds:config3.council?.maxRounds??3,sessionID:ctx?.sessionID,escalationConfigured:config3.council?.escalateOnMaxRounds!==void 0,request:input,verdictCount:input.verdicts.length,members:[...new Set(input.verdicts.map((v)=>v.agent))].slice(0,5),probePendingEvidence:async(attemptId,round)=>hasFinalEvidenceAttempt(directory,attemptId,round),evaluate:async(authoritativeRound)=>{if(membersVoted.length<requiredMembers)return{disposition:"insufficient_quorum",response:{success:!1,reason:"insufficient_quorum",message:`Final council quorum not met: ${membersVoted.length} of ${requiredMembers} required distinct canonical members provided verdicts (policy: ${completionPolicy.mode}${completionPolicy.mode==="quorum"?`, minimumMembers: ${completionPolicy.minimumMembers}`:""}). Members voted: [${membersVoted.join(", ")}]. Members absent: [${membersAbsent.join(", ")}].`+(unknownAgents.length>0?` Unknown identities (never counted): [${unknownAgents.join(", ")}].`:"")+(duplicateAgents.length>0?` Duplicate identities (collapsed): [${duplicateAgents.join(", ")}].`:"")+" Dispatch the absent council members with project-scoped context and collect their verdicts before calling write_final_council_evidence.",membersVoted,membersAbsent,quorumRequired:requiredMembers,completionPolicy,...unknownAgents.length>0?{unknownAgents}:{},...duplicateAgents.length>0?{duplicateAgents}:{}},transition:"stay",gateEffect:"none"};let synthesis=synthesizeFinalCouncilAdvisory(input.projectSummary.trim(),resolved,authoritativeRound,config3.council);if(synthesis.overallVerdict==="CONCERNS"&&synthesis.blockingConcernsCount>0)return{disposition:"blocking_concerns_unresolved",response:{success:!1,reason:"blocking_concerns_unresolved",overallVerdict:synthesis.overallVerdict,blockingConcernsCount:synthesis.blockingConcernsCount,requiredFixes:synthesis.requiredFixes,unifiedFeedbackMd:synthesis.unifiedFeedbackMd,message:`Final council returned CONCERNS with ${synthesis.blockingConcernsCount} HIGH/CRITICAL finding(s) promoted to requiredFixes. These must be resolved before the project can close. Do NOT write evidence or proceed — address every requiredFix and resubmit.`},transition:"advance",gateEffect:"blocked",verdict:synthesis.overallVerdict,quorumSize:synthesis.quorumSize};if(!plan)return{disposition:"plan_not_found",response:{success:!1,reason:"plan_not_found",message:"Cannot write final council evidence: plan.json not found. The plan must be loaded and available before writing final council evidence.",phase:input.phase,plan_id:"unknown"},transition:"stay",gateEffect:"none"};let normalizedVerdict=normalizeFinalVerdict(synthesis.overallVerdict,synthesis.requiredFixes.length),evidenceEntry={type:"final-council",phase:input.phase,plan_id:planId,plan_hash:planHash,plan_identity_hash:planIdentityHash,...councilIdentityEvidenceFields(identity),final_completion_policy:completionPolicy,freshness_max_age_hours:config3.council?.freshnessMaxAgeHours??24,verdict:normalizedVerdict,rawCouncilVerdict:synthesis.overallVerdict,quorumSize:synthesis.quorumSize,membersVoted,membersAbsent,requiredFixes:synthesis.requiredFixes,advisoryFindings:synthesis.advisoryFindings,advisoryNotes:synthesis.advisoryNotes,unresolvedConflicts:synthesis.unresolvedConflicts,roundNumber:synthesis.roundNumber,allCriteriaMet:synthesis.allCriteriaMet,memberVerdicts:synthesis.memberVerdicts,unifiedFeedbackMd:synthesis.unifiedFeedbackMd,projectSummary:synthesis.projectSummary,timestamp:synthesis.timestamp},validatedPath;try{validatedPath=_internals308.validateSwarmPath(directory,path371.join("evidence","final-council.json"))}catch(error93){return{disposition:"invalid_evidence_path",response:{success:!1,phase:input.phase,message:error93 instanceof Error?error93.message:"Failed to validate path"},transition:"stay",gateEffect:"none"}}let evidenceDir=path371.dirname(validatedPath),accepted=synthesis.overallVerdict==="APPROVE"||synthesis.overallVerdict==="CONCERNS"&&synthesis.blockingConcernsCount===0;return{disposition:`evaluated_${synthesis.overallVerdict.toLowerCase()}`,response:{success:!0,phase:input.phase,overallVerdict:synthesis.overallVerdict,verdict:normalizedVerdict,vetoedBy:synthesis.vetoedBy,roundNumber:synthesis.roundNumber,allCriteriaMet:synthesis.allCriteriaMet,requiredFixesCount:synthesis.requiredFixes.length,advisoryFindingsCount:synthesis.advisoryFindings.length,unresolvedConflictsCount:synthesis.unresolvedConflicts.length,advisoryNotes:synthesis.advisoryNotes,membersVoted,membersAbsent,quorumSize:synthesis.quorumSize,quorumMet:!0,completionPolicy,evidencePath:synthesis.evidencePath,unifiedFeedbackMd:synthesis.unifiedFeedbackMd,message:"Final council evidence written to .swarm/evidence/final-council.json"},transition:accepted?"close":"advance",gateEffect:accepted?"allowed":"blocked",verdict:synthesis.overallVerdict,quorumSize:synthesis.quorumSize,evidence:{reference:synthesis.evidencePath,commit:async(attemptId)=>{await withEvidenceLock(directory,path371.join("evidence","final-council.json"),"write-final-council-evidence",attemptId,async()=>{let currentPlan=await loadPlan(directory);if(!currentPlan||computeCouncilReviewHash(currentPlan)!==reviewHash)throw Error("final council plan changed before evidence publication");await fs228.promises.mkdir(evidenceDir,{recursive:!0});let tempPath=path371.join(evidenceDir,`.final-council.${attemptId}.tmp`);try{await fs228.promises.writeFile(tempPath,JSON.stringify({entries:[{...evidenceEntry,attemptId}]},null,2),"utf-8"),await fs228.promises.rename(tempPath,validatedPath),invalidateCachedArtifact(validatedPath)}finally{await fs228.promises.rm(tempPath,{force:!0}).catch(()=>{})}})}},afterCommit:async()=>{try{let memoryConfig=config3.memory;if(memoryConfig?.enabled===!0&&ctx?.sessionID){let provider=createConfiguredMemoryProvider(directory,memoryConfig);try{await applyCouncilReward(provider,{runId:ctx.sessionID,unitId:void 0,reward:COUNCIL_VERDICT_REWARDS[synthesis.overallVerdict],eta:memoryConfig.qLearning.learningRate,initialQValue:memoryConfig.qLearning.initialQValue,qLearning:memoryConfig.qLearning,timestamp:new Date().toISOString(),verdictLabel:synthesis.overallVerdict})}finally{await provider.close?.()}}}catch(rewardErr){warn(`[write-final-council-evidence] final council reward capture failed: ${rewardErr instanceof Error?rewardErr.message:String(rewardErr)}`)}}}}})}var write_final_council_evidence=createSwarmTool({allowWorkingDirectoryOverride:!0,description:"Write final council evidence for a completed project. This is not General Council mode and does not use convene_general_council. PREREQUISITE: dispatch critic, reviewer, sme, test_engineer, and explorer as project-scoped Agent tasks, collect their CouncilMemberVerdict JSON, then call this tool to synthesize and persist .swarm/evidence/final-council.json. Quorum follows council.finalCompletionPolicy: default requires all five canonical roles with zero absentees; an explicit quorum policy accepts a bounded minimum of distinct canonical members. Member names may be exact canonical roles or multi-swarm prefixed names (e.g. local_critic); unknown and duplicate identities never count.",args:{phase:exports_external.number().int().min(1).max(1000).describe("The final phase number for the project being reviewed"),projectSummary:exports_external.string().min(1).describe("Summary of the completed project and total work reviewed"),roundNumber:exports_external.number().int().min(1).max(10).optional().describe("1-indexed final council round number. Defaults to the current server round."),verdicts:exports_external.array(VerdictSchema3).min(1).max(5).describe("Collected CouncilMemberVerdict objects from critic, reviewer, sme, test_engineer, and explorer (canonical or multi-swarm prefixed names).")},execute:async(args2,directory,ctx)=>executeWriteFinalCouncilEvidence(args2,directory,ctx)});function hasFinalEvidenceAttempt(directory,attemptId,round){try{let evidencePath=validateSwarmPath(directory,path371.join("evidence","final-council.json")),parsed=JSON.parse(fs228.readFileSync(evidencePath,"utf8"));return Boolean(parsed.entries?.some((entry)=>entry.type==="final-council"&&entry.attemptId===attemptId&&entry.roundNumber===round))}catch{return!1}}var _internals308={validateSwarmPath};init_zod();import fs229 from"node:fs";import path372 from"node:path";init_utils2();init_swarm_artifact_cache();init_create_tool();async function executeWriteHallucinationEvidence(args2,directory){let phase=args2.phase;if(!Number.isInteger(phase)||phase<1)return JSON.stringify({success:!1,phase,message:"Invalid phase: must be a positive integer"},null,2);if(!isAcceptedVerdict2(args2.verdict))return JSON.stringify({success:!1,phase,message:"Invalid verdict: must be 'APPROVED' or 'NEEDS_REVISION'"},null,2);let summary=args2.summary;if(typeof summary!=="string"||summary.trim().length===0)return JSON.stringify({success:!1,phase,message:"Invalid summary: must be a non-empty string"},null,2);let normalizedVerdict=_internals309.normalizeVerdict2(args2.verdict),evidenceContent={entries:[{type:"hallucination-verification",verdict:normalizedVerdict,summary:summary.trim(),timestamp:new Date().toISOString(),findings:args2.findings}]},filename="hallucination-guard.json",relativePath2=path372.join("evidence",String(phase),filename),validatedPath;try{validatedPath=validateSwarmPath(directory,relativePath2)}catch(error93){return JSON.stringify({success:!1,phase,message:error93 instanceof Error?error93.message:"Failed to validate path"},null,2)}let evidenceDir=path372.dirname(validatedPath);try{await fs229.promises.mkdir(evidenceDir,{recursive:!0});let tempPath=path372.join(evidenceDir,`.${filename}.tmp`);return await fs229.promises.writeFile(tempPath,JSON.stringify(evidenceContent,null,2),"utf-8"),await fs229.promises.rename(tempPath,validatedPath),invalidateCachedArtifact(validatedPath),JSON.stringify({success:!0,phase,verdict:normalizedVerdict,message:`Hallucination evidence written to .swarm/evidence/${phase}/hallucination-guard.json`},null,2)}catch(error93){return JSON.stringify({success:!1,phase,message:error93 instanceof Error?error93.message:String(error93)},null,2)}}var _internals309={normalizeVerdict2,VERDICT_SET_2,isAcceptedVerdict2},write_hallucination_evidence=createSwarmTool({allowWorkingDirectoryOverride:!0,description:"Write hallucination verification evidence for a completed phase. Normalizes verdict (APPROVED->approved, NEEDS_REVISION->rejected) and writes a gate-contract formatted EvidenceBundle to .swarm/evidence/{phase}/hallucination-guard.json. Use this after critic_hallucination_verifier delegation to persist the verification result. Unlike write_drift_evidence, this tool does NOT lock the QA gate profile.",args:{phase:exports_external.number().int().min(1).describe("The phase number for the hallucination verification (e.g., 1, 2, 3)"),verdict:exports_external.enum(VERDICT_SET_2).describe("Verdict of the hallucination verification: 'APPROVED' or 'NEEDS_REVISION'"),summary:exports_external.string().describe("Human-readable summary of the hallucination verification"),findings:exports_external.string().optional().describe("Optional bullet list of FABRICATED/DRIFTED/UNSUPPORTED/BROKEN findings (for NEEDS_REVISION)")},execute:async(args2,directory)=>{let rawPhase=args2.phase!==void 0?Number(args2.phase):0;try{let typedArgs={phase:Number(args2.phase),verdict:String(args2.verdict),summary:String(args2.summary??""),findings:args2.findings!==void 0?String(args2.findings):void 0};return await executeWriteHallucinationEvidence(typedArgs,directory)}catch(error93){return JSON.stringify({success:!1,phase:rawPhase,message:error93 instanceof Error?error93.message:"Unknown error"},null,2)}}});init_zod();import fs230 from"node:fs";import path373 from"node:path";init_utils2();init_swarm_artifact_cache();init_create_tool();async function executeWriteMutationEvidence(args2,directory){let phase=args2.phase;if(!Number.isInteger(phase)||phase<1)return JSON.stringify({success:!1,phase,message:"Invalid phase: must be a positive integer"},null,2);if(!isAcceptedVerdict4(args2.verdict))return JSON.stringify({success:!1,phase,message:"Invalid verdict: must be 'PASS', 'WARN', 'FAIL', or 'SKIP'"},null,2);if(args2.killRate!==void 0){if(typeof args2.killRate!=="number"||Number.isNaN(args2.killRate))return JSON.stringify({success:!1,phase,message:"Invalid killRate: must be a number"},null,2)}if(args2.adjustedKillRate!==void 0){if(typeof args2.adjustedKillRate!=="number"||Number.isNaN(args2.adjustedKillRate))return JSON.stringify({success:!1,phase,message:"Invalid adjustedKillRate: must be a number"},null,2)}let summary=args2.summary;if(typeof summary!=="string"||summary.trim().length===0)return JSON.stringify({success:!1,phase,message:"Invalid summary: must be a non-empty string"},null,2);let normalizedVerdict=_internals310.normalizeVerdict4(args2.verdict),evidenceEntry={type:"mutation-gate",verdict:normalizedVerdict,killRate:args2.killRate??0,adjustedKillRate:args2.adjustedKillRate??0,summary:summary.trim(),timestamp:new Date().toISOString()};if(args2.survivedMutants!==void 0)evidenceEntry.survivedMutants=args2.survivedMutants;let evidenceContent={entries:[evidenceEntry]},filename="mutation-gate.json",relativePath2=path373.join("evidence",String(phase),filename),validatedPath;try{validatedPath=validateSwarmPath(directory,relativePath2)}catch(error93){return JSON.stringify({success:!1,phase,message:error93 instanceof Error?error93.message:"Failed to validate path"},null,2)}let evidenceDir=path373.dirname(validatedPath);try{await fs230.promises.mkdir(evidenceDir,{recursive:!0});let tempPath=path373.join(evidenceDir,`.${filename}.tmp`);return await fs230.promises.writeFile(tempPath,JSON.stringify(evidenceContent,null,2),"utf-8"),await fs230.promises.rename(tempPath,validatedPath),invalidateCachedArtifact(validatedPath),JSON.stringify({success:!0,phase,verdict:normalizedVerdict,message:`Mutation gate evidence written to .swarm/evidence/${phase}/mutation-gate.json`},null,2)}catch(error93){return JSON.stringify({success:!1,phase,message:error93 instanceof Error?error93.message:String(error93)},null,2)}}var _internals310={normalizeVerdict4,VERDICT_SET_4,isAcceptedVerdict4},write_mutation_evidence=createSwarmTool({allowWorkingDirectoryOverride:!0,description:'Write mutation gate evidence for a completed phase. Accepts phase, verdict (PASS/WARN/FAIL/SKIP), killRate, adjustedKillRate, summary, and optional survivedMutants. Normalizes uppercase verdicts to lowercase (PASS→pass, WARN→warn, FAIL→fail, SKIP→skip) and writes entries[0].type="mutation-gate" to .swarm/evidence/{phase}/mutation-gate.json using atomic temp+rename write. Use this after mutation_test tool returns to persist the gate verdict.',args:{phase:exports_external.number().int().min(1).describe("The phase number for the mutation gate (e.g., 1, 2, 3)"),verdict:exports_external.enum(VERDICT_SET_4).describe("Verdict of the mutation gate: 'PASS', 'WARN', 'FAIL', or 'SKIP'"),killRate:exports_external.number().optional().describe("The raw kill rate (e.g., 0.85)"),adjustedKillRate:exports_external.number().optional().describe("The adjusted kill rate accounting for timeout survived mutants (e.g., 0.87)"),summary:exports_external.string().describe("Human-readable summary of the mutation gate result"),survivedMutants:exports_external.string().optional().describe("Optional JSON-serialized list of survived mutants")},execute:async(args2,directory)=>{let rawPhase=args2.phase!==void 0?Number(args2.phase):0;try{let typedArgs={phase:Number(args2.phase),verdict:String(args2.verdict),killRate:args2.killRate!==void 0?Number(args2.killRate):void 0,adjustedKillRate:args2.adjustedKillRate!==void 0?Number(args2.adjustedKillRate):void 0,summary:String(args2.summary??""),survivedMutants:args2.survivedMutants!==void 0?String(args2.survivedMutants):void 0};return await executeWriteMutationEvidence(typedArgs,directory)}catch(error93){return JSON.stringify({success:!1,phase:rawPhase,message:error93 instanceof Error?error93.message:"Unknown error"},null,2)}}});init_zod();init_pr_review_contract();init_pr_workflow_gate();init_utils2();init_finding_policy();init_create_tool();import{createHash as createHash116,randomUUID as randomUUID48}from"node:crypto";import*as fs231 from"node:fs";import*as path374 from"node:path";var PersistedFindingSchema=PrReviewFindingSchema.extend({boundary:exports_external.enum(["post_explorer","post_reviewer","post_critic"]),pr_head_sha:exports_external.string().regex(/^[0-9a-f]{6,64}$/i),recorded_at:exports_external.string().datetime()}).passthrough(),PersistedHandoffSchema=PrReviewHandoffSchema.extend({schema_version:exports_external.literal(1),run_id:PrReviewRunIdSchema,pr_head_sha:exports_external.string().regex(/^[0-9a-f]{6,64}$/i),created_at:exports_external.string().datetime()}).strict();function failure3(message){return JSON.stringify({success:!1,message},null,2)}async function readFindings(filePath){try{return(await readBoundedUtf8File2(filePath,PR_REVIEW_FINDINGS_MAX_BYTES,"findings artifact")).split(/\r?\n/).filter(Boolean).map((line,index)=>{let decoded;try{decoded=JSON.parse(line)}catch(error93){throw Error(`line ${index+1} is not JSON: ${error93 instanceof Error?error93.message:String(error93)}`)}if(decoded!==null&&typeof decoded==="object"){let record3=decoded;if(record3.risk_impact===void 0)record3.risk_impact="UNKNOWN";if(record3.risk_tags===void 0)record3.risk_tags=[]}let parsed=PersistedFindingSchema.safeParse(decoded);if(!parsed.success)throw Error(`line ${index+1} violates the persisted finding schema: ${formatPrReviewValidationIssues(parsed.error.issues,decoded).join("; ")}`);return parsed.data})}catch(error93){if(error93.code==="ENOENT")return[];throw error93}}async function readBoundedUtf8File2(filePath,maxBytes,label){let stat25=await fs231.promises.stat(filePath);if(!stat25.isFile()||stat25.size>maxBytes)throw Error(`${label} is not a bounded regular file (max ${maxBytes} bytes)`);let text=await fs231.promises.readFile(filePath,"utf8"),bytes=Buffer.byteLength(text,"utf8");if(bytes>maxBytes)throw Error(`${label} exceeds ${maxBytes} bytes after read (got ${bytes})`);return text}async function atomicWrite8(filePath,content){await fs231.promises.mkdir(path374.dirname(filePath),{recursive:!0});let tempPath=path374.join(path374.dirname(filePath),`.${path374.basename(filePath)}.${randomUUID48()}.tmp`);try{await fs231.promises.writeFile(tempPath,content,{encoding:"utf8",flag:"wx"}),await fs231.promises.rename(tempPath,filePath)}finally{await fs231.promises.rm(tempPath,{force:!0}).catch(()=>{return})}}async function atomicCreate(filePath,content){await fs231.promises.mkdir(path374.dirname(filePath),{recursive:!0});let tempPath=path374.join(path374.dirname(filePath),`.${path374.basename(filePath)}.${randomUUID48()}.tmp`);try{await fs231.promises.writeFile(tempPath,content,{encoding:"utf8",flag:"wx"});try{return await fs231.promises.link(tempPath,filePath),!0}catch(error93){if(error93.code==="EEXIST")return!1;throw error93}}finally{await fs231.promises.rm(tempPath,{force:!0}).catch(()=>{return})}}var _internals311={atomicWrite:atomicWrite8,atomicCreate,assertBoundary:assertPrReviewArtifactBoundary,assertCriticSettlements,readFindings};function operationFailure(operation,relativePath2,expected,error93){return failure3(`operation ${operation} path "${relativePath2}": expected ${expected}, got ${JSON.stringify(error93 instanceof Error?error93.message:String(error93))}`)}function latestFindings(records){let latest=new Map;for(let record3 of records)latest.set(record3.finding_id,record3);return latest}function canonicalFindingRecords(records){return JSON.stringify(records.map((record3)=>({finding_id:record3.finding_id,status:record3.status,file_line:record3.file_line,evidence:record3.evidence,next_action:record3.next_action,severity:record3.severity,category:record3.category,confidence:record3.confidence,provenance:record3.provenance,risk_impact:record3.risk_impact,risk_tags:record3.risk_tags,critic_status:record3.critic_status})).sort((left,right)=>left.finding_id.localeCompare(right.finding_id)))}function policyLocation(fileLine){let match=fileLine.trim().match(/^(.*?):(\d+)(?:-(\d+))?$/);if(!match)return{file:fileLine.trim(),line:1};return{file:match[1],line:Number(match[2]),...match[3]?{lineEnd:Number(match[3])}:{}}}function policyCandidates(records,sessionID,boundary){return records.map((record3)=>({finding:record3.evidence,severity:record3.severity??"NONE",action:record3.next_action,confidence:record3.confidence??"MEDIUM",category:record3.category??"review-finding",location:policyLocation(record3.file_line),provenance:((record3.provenance?.length)?record3.provenance:[`session:${sessionID}`]).map((identity)=>({identity,lane:boundary})),status:record3.status,sourceFindingId:record3.finding_id}))}function assertCriticSettlements(records,existing,authoritativeCriticVerdicts){let priorById=latestFindings(existing.filter((record3)=>record3.boundary==="post_reviewer")),settlements=[];for(let record3 of records){let prior=priorById.get(record3.finding_id),authoritative=authoritativeCriticVerdicts.get(record3.finding_id),needsCriticAuthority=prior?.next_action==="route_to_critic"||record3.critic_status!==void 0;if(needsCriticAuthority&&!authoritative)throw Error(`critic settlement for ${record3.finding_id} has no authenticated authoritative critic verdict`);if(authoritative?.status==="DOWNGRADED"&&record3.severity===void 0)throw Error(`critic settlement for ${record3.finding_id} DOWNGRADED verdict requires an explicit severity matching the authenticated authoritative critic verdict`);if(authoritative&&record3.severity!==void 0&&authoritative.severity!==record3.severity)throw Error(`critic settlement for ${record3.finding_id} severity contradicts the authenticated authoritative critic verdict`);if(record3.critic_status&&authoritative){if(record3.critic_status!==authoritative.status)throw Error(`critic settlement for ${record3.finding_id} status "${record3.critic_status}" contradicts the authenticated authoritative critic status "${authoritative.status}"`)}let outcome=authoritative?.status==="DISPROVED"||record3.status==="DISPROVED"?"DISPROVED":authoritative?.status==="DOWNGRADED"?"DOWNGRADED":authoritative?.status==="UPHELD"?"UPHELD":prior?.severity&&record3.severity&&prior.severity!==record3.severity?"DOWNGRADED":"UPHELD",settled=settleCriticFinding({finding:{id:record3.finding_id,status:record3.status,severity:record3.severity??"NONE",action:record3.next_action},outcome,finalSeverity:record3.severity,finalAction:record3.next_action});if(settled.finalFinding.severity!==(record3.severity??"NONE")||settled.finalFinding.action!==record3.next_action)throw Error(`critic settlement for ${record3.finding_id} does not match the final persisted severity/action`);if(needsCriticAuthority||authoritative)settlements.push({findingId:record3.finding_id,terminal:settled.terminal,status:settled.status,finalFinding:settled.finalFinding,handoffFindingIds:settled.handoffFindingIds})}return settlements}async function executeWritePrReviewArtifact(args2,directory,context={}){let parsed=WritePrReviewArtifactArgsSchema.safeParse(args2);if(!parsed.success)return failure3(`Invalid PR-review artifact: ${formatPrReviewValidationIssues(parsed.error.issues,args2).join("; ")}`);let sessionID=context.sessionID?.trim();if(!sessionID)return failure3(formatPrReviewRuntimeFieldError("session_id","a non-empty active session identifier",context.sessionID));let state2;try{state2=await readPrWorkflowGateState(directory,sessionID)}catch(error93){return operationFailure("read",`pr-workflow-gates/${prWorkflowSessionFileStem(sessionID)}.json`,"a bounded valid PR workflow state artifact",error93)}if(state2?.mode!=="PR_REVIEW"||!state2.prHeadSha)return failure3(formatPrReviewRuntimeFieldError("workflow.mode",'an active head-bound "PR_REVIEW" workflow',state2?{mode:state2.mode,pr_head_sha:state2.prHeadSha}:null));if(state2.prHeadSha!==parsed.data.pr_head_sha.toLowerCase())return failure3(formatPrReviewRuntimeFieldError("pr_head_sha",`"${state2.prHeadSha}"`,parsed.data.pr_head_sha));let resolvedRunId;try{resolvedRunId=await resolvePrReviewWriterRunId(directory,sessionID,parsed.data.run_id)}catch(error93){let message=error93 instanceof Error?error93.message:String(error93);return message.startsWith("BLOCKED: field ")?failure3(message):operationFailure("reserve",`pr-review/${parsed.data.run_id??"<generated-run-id>"}/run-reservation.json`,"a create-only reservation owned by the active workflow",error93)}let relativeFindingsPath=path374.join("pr-review",resolvedRunId,"findings.jsonl"),findingsPath;try{findingsPath=validateSwarmPath(directory,relativeFindingsPath)}catch(error93){return operationFailure("resolve",relativeFindingsPath.split(path374.sep).join("/"),"a contained path below the project .swarm directory",error93)}let existing;try{existing=await readFindings(findingsPath)}catch(error93){return failure3(`operation read path "${relativeFindingsPath.split(path374.sep).join("/")}": expected bounded JSONL matching the persisted findings schema, got ${error93 instanceof Error?error93.message:String(error93)}`)}if(parsed.data.kind==="findings"){let findingsInput=parsed.data,findingIds=findingsInput.records.map((record3)=>record3.finding_id),existingBoundaryRecords=existing.filter((record3)=>record3.boundary===findingsInput.boundary),hasExistingBoundaryRecords=existingBoundaryRecords.length>0,isExactReplay=hasExistingBoundaryRecords&&canonicalFindingRecords(existingBoundaryRecords)===canonicalFindingRecords(findingsInput.records),boundaryCommitted=state2.prReviewArtifactRunId===resolvedRunId&&(state2.prReviewArtifactBoundaries??[]).includes(findingsInput.boundary),existingBoundaryIds=new Set(existingBoundaryRecords.map((record3)=>record3.finding_id)),requestedFindingIds=new Set(findingIds),isPostExplorerSupersession=boundaryCommitted&&findingsInput.boundary==="post_explorer"&&Boolean(state2.prReviewTriggerEvalPath)&&existingBoundaryIds.size<requestedFindingIds.size&&[...existingBoundaryIds].every((id)=>requestedFindingIds.has(id)),isCommittedReplay=isExactReplay&&boundaryCommitted,partialAdmissionToRollback,rollbackPartialAdmission=async()=>{if(!partialAdmissionToRollback)return;try{return await rollbackPrReviewPartialBaseCoverageAdmission(directory,sessionID,partialAdmissionToRollback)?void 0:"partial base coverage admission could not be safely rolled back because durable state changed"}catch(error93){return`partial base coverage admission rollback failed: ${error93 instanceof Error?error93.message:String(error93)}`}},withPartialAdmissionRollback=async(result)=>{let rollbackError=await rollbackPartialAdmission();if(!rollbackError)return result;try{let decoded=JSON.parse(result);return typeof decoded.message==="string"?failure3(`${decoded.message}; ${rollbackError}`):result}catch{return result}};if(!isCommittedReplay)try{await _internals311.assertBoundary(directory,sessionID,resolvedRunId,findingsInput.boundary,findingIds,findingsInput.partial_base_coverage?{skipBaseCoverage:!0}:void 0)}catch(error93){return withPartialAdmissionRollback(failure3(formatPrReviewRuntimeFieldError(findingsInput.partial_base_coverage?"partial_base_coverage":"boundary",findingsInput.partial_base_coverage?"a terminal N-of-6 settlement: every declared unresolved dimension terminal (typed failure, explicit cancellation, or never launched) after every other boundary predicate passes":`the legal next "${findingsInput.boundary}" checkpoint for run "${resolvedRunId}" with exact inventory [${findingIds.join(", ")}]`,error93 instanceof Error?error93.message:String(error93))))}try{await assertPrReviewArtifactRecordsMatchAuthoritativeVerdicts(directory,sessionID,findingsInput.boundary,findingsInput.records)}catch(error93){return failure3(formatPrReviewRuntimeFieldError("records",`records exactly matching authoritative ${findingsInput.boundary} verdicts and disposition rules`,error93 instanceof Error?error93.message:String(error93)))}if(hasExistingBoundaryRecords&&boundaryCommitted&&!isExactReplay&&!isPostExplorerSupersession)return failure3(formatPrReviewRuntimeFieldError("records",`an exact replay of the already-persisted "${findingsInput.boundary}" boundary`,findingsInput.records));if(!isCommittedReplay)try{if(findingsInput.partial_base_coverage){let hadPartialAdmission=Boolean(state2.prReviewPartialBaseCoverage||state2.prReviewCoverageDisclosurePath||state2.prReviewCoverageDisclosureDigest);if(await _internals311.assertBoundary(directory,sessionID,resolvedRunId,findingsInput.boundary,findingIds,{skipBaseCoverage:!0}),state2=await admitPrReviewPartialBaseCoverage2(directory,sessionID,resolvedRunId,findingsInput.partial_base_coverage.unresolved_dimensions),!hadPartialAdmission&&state2.prReviewPartialBaseCoverage&&state2.prReviewCoverageDisclosurePath&&state2.prReviewCoverageDisclosureDigest)partialAdmissionToRollback={runId:state2.prReviewPartialBaseCoverage.runId,boundary:findingsInput.boundary,relativePath:state2.prReviewCoverageDisclosurePath,digest:state2.prReviewCoverageDisclosureDigest}}if(findingsInput.partial_base_coverage)await _internals311.assertBoundary(directory,sessionID,resolvedRunId,findingsInput.boundary,findingIds)}catch(error93){return withPartialAdmissionRollback(failure3(formatPrReviewRuntimeFieldError(findingsInput.partial_base_coverage?"partial_base_coverage":"boundary",findingsInput.partial_base_coverage?"a terminal N-of-6 settlement: every declared unresolved dimension terminal (typed failure, explicit cancellation, or never launched) after every other boundary predicate passes":`the legal next "${findingsInput.boundary}" checkpoint for run "${resolvedRunId}" with exact inventory [${findingIds.join(", ")}]`,error93 instanceof Error?error93.message:String(error93))))}let recordedAt=new Date().toISOString(),appended=isExactReplay?[]:findingsInput.records.map((record3)=>({...record3,boundary:findingsInput.boundary,pr_head_sha:state2.prHeadSha,recorded_at:recordedAt})),allRecords=[...existing,...appended],serializedFindings=allRecords.map((record3)=>JSON.stringify(record3)).join(`
|
|
7830
7830
|
`)+(allRecords.length>0?`
|
|
7831
7831
|
`:""),findingsDigest=createHash116("sha256").update(serializedFindings,"utf8").digest("hex"),criticSettlements;if(findingsInput.boundary==="post_critic")try{let authoritativeCriticVerdicts=existing.some((record3)=>record3.boundary==="post_reviewer"&&record3.next_action==="route_to_critic")?await readAuthoritativePrReviewCriticVerdicts(directory,sessionID):new Map;criticSettlements=assertCriticSettlements(findingsInput.records,existing,authoritativeCriticVerdicts)}catch(error93){return withPartialAdmissionRollback(operationFailure("validate",relativeFindingsPath.split(path374.sep).join("/"),"an authoritative critic settlement matching the authenticated critic verdict map",error93))}if(!isExactReplay){let serializedBytes=Buffer.byteLength(serializedFindings,"utf8");if(serializedBytes>PR_REVIEW_FINDINGS_MAX_BYTES)return withPartialAdmissionRollback(failure3(formatPrReviewRuntimeFieldError("records",`a complete findings artifact at most ${PR_REVIEW_FINDINGS_MAX_BYTES} UTF-8 bytes`,`${serializedBytes} bytes`)));try{await _internals311.atomicWrite(findingsPath,serializedFindings)}catch(error93){return withPartialAdmissionRollback(operationFailure("write",relativeFindingsPath.split(path374.sep).join("/"),"an atomic findings checkpoint write",error93))}}let latest2=latestFindings(allRecords);if(findingsInput.boundary==="post_critic")try{let synthesis=synthesizePrReviewFindings({candidates:policyCandidates([...latest2.values()],sessionID,findingsInput.boundary)});await persistReviewOutcome({projectRoot:directory,routeReceipt:{kind:"pr_review_finding_policy",version:1,sessionId:sessionID,taskId:resolvedRunId,boundary:findingsInput.boundary,prHeadSha:state2.prHeadSha,findingsPath:relativeFindingsPath.split(path374.sep).join("/"),findingsDigest},synthesis:{...synthesis,criticSettlements}})}catch(error93){return withPartialAdmissionRollback(operationFailure("persist",`pr-review/${resolvedRunId}/finding-policy.json`,"an authoritative version-1 critic settlement and finding-policy evidence record",error93))}let handoffRequired=deriveFeedbackHandoffFindingIds([...latest2.values()]).length>0;if(!isCommittedReplay)try{await markPrReviewArtifactBoundary(directory,sessionID,resolvedRunId,findingsInput.boundary,relativeFindingsPath.split(path374.sep).join("/"),findingIds,handoffRequired)}catch(error93){return withPartialAdmissionRollback(operationFailure("update",`pr-workflow-gates/${prWorkflowSessionFileStem(sessionID)}.json`,`a durable ${findingsInput.boundary} boundary receipt`,error93))}return JSON.stringify({success:!0,run_id:resolvedRunId,path:relativeFindingsPath.split(path374.sep).join("/"),boundary:findingsInput.boundary,appended:appended.length,replayed:isExactReplay,handoff_required:handoffRequired,...state2.prReviewPartialBaseCoverage?{partial_base_coverage:{unresolved_dimensions:normalizePrReviewPartialBaseCoverageRecord(state2.prReviewPartialBaseCoverage).unresolvedDimensions.map((entry)=>({dimension:entry.dimension,terminal_state:entry.terminalState,reason_kind:entry.reasonKind,failure_class:entry.failureClass})),path:state2.prReviewCoverageDisclosurePath,digest:state2.prReviewCoverageDisclosureDigest}}:{}},null,2)}let latest=latestFindings(existing),actionableIds=deriveFeedbackHandoffFindingIds([...latest.values()]),requestedIds=[...new Set(parsed.data.handoff.finding_ids)].sort();if(actionableIds.length===0||JSON.stringify(actionableIds)!==JSON.stringify(requestedIds))return failure3(`field handoff.finding_ids: expected authoritative actionable set [${actionableIds.join(", ")||"(none)"}], got requested [${requestedIds.join(", ")||"(none)"}]`);let relativeHandoffPath=path374.join("pr-review",resolvedRunId,"feedback-handoff.json"),handoffPath;try{handoffPath=validateSwarmPath(directory,relativeHandoffPath)}catch(error93){return operationFailure("resolve",relativeHandoffPath.split(path374.sep).join("/"),"a contained path below the project .swarm directory",error93)}let handoffRecord={schema_version:1,run_id:resolvedRunId,pr_head_sha:state2.prHeadSha,created_at:new Date().toISOString(),...parsed.data.handoff},comparableHandoff=(record3)=>({schema_version:record3.schema_version,run_id:record3.run_id,pr_head_sha:record3.pr_head_sha,pr_url:record3.pr_url,finding_ids:record3.finding_ids,summary:record3.summary,provenance:record3.provenance}),handoffsMatch=(existing2)=>JSON.stringify(comparableHandoff(existing2))===JSON.stringify(comparableHandoff(handoffRecord)),readPersistedHandoff=async()=>{let raw=await readBoundedUtf8File2(handoffPath,PR_REVIEW_HANDOFF_MAX_BYTES,"handoff artifact"),decoded;try{decoded=JSON.parse(raw)}catch(error93){throw Error(`invalid JSON: ${error93 instanceof Error?error93.message:String(error93)}`)}let validated=PersistedHandoffSchema.safeParse(decoded);if(!validated.success)throw Error(`schema mismatch: ${formatPrReviewValidationIssues(validated.error.issues,decoded).join("; ")}`);return validated.data},existingHandoff=null;try{existingHandoff=await readPersistedHandoff()}catch(error93){if(error93.code!=="ENOENT")return failure3(`operation read path "${relativeHandoffPath.split(path374.sep).join("/")}": expected bounded JSON matching the persisted handoff schema, got ${error93 instanceof Error?error93.message:String(error93)}`)}if(existingHandoff){if(!handoffsMatch(existingHandoff))return failure3("field handoff: expected an exact retry of the persisted handoff, got conflicting handoff content")}else{let serializedHandoff=`${JSON.stringify(handoffRecord,null,2)}
|
|
@@ -7837,7 +7837,7 @@ ${outputSummary}`,sessionId,"tool")}catch{}}}}init_utils();init_git_executable()
|
|
|
7837
7837
|
${tailContent.join(`
|
|
7838
7838
|
`)}
|
|
7839
7839
|
${footerLines.join(`
|
|
7840
|
-
`)}`}init_core_events();init_skill_propagation_gate();init_warning_buffer();init_canonical_root();init_cache_paths();import*as fs234 from"node:fs";import*as os32 from"node:os";import*as path377 from"node:path";import*as fs233 from"node:fs";import*as path376 from"node:path";var _internals314={realpathSyncNative:fs233.realpathSync.native};function hostWindowsPath(input){return input.replace(/^\/([a-zA-Z]):(?:[\\/]|$)/,(_m,d)=>`${d.toUpperCase()}:/`).replace(/^\/([a-zA-Z])(?:\/|$)/,(_m,d)=>`${d.toUpperCase()}:/`).replace(/^\/cygdrive\/([a-zA-Z])(?:\/|$)/,(_m,d)=>`${d.toUpperCase()}:/`).replace(/^\/mnt\/([a-zA-Z])(?:\/|$)/,(_m,d)=>`${d.toUpperCase()}:/`)}function hostNormalizePath(input){let resolved=path376.resolve(hostWindowsPath(input));try{return _internals314.realpathSyncNative(resolved)}catch{return resolved}}function hostNormalizePathPattern(pattern){if(pattern==="*")return pattern;let match=/^(.*)[\\/]\*$/.exec(pattern);if(!match)return hostNormalizePath(pattern);let dir=/^[A-Za-z]:$/.test(match[1])?`${match[1]}\\`:match[1];return path376.join(hostNormalizePath(dir),"*")}init_lane_context();class LastWinsRuleMap{entries=new Map;set(pattern,action2){this.entries.delete(pattern),this.entries.set(pattern,action2)}toObject(){return Object.fromEntries(this.entries)}}var SKILL_DIR_NAMES=["skill","skills"],HOST_HOME_SKILL_MARKERS=[".claude",".agents"];function laneDirectoryPattern(dir){return hostNormalizePathPattern(path377.join(dir,"*"))}function isExpressibleDirectory(dir){return!dir.includes("*")&&!dir.includes("?")}function push(out,seen,dir,reason){if(!dir)return;let resolved;try{resolved=path377.resolve(dir)}catch{return}if(!isExpressibleDirectory(resolved))return;let key2=canonicalRootKeyFresh(resolved);if(seen.has(key2))return;seen.add(key2),out.push({dir:resolved,pattern:laneDirectoryPattern(resolved),reason})}function buildLaneAllowlist(lane,configuredSkillPaths=[],configuredSkillUrls=[]){let out=[],seen=new Set;push(out,seen,lane.parentProjectPath,"parent project the lane is a git worktree of"),push(out,seen,lane.lanePath,"the lane worktree itself"),push(out,seen,getPluginConfigDir(),"OpenCode XDG config dir (host Global.Path.config)"),push(out,seen,getHostConfigDir(),"OpenCode config dir override (OPENCODE_CONFIG_DIR), when set");let tmpRoot=os32.tmpdir();if(push(out,seen,path377.join(tmpRoot,"opencode"),"OpenCode's own temp dir (host Global.Path.tmp)"),process.platform==="win32")push(out,seen,path377.join(tmpRoot,"swwt"),"shortened-worktree lane root (Windows path-budget fallback)");push(out,seen,path377.join(getHostDataDir(),"plans"),"OpenCode plan storage (host `plan` agent's native allow)");let home;try{home=os32.homedir()}catch{home=void 0}let projectRoots=[{base:lane.parentProjectPath,label:"parent project"},{base:lane.lanePath,label:"lane"}];for(let marker of HOST_HOME_SKILL_MARKERS){for(let{base,label}of projectRoots)push(out,seen,path377.resolve(base,marker,"skills"),`skill root (${label}): ${marker}/skills`);if(home)push(out,seen,path377.resolve(home,marker,"skills"),`skill root (user level): ~/${marker}/skills`)}let configSkillRoots=[{base:getPluginConfigDir(),label:"XDG config dir"},{base:getHostConfigDir(),label:"config dir override"},...projectRoots.map(({base,label})=>({base:path377.resolve(base,".opencode"),label:`${label} .opencode`})),...home?[{base:path377.join(home,".opencode"),label:"user-level .opencode"}]:[]];for(let{base,label}of configSkillRoots)for(let dirName of SKILL_DIR_NAMES)push(out,seen,path377.resolve(base,dirName),`skill root (${label}): ${dirName}/`);for(let relative92 of SKILL_SEARCH_ROOTS){for(let{base,label}of projectRoots)push(out,seen,path377.resolve(base,relative92),`skill root (${label}): ${relative92}`);if(home)push(out,seen,path377.resolve(home,relative92),`skill root (user level): ~/${relative92}`)}if((Array.isArray(configuredSkillUrls)?configuredSkillUrls:[]).some((u)=>typeof u==="string"&&u.trim()!==""))push(out,seen,getHostSkillCacheDir(),"URL-sourced skill cache (only because skills.urls is configured)");let skillPaths=Array.isArray(configuredSkillPaths)?configuredSkillPaths:[];for(let configured of skillPaths){if(typeof configured!=="string"||configured.trim()==="")continue;let expanded=configured.startsWith("~/")&&home?path377.join(home,configured.slice(2)):configured;push(out,seen,path377.isAbsolute(expanded)?expanded:path377.resolve(lane.lanePath,expanded),`configured skills.path: ${configured}`)}return out}function normalizeExisting(existing){if(typeof existing==="string")return{"*":existing};if(existing&&typeof existing==="object"&&!Array.isArray(existing))return{...existing};return}function buildLaneExternalDirectoryRules(mode,lane,existing,precomputedAllowlist){if(mode==="off")return null;let rules=new LastWinsRuleMap;if(rules.set("*","deny"),mode==="scoped_allow")for(let entry of precomputedAllowlist??buildLaneAllowlist(lane))rules.set(entry.pattern,"allow");let coercedAskPatterns=[],user=normalizeExisting(existing);if(user)for(let[pattern,action2]of Object.entries(user)){if(action2==="ask"){coercedAskPatterns.push(pattern),rules.set(pattern,"deny");continue}rules.set(pattern,action2)}return{rules:rules.toObject(),coercedAskPatterns}}function renderLanePermissionAdvisory(mode,lane,allowlist,coercedAskPatterns=[]){let scope=mode==="deny"?"ALL external directory access is denied in this lane":`external directory access is limited to ${allowlist.length} justified path(s)`,parts=[`[swarm] Worktree-lane permissions active for ${lane.lanePath} (worktree of ${lane.parentProjectPath}).`,`Policy worktree.lane_permissions="${mode}": ${scope}; anything else is denied rather than left pending.`,'A lane instance has no TUI attached, so an "ask" there can never be answered and would hang the lane forever.'];if(coercedAskPatterns.length>0)parts.push(`Your configured external_directory "ask" rule(s) [${coercedAskPatterns.join(", ")}] were treated as "deny" here for that reason — change them to "allow" if the lane needs those paths.`);return parts.push("To widen the allowlist, add the directory to opencode.json:",' { "permission": { "external_directory": { "<absolute-dir>/*": "allow" } } }','To restore the previous (hanging) behaviour, set worktree.lane_permissions to "off".'),parts.join(" ")}var _internals315={resolveLaneContext,addDeferredWarning,appendFileSync:fs234.appendFileSync,mkdirSync:fs234.mkdirSync};function readConfiguredSkillList(opencodeConfig,key2){let skills=opencodeConfig.skills;if(!skills||typeof skills!=="object"||Array.isArray(skills))return[];let value=skills[key2];if(!Array.isArray(value))return[];return value.filter((v)=>typeof v==="string"&&v.trim()!=="")}function downgradeAgentAskRules(opencodeConfig){let coerced=[],agents=opencodeConfig.agent;if(!agents||typeof agents!=="object"||Array.isArray(agents))return coerced;for(let[agentName,rawAgent]of Object.entries(agents)){if(!rawAgent||typeof rawAgent!=="object"||Array.isArray(rawAgent))continue;let rawPermission=rawAgent.permission;if(!rawPermission||typeof rawPermission!=="object"||Array.isArray(rawPermission))continue;let agentPermission=rawPermission,external3=agentPermission.external_directory;if(external3==="ask"){agentPermission.external_directory="deny",coerced.push(`${agentName}.*`);continue}if(!external3||typeof external3!=="object"||Array.isArray(external3))continue;let map3=external3;for(let[pattern,action2]of Object.entries(map3)){if(action2!=="ask")continue;map3[pattern]="deny",coerced.push(`${agentName}.${pattern}`)}}return coerced}function recordLanePermissionEvent(directory,event){try{appendCoreEventSync(directory,event)}catch{}}function applyLanePermissions(opencodeConfig,directory,mode){let lane=_internals315.resolveLaneContext(directory);if(!lane)return{lane:!1};let eventRoot=lane.lanePath;if(mode==="off")return recordLanePermissionEvent(eventRoot,{event:"lane_permissions",timestamp:new Date().toISOString(),decision:"skipped",mode,lanePath:lane.lanePath,parentProjectPath:lane.parentProjectPath,reason:'worktree.lane_permissions is "off"; external_directory asks in this lane cannot be answered and will hang'}),{lane:!0,mode};let permission=(()=>{let current=opencodeConfig.permission;if(current&&typeof current==="object"&&!Array.isArray(current))return current;let created={};return opencodeConfig.permission=created,created})(),agentCoerced=downgradeAgentAskRules(opencodeConfig),allowlist=mode==="scoped_allow"?buildLaneAllowlist(lane,readConfiguredSkillList(opencodeConfig,"paths"),readConfiguredSkillList(opencodeConfig,"urls")):[],build=buildLaneExternalDirectoryRules(mode,lane,permission.external_directory,allowlist);if(!build)return{lane:!0,mode};let{rules,coercedAskPatterns:topLevelCoerced}=build;permission.external_directory=rules;let coercedAskPatterns=[...topLevelCoerced,...agentCoerced];return _internals315.addDeferredWarning(renderLanePermissionAdvisory(mode,lane,allowlist,coercedAskPatterns)),recordLanePermissionEvent(eventRoot,{event:"lane_permissions",timestamp:new Date().toISOString(),decision:"applied",mode,lanePath:lane.lanePath,parentProjectPath:lane.parentProjectPath,allowlist:allowlist.map((entry)=>({pattern:entry.pattern,reason:entry.reason})),rules,coercedAskPatterns,remedy:'Add { "permission": { "external_directory": { "<absolute-dir>/*": "allow" } } } to opencode.json to widen the allowlist.'}),{lane:!0,mode,rules}}init_warning_buffer();init_archive_sqlite();init_fixtures();init_gate_ground_truth();init_pr_review_recovery();init_public_api();init_contracts2();init_factory();init_hash();init_patch();init_protected_path_policy();init_git_executable();init_path_security();init_project_boundary();init_contracts2();init_hash();import{spawn as spawn6}from"node:child_process";import{createHash as createHash117}from"node:crypto";import{existsSync as existsSync200,lstatSync as lstatSync44}from"node:fs";import*as path378 from"node:path";var SHA_RE=/^[a-f0-9]{40,64}$/,RECORD_VERSION2=1,GIT_TIMEOUT_MS13=3000,MAX_GIT_OUTPUT_BYTES3=32768,TEXT_DECODER=new TextDecoder("utf-8",{fatal:!0});function normalizeRelativePath2(value){return value.replace(/\\/g,"/").replace(/^\.\/+/,"")}function decodeQuotedGitPathToken(value){if(!value.startsWith('"')||!value.endsWith('"'))return null;let decoded="";for(let index=1;index<value.length-1;index++){let current=value[index];if(current!=="\\"){decoded+=current;continue}let next=value[index+1];if(!next)return null;if(/[0-7]/.test(next)){let octal=next,cursor=index+2;while(cursor<value.length-1&&octal.length<3){let digit=value[cursor];if(!/[0-7]/.test(digit))break;octal+=digit,cursor++}decoded+=String.fromCharCode(Number.parseInt(octal,8)),index+=octal.length;continue}decoded+=next==="t"?"\t":next==="n"?`
|
|
7840
|
+
`)}`}init_core_events();init_skill_propagation_gate();init_warning_buffer();init_canonical_root();init_cache_paths();import*as fs234 from"node:fs";import*as os32 from"node:os";import*as path377 from"node:path";import*as fs233 from"node:fs";import*as path376 from"node:path";var _internals314={realpathSyncNative:fs233.realpathSync.native};function hostWindowsPath(input){return input.replace(/^\/([a-zA-Z]):(?:[\\/]|$)/,(_m,d)=>`${d.toUpperCase()}:/`).replace(/^\/([a-zA-Z])(?:\/|$)/,(_m,d)=>`${d.toUpperCase()}:/`).replace(/^\/cygdrive\/([a-zA-Z])(?:\/|$)/,(_m,d)=>`${d.toUpperCase()}:/`).replace(/^\/mnt\/([a-zA-Z])(?:\/|$)/,(_m,d)=>`${d.toUpperCase()}:/`)}function hostNormalizePath(input){let resolved=path376.resolve(hostWindowsPath(input));try{return _internals314.realpathSyncNative(resolved)}catch{return resolved}}function hostNormalizePathPattern(pattern){if(pattern==="*")return pattern;let match=/^(.*)[\\/]\*$/.exec(pattern);if(!match)return hostNormalizePath(pattern);let dir=/^[A-Za-z]:$/.test(match[1])?`${match[1]}\\`:match[1];return path376.join(hostNormalizePath(dir),"*")}init_lane_context();class LastWinsRuleMap{entries=new Map;set(pattern,action2){this.entries.delete(pattern),this.entries.set(pattern,action2)}toObject(){return Object.fromEntries(this.entries)}}var SKILL_DIR_NAMES=["skill","skills"],HOST_HOME_SKILL_MARKERS=[".claude",".agents"];function laneDirectoryPattern(dir){return hostNormalizePathPattern(path377.join(dir,"*"))}function isExpressibleDirectory(dir){return!dir.includes("*")&&!dir.includes("?")}function push(out,seen,dir,reason){if(!dir)return;let resolved;try{resolved=path377.resolve(dir)}catch{return}if(!isExpressibleDirectory(resolved))return;let key2=canonicalRootKeyFresh(resolved);if(seen.has(key2))return;seen.add(key2),out.push({dir:resolved,pattern:laneDirectoryPattern(resolved),reason})}function buildLaneAllowlist(lane,configuredSkillPaths=[],configuredSkillUrls=[]){let out=[],seen=new Set;push(out,seen,lane.parentProjectPath,"parent project the lane is a git worktree of"),push(out,seen,lane.lanePath,"the lane worktree itself"),push(out,seen,getPluginConfigDir(),"OpenCode XDG config dir (host Global.Path.config)"),push(out,seen,getHostConfigDir(),"OpenCode config dir override (OPENCODE_CONFIG_DIR), when set");let tmpRoot=os32.tmpdir();if(push(out,seen,path377.join(tmpRoot,"opencode"),"OpenCode's own temp dir (host Global.Path.tmp)"),process.platform==="win32")push(out,seen,path377.join(tmpRoot,"swwt"),"shortened-worktree lane root (Windows path-budget fallback)");push(out,seen,path377.join(getHostDataDir(),"plans"),"OpenCode plan storage (host `plan` agent's native allow)");let home;try{home=os32.homedir()}catch{home=void 0}let projectRoots=[{base:lane.parentProjectPath,label:"parent project"},{base:lane.lanePath,label:"lane"}];for(let marker of HOST_HOME_SKILL_MARKERS){for(let{base,label}of projectRoots)push(out,seen,path377.resolve(base,marker,"skills"),`skill root (${label}): ${marker}/skills`);if(home)push(out,seen,path377.resolve(home,marker,"skills"),`skill root (user level): ~/${marker}/skills`)}let configSkillRoots=[{base:getPluginConfigDir(),label:"XDG config dir"},{base:getHostConfigDir(),label:"config dir override"},...projectRoots.map(({base,label})=>({base:path377.resolve(base,".opencode"),label:`${label} .opencode`})),...home?[{base:path377.join(home,".opencode"),label:"user-level .opencode"}]:[]];for(let{base,label}of configSkillRoots)for(let dirName of SKILL_DIR_NAMES)push(out,seen,path377.resolve(base,dirName),`skill root (${label}): ${dirName}/`);for(let relative93 of SKILL_SEARCH_ROOTS){for(let{base,label}of projectRoots)push(out,seen,path377.resolve(base,relative93),`skill root (${label}): ${relative93}`);if(home)push(out,seen,path377.resolve(home,relative93),`skill root (user level): ~/${relative93}`)}if((Array.isArray(configuredSkillUrls)?configuredSkillUrls:[]).some((u)=>typeof u==="string"&&u.trim()!==""))push(out,seen,getHostSkillCacheDir(),"URL-sourced skill cache (only because skills.urls is configured)");let skillPaths=Array.isArray(configuredSkillPaths)?configuredSkillPaths:[];for(let configured of skillPaths){if(typeof configured!=="string"||configured.trim()==="")continue;let expanded=configured.startsWith("~/")&&home?path377.join(home,configured.slice(2)):configured;push(out,seen,path377.isAbsolute(expanded)?expanded:path377.resolve(lane.lanePath,expanded),`configured skills.path: ${configured}`)}return out}function normalizeExisting(existing){if(typeof existing==="string")return{"*":existing};if(existing&&typeof existing==="object"&&!Array.isArray(existing))return{...existing};return}function buildLaneExternalDirectoryRules(mode,lane,existing,precomputedAllowlist){if(mode==="off")return null;let rules=new LastWinsRuleMap;if(rules.set("*","deny"),mode==="scoped_allow")for(let entry of precomputedAllowlist??buildLaneAllowlist(lane))rules.set(entry.pattern,"allow");let coercedAskPatterns=[],user=normalizeExisting(existing);if(user)for(let[pattern,action2]of Object.entries(user)){if(action2==="ask"){coercedAskPatterns.push(pattern),rules.set(pattern,"deny");continue}rules.set(pattern,action2)}return{rules:rules.toObject(),coercedAskPatterns}}function renderLanePermissionAdvisory(mode,lane,allowlist,coercedAskPatterns=[]){let scope=mode==="deny"?"ALL external directory access is denied in this lane":`external directory access is limited to ${allowlist.length} justified path(s)`,parts=[`[swarm] Worktree-lane permissions active for ${lane.lanePath} (worktree of ${lane.parentProjectPath}).`,`Policy worktree.lane_permissions="${mode}": ${scope}; anything else is denied rather than left pending.`,'A lane instance has no TUI attached, so an "ask" there can never be answered and would hang the lane forever.'];if(coercedAskPatterns.length>0)parts.push(`Your configured external_directory "ask" rule(s) [${coercedAskPatterns.join(", ")}] were treated as "deny" here for that reason — change them to "allow" if the lane needs those paths.`);return parts.push("To widen the allowlist, add the directory to opencode.json:",' { "permission": { "external_directory": { "<absolute-dir>/*": "allow" } } }','To restore the previous (hanging) behaviour, set worktree.lane_permissions to "off".'),parts.join(" ")}var _internals315={resolveLaneContext,addDeferredWarning,appendFileSync:fs234.appendFileSync,mkdirSync:fs234.mkdirSync};function readConfiguredSkillList(opencodeConfig,key2){let skills=opencodeConfig.skills;if(!skills||typeof skills!=="object"||Array.isArray(skills))return[];let value=skills[key2];if(!Array.isArray(value))return[];return value.filter((v)=>typeof v==="string"&&v.trim()!=="")}function downgradeAgentAskRules(opencodeConfig){let coerced=[],agents=opencodeConfig.agent;if(!agents||typeof agents!=="object"||Array.isArray(agents))return coerced;for(let[agentName,rawAgent]of Object.entries(agents)){if(!rawAgent||typeof rawAgent!=="object"||Array.isArray(rawAgent))continue;let rawPermission=rawAgent.permission;if(!rawPermission||typeof rawPermission!=="object"||Array.isArray(rawPermission))continue;let agentPermission=rawPermission,external3=agentPermission.external_directory;if(external3==="ask"){agentPermission.external_directory="deny",coerced.push(`${agentName}.*`);continue}if(!external3||typeof external3!=="object"||Array.isArray(external3))continue;let map3=external3;for(let[pattern,action2]of Object.entries(map3)){if(action2!=="ask")continue;map3[pattern]="deny",coerced.push(`${agentName}.${pattern}`)}}return coerced}function recordLanePermissionEvent(directory,event){try{appendCoreEventSync(directory,event)}catch{}}function applyLanePermissions(opencodeConfig,directory,mode){let lane=_internals315.resolveLaneContext(directory);if(!lane)return{lane:!1};let eventRoot=lane.lanePath;if(mode==="off")return recordLanePermissionEvent(eventRoot,{event:"lane_permissions",timestamp:new Date().toISOString(),decision:"skipped",mode,lanePath:lane.lanePath,parentProjectPath:lane.parentProjectPath,reason:'worktree.lane_permissions is "off"; external_directory asks in this lane cannot be answered and will hang'}),{lane:!0,mode};let permission=(()=>{let current=opencodeConfig.permission;if(current&&typeof current==="object"&&!Array.isArray(current))return current;let created={};return opencodeConfig.permission=created,created})(),agentCoerced=downgradeAgentAskRules(opencodeConfig),allowlist=mode==="scoped_allow"?buildLaneAllowlist(lane,readConfiguredSkillList(opencodeConfig,"paths"),readConfiguredSkillList(opencodeConfig,"urls")):[],build=buildLaneExternalDirectoryRules(mode,lane,permission.external_directory,allowlist);if(!build)return{lane:!0,mode};let{rules,coercedAskPatterns:topLevelCoerced}=build;permission.external_directory=rules;let coercedAskPatterns=[...topLevelCoerced,...agentCoerced];return _internals315.addDeferredWarning(renderLanePermissionAdvisory(mode,lane,allowlist,coercedAskPatterns)),recordLanePermissionEvent(eventRoot,{event:"lane_permissions",timestamp:new Date().toISOString(),decision:"applied",mode,lanePath:lane.lanePath,parentProjectPath:lane.parentProjectPath,allowlist:allowlist.map((entry)=>({pattern:entry.pattern,reason:entry.reason})),rules,coercedAskPatterns,remedy:'Add { "permission": { "external_directory": { "<absolute-dir>/*": "allow" } } } to opencode.json to widen the allowlist.'}),{lane:!0,mode,rules}}init_warning_buffer();init_archive_sqlite();init_fixtures();init_gate_ground_truth();init_pr_review_recovery();init_public_api();init_contracts2();init_factory();init_hash();init_patch();init_protected_path_policy();init_git_executable();init_path_security();init_project_boundary();init_contracts2();init_hash();import{spawn as spawn6}from"node:child_process";import{createHash as createHash117}from"node:crypto";import{existsSync as existsSync200,lstatSync as lstatSync44}from"node:fs";import*as path378 from"node:path";var SHA_RE=/^[a-f0-9]{40,64}$/,RECORD_VERSION2=1,GIT_TIMEOUT_MS13=3000,MAX_GIT_OUTPUT_BYTES3=32768,TEXT_DECODER=new TextDecoder("utf-8",{fatal:!0});function normalizeRelativePath2(value){return value.replace(/\\/g,"/").replace(/^\.\/+/,"")}function decodeQuotedGitPathToken(value){if(!value.startsWith('"')||!value.endsWith('"'))return null;let decoded="";for(let index=1;index<value.length-1;index++){let current=value[index];if(current!=="\\"){decoded+=current;continue}let next=value[index+1];if(!next)return null;if(/[0-7]/.test(next)){let octal=next,cursor=index+2;while(cursor<value.length-1&&octal.length<3){let digit=value[cursor];if(!/[0-7]/.test(digit))break;octal+=digit,cursor++}decoded+=String.fromCharCode(Number.parseInt(octal,8)),index+=octal.length;continue}decoded+=next==="t"?"\t":next==="n"?`
|
|
7841
7841
|
`:next==="r"?"\r":next==="b"?"\b":next==="f"?"\f":next,index++}return decoded}function parseGitPathToken(value,startIndex=0){if(startIndex>=value.length)return null;if(value[startIndex]==='"'){let index2=startIndex+1;while(index2<value.length){let current=value[index2];if(current==="\\"){index2+=2;continue}if(current==='"')return{token:value.slice(startIndex,index2+1),nextIndex:index2+1};index2++}return null}let index=startIndex;while(index<value.length&&value[index]!==" ")index++;return{token:value.slice(startIndex,index),nextIndex:index}}function parseGitPathValue(value,expectedPrefix){let trimmed=value.trim(),parsed=parseGitPathToken(trimmed);if(!parsed||parsed.nextIndex!==value.trim().length)return null;let decoded=parsed.token.startsWith('"')?decodeQuotedGitPathToken(parsed.token):parsed.token;if(!decoded)return null;if(decoded==="/dev/null")return decoded;if(expectedPrefix&&!decoded.startsWith(expectedPrefix))return null;return normalizeRelativePath2(expectedPrefix?decoded.slice(expectedPrefix.length):decoded)}function parseGitHeaderPath(line,headerPrefix,expectedPathPrefix){if(!line.startsWith(headerPrefix))return null;return parseGitPathValue(line.slice(headerPrefix.length),expectedPathPrefix)}function parseDiffGitLine(line){if(!line.startsWith("diff --git "))return null;let body=line.slice(11),oldToken=parseGitPathToken(body);if(!oldToken)return null;let cursor=oldToken.nextIndex;while(cursor<body.length&&body[cursor]===" ")cursor++;let newToken=parseGitPathToken(body,cursor);if(!newToken)return null;cursor=newToken.nextIndex;while(cursor<body.length&&body[cursor]===" ")cursor++;if(cursor!==body.length)return null;let oldDecoded=parseGitPathValue(oldToken.token,"a/"),newDecoded=parseGitPathValue(newToken.token,"b/");if(!oldDecoded||!newDecoded)return null;return{oldPath:oldDecoded,newPath:newDecoded}}function isWithinPrefix(relativePath2,prefix){return relativePath2===prefix||relativePath2.startsWith(`${prefix}/`)}function isAllowlisted(relativePath2,allowlist){return allowlist.some((prefix)=>isWithinPrefix(relativePath2,normalizeRelativePath2(prefix)))}function isProtectedPath4(relativePath2,extraProtectedPaths){return isPolicyProtectedPath(relativePath2,{additional:[".opencode",".claude",".agents","dist","evaluation-fixtures","src/services/skill-improver","src/services/skill-optimizer","src/evidence","scripts",...extraProtectedPaths]})}function parseCount(token){if(!token)return 1;let parsed=Number.parseInt(token,10);return Number.isFinite(parsed)&&parsed>=0?parsed:-1}function validateParsedHunk(hunk){if(hunk.oldCount<0||hunk.newCount<0)return!1;if(hunk.oldCount===0?hunk.oldStart<0:hunk.oldStart<1)return!1;if(hunk.newCount===0?hunk.newStart<0:hunk.newStart<1)return!1;let oldSeen=0,newSeen=0,previousWasContent=!1;for(let line of hunk.lines){if(line==="\"){if(!previousWasContent)return!1;previousWasContent=!1;continue}let marker=line[0];if(marker===" ")oldSeen++,newSeen++;else if(marker==="-")oldSeen++;else if(marker==="+")newSeen++;else return!1;previousWasContent=!0}return oldSeen===hunk.oldCount&&newSeen===hunk.newCount}function validateHunkOrdering(hunks){let nextOldAnchor=0,nextNewAnchor=0;for(let hunk of hunks){let oldAnchor=hunk.oldCount===0?hunk.oldStart:hunk.oldStart-1,newAnchor=hunk.newCount===0?hunk.newStart:hunk.newStart-1;if(oldAnchor<nextOldAnchor||newAnchor<nextNewAnchor)return!1;nextOldAnchor=oldAnchor+hunk.oldCount,nextNewAnchor=newAnchor+hunk.newCount}return!0}function parsePatch(patch2){let lines=patch2.replace(/\r\n/g,`
|
|
7842
7842
|
`).split(`
|
|
7843
7843
|
`),files=[],index=0;while(index<lines.length){let line=lines[index];if(!line){index++;continue}let diffLine=parseDiffGitLine(line);if(!diffLine)return null;let{oldPath,newPath}=diffLine;index++;let operation=oldPath===newPath?"modify":"rename",declaredOldPath=oldPath,declaredNewPath=newPath,oldMode,newMode,oldObjectId,newObjectId;while(index<lines.length){let header=lines[index];if(!header){index++;continue}if(parseDiffGitLine(header))break;if(header.startsWith("new file mode ")){operation="add",newMode=header.slice(14),index++;continue}if(header.startsWith("deleted file mode ")){operation="delete",oldMode=header.slice(18),index++;continue}if(header.startsWith("rename from ")){operation="rename";let parsedPath=parseGitPathValue(header.slice(12));if(!parsedPath||parsedPath==="/dev/null")return null;declaredOldPath=parsedPath,index++;continue}if(header.startsWith("rename to ")){let parsedPath=parseGitPathValue(header.slice(10));if(!parsedPath||parsedPath==="/dev/null")return null;declaredNewPath=parsedPath,index++;continue}if(header.startsWith("copy from ")){operation="copy";let parsedPath=parseGitPathValue(header.slice(10));if(!parsedPath||parsedPath==="/dev/null")return null;declaredOldPath=parsedPath,index++;continue}if(header.startsWith("copy to ")){let parsedPath=parseGitPathValue(header.slice(8));if(!parsedPath||parsedPath==="/dev/null")return null;declaredNewPath=parsedPath,index++;continue}if(header.startsWith("old mode ")){operation="mode",oldMode=header.slice(9),index++;continue}if(header.startsWith("new mode ")){newMode=header.slice(9),index++;continue}if(header.startsWith("similarity index ")||header.startsWith("dissimilarity index ")){index++;continue}if(header==="GIT binary patch"||header.startsWith("Binary files "))return null;if(header.startsWith("index ")){let objectMatch=/^index ([a-f0-9]{7,64})\.\.([a-f0-9]{7,64})(?: [0-7]{6})?$/.exec(header);if(!objectMatch)return null;oldObjectId=objectMatch[1],newObjectId=objectMatch[2],index++;continue}let parsedOldHeader=parseGitHeaderPath(header,"--- ",operation==="add"?void 0:"a/"),parsedNewHeader=parseGitHeaderPath(String(lines[index+1]??""),"+++ ",operation==="delete"?void 0:"b/"),expectedOld=operation==="add"?"/dev/null":declaredOldPath,expectedNew=operation==="delete"?"/dev/null":declaredNewPath;if(parsedOldHeader!==expectedOld)return null;if(parsedNewHeader!==expectedNew)return null;index+=2;break}let hunks=[];while(index<lines.length){let hunkHeader=lines[index];if(!hunkHeader){index++;continue}if(parseDiffGitLine(hunkHeader))break;let hunkMatch=/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/.exec(hunkHeader);if(!hunkMatch)return null;index++;let hunkLines=[];while(index<lines.length){let hunkLine=lines[index];if(hunkLine===""){index++;continue}if(hunkLine.startsWith("@@ -")||parseDiffGitLine(hunkLine))break;if(hunkLine.startsWith(" ")||hunkLine.startsWith("+")||hunkLine.startsWith("-")||hunkLine==="\"){hunkLines.push(hunkLine),index++;continue}return null}if(hunks.push({oldStart:Number.parseInt(hunkMatch[1],10),oldCount:parseCount(hunkMatch[2]),newStart:Number.parseInt(hunkMatch[3],10),newCount:parseCount(hunkMatch[4]),lines:hunkLines}),!validateParsedHunk(hunks[hunks.length-1]))return null}if(hunks.length===0&&operation!=="mode"&&operation!=="rename"&&operation!=="copy")return null;if(!validateHunkOrdering(hunks))return null;files.push({oldRelativePath:operation==="add"?null:declaredOldPath,relativePath:operation==="delete"?declaredOldPath:declaredNewPath,operation,oldMode,newMode,oldObjectId,newObjectId,hunks})}return files.length>0?{files}:null}function splitTextLines(text){let normalized=text.replace(/\r\n/g,`
|
|
@@ -7845,7 +7845,7 @@ ${footerLines.join(`
|
|
|
7845
7845
|
`),lines=normalized.split(`
|
|
7846
7846
|
`);if(trailingNewline)lines.pop();if(normalized.length===0)lines.length=0;return{lines,trailingNewline}}function applyFilePatch(baseContent,patch2){let split=splitTextLines(baseContent),source=split.lines,output=[],cursor=0,targetHasNoTrailingNewline=!1,previousMarker;for(let hunk of patch2.hunks){let targetIndex=hunk.oldCount===0?hunk.oldStart:hunk.oldStart-1,targetNewIndex=hunk.newCount===0?hunk.newStart:hunk.newStart-1;if(targetIndex<cursor)return null;while(cursor<targetIndex)output.push(source[cursor]),cursor++;if(output.length!==targetNewIndex)return null;for(let rawLine of hunk.lines){if(rawLine==="\"){if(previousMarker==="+"||previousMarker===" ")targetHasNoTrailingNewline=!0;continue}let marker=rawLine[0];previousMarker=marker;let value=rawLine.slice(1);if(marker===" "){if(source[cursor]!==value)return null;output.push(value),cursor++;continue}if(marker==="-"){if(source[cursor]!==value)return null;cursor++;continue}if(marker==="+"){output.push(value);continue}return null}}let patchTouchesOldEof=cursor===source.length;while(cursor<source.length)output.push(source[cursor]),cursor++;let trailingNewline=patchTouchesOldEof?!targetHasNoTrailingNewline:split.trailingNewline;return`${output.join(`
|
|
7847
7847
|
`)}${output.length>0&&trailingNewline?`
|
|
7848
|
-
`:""}`}function gitBlobObjectId(content,algorithm){let header=Buffer.from(`blob ${content.byteLength}\x00`,"utf8");return createHash117(algorithm).update(header).update(content).digest("hex")}function matchesDeclaredObjectId(actual,declared){return/^0+$/.test(declared)?!1:actual.startsWith(declared)}function decodeTextFile(relativePath2,buffer){if(buffer.includes(0))throw Error(`binary file rejected: ${relativePath2}`);return TEXT_DECODER.decode(buffer)}function parseBaseTreeEntry(output){let trimmed=output.split("\x00").find(Boolean)?.trim();if(!trimmed)return null;let match=/^(\d{6}) blob ([a-f0-9]{40,64})\t(.+)$/.exec(trimmed);if(!match)return null;return{mode:match[1],objectId:match[2],relativePath:normalizeRelativePath2(match[3])}}function fail3(code,reason){return{ok:!1,code,reason}}function snapshotPathIdentity(absolutePath2){if(!existsSync200(absolutePath2))return{exists:!1};let stat25=_internals316.lstatSync(absolutePath2),isSymbolicLink=typeof stat25.isSymbolicLink==="function"?stat25.isSymbolicLink():!1,isFile=typeof stat25.isFile==="function"?stat25.isFile():!1;return{exists:!0,isSymbolicLink,isFile,nlink:stat25.nlink,size:stat25.size,mtimeMs:stat25.mtimeMs,ctimeMs:stat25.ctimeMs,dev:stat25.dev,ino:stat25.ino,mode:stat25.mode}}function samePathIdentity(left,right){if(left.exists!==right.exists)return!1;if(!left.exists)return!0;return left.isSymbolicLink===right.isSymbolicLink&&left.isFile===right.isFile&&left.nlink===right.nlink&&left.size===right.size&&left.mtimeMs===right.mtimeMs&&left.ctimeMs===right.ctimeMs&&left.dev===right.dev&&left.ino===right.ino&&left.mode===right.mode}async function validateSourceCandidate(args2){if(assertProjectRoot(args2.directory),args2.config.source_allowlist.length===0)return fail3("ALLOWLIST_EMPTY","harness source allowlist is empty");if(!SHA_RE.test(args2.baseSha))return fail3("INVALID_BASE_SHA","baseSha must be a 40-64 hex digest");if(Buffer.byteLength(args2.patch,"utf8")>args2.config.max_patch_bytes)return fail3("PATCH_TOO_LARGE",`patch exceeds max_patch_bytes (${args2.config.max_patch_bytes})`);let base=await _internals316.runGitCommand(args2.directory,["rev-parse","HEAD"]);if(!base.ok)return fail3("GIT_FAILED",`git rev-parse failed: ${base.stderr||base.stdout}`);let currentBase=base.stdout.trim().toLowerCase();if(currentBase!==args2.baseSha.toLowerCase())return fail3("STALE_BASE",`source candidate base ${args2.baseSha} does not match current HEAD ${currentBase}`);let parsed=parsePatch(args2.patch);if(!parsed)return fail3("UNSUPPORTED_PATCH","patch grammar is not an admitted two-way unified diff");if(parsed.files.length>args2.config.max_files)return fail3("FILE_COUNT_EXCEEDED",`patch touches ${parsed.files.length} files, exceeding max_files ${args2.config.max_files}`);let approvedPaths=[],files=[],admittedPathSnapshots=new Map,totalBytes=0,totalChangedLines=0;for(let filePatch of parsed.files){let relativePath2=normalizeRelativePath2(filePatch.relativePath),oldRelativePath=filePatch.oldRelativePath?normalizeRelativePath2(filePatch.oldRelativePath):null;for(let admittedPath of[...new Set([relativePath2,oldRelativePath].filter(Boolean))]){let rejection=validateTargetWithinRoot(admittedPath,args2.directory);if(rejection)return fail3("PATH_REJECTED",`${admittedPath}: ${rejection}`);if(!isAllowlisted(admittedPath,args2.config.source_allowlist))return fail3("PATH_NOT_ALLOWLISTED",`${admittedPath} is outside the harness source allowlist`);if(isProtectedPath4(admittedPath,args2.config.extra_protected_paths))return fail3("PROTECTED_PATH",`${admittedPath} is protected from harness source candidates`)}let sourcePath=oldRelativePath??relativePath2;for(let admittedPath of[...new Set([relativePath2,oldRelativePath].filter(Boolean))]){let absolutePath2=path378.resolve(args2.directory,admittedPath),identity=snapshotPathIdentity(absolutePath2);if(admittedPathSnapshots.set(admittedPath,identity),!identity.exists)continue;if(identity.isSymbolicLink)return fail3("SYMLINK_PATH",`${admittedPath} is a symlink or junction`);if(identity.isFile&&(identity.nlink??0)>1)return fail3("HARDLINK_PATH",`${admittedPath} is a hardlinked file and is not trusted for harness source candidates`)}let tracked=await _internals316.runGitCommand(args2.directory,["ls-tree","-z",args2.baseSha,"--",sourcePath]);if(!tracked.ok)return fail3("GIT_FAILED",`git ls-tree failed for ${sourcePath}`);let trackedEntry=parseBaseTreeEntry(tracked.stdout);if(!trackedEntry&&filePatch.operation!=="add")return fail3("UNTRACKED_PATH",`${sourcePath} is not tracked`);if(trackedEntry&&filePatch.operation==="add")return fail3("UNTRACKED_PATH",`${relativePath2} already exists in the tracked base`);if(filePatch.oldObjectId){if(filePatch.operation==="add"){if(!/^0+$/.test(filePatch.oldObjectId))return fail3("UNSUPPORTED_PATCH",`${relativePath2} add has a non-zero old object id`)}else if(!trackedEntry||!matchesDeclaredObjectId(trackedEntry.objectId,filePatch.oldObjectId))return fail3("STALE_BASE",`${sourcePath} object id does not match the declared patch base`)}if(filePatch.operation!=="add"&&(!trackedEntry||trackedEntry.relativePath!==sourcePath))return fail3("UNTRACKED_PATH",`${sourcePath} is not an admitted tracked file`);if(relativePath2!==sourcePath){let targetTracked=await _internals316.runGitCommand(args2.directory,["ls-tree","-z",args2.baseSha,"--",relativePath2]);if(!targetTracked.ok)return fail3("GIT_FAILED",`git ls-tree failed for ${relativePath2}`);if(parseBaseTreeEntry(targetTracked.stdout))return fail3("UNTRACKED_PATH",`${relativePath2} already exists in the tracked base`)}let trackedMode=trackedEntry?.mode??filePatch.newMode??"100644";if(!["100644","100755"].includes(trackedMode))return fail3("UNSUPPORTED_TRACKED_MODE",`${relativePath2} uses unsupported tracked mode ${trackedMode}`);let beforeBuffer=Buffer.alloc(0);if(trackedEntry){let baseBlob=await _internals316.runGitBinaryCommand(args2.directory,["show","--no-textconv",`${args2.baseSha}:${sourcePath}`],args2.config.max_file_bytes+1);if(!baseBlob.ok)return fail3("GIT_FAILED",`git show failed for ${sourcePath}: ${baseBlob.stderr}`);beforeBuffer=baseBlob.stdout}let beforeText;try{beforeText=decodeTextFile(relativePath2,beforeBuffer)}catch(error93){return fail3("BINARY_FILE",error93 instanceof Error?error93.message:String(error93))}let patchedText=filePatch.hunks.length===0?beforeText:applyFilePatch(beforeText,filePatch);if(patchedText===null)return fail3("PATCH_DOES_NOT_APPLY",`${relativePath2} did not apply cleanly`);let afterText=filePatch.operation==="delete"?"":patchedText;if(filePatch.newObjectId)if(filePatch.operation==="delete"){if(!/^0+$/.test(filePatch.newObjectId))return fail3("UNSUPPORTED_PATCH",`${relativePath2} delete has a non-zero new object id`)}else{let objectAlgorithm=args2.baseSha.length===64?"sha256":"sha1",actualObjectId=gitBlobObjectId(Buffer.from(afterText,"utf8"),objectAlgorithm);if(!matchesDeclaredObjectId(actualObjectId,filePatch.newObjectId))return fail3("PATCH_DOES_NOT_APPLY",`${relativePath2} object id does not match reconstructed output`)}if(filePatch.newMode&&!["100644","100755"].includes(filePatch.newMode))return fail3("UNSUPPORTED_TRACKED_MODE",`${relativePath2} requests unsupported mode ${filePatch.newMode}`);if(filePatch.oldMode&&trackedEntry&&filePatch.oldMode!==trackedMode)return fail3("UNSUPPORTED_TRACKED_MODE",`${sourcePath} mode does not match the tracked base`);if(afterText.includes("\x00"))return fail3("BINARY_FILE",`${relativePath2} patch produces binary output`);let bytesBefore=Buffer.byteLength(beforeText,"utf8"),bytesAfter=Buffer.byteLength(afterText,"utf8");if(Math.max(bytesBefore,bytesAfter)>args2.config.max_file_bytes)return fail3("FILE_TOO_LARGE",`${relativePath2} exceeds max_file_bytes ${args2.config.max_file_bytes}`);if(totalBytes+=bytesAfter,totalBytes>args2.config.max_total_bytes)return fail3("TOTAL_TOO_LARGE",`patched output exceeds max_total_bytes ${args2.config.max_total_bytes}`);let addedLines=0,removedLines=0;for(let line of filePatch.hunks.flatMap((hunk)=>hunk.lines)){if(line.startsWith("+")&&!line.startsWith("+++"))addedLines++;if(line.startsWith("-")&&!line.startsWith("---"))removedLines++}let changedLines=addedLines+removedLines;if(totalChangedLines+=changedLines,totalChangedLines>args2.config.max_changed_lines)return fail3("LINE_COUNT_EXCEEDED",`patch exceeds max_changed_lines ${args2.config.max_changed_lines}`);approvedPaths.push(relativePath2),files.push({relativePath:relativePath2,...oldRelativePath&&oldRelativePath!==relativePath2?{oldRelativePath}:{},operation:filePatch.operation,trackedMode,...filePatch.newMode?{afterMode:filePatch.newMode}:{},beforeSha256:sha2569(beforeText),afterSha256:sha2569(afterText),bytesBefore,bytesAfter,addedLines,removedLines,changedLines})}for(let[admittedPath,initialIdentity]of admittedPathSnapshots){let absolutePath2=path378.resolve(args2.directory,admittedPath),finalIdentity=snapshotPathIdentity(absolutePath2);if(!samePathIdentity(initialIdentity,finalIdentity))return fail3("PATH_CHANGED_DURING_VALIDATION",`${admittedPath} changed on disk while the harness source candidate was being validated`);if(finalIdentity.exists&&finalIdentity.isSymbolicLink)return fail3("SYMLINK_PATH",`${admittedPath} became a symlink or junction during validation`);if(finalIdentity.exists&&finalIdentity.isFile&&(finalIdentity.nlink??0)>1)return fail3("HARDLINK_PATH",`${admittedPath} became a hardlinked file during validation`)}let manifestBase={v:RECORD_VERSION2,candidateId:args2.candidateId,baseSha:args2.baseSha.toLowerCase(),origin:args2.origin,patchSha256:sha2569(args2.patch),promptArtifactHashes:[],approvedPaths:[...approvedPaths].sort(),files},riskTier=deriveHarnessCandidateRiskTier(manifestBase),manifestHash2=computeHarnessCandidateManifestHash(manifestBase);return{ok:!0,candidate:{...parseHarnessCandidateManifest({...manifestBase,riskTier,manifestHash:manifestHash2}),patch:args2.patch}}}async function runGitCommand(directory,args2){return new Promise((resolve151)=>{let stdout="",stderr="",stdoutBytes=0,stderrBytes=0,settled=!1,proc=spawn6(resolveGitExecutable(),args2,{cwd:directory,stdio:["ignore","pipe","pipe"],timeout:GIT_TIMEOUT_MS13}),finish=(result)=>{if(settled)return;settled=!0;try{proc.kill()}catch{}resolve151(result)};proc.stdout?.on("data",(chunk)=>{if(stdoutBytes>=MAX_GIT_OUTPUT_BYTES3)return;let slice=chunk.subarray(0,MAX_GIT_OUTPUT_BYTES3-stdoutBytes);stdout+=slice.toString("utf8"),stdoutBytes+=slice.byteLength}),proc.stderr?.on("data",(chunk)=>{if(stderrBytes>=MAX_GIT_OUTPUT_BYTES3)return;let slice=chunk.subarray(0,MAX_GIT_OUTPUT_BYTES3-stderrBytes);stderr+=slice.toString("utf8"),stderrBytes+=slice.byteLength}),proc.on("error",(error93)=>{finish({ok:!1,code:1,stdout,stderr:String(error93)})}),proc.on("close",(code)=>{finish({ok:code===0,code:code??1,stdout,stderr})})})}async function runGitBinaryCommand(directory,args2,maxOutputBytes=MAX_GIT_OUTPUT_BYTES3){return new Promise((resolve151)=>{let stdoutChunks=[],stdoutBytes=0,stderr="",stderrBytes=0,settled=!1,proc=spawn6(resolveGitExecutable(),args2,{cwd:directory,stdio:["ignore","pipe","pipe"],timeout:GIT_TIMEOUT_MS13}),finish=(result)=>{if(settled)return;settled=!0;try{proc.kill()}catch{}resolve151(result)};proc.stdout?.on("data",(chunk)=>{if(stdoutBytes>=maxOutputBytes)return;let slice=chunk.subarray(0,maxOutputBytes-stdoutBytes);if(stdoutChunks.push(slice),stdoutBytes+=slice.byteLength,slice.byteLength<chunk.byteLength||stdoutBytes>=maxOutputBytes)finish({ok:!1,code:1,stdout:Buffer.concat(stdoutChunks),stderr:`git output exceeds bound ${maxOutputBytes}`})}),proc.stderr?.on("data",(chunk)=>{if(stderrBytes>=MAX_GIT_OUTPUT_BYTES3)return;let slice=chunk.subarray(0,MAX_GIT_OUTPUT_BYTES3-stderrBytes);stderr+=slice.toString("utf8"),stderrBytes+=slice.byteLength}),proc.on("error",(error93)=>{finish({ok:!1,code:1,stdout:Buffer.concat(stdoutChunks),stderr:String(error93)})}),proc.on("close",(code)=>{finish({ok:code===0,code:code??1,stdout:Buffer.concat(stdoutChunks),stderr})})})}var _internals316={runGitCommand,runGitBinaryCommand,lstatSync:lstatSync44};init_store3();function projectStaticBlueprint2(agents){let runtimeDefinitions=Object.entries(agents).sort(([leftKey,left],[rightKey,right])=>left.name.localeCompare(right.name)||leftKey.localeCompare(rightKey)).map(([,agent])=>{let config3=agent.config,tools=config3.tools?Object.fromEntries(Object.entries(config3.tools).sort(([a],[b])=>a.localeCompare(b))):config3.tools;return{name:agent.name,description:agent.description,config:{...config3,tools,mode:config3.mode==="primary"?"primary":"subagent",temperature:config3.temperature??0.1,prompt:config3.prompt??`Static runtime definition for ${agent.name}`}}}),registeredToolIds=[...new Set(runtimeDefinitions.flatMap((definition)=>Object.keys(definition.config.tools??{})))].sort();return createAgentFactory({runtimeDefinitions,registeredToolIds}).projectBlueprint({blueprintId:"static-runtime-shadow"})}function diffHarnessBlueprints(left,right){let changes={};for(let key2 of[...new Set([...Object.keys(left),...Object.keys(right)])].sort())if(canonicalJson6(left[key2])!==canonicalJson6(right[key2]))changes[key2]={before:left[key2],after:right[key2]};return{changes,summary:{changeCount:Object.keys(changes).length,changedKeys:Object.keys(changes).sort()}}}var harnessMutationV1=Object.freeze(Object.assign(function(){return harnessMutationV1},{validateBlueprint:parseHarnessBlueprint,projectStaticBlueprint:projectStaticBlueprint2,applyPatchSet:applyBlueprintPatch,validateSourceCandidate,saveCandidate:recordHarnessCandidate,saveVersion:saveHarnessVersion,activate:activateHarnessCandidate,rollback:rollbackHarnessVersion,current:loadHarnessCurrent,history:listHarnessHistory,diff:diffHarnessBlueprints,auditLedger:auditHarnessLedger,recoverCorruptTail:recoverHarnessCorruptTail}));markStartupImportComplete();var _heartbeatTimers=new Map,MAX_TRACKED_HEARTBEAT_SESSIONS=500,_architectCompactionPending=new Map,MAX_TRACKED_ARCHITECT_COMPACTIONS=500,SESSION_DELETION_RECEIPT_RECONCILIATION_EVENT_DEADLINE_MS=250;function capSessionMap(map3,max,justInserted){while(map3.size>max){let oldest=map3.keys().next().value;if(oldest===void 0||oldest===justInserted)break;map3.delete(oldest)}}function resolveSoundingBoardCallerCategory(args2){if(!args2||typeof args2!=="object"||Array.isArray(args2))return{supplied:!1};let record3=args2;if(Object.hasOwn(record3,"category"))return{supplied:!0,value:record3.category};return{supplied:!1}}function applySoundingBoardResponsePolicy(rawResponse,args2){let callerCategory=resolveSoundingBoardCallerCategory(args2),parsed=parseSoundingBoardResponse(rawResponse,callerCategory.supplied?{category:callerCategory.value}:void 0);if(!parsed)return null;let guarded=applyAlwaysSurfacePolicy(parsed);if(guarded.protocolError&&guarded.verdict==="UNNECESSARY")return{...guarded,verdict:"APPROVED",warning:guarded.warning??"Invalid or missing Category metadata; verdict was surfaced as APPROVED."};return guarded}var instanceExitCleanups=new Map,instanceExitCleanupCounter=0,processExitCleanupRegistered=!1,processSignalCleanupHandlers=[],signalExitCleanupInFlight=!1;function runInstanceExitCleanups(){for(let cleanup of instanceExitCleanups.values())try{cleanup()}catch{}}function makeSignalExitCleanupHandler(signal2){let handler=()=>{if(signalExitCleanupInFlight)return;signalExitCleanupInFlight=!0;try{runInstanceExitCleanups()}catch{}finally{process.off(signal2,handler),process.kill(process.pid,signal2)}};return handler}function registerProcessExitCleanupDispatcher(){if(processExitCleanupRegistered)return;processExitCleanupRegistered=!0,process.on("exit",runInstanceExitCleanups),processSignalCleanupHandlers=[{signal:"SIGINT",handler:makeSignalExitCleanupHandler("SIGINT")},{signal:"SIGTERM",handler:makeSignalExitCleanupHandler("SIGTERM")}];for(let{signal:signal2,handler}of processSignalCleanupHandlers)process.on(signal2,handler)}var _delegationTelemetryByCallID=new Map,MAX_TRACKED_DELEGATION_TELEMETRY=500;function _resetDelegationTelemetryPairingForTesting(){_delegationTelemetryByCallID.clear(),pendingCostCorrectionByChildSession.clear(),scheduledCostCorrectionRecoveryBySession.clear(),latestAssistantUsageBySession.clear()}var SWARM_COMMAND_SYSTEM_RULE_TAG="[opencode-swarm:swarm-command-rule]",PACKAGE_ROOT2=path380.resolve(path380.dirname(fileURLToPath8(import.meta.url)),".."),SYNC_BUNDLED_SKILLS_TIMEOUT_MS=2000,BACKGROUND_MAINTENANCE_INIT_TIMEOUT_MS=1e4,TRAJECTORY_CLEANUP_INIT_TIMEOUT_MS=1e4,RETENTION_SWEEP_INIT_TIMEOUT_MS=5000,LOAD_PLUGIN_CONFIG_TIMEOUT_MS=2000;function createSwarmCommandSystemRuleHook(agentDefinitions,registeredAgents,options={}){let surface=options.surface??"system";return async(input,output)=>{let{sessionID,agent,expectedGeneration}=input,activeAgentName=sessionID?surface==="messages"?agent??swarmState.activeAgent.get(sessionID)??swarmState.agentSessions.get(sessionID)?.agentName:swarmState.activeAgent.get(sessionID)??agent??swarmState.agentSessions.get(sessionID)?.agentName:agent;if(surface==="system"&&isSessionBoundArchitect(sessionID,activeAgentName))return;if(!agentHasSwarmCommandTool(activeAgentName,agentDefinitions,registeredAgents))return;let system=Array.isArray(output.system)?output.system:[];if(system.some((entry)=>entry.includes(SWARM_COMMAND_SYSTEM_RULE_TAG)))return;let banner=[SWARM_COMMAND_SYSTEM_RULE_TAG,"When a user asks for a supported /swarm command and the message instructs you to call the `swarm_command` tool, call that tool exactly once with the provided JSON arguments. After the tool returns, show the tool output verbatim and do not add extra swarm state, summaries, or invented command output."].join(`
|
|
7848
|
+
`:""}`}function gitBlobObjectId(content,algorithm){let header=Buffer.from(`blob ${content.byteLength}\x00`,"utf8");return createHash117(algorithm).update(header).update(content).digest("hex")}function matchesDeclaredObjectId(actual,declared){return/^0+$/.test(declared)?!1:actual.startsWith(declared)}function decodeTextFile(relativePath2,buffer){if(buffer.includes(0))throw Error(`binary file rejected: ${relativePath2}`);return TEXT_DECODER.decode(buffer)}function parseBaseTreeEntry(output){let trimmed=output.split("\x00").find(Boolean)?.trim();if(!trimmed)return null;let match=/^(\d{6}) blob ([a-f0-9]{40,64})\t(.+)$/.exec(trimmed);if(!match)return null;return{mode:match[1],objectId:match[2],relativePath:normalizeRelativePath2(match[3])}}function fail3(code,reason){return{ok:!1,code,reason}}function snapshotPathIdentity(absolutePath2){if(!existsSync200(absolutePath2))return{exists:!1};let stat25=_internals316.lstatSync(absolutePath2),isSymbolicLink=typeof stat25.isSymbolicLink==="function"?stat25.isSymbolicLink():!1,isFile=typeof stat25.isFile==="function"?stat25.isFile():!1;return{exists:!0,isSymbolicLink,isFile,nlink:stat25.nlink,size:stat25.size,mtimeMs:stat25.mtimeMs,ctimeMs:stat25.ctimeMs,dev:stat25.dev,ino:stat25.ino,mode:stat25.mode}}function samePathIdentity(left,right){if(left.exists!==right.exists)return!1;if(!left.exists)return!0;return left.isSymbolicLink===right.isSymbolicLink&&left.isFile===right.isFile&&left.nlink===right.nlink&&left.size===right.size&&left.mtimeMs===right.mtimeMs&&left.ctimeMs===right.ctimeMs&&left.dev===right.dev&&left.ino===right.ino&&left.mode===right.mode}async function validateSourceCandidate(args2){if(assertProjectRoot(args2.directory),args2.config.source_allowlist.length===0)return fail3("ALLOWLIST_EMPTY","harness source allowlist is empty");if(!SHA_RE.test(args2.baseSha))return fail3("INVALID_BASE_SHA","baseSha must be a 40-64 hex digest");if(Buffer.byteLength(args2.patch,"utf8")>args2.config.max_patch_bytes)return fail3("PATCH_TOO_LARGE",`patch exceeds max_patch_bytes (${args2.config.max_patch_bytes})`);let base=await _internals316.runGitCommand(args2.directory,["rev-parse","HEAD"]);if(!base.ok)return fail3("GIT_FAILED",`git rev-parse failed: ${base.stderr||base.stdout}`);let currentBase=base.stdout.trim().toLowerCase();if(currentBase!==args2.baseSha.toLowerCase())return fail3("STALE_BASE",`source candidate base ${args2.baseSha} does not match current HEAD ${currentBase}`);let parsed=parsePatch(args2.patch);if(!parsed)return fail3("UNSUPPORTED_PATCH","patch grammar is not an admitted two-way unified diff");if(parsed.files.length>args2.config.max_files)return fail3("FILE_COUNT_EXCEEDED",`patch touches ${parsed.files.length} files, exceeding max_files ${args2.config.max_files}`);let approvedPaths=[],files=[],admittedPathSnapshots=new Map,totalBytes=0,totalChangedLines=0;for(let filePatch of parsed.files){let relativePath2=normalizeRelativePath2(filePatch.relativePath),oldRelativePath=filePatch.oldRelativePath?normalizeRelativePath2(filePatch.oldRelativePath):null;for(let admittedPath of[...new Set([relativePath2,oldRelativePath].filter(Boolean))]){let rejection=validateTargetWithinRoot(admittedPath,args2.directory);if(rejection)return fail3("PATH_REJECTED",`${admittedPath}: ${rejection}`);if(!isAllowlisted(admittedPath,args2.config.source_allowlist))return fail3("PATH_NOT_ALLOWLISTED",`${admittedPath} is outside the harness source allowlist`);if(isProtectedPath4(admittedPath,args2.config.extra_protected_paths))return fail3("PROTECTED_PATH",`${admittedPath} is protected from harness source candidates`)}let sourcePath=oldRelativePath??relativePath2;for(let admittedPath of[...new Set([relativePath2,oldRelativePath].filter(Boolean))]){let absolutePath2=path378.resolve(args2.directory,admittedPath),identity=snapshotPathIdentity(absolutePath2);if(admittedPathSnapshots.set(admittedPath,identity),!identity.exists)continue;if(identity.isSymbolicLink)return fail3("SYMLINK_PATH",`${admittedPath} is a symlink or junction`);if(identity.isFile&&(identity.nlink??0)>1)return fail3("HARDLINK_PATH",`${admittedPath} is a hardlinked file and is not trusted for harness source candidates`)}let tracked=await _internals316.runGitCommand(args2.directory,["ls-tree","-z",args2.baseSha,"--",sourcePath]);if(!tracked.ok)return fail3("GIT_FAILED",`git ls-tree failed for ${sourcePath}`);let trackedEntry=parseBaseTreeEntry(tracked.stdout);if(!trackedEntry&&filePatch.operation!=="add")return fail3("UNTRACKED_PATH",`${sourcePath} is not tracked`);if(trackedEntry&&filePatch.operation==="add")return fail3("UNTRACKED_PATH",`${relativePath2} already exists in the tracked base`);if(filePatch.oldObjectId){if(filePatch.operation==="add"){if(!/^0+$/.test(filePatch.oldObjectId))return fail3("UNSUPPORTED_PATCH",`${relativePath2} add has a non-zero old object id`)}else if(!trackedEntry||!matchesDeclaredObjectId(trackedEntry.objectId,filePatch.oldObjectId))return fail3("STALE_BASE",`${sourcePath} object id does not match the declared patch base`)}if(filePatch.operation!=="add"&&(!trackedEntry||trackedEntry.relativePath!==sourcePath))return fail3("UNTRACKED_PATH",`${sourcePath} is not an admitted tracked file`);if(relativePath2!==sourcePath){let targetTracked=await _internals316.runGitCommand(args2.directory,["ls-tree","-z",args2.baseSha,"--",relativePath2]);if(!targetTracked.ok)return fail3("GIT_FAILED",`git ls-tree failed for ${relativePath2}`);if(parseBaseTreeEntry(targetTracked.stdout))return fail3("UNTRACKED_PATH",`${relativePath2} already exists in the tracked base`)}let trackedMode=trackedEntry?.mode??filePatch.newMode??"100644";if(!["100644","100755"].includes(trackedMode))return fail3("UNSUPPORTED_TRACKED_MODE",`${relativePath2} uses unsupported tracked mode ${trackedMode}`);let beforeBuffer=Buffer.alloc(0);if(trackedEntry){let baseBlob=await _internals316.runGitBinaryCommand(args2.directory,["show","--no-textconv",`${args2.baseSha}:${sourcePath}`],args2.config.max_file_bytes+1);if(!baseBlob.ok)return fail3("GIT_FAILED",`git show failed for ${sourcePath}: ${baseBlob.stderr}`);beforeBuffer=baseBlob.stdout}let beforeText;try{beforeText=decodeTextFile(relativePath2,beforeBuffer)}catch(error93){return fail3("BINARY_FILE",error93 instanceof Error?error93.message:String(error93))}let patchedText=filePatch.hunks.length===0?beforeText:applyFilePatch(beforeText,filePatch);if(patchedText===null)return fail3("PATCH_DOES_NOT_APPLY",`${relativePath2} did not apply cleanly`);let afterText=filePatch.operation==="delete"?"":patchedText;if(filePatch.newObjectId)if(filePatch.operation==="delete"){if(!/^0+$/.test(filePatch.newObjectId))return fail3("UNSUPPORTED_PATCH",`${relativePath2} delete has a non-zero new object id`)}else{let objectAlgorithm=args2.baseSha.length===64?"sha256":"sha1",actualObjectId=gitBlobObjectId(Buffer.from(afterText,"utf8"),objectAlgorithm);if(!matchesDeclaredObjectId(actualObjectId,filePatch.newObjectId))return fail3("PATCH_DOES_NOT_APPLY",`${relativePath2} object id does not match reconstructed output`)}if(filePatch.newMode&&!["100644","100755"].includes(filePatch.newMode))return fail3("UNSUPPORTED_TRACKED_MODE",`${relativePath2} requests unsupported mode ${filePatch.newMode}`);if(filePatch.oldMode&&trackedEntry&&filePatch.oldMode!==trackedMode)return fail3("UNSUPPORTED_TRACKED_MODE",`${sourcePath} mode does not match the tracked base`);if(afterText.includes("\x00"))return fail3("BINARY_FILE",`${relativePath2} patch produces binary output`);let bytesBefore=Buffer.byteLength(beforeText,"utf8"),bytesAfter=Buffer.byteLength(afterText,"utf8");if(Math.max(bytesBefore,bytesAfter)>args2.config.max_file_bytes)return fail3("FILE_TOO_LARGE",`${relativePath2} exceeds max_file_bytes ${args2.config.max_file_bytes}`);if(totalBytes+=bytesAfter,totalBytes>args2.config.max_total_bytes)return fail3("TOTAL_TOO_LARGE",`patched output exceeds max_total_bytes ${args2.config.max_total_bytes}`);let addedLines=0,removedLines=0;for(let line of filePatch.hunks.flatMap((hunk)=>hunk.lines)){if(line.startsWith("+")&&!line.startsWith("+++"))addedLines++;if(line.startsWith("-")&&!line.startsWith("---"))removedLines++}let changedLines=addedLines+removedLines;if(totalChangedLines+=changedLines,totalChangedLines>args2.config.max_changed_lines)return fail3("LINE_COUNT_EXCEEDED",`patch exceeds max_changed_lines ${args2.config.max_changed_lines}`);approvedPaths.push(relativePath2),files.push({relativePath:relativePath2,...oldRelativePath&&oldRelativePath!==relativePath2?{oldRelativePath}:{},operation:filePatch.operation,trackedMode,...filePatch.newMode?{afterMode:filePatch.newMode}:{},beforeSha256:sha2569(beforeText),afterSha256:sha2569(afterText),bytesBefore,bytesAfter,addedLines,removedLines,changedLines})}for(let[admittedPath,initialIdentity]of admittedPathSnapshots){let absolutePath2=path378.resolve(args2.directory,admittedPath),finalIdentity=snapshotPathIdentity(absolutePath2);if(!samePathIdentity(initialIdentity,finalIdentity))return fail3("PATH_CHANGED_DURING_VALIDATION",`${admittedPath} changed on disk while the harness source candidate was being validated`);if(finalIdentity.exists&&finalIdentity.isSymbolicLink)return fail3("SYMLINK_PATH",`${admittedPath} became a symlink or junction during validation`);if(finalIdentity.exists&&finalIdentity.isFile&&(finalIdentity.nlink??0)>1)return fail3("HARDLINK_PATH",`${admittedPath} became a hardlinked file during validation`)}let manifestBase={v:RECORD_VERSION2,candidateId:args2.candidateId,baseSha:args2.baseSha.toLowerCase(),origin:args2.origin,patchSha256:sha2569(args2.patch),promptArtifactHashes:[],approvedPaths:[...approvedPaths].sort(),files},riskTier=deriveHarnessCandidateRiskTier(manifestBase),manifestHash2=computeHarnessCandidateManifestHash(manifestBase);return{ok:!0,candidate:{...parseHarnessCandidateManifest({...manifestBase,riskTier,manifestHash:manifestHash2}),patch:args2.patch}}}async function runGitCommand(directory,args2){return new Promise((resolve152)=>{let stdout="",stderr="",stdoutBytes=0,stderrBytes=0,settled=!1,proc=spawn6(resolveGitExecutable(),args2,{cwd:directory,stdio:["ignore","pipe","pipe"],timeout:GIT_TIMEOUT_MS13}),finish=(result)=>{if(settled)return;settled=!0;try{proc.kill()}catch{}resolve152(result)};proc.stdout?.on("data",(chunk)=>{if(stdoutBytes>=MAX_GIT_OUTPUT_BYTES3)return;let slice=chunk.subarray(0,MAX_GIT_OUTPUT_BYTES3-stdoutBytes);stdout+=slice.toString("utf8"),stdoutBytes+=slice.byteLength}),proc.stderr?.on("data",(chunk)=>{if(stderrBytes>=MAX_GIT_OUTPUT_BYTES3)return;let slice=chunk.subarray(0,MAX_GIT_OUTPUT_BYTES3-stderrBytes);stderr+=slice.toString("utf8"),stderrBytes+=slice.byteLength}),proc.on("error",(error93)=>{finish({ok:!1,code:1,stdout,stderr:String(error93)})}),proc.on("close",(code)=>{finish({ok:code===0,code:code??1,stdout,stderr})})})}async function runGitBinaryCommand(directory,args2,maxOutputBytes=MAX_GIT_OUTPUT_BYTES3){return new Promise((resolve152)=>{let stdoutChunks=[],stdoutBytes=0,stderr="",stderrBytes=0,settled=!1,proc=spawn6(resolveGitExecutable(),args2,{cwd:directory,stdio:["ignore","pipe","pipe"],timeout:GIT_TIMEOUT_MS13}),finish=(result)=>{if(settled)return;settled=!0;try{proc.kill()}catch{}resolve152(result)};proc.stdout?.on("data",(chunk)=>{if(stdoutBytes>=maxOutputBytes)return;let slice=chunk.subarray(0,maxOutputBytes-stdoutBytes);if(stdoutChunks.push(slice),stdoutBytes+=slice.byteLength,slice.byteLength<chunk.byteLength||stdoutBytes>=maxOutputBytes)finish({ok:!1,code:1,stdout:Buffer.concat(stdoutChunks),stderr:`git output exceeds bound ${maxOutputBytes}`})}),proc.stderr?.on("data",(chunk)=>{if(stderrBytes>=MAX_GIT_OUTPUT_BYTES3)return;let slice=chunk.subarray(0,MAX_GIT_OUTPUT_BYTES3-stderrBytes);stderr+=slice.toString("utf8"),stderrBytes+=slice.byteLength}),proc.on("error",(error93)=>{finish({ok:!1,code:1,stdout:Buffer.concat(stdoutChunks),stderr:String(error93)})}),proc.on("close",(code)=>{finish({ok:code===0,code:code??1,stdout:Buffer.concat(stdoutChunks),stderr})})})}var _internals316={runGitCommand,runGitBinaryCommand,lstatSync:lstatSync44};init_store3();function projectStaticBlueprint2(agents){let runtimeDefinitions=Object.entries(agents).sort(([leftKey,left],[rightKey,right])=>left.name.localeCompare(right.name)||leftKey.localeCompare(rightKey)).map(([,agent])=>{let config3=agent.config,tools=config3.tools?Object.fromEntries(Object.entries(config3.tools).sort(([a],[b])=>a.localeCompare(b))):config3.tools;return{name:agent.name,description:agent.description,config:{...config3,tools,mode:config3.mode==="primary"?"primary":"subagent",temperature:config3.temperature??0.1,prompt:config3.prompt??`Static runtime definition for ${agent.name}`}}}),registeredToolIds=[...new Set(runtimeDefinitions.flatMap((definition)=>Object.keys(definition.config.tools??{})))].sort();return createAgentFactory({runtimeDefinitions,registeredToolIds}).projectBlueprint({blueprintId:"static-runtime-shadow"})}function diffHarnessBlueprints(left,right){let changes={};for(let key2 of[...new Set([...Object.keys(left),...Object.keys(right)])].sort())if(canonicalJson6(left[key2])!==canonicalJson6(right[key2]))changes[key2]={before:left[key2],after:right[key2]};return{changes,summary:{changeCount:Object.keys(changes).length,changedKeys:Object.keys(changes).sort()}}}var harnessMutationV1=Object.freeze(Object.assign(function(){return harnessMutationV1},{validateBlueprint:parseHarnessBlueprint,projectStaticBlueprint:projectStaticBlueprint2,applyPatchSet:applyBlueprintPatch,validateSourceCandidate,saveCandidate:recordHarnessCandidate,saveVersion:saveHarnessVersion,activate:activateHarnessCandidate,rollback:rollbackHarnessVersion,current:loadHarnessCurrent,history:listHarnessHistory,diff:diffHarnessBlueprints,auditLedger:auditHarnessLedger,recoverCorruptTail:recoverHarnessCorruptTail}));markStartupImportComplete();var _heartbeatTimers=new Map,MAX_TRACKED_HEARTBEAT_SESSIONS=500,_architectCompactionPending=new Map,MAX_TRACKED_ARCHITECT_COMPACTIONS=500,SESSION_DELETION_RECEIPT_RECONCILIATION_EVENT_DEADLINE_MS=250;function capSessionMap(map3,max,justInserted){while(map3.size>max){let oldest=map3.keys().next().value;if(oldest===void 0||oldest===justInserted)break;map3.delete(oldest)}}function resolveSoundingBoardCallerCategory(args2){if(!args2||typeof args2!=="object"||Array.isArray(args2))return{supplied:!1};let record3=args2;if(Object.hasOwn(record3,"category"))return{supplied:!0,value:record3.category};return{supplied:!1}}function applySoundingBoardResponsePolicy(rawResponse,args2){let callerCategory=resolveSoundingBoardCallerCategory(args2),parsed=parseSoundingBoardResponse(rawResponse,callerCategory.supplied?{category:callerCategory.value}:void 0);if(!parsed)return null;let guarded=applyAlwaysSurfacePolicy(parsed);if(guarded.protocolError&&guarded.verdict==="UNNECESSARY")return{...guarded,verdict:"APPROVED",warning:guarded.warning??"Invalid or missing Category metadata; verdict was surfaced as APPROVED."};return guarded}var instanceExitCleanups=new Map,instanceExitCleanupCounter=0,processExitCleanupRegistered=!1,processSignalCleanupHandlers=[],signalExitCleanupInFlight=!1;function runInstanceExitCleanups(){for(let cleanup of instanceExitCleanups.values())try{cleanup()}catch{}}function makeSignalExitCleanupHandler(signal2){let handler=()=>{if(signalExitCleanupInFlight)return;signalExitCleanupInFlight=!0;try{runInstanceExitCleanups()}catch{}finally{process.off(signal2,handler),process.kill(process.pid,signal2)}};return handler}function registerProcessExitCleanupDispatcher(){if(processExitCleanupRegistered)return;processExitCleanupRegistered=!0,process.on("exit",runInstanceExitCleanups),processSignalCleanupHandlers=[{signal:"SIGINT",handler:makeSignalExitCleanupHandler("SIGINT")},{signal:"SIGTERM",handler:makeSignalExitCleanupHandler("SIGTERM")}];for(let{signal:signal2,handler}of processSignalCleanupHandlers)process.on(signal2,handler)}var _delegationTelemetryByCallID=new Map,MAX_TRACKED_DELEGATION_TELEMETRY=500;function _resetDelegationTelemetryPairingForTesting(){_delegationTelemetryByCallID.clear(),pendingCostCorrectionByChildSession.clear(),scheduledCostCorrectionRecoveryBySession.clear(),latestAssistantUsageBySession.clear()}var SWARM_COMMAND_SYSTEM_RULE_TAG="[opencode-swarm:swarm-command-rule]",PACKAGE_ROOT2=path380.resolve(path380.dirname(fileURLToPath8(import.meta.url)),".."),SYNC_BUNDLED_SKILLS_TIMEOUT_MS=2000,BACKGROUND_MAINTENANCE_INIT_TIMEOUT_MS=1e4,TRAJECTORY_CLEANUP_INIT_TIMEOUT_MS=1e4,RETENTION_SWEEP_INIT_TIMEOUT_MS=5000,LOAD_PLUGIN_CONFIG_TIMEOUT_MS=2000;function createSwarmCommandSystemRuleHook(agentDefinitions,registeredAgents,options={}){let surface=options.surface??"system";return async(input,output)=>{let{sessionID,agent,expectedGeneration}=input,activeAgentName=sessionID?surface==="messages"?agent??swarmState.activeAgent.get(sessionID)??swarmState.agentSessions.get(sessionID)?.agentName:swarmState.activeAgent.get(sessionID)??agent??swarmState.agentSessions.get(sessionID)?.agentName:agent;if(surface==="system"&&isSessionBoundArchitect(sessionID,activeAgentName))return;if(!agentHasSwarmCommandTool(activeAgentName,agentDefinitions,registeredAgents))return;let system=Array.isArray(output.system)?output.system:[];if(system.some((entry)=>entry.includes(SWARM_COMMAND_SYSTEM_RULE_TAG)))return;let banner=[SWARM_COMMAND_SYSTEM_RULE_TAG,"When a user asks for a supported /swarm command and the message instructs you to call the `swarm_command` tool, call that tool exactly once with the provided JSON arguments. After the tool returns, show the tool output verbatim and do not add extra swarm state, summaries, or invented command output."].join(`
|
|
7849
7849
|
`);if(system.push(banner),sessionID)if(surface==="messages"&&output.deliveryBudgetReceipts){let receipt=recordProducerEmissionWithReceipt(sessionID,"swarm-command-banner",estimateTokens(banner),surface,{expectedGeneration});if(receipt)output.deliveryBudgetReceipts.push(receipt)}else recordProducerEmission(sessionID,"swarm-command-banner",estimateTokens(banner),0,surface,{expectedGeneration})}}function schedulePostResolutionTasks(tasks){if(tasks.length===0)return;noteQueueScheduled();let timer=setTimeout(()=>{for(let task2 of tasks){let wrapped=wrapPostResolutionTask(task2);try{Promise.resolve(wrapped()).catch((err2)=>{log("post-resolution startup task failed (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})})}catch(err2){log("post-resolution startup task failed (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})}}},0);if(typeof timer.unref==="function")timer.unref()}var createRepoGraphBuilderHookForInit=createRepoGraphBuilderHook,schedulePostResolutionTasksForInit=schedulePostResolutionTasks,loadPluginConfigWithMetaAsyncForInit=loadPluginConfigWithMetaAsync,loadSnapshotForInit=loadSnapshot,ensureSwarmGitExcludedForInit=ensureSwarmGitExcluded,resolveAutoReviewConfigForInit=resolveAutoReviewConfig,regenerateMemoryReflectionForInit=async(directory,config3)=>{let{regenerateMemoryReflection:regenerateMemoryReflection2}=await Promise.resolve().then(() => (init_reflection_service(),exports_reflection_service));return regenerateMemoryReflection2(directory,config3)};function overrideIndexInternalsForTest(overrides2){let previousCreateRepoGraphBuilderHook=createRepoGraphBuilderHookForInit,previousSchedulePostResolutionTasks=schedulePostResolutionTasksForInit,previousLoadPluginConfigWithMetaAsync=loadPluginConfigWithMetaAsyncForInit,previousLoadSnapshot=loadSnapshotForInit,previousEnsureSwarmGitExcluded=ensureSwarmGitExcludedForInit,previousResolveAutoReviewConfig=resolveAutoReviewConfigForInit,previousRegenerateMemoryReflection=regenerateMemoryReflectionForInit;if(overrides2.createRepoGraphBuilderHook)createRepoGraphBuilderHookForInit=overrides2.createRepoGraphBuilderHook;if(overrides2.schedulePostResolutionTasks)schedulePostResolutionTasksForInit=overrides2.schedulePostResolutionTasks;if(overrides2.loadPluginConfigWithMetaAsync)loadPluginConfigWithMetaAsyncForInit=overrides2.loadPluginConfigWithMetaAsync;if(overrides2.loadSnapshot)loadSnapshotForInit=overrides2.loadSnapshot;if(overrides2.ensureSwarmGitExcluded)ensureSwarmGitExcludedForInit=overrides2.ensureSwarmGitExcluded;if(overrides2.resolveAutoReviewConfig)resolveAutoReviewConfigForInit=overrides2.resolveAutoReviewConfig;if(overrides2.regenerateMemoryReflection)regenerateMemoryReflectionForInit=overrides2.regenerateMemoryReflection;return()=>{createRepoGraphBuilderHookForInit=previousCreateRepoGraphBuilderHook,schedulePostResolutionTasksForInit=previousSchedulePostResolutionTasks,loadPluginConfigWithMetaAsyncForInit=previousLoadPluginConfigWithMetaAsync,loadSnapshotForInit=previousLoadSnapshot,ensureSwarmGitExcludedForInit=previousEnsureSwarmGitExcluded,resolveAutoReviewConfigForInit=previousResolveAutoReviewConfig,regenerateMemoryReflectionForInit=previousRegenerateMemoryReflection}}function schedulePostResolutionTasksForTest(tasks){schedulePostResolutionTasks(tasks)}async function recoverPendingCostCorrectionForTest(directory,parentSessionId,childSessionId,pricing){return recoverPendingCostCorrection(directory,parentSessionId,childSessionId,pricing)}function computeEffectiveTruncatableTools(defaultTools,configuredTools){let effective=configuredTools&&configuredTools.length>0?new Set(configuredTools):new Set(defaultTools);for(let exempt of SUMMARIZER_EXEMPT_TOOL_NAMES)effective.delete(exempt);return effective}var OpenCodeSwarm=async(ctx)=>{beginStartupServerInterval();let postResolutionTasks=[];try{let hooks2=await initializeOpenCodeSwarm(ctx,postResolutionTasks);return schedulePostResolutionTasksForInit(postResolutionTasks),endStartupServerInterval(),hooks2}catch(err2){let stack=err2 instanceof Error?err2.stack??err2.message:String(err2);throw console.error("[opencode-swarm] FATAL: plugin initialization failed. Plugin will not be available."),console.error(stack),err2}},MAX_TRACKED_ASSISTANT_USAGE_EVENTS=200,latestAssistantUsageBySession=new Map,pendingCostCorrectionByChildSession=new Map,scheduledCostCorrectionRecoveryBySession=new Set;function trackPendingCostCorrection(childSessionId,pending){pendingCostCorrectionByChildSession.delete(childSessionId),pendingCostCorrectionByChildSession.set(childSessionId,pending);while(pendingCostCorrectionByChildSession.size>MAX_TRACKED_ASSISTANT_USAGE_EVENTS){let oldest=pendingCostCorrectionByChildSession.keys().next().value;if(oldest===void 0)break;pendingCostCorrectionByChildSession.delete(oldest)}}function emitPendingCostCorrection(sessionId,raw){let pending=pendingCostCorrectionByChildSession.get(sessionId);if(!pending)return!1;let fields=buildDelegationCostFields({raw,model:pending.model,gate:pending.gate,retry_index:pending.retryIndex,pricing:pending.pricing});if(fields.evidence_status!=="complete")return!0;if(!isCostUpgrade(pending.currentFields.cost_evidence??[],fields.cost_evidence??[]))return!0;let nextVersion=pending.version+1;return emit("delegation_cost_correction",{sessionId:pending.parentSessionId,agentName:pending.agentName,taskId:pending.taskId,record_id:pending.recordId,identity_fingerprint:pending.identityFingerprint,parent_session_digest:pending.parentSessionDigest,version:nextVersion,...fields}),pending.version=nextVersion,pending.currentFields=fields,!0}async function recoverPendingCostCorrection(directory,parentSessionId,childSessionId,pricing){let events=await readTelemetryEventsAsync(directory),folded=foldTelemetryEvents(events),parentSessionDigest=createHash118("sha256").update(`delegation-cost-parent-v1\x00${parentSessionId}`).digest("hex").slice(0,32),childSessionDigest=createHash118("sha256").update(`delegation-cost-child-v1\x00${childSessionId}`).digest("hex").slice(0,32),candidates=folded.events.filter((event2)=>event2.event==="delegation_end"&&event2.parent_session_digest===parentSessionDigest&&event2.cost_source!=="reported"&&typeof event2.record_id==="string"&&typeof event2.identity_fingerprint==="string"),exactCandidates=candidates.filter((event2)=>event2.child_session_digest===childSessionDigest),selectedCandidates=exactCandidates.length>0?exactCandidates:candidates;if(selectedCandidates.length===0)return null;if(selectedCandidates.length!==1)return;let event=selectedCandidates[0],effective=event;if(effective.cost_source==="reported")return null;let currentFields={tokens_input:typeof effective.tokens_input==="number"?effective.tokens_input:null,tokens_output:typeof effective.tokens_output==="number"?effective.tokens_output:null,tokens_reasoning:typeof effective.tokens_reasoning==="number"?effective.tokens_reasoning:null,tokens_cache:typeof effective.tokens_cache==="number"?effective.tokens_cache:null,cost_usd:typeof effective.cost_usd==="number"?effective.cost_usd:null,cost_source:effective.cost_source==="reported"||effective.cost_source==="estimated"?effective.cost_source:"unavailable",cost_evidence:Array.isArray(effective.cost_evidence)?effective.cost_evidence:void 0};return{recordId:event.record_id,identityFingerprint:event.identity_fingerprint,parentSessionId,parentSessionDigest,agentName:typeof event.agentName==="string"?event.agentName:"unknown",taskId:typeof event.taskId==="string"?event.taskId:"",model:typeof event.model==="string"?event.model:"unknown",gate:typeof event.gate==="string"?event.gate:void 0,retryIndex:typeof event.retry_index==="number"?event.retry_index:void 0,pricing,version:folded.versions[event.record_id]??1,currentFields}}function rememberAssistantUsageEvent(input){let event=isPlainRecord3(input)?input.event:void 0;if(!isPlainRecord3(event))return;if(event.type==="message.updated"){let properties=isPlainRecord3(event.properties)?event.properties:void 0,info=isPlainRecord3(properties?.info)?properties.info:void 0;if(info?.role==="assistant")return rememberAssistantUsage(info.sessionID,info),typeof info.sessionID==="string"?{sessionId:info.sessionID,raw:info}:void 0;return}if(event.type==="message.part.updated"){let properties=isPlainRecord3(event.properties)?event.properties:void 0,part=isPlainRecord3(properties?.part)?properties.part:void 0;if(part?.type==="step-finish")return rememberAssistantUsage(part.sessionID,part),typeof part.sessionID==="string"?{sessionId:part.sessionID,raw:part}:void 0}return}function rememberAssistantUsage(sessionID,raw){if(typeof sessionID!=="string"||sessionID.trim()==="")return;latestAssistantUsageBySession.set(sessionID,raw);while(latestAssistantUsageBySession.size>MAX_TRACKED_ASSISTANT_USAGE_EVENTS){let oldest=latestAssistantUsageBySession.keys().next().value;if(oldest===void 0)break;latestAssistantUsageBySession.delete(oldest)}}function consumeAssistantUsageForTask(_parentSessionID,taskOutput){let sessionIDs=collectSessionIDs(taskOutput);for(let sessionID of sessionIDs){let usage=latestAssistantUsageBySession.get(sessionID);if(usage!==void 0)return latestAssistantUsageBySession.delete(sessionID),usage}return}function collectSessionIDs(raw){let found=[],seen=new Set,visit=(value,depth)=>{if(depth>3||!isPlainRecord3(value)||seen.has(value))return;seen.add(value);for(let key2 of["sessionID","sessionId","session_id"]){let candidate2=value[key2];if(typeof candidate2==="string"&&candidate2.trim()!=="")found.push(candidate2)}for(let key2 of["metadata","data","info","message","response","output"])visit(value[key2],depth+1)};return visit(raw,0),[...new Set(found)]}function isPlainRecord3(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function writeBootstrapRootRedirectRecord(bootstrapRoot,openedDirectory){try{let advisoriesDir=path380.join(bootstrapRoot,".swarm","advisories");mkdirSync101(advisoriesDir,{recursive:!0}),writeFileSync66(path380.join(advisoriesDir,"bootstrap-root-redirect.json"),JSON.stringify({kind:"bootstrap-root-redirect",opened_directory:openedDirectory,project_root:bootstrapRoot,note:"Runtime state, project config, and telemetry for the opened workspace are owned by the project root."}))}catch{}}async function initializeOpenCodeSwarm(ctx,postResolutionTasks){console.warn(`[opencode-swarm] running v${package_default.version}`),clearDeferredWarnings(),resetConfigAdvisoryDedup(),resetArchitectPromptBudgetAdvisories();let rootDecision=resolveProjectRootDecision(ctx.directory),bootstrapRoot=rootDecision.kind==="redirect"?rootDecision.owningRoot:ctx.directory,bootstrapStateWritesEnabled=rootDecision.kind!=="fail-closed",__initIoStart=performance2.now(),configLoadP=withTimeout(loadPluginConfigWithMetaAsyncForInit(bootstrapRoot),LOAD_PLUGIN_CONFIG_TIMEOUT_MS,Error(`loadPluginConfigWithMetaAsync exceeded ${LOAD_PLUGIN_CONFIG_TIMEOUT_MS}ms budget; continuing with safe-default config`)).catch((err2)=>{let msg=err2 instanceof Error?err2.message:String(err2);return log("loadPluginConfig timed out or failed (non-fatal)",{error:msg}),advisoryWarn(`[opencode-swarm] Config load exceeded ${LOAD_PLUGIN_CONFIG_TIMEOUT_MS}ms budget; running with default configuration for this session.`),getSafeDefaultConfigLoadResult()}),snapshotP=bootstrapStateWritesEnabled&&hasSwarmState(bootstrapRoot)?withTimeout(loadSnapshotForInit(bootstrapRoot),5000,Error("loadSnapshot exceeded 5s budget; continuing without snapshot rehydration")).catch((err2)=>{let msg=err2 instanceof Error?err2.message:String(err2);log("loadSnapshot timed out or failed (non-fatal)",{error:msg})}):Promise.resolve(),gitExcludeP=bootstrapStateWritesEnabled&&hasGitMarkerAncestor(bootstrapRoot)?withTimeout(ensureSwarmGitExcludedForInit(bootstrapRoot),ENSURE_SWARM_GIT_EXCLUDED_OUTER_TIMEOUT_MS,Error(`ensureSwarmGitExcluded exceeded ${ENSURE_SWARM_GIT_EXCLUDED_OUTER_TIMEOUT_MS}ms budget; continuing without git-hygiene check`)).catch((err2)=>{let msg=err2 instanceof Error?err2.message:String(err2);log("ensureSwarmGitExcluded timed out or failed (non-fatal)",{error:msg})}):Promise.resolve(),projectContextP=hasManifestAncestor(ctx.directory)?(()=>{let timeoutError2=Error("language-backend detection exceeded 300ms; continuing with unresolved sentinels");return withTimeoutSignal(async(signal2)=>{return(await Promise.resolve().then(() => (init_project_context(),exports_project_context))).buildProjectContext(ctx.directory,signal2)},300,timeoutError2).catch((err2)=>{let msg=err2 instanceof Error?err2.message:String(err2);return log("language-backend detection timed out or failed (non-fatal)",{error:msg}),null})})():Promise.resolve(null);await Promise.all([configLoadP,snapshotP,gitExcludeP,projectContextP]);let{config:config3,loadedFromFile}=await configLoadP;if(rootDecision.kind==="redirect"){let redirectHint=`[opencode-swarm] project-root ownership: "${ctx.directory}" is an ordinary subdirectory — runtime state, project config, and telemetry for this workspace are owned by the project root "${bootstrapRoot}". Open the project root (or add a .git/.opencode marker in "${ctx.directory}") to make this directory independent.`;console.warn(redirectHint),addDeferredWarning(redirectHint),advisoryWarn(redirectHint),writeBootstrapRootRedirectRecord(bootstrapRoot,ctx.directory)}else if(rootDecision.kind==="fail-closed"){let failClosedHint=`[opencode-swarm] project-root ownership: cannot verify "${ctx.directory}" (${rootDecision.reason}) — runtime state is disabled for this session. Reopen the project from its verified root.`;console.warn(failClosedHint),addDeferredWarning(failClosedHint),advisoryWarn(failClosedHint)}if(log(`init-path I/O completed in ${(performance2.now()-__initIoStart).toFixed(1)}ms (parallel: config+snapshot+git-exclude)`),setGitBinaryOverride(config3.git?.binary),config3.full_auto?.enabled===!0){let criticModel=config3.full_auto.critic_model??config3.agents?.critic?.model??DEFAULT_MODELS.critic,architectModel=config3.agents?.architect?.model??DEFAULT_MODELS.default;if(criticModel===architectModel)if(!config3.quiet)console.warn("[opencode-swarm] Full-auto mode warning: critic model matches architect model. Model validation is advisory-only; full-auto remains enabled. (Runtime architect model is determined by the orchestrator)");else addDeferredWarning("[opencode-swarm] Full-auto mode warning: critic model matches architect model. Model validation is advisory-only; full-auto remains enabled. (Runtime architect model is determined by the orchestrator)")}{let noFallback=[],hasNoFallback=(cfg)=>cfg.model&&(!cfg.fallback_models||cfg.fallback_models.length===0);if(config3.agents){for(let[name,cfg]of Object.entries(config3.agents))if(hasNoFallback(cfg))noFallback.push(`${name}(${cfg.model})`)}if(config3.swarms){for(let[swarmId,swarm]of Object.entries(config3.swarms))if(swarm.agents){for(let[name,cfg]of Object.entries(swarm.agents))if(hasNoFallback(cfg))noFallback.push(`${swarmId}/${name}(${cfg.model})`)}}if(noFallback.length>0){let msg=`[opencode-swarm] WARNING: ${noFallback.length} agent(s) use a custom model without fallback_models: `+noFallback.join(", ")+'. Add "fallback_models": ["model-a"] to each agent config for reliability.';if(!config3.quiet)console.warn(msg);else addDeferredWarning(msg)}}if(swarmState.fullAutoEnabledInConfig=config3.full_auto?.enabled===!0,swarmState.opencodeClient=ctx.client,initObservability({directory:bootstrapRoot,provenance:{pluginVersion:package_default.version,runtime:process.versions.bun===void 0?"node":"bun",runtimeVersion:process.versions.bun??process.versions.node,os:process.platform,arch:process.arch}}),bootstrapStateWritesEnabled)registerObservabilityEventSink(bootstrapRoot),initTelemetry(bootstrapRoot);startHeartbeatTracking();let otlpExportConfig=config3.observability?.export;if(otlpExportConfig!==void 0&&bootstrapStateWritesEnabled){if(registerOtlpExporter(bootstrapRoot,otlpExportConfig),isOtlpExporterActive())postResolutionTasks.push(()=>{flushOtlpExporterForTesting(bootstrapRoot).catch(()=>{})})}let repoGraphConfig=RepoGraphConfigSchema.parse(config3.repo_graph??{}),repoGraphHookFactory=createRepoGraphBuilderHookForInit,repoGraphHook=repoGraphConfig.enabled&&bootstrapStateWritesEnabled?repoGraphHookFactory(bootstrapRoot,void 0,{enabled:!0,initRefresh:repoGraphConfig.init_refresh,refreshCap:repoGraphConfig.refresh_cap,walkBudgetMs:repoGraphConfig.walk_budget_ms,maxFiles:repoGraphConfig.max_files,excludeDirs:repoGraphConfig.exclude_dirs}):null,repoGraphInitPromise;if(repoGraphHook)postResolutionTasks.push(()=>{let watchdog=setTimeout(()=>{log("[repo-graph] init exceeded 30s budget; scan will continue but is overdue")},30000);if(typeof watchdog.unref==="function")watchdog.unref();repoGraphInitPromise=repoGraphHook.init().catch(()=>{}).finally(()=>clearTimeout(watchdog))});if(postResolutionTasks.push(function(){if(!bootstrapStateWritesEnabled)return Promise.resolve();return startSnapshotCoordinationInitialization(bootstrapRoot)}),postResolutionTasks.push(()=>{runModelPreflight(config3,swarmState.opencodeClient,{generatedAgentNames:swarmState.generatedAgentNames}).then((result)=>{let msg=formatModelPreflightWarning(result);if(!msg)return;if(!config3.quiet)console.warn(msg);else addDeferredWarning(msg);for(let resolution of result.resolutions)if(resolution.status==="unresolved"||resolution.status==="missing-selection")telemetry.modelUnresolved(resolution.agent,resolution.model||"(no final selection)",resolution.detail??"does not resolve")}).catch(()=>{})}),postResolutionTasks.push(()=>{if(bootstrapStateWritesEnabled)runInitOrphanRecovery(bootstrapRoot).catch((err2)=>{let msg=err2 instanceof Error?err2.message:String(err2);log("initOrphanRecovery failed (non-fatal)",{error:msg})})}),postResolutionTasks.push(function(){return withTimeout(bootstrapStateWritesEnabled?cleanupOldTrajectoryFiles(bootstrapRoot):Promise.resolve(),TRAJECTORY_CLEANUP_INIT_TIMEOUT_MS,Error(`trajectory cleanup exceeded ${TRAJECTORY_CLEANUP_INIT_TIMEOUT_MS}ms post-init budget; continuing without it (lazy per-session cleanup remains a backstop)`)).catch((err2)=>{let msg=err2 instanceof Error?err2.message:String(err2);log("post-init trajectory cleanup timed out or failed (non-fatal)",{error:msg})}).then(()=>{return})}),postResolutionTasks.push(function(){if(!bootstrapStateWritesEnabled)return Promise.resolve();let retentionConfig=config3?.retention,retentionDaysValue=config3?.summaries?.retention_days,sweepCancelled=!1;return withTimeout(runRetentionSweep(bootstrapRoot,{enabled:retentionConfig?.enabled!==!1,dryRun:retentionConfig?.dry_run===!0,summariesRetentionDays:typeof retentionDaysValue==="number"&&retentionDaysValue>=1?retentionDaysValue:void 0,shouldContinue:()=>!sweepCancelled}),RETENTION_SWEEP_INIT_TIMEOUT_MS,Error(`retention sweep exceeded ${RETENTION_SWEEP_INIT_TIMEOUT_MS}ms post-init budget; continuing without it (close-time sweeps remain a backstop)`)).catch((err2)=>{sweepCancelled=!0;let msg=err2 instanceof Error?err2.message:String(err2);log("post-init retention sweep timed out or failed (non-fatal)",{error:msg})}).then(()=>{return})}),config3.hooks?.background_subagents===!0)postResolutionTasks.push(function(){if(!bootstrapStateWritesEnabled)return Promise.resolve();return withTimeout(Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations)).then((m)=>m.maintainBackgroundDelegations(bootstrapRoot,{lockTimeoutMs:5000,reason:"post-init",onLegacyCoderSettlementReconciled:backgroundCompletionObserver.reconcilePending,onLegacyCoderSettlementAdvisoryReplaced:backgroundCompletionObserver.notifyLegacyCoderSettlementAdvisoryReplaced})),BACKGROUND_MAINTENANCE_INIT_TIMEOUT_MS,Error(`background maintenance exceeded ${BACKGROUND_MAINTENANCE_INIT_TIMEOUT_MS}ms post-init budget; continuing without it (other maintenance points remain)`)).catch((err2)=>{let msg=err2 instanceof Error?err2.message:String(err2);log("post-init background maintenance timed out or failed (non-fatal)",{error:msg})}).then(()=>{return})});if(bootstrapStateWritesEnabled)writeSwarmConfigExampleIfNew(bootstrapRoot);if(postResolutionTasks.push(()=>{if(!bootstrapStateWritesEnabled)return;withTimeout(syncBundledProjectSkillsIfMissingAsync(bootstrapRoot,PACKAGE_ROOT2,config3.quiet),SYNC_BUNDLED_SKILLS_TIMEOUT_MS,Error(`syncBundledProjectSkillsIfMissingAsync exceeded ${SYNC_BUNDLED_SKILLS_TIMEOUT_MS}ms budget; continuing without skill materialization (command-path sync remains a backstop)`)).catch((err2)=>{let msg=err2 instanceof Error?err2.message:String(err2);log("bundled skill materialization timed out or failed (non-fatal)",{error:msg})})}),config3.version_check!==!1)postResolutionTasks.push(()=>{scheduleVersionCheck(package_default.version,(msg)=>{if(config3.quiet)addDeferredWarning(msg);else console.warn(msg)})});let projectContext=await projectContextP,autoReviewConfig;try{autoReviewConfig=resolveAutoReviewConfigForInit(config3.auto_review??{},{preset:config3.preset})}catch(error93){addDeferredWarning(`[swarm] Invalid auto_review configuration; auto-review is disabled until corrected: ${error93 instanceof Error?error93.message:String(error93)}`),autoReviewConfig=resolveAutoReviewConfigForInit({enabled:!1})}let configWithResolvedAutoReview={...config3,auto_review:autoReviewConfig},agents=getAgentConfigs(configWithResolvedAutoReview,bootstrapRoot,void 0,projectContext??void 0),largestArchitectChars=Object.entries(agents).reduce((max,[name,cfg])=>{if(!name.endsWith("_architect")&&name!=="architect")return max;let len=cfg.prompt?.length??0;return len>max?len:max},0);log("architect prompt size",{chars:largestArchitectChars});let agentDefinitions=createAgents(configWithResolvedAutoReview,projectContext??void 0),agentDefinitionMap=Object.fromEntries(agentDefinitions.map((agent)=>[agent.name,agent])),instanceGeneratedAgentNames=Object.freeze(Object.keys(agents));swarmState.curatorInitAgentNames=Object.keys(agents).filter((k)=>k==="curator_init"||k.endsWith("_curator_init")),swarmState.curatorPhaseAgentNames=Object.keys(agents).filter((k)=>k==="curator_phase"||k.endsWith("_curator_phase")),swarmState.curatorPostmortemAgentNames=Object.keys(agents).filter((k)=>k==="curator_postmortem"||k.endsWith("_curator_postmortem")),swarmState.curatorConsolidationAgentNames=Object.keys(agents).filter((k)=>k==="curator_consolidation"||k.endsWith("_curator_consolidation")),swarmState.skillImproverAgentNames=Object.keys(agents).filter((k)=>k==="skill_improver"||k.endsWith("_skill_improver")),swarmState.specWriterAgentNames=Object.keys(agents).filter((k)=>k==="spec_writer"||k.endsWith("_spec_writer")),swarmState.generatedAgentNames=[...instanceGeneratedAgentNames];let pipelineHook=createPipelineTrackerHook(config3,bootstrapRoot),systemEnhancerHook=createSystemEnhancerHook(config3,bootstrapRoot),architectMessagesEnhancerHook=createSystemEnhancerHook(config3,bootstrapRoot,{surface:"messages",deferRealtimeLearningNudgeState:!0,reservedEnvelopeTokens:guidanceCarrierEnvelopeTokens("architect-session")}),contextCapsuleInjectHook=createContextCapsuleInjectHook(config3,bootstrapRoot),compactionHook=createCompactionCustomizerHook(config3,bootstrapRoot),resolveIncomingAgentModel=(agentName)=>resolveRuntimeAgentModel(config3,agents,agentName),resolveTaskRouteModelChain=(exactAgentName)=>{if(!exactAgentName)return null;let trimmedAgentName=exactAgentName.trim();if(!trimmedAgentName)return null;let role=stripKnownSwarmPrefix(trimmedAgentName),swarmAgents=getSwarmAgents(extractSwarmIdFromAgentName(trimmedAgentName));return{exactAgentName:trimmedAgentName,role,primaryModel:resolveRuntimeAgentModel(config3,agents,trimmedAgentName)??resolveRegisteredAgentModel(config3,trimmedAgentName),fallbackModels:swarmAgents?.[role]?.fallback_models??[]}},extractBoundedErrorSignal=(value,depth=0)=>{if(depth>4)return[];if(typeof value==="string"){let trimmed=value.trim();return trimmed?[trimmed.slice(0,512)]:[]}if(typeof value==="number"||typeof value==="boolean")return[String(value)];if(!value||typeof value!=="object")return[];if(value instanceof Error)return[...extractBoundedErrorSignal(value.name,depth+1),...extractBoundedErrorSignal(value.message,depth+1)];let record3=value,parts=[];for(let key2 of["message","reason","code","status","statusCode","error","cause","detail","details","data","name"])parts.push(...extractBoundedErrorSignal(record3[key2],depth+1));return parts},extractSessionErrorSignal=(properties)=>{if(!properties)return"";return extractBoundedErrorSignal(properties).filter(Boolean).join(" ").slice(0,2048)},resolveTaskRouteForChildSession=(childSessionID)=>{let trimmedChildSessionID=childSessionID.trim();if(!trimmedChildSessionID)return;return getPendingTaskModelRouteSnapshot().find((route)=>route.childSessionID===trimmedChildSessionID)},lookupParentSessionIDForTaskRoute=async(childSessionID)=>{let sessionApi=ctx.client?.session;if(!sessionApi?.get)return;try{let result=await sessionApi.get({path:{id:childSessionID},query:{directory:bootstrapRoot}});return typeof result?.data?.parentID==="string"&&result.data.parentID.trim()!==""?result.data.parentID.trim():void 0}catch{return}},schedulePendingCostCorrectionRecovery=(rememberedUsage)=>{if(scheduledCostCorrectionRecoveryBySession.has(rememberedUsage.sessionId))return;scheduledCostCorrectionRecoveryBySession.add(rememberedUsage.sessionId);while(scheduledCostCorrectionRecoveryBySession.size>MAX_TRACKED_ASSISTANT_USAGE_EVENTS){let oldest=scheduledCostCorrectionRecoveryBySession.values().next().value;if(oldest===void 0)break;scheduledCostCorrectionRecoveryBySession.delete(oldest)}(async()=>{let parentSessionId=await withTimeout(lookupParentSessionIDForTaskRoute(rememberedUsage.sessionId),1000,Error("late cost parent lookup exceeded 1000ms")).catch(()=>{return});if(!parentSessionId)return;let recovered=await recoverPendingCostCorrection(bootstrapRoot,parentSessionId,rememberedUsage.sessionId,config3.pricing),corrected=!1;if(recovered)trackPendingCostCorrection(rememberedUsage.sessionId,recovered),emit("delegation_cost_binding",{sessionId:parentSessionId,parent_session_digest:recovered.parentSessionDigest,record_id:recovered.recordId,identity_fingerprint:recovered.identityFingerprint,child_session_digest:createHash118("sha256").update(`delegation-cost-child-v1\x00${rememberedUsage.sessionId}`).digest("hex").slice(0,32)}),corrected=emitPendingCostCorrection(rememberedUsage.sessionId,rememberedUsage.raw);if(recovered===null)corrected=!0;if(!corrected)emit("delegation_cost_join",{sessionId:parentSessionId,reason:"join_miss"})})().catch(()=>{return}).finally(()=>{scheduledCostCorrectionRecoveryBySession.delete(rememberedUsage.sessionId)})};registerFullAutoRecoveryBlockerEvaluator(({sessionID})=>{let invocationID=getAgentSession(sessionID)?.activeInvocationId??0;if(invocationID<=0)return[];return[...new Set(listBlockingActionCircuitsForInvocation(sessionID,invocationID).map((entry)=>entry.circuitKind))]});let contextBudgetHandler=createContextBudgetHandler(config3,resolveIncomingAgentModel,bootstrapRoot),finalContextAccountingStep=createFinalContextAccountingStep({config:config3,directory:bootstrapRoot,resolveAgentModelFn:resolveIncomingAgentModel}),evaluationModelDispatcher=createEvaluationModelDispatcher(ctx.client,config3.pricing),reviewModelDispatcher=createReviewModelDispatcher(ctx.client,config3.pricing),findingValidationScheduler=createFindingValidationScheduler(),reviewAgentModelRegistry=captureReviewAgentModelRegistry(config3,instanceGeneratedAgentNames),getActiveReviewAgentName=(sessionID)=>swarmState.activeAgent.get(sessionID)??swarmState.agentSessions.get(sessionID)?.agentName,roleFilterSystemHook=createRoleFilterSystemHook(getActiveReviewAgentName),systemRenderBoundaryHook=createSystemRenderBoundaryHook(),commandHandler=createSwarmCommandHandler(bootstrapRoot,agentDefinitionMap,{getActiveAgentName:getActiveReviewAgentName,config:config3,packageRoot:PACKAGE_ROOT2,registeredAgents:agents,evaluationModelDispatcher,reviewModelDispatcher,autoReviewConfig,reviewAgentModelRegistry}),swarmCommandSystemRuleHook=createSwarmCommandSystemRuleHook(agentDefinitionMap,agents),architectMessagesCommandRuleHook=createSwarmCommandSystemRuleHook(agentDefinitionMap,agents,{surface:"messages"}),activityHooks=createAgentActivityHooks(config3,bootstrapRoot),learningConfig=LearningConfigSchema.parse(config3.learning??{}),prmConfig=config3.prm??PrmConfigSchema.parse({}),prmHook=createPrmHook(prmConfig,bootstrapRoot,resolvePrmPatternPersistenceOptions(learningConfig)),trajectoryLoggerHook=createTrajectoryLoggerHook({enabled:!0,max_lines:prmConfig.max_trajectory_lines},bootstrapRoot),delegationGateHooks=createDelegationGateHook(configWithResolvedAutoReview,bootstrapRoot,agents),advisoryInjector=(sessionId,message)=>{let session=swarmState.agentSessions.get(sessionId);if(session)pushAdvisory(session,message)},backgroundCompletionObserver=createBackgroundCompletionObserver({config:{enabled:config3.hooks?.background_subagents===!0},directory:bootstrapRoot,reviewerReceiptOptions:{dispatcher:reviewModelDispatcher,config:autoReviewConfig,generatedAgentNames:instanceGeneratedAgentNames,agentModelRegistry:reviewAgentModelRegistry,injectAdvisory:advisoryInjector,validationScheduler:findingValidationScheduler}}),backgroundSubagentsEnabled=config3.hooks?.background_subagents===!0,pendingDelegationsModulePromise=null,maintainBackgroundDelegationsOnSessionEvent=async()=>{let modulePromise=pendingDelegationsModulePromise;if(modulePromise===null)modulePromise=Promise.resolve().then(() => (init_pending_delegations(),exports_pending_delegations)).catch((err2)=>{throw pendingDelegationsModulePromise=null,err2}),pendingDelegationsModulePromise=modulePromise;await(await modulePromise).maintainBackgroundDelegations(bootstrapRoot,{lockTimeoutMs:2000,reason:"session-close",onLegacyCoderSettlementReconciled:backgroundCompletionObserver.reconcilePending,onLegacyCoderSettlementAdvisoryReplaced:backgroundCompletionObserver.notifyLegacyCoderSettlementAdvisoryReplaced})},delegationSanitizerHook=createDelegationSanitizerHook(bootstrapRoot),trainingCaptureObserver=createTrainingCaptureObserver(bootstrapRoot),memoryLifecycleHooks=createMemoryLifecycleHooks({directory:bootstrapRoot,config:config3.memory,getActiveAgentName:(sessionID)=>sessionID?swarmState.activeAgent.get(sessionID):void 0,getActiveTaskId:(sessionID)=>sessionID?swarmState.agentSessions.get(sessionID)?.currentTaskId??void 0:void 0});if(config3.memory?.enabled===!0&&config3.memory.reflection?.enabled===!0){let reflectionConfig=config3.memory,regenerateMemoryReflectionTask=()=>withTimeout(repoGraphInitPromise??Promise.resolve(),5000,Error("repo graph refresh exceeded reflection wait budget")).catch(()=>{return}).then(()=>withTimeout(bootstrapStateWritesEnabled?regenerateMemoryReflectionForInit(bootstrapRoot,reflectionConfig):Promise.resolve(),15000,Error("memory reflection startup regeneration exceeded 15s"))).catch((err2)=>{log("memory reflection startup regeneration failed (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})}).then(()=>{return});postResolutionTasks.push(regenerateMemoryReflectionTask)}let guardrailsFallback=config3.guardrails?.enabled===!1?{...config3.guardrails,enabled:!1}:config3.guardrails??{},guardrailsConfig=GuardrailsConfigSchema.parse(guardrailsFallback),dispatchProtectionConfig=DispatchProtectionConfigSchema.parse(config3.dispatch_protection??{});if(loadedFromFile&&guardrailsConfig.enabled===!1)warn(""),warn("══════════════════════════════════════════════════════════════"),warn("[opencode-swarm] \uD83D\uDD34 SECURITY WARNING: GUARDRAILS ARE DISABLED"),warn("══════════════════════════════════════════════════════════════"),warn("Guardrails have been explicitly disabled in user configuration."),warn("This disables safety measures including:"),warn(" - Tool call limits"),warn(" - Duration limits"),warn(" - Repetition detection"),warn(" - Error rate limits"),warn(" - Idle timeouts"),warn(""),warn("Only disable guardrails if you fully understand the security implications."),warn('To re-enable guardrails, set "guardrails.enabled" to true in your config.'),warn("══════════════════════════════════════════════════════════════"),warn("");let delegationHandler=createDelegationTrackerHook(config3,guardrailsConfig.enabled,bootstrapRoot),authorityConfig=AuthorityConfigSchema.parse(config3.authority??{}),worktreeDirOverride=resolveWorktreeIsolationConfig(config3).worktree_dir,guardrailsHooks=createGuardrailsHooks(bootstrapRoot,void 0,guardrailsConfig,authorityConfig,worktreeDirOverride?[worktreeDirOverride]:[],resolveIncomingAgentModel),durableBackgroundAdvisoryMessagesTransform=async(input,output)=>{let mctx=resolveMessageTransformContext(output);if(!mctx.sessionID){await guardrailsHooks.messagesTransform(input,output);return}let observedTexts=(output.messages??[]).flatMap((message)=>(message.parts??[]).filter((part)=>part.type==="text"&&typeof part.text==="string").map((part)=>part.text));await backgroundCompletionObserver.ackObservedAdvisories(mctx.sessionID,observedTexts);let prepared=await backgroundCompletionObserver.prepareAdvisories(mctx.sessionID);if(!prepared){await guardrailsHooks.messagesTransform(input,output);return}let session=swarmState.agentSessions.get(mctx.sessionID),pendingBefore=session?[...session.pendingAdvisoryMessages??[]]:void 0,guardrailsSnapshot=session?{resumeModelAdvisoryDone:session.resumeModelAdvisoryDone,configModelAdvisoryDone:session.configModelAdvisoryDone,lastObservedModel:session.lastObservedModel,lastObservedProviderID:session.lastObservedProviderID,lastProviderRecoveryFingerprint:session.lastProviderRecoveryFingerprint,loopWarningPending:session.loopWarningPending}:void 0,messagesBefore=output.messages?structuredClone(output.messages):void 0;try{if(session)for(let message of prepared.messages)pushAdvisory(session,message);if(await guardrailsHooks.messagesTransform(input,output),!prepared.messages.every((message)=>(output.messages??[]).some((candidate2)=>(candidate2.parts??[]).some((part)=>part.type==="text"&&typeof part.text==="string"&&part.text.includes(message)))))throw Error("durable background advisory insertion failed")}catch(error93){if(session&&pendingBefore)session.pendingAdvisoryMessages=pendingBefore;if(session&&guardrailsSnapshot)session.resumeModelAdvisoryDone=guardrailsSnapshot.resumeModelAdvisoryDone,session.configModelAdvisoryDone=guardrailsSnapshot.configModelAdvisoryDone,session.lastObservedModel=guardrailsSnapshot.lastObservedModel,session.lastObservedProviderID=guardrailsSnapshot.lastObservedProviderID,session.lastProviderRecoveryFingerprint=guardrailsSnapshot.lastProviderRecoveryFingerprint,session.loopWarningPending=guardrailsSnapshot.loopWarningPending;if(Array.isArray(output.messages)&&messagesBefore){output.messages.length=0;for(let message of messagesBefore)output.messages.push(message)}else output.messages=messagesBefore;await backgroundCompletionObserver.releaseAdvisories(mctx.sessionID,prepared),warn(`[background] advisory injection rolled back for ${mctx.sessionID}: ${error93 instanceof Error?error93.message:String(error93)}`)}},fullAutoInterceptHook=createFullAutoInterceptHook(config3,bootstrapRoot),fullAutoPermissionHook=createFullAutoPermissionHook({config:config3,directory:bootstrapRoot}),fullAutoInputProbeHook=createFullAutoInputProbeHook({config:config3,directory:bootstrapRoot}),fullAutoDelegationHook=createFullAutoDelegationHook({config:config3,directory:bootstrapRoot}),ccCommandInterceptHook=createCcCommandInterceptHook({}),issueTraceHook=createIssueTraceHook(config3,bootstrapRoot),watchdogConfig=WatchdogConfigSchema.parse(config3.watchdog??{}),scopeGuardHook=createScopeGuardHook({enabled:watchdogConfig.scope_guard},bootstrapRoot,advisoryInjector),prWorkflowResponseGate=createPrWorkflowResponseGate({directory:bootstrapRoot,client:ctx.client}),prWorkflowSessionResolver=createPrWorkflowSessionResolver({directory:bootstrapRoot,client:ctx.client}),delegationLedgerHook=createDelegationLedgerHook({enabled:watchdogConfig.delegation_ledger},bootstrapRoot,advisoryInjector),initOrphanRecoveryAdvisoryHook=createInitOrphanRecoveryAdvisoryHook(bootstrapRoot),selfReviewConfig=SelfReviewConfigSchema.parse(config3.self_review??{}),selfReviewHook=createSelfReviewHook({enabled:selfReviewConfig.enabled,skip_in_turbo:selfReviewConfig.skip_in_turbo},advisoryInjector),autoReviewHook=createAutoReviewHook({config:autoReviewConfig,directory:bootstrapRoot,dispatcher:reviewModelDispatcher,generatedAgentNames:instanceGeneratedAgentNames,agentModelRegistry:reviewAgentModelRegistry,getActiveAgentName:getActiveReviewAgentName,injectAdvisory:advisoryInjector}),summaryConfig=SummaryConfigSchema.parse(config3.summaries??{}),toolSummarizerHook=createToolSummarizerHook(summaryConfig,bootstrapRoot),knowledgeConfigBase=config3.knowledge??{},knowledgeConfig=KnowledgeConfigSchema.parse(knowledgeConfigBase),skillImproverConfig=SkillImproverConfigSchema.parse(config3.skill_improver??{}),skillPropagationConfig=SkillPropagationConfigSchema.parse(config3.skillPropagation??{});if(skillImproverConfig.enabled&&skillImproverConfig.trigger==="scheduled")postResolutionTasks.push(()=>{return Promise.resolve().then(() => (init_skill_consolidation(),exports_skill_consolidation)).then(({runSkillConsolidationFireAndForget:runSkillConsolidationFireAndForget2})=>{runSkillConsolidationFireAndForget2({directory:bootstrapRoot,config:skillImproverConfig,source:"startup",enrichmentQuota:{maxCalls:knowledgeConfig.enrichment.max_calls_per_day,window:knowledgeConfig.enrichment.quota_window},evaluateDrafts:!0},void 0,(err2)=>{let msg=err2 instanceof Error?err2.message:String(err2);log("scheduled skill consolidation failed (non-fatal)",{error:msg})})}).catch((err2)=>{let msg=err2 instanceof Error?err2.message:String(err2);log("failed to schedule skill consolidation (non-fatal)",{error:msg})})});let knowledgeCuratorHook=knowledgeConfig.enabled?createKnowledgeCuratorHook(bootstrapRoot,knowledgeConfig,{llmDelegateFactory:(sessionID)=>createCuratorLLMDelegate(bootstrapRoot,"phase",sessionID),enrichmentQuota:{maxCalls:knowledgeConfig.enrichment.max_calls_per_day,window:knowledgeConfig.enrichment.quota_window}}):void 0,hivePromoterHook=knowledgeConfig.enabled&&knowledgeConfig.hive_enabled?createHivePromoterHook(bootstrapRoot,knowledgeConfig):void 0,knowledgeInjectorHook=knowledgeConfig.enabled?createKnowledgeInjectorHook(bootstrapRoot,knowledgeConfig,config3.context_budget?.model_limits??{},config3.context_budget?.unified_injection_tokens):void 0,steeringConsumedHook=createSteeringConsumedHook(bootstrapRoot),coChangeSuggesterHook=createCoChangeSuggesterHook(bootstrapRoot),darkMatterDetectorHook=createDarkMatterDetectorHook(bootstrapRoot),slopDetectorHook=config3.slop_detector?.enabled!==!1?createSlopDetectorHook(config3.slop_detector??{enabled:!0,classThreshold:3,commentStripThreshold:5,diffLineThreshold:200,importHygieneThreshold:2},bootstrapRoot,(sessionId,message)=>{let s=swarmState.agentSessions.get(sessionId);if(s)pushAdvisory(s,message)}):null,incrementalVerifyHook=config3.incremental_verify?.enabled!==!1?createIncrementalVerifyHook(config3.incremental_verify??{enabled:!0,command:null,timeoutMs:30000,triggerAgents:["coder"]},bootstrapRoot,(sessionId,message)=>{let s=swarmState.agentSessions.get(sessionId);if(s)pushAdvisory(s,message)}):null,compactionServiceHook=config3.compaction_service?.enabled!==!1?createCompactionService(config3.compaction_service??{enabled:!0,observationThreshold:40,reflectionThreshold:60,emergencyThreshold:80,preserveLastNTurns:5},bootstrapRoot,(sessionId,message)=>{let s=swarmState.agentSessions.get(sessionId);if(s)pushAdvisory(s,message)}):null,snapshotWriterHook=bootstrapStateWritesEnabled?createSnapshotWriterHook(bootstrapRoot):async()=>{},automationConfig=AutomationConfigSchema.parse(config3.automation??{}),automationManager,preflightTriggerManager,prMonitorWorker=null,planSyncWorker=null;if(automationConfig.mode!=="manual"){if(automationManager=createAutomationManager(automationConfig),bootstrapStateWritesEnabled)automationManager.start();let{PreflightTriggerManager:PTM}=await Promise.resolve().then(() => (init_trigger(),exports_trigger));preflightTriggerManager=new PTM(automationConfig);let{getSharedAutomationStatusArtifact:getSharedAutomationStatusArtifact2}=await Promise.resolve().then(() => (init_status_artifact(),exports_status_artifact)),swarmDir=path380.resolve(bootstrapRoot,".swarm"),automationStatusArtifactPostInitTask=async()=>{try{getSharedAutomationStatusArtifact2(swarmDir).updateConfig(automationConfig.mode,automationConfig.capabilities)}catch(err2){log("automation status artifact init failed (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})}};if(bootstrapStateWritesEnabled)postResolutionTasks.push(automationStatusArtifactPostInitTask);if(automationConfig.capabilities?.evidence_auto_summaries===!0&&bootstrapStateWritesEnabled){let{createEvidenceSummaryIntegration:createEvidenceSummaryIntegration2}=await Promise.resolve().then(() => (init_evidence_summary_integration(),exports_evidence_summary_integration));createEvidenceSummaryIntegration2({automationConfig,directory:bootstrapRoot,projectDir:bootstrapRoot,summaryFilename:"evidence-summary.json"}),log("Evidence summary integration initialized",{directory:bootstrapRoot})}if(automationConfig.capabilities?.phase_preflight===!0&&bootstrapStateWritesEnabled){let{createPreflightIntegration:createPreflightIntegration2}=await Promise.resolve().then(() => (init_preflight_integration(),exports_preflight_integration));try{let{manager}=createPreflightIntegration2({automationConfig,directory:bootstrapRoot,swarmDir});preflightTriggerManager=manager,log("Preflight integration initialized",{directory:bootstrapRoot})}catch(err2){log("Preflight integration failed to initialize (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})}}if(automationConfig.capabilities?.plan_sync===!0&&bootstrapStateWritesEnabled)try{planSyncWorker=new PlanSyncWorker({directory:bootstrapRoot}),planSyncWorker.start(),log("PlanSyncWorker initialized",{directory:bootstrapRoot})}catch(err2){log("PlanSyncWorker failed to initialize (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})}log("Automation framework initialized",{mode:automationConfig.mode,enabled:automationManager?.isEnabled(),running:automationManager?.isActive(),preflightEnabled:preflightTriggerManager?.isEnabled()})}let prMonitorConfig=PrMonitorConfigSchema.parse(config3.pr_monitor??{});function ensurePrMonitorWorkerRunning(directory){try{if(!prMonitorConfig.enabled)return;if(!prMonitorWorker)prMonitorWorker=new PrMonitorWorker({directory,config:prMonitorConfig});if(!prMonitorWorker.isRunning())prMonitorWorker.start(),log("PR Monitor Worker started",{directory})}catch(err2){error48("[pr-monitor] Worker failed to start (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})}}ensurePrSubscriptionDispatcherInstalled(),registerPrMonitorWorkerHandler(bootstrapRoot,ensurePrMonitorWorkerRunning);let prEventCleanup=null,prFeedbackLoopRuntimeCleanup=null;if(isPrFeedbackLoopEnabled(config3))try{let registration=registerPrFeedbackLoopRuntime({client:ctx.client,directory:ctx.directory,config:config3,agentNames:instanceGeneratedAgentNames,resolveSessionAgent:(sessionID)=>swarmState.activeAgent.get(sessionID)??getAgentSession(sessionID)?.agentName});prFeedbackLoopRuntimeCleanup=registration,postResolutionTasks.push(()=>registration.promote())}catch(err2){log("[pr-feedback-loop] Runtime registration failed (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})}let prEventDelivery=null;if(prMonitorConfig.enabled){try{let{registerPrEventSubscribers:registerPrEventSubscribers2}=await Promise.resolve().then(() => (init_pr_event_subscribers(),exports_pr_event_subscribers));prEventCleanup=registerPrEventSubscribers2({directory:bootstrapRoot,config:prMonitorConfig})}catch(err2){log("[pr-monitor] Failed to register PR event subscribers (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})}if(prMonitorConfig.event_delivery==="prompt")try{let deliveryModule=await Promise.resolve().then(() => (init_pr_event_delivery(),exports_pr_event_delivery)),registration=deliveryModule.registerPrEventDelivery({client:ctx.client,directory:bootstrapRoot,config:prMonitorConfig});postResolutionTasks.push(()=>registration.promote()),prEventDelivery={noteSessionIdle:(sessionID,directory)=>deliveryModule.noteSessionIdle(sessionID,directory),unregister:registration}}catch(err2){log("[pr-monitor] Failed to register wake delivery (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})}}let prAutoSubscribeHook=createPrAutoSubscribeHook(bootstrapRoot,prMonitorConfig);if(prMonitorConfig.enabled)postResolutionTasks.push(()=>{listActive(bootstrapRoot).then((active)=>{if(active.length>0)ensurePrMonitorWorkerRunning(bootstrapRoot)}).catch((err2)=>{error48("[pr-monitor] Startup scan failed (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})})});let automationCleaned=!1,cleanupAutomation=()=>{if(automationCleaned)return;automationCleaned=!0,automationManager?.stop(),prMonitorWorker?.stop(),planSyncWorker?.stop(),dashboardDisposed=!0;try{closeDashboardServerForRootIfOwner(bootstrapRoot,dashboardHandleRef.current)}catch{}removePrMonitorWorkerHandler(bootstrapRoot,ensurePrMonitorWorkerRunning),prEventCleanup?.(),prEventDelivery?.unregister(),prFeedbackLoopRuntimeCleanup?.(),markSnapshotCoordinationClosing(bootstrapRoot);try{if(closeGroupCommitWriter(bootstrapRoot),getSnapshotCoordinationStatus(bootstrapRoot).settled)closeProjectDb(bootstrapRoot)}catch{}},instanceExitCleanupToken=`${bootstrapRoot}#${++instanceExitCleanupCounter}`;if(registerProcessExitCleanupDispatcher(),instanceExitCleanups.set(instanceExitCleanupToken,cleanupAutomation),shouldRunOnStartup(automationConfig)){let enableAutofix=automationConfig.capabilities?.config_doctor_autofix===!0;postResolutionTasks.push(()=>{return Promise.resolve().then(() => (init_config_doctor(),exports_config_doctor)).then(({runConfigDoctorWithFixes:runConfigDoctorWithFixes2})=>{return runConfigDoctorWithFixes2(bootstrapRoot,config3,enableAutofix).then((doctorResult)=>{if(doctorResult.result.findings.length>0){log("Config Doctor ran on startup",{findings:doctorResult.result.findings.length,errors:doctorResult.result.summary.error,warnings:doctorResult.result.summary.warn,appliedFixes:doctorResult.appliedFixes.length,autofixEnabled:enableAutofix});try{let autoFixableCount=doctorResult.result.findings.filter((f)=>f.autoFixable).length,appliedCount=doctorResult.appliedFixes.length;if(!enableAutofix&&autoFixableCount>0){let msg=`[opencode-swarm] Config Doctor found ${autoFixableCount} auto-fixable issue(s). Run /swarm config doctor --fix to apply.`;if(!config3.quiet)console.warn(msg);else addDeferredWarning(msg)}else if(enableAutofix){let parts=[];if(appliedCount>0)parts.push(`applied ${appliedCount} fix(es) automatically`);let unapplied=Math.max(0,autoFixableCount-appliedCount);if(unapplied>0)parts.push(`${unapplied} auto-fixable issue(s) need explicit review — run /swarm config doctor --fix`);if(parts.length>0){let msg=`[opencode-swarm] Config Doctor: ${parts.join("; ")}.`;if(!config3.quiet)console.warn(msg);else addDeferredWarning(msg)}}}catch{}}}).catch((err2)=>{log("Config Doctor error (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})})})})}let dashboardPort=config3.dashboard?.port??0,dashboardHandleRef={current:null},dashboardDisposed=!1;if(dashboardPort>0)postResolutionTasks.push(async function(){try{let{startDashboardServer:startDashboardServer2}=await Promise.resolve().then(() => (init_dashboard(),exports_dashboard)),handle=await startDashboardServer2({port:dashboardPort,host:"127.0.0.1",directory:bootstrapRoot});if(!handle.listening){advisoryWarn(`Swarm dashboard disabled: port ${dashboardPort} is unavailable (in use or bind failed). Free the port or change dashboard.port in opencode-swarm.json.`);return}if(dashboardDisposed){handle.close();return}dashboardHandleRef.current=handle,log("swarm dashboard listening (loopback, token-protected)",{port:handle.port})}catch(err2){log("dashboard startup failed (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})}});log("Plugin initialized",{maxIterations:config3.max_iterations,agentCount:Object.keys(agents).length,hooks:{pipeline:!!pipelineHook["experimental.chat.messages.transform"],systemEnhancer:!!systemEnhancerHook["experimental.chat.system.transform"],compaction:!!compactionHook["experimental.session.compacting"],contextBudget:!!contextBudgetHandler,commands:!0,agentActivity:config3.hooks?.agent_activity!==!1,delegationTracker:config3.hooks?.delegation_tracker===!0,guardrails:guardrailsConfig.enabled,toolSummarizer:summaryConfig.enabled,knowledge:knowledgeConfig.enabled},automation:{mode:automationConfig.mode,capabilities:automationConfig.capabilities}});let messagesTransformTrainingCaptureStep=(_input,output)=>{return trainingCaptureObserver.observeMessages(output)},messagesTransformDelegationLedgerStep=(_input,output)=>{if(process.env.DEBUG_SWARM)console.error("[DIAG] messagesTransform START");let mctx=resolveMessageTransformContext(output);if(mctx.sessionID){let archAgent=swarmState.activeAgent.get(mctx.sessionID),archSession=swarmState.agentSessions.get(mctx.sessionID),agentName=archAgent??archSession?.agentName??"";if(stripKnownSwarmPrefix(agentName)===ORCHESTRATOR_NAME)try{delegationLedgerHook.onArchitectResume(mctx.sessionID)}catch{}}return Promise.resolve()},stagedArchitectGuidanceByMessages=new WeakMap,settleDeliveryBudgetReceipts=(receipts,action2)=>{for(let receipt of receipts)if(action2==="commit")commitInjectionBudgetReceipt(receipt);else refundInjectionBudgetReceipt(receipt)},messagesTransformArchitectEnhancerStage=async(_input,output)=>{let messages=output?.messages;if(!Array.isArray(messages))return;let mctx=resolveMessageTransformContext(output),sessionID=mctx.sessionID;if(!sessionID)return;let compactionPending=_architectCompactionPending.delete(sessionID);if(!isSessionBoundArchitect(sessionID,mctx.agent)||compactionPending)return;let identity=getLiveContextModelIdentity(sessionID),context=identity?getLiveContextWindow(sessionID,identity):void 0,model=identity?{id:identity.modelID,providerID:identity.providerID,limit:context===void 0?void 0:{context}}:void 0,stagedOutput={system:[],deliveryBudgetReceipts:[],deferredRealtimeLearningNudges:[]},enhancer=architectMessagesEnhancerHook["experimental.chat.system.transform"];try{if(typeof enhancer==="function")await enhancer({sessionID,model},stagedOutput);let stagedAgent=mctx.agent??swarmState.activeAgent.get(sessionID)??swarmState.agentSessions.get(sessionID)?.agentName??"architect";stagedArchitectGuidanceByMessages.set(messages,{sessionID,agent:stagedAgent,system:stagedOutput.system,deferredRealtimeLearningNudges:stagedOutput.deferredRealtimeLearningNudges??[],turnLedgerGeneration:stagedOutput.turnLedgerGeneration,systemEnhancerBudgetReceipt:stagedOutput.systemEnhancerBudgetReceipt,fenceBudgetReceipt:stagedOutput.fenceBudgetReceipt,deliveryBudgetReceipts:stagedOutput.deliveryBudgetReceipts})}catch{if(settleDeliveryBudgetReceipts(stagedOutput.deliveryBudgetReceipts,"refund"),stagedOutput.systemEnhancerBudgetReceipt)refundInjectionBudgetReceipt(stagedOutput.systemEnhancerBudgetReceipt);if(stagedOutput.fenceBudgetReceipt)refundInjectionBudgetReceipt(stagedOutput.fenceBudgetReceipt)}},messagesTransformArchitectEnhancerDeliveryStep=async(_input,output)=>{let messages=output?.messages;if(!Array.isArray(messages))return;let staged=stagedArchitectGuidanceByMessages.get(messages);if(!staged)return;stagedArchitectGuidanceByMessages.delete(messages);let deliveryConfirmed=!1;try{let stagedOutput={system:staged.system,deliveryBudgetReceipts:staged.deliveryBudgetReceipts};await roleFilterSystemHook["experimental.chat.system.transform"]({sessionID:staged.sessionID,agent:staged.agent,expectedGeneration:staged.turnLedgerGeneration},stagedOutput),await architectMessagesCommandRuleHook({sessionID:staged.sessionID,agent:staged.agent,expectedGeneration:staged.turnLedgerGeneration},stagedOutput);let text=stagedOutput.system.filter((entry)=>entry.trim()).join(`
|
|
7850
7850
|
|
|
7851
7851
|
`),carrier=appendGuidanceCarrier(messages,"architect-session",text,{sessionID:staged.sessionID});if(!deliveredGuidanceDelta(carrier,text)){if(settleDeliveryBudgetReceipts(staged.deliveryBudgetReceipts,"refund"),staged.systemEnhancerBudgetReceipt)refundInjectionBudgetReceipt(staged.systemEnhancerBudgetReceipt);if(staged.fenceBudgetReceipt)refundInjectionBudgetReceipt(staged.fenceBudgetReceipt);return}if(staged.systemEnhancerBudgetReceipt)commitInjectionBudgetReceipt(staged.systemEnhancerBudgetReceipt);if(staged.fenceBudgetReceipt)commitInjectionBudgetReceipt(staged.fenceBudgetReceipt);settleDeliveryBudgetReceipts(staged.deliveryBudgetReceipts,"commit"),deliveryConfirmed=!0;for(let sessionID of staged.deferredRealtimeLearningNudges)recordRealtimeLearningNudge(sessionID);let carrierTokens=estimateTokens(messageTextOf(carrier)),stagedTokens=estimateTokens(text),fenceOverheadTokens=Math.max(0,carrierTokens-stagedTokens);if(fenceOverheadTokens>0){if(staged.sessionID&&staged.turnLedgerGeneration!==void 0)recordProducerEmission(staged.sessionID,"guidance-carrier-fence",fenceOverheadTokens,0,"messages",{expectedGeneration:staged.turnLedgerGeneration})}}catch{if(!deliveryConfirmed){if(settleDeliveryBudgetReceipts(staged.deliveryBudgetReceipts,"refund"),staged.systemEnhancerBudgetReceipt)refundInjectionBudgetReceipt(staged.systemEnhancerBudgetReceipt);if(staged.fenceBudgetReceipt)refundInjectionBudgetReceipt(staged.fenceBudgetReceipt)}}},messagesTransformKnowledgeApplicationScanStep=(_input,output)=>{try{let mctx=resolveMessageTransformContext(output);return knowledgeApplicationTransformScan(bootstrapRoot,output,mctx.sessionID)}catch{return Promise.resolve()}},messagesTransformSkillPropagationScanStep=(_input,output)=>{try{if(!skillPropagationConfig.enabled)return Promise.resolve();let mctx=resolveMessageTransformContext(output);return skillPropagationTransformScan(bootstrapRoot,output,mctx.sessionID,skillPropagationConfig)}catch{return Promise.resolve()}},messagesTransformSystemGuidanceMaterializeStep=(_input,output)=>{if(Array.isArray(output.messages))materializeSystemGuidanceInPlace(output.messages);if(process.env.DEBUG_SWARM)console.error("[DIAG] messagesTransform DONE");return Promise.resolve()},messagesTransformGuidanceCarrierOrderStep=(_input,output)=>{if(Array.isArray(output?.messages))moveGuidanceCarriersToEnd(output.messages);return Promise.resolve()},systemTransformStartDiagnostic=async(_input,_output)=>{if(process.env.DEBUG_SWARM)console.error("[DIAG] systemTransform START")},systemTransformEnhancerDoneDiagnostic=async(_input,_output)=>{if(process.env.DEBUG_SWARM)console.error("[DIAG] systemTransform enhancer DONE")},systemTransformHeartbeatStep=(input,_output)=>{try{let{sessionID}=input;if(!sessionID)return Promise.resolve();let lastTime=_heartbeatTimers.get(sessionID);if(Date.now()-(lastTime??0)>30000)_heartbeatTimers.set(sessionID,Date.now()),capSessionMap(_heartbeatTimers,MAX_TRACKED_HEARTBEAT_SESSIONS,sessionID),telemetry.heartbeat(sessionID)}catch{}return Promise.resolve()};return{name:"opencode-swarm",dispose:async()=>{try{cancelDeferredMaintenanceScans(bootstrapRoot)}catch(err2){log("dispose deferred-scan cancellation failed (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})}if(cleanupAutomation(),instanceExitCleanups.delete(instanceExitCleanupToken),instanceExitCleanups.size===0&&processExitCleanupRegistered){process.off("exit",runInstanceExitCleanups);for(let{signal:signal2,handler}of processSignalCleanupHandlers)process.off(signal2,handler);processSignalCleanupHandlers=[],processExitCleanupRegistered=!1}evictAndClose(bootstrapRoot);try{await closeSnapshotCoordinationInitialization(bootstrapRoot),closeGroupCommitWriter(bootstrapRoot),closeProjectDb(bootstrapRoot)}catch(err2){log("dispose durable-state close failed (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})}},agent:agents,tool:buildPluginToolObject(agentDefinitionMap,config3,evaluationModelDispatcher,reviewModelDispatcher,instanceGeneratedAgentNames,reviewAgentModelRegistry,getActiveReviewAgentName),event:async(input)=>{try{let rememberedUsage=rememberAssistantUsageEvent(input);if(rememberedUsage){if(!emitPendingCostCorrection(rememberedUsage.sessionId,rememberedUsage.raw))schedulePendingCostCorrectionRecovery(rememberedUsage)}let lifecycleEvent=input.event;if(lifecycleEvent?.type==="message.part.updated"){let part=lifecycleEvent.properties?.part,metadata=part?.state?.metadata,eventParentSessionID=typeof part?.sessionID==="string"&&part.sessionID.trim()!==""?part.sessionID:void 0,eventChildSessionID=typeof metadata?.sessionId==="string"&&metadata.sessionId.trim()!==""?metadata.sessionId:void 0;if(part?.type==="tool"&&typeof part?.tool==="string"&&isTaskToolId(part.tool)&&typeof part.callID==="string"&&part.callID.trim()!==""&&eventParentSessionID!==void 0&&eventChildSessionID!==void 0&&eventParentSessionID!==eventChildSessionID){await delegationGateHooks.taskMetadata({callID:part.callID,parentSessionID:eventParentSessionID,childSessionID:eventChildSessionID}),bindPendingTaskModelRouteChild({parentSessionID:eventParentSessionID,callID:part.callID,childSessionID:eventChildSessionID});let fullAutoRunState=loadFullAutoRunState(bootstrapRoot,eventParentSessionID);if(fullAutoRunState?.runGeneration!==void 0)bindFullAutoSevereChildSession({childSessionID:eventChildSessionID,parentSessionID:eventParentSessionID,parentCallID:part.callID,generation:fullAutoRunState.runGeneration})}}if(lifecycleEvent?.type==="session.error"){let properties=lifecycleEvent.properties,childSessionID=typeof properties?.sessionID==="string"?properties.sessionID:typeof properties?.sessionId==="string"?properties.sessionId:typeof properties?.info==="object"&&properties.info&&typeof properties.info.id==="string"?properties.info.id??"":"",route=childSessionID?resolveTaskRouteForChildSession(childSessionID):void 0,routeModel=resolveTaskRouteModelChain(route?swarmState.activeAgent.get(childSessionID)??swarmState.agentSessions.get(childSessionID)?.agentName??route.role:swarmState.activeAgent.get(childSessionID)??swarmState.agentSessions.get(childSessionID)?.agentName),errorSignal=extractSessionErrorSignal(properties);if(route&&routeModel&&errorSignal&&isRetryableProviderFailure(classifyProviderFailure(errorSignal)))advancePendingTaskModelRoute({childSessionID,role:route.role,actionDigest:route.actionDigest,primaryModel:routeModel.primaryModel,fallbackModels:routeModel.fallbackModels})}let lifecycleStatus=lifecycleEvent?.properties?.status;if(lifecycleEvent?.type==="session.deleted"||lifecycleEvent?.type==="session.removed"||lifecycleEvent?.type==="session.idle"||lifecycleEvent?.type==="session.error"||lifecycleEvent?.type==="session.status"&&(lifecycleStatus==="idle"||typeof lifecycleStatus==="object"&&(lifecycleStatus.type==="idle"||lifecycleStatus.type==="error"))){let properties=lifecycleEvent.properties,sessionID=properties?.sessionID??properties?.sessionId??properties?.info?.sessionID??properties?.info?.id??properties?.id;if(sessionID){if(delegationGateHooks.sessionEnded(sessionID,lifecycleEvent.type==="session.deleted"||lifecycleEvent.type==="session.removed"),lifecycleEvent.type==="session.deleted"||lifecycleEvent.type==="session.removed"){_architectCompactionPending.delete(sessionID);try{await terminalizePrWorkflowGateForSession2(bootstrapRoot,sessionID)}catch{warn("PR workflow gate terminalization on session deletion failed (non-fatal)")}try{let reconciliation=reconcilePrWorkflowCheckoutReceipts(bootstrapRoot,sessionID),summary=await withTimeout(reconciliation,SESSION_DELETION_RECEIPT_RECONCILIATION_EVENT_DEADLINE_MS,Error("PR workflow checkout receipt reconciliation exceeded the session-deletion event budget"));log("PR workflow checkout receipts reconciled on session deletion",{inspected:summary.inspectedReceiptCount,collected:summary.collectedStashOids.length,retiredMissing:summary.retiredMissingStashOids.length,preserved:summary.preservedStashOids.length,failures:summary.failures.length})}catch{warn("PR workflow checkout receipt reconciliation on session deletion failed or exceeded its event budget (non-fatal)")}if(bootstrapStateWritesEnabled)deleteSnapshotSessionRows(bootstrapRoot,sessionID);clearPendingTaskModelRoutesForSession(sessionID),clearSessionActionCircuits(sessionID),clearFullAutoSevereSession(sessionID)}if(backgroundSubagentsEnabled&&bootstrapStateWritesEnabled)try{await maintainBackgroundDelegationsOnSessionEvent()}catch{}try{let{recoverTerminalLaneReceipts:recoverTerminalLaneReceipts2}=await Promise.resolve().then(() => (init_delegation_lifecycle(),exports_delegation_lifecycle));await recoverTerminalLaneReceipts2(bootstrapRoot)}catch{}}}if(prWorkflowSessionResolver.observeEvent(input),await prWorkflowResponseGate.event(input),prEventDelivery){let evt=input.event,idleSessionID=evt?.properties?.sessionID??evt?.data?.sessionID;if(evt?.type==="session.idle"&&typeof idleSessionID==="string")prEventDelivery.noteSessionIdle(idleSessionID,ctx.directory)}await backgroundCompletionObserver.event(input)}catch(err2){warn(`[swarm] event hook error: ${err2 instanceof Error?err2.message:String(err2)}`)}},config:async(opencodeConfig)=>{let isObjectRecord=(value)=>typeof value==="object"&&value!==null,pluginConfig=opencodeConfig;if(!isObjectRecord(pluginConfig.agent))pluginConfig.agent={};let agentConfig=pluginConfig.agent;Object.assign(agentConfig,agents);try{applyLanePermissions(opencodeConfig,ctx.directory,config3?.worktree?.lane_permissions??"scoped_allow")}catch(err2){addDeferredWarning(`[swarm] lane permission scoping failed: ${err2 instanceof Error?err2.message:String(err2)}`)}let autoSelect=config3?.auto_select_architect;if(autoSelect)if(Object.keys(agents).some((name)=>stripKnownSwarmPrefix(name)==="architect")){for(let builtin of["build","plan"]){let existing=agentConfig[builtin];if(isObjectRecord(existing)&&existing.disable===!0)continue;agentConfig[builtin]={...isObjectRecord(existing)?existing:{},disable:!0}}if(autoSelect===!0){let primaryArchitects=Object.entries(agents).filter(([name,cfg])=>stripKnownSwarmPrefix(name)==="architect"&&isObjectRecord(cfg)&&cfg.mode==="primary");if(primaryArchitects.length>1){let names=primaryArchitects.map(([n])=>n).join(", ");addDeferredWarning(`[swarm] auto_select_architect is true but ${primaryArchitects.length} architect agents are primary (${names}). Consider setting auto_select_architect to a specific agent name.`)}}if(typeof autoSelect==="string"&&autoSelect!==""){let targetName=autoSelect;if(Object.hasOwn(agents,targetName)&&stripKnownSwarmPrefix(targetName)==="architect"){for(let[name,cfg]of Object.entries(agents))if(stripKnownSwarmPrefix(name)==="architect"&&name!==targetName)agentConfig[name]={...isObjectRecord(cfg)?cfg:{},mode:"subagent"};let targetExisting=agentConfig[targetName],targetAgent=agents[targetName];agentConfig[targetName]={...isObjectRecord(targetExisting)?targetExisting:{},...isObjectRecord(targetAgent)?targetAgent:{},mode:"primary"}}else addDeferredWarning(`[swarm] auto_select_architect is set to "${targetName}" but that is not a known architect agent. No architect demotion applied.`)}}else addDeferredWarning("[swarm] auto_select_architect is enabled but no architect agents were found in the generated set. The option has no effect.");let shortcutDescription=(cmd)=>{let entry=COMMAND_REGISTRY[cmd];if(!entry?.description)return`Use /swarm ${cmd}`;let desc=entry.description.charAt(0).toLowerCase()+entry.description.slice(1);return`Use /swarm ${cmd} to ${desc}`};opencodeConfig.command={...opencodeConfig.command||{},swarm:{template:"/swarm $ARGUMENTS",description:(()=>{return`Swarm management commands: /swarm [${VALID_COMMANDS.filter((cmd)=>{let entry=COMMAND_REGISTRY[cmd];return!entry.aliasOf&&!entry.deprecated&&!entry.subcommandOf}).join("|")}]`})()},"swarm-status":{template:"/swarm status",description:"Use /swarm status to show current swarm status and active phase"},"swarm-show-plan":{template:"/swarm show-plan $ARGUMENTS",description:"Use /swarm show-plan to view or filter the current execution plan"},"swarm-plan":{template:"/swarm show-plan $ARGUMENTS",description:"Deprecated alias for /swarm show-plan (runs the canonical command)"},"swarm-agents":{template:"/swarm agents",description:"Use /swarm agents to list registered swarm agents"},"swarm-history":{template:"/swarm history",description:"Use /swarm history to show completed phases summary"},"swarm-config":{template:"/swarm config $ARGUMENTS",description:"Use /swarm config to show or validate configuration"},"swarm-evidence":{template:"/swarm evidence $ARGUMENTS",description:"Use /swarm evidence to view evidence bundles and summaries"},"swarm-handoff":{template:"/swarm handoff",description:"Use /swarm handoff to prepare handoff brief for switching models mid-task"},"swarm-archive":{template:"/swarm archive",description:"Use /swarm archive to archive old evidence bundles"},"swarm-diagnose":{template:"/swarm diagnose",description:"Use /swarm diagnose to run health checks on swarm state"},"swarm-diagnosis":{template:"/swarm diagnosis",description:"Use /swarm diagnosis to run health checks on swarm state"},"swarm-preflight":{template:"/swarm preflight",description:"Use /swarm preflight to run preflight automation checks"},"swarm-sync-plan":{template:"/swarm sync-plan",description:"Use /swarm sync-plan to sync plan.json with plan.md"},"swarm-benchmark":{template:"/swarm benchmark",description:"Use /swarm benchmark to show performance metrics"},"swarm-gate-audit":{template:"/swarm gate-audit $ARGUMENTS",description:"Use /swarm gate-audit to run the bounded Tier-1 production gate matrix"},"swarm-gate-stats":{template:"/swarm gate-stats $ARGUMENTS",description:"Use /swarm gate-stats to summarize stored gate-audit evidence"},"swarm-skill-opt":{template:"/swarm skill-opt $ARGUMENTS",description:"Use /swarm skill-opt to govern skill optimization (plan|run|status|diff|approve|reject|rollback|history)"},"swarm-harness-opt":{template:"/swarm harness-opt $ARGUMENTS",description:"Use /swarm harness-opt to govern harness optimization rounds (plan|run|status|stop|history)"},"swarm-costs":{template:"/swarm costs $ARGUMENTS",description:"Use /swarm costs to show per-agent, task, gate, and retry token/cost totals"},"swarm-report":{template:"/swarm report $ARGUMENTS",description:"Use /swarm report to query swarm observability events (--task/--session/--trace/--run/--since/--json)"},"swarm-dashboard":{template:"/swarm dashboard",description:"Use /swarm dashboard to show the opt-in local mission-control dashboard URL and status"},"swarm-export":{template:"/swarm export",description:"Use /swarm export to export plan and context as JSON"},"swarm-dataset-consent":{template:"/swarm dataset consent $ARGUMENTS",description:"Use /swarm dataset consent to grant or revoke the training-content consent (human-only, confirm token)"},"swarm-dataset-export":{template:"/swarm dataset export $ARGUMENTS",description:"Use /swarm dataset export to preview/write the deterministic governed dataset export (human-only, confirm token)"},"swarm-dataset-withdraw":{template:"/swarm dataset withdraw $ARGUMENTS",description:"Use /swarm dataset withdraw to purge vault content, tombstone, and revoke exports (human-only, confirm token)"},"swarm-reset":{template:"/swarm reset --confirm",description:"Use /swarm reset --confirm to clear swarm state (requires --confirm)"},"swarm-rollback":{template:"/swarm rollback $ARGUMENTS",description:"Use /swarm rollback to restore swarm state to a checkpoint"},"swarm-retrieve":{template:"/swarm retrieve $ARGUMENTS",description:"Use /swarm retrieve to retrieve full output from summary"},"swarm-clarify":{template:"/swarm clarify $ARGUMENTS",description:"Use /swarm clarify to clarify and refine a feature specification"},"swarm-analyze":{template:"/swarm analyze",description:"Use /swarm analyze to analyze spec vs plan for coverage gaps"},"swarm-specify":{template:"/swarm specify $ARGUMENTS",description:"Use /swarm specify to generate or import a feature specification"},"swarm-brainstorm":{template:"/swarm brainstorm $ARGUMENTS",description:"Use /swarm brainstorm to enter the architect MODE: BRAINSTORM planning workflow"},"swarm-loop":{template:"/swarm loop $ARGUMENTS",description:"Use /swarm loop <objective> to run a compound-engineering loop: brainstorm → plan → build → review → improve, iterating until done [--max-cycles 1..5] [--autonomy checkpoint|auto] [--depth standard|exhaustive] [--resume]"},"swarm-council":{template:"/swarm council $ARGUMENTS",description:"Use /swarm council <question> to convene a multi-model General Council deliberation (generalist / skeptic / domain expert) [--spec-review]"},"swarm-pr-review":{template:"/swarm pr-review $ARGUMENTS",description:"Use /swarm pr-review to launch deep PR review with multi-lane analysis"},"swarm-review":{template:"/swarm review $ARGUMENTS",description:"Use /swarm review to run the bounded whole-diff review engine for the selected local scope"},"swarm-pr-feedback":{template:"/swarm pr-feedback $ARGUMENTS",description:"Use /swarm pr-feedback to ingest and close known PR feedback (review comments, CI failures, conflicts) without a fresh broad review"},"swarm-abort-pr-workflow":{template:"/swarm abort-pr-workflow $ARGUMENTS",description:"Use /swarm abort-pr-workflow to clear a stuck PR_REVIEW/PR_FEEDBACK mechanical gate and stop the auto-resume loop; cancel an armed PR_FEEDBACK without publication with PR_FEEDBACK --cancel-publication <reason...> (human-only escape hatch)"},"swarm-pr-feedback-loop":{template:"/swarm pr-feedback-loop $ARGUMENTS",description:"Use /swarm pr-feedback-loop stop <reason...> to stop the autonomous PR babysitting settling loop for this session (human-only)"},"swarm-approve-plan-critic":{template:"/swarm approve-plan-critic $ARGUMENTS",description:"Use /swarm approve-plan-critic to record a MANUAL plan-critic approval that unblocks the ratchet-tighter critic_pre_plan execution gate when the critic already returned APPROVED but the snapshot was not recorded (human-only escape hatch)"},"swarm-approve-write":{template:"/swarm approve-write $ARGUMENTS",description:"Use /swarm approve-write to issue one exact, session-bound, one-shot write approval (human-only)"},"swarm-ci-monitor":{template:"/swarm ci-monitor $ARGUMENTS",description:"Use /swarm ci-monitor to drive an already-reviewed, approved PR to green and merged (monitor CI, fix, merge)"},"swarm-pr-subscribe":{template:"/swarm pr subscribe $ARGUMENTS",description:shortcutDescription("pr subscribe")},"swarm-pr-unsubscribe":{template:"/swarm pr unsubscribe $ARGUMENTS",description:shortcutDescription("pr unsubscribe")},"swarm-pr-status":{template:"/swarm pr status",description:shortcutDescription("pr status")},"swarm-ci-simulate":{template:"/swarm ci-simulate $ARGUMENTS",description:shortcutDescription("ci-simulate")},"swarm-ci":{template:"/swarm ci $ARGUMENTS",description:shortcutDescription("ci")},"swarm-learning":{template:"/swarm learning",description:shortcutDescription("learning")},"swarm-post-mortem":{template:"/swarm post-mortem $ARGUMENTS",description:shortcutDescription("post-mortem")},"swarm-deep-dive":{template:"/swarm deep-dive $ARGUMENTS",description:"Use /swarm deep-dive to launch a read-only deep audit with parallel explorer waves, dual reviewers, and critic challenge"},"swarm-deep-research":{template:"/swarm deep-research $ARGUMENTS",description:"Use /swarm deep-research <question> to run a multi-source, fact-checked deep research pass and synthesize a cited report [--depth standard|exhaustive] [--max-researchers 1..6] [--rounds 1..4] [--brief]"},"swarm-codebase-review":{template:"/swarm codebase-review $ARGUMENTS",description:"Use /swarm codebase-review to launch codebase-review-swarm for a quote-grounded full-repo or large-subsystem audit"},"swarm-design-docs":{template:"/swarm design-docs $ARGUMENTS",description:"Use /swarm design-docs to generate or sync language-agnostic design docs for the project under build"},"swarm-sdd":{template:"/swarm sdd $ARGUMENTS",description:"Use /swarm sdd to inspect OpenSpec-compatible SDD artifacts"},"swarm-sdd-status":{template:"/swarm sdd status",description:"Use /swarm sdd status to show effective spec and OpenSpec artifact status"},"swarm-sdd-validate":{template:"/swarm sdd validate $ARGUMENTS",description:"Use /swarm sdd validate to validate OpenSpec-compatible SDD artifacts"},"swarm-sdd-project":{template:"/swarm sdd project $ARGUMENTS",description:"Use /swarm sdd project to materialize OpenSpec artifacts into .swarm/spec.md"},"swarm-blueprint-validate":{template:"/swarm blueprint validate $ARGUMENTS",description:shortcutDescription("blueprint validate")},"swarm-blueprint-current":{template:"/swarm blueprint current",description:shortcutDescription("blueprint current")},"swarm-blueprint-history":{template:"/swarm blueprint history",description:shortcutDescription("blueprint history")},"swarm-blueprint-diff":{template:"/swarm blueprint diff $ARGUMENTS",description:shortcutDescription("blueprint diff")},"swarm-blueprint-export":{template:"/swarm blueprint export $ARGUMENTS",description:shortcutDescription("blueprint export")},"swarm-harness-candidate-validate":{template:"/swarm harness candidate validate $ARGUMENTS",description:shortcutDescription("harness candidate validate")},"swarm-harness-candidate-show":{template:"/swarm harness candidate show $ARGUMENTS",description:shortcutDescription("harness candidate show")},"swarm-harness-candidate-diff":{template:"/swarm harness candidate diff $ARGUMENTS",description:shortcutDescription("harness candidate diff")},"swarm-issue":{template:"/swarm issue $ARGUMENTS",description:"Use /swarm issue to ingest a GitHub issue into the swarm workflow"},"swarm-qa-gates":{template:"/swarm qa-gates $ARGUMENTS",description:"Use /swarm qa-gates to view or modify QA gate profile for the current plan"},"swarm-dark-matter":{template:"/swarm dark-matter",description:"Use /swarm dark-matter to detect hidden file couplings"},"swarm-knowledge":{template:"/swarm knowledge $ARGUMENTS",description:"Use /swarm knowledge for knowledge management (quarantine/restore/migrate)"},"swarm-memory":{template:"/swarm memory $ARGUMENTS",description:"Use /swarm memory for memory status, JSONL export/import, and SQLite migration"},"swarm-memory-status":{template:"/swarm memory status",description:"Use /swarm memory status to show provider and migration status"},"swarm-memory-export":{template:"/swarm memory export",description:"Use /swarm memory export to write current memory to JSONL"},"swarm-memory-import":{template:"/swarm memory import",description:"Use /swarm memory import to import legacy JSONL into SQLite"},"swarm-memory-migrate":{template:"/swarm memory migrate",description:"Use /swarm memory migrate to run the one-time SQLite migration"},"swarm-curate":{template:"/swarm curate",description:"Use /swarm curate to curate knowledge artifacts and entries"},"swarm-consolidate":{template:"/swarm consolidate $ARGUMENTS",description:"Use /swarm consolidate to run quota-bounded skill-improver consolidation"},"swarm-concurrency":{template:"/swarm concurrency $ARGUMENTS",description:"Use /swarm concurrency to manage runtime concurrency override for plan execution"},"swarm-turbo":{template:"/swarm turbo",description:"Use /swarm turbo to enable turbo mode for faster execution"},"swarm-epic":{template:"/swarm epic $ARGUMENTS",description:shortcutDescription("epic")},"swarm-coupling":{template:"/swarm coupling $ARGUMENTS",description:shortcutDescription("coupling")},"swarm-lanes":{template:"/swarm lanes",description:shortcutDescription("lanes")},"swarm-guardrail-explain":{template:"/swarm guardrail explain $ARGUMENTS",description:shortcutDescription("guardrail explain")},"swarm-guardrail-reset":{template:"/swarm guardrail reset $ARGUMENTS",description:shortcutDescription("guardrail reset")},"swarm-guardrail-log":{template:"/swarm guardrail-log $ARGUMENTS",description:shortcutDescription("guardrail-log")},"swarm-full-auto":{template:"/swarm full-auto $ARGUMENTS",description:"Toggle Full-Auto Mode for the active session [on|off]"},"swarm-auto-proceed":{template:"/swarm auto-proceed $ARGUMENTS",description:"Toggle auto-proceed mode for automatic phase advancement"},"swarm-write-retro":{template:"/swarm write-retro $ARGUMENTS",description:"Use /swarm write-retro to manually write a phase retrospective"},"swarm-reset-session":{template:"/swarm reset-session",description:"Use /swarm reset-session to clear session state and delegation chains"},"swarm-recover":{template:"/swarm recover $ARGUMENTS",description:"Use /swarm recover to settle wedged coder settlements [task_id] [--force]"},"swarm-simulate":{template:"/swarm simulate $ARGUMENTS",description:"Use /swarm simulate to run a simulated agent session"},"swarm-promote":{template:"/swarm promote $ARGUMENTS",description:"Use /swarm promote to promote knowledge entries to production"},"swarm-checkpoint":{template:"/swarm checkpoint $ARGUMENTS",description:"Use /swarm checkpoint to save or restore git checkpoints"},"swarm-config-doctor":{template:"/swarm config doctor",description:"Use /swarm config doctor to diagnose configuration issues"},"swarm-evidence-summary":{template:"/swarm evidence summary",description:"Use /swarm evidence summary to generate evidence summaries"},"swarm-finalize":{template:"/swarm finalize",description:"Use /swarm finalize to archive the swarm project and close active state"},"swarm-close":{template:"/swarm close",description:"Deprecated alias for /swarm finalize"},"swarm-acknowledge-spec-drift":{template:"/swarm acknowledge-spec-drift",description:"Use /swarm acknowledge-spec-drift to acknowledge spec drift and suppress further warnings"},"swarm-doctor-tools":{template:"/swarm doctor tools",description:"Use /swarm doctor tools to run tool registration coherence check"},"swarm-context-map-stats":{template:"/swarm context-map stats",description:shortcutDescription("context-map-stats")},"swarm-link":{template:"/swarm link $ARGUMENTS",description:"Use /swarm link to link this worktree to a shared knowledge store [name|status]"},"swarm-unlink":{template:"/swarm unlink $ARGUMENTS",description:"Use /swarm unlink to unlink this worktree from the shared knowledge store [--no-copy]"}},log("Config applied",{agents:Object.keys(agents),commands:["swarm"]})},"experimental.chat.messages.transform":withStartupFirstUseTracking("first_turn",void 0,composeHandlers(...[messagesTransformArchitectEnhancerStage,messagesTransformTrainingCaptureStep,messagesTransformDelegationLedgerStep,pipelineHook["experimental.chat.messages.transform"],contextBudgetHandler,initOrphanRecoveryAdvisoryHook.messagesTransform,durableBackgroundAdvisoryMessagesTransform,fullAutoInterceptHook?.messagesTransform,ccCommandInterceptHook?.messagesTransform,delegationGateHooks.messagesTransform,issueTraceHook.messagesTransform,delegationSanitizerHook,memoryLifecycleHooks.messagesTransform,knowledgeInjectorHook,messagesTransformKnowledgeApplicationScanStep,messagesTransformSkillPropagationScanStep,messagesTransformArchitectEnhancerDeliveryStep,messagesTransformSystemGuidanceMaterializeStep,messagesTransformGuidanceCarrierOrderStep,finalContextAccountingStep].filter((fn2)=>Boolean(fn2)))),"experimental.text.complete":prWorkflowResponseGate.textComplete,"experimental.chat.system.transform":composeHandlers(...[systemTransformStartDiagnostic,systemEnhancerHook["experimental.chat.system.transform"],systemTransformEnhancerDoneDiagnostic,contextCapsuleInjectHook["experimental.chat.system.transform"],systemTransformHeartbeatStep,automationConfig.capabilities?.phase_preflight===!0&&preflightTriggerManager?createPhaseMonitorHook(bootstrapRoot,preflightTriggerManager,void 0,(sessionId)=>createCuratorLLMDelegate(bootstrapRoot,"init",sessionId)):knowledgeConfig.enabled?createPhaseMonitorHook(bootstrapRoot,void 0,void 0,(sessionId)=>createCuratorLLMDelegate(bootstrapRoot,"init",sessionId)):void 0,swarmCommandSystemRuleHook,roleFilterSystemHook["experimental.chat.system.transform"],systemRenderBoundaryHook["experimental.chat.system.transform"]].filter(Boolean)),"experimental.session.compacting":async(input,output)=>{let{sessionID}=input??{};if(sessionID)_architectCompactionPending.delete(sessionID),_architectCompactionPending.set(sessionID,!0),capSessionMap(_architectCompactionPending,MAX_TRACKED_ARCHITECT_COMPACTIONS,sessionID),advanceTurnGeneration(sessionID);let delegate=compactionHook["experimental.session.compacting"];if(typeof delegate==="function")await delegate(input,output)},"command.execute.before":safeHook(commandHandler),"tool.execute.before":async(input,output)=>{if(process.env.DEBUG_SWARM)console.error(`[DIAG] toolBefore tool=${normalizeToolName(input.tool)??input.tool} session=${input.sessionID}`);if(!swarmState.activeAgent.has(input.sessionID))swarmState.activeAgent.set(input.sessionID,ORCHESTRATOR_NAME);let session=swarmState.agentSessions.get(input.sessionID),activeAgent=swarmState.activeAgent.get(input.sessionID);if(session&&activeAgent&&activeAgent!==ORCHESTRATOR_NAME){if(stripKnownSwarmPrefix(activeAgent)!==ORCHESTRATOR_NAME){if(!session.delegationActive&&Date.now()-session.lastAgentEventTime>1e4)swarmState.activeAgent.set(input.sessionID,ORCHESTRATOR_NAME),ensureAgentSession(input.sessionID,ORCHESTRATOR_NAME,bootstrapRoot)}}let failClosedRegionCompleted=!1;try{if(dispatchProtectionConfig.enabled&&spawnCircuitIsTaskTool(input.tool)){let armed=armDispatchIdentity(input.callID,input.tool,output.args),invocationID=invocationIdForSession(input.sessionID);assertDispatchSpawnCircuitAdmits({sessionID:input.sessionID,invocationID,actionDigest:armed.digest,threshold:dispatchProtectionConfig.spawn_failure_threshold,halfOpenAfterMs:dispatchProtectionConfig.half_open_after_ms}),await acquireDispatchToken({directory:bootstrapRoot,ratePerSecond:dispatchProtectionConfig.rate_per_second,burstCapacity:dispatchProtectionConfig.burst_capacity})}await guardrailsHooks.toolBefore(input,output),await scopeGuardHook.toolBefore(input,output);let prWorkflowControllerSessionID=await prWorkflowSessionResolver.resolve(input.sessionID),prWorkflowToolContext=resolveToolBeforeContext(input,output);await enforcePrWorkflowToolBefore(bootstrapRoot,prWorkflowControllerSessionID,normalizeToolName(input.tool)??input.tool,prWorkflowToolContext.args??void 0,instanceGeneratedAgentNames,input.callID),await delegationGateHooks.toolBefore(input,output),await fullAutoDelegationHook.toolBefore(input,output),await fullAutoPermissionHook.toolBefore(input,output),await knowledgeApplicationGateBefore(bootstrapRoot,{tool:input.tool,agent:resolveToolBeforeContext(input,output).agent,sessionID:input.sessionID},KnowledgeApplicationConfigSchema.parse(config3.knowledge_application??{}));let skillResult=await skillPropagationGateBefore(bootstrapRoot,{tool:input.tool,agent:resolveToolBeforeContext(input,output).agent,sessionID:input.sessionID,args:resolveToolBeforeContext(input,output).args??void 0},skillPropagationConfig);if(skillResult.blocked)throw Error(skillResult.reason??"Blocked by skill propagation gate");if(skillResult.reason){let skillSession=ensureAgentSession(input.sessionID,swarmState.activeAgent.get(input.sessionID)??ORCHESTRATOR_NAME,bootstrapRoot);pushAdvisory(skillSession,skillResult.reason)}let toolBeforeCtx=resolveToolBeforeContext(input,output),toolBeforeArgs=toolBeforeCtx.args??{},skillAttributionPlanTaskOptions=toTaskIdPlanContextOptions(await loadPlanTaskIdContext(bootstrapRoot));if(injectSkillsIntoDelegation(bootstrapRoot,toolBeforeArgs,skillResult.recommendedSkills,stripKnownSwarmPrefix(parseDelegationArgs(toolBeforeArgs)?.targetAgent??"")||toolBeforeCtx.agent,input.sessionID,{quiet:config3.quiet,...skillAttributionPlanTaskOptions}),failClosedRegionCompleted=!0,knowledgeConfig.enabled)await injectDelegateDirectivesBefore(bootstrapRoot,{tool:input.tool,agent:toolBeforeCtx.agent,sessionID:input.sessionID,args:toolBeforeArgs},knowledgeConfig);setStoredInputArgs(input.callID,output.args);let pressurePct=getFinalPromptPressure(input.sessionID)?.pct??getSessionBudgetPct(input.sessionID);if(pressurePct>=50){let pressureSession=ensureAgentSession(input.sessionID,swarmState.activeAgent.get(input.sessionID)??ORCHESTRATOR_NAME,bootstrapRoot);if(!pressureSession.contextPressureWarningSent)pressureSession.contextPressureWarningSent=!0,pushAdvisory(pressureSession,`CONTEXT PRESSURE (estimated): ${pressurePct.toFixed(1)}% estimated prompt pressure of the model context window. Prioritize completing the current task before starting new work.`)}if(autoReviewConfig.enabled)await beginApprovedReviewerScopeLifecycle({directory:bootstrapRoot,tool:input.tool,args:toolBeforeArgs,parentSessionID:input.sessionID,callID:input.callID,maxBytes:autoReviewConfig.max_diff_kb*1024});if(await safeHook(activityHooks.toolBefore)(input,output),await reserveApprovedPhaseParticipation({directory:bootstrapRoot,tool:input.tool,parentSessionId:input.sessionID,callId:input.callID,args:toolBeforeArgs,policy:config3.phase_complete}),isTaskToolId(input.tool)&&typeof toolBeforeArgs.subagent_type==="string"&&toolBeforeArgs.subagent_type.trim()!==""){let actionIdentity2=createActionIdentity({tool:input.tool,args:toolBeforeArgs});registerPendingTaskModelRoute({parentSessionID:input.sessionID,invocationID:String(getAgentSession(input.sessionID)?.activeInvocationId??0),callID:input.callID,role:stripKnownSwarmPrefix(toolBeforeArgs.subagent_type),actionDigest:actionIdentity2.digest,swarmID:actionIdentity2.swarm??void 0})}if(resetGateDenialStreaks(input.sessionID,input.tool,toolBeforeArgs),isTaskToolId(input.tool)){let delegatedAgent=typeof toolBeforeArgs.subagent_type==="string"&&toolBeforeArgs.subagent_type.length>0?toolBeforeArgs.subagent_type:swarmState.activeAgent.get(input.sessionID)??"unknown",delegationTaskId=swarmState.agentSessions.get(input.sessionID)?.currentTaskId??"";_delegationTelemetryByCallID.set(input.callID,{agentName:delegatedAgent,taskId:delegationTaskId}),capSessionMap(_delegationTelemetryByCallID,MAX_TRACKED_DELEGATION_TELEMETRY,input.callID),telemetry.delegationBegin(input.sessionID,delegatedAgent,delegationTaskId)}}catch(err2){if(!failClosedRegionCompleted){let deniedMessage=err2&&typeof err2==="object"&&typeof err2.message==="string"?err2.message:null,deniedArgs;try{deniedArgs=resolveToolBeforeContext(input,output).args??void 0}catch{deniedArgs=void 0}if(deniedMessage!==null&&!isAbortLikeError(err2))try{await recordDeniedToolCall(input.sessionID,{tool:input.tool,callID:input.callID,args:deniedArgs},deniedMessage,bootstrapRoot,{maxLines:prmConfig.max_trajectory_lines})}catch{}noteGateDenial(input.sessionID,input.tool,err2,{enabled:guardrailsConfig.enabled,warnThreshold:guardrailsConfig.gate_denial_warn_threshold,stopThreshold:guardrailsConfig.gate_denial_stop_threshold},deniedArgs)}if(isTaskToolId(input.tool))try{await delegationGateHooks.abortDeniedSettlementForCall(input.callID,input.sessionID)}catch{}throw err2}},"tool.execute.after":async(input,output)=>{let _dbg=!!process.env.DEBUG_SWARM,_toolName=normalizeToolName(input.tool)??input.tool;if(_dbg)console.error(`[DIAG] toolAfter START tool=${_toolName} session=${input.sessionID}`);let isTaskTool8=isTaskToolId(input.tool),afterCtx=resolveToolAfterContext(input);if(await safeHook(()=>trainingCaptureObserver.observeToolExecution({tool:input.tool,sessionID:input.sessionID,input:afterCtx.args,output,error:output?.state==="error"?output:void 0}))(input,output),dispatchProtectionConfig.enabled&&spawnCircuitIsTaskTool(input.tool))try{let identity=takeArmedDispatchIdentity(input.callID)??dispatchIdentityFor(input.tool,afterCtx.args),invocationID=invocationIdForSession(input.sessionID);if(output?.state==="error"){let{opened}=noteDispatchSpawnFailure({sessionID:input.sessionID,invocationID,actionDigest:identity.digest,threshold:dispatchProtectionConfig.spawn_failure_threshold,halfOpenAfterMs:dispatchProtectionConfig.half_open_after_ms});if(opened)telemetry.loopDetected(input.sessionID,swarmState.activeAgent.get(input.sessionID)??"agent",`dispatch.spawn:${identity.pattern}`)}else if(output?.state==="completed")noteDispatchSpawnSuccess({sessionID:input.sessionID,invocationID,actionDigest:identity.digest})}catch{}try{let pushCommand=afterCtx.args?.command;if(typeof pushCommand==="string"&&/^\s*git\s+push/i.test(pushCommand)){let pushAttemptSessionID=await prWorkflowSessionResolver.resolve(input.sessionID);await recordPrFeedbackPushAttemptResult(bootstrapRoot,{sessionID:pushAttemptSessionID,callID:input.callID,tool:input.tool},pushCommand,output)}}catch{}if(autoReviewConfig.enabled&&isTaskTool8)await completeReviewerScopeLifecycle({directory:bootstrapRoot,tool:input.tool,args:afterCtx.args,output,parentSessionID:input.sessionID,callID:input.callID});let hookChain=async()=>{if(await activityHooks.toolAfter(input,output),_dbg)console.error(`[DIAG] toolAfter activity done tool=${_toolName}`);if(await safeHook(trajectoryLoggerHook.toolAfter)(input,output),_dbg)console.error(`[DIAG] toolAfter trajectoryLogger done tool=${_toolName}`);if(knowledgeConfig.enabled)await safeHook(()=>collectDelegateAcksAfter(bootstrapRoot,{tool:input.tool,sessionID:input.sessionID,args:afterCtx.args},output))(input,output),await safeHook(()=>collectReviewerVerdictsAfter(bootstrapRoot,{tool:input.tool,sessionID:input.sessionID,args:afterCtx.args},output))(input,output),await safeHook(()=>microReflectorAfter(bootstrapRoot,input,output,createCuratorLLMDelegate(bootstrapRoot,"phase",input.sessionID),{maxCalls:knowledgeConfig.enrichment.max_calls_per_day,window:knowledgeConfig.enrichment.quota_window},{enabled:learningConfig.realtime_admission.enabled,maxQueueSize:learningConfig.realtime_admission.max_queue_size}))(input,output);if(await safeHook(async()=>{let summary=await realtimeAdmissionAfter(bootstrapRoot,{tool:input.tool,sessionID:input.sessionID},learningConfig.realtime_admission,async()=>{let plan=await loadPlan(bootstrapRoot).catch(()=>null);return{knowledgeConfig,projectName:plan?.title??"unknown",phaseNumber:plan?.current_phase??1,sessionID:input.sessionID,llmDelegate:createCuratorLLMDelegate(bootstrapRoot,"phase",input.sessionID),onKnowledgeChanged:bumpKnowledgeGeneration}});if(summary)log("realtime admission drain",{sessionID:input.sessionID,...summary})})(input,output),await safeHook(async()=>{await collectReviewerReceiptAfter(bootstrapRoot,{tool:input.tool,sessionID:input.sessionID,callID:input.callID,args:afterCtx.args},output,{dispatcher:reviewModelDispatcher,config:autoReviewConfig,generatedAgentNames:instanceGeneratedAgentNames,agentModelRegistry:reviewAgentModelRegistry,injectAdvisory:advisoryInjector,validationScheduler:findingValidationScheduler})})(input,output),await safeHook(autoReviewHook.toolAfter)(input,afterCtx),await safeHook(prmHook.toolAfter)(input,output),await guardrailsHooks.toolAfter(input,output),_dbg)console.error(`[DIAG] toolAfter guardrails done tool=${_toolName}`);if(await safeHook(delegationLedgerHook.toolAfter)(input,output),_dbg)console.error(`[DIAG] toolAfter ledger done tool=${_toolName}`);if(await safeHook(selfReviewHook.toolAfter)(input,output),_dbg)console.error(`[DIAG] toolAfter selfReview done tool=${_toolName}`);if(await safeHook(memoryLifecycleHooks.toolAfter)(input,output),_dbg)console.error(`[DIAG] toolAfter memory done tool=${_toolName}`);if(await safeHook(delegationGateHooks.toolAfter)(input,output),await safeHook(async()=>{await observePhaseParticipationToolResult({directory:bootstrapRoot,tool:input.tool,parentSessionId:input.sessionID,callId:input.callID,output})})(input,output),_dbg)console.error(`[DIAG] toolAfter delegationGate done tool=${_toolName}`);if(await safeHook(fullAutoInputProbeHook.toolAfter)(input,output),await safeHook(fullAutoDelegationHook.toolAfter)(input,output),await safeHook(prAutoSubscribeHook.toolAfter)(input,output),isTaskTool8&&typeof output.output==="string")try{let adversarialMatches=detectAdversarialPatterns(output.output);if(adversarialMatches.length>0){let sessionId=input.sessionID,session=swarmState.agentSessions.get(sessionId);if(session)pushAdvisory(session,`ADVERSARIAL PATTERN DETECTED: ${adversarialMatches.map((p)=>p.pattern).join(", ")}. Review agent output for potential prompt injection or gate bypass.`);if("adversarialPatternDetected"in telemetry)telemetry.adversarialPatternDetected(input.sessionID,adversarialMatches)}}catch{}try{recordToolCall(_toolName,resolveToolAfterContext(input).args,input.sessionID)}catch{}try{let spiralMatch=await detectDebuggingSpiral(bootstrapRoot,input.sessionID);if(spiralMatch){let taskId=swarmState.agentSessions.get(input.sessionID)?.currentTaskId??`session-${input.sessionID.slice(0,12)}`,spiralResult=await handleDebuggingSpiral(spiralMatch,taskId,bootstrapRoot),session=swarmState.agentSessions.get(input.sessionID);if(session)pushAdvisory(session,spiralResult.message)}}catch{}if(knowledgeCuratorHook)await safeHook(knowledgeCuratorHook)(input,output);if(hivePromoterHook)await safeHook(hivePromoterHook)(input,output);if(_dbg)console.error(`[DIAG] toolAfter knowledge done tool=${_toolName}`);if(await safeHook(steeringConsumedHook)(input,output),await safeHook(coChangeSuggesterHook)(input,output),await safeHook(darkMatterDetectorHook)(input,output),_dbg)console.error(`[DIAG] toolAfter intelligence done tool=${_toolName}`);if(await snapshotWriterHook(input,output),await toolSummarizerHook?.(input,output),_dbg)console.error(`[DIAG] toolAfter snapshot+summarizer done tool=${_toolName}`);let execMode=config3.execution_mode??"balanced";if(execMode==="strict"){if(slopDetectorHook)await slopDetectorHook.toolAfter(input,output);if(incrementalVerifyHook)await incrementalVerifyHook.toolAfter(input,output)}if(execMode!=="fast"&&compactionServiceHook)await compactionServiceHook.toolAfter(input,output);if(repoGraphHook)await safeHook(repoGraphHook.toolAfter)(input,output);if(isTaskTool8&&config3.context_map?.enabled===!0&&input.sessionID)try{let contextMapTaskId=swarmState.agentSessions.get(input.sessionID)?.currentTaskId??null;if(contextMapTaskId){let agentOutput=typeof output.output==="string"?output.output:"";updateContextMapAfterAgent({task_id:contextMapTaskId,agent_role:swarmState.activeAgent.get(input.sessionID)??"unknown",files_touched:[],implementation_summary:agentOutput.slice(0,500),task_goal:"",final_status:"completed",directory:bootstrapRoot})}}catch{}let toolOutputConfig=config3.tool_output;if(toolOutputConfig&&toolOutputConfig.truncation_enabled!==!1&&typeof output.output==="string"){let defaultTruncatableTools=new Set(["diff","symbols","bash","shell","test_runner","lint","pre_check_batch","complexity_hotspots","pkg_audit","sbom_generate","schema_drift"]),configuredTools=toolOutputConfig.truncation_tools,truncatableTools=computeEffectiveTruncatableTools(defaultTruncatableTools,configuredTools),maxLines=toolOutputConfig.per_tool?.[input.tool]??toolOutputConfig.max_lines??150;if(truncatableTools.has(input.tool))output.output=truncateToolOutput(output.output,maxLines,input.tool,10)}};try{await hookChain()}catch(err2){let warning=`[swarm] toolAfter hook chain error tool=${_toolName}: ${err2 instanceof Error?err2.message:String(err2)}`;if(!config3.quiet)console.warn(warning);else addDeferredWarning(warning)}if(isTaskTool8){let backgroundResultIsRunning=outputLooksLikeBackgroundRunning(output),sessionId=input.sessionID,beganDelegation=_delegationTelemetryByCallID.get(input.callID),storedSubagentType=typeof afterCtx.args?.subagent_type==="string"?afterCtx.args.subagent_type:void 0,agentName=beganDelegation?.agentName||storedSubagentType||swarmState.activeAgent.get(sessionId)||"unknown",baseAgentName=stripKnownSwarmPrefix(agentName),preHandoffSession=swarmState.agentSessions.get(sessionId),activeWindow=getActiveWindow(sessionId),configuredModel=resolveRegisteredAgentModel(config3,agentName)??DEFAULT_MODELS[baseAgentName]??DEFAULT_MODELS.default,assistantUsage=consumeAssistantUsageForTask(sessionId,output),costFields=buildDelegationCostFields({raw:{metadata:output.metadata,output,assistant:assistantUsage},model:configuredModel,gate:preHandoffSession?.lastDelegationReason,retry_index:activeWindow?.transientRetryCount,pricing:config3.pricing}),childSessionID=collectSessionIDs(output)[0],recordMaterial=`${sessionId}\x00${input.callID}`;if(costFields.record_id=createHash118("sha256").update(`delegation-cost-id-v1\x00${recordMaterial}`).digest("hex").slice(0,32),costFields.identity_fingerprint=createHash118("sha256").update(`delegation-cost-identity-v1\x00${recordMaterial}\x00${agentName}\x00${configuredModel}`).digest("hex").slice(0,32),costFields.version=1,costFields.parent_session_digest=createHash118("sha256").update(`delegation-cost-parent-v1\x00${sessionId}`).digest("hex").slice(0,32),childSessionID)costFields.child_session_digest=createHash118("sha256").update(`delegation-cost-child-v1\x00${childSessionID}`).digest("hex").slice(0,32);swarmState.activeAgent.set(sessionId,ORCHESTRATOR_NAME),ensureAgentSession(sessionId,ORCHESTRATOR_NAME,bootstrapRoot);let taskSession=swarmState.agentSessions.get(sessionId);if(taskSession){if(taskSession.delegationActive=!1,taskSession.lastAgentEventTime=Date.now(),!backgroundResultIsRunning){let costTaskId=beganDelegation?.taskId||taskSession.currentTaskId||"";if(_delegationTelemetryByCallID.delete(input.callID),telemetry.delegationEnd(sessionId,agentName,costTaskId,"completed",costFields),childSessionID&&costFields.evidence_status!=="complete"&&costFields.record_id&&costFields.identity_fingerprint)trackPendingCostCorrection(childSessionID,{recordId:costFields.record_id,identityFingerprint:costFields.identity_fingerprint,parentSessionId:sessionId,parentSessionDigest:costFields.parent_session_digest,agentName,taskId:costTaskId,model:configuredModel,gate:preHandoffSession?.lastDelegationReason,retryIndex:activeWindow?.transientRetryCount,pricing:config3.pricing,version:1,currentFields:costFields});if(baseAgentName==="reviewer"||baseAgentName==="test_engineer"||baseAgentName==="critic"||baseAgentName==="critic_sounding_board")pushAdvisory(taskSession,`[PIPELINE] ${baseAgentName} delegation complete for task ${taskSession.currentTaskId??"unknown"}. `+"Resume the QA gate pipeline — check your task pipeline steps for the next required action. "+"Do not stop here.");if(baseAgentName==="critic_sounding_board"){let rawResponse=typeof output.output==="string"?output.output:"",parsed=applySoundingBoardResponsePolicy(rawResponse,afterCtx.args);if(parsed){let verdictMsg=`[SOUNDING_BOARD] Verdict: ${parsed.verdict}. ${parsed.reasoning}`;if(parsed.category)verdictMsg+=` Category: ${parsed.category}`;if(parsed.improvedQuestion)verdictMsg+=` Rephrase to: ${parsed.improvedQuestion}`;if(parsed.answer)verdictMsg+=` Answer: ${parsed.answer}`;if(parsed.warning)verdictMsg+=` WARNING: ${parsed.warning}`;pushAdvisory(taskSession,verdictMsg),taskSession.lastDelegationReason="critic_consultation"}else pushAdvisory(taskSession,`[SOUNDING_BOARD] WARNING: Could not parse a structured verdict from critic_sounding_board response (${rawResponse.length} chars). `+"Treat as REPHRASE — review the raw response before surfacing to user or escalating. "+"Do not silently accept as resolved.")}}}if(_dbg)console.error(`[DIAG] Task handoff DONE session=${sessionId} activeAgent=${swarmState.activeAgent.get(sessionId)}`)}if(deleteStoredInputArgs(input.callID),_dbg)console.error(`[DIAG] toolAfter COMPLETE tool=${_toolName}`)},"chat.message":async(input,output)=>{try{if(input?.sessionID&&typeof input?.agent==="string"){let routeModel=resolveTaskRouteModelChain(String(input.agent));if(routeModel){if((await resolveTaskChatModelOverride({childSessionID:String(input.sessionID),role:routeModel.role,primaryModel:routeModel.primaryModel,fallbackModels:routeModel.fallbackModels,lookupParentSessionID:lookupParentSessionIDForTaskRoute})).status==="exhausted"){let error93=Error(`MODEL_FALLBACK_EXHAUSTED: no configured model remains for ${routeModel.role}`);throw error93.name="TaskModelFallbackExhaustedError",error93}}}}catch(error93){if(error93 instanceof Error&&error93.name==="TaskModelFallbackExhaustedError")throw error93}await safeHook(async(input2,output2)=>{if(process.env.DEBUG_SWARM)console.error(`[DIAG] chat.message agent=${input2.agent??"none"} session=${input2.sessionID}`);try{if(input2?.sessionID&&typeof input2?.agent==="string"&&input2.agent.trim()!=="")maybeEmitNonArchitectAdvisory(String(input2.sessionID),String(input2.agent))}catch{}if(input2?.sessionID&&typeof input2?.agent==="string"&&output2&&typeof output2==="object"&&typeof output2.message==="object"&&output2.message!==null){let routeModel=resolveTaskRouteModelChain(String(input2.agent));if(routeModel){let resolution=await resolveTaskChatModelOverride({childSessionID:String(input2.sessionID),role:routeModel.role,primaryModel:routeModel.primaryModel,fallbackModels:routeModel.fallbackModels,lookupParentSessionID:lookupParentSessionIDForTaskRoute});if(resolution.status==="override"&&resolution.model)output2.message.model=resolution.model}}if(input2?.sessionID){let messageModel=output2.message?.model;if(messageModel&&typeof messageModel==="object")setLiveContextWindow(String(input2.sessionID),void 0,{modelID:typeof messageModel.modelID==="string"?messageModel.modelID:typeof messageModel.id==="string"?messageModel.id:void 0,providerID:typeof messageModel.providerID==="string"?messageModel.providerID:void 0})}if(await delegationHandler(input2,output2),input2?.sessionID)try{await cacheCohortIdAtMessage(bootstrapRoot,input2.sessionID)}catch{}try{if(input2?.sessionID&&input2?.agent){if(stripKnownSwarmPrefix(String(input2.agent))==="architect")tickAndMaybeDispatchCadence(bootstrapRoot,input2.sessionID,"architectTurns",config3,{activeAgent:String(input2.agent)})}}catch{}if(process.env.DEBUG_SWARM)console.error(`[DIAG] chat.message DONE agent=${input2.agent??"none"}`)})(input,output)},automation:automationManager}}var src_default={id:"opencode-swarm",server:OpenCodeSwarm};export{schedulePostResolutionTasksForTest,recoverPendingCostCorrectionForTest,recordTestImpactGateGroundTruth,overrideIndexInternalsForTest,loadTier1EvaluationTasks,harnessMutationV1,evaluationV1,evaluatePrReviewRecoveryV1,evaluateCandidateV1,src_default as default,computeEffectiveTruncatableTools,capSessionMap,archiveSqliteSnapshot,applySoundingBoardResponsePolicy,_resetDelegationTelemetryPairingForTesting};
|