opencode-swarm 7.112.0 → 7.112.2

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.
Files changed (24) hide show
  1. package/dist/cli/{curator-llm-factory-8rnk2083.js → curator-llm-factory-5bns4xy6.js} +6 -6
  2. package/dist/cli/{curator-j7ty8k6t.js → curator-snvp9542.js} +6 -6
  3. package/dist/cli/{guardrail-explain-2j0gw8f0.js → guardrail-explain-4s7djf9p.js} +7 -7
  4. package/dist/cli/{hive-promoter-y179n7wx.js → hive-promoter-zs295trk.js} +6 -6
  5. package/dist/cli/{index-hg0pamsa.js → index-30ejh1tx.js} +1 -1
  6. package/dist/cli/{index-t7efm8vz.js → index-32bx4kch.js} +68 -3
  7. package/dist/cli/{index-b83y9a7r.js → index-82v0d72f.js} +3 -3
  8. package/dist/cli/{index-x4bghdyv.js → index-9fjpecax.js} +1 -1
  9. package/dist/cli/{index-cye4g7zj.js → index-hpp2r0sd.js} +1 -1
  10. package/dist/cli/{index-c3h3d8kh.js → index-k6wd3chp.js} +7 -7
  11. package/dist/cli/{index-j5c98bd9.js → index-snmfqhez.js} +18 -50
  12. package/dist/cli/{index-2aqs6daa.js → index-t6wfwdm1.js} +3 -3
  13. package/dist/cli/index.js +6 -6
  14. package/dist/cli/{knowledge-escalator-t1e2211j.js → knowledge-escalator-4gbz527n.js} +3 -3
  15. package/dist/cli/{knowledge-events-2h3gvtfa.js → knowledge-events-b6x28fgc.js} +1 -1
  16. package/dist/cli/{knowledge-store-gpta9gzh.js → knowledge-store-h3cjx4dg.js} +6 -2
  17. package/dist/cli/{knowledge-validator-03f0hm0p.js → knowledge-validator-q6jw2p0t.js} +2 -2
  18. package/dist/cli/{skill-generator-2tsqqaa2.js → skill-generator-fe6q8xgm.js} +4 -4
  19. package/dist/hooks/knowledge-events.d.ts +21 -1
  20. package/dist/hooks/knowledge-injector.d.ts +4 -0
  21. package/dist/hooks/knowledge-reader.d.ts +16 -0
  22. package/dist/hooks/knowledge-store.d.ts +23 -0
  23. package/dist/index.js +17 -17
  24. 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.112.0",description:"Architect-centric agentic swarm plugin for OpenCode - hub-and-spoke orchestration with SME consultation, code generation, and QA review",main:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",default:"./dist/index.js"},"./package.json":"./package.json"},bin:{"opencode-swarm":"./dist/cli/index.js"},type:"module",engines:{bun:">=1.3.13"},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",".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/swarm",".opencode/skills/swarm-ci-monitor",".opencode/skills/worktree-retry-cleanup","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",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"},dependencies:{"@opencode-ai/plugin":"^1.1.53","@opencode-ai/sdk":"^1.1.53","@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"}}});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"],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]});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_oversight","coder","test_engineer"]},diff_summary:{description:"filter classified AST changes by category, risk level, or file for reviewer drill-down",agents:["architect","reviewer","critic_oversight"]},syntax_check:{description:"check syntax of source files using tree-sitter parsers across multiple languages, returning per-file errors",agents:["architect","coder","test_engineer"]},placeholder_scan:{description:"todo and FIXME comment detection",agents:["architect","reviewer"]},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","coder","test_engineer"]},lint:{description:"run project linter in check or fix mode; supports biome, eslint, ruff, clippy, and more, returns structured results",agents:["architect","reviewer","coder"]},secretscan:{description:"scan for secrets (API keys, tokens, passwords) via regex and entropy; returns redacted previews, excludes common dirs",agents:["architect","reviewer","critic_oversight"]},sast_scan:{description:"static analysis security scan",agents:["architect","reviewer","critic_oversight"]},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"]},quality_budget:{description:"code quality budget check",agents:["architect"]},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","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","critic_oversight","explorer","test_engineer"]},schema_drift:{description:"OpenAPI spec vs route drift",agents:["architect","sme","researcher","docs","explorer"]},todo_extract:{description:"structured TODO/FIXME extraction",agents:["architect","researcher","docs","explorer"]},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"]},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_oversight","test_engineer"]},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"]},test_runner:{description:"auto-detect and run tests",agents:["architect","reviewer","test_engineer"]},test_impact:{description:"identify test files impacted by changed source files via import analysis",agents:["architect","reviewer","critic_oversight","test_engineer"]},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","explorer","architect"]},gitingest:{description:"fetch a GitHub repository full content via gitingest.com",agents:["architect","docs","explorer"]},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","coder","test_engineer"]},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"]},extract_code_blocks:{description:"extract code blocks from text content and save them to files",agents:["architect","sme","docs","docs_design","designer","spec_writer","reviewer","explorer","coder","test_engineer"]},phase_complete:{description:"mark a phase as complete and track dispatched agents",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"]},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","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, 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_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"]},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"]},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"]},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_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"]},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","critic_oversight","explorer","coder"]},get_qa_gate_profile:{description:"retrieve the QA gate profile for the current plan: 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.",agents:["architect"]},set_qa_gates:{description:"configure the QA gate profile for the current plan. Architect-only. Ratchet-tighter only — rejected once the profile is 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.",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","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_command:{description:"run supported /swarm commands through the canonical command registry",agents:["architect","sme","researcher","docs","docs_design","designer","reviewer","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.",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)}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,DEFAULT_MODELS,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.112.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",".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/swarm",".opencode/skills/swarm-ci-monitor",".opencode/skills/worktree-retry-cleanup","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",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"},dependencies:{"@opencode-ai/plugin":"^1.1.53","@opencode-ai/sdk":"^1.1.53","@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"}}});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"],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]});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_oversight","coder","test_engineer"]},diff_summary:{description:"filter classified AST changes by category, risk level, or file for reviewer drill-down",agents:["architect","reviewer","critic_oversight"]},syntax_check:{description:"check syntax of source files using tree-sitter parsers across multiple languages, returning per-file errors",agents:["architect","coder","test_engineer"]},placeholder_scan:{description:"todo and FIXME comment detection",agents:["architect","reviewer"]},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","coder","test_engineer"]},lint:{description:"run project linter in check or fix mode; supports biome, eslint, ruff, clippy, and more, returns structured results",agents:["architect","reviewer","coder"]},secretscan:{description:"scan for secrets (API keys, tokens, passwords) via regex and entropy; returns redacted previews, excludes common dirs",agents:["architect","reviewer","critic_oversight"]},sast_scan:{description:"static analysis security scan",agents:["architect","reviewer","critic_oversight"]},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"]},quality_budget:{description:"code quality budget check",agents:["architect"]},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","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","critic_oversight","explorer","test_engineer"]},schema_drift:{description:"OpenAPI spec vs route drift",agents:["architect","sme","researcher","docs","explorer"]},todo_extract:{description:"structured TODO/FIXME extraction",agents:["architect","researcher","docs","explorer"]},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"]},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_oversight","test_engineer"]},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"]},test_runner:{description:"auto-detect and run tests",agents:["architect","reviewer","test_engineer"]},test_impact:{description:"identify test files impacted by changed source files via import analysis",agents:["architect","reviewer","critic_oversight","test_engineer"]},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","explorer","architect"]},gitingest:{description:"fetch a GitHub repository full content via gitingest.com",agents:["architect","docs","explorer"]},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","coder","test_engineer"]},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"]},extract_code_blocks:{description:"extract code blocks from text content and save them to files",agents:["architect","sme","docs","docs_design","designer","spec_writer","reviewer","explorer","coder","test_engineer"]},phase_complete:{description:"mark a phase as complete and track dispatched agents",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"]},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","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, 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_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"]},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"]},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"]},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_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"]},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","critic_oversight","explorer","coder"]},get_qa_gate_profile:{description:"retrieve the QA gate profile for the current plan: 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.",agents:["architect"]},set_qa_gates:{description:"configure the QA gate profile for the current plan. Architect-only. Ratchet-tighter only — rejected once the profile is 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.",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","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_command:{description:"run supported /swarm commands through the canonical command registry",agents:["architect","sme","researcher","docs","docs_design","designer","reviewer","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.",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)}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,DEFAULT_MODELS,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
 
@@ -1074,7 +1074,7 @@ RULES:
1074
1074
  - The manifest must be small (<100 lines). Pointers only, not full content.
1075
1075
  - Do NOT rephrase or summarize doc content with your own words — use the actual text from the file
1076
1076
  - Full doc content is only loaded when relevant to the current task, never preloaded
1077
- `});class AutomationEventBus{listeners=new Map;eventHistory=[];maxHistorySize;constructor(options){this.maxHistorySize=options?.maxHistorySize??100}subscribe(type,listener){if(!this.listeners.has(type))this.listeners.set(type,new Set);return this.listeners.get(type).add(listener),()=>{this.listeners.get(type)?.delete(listener)}}async publish(type,payload,source){let event={type,timestamp:Date.now(),payload,source};if(this.eventHistory.push(event),this.eventHistory.length>this.maxHistorySize)this.eventHistory.shift();log(`[EventBus] ${type}`,{source,payload:typeof payload==="object"?"...":payload});let listeners=this.listeners.get(type);if(listeners)await Promise.all(Array.from(listeners).map(async(listener)=>{try{await listener(event)}catch(error93){log(`[EventBus] Listener error for ${type}`,{error:error93})}}))}getHistory(types2){if(!types2||types2.length===0)return[...this.eventHistory];return this.eventHistory.filter((e)=>types2.includes(e.type))}clearHistory(){this.eventHistory=[]}getListenerCount(type){return this.listeners.get(type)?.size??0}hasListeners(type){return this.getListenerCount(type)>0}}function getGlobalEventBus(){if(!globalEventBus)globalEventBus=new AutomationEventBus;return globalEventBus}var globalEventBus=null;var init_event_bus=__esm(()=>{init_utils()});var exports_knowledge_validator={};__export(exports_knowledge_validator,{validateSkillPath:()=>validateSkillPath,validateSkillCandidatePath:()=>validateSkillCandidatePath,validateLesson:()=>validateLesson,validateActionableFields:()=>validateActionableFields,validateActionability:()=>validateActionability,unarchiveEntry:()=>unarchiveEntry,restoreEntry:()=>restoreEntry,resolveUnactionablePath:()=>resolveUnactionablePath,quarantineEntry:()=>quarantineEntry,auditEntryHealth:()=>auditEntryHealth,appendUnactionable:()=>appendUnactionable,_internals:()=>_internals29,SECURITY_DEGRADING_PATTERNS:()=>SECURITY_DEGRADING_PATTERNS,RETIRED_SKILL_HISTORY_MAX:()=>RETIRED_SKILL_HISTORY_MAX,INVISIBLE_FORMAT_CHARS:()=>INVISIBLE_FORMAT_CHARS,INJECTION_PATTERNS:()=>INJECTION_PATTERNS,DANGEROUS_COMMAND_WARNING_PATTERNS:()=>DANGEROUS_COMMAND_WARNING_PATTERNS,DANGEROUS_COMMAND_PATTERNS:()=>DANGEROUS_COMMAND_PATTERNS,DANGEROUS_COMMAND_ERROR_PATTERNS:()=>DANGEROUS_COMMAND_ERROR_PATTERNS,ALLOWED_SKILL_PATH_PREFIXES:()=>ALLOWED_SKILL_PATH_PREFIXES,ACTIONABLE_STRING_MAX:()=>ACTIONABLE_STRING_MAX,ACTIONABLE_LIST_MAX:()=>ACTIONABLE_LIST_MAX});import{appendFile as appendFile5,mkdir as mkdir8}from"node:fs/promises";import*as path53 from"node:path";function normalizeText(text){return text.normalize("NFKC").toLowerCase().replace(/[^\w\s]/g," ").replace(/\s+/g," ").trim()}function extractContextWords(text,word,contextWindow=3){let words=text.split(" "),context=new Set;if(!word.includes(" ")){let from=0,idx=words.indexOf(word,from);while(idx!==-1){let start=Math.max(0,idx-contextWindow),end=Math.min(words.length,idx+contextWindow+1);for(let i2=start;i2<end;i2++)if(i2!==idx&&words[i2]&&words[i2].length>0)context.add(words[i2]);from=idx+1,idx=words.indexOf(word,from)}return context}let termLen=word.split(" ").length,i=0;while(i<=words.length-termLen)if(words.slice(i,i+termLen).join(" ")===word){let start=Math.max(0,i-contextWindow),end=Math.min(words.length,i+termLen+contextWindow);for(let j=start;j<end;j++)if(j<i||j>=i+termLen){if(words[j]&&words[j].length>0)context.add(words[j])}i+=termLen}else i+=1;return context}function hasSignificantOverlap(set1,set22){if(set1.size===0||set22.size===0)return!1;return[...set1].some((word)=>set22.has(word))}function detectContradiction(candidate,existingLessons){let candidateTags=inferTags2(candidate);if(candidateTags.length===0)return!1;let candidateNorm=normalizeText(candidate);for(let existing of existingLessons){let existingTags=inferTags2(existing);if(!candidateTags.some((t)=>existingTags.includes(t)))continue;let existingNorm=normalizeText(existing);for(let[wordA,wordB]of NEGATION_PAIRS){if(candidateNorm.includes(wordA)&&existingNorm.includes(wordB)){let contextA=extractContextWords(candidateNorm,wordA),contextB=extractContextWords(existingNorm,wordB);if(hasSignificantOverlap(contextA,contextB))return!0}if(candidateNorm.includes(wordB)&&existingNorm.includes(wordA)){let contextB=extractContextWords(candidateNorm,wordB),contextA=extractContextWords(existingNorm,wordA);if(hasSignificantOverlap(contextA,contextB))return!0}}}return!1}function isVagueLesson(lesson){let words=normalizeText(lesson).split(/\s+/),hasTechRef=words.some((w)=>TECH_REFERENCE_WORDS.has(w)),hasActionVerb=words.some((w)=>ACTION_VERB_WORDS.has(w));return!hasTechRef&&!hasActionVerb}function validateLesson(candidate,existingLessons,meta3){if(!candidate||typeof candidate!=="string")return{valid:!1,layer:1,reason:"lesson too short (min 15 chars)",severity:"error"};if(!Array.isArray(existingLessons))existingLessons=[];if(candidate.length<15)return{valid:!1,layer:1,reason:"lesson too short (min 15 chars)",severity:"error"};if(candidate.length>280)return{valid:!1,layer:1,reason:"lesson too long (max 280 chars)",severity:"error"};if(!VALID_CATEGORIES.has(meta3.category))return{valid:!1,layer:1,reason:`invalid category: ${meta3.category}`,severity:"error"};let isGlobalScope=meta3.scope==="global",isStackScope=/^stack:[a-zA-Z0-9_-]{1,64}$/.test(meta3.scope);if(!isGlobalScope&&!isStackScope)return{valid:!1,layer:1,reason:"invalid scope: must be 'global' or 'stack:<name>'",severity:"error"};if(!(meta3.confidence>=0&&meta3.confidence<=1))return{valid:!1,layer:1,reason:"confidence out of range [0.0, 1.0]",severity:"error"};let normalizedCandidate=candidate.normalize("NFKC").replace(INVISIBLE_FORMAT_CHARS," ").replace(/\s+/g," ").toLowerCase();for(let pattern of DANGEROUS_COMMAND_ERROR_PATTERNS)if(pattern.test(normalizedCandidate))return{valid:!1,layer:2,reason:"dangerous command pattern detected",severity:"error"};for(let pattern of DANGEROUS_COMMAND_WARNING_PATTERNS)if(pattern.test(normalizedCandidate))return{valid:!0,layer:2,reason:"potentially dangerous command pattern queued for review",severity:"warning"};for(let pattern of SECURITY_DEGRADING_PATTERNS)if(pattern.test(normalizedCandidate))return{valid:!1,layer:2,reason:"security-degrading instruction detected",severity:"error"};for(let pattern of INJECTION_PATTERNS)if(pattern.test(candidate))return{valid:!1,layer:2,reason:"injection pattern detected",severity:"error"};if(detectContradiction(candidate,existingLessons))return{valid:!0,layer:3,reason:"possible contradiction with an existing lesson with shared tags",severity:"warning"};if(isVagueLesson(candidate))return{valid:!0,layer:3,reason:"lesson may be too vague (no tech reference or action verb)",severity:"warning"};return{valid:!0,layer:null,reason:null,severity:null}}function isCleanShortString(s){if(typeof s!=="string")return!1;if(s.length===0||s.length>ACTIONABLE_STRING_MAX)return!1;return!/[\x00-\x08\x0b-\x0c\x0e-\x1f\x7f]/.test(s)}function validateSkillPath(p){if(typeof p!=="string")return!1;if(p.length===0||p.length>256)return!1;if(p.includes("\x00"))return!1;if(path53.isAbsolute(p))return!1;if(p.includes(".."))return!1;let norm=p.replace(/\\/g,"/");return ALLOWED_SKILL_PATH_PREFIXES.some((prefix)=>norm.startsWith(prefix))}function validateSkillCandidatePath(p){if(typeof p!=="string")return!1;if(p.length===0||p.length>256)return!1;if(p.includes("\x00"))return!1;if(path53.isAbsolute(p))return!1;if(p.includes(".."))return!1;let norm=p.replace(/\\/g,"/");if(!norm.startsWith(".swarm/skills/candidates/"))return!1;let filename=norm.slice(25);return/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\.json$/i.test(filename)}function validateActionableFields(fields){let errors5=[];if(!fields)return{valid:!0,errors:errors5};function checkStringList(name,list){if(list===void 0)return;if(!Array.isArray(list)){errors5.push(`${name} must be an array`);return}if(list.length>ACTIONABLE_LIST_MAX)errors5.push(`${name} exceeds ${ACTIONABLE_LIST_MAX} items`);for(let item of list)if(!isCleanShortString(item)){errors5.push(`${name} contains invalid string`);return}}function checkNameList(name,list){if(list===void 0)return;if(!Array.isArray(list)){errors5.push(`${name} must be an array`);return}if(list.length>ACTIONABLE_LIST_MAX)errors5.push(`${name} exceeds ${ACTIONABLE_LIST_MAX} items`);for(let item of list)if(typeof item!=="string"||!NAME_PATTERN.test(item)){errors5.push(`${name} contains invalid name`);return}}if(checkStringList("triggers",fields.triggers),checkStringList("required_actions",fields.required_actions),checkStringList("forbidden_actions",fields.forbidden_actions),checkStringList("verification_checks",fields.verification_checks),checkNameList("applies_to_agents",fields.applies_to_agents),checkNameList("applies_to_tools",fields.applies_to_tools),fields.source_refs!==void 0){if(!Array.isArray(fields.source_refs))errors5.push("source_refs must be an array");else if(fields.source_refs.length>ACTIONABLE_LIST_MAX)errors5.push(`source_refs exceeds ${ACTIONABLE_LIST_MAX} items`);else for(let ref of fields.source_refs)if(typeof ref!=="string"||ref.length===0||ref.length>ACTIONABLE_STRING_MAX||SOURCE_REF_FORBIDDEN.test(ref)){errors5.push("source_refs contains invalid value");break}}if(fields.source_knowledge_ids!==void 0){if(!Array.isArray(fields.source_knowledge_ids))errors5.push("source_knowledge_ids must be an array");else for(let id of fields.source_knowledge_ids)if(typeof id!=="string"||id.length===0||id.length>64){errors5.push("source_knowledge_ids contains invalid value");break}}if(fields.directive_priority!==void 0&&!VALID_DIRECTIVE_PRIORITIES.has(String(fields.directive_priority)))errors5.push("directive_priority must be low|medium|high|critical");if(fields.generated_skill_slug!==void 0){if(typeof fields.generated_skill_slug!=="string"||!/^[a-z0-9][a-z0-9-]{0,63}$/.test(fields.generated_skill_slug))errors5.push("generated_skill_slug must be a kebab-case slug")}if(fields.generated_skill_path!==void 0&&!validateSkillPath(fields.generated_skill_path))errors5.push("generated_skill_path must be repo-local under allowed prefix");if(fields.draft_generated_skill_slug!==void 0){if(typeof fields.draft_generated_skill_slug!=="string"||!/^[a-z0-9][a-z0-9-]{0,63}$/.test(fields.draft_generated_skill_slug))errors5.push("draft_generated_skill_slug must be a kebab-case slug")}if(fields.draft_generated_skill_path!==void 0&&!validateSkillPath(fields.draft_generated_skill_path))errors5.push("draft_generated_skill_path must be repo-local under allowed prefix");if(fields.retired_skill_history!==void 0){if(!Array.isArray(fields.retired_skill_history))errors5.push("retired_skill_history must be an array of slugs");else if(fields.retired_skill_history.length>RETIRED_SKILL_HISTORY_MAX)errors5.push(`retired_skill_history exceeds ${RETIRED_SKILL_HISTORY_MAX} items`);else if(!fields.retired_skill_history.every((s)=>typeof s==="string"&&/^[a-z0-9][a-z0-9-]{0,63}$/.test(s)))errors5.push("retired_skill_history entries must be kebab-case slugs")}return{valid:errors5.length===0,errors:errors5}}function hasNonEmptyList(v){return Array.isArray(v)&&v.length>0}function validateActionability(entry){let hasPredicate=hasNonEmptyList(entry.forbidden_actions)||hasNonEmptyList(entry.required_actions)||hasNonEmptyList(entry.verification_checks)||typeof entry.verification_predicate==="string"&&entry.verification_predicate.trim().length>0,hasScope=hasNonEmptyList(entry.applies_to_tools)||hasNonEmptyList(entry.applies_to_agents);if(hasPredicate&&hasScope)return{actionable:!0};return{actionable:!1,reason:!hasPredicate&&!hasScope?"missing_predicate_and_scope":!hasPredicate?"missing_predicate":"missing_scope"}}function resolveUnactionablePath(directory){return path53.join(resolveKnowledgeStoreDir(directory),"knowledge-unactionable.jsonl")}async function appendUnactionable(directory,entry,reason){let filePath=resolveUnactionablePath(directory),dirPath=path53.dirname(filePath);await mkdir8(dirPath,{recursive:!0}),await transactKnowledge(filePath,(existing)=>{let record3={...entry,status:"quarantined_unactionable",unactionable_reason:reason,quarantined_at:new Date().toISOString()},duplicate=findNearDuplicate(record3.lesson,existing,0.6);if(duplicate?.unactionable_reason===reason)return duplicate.quarantined_at=record3.quarantined_at,duplicate.updated_at=record3.updated_at,existing;let next=[...existing,record3];return next.length>200?next.slice(-200):next})}function auditEntryHealth(entry){let utilityScore=entry.utility_score;if((entry.retrieval_outcomes?.shown_count??entry.retrieval_outcomes?.applied_count??0)>=5&&utilityScore!==void 0&&utilityScore<=0)return{healthy:!1,concern:"Low-utility entry"};if(entry.confidence<0.1)return{healthy:!1,concern:"Near-zero confidence"};if(entry.auto_generated===!0&&entry.confirmed_by.length===0)return{healthy:!1,concern:"Unconfirmed auto-generated"};return{healthy:!0}}async function quarantineEntry(directory,entryId,reason,reportedBy){if(!directory||directory.includes("..")){warn("[knowledge-validator] quarantineEntry: directory traversal attempt blocked");return}if(!entryId||entryId.includes("\x00")||entryId.includes(`
1077
+ `});class AutomationEventBus{listeners=new Map;eventHistory=[];maxHistorySize;constructor(options){this.maxHistorySize=options?.maxHistorySize??100}subscribe(type,listener){if(!this.listeners.has(type))this.listeners.set(type,new Set);return this.listeners.get(type).add(listener),()=>{this.listeners.get(type)?.delete(listener)}}async publish(type,payload,source){let event={type,timestamp:Date.now(),payload,source};if(this.eventHistory.push(event),this.eventHistory.length>this.maxHistorySize)this.eventHistory.shift();log(`[EventBus] ${type}`,{source,payload:typeof payload==="object"?"...":payload});let listeners=this.listeners.get(type);if(listeners)await Promise.all(Array.from(listeners).map(async(listener)=>{try{await listener(event)}catch(error93){log(`[EventBus] Listener error for ${type}`,{error:error93})}}))}getHistory(types2){if(!types2||types2.length===0)return[...this.eventHistory];return this.eventHistory.filter((e)=>types2.includes(e.type))}clearHistory(){this.eventHistory=[]}getListenerCount(type){return this.listeners.get(type)?.size??0}hasListeners(type){return this.getListenerCount(type)>0}}function getGlobalEventBus(){if(!globalEventBus)globalEventBus=new AutomationEventBus;return globalEventBus}var globalEventBus=null;var init_event_bus=__esm(()=>{init_utils()});function isActiveSwarmKnowledgeEntry(entry){return isActiveStatus(entry.status)}function findActiveSwarmNearDuplicate(lesson,entries,threshold){return findNearDuplicate(lesson,entries.filter(isActiveSwarmKnowledgeEntry),threshold)}function distinctPhaseCount(records){let phases=new Set;for(let record3 of records??[])if(Number.isInteger(record3.phase_number))phases.add(record3.phase_number);return phases.size}function reinforceSwarmKnowledgeEntry(entry,confirmation){if(!isActiveSwarmKnowledgeEntry(entry))return{entryId:entry.id,reinforced:!1,reason:"inactive"};if((entry.confirmed_by??[]).some((record3)=>record3.phase_number===confirmation.phase_number))return{entryId:entry.id,reinforced:!1,reason:"already_confirmed_phase"};return entry.confirmed_by=[...entry.confirmed_by??[],confirmation],entry.updated_at=confirmation.confirmed_at,entry.phases_alive=0,entry.confidence=computeConfidence(distinctPhaseCount(entry.confirmed_by),entry.auto_generated??!1),{entryId:entry.id,reinforced:!0,reason:"reinforced"}}var init_knowledge_reinforcement=__esm(()=>{init_knowledge_store();init_knowledge_types()});var exports_knowledge_validator={};__export(exports_knowledge_validator,{validateSkillPath:()=>validateSkillPath,validateSkillCandidatePath:()=>validateSkillCandidatePath,validateLesson:()=>validateLesson,validateActionableFields:()=>validateActionableFields,validateActionability:()=>validateActionability,unarchiveEntry:()=>unarchiveEntry,restoreEntry:()=>restoreEntry,resolveUnactionablePath:()=>resolveUnactionablePath,quarantineEntry:()=>quarantineEntry,auditEntryHealth:()=>auditEntryHealth,appendUnactionable:()=>appendUnactionable,_internals:()=>_internals29,SECURITY_DEGRADING_PATTERNS:()=>SECURITY_DEGRADING_PATTERNS,RETIRED_SKILL_HISTORY_MAX:()=>RETIRED_SKILL_HISTORY_MAX,INVISIBLE_FORMAT_CHARS:()=>INVISIBLE_FORMAT_CHARS,INJECTION_PATTERNS:()=>INJECTION_PATTERNS,DANGEROUS_COMMAND_WARNING_PATTERNS:()=>DANGEROUS_COMMAND_WARNING_PATTERNS,DANGEROUS_COMMAND_PATTERNS:()=>DANGEROUS_COMMAND_PATTERNS,DANGEROUS_COMMAND_ERROR_PATTERNS:()=>DANGEROUS_COMMAND_ERROR_PATTERNS,ALLOWED_SKILL_PATH_PREFIXES:()=>ALLOWED_SKILL_PATH_PREFIXES,ACTIONABLE_STRING_MAX:()=>ACTIONABLE_STRING_MAX,ACTIONABLE_LIST_MAX:()=>ACTIONABLE_LIST_MAX});import{appendFile as appendFile5,mkdir as mkdir8}from"node:fs/promises";import*as path53 from"node:path";function normalizeText(text){return text.normalize("NFKC").toLowerCase().replace(/[^\w\s]/g," ").replace(/\s+/g," ").trim()}function extractContextWords(text,word,contextWindow=3){let words=text.split(" "),context=new Set;if(!word.includes(" ")){let from=0,idx=words.indexOf(word,from);while(idx!==-1){let start=Math.max(0,idx-contextWindow),end=Math.min(words.length,idx+contextWindow+1);for(let i2=start;i2<end;i2++)if(i2!==idx&&words[i2]&&words[i2].length>0)context.add(words[i2]);from=idx+1,idx=words.indexOf(word,from)}return context}let termLen=word.split(" ").length,i=0;while(i<=words.length-termLen)if(words.slice(i,i+termLen).join(" ")===word){let start=Math.max(0,i-contextWindow),end=Math.min(words.length,i+termLen+contextWindow);for(let j=start;j<end;j++)if(j<i||j>=i+termLen){if(words[j]&&words[j].length>0)context.add(words[j])}i+=termLen}else i+=1;return context}function hasSignificantOverlap(set1,set22){if(set1.size===0||set22.size===0)return!1;return[...set1].some((word)=>set22.has(word))}function detectContradiction(candidate,existingLessons){let candidateTags=inferTags2(candidate);if(candidateTags.length===0)return!1;let candidateNorm=normalizeText(candidate);for(let existing of existingLessons){let existingTags=inferTags2(existing);if(!candidateTags.some((t)=>existingTags.includes(t)))continue;let existingNorm=normalizeText(existing);for(let[wordA,wordB]of NEGATION_PAIRS){if(candidateNorm.includes(wordA)&&existingNorm.includes(wordB)){let contextA=extractContextWords(candidateNorm,wordA),contextB=extractContextWords(existingNorm,wordB);if(hasSignificantOverlap(contextA,contextB))return!0}if(candidateNorm.includes(wordB)&&existingNorm.includes(wordA)){let contextB=extractContextWords(candidateNorm,wordB),contextA=extractContextWords(existingNorm,wordA);if(hasSignificantOverlap(contextA,contextB))return!0}}}return!1}function isVagueLesson(lesson){let words=normalizeText(lesson).split(/\s+/),hasTechRef=words.some((w)=>TECH_REFERENCE_WORDS.has(w)),hasActionVerb=words.some((w)=>ACTION_VERB_WORDS.has(w));return!hasTechRef&&!hasActionVerb}function validateLesson(candidate,existingLessons,meta3){if(!candidate||typeof candidate!=="string")return{valid:!1,layer:1,reason:"lesson too short (min 15 chars)",severity:"error"};if(!Array.isArray(existingLessons))existingLessons=[];if(candidate.length<15)return{valid:!1,layer:1,reason:"lesson too short (min 15 chars)",severity:"error"};if(candidate.length>280)return{valid:!1,layer:1,reason:"lesson too long (max 280 chars)",severity:"error"};if(!VALID_CATEGORIES.has(meta3.category))return{valid:!1,layer:1,reason:`invalid category: ${meta3.category}`,severity:"error"};let isGlobalScope=meta3.scope==="global",isStackScope=/^stack:[a-zA-Z0-9_-]{1,64}$/.test(meta3.scope);if(!isGlobalScope&&!isStackScope)return{valid:!1,layer:1,reason:"invalid scope: must be 'global' or 'stack:<name>'",severity:"error"};if(!(meta3.confidence>=0&&meta3.confidence<=1))return{valid:!1,layer:1,reason:"confidence out of range [0.0, 1.0]",severity:"error"};let normalizedCandidate=candidate.normalize("NFKC").replace(INVISIBLE_FORMAT_CHARS," ").replace(/\s+/g," ").toLowerCase();for(let pattern of DANGEROUS_COMMAND_ERROR_PATTERNS)if(pattern.test(normalizedCandidate))return{valid:!1,layer:2,reason:"dangerous command pattern detected",severity:"error"};for(let pattern of DANGEROUS_COMMAND_WARNING_PATTERNS)if(pattern.test(normalizedCandidate))return{valid:!0,layer:2,reason:"potentially dangerous command pattern queued for review",severity:"warning"};for(let pattern of SECURITY_DEGRADING_PATTERNS)if(pattern.test(normalizedCandidate))return{valid:!1,layer:2,reason:"security-degrading instruction detected",severity:"error"};for(let pattern of INJECTION_PATTERNS)if(pattern.test(candidate))return{valid:!1,layer:2,reason:"injection pattern detected",severity:"error"};if(detectContradiction(candidate,existingLessons))return{valid:!0,layer:3,reason:"possible contradiction with an existing lesson with shared tags",severity:"warning"};if(isVagueLesson(candidate))return{valid:!0,layer:3,reason:"lesson may be too vague (no tech reference or action verb)",severity:"warning"};return{valid:!0,layer:null,reason:null,severity:null}}function isCleanShortString(s){if(typeof s!=="string")return!1;if(s.length===0||s.length>ACTIONABLE_STRING_MAX)return!1;return!/[\x00-\x08\x0b-\x0c\x0e-\x1f\x7f]/.test(s)}function validateSkillPath(p){if(typeof p!=="string")return!1;if(p.length===0||p.length>256)return!1;if(p.includes("\x00"))return!1;if(path53.isAbsolute(p))return!1;if(p.includes(".."))return!1;let norm=p.replace(/\\/g,"/");return ALLOWED_SKILL_PATH_PREFIXES.some((prefix)=>norm.startsWith(prefix))}function validateSkillCandidatePath(p){if(typeof p!=="string")return!1;if(p.length===0||p.length>256)return!1;if(p.includes("\x00"))return!1;if(path53.isAbsolute(p))return!1;if(p.includes(".."))return!1;let norm=p.replace(/\\/g,"/");if(!norm.startsWith(".swarm/skills/candidates/"))return!1;let filename=norm.slice(25);return/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\.json$/i.test(filename)}function validateActionableFields(fields){let errors5=[];if(!fields)return{valid:!0,errors:errors5};function checkStringList(name,list){if(list===void 0)return;if(!Array.isArray(list)){errors5.push(`${name} must be an array`);return}if(list.length>ACTIONABLE_LIST_MAX)errors5.push(`${name} exceeds ${ACTIONABLE_LIST_MAX} items`);for(let item of list)if(!isCleanShortString(item)){errors5.push(`${name} contains invalid string`);return}}function checkNameList(name,list){if(list===void 0)return;if(!Array.isArray(list)){errors5.push(`${name} must be an array`);return}if(list.length>ACTIONABLE_LIST_MAX)errors5.push(`${name} exceeds ${ACTIONABLE_LIST_MAX} items`);for(let item of list)if(typeof item!=="string"||!NAME_PATTERN.test(item)){errors5.push(`${name} contains invalid name`);return}}if(checkStringList("triggers",fields.triggers),checkStringList("required_actions",fields.required_actions),checkStringList("forbidden_actions",fields.forbidden_actions),checkStringList("verification_checks",fields.verification_checks),checkNameList("applies_to_agents",fields.applies_to_agents),checkNameList("applies_to_tools",fields.applies_to_tools),fields.source_refs!==void 0){if(!Array.isArray(fields.source_refs))errors5.push("source_refs must be an array");else if(fields.source_refs.length>ACTIONABLE_LIST_MAX)errors5.push(`source_refs exceeds ${ACTIONABLE_LIST_MAX} items`);else for(let ref of fields.source_refs)if(typeof ref!=="string"||ref.length===0||ref.length>ACTIONABLE_STRING_MAX||SOURCE_REF_FORBIDDEN.test(ref)){errors5.push("source_refs contains invalid value");break}}if(fields.source_knowledge_ids!==void 0){if(!Array.isArray(fields.source_knowledge_ids))errors5.push("source_knowledge_ids must be an array");else for(let id of fields.source_knowledge_ids)if(typeof id!=="string"||id.length===0||id.length>64){errors5.push("source_knowledge_ids contains invalid value");break}}if(fields.directive_priority!==void 0&&!VALID_DIRECTIVE_PRIORITIES.has(String(fields.directive_priority)))errors5.push("directive_priority must be low|medium|high|critical");if(fields.generated_skill_slug!==void 0){if(typeof fields.generated_skill_slug!=="string"||!/^[a-z0-9][a-z0-9-]{0,63}$/.test(fields.generated_skill_slug))errors5.push("generated_skill_slug must be a kebab-case slug")}if(fields.generated_skill_path!==void 0&&!validateSkillPath(fields.generated_skill_path))errors5.push("generated_skill_path must be repo-local under allowed prefix");if(fields.draft_generated_skill_slug!==void 0){if(typeof fields.draft_generated_skill_slug!=="string"||!/^[a-z0-9][a-z0-9-]{0,63}$/.test(fields.draft_generated_skill_slug))errors5.push("draft_generated_skill_slug must be a kebab-case slug")}if(fields.draft_generated_skill_path!==void 0&&!validateSkillPath(fields.draft_generated_skill_path))errors5.push("draft_generated_skill_path must be repo-local under allowed prefix");if(fields.retired_skill_history!==void 0){if(!Array.isArray(fields.retired_skill_history))errors5.push("retired_skill_history must be an array of slugs");else if(fields.retired_skill_history.length>RETIRED_SKILL_HISTORY_MAX)errors5.push(`retired_skill_history exceeds ${RETIRED_SKILL_HISTORY_MAX} items`);else if(!fields.retired_skill_history.every((s)=>typeof s==="string"&&/^[a-z0-9][a-z0-9-]{0,63}$/.test(s)))errors5.push("retired_skill_history entries must be kebab-case slugs")}return{valid:errors5.length===0,errors:errors5}}function hasNonEmptyList(v){return Array.isArray(v)&&v.length>0}function validateActionability(entry){let hasPredicate=hasNonEmptyList(entry.forbidden_actions)||hasNonEmptyList(entry.required_actions)||hasNonEmptyList(entry.verification_checks)||typeof entry.verification_predicate==="string"&&entry.verification_predicate.trim().length>0,hasScope=hasNonEmptyList(entry.applies_to_tools)||hasNonEmptyList(entry.applies_to_agents);if(hasPredicate&&hasScope)return{actionable:!0};return{actionable:!1,reason:!hasPredicate&&!hasScope?"missing_predicate_and_scope":!hasPredicate?"missing_predicate":"missing_scope"}}function resolveUnactionablePath(directory){return path53.join(resolveKnowledgeStoreDir(directory),"knowledge-unactionable.jsonl")}async function appendUnactionable(directory,entry,reason){let filePath=resolveUnactionablePath(directory),dirPath=path53.dirname(filePath);await mkdir8(dirPath,{recursive:!0}),await transactKnowledge(filePath,(existing)=>{let record3={...entry,status:"quarantined_unactionable",unactionable_reason:reason,quarantined_at:new Date().toISOString()},duplicate=findNearDuplicate(record3.lesson,existing,0.6);if(duplicate?.unactionable_reason===reason)return duplicate.quarantined_at=record3.quarantined_at,duplicate.updated_at=record3.updated_at,existing;let next=[...existing,record3];return next.length>200?next.slice(-200):next})}function auditEntryHealth(entry){let utilityScore=entry.utility_score;if((entry.retrieval_outcomes?.shown_count??entry.retrieval_outcomes?.applied_count??0)>=5&&utilityScore!==void 0&&utilityScore<=0)return{healthy:!1,concern:"Low-utility entry"};if(entry.confidence<0.1)return{healthy:!1,concern:"Near-zero confidence"};if(entry.auto_generated===!0&&entry.confirmed_by.length===0)return{healthy:!1,concern:"Unconfirmed auto-generated"};return{healthy:!0}}async function quarantineEntry(directory,entryId,reason,reportedBy){if(!directory||directory.includes("..")){warn("[knowledge-validator] quarantineEntry: directory traversal attempt blocked");return}if(!entryId||entryId.includes("\x00")||entryId.includes(`
1078
1078
  `)){warn("[knowledge-validator] quarantineEntry: invalid entryId rejected");return}if(!["architect","user","auto"].includes(reportedBy))return;let sanitizedReason=reason.slice(0,500).replace(/[\x00-\x08\x0b-\x0c\x0e-\x1f\x7f\x0d]/g,""),knowledgePath=resolveSwarmKnowledgePath(directory),quarantinePath=path53.join(resolveKnowledgeStoreDir(directory),"knowledge-quarantined.jsonl"),rejectedPath=resolveSwarmRejectedPath(directory),swarmDir=resolveKnowledgeStoreDir(directory);await mkdir8(swarmDir,{recursive:!0});let release;try{release=await import_proper_lockfile3.default.lock(swarmDir,{retries:{retries:5,minTimeout:100,maxTimeout:500},stale:5000});let entries=await readKnowledge(knowledgePath),entry=entries.find((e)=>e.id===entryId);if(!entry)return;let remaining=entries.filter((e)=>e.id!==entryId),quarantined={...entry,status:"quarantined",original_status:entry.status,quarantine_reason:sanitizedReason,quarantined_at:new Date().toISOString(),reported_by:reportedBy},jsonlContent=remaining.length>0?`${remaining.map((e)=>JSON.stringify(e)).join(`
1079
1079
  `)}
1080
1080
  `:"";await atomicWriteFile(knowledgePath,jsonlContent),await appendFile5(quarantinePath,`${JSON.stringify(quarantined)}
@@ -1090,7 +1090,7 @@ RULES:
1090
1090
  `:"";await atomicWriteFile(rejectedPath,rejectedContent)}finally{if(release)await release()}}async function unarchiveEntry(directory,entryId){if(!directory||directory.includes(".."))return warn("[knowledge-validator] unarchiveEntry: directory traversal attempt blocked"),{restored:!1,reason:"not_found"};if(!entryId||entryId.includes("\x00")||entryId.includes(`
1091
1091
  `))return warn("[knowledge-validator] unarchiveEntry: invalid entryId rejected"),{restored:!1,reason:"not_found"};let storeDir=resolveKnowledgeStoreDir(directory),knowledgePath=resolveSwarmKnowledgePath(directory),swarmDir=storeDir;await mkdir8(swarmDir,{recursive:!0});let release;try{release=await import_proper_lockfile3.default.lock(swarmDir,{retries:{retries:5,minTimeout:100,maxTimeout:500},stale:5000});let entries=await readKnowledge(knowledgePath),target=entries.find((e)=>e.id===entryId);if(!target)return{restored:!1,reason:"not_found"};if(target.status!=="archived")return{restored:!1,reason:"not_archived"};let validation=validateLesson(target.lesson,[],{category:target.category,scope:target.scope,confidence:target.confidence});if(!validation.valid)return warn(`[knowledge-validator] unarchiveEntry: entry ${entryId} failed re-validation: ${validation.reason}`),{restored:!1,reason:"invalid_lesson"};let restoredStatus=target.archived_from??"candidate",finalStatus=new Set(["candidate","established","promoted"]).has(restoredStatus)?restoredStatus:"candidate",{archived_from:_af,archived_at:_at,recent_negative_phase_count:_rnpc,last_demotion_phase:_ldp,...rest}=target,restored={...rest,status:finalStatus,updated_at:new Date().toISOString(),recent_negative_phase_count:0,last_demotion_phase:void 0},next=entries.map((e)=>e.id===entryId?restored:e),jsonlContent=next.length>0?`${next.map((e)=>JSON.stringify(e)).join(`
1092
1092
  `)}
1093
- `:"";return await atomicWriteFile(knowledgePath,jsonlContent),{restored:!0,restored_to:finalStatus}}finally{if(release)await release()}}var import_proper_lockfile3,DANGEROUS_COMMAND_ERROR_PATTERNS,DANGEROUS_COMMAND_WARNING_PATTERNS,DANGEROUS_COMMAND_PATTERNS,SECURITY_DEGRADING_PATTERNS,INVISIBLE_FORMAT_CHARS,INJECTION_PATTERNS,VALID_CATEGORIES,TECH_REFERENCE_WORDS,ACTION_VERB_WORDS,NEGATION_PAIRS,ACTIONABLE_STRING_MAX=200,ACTIONABLE_LIST_MAX=20,RETIRED_SKILL_HISTORY_MAX=50,NAME_PATTERN,SOURCE_REF_FORBIDDEN,ALLOWED_SKILL_PATH_PREFIXES,VALID_DIRECTIVE_PRIORITIES,_internals29;var init_knowledge_validator=__esm(()=>{init_task_file();init_logger();init_knowledge_link();init_knowledge_store();import_proper_lockfile3=__toESM(require_proper_lockfile(),1),DANGEROUS_COMMAND_ERROR_PATTERNS=[/\brm\s+-rf\b/,/\bsudo\s+rm\b/,/\bmkfs\b/,/\bdd\s+if=/,/:\(\)\s*\{/,/\bchmod\s+-R\s+777\b/i,/\bdeltree\b/,/\brmdir\s+\/s\b/],DANGEROUS_COMMAND_WARNING_PATTERNS=[/\bformat\b/,/\bkill\s+-9\b/,/\bpkill\b/,/\bkillall\b/,/`[^`]*`/,/\$\([^)]*\)/],DANGEROUS_COMMAND_PATTERNS=[...DANGEROUS_COMMAND_ERROR_PATTERNS,...DANGEROUS_COMMAND_WARNING_PATTERNS],SECURITY_DEGRADING_PATTERNS=[/disable\s+.{0,50}firewall/i,/turn\s+off\s+.{0,50}security/i,/skip\s+.{0,50}auth/i,/bypass\s+.{0,50}auth/i,/ignore\s+.{0,50}certificate/i,/disable\s+.{0,50}tls/i,/disable\s+.{0,50}ssl/i,/no\s+.{0,50}validation/i,/disable\s+.{0,50}2fa/i,/remove\s+.{0,50}password/i],INVISIBLE_FORMAT_CHARS=/[\u00AD\u200B-\u200F\u202A-\u202E\u2060-\u2064\u2066-\u2069\uFEFF]/g,INJECTION_PATTERNS=[/[\x00-\x08\x0b-\x0c\x0e-\x1f\x7f\x0d]/,/[\u00AD\u200B-\u200F\u202A-\u202E\u2060-\u2064\u2066-\u2069\uFEFF]/,/^system\s*:/i,/<script/i,/javascript:/i,/\beval\(/i,/\b__proto__\b/,/\bconstructor\[/,/\.prototype\[/],VALID_CATEGORIES=new Set(["process","architecture","tooling","security","testing","debugging","performance","integration","todo","other"]),TECH_REFERENCE_WORDS=new Set(["git","docker","typescript","bun","vitest","node","python","react","sql","api","hook","test","schema","config","file","function","class","module","import","export"]),ACTION_VERB_WORDS=new Set(["use","avoid","prefer","run","check","always","never","ensure","call","write","add","remove","update","set","enable","disable"]),NEGATION_PAIRS=[["always","never"],["must","must not"],["must","should not"],["enable","disable"],["use","avoid"],["use","don't use"],["recommended","not recommended"]];NAME_PATTERN=/^[a-z][a-z0-9_]{0,63}$/,SOURCE_REF_FORBIDDEN=/(\.\.\/|\.\.\\|\0|[\x00-\x1f\x7f])/,ALLOWED_SKILL_PATH_PREFIXES=[".opencode/skills/generated/",".swarm/skills/proposals/",".swarm/skills/candidates/"],VALID_DIRECTIVE_PRIORITIES=new Set(["low","medium","high","critical"]);_internals29={validateLesson,auditEntryHealth,quarantineEntry,restoreEntry,unarchiveEntry,extractContextWords,hasSignificantOverlap}});var exports_knowledge_store={};__export(exports_knowledge_store,{wordBigrams:()=>wordBigrams,transactKnowledge:()=>transactKnowledge,transactFile:()=>transactFile,sweepStaleTodos:()=>sweepStaleTodos,sweepAgedEntries:()=>sweepAgedEntries,rewriteKnowledge:()=>rewriteKnowledge,resolveSwarmRetractionsPath:()=>resolveSwarmRetractionsPath,resolveSwarmRejectedPath:()=>resolveSwarmRejectedPath,resolveSwarmKnowledgePath:()=>resolveSwarmKnowledgePath,resolveHiveRejectedPath:()=>resolveHiveRejectedPath,resolveHiveKnowledgePath:()=>resolveHiveKnowledgePath,resolveHiveEventsPath:()=>resolveHiveEventsPath,readRetractionRecords:()=>readRetractionRecords,readRejectedLessons:()=>readRejectedLessons,readKnowledge:()=>readKnowledge,normalizeEntry:()=>normalizeEntry,normalize:()=>normalize5,jaccardBigram:()=>jaccardBigram,inferTags:()=>inferTags2,getPlatformConfigDir:()=>getPlatformConfigDir,getArchivedKnowledgeIds:()=>getArchivedKnowledgeIds,findNearDuplicate:()=>findNearDuplicate,enforceKnowledgeCap:()=>enforceKnowledgeCap,computeOutcomeSignal:()=>computeOutcomeSignal,computeConfidence:()=>computeConfidence,bumpKnowledgeConfidenceBatch:()=>bumpKnowledgeConfidenceBatch,appendRetractionRecord:()=>appendRetractionRecord,appendRejectedLesson:()=>appendRejectedLesson,appendKnowledgeWithCapEnforcement:()=>appendKnowledgeWithCapEnforcement,appendKnowledge:()=>appendKnowledge,_internals:()=>_internals30,OUTCOME_SIGNAL_SMOOTHING:()=>OUTCOME_SIGNAL_SMOOTHING});import{existsSync as existsSync25}from"node:fs";import{appendFile as appendFile6,mkdir as mkdir9,readFile as readFile9}from"node:fs/promises";import*as os15 from"node:os";import*as path54 from"node:path";function getPlatformConfigDir(){let platform=process.platform,home=process.env.HOME||os15.homedir();if(platform==="win32")return path54.join(process.env.LOCALAPPDATA||path54.join(home,"AppData","Local"),"opencode-swarm","config");else if(platform==="darwin")return path54.join(home,"Library","Application Support","opencode-swarm");else return path54.join(process.env.XDG_CONFIG_HOME||path54.join(home,".config"),"opencode-swarm")}function resolveSwarmKnowledgePath(directory){return path54.join(resolveKnowledgeStoreDir(directory),"knowledge.jsonl")}function resolveSwarmRejectedPath(directory){return path54.join(resolveKnowledgeStoreDir(directory),"knowledge-rejected.jsonl")}function resolveSwarmRetractionsPath(directory){return path54.join(resolveKnowledgeStoreDir(directory),"knowledge-retractions.jsonl")}function resolveHiveKnowledgePath(){let platform=process.platform,home=process.env.HOME||os15.homedir(),dataDir;if(platform==="win32")dataDir=path54.join(process.env.LOCALAPPDATA||path54.join(home,"AppData","Local"),"opencode-swarm","Data");else if(platform==="darwin")dataDir=path54.join(home,"Library","Application Support","opencode-swarm");else dataDir=path54.join(process.env.XDG_DATA_HOME||path54.join(home,".local","share"),"opencode-swarm");return path54.join(dataDir,"shared-learnings.jsonl")}function resolveHiveRejectedPath(){let hivePath=resolveHiveKnowledgePath();return path54.join(path54.dirname(hivePath),"shared-learnings-rejected.jsonl")}function resolveHiveEventsPath(){let hivePath=resolveHiveKnowledgePath();return path54.join(path54.dirname(hivePath),"shared-knowledge-events.jsonl")}function parseKnowledgeContent(content,max){let results=[];for(let line of content.split(`
1093
+ `:"";return await atomicWriteFile(knowledgePath,jsonlContent),{restored:!0,restored_to:finalStatus}}finally{if(release)await release()}}var import_proper_lockfile3,DANGEROUS_COMMAND_ERROR_PATTERNS,DANGEROUS_COMMAND_WARNING_PATTERNS,DANGEROUS_COMMAND_PATTERNS,SECURITY_DEGRADING_PATTERNS,INVISIBLE_FORMAT_CHARS,INJECTION_PATTERNS,VALID_CATEGORIES,TECH_REFERENCE_WORDS,ACTION_VERB_WORDS,NEGATION_PAIRS,ACTIONABLE_STRING_MAX=200,ACTIONABLE_LIST_MAX=20,RETIRED_SKILL_HISTORY_MAX=50,NAME_PATTERN,SOURCE_REF_FORBIDDEN,ALLOWED_SKILL_PATH_PREFIXES,VALID_DIRECTIVE_PRIORITIES,_internals29;var init_knowledge_validator=__esm(()=>{init_task_file();init_logger();init_knowledge_link();init_knowledge_store();import_proper_lockfile3=__toESM(require_proper_lockfile(),1),DANGEROUS_COMMAND_ERROR_PATTERNS=[/\brm\s+-rf\b/,/\bsudo\s+rm\b/,/\bmkfs\b/,/\bdd\s+if=/,/:\(\)\s*\{/,/\bchmod\s+-R\s+777\b/i,/\bdeltree\b/,/\brmdir\s+\/s\b/],DANGEROUS_COMMAND_WARNING_PATTERNS=[/\bformat\b/,/\bkill\s+-9\b/,/\bpkill\b/,/\bkillall\b/,/`[^`]*`/,/\$\([^)]*\)/],DANGEROUS_COMMAND_PATTERNS=[...DANGEROUS_COMMAND_ERROR_PATTERNS,...DANGEROUS_COMMAND_WARNING_PATTERNS],SECURITY_DEGRADING_PATTERNS=[/disable\s+.{0,50}firewall/i,/turn\s+off\s+.{0,50}security/i,/skip\s+.{0,50}auth/i,/bypass\s+.{0,50}auth/i,/ignore\s+.{0,50}certificate/i,/disable\s+.{0,50}tls/i,/disable\s+.{0,50}ssl/i,/no\s+.{0,50}validation/i,/disable\s+.{0,50}2fa/i,/remove\s+.{0,50}password/i],INVISIBLE_FORMAT_CHARS=/[\u00AD\u200B-\u200F\u202A-\u202E\u2060-\u2064\u2066-\u2069\uFEFF]/g,INJECTION_PATTERNS=[/[\x00-\x08\x0b-\x0c\x0e-\x1f\x7f\x0d]/,/[\u00AD\u200B-\u200F\u202A-\u202E\u2060-\u2064\u2066-\u2069\uFEFF]/,/^system\s*:/i,/<script/i,/javascript:/i,/\beval\(/i,/\b__proto__\b/,/\bconstructor\[/,/\.prototype\[/],VALID_CATEGORIES=new Set(["process","architecture","tooling","security","testing","debugging","performance","integration","todo","other"]),TECH_REFERENCE_WORDS=new Set(["git","docker","typescript","bun","vitest","node","python","react","sql","api","hook","test","schema","config","file","function","class","module","import","export"]),ACTION_VERB_WORDS=new Set(["use","avoid","prefer","run","check","always","never","ensure","call","write","add","remove","update","set","enable","disable"]),NEGATION_PAIRS=[["always","never"],["must","must not"],["must","should not"],["enable","disable"],["use","avoid"],["use","don't use"],["recommended","not recommended"]];NAME_PATTERN=/^[a-z][a-z0-9_]{0,63}$/,SOURCE_REF_FORBIDDEN=/(\.\.\/|\.\.\\|\0|[\x00-\x1f\x7f])/,ALLOWED_SKILL_PATH_PREFIXES=[".opencode/skills/generated/",".swarm/skills/proposals/",".swarm/skills/candidates/"],VALID_DIRECTIVE_PRIORITIES=new Set(["low","medium","high","critical"]);_internals29={validateLesson,auditEntryHealth,quarantineEntry,restoreEntry,unarchiveEntry,extractContextWords,hasSignificantOverlap}});var exports_knowledge_store={};__export(exports_knowledge_store,{wordBigrams:()=>wordBigrams,transactKnowledge:()=>transactKnowledge,transactFile:()=>transactFile,sweepStaleTodos:()=>sweepStaleTodos,sweepAgedEntries:()=>sweepAgedEntries,rewriteKnowledge:()=>rewriteKnowledge,resolveSwarmRetractionsPath:()=>resolveSwarmRetractionsPath,resolveSwarmRejectedPath:()=>resolveSwarmRejectedPath,resolveSwarmKnowledgePath:()=>resolveSwarmKnowledgePath,resolveHiveRejectedPath:()=>resolveHiveRejectedPath,resolveHiveKnowledgePath:()=>resolveHiveKnowledgePath,resolveHiveEventsPath:()=>resolveHiveEventsPath,readRetractionRecords:()=>readRetractionRecords,readRejectedLessons:()=>readRejectedLessons,readKnowledge:()=>readKnowledge,normalizeEntry:()=>normalizeEntry,normalize:()=>normalize5,jaccardBigram:()=>jaccardBigram,inferTags:()=>inferTags2,getPlatformConfigDir:()=>getPlatformConfigDir,getArchivedKnowledgeIds:()=>getArchivedKnowledgeIds,findNearDuplicate:()=>findNearDuplicate,enforceKnowledgeCap:()=>enforceKnowledgeCap,confirmEntriesPhase:()=>confirmEntriesPhase,computeOutcomeSignal:()=>computeOutcomeSignal,computeConfidence:()=>computeConfidence,bumpKnowledgeConfidenceBatch:()=>bumpKnowledgeConfidenceBatch,appendRetractionRecord:()=>appendRetractionRecord,appendRejectedLesson:()=>appendRejectedLesson,appendKnowledgeWithCapEnforcement:()=>appendKnowledgeWithCapEnforcement,appendKnowledge:()=>appendKnowledge,_internals:()=>_internals30,OUTCOME_SIGNAL_SMOOTHING:()=>OUTCOME_SIGNAL_SMOOTHING,MAX_CONFIRMED_BY:()=>MAX_CONFIRMED_BY});import{existsSync as existsSync25}from"node:fs";import{appendFile as appendFile6,mkdir as mkdir9,readFile as readFile9}from"node:fs/promises";import*as os15 from"node:os";import*as path54 from"node:path";function getPlatformConfigDir(){let platform=process.platform,home=process.env.HOME||os15.homedir();if(platform==="win32")return path54.join(process.env.LOCALAPPDATA||path54.join(home,"AppData","Local"),"opencode-swarm","config");else if(platform==="darwin")return path54.join(home,"Library","Application Support","opencode-swarm");else return path54.join(process.env.XDG_CONFIG_HOME||path54.join(home,".config"),"opencode-swarm")}function resolveSwarmKnowledgePath(directory){return path54.join(resolveKnowledgeStoreDir(directory),"knowledge.jsonl")}function resolveSwarmRejectedPath(directory){return path54.join(resolveKnowledgeStoreDir(directory),"knowledge-rejected.jsonl")}function resolveSwarmRetractionsPath(directory){return path54.join(resolveKnowledgeStoreDir(directory),"knowledge-retractions.jsonl")}function resolveHiveKnowledgePath(){let platform=process.platform,home=process.env.HOME||os15.homedir(),dataDir;if(platform==="win32")dataDir=path54.join(process.env.LOCALAPPDATA||path54.join(home,"AppData","Local"),"opencode-swarm","Data");else if(platform==="darwin")dataDir=path54.join(home,"Library","Application Support","opencode-swarm");else dataDir=path54.join(process.env.XDG_DATA_HOME||path54.join(home,".local","share"),"opencode-swarm");return path54.join(dataDir,"shared-learnings.jsonl")}function resolveHiveRejectedPath(){let hivePath=resolveHiveKnowledgePath();return path54.join(path54.dirname(hivePath),"shared-learnings-rejected.jsonl")}function resolveHiveEventsPath(){let hivePath=resolveHiveKnowledgePath();return path54.join(path54.dirname(hivePath),"shared-knowledge-events.jsonl")}function parseKnowledgeContent(content,max){let results=[];for(let line of content.split(`
1094
1094
  `)){if(Number.isFinite(max)&&results.length>=max)break;let trimmed=line.trim();if(!trimmed)continue;try{results.push(normalizeEntry(JSON.parse(trimmed)))}catch{console.warn(`[knowledge-store] Skipping corrupted JSONL line: ${trimmed.slice(0,80)}`)}}return results}async function readKnowledge(filePath,maxEntries){let resolvedPath=path54.resolve(filePath),cap=maxEntries!==void 0&&maxEntries>0?maxEntries:void 0;if(cap!==void 0){if(!existsSync25(resolvedPath))return[];let content=await readFile9(resolvedPath,"utf-8");return parseKnowledgeContent(content,cap)}return await readCachedParsedFile(resolvedPath,KNOWLEDGE_JSONL_CACHE_NAMESPACE,async()=>{if(!existsSync25(resolvedPath))return null;return await readFile9(resolvedPath,"utf-8")},(content)=>parseKnowledgeContent(content,1/0))??[]}function normalizeEntry(raw){if(!raw||typeof raw!=="object")return raw;let obj=raw;if(!("retrieval_outcomes"in obj))return raw;let ro=obj.retrieval_outcomes;if(!ro||typeof ro!=="object")ro={},obj.retrieval_outcomes=ro;if(typeof ro.shown_count!=="number")ro.shown_count=typeof ro.applied_count==="number"?ro.applied_count:0;if(typeof ro.acknowledged_count!=="number")ro.acknowledged_count=0;if(typeof ro.applied_explicit_count!=="number")ro.applied_explicit_count=0;if(typeof ro.ignored_count!=="number")ro.ignored_count=0;if(typeof ro.violated_count!=="number")ro.violated_count=0;if(typeof ro.contradicted_count!=="number")ro.contradicted_count=0;if(typeof ro.succeeded_after_shown_count!=="number")ro.succeeded_after_shown_count=typeof ro.succeeded_after_count==="number"?ro.succeeded_after_count:0;if(typeof ro.failed_after_shown_count!=="number")ro.failed_after_shown_count=typeof ro.failed_after_count==="number"?ro.failed_after_count:0;try{if(typeof obj.encounter_score!=="number"||Number.isNaN(obj.encounter_score))obj.encounter_score=0}catch{try{Object.defineProperty(obj,"encounter_score",{value:0,writable:!0,configurable:!0,enumerable:!0})}catch{}}if(typeof obj.recent_negative_phase_count!=="number")obj.recent_negative_phase_count=0;let arrayFields=["triggers","required_actions","forbidden_actions","applies_to_agents","applies_to_tools","verification_checks","source_refs","source_knowledge_ids"];for(let f of arrayFields){let v=obj[f];if(v!==void 0&&!Array.isArray(v))delete obj[f]}if(!Array.isArray(obj.tags))obj.tags=[];return raw}async function readRejectedLessons(directory){return readKnowledge(resolveSwarmRejectedPath(directory))}async function readRetractionRecords(directory){return readKnowledge(resolveSwarmRetractionsPath(directory))}async function appendRetractionRecord(directory,record3){await appendKnowledge(resolveSwarmRetractionsPath(directory),record3)}async function appendKnowledge(filePath,entry){let dir=path54.dirname(filePath);await mkdir9(dir,{recursive:!0});let release=null;try{release=await import_proper_lockfile4.default.lock(dir,{retries:{retries:5,minTimeout:100,maxTimeout:500},stale:5000}),await appendFile6(filePath,`${JSON.stringify(entry)}
1095
1095
  `,"utf-8")}finally{if(release)try{await release()}catch{}}}async function rewriteKnowledge(filePath,entries){let dir=path54.dirname(filePath);await mkdir9(dir,{recursive:!0});let release=null;try{release=await import_proper_lockfile4.default.lock(dir,{retries:{retries:5,minTimeout:100,maxTimeout:500},stale:5000});let content=entries.map((e)=>JSON.stringify(e)).join(`
1096
1096
  `)+(entries.length>0?`
@@ -1098,9 +1098,9 @@ RULES:
1098
1098
  `)+(entries.length>0?`
1099
1099
  `:"");await atomicWriteFile(fp,content)},mutate)}async function getArchivedKnowledgeIds(directory){let archived=new Set,swarmPath=resolveSwarmKnowledgePath(directory);try{let lines=(await readFile9(swarmPath,"utf-8")).split(`
1100
1100
  `).filter((l)=>l.trim());for(let line of lines)try{let entry=JSON.parse(line);if(!isActiveStatus(entry.status))archived.add(entry.id)}catch{}}catch{}let hivePath=resolveHiveKnowledgePath();try{let lines=(await readFile9(hivePath,"utf-8")).split(`
1101
- `).filter((l)=>l.trim());for(let line of lines)try{let entry=JSON.parse(line);if(!isActiveStatus(entry.status))archived.add(entry.id)}catch{}}catch{}return archived}async function appendKnowledgeWithCapEnforcement(filePath,entry,maxEntries){return transactKnowledge(filePath,(entries)=>{let updated=[...entries,entry];if(updated.length>maxEntries)return selectKnowledgeCapSurvivors(updated,maxEntries);return updated})}async function enforceKnowledgeCap(filePath,maxEntries){await transactKnowledge(filePath,(entries)=>{if(entries.length<=maxEntries)return null;return selectKnowledgeCapSurvivors(entries,maxEntries)})}function selectKnowledgeCapSurvivors(entries,maxEntries){if(entries.length<=maxEntries)return entries;if(maxEntries<=0)return[];let candidates=entries.map((entry,index)=>{let maybeKnowledge=entry;return{entry,index,status:maybeKnowledge.status,outcomeSignal:computeOutcomeSignal(maybeKnowledge.retrieval_outcomes)}}),evictable=candidates.every((c)=>c.status==="promoted")?candidates:candidates.filter((c)=>c.status!=="promoted"),targetDropCount=entries.length-maxEntries,dropCount=Math.min(targetDropCount,evictable.length);if(dropCount<=0)return entries;let drop=new Set([...evictable].sort((a,b)=>{let inactiveDelta=getKnowledgeCapStatusPriority(a.status)-getKnowledgeCapStatusPriority(b.status);if(inactiveDelta!==0)return inactiveDelta;let signalDelta=a.outcomeSignal-b.outcomeSignal;if(signalDelta!==0)return signalDelta;return a.index-b.index}).slice(0,dropCount).map((c)=>c.index));return candidates.filter((c)=>!drop.has(c.index)).map((c)=>c.entry)}function getKnowledgeCapStatusPriority(status){if(!isActiveStatus(status))return 0;return 1}async function sweepAgedEntries(filePath,defaultMaxPhases){let result={scanned:0,aged:0,archived:0,removed:0,skipped_promoted:0};return await transactKnowledge(filePath,(entries)=>{if(result.scanned=entries.length,entries.length===0)return null;let now=new Date().toISOString(),mutated=!1;for(let entry of entries){if(entry.status==="archived")continue;if(entry.status==="promoted"){result.skipped_promoted++;continue}entry.phases_alive=(entry.phases_alive??0)+1,result.aged++,mutated=!0;let ttl=entry.max_phases??defaultMaxPhases;if(entry.phases_alive>ttl)entry.archived_from=entry.status,entry.archived_at=now,entry.status="archived",entry.updated_at=now,result.archived++}return mutated?entries:null}),result}async function sweepStaleTodos(filePath,todoMaxPhases){let result={scanned:0,aged:0,archived:0,removed:0,skipped_promoted:0};return await transactKnowledge(filePath,(entries)=>{if(result.scanned=entries.length,entries.length===0)return null;let kept=entries.filter((e)=>{if(e.category!=="todo"||e.status==="promoted")return!0;if((e.phases_alive??0)>todoMaxPhases)return result.removed++,!1;return!0});return result.removed>0?kept:null}),result}async function appendRejectedLesson(directory,lesson,maxEntries=20){let filePath=resolveSwarmRejectedPath(directory);await transactKnowledge(filePath,(existing)=>{let updated=[...existing,lesson];if(updated.length>maxEntries)return updated.slice(updated.length-maxEntries);return updated})}function normalize5(text){return(typeof text==="string"?text:String(text??"")).toLowerCase().replace(/[^\w\s]/g," ").replace(/\s+/g," ").trim()}function wordBigrams(text){let words=normalize5(text).split(" ").filter(Boolean),bigrams=new Set;for(let i=0;i<words.length-1;i++)bigrams.add(`${words[i]} ${words[i+1]}`);return bigrams}function jaccardBigram(a,b){if(a.size===0&&b.size===0)return 1;let aArr=Array.from(a),intersection3=new Set(aArr.filter((x)=>b.has(x))),union3=new Set([...aArr,...Array.from(b)]);return intersection3.size/union3.size}function findNearDuplicate(candidate,entries,threshold=0.6){let candidateBigrams=wordBigrams(candidate);return entries.find((entry)=>{let entryBigrams=wordBigrams(entry.lesson);return jaccardBigram(candidateBigrams,entryBigrams)>=threshold})}function computeConfidence(confirmedByCount,autoGenerated){let score=0.5;if(score+=Math.min(confirmedByCount,3)*0.1,!autoGenerated)score+=0.1;return Math.min(score,1)}function computeOutcomeSignal(outcomes){if(!outcomes)return 0;let positives=(outcomes.applied_explicit_count??0)+(outcomes.succeeded_after_shown_count??0),negatives=(outcomes.ignored_count??0)+(outcomes.violated_count??0)+(outcomes.contradicted_count??0)+(outcomes.failed_after_shown_count??0),total=positives+negatives;if(total===0)return 0;return(positives-negatives)/(total+OUTCOME_SIGNAL_SMOOTHING)}function inferTags2(lesson){let lower=lesson.toLowerCase(),tags=[];if(/(^|\s)(?:todo|remember|don't?(?:\s+)?forget)(?:\s|:|,|$)/i.test(lesson))tags.push("todo");if(/\b(?:typescript|ts)\b/.test(lower))tags.push("typescript");if(/\b(?:javascript|js)\b/.test(lower))tags.push("javascript");if(/\b(?:python)\b/.test(lower))tags.push("python");if(/\b(?:bun|node|deno)\b/.test(lower))tags.push("runtime");if(/\b(?:react|vue|svelte|angular)\b/.test(lower))tags.push("frontend");if(/\b(?:git|github|gitlab)\b/.test(lower))tags.push("git");if(/\b(?:docker|kubernetes|k8s)\b/.test(lower))tags.push("container");if(/\b(?:sql|postgres|mysql|sqlite)\b/.test(lower))tags.push("database");if(/\b(?:test|spec|vitest|jest|mocha)\b/.test(lower))tags.push("testing");if(/\b(?:ci|cd|pipeline|workflow|action)\b/.test(lower))tags.push("ci-cd");if(/\b(?:security|auth|token|password|encrypt)\b/.test(lower))tags.push("security");if(/\b(?:performance|latency|throughput|cache)\b/.test(lower))tags.push("performance");if(/\b(?:api|rest|graphql|grpc|endpoint)\b/.test(lower))tags.push("api");if(/\b(?:swarm|architect|agent|hook|plan)\b/.test(lower))tags.push("opencode-swarm");return Array.from(new Set(tags))}async function bumpKnowledgeConfidenceBatch(directory,deltas,options){if(deltas.length===0)return;let swarmPath=resolveSwarmKnowledgePath(directory),hivePath=resolveHiveKnowledgePath(),touchedSwarm=[],touchedHive=[];try{touchedSwarm.push(...await applyConfidenceDeltas(swarmPath,deltas));let swarmIds=new Set(touchedSwarm.map((e)=>e.id)),hiveOnly=deltas.filter((d)=>!swarmIds.has(d.id));if(hiveOnly.length>0)touchedHive.push(...await applyConfidenceDeltas(hivePath,hiveOnly));await applyConfidenceFloorAction(directory,[...touchedSwarm,...touchedHive],options).catch((err)=>{console.warn("[knowledge-store] confidence-floor action sweep failed (best-effort):",err instanceof Error?err.message:String(err))})}catch(err){console.warn("[knowledge-store] bumpKnowledgeConfidenceBatch failed (fail-open):",err instanceof Error?err.message:String(err))}}async function applyConfidenceFloorAction(directory,touched,options){let action=options?.floorAction??"demote";if(action==="none"||touched.length===0)return;let minOutcomes=options?.floorMinOutcomes??3,signalThreshold=options?.floorSignalThreshold??0,FLOOR_EPSILON=0.000000001,atFloor=touched.filter((e)=>e.confidence<=CONFIDENCE_FLOOR+FLOOR_EPSILON),recovered=touched.filter((e)=>e.confidence>CONFIDENCE_FLOOR+FLOOR_EPSILON&&e.confidence_floor_demoted);if(atFloor.length===0&&recovered.length===0)return;let{readKnowledgeCounterRollups,effectiveRetrievalOutcomes}=await Promise.resolve().then(() => (init_knowledge_events(),exports_knowledge_events)),rollups=await readKnowledgeCounterRollups(directory),flagIds=new Set;for(let e of atFloor){let outcomes=effectiveRetrievalOutcomes(e.retrieval_outcomes,rollups?.get(e.id)),signal=computeOutcomeSignal(outcomes),totalEvidence=(outcomes.applied_explicit_count??0)+(outcomes.succeeded_after_shown_count??0)+(outcomes.ignored_count??0)+(outcomes.violated_count??0)+(outcomes.contradicted_count??0)+(outcomes.failed_after_shown_count??0);if(signal<signalThreshold&&totalEvidence>=minOutcomes)flagIds.add(e.id)}for(let e of recovered)flagIds.add(e.id);if(flagIds.size===0)return;let swarmPath=resolveSwarmKnowledgePath(directory),hivePath=resolveHiveKnowledgePath(),toQuarantine=[];await transactKnowledge(swarmPath,(swarmEntries)=>{let now=new Date().toISOString();for(let entry of swarmEntries){if(!flagIds.has(entry.id))continue;if(atFloor.find((e)=>e.id===entry.id)){if(entry.confidence_floor_demoted=!0,action==="quarantine")toQuarantine.push({id:entry.id,tier:"swarm"})}else entry.confidence_floor_demoted=!1;entry.updated_at=now}return swarmEntries}).catch((err)=>{console.warn("[knowledge-store] confidence-floor swarm flag transaction failed (best-effort):",err instanceof Error?err.message:String(err))});let hiveFlagIds=new Set;for(let e of atFloor)if(e.tier==="hive"&&flagIds.has(e.id))hiveFlagIds.add(e.id);for(let e of recovered)if(e.tier==="hive"&&flagIds.has(e.id))hiveFlagIds.add(e.id);if(hiveFlagIds.size>0)await transactKnowledge(hivePath,(hiveEntries)=>{let now=new Date().toISOString();for(let entry of hiveEntries){if(!hiveFlagIds.has(entry.id))continue;if(atFloor.find((e)=>e.id===entry.id))entry.confidence_floor_demoted=!0;else entry.confidence_floor_demoted=!1;entry.updated_at=now}return hiveEntries}).catch((err)=>{console.warn("[knowledge-store] confidence-floor hive flag transaction failed (best-effort):",err instanceof Error?err.message:String(err))});if(action==="quarantine"&&toQuarantine.length>0){let{quarantineEntry:quarantineEntry2}=await Promise.resolve().then(() => (init_knowledge_validator(),exports_knowledge_validator));for(let{id}of toQuarantine)await quarantineEntry2(directory,id,"confidence_floor_negative_outcome","auto").catch((err)=>{console.warn("[knowledge-store] confidence-floor quarantine failed (best-effort):",err instanceof Error?err.message:String(err))})}}async function applyConfidenceDeltas(filePath,deltas){let idDeltaMap=new Map;for(let d of deltas){let existing=idDeltaMap.get(d.id);idDeltaMap.set(d.id,existing!==void 0?existing+d.delta:d.delta)}let touched=[],release=null;try{let dir=path54.dirname(filePath);await mkdir9(dir,{recursive:!0}),release=await import_proper_lockfile4.default.lock(dir,{retries:{retries:5,minTimeout:100,maxTimeout:500},stale:5000});let entries=await readKnowledge(filePath);if(entries.length===0)return[];let now=new Date().toISOString(),mutated=!1;for(let entry of entries){let delta=idDeltaMap.get(entry.id);if(delta===void 0)continue;entry.confidence=Math.max(CONFIDENCE_FLOOR,Math.min(CONFIDENCE_CEILING,entry.confidence+delta)),entry.updated_at=now,mutated=!0,touched.push(entry)}if(mutated){let content=entries.map((e)=>JSON.stringify(e)).join(`
1101
+ `).filter((l)=>l.trim());for(let line of lines)try{let entry=JSON.parse(line);if(!isActiveStatus(entry.status))archived.add(entry.id)}catch{}}catch{}return archived}async function appendKnowledgeWithCapEnforcement(filePath,entry,maxEntries){return transactKnowledge(filePath,(entries)=>{let updated=[...entries,entry];if(updated.length>maxEntries)return selectKnowledgeCapSurvivors(updated,maxEntries);return updated})}async function enforceKnowledgeCap(filePath,maxEntries){await transactKnowledge(filePath,(entries)=>{if(entries.length<=maxEntries)return null;return selectKnowledgeCapSurvivors(entries,maxEntries)})}function selectKnowledgeCapSurvivors(entries,maxEntries){if(entries.length<=maxEntries)return entries;if(maxEntries<=0)return[];let candidates=entries.map((entry,index)=>{let maybeKnowledge=entry;return{entry,index,status:maybeKnowledge.status,outcomeSignal:computeOutcomeSignal(maybeKnowledge.retrieval_outcomes)}}),evictable=candidates.every((c)=>c.status==="promoted")?candidates:candidates.filter((c)=>c.status!=="promoted"),targetDropCount=entries.length-maxEntries,dropCount=Math.min(targetDropCount,evictable.length);if(dropCount<=0)return entries;let drop=new Set([...evictable].sort((a,b)=>{let inactiveDelta=getKnowledgeCapStatusPriority(a.status)-getKnowledgeCapStatusPriority(b.status);if(inactiveDelta!==0)return inactiveDelta;let signalDelta=a.outcomeSignal-b.outcomeSignal;if(signalDelta!==0)return signalDelta;return a.index-b.index}).slice(0,dropCount).map((c)=>c.index));return candidates.filter((c)=>!drop.has(c.index)).map((c)=>c.entry)}function getKnowledgeCapStatusPriority(status){if(!isActiveStatus(status))return 0;return 1}async function sweepAgedEntries(filePath,defaultMaxPhases){let result={scanned:0,aged:0,archived:0,removed:0,skipped_promoted:0};return await transactKnowledge(filePath,(entries)=>{if(result.scanned=entries.length,entries.length===0)return null;let now=new Date().toISOString(),mutated=!1;for(let entry of entries){if(entry.status==="archived")continue;if(entry.status==="promoted"){result.skipped_promoted++;continue}entry.phases_alive=(entry.phases_alive??0)+1,result.aged++,mutated=!0;let ttl=entry.max_phases??defaultMaxPhases;if(entry.phases_alive>ttl)entry.archived_from=entry.status,entry.archived_at=now,entry.status="archived",entry.updated_at=now,result.archived++}return mutated?entries:null}),result}async function sweepStaleTodos(filePath,todoMaxPhases){let result={scanned:0,aged:0,archived:0,removed:0,skipped_promoted:0};return await transactKnowledge(filePath,(entries)=>{if(result.scanned=entries.length,entries.length===0)return null;let kept=entries.filter((e)=>{if(e.category!=="todo"||e.status==="promoted")return!0;if((e.phases_alive??0)>todoMaxPhases)return result.removed++,!1;return!0});return result.removed>0?kept:null}),result}async function appendRejectedLesson(directory,lesson,maxEntries=20){let filePath=resolveSwarmRejectedPath(directory);await transactKnowledge(filePath,(existing)=>{let updated=[...existing,lesson];if(updated.length>maxEntries)return updated.slice(updated.length-maxEntries);return updated})}function normalize5(text){return(typeof text==="string"?text:String(text??"")).toLowerCase().replace(/[^\w\s]/g," ").replace(/\s+/g," ").trim()}function wordBigrams(text){let words=normalize5(text).split(" ").filter(Boolean),bigrams=new Set;for(let i=0;i<words.length-1;i++)bigrams.add(`${words[i]} ${words[i+1]}`);return bigrams}function jaccardBigram(a,b){if(a.size===0&&b.size===0)return 1;let aArr=Array.from(a),intersection3=new Set(aArr.filter((x)=>b.has(x))),union3=new Set([...aArr,...Array.from(b)]);return intersection3.size/union3.size}function findNearDuplicate(candidate,entries,threshold=0.6){let candidateBigrams=wordBigrams(candidate);return entries.find((entry)=>{let entryBigrams=wordBigrams(entry.lesson);return jaccardBigram(candidateBigrams,entryBigrams)>=threshold})}function computeConfidence(confirmedByCount,autoGenerated){let score=0.5;if(score+=Math.min(confirmedByCount,3)*0.1,!autoGenerated)score+=0.1;return Math.min(score,1)}async function confirmEntriesPhase(directory,ids,phaseNumber,projectName){if(ids.length===0)return;let knowledgePath=resolveSwarmKnowledgePath(directory);await transactKnowledge(knowledgePath,(current)=>{let idSet=new Set(ids),changed=!1,now=new Date().toISOString();for(let entry of current){if(!idSet.has(entry.id))continue;if(reinforceSwarmKnowledgeEntry(entry,{phase_number:phaseNumber,confirmed_at:now,project_name:projectName}).reinforced){let records=entry.confirmed_by??[];if(records.length>MAX_CONFIRMED_BY)entry.confirmed_by=[...records].sort((a,b)=>a.confirmed_at.localeCompare(b.confirmed_at)).slice(-MAX_CONFIRMED_BY),entry.confidence=computeConfidence(new Set(entry.confirmed_by.map((r)=>r.phase_number).filter((n)=>Number.isInteger(n))).size,entry.auto_generated??!1);changed=!0}}return changed?current:null}).catch(()=>{})}function computeOutcomeSignal(outcomes){if(!outcomes)return 0;let positives=(outcomes.applied_explicit_count??0)+(outcomes.succeeded_after_shown_count??0),negatives=(outcomes.ignored_count??0)+(outcomes.violated_count??0)+(outcomes.contradicted_count??0)+(outcomes.failed_after_shown_count??0),total=positives+negatives;if(total===0)return 0;return(positives-negatives)/(total+OUTCOME_SIGNAL_SMOOTHING)}function inferTags2(lesson){let lower=lesson.toLowerCase(),tags=[];if(/(^|\s)(?:todo|remember|don't?(?:\s+)?forget)(?:\s|:|,|$)/i.test(lesson))tags.push("todo");if(/\b(?:typescript|ts)\b/.test(lower))tags.push("typescript");if(/\b(?:javascript|js)\b/.test(lower))tags.push("javascript");if(/\b(?:python)\b/.test(lower))tags.push("python");if(/\b(?:bun|node|deno)\b/.test(lower))tags.push("runtime");if(/\b(?:react|vue|svelte|angular)\b/.test(lower))tags.push("frontend");if(/\b(?:git|github|gitlab)\b/.test(lower))tags.push("git");if(/\b(?:docker|kubernetes|k8s)\b/.test(lower))tags.push("container");if(/\b(?:sql|postgres|mysql|sqlite)\b/.test(lower))tags.push("database");if(/\b(?:test|spec|vitest|jest|mocha)\b/.test(lower))tags.push("testing");if(/\b(?:ci|cd|pipeline|workflow|action)\b/.test(lower))tags.push("ci-cd");if(/\b(?:security|auth|token|password|encrypt)\b/.test(lower))tags.push("security");if(/\b(?:performance|latency|throughput|cache)\b/.test(lower))tags.push("performance");if(/\b(?:api|rest|graphql|grpc|endpoint)\b/.test(lower))tags.push("api");if(/\b(?:swarm|architect|agent|hook|plan)\b/.test(lower))tags.push("opencode-swarm");return Array.from(new Set(tags))}async function bumpKnowledgeConfidenceBatch(directory,deltas,options){if(deltas.length===0)return;let swarmPath=resolveSwarmKnowledgePath(directory),hivePath=resolveHiveKnowledgePath(),touchedSwarm=[],touchedHive=[];try{touchedSwarm.push(...await applyConfidenceDeltas(swarmPath,deltas));let swarmIds=new Set(touchedSwarm.map((e)=>e.id)),hiveOnly=deltas.filter((d)=>!swarmIds.has(d.id));if(hiveOnly.length>0)touchedHive.push(...await applyConfidenceDeltas(hivePath,hiveOnly));await applyConfidenceFloorAction(directory,[...touchedSwarm,...touchedHive],options).catch((err)=>{console.warn("[knowledge-store] confidence-floor action sweep failed (best-effort):",err instanceof Error?err.message:String(err))})}catch(err){console.warn("[knowledge-store] bumpKnowledgeConfidenceBatch failed (fail-open):",err instanceof Error?err.message:String(err))}}async function applyConfidenceFloorAction(directory,touched,options){let action=options?.floorAction??"demote";if(action==="none"||touched.length===0)return;let minOutcomes=options?.floorMinOutcomes??3,signalThreshold=options?.floorSignalThreshold??0,FLOOR_EPSILON=0.000000001,atFloor=touched.filter((e)=>e.confidence<=CONFIDENCE_FLOOR+FLOOR_EPSILON),recovered=touched.filter((e)=>e.confidence>CONFIDENCE_FLOOR+FLOOR_EPSILON&&e.confidence_floor_demoted);if(atFloor.length===0&&recovered.length===0)return;let{readKnowledgeCounterRollups,effectiveRetrievalOutcomes}=await Promise.resolve().then(() => (init_knowledge_events(),exports_knowledge_events)),rollups=await readKnowledgeCounterRollups(directory),flagIds=new Set;for(let e of atFloor){let outcomes=effectiveRetrievalOutcomes(e.retrieval_outcomes,rollups?.get(e.id)),signal=computeOutcomeSignal(outcomes),totalEvidence=(outcomes.applied_explicit_count??0)+(outcomes.succeeded_after_shown_count??0)+(outcomes.ignored_count??0)+(outcomes.violated_count??0)+(outcomes.contradicted_count??0)+(outcomes.failed_after_shown_count??0);if(signal<signalThreshold&&totalEvidence>=minOutcomes)flagIds.add(e.id)}for(let e of recovered)flagIds.add(e.id);if(flagIds.size===0)return;let swarmPath=resolveSwarmKnowledgePath(directory),hivePath=resolveHiveKnowledgePath(),toQuarantine=[];await transactKnowledge(swarmPath,(swarmEntries)=>{let now=new Date().toISOString();for(let entry of swarmEntries){if(!flagIds.has(entry.id))continue;if(atFloor.find((e)=>e.id===entry.id)){if(entry.confidence_floor_demoted=!0,action==="quarantine")toQuarantine.push({id:entry.id,tier:"swarm"})}else entry.confidence_floor_demoted=!1;entry.updated_at=now}return swarmEntries}).catch((err)=>{console.warn("[knowledge-store] confidence-floor swarm flag transaction failed (best-effort):",err instanceof Error?err.message:String(err))});let hiveFlagIds=new Set;for(let e of atFloor)if(e.tier==="hive"&&flagIds.has(e.id))hiveFlagIds.add(e.id);for(let e of recovered)if(e.tier==="hive"&&flagIds.has(e.id))hiveFlagIds.add(e.id);if(hiveFlagIds.size>0)await transactKnowledge(hivePath,(hiveEntries)=>{let now=new Date().toISOString();for(let entry of hiveEntries){if(!hiveFlagIds.has(entry.id))continue;if(atFloor.find((e)=>e.id===entry.id))entry.confidence_floor_demoted=!0;else entry.confidence_floor_demoted=!1;entry.updated_at=now}return hiveEntries}).catch((err)=>{console.warn("[knowledge-store] confidence-floor hive flag transaction failed (best-effort):",err instanceof Error?err.message:String(err))});if(action==="quarantine"&&toQuarantine.length>0){let{quarantineEntry:quarantineEntry2}=await Promise.resolve().then(() => (init_knowledge_validator(),exports_knowledge_validator));for(let{id}of toQuarantine)await quarantineEntry2(directory,id,"confidence_floor_negative_outcome","auto").catch((err)=>{console.warn("[knowledge-store] confidence-floor quarantine failed (best-effort):",err instanceof Error?err.message:String(err))})}}async function applyConfidenceDeltas(filePath,deltas){let idDeltaMap=new Map;for(let d of deltas){let existing=idDeltaMap.get(d.id);idDeltaMap.set(d.id,existing!==void 0?existing+d.delta:d.delta)}let touched=[],release=null;try{let dir=path54.dirname(filePath);await mkdir9(dir,{recursive:!0}),release=await import_proper_lockfile4.default.lock(dir,{retries:{retries:5,minTimeout:100,maxTimeout:500},stale:5000});let entries=await readKnowledge(filePath);if(entries.length===0)return[];let now=new Date().toISOString(),mutated=!1;for(let entry of entries){let delta=idDeltaMap.get(entry.id);if(delta===void 0)continue;entry.confidence=Math.max(CONFIDENCE_FLOOR,Math.min(CONFIDENCE_CEILING,entry.confidence+delta)),entry.updated_at=now,mutated=!0,touched.push(entry)}if(mutated){let content=entries.map((e)=>JSON.stringify(e)).join(`
1102
1102
  `)+(entries.length>0?`
1103
- `:"");await atomicWriteFile(filePath,content)}}catch(err){console.warn(`[knowledge-store] applyConfidenceDeltas failed on ${filePath} (fail-open):`,err instanceof Error?err.message:String(err))}finally{if(release)try{await release()}catch{}}return touched}var import_proper_lockfile4,KNOWLEDGE_JSONL_CACHE_NAMESPACE="knowledge-jsonl:normalized:v1",OUTCOME_SIGNAL_SMOOTHING=4,CONFIDENCE_FLOOR=0.1,CONFIDENCE_CEILING=1,_internals30;var init_knowledge_store=__esm(()=>{init_task_file();init_swarm_artifact_cache();init_knowledge_link();init_knowledge_types();import_proper_lockfile4=__toESM(require_proper_lockfile(),1);_internals30={getPlatformConfigDir,resolveSwarmKnowledgePath,resolveSwarmRejectedPath,resolveHiveKnowledgePath,resolveHiveRejectedPath,resolveHiveEventsPath,readKnowledge,parseKnowledgeContent,readRejectedLessons,appendKnowledge,rewriteKnowledge,transactKnowledge,enforceKnowledgeCap,sweepAgedEntries,sweepStaleTodos,appendRejectedLesson,normalize:normalize5,wordBigrams,jaccardBigram,findNearDuplicate,computeConfidence,computeOutcomeSignal,selectKnowledgeCapSurvivors,inferTags:inferTags2,bumpKnowledgeConfidenceBatch,getArchivedKnowledgeIds}});var exports_knowledge_events={};__export(exports_knowledge_events,{resolveLegacyApplicationLogPath:()=>resolveLegacyApplicationLogPath,resolveKnowledgeEventsPath:()=>resolveKnowledgeEventsPath,resolveKnowledgeCounterBaselinePath:()=>resolveKnowledgeCounterBaselinePath,resolveHiveEventsPath:()=>resolveHiveEventsPath2,recordKnowledgeEvent:()=>recordKnowledgeEvent,recordHiveKnowledgeEvent:()=>recordHiveKnowledgeEvent,recomputeCounters:()=>recomputeCounters,readLegacyApplicationRecords:()=>readLegacyApplicationRecords,readKnowledgeEvents:()=>readKnowledgeEvents,readKnowledgeCounterRollups:()=>readKnowledgeCounterRollups,readHiveKnowledgeEvents:()=>readHiveKnowledgeEvents,newTraceId:()=>newTraceId,newEventId:()=>newEventId,effectiveRetrievalOutcomes:()=>effectiveRetrievalOutcomes,countViolationsInWindow:()=>countViolationsInWindow,countEntryViolationsInWindow:()=>countEntryViolationsInWindow,countEntryContradictionsInWindow:()=>countEntryContradictionsInWindow,applyKnowledgeVerdictFeedback:()=>applyKnowledgeVerdictFeedback,appendKnowledgeEvent:()=>appendKnowledgeEvent,appendHiveKnowledgeEvent:()=>appendHiveKnowledgeEvent,_internals:()=>_internals31,RECEIPT_EVENT_TYPES:()=>RECEIPT_EVENT_TYPES,MAX_VIOLATION_TIMESTAMPS:()=>MAX_VIOLATION_TIMESTAMPS,MAX_EVENT_LOG_ENTRIES:()=>MAX_EVENT_LOG_ENTRIES,KNOWLEDGE_EVENT_SCHEMA_VERSION:()=>KNOWLEDGE_EVENT_SCHEMA_VERSION});import{randomUUID as randomUUID5}from"node:crypto";import{existsSync as existsSync26}from"node:fs";import{appendFile as appendFile7,mkdir as mkdir10,readFile as readFile10,stat as stat7}from"node:fs/promises";import*as os16 from"node:os";import*as path55 from"node:path";function resolveKnowledgeEventsPath(directory){return path55.join(resolveKnowledgeStoreDir(directory),"knowledge-events.jsonl")}function resolveKnowledgeCounterBaselinePath(directory){return path55.join(resolveKnowledgeStoreDir(directory),"knowledge-counter-baseline.json")}function resolveHiveEventsPath2(){let platform=process.platform,home=process.env.HOME||os16.homedir(),dir;if(platform==="win32")dir=path55.join(process.env.LOCALAPPDATA||path55.join(home,"AppData","Local"),"opencode-swarm","Data");else if(platform==="darwin")dir=path55.join(home,"Library","Application Support","opencode-swarm");else dir=path55.join(process.env.XDG_DATA_HOME||path55.join(home,".local","share"),"opencode-swarm");return path55.join(dir,"shared-knowledge-events.jsonl")}function resolveLegacyApplicationLogPath(directory){return path55.join(resolveKnowledgeStoreDir(directory),"knowledge-application.jsonl")}function newTraceId(){return randomUUID5()}function newEventId(){return randomUUID5()}function withDefaults(event){return{schema_version:KNOWLEDGE_EVENT_SCHEMA_VERSION,...event,event_id:event.event_id||newEventId(),timestamp:event.timestamp||new Date().toISOString()}}async function appendKnowledgeEvent(directory,event){let populated=withDefaults(event),filePath=resolveKnowledgeEventsPath(directory),dirPath=path55.dirname(filePath);await mkdir10(dirPath,{recursive:!0});let release;try{release=await import_proper_lockfile5.default.lock(dirPath,{retries:{retries:200,minTimeout:10,maxTimeout:100}}),await appendFile7(filePath,`${JSON.stringify(populated)}
1103
+ `:"");await atomicWriteFile(filePath,content)}}catch(err){console.warn(`[knowledge-store] applyConfidenceDeltas failed on ${filePath} (fail-open):`,err instanceof Error?err.message:String(err))}finally{if(release)try{await release()}catch{}}return touched}var import_proper_lockfile4,KNOWLEDGE_JSONL_CACHE_NAMESPACE="knowledge-jsonl:normalized:v1",MAX_CONFIRMED_BY=50,OUTCOME_SIGNAL_SMOOTHING=4,CONFIDENCE_FLOOR=0.1,CONFIDENCE_CEILING=1,_internals30;var init_knowledge_store=__esm(()=>{init_task_file();init_swarm_artifact_cache();init_knowledge_link();init_knowledge_reinforcement();init_knowledge_types();import_proper_lockfile4=__toESM(require_proper_lockfile(),1);_internals30={getPlatformConfigDir,resolveSwarmKnowledgePath,resolveSwarmRejectedPath,resolveHiveKnowledgePath,resolveHiveRejectedPath,resolveHiveEventsPath,readKnowledge,parseKnowledgeContent,readRejectedLessons,appendKnowledge,rewriteKnowledge,transactKnowledge,enforceKnowledgeCap,sweepAgedEntries,sweepStaleTodos,appendRejectedLesson,normalize:normalize5,wordBigrams,jaccardBigram,findNearDuplicate,computeConfidence,computeOutcomeSignal,selectKnowledgeCapSurvivors,inferTags:inferTags2,bumpKnowledgeConfidenceBatch,getArchivedKnowledgeIds}});var exports_knowledge_events={};__export(exports_knowledge_events,{resolveLegacyApplicationLogPath:()=>resolveLegacyApplicationLogPath,resolveKnowledgeEventsPath:()=>resolveKnowledgeEventsPath,resolveKnowledgeCounterBaselinePath:()=>resolveKnowledgeCounterBaselinePath,resolveHiveEventsPath:()=>resolveHiveEventsPath2,recordKnowledgeEvent:()=>recordKnowledgeEvent,recordHiveKnowledgeEvent:()=>recordHiveKnowledgeEvent,recomputeCounters:()=>recomputeCounters,readLegacyApplicationRecords:()=>readLegacyApplicationRecords,readKnowledgeEvents:()=>readKnowledgeEvents,readKnowledgeCounterRollups:()=>readKnowledgeCounterRollups,readHiveKnowledgeEvents:()=>readHiveKnowledgeEvents,newTraceId:()=>newTraceId,newEventId:()=>newEventId,effectiveRetrievalOutcomes:()=>effectiveRetrievalOutcomes,countViolationsInWindow:()=>countViolationsInWindow,countEntryViolationsInWindow:()=>countEntryViolationsInWindow,countEntryContradictionsInWindow:()=>countEntryContradictionsInWindow,applyKnowledgeVerdictFeedback:()=>applyKnowledgeVerdictFeedback,appendKnowledgeEvent:()=>appendKnowledgeEvent,appendHiveKnowledgeEvent:()=>appendHiveKnowledgeEvent,_internals:()=>_internals31,RECEIPT_EVENT_TYPES:()=>RECEIPT_EVENT_TYPES,MAX_VIOLATION_TIMESTAMPS:()=>MAX_VIOLATION_TIMESTAMPS,MAX_EVENT_LOG_ENTRIES:()=>MAX_EVENT_LOG_ENTRIES,KNOWLEDGE_EVENT_SCHEMA_VERSION:()=>KNOWLEDGE_EVENT_SCHEMA_VERSION});import{randomUUID as randomUUID5}from"node:crypto";import{existsSync as existsSync26}from"node:fs";import{appendFile as appendFile7,mkdir as mkdir10,readFile as readFile10,stat as stat7}from"node:fs/promises";import*as os16 from"node:os";import*as path55 from"node:path";function resolveKnowledgeEventsPath(directory){return path55.join(resolveKnowledgeStoreDir(directory),"knowledge-events.jsonl")}function resolveKnowledgeCounterBaselinePath(directory){return path55.join(resolveKnowledgeStoreDir(directory),"knowledge-counter-baseline.json")}function resolveHiveEventsPath2(){let platform=process.platform,home=process.env.HOME||os16.homedir(),dir;if(platform==="win32")dir=path55.join(process.env.LOCALAPPDATA||path55.join(home,"AppData","Local"),"opencode-swarm","Data");else if(platform==="darwin")dir=path55.join(home,"Library","Application Support","opencode-swarm");else dir=path55.join(process.env.XDG_DATA_HOME||path55.join(home,".local","share"),"opencode-swarm");return path55.join(dir,"shared-knowledge-events.jsonl")}function resolveLegacyApplicationLogPath(directory){return path55.join(resolveKnowledgeStoreDir(directory),"knowledge-application.jsonl")}function newTraceId(){return randomUUID5()}function newEventId(){return randomUUID5()}function withDefaults(event){return{schema_version:KNOWLEDGE_EVENT_SCHEMA_VERSION,...event,event_id:event.event_id||newEventId(),timestamp:event.timestamp||new Date().toISOString()}}async function appendKnowledgeEvent(directory,event){let populated=withDefaults(event),filePath=resolveKnowledgeEventsPath(directory),dirPath=path55.dirname(filePath);await mkdir10(dirPath,{recursive:!0});let release;try{release=await import_proper_lockfile5.default.lock(dirPath,{retries:{retries:200,minTimeout:10,maxTimeout:100}}),await appendFile7(filePath,`${JSON.stringify(populated)}
1104
1104
  `,"utf-8");try{let lines=(await readFile10(filePath,"utf-8")).split(`
1105
1105
  `).filter((line)=>line.trim().length>0);if(lines.length>MAX_EVENT_LOG_ENTRIES){let evicted=lines.slice(0,lines.length-MAX_EVENT_LOG_ENTRIES),trimmed=lines.slice(lines.length-MAX_EVENT_LOG_ENTRIES);await foldEvictedEventsIntoBaseline(directory,evicted,filePath),await atomicWriteFile(filePath,`${trimmed.join(`
1106
1106
  `)}
@@ -1214,7 +1214,7 @@ ${llmOutput}
1214
1214
 
1215
1215
  ${verificationSummary}
1216
1216
 
1217
- ${actionSummary}`}catch(err){let msg=err instanceof Error?err.message:String(err);warnings.push(`LLM delegate failed, falling back to data-only report: ${msg}`),reportContent=_internals37.buildDataOnlyReport(effectivePlanId,planSummary,knowledgeSummary,curatorDigest,proposals,unactionable,retrospectives,driftReports,{scope,sessionID:options.sessionID,planLoaded})}else reportContent=_internals37.buildDataOnlyReport(effectivePlanId,planSummary,knowledgeSummary,curatorDigest,proposals,unactionable,retrospectives,driftReports,{scope,sessionID:options.sessionID,planLoaded});try{let{mkdirSync:mkdirSync22}=await import("node:fs");mkdirSync22(path65.dirname(reportPath),{recursive:!0}),await atomicWriteFile(reportPath,reportContent)}catch(err){let msg=err instanceof Error?err.message:String(err);return{success:!1,planId:effectivePlanId,reportPath:null,summary:null,warnings:[...warnings,`Failed to write report: ${msg}`]}}let totalEntries=knowledgeSummary.length,neverAppliedCount=knowledgeSummary.filter((e)=>e.applied===0&&e.violated===0&&e.ignored===0).length,totalViolations=knowledgeSummary.reduce((s,e)=>s+e.violated,0),mechanicalSummary=[`Post-mortem for plan "${effectivePlanId}": ${totalEntries} knowledge entries reviewed.`,`${neverAppliedCount} never-applied entries flagged; ${totalViolations} total violations recorded.`,`${proposals.length} pending proposals, ${unactionable.length} quarantined entries.`].join(" ");return{success:!0,planId:effectivePlanId,reportPath,summary:llmSummary??mechanicalSummary,warnings,actions:actionResult}}finally{if(lock.release)try{await lock.release()}catch{}}}var MAX_INPUT_TEXT_CHARS=500,MAX_KNOWLEDGE_ENTRIES=500,MAX_PROPOSALS=50,MAX_RETROSPECTIVES=50,MAX_DRIFT_REPORTS=50,MAX_UNACTIONABLE=1000,_internals37;var init_curator_postmortem=__esm(()=>{init_task_file();init_file_locks();init_manager();init_utils3();init_curator();init_knowledge_events();init_knowledge_link();init_knowledge_store();init_knowledge_types();init_utils2();_internals37={acquirePostMortemLock,collectKnowledgeSummary,collectRetrospectives,collectDriftReports,collectPendingProposals,readJsonlFile,buildDataOnlyReport,assembleLLMInput,buildStateFreshnessSection,buildActionVerificationSection,isReportValid,parsePostMortemActions,executePostMortemActions,verifyPostMortemKnowledgeActions,repairPostMortemActions,loadDefaultKnowledgeConfig:async()=>{let{KnowledgeConfigSchema:KnowledgeConfigSchema2}=await Promise.resolve().then(() => (init_schema(),exports_schema));return KnowledgeConfigSchema2.parse({})},applyCuratorKnowledgeUpdates:async(directory,recommendations,knowledgeConfig)=>{let{applyCuratorKnowledgeUpdates:applyCuratorKnowledgeUpdates2}=await Promise.resolve().then(() => (init_curator(),exports_curator));return applyCuratorKnowledgeUpdates2(directory,recommendations,knowledgeConfig)},checkHivePromotions:async(entries,knowledgeConfig)=>{let{checkHivePromotions:checkHivePromotions2}=await Promise.resolve().then(() => (init_hive_promoter(),exports_hive_promoter));return checkHivePromotions2(entries,knowledgeConfig)},applyProposalTriage:async(directory,triage)=>{let{_internals:skillInternals,activateProposal:activateProposal2,listSkills:listSkills2,sanitizeSlug:sanitizeSlug2}=await Promise.resolve().then(() => (init_skill_generator(),exports_skill_generator)),result={approved:[],rejected:[],skipped:[]},skills=await listSkills2(directory),proposalSlugs=new Set(skills.proposals.map((p)=>p.slug));for(let item of triage){let slug=sanitizeSlug2(normalizeProposalSlug(item.proposal_id));if(!slug||!proposalSlugs.has(slug)){result.skipped.push(slug||item.proposal_id);continue}if(item.action==="apply"){if((await activateProposal2(directory,slug,!1,{evaluate:!0,operation:"post_mortem_queue_triage",confirmUnevaluated:!0})).activated)result.approved.push(slug);else result.skipped.push(slug);continue}let proposal=skills.proposals.find((p)=>p.slug===slug);if(!proposal){result.skipped.push(slug);continue}try{skillInternals.unlinkSync(proposal.path),result.rejected.push(slug)}catch{result.skipped.push(slug)}}return result},readPriorDriftReports:async(directory)=>{let{readPriorDriftReports:readPriorDriftReports2}=await Promise.resolve().then(() => (init_curator_drift(),exports_curator_drift));return readPriorDriftReports2(directory)},readSwarmKnowledge:(directory)=>readKnowledge(resolveSwarmKnowledgePath(directory))}});import{mkdir as mkdir15,readFile as readFile16,rename as rename9,stat as stat9,unlink as unlink4,writeFile as writeFile12}from"node:fs/promises";import*as path66 from"node:path";function emptySynonymMap(){return{version:1,cursor:0,pairs:{}}}function resolveSynonymMapPath(directory){return validateSwarmPath(directory,SYNONYM_MAP_FILENAME)}function sanitizeToken(raw){if(typeof raw!=="string")return null;let token=raw.replace(/[\x00-\x1f\x7f-\x9f]/g," ").toLowerCase().replace(/\s+/g," ").trim();if(token.length===0)return null;if(token.length>MAX_TOKEN_LENGTH)return null;return token}function pairKey(a,b){return a<b?`${a}${PAIR_SEP}${b}`:`${b}${PAIR_SEP}${a}`}function tokensForEntry(entry){let out=new Set,fields=[entry.triggers,entry.tags,entry.applies_to_tools,entry.applies_to_agents];for(let field of fields){if(!Array.isArray(field))continue;for(let raw of field){let token=sanitizeToken(raw);if(token)out.add(token)}}return Array.from(out)}function evictToCap(map3,maxPairs){let keys=Object.keys(map3.pairs);if(keys.length<=maxPairs)return;keys.sort((k1,k2)=>{let s1=map3.pairs[k1].seq,s2=map3.pairs[k2].seq;if(s1!==s2)return s1-s2;return k1<k2?-1:1});let removeCount=keys.length-maxPairs;for(let i=0;i<removeCount;i++)delete map3.pairs[keys[i]]}function recordEntryCooccurrences(map3,entry,maxPairs=DEFAULT_MAX_PAIRS){let tokens=tokensForEntry(entry);if(tokens.length<2)return map3;for(let i=0;i<tokens.length;i++)for(let j=i+1;j<tokens.length;j++){let a=tokens[i],b=tokens[j];if(a===b)continue;let key=pairKey(a,b),seq=++map3.cursor,existing=map3.pairs[key];if(existing)existing.count+=1,existing.seq=seq;else{let[lo,hi]=a<b?[a,b]:[b,a];map3.pairs[key]={a:lo,b:hi,count:1,seq}}}return evictToCap(map3,maxPairs),map3}function buildSynonymMap(entries,maxPairs=DEFAULT_MAX_PAIRS){let map3=emptySynonymMap();for(let entry of entries)recordEntryCooccurrences(map3,entry,maxPairs);return map3}function buildSynonymIndex(map3,minCooccurrence=DEFAULT_MIN_COOCCURRENCE){let index=new Map,threshold=Math.max(1,minCooccurrence);for(let pair of Object.values(map3.pairs)){if(pair.count<threshold)continue;add(index,pair.a,pair.b),add(index,pair.b,pair.a)}return index}function add(index,from,to){let set3=index.get(from);if(!set3)set3=new Set,index.set(from,set3);set3.add(to)}function expandTokens(index,queryTokens,maxPerToken=DEFAULT_MAX_EXPANSIONS_PER_TOKEN){let originals=new Set;for(let raw of queryTokens){let token=sanitizeToken(raw);if(token)originals.add(token)}let expanded=new Set;for(let token of originals){let synonyms=index.get(token);if(!synonyms)continue;let sorted=Array.from(synonyms).sort(),added=0;for(let syn of sorted){if(added>=maxPerToken)break;if(originals.has(syn))continue;if(expanded.has(syn))continue;expanded.add(syn),added+=1}}return Array.from(expanded)}function isSynonymPair(value){if(typeof value!=="object"||value===null)return!1;let p=value;return typeof p.a==="string"&&typeof p.b==="string"&&typeof p.count==="number"&&Number.isFinite(p.count)&&typeof p.seq==="number"&&Number.isFinite(p.seq)}function coerceSynonymMap(parsed,maxPairs=DEFAULT_MAX_PAIRS){if(typeof parsed!=="object"||parsed===null)return emptySynonymMap();let obj=parsed;if(obj.version!==1||typeof obj.pairs!=="object"||obj.pairs===null)return emptySynonymMap();let out=emptySynonymMap(),cursor=typeof obj.cursor==="number"&&Number.isFinite(obj.cursor)?obj.cursor:0;for(let value of Object.values(obj.pairs)){if(!isSynonymPair(value))continue;let a=sanitizeToken(value.a),b=sanitizeToken(value.b);if(!a||!b||a===b)continue;let count=Math.max(0,Math.floor(value.count));if(count<=0)continue;let key=pairKey(a,b),seq=Number.isFinite(value.seq)?value.seq:++cursor;if(seq>cursor)cursor=seq;let existing=out.pairs[key];if(existing)existing.count=Math.max(existing.count,count),existing.seq=Math.max(existing.seq,seq);else{let[lo,hi]=a<b?[a,b]:[b,a];out.pairs[key]={a:lo,b:hi,count,seq}}}return out.cursor=cursor,evictToCap(out,Math.max(1,Math.floor(maxPairs))),out}async function readSynonymMap(directory,maxPairs=DEFAULT_MAX_PAIRS){let filePath;try{filePath=resolveSynonymMapPath(directory)}catch{return emptySynonymMap()}try{let ceiling=Math.max(MIN_READ_CEILING_BYTES,Math.floor(maxPairs)*APPROX_BYTES_PER_PAIR);if((await stat9(filePath)).size>ceiling)return emptySynonymMap();let raw=await readFile16(filePath,"utf-8");return coerceSynonymMap(JSON.parse(raw),maxPairs)}catch{return emptySynonymMap()}}async function writeSynonymMapAtomic(filePath,map3){await mkdir15(path66.dirname(filePath),{recursive:!0});let tmp=`${filePath}.tmp.${Date.now()}.${Math.floor(Math.random()*1e9)}`;try{await writeFile12(tmp,JSON.stringify(map3,null,2),"utf-8"),await rename9(tmp,filePath)}finally{try{await unlink4(tmp)}catch{}}}async function rebuildSynonymMap(directory,entries,maxPairs=DEFAULT_MAX_PAIRS){let filePath=resolveSynonymMapPath(directory),dir=path66.dirname(filePath);await mkdir15(dir,{recursive:!0});let release=null;try{release=await import_proper_lockfile7.default.lock(dir,{retries:{retries:5,minTimeout:100,maxTimeout:500},stale:5000});let map3=buildSynonymMap(entries,maxPairs);return await writeSynonymMapAtomic(filePath,map3),map3}finally{if(release)try{await release()}catch{}}}var import_proper_lockfile7,SYNONYM_MAP_FILENAME="synonym-map.json",MAX_TOKEN_LENGTH=64,DEFAULT_MAX_PAIRS=500,DEFAULT_MIN_COOCCURRENCE=3,DEFAULT_MAX_EXPANSIONS_PER_TOKEN=4,PAIR_SEP,APPROX_BYTES_PER_PAIR=512,MIN_READ_CEILING_BYTES=65536;var init_synonym_map=__esm(()=>{init_utils2();import_proper_lockfile7=__toESM(require_proper_lockfile(),1);PAIR_SEP=String.fromCharCode(0)});function isActiveSwarmKnowledgeEntry(entry){return isActiveStatus(entry.status)}function findActiveSwarmNearDuplicate(lesson,entries,threshold){return findNearDuplicate(lesson,entries.filter(isActiveSwarmKnowledgeEntry),threshold)}function distinctPhaseCount(records){let phases=new Set;for(let record3 of records??[])if(Number.isInteger(record3.phase_number))phases.add(record3.phase_number);return phases.size}function reinforceSwarmKnowledgeEntry(entry,confirmation){if(!isActiveSwarmKnowledgeEntry(entry))return{entryId:entry.id,reinforced:!1,reason:"inactive"};if((entry.confirmed_by??[]).some((record3)=>record3.phase_number===confirmation.phase_number))return{entryId:entry.id,reinforced:!1,reason:"already_confirmed_phase"};return entry.confirmed_by=[...entry.confirmed_by??[],confirmation],entry.updated_at=confirmation.confirmed_at,entry.phases_alive=0,entry.confidence=computeConfidence(distinctPhaseCount(entry.confirmed_by),entry.auto_generated??!1),{entryId:entry.id,reinforced:!0,reason:"reinforced"}}var init_knowledge_reinforcement=__esm(()=>{init_knowledge_store();init_knowledge_types()});import*as fs31 from"node:fs";import*as path67 from"node:path";function extractSkillName(skillPath){let base=path67.basename(skillPath,path67.extname(skillPath));if(base!=="SKILL")return base;return path67.basename(path67.dirname(skillPath))}function stripQuotes(value){let trimmed=value.trim();if(trimmed.startsWith('"')&&trimmed.endsWith('"')||trimmed.startsWith("'")&&trimmed.endsWith("'"))return trimmed.slice(1,-1).trim();return trimmed}function normalizeDescription(description){let singleLine=description.replace(/\s+/g," ").trim();if(!singleLine)return"No description provided";return singleLine.length>240?`${singleLine.slice(0,237)}...`:singleLine}function normalizeTrigger(value){return stripQuotes(value).replace(/\s+/g," ").trim().slice(0,MAX_SKILL_TRIGGER_LENGTH)}function normalizeTriggerList(values){let out=[],seen=new Set;for(let raw of values){let value=normalizeTrigger(raw);if(!value)continue;let key=value.toLowerCase();if(seen.has(key))continue;if(seen.add(key),out.push(value),out.length>=MAX_SKILL_TRIGGERS)break}return out}function finiteRankValue(value){return Number.isFinite(value)?value:0}function parseInlineStringList(rawValue){let trimmed=rawValue.trim();if(!trimmed)return[];if(trimmed.startsWith("[")&&trimmed.endsWith("]")){let body=trimmed.slice(1,-1).trim();if(!body)return[];try{let parsed=JSON.parse(trimmed);if(Array.isArray(parsed))return parsed.filter((entry)=>typeof entry==="string")}catch{}return body.split(",").map((entry)=>stripQuotes(entry))}return[trimmed]}function collectYamlList(lines,start,end){let values=[],i=start;for(;i<end;i++){let line=lines[i]??"";if(/^[A-Za-z_][A-Za-z0-9_-]*\s*:/.test(line))break;let match=line.match(/^\s+-\s+(.+?)\s*$/);if(match)values.push(match[1])}return{values,nextIndex:i-1}}function parseSkillFrontmatter(content,skillPath){let normalizedPath=skillPath.replace(/^file:/,"").replace(/\\/g,"/"),fallbackName=extractSkillName(normalizedPath),fallback={path:normalizedPath,name:fallbackName,description:"No description provided"},lines=content.split(/\r?\n/);if(lines[0]?.trim()!=="---")return fallback;let end=lines.findIndex((line,index)=>index>0&&line.trim()==="---");if(end===-1)return fallback;let name=fallbackName,description="",skillType,triggers=[];for(let i=1;i<end;i++){let match=(lines[i]??"").match(/^([A-Za-z_][A-Za-z0-9_-]*)\s*:\s*(.*)$/);if(!match)continue;let key=match[1].toLowerCase(),rawValue=match[2].trim();if(key==="name"){let parsed=stripQuotes(rawValue);if(parsed)name=parsed;continue}if(key==="skill_type"){if(rawValue==="directive"||rawValue==="workflow")skillType=rawValue;continue}if(key==="triggers"){if(rawValue===""){let collected=collectYamlList(lines,i+1,end);triggers=normalizeTriggerList(collected.values),i=collected.nextIndex}else triggers=normalizeTriggerList(parseInlineStringList(rawValue));continue}if(key!=="description")continue;if(rawValue===">"||rawValue==="|"){let collected=[];for(let j=i+1;j<end;j++){let next=lines[j]??"";if(/^[A-Za-z_][A-Za-z0-9_-]*\s*:/.test(next))break;collected.push(next.trim()),i=j}description=collected.join(" ")}else description=stripQuotes(rawValue)}let meta3={path:normalizedPath,name:name||fallbackName,description:normalizeDescription(description)};if(skillType)meta3.skillType=skillType;if(triggers.length>0)meta3.triggers=triggers;return meta3}function readFilePrefix(filePath){let fd=fs31.openSync(filePath,"r");try{let buffer=Buffer.alloc(SKILL_FRONTMATTER_READ_BYTES),bytesRead=fs31.readSync(fd,buffer,0,SKILL_FRONTMATTER_READ_BYTES,0);return buffer.toString("utf-8",0,bytesRead)}finally{fs31.closeSync(fd)}}function readSkillMetadata(skillPath,directory){let normalizedPath=skillPath.replace(/^file:/,"").replace(/\\/g,"/"),fallback=parseSkillFrontmatter("",normalizedPath);try{if(path67.isAbsolute(normalizedPath)||normalizedPath.split("/").includes(".."))return fallback;let root=path67.resolve(directory),absolutePath=path67.resolve(directory,normalizedPath);if(absolutePath!==root&&!absolutePath.startsWith(root+path67.sep))return fallback;let content=readFilePrefix(absolutePath);return parseSkillFrontmatter(content,normalizedPath)}catch{return fallback}}function computeRecencyScore(lastUsedTimestamp){if(!lastUsedTimestamp)return 0;let lastUsed=new Date(lastUsedTimestamp).getTime();if(Number.isNaN(lastUsed))return 0;let ageMs=Date.now()-lastUsed;if(ageMs<=0)return 1;if(ageMs>=RECENCY_DECAY_MS)return 0;return 1-ageMs/RECENCY_DECAY_MS}function extractKeywords(text){let words=text.toLowerCase().split(/[^a-z0-9]+/).filter((w)=>w.length>=MIN_KEYWORD_LENGTH);return new Set(words)}function computeContextMatchScore(taskDescription,skillPath,metadata){let taskKeywords=extractKeywords(taskDescription);if(taskKeywords.size===0)return 0;let skillName=extractSkillName(skillPath),skillText=`${skillPath} ${skillName} ${metadata?.name??""} ${metadata?.description??""}`,skillKeywords=extractKeywords(skillText),matchCount=0;for(let kw of taskKeywords)if(skillKeywords.has(kw))matchCount++;return matchCount/taskKeywords.size}function normalizeTriggerMatchText(text){return text.toLowerCase().replace(/\s+/g," ").trim()}function computeTriggerMatchBoost(taskDescription,triggers){if(!triggers||triggers.length===0)return 0;let task=normalizeTriggerMatchText(taskDescription);if(!task)return 0;for(let raw of triggers){let trigger=normalizeTriggerMatchText(raw);if(trigger.length>=SKILL_TRIGGER_MIN_LENGTH&&task.includes(trigger))return SKILL_TRIGGER_BOOST}return 0}function computeSkillRelevanceScore(skillPath,taskDescription,usageHistory,metadata){let contextScore=computeContextMatchScore(taskDescription,skillPath,metadata)*CONTEXT_WEIGHT,triggerBoost=computeTriggerMatchBoost(taskDescription,metadata?.triggers);if(usageHistory.length===0)return Math.min(1,contextScore+triggerBoost);let usageCount=usageHistory.length,frequencyScore=Math.min(1,usageCount/FREQUENCY_CAP)*FREQUENCY_WEIGHT,entriesWithVerdict=usageHistory.filter((e)=>e.complianceVerdict!==void 0&&e.complianceVerdict!=="not_checked"),compliantCount=entriesWithVerdict.filter((e)=>e.complianceVerdict==="compliant").length,denominator=Math.max(1,entriesWithVerdict.length),complianceScore=compliantCount/denominator*COMPLIANCE_WEIGHT,lastUsedTimestamp=[...usageHistory].sort((a,b)=>b.timestamp>a.timestamp?1:b.timestamp<a.timestamp?-1:0)[0]?.timestamp??"",recencyScore=computeRecencyScore(lastUsedTimestamp)*RECENCY_WEIGHT,taskDiversityScore=new Set(usageHistory.map((e)=>e.taskID).filter(Boolean)).size/Math.max(1,usageHistory.length)*TASK_DIVERSITY_WEIGHT,workflowBoost=0;if(metadata?.skillType==="workflow"&&contextScore>=WORKFLOW_BOOST_MIN_CONTEXT)workflowBoost=WORKFLOW_BOOST;return Math.min(1,frequencyScore+complianceScore+recencyScore+taskDiversityScore+contextScore+triggerBoost+workflowBoost)}function rankSkillsForContext(skills,taskContext,directory){let allEntries=readSkillUsageEntries(directory),results=[];for(let skillPath of skills){let skillEntries=allEntries.filter((e)=>e.skillPath===skillPath),metadata=_internals38.readSkillMetadata(skillPath,directory),score=computeSkillRelevanceScore(skillPath,taskContext,skillEntries,metadata),entriesWithVerdict=skillEntries.filter((e)=>e.complianceVerdict!==void 0&&e.complianceVerdict!=="not_checked"),compliantCount=entriesWithVerdict.filter((e)=>e.complianceVerdict==="compliant").length,complianceRate=entriesWithVerdict.length>0?compliantCount/entriesWithVerdict.length:0;results.push({skillPath,score:finiteRankValue(score),usageCount:skillEntries.length,complianceRate})}return results.sort((a,b)=>{let scoreDelta=finiteRankValue(b.score)-finiteRankValue(a.score);if(scoreDelta!==0)return scoreDelta;let usageDelta=b.usageCount-a.usageCount;if(usageDelta!==0)return usageDelta;return a.skillPath.localeCompare(b.skillPath)}),results}function getSkillStats(skillPath,directory){let entries=readSkillUsageEntries(directory,{skillPath});if(entries.length===0)return{totalUsage:0,complianceRate:0,lastUsed:"",topAgents:[]};let entriesWithVerdict=entries.filter((e)=>e.complianceVerdict!==void 0&&e.complianceVerdict!=="not_checked"),compliantCount=entriesWithVerdict.filter((e)=>e.complianceVerdict==="compliant").length,complianceRate=entriesWithVerdict.length>0?compliantCount/entriesWithVerdict.length:0,lastUsed=[...entries].sort((a,b)=>b.timestamp>a.timestamp?1:b.timestamp<a.timestamp?-1:0)[0]?.timestamp??"",agentCounts=new Map;for(let entry of entries)agentCounts.set(entry.agentName,(agentCounts.get(entry.agentName)??0)+1);let topAgents=Array.from(agentCounts.entries()).sort((a,b)=>b[1]-a[1]).map(([agent,count])=>({agent,count}));return{totalUsage:entries.length,complianceRate,lastUsed,topAgents}}function formatSkillIndexWithContext(skills,directory){let usageLogPath=path67.join(directory,".swarm","skill-usage.jsonl"),hasHistory=!1;try{hasHistory=fs31.statSync(usageLogPath).size>0}catch{}if(!hasHistory)return skills.map((sp)=>{let meta3=_internals38.readSkillMetadata(sp,directory);return` - file:${meta3.path} - ${meta3.name}: ${meta3.description}`}).join(`
1217
+ ${actionSummary}`}catch(err){let msg=err instanceof Error?err.message:String(err);warnings.push(`LLM delegate failed, falling back to data-only report: ${msg}`),reportContent=_internals37.buildDataOnlyReport(effectivePlanId,planSummary,knowledgeSummary,curatorDigest,proposals,unactionable,retrospectives,driftReports,{scope,sessionID:options.sessionID,planLoaded})}else reportContent=_internals37.buildDataOnlyReport(effectivePlanId,planSummary,knowledgeSummary,curatorDigest,proposals,unactionable,retrospectives,driftReports,{scope,sessionID:options.sessionID,planLoaded});try{let{mkdirSync:mkdirSync22}=await import("node:fs");mkdirSync22(path65.dirname(reportPath),{recursive:!0}),await atomicWriteFile(reportPath,reportContent)}catch(err){let msg=err instanceof Error?err.message:String(err);return{success:!1,planId:effectivePlanId,reportPath:null,summary:null,warnings:[...warnings,`Failed to write report: ${msg}`]}}let totalEntries=knowledgeSummary.length,neverAppliedCount=knowledgeSummary.filter((e)=>e.applied===0&&e.violated===0&&e.ignored===0).length,totalViolations=knowledgeSummary.reduce((s,e)=>s+e.violated,0),mechanicalSummary=[`Post-mortem for plan "${effectivePlanId}": ${totalEntries} knowledge entries reviewed.`,`${neverAppliedCount} never-applied entries flagged; ${totalViolations} total violations recorded.`,`${proposals.length} pending proposals, ${unactionable.length} quarantined entries.`].join(" ");return{success:!0,planId:effectivePlanId,reportPath,summary:llmSummary??mechanicalSummary,warnings,actions:actionResult}}finally{if(lock.release)try{await lock.release()}catch{}}}var MAX_INPUT_TEXT_CHARS=500,MAX_KNOWLEDGE_ENTRIES=500,MAX_PROPOSALS=50,MAX_RETROSPECTIVES=50,MAX_DRIFT_REPORTS=50,MAX_UNACTIONABLE=1000,_internals37;var init_curator_postmortem=__esm(()=>{init_task_file();init_file_locks();init_manager();init_utils3();init_curator();init_knowledge_events();init_knowledge_link();init_knowledge_store();init_knowledge_types();init_utils2();_internals37={acquirePostMortemLock,collectKnowledgeSummary,collectRetrospectives,collectDriftReports,collectPendingProposals,readJsonlFile,buildDataOnlyReport,assembleLLMInput,buildStateFreshnessSection,buildActionVerificationSection,isReportValid,parsePostMortemActions,executePostMortemActions,verifyPostMortemKnowledgeActions,repairPostMortemActions,loadDefaultKnowledgeConfig:async()=>{let{KnowledgeConfigSchema:KnowledgeConfigSchema2}=await Promise.resolve().then(() => (init_schema(),exports_schema));return KnowledgeConfigSchema2.parse({})},applyCuratorKnowledgeUpdates:async(directory,recommendations,knowledgeConfig)=>{let{applyCuratorKnowledgeUpdates:applyCuratorKnowledgeUpdates2}=await Promise.resolve().then(() => (init_curator(),exports_curator));return applyCuratorKnowledgeUpdates2(directory,recommendations,knowledgeConfig)},checkHivePromotions:async(entries,knowledgeConfig)=>{let{checkHivePromotions:checkHivePromotions2}=await Promise.resolve().then(() => (init_hive_promoter(),exports_hive_promoter));return checkHivePromotions2(entries,knowledgeConfig)},applyProposalTriage:async(directory,triage)=>{let{_internals:skillInternals,activateProposal:activateProposal2,listSkills:listSkills2,sanitizeSlug:sanitizeSlug2}=await Promise.resolve().then(() => (init_skill_generator(),exports_skill_generator)),result={approved:[],rejected:[],skipped:[]},skills=await listSkills2(directory),proposalSlugs=new Set(skills.proposals.map((p)=>p.slug));for(let item of triage){let slug=sanitizeSlug2(normalizeProposalSlug(item.proposal_id));if(!slug||!proposalSlugs.has(slug)){result.skipped.push(slug||item.proposal_id);continue}if(item.action==="apply"){if((await activateProposal2(directory,slug,!1,{evaluate:!0,operation:"post_mortem_queue_triage",confirmUnevaluated:!0})).activated)result.approved.push(slug);else result.skipped.push(slug);continue}let proposal=skills.proposals.find((p)=>p.slug===slug);if(!proposal){result.skipped.push(slug);continue}try{skillInternals.unlinkSync(proposal.path),result.rejected.push(slug)}catch{result.skipped.push(slug)}}return result},readPriorDriftReports:async(directory)=>{let{readPriorDriftReports:readPriorDriftReports2}=await Promise.resolve().then(() => (init_curator_drift(),exports_curator_drift));return readPriorDriftReports2(directory)},readSwarmKnowledge:(directory)=>readKnowledge(resolveSwarmKnowledgePath(directory))}});import{mkdir as mkdir15,readFile as readFile16,rename as rename9,stat as stat9,unlink as unlink4,writeFile as writeFile12}from"node:fs/promises";import*as path66 from"node:path";function emptySynonymMap(){return{version:1,cursor:0,pairs:{}}}function resolveSynonymMapPath(directory){return validateSwarmPath(directory,SYNONYM_MAP_FILENAME)}function sanitizeToken(raw){if(typeof raw!=="string")return null;let token=raw.replace(/[\x00-\x1f\x7f-\x9f]/g," ").toLowerCase().replace(/\s+/g," ").trim();if(token.length===0)return null;if(token.length>MAX_TOKEN_LENGTH)return null;return token}function pairKey(a,b){return a<b?`${a}${PAIR_SEP}${b}`:`${b}${PAIR_SEP}${a}`}function tokensForEntry(entry){let out=new Set,fields=[entry.triggers,entry.tags,entry.applies_to_tools,entry.applies_to_agents];for(let field of fields){if(!Array.isArray(field))continue;for(let raw of field){let token=sanitizeToken(raw);if(token)out.add(token)}}return Array.from(out)}function evictToCap(map3,maxPairs){let keys=Object.keys(map3.pairs);if(keys.length<=maxPairs)return;keys.sort((k1,k2)=>{let s1=map3.pairs[k1].seq,s2=map3.pairs[k2].seq;if(s1!==s2)return s1-s2;return k1<k2?-1:1});let removeCount=keys.length-maxPairs;for(let i=0;i<removeCount;i++)delete map3.pairs[keys[i]]}function recordEntryCooccurrences(map3,entry,maxPairs=DEFAULT_MAX_PAIRS){let tokens=tokensForEntry(entry);if(tokens.length<2)return map3;for(let i=0;i<tokens.length;i++)for(let j=i+1;j<tokens.length;j++){let a=tokens[i],b=tokens[j];if(a===b)continue;let key=pairKey(a,b),seq=++map3.cursor,existing=map3.pairs[key];if(existing)existing.count+=1,existing.seq=seq;else{let[lo,hi]=a<b?[a,b]:[b,a];map3.pairs[key]={a:lo,b:hi,count:1,seq}}}return evictToCap(map3,maxPairs),map3}function buildSynonymMap(entries,maxPairs=DEFAULT_MAX_PAIRS){let map3=emptySynonymMap();for(let entry of entries)recordEntryCooccurrences(map3,entry,maxPairs);return map3}function buildSynonymIndex(map3,minCooccurrence=DEFAULT_MIN_COOCCURRENCE){let index=new Map,threshold=Math.max(1,minCooccurrence);for(let pair of Object.values(map3.pairs)){if(pair.count<threshold)continue;add(index,pair.a,pair.b),add(index,pair.b,pair.a)}return index}function add(index,from,to){let set3=index.get(from);if(!set3)set3=new Set,index.set(from,set3);set3.add(to)}function expandTokens(index,queryTokens,maxPerToken=DEFAULT_MAX_EXPANSIONS_PER_TOKEN){let originals=new Set;for(let raw of queryTokens){let token=sanitizeToken(raw);if(token)originals.add(token)}let expanded=new Set;for(let token of originals){let synonyms=index.get(token);if(!synonyms)continue;let sorted=Array.from(synonyms).sort(),added=0;for(let syn of sorted){if(added>=maxPerToken)break;if(originals.has(syn))continue;if(expanded.has(syn))continue;expanded.add(syn),added+=1}}return Array.from(expanded)}function isSynonymPair(value){if(typeof value!=="object"||value===null)return!1;let p=value;return typeof p.a==="string"&&typeof p.b==="string"&&typeof p.count==="number"&&Number.isFinite(p.count)&&typeof p.seq==="number"&&Number.isFinite(p.seq)}function coerceSynonymMap(parsed,maxPairs=DEFAULT_MAX_PAIRS){if(typeof parsed!=="object"||parsed===null)return emptySynonymMap();let obj=parsed;if(obj.version!==1||typeof obj.pairs!=="object"||obj.pairs===null)return emptySynonymMap();let out=emptySynonymMap(),cursor=typeof obj.cursor==="number"&&Number.isFinite(obj.cursor)?obj.cursor:0;for(let value of Object.values(obj.pairs)){if(!isSynonymPair(value))continue;let a=sanitizeToken(value.a),b=sanitizeToken(value.b);if(!a||!b||a===b)continue;let count=Math.max(0,Math.floor(value.count));if(count<=0)continue;let key=pairKey(a,b),seq=Number.isFinite(value.seq)?value.seq:++cursor;if(seq>cursor)cursor=seq;let existing=out.pairs[key];if(existing)existing.count=Math.max(existing.count,count),existing.seq=Math.max(existing.seq,seq);else{let[lo,hi]=a<b?[a,b]:[b,a];out.pairs[key]={a:lo,b:hi,count,seq}}}return out.cursor=cursor,evictToCap(out,Math.max(1,Math.floor(maxPairs))),out}async function readSynonymMap(directory,maxPairs=DEFAULT_MAX_PAIRS){let filePath;try{filePath=resolveSynonymMapPath(directory)}catch{return emptySynonymMap()}try{let ceiling=Math.max(MIN_READ_CEILING_BYTES,Math.floor(maxPairs)*APPROX_BYTES_PER_PAIR);if((await stat9(filePath)).size>ceiling)return emptySynonymMap();let raw=await readFile16(filePath,"utf-8");return coerceSynonymMap(JSON.parse(raw),maxPairs)}catch{return emptySynonymMap()}}async function writeSynonymMapAtomic(filePath,map3){await mkdir15(path66.dirname(filePath),{recursive:!0});let tmp=`${filePath}.tmp.${Date.now()}.${Math.floor(Math.random()*1e9)}`;try{await writeFile12(tmp,JSON.stringify(map3,null,2),"utf-8"),await rename9(tmp,filePath)}finally{try{await unlink4(tmp)}catch{}}}async function rebuildSynonymMap(directory,entries,maxPairs=DEFAULT_MAX_PAIRS){let filePath=resolveSynonymMapPath(directory),dir=path66.dirname(filePath);await mkdir15(dir,{recursive:!0});let release=null;try{release=await import_proper_lockfile7.default.lock(dir,{retries:{retries:5,minTimeout:100,maxTimeout:500},stale:5000});let map3=buildSynonymMap(entries,maxPairs);return await writeSynonymMapAtomic(filePath,map3),map3}finally{if(release)try{await release()}catch{}}}var import_proper_lockfile7,SYNONYM_MAP_FILENAME="synonym-map.json",MAX_TOKEN_LENGTH=64,DEFAULT_MAX_PAIRS=500,DEFAULT_MIN_COOCCURRENCE=3,DEFAULT_MAX_EXPANSIONS_PER_TOKEN=4,PAIR_SEP,APPROX_BYTES_PER_PAIR=512,MIN_READ_CEILING_BYTES=65536;var init_synonym_map=__esm(()=>{init_utils2();import_proper_lockfile7=__toESM(require_proper_lockfile(),1);PAIR_SEP=String.fromCharCode(0)});import*as fs31 from"node:fs";import*as path67 from"node:path";function extractSkillName(skillPath){let base=path67.basename(skillPath,path67.extname(skillPath));if(base!=="SKILL")return base;return path67.basename(path67.dirname(skillPath))}function stripQuotes(value){let trimmed=value.trim();if(trimmed.startsWith('"')&&trimmed.endsWith('"')||trimmed.startsWith("'")&&trimmed.endsWith("'"))return trimmed.slice(1,-1).trim();return trimmed}function normalizeDescription(description){let singleLine=description.replace(/\s+/g," ").trim();if(!singleLine)return"No description provided";return singleLine.length>240?`${singleLine.slice(0,237)}...`:singleLine}function normalizeTrigger(value){return stripQuotes(value).replace(/\s+/g," ").trim().slice(0,MAX_SKILL_TRIGGER_LENGTH)}function normalizeTriggerList(values){let out=[],seen=new Set;for(let raw of values){let value=normalizeTrigger(raw);if(!value)continue;let key=value.toLowerCase();if(seen.has(key))continue;if(seen.add(key),out.push(value),out.length>=MAX_SKILL_TRIGGERS)break}return out}function finiteRankValue(value){return Number.isFinite(value)?value:0}function parseInlineStringList(rawValue){let trimmed=rawValue.trim();if(!trimmed)return[];if(trimmed.startsWith("[")&&trimmed.endsWith("]")){let body=trimmed.slice(1,-1).trim();if(!body)return[];try{let parsed=JSON.parse(trimmed);if(Array.isArray(parsed))return parsed.filter((entry)=>typeof entry==="string")}catch{}return body.split(",").map((entry)=>stripQuotes(entry))}return[trimmed]}function collectYamlList(lines,start,end){let values=[],i=start;for(;i<end;i++){let line=lines[i]??"";if(/^[A-Za-z_][A-Za-z0-9_-]*\s*:/.test(line))break;let match=line.match(/^\s+-\s+(.+?)\s*$/);if(match)values.push(match[1])}return{values,nextIndex:i-1}}function parseSkillFrontmatter(content,skillPath){let normalizedPath=skillPath.replace(/^file:/,"").replace(/\\/g,"/"),fallbackName=extractSkillName(normalizedPath),fallback={path:normalizedPath,name:fallbackName,description:"No description provided"},lines=content.split(/\r?\n/);if(lines[0]?.trim()!=="---")return fallback;let end=lines.findIndex((line,index)=>index>0&&line.trim()==="---");if(end===-1)return fallback;let name=fallbackName,description="",skillType,triggers=[];for(let i=1;i<end;i++){let match=(lines[i]??"").match(/^([A-Za-z_][A-Za-z0-9_-]*)\s*:\s*(.*)$/);if(!match)continue;let key=match[1].toLowerCase(),rawValue=match[2].trim();if(key==="name"){let parsed=stripQuotes(rawValue);if(parsed)name=parsed;continue}if(key==="skill_type"){if(rawValue==="directive"||rawValue==="workflow")skillType=rawValue;continue}if(key==="triggers"){if(rawValue===""){let collected=collectYamlList(lines,i+1,end);triggers=normalizeTriggerList(collected.values),i=collected.nextIndex}else triggers=normalizeTriggerList(parseInlineStringList(rawValue));continue}if(key!=="description")continue;if(rawValue===">"||rawValue==="|"){let collected=[];for(let j=i+1;j<end;j++){let next=lines[j]??"";if(/^[A-Za-z_][A-Za-z0-9_-]*\s*:/.test(next))break;collected.push(next.trim()),i=j}description=collected.join(" ")}else description=stripQuotes(rawValue)}let meta3={path:normalizedPath,name:name||fallbackName,description:normalizeDescription(description)};if(skillType)meta3.skillType=skillType;if(triggers.length>0)meta3.triggers=triggers;return meta3}function readFilePrefix(filePath){let fd=fs31.openSync(filePath,"r");try{let buffer=Buffer.alloc(SKILL_FRONTMATTER_READ_BYTES),bytesRead=fs31.readSync(fd,buffer,0,SKILL_FRONTMATTER_READ_BYTES,0);return buffer.toString("utf-8",0,bytesRead)}finally{fs31.closeSync(fd)}}function readSkillMetadata(skillPath,directory){let normalizedPath=skillPath.replace(/^file:/,"").replace(/\\/g,"/"),fallback=parseSkillFrontmatter("",normalizedPath);try{if(path67.isAbsolute(normalizedPath)||normalizedPath.split("/").includes(".."))return fallback;let root=path67.resolve(directory),absolutePath=path67.resolve(directory,normalizedPath);if(absolutePath!==root&&!absolutePath.startsWith(root+path67.sep))return fallback;let content=readFilePrefix(absolutePath);return parseSkillFrontmatter(content,normalizedPath)}catch{return fallback}}function computeRecencyScore(lastUsedTimestamp){if(!lastUsedTimestamp)return 0;let lastUsed=new Date(lastUsedTimestamp).getTime();if(Number.isNaN(lastUsed))return 0;let ageMs=Date.now()-lastUsed;if(ageMs<=0)return 1;if(ageMs>=RECENCY_DECAY_MS)return 0;return 1-ageMs/RECENCY_DECAY_MS}function extractKeywords(text){let words=text.toLowerCase().split(/[^a-z0-9]+/).filter((w)=>w.length>=MIN_KEYWORD_LENGTH);return new Set(words)}function computeContextMatchScore(taskDescription,skillPath,metadata){let taskKeywords=extractKeywords(taskDescription);if(taskKeywords.size===0)return 0;let skillName=extractSkillName(skillPath),skillText=`${skillPath} ${skillName} ${metadata?.name??""} ${metadata?.description??""}`,skillKeywords=extractKeywords(skillText),matchCount=0;for(let kw of taskKeywords)if(skillKeywords.has(kw))matchCount++;return matchCount/taskKeywords.size}function normalizeTriggerMatchText(text){return text.toLowerCase().replace(/\s+/g," ").trim()}function computeTriggerMatchBoost(taskDescription,triggers){if(!triggers||triggers.length===0)return 0;let task=normalizeTriggerMatchText(taskDescription);if(!task)return 0;for(let raw of triggers){let trigger=normalizeTriggerMatchText(raw);if(trigger.length>=SKILL_TRIGGER_MIN_LENGTH&&task.includes(trigger))return SKILL_TRIGGER_BOOST}return 0}function computeSkillRelevanceScore(skillPath,taskDescription,usageHistory,metadata){let contextScore=computeContextMatchScore(taskDescription,skillPath,metadata)*CONTEXT_WEIGHT,triggerBoost=computeTriggerMatchBoost(taskDescription,metadata?.triggers);if(usageHistory.length===0)return Math.min(1,contextScore+triggerBoost);let usageCount=usageHistory.length,frequencyScore=Math.min(1,usageCount/FREQUENCY_CAP)*FREQUENCY_WEIGHT,entriesWithVerdict=usageHistory.filter((e)=>e.complianceVerdict!==void 0&&e.complianceVerdict!=="not_checked"),compliantCount=entriesWithVerdict.filter((e)=>e.complianceVerdict==="compliant").length,denominator=Math.max(1,entriesWithVerdict.length),complianceScore=compliantCount/denominator*COMPLIANCE_WEIGHT,lastUsedTimestamp=[...usageHistory].sort((a,b)=>b.timestamp>a.timestamp?1:b.timestamp<a.timestamp?-1:0)[0]?.timestamp??"",recencyScore=computeRecencyScore(lastUsedTimestamp)*RECENCY_WEIGHT,taskDiversityScore=new Set(usageHistory.map((e)=>e.taskID).filter(Boolean)).size/Math.max(1,usageHistory.length)*TASK_DIVERSITY_WEIGHT,workflowBoost=0;if(metadata?.skillType==="workflow"&&contextScore>=WORKFLOW_BOOST_MIN_CONTEXT)workflowBoost=WORKFLOW_BOOST;return Math.min(1,frequencyScore+complianceScore+recencyScore+taskDiversityScore+contextScore+triggerBoost+workflowBoost)}function rankSkillsForContext(skills,taskContext,directory){let allEntries=readSkillUsageEntries(directory),results=[];for(let skillPath of skills){let skillEntries=allEntries.filter((e)=>e.skillPath===skillPath),metadata=_internals38.readSkillMetadata(skillPath,directory),score=computeSkillRelevanceScore(skillPath,taskContext,skillEntries,metadata),entriesWithVerdict=skillEntries.filter((e)=>e.complianceVerdict!==void 0&&e.complianceVerdict!=="not_checked"),compliantCount=entriesWithVerdict.filter((e)=>e.complianceVerdict==="compliant").length,complianceRate=entriesWithVerdict.length>0?compliantCount/entriesWithVerdict.length:0;results.push({skillPath,score:finiteRankValue(score),usageCount:skillEntries.length,complianceRate})}return results.sort((a,b)=>{let scoreDelta=finiteRankValue(b.score)-finiteRankValue(a.score);if(scoreDelta!==0)return scoreDelta;let usageDelta=b.usageCount-a.usageCount;if(usageDelta!==0)return usageDelta;return a.skillPath.localeCompare(b.skillPath)}),results}function getSkillStats(skillPath,directory){let entries=readSkillUsageEntries(directory,{skillPath});if(entries.length===0)return{totalUsage:0,complianceRate:0,lastUsed:"",topAgents:[]};let entriesWithVerdict=entries.filter((e)=>e.complianceVerdict!==void 0&&e.complianceVerdict!=="not_checked"),compliantCount=entriesWithVerdict.filter((e)=>e.complianceVerdict==="compliant").length,complianceRate=entriesWithVerdict.length>0?compliantCount/entriesWithVerdict.length:0,lastUsed=[...entries].sort((a,b)=>b.timestamp>a.timestamp?1:b.timestamp<a.timestamp?-1:0)[0]?.timestamp??"",agentCounts=new Map;for(let entry of entries)agentCounts.set(entry.agentName,(agentCounts.get(entry.agentName)??0)+1);let topAgents=Array.from(agentCounts.entries()).sort((a,b)=>b[1]-a[1]).map(([agent,count])=>({agent,count}));return{totalUsage:entries.length,complianceRate,lastUsed,topAgents}}function formatSkillIndexWithContext(skills,directory){let usageLogPath=path67.join(directory,".swarm","skill-usage.jsonl"),hasHistory=!1;try{hasHistory=fs31.statSync(usageLogPath).size>0}catch{}if(!hasHistory)return skills.map((sp)=>{let meta3=_internals38.readSkillMetadata(sp,directory);return` - file:${meta3.path} - ${meta3.name}: ${meta3.description}`}).join(`
1218
1218
  `);let lines=[];for(let skillPath of skills){let stats2=getSkillStats(skillPath,directory),meta3=_internals38.readSkillMetadata(skillPath,directory),compliancePct=Math.round(stats2.complianceRate*100),topAgentNames=stats2.topAgents.slice(0,3).map((a)=>a.agent).join(", ");lines.push(` - file:${meta3.path} - ${meta3.name}: ${meta3.description} (used: ${stats2.totalUsage}, compliance: ${compliancePct}%)`+(stats2.topAgents.length>0?` → ${topAgentNames}`:""))}return lines.join(`
1219
1219
  `)}var FREQUENCY_CAP=10,FREQUENCY_WEIGHT=0.3,COMPLIANCE_WEIGHT=0.3,RECENCY_WEIGHT=0.15,TASK_DIVERSITY_WEIGHT=0.05,CONTEXT_WEIGHT=0.2,WORKFLOW_BOOST=0.1,SKILL_TRIGGER_BOOST=0.3,SKILL_TRIGGER_MIN_LENGTH=3,MAX_SKILL_TRIGGERS=20,MAX_SKILL_TRIGGER_LENGTH=120,WORKFLOW_BOOST_MIN_CONTEXT=0.05,RECENCY_DECAY_MS=2592000000,SKILL_FRONTMATTER_READ_BYTES=16384,_internals38,MIN_KEYWORD_LENGTH=3;var init_skill_scoring=__esm(()=>{init_skill_usage_log();_internals38={computeSkillRelevanceScore:null,rankSkillsForContext:null,getSkillStats:null,formatSkillIndexWithContext:null,parseSkillFrontmatter:null,readSkillMetadata:null,extractSkillName:null,computeRecencyScore:null,computeContextMatchScore:null,computeTriggerMatchBoost:null};_internals38.computeSkillRelevanceScore=computeSkillRelevanceScore;_internals38.rankSkillsForContext=rankSkillsForContext;_internals38.getSkillStats=getSkillStats;_internals38.formatSkillIndexWithContext=formatSkillIndexWithContext;_internals38.parseSkillFrontmatter=parseSkillFrontmatter;_internals38.readSkillMetadata=readSkillMetadata;_internals38.extractSkillName=extractSkillName;_internals38.computeRecencyScore=computeRecencyScore;_internals38.computeContextMatchScore=computeContextMatchScore;_internals38.computeTriggerMatchBoost=computeTriggerMatchBoost});import*as fs32 from"node:fs";import*as path68 from"node:path";function parseSimpleYaml(content){let lines=content.split(`
1220
1220
  `),result={},_currentSection=null,currentSubSection=null,currentList=[],currentListItem=null;for(let line of lines){if(!line.trim()||line.trim().startsWith("#"))continue;let indent=line.search(/\S/),trimmed=line.trim();if(indent===0&&trimmed.endsWith(":")){if(_currentSection&&currentSubSection&&currentList.length>0){if(!result[_currentSection])result[_currentSection]={};result[_currentSection][currentSubSection]=currentList}else if(currentSubSection&&currentList.length>0)result[currentSubSection]=currentList;_currentSection=trimmed.slice(0,-1),currentSubSection=null,currentList=[],currentListItem=null;continue}if(indent===2&&trimmed.endsWith(":")){if(_currentSection&&currentSubSection&&currentList.length>0){if(!result[_currentSection])result[_currentSection]={};result[_currentSection][currentSubSection]=currentList}else if(currentSubSection&&currentList.length>0)result[currentSubSection]=currentList;currentSubSection=trimmed.slice(0,-1),currentList=[],currentListItem=null;continue}if(trimmed.startsWith("- ")){currentListItem=null;let rest=trimmed.slice(2);if(rest.includes(":")){let colonIndex=rest.indexOf(":"),key=rest.slice(0,colonIndex).trim(),value=rest.slice(colonIndex+1).trim();currentListItem={[key]:parseYamlValue(value)}}else currentListItem={path:trimmed.slice(2)};currentList.push(currentListItem);continue}if(indent>=4&&currentListItem){if(trimmed.includes(":")){let colonIndex=trimmed.indexOf(":"),key=trimmed.slice(0,colonIndex).trim(),value=trimmed.slice(colonIndex+1).trim();currentListItem[key]=parseYamlValue(value)}}}if(currentSubSection&&currentList.length>0)if(_currentSection){if(!result[_currentSection])result[_currentSection]={};result[_currentSection][currentSubSection]=currentList}else result[currentSubSection]=currentList;return result}function parseYamlValue(value){let trimmed=value.trim();if(trimmed.startsWith('"')&&trimmed.endsWith('"')||trimmed.startsWith("'")&&trimmed.endsWith("'"))return trimmed.slice(1,-1);if(trimmed.startsWith("[")&&trimmed.endsWith("]")){let inner=trimmed.slice(1,-1);if(!inner.trim())return[];return inner.split(",").map((s)=>s.trim().replace(/^["']|["']$/g,""))}if(trimmed.toLowerCase()==="true")return!0;if(trimmed.toLowerCase()==="false")return!1;if(/^-?\d+(\.\d+)?$/.test(trimmed))return trimmed.includes(".")?parseFloat(trimmed):parseInt(trimmed,10);return trimmed}function loadRoutingSkills(directory,targetAgent){let routingPath=path68.join(directory,".opencode","skill-routing.yaml");if(!_internals39.existsSync(routingPath))return[];try{let content=_internals39.readFileSync(routingPath,"utf-8"),config3=parseSimpleYaml(content);if(!config3?.routing)return[];let routingEntries=config3.routing[targetAgent];if(!routingEntries||routingEntries.length===0)return[];return routingEntries.map((entry)=>entry.path)}catch{return[]}}function discoverAvailableSkills(directory){let results=[];for(let root of SKILL_SEARCH_ROOTS){let rootPath=path68.join(directory,root);if(!_internals39.existsSync(rootPath))continue;let entries;try{entries=_internals39.readdirSync(rootPath)}catch{continue}for(let entry of entries){if(entry.startsWith("."))continue;let skillDir=path68.join(rootPath,entry);if(_internals39.existsSync(path68.join(skillDir,"retired.marker"))||_internals39.existsSync(path68.join(skillDir,"stale.marker")))continue;let skillFile=path68.join(skillDir,"SKILL.md");try{if(_internals39.statSync(skillDir).isDirectory()&&_internals39.existsSync(skillFile))results.push(path68.join(root,entry,"SKILL.md").replace(/\\/g,"/"))}catch(err){warn(`[skill-propagation-gate] failed to stat skill directory ${entry}: ${err instanceof Error?err.message:String(err)}`)}}}return[...new Set(results)]}function parseDelegationArgs(args2){if(!args2||typeof args2!=="object")return null;let record3=args2,subagentType=typeof record3.subagent_type==="string"?record3.subagent_type:"",prompt=typeof record3.prompt==="string"?record3.prompt:"";if(!subagentType&&!prompt)return null;let targetAgent=subagentType;if(!targetAgent&&prompt){let lines=prompt.split(`
@@ -5206,7 +5206,7 @@ Make sure to run 'bun run build' to copy grammar files to dist/lang/grammars/. I
5206
5206
  WASM path: ${wasmPath}`)}return parserCache.set(normalizedId,parser),initializedLanguages.add(normalizedId),parser})();inflightLoads.set(normalizedId,loadPromise);try{return await loadPromise}finally{inflightLoads.delete(normalizedId)}}async function isGrammarAvailable(languageId){if(typeof languageId!=="string"||languageId.length>100)return!1;let normalizedId;try{normalizedId=sanitizeLanguageId(languageId).toLowerCase()}catch{return!1}if(normalizedId.length===0)return!1;if(parserCache.has(normalizedId))return!0;try{let wasmFileName=getWasmFileName(normalizedId),wasmPath=path142.join(getGrammarsDirAbsolute(),wasmFileName);return statSync28(wasmPath),!0}catch{return!1}}function clearParserCache(){parserCache.clear(),inflightLoads.clear(),initializedLanguages.clear(),treeSitterInitPromise=null}function getInitializedLanguages(){return Array.from(initializedLanguages)}function getSupportedLanguages(){return Object.keys(LANGUAGE_WASM_MAP)}var parserCache,inflightLoads,GRAMMAR_LOAD_TIMEOUT_MS=1e4,initializedLanguages,treeSitterInitPromise=null,_internals91,LANGUAGE_WASM_MAP;var init_runtime=__esm(()=>{parserCache=new Map,inflightLoads=new Map,initializedLanguages=new Set,_internals91={parserInit:TreeSitterParser.init,getModuleDir:()=>path142.dirname(fileURLToPath4(import.meta.url)),fileExists:existsSync81};LANGUAGE_WASM_MAP={javascript:"tree-sitter-javascript.wasm",typescript:"tree-sitter-typescript.wasm",tsx:"tree-sitter-tsx.wasm",python:"tree-sitter-python.wasm",go:"tree-sitter-go.wasm",rust:"tree-sitter-rust.wasm",cpp:"tree-sitter-cpp.wasm",c:"tree-sitter-cpp.wasm",csharp:"tree-sitter-c-sharp.wasm",css:"tree-sitter-css.wasm",bash:"tree-sitter-bash.wasm",ruby:"tree-sitter-ruby.wasm",php:"tree-sitter-php.wasm",java:"tree-sitter-java.wasm",kotlin:"tree-sitter-kotlin.wasm",swift:"tree-sitter-swift.wasm",dart:"tree-sitter-dart.wasm",powershell:"tree-sitter-powershell.wasm",ini:"tree-sitter-ini.wasm",regex:"tree-sitter-regex.wasm"}});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 crypto10 from"node:crypto";import*as fs87 from"node:fs";import{mkdir as mkdir28,readdir as readdir9,readFile as readFile30,realpath as realpath4,stat as stat13,writeFile as writeFile22}from"node:fs/promises";import*as path155 from"node:path";function normalizeSeparators(filePath){return filePath.replace(/\\/g,"/")}function matchesDocPattern(filePath,patterns){let normalizedPath=normalizeSeparators(filePath),basename22=path155.basename(filePath);for(let pattern of patterns){if(!pattern.includes("/")&&!pattern.includes("\\")){if(basename22===pattern)return!0;continue}if(pattern.startsWith("**/")){let filenamePattern=pattern.slice(3);if(basename22===filenamePattern)return!0;continue}let dirPrefix=normalizeSeparators(pattern).replace(/\/\*\*.*$/,"").replace(/\/\*.*$/,"");if(normalizedPath.startsWith(`${dirPrefix}/`)||normalizedPath===dirPrefix)return!0}return!1}function extractTitleAndSummary(content,filename){let lines=content.split(`
5207
5207
  `),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 manifestPath=path155.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 readFile30(manifestPath,"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=path155.join(directory,file3.path);if(fs87.statSync(fullPath).mtimeMs>file3.mtime){cacheValid=!1;break}}catch{cacheValid=!1;break}if(cacheValid)return{manifest:existingManifest,cached:!0}}}catch{}let resolvedDirectory=await realpath4(directory).catch(()=>directory),discoveredFiles=[],rootReadable=!1,truncated=!1,walkDir2=async(dir)=>{let entries;try{if(entries=await readdir9(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=path155.join(dir,entry.name),resolved=await realpath4(symlinkPath),rel=path155.relative(resolvedDirectory,resolved);if(rel.startsWith("..")||path155.isAbsolute(rel))continue;isFile=(await stat13(symlinkPath)).isFile()}catch{continue}if(isDir){if(!SKIP_DIRECTORIES3.has(entry.name))await walkDir2(path155.join(dir,entry.name));continue}if(!isFile)continue;let fullPath=path155.join(dir,entry.name),relPath=normalizeSeparators(path155.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 stat13(fullPath)}catch{continue}let content;try{content=await readFile30(fullPath,"utf-8")}catch{continue}let{title,summary}=extractTitleAndSummary(content,path155.basename(relPath));discoveredFiles.push({path:relPath,title,summary,lines:content.split(`
5208
5208
  `).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 mkdir28(path155.dirname(manifestPath),{recursive:!0}),await writeFile22(manifestPath,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(`
5209
- `),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 manifestPath=path155.join(directory,".swarm","doc-manifest.json"),manifest;try{let content=await readFile30(manifestPath,"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(normalize5(taskContext)),extractedCount=0,skippedCount=0,details=[];for(let docFile of manifest.files){let docContext=`${docFile.path} ${docFile.title} ${docFile.summary}`,docBigrams=wordBigrams(normalize5(docContext)),score=jaccardBigram(taskBigrams,docBigrams);if(score<=RELEVANCE_THRESHOLD){skippedCount++;continue}let fullContent;try{fullContent=await readFile30(path155.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_THRESHOLD3)){let entry={id:crypto10.randomUUID(),tier:"swarm",lesson:constraint,category:"architecture",tags:["doc-scan",path155.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_THRESHOLD3=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 manifestPath=path155.join(directory,".swarm","doc-manifest.json");try{fs87.unlinkSync(manifestPath)}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 existsSync86}from"node:fs";import{readFile as readFile31}from"node:fs/promises";import*as path156 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(!existsSync86(filePath))return{};try{let content=await readFile31(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){let shownFile=path156.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)=>{return shownData[canonicalKey]=lessonIds,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 swarmPath=resolveSwarmKnowledgePath(directory),swarmEntries=await readKnowledge(swarmPath),hiveEntries=[];if(config3.hive_enabled!==!1){let hivePath=resolveHiveKnowledgePath();hiveEntries=await readKnowledge(hivePath)}let seenLessons=new Set,merged=[];for(let entry of hiveEntries){let normalized=normalize5(entry.lesson);seenLessons.add(normalized),merged.push({...entry,relevanceScore:{category:0,confidence:0,keywords:0},finalScore:0})}for(let entry of swarmEntries){let normalized=normalize5(entry.lesson);if(seenLessons.has(normalized))continue;let swarmBigrams=wordBigrams(normalized);if(hiveEntries.some((hiveEntry)=>jaccardBigram(swarmBigrams,wordBigrams(normalize5(hiveEntry.lesson)))>=JACCARD_THRESHOLD2))continue;if(merged.some((m)=>m.tier==="swarm"&&jaccardBigram(swarmBigrams,wordBigrams(normalize5(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(normalize5(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,topN=ranked.slice(0,maxInject);if(topN.length>0&&context?.currentPhase)recordLessonsShown(directory,topN.map((e)=>e.id),context.currentPhase).catch((err)=>{warn("[knowledge-reader] recordLessonsShown unexpected rejection:",err)});return topN}async function updateRetrievalOutcome(directory,phaseInfo,phaseSucceeded){let shownFile=path156.join(directory,".swarm",".knowledge-shown.json");try{if(!existsSync86(shownFile))return;let shownIds;try{let content=await readFile31(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 _internals95.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,_internals95;var init_knowledge_reader=__esm(()=>{init_task_file();init_logger();init_knowledge_events();init_knowledge_store();init_knowledge_types();_internals95={readMergedKnowledge,updateRetrievalOutcome,scoreDirectiveAgainstContext,transactShownFile,recordKnowledgeEvent}});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(normalize5(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=!0,applyScopeFilter=!0,forceReadHive=!1,applyRoleScope=!0}=params,traceId=newTraceId(),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 readKnowledgeCounterRollups(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(normalize5(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=normalize5(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(normalize5(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=normalize5(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=normalize5(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:()=>_internals96});var knowledge_recall,_internals96;var init_knowledge_recall=__esm(()=>{init_zod();init_config();init_schema();init_search_knowledge();init_knowledge_diagnostics();init_logger();init_create_tool();knowledge_recall=createSwarmTool({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")},execute:async(args2,directory,ctx)=>{let queryInput,topNInput,tierInput,debugInput;try{if(args2&&typeof args2==="object"){let obj=args2;queryInput=obj.query,topNInput=obj.top_n,tierInput=obj.tier,debugInput=obj.debug}}catch{}let wantDebug=debugInput===!0;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}),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)}}),_internals96={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(`
5209
+ `),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 manifestPath=path155.join(directory,".swarm","doc-manifest.json"),manifest;try{let content=await readFile30(manifestPath,"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(normalize5(taskContext)),extractedCount=0,skippedCount=0,details=[];for(let docFile of manifest.files){let docContext=`${docFile.path} ${docFile.title} ${docFile.summary}`,docBigrams=wordBigrams(normalize5(docContext)),score=jaccardBigram(taskBigrams,docBigrams);if(score<=RELEVANCE_THRESHOLD){skippedCount++;continue}let fullContent;try{fullContent=await readFile30(path155.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_THRESHOLD3)){let entry={id:crypto10.randomUUID(),tier:"swarm",lesson:constraint,category:"architecture",tags:["doc-scan",path155.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_THRESHOLD3=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 manifestPath=path155.join(directory,".swarm","doc-manifest.json");try{fs87.unlinkSync(manifestPath)}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 existsSync86}from"node:fs";import{readFile as readFile31}from"node:fs/promises";import*as path156 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(!existsSync86(filePath))return{};try{let content=await readFile31(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=path156.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 swarmPath=resolveSwarmKnowledgePath(directory),swarmEntries=await readKnowledge(swarmPath),hiveEntries=[];if(config3.hive_enabled!==!1){let hivePath=resolveHiveKnowledgePath();hiveEntries=await readKnowledge(hivePath)}let seenLessons=new Set,merged=[];for(let entry of hiveEntries){let normalized=normalize5(entry.lesson);seenLessons.add(normalized),merged.push({...entry,relevanceScore:{category:0,confidence:0,keywords:0},finalScore:0})}for(let entry of swarmEntries){let normalized=normalize5(entry.lesson);if(seenLessons.has(normalized))continue;let swarmBigrams=wordBigrams(normalized);if(hiveEntries.some((hiveEntry)=>jaccardBigram(swarmBigrams,wordBigrams(normalize5(hiveEntry.lesson)))>=JACCARD_THRESHOLD2))continue;if(merged.some((m)=>m.tier==="swarm"&&jaccardBigram(swarmBigrams,wordBigrams(normalize5(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(normalize5(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=path156.join(directory,".swarm",".knowledge-shown.json");try{if(!existsSync86(shownFile))return;let shownIds;try{let content=await readFile31(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 _internals95.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,_internals95;var init_knowledge_reader=__esm(()=>{init_task_file();init_logger();init_knowledge_events();init_knowledge_store();init_knowledge_types();_internals95={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(normalize5(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=!0,applyScopeFilter=!0,forceReadHive=!1,applyRoleScope=!0}=params,traceId=newTraceId(),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 readKnowledgeCounterRollups(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(normalize5(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=normalize5(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(normalize5(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=normalize5(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=normalize5(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:()=>_internals96});var knowledge_recall,_internals96;var init_knowledge_recall=__esm(()=>{init_zod();init_config();init_schema();init_search_knowledge();init_knowledge_diagnostics();init_logger();init_create_tool();knowledge_recall=createSwarmTool({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")},execute:async(args2,directory,ctx)=>{let queryInput,topNInput,tierInput,debugInput;try{if(args2&&typeof args2==="object"){let obj=args2;queryInput=obj.query,topNInput=obj.top_n,tierInput=obj.tier,debugInput=obj.debug}}catch{}let wantDebug=debugInput===!0;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}),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)}}),_internals96={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(`
5210
5210
  `);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(`
5211
5211
  `);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(`
5212
5212
  `)}var init_prompt_renderer=()=>{};var exports_design_doc_drift={};__export(exports_design_doc_drift,{runDesignDocDriftCheck:()=>runDesignDocDriftCheck,_internals:()=>_internals131});import*as fs130 from"node:fs";import*as path206 from"node:path";function mtimeMsOrNull(absPath){try{return fs130.statSync(absPath).mtimeMs}catch{return null}}function resolveAnchorWithin(directory,anchor){if(!anchor||typeof anchor!=="string")return null;let root=path206.resolve(directory),resolved=path206.resolve(root,anchor),rel=path206.relative(root,resolved);if(rel.startsWith("..")||path206.isAbsolute(rel))return null;return resolved}async function runDesignDocDriftCheck(directory,phase,outDir){try{let root=path206.resolve(directory),outAbs=path206.resolve(root,outDir),outRel=path206.relative(root,outAbs);if(outRel.startsWith("..")||path206.isAbsolute(outRel))return null;let docMtimes=new Map,checkedDocs=[],missingDocs=[];for(let[docName,relFile]of Object.entries(DESIGN_DOC_FILES)){let abs=path206.join(outAbs,relFile),mtime=mtimeMsOrNull(abs);if(docMtimes.set(docName,mtime),mtime===null)missingDocs.push(path206.join(outDir,relFile));else checkedDocs.push(path206.join(outDir,relFile))}let traceabilityAbs=path206.join(outAbs,TRACEABILITY_REL),registry3=null;try{if((await fs130.promises.stat(traceabilityAbs)).size<=MAX_TRACEABILITY_BYTES){let raw=await fs130.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 fs130.promises.mkdir(path206.dirname(filePath),{recursive:!0}),await fs130.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,_internals131;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":path206.join("reference","reference-impl.md"),"idiom-notes":path206.join("reference","idiom-notes.md")},TRACEABILITY_REL=path206.join("reference","traceability.json");_internals131={mtimeMsOrNull,resolveAnchorWithin,DESIGN_DOC_FILES}});var exports_project_context={};__export(exports_project_context,{buildProjectContext:()=>buildProjectContext,_internals:()=>_internals150,LANG_BACKEND_DETECTION_TIMEOUT_MS:()=>LANG_BACKEND_DETECTION_TIMEOUT_MS});import*as fs153 from"node:fs";import*as path235 from"node:path";function detectFileExists2(directory,pattern){if(pattern.includes("*")||pattern.includes("?"))try{let files=fs153.readdirSync(directory),regex=new RegExp(`^${pattern.replace(/\./g,"\\.").replace(/\*/g,".*").replace(/\?/g,".")}$`);return files.some((f)=>regex.test(f))}catch{return!1}try{return fs153.accessSync(path235.join(directory,pattern)),!0}catch{return!1}}function selectTestCommandFromScriptsTest(backend,directory){let pkgRaw;try{pkgRaw=fs153.readFileSync(path235.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 _internals150.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=_internals150.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,_internals150;var init_project_context=__esm(()=>{init_dispatch();init_framework_detector();_internals150={pickBackend,pickedProfiles}});init_package();init_agents2();init_critic();import*as path236 from"node:path";import{fileURLToPath as fileURLToPath5}from"node:url";init_event_bus();init_evidence_summary_integration();init_manager3();init_manager();init_utils();import*as fs67 from"node:fs";import*as path128 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 path128.resolve(this.directory,".swarm")}getPlanJsonPath(){return path128.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=fs67.statSync(this.getPlanJsonPath());this.lastStat={mtimeMs:stats2.mtimeMs,size:stats2.size}}catch{this.lastStat=null}}setupNativeWatcher(){let swarmDir=this.getSwarmDir();try{if(!fs67.existsSync(swarmDir))return log("[PlanSyncWorker] Swarm directory does not exist yet"),!1;return this.watcher=fs67.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);this.pollTimer=setInterval(()=>{if(this.disposed||this.status!=="running")return;this.pollCheck()},this.pollIntervalMs),log("[PlanSyncWorker] Polling fallback established",{intervalMs:this.pollIntervalMs})}pollCheck(){try{let planPath=this.getPlanJsonPath();if(!fs67.existsSync(planPath)){if(this.lastStat!==null)this.lastStat=null,log("[PlanSyncWorker] plan.json deleted");return}let stats2=fs67.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(_internals13.loadPlanJsonOnly(this.directory),this.syncTimeoutMs,"Sync operation timed out");if(plan&&plan.phases.length>0)await _internals13.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=path128.join(swarmDir,"plan.json"),markerPath=path128.join(swarmDir,".plan-write-marker"),planStats=fs67.statSync(planJsonPath),planMtimeMs=Math.floor(planStats.mtimeMs),markerContent=fs67.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((resolve46,reject)=>{let timer=setTimeout(()=>{reject(Error(`${timeoutMessage2} (${ms}ms)`))},ms);promise3.then((result)=>{clearTimeout(timer),resolve46(result)}).catch((error93)=>{clearTimeout(timer),reject(error93)})})}}init_pr_event_subscribers();import*as child_process10 from"node:child_process";init_zod();init_bun_compat();init_logger();function sanitizeLabel(label){return label.replace(/[<>]/g," ").replace(/[\p{Cc}]/gu," ").replace(/\s+/g," ").trim().slice(0,120)}function neutralizeUntrustedMarkdown(content,sourceLabel="GitHub content"){let normalized=content.replaceAll(String.fromCharCode(0),"").replace(/\r\n/g,`
@@ -5769,22 +5769,22 @@ ${untracked.slice(0,100).map((f)=>`- ${f}`).join(`
5769
5769
  ## RUN MEMORY — Previous Task Outcomes
5770
5770
  `,suffix=`
5771
5771
  Use this data to avoid repeating known failure patterns.`,summaryText=summaries.join(`
5772
- `),estimateTokens5=(text)=>{return Math.ceil(text.length*0.33)},totalText=prefix+summaryText+suffix;if(estimateTokens5(totalText)>MAX_SUMMARY_TOKENS){let prefixTokens=estimateTokens5(prefix),suffixTokens=estimateTokens5(suffix),availableContentTokens=MAX_SUMMARY_TOKENS-prefixTokens-suffixTokens;if(availableContentTokens>0){let maxContentChars=Math.floor(availableContentTokens/0.33);summaryText=summaryText.slice(0,maxContentChars)}else summaryText=""}return prefix+summaryText+suffix}var _internals99={generateTaskFingerprint,recordOutcome,getTaskHistory,getFailures,getRunMemorySummary,groupByTaskId,summarizeTask};init_state2();init_logger();init_curator_drift();init_extractors();init_knowledge_escalator();init_knowledge_events();init_knowledge_store();init_knowledge_types();init_model_limits();init_search_knowledge();init_utils2();var INJECTION_SENTINEL=`${String.fromCharCode(8204)}[[KNOWLEDGE-INJECTED]]`,defaultSearchKnowledge=searchKnowledge;function getRenderedEntryIds(entries,renderedBlock,cfg,currentProject){if(!renderedBlock)return[];let maxDisplayChars=cfg.max_lesson_display_chars??120,ids=[];for(let entry of entries){if(renderedBlock.includes(`- id: ${entry.id}`)){ids.push(entry.id);continue}let lessonText=sanitizeLessonForContext(entry.lesson);if(lessonText.length>maxDisplayChars)lessonText=`${lessonText.slice(0,maxDisplayChars)}…`;let rawSource=entry.tier==="hive"&&"source_project"in entry?entry.source_project??null:null,source=rawSource!==null&&rawSource!==currentProject?` (from: ${sanitizeLessonForContext(rawSource)})`:"";if(renderedBlock.includes(`${lessonText}${source}`))ids.push(entry.id)}return ids}function buildKnowledgeBlock(entries,charBudget,cfg,currentProject){if(entries.length===0)return null;let maxDisplayChars=cfg.max_lesson_display_chars??120,lines=entries.map((entry)=>{let tier=entry.tier==="hive"?"[H]":"[S]",confirmedBy=entry.confirmed_by?.length??0,confirm=confirmedBy>=3?" ✓✓":confirmedBy>=1?" ✓":"",lessonText=sanitizeLessonForContext(entry.lesson);if(lessonText.length>maxDisplayChars)lessonText=`${lessonText.slice(0,maxDisplayChars)}…`;let rawSource=entry.tier==="hive"&&"source_project"in entry?entry.source_project??null:null,source=rawSource!==null&&rawSource!==currentProject?` (from: ${sanitizeLessonForContext(rawSource)})`:"";return`${tier} ${lessonText}${source}${confirm}`}),header=`\uD83D\uDCDA Lessons:
5772
+ `),estimateTokens5=(text)=>{return Math.ceil(text.length*0.33)},totalText=prefix+summaryText+suffix;if(estimateTokens5(totalText)>MAX_SUMMARY_TOKENS){let prefixTokens=estimateTokens5(prefix),suffixTokens=estimateTokens5(suffix),availableContentTokens=MAX_SUMMARY_TOKENS-prefixTokens-suffixTokens;if(availableContentTokens>0){let maxContentChars=Math.floor(availableContentTokens/0.33);summaryText=summaryText.slice(0,maxContentChars)}else summaryText=""}return prefix+summaryText+suffix}var _internals99={generateTaskFingerprint,recordOutcome,getTaskHistory,getFailures,getRunMemorySummary,groupByTaskId,summarizeTask};init_state2();init_logger();init_curator_drift();init_extractors();init_knowledge_escalator();init_knowledge_events();init_knowledge_reader();init_knowledge_store();init_knowledge_types();init_model_limits();init_search_knowledge();init_utils2();var INJECTION_SENTINEL=`${String.fromCharCode(8204)}[[KNOWLEDGE-INJECTED]]`,defaultSearchKnowledge=searchKnowledge;function phaseNumberOf(label){if(!label)return;let m=/^Phase\s+(\d+)/i.exec(label);return m?Number(m[1]):void 0}function recordInjectionSkip(directory,reason,detail){_internals100.recordKnowledgeEvent(directory,{type:"injection_skip",reason,agent:detail?.agent,session_id:detail?.sessionId,phase:detail?.phase,detail:detail?.extra}).catch(()=>{})}function buildKnowledgeBlock(entries,charBudget,cfg,currentProject){if(entries.length===0)return{block:null,renderedIds:[]};let maxDisplayChars=cfg.max_lesson_display_chars??120,rendered=entries.map((entry)=>{let tier=entry.tier==="hive"?"[H]":"[S]",confirmedBy=entry.confirmed_by?.length??0,confirm=confirmedBy>=3?" ✓✓":confirmedBy>=1?" ✓":"",lessonText=sanitizeLessonForContext(entry.lesson);if(lessonText.length>maxDisplayChars)lessonText=`${lessonText.slice(0,maxDisplayChars)}…`;let rawSource=entry.tier==="hive"&&"source_project"in entry?entry.source_project??null:null,source=rawSource!==null&&rawSource!==currentProject?` (from: ${sanitizeLessonForContext(rawSource)})`:"";return{id:entry.id,line:`${tier} ${lessonText}${source}${confirm}`}}),header=`\uD83D\uDCDA Lessons:
5773
5773
  `,block=`${header}
5774
- ${lines.join(`
5775
- `)}`;while(block.length>charBudget&&lines.length>0)lines.pop(),block=`${header}
5776
- ${lines.join(`
5777
- `)}`;return lines.length>0?block:null}function buildDirectiveBlock(entries,charBudget,cfg){if(entries.length===0)return null;let maxDisplay=cfg.max_lesson_display_chars??120,lines=[];lines.push("<swarm_knowledge_directives>");for(let e of entries){let trigger=e.triggers&&e.triggers.length>0?sanitizeLessonForContext(e.triggers[0]).slice(0,maxDisplay):"",required3=e.required_actions&&e.required_actions.length>0?sanitizeLessonForContext(e.required_actions[0]).slice(0,maxDisplay):"",forbidden=e.forbidden_actions&&e.forbidden_actions.length>0?sanitizeLessonForContext(e.forbidden_actions[0]).slice(0,maxDisplay):"",verification=e.verification_checks&&e.verification_checks.length>0?sanitizeLessonForContext(e.verification_checks[0]).slice(0,maxDisplay):"",skillRef=e.generated_skill_path?`file:${sanitizeLessonForContext(e.generated_skill_path)}`:"",priority=e.directive_priority??"medium",lesson=sanitizeLessonForContext(e.lesson).slice(0,maxDisplay);if(lines.push(`- id: ${e.id}`),lines.push(` confidence: ${Number(e.confidence).toFixed(2)}`),lines.push(` priority: ${priority}`),lines.push(` lesson: ${lesson}`),trigger)lines.push(` trigger: ${trigger}`);if(required3)lines.push(` required: ${required3}`);if(forbidden)lines.push(` forbidden: ${forbidden}`);if(skillRef)lines.push(` skill: ${skillRef}`);if(verification)lines.push(` verification: ${verification}`)}lines.push("</swarm_knowledge_directives>");let block=lines.join(`
5778
- `);while(block.length>charBudget&&lines.length>3){let lastIdx=-1;for(let i=lines.length-2;i>=0;i--)if(lines[i].startsWith("- id:")){lastIdx=i;break}if(lastIdx<0)break;lines.splice(lastIdx,lines.length-1-lastIdx),block=lines.join(`
5779
- `)}if(lines.length<=2)return null;return block}var sanitizeLessonForContext=sanitizeContextText,DELEGATE_DIRECTIVE_BLOCK_TAG="<delegate_knowledge_directives>";function buildDelegateDirectiveBlock(entries,cfg){if(entries.length===0)return null;let maxDisplay=cfg.max_lesson_display_chars??120,FIELD_CAP=240,renderList=(items)=>{if(!items||items.length===0)return null;let joined=items.map((s)=>sanitizeLessonForContext(s)).filter((s)=>s.length>0).join("; ");if(!joined)return null;return joined.length>FIELD_CAP?`${joined.slice(0,FIELD_CAP)}…`:joined},sorted=[...entries].sort((a,b)=>{let pr=directivePriorityRank(a.directive_priority)-directivePriorityRank(b.directive_priority);if(pr!==0)return pr;return a.id<b.id?-1:a.id>b.id?1:0}),lines=[];lines.push(DELEGATE_DIRECTIVE_BLOCK_TAG),lines.push("These directives were learned from prior swarm runs and scoped to your role. Apply them to the task below."),lines.push("ACK CONTRACT: end your FINAL message with one line per CRITICAL directive in this block:"),lines.push(" KNOWLEDGE_APPLIED:<id> — you applied it"),lines.push(" KNOWLEDGE_IGNORED:<id> reason=<short why> — you intentionally did not apply it"),lines.push(" KNOWLEDGE_N_A:<id> reason=<why> — it did not apply to your task"),lines.push("Omitting a critical id is a contract violation.");for(let e of sorted){let priority=e.directive_priority??"medium",lesson=sanitizeLessonForContext(e.lesson).slice(0,maxDisplay);lines.push(`- id: ${e.id}`),lines.push(` priority: ${priority}`),lines.push(` lesson: ${lesson}`);let forbidden=renderList(e.forbidden_actions);if(forbidden)lines.push(` forbidden: ${forbidden}`);let required3=renderList(e.required_actions);if(required3)lines.push(` required: ${required3}`);let verification=renderList(e.verification_checks);if(verification)lines.push(` verification: ${verification}`)}return lines.push("</delegate_knowledge_directives>"),lines.join(`
5774
+ ${rendered.map((r)=>r.line).join(`
5775
+ `)}`;while(block.length>charBudget&&rendered.length>0)rendered.pop(),block=`${header}
5776
+ ${rendered.map((r)=>r.line).join(`
5777
+ `)}`;return rendered.length>0?{block,renderedIds:rendered.map((r)=>r.id)}:{block:null,renderedIds:[]}}function buildDirectiveBlock(entries,charBudget,cfg){if(entries.length===0)return{block:null,renderedIds:[]};let maxDisplay=cfg.max_lesson_display_chars??120,records=[];for(let e of entries){let trigger=e.triggers&&e.triggers.length>0?sanitizeLessonForContext(e.triggers[0]).slice(0,maxDisplay):"",required3=e.required_actions&&e.required_actions.length>0?sanitizeLessonForContext(e.required_actions[0]).slice(0,maxDisplay):"",forbidden=e.forbidden_actions&&e.forbidden_actions.length>0?sanitizeLessonForContext(e.forbidden_actions[0]).slice(0,maxDisplay):"",verification=e.verification_checks&&e.verification_checks.length>0?sanitizeLessonForContext(e.verification_checks[0]).slice(0,maxDisplay):"",skillRef=e.generated_skill_path?`file:${sanitizeLessonForContext(e.generated_skill_path)}`:"",priority=e.directive_priority??"medium",lesson=sanitizeLessonForContext(e.lesson).slice(0,maxDisplay),rec=[];if(rec.push(`- id: ${e.id}`),rec.push(` confidence: ${Number(e.confidence).toFixed(2)}`),rec.push(` priority: ${priority}`),rec.push(` lesson: ${lesson}`),trigger)rec.push(` trigger: ${trigger}`);if(required3)rec.push(` required: ${required3}`);if(forbidden)rec.push(` forbidden: ${forbidden}`);if(skillRef)rec.push(` skill: ${skillRef}`);if(verification)rec.push(` verification: ${verification}`);records.push({id:e.id,lines:rec})}let block=["<swarm_knowledge_directives>",...records.flatMap((r)=>r.lines),"</swarm_knowledge_directives>"].join(`
5778
+ `);while(block.length>charBudget&&records.length>0)records.pop(),block=["<swarm_knowledge_directives>",...records.flatMap((r)=>r.lines),"</swarm_knowledge_directives>"].join(`
5779
+ `);if(records.length===0)return{block:null,renderedIds:[]};return{block,renderedIds:records.map((r)=>r.id)}}var sanitizeLessonForContext=sanitizeContextText,DELEGATE_DIRECTIVE_BLOCK_TAG="<delegate_knowledge_directives>";function buildDelegateDirectiveBlock(entries,cfg){if(entries.length===0)return null;let maxDisplay=cfg.max_lesson_display_chars??120,FIELD_CAP=240,renderList=(items)=>{if(!items||items.length===0)return null;let joined=items.map((s)=>sanitizeLessonForContext(s)).filter((s)=>s.length>0).join("; ");if(!joined)return null;return joined.length>FIELD_CAP?`${joined.slice(0,FIELD_CAP)}…`:joined},sorted=[...entries].sort((a,b)=>{let pr=directivePriorityRank(a.directive_priority)-directivePriorityRank(b.directive_priority);if(pr!==0)return pr;return a.id<b.id?-1:a.id>b.id?1:0}),lines=[];lines.push(DELEGATE_DIRECTIVE_BLOCK_TAG),lines.push("These directives were learned from prior swarm runs and scoped to your role. Apply them to the task below."),lines.push("ACK CONTRACT: end your FINAL message with one line per CRITICAL directive in this block:"),lines.push(" KNOWLEDGE_APPLIED:<id> — you applied it"),lines.push(" KNOWLEDGE_IGNORED:<id> reason=<short why> — you intentionally did not apply it"),lines.push(" KNOWLEDGE_N_A:<id> reason=<why> — it did not apply to your task"),lines.push("Omitting a critical id is a contract violation.");for(let e of sorted){let priority=e.directive_priority??"medium",lesson=sanitizeLessonForContext(e.lesson).slice(0,maxDisplay);lines.push(`- id: ${e.id}`),lines.push(` priority: ${priority}`),lines.push(` lesson: ${lesson}`);let forbidden=renderList(e.forbidden_actions);if(forbidden)lines.push(` forbidden: ${forbidden}`);let required3=renderList(e.required_actions);if(required3)lines.push(` required: ${required3}`);let verification=renderList(e.verification_checks);if(verification)lines.push(` verification: ${verification}`)}return lines.push("</delegate_knowledge_directives>"),lines.join(`
5780
5780
  `)}function parseDelegateDirectiveBlock(text){if(!text||!text.includes(DELEGATE_DIRECTIVE_BLOCK_TAG))return[];let start=text.indexOf(DELEGATE_DIRECTIVE_BLOCK_TAG),endTag="</delegate_knowledge_directives>",endIdx=text.indexOf(endTag,start),body=endIdx>=0?text.slice(start,endIdx):text.slice(start),out=[];for(let line of body.split(`
5781
- `)){let idM=/^- id:\s*(\S+)\s*$/.exec(line);if(idM){out.push({id:idM[1],priority:"medium"});continue}let prM=/^\s+priority:\s*(low|medium|high|critical)\s*$/.exec(line);if(prM&&out.length>0)out[out.length-1].priority=prM[1]}return out}async function injectForDelegate(params){let{directory,agent,taskTitle,sessionId,config:config3}=params,cap2=config3.delegate_max_inject_count??8,expectedTools=params.expectedTools&&params.expectedTools.length>0?params.expectedTools:defaultExpectedToolsForAgent(agent);if(cap2<=0)return{entries:[],trace_id:""};let role=stripKnownSwarmPrefix(agent).toLowerCase(),firstTool=expectedTools.length>0?expectedTools[0]:void 0,context={currentPhase:taskTitle??"",taskTitle,lastUserMessage:taskTitle,targetAgent:agent,currentTool:firstTool,mode:"delegation"},searchFn=params.searchFn??(_internals100.searchKnowledge===defaultSearchKnowledge?searchKnowledge:_internals100.searchKnowledge);try{let search=await searchFn({directory,config:config3,context,mode:"delegate_inject",agent,sessionId,tier:"all",applyScopeFilter:!0,applyRoleScope:!1,maxResults:Math.max(40,cap2*4),emitEvent:!1}),capped=search.results.filter((e)=>matchesDelegateScope(e,role,expectedTools)).slice(0,cap2);if(capped.length>0){let ranks={},scores={};capped.forEach((e,idx)=>{ranks[e.id]=idx+1,scores[e.id]=e.finalScore}),await _internals100.recordKnowledgeEvent(directory,{type:"retrieved",trace_id:search.trace_id,session_id:sessionId??"unknown",phase:params.phase??taskTitle,agent,query:taskTitle??"",retrieval_mode:"delegate_inject",result_ids:capped.map((e)=>e.id),ranks,scores})}return{entries:capped,trace_id:search.trace_id}}catch{return{entries:[],trace_id:""}}}async function injectForDelegateIntoMessages(directory,config3,output,agentName,sessionId){if(!output.messages||output.messages.length===0)return;if(output.messages.some((m)=>m.parts?.some((p)=>p.text?.includes(DELEGATE_DIRECTIVE_BLOCK_TAG))))return;let taskTitle;for(let i=output.messages.length-1;i>=0;i--){let m=output.messages[i];if(m.info?.role==="user"){let t=m.parts?.map((p)=>p.text??"").join(" ").trim();if(t){taskTitle=t.slice(0,800);break}}}let{entries}=await injectForDelegate({directory,agent:agentName,expectedTools:defaultExpectedToolsForAgent(agentName),taskTitle,sessionId,config:config3}),block=buildDelegateDirectiveBlock(entries,config3);if(!block)return;injectKnowledgeMessage(output,block)}function isOrchestratorAgent(agentName){return stripKnownSwarmPrefix(agentName).toLowerCase()==="architect"}var DELEGATED_AGENTS=new Set(["coder","reviewer","test_engineer","sme","docs","designer","critic","curator"]);function isDelegatedAgent(agentName){let stripped=stripKnownSwarmPrefix(agentName).toLowerCase();return DELEGATED_AGENTS.has(stripped)}var DELEGATE_DEFAULT_TOOLS={coder:["edit","write","patch","bash"],reviewer:["read","grep","glob"],test_engineer:["edit","write","bash","read"],sme:["read","grep","glob","webfetch"],docs:["read","edit","write","grep"],designer:["read","write","edit"],critic:["read","grep","glob"],curator:["read","grep","glob"]};function defaultExpectedToolsForAgent(agentName){let role=stripKnownSwarmPrefix(agentName).toLowerCase();return[...DELEGATE_DEFAULT_TOOLS[role]??[]]}var DIRECTIVE_PRIORITY_RANK={critical:0,high:1,medium:2,low:3};function directivePriorityRank(p){return DIRECTIVE_PRIORITY_RANK[p??"medium"]??2}function matchesDelegateScope(entry,role,expectedTools){let agents=(entry.applies_to_agents??[]).map((a)=>stripKnownSwarmPrefix(a).toLowerCase()),tools=(entry.applies_to_tools??[]).map((t)=>t.toLowerCase());if(agents.length===0&&tools.length===0)return!0;let normRole=stripKnownSwarmPrefix(role).toLowerCase();if(agents.includes(normRole))return!0;let expected=expectedTools.map((t)=>t.toLowerCase());if(tools.some((t)=>expected.includes(t)))return!0;return!1}function injectKnowledgeMessage(output,text){if(!output.messages)return;if(output.messages.some((m)=>m.parts?.some((p)=>p.text?.includes(INJECTION_SENTINEL))))return;let insertIdx=output.messages.length-1;for(let i=output.messages.length-1;i>=0;i--)if(output.messages[i].info?.role==="user"){insertIdx=i;break}let knowledgeMessage={info:{role:"system"},parts:[{type:"text",text:`${INJECTION_SENTINEL}${text}`}]};output.messages.splice(insertIdx,0,knowledgeMessage)}function createKnowledgeInjectorHook(directory,config3,modelLimitOverrides={},unifiedInjectionTokens=void 0){function buildContextCacheKey(phase,ctx){let parts=[String(phase),ctx.currentTool??"",ctx.currentAction??"",ctx.targetAgent??"",ctx.taskId??"",(ctx.filePaths??[]).slice(0,8).join(","),ctx.lastUserMessage?createHash19("sha1").update(ctx.lastUserMessage).digest("hex").slice(0,16):""].join("|");return createHash19("sha1").update(parts).digest("hex").slice(0,16)}let lastSeenCacheKey=null,cachedInjectionText=null,cachedShownIds=[],cachedCriticalIds=[];return safeHook(async(_input,output)=>{if(!output.messages||output.messages.length===0)return;let plan=await loadPlan(directory),currentPhase=plan?.current_phase??1,CHARS_PER_TOKEN=3.0303030303030303,{modelID,providerID}=extractModelInfo(output.messages),modelLimitTokens=resolveModelLimit(modelID,providerID,modelLimitOverrides),MODEL_LIMIT_CHARS=Math.floor(modelLimitTokens*CHARS_PER_TOKEN),existingChars=output.messages.reduce((sum,msg)=>{return sum+(msg.parts?.reduce((s,p)=>s+(p.text?.length??0),0)??0)},0),headroomChars=MODEL_LIMIT_CHARS-existingChars,MIN_INJECT_CHARS=config3.context_budget_threshold??300;if(headroomChars<MIN_INJECT_CHARS){warn(`[knowledge-injector] Skipping: only ${headroomChars} chars of headroom remain (existing: ${existingChars}, limit: ${MODEL_LIMIT_CHARS})`);return}let maxInjectChars=config3.inject_char_budget??2000,effectiveBudget=headroomChars>=MODEL_LIMIT_CHARS*0.6?maxInjectChars:headroomChars>=MODEL_LIMIT_CHARS*0.2?Math.floor(maxInjectChars*0.5):Math.floor(maxInjectChars*0.25),systemMsg=output.messages.find((m)=>m.info?.role==="system"),agentName=systemMsg?.info?.agent;if(!agentName)return;if(unifiedInjectionTokens!==void 0){let sessionID2=systemMsg?.info?.sessionID,seDemand=sessionID2?getSystemEnhancerDemand(sessionID2):0,allocation=allocateInjectionBudget(seDemand,effectiveBudget,{totalBudgetTokens:unifiedInjectionTokens});effectiveBudget=Math.floor(allocation.knowledgeInjectorTokens/0.33)}if(isDelegatedAgent(agentName)){await injectForDelegateIntoMessages(directory,config3,output,agentName,systemMsg?.info?.sessionID);return}if(!isOrchestratorAgent(agentName))return;let phaseDescription=plan?extractCurrentPhaseFromPlan(plan)??`Phase ${currentPhase}`:"Phase 0",projectName=plan?.title??"unknown",lastUserMessage;for(let i=output.messages.length-1;i>=0;i--){let m=output.messages[i];if(m.info?.role==="user"){let t=m.parts?.map((p)=>p.text??"").join(" ").trim();if(t){lastUserMessage=t.slice(0,800);break}}}let taskId=getCurrentTaskId(plan),retrievalCtx={projectName,currentPhase:phaseDescription,mode:"phase_start",lastUserMessage,taskId},cacheKey=buildContextCacheKey(currentPhase,retrievalCtx);if(cacheKey===lastSeenCacheKey&&cachedInjectionText!==null){injectKnowledgeMessage(output,cachedInjectionText);let sessionID2=systemMsg?.info?.sessionID;if(sessionID2)if(cachedCriticalIds.length>0)setCriticalShownIds(sessionID2,{ids:cachedCriticalIds,phase:`Phase ${currentPhase}`,generatedAt:Date.now()});else clearCriticalShownIds(sessionID2);return}lastSeenCacheKey=cacheKey,cachedInjectionText=null,cachedShownIds=[],cachedCriticalIds=[];let _context={projectName,currentPhase:phaseDescription},search=await(_internals100.searchKnowledge===defaultSearchKnowledge?searchKnowledge:_internals100.searchKnowledge)({directory,config:config3,context:retrievalCtx,mode:"auto_injection",agent:"architect",sessionId:systemMsg?.info?.sessionID,emitEvent:!1}),filteredEntries=search.results,freshPreamble=null;try{let driftReports=await readPriorDriftReports(directory);if(driftReports.length>0){let latestReport=driftReports[driftReports.length-1],driftText=buildDriftInjectionText(latestReport,500);if(driftText)freshPreamble=sanitizeContextText(driftText)}}catch{}try{let briefingContent=await readSwarmFileAsync(directory,"curator-briefing.md");if(briefingContent){let truncatedBriefing=sanitizeContextText(briefingContent).slice(0,500);freshPreamble=freshPreamble?`<curator_briefing>${truncatedBriefing}</curator_briefing>
5781
+ `)){let idM=/^- id:\s*(\S+)\s*$/.exec(line);if(idM){out.push({id:idM[1],priority:"medium"});continue}let prM=/^\s+priority:\s*(low|medium|high|critical)\s*$/.exec(line);if(prM&&out.length>0)out[out.length-1].priority=prM[1]}return out}async function injectForDelegate(params){let{directory,agent,taskTitle,sessionId,config:config3}=params,cap2=config3.delegate_max_inject_count??8,expectedTools=params.expectedTools&&params.expectedTools.length>0?params.expectedTools:defaultExpectedToolsForAgent(agent);if(cap2<=0)return{entries:[],trace_id:""};let role=stripKnownSwarmPrefix(agent).toLowerCase(),firstTool=expectedTools.length>0?expectedTools[0]:void 0,context={currentPhase:taskTitle??"",taskTitle,lastUserMessage:taskTitle,targetAgent:agent,currentTool:firstTool,mode:"delegation"},searchFn=params.searchFn??(_internals100.searchKnowledge===defaultSearchKnowledge?searchKnowledge:_internals100.searchKnowledge);try{let search=await searchFn({directory,config:config3,context,mode:"delegate_inject",agent,sessionId,tier:"all",applyScopeFilter:!0,applyRoleScope:!1,maxResults:Math.max(40,cap2*4),emitEvent:!1}),capped=search.results.filter((e)=>matchesDelegateScope(e,role,expectedTools)).slice(0,cap2);if(capped.length>0){let ranks={},scores={};if(capped.forEach((e,idx)=>{ranks[e.id]=idx+1,scores[e.id]=e.finalScore}),await _internals100.recordKnowledgeEvent(directory,{type:"retrieved",trace_id:search.trace_id,session_id:sessionId??"unknown",phase:params.phase??taskTitle,agent,query:taskTitle??"",retrieval_mode:"delegate_inject",result_ids:capped.map((e)=>e.id),ranks,scores}),params.phase){let shownIds=capped.map((e)=>e.id);_internals100.recordLessonsShown(directory,shownIds,params.phase).catch(()=>{}),_internals100.recordKnowledgeShown(directory,shownIds,{phase:params.phase,targetAgent:agent,sessionId}).catch(()=>{});let phaseNum=phaseNumberOf(params.phase);if(phaseNum!==void 0){let projectName=(await loadPlan(directory).catch(()=>null))?.title??"unknown";_internals100.confirmEntriesPhase(directory,shownIds,phaseNum,projectName).catch(()=>{})}}}return{entries:capped,trace_id:search.trace_id}}catch{return{entries:[],trace_id:""}}}async function injectForDelegateIntoMessages(directory,config3,output,agentName,sessionId){if(!output.messages||output.messages.length===0)return;if(output.messages.some((m)=>m.parts?.some((p)=>p.text?.includes(DELEGATE_DIRECTIVE_BLOCK_TAG))))return;let taskTitle;for(let i=output.messages.length-1;i>=0;i--){let m=output.messages[i];if(m.info?.role==="user"){let t=m.parts?.map((p)=>p.text??"").join(" ").trim();if(t){taskTitle=t.slice(0,800);break}}}let plan=await loadPlan(directory).catch(()=>null),phaseLabel=plan?extractCurrentPhaseFromPlan(plan)??`Phase ${plan.current_phase??1}`:void 0,{entries}=await injectForDelegate({directory,agent:agentName,expectedTools:defaultExpectedToolsForAgent(agentName),taskTitle,sessionId,phase:phaseLabel,config:config3}),block=buildDelegateDirectiveBlock(entries,config3);if(!block)return;injectKnowledgeMessage(output,block)}function isOrchestratorAgent(agentName){return stripKnownSwarmPrefix(agentName).toLowerCase()==="architect"}var DELEGATED_AGENTS=new Set(["coder","reviewer","test_engineer","sme","docs","designer","critic","curator"]);function isDelegatedAgent(agentName){let stripped=stripKnownSwarmPrefix(agentName).toLowerCase();return DELEGATED_AGENTS.has(stripped)}var DELEGATE_DEFAULT_TOOLS={coder:["edit","write","patch","bash"],reviewer:["read","grep","glob"],test_engineer:["edit","write","bash","read"],sme:["read","grep","glob","webfetch"],docs:["read","edit","write","grep"],designer:["read","write","edit"],critic:["read","grep","glob"],curator:["read","grep","glob"]};function defaultExpectedToolsForAgent(agentName){let role=stripKnownSwarmPrefix(agentName).toLowerCase();return[...DELEGATE_DEFAULT_TOOLS[role]??[]]}var DIRECTIVE_PRIORITY_RANK={critical:0,high:1,medium:2,low:3};function directivePriorityRank(p){return DIRECTIVE_PRIORITY_RANK[p??"medium"]??2}function matchesDelegateScope(entry,role,expectedTools){let agents=(entry.applies_to_agents??[]).map((a)=>stripKnownSwarmPrefix(a).toLowerCase()),tools=(entry.applies_to_tools??[]).map((t)=>t.toLowerCase());if(agents.length===0&&tools.length===0)return!0;let normRole=stripKnownSwarmPrefix(role).toLowerCase();if(agents.includes(normRole))return!0;let expected=expectedTools.map((t)=>t.toLowerCase());if(tools.some((t)=>expected.includes(t)))return!0;return!1}function injectKnowledgeMessage(output,text){if(!output.messages)return;if(output.messages.some((m)=>m.parts?.some((p)=>p.text?.includes(INJECTION_SENTINEL))))return;let insertIdx=output.messages.length-1;for(let i=output.messages.length-1;i>=0;i--)if(output.messages[i].info?.role==="user"){insertIdx=i;break}let knowledgeMessage={info:{role:"system"},parts:[{type:"text",text:`${INJECTION_SENTINEL}${text}`}]};output.messages.splice(insertIdx,0,knowledgeMessage)}function createKnowledgeInjectorHook(directory,config3,modelLimitOverrides={},unifiedInjectionTokens=void 0){function buildContextCacheKey(phase,ctx){let parts=[String(phase),ctx.currentTool??"",ctx.currentAction??"",ctx.targetAgent??"",ctx.taskId??"",(ctx.filePaths??[]).slice(0,8).join(","),ctx.lastUserMessage?createHash19("sha1").update(ctx.lastUserMessage).digest("hex").slice(0,16):""].join("|");return createHash19("sha1").update(parts).digest("hex").slice(0,16)}let lastSeenCacheKey=null,cachedInjectionText=null,cachedShownIds=[],cachedCriticalIds=[];return safeHook(async(_input,output)=>{if(!output.messages||output.messages.length===0)return;let plan=await loadPlan(directory),currentPhase=plan?.current_phase??1,CHARS_PER_TOKEN=3.0303030303030303,{modelID,providerID}=extractModelInfo(output.messages),modelLimitTokens=resolveModelLimit(modelID,providerID,modelLimitOverrides),MODEL_LIMIT_CHARS=Math.floor(modelLimitTokens*CHARS_PER_TOKEN),existingChars=output.messages.reduce((sum,msg)=>{return sum+(msg.parts?.reduce((s,p)=>s+(p.text?.length??0),0)??0)},0),headroomChars=MODEL_LIMIT_CHARS-existingChars,MIN_INJECT_CHARS=config3.context_budget_threshold??300;if(headroomChars<MIN_INJECT_CHARS){warn(`[knowledge-injector] Skipping: only ${headroomChars} chars of headroom remain (existing: ${existingChars}, limit: ${MODEL_LIMIT_CHARS})`),recordInjectionSkip(directory,"headroom_budget",{extra:{headroomChars,existingChars,modelLimitChars:MODEL_LIMIT_CHARS,modelID}});return}let maxInjectChars=config3.inject_char_budget??2000,effectiveBudget=headroomChars>=MODEL_LIMIT_CHARS*0.6?maxInjectChars:headroomChars>=MODEL_LIMIT_CHARS*0.2?Math.floor(maxInjectChars*0.5):Math.floor(maxInjectChars*0.25),systemMsg=output.messages.find((m)=>m.info?.role==="system"),agentName=systemMsg?.info?.agent,sessionId=systemMsg?.info?.sessionID;if(!agentName){recordInjectionSkip(directory,"no_agent_name",{sessionId});return}if(unifiedInjectionTokens!==void 0){let sessionID2=systemMsg?.info?.sessionID,seDemand=sessionID2?getSystemEnhancerDemand(sessionID2):0,allocation=allocateInjectionBudget(seDemand,effectiveBudget,{totalBudgetTokens:unifiedInjectionTokens});effectiveBudget=Math.floor(allocation.knowledgeInjectorTokens/0.33)}if(isDelegatedAgent(agentName)){await injectForDelegateIntoMessages(directory,config3,output,agentName,systemMsg?.info?.sessionID);return}if(!isOrchestratorAgent(agentName)){recordInjectionSkip(directory,"not_architect",{agent:agentName,sessionId});return}let phaseDescription=plan?extractCurrentPhaseFromPlan(plan)??`Phase ${currentPhase}`:"Phase 0",projectName=plan?.title??"unknown",lastUserMessage;for(let i=output.messages.length-1;i>=0;i--){let m=output.messages[i];if(m.info?.role==="user"){let t=m.parts?.map((p)=>p.text??"").join(" ").trim();if(t){lastUserMessage=t.slice(0,800);break}}}let taskId=getCurrentTaskId(plan),retrievalCtx={projectName,currentPhase:phaseDescription,mode:"phase_start",lastUserMessage,taskId},cacheKey=buildContextCacheKey(currentPhase,retrievalCtx);if(cacheKey===lastSeenCacheKey&&cachedInjectionText!==null){injectKnowledgeMessage(output,cachedInjectionText);let sessionID2=systemMsg?.info?.sessionID;if(sessionID2)if(cachedCriticalIds.length>0)setCriticalShownIds(sessionID2,{ids:cachedCriticalIds,phase:`Phase ${currentPhase}`,generatedAt:Date.now()});else clearCriticalShownIds(sessionID2);return}lastSeenCacheKey=cacheKey,cachedInjectionText=null,cachedShownIds=[],cachedCriticalIds=[];let _context={projectName,currentPhase:phaseDescription},search=await(_internals100.searchKnowledge===defaultSearchKnowledge?searchKnowledge:_internals100.searchKnowledge)({directory,config:config3,context:retrievalCtx,mode:"auto_injection",agent:"architect",sessionId:systemMsg?.info?.sessionID,emitEvent:!1}),filteredEntries=search.results,freshPreamble=null;try{let driftReports=await readPriorDriftReports(directory);if(driftReports.length>0){let latestReport=driftReports[driftReports.length-1],driftText=buildDriftInjectionText(latestReport,500);if(driftText)freshPreamble=sanitizeContextText(driftText)}}catch{}try{let briefingContent=await readSwarmFileAsync(directory,"curator-briefing.md");if(briefingContent){let truncatedBriefing=sanitizeContextText(briefingContent).slice(0,500);freshPreamble=freshPreamble?`<curator_briefing>${truncatedBriefing}</curator_briefing>
5782
5782
 
5783
- ${freshPreamble}`:`<curator_briefing>${truncatedBriefing}</curator_briefing>`}}catch{}if(filteredEntries.length===0){let sessionID2=systemMsg?.info?.sessionID;if(sessionID2)clearCriticalShownIds(sessionID2);if(cachedShownIds=[],cachedCriticalIds=[],freshPreamble===null)return;cachedInjectionText=freshPreamble,injectKnowledgeMessage(output,cachedInjectionText);return}let runMemory=null;try{runMemory=await getRunMemorySummary(directory)}catch(err){warn(`[knowledge-injector] run memory summary unavailable: ${err instanceof Error?err.message:String(err)}`)}let isFullBudget=effectiveBudget===maxInjectChars,directiveBudget=Math.floor(effectiveBudget*0.45),lessonBudget=Math.floor(effectiveBudget*0.3),directiveEntries=filteredEntries.filter((e)=>e.triggers&&e.triggers.length>0||e.required_actions&&e.required_actions.length>0||e.forbidden_actions&&e.forbidden_actions.length>0||e.directive_priority==="critical"||e.directive_priority==="high"||e.generated_skill_path),directiveBlock=buildDirectiveBlock(directiveEntries,directiveBudget,config3),lessonBlock=buildKnowledgeBlock(filteredEntries,lessonBudget,config3,projectName),renderedDirectiveIds=getRenderedEntryIds(directiveEntries,directiveBlock,config3,projectName),renderedIdSet=new Set([...renderedDirectiveIds,...getRenderedEntryIds(filteredEntries,lessonBlock,config3,projectName)]),renderedDirectiveIdSet=new Set(renderedDirectiveIds);cachedShownIds=filteredEntries.map((entry)=>entry.id).filter((id)=>renderedIdSet.has(id));let parts=[],remaining=effectiveBudget;try{let escalations=await _internals100.readRecentEscalations(directory),escalationBriefing=_internals100.buildEscalationBriefing(escalations);if(escalationBriefing&&escalationBriefing.length<=remaining)parts.push(escalationBriefing),remaining-=escalationBriefing.length}catch{}if(directiveBlock)parts.push(directiveBlock),remaining-=directiveBlock.length;if(lessonBlock)parts.push(lessonBlock),remaining-=lessonBlock.length;if(runMemory&&remaining>300){let sanitizedRunMemory=sanitizeContextText(runMemory);parts.push(sanitizedRunMemory),remaining-=sanitizedRunMemory.length}if(freshPreamble&&remaining>200){let preambleToUse=freshPreamble;if(!isFullBudget)preambleToUse=preambleToUse.replace(/<curator_briefing>[\s\S]*?<\/curator_briefing>\s*/g,"");if(preambleToUse.trim().length>0&&preambleToUse.length<=remaining)parts.push(preambleToUse),remaining-=preambleToUse.length}try{let rejected=await readRejectedLessons(directory);if(rejected.length>0&&remaining>150){let rejectedBlock=`⚠️ Previously rejected patterns (do not re-learn):
5783
+ ${freshPreamble}`:`<curator_briefing>${truncatedBriefing}</curator_briefing>`}}catch{}if(filteredEntries.length===0){let sessionID2=systemMsg?.info?.sessionID;if(sessionID2)clearCriticalShownIds(sessionID2);if(cachedShownIds=[],cachedCriticalIds=[],recordInjectionSkip(directory,"no_matching_entries",{agent:agentName,sessionId:sessionID2,phase:currentPhase}),freshPreamble===null)return;cachedInjectionText=freshPreamble,injectKnowledgeMessage(output,cachedInjectionText);return}let runMemory=null;try{runMemory=await getRunMemorySummary(directory)}catch(err){warn(`[knowledge-injector] run memory summary unavailable: ${err instanceof Error?err.message:String(err)}`)}let isFullBudget=effectiveBudget===maxInjectChars,directiveBudget=Math.floor(effectiveBudget*0.45),lessonBudget=Math.floor(effectiveBudget*0.3),directiveEntries=filteredEntries.filter((e)=>e.triggers&&e.triggers.length>0||e.required_actions&&e.required_actions.length>0||e.forbidden_actions&&e.forbidden_actions.length>0||e.directive_priority==="critical"||e.directive_priority==="high"||e.generated_skill_path),directiveBuilt=buildDirectiveBlock(directiveEntries,directiveBudget,config3),directiveBlock=directiveBuilt.block,lessonBuilt=buildKnowledgeBlock(filteredEntries,lessonBudget,config3,projectName),lessonBlock=lessonBuilt.block,renderedDirectiveIdSet=new Set(directiveBuilt.renderedIds);if(cachedShownIds=[...new Set([...directiveBuilt.renderedIds,...lessonBuilt.renderedIds])],cachedShownIds.length===0)recordInjectionSkip(directory,"rendered_id_match_failed",{agent:agentName,sessionId:systemMsg?.info?.sessionID,phase:currentPhase,extra:{filteredCount:filteredEntries.length,directiveCount:directiveEntries.length}});let parts=[],remaining=effectiveBudget;try{let escalations=await _internals100.readRecentEscalations(directory),escalationBriefing=_internals100.buildEscalationBriefing(escalations);if(escalationBriefing&&escalationBriefing.length<=remaining)parts.push(escalationBriefing),remaining-=escalationBriefing.length}catch{}if(directiveBlock)parts.push(directiveBlock),remaining-=directiveBlock.length;if(lessonBlock)parts.push(lessonBlock),remaining-=lessonBlock.length;if(runMemory&&remaining>300){let sanitizedRunMemory=sanitizeContextText(runMemory);parts.push(sanitizedRunMemory),remaining-=sanitizedRunMemory.length}if(freshPreamble&&remaining>200){let preambleToUse=freshPreamble;if(!isFullBudget)preambleToUse=preambleToUse.replace(/<curator_briefing>[\s\S]*?<\/curator_briefing>\s*/g,"");if(preambleToUse.trim().length>0&&preambleToUse.length<=remaining)parts.push(preambleToUse),remaining-=preambleToUse.length}try{let rejected=await readRejectedLessons(directory);if(rejected.length>0&&remaining>150){let rejectedBlock=`⚠️ Previously rejected patterns (do not re-learn):
5784
5784
  `+rejected.slice(-3).map((r)=>` ⚠️ REJECTED PATTERN: "${sanitizeLessonForContext(r.lesson).slice(0,80)}" — ${sanitizeLessonForContext(r.rejection_reason)}`).join(`
5785
5785
  `);if(rejectedBlock.length<=remaining)parts.push(rejectedBlock)}}catch(err){warn(`[knowledge-injector] rejected pattern warnings unavailable: ${err instanceof Error?err.message:String(err)}`)}cachedInjectionText=parts.join(`
5786
5786
 
5787
- `),injectKnowledgeMessage(output,cachedInjectionText);let sessionID=systemMsg?.info?.sessionID;if(sessionID){let criticalIds=filteredEntries.filter((e)=>renderedDirectiveIdSet.has(e.id)).filter((e)=>e.directive_priority==="critical"&&isActiveStatus(e.status)).map((e)=>e.id);if(cachedCriticalIds=criticalIds,criticalIds.length>0)setCriticalShownIds(sessionID,{ids:criticalIds,phase:`Phase ${currentPhase}`,generatedAt:Date.now()});else clearCriticalShownIds(sessionID)}if(cachedShownIds.length>0){let phaseLabel=`Phase ${currentPhase}`,scoreById=new Map(filteredEntries.map((e)=>[e.id,e.finalScore])),ranks={},scores={};cachedShownIds.forEach((id,idx)=>{ranks[id]=idx+1,scores[id]=scoreById.get(id)??0}),await _internals100.recordKnowledgeEvent(directory,{type:"retrieved",trace_id:search.trace_id,session_id:systemMsg?.info?.sessionID??"unknown",phase:retrievalCtx.currentPhase,task_id:retrievalCtx.taskId,agent:"architect",query:retrievalCtx.lastUserMessage??retrievalCtx.currentPhase??"",retrieval_mode:"auto_injection",result_ids:cachedShownIds,ranks,scores}),_internals100.recordKnowledgeShown(directory,cachedShownIds,{phase:phaseLabel,tool:retrievalCtx.currentTool,action:retrievalCtx.currentAction,targetAgent:retrievalCtx.targetAgent,taskId:retrievalCtx.taskId}).catch(()=>{})}})}var _internals100={searchKnowledge,recordKnowledgeEvent,recordKnowledgeShown,readRecentEscalations,buildEscalationBriefing};init_skill_propagation_gate();init_utils2();function isTaskTool3(tool3){return tool3==="Task"||tool3==="task"}function extractTaskId2(prompt){let m=/\btask[_-]?id\s*[:=]\s*([A-Za-z0-9._-]{1,80})/i.exec(prompt);return m?m[1]:void 0}async function appendUnacknowledgedCritical(directory,record3){let filePath=validateSwarmPath(directory,"unacknowledged-criticals.jsonl");await mkdir32(path161.dirname(filePath),{recursive:!0}),await appendFile17(filePath,`${JSON.stringify(record3)}
5787
+ `),injectKnowledgeMessage(output,cachedInjectionText);let sessionID=systemMsg?.info?.sessionID;if(sessionID){let criticalIds=filteredEntries.filter((e)=>renderedDirectiveIdSet.has(e.id)).filter((e)=>e.directive_priority==="critical"&&isActiveStatus(e.status)).map((e)=>e.id);if(cachedCriticalIds=criticalIds,criticalIds.length>0)setCriticalShownIds(sessionID,{ids:criticalIds,phase:`Phase ${currentPhase}`,generatedAt:Date.now()});else clearCriticalShownIds(sessionID)}if(cachedShownIds.length>0){let phaseLabel=`Phase ${currentPhase}`,scoreById=new Map(filteredEntries.map((e)=>[e.id,e.finalScore])),ranks={},scores={};cachedShownIds.forEach((id,idx)=>{ranks[id]=idx+1,scores[id]=scoreById.get(id)??0}),await _internals100.recordKnowledgeEvent(directory,{type:"retrieved",trace_id:search.trace_id,session_id:systemMsg?.info?.sessionID??"unknown",phase:retrievalCtx.currentPhase,task_id:retrievalCtx.taskId,agent:"architect",query:retrievalCtx.lastUserMessage??retrievalCtx.currentPhase??"",retrieval_mode:"auto_injection",result_ids:cachedShownIds,ranks,scores}),_internals100.recordKnowledgeShown(directory,cachedShownIds,{phase:phaseLabel,tool:retrievalCtx.currentTool,action:retrievalCtx.currentAction,targetAgent:retrievalCtx.targetAgent,taskId:retrievalCtx.taskId}).catch(()=>{}),_internals100.recordLessonsShown(directory,cachedShownIds,phaseLabel).catch(()=>{}),_internals100.confirmEntriesPhase(directory,cachedShownIds,currentPhase,projectName).catch(()=>{})}})}var _internals100={searchKnowledge,recordKnowledgeEvent,recordKnowledgeShown,readRecentEscalations,buildEscalationBriefing,recordLessonsShown,confirmEntriesPhase};init_skill_propagation_gate();init_utils2();function isTaskTool3(tool3){return tool3==="Task"||tool3==="task"}function extractTaskId2(prompt){let m=/\btask[_-]?id\s*[:=]\s*([A-Za-z0-9._-]{1,80})/i.exec(prompt);return m?m[1]:void 0}async function appendUnacknowledgedCritical(directory,record3){let filePath=validateSwarmPath(directory,"unacknowledged-criticals.jsonl");await mkdir32(path161.dirname(filePath),{recursive:!0}),await appendFile17(filePath,`${JSON.stringify(record3)}
5788
5788
  `,"utf-8")}async function collectDelegateAcks(params){let result={emitted:[],unacknowledgedCriticals:[]};try{let shown=parseDelegateDirectiveBlock(params.prompt);if(shown.length===0)return result;let shownById=new Map(shown.map((d)=>[d.id,d])),criticalIds=shown.filter((d)=>d.priority==="critical").map((d)=>d.id),acks=parseAcknowledgments(params.transcript),ackedIds=new Set,violatedIds=new Set,sessionId=params.sessionId??"unknown",taskId=params.taskId??extractTaskId2(params.prompt),traceId=newTraceId();for(let ack of acks){if(!shownById.has(ack.id))continue;if(ackedIds.add(ack.id),await recordKnowledgeEvent(params.directory,{type:ack.result,trace_id:traceId,knowledge_id:ack.id,session_id:sessionId,task_id:taskId,agent:params.agent,reason:ack.reason}),ack.result==="violated")violatedIds.add(ack.id);result.emitted.push({id:ack.id,type:ack.result})}for(let id of criticalIds){if(ackedIds.has(id))continue;result.unacknowledgedCriticals.push(id),await recordKnowledgeEvent(params.directory,{type:"violated",trace_id:traceId,knowledge_id:id,session_id:sessionId,task_id:taskId,agent:params.agent,reason:"unacknowledged"}),violatedIds.add(id),result.emitted.push({id,type:"violated"});try{await appendUnacknowledgedCritical(params.directory,{timestamp:new Date().toISOString(),knowledge_id:id,agent:params.agent,session_id:sessionId,task_id:taskId,reason:"unacknowledged"})}catch{}}if(violatedIds.size>0)await escalateViolatedEntries(params.directory,[...violatedIds])}catch{}return result}async function collectDelegateAcksAfter(directory,input,output){if(!isTaskTool3(input.tool))return;let argsRecord=input.args&&typeof input.args==="object"?input.args:null,prompt=argsRecord&&typeof argsRecord.prompt==="string"?argsRecord.prompt:"";if(!prompt)return;let transcript=typeof output.output==="string"?output.output:"";if(!transcript)return;let agent=parseDelegationArgs(input.args)?.targetAgent??"unknown",sessionId=typeof input.sessionID==="string"?input.sessionID:void 0;await collectDelegateAcks({directory,prompt,transcript,agent,sessionId})}var PRIORITY_RANK={critical:0,high:1,medium:2,low:3};function buildDirectiveComplianceBlock(directives){if(directives.length===0)return null;let sorted=[...directives].sort((a,b)=>{let pr=(PRIORITY_RANK[a.priority]??2)-(PRIORITY_RANK[b.priority]??2);if(pr!==0)return pr;return a.id<b.id?-1:a.id>b.id?1:0}),lines=[];lines.push("<directives_to_verify>"),lines.push("Produce a DIRECTIVE_COMPLIANCE verdict for EVERY id below. Run any verification_predicate provided.");for(let d of sorted){if(lines.push(`- id: ${d.id}`),lines.push(` priority: ${d.priority}`),d.lesson)lines.push(` lesson: ${d.lesson}`);if(d.verification_predicate)lines.push(` verification_predicate: ${d.verification_predicate}`)}return lines.push("</directives_to_verify>"),lines.push(""),lines.push(`DIRECTIVE_COMPLIANCE: one line per knowledge directive shown during this phase (the IDs are listed in the DIRECTIVES TO VERIFY block of your prompt). Use exactly one of:
5789
5789
  VERIFIED:<id> evidence=<file:line | predicate_passed>
5790
5790
  VIOLATED:<id> evidence=<file:line | failing_predicate>