opencode-swarm 7.186.3 → 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-3ft68we2.js → auto-checkpoint-3fsd5nhp.js} +7 -7
- package/dist/cli/{checkpoint-27a98tkw.js → checkpoint-cnt2zfc4.js} +12 -12
- package/dist/cli/{coder-settlement-z3r3mx9z.js → coder-settlement-h9t6anbr.js} +8 -8
- package/dist/cli/{config-doctor-d7tpqsk7.js → config-doctor-7vewvger.js} +2 -2
- package/dist/cli/{core-jzvq5n4x.js → core-azfp090f.js} +1 -1
- package/dist/cli/{curation-policy-1zdsb3h0.js → curation-policy-3dvythny.js} +5 -5
- package/dist/cli/{curator-hq3znz6x.js → curator-6347y33h.js} +34 -34
- package/dist/cli/{curator-drift-b3yfwf6r.js → curator-drift-rsh7k3vj.js} +5 -5
- package/dist/cli/{curator-llm-factory-x9xwvhf2.js → curator-llm-factory-bvazaeax.js} +34 -34
- package/dist/cli/{evidence-summary-service-y2c01066.js → evidence-summary-service-71g302wy.js} +15 -15
- package/dist/cli/{gate-evidence-0c3g9dye.js → gate-evidence-zfj7q5f7.js} +5 -5
- package/dist/cli/{guardrail-explain-49cp1v40.js → guardrail-explain-mfgjbr2t.js} +35 -35
- package/dist/cli/{guardrail-log-5vbtcfxm.js → guardrail-log-j0afxr5d.js} +6 -6
- package/dist/cli/{guardrail-reset-fk26vkf9.js → guardrail-reset-mqv4chxa.js} +34 -34
- package/dist/cli/{hive-promoter-tv86mzjk.js → hive-promoter-5t3xhvf5.js} +34 -34
- package/dist/cli/{index-x0aa15wh.js → index-02fema92.js} +3 -3
- package/dist/cli/{index-rm4z4a34.js → index-02stsgw6.js} +4 -4
- package/dist/cli/{index-57f4m0jx.js → index-0ab8x2nj.js} +1 -1
- package/dist/cli/{index-5f27zcmk.js → index-0tccxc8m.js} +1 -1
- package/dist/cli/{index-q5r4713h.js → index-1cdkdha7.js} +4 -4
- package/dist/cli/{index-c0629bpk.js → index-2mtbc0wz.js} +1 -1
- package/dist/cli/{index-4tpwp24b.js → index-4dkmehar.js} +1 -1
- package/dist/cli/{index-xavr110v.js → index-5mh1638n.js} +4 -4
- package/dist/cli/{index-kbcx6rqh.js → index-743kwz1r.js} +2 -2
- package/dist/cli/{index-awhynpzh.js → index-7fk8zcnj.js} +1 -1
- package/dist/cli/{index-vzfwgs6g.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-dvr0qqpd.js → index-92hcbz8j.js} +3 -3
- package/dist/cli/{index-yjgg48mb.js → index-bb2myjge.js} +2 -2
- package/dist/cli/{index-j4m289f6.js → index-dg39ea2t.js} +2 -2
- package/dist/cli/{index-j94gxxr9.js → index-f2nbkpsd.js} +5 -5
- package/dist/cli/{index-sqksezk4.js → index-h9gkgwn6.js} +1 -1
- package/dist/cli/{index-r8eakfzj.js → index-htwb6znd.js} +7 -7
- package/dist/cli/{index-98hksf1k.js → index-j0j82th1.js} +1 -1
- package/dist/cli/{index-jh7zxttz.js → index-j3j3xknh.js} +3 -3
- package/dist/cli/{index-z4mwsjw0.js → index-m47nt45k.js} +4 -4
- package/dist/cli/{index-8ehsv9yw.js → index-m9xhje7p.js} +1 -1
- package/dist/cli/{index-hz5460h6.js → index-mcvp13x7.js} +1 -1
- package/dist/cli/{index-y9wsfekf.js → index-mr86ywsj.js} +1 -1
- package/dist/cli/{index-2jnw5f1m.js → index-ne82w55j.js} +6 -6
- package/dist/cli/{index-0aqhn0vx.js → index-nkr29v6k.js} +3 -3
- package/dist/cli/{index-gagz268y.js → index-p3tkx10s.js} +4 -4
- package/dist/cli/{index-5xqahbey.js → index-qt6101j8.js} +1 -1
- package/dist/cli/{index-30231sgv.js → index-scasxhsf.js} +34 -34
- package/dist/cli/{index-brc3ya4v.js → index-sev04gtf.js} +2 -2
- package/dist/cli/{index-1m3502g5.js → index-tq8f6ar8.js} +3 -3
- package/dist/cli/{index-kfrjsjsq.js → index-tynapn5c.js} +85 -86
- package/dist/cli/{index-k0y18g1z.js → index-v2b00xgq.js} +1 -1
- package/dist/cli/{index-m4x88cwp.js → index-vacbzrma.js} +1 -1
- package/dist/cli/{index-1f7mkb7p.js → index-xdjwefa5.js} +43 -43
- package/dist/cli/{index-s4dd6e7d.js → index-xdtt2xxx.js} +2 -2
- package/dist/cli/{index-y4bn9az1.js → index-xn3axfb7.js} +36 -36
- package/dist/cli/{index-w2vzq8ws.js → index-ys4888ae.js} +3 -3
- package/dist/cli/index.js +35 -35
- package/dist/cli/{knowledge-escalator-2madg0ca.js → knowledge-escalator-d51hm9bf.js} +11 -11
- package/dist/cli/{knowledge-events-gqctvgs7.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-sqp37v4m.js → knowledge-store-5yq3dr0w.js} +5 -5
- package/dist/cli/{knowledge-validator-vm75w5pd.js → knowledge-validator-snb5k0t7.js} +7 -7
- package/dist/cli/{mcp-hd4g629b.js → mcp-85386zbc.js} +1 -1
- package/dist/cli/{model-preflight-a1tdp8za.js → model-preflight-bjcm13dz.js} +34 -34
- package/dist/cli/{pending-delegations-s999zx97.js → pending-delegations-gajb3g07.js} +7 -7
- package/dist/cli/{pr-subscriptions-eyz5vt2e.js → pr-subscriptions-5nxh5d6n.js} +7 -7
- package/dist/cli/{pr-workflow-gate-zynajz1z.js → pr-workflow-gate-2ky49yr6.js} +34 -34
- package/dist/cli/{runner-fbmancth.js → runner-mfxyvzv5.js} +5 -5
- package/dist/cli/{scan-cursor-z9ns85nn.js → scan-cursor-44kwkvzz.js} +6 -6
- package/dist/cli/{schema-fbjzdke4.js → schema-f8rw7sep.js} +1 -1
- package/dist/cli/{scope-persistence-n8deptf7.js → scope-persistence-90yg8kfc.js} +11 -11
- package/dist/cli/{server-34119777.js → server-x5aaqtfp.js} +34 -34
- package/dist/cli/{skill-generator-5wd9jyv0.js → skill-generator-5dytd2v5.js} +13 -13
- package/dist/cli/{snapshot-coordination-init-fehge5m6.js → snapshot-coordination-init-16g8rnk9.js} +34 -34
- package/dist/cli/{speckit-checkoff-4s2pzjh7.js → speckit-checkoff-s06hxcsr.js} +3 -3
- package/dist/cli/{telemetry-3bjvjbcp.js → telemetry-rb8hrvbx.js} +1 -1
- package/dist/cli/{worktree-collision-ownership-4mr9e88y.js → worktree-collision-ownership-rfspbxph.js} +7 -7
- package/dist/cli/{worktree-isolation-ezph1j56.js → worktree-isolation-1bzyww4e.js} +34 -34
- package/dist/index.js +7 -7
- 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.3",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(`
|