opencode-swarm 7.148.2 → 7.148.3
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/dist/cli/{config-doctor-6danhdcy.js → config-doctor-q3fw9744.js} +2 -2
- package/dist/cli/{core-0ghwny8q.js → core-y72nw57z.js} +1 -1
- package/dist/cli/{curator-wvm7qbkk.js → curator-bsr0xx05.js} +17 -17
- package/dist/cli/{curator-llm-factory-6n47j5qn.js → curator-llm-factory-sdxsn88r.js} +17 -17
- package/dist/cli/{evidence-summary-service-0xwrkmf9.js → evidence-summary-service-rk5exnrk.js} +6 -6
- package/dist/cli/{gate-evidence-6e5yhcy6.js → gate-evidence-cn0dvw8m.js} +2 -2
- package/dist/cli/{guardrail-explain-tgv7rvap.js → guardrail-explain-fnnka0vt.js} +18 -18
- package/dist/cli/{guardrail-log-k0zk6rbs.js → guardrail-log-gsx9kj51.js} +3 -3
- package/dist/cli/{guardrail-reset-4fw16xmb.js → guardrail-reset-kk1rdmm0.js} +17 -17
- package/dist/cli/{hive-promoter-zemwxxw1.js → hive-promoter-w7cr6qym.js} +17 -17
- package/dist/cli/{index-nqwn8sf0.js → index-08d3pb9a.js} +1 -1
- package/dist/cli/{index-q6kscnts.js → index-2d582j6q.js} +1 -1
- package/dist/cli/{index-wgrvq2bc.js → index-3vescfdb.js} +4 -4
- package/dist/cli/{index-3pbvdde0.js → index-4aqnb12y.js} +2 -2
- package/dist/cli/{index-mgcffsk0.js → index-65jw48eb.js} +1 -1
- package/dist/cli/{index-hsq8nyen.js → index-7a41ca8k.js} +47 -47
- package/dist/cli/{index-x9jppg8b.js → index-8sz9t8s2.js} +1 -1
- package/dist/cli/{index-mbcyz77e.js → index-8w63kj4x.js} +1 -1
- package/dist/cli/{index-nxydm56k.js → index-8y79znpe.js} +1 -1
- package/dist/cli/{index-crpkb5x6.js → index-afwwz4py.js} +5 -5
- package/dist/cli/{index-k2ad2vtb.js → index-b0703hjg.js} +1 -1
- package/dist/cli/{index-5vyej8pc.js → index-c9xfy8yj.js} +3 -3
- package/dist/cli/{index-x9q0b3a8.js → index-dh85aep3.js} +2 -2
- package/dist/cli/{index-s0s1e5jp.js → index-dmbvep3q.js} +3 -3
- package/dist/cli/{index-s0nss8c4.js → index-et35gcph.js} +1 -1
- package/dist/cli/{index-7jaq84cg.js → index-fp9d0e6f.js} +1 -1
- package/dist/cli/{index-84ytts36.js → index-harsx832.js} +2 -2
- package/dist/cli/{index-xn7h24x4.js → index-hwfs0ze1.js} +3 -3
- package/dist/cli/{index-03wz9h63.js → index-kn36sxj0.js} +19 -19
- package/dist/cli/{index-pzt7ed53.js → index-xq8eydnk.js} +3 -3
- package/dist/cli/{index-ndqhtgrc.js → index-y8kppv1z.js} +1 -1
- package/dist/cli/index.js +17 -17
- package/dist/cli/{knowledge-escalator-rfw35yt1.js → knowledge-escalator-jxpz0mv5.js} +6 -6
- package/dist/cli/{knowledge-events-wmjm5wn6.js → knowledge-events-kjwmc21q.js} +4 -4
- package/dist/cli/{knowledge-store-f2ev6s5p.js → knowledge-store-j9bzs7zx.js} +1 -1
- package/dist/cli/{knowledge-validator-6cmwpx9e.js → knowledge-validator-56w52rwr.js} +2 -2
- package/dist/cli/{scan-cursor-x1ma7edk.js → scan-cursor-7xbrxm2c.js} +2 -2
- package/dist/cli/{schema-g5ggmb47.js → schema-gcjdpfr9.js} +1 -1
- package/dist/cli/{scope-persistence-gt0zpp6a.js → scope-persistence-2n9nk833.js} +4 -4
- package/dist/cli/{skill-generator-q6m110d5.js → skill-generator-z70bhhx9.js} +7 -7
- package/dist/cli/{worktree-isolation-akwwt8n5.js → worktree-isolation-vg6g00mq.js} +17 -17
- package/dist/index.js +2 -2
- 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.148.2",description:"Architect-centric agentic swarm plugin for OpenCode - hub-and-spoke orchestration with SME consultation, code generation, and QA review",main:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",default:"./dist/index.js"},"./package.json":"./package.json"},bin:{"opencode-swarm":"./dist/cli/index.js"},type:"module",engines:{bun:">=1.3.13"},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/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/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","README.md","LICENSE"],scripts:{clean:`bun -e "require('fs').rmSync('dist',{recursive:true,force:true})"`,build:"bun run clean && 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","drift:check":"bun run scripts/drift-check.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: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","check:events":"bun run scripts/check-event-contract.ts","check:retention":"bun run scripts/check-retention-registry.ts","check:test-file-cap":"bun run scripts/check-test-file-cap.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:memory-recall":"bun run scripts/memory-recall-regression.ts"},dependencies:{"@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.1.8"},devDependencies:{"@biomejs/biome":"2.3.14","@types/picomatch":"^4.0.3","bun-types":"1.3.8","js-yaml":"^4.1.1",typescript:"^5.7.3"},peerDependencies:{"@xenova/transformers":"^2.17.2"},peerDependenciesMeta:{"@xenova/transformers":{optional:!0}}}});var QA_AGENTS,PIPELINE_AGENTS,ORCHESTRATOR_NAME="architect",ALL_SUBAGENT_NAMES,ALL_AGENT_NAMES;var init_agent_names=__esm(()=>{QA_AGENTS=["reviewer","critic","critic_oversight","critic_finding_validator"],PIPELINE_AGENTS=["explorer","coder","test_engineer"],ALL_SUBAGENT_NAMES=["sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","curator_postmortem","curator_consolidation","council_generalist","council_skeptic","council_domain_expert","skill_improver","spec_writer",...QA_AGENTS,...PIPELINE_AGENTS],ALL_AGENT_NAMES=["architect",...ALL_SUBAGENT_NAMES]});function getPrWorkflowToolCapability(toolName,mode){let metadata=TOOL_METADATA[toolName];if(!metadata?.prWorkflow?.modes.includes(mode))return null;return metadata.prWorkflow.capability}var TOOL_METADATA,TOOL_NAMES,TOOL_NAME_SET,TOOL_DESCRIPTIONS,AGENT_TOOL_MAP;var init_tool_metadata=__esm(()=>{init_agent_names();TOOL_METADATA={diff:{description:"structured git diff with contract change detection",agents:["architect","reviewer","critic_finding_validator","critic_oversight","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},diff_summary:{description:"filter classified AST changes by category, risk level, or file for reviewer drill-down",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},syntax_check:{description:"check syntax of source files using tree-sitter parsers across multiple languages, returning per-file errors",agents:["architect","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},placeholder_scan:{description:"todo and FIXME comment detection",agents:["architect","reviewer","critic_finding_validator"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},imports:{description:"find all consumers that import from a given file — use before refactoring shared modules to avoid breaking unseen dependents",agents:["architect","sme","researcher","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},lint:{description:"run project linter in check or fix mode; supports biome, eslint, ruff, clippy, and more, returns structured results",agents:["architect","reviewer","critic_finding_validator","coder"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},secretscan:{description:"scan for secrets (API keys, tokens, passwords) via regex and entropy; returns redacted previews, excludes common dirs",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},sast_scan:{description:"static analysis security scan",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},build_check:{description:"discover and run build, typecheck, and test commands for various project ecosystems in the working directory",agents:["architect","coder","test_engineer"]},pre_check_batch:{description:"parallel verification: lint:check + secretscan + sast_scan + quality_budget",agents:["architect","reviewer","critic_finding_validator"]},quality_budget:{description:"code quality budget check",agents:["architect"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},symbols:{description:"extract exported symbols (functions, classes, interfaces, types) from source files; supports TypeScript, JavaScript, and Python",agents:["architect","sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},complexity_hotspots:{description:"git churn × complexity risk map",agents:["architect","sme","researcher","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","critic_oversight","explorer","test_engineer"]},schema_drift:{description:"OpenAPI spec vs route drift",agents:["architect","sme","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},todo_extract:{description:"structured TODO/FIXME extraction",agents:["architect","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},evidence_check:{description:"verify task evidence completeness",agents:["architect","critic_oversight"]},check_gate_status:{description:"check the gate status of a specific task",agents:["architect","critic_oversight"]},completion_verify:{description:"verify completed tasks have required evidence",agents:["architect","critic_oversight"]},complete_pr_workflow:{description:"validate terminal PR workflow evidence and clear its durable session gate",agents:["architect"]},abort_pr_workflow:{description:"abort an unrecoverable PR_REVIEW/PR_FEEDBACK mechanical gate and clear its durable session state",agents:["architect"]},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)",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"]},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) so the /swarm issue --trace workflow can satisfy its recurrence gate before commit-pr handoff",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",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 corrupt exact-task gate evidence and install a fresh blocked generation that requires every gate to rerun",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"]},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, 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. 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"],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, and profile hash. 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_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 so you can keep working; launch_timeout_ms is only a promptAsync acceptance budget, not a lane runtime timeout; poll incrementally with collect_lane_results (wait omitted or false) while doing independent investigation, or join with wait: true when you need all results",agents:["architect"]},collect_lane_results:{description:"collect or poll results for a dispatch_lanes_async batch; supports both non-blocking polling (wait omitted or false) and blocking join (wait: true). Non-blocking polls include pending lane identities by default and process settled lanes incrementally while continuing independent work; busy/retry lanes are not timed out just because they run for a long time. Does not advance workflow gates. Inline output for a settled lane is delivered only once: later polls of the same lane set output_omitted_repeat: true and omit output, but still include output_ref for recovery 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_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 deepMergeInternal(base,override,depth){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);else result[key]=overrideVal}return result}function deepMerge(base,override){if(!base)return override;if(!override)return base;return deepMergeInternal(base,override,0)}var MAX_MERGE_DEPTH=10;function freezeSet(items){let set=new Set(items),proxy=new Proxy(set,{get(target,prop){if(prop==="add"||prop==="delete"||prop==="clear")return()=>{throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS 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("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},deleteProperty(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},defineProperty(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},setPrototypeOf(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS 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,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,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.148.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"},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/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/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","README.md","LICENSE"],scripts:{clean:`bun -e "require('fs').rmSync('dist',{recursive:true,force:true})"`,build:"bun run clean && 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","drift:check":"bun run scripts/drift-check.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: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","check:events":"bun run scripts/check-event-contract.ts","check:retention":"bun run scripts/check-retention-registry.ts","check:test-file-cap":"bun run scripts/check-test-file-cap.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:memory-recall":"bun run scripts/memory-recall-regression.ts"},dependencies:{"@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.1.8"},devDependencies:{"@biomejs/biome":"2.3.14","@types/picomatch":"^4.0.3","bun-types":"1.3.8","js-yaml":"^4.1.1",typescript:"^5.7.3"},peerDependencies:{"@xenova/transformers":"^2.17.2"},peerDependenciesMeta:{"@xenova/transformers":{optional:!0}}}});var QA_AGENTS,PIPELINE_AGENTS,ORCHESTRATOR_NAME="architect",ALL_SUBAGENT_NAMES,ALL_AGENT_NAMES;var init_agent_names=__esm(()=>{QA_AGENTS=["reviewer","critic","critic_oversight","critic_finding_validator"],PIPELINE_AGENTS=["explorer","coder","test_engineer"],ALL_SUBAGENT_NAMES=["sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","curator_postmortem","curator_consolidation","council_generalist","council_skeptic","council_domain_expert","skill_improver","spec_writer",...QA_AGENTS,...PIPELINE_AGENTS],ALL_AGENT_NAMES=["architect",...ALL_SUBAGENT_NAMES]});function getPrWorkflowToolCapability(toolName,mode){let metadata=TOOL_METADATA[toolName];if(!metadata?.prWorkflow?.modes.includes(mode))return null;return metadata.prWorkflow.capability}var TOOL_METADATA,TOOL_NAMES,TOOL_NAME_SET,TOOL_DESCRIPTIONS,AGENT_TOOL_MAP;var init_tool_metadata=__esm(()=>{init_agent_names();TOOL_METADATA={diff:{description:"structured git diff with contract change detection",agents:["architect","reviewer","critic_finding_validator","critic_oversight","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},diff_summary:{description:"filter classified AST changes by category, risk level, or file for reviewer drill-down",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},syntax_check:{description:"check syntax of source files using tree-sitter parsers across multiple languages, returning per-file errors",agents:["architect","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},placeholder_scan:{description:"todo and FIXME comment detection",agents:["architect","reviewer","critic_finding_validator"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},imports:{description:"find all consumers that import from a given file — use before refactoring shared modules to avoid breaking unseen dependents",agents:["architect","sme","researcher","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},lint:{description:"run project linter in check or fix mode; supports biome, eslint, ruff, clippy, and more, returns structured results",agents:["architect","reviewer","critic_finding_validator","coder"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},secretscan:{description:"scan for secrets (API keys, tokens, passwords) via regex and entropy; returns redacted previews, excludes common dirs",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},sast_scan:{description:"static analysis security scan",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},build_check:{description:"discover and run build, typecheck, and test commands for various project ecosystems in the working directory",agents:["architect","coder","test_engineer"]},pre_check_batch:{description:"parallel verification: lint:check + secretscan + sast_scan + quality_budget",agents:["architect","reviewer","critic_finding_validator"]},quality_budget:{description:"code quality budget check",agents:["architect"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},symbols:{description:"extract exported symbols (functions, classes, interfaces, types) from source files; supports TypeScript, JavaScript, and Python",agents:["architect","sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},complexity_hotspots:{description:"git churn × complexity risk map",agents:["architect","sme","researcher","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","critic_oversight","explorer","test_engineer"]},schema_drift:{description:"OpenAPI spec vs route drift",agents:["architect","sme","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},todo_extract:{description:"structured TODO/FIXME extraction",agents:["architect","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},evidence_check:{description:"verify task evidence completeness",agents:["architect","critic_oversight"]},check_gate_status:{description:"check the gate status of a specific task",agents:["architect","critic_oversight"]},completion_verify:{description:"verify completed tasks have required evidence",agents:["architect","critic_oversight"]},complete_pr_workflow:{description:"validate terminal PR workflow evidence and clear its durable session gate",agents:["architect"]},abort_pr_workflow:{description:"abort an unrecoverable PR_REVIEW/PR_FEEDBACK mechanical gate and clear its durable session state",agents:["architect"]},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)",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"]},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) so the /swarm issue --trace workflow can satisfy its recurrence gate before commit-pr handoff",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",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 corrupt exact-task gate evidence and install a fresh blocked generation that requires every gate to rerun",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"]},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, 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. 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"],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, and profile hash. 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_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 so you can keep working; launch_timeout_ms is only a promptAsync acceptance budget, not a lane runtime timeout; poll incrementally with collect_lane_results (wait omitted or false) while doing independent investigation, or join with wait: true when you need all results",agents:["architect"]},collect_lane_results:{description:"collect or poll results for a dispatch_lanes_async batch; supports both non-blocking polling (wait omitted or false) and blocking join (wait: true). Non-blocking polls include pending lane identities by default and process settled lanes incrementally while continuing independent work; busy/retry lanes are not timed out just because they run for a long time. Does not advance workflow gates. Inline output for a settled lane is delivered only once: later polls of the same lane set output_omitted_repeat: true and omit output, but still include output_ref for recovery 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_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 deepMergeInternal(base,override,depth){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);else result[key]=overrideVal}return result}function deepMerge(base,override){if(!base)return override;if(!override)return base;return deepMergeInternal(base,override,0)}var MAX_MERGE_DEPTH=10;function freezeSet(items){let set=new Set(items),proxy=new Proxy(set,{get(target,prop){if(prop==="add"||prop==="delete"||prop==="clear")return()=>{throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS 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("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},deleteProperty(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},defineProperty(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},setPrototypeOf(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS 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,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,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
|
|
|
@@ -6315,7 +6315,7 @@ ${instruction}`}async function sendWakePrompt(sessionID,events,messageID){let ac
|
|
|
6315
6315
|
`);default:return null}}var CLEAR_UNADDRESSED_DELAY_MS=2000,MAX_PENDING_CLEARS=200,pendingClears,_internals168,AUTO_PR_FEEDBACK_EVENTS,EVENT_CONFIG_MAP,CONTENT_EVENT_TYPES;var init_pr_event_subscribers=__esm(()=>{init_pr_workflow_gate();init_state2();init_utils();init_event_bus();init_pr_event_delivery();init_pr_feedback_event_queue();init_pr_subscriptions();pendingClears=new Map,_internals168={handlePrEvent,getGlobalEventBus,listActive,updateSnapshot,getAgentSession,readPrWorkflowGateState,activatePrWorkflow,enqueuePrFeedbackMonitorEvent,deliverPrActivity,isPrEventDeliveryRegistered,scheduleClearUnaddressed,clearUnaddressedDelayMs:CLEAR_UNADDRESSED_DELAY_MS,log,formatAdvisory},AUTO_PR_FEEDBACK_EVENTS=new Set(["pr.ci.failed","pr.merge.conflict"]),EVENT_CONFIG_MAP={"pr.ci.failed":"notify_ci_failure","pr.ci.passed":"notify_ci_success","pr.new.comment":"notify_new_comments","pr.merge.conflict":"notify_merge_conflict","pr.merge.conflict_resolved":"notify_merge_conflict","pr.review.changes_requested":"notify_review_activity","pr.review.approved":"notify_review_activity","pr.merged":"notify_merged","pr.closed":"notify_closed"};CONTENT_EVENT_TYPES=new Set(["pr.new.comment","pr.review.changes_requested","pr.review.approved","pr.review.comment"])});var exports_status_artifact={};__export(exports_status_artifact,{AutomationStatusArtifact:()=>AutomationStatusArtifact});import*as fs115 from"node:fs";import*as path218 from"node:path";function createEmptySnapshot(mode,capabilities){return{timestamp:Date.now(),mode,enabled:mode!=="manual",currentPhase:0,lastTrigger:null,pendingActions:0,lastOutcome:null,capabilities}}function validateFilename(filename){if(filename.includes("\x00"))throw Error("Invalid filename: contains null byte");let pathSeparators=["/","\\",".."];for(let sep41 of pathSeparators)if(filename.includes(sep41))throw Error(`Invalid filename: contains path separator '${sep41}'`);if(filename.startsWith("/")||filename.startsWith("\\")||/^[a-zA-Z]:/.test(filename))throw Error("Invalid filename: absolute paths not allowed");if(filename.length>MAX_FILENAME_LENGTH)throw Error(`Invalid filename: exceeds maximum length of ${MAX_FILENAME_LENGTH} characters`);if(!SAFE_FILENAME_PATTERN.test(filename))throw Error("Invalid filename: contains unsafe characters");if(filename.includes("/")||filename.includes("\\"))throw Error("Invalid filename: path separators not allowed");if(!filename.trim()||filename.trim()!==filename)throw Error("Invalid filename: cannot be empty or contain leading/trailing whitespace");return filename}class AutomationStatusArtifact{swarmDir;filename;currentSnapshot;constructor(swarmDir,filename="automation-status.json"){let sanitizedFilename=validateFilename(filename);this.swarmDir=swarmDir,this.filename=sanitizedFilename,this.currentSnapshot=this.load()??createEmptySnapshot("manual",{plan_sync:!1,phase_preflight:!1,config_doctor_on_startup:!1,config_doctor_autofix:!1,evidence_auto_summaries:!1,decision_drift_detection:!1})}getFilePath(){return path218.join(this.swarmDir,this.filename)}load(){let filePath=this.getFilePath();try{if(fs115.existsSync(filePath)){let content=fs115.readFileSync(filePath,"utf-8");return JSON.parse(content)}}catch{}return null}write(){let filePath=this.getFilePath();if(!fs115.existsSync(this.swarmDir))fs115.mkdirSync(this.swarmDir,{recursive:!0});fs115.writeFileSync(filePath,JSON.stringify(this.currentSnapshot,null,2),"utf-8")}getSnapshot(){return{...this.currentSnapshot}}read(){let loaded=this.load();if(loaded)this.currentSnapshot=loaded;return this.getSnapshot()}updateConfig(mode,capabilities){this.currentSnapshot={...this.currentSnapshot,mode,enabled:mode!=="manual",timestamp:Date.now(),capabilities},this.write()}updatePhase(phase){this.currentSnapshot={...this.currentSnapshot,currentPhase:phase,timestamp:Date.now()},this.write()}recordTrigger(triggeredAt,triggeredPhase,source,reason){this.currentSnapshot={...this.currentSnapshot,lastTrigger:{triggeredAt,triggeredPhase,source,reason},timestamp:Date.now()},this.write()}updatePendingActions(count){this.currentSnapshot={...this.currentSnapshot,pendingActions:count,timestamp:Date.now()},this.write()}recordOutcome(state,phase,message){this.currentSnapshot={...this.currentSnapshot,lastOutcome:{state,phase,outcomeAt:Date.now(),message:message??null},timestamp:Date.now()},this.write()}clearOutcome(){this.currentSnapshot={...this.currentSnapshot,lastOutcome:{state:"none",phase:null,outcomeAt:null,message:null},timestamp:Date.now()},this.write()}isEnabled(){return this.currentSnapshot.enabled}hasCapability(capability){return this.currentSnapshot.capabilities[capability]===!0}getGuiSummary(){let{currentSnapshot}=this,status="Disabled";if(currentSnapshot.enabled)status=currentSnapshot.mode.charAt(0).toUpperCase()+currentSnapshot.mode.slice(1);let lastTrigger=null;if(currentSnapshot.lastTrigger?.triggeredAt)lastTrigger=new Date(currentSnapshot.lastTrigger.triggeredAt).toLocaleTimeString();let outcome=null;if(currentSnapshot.lastOutcome?.state&¤tSnapshot.lastOutcome.state!=="none")outcome=currentSnapshot.lastOutcome.state;return{status,phase:currentSnapshot.currentPhase,lastTrigger,pending:currentSnapshot.pendingActions,outcome}}}var MAX_FILENAME_LENGTH=255,SAFE_FILENAME_PATTERN;var init_status_artifact=__esm(()=>{SAFE_FILENAME_PATTERN=/^[a-zA-Z0-9._-]+$/});var exports_trigger={};__export(exports_trigger,{PreflightTriggerManager:()=>PreflightTriggerManager,PhaseBoundaryTrigger:()=>PhaseBoundaryTrigger});class PhaseBoundaryTrigger{eventBus;config;lastKnownPhase=0;lastTriggeredPhase=0;constructor(eventBus,config3){this.eventBus=eventBus??getGlobalEventBus(),this.config={minCompletedTasksThreshold:config3?.minCompletedTasksThreshold??1,allowZeroTaskTrigger:config3?.allowZeroTaskTrigger??!1}}setCurrentPhase(phase){this.lastKnownPhase=phase}getCurrentPhase(){return this.lastKnownPhase}get lastTriggeredPhaseValue(){return this.lastTriggeredPhase}detectBoundary(newPhase,completedTasks,totalTasks){if(newPhase===this.lastKnownPhase)return{detected:!1,previousPhase:this.lastKnownPhase,currentPhase:newPhase,reason:"Phase unchanged",completedTaskCount:completedTasks,totalTaskCount:totalTasks};let boundaryResult={detected:!0,previousPhase:this.lastKnownPhase,currentPhase:newPhase,reason:`Phase transition from ${this.lastKnownPhase} to ${newPhase}`,completedTaskCount:completedTasks,totalTaskCount:totalTasks};return this.lastKnownPhase=newPhase,this.eventBus.publish("phase.boundary.detected",boundaryResult),boundaryResult}shouldTriggerPreflight(boundaryResult){if(this.lastTriggeredPhase===boundaryResult.currentPhase)return log("[Trigger] Preflight already triggered for phase",{phase:boundaryResult.currentPhase}),!1;let threshold=this.config.minCompletedTasksThreshold??1;if(!(this.config.allowZeroTaskTrigger||boundaryResult.completedTaskCount>=threshold))return log("[Trigger] Preflight skipped - insufficient task completion",{completed:boundaryResult.completedTaskCount,required:threshold}),!1;return!0}markTriggered(phase){this.lastTriggeredPhase=phase}reset(){this.lastKnownPhase=0,this.lastTriggeredPhase=0}}class PreflightTriggerManager{automationConfig;eventBus;trigger;requestQueue;requestCounter=0;preflightHandler=null;unsubscribe=null;unsubscribeSkipped=null;constructor(automationConfig,eventBus,triggerConfig){this.automationConfig=automationConfig,this.eventBus=eventBus??getGlobalEventBus(),this.trigger=new PhaseBoundaryTrigger(this.eventBus,triggerConfig),this.requestQueue=new AutomationQueue({maxSize:100,defaultMaxRetries:3,overflowStrategy:"evict-oldest"}),this.unsubscribeSkipped=this.eventBus.subscribe("preflight.skipped",(event)=>{let payload=event.payload;if(payload.reason==="queue_overflow"||payload.reason==="queue_enqueue_error")criticalWarn("[PreflightTrigger] preflight skipped",{reason:payload.reason,phase:payload.phase,requestId:payload.requestId,queueDepth:this.requestQueue.size()})})}isEnabled(){if(!this.automationConfig)return!1;if(!this.automationConfig.capabilities)return!1;if(this.automationConfig.mode==="manual")return!1;return this.automationConfig.capabilities.phase_preflight===!0}getMode(){if(!this.automationConfig)return"unknown";return this.automationConfig.mode??"unknown"}updatePhase(phase){this.trigger.setCurrentPhase(phase)}async checkAndTrigger(currentPhase,completedTasks,totalTasks){let phasePreflight=this.automationConfig?.capabilities?.phase_preflight,mode=this.automationConfig?.mode;if(!this.isEnabled())return log("[PreflightTrigger] Disabled via feature flags",{mode:mode??"unknown",phase_preflight:phasePreflight}),await this.eventBus.publish("preflight.skipped",{reason:"feature_disabled",mode:mode??"unknown",phase_preflight:phasePreflight}),!1;let boundaryResult=this.trigger.detectBoundary(currentPhase,completedTasks,totalTasks);if(!boundaryResult.detected)return!1;if(!this.trigger.shouldTriggerPreflight(boundaryResult))return await this.eventBus.publish("preflight.skipped",{reason:"threshold_not_met",boundary:boundaryResult}),!1;return this.triggerPreflight(boundaryResult)}async triggerPreflight(boundaryResult){let requestId=`preflight-${Date.now()}-${++this.requestCounter}`,request={id:requestId,triggeredAt:Date.now(),currentPhase:boundaryResult.currentPhase,source:"phase_boundary",reason:boundaryResult.reason,metadata:{completedTaskCount:boundaryResult.completedTaskCount,totalTaskCount:boundaryResult.totalTaskCount}};try{this.requestQueue.enqueue(request,"high")}catch(error93){log("[PreflightTrigger] Queue enqueue failed (continuing)",{requestId,phase:boundaryResult.currentPhase,error:error93 instanceof Error?error93.message:String(error93)}),await this.eventBus.publish("preflight.skipped",{reason:"queue_enqueue_error",requestId,phase:boundaryResult.currentPhase})}return this.trigger.markTriggered(boundaryResult.currentPhase),await this.eventBus.publish("preflight.requested",request),await this.eventBus.publish("preflight.triggered",{requestId,phase:boundaryResult.currentPhase,timestamp:request.triggeredAt}),log("[PreflightTrigger] Preflight triggered",{requestId,phase:boundaryResult.currentPhase,completed:boundaryResult.completedTaskCount,total:boundaryResult.totalTaskCount}),!0}getPendingRequests(){return this.requestQueue.getAll().map((item)=>item.payload)}getQueueSize(){return this.requestQueue.size()}getStats(){let mode="unknown";try{mode=this.getMode()}catch{mode="unknown"}return{enabled:this.isEnabled(),mode,currentPhase:this.trigger.getCurrentPhase(),lastTriggeredPhase:this.trigger.lastTriggeredPhaseValue,pendingRequests:this.getQueueSize()}}reset(){if(this.trigger.reset(),this.requestQueue.clear(),this.unsubscribe)this.unsubscribe(),this.unsubscribe=null;if(this.unsubscribeSkipped)this.unsubscribeSkipped(),this.unsubscribeSkipped=null}registerHandler(handler){if(this.unsubscribe)this.unsubscribe();this.preflightHandler=handler;let HANDLER_TIMEOUT_MS=120000;this.unsubscribe=this.eventBus.subscribe("preflight.requested",async(event)=>{let request=event.payload,timeoutHandle;try{if(this.preflightHandler)await Promise.race([this.preflightHandler(request),new Promise((_,reject)=>{timeoutHandle=setTimeout(()=>{reject(Error(`Preflight handler timed out after ${HANDLER_TIMEOUT_MS}ms`))},HANDLER_TIMEOUT_MS)})])}catch(error93){log("[PreflightTrigger] Handler error",{requestId:request.id,phase:request.currentPhase,errorType:error93 instanceof Error?error93.name:"unknown"})}finally{clearTimeout(timeoutHandle);let match=this.requestQueue.getAll().find((it)=>it.payload.id===request.id);if(match)this.requestQueue.complete(match.id)}}),log("[PreflightTrigger] Handler registered")}unregisterHandler(){if(this.unsubscribe)this.unsubscribe(),this.unsubscribe=null;this.preflightHandler=null,log("[PreflightTrigger] Handler unregistered")}hasHandler(){return this.preflightHandler!==null}}var init_trigger=__esm(()=>{init_utils();init_event_bus();init_queue()});function truncateWords(text,maxWords){let trimmed=text.trim();if(trimmed.length===0)return{text:trimmed,truncated:!1};let words=trimmed.split(/\s+/);if(words.length<=maxWords)return{text:trimmed,truncated:!1};return{text:`${words.slice(0,maxWords).join(" ")}…`,truncated:!0}}function capArray(items,maxItems){if(items.length<=maxItems)return{items,truncated:!1};return{items:items.slice(0,maxItems),truncated:!0}}function normalizeAgentWorkSummary(input,maxSummaryWords=MAX_AGENT_SUMMARY_WORDS){let truncated=!1,sum=truncateWords(input.summary,maxSummaryWords);truncated||=sum.truncated;let cap2=(items)=>{let r=capArray(items??[],MAX_LIST_ITEMS);return truncated||=r.truncated,r.items},candidate2={schema_version:SUMMARY_SCHEMA_VERSION,phase:input.phase,task_id:input.task_id,session_id:input.session_id,agent:input.agent,parent_agent:input.parent_agent,summary:sum.text,key_decisions:cap2(input.key_decisions),constraints_observed:cap2(input.constraints_observed),constraints_violated:cap2(input.constraints_violated),assumptions:cap2(input.assumptions),risks:cap2(input.risks),files_touched:input.files_touched?capArray(input.files_touched,50).items:void 0,evidence_refs:capArray(input.evidence_refs??[],20).items,created_at:input.created_at??new Date().toISOString(),truncated:truncated||void 0};return AgentWorkSummarySchema.parse(candidate2)}var SUMMARY_SCHEMA_VERSION="1.0.0",MAX_AGENT_SUMMARY_WORDS=100,MAX_PHASE_SUMMARY_WORDS=250,MAX_LIST_ITEMS=5,SupervisorVerdictSchema,AgentWorkSummarySchema,PhaseArchitectureSummarySchema,SupervisorFindingSchema,KnowledgeRecommendationSchema,EvidenceProvenanceSchema,ArchitectureSupervisorReportSchema;var init_schema3=__esm(()=>{init_zod();SupervisorVerdictSchema=exports_external.enum(["APPROVE","CONCERNS","REJECT"]);AgentWorkSummarySchema=exports_external.object({schema_version:exports_external.literal(SUMMARY_SCHEMA_VERSION),phase:exports_external.number().int().min(0).max(999),task_id:exports_external.string().min(1).optional(),session_id:exports_external.string().min(1),agent:exports_external.string().min(1),parent_agent:exports_external.string().min(1).optional(),summary:exports_external.string().min(1),key_decisions:exports_external.array(exports_external.string().min(1)).max(MAX_LIST_ITEMS).default([]),constraints_observed:exports_external.array(exports_external.string().min(1)).max(MAX_LIST_ITEMS).default([]),constraints_violated:exports_external.array(exports_external.string().min(1)).max(MAX_LIST_ITEMS).default([]),assumptions:exports_external.array(exports_external.string().min(1)).max(MAX_LIST_ITEMS).default([]),risks:exports_external.array(exports_external.string().min(1)).max(MAX_LIST_ITEMS).default([]),files_touched:exports_external.array(exports_external.string().min(1)).max(50).optional(),evidence_refs:exports_external.array(exports_external.string().min(1)).max(20).default([]),created_at:exports_external.string().datetime(),truncated:exports_external.boolean().optional()});PhaseArchitectureSummarySchema=exports_external.object({schema_version:exports_external.literal(SUMMARY_SCHEMA_VERSION),phase:exports_external.number().int().min(0).max(999),summary:exports_external.string().default(""),agents_seen:exports_external.array(exports_external.string().min(1)).default([]),tasks_seen:exports_external.array(exports_external.string().min(1)).default([]),key_decisions:exports_external.array(exports_external.string().min(1)).default([]),conflicts:exports_external.array(exports_external.string().min(1)).default([]),unresolved_risks:exports_external.array(exports_external.string().min(1)).default([]),constraint_violations:exports_external.array(exports_external.string().min(1)).default([]),evidence_refs:exports_external.array(exports_external.string().min(1)).default([]),created_at:exports_external.string().datetime()}),SupervisorFindingSchema=exports_external.object({severity:exports_external.enum(["low","medium","high","critical"]),category:exports_external.string().min(1),agents:exports_external.array(exports_external.string().min(1)).default([]),tasks:exports_external.array(exports_external.string().min(1)).default([]),evidence_refs:exports_external.array(exports_external.string().min(1)).default([]),description:exports_external.string().min(1),recommendation:exports_external.string().default("")}),KnowledgeRecommendationSchema=exports_external.object({lesson:exports_external.string().min(1),target_agents:exports_external.array(exports_external.string().min(1)).default([]),confidence:exports_external.number().min(0).max(1).default(0.5),evidence_refs:exports_external.array(exports_external.string().min(1)).default([])}),EvidenceProvenanceSchema=exports_external.object({agent_name:exports_external.string().min(1).optional(),session_id:exports_external.string().min(1).optional(),captured_at:exports_external.string().datetime().optional()}),ArchitectureSupervisorReportSchema=exports_external.object({schema_version:exports_external.literal(SUMMARY_SCHEMA_VERSION),phase:exports_external.number().int().min(0).max(999),verdict:SupervisorVerdictSchema,findings:exports_external.array(SupervisorFindingSchema).default([]),knowledge_recommendations:exports_external.array(KnowledgeRecommendationSchema).default([]),created_at:exports_external.string().datetime(),provenance:EvidenceProvenanceSchema.optional()})});import{existsSync as existsSync118,mkdirSync as mkdirSync65,readFileSync as readFileSync92}from"node:fs";import*as path229 from"node:path";function writeRawSidecar(absPath,bundle){mkdirSync65(path229.dirname(absPath),{recursive:!0}),atomicWriteSwarmFileSync(absPath,JSON.stringify(bundle,null,2))}async function writeAgentSummary(directory,summary){let taskId=summary.task_id??`phase-${summary.phase}-summaries`;return await saveEvidence(directory,taskId,{task_id:taskId,type:"note",timestamp:summary.created_at,agent:summary.agent,verdict:"info",summary:summary.summary,metadata:{kind:AGENT_SUMMARY_METADATA_KIND,phase:summary.phase,session_id:summary.session_id,payload:summary}}),taskId}async function listAgentSummaries(directory,filter={}){let taskIds=await listEvidenceTaskIds(directory),results=[];for(let taskId of taskIds){let loaded=await loadEvidence(directory,taskId);if(loaded.status!=="found")continue;for(let entry of loaded.bundle.entries){if(entry.type!=="note")continue;let meta3=entry.metadata;if(!meta3||meta3.kind!==AGENT_SUMMARY_METADATA_KIND)continue;if(filter.phase!==void 0&&meta3.phase!==filter.phase)continue;if(filter.session!==void 0&&meta3.session_id!==filter.session)continue;let parsed=AgentWorkSummarySchema.safeParse(meta3.payload);if(!parsed.success){warn(`Skipping malformed agent summary in task ${taskId}: ${parsed.error.issues.map((i)=>i.message).join(", ")}`);continue}results.push(parsed.data)}}return results}function writePhaseArchitectureSummary(directory,summary){let rel=path229.join("evidence",String(summary.phase),PHASE_SUMMARY_FILE),abs=validateSwarmPath(directory,rel);return writeRawSidecar(abs,summary),abs}function writeSupervisorReport(directory,report){let rel=path229.join("evidence",String(report.phase),SUPERVISOR_REPORT_FILE),abs=validateSwarmPath(directory,rel),bundle={entries:[{type:SUPERVISOR_ENTRY_TYPE,phase_number:report.phase,scope:"phase",timestamp:report.created_at,verdict:report.verdict,findings:report.findings,knowledge_recommendations:report.knowledge_recommendations,...report.provenance?{provenance:report.provenance}:{}}]};return writeRawSidecar(abs,bundle),abs}function readSupervisorReportRaw(directory,phase){let rel=path229.join("evidence",String(phase),SUPERVISOR_REPORT_FILE),abs;try{abs=validateSwarmPath(directory,rel)}catch{return null}if(!existsSync118(abs))return null;try{return JSON.parse(readFileSync92(abs,"utf-8")).entries?.find((e)=>e.type===SUPERVISOR_ENTRY_TYPE)??null}catch{return null}}var AGENT_SUMMARY_METADATA_KIND="agent_summary",PHASE_SUMMARY_FILE="phase-architecture-summary.json",SUPERVISOR_REPORT_FILE="architecture-supervisor.json",SUPERVISOR_ENTRY_TYPE="architecture-supervisor";var init_store4=__esm(()=>{init_manager2();init_utils2();init_utils();init_atomic_write();init_schema3()});var exports_aggregate={};__export(exports_aggregate,{aggregatePhaseSummary:()=>aggregatePhaseSummary});function dedupe2(values){return Array.from(new Set(values)).filter((v)=>v.trim().length>0)}function detectConflicts(summaries){let observedBy=new Map,violatedBy=new Map;for(let s of summaries){for(let c of s.constraints_observed){if(!observedBy.has(c))observedBy.set(c,new Set);observedBy.get(c)?.add(s.agent)}for(let c of s.constraints_violated){if(!violatedBy.has(c))violatedBy.set(c,new Set);violatedBy.get(c)?.add(s.agent)}}let conflicts=[];for(let[constraint,violators]of violatedBy){let observers=observedBy.get(constraint);if(observers&&observers.size>0){let obs=Array.from(observers).sort().join(", "),vio=Array.from(violators).sort().join(", ");conflicts.push(`Constraint "${constraint}" observed by [${obs}] but violated by [${vio}]`)}}return conflicts.sort()}async function aggregatePhaseSummary(directory,phase,options={}){let summaries=await listAgentSummaries(directory,{phase});if(summaries.length===0)return null;let agentsSeen=dedupe2(summaries.map((s)=>s.agent)).sort(),tasksSeen=dedupe2(summaries.map((s)=>s.task_id).filter((t)=>Boolean(t))).sort(),keyDecisions=dedupe2(summaries.flatMap((s)=>s.key_decisions)),unresolvedRisks=dedupe2(summaries.flatMap((s)=>s.risks)),constraintViolations=dedupe2(summaries.flatMap((s)=>s.constraints_violated)),evidenceRefs=dedupe2(summaries.flatMap((s)=>s.evidence_refs)),conflicts=detectConflicts(summaries),headline=`Phase ${phase}: ${summaries.length} agent summary(ies) across ${tasksSeen.length} task(s); ${constraintViolations.length} constraint violation(s), ${conflicts.length} cross-agent conflict(s).`,cap2=options.maxPhaseSummaryWords??MAX_PHASE_SUMMARY_WORDS,summaryText=truncateWords(headline,cap2).text,phaseSummary={schema_version:SUMMARY_SCHEMA_VERSION,phase,summary:summaryText,agents_seen:agentsSeen,tasks_seen:tasksSeen,key_decisions:keyDecisions,conflicts,unresolved_risks:unresolvedRisks,constraint_violations:constraintViolations,evidence_refs:evidenceRefs,created_at:options.now?.()??new Date().toISOString()};return writePhaseArchitectureSummary(directory,phaseSummary),phaseSummary}var init_aggregate=__esm(()=>{init_schema3();init_store4()});var exports_preflight_integration={};__export(exports_preflight_integration,{runManualPreflight:()=>runManualPreflight,createPreflightIntegration:()=>createPreflightIntegration});function createPreflightIntegration(config3){let{automationConfig,directory,swarmDir,preflightConfig,updateStatusArtifact=!0}=config3;if(automationConfig?.capabilities?.phase_preflight!==!0)throw Error("Preflight is not enabled in automation capabilities. Set automation.capabilities.phase_preflight to true.");let manager=new PreflightTriggerManager(automationConfig,void 0,{directory}),statusArtifact=null;if(updateStatusArtifact&&swarmDir)statusArtifact=new AutomationStatusArtifact(swarmDir);let preflightHandler=async(request)=>{log("[PreflightIntegration] Handling preflight request",{requestId:request.id,phase:request.currentPhase,source:request.source});let report=await runPreflight(directory,request.currentPhase,preflightConfig);if(statusArtifact){let state=report.overall==="pass"?"success":"failure";statusArtifact.recordOutcome(state,request.currentPhase,report.message),log("[PreflightIntegration] Status artifact updated",{state,phase:request.currentPhase,message:report.message})}log("[PreflightIntegration] Preflight complete",{requestId:request.id,overall:report.overall,message:report.message,durationMs:report.totalDurationMs})};return manager.registerHandler(preflightHandler),{manager,cleanup:()=>{manager.unregisterHandler()}}}async function runManualPreflight(directory,phase,config3){return runPreflight(directory,phase,config3)}var init_preflight_integration=__esm(()=>{init_status_artifact();init_trigger();init_preflight_service();init_logger()});var exports_doc_scan={};__export(exports_doc_scan,{scanDocIndex:()=>scanDocIndex,extractDocConstraints:()=>extractDocConstraints,doc_scan:()=>doc_scan,doc_extract:()=>doc_extract});import*as crypto14 from"node:crypto";import*as fs132 from"node:fs";import{mkdir as mkdir48,readdir as readdir17,readFile as readFile48,realpath as realpath11,stat as stat20,writeFile as writeFile26}from"node:fs/promises";import*as path237 from"node:path";function normalizeSeparators(filePath){return filePath.replace(/\\/g,"/")}function matchesDocPattern(filePath,patterns){let normalizedPath2=normalizeSeparators(filePath),basename33=path237.basename(filePath);for(let pattern of patterns){if(!pattern.includes("/")&&!pattern.includes("\\")){if(basename33===pattern)return!0;continue}if(pattern.startsWith("**/")){let filenamePattern=pattern.slice(3);if(basename33===filenamePattern)return!0;continue}let dirPrefix=normalizeSeparators(pattern).replace(/\/\*\*.*$/,"").replace(/\/\*.*$/,"");if(normalizedPath2.startsWith(`${dirPrefix}/`)||normalizedPath2===dirPrefix)return!0}return!1}function extractTitleAndSummary(content,filename){let lines=content.split(`
|
|
6316
6316
|
`),title=filename,summary="",foundTitle=!1,potentialSummaryLines=[];for(let i=0;i<lines.length&&i<READ_LINES_LIMIT;i++){let line=lines[i].trim();if(!foundTitle&&line.startsWith("# ")){title=line.slice(2).trim(),foundTitle=!0;continue}if(line&&!line.startsWith("#"))potentialSummaryLines.push(line)}for(let line of potentialSummaryLines)if(summary+=(summary?" ":"")+line,summary.length>=MAX_SUMMARY_LENGTH)break;if(summary.length>MAX_SUMMARY_LENGTH)summary=`${summary.slice(0,MAX_SUMMARY_LENGTH-3)}...`;return{title,summary}}function stripMarkdown(text){return text.replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/\*\*([^*]+)\*\*/g,"$1").replace(/`([^`]+)`/g,"$1").replace(/^\s*[-*•]\s+/gm,"").replace(/^\s*\d+\.\s+/gm,"").trim()}async function scanDocIndex(directory){let manifestPath2=path237.join(directory,".swarm","doc-manifest.json"),defaultPatterns=DocsConfigSchema.parse({}).doc_patterns,extraPatterns=["ARCHITECTURE.md","CLAUDE.md","AGENTS.md",".github/*.md","doc/**/*.md"],allPatterns=[...defaultPatterns,...extraPatterns];try{let manifestContent=await readFile48(manifestPath2,"utf-8"),existingManifest=JSON.parse(manifestContent);if(existingManifest.schema_version===1&&existingManifest.files){let cacheValid=!0;for(let file3 of existingManifest.files)try{let fullPath=path237.join(directory,file3.path);if(fs132.statSync(fullPath).mtimeMs>file3.mtime){cacheValid=!1;break}}catch{cacheValid=!1;break}if(cacheValid)return{manifest:existingManifest,cached:!0}}}catch{}let resolvedDirectory=await realpath11(directory).catch(()=>directory),discoveredFiles=[],rootReadable=!1,truncated=!1,walkDir2=async(dir)=>{let entries;try{if(entries=await readdir17(dir,{withFileTypes:!0}),dir===directory)rootReadable=!0}catch{return}for(let entry of entries){let isDir=entry.isDirectory(),isFile=entry.isFile();if(entry.isSymbolicLink())try{let symlinkPath=path237.join(dir,entry.name),resolved=await realpath11(symlinkPath),rel=path237.relative(resolvedDirectory,resolved);if(rel.startsWith("..")||path237.isAbsolute(rel))continue;isFile=(await stat20(symlinkPath)).isFile()}catch{continue}if(isDir){if(!SKIP_DIRECTORIES3.has(entry.name))await walkDir2(path237.join(dir,entry.name));continue}if(!isFile)continue;let fullPath=path237.join(dir,entry.name),relPath=normalizeSeparators(path237.relative(directory,fullPath)),skipThisFile=!1;for(let pattern of SKIP_PATTERNS)if(pattern.test(relPath)){skipThisFile=!0;break}if(skipThisFile)continue;if(!matchesDocPattern(relPath,allPatterns))continue;if(discoveredFiles.length>=MAX_INDEXED_FILES){truncated=!0;return}let fileStat;try{fileStat=await stat20(fullPath)}catch{continue}let content;try{content=await readFile48(fullPath,"utf-8")}catch{continue}let{title,summary}=extractTitleAndSummary(content,path237.basename(relPath));discoveredFiles.push({path:relPath,title,summary,lines:content.split(`
|
|
6317
6317
|
`).length,mtime:fileStat.mtimeMs})}};if(await walkDir2(directory),!rootReadable)return{manifest:{schema_version:1,scanned_at:new Date().toISOString(),files:[]},cached:!1};if(discoveredFiles.sort((a,b)=>a.path.toLowerCase().localeCompare(b.path.toLowerCase())),discoveredFiles.length>MAX_INDEXED_FILES)discoveredFiles.splice(MAX_INDEXED_FILES),truncated=!0;if(truncated&&discoveredFiles.length>0)discoveredFiles[0].summary=`[Warning: ${MAX_INDEXED_FILES}+ docs found, listing first ${MAX_INDEXED_FILES}] `+discoveredFiles[0].summary;let manifest={schema_version:1,scanned_at:new Date().toISOString(),files:discoveredFiles};try{await mkdir48(path237.dirname(manifestPath2),{recursive:!0}),await writeFile26(manifestPath2,JSON.stringify(manifest,null,2),"utf-8")}catch{}return{manifest,cached:!1}}function isConstraintLine(line){let upperLine=line.toUpperCase();for(let pattern of CONSTRAINT_PATTERNS)if(pattern.test(upperLine))return!0;if(/^\s*[-*•]/.test(line)&&ACTION_WORDS.test(line))return!0;return!1}function extractConstraintsFromContent(content){let lines=content.split(`
|
|
6318
|
-
`),constraints=[];for(let line of lines){if(constraints.length>=MAX_CONSTRAINTS_PER_DOC)break;let trimmed=line.trim();if(!trimmed)continue;if(isConstraintLine(trimmed)){let cleaned=stripMarkdown(trimmed),len=cleaned.length;if(len>=MIN_LESSON_LENGTH&&len<=MAX_CONSTRAINT_LENGTH)constraints.push(cleaned)}}return constraints}async function extractDocConstraints(directory,taskFiles,taskDescription){let manifestPath2=path237.join(directory,".swarm","doc-manifest.json"),manifest;try{let content=await readFile48(manifestPath2,"utf-8");manifest=JSON.parse(content)}catch{manifest=(await scanDocIndex(directory)).manifest}let knowledgePath=resolveSwarmKnowledgePath(directory),existingEntries=await readKnowledge(knowledgePath),taskContext=[...taskFiles,taskDescription].join(" "),taskBigrams=wordBigrams(normalize6(taskContext)),extractedCount=0,skippedCount=0,details=[];for(let docFile of manifest.files){let docContext=`${docFile.path} ${docFile.title} ${docFile.summary}`,docBigrams=wordBigrams(normalize6(docContext)),score=jaccardBigram(taskBigrams,docBigrams);if(score<=RELEVANCE_THRESHOLD){skippedCount++;continue}let fullContent;try{fullContent=await readFile48(path237.join(directory,docFile.path),"utf-8")}catch{skippedCount++;continue}let constraints=extractConstraintsFromContent(fullContent);if(constraints.length===0){skippedCount++;continue}let docDetails={path:docFile.path,score,constraints:[]};for(let constraint of constraints)if(!findNearDuplicate(constraint,existingEntries,DEDUP_THRESHOLD2)){let entry={id:crypto14.randomUUID(),tier:"swarm",lesson:constraint,category:"architecture",tags:["doc-scan",path237.basename(docFile.path)],scope:"global",confidence:0.5,status:"candidate",confirmed_by:[],project_name:"",retrieval_outcomes:{applied_count:0,succeeded_after_count:0,failed_after_count:0},schema_version:1,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),auto_generated:!0,hive_eligible:!1};await appendKnowledge(knowledgePath,entry),existingEntries.push(entry),extractedCount++,docDetails.constraints.push(constraint)}if(docDetails.constraints.length>0)details.push(docDetails);else skippedCount++}return{extracted:extractedCount,skipped:skippedCount,details}}var SKIP_DIRECTORIES3,SKIP_PATTERNS,MAX_SUMMARY_LENGTH=200,MAX_INDEXED_FILES=100,READ_LINES_LIMIT=30,MIN_LESSON_LENGTH=15,MAX_CONSTRAINTS_PER_DOC=5,MAX_CONSTRAINT_LENGTH=200,RELEVANCE_THRESHOLD=0.1,DEDUP_THRESHOLD2=0.6,CONSTRAINT_PATTERNS,ACTION_WORDS,doc_scan,doc_extract;var init_doc_scan=__esm(()=>{init_zod();init_schema();init_knowledge_store();init_create_tool();SKIP_DIRECTORIES3=new Set(["node_modules",".git",".swarm","dist","build",".next","vendor","bazel-out","bazel-bin","bazel-genfiles","bazel-testlogs",".gradle","target"]),SKIP_PATTERNS=[/\.test\./,/\.spec\./,/\.d\.ts$/];CONSTRAINT_PATTERNS=[/\bMUST\b/,/\bMUST NOT\b/,/\bSHOULD\b/,/\bSHOULD NOT\b/,/\bDO NOT\b/,/\bALWAYS\b/,/\bNEVER\b/,/\bREQUIRED\b/],ACTION_WORDS=/\b(must|should|don't|avoid|ensure|use|follow)\b/i;doc_scan=createSwarmTool({description:"Scan project documentation files and build an index manifest. Caches results in .swarm/doc-manifest.json for fast subsequent scans.",args:{force:exports_external.boolean().optional().describe("Force re-scan even if cache is valid")},execute:async(args2,directory)=>{let force=!1;try{if(args2&&typeof args2==="object"){if(args2.force===!0)force=!0}}catch{}if(force){let manifestPath2=path237.join(directory,".swarm","doc-manifest.json");try{fs132.unlinkSync(manifestPath2)}catch{}}let{manifest,cached:cached3}=await scanDocIndex(directory);return JSON.stringify({success:!0,files_count:manifest.files.length,cached:cached3,manifest},null,2)}}),doc_extract=createSwarmTool({description:"Extract actionable constraints from project documentation relevant to the current task. Scans docs via doc-manifest, scores relevance via Jaccard bigram similarity, and stores non-duplicate constraints in .swarm/knowledge.jsonl.",args:{task_files:exports_external.array(exports_external.string()).describe("List of file paths involved in the current task"),task_description:exports_external.string().describe("Description of the current task")},execute:async(args2,directory)=>{let taskFiles=[],taskDescription="";try{if(args2&&typeof args2==="object"){let obj=args2;if(Array.isArray(obj.task_files))taskFiles=obj.task_files.filter((f)=>typeof f==="string");if(typeof obj.task_description==="string")taskDescription=obj.task_description}}catch{}if(taskFiles.length===0&&!taskDescription)return JSON.stringify({success:!1,error:"task_files or task_description is required"});let result=await extractDocConstraints(directory,taskFiles,taskDescription);return JSON.stringify({success:!0,...result},null,2)}})});import{existsSync as existsSync122}from"node:fs";import{readFile as readFile49}from"node:fs/promises";import*as path238 from"node:path";function inferCategoriesFromPhase(phaseDescription){let lower=phaseDescription.toLowerCase(),patterns=[{pattern:/\b(?:test|qa|quality|verification|validation)\b/,categories:["testing","debugging"]},{pattern:/\b(?:implement|build|develop|coding|code)\b/,categories:["tooling","architecture","debugging"]},{pattern:/\b(?:integrat|deploy|ci|cd|release|publish)\b/,categories:["integration","tooling","performance"]},{pattern:/\b(?:plan|design|architect|spec|requirement)\b/,categories:["architecture","process"]},{pattern:/\b(?:review|refactor|cleanup|polish|optimi)\b/,categories:["performance","architecture","process"]},{pattern:/\b(?:secur|audit|harden|compliance)\b/,categories:["security","testing"]},{pattern:/\b(?:setup|config|scaffold|init|bootstrap)\b/,categories:["tooling","other"]},{pattern:/\b(?:doc|readme|changelog)\b/,categories:["process","tooling"]}];for(let{pattern,categories}of patterns)if(pattern.test(lower))return categories;return["process","tooling"]}async function transactShownFile(shownFile,mutate){return transactFile(shownFile,async(filePath)=>{if(!existsSync122(filePath))return{};try{let content=await readFile49(filePath,"utf-8");return JSON.parse(content)}catch{return{}}},async(filePath,data)=>{await atomicWriteFile(filePath,JSON.stringify(data,null,2))},mutate)}async function recordLessonsShown(directory,lessonIds,currentPhase){if(lessonIds.length===0)return;let shownFile=path238.join(directory,".swarm",".knowledge-shown.json");try{let phaseMatch=/^Phase\s+(\d+)/i.exec(currentPhase),canonicalKey=phaseMatch?`Phase ${phaseMatch[1]}`:currentPhase;if(!await transactShownFile(shownFile,(shownData)=>{let existing=new Set(shownData[canonicalKey]??[]);for(let id of lessonIds)existing.add(id);return shownData[canonicalKey]=[...existing],shownData}))warn("[swarm] Knowledge: failed to record shown lessons")}catch{warn("[swarm] Knowledge: failed to record shown lessons")}}async function readMergedKnowledge(directory,config3,context,opts){let swarmPath3=resolveSwarmKnowledgePath(directory),swarmEntries=await readKnowledge(swarmPath3),hiveEntries=[];if(config3.hive_enabled!==!1){let hivePath=resolveHiveKnowledgePath2();hiveEntries=await readKnowledge(hivePath)}let seenLessons=new Set,merged=[];for(let entry of hiveEntries){let normalized=normalize6(entry.lesson);seenLessons.add(normalized),merged.push({...entry,relevanceScore:{category:0,confidence:0,keywords:0},finalScore:0})}for(let entry of swarmEntries){let normalized=normalize6(entry.lesson);if(seenLessons.has(normalized))continue;let swarmBigrams=wordBigrams(normalized);if(hiveEntries.some((hiveEntry)=>jaccardBigram(swarmBigrams,wordBigrams(normalize6(hiveEntry.lesson)))>=JACCARD_THRESHOLD2))continue;if(merged.some((m)=>m.tier==="swarm"&&jaccardBigram(swarmBigrams,wordBigrams(normalize6(m.lesson)))>=JACCARD_THRESHOLD2))continue;seenLessons.add(normalized),merged.push({...entry,relevanceScore:{category:0,confidence:0,keywords:0},finalScore:0})}let retractionRecords=await readRetractionRecords(directory),suppressedLessons=new Set(retractionRecords.map((record3)=>record3.normalized_lesson).filter((value)=>typeof value==="string"&&value.length>0)),scopeFilter=config3.scope_filter??["global"],ranked=merged.filter((entry)=>(opts?.skipScopeFilter||scopeFilter.some((pattern)=>(entry.scope??"global")===pattern))&&isActiveStatus(entry.status)&&!suppressedLessons.has(normalize6(entry.lesson))).map((entry)=>{let categoryScore=0;if(context?.currentPhase){if(inferCategoriesFromPhase(context.currentPhase).includes(entry.category))categoryScore=1;else if(entry.category==="process")categoryScore=0.5}else categoryScore=0.5;let confidenceScore=entry.confidence,keywordsScore=0;if(context?.techStack&&entry.tags.length>0){let matchingTags=entry.tags.filter((t)=>context.techStack.some((s)=>t.toLowerCase().includes(s.toLowerCase())||s.toLowerCase().includes(t.toLowerCase()))).length;keywordsScore=Math.min(matchingTags/Math.max(entry.tags.length,1),1)}else if(entry.tags.length===0)keywordsScore=0.5;let tierBoost=0,isSameProject=!1;if(entry.tier==="hive"&&"source_project"in entry){let sourceProject=entry.source_project;isSameProject=!!(context?.projectName&&sourceProject===context.projectName),tierBoost=HIVE_TIER_BOOST}let sameProjectPenalty=isSameProject?DEFAULT_SAME_PROJECT_PENALTY:0,finalScore=categoryScore*0.4+confidenceScore*0.35+keywordsScore*0.25+tierBoost+sameProjectPenalty;return{...entry,relevanceScore:{category:categoryScore,confidence:confidenceScore,keywords:keywordsScore},finalScore:Math.min(Math.max(finalScore,0),1)}});ranked.sort((a,b)=>{let scoreDiff=b.finalScore-a.finalScore;if(Math.abs(scoreDiff)>0.001)return scoreDiff;let dateA=new Date(a.created_at).getTime();return new Date(b.created_at).getTime()-dateA});let maxInject=config3.max_inject_count??5;return ranked.slice(0,maxInject)}async function updateRetrievalOutcome(directory,phaseInfo,phaseSucceeded){let shownFile=path238.join(directory,".swarm",".knowledge-shown.json");try{if(!existsSync122(shownFile))return;let shownIds;try{let content=await readFile49(shownFile,"utf-8");shownIds=JSON.parse(content)[phaseInfo]}catch{return}if(!shownIds||shownIds.length===0)return;let outcome=phaseSucceeded?"success":"failure",evidenceSummary=`${phaseInfo} ${phaseSucceeded?"succeeded":"failed"} after entry was shown`;await transactShownFile(shownFile,(data)=>{return delete data[phaseInfo],data});for(let id of shownIds)await _internals182.recordKnowledgeEvent(directory,{type:"outcome",knowledge_id:id,phase:phaseInfo,outcome,evidence_summary:evidenceSummary})}catch{warn("[swarm] Knowledge: failed to update retrieval outcomes")}}function lc(s){return(s??"").toLowerCase()}function anyMatch(haystack,needles){if(needles.length===0)return!1;let hay=haystack.map(lc);return needles.some((n)=>hay.some((h)=>h.includes(lc(n))))}function tokenizeContext(ctx){let parts=[];if(ctx.taskTitle)parts.push(ctx.taskTitle);if(ctx.taskDescription)parts.push(ctx.taskDescription);if(ctx.lastUserMessage)parts.push(ctx.lastUserMessage);if(ctx.currentAction)parts.push(ctx.currentAction);if(ctx.currentTool)parts.push(ctx.currentTool);if(ctx.targetAgent)parts.push(ctx.targetAgent);if(ctx.declaredScope)parts.push(ctx.declaredScope);if(ctx.recentReviewerFailures)parts.push(...ctx.recentReviewerFailures);if(ctx.recentTestFailures)parts.push(...ctx.recentTestFailures);if(ctx.recentToolErrors)parts.push(...ctx.recentToolErrors);if(ctx.planConstraints)parts.push(...ctx.planConstraints);if(ctx.filePaths)parts.push(...ctx.filePaths);return parts.map(lc)}function scoreDirectiveAgainstContext(entry,ctx){let haystack=tokenizeContext(ctx),triggerHit=entry.triggers&&entry.triggers.length>0?anyMatch(haystack,entry.triggers):!1,actionHit=entry.applies_to_tools&&entry.applies_to_tools.length>0?entry.applies_to_tools.map(lc).some((t)=>t===lc(ctx.currentTool)||t===lc(ctx.currentAction)):!1,agentHit=entry.applies_to_agents&&entry.applies_to_agents.length>0?entry.applies_to_agents.map(lc).some((a)=>a===lc(ctx.targetAgent)):!1,score=0;if(triggerHit)score+=0.5;if(actionHit)score+=0.35;if(agentHit)score+=0.25;if(entry.directive_priority==="critical")score+=0.4;else if(entry.directive_priority==="high")score+=0.2;else if(entry.directive_priority==="medium")score+=0.1;return{triggerHit,actionHit,agentHit,score:Math.min(1,score)}}var JACCARD_THRESHOLD2=0.6,HIVE_TIER_BOOST=0.05,DEFAULT_SAME_PROJECT_PENALTY=-0.05,_internals182;var init_knowledge_reader=__esm(()=>{init_task_file();init_logger();init_knowledge_events();init_knowledge_store();init_knowledge_types();_internals182={readMergedKnowledge,updateRetrievalOutcome,scoreDirectiveAgainstContext,transactShownFile,recordKnowledgeEvent,recordLessonsShown}});function entryText(e){return`${e.lesson} ${e.tags.join(" ")} ${e.category}`}function entryAgePhases(e){let cb=e.confirmed_by;if(!Array.isArray(cb)||cb.length===0)return 0;let phases=new Set;for(let c of cb)if(typeof c?.phase_number==="number")phases.add(c.phase_number);return phases.size>0?phases.size:cb.length}function clampLambda(v){if(typeof v!=="number"||Number.isNaN(v))return 0.5;return Math.min(1,Math.max(0,v))}function mmrRerank(pool,pinned,max,lambda){if(pool.length===0)return[];let bigrams=new Map,bg=(e)=>{let s=bigrams.get(e.id);if(!s)s=wordBigrams(normalize6(e.lesson??"")),bigrams.set(e.id,s);return s},selected=[...pinned],candidates=[...pool],out=[];while(selected.length<max&&candidates.length>0){let bestIdx=-1,bestScore=Number.NEGATIVE_INFINITY,best=null;for(let i=0;i<candidates.length;i++){let c=candidates[i],maxSim=0;for(let s of selected){let sim=jaccardBigram(bg(c),bg(s));if(sim>maxSim)maxSim=sim}let score=lambda*c.finalScore-(1-lambda)*maxSim;if(score>bestScore+0.000000001||Math.abs(score-bestScore)<=0.000000001&&best!==null&&tieBreak(c,best)<0)bestScore=score,bestIdx=i,best=c}if(bestIdx<0||best===null)break;out.push(best),selected.push(best),candidates.splice(bestIdx,1)}return out}function tieBreak(a,b){if(Math.abs(a.finalScore-b.finalScore)>0.000000001)return b.finalScore-a.finalScore;let at=new Date(a.created_at).getTime(),bt=new Date(b.created_at).getTime();if(at!==bt)return bt-at;return a.id<b.id?-1:a.id>b.id?1:0}function statusBoost(status){if(status==="promoted")return 0.15;if(status==="established")return 0.1;return 0}async function searchKnowledge(params){let{directory,config:config3,query,context,mode,agent="unknown",sessionId="unknown",tier="all",emitEvent=!1,applyScopeFilter=!0,forceReadHive=!1,applyRoleScope=!0}=params,traceId=newTraceId2(),max=params.maxResults??config3.max_inject_count??5,results=[],synonymTokens=[],synonymTrace={};try{let mergeConfig={...config3,hive_enabled:tier==="swarm"?!1:forceReadHive?!0:config3.hive_enabled,max_inject_count:Math.max(20,max)},projected={projectName:context?.projectName??"unknown",currentPhase:context?.currentPhase??"",techStack:context?.techStack,recentErrors:[...context?.recentReviewerFailures??[],...context?.recentTestFailures??[],...context?.recentToolErrors??[]]},candidates=await readMergedKnowledge(directory,mergeConfig,projected,{skipScopeFilter:!applyScopeFilter}),counterRollups=await readAuthoritativeKnowledgeCounterRollups(directory);candidates=candidates.filter((e)=>{if(!isActiveStatus(e.status))return!1;if(tier==="hive"&&e.tier!=="hive")return!1;return!0});let role=stripKnownSwarmPrefix(agent).toLowerCase();if(applyRoleScope&&role&&role!=="unknown")candidates=candidates.filter((e)=>{if(!e.applies_to_agents||e.applies_to_agents.length===0)return!0;if(role==="architect")return!0;return e.applies_to_agents.map((a)=>stripKnownSwarmPrefix(a).toLowerCase()).includes(role)});let queryText=(query??"").trim(),queryBigrams=queryText?wordBigrams(normalize6(queryText)):null,hasQuery=queryBigrams!==null,textWeight=hasQuery?TEXT_WEIGHT:0,metaWeight=hasQuery?META_WEIGHT:1,compositeRaw=[queryText,context?.taskTitle,context?.taskDescription,context?.lastUserMessage,context?.currentAction,...context?.recentReviewerFailures??[],...context?.recentTestFailures??[],...context?.recentToolErrors??[]].filter((s)=>typeof s==="string"&&s.length>0).join(" "),compositeNorm=normalize6(compositeRaw),hasComposite=compositeNorm.length>0;try{if(hasComposite){let synMap=await readSynonymMap(directory,config3.retrieval?.synonym_map_max_pairs),synIndex=buildSynonymIndex(synMap,config3.retrieval?.synonym_min_cooccurrence),baseTokens=compositeNorm.split(" ").filter(Boolean);synonymTokens=expandTokens(synIndex,baseTokens)}}catch{synonymTokens=[]}let minConf=typeof config3.directive_min_confidence==="number"?config3.directive_min_confidence:DIRECTIVE_BOOST_MIN_CONFIDENCE,scored=candidates.map((entry)=>{let retrievalOutcomes=effectiveRetrievalOutcomes(entry.retrieval_outcomes,counterRollups.get(entry.id)),textScore=queryBigrams?jaccardBigram(queryBigrams,wordBigrams(normalize6(entryText(entry)))):0,metaScore=entry.finalScore,ds=context?scoreDirectiveAgainstContext(entry,context):{triggerHit:!1,actionHit:!1,agentHit:!1,score:0},confBoost=context&&entry.confidence>=minConf&&(ds.actionHit||ds.agentHit)?0.25:0,generatedSkillBoost=entry.generated_skill_path&&entry.status!=="archived"?0.05:0,outcomeBoost=computeOutcomeSignal(retrievalOutcomes)*OUTCOME_RANK_WEIGHT,coldStartBonus=(retrievalOutcomes.applied_explicit_count??0)===0&&entryAgePhases(entry)<(config3.retrieval?.cold_start_max_age_phases??DEFAULT_COLD_START_MAX_AGE_PHASES)?config3.retrieval?.cold_start_bonus??DEFAULT_COLD_START_BONUS:0,synonymBoost=0;if(synonymTokens.length>0){let entryHay=normalize6(entryText(entry)),matched=[];for(let t of synonymTokens)if(t.length>0&&entryHay.includes(t))matched.push(t);if(matched.length>0)synonymBoost=SYNONYM_TEXT_BOOST,synonymTrace[entry.id]=matched}let triggerRecallBoost=!ds.triggerHit&&hasComposite&&Array.isArray(entry.triggers)&&entry.triggers.some((tr)=>{let n=normalize6(tr);return n.length>=TRIGGER_RECALL_MIN_LEN&&compositeNorm.includes(n)})?TRIGGER_RECALL_BOOST:0,finalScore=Math.min(1,Math.max(0,textWeight*textScore+metaWeight*metaScore+ds.score+confBoost+generatedSkillBoost+outcomeBoost+coldStartBonus+synonymBoost+triggerRecallBoost+(hasQuery&&!entry.confidence_floor_demoted?statusBoost(entry.status):0))),statusScoreBoost=hasQuery&&!entry.confidence_floor_demoted?statusBoost(entry.status):0,isCritical=entry.directive_priority==="critical"&&(ds.triggerHit||ds.actionHit||ds.agentHit),isForceHive=forceReadHive&&entry.tier==="hive";return{...entry,retrieval_outcomes:retrievalOutcomes,finalScore,coldStartBoost:coldStartBonus,score_breakdown:{text_score:textScore,metadata_score:metaScore,directive_score:ds.score,confidence_boost:confBoost,generated_skill_boost:generatedSkillBoost,outcome_boost:outcomeBoost,cold_start_boost:coldStartBonus,synonym_boost:synonymBoost,trigger_recall_boost:triggerRecallBoost,status_boost:statusScoreBoost,final_score:finalScore,...synonymTrace[entry.id]?{synonym_matches:synonymTrace[entry.id]}:{}},__critical:isCritical,__forceHive:isForceHive}});scored.sort((a,b)=>{let diff=b.finalScore-a.finalScore;if(Math.abs(diff)>0.001)return diff;return new Date(b.created_at).getTime()-new Date(a.created_at).getTime()});let top=[],seen=new Set;for(let e of scored){if(top.length>=max)break;if(e.__critical&&!seen.has(e.id))top.push(e),seen.add(e.id)}for(let e of scored){if(top.length>=max)break;if(e.__forceHive&&!seen.has(e.id))top.push(e),seen.add(e.id)}let lambda=clampLambda(config3.retrieval?.mmr_lambda),remaining=scored.filter((e)=>!seen.has(e.id)),selected=mmrRerank(remaining,top,max,lambda);for(let e of selected){if(top.length>=max)break;if(!seen.has(e.id))top.push(e),seen.add(e.id)}results=top.map(({__critical:_c,__forceHive:_f,...rest})=>rest)}catch(err){warn(`[search-knowledge] retrieval failed: ${err instanceof Error?err.message:String(err)}`),results=[]}if(emitEvent){let ranks={},scores={};results.forEach((e,idx)=>{ranks[e.id]=idx+1,scores[e.id]=e.finalScore});let synonymBreakdown={};for(let e of results)if(synonymTrace[e.id])synonymBreakdown[e.id]=synonymTrace[e.id];let scoreBreakdown=synonymTokens.length>0?{synonyms_expanded:synonymTokens,synonym_matches:synonymBreakdown}:void 0;await recordKnowledgeEvent(directory,{type:"retrieved",trace_id:traceId,session_id:sessionId,phase:context?.currentPhase,task_id:context?.taskId,agent,query:query??context?.lastUserMessage??context?.currentPhase??"",retrieval_mode:mode,result_ids:results.map((e)=>e.id),ranks,scores,...scoreBreakdown?{score_breakdown:scoreBreakdown}:{}})}return{trace_id:traceId,results}}var TEXT_WEIGHT=0.6,META_WEIGHT=0.4,DIRECTIVE_BOOST_MIN_CONFIDENCE=0.75,SYNONYM_TEXT_BOOST=0.15,TRIGGER_RECALL_BOOST=0.3,TRIGGER_RECALL_MIN_LEN=3,DEFAULT_COLD_START_BONUS=0.08,DEFAULT_COLD_START_MAX_AGE_PHASES=3,OUTCOME_RANK_WEIGHT=0.1;var init_search_knowledge=__esm(()=>{init_schema();init_synonym_map();init_logger();init_knowledge_events();init_knowledge_reader();init_knowledge_store();init_knowledge_types()});var exports_knowledge_recall={};__export(exports_knowledge_recall,{knowledge_recall:()=>knowledge_recall,_internals:()=>_internals183});var knowledge_recall,_internals183;var init_knowledge_recall=__esm(()=>{init_zod();init_config();init_schema();init_knowledge_events();init_knowledge_receipt_ledger();init_knowledge_types();init_search_knowledge();init_knowledge_diagnostics();init_logger();init_create_tool();knowledge_recall=createSwarmTool({allowWorkingDirectoryOverride:!0,description:"Performs semantic natural-language search across the knowledge base for relevant past decisions, patterns, and lessons learned. Returns ranked results via the unified hybrid retrieval service and a trace_id for knowledge_receipt. This is the tool to use when the user has a QUESTION about what the knowledge base contains. For structured filter-based retrieval (by category, status, or score), use `knowledge_query` instead.",args:{query:exports_external.string().min(3).describe("Natural language search query"),top_n:exports_external.number().int().min(1).max(20).optional().describe("Maximum results to return (default: 5)"),tier:exports_external.enum(["all","swarm","hive"]).optional().describe("Knowledge tier to search (default: 'all')"),debug:exports_external.boolean().optional().describe("Include path/version/health debug metadata in the response"),repair_re_evaluation:exports_external.object({repair_id:exports_external.string().uuid(),phase:exports_external.string().min(1).max(256),task_id:exports_external.string().min(1).max(256).optional(),scope_complete:exports_external.literal(!0)}).optional().describe("Architect-only explicit completion of a repaired receipt scope. The query must comprehensively re-evaluate the exact affected phase/session scope.")},execute:async(args2,directory,ctx)=>{let queryInput,topNInput,tierInput,debugInput,repairInput;try{if(args2&&typeof args2==="object"){let obj=args2;queryInput=obj.query,topNInput=obj.top_n,tierInput=obj.tier,debugInput=obj.debug,repairInput=obj.repair_re_evaluation}}catch{}let wantDebug=debugInput===!0,repairReevaluation;if(repairInput!==void 0){if(stripKnownSwarmPrefix(ctx?.agent??"")!=="architect"||typeof repairInput!=="object"||repairInput===null)return JSON.stringify({results:[],total:0,unverifiable:!0,code:"RECEIPT_REEVALUATION_ARCHITECT_ONLY",error:"Only the architect may complete an explicit receipt repair re-evaluation."});let candidate2=repairInput;if(typeof candidate2.repair_id!=="string"||!candidate2.repair_id||typeof candidate2.phase!=="string"||!candidate2.phase||candidate2.scope_complete!==!0||candidate2.task_id!==void 0&&typeof candidate2.task_id!=="string")return JSON.stringify({results:[],total:0,unverifiable:!0,code:"RECEIPT_REEVALUATION_PROOF_INVALID",error:"Explicit re-evaluation requires repair_id, exact phase, and scope_complete=true."});repairReevaluation={repair_id:candidate2.repair_id,phase:candidate2.phase,scope_complete:!0,...typeof candidate2.task_id==="string"?{task_id:candidate2.task_id}:{}}}if(typeof queryInput!=="string"||queryInput.length<3)return JSON.stringify({results:[],total:0,error:"query must be a string with at least 3 characters"});let topN=5;if(typeof topNInput==="number"&&Number.isInteger(topNInput))topN=Math.max(1,Math.min(20,topNInput));let tier="all";if(tierInput==="swarm"||tierInput==="hive")tier=tierInput;let knowledgeConfig=KnowledgeConfigSchema.parse({});try{let{config:config3}=loadPluginConfigWithMeta(directory);knowledgeConfig=KnowledgeConfigSchema.parse(config3.knowledge??{})}catch{}let{trace_id,results}=await searchKnowledge({directory,config:knowledgeConfig,query:queryInput,mode:"manual",agent:ctx?.agent??"unknown",sessionId:ctx?.sessionID??"unknown",tier,maxResults:topN,applyScopeFilter:!1,forceReadHive:!0,applyRoleScope:!1,emitEvent:!1}),sessionId=ctx?.sessionID??"unknown";if(results.length>0){let membership=await commitDisplayedMembership(directory,{trace_id,session_id:sessionId,exposure_kind:"manual_recall",agent:ctx?.agent??"unknown",grace_days:knowledgeConfig.receipt_close_grace_days,phase:repairReevaluation?.phase,task_id:repairReevaluation?.task_id,repair_re_evaluation:repairReevaluation,entries:results.map((entry,index)=>({entry_id:entry.id,critical:entry.directive_priority==="critical"&&isActiveStatus(entry.status),rank:index+1,score:entry.finalScore}))});if(!membership.ok||membership.memberships.some((item)=>item.terminal))return JSON.stringify({results:[],total:0,unverifiable:!0,code:membership.ok?"terminal_trace_reuse":membership.code,error:membership.ok?"retrieval trace was already terminalized":membership.detail})}else{let empty=await commitEmptyRetrieval(directory,{trace_id,session_id:sessionId,agent:ctx?.agent??"unknown",grace_days:knowledgeConfig.receipt_close_grace_days,phase:repairReevaluation?.phase,task_id:repairReevaluation?.task_id,repair_re_evaluation:repairReevaluation});if(!empty.ok)return JSON.stringify({results:[],total:0,unverifiable:!0,code:empty.code,error:empty.detail});if(!empty.terminal_event_id)return JSON.stringify({results:[],total:0,unverifiable:!0,code:"store_unavailable",error:"empty retrieval terminal did not commit"})}let ranks=Object.fromEntries(results.map((entry,index)=>[entry.id,index+1])),scores=Object.fromEntries(results.map((entry)=>[entry.id,entry.finalScore]));await recordKnowledgeEvent(directory,{type:"retrieved",trace_id,session_id:sessionId,agent:ctx?.agent??"unknown",query:queryInput,retrieval_mode:"manual",result_ids:results.map((entry)=>entry.id),ranks,scores});let scored=results.map((e)=>({id:e.id,confidence:e.confidence,category:e.category,lesson:e.lesson,score:e.finalScore,score_breakdown:e.score_breakdown}));log("[knowledge_recall] completed",{agent:ctx?.agent??"unknown",session_id:ctx?.sessionID??"unknown",query:queryInput,tier,result_count:scored.length,trace_id});let result={results:scored,total:scored.length,trace_id};if(wantDebug)result.debug=await computeKnowledgeDebug(directory);return JSON.stringify(result)}}),_internals183={knowledge_recall}});var exports_prompt_renderer={};__export(exports_prompt_renderer,{renderEnvironmentPrompt:()=>renderEnvironmentPrompt});function renderEnvironmentPrompt(profile,audience){let policy=deriveCommandPolicy(profile),header=["RUNTIME ENVIRONMENT",`- Host OS: ${profile.hostOS}`,`- Shell family: ${profile.shellFamily}`,`- Execution mode: ${profile.executionMode}`,`- Path style: ${profile.pathStyle}`].join(`
|
|
6318
|
+
`),constraints=[];for(let line of lines){if(constraints.length>=MAX_CONSTRAINTS_PER_DOC)break;let trimmed=line.trim();if(!trimmed)continue;if(isConstraintLine(trimmed)){let cleaned=stripMarkdown(trimmed),len=cleaned.length;if(len>=MIN_LESSON_LENGTH&&len<=MAX_CONSTRAINT_LENGTH)constraints.push(cleaned)}}return constraints}async function extractDocConstraints(directory,taskFiles,taskDescription){let manifestPath2=path237.join(directory,".swarm","doc-manifest.json"),manifest;try{let content=await readFile48(manifestPath2,"utf-8");manifest=JSON.parse(content)}catch{manifest=(await scanDocIndex(directory)).manifest}let knowledgePath=resolveSwarmKnowledgePath(directory),existingEntries=await readKnowledge(knowledgePath),taskContext=[...taskFiles,taskDescription].join(" "),taskBigrams=wordBigrams(normalize6(taskContext)),extractedCount=0,skippedCount=0,details=[];for(let docFile of manifest.files){let docContext=`${docFile.path} ${docFile.title} ${docFile.summary}`,docBigrams=wordBigrams(normalize6(docContext)),score=jaccardBigram(taskBigrams,docBigrams);if(score<=RELEVANCE_THRESHOLD){skippedCount++;continue}let fullContent;try{fullContent=await readFile48(path237.join(directory,docFile.path),"utf-8")}catch{skippedCount++;continue}let constraints=extractConstraintsFromContent(fullContent);if(constraints.length===0){skippedCount++;continue}let docDetails={path:docFile.path,score,constraints:[]};for(let constraint of constraints)if(!findNearDuplicate(constraint,existingEntries,DEDUP_THRESHOLD2)){let entry={id:crypto14.randomUUID(),tier:"swarm",lesson:constraint,category:"architecture",tags:["doc-scan",path237.basename(docFile.path)],scope:"global",confidence:0.5,status:"candidate",confirmed_by:[],project_name:"",retrieval_outcomes:{applied_count:0,succeeded_after_count:0,failed_after_count:0},schema_version:1,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),auto_generated:!0,hive_eligible:!1};await appendKnowledge(knowledgePath,entry),existingEntries.push(entry),extractedCount++,docDetails.constraints.push(constraint)}if(docDetails.constraints.length>0)details.push(docDetails);else skippedCount++}return{extracted:extractedCount,skipped:skippedCount,details}}var SKIP_DIRECTORIES3,SKIP_PATTERNS,MAX_SUMMARY_LENGTH=200,MAX_INDEXED_FILES=100,READ_LINES_LIMIT=30,MIN_LESSON_LENGTH=15,MAX_CONSTRAINTS_PER_DOC=5,MAX_CONSTRAINT_LENGTH=200,RELEVANCE_THRESHOLD=0.1,DEDUP_THRESHOLD2=0.6,CONSTRAINT_PATTERNS,ACTION_WORDS,doc_scan,doc_extract;var init_doc_scan=__esm(()=>{init_zod();init_schema();init_knowledge_store();init_create_tool();SKIP_DIRECTORIES3=new Set(["node_modules",".git",".swarm","dist","build",".next","vendor","bazel-out","bazel-bin","bazel-genfiles","bazel-testlogs",".gradle","target"]),SKIP_PATTERNS=[/\.test\./,/\.spec\./,/\.d\.ts$/];CONSTRAINT_PATTERNS=[/\bMUST\b/,/\bMUST NOT\b/,/\bSHOULD\b/,/\bSHOULD NOT\b/,/\bDO NOT\b/,/\bALWAYS\b/,/\bNEVER\b/,/\bREQUIRED\b/],ACTION_WORDS=/\b(must|should|don't|avoid|ensure|use|follow)\b/i;doc_scan=createSwarmTool({description:"Scan project documentation files and build an index manifest. Caches results in .swarm/doc-manifest.json for fast subsequent scans.",args:{force:exports_external.boolean().optional().describe("Force re-scan even if cache is valid")},execute:async(args2,directory)=>{let force=!1;try{if(args2&&typeof args2==="object"){if(args2.force===!0)force=!0}}catch{}if(force){let manifestPath2=path237.join(directory,".swarm","doc-manifest.json");try{fs132.unlinkSync(manifestPath2)}catch{}}let{manifest,cached:cached3}=await scanDocIndex(directory);return JSON.stringify({success:!0,files_count:manifest.files.length,cached:cached3,manifest},null,2)}}),doc_extract=createSwarmTool({description:"Extract actionable constraints from project documentation relevant to the current task. Scans docs via doc-manifest, scores relevance via Jaccard bigram similarity, and stores non-duplicate constraints in .swarm/knowledge.jsonl.",args:{task_files:exports_external.array(exports_external.string()).describe("List of file paths involved in the current task"),task_description:exports_external.string().describe("Description of the current task")},execute:async(args2,directory)=>{let taskFiles=[],taskDescription="";try{if(args2&&typeof args2==="object"){let obj=args2;if(Array.isArray(obj.task_files))taskFiles=obj.task_files.filter((f)=>typeof f==="string");if(typeof obj.task_description==="string")taskDescription=obj.task_description}}catch{}if(taskFiles.length===0&&!taskDescription)return JSON.stringify({success:!1,error:"task_files or task_description is required"});let result=await extractDocConstraints(directory,taskFiles,taskDescription);return JSON.stringify({success:!0,...result},null,2)}})});import{existsSync as existsSync122}from"node:fs";import{readFile as readFile49}from"node:fs/promises";import*as path238 from"node:path";function inferCategoriesFromPhase(phaseDescription){let lower=phaseDescription.toLowerCase(),patterns=[{pattern:/\b(?:test|qa|quality|verification|validation)\b/,categories:["testing","debugging"]},{pattern:/\b(?:implement|build|develop|coding|code)\b/,categories:["tooling","architecture","debugging"]},{pattern:/\b(?:integrat|deploy|ci|cd|release|publish)\b/,categories:["integration","tooling","performance"]},{pattern:/\b(?:plan|design|architect|spec|requirement)\b/,categories:["architecture","process"]},{pattern:/\b(?:review|refactor|cleanup|polish|optimi)\b/,categories:["performance","architecture","process"]},{pattern:/\b(?:secur|audit|harden|compliance)\b/,categories:["security","testing"]},{pattern:/\b(?:setup|config|scaffold|init|bootstrap)\b/,categories:["tooling","other"]},{pattern:/\b(?:doc|readme|changelog)\b/,categories:["process","tooling"]}];for(let{pattern,categories}of patterns)if(pattern.test(lower))return categories;return["process","tooling"]}async function transactShownFile(shownFile,mutate){return transactFile(shownFile,async(filePath)=>{if(!existsSync122(filePath))return{};try{let content=await readFile49(filePath,"utf-8");return JSON.parse(content)}catch{return{}}},async(filePath,data)=>{await atomicWriteFile(filePath,JSON.stringify(data,null,2))},mutate)}async function recordLessonsShown(directory,lessonIds,currentPhase){if(lessonIds.length===0)return;let shownFile=path238.join(directory,".swarm",".knowledge-shown.json");try{let phaseMatch=/^Phase\s+(\d+)/i.exec(currentPhase),canonicalKey=phaseMatch?`Phase ${phaseMatch[1]}`:currentPhase;if(!await transactShownFile(shownFile,(shownData)=>{let existing=new Set(shownData[canonicalKey]??[]);for(let id of lessonIds)existing.add(id);return shownData[canonicalKey]=[...existing],shownData}))warn("[swarm] Knowledge: failed to record shown lessons")}catch{warn("[swarm] Knowledge: failed to record shown lessons")}}async function readMergedKnowledge(directory,config3,context,opts){let swarmPath3=resolveSwarmKnowledgePath(directory),swarmEntries=await readKnowledge(swarmPath3),hiveEntries=[];if(config3.hive_enabled!==!1){let hivePath=resolveHiveKnowledgePath2();hiveEntries=await readKnowledge(hivePath)}let seenLessons=new Set,merged=[];for(let entry of hiveEntries){let normalized=normalize6(entry.lesson);seenLessons.add(normalized),merged.push({...entry,relevanceScore:{category:0,confidence:0,keywords:0},finalScore:0})}for(let entry of swarmEntries){let normalized=normalize6(entry.lesson);if(seenLessons.has(normalized))continue;let swarmBigrams=wordBigrams(normalized);if(hiveEntries.some((hiveEntry)=>jaccardBigram(swarmBigrams,wordBigrams(normalize6(hiveEntry.lesson)))>=JACCARD_THRESHOLD2))continue;if(merged.some((m)=>m.tier==="swarm"&&jaccardBigram(swarmBigrams,wordBigrams(normalize6(m.lesson)))>=JACCARD_THRESHOLD2))continue;seenLessons.add(normalized),merged.push({...entry,relevanceScore:{category:0,confidence:0,keywords:0},finalScore:0})}let retractionRecords=await readRetractionRecords(directory),suppressedLessons=new Set(retractionRecords.map((record3)=>record3.normalized_lesson).filter((value)=>typeof value==="string"&&value.length>0)),scopeFilter=config3.scope_filter??["global"],ranked=merged.filter((entry)=>(opts?.skipScopeFilter||scopeFilter.some((pattern)=>(entry.scope??"global")===pattern))&&isActiveStatus(entry.status)&&!suppressedLessons.has(normalize6(entry.lesson))).map((entry)=>{let categoryScore=0;if(context?.currentPhase){if(inferCategoriesFromPhase(context.currentPhase).includes(entry.category))categoryScore=1;else if(entry.category==="process")categoryScore=0.5}else categoryScore=0.5;let confidenceScore=entry.confidence,keywordsScore=0;if(context?.techStack&&entry.tags.length>0){let matchingTags=entry.tags.filter((t)=>context.techStack.some((s)=>t.toLowerCase().includes(s.toLowerCase())||s.toLowerCase().includes(t.toLowerCase()))).length;keywordsScore=Math.min(matchingTags/Math.max(entry.tags.length,1),1)}else if(entry.tags.length===0)keywordsScore=0.5;let tierBoost=0,isSameProject=!1;if(entry.tier==="hive"&&"source_project"in entry){let sourceProject=entry.source_project;isSameProject=!!(context?.projectName&&sourceProject===context.projectName),tierBoost=HIVE_TIER_BOOST}let sameProjectPenalty=isSameProject?DEFAULT_SAME_PROJECT_PENALTY:0,finalScore=categoryScore*0.4+confidenceScore*0.35+keywordsScore*0.25+tierBoost+sameProjectPenalty;return{...entry,relevanceScore:{category:categoryScore,confidence:confidenceScore,keywords:keywordsScore},finalScore:Math.min(Math.max(finalScore,0),1)}});ranked.sort((a,b)=>{let scoreDiff=b.finalScore-a.finalScore;if(Math.abs(scoreDiff)>0.001)return scoreDiff;let dateA=new Date(a.created_at).getTime();return new Date(b.created_at).getTime()-dateA});let maxInject=config3.max_inject_count??5;return ranked.slice(0,maxInject)}async function updateRetrievalOutcome(directory,phaseInfo,phaseSucceeded){let shownFile=path238.join(directory,".swarm",".knowledge-shown.json");try{if(!existsSync122(shownFile))return;let shownIds;try{let content=await readFile49(shownFile,"utf-8");shownIds=JSON.parse(content)[phaseInfo]}catch{return}if(!shownIds||shownIds.length===0)return;let outcome=phaseSucceeded?"success":"failure",evidenceSummary=`${phaseInfo} ${phaseSucceeded?"succeeded":"failed"} after entry was shown`;await transactShownFile(shownFile,(data)=>{return delete data[phaseInfo],data});for(let id of shownIds)await _internals182.recordKnowledgeEvent(directory,{type:"outcome",knowledge_id:id,phase:phaseInfo,outcome,evidence_summary:evidenceSummary})}catch{warn("[swarm] Knowledge: failed to update retrieval outcomes")}}function lc(s){return(s??"").toLowerCase()}function anyMatch(haystack,needles){if(needles.length===0)return!1;let hay=haystack.map(lc);return needles.some((n)=>hay.some((h)=>h.includes(lc(n))))}function tokenizeContext(ctx){let parts=[];if(ctx.taskTitle)parts.push(ctx.taskTitle);if(ctx.taskDescription)parts.push(ctx.taskDescription);if(ctx.lastUserMessage)parts.push(ctx.lastUserMessage);if(ctx.currentAction)parts.push(ctx.currentAction);if(ctx.currentTool)parts.push(ctx.currentTool);if(ctx.targetAgent)parts.push(ctx.targetAgent);if(ctx.declaredScope)parts.push(ctx.declaredScope);if(ctx.recentReviewerFailures)parts.push(...ctx.recentReviewerFailures);if(ctx.recentTestFailures)parts.push(...ctx.recentTestFailures);if(ctx.recentToolErrors)parts.push(...ctx.recentToolErrors);if(ctx.planConstraints)parts.push(...ctx.planConstraints);if(ctx.filePaths)parts.push(...ctx.filePaths);return parts.map(lc)}function scoreDirectiveAgainstContext(entry,ctx){let haystack=tokenizeContext(ctx),triggerHit=entry.triggers&&entry.triggers.length>0?anyMatch(haystack,entry.triggers):!1,actionHit=entry.applies_to_tools&&entry.applies_to_tools.length>0?entry.applies_to_tools.map(lc).some((t)=>t===lc(ctx.currentTool)||t===lc(ctx.currentAction)):!1,agentHit=entry.applies_to_agents&&entry.applies_to_agents.length>0?entry.applies_to_agents.map(lc).some((a)=>a===lc(ctx.targetAgent)):!1,score=0;if(triggerHit)score+=0.5;if(actionHit)score+=0.35;if(agentHit)score+=0.25;if(entry.directive_priority==="critical")score+=0.4;else if(entry.directive_priority==="high")score+=0.2;else if(entry.directive_priority==="medium")score+=0.1;return{triggerHit,actionHit,agentHit,score:Math.min(1,score)}}var JACCARD_THRESHOLD2=0.6,HIVE_TIER_BOOST=0.05,DEFAULT_SAME_PROJECT_PENALTY=-0.05,_internals182;var init_knowledge_reader=__esm(()=>{init_task_file();init_logger();init_knowledge_events();init_knowledge_store();init_knowledge_types();_internals182={readMergedKnowledge,updateRetrievalOutcome,scoreDirectiveAgainstContext,transactShownFile,recordKnowledgeEvent,recordLessonsShown}});function entryText(e){return`${e.lesson} ${e.tags.join(" ")} ${e.category}`}function entryAgePhases(e){let cb=e.confirmed_by;if(!Array.isArray(cb)||cb.length===0)return 0;let phases=new Set;for(let c of cb)if(typeof c?.phase_number==="number")phases.add(c.phase_number);return phases.size>0?phases.size:cb.length}function clampLambda(v){if(typeof v!=="number"||Number.isNaN(v))return 0.5;return Math.min(1,Math.max(0,v))}function mmrRerank(pool,pinned,max,lambda){if(pool.length===0)return[];let bigrams=new Map,bg=(e)=>{let s=bigrams.get(e.id);if(!s)s=wordBigrams(normalize6(e.lesson??"")),bigrams.set(e.id,s);return s},selected=[...pinned],candidates=[...pool],out=[];while(selected.length<max&&candidates.length>0){let bestIdx=-1,bestScore=Number.NEGATIVE_INFINITY,best=null;for(let i=0;i<candidates.length;i++){let c=candidates[i],maxSim=0;for(let s of selected){let sim=jaccardBigram(bg(c),bg(s));if(sim>maxSim)maxSim=sim}let score=lambda*c.finalScore-(1-lambda)*maxSim;if(score>bestScore+0.000000001||Math.abs(score-bestScore)<=0.000000001&&best!==null&&tieBreak(c,best)<0)bestScore=score,bestIdx=i,best=c}if(bestIdx<0||best===null)break;out.push(best),selected.push(best),candidates.splice(bestIdx,1)}return out}function tieBreak(a,b){if(Math.abs(a.finalScore-b.finalScore)>0.000000001)return b.finalScore-a.finalScore;let at=new Date(a.created_at).getTime(),bt=new Date(b.created_at).getTime();if(at!==bt)return bt-at;return a.id<b.id?-1:a.id>b.id?1:0}function statusBoost(status){if(status==="promoted")return 0.15;if(status==="established")return 0.1;return 0}async function searchKnowledge(params){let{directory,config:config3,query,context,mode,agent="unknown",sessionId="unknown",tier="all",emitEvent=!1,applyScopeFilter=!0,forceReadHive=!1,applyRoleScope=!0}=params,traceId=newTraceId2(),max=params.maxResults??config3.max_inject_count??5,results=[],synonymTokens=[],synonymTrace={};try{let mergeConfig={...config3,hive_enabled:tier==="swarm"?!1:forceReadHive?!0:config3.hive_enabled,max_inject_count:Math.max(20,max)},projected={projectName:context?.projectName??"unknown",currentPhase:context?.currentPhase??"",techStack:context?.techStack,recentErrors:[...context?.recentReviewerFailures??[],...context?.recentTestFailures??[],...context?.recentToolErrors??[]]},candidates=await readMergedKnowledge(directory,mergeConfig,projected,{skipScopeFilter:!applyScopeFilter}),counterRollups=await readAuthoritativeKnowledgeCounterRollups(directory);candidates=candidates.filter((e)=>{if(!isActiveStatus(e.status))return!1;if(tier==="hive"&&e.tier!=="hive")return!1;return!0});let role=stripKnownSwarmPrefix(agent).toLowerCase();if(applyRoleScope&&role&&role!=="unknown")candidates=candidates.filter((e)=>{if(!e.applies_to_agents||e.applies_to_agents.length===0)return!0;if(role==="architect")return!0;return e.applies_to_agents.map((a)=>stripKnownSwarmPrefix(a).toLowerCase()).includes(role)});let queryText=(query??"").trim(),queryBigrams=queryText?wordBigrams(normalize6(queryText)):null,hasQuery=queryBigrams!==null,textWeight=hasQuery?TEXT_WEIGHT:0,metaWeight=hasQuery?META_WEIGHT:1,compositeRaw=[queryText,context?.taskTitle,context?.taskDescription,context?.lastUserMessage,context?.currentAction,...context?.recentReviewerFailures??[],...context?.recentTestFailures??[],...context?.recentToolErrors??[]].filter((s)=>typeof s==="string"&&s.length>0).join(" "),compositeNorm=normalize6(compositeRaw),hasComposite=compositeNorm.length>0;try{if(hasComposite){let synMap=await readSynonymMap(directory,config3.retrieval?.synonym_map_max_pairs),synIndex=buildSynonymIndex(synMap,config3.retrieval?.synonym_min_cooccurrence),baseTokens=compositeNorm.split(" ").filter(Boolean);synonymTokens=expandTokens(synIndex,baseTokens)}}catch{synonymTokens=[]}let minConf=typeof config3.directive_min_confidence==="number"?config3.directive_min_confidence:DIRECTIVE_BOOST_MIN_CONFIDENCE,scored=candidates.map((entry)=>{let retrievalOutcomes=effectiveRetrievalOutcomes(entry.retrieval_outcomes,counterRollups.get(entry.id)),textScore=queryBigrams?jaccardBigram(queryBigrams,wordBigrams(normalize6(entryText(entry)))):0,metaScore=entry.finalScore,ds=context?scoreDirectiveAgainstContext(entry,context):{triggerHit:!1,actionHit:!1,agentHit:!1,score:0},confBoost=context&&entry.confidence>=minConf&&(ds.actionHit||ds.agentHit)?0.25:0,generatedSkillBoost=entry.generated_skill_path&&entry.status!=="archived"?0.05:0,outcomeBoost=computeOutcomeSignal(retrievalOutcomes)*OUTCOME_RANK_WEIGHT,coldStartBonus=(retrievalOutcomes.applied_explicit_count??0)===0&&entryAgePhases(entry)<(config3.retrieval?.cold_start_max_age_phases??DEFAULT_COLD_START_MAX_AGE_PHASES)?config3.retrieval?.cold_start_bonus??DEFAULT_COLD_START_BONUS:0,synonymBoost=0;if(synonymTokens.length>0){let entryHay=normalize6(entryText(entry)),matched=[];for(let t of synonymTokens)if(t.length>0&&entryHay.includes(t))matched.push(t);if(matched.length>0)synonymBoost=SYNONYM_TEXT_BOOST,synonymTrace[entry.id]=matched}let triggerRecallBoost=!ds.triggerHit&&hasComposite&&Array.isArray(entry.triggers)&&entry.triggers.some((tr)=>{let n=normalize6(tr);return n.length>=TRIGGER_RECALL_MIN_LEN&&compositeNorm.includes(n)})?TRIGGER_RECALL_BOOST:0,finalScore=Math.min(1,Math.max(0,textWeight*textScore+metaWeight*metaScore+ds.score+confBoost+generatedSkillBoost+outcomeBoost+coldStartBonus+synonymBoost+triggerRecallBoost+(hasQuery&&!entry.confidence_floor_demoted?statusBoost(entry.status):0))),statusScoreBoost=hasQuery&&!entry.confidence_floor_demoted?statusBoost(entry.status):0,isCritical=entry.directive_priority==="critical"&&(ds.triggerHit||ds.actionHit||ds.agentHit),isForceHive=forceReadHive&&entry.tier==="hive";return{...entry,retrieval_outcomes:retrievalOutcomes,finalScore,coldStartBoost:coldStartBonus,score_breakdown:{text_score:textScore,metadata_score:metaScore,directive_score:ds.score,confidence_boost:confBoost,generated_skill_boost:generatedSkillBoost,outcome_boost:outcomeBoost,cold_start_boost:coldStartBonus,synonym_boost:synonymBoost,trigger_recall_boost:triggerRecallBoost,status_boost:statusScoreBoost,final_score:finalScore,...synonymTrace[entry.id]?{synonym_matches:synonymTrace[entry.id]}:{}},__critical:isCritical,__forceHive:isForceHive}});scored.sort((a,b)=>{let diff=b.finalScore-a.finalScore;if(Math.abs(diff)>0.001)return diff;return new Date(b.created_at).getTime()-new Date(a.created_at).getTime()});let top=[],seen=new Set;for(let e of scored){if(top.length>=max)break;if(e.__critical&&!seen.has(e.id))top.push(e),seen.add(e.id)}for(let e of scored){if(top.length>=max)break;if(e.__forceHive&&!seen.has(e.id))top.push(e),seen.add(e.id)}let lambda=clampLambda(config3.retrieval?.mmr_lambda),remaining=scored.filter((e)=>!seen.has(e.id)),selected=mmrRerank(remaining,top,max,lambda);for(let e of selected){if(top.length>=max)break;if(!seen.has(e.id))top.push(e),seen.add(e.id)}results=top.map(({__critical:_c,__forceHive:_f,...rest})=>rest)}catch(err){warn(`[search-knowledge] retrieval failed: ${err instanceof Error?err.message:String(err)}`),results=[]}if(emitEvent){let ranks={},scores={};results.forEach((e,idx)=>{ranks[e.id]=idx+1,scores[e.id]=e.finalScore});let synonymBreakdown={};for(let e of results)if(synonymTrace[e.id])synonymBreakdown[e.id]=synonymTrace[e.id];let scoreBreakdown=synonymTokens.length>0?{synonyms_expanded:synonymTokens,synonym_matches:synonymBreakdown}:void 0;await recordKnowledgeEvent(directory,{type:"retrieved",trace_id:traceId,session_id:sessionId,phase:context?.currentPhase,task_id:context?.taskId,agent,query:query??context?.lastUserMessage??context?.currentPhase??"",retrieval_mode:mode,result_ids:results.map((e)=>e.id),ranks,scores,...scoreBreakdown?{score_breakdown:scoreBreakdown}:{}})}return{trace_id:traceId,results}}var TEXT_WEIGHT=0.6,META_WEIGHT=0.4,DIRECTIVE_BOOST_MIN_CONFIDENCE=0.75,SYNONYM_TEXT_BOOST=0.15,TRIGGER_RECALL_BOOST=0.3,TRIGGER_RECALL_MIN_LEN=3,DEFAULT_COLD_START_BONUS=0.08,DEFAULT_COLD_START_MAX_AGE_PHASES=3,OUTCOME_RANK_WEIGHT=0.1;var init_search_knowledge=__esm(()=>{init_schema();init_synonym_map();init_logger();init_knowledge_events();init_knowledge_reader();init_knowledge_store();init_knowledge_types()});var exports_knowledge_recall={};__export(exports_knowledge_recall,{knowledge_recall:()=>knowledge_recall,_internals:()=>_internals183});var knowledge_recall,_internals183;var init_knowledge_recall=__esm(()=>{init_zod();init_config();init_schema();init_knowledge_events();init_knowledge_receipt_ledger();init_knowledge_types();init_search_knowledge();init_knowledge_diagnostics();init_logger();init_create_tool();knowledge_recall=createSwarmTool({allowWorkingDirectoryOverride:!0,description:"Performs semantic natural-language search across the knowledge base for relevant past decisions, patterns, and lessons learned. Returns ranked results via the unified hybrid retrieval service and a trace_id for knowledge_receipt. This is the tool to use when the user has a QUESTION about what the knowledge base contains. For structured filter-based retrieval (by category, status, or score), use `knowledge_query` instead.",args:{query:exports_external.string().min(3).describe("Natural language search query"),top_n:exports_external.number().int().min(1).max(20).optional().describe("Maximum results to return (default: 5)"),tier:exports_external.enum(["all","swarm","hive"]).optional().describe("Knowledge tier to search (default: 'all')"),debug:exports_external.boolean().optional().describe("Include path/version/health debug metadata in the response"),repair_re_evaluation:exports_external.object({repair_id:exports_external.string().uuid(),phase:exports_external.string().min(1).max(256),task_id:exports_external.string().min(1).max(256).optional(),scope_complete:exports_external.boolean()}).optional().describe("Architect-only explicit completion of a repaired receipt scope. The query must comprehensively re-evaluate the exact affected phase/session scope.")},execute:async(args2,directory,ctx)=>{let queryInput,topNInput,tierInput,debugInput,repairInput;try{if(args2&&typeof args2==="object"){let obj=args2;queryInput=obj.query,topNInput=obj.top_n,tierInput=obj.tier,debugInput=obj.debug,repairInput=obj.repair_re_evaluation}}catch{}let wantDebug=debugInput===!0,repairReevaluation;if(repairInput!==void 0){if(stripKnownSwarmPrefix(ctx?.agent??"")!=="architect"||typeof repairInput!=="object"||repairInput===null)return JSON.stringify({results:[],total:0,unverifiable:!0,code:"RECEIPT_REEVALUATION_ARCHITECT_ONLY",error:"Only the architect may complete an explicit receipt repair re-evaluation."});let candidate2=repairInput;if(typeof candidate2.repair_id!=="string"||!candidate2.repair_id||typeof candidate2.phase!=="string"||!candidate2.phase||candidate2.scope_complete!==!0||candidate2.task_id!==void 0&&typeof candidate2.task_id!=="string")return JSON.stringify({results:[],total:0,unverifiable:!0,code:"RECEIPT_REEVALUATION_PROOF_INVALID",error:"Explicit re-evaluation requires repair_id, exact phase, and scope_complete=true."});repairReevaluation={repair_id:candidate2.repair_id,phase:candidate2.phase,scope_complete:!0,...typeof candidate2.task_id==="string"?{task_id:candidate2.task_id}:{}}}if(typeof queryInput!=="string"||queryInput.length<3)return JSON.stringify({results:[],total:0,error:"query must be a string with at least 3 characters"});let topN=5;if(typeof topNInput==="number"&&Number.isInteger(topNInput))topN=Math.max(1,Math.min(20,topNInput));let tier="all";if(tierInput==="swarm"||tierInput==="hive")tier=tierInput;let knowledgeConfig=KnowledgeConfigSchema.parse({});try{let{config:config3}=loadPluginConfigWithMeta(directory);knowledgeConfig=KnowledgeConfigSchema.parse(config3.knowledge??{})}catch{}let{trace_id,results}=await searchKnowledge({directory,config:knowledgeConfig,query:queryInput,mode:"manual",agent:ctx?.agent??"unknown",sessionId:ctx?.sessionID??"unknown",tier,maxResults:topN,applyScopeFilter:!1,forceReadHive:!0,applyRoleScope:!1,emitEvent:!1}),sessionId=ctx?.sessionID??"unknown";if(results.length>0){let membership=await commitDisplayedMembership(directory,{trace_id,session_id:sessionId,exposure_kind:"manual_recall",agent:ctx?.agent??"unknown",grace_days:knowledgeConfig.receipt_close_grace_days,phase:repairReevaluation?.phase,task_id:repairReevaluation?.task_id,repair_re_evaluation:repairReevaluation,entries:results.map((entry,index)=>({entry_id:entry.id,critical:entry.directive_priority==="critical"&&isActiveStatus(entry.status),rank:index+1,score:entry.finalScore}))});if(!membership.ok||membership.memberships.some((item)=>item.terminal))return JSON.stringify({results:[],total:0,unverifiable:!0,code:membership.ok?"terminal_trace_reuse":membership.code,error:membership.ok?"retrieval trace was already terminalized":membership.detail})}else{let empty=await commitEmptyRetrieval(directory,{trace_id,session_id:sessionId,agent:ctx?.agent??"unknown",grace_days:knowledgeConfig.receipt_close_grace_days,phase:repairReevaluation?.phase,task_id:repairReevaluation?.task_id,repair_re_evaluation:repairReevaluation});if(!empty.ok)return JSON.stringify({results:[],total:0,unverifiable:!0,code:empty.code,error:empty.detail});if(!empty.terminal_event_id)return JSON.stringify({results:[],total:0,unverifiable:!0,code:"store_unavailable",error:"empty retrieval terminal did not commit"})}let ranks=Object.fromEntries(results.map((entry,index)=>[entry.id,index+1])),scores=Object.fromEntries(results.map((entry)=>[entry.id,entry.finalScore]));await recordKnowledgeEvent(directory,{type:"retrieved",trace_id,session_id:sessionId,agent:ctx?.agent??"unknown",query:queryInput,retrieval_mode:"manual",result_ids:results.map((entry)=>entry.id),ranks,scores});let scored=results.map((e)=>({id:e.id,confidence:e.confidence,category:e.category,lesson:e.lesson,score:e.finalScore,score_breakdown:e.score_breakdown}));log("[knowledge_recall] completed",{agent:ctx?.agent??"unknown",session_id:ctx?.sessionID??"unknown",query:queryInput,tier,result_count:scored.length,trace_id});let result={results:scored,total:scored.length,trace_id};if(wantDebug)result.debug=await computeKnowledgeDebug(directory);return JSON.stringify(result)}}),_internals183={knowledge_recall}});var exports_prompt_renderer={};__export(exports_prompt_renderer,{renderEnvironmentPrompt:()=>renderEnvironmentPrompt});function renderEnvironmentPrompt(profile,audience){let policy=deriveCommandPolicy(profile),header=["RUNTIME ENVIRONMENT",`- Host OS: ${profile.hostOS}`,`- Shell family: ${profile.shellFamily}`,`- Execution mode: ${profile.executionMode}`,`- Path style: ${profile.pathStyle}`].join(`
|
|
6319
6319
|
`);if(audience==="coder")return[header,policy.avoidPosixExamples?"- Command policy: Prefer PowerShell-native commands and Node.js APIs. Do not start with POSIX commands (ls, grep, rm, cat, export, pwd) unless the environment profile indicates Docker, WSL, or a POSIX shell.":"- Command policy: Use POSIX-native commands and Node.js APIs.","","EXECUTION ENVIRONMENT AWARENESS","- This session includes a runtime environment profile. Follow it exactly.","- Decision ladder when shell commands are necessary:"," 1. Prefer swarm tools and Node.js fs/path APIs."," 2. Use shell only when the task truly requires it."," 3. When shell commands are needed, match the active shell family above."].join(`
|
|
6320
6320
|
`);return[header,"- Test execution policy: Always execute tests via the swarm test runner tool.",policy.avoidPosixExamples?" Do not describe POSIX shell setup commands unless the profile indicates Docker, WSL, or POSIX shell.":" Use POSIX semantics for test commands.","","ENVIRONMENT-SPECIFIC TEST EXECUTION RULES",profile.isWindowsNative?"- Native Windows + PowerShell: Assume PowerShell semantics for paths and env vars. Prefer Pester for PowerShell modules where appropriate.":profile.isWindowsDocker?"- Windows + Docker: Host paths are Windows-style; in-container operations use POSIX semantics.":"- Linux/macOS: Use POSIX semantics for all shell-related reasoning.","- In all modes: prefer the swarm test runner over ad hoc shell commands.","- When tests are skipped due to environment issues, explicitly mention the environment profile assumptions in your verdict."].join(`
|
|
6321
6321
|
`)}var init_prompt_renderer=()=>{};var exports_design_doc_drift={};__export(exports_design_doc_drift,{runDesignDocDriftCheck:()=>runDesignDocDriftCheck,_internals:()=>_internals228});import*as fs175 from"node:fs";import*as path290 from"node:path";function mtimeMsOrNull(absPath){try{return fs175.statSync(absPath).mtimeMs}catch{return null}}function resolveAnchorWithin(directory,anchor){if(!anchor||typeof anchor!=="string")return null;let root=path290.resolve(directory),resolved=path290.resolve(root,anchor),rel=path290.relative(root,resolved);if(rel.startsWith("..")||path290.isAbsolute(rel))return null;return resolved}async function runDesignDocDriftCheck(directory,phase,outDir){try{let root=path290.resolve(directory),outAbs=path290.resolve(root,outDir),outRel=path290.relative(root,outAbs);if(outRel.startsWith("..")||path290.isAbsolute(outRel))return null;let docMtimes=new Map,checkedDocs=[],missingDocs=[];for(let[docName,relFile]of Object.entries(DESIGN_DOC_FILES)){let abs=path290.join(outAbs,relFile),mtime=mtimeMsOrNull(abs);if(docMtimes.set(docName,mtime),mtime===null)missingDocs.push(path290.join(outDir,relFile));else checkedDocs.push(path290.join(outDir,relFile))}let traceabilityAbs=path290.join(outAbs,TRACEABILITY_REL),registry3=null;try{if((await fs175.promises.stat(traceabilityAbs)).size<=MAX_TRACEABILITY_BYTES){let raw=await fs175.promises.readFile(traceabilityAbs,"utf-8"),parsed=JSON.parse(raw);registry3=parsed&&typeof parsed==="object"&&!Array.isArray(parsed)?parsed:null}}catch{registry3=null}let noDocs=checkedDocs.length===0||registry3===null,effectiveSpec=readEffectiveSpecSync(root),specMtime=effectiveSpec?.mtime?Date.parse(effectiveSpec.mtime):null,staleSections=[];if(!noDocs&&Array.isArray(registry3?.sections))for(let section of registry3.sections){if(!section||typeof section.section_id!=="string")continue;if(typeof section.doc!=="string"||!docMtimes.has(section.doc))continue;let docMtime=docMtimes.get(section.doc)??null;if(docMtime===null){staleSections.push({section_id:section.section_id,doc:section.doc,reason:"owning design doc is missing"});continue}let flagged=!1;for(let anchor of section.code_anchors??[]){let anchorAbs=resolveAnchorWithin(directory,anchor);if(anchorAbs===null)continue;let anchorMtime=mtimeMsOrNull(anchorAbs);if(anchorMtime!==null&&anchorMtime>docMtime){staleSections.push({section_id:section.section_id,doc:section.doc,reason:`code anchor ${anchor} changed after the doc`}),flagged=!0;break}}if(!flagged&&specMtime!==null&&specMtime>docMtime&&(section.spec_frs?.length??0)>0)staleSections.push({section_id:section.section_id,doc:section.doc,reason:"effective spec changed after the doc"})}let verdict=noDocs?"NO_DOCS":staleSections.length>0?"DOC_STALE":"DOC_FRESH",report={schema_version:1,phase,timestamp:new Date().toISOString(),out_dir:outDir,verdict,stale_sections:staleSections,missing_docs:missingDocs,checked_docs:checkedDocs},filename=`${DOC_DRIFT_REPORT_PREFIX}${phase}.json`,filePath=validateSwarmPath(directory,filename);return await fs175.promises.mkdir(path290.dirname(filePath),{recursive:!0}),await fs175.promises.writeFile(filePath,JSON.stringify(report,null,2),"utf-8"),getGlobalEventBus().publish("curator.docdrift.completed",{phase,verdict,stale_count:staleSections.length,report_path:filePath}),report}catch(err){try{getGlobalEventBus().publish("curator.error",{operation:"docdrift",phase,error:String(err)})}catch{}return warn(`[design-doc-drift] check failed for phase ${phase}: ${String(err)}`),null}}var DOC_DRIFT_REPORT_PREFIX="doc-drift-phase-",MAX_TRACEABILITY_BYTES=1048576,DESIGN_DOC_FILES,TRACEABILITY_REL,_internals228;var init_design_doc_drift=__esm(()=>{init_event_bus();init_effective_spec();init_logger();init_utils2();DESIGN_DOC_FILES={domain:"domain.md","technical-spec":"technical-spec.md","behavior-spec":"behavior-spec.md","reference-impl":path290.join("reference","reference-impl.md"),"idiom-notes":path290.join("reference","idiom-notes.md")},TRACEABILITY_REL=path290.join("reference","traceability.json");_internals228={mtimeMsOrNull,resolveAnchorWithin,DESIGN_DOC_FILES}});var exports_project_context={};__export(exports_project_context,{buildProjectContext:()=>buildProjectContext,_internals:()=>_internals256,LANG_BACKEND_DETECTION_TIMEOUT_MS:()=>LANG_BACKEND_DETECTION_TIMEOUT_MS});import*as fs206 from"node:fs";import*as path328 from"node:path";function detectFileExists2(directory,pattern){if(pattern.includes("*")||pattern.includes("?"))try{let files=fs206.readdirSync(directory),regex=new RegExp(`^${pattern.replace(/\./g,"\\.").replace(/\*/g,".*").replace(/\?/g,".")}$`);return files.some((f)=>regex.test(f))}catch{return!1}try{return fs206.accessSync(path328.join(directory,pattern)),!0}catch{return!1}}function selectTestCommandFromScriptsTest(backend,directory){let pkgRaw;try{pkgRaw=fs206.readFileSync(path328.join(directory,"package.json"),"utf-8")}catch{return null}let pkg;try{pkg=JSON.parse(pkgRaw)}catch{return null}let script=pkg.scripts?.test;if(!script)return null;let fwName=null;if(script.includes("vitest"))fwName="vitest";else if(script.includes("jest"))fwName="jest";else if(script.includes("mocha"))fwName="mocha";else if(script.includes("bun test"))fwName="bun:test";if(!fwName)return null;let fw=backend.test.frameworks.find((f)=>f.name===fwName);return fw?fw.cmd:null}function selectTestCommandFast(backend,directory){let fromScripts=selectTestCommandFromScriptsTest(backend,directory);if(fromScripts!==null)return fromScripts;let sorted=[...backend.test.frameworks].sort((a,b)=>b.priority-a.priority);for(let fw of sorted){if(!detectFileExists2(directory,fw.detect))continue;return fw.cmd}return null}function selectBuildCommandFast(backend,directory){let sorted=[...backend.build.commands].sort((a,b)=>b.priority-a.priority);for(let cmd of sorted){if(cmd.detectFile&&!detectFileExists2(directory,cmd.detectFile))continue;return cmd.cmd}return null}function selectLintCommand(backend,directory){let sorted=[...backend.lint.linters].sort((a,b)=>b.priority-a.priority);for(let lint2 of sorted){if(!detectFileExists2(directory,lint2.detect))continue;return lint2.cmd}return null}async function buildProjectContext(directory){let backend=await _internals256.pickBackend(directory);if(!backend)return null;let ctx=emptyProjectContext();ctx.PROJECT_LANGUAGE=backend.displayName;let buildCmd=selectBuildCommandFast(backend,directory);if(buildCmd)ctx.BUILD_CMD=buildCmd;let testCmd=selectTestCommandFast(backend,directory);if(testCmd)ctx.TEST_CMD=testCmd;let lintCmd=selectLintCommand(backend,directory);if(lintCmd)ctx.LINT_CMD=lintCmd;if(backend.id==="php"){let overlay=getLaravelCommandOverlay(directory);if(overlay){if(ctx.TEST_CMD=overlay.testCommand,overlay.lintCommand)ctx.LINT_CMD=overlay.lintCommand}}let[frameworkSel,entryPoints]=await Promise.all([backend.selectFramework?backend.selectFramework(directory).catch(()=>null):Promise.resolve(null),backend.selectEntryPoints?backend.selectEntryPoints(directory).catch(()=>[]):Promise.resolve([])]);if(frameworkSel)ctx.PROJECT_FRAMEWORK=frameworkSel.name;if(entryPoints.length>0)ctx.ENTRY_POINTS=entryPoints.join(", ");if(backend.prompts.coderConstraints.length>0)ctx.CODER_CONSTRAINTS=bulletList(backend.prompts.coderConstraints);if(backend.prompts.testConstraints&&backend.prompts.testConstraints.length>0)ctx.TEST_CONSTRAINTS=bulletList(backend.prompts.testConstraints);if(backend.prompts.reviewerChecklist.length>0)ctx.REVIEWER_CHECKLIST=bulletList(backend.prompts.reviewerChecklist);let profiles=_internals256.pickedProfiles(directory);if(profiles.length>1)ctx.PROJECT_CONTEXT_SECONDARY_LANGUAGES=profiles.slice(1).map((p)=>p.id).join(", ");return ctx}var LANG_BACKEND_DETECTION_TIMEOUT_MS=300,_internals256;var init_project_context=__esm(()=>{init_dispatch();init_framework_detector();_internals256={pickBackend,pickedProfiles}});init_package();init_agents2();init_critic();import*as path329 from"node:path";import{performance as performance2}from"node:perf_hooks";import{fileURLToPath as fileURLToPath7}from"node:url";init_event_bus();init_evidence_summary_integration();init_manager3();init_manager();init_utils();import*as fs114 from"node:fs";import*as path215 from"node:path";class PlanSyncWorker{directory;debounceMs;pollIntervalMs;syncTimeoutMs;onSyncComplete;status="stopped";watcher=null;pollTimer=null;debounceTimer=null;syncing=!1;pendingSync=!1;lastStat=null;disposed=!1;constructor(options={}){this.directory=options.directory??"",this.debounceMs=options.debounceMs??500,this.pollIntervalMs=options.pollIntervalMs??2000,this.syncTimeoutMs=options.syncTimeoutMs??30000,this.onSyncComplete=options.onSyncComplete}getSwarmDir(){return path215.resolve(this.directory,".swarm")}getPlanJsonPath(){return path215.join(this.getSwarmDir(),"plan.json")}start(){if(this.disposed){log("[PlanSyncWorker] Cannot start - worker has been disposed");return}if(!this.directory){log("[PlanSyncWorker] Cannot start - no directory provided");return}if(this.status==="running"||this.status==="starting"){log("[PlanSyncWorker] Already running or starting");return}this.status="starting",log("[PlanSyncWorker] Starting..."),this.initializeStat(),this.setupPolling(),this.setupNativeWatcher(),this.status="running",log("[PlanSyncWorker] Started watching for plan.json changes")}stop(){if(this.status==="stopped"||this.status==="stopping")return;if(this.status="stopping",log("[PlanSyncWorker] Stopping..."),this.clearDebounce(),this.watcher)this.watcher.close(),this.watcher=null;if(this.pollTimer)clearInterval(this.pollTimer),this.pollTimer=null;this.status="stopped",log("[PlanSyncWorker] Stopped")}dispose(){this.stop(),this.disposed=!0,this.lastStat=null,log("[PlanSyncWorker] Disposed")}getStatus(){return this.status}isRunning(){return this.status==="running"}initializeStat(){try{let stats2=fs114.statSync(this.getPlanJsonPath());this.lastStat={mtimeMs:stats2.mtimeMs,size:stats2.size}}catch{this.lastStat=null}}setupNativeWatcher(){let swarmDir=this.getSwarmDir();try{if(!fs114.existsSync(swarmDir))return log("[PlanSyncWorker] Swarm directory does not exist yet"),!1;return this.watcher=fs114.watch(swarmDir,{persistent:!1},(_eventType,filename)=>{if(this.disposed||this.status!=="running")return;if(filename&&(filename.includes(".tmp.")||filename.endsWith(".rebuild")))return;if(filename==="plan.json"||filename===void 0)this.debouncedSync()}),this.watcher.on("error",(error93)=>{if(this.disposed||this.status!=="running")return;if(log("[PlanSyncWorker] Watcher error, falling back to polling",{error:error93.message}),this.watcher)this.watcher.close(),this.watcher=null;this.setupPolling()}),log("[PlanSyncWorker] Native fs.watch established"),!0}catch(error93){return log("[PlanSyncWorker] Failed to setup native watcher",{error:error93 instanceof Error?error93.message:String(error93)}),!1}}setupPolling(){if(this.pollTimer)clearInterval(this.pollTimer);if(this.pollTimer=setInterval(()=>{if(this.disposed||this.status!=="running")return;this.pollCheck()},this.pollIntervalMs),typeof this.pollTimer.unref==="function")this.pollTimer.unref();log("[PlanSyncWorker] Polling fallback established",{intervalMs:this.pollIntervalMs})}pollCheck(){try{let planPath=this.getPlanJsonPath();if(!fs114.existsSync(planPath)){if(this.lastStat!==null)this.lastStat=null,log("[PlanSyncWorker] plan.json deleted");return}let stats2=fs114.statSync(planPath),currentStat={mtimeMs:stats2.mtimeMs,size:stats2.size};if(this.lastStat===null||currentStat.mtimeMs!==this.lastStat.mtimeMs||currentStat.size!==this.lastStat.size)this.lastStat=currentStat,this.debouncedSync()}catch(error93){log("[PlanSyncWorker] Poll check error",{error:error93 instanceof Error?error93.message:String(error93)})}}debouncedSync(){if(this.disposed||this.status!=="running")return;if(this.debounceTimer)clearTimeout(this.debounceTimer);this.debounceTimer=setTimeout(()=>{if(this.disposed||this.status!=="running")return;this.debounceTimer=null,this.triggerSync()},this.debounceMs)}clearDebounce(){if(this.debounceTimer)clearTimeout(this.debounceTimer),this.debounceTimer=null}triggerSync(){if(this.syncing){this.pendingSync=!0,log("[PlanSyncWorker] Sync pending (in-flight)");return}this.executeSync()}async executeSync(){this.syncing=!0;try{log("[PlanSyncWorker] Syncing plan..."),this.checkForUnauthorizedWrite();let plan=await this.withTimeout(_internals32.loadPlanJsonOnly(this.directory),this.syncTimeoutMs,"Sync operation timed out");if(plan&&plan.phases.length>0)await _internals32.regeneratePlanMarkdown(this.directory,plan),log("[PlanSyncWorker] Sync complete",{title:plan.title,phase:plan.current_phase}),this.safeCallback(!0);else if(plan)log("[PlanSyncWorker] Plan has no phases, skipping markdown regeneration"),this.safeCallback(!0);else log("[PlanSyncWorker] No plan found to sync"),this.safeCallback(!0)}catch(error93){if(error93 instanceof Error&&error93.message.includes("timed out"))log("[PlanSyncWorker] Sync timed out after "+this.syncTimeoutMs+"ms, worker remains active");else log("[PlanSyncWorker] Sync failed",{error:error93 instanceof Error?error93.message:String(error93)});this.safeCallback(!1,error93 instanceof Error?error93:Error(String(error93)))}finally{if(this.syncing=!1,this.pendingSync&&!this.disposed&&this.status==="running")this.pendingSync=!1,log("[PlanSyncWorker] Executing pending sync"),this.executeSync()}}safeCallback(success3,error93){if(this.onSyncComplete)try{this.onSyncComplete(success3,error93)}catch(callbackError){log("[PlanSyncWorker] onSyncComplete callback threw error (ignored)",{callbackError:callbackError instanceof Error?callbackError.message:String(callbackError)})}}checkForUnauthorizedWrite(){try{let swarmDir=this.getSwarmDir(),planJsonPath=path215.join(swarmDir,"plan.json"),markerPath=path215.join(swarmDir,".plan-write-marker"),planStats=fs114.statSync(planJsonPath),planMtimeMs=Math.floor(planStats.mtimeMs),markerContent=fs114.readFileSync(markerPath,"utf8"),marker=JSON.parse(markerContent);if(marker.in_progress===!0){log("[PlanSyncWorker] Skipping unauthorized-write check - plan write in progress");return}let markerTimestampMs=new Date(marker.timestamp).getTime();if(planMtimeMs>markerTimestampMs+5000)log("[PlanSyncWorker] WARNING: plan.json may have been written outside save_plan/savePlan - unauthorized direct write suspected",{planMtimeMs,markerTimestampMs})}catch{}}withTimeout(promise3,ms,timeoutMessage2){return new Promise((resolve88,reject)=>{let timer=setTimeout(()=>{reject(Error(`${timeoutMessage2} (${ms}ms)`))},ms);promise3.then((result)=>{clearTimeout(timer),resolve88(result)}).catch((error93)=>{clearTimeout(timer),reject(error93)})})}}init_pr_event_subscribers();import*as child_process10 from"node:child_process";init_zod();init_gh_evidence();init_bun_compat();init_logger();init_branch();var GIT_TIMEOUT_MS8=30000,EvidencePlanSchema=exports_external.object({phases:exports_external.array(exports_external.object({tasks:exports_external.array(exports_external.object({id:exports_external.string(),status:exports_external.string().optional()}).passthrough()).optional()}).passthrough()).optional()}).passthrough();function ghExec(args2,cwd){let ghBinary=_internals169.resolveGhBinary()??"gh";for(let attempt=0;attempt<MAX_TRANSIENT_RETRIES;attempt++){let result=child_process10.spawnSync(ghBinary,args2,{cwd,encoding:"utf-8",timeout:GIT_TIMEOUT_MS8,windowsHide:!0,maxBuffer:MAX_OUTPUT_BYTES5,stdio:["ignore","pipe","pipe"]});if(result.error){if(isTransientSpawnError(result.error)&&attempt<MAX_TRANSIENT_RETRIES-1){transientBackoff(attempt);continue}if(result.error.code==="ENOENT")throw Error("gh failed to start: ENOENT — gh not installed or not on PATH");throw Error(`gh failed to start: ${result.error.code} — ${result.error.message}`)}if(result.status!==0)throw Error(result.stderr||result.stdout||`gh exited with ${result.status}`);return result.stdout}throw Error("gh exited with null")}var MAX_OUTPUT_BYTES5=5242880,__spawnSyncSeam2={spawnSync:(cmd,args2,options)=>{let mergedEnv=mergeEnvForChild(options?.env,options?.envOverrides);return child_process10.spawnSync(cmd,args2,{...options,env:mergedEnv})}};function spawnSyncWithTransientRetry(command,args2,options){for(let attempt=0;attempt<MAX_TRANSIENT_RETRIES;attempt++){let result=__spawnSyncSeam2.spawnSync(command,args2,options);if(result.error){if(isTransientSpawnError(result.error)&&attempt<MAX_TRANSIENT_RETRIES-1){transientBackoff(attempt);continue}throw Error(`${command} failed: ${result.error.code} — ${result.error.message}`)}if(result.status!==0){let reason=result.stderr||result.stdout||`${command} exited with ${result.status}`;throw Error(`${command} failed: ${reason}`)}return result}throw Error(`${command} exited with null`)}async function ghExecAsync(args2,cwd){return new Promise((resolve90,reject)=>{let ghBinary=_internals169.resolveGhBinary()??"gh",proc=child_process10.spawn(ghBinary,args2,{cwd,stdio:["ignore","pipe","pipe"]}),stdoutChunks=[],stderrChunks=[],stdoutBytes=0,stderrBytes=0,settled=!1;function cleanup(){if(clearTimeout(timer),!proc.killed)try{proc.kill()}catch{}}function settle(fn2){if(settled)return;settled=!0,cleanup(),fn2()}proc.stdout?.on("data",(chunk)=>{if(stdoutBytes+=chunk.length,stdoutBytes>MAX_OUTPUT_BYTES5){settle(()=>reject(Error(`gh ${args2[0]} stdout exceeded ${MAX_OUTPUT_BYTES5} bytes`)));return}stdoutChunks.push(chunk)}),proc.stderr?.on("data",(chunk)=>{if(stderrBytes+=chunk.length,stderrBytes>MAX_OUTPUT_BYTES5){settle(()=>reject(Error(`gh ${args2[0]} stderr exceeded ${MAX_OUTPUT_BYTES5} bytes`)));return}stderrChunks.push(chunk)});let timer=setTimeout(()=>{settle(()=>reject(Error(`gh ${args2[0]} timed out after ${GIT_TIMEOUT_MS8}ms`)))},GIT_TIMEOUT_MS8);proc.on("error",(err)=>{settle(()=>reject(err))}),proc.on("close",(code)=>{settle(()=>{if(code!==0){let stderr=Buffer.concat(stderrChunks).toString("utf-8");reject(Error(stderr||`gh exited with ${code}`))}else{let stdout=Buffer.concat(stdoutChunks).toString("utf-8");resolve90(stdout)}})})})}var _internals169={ghExec,ghExecAsync,spawnSyncWithTransientRetry,spawnSync:__spawnSyncSeam2.spawnSync,readLaneEnvFileFromDiskSync,getMergeGroupRun,resolveGhBinary};async function getPRStatus(prNumber,repoFullName,cwd){let stdout;try{stdout=await _internals169.ghExecAsync(["pr","view",String(prNumber),"--repo",repoFullName,"--json","number,state,mergeable,mergeStateStatus,headRefOid,statusCheckRollup"],cwd)}catch(err){throw Error(`Failed to fetch PR status for ${repoFullName}#${prNumber}: ${err instanceof Error?err.message:String(err)}`)}return JSON.parse(stdout)}async function getPRComments(prNumber,repoFullName,cwd,since){let query=since?`?since=${since}`:"",issueCommentsPath=`repos/${repoFullName}/issues/${prNumber}/comments${query}`,reviewCommentsPath=`repos/${repoFullName}/pulls/${prNumber}/comments${query}`,issueComments,reviewComments;try{let issueRaw=await _internals169.ghExecAsync(["api",issueCommentsPath],cwd);issueComments=JSON.parse(issueRaw)}catch(err){throw Error(`Failed to fetch issue comments for ${repoFullName}#${prNumber}: ${err instanceof Error?err.message:String(err)}`)}try{let reviewRaw=await _internals169.ghExecAsync(["api",reviewCommentsPath],cwd);reviewComments=JSON.parse(reviewRaw)}catch(err){throw Error(`Failed to fetch review comments for ${repoFullName}#${prNumber}: ${err instanceof Error?err.message:String(err)}`)}let mapIssueComment=(c)=>({id:String(c.id??""),author:String(c.user?.login??""),body:neutralizeUntrustedMarkdown(String(c.body??""),"GitHub issue comment"),createdAt:String(c.created_at??""),isReviewComment:!1}),mapReviewComment=(c)=>({id:String(c.id??""),author:String(c.user?.login??""),body:neutralizeUntrustedMarkdown(String(c.body??""),"GitHub review comment"),createdAt:String(c.created_at??""),isReviewComment:!0});return[...issueComments.map(mapIssueComment),...reviewComments.map(mapReviewComment)]}async function getMergeState(prNumber,repoFullName,cwd){let stdout;try{stdout=await _internals169.ghExecAsync(["pr","view",String(prNumber),"--repo",repoFullName,"--json","mergeable,mergeStateStatus,headRefOid"],cwd)}catch(err){throw Error(`Failed to fetch merge state for ${repoFullName}#${prNumber}: ${err instanceof Error?err.message:String(err)}`)}let parsed=JSON.parse(stdout);return{mergeable:parsed.mergeable,mergeStateStatus:parsed.mergeStateStatus,headRefOid:parsed.headRefOid}}async function getPRReviewState(prNumber,repoFullName,cwd){let stdout;try{stdout=await _internals169.ghExecAsync(["pr","view",String(prNumber),"--repo",repoFullName,"--json","reviewDecision,reviewRequests"],cwd)}catch(err){throw Error(`Failed to fetch review state for ${repoFullName}#${prNumber}: ${err instanceof Error?err.message:String(err)}`)}let parsed=JSON.parse(stdout);return{reviewDecision:parsed.reviewDecision??"",reviewRequestCount:parsed.reviewRequests?.length??0}}async function getMergeGroupRun(statusCheckRollup,repoFullName,cwd){let mergeGroupCheck=statusCheckRollup.find((check3)=>check3.name==="Merge pull request"&&check3.detailsUrl);if(!mergeGroupCheck?.detailsUrl)return null;let runIdMatch=mergeGroupCheck.detailsUrl.match(/\/actions\/runs\/(\d+)/);if(!runIdMatch)return null;let runId=runIdMatch[1],stdout;try{stdout=await _internals169.ghExecAsync(["run","view",runId,"--json","status,conclusion,htmlUrl","--repo",repoFullName],cwd)}catch(err){throw Error(`Failed to fetch merge group run for ${repoFullName}: ${err instanceof Error?err.message:String(err)}`)}let parsed=JSON.parse(stdout);return{status:parsed.status??"",conclusion:parsed.conclusion??null,htmlUrl:parsed.htmlUrl??""}}init_utils();init_event_bus();init_pr_subscriptions();var MEANINGFUL_SNAPSHOT_FIELDS=["isWatching","headRefOid","mergeGroupRunStatus","mergeGroupRunConclusion","mergeGroupRunHtmlUrl","lastCommentId"];function shouldSkipIdlePoll(idleCount,cycleNumber){if(idleCount<3)return!1;let skipEvery=idleCount>=6?3:2;return cycleNumber%skipEvery!==0}class PrMonitorWorker{directory;config;onEvent;status="stopped";pollTimer=null;disposed=!1;circuitBreakerMap=new Map;idlePollCountMap=new Map;pollCycleCount=0;reviewStateMap=new Map;mergedOrClosedKeys=new Set;constructor(options){this.directory=options.directory,this.config=options.config,this.onEvent=options.onEvent}start(){if(this.disposed){log("[PrMonitorWorker] Cannot start — worker has been disposed");return}if(!this.directory){log("[PrMonitorWorker] Cannot start — no directory provided");return}if(!this.config.enabled){log("[PrMonitorWorker] Cannot start — pr_monitor.enabled is false");return}if(this.status==="running"||this.status==="starting"){log("[PrMonitorWorker] Already running or starting");return}if(this.status="starting",log("[PrMonitorWorker] Starting..."),this.pollTimer=setInterval(()=>{if(this.disposed||this.status!=="running")return;this.executePollCycle().catch((err)=>{log("[PrMonitorWorker] Unhandled poll cycle error",{error:err instanceof Error?err.message:String(err)})})},this.config.poll_interval_seconds*1000),typeof this.pollTimer.unref==="function")this.pollTimer.unref();this.status="running",log("[PrMonitorWorker] Started polling",{intervalSeconds:this.config.poll_interval_seconds})}stop(){if(this.status==="stopped"||this.status==="stopping")return;if(this.status="stopping",log("[PrMonitorWorker] Stopping..."),this.pollTimer)clearInterval(this.pollTimer),this.pollTimer=null;this.status="stopped",this.circuitBreakerMap.clear(),this.reviewStateMap.clear(),this.idlePollCountMap.clear(),this.pollCycleCount=0,log("[PrMonitorWorker] Stopped")}dispose(){this.stop(),this.disposed=!0,log("[PrMonitorWorker] Disposed")}getStatus(){return this.status}isRunning(){return this.status==="running"}async pollCycle(){if(this.disposed)return;await this.executePollCycle()}async executePollCycle(){log("[PrMonitorWorker] Poll cycle starting");try{let activeSubs=await _internals170.listActive(this.directory);if(activeSubs.length===0){log("[PrMonitorWorker] No active subscriptions"),await this.runSweep();return}let toPoll=activeSubs.slice(0,this.config.max_prs_per_cycle),concurrencyLimit=this.config.max_concurrent_pr_polls;this.pollCycleCount++,await this.processWithConcurrency(toPoll,concurrencyLimit),await this.runSweep()}catch(err){log("[PrMonitorWorker] Poll cycle error",{error:err instanceof Error?err.message:String(err)})}}async processWithConcurrency(subs,concurrencyLimit){let index=0,runNext=async()=>{while(index<subs.length){let currentIndex=index;if(index++,this.disposed)return;await this.pollWithTimeout(subs[currentIndex])}},workers=Array.from({length:Math.min(concurrencyLimit,subs.length)},()=>runNext());await Promise.all(workers)}async pollWithTimeout(sub){let timeoutMs=this.config.poll_timeout_ms,timer,timedOut=!1,timeoutPromise=new Promise((_,reject)=>{timer=setTimeout(()=>{timedOut=!0,reject(Error(`PR poll timed out after ${timeoutMs}ms for ${sub.repoFullName}#${sub.prNumber}`))},timeoutMs)});try{await Promise.race([this.pollSinglePr(sub,()=>timedOut),timeoutPromise])}catch(err){await this.handlePollError(sub,err instanceof Error?err:Error(String(err)))}finally{if(timer)clearTimeout(timer)}}async pollSinglePr(sub,isTimedOut){let correlationId=sub.correlationId;if(!this.circuitBreakerMap.has(correlationId)&&sub.errorCount>0)this.circuitBreakerMap.set(correlationId,{errorCount:sub.errorCount,suspendedUntil:0,cooldownLevel:0});let cb=this.circuitBreakerMap.get(correlationId);if(cb&&cb.suspendedUntil>Date.now()){log("[PrMonitorWorker] PR suspended by circuit breaker",{correlationId,suspendedUntil:new Date(cb.suspendedUntil).toISOString()});return}let idleCount=this.idlePollCountMap.get(correlationId)??0;if(shouldSkipIdlePoll(idleCount,this.pollCycleCount)){log("[PrMonitorWorker] Skipping idle PR poll (backoff)",{correlationId,idleCount});return}try{let[statusResult,commentsResult,mergeResult,reviewResult]=await Promise.all([_internals170.getPRStatus(sub.prNumber,sub.repoFullName,this.directory),_internals170.getPRComments(sub.prNumber,sub.repoFullName,this.directory),_internals170.getMergeState(sub.prNumber,sub.repoFullName,this.directory),_internals170.getPRReviewState(sub.prNumber,sub.repoFullName,this.directory)]);if(isTimedOut?.()){log("[PrMonitorWorker] Skipping late result — poll already timed out",{correlationId:sub.correlationId});return}let mergeGroupRunResult=null,mergeGroupRunFetchSucceeded=!1;try{mergeGroupRunResult=await _internals170.getMergeGroupRun(statusResult.statusCheckRollup,sub.repoFullName,this.directory),mergeGroupRunFetchSucceeded=!0}catch(err){log("[PrMonitorWorker] Failed to fetch merge group run",{correlationId:sub.correlationId,error:err instanceof Error?err.message:String(err)})}if(isTimedOut?.()){log("[PrMonitorWorker] Skipping late result — poll already timed out",{correlationId:sub.correlationId});return}let changes=this.computeChanges(sub,{status:statusResult,comments:commentsResult,merge:mergeResult,review:reviewResult,mergeGroupRun:mergeGroupRunResult},mergeGroupRunFetchSucceeded);if(await this.applyChanges(sub,changes,isTimedOut),!isTimedOut?.()){this.circuitBreakerMap.delete(correlationId),await _internals170.updateSnapshot(this.directory,correlationId,{errorCount:0,lastCheckedAt:Date.now()});let hasMeaningfulSnapshotChange=!1;for(let field of MEANINGFUL_SNAPSHOT_FIELDS)if(Object.hasOwn(changes.snapshotUpdates,field)){let newVal=changes.snapshotUpdates[field],priorVal=sub[field];if(newVal!==priorVal){hasMeaningfulSnapshotChange=!0;break}}if(changes.events.length>0||hasMeaningfulSnapshotChange)this.idlePollCountMap.set(correlationId,0);else this.idlePollCountMap.set(correlationId,(this.idlePollCountMap.get(correlationId)??0)+1)}}catch(err){if(isTimedOut?.()){log("[PrMonitorWorker] Skipping late error — poll already timed out",{correlationId:sub.correlationId});return}await this.handlePollError(sub,err instanceof Error?err:Error(String(err)))}}computeChanges(sub,current,mergeGroupRunFetchSucceeded){let events=[],snapshotUpdates={headRefOid:current.status.headRefOid,mergeableState:current.merge.mergeable,lastCheckedAt:Date.now()};if(mergeGroupRunFetchSucceeded)snapshotUpdates.mergeGroupRunStatus=current.mergeGroupRun?.status,snapshotUpdates.mergeGroupRunConclusion=current.mergeGroupRun?.conclusion??void 0,snapshotUpdates.mergeGroupRunHtmlUrl=current.mergeGroupRun?.htmlUrl;let isMerged=!1,isClosed=!1,newReviewDecision="";if(current.status.headRefOid!==sub.headRefOid)events.push({type:"pr.status.updated",payload:{prNumber:sub.prNumber,repoFullName:sub.repoFullName,prUrl:sub.prUrl,previousOid:sub.headRefOid,currentOid:current.status.headRefOid}});let currentCheckSet=this.serializeChecks(current.status.statusCheckRollup);if(snapshotUpdates.lastCheckRunSet=currentCheckSet,sub.lastCheckRunSet!==void 0&¤tCheckSet!==sub.lastCheckRunSet){let prevChecks=this.parseCheckSet(sub.lastCheckRunSet);this.computeCIEvents(sub,prevChecks,current.status.statusCheckRollup,events)}if(snapshotUpdates.lastCheckRunSet=currentCheckSet,current.comments.length>0){let sorted=[...current.comments].sort((a,b)=>a.createdAt.localeCompare(b.createdAt)),newComments;if(sub.lastCommentId===void 0)newComments=sorted;else{let lastIdx=sorted.findIndex((c)=>c.id===sub.lastCommentId);newComments=lastIdx>=0?sorted.slice(lastIdx+1):sorted}for(let comment of newComments)events.push({type:"pr.new.comment",payload:{prNumber:sub.prNumber,repoFullName:sub.repoFullName,prUrl:sub.prUrl,commentId:comment.id,author:comment.author,body:comment.body,createdAt:comment.createdAt,isReviewComment:comment.isReviewComment}});snapshotUpdates.lastCommentId=sorted[sorted.length-1].id}if(current.merge.mergeable==="CONFLICTING"&&sub.mergeableState!=="CONFLICTING")events.push({type:"pr.merge.conflict",payload:{prNumber:sub.prNumber,repoFullName:sub.repoFullName,prUrl:sub.prUrl,mergeableState:current.merge.mergeable}});else if(sub.mergeableState==="CONFLICTING"&¤t.merge.mergeable!=="CONFLICTING")events.push({type:"pr.merge.conflict_resolved",payload:{prNumber:sub.prNumber,repoFullName:sub.repoFullName,prUrl:sub.prUrl,mergeableState:current.merge.mergeable}});let prevReviewDecision=this.reviewStateMap.get(sub.correlationId)??"";if(current.review.reviewDecision&¤t.review.reviewDecision!==prevReviewDecision){if(current.review.reviewDecision==="CHANGES_REQUESTED"&&prevReviewDecision!=="CHANGES_REQUESTED")events.push({type:"pr.review.changes_requested",payload:{prNumber:sub.prNumber,repoFullName:sub.repoFullName,prUrl:sub.prUrl,reviewDecision:current.review.reviewDecision}});else if(current.review.reviewDecision==="APPROVED"&&prevReviewDecision!=="APPROVED")events.push({type:"pr.review.approved",payload:{prNumber:sub.prNumber,repoFullName:sub.repoFullName,prUrl:sub.prUrl,reviewDecision:current.review.reviewDecision}});newReviewDecision=current.review.reviewDecision}if(current.status.state==="MERGED")isMerged=!0,events.push({type:"pr.merged",payload:{prNumber:sub.prNumber,repoFullName:sub.repoFullName,prUrl:sub.prUrl,headRefOid:current.status.headRefOid}}),snapshotUpdates.isWatching=!1;if(current.status.state==="CLOSED")isClosed=!0,events.push({type:"pr.closed",payload:{prNumber:sub.prNumber,repoFullName:sub.repoFullName,prUrl:sub.prUrl}}),snapshotUpdates.isWatching=!1;return snapshotUpdates.hasUnaddressedEvents=events.length>0,{events,snapshotUpdates,isMerged,isClosed,newReviewDecision}}computeCIEvents(sub,prevChecks,currentChecks,events){let allPassed=!0,prevMap=new Map(prevChecks.map((c)=>[c.name,c.conclusion])),newlyFailedChecks=[];for(let check3 of currentChecks){if(check3.conclusion==="failure"||check3.conclusion==="FAILURE"){let prev=prevMap.get(check3.name);if(prev!=="failure"&&prev!=="FAILURE")newlyFailedChecks.push({name:check3.name,conclusion:check3.conclusion})}if(check3.conclusion!=="success"&&check3.conclusion!=="SUCCESS")allPassed=!1}if(newlyFailedChecks.length>0)events.push({type:"pr.ci.failed",payload:{prNumber:sub.prNumber,repoFullName:sub.repoFullName,prUrl:sub.prUrl,failedChecks:newlyFailedChecks}});if(allPassed&¤tChecks.length>0){if(prevChecks.some((c)=>c.conclusion!=="success"&&c.conclusion!=="SUCCESS")||prevChecks.length===0)events.push({type:"pr.ci.passed",payload:{prNumber:sub.prNumber,repoFullName:sub.repoFullName,prUrl:sub.prUrl,checkCount:currentChecks.length}})}}async applyChanges(sub,changes,isTimedOut){if(isTimedOut?.()){log("[PrMonitorWorker] Skipping change application — poll already timed out",{correlationId:sub.correlationId});return}for(let{type,payload}of changes.events)await this.emitEvent(type,payload);if(isTimedOut?.()){log("[PrMonitorWorker] Skipping state mutations — poll timed out during event emission",{correlationId:sub.correlationId});return}if(changes.newReviewDecision)this.reviewStateMap.set(sub.correlationId,changes.newReviewDecision);if(changes.isMerged&&this.config.auto_unsubscribe_on_merge||changes.isClosed&&this.config.auto_unsubscribe_on_close)this.mergedOrClosedKeys.add(`${sub.repoFullName}::${sub.prNumber}`);if(changes.isMerged&&this.config.auto_unsubscribe_on_merge){await _internals170.unsubscribe(this.directory,sub.correlationId),this.reviewStateMap.delete(sub.correlationId),this.circuitBreakerMap.delete(sub.correlationId),log("[PrMonitorWorker] Auto-unsubscribed merged PR",{correlationId:sub.correlationId});return}if(changes.isClosed&&this.config.auto_unsubscribe_on_close){await _internals170.unsubscribe(this.directory,sub.correlationId),this.reviewStateMap.delete(sub.correlationId),this.circuitBreakerMap.delete(sub.correlationId),log("[PrMonitorWorker] Auto-unsubscribed closed PR",{correlationId:sub.correlationId});return}if(isTimedOut?.()){log("[PrMonitorWorker] Skipping snapshot update — poll timed out before write",{correlationId:sub.correlationId});return}await _internals170.updateSnapshot(this.directory,sub.correlationId,changes.snapshotUpdates)}async handlePollError(sub,error93){let correlationId=sub.correlationId,cb=this.circuitBreakerMap.get(correlationId)??{errorCount:0,suspendedUntil:0,cooldownLevel:0};if(cb.errorCount++,await _internals170.updateSnapshot(this.directory,correlationId,{errorCount:cb.errorCount,lastCheckedAt:Date.now()}),cb.errorCount>=this.config.failure_threshold){cb.cooldownLevel++;let cooldownSeconds=Math.min(this.config.cooldown_seconds*2**(cb.cooldownLevel-1),this.config.max_cooldown_seconds);cb.suspendedUntil=Date.now()+cooldownSeconds*1000,this.circuitBreakerMap.set(correlationId,cb),error48("[PrMonitorWorker] Circuit breaker tripped for PR",{correlationId,errorCount:cb.errorCount,cooldownSeconds}),await this.emitEvent("pr.error",{prNumber:sub.prNumber,repoFullName:sub.repoFullName,prUrl:sub.prUrl,reason:"circuit_breaker",errorCount:cb.errorCount,cooldownSeconds})}else this.circuitBreakerMap.set(correlationId,cb),log("[PrMonitorWorker] Poll error for PR",{correlationId,errorCount:cb.errorCount,error:error93.message})}async emitEvent(type,payload){let event={type,timestamp:Date.now(),payload,source:"pr-monitor-worker"};try{await _internals170.getGlobalEventBus().publish(type,payload,"pr-monitor-worker")}catch(err){log("[PrMonitorWorker] Event publish failed",{type,error:err instanceof Error?err.message:String(err)})}if(this.onEvent)try{this.onEvent(event)}catch{}}async runSweep(){if(this.config.cleanup_ttl_days>0)try{let keysToPass=this.mergedOrClosedKeys.size>0?this.mergedOrClosedKeys:void 0;await _internals170.sweepStale(this.directory,this.config.cleanup_ttl_days,keysToPass)}catch(err){log("[PrMonitorWorker] Sweep failed",{error:err instanceof Error?err.message:String(err)})}finally{this.mergedOrClosedKeys.clear()}else this.mergedOrClosedKeys.clear()}serializeChecks(checks5){return JSON.stringify(checks5.map((c)=>({n:c.name,c:c.conclusion})))}parseCheckSet(serialized3){try{return JSON.parse(serialized3).map((p)=>({name:p.n,conclusion:p.c}))}catch{return[]}}}var _internals170={getPRStatus,getPRComments,getMergeState,getMergeGroupRun,getPRReviewState,listActive,updateSnapshot,unsubscribe,sweepStale,getGlobalEventBus};init_queue();init_status_artifact();init_trigger();init_worker();import{createHash as createHash58}from"node:crypto";import*as path220 from"node:path";init_zod();init_task_envelope();init_workspace_snapshot();init_plan_schema();init_schema();init_task_result_classifier();init_utils2();init_ledger();init_manager();init_utils3();init_atomic_write();init_lock();init_task_file();import{createHash as createHash57}from"node:crypto";import*as fs116 from"node:fs";import*as path219 from"node:path";var PHASE_PARTICIPATION_FILE="evidence/phase-participation.json",PHASE_PARTICIPATION_QUARANTINE_DIR="evidence/phase-participation-quarantine",MAX_PHASE_PARTICIPATION_BYTES=262144,MAX_PHASE_PARTICIPATION_PENDING=128,MAX_PHASE_PARTICIPATION_RECEIPTS=128,MAX_PHASE_PARTICIPATION_QUARANTINE_FILES=16,MAX_PHASE_PARTICIPATION_QUARANTINE_BYTES=1048576,MAX_PHASE_PARTICIPATION_QUARANTINE_DIRECTORY_ENTRIES=64,MAX_PENDING_IN_MEMORY=128,MAX_ID_CHARS=256,WorkspaceSchema2=exports_external.object({directory:exports_external.string().max(4096),gitHead:exports_external.string().max(256).nullable(),prHeadSha:exports_external.string().max(256).nullable()}).strict(),BindingSchema=exports_external.object({role:exports_external.string().min(1).max(120),prefixedRole:exports_external.string().min(1).max(120),planId:exports_external.string().min(1).max(512),planIdentityHash:exports_external.string().length(64),planStructureHash:exports_external.string().length(64),phase:exports_external.number().int().nonnegative(),taskId:exports_external.string().min(1).max(120).nullable(),parentSessionId:exports_external.string().min(1).max(MAX_ID_CHARS),callId:exports_external.string().min(1).max(MAX_ID_CHARS),policyDigest:exports_external.string().length(64),workspace:WorkspaceSchema2,capturedAt:exports_external.number().int().nonnegative()}).strict(),PendingSchema=BindingSchema.extend({childSessionId:exports_external.string().min(1).max(MAX_ID_CHARS)}).strict(),ReceiptSchema=PendingSchema.extend({receiptId:exports_external.string().length(64),resultDigest:exports_external.string().length(64),completedAt:exports_external.number().int().nonnegative(),childIdentityAvailable:exports_external.boolean()}).strict(),StoreSchema=exports_external.object({schemaVersion:exports_external.literal(1),pending:exports_external.array(PendingSchema).max(MAX_PHASE_PARTICIPATION_PENDING),receipts:exports_external.array(ReceiptSchema).max(MAX_PHASE_PARTICIPATION_RECEIPTS)}).strict(),foregroundReservations=new Map;function emptyStore(){return{schemaVersion:1,pending:[],receipts:[]}}function correlationKey(parentSessionId,callId){return`${parentSessionId}\x00${callId}`}function sha2564(value){return createHash57("sha256").update(value).digest("hex")}function policyDigest(policy){return sha2564(stableCanonicalStringify(policy??{}))}function captureParticipationWorkspace(directory){let workspace=captureWorkspaceSnapshot(directory,{resolveCurrentPrHeadSha:!0});return{directory:workspace.directory,gitHead:workspace.gitHead,prHeadSha:workspace.prHeadSha}}function boundedPut(binding){let key=correlationKey(binding.parentSessionId,binding.callId);foregroundReservations.delete(key),foregroundReservations.set(key,binding);while(foregroundReservations.size>MAX_PENDING_IN_MEMORY){let oldest=foregroundReservations.keys().next().value;if(!oldest)break;foregroundReservations.delete(oldest)}}function takeBinding(parentSessionId,callId){let key=correlationKey(parentSessionId,callId),binding=foregroundReservations.get(key)??null;return foregroundReservations.delete(key),binding}async function persistWithBindingRecovery(directory,binding,operation){try{await withEvidenceLock(directory,PHASE_PARTICIPATION_FILE,"docs","phase-participation",operation)}catch(error93){throw boundedPut(binding),error93}}function buildBinding(input){return{role:stripKnownSwarmPrefix(input.role),prefixedRole:input.role,planId:derivePlanId(input.plan),planIdentityHash:derivePlanIdentityHash(input.plan),planStructureHash:computePlanStructureHash(input.plan),phase:input.phase,taskId:input.taskId,parentSessionId:input.parentSessionId,callId:input.callId,policyDigest:policyDigest(input.policy),workspace:captureParticipationWorkspace(input.directory),capturedAt:Date.now()}}function extractPlanTaskId2(args2){let raw=args2.task_id??args2.taskId;if(typeof raw==="string"&&raw.trim().length>0)return raw.trim().slice(0,120);let text=[args2.prompt,args2.description,args2.task].filter((value)=>typeof value==="string").join(`
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "opencode-swarm",
|
|
3
|
-
"version": "7.148.
|
|
3
|
+
"version": "7.148.3",
|
|
4
4
|
"description": "Architect-centric agentic swarm plugin for OpenCode - hub-and-spoke orchestration with SME consultation, code generation, and QA review",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"types": "dist/index.d.ts",
|